Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

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

rcourtman704e738913c3
diff --git a/frontend-modern/src/api/__tests__/agentCapabilities.branchcov.test.ts b/frontend-modern/src/api/__tests__/agentCapabilities.branchcov.test.ts
new file mode 100644
index 0000000000..da16be194c
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/agentCapabilities.branchcov.test.ts
@@ -0,0 +1,517 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getAgentMCPAdapterConfigFamilies,
+ getAgentSurfaceContractEntries,
+ getAgentSurfaceToolPosturePresentation,
+ groupAgentCapabilitiesByManifestCategories,
+ normalizeAgentSurfaceToolContract,
+ type AgentCapabilitiesManifest,
+ type AgentCapability,
+ type AgentMCPAdapterContract,
+ type AgentOperatorSurfaceContract,
+ type AgentSurfaceAffordanceContract,
+ type AgentSurfaceContractComponent,
+} from '../agentCapabilities';
+
+const capability = (overrides: Partial<AgentCapability> = {}): AgentCapability => ({
+ name: 'cap',
+ category: 'context',
+ description: 'desc',
+ method: 'GET',
+ path: '/api/cap',
+ scope: 'monitoring:read',
+ actionMode: 'read',
+ approvalPolicy: 'scope_only',
+ ...overrides,
+});
+
+const component = (overrides: Partial<AgentSurfaceContractComponent> = {}): AgentSurfaceContractComponent => ({
+ id: 'component_id',
+ label: 'Component',
+ description: 'component description',
+ ...overrides,
+});
+
+const operatorSurface = (
+ overrides: Partial<AgentOperatorSurfaceContract> = {},
+): AgentOperatorSurfaceContract => ({
+ id: 'pulse_assistant',
+ label: 'Pulse Assistant',
+ description: 'assistant surface',
+ native: true,
+ externalAdapter: false,
+ ...overrides,
+});
+
+const adapter = (overrides: Partial<AgentMCPAdapterContract> = {}): AgentMCPAdapterContract => ({
+ serverName: 'pulse',
+ command: 'pulse-mcp',
+ baseUrlFlag: '--base-url',
+ defaultBaseUrl: 'http://localhost:7655',
+ tokenEnv: 'PULSE_API_TOKEN',
+ configFamilies: [],
+ ...overrides,
+});
+
+const manifest = (overrides: Partial<AgentCapabilitiesManifest> = {}): AgentCapabilitiesManifest => ({
+ version: 'v1',
+ surfaceContract: {
+ core: component({ id: 'core', label: 'Core' }),
+ proactiveEngine: component({ id: 'patrol', label: 'Patrol' }),
+ operatorSurfaces: [],
+ },
+ surfaceToolContracts: [],
+ mcpAdapter: adapter(),
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [],
+ ...overrides,
+});
+
+const affordance = (key: keyof AgentSurfaceAffordanceContract): AgentSurfaceAffordanceContract => {
+ const obj: AgentSurfaceAffordanceContract = {};
+ obj[key] = true;
+ return obj;
+};
+
+const DEFAULT_CONFIG_FAMILY_IDS = ['opencode', 'claude-style', 'custom-mcp'];
+
+describe('agentCapabilities branch coverage', () => {
+ describe('getAgentSurfaceToolPosturePresentation', () => {
+ it('renders singular breakdown strings and capability_manifest source for one tool of each kind', () => {
+ const presentation = getAgentSurfaceToolPosturePresentation({
+ surfaceId: 'pulse_mcp',
+ surfaceLabel: ' Pulse MCP ',
+ toolSource: ' capability_manifest ',
+ toolNames: ['get_context'],
+ registryToolNames: ['get_context'],
+ capabilityNames: ['get_context'],
+ nativeToolNames: ['get_context'],
+ });
+
+ expect(presentation).toMatchObject({
+ surfaceLabel: 'Pulse MCP',
+ label: '1 capability',
+ tone: 'ready',
+ toolCount: 1,
+ });
+ expect(presentation?.detail).toBe(
+ '1 registry capability, 1 published capability, 1 native capability, Actions, Resources, Prompts, Capability metadata',
+ );
+ expect(presentation?.title).toBe(
+ 'Pulse MCP capability availability. Source: Capability manifest. 1 registry capability, 1 published capability, 1 native capability, Actions, Resources, Prompts, Capability metadata',
+ );
+ });
+
+ it('renders plural breakdown strings and falls back to surfaceId when surfaceLabel is absent', () => {
+ const presentation = getAgentSurfaceToolPosturePresentation({
+ surfaceId: 'pulse_assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['q1', 'q2'],
+ registryToolNames: ['q1', 'q2'],
+ capabilityNames: ['q1', 'q2'],
+ nativeToolNames: ['q1', 'q2'],
+ });
+
+ expect(presentation).toMatchObject({
+ surfaceLabel: 'pulse_assistant',
+ label: '2 capabilities',
+ tone: 'ready',
+ toolCount: 2,
+ });
+ expect(presentation?.detail).toBe(
+ '2 registry capabilities, 2 published capabilities, 2 native capabilities, Actions, Interactive questions',
+ );
+ expect(presentation?.title).toContain('Source: Assistant registry');
+ });
+
+ it('uses the default toolSource word splitter and omits detail when nothing is available', () => {
+ const presentation = getAgentSurfaceToolPosturePresentation({
+ surfaceId: 'standalone_cli',
+ toolSource: 'my-cool_source',
+ toolNames: [],
+ });
+
+ expect(presentation).toMatchObject({
+ surfaceLabel: 'standalone_cli',
+ label: '0 capabilities',
+ tone: 'empty',
+ toolCount: 0,
+ });
+ expect(presentation?.detail).toBeUndefined();
+ expect(presentation?.title).toBe(
+ 'standalone_cli capability availability. Source: My Cool Source',
+ );
+ });
+
+ it('returns null when the contract normalizes away', () => {
+ expect(getAgentSurfaceToolPosturePresentation(undefined)).toBeNull();
+ expect(
+ getAgentSurfaceToolPosturePresentation({ surfaceId: ' ', toolSource: 'x', toolNames: [] }),
+ ).toBeNull();
+ });
+ });
+
+ describe('normalizedConfigFamilies (via getAgentMCPAdapterConfigFamilies)', () => {
+ it('clones the default families when no adapter or families are supplied', () => {
+ const families = getAgentMCPAdapterConfigFamilies(undefined);
+
+ expect(families.map((family) => family.id)).toEqual(DEFAULT_CONFIG_FAMILY_IDS);
+ // cloned arrays are fresh copies of the defaults (fileHints present on opencode)
+ expect(families[0]?.fileHints).toEqual([
+ 'opencode.json',
+ 'opencode.jsonc',
+ '~/.config/opencode/opencode.json',
+ ]);
+ // the custom-mcp default carries no fileHints
+ expect(families[2]?.fileHints).toBeUndefined();
+ });
+
+ it('falls back to defaults for an empty families array', () => {
+ expect(
+ getAgentMCPAdapterConfigFamilies(adapter({ configFamilies: [] })).map((f) => f.id),
+ ).toEqual(DEFAULT_CONFIG_FAMILY_IDS);
+ });
+
+ it('falls back to defaults when every supplied family is unidentifiable', () => {
+ const families = getAgentMCPAdapterConfigFamilies({
+ ...adapter(),
+ configFamilies: [{ id: ' ', label: ' ', shape: ' ' }],
+ });
+
+ expect(families.map((f) => f.id)).toEqual(DEFAULT_CONFIG_FAMILY_IDS);
+ });
+
+ it('derives id from label and filters fileHints/clientLabels, dropping empty descriptions', () => {
+ const families = getAgentMCPAdapterConfigFamilies({
+ ...adapter(),
+ configFamilies: [
+ {
+ id: ' ',
+ label: ' My Client ',
+ shape: 'my_shape',
+ description: ' ',
+ fileHints: [' hint/a ', '', ' '],
+ clientLabels: [' My Client ', ''],
+ },
+ ],
+ });
+
+ expect(families).toEqual([
+ {
+ id: 'My Client',
+ label: 'My Client',
+ shape: 'my_shape',
+ description: undefined,
+ fileHints: ['hint/a'],
+ clientLabels: ['My Client'],
+ },
+ ]);
+ });
+
+ it('derives id and label from shape when only shape is present and keeps undefined fileHints', () => {
+ const families = getAgentMCPAdapterConfigFamilies({
+ ...adapter(),
+ configFamilies: [
+ {
+ id: '',
+ label: '',
+ shape: 'only_shape',
+ description: 'kept description',
+ clientLabels: ['x'],
+ },
+ ],
+ });
+
+ expect(families).toEqual([
+ {
+ id: 'only_shape',
+ label: 'only_shape',
+ shape: 'only_shape',
+ description: 'kept description',
+ fileHints: undefined,
+ clientLabels: ['x'],
+ },
+ ]);
+ });
+
+ it('normalizes multiple mixed families alongside the defaults only when all are dropped', () => {
+ const families = getAgentMCPAdapterConfigFamilies({
+ ...adapter(),
+ configFamilies: [
+ { id: 'good', label: 'Good', shape: 'good_shape' },
+ { id: '', label: '', shape: '' },
+ ],
+ });
+
+ expect(families.map((f) => f.id)).toEqual(['good']);
+ expect(families[0]?.description).toBeUndefined();
+ });
+ });
+
+ describe('groupAgentCapabilitiesByManifestCategories', () => {
+ it('returns an empty array for an undefined manifest', () => {
+ expect(groupAgentCapabilitiesByManifestCategories(undefined)).toEqual([]);
+ });
+
+ it('sanitizes legacy capability descriptions including the empty case', () => {
+ const sections = groupAgentCapabilitiesByManifestCategories(
+ manifest({
+ categories: [{ id: 'context', label: 'Context' }],
+ capabilities: [
+ capability({ name: 'a', description: 'Uses legacy Pro activation aliases here.' }),
+ capability({ name: 'b', description: 'Pro activation completed/resolved proof.' }),
+ capability({
+ name: 'c',
+ description: 'Patrol autonomy completed/resolved outcome status.',
+ }),
+ capability({
+ name: 'd',
+ description: 'Patrol autonomy completed/resolved outcome evidence.',
+ }),
+ capability({ name: 'e', description: ' ' }),
+ ],
+ }),
+ );
+
+ expect(sections[0]?.entries.map((entry) => entry.description)).toEqual([
+ 'Uses compatibility aliases here.',
+ 'Patrol mode completed/resolved outcome status.',
+ 'Patrol mode completed/resolved outcome status.',
+ 'Patrol mode outcome evidence.',
+ '',
+ ]);
+ });
+
+ it('uses fallback labels, drops empty descriptions, and skips categories with no entries', () => {
+ const sections = groupAgentCapabilitiesByManifestCategories(
+ manifest({
+ categories: [
+ { id: 'context', label: ' ' },
+ { id: 'orphaned', label: 'Orphaned', description: ' ' },
+ ],
+ capabilities: [capability({ name: 'cap', category: 'context' })],
+ }),
+ );
+
+ expect(sections).toHaveLength(1);
+ expect(sections[0]?.id).toBe('context');
+ expect(sections[0]?.label).toBe('context');
+ expect(sections[0]?.description).toBeUndefined();
+ expect(sections[0]?.entries.map((entry) => entry.name)).toEqual(['cap']);
+ });
+ });
+
+ describe('surfaceAffordancesDeclared (via normalizeAgentSurfaceToolContract)', () => {
+ const declaredKeys: Array<keyof AgentSurfaceAffordanceContract> = [
+ 'tools',
+ 'resources',
+ 'prompts',
+ 'capabilityMetadata',
+ 'interactiveQuestions',
+ ];
+
+ for (const key of declaredKeys) {
+ it(`keeps affordances and gates tools when only ${key} is declared`, () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 'standalone',
+ toolSource: 'x',
+ toolNames: ['t'],
+ affordances: affordance(key),
+ });
+
+ expect(normalized?.affordances).toEqual(affordance(key));
+ expect(normalized?.toolNames).toEqual(key === 'tools' ? ['t'] : []);
+ });
+ }
+
+ it('falls back to default affordances for a known surface when none are declared', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 'pulse_mcp',
+ toolSource: 'x',
+ toolNames: ['t'],
+ });
+
+ expect(normalized?.affordances).toEqual({
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ });
+ });
+
+ it('yields undefined affordances for an unknown surface when none are declared', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 'unknown_surface',
+ toolSource: 'x',
+ toolNames: ['t'],
+ });
+
+ expect(normalized?.affordances).toBeUndefined();
+ expect(normalized?.toolNames).toEqual([]);
+ });
+
+ it('treats an all-false affordances object as undeclared', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 'pulse_assistant',
+ toolSource: 'x',
+ toolNames: ['t'],
+ affordances: { tools: false, resources: false },
+ });
+
+ expect(normalized?.affordances).toEqual({ tools: true, interactiveQuestions: true });
+ });
+ });
+
+ describe('normalizeAgentSurfaceToolContract', () => {
+ it('returns undefined for an undefined contract', () => {
+ expect(normalizeAgentSurfaceToolContract(undefined)).toBeUndefined();
+ });
+
+ it('returns undefined when surfaceId is empty or whitespace', () => {
+ expect(
+ normalizeAgentSurfaceToolContract({ surfaceId: '', toolSource: 'x', toolNames: [] }),
+ ).toBeUndefined();
+ expect(
+ normalizeAgentSurfaceToolContract({ surfaceId: ' ', toolSource: 'x', toolNames: [] }),
+ ).toBeUndefined();
+ });
+
+ it('defaults an empty toolSource to unknown and an empty surfaceLabel to undefined', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 's',
+ surfaceLabel: ' ',
+ toolSource: ' ',
+ toolNames: [],
+ });
+
+ expect(normalized?.toolSource).toBe('unknown');
+ expect(normalized?.surfaceLabel).toBeUndefined();
+ });
+
+ it('clears tool lists and returns undefined optionals when tools are disabled', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 'unknown_x',
+ toolSource: 'x',
+ toolNames: ['a', 'b'],
+ registryToolNames: ['a'],
+ capabilityNames: ['c'],
+ nativeToolNames: ['n'],
+ });
+
+ expect(normalized?.toolNames).toEqual([]);
+ expect(normalized?.registryToolNames).toBeUndefined();
+ expect(normalized?.capabilityNames).toBeUndefined();
+ expect(normalized?.nativeToolNames).toBeUndefined();
+ });
+
+ it('dedupes and trims all tool lists when tools are enabled', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 'pulse_mcp',
+ toolSource: 'x',
+ toolNames: [' a ', 'a', ' b ', ''],
+ registryToolNames: ['a', 'a', ' '],
+ capabilityNames: ['c1', 'c1', 'c2'],
+ nativeToolNames: ['n1'],
+ });
+
+ expect(normalized?.toolNames).toEqual(['a', 'b']);
+ expect(normalized?.registryToolNames).toEqual(['a']);
+ expect(normalized?.capabilityNames).toEqual(['c1', 'c2']);
+ expect(normalized?.nativeToolNames).toEqual(['n1']);
+ });
+
+ it('returns undefined optionals for explicitly empty lists when tools are enabled', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: 'pulse_mcp',
+ toolSource: 'x',
+ toolNames: [],
+ registryToolNames: [],
+ capabilityNames: [],
+ nativeToolNames: [],
+ });
+
+ expect(normalized?.registryToolNames).toBeUndefined();
+ expect(normalized?.capabilityNames).toBeUndefined();
+ expect(normalized?.nativeToolNames).toBeUndefined();
+ });
+ });
+
+ describe('trimSurfaceContractComponent (via getAgentSurfaceContractEntries)', () => {
+ it('returns an empty array for an undefined manifest', () => {
+ expect(getAgentSurfaceContractEntries(undefined)).toEqual([]);
+ });
+
+ it('returns an empty array when surfaceContract is missing', () => {
+ const malformed = { version: 'v1' } as unknown as AgentCapabilitiesManifest;
+ expect(getAgentSurfaceContractEntries(malformed)).toEqual([]);
+ });
+
+ it('omits empty-label components/surfaces, falls id back to label, and drops empty descriptions', () => {
+ const entries = getAgentSurfaceContractEntries(
+ manifest({
+ surfaceContract: {
+ core: { id: '', label: 'Core', description: ' ' },
+ proactiveEngine: { id: 'p', label: ' ', description: 'kept' },
+ operatorSurfaces: [
+ operatorSurface({ id: '', label: 'Native Surface', description: ' ', native: true }),
+ operatorSurface({ id: 'ext', label: ' ', description: 'x', externalAdapter: true }),
+ ],
+ },
+ }),
+ );
+
+ expect(entries).toEqual([
+ {
+ id: 'Core',
+ label: 'Core',
+ description: undefined,
+ badges: [],
+ },
+ {
+ id: 'Native Surface',
+ label: 'Native Surface',
+ description: undefined,
+ badges: ['Native surface'],
+ },
+ ]);
+ });
+
+ it('projects default affordance badges for a known native surface', () => {
+ const entries = getAgentSurfaceContractEntries(
+ manifest({
+ surfaceContract: {
+ core: component({ id: 'c', label: 'C' }),
+ proactiveEngine: component({ id: 'p', label: 'P' }),
+ operatorSurfaces: [operatorSurface({ id: 'pulse_assistant', label: 'Assistant' })],
+ },
+ }),
+ );
+
+ expect(entries[2]?.badges).toEqual(['Native surface', 'Actions', 'Interactive questions']);
+ });
+
+ it('projects only declared affordance badges for an external adapter surface', () => {
+ const entries = getAgentSurfaceContractEntries(
+ manifest({
+ surfaceContract: {
+ core: component({ id: 'c', label: 'C' }),
+ proactiveEngine: component({ id: 'p', label: 'P' }),
+ operatorSurfaces: [
+ operatorSurface({
+ id: 'ext',
+ label: 'Ext',
+ native: false,
+ externalAdapter: true,
+ affordances: { resources: true },
+ }),
+ ],
+ },
+ }),
+ );
+
+ expect(entries[2]?.badges).toEqual(['External adapter', 'Resources']);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.branchcov.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.branchcov.test.ts
new file mode 100644
index 0000000000..5ca4ead3cf
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.branchcov.test.ts
@@ -0,0 +1,804 @@
+import { describe, expect, it } from 'vitest';
+import type { AssistantTranscriptOptions } from '../transcriptExport';
+import { formatAssistantTranscript, hasAssistantTranscriptContent } from '../transcriptExport';
+import type { ChatMessage, StreamDisplayEvent } from '../types';
+
+const timestamp = new Date('2026-06-06T12:34:56Z');
+
+const assistantWithEvents = (events: StreamDisplayEvent[]): ChatMessage => ({
+ id: 'assistant-1',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ streamEvents: events,
+});
+
+const render = (
+ messages: ChatMessage[],
+ options: Partial<AssistantTranscriptOptions> = {},
+): string =>
+ formatAssistantTranscript({
+ messages,
+ generatedAt: timestamp,
+ ...options,
+ });
+
+const readToolInput = (command: string): string =>
+ JSON.stringify({ action: 'exec', command, target_host: 'current_resource' });
+
+// ---------------------------------------------------------------------------
+// formatTimestamp — reachable through appendMessageMetadata -> formatAssistantTranscript
+// ---------------------------------------------------------------------------
+
+describe('formatTimestamp guard branches', () => {
+ it('formats a valid Date into the Time metadata line', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Answer text',
+ timestamp: new Date('2026-06-06T12:34:56Z'),
+ },
+ ]);
+ expect(transcript).toContain('Time:');
+ expect(transcript).toContain('2026');
+ });
+
+ it('returns empty for a NaN date, leaving the Time label without a formatted value', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Answer text',
+ timestamp: new Date(NaN),
+ },
+ ]);
+ const timeLine = transcript.split('\n').find((line) => line.startsWith('Time:'));
+ expect(timeLine).toBe('Time: ');
+ });
+
+ it('returns empty when timestamp is not a Date instance', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Answer text',
+ timestamp: '2026-06-06T12:00:00Z' as unknown as Date,
+ },
+ ]);
+ const timeLine = transcript.split('\n').find((line) => line.startsWith('Time:'));
+ expect(timeLine).toBe('Time: ');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatGeneratedAt — reachable through formatAssistantTranscript
+// ---------------------------------------------------------------------------
+
+describe('formatGeneratedAt guard branches', () => {
+ it('emits a Generated ISO line for a valid date', () => {
+ const transcript = render(
+ [{ id: 'a1', role: 'assistant', content: 'Hi', timestamp }],
+ { generatedAt: new Date('2026-06-06T12:34:56Z') },
+ );
+ expect(transcript).toContain('Generated: 2026-06-06T12:34:56.000Z');
+ });
+
+ it('omits the Generated line for a NaN date', () => {
+ const transcript = render(
+ [{ id: 'a1', role: 'assistant', content: 'Hi', timestamp }],
+ { generatedAt: new Date(NaN) },
+ );
+ expect(transcript).not.toContain('Generated:');
+ });
+
+ it('omits the Generated line when generatedAt is not a Date instance', () => {
+ const transcript = render(
+ [{ id: 'a1', role: 'assistant', content: 'Hi', timestamp }],
+ { generatedAt: 'not-a-date' as unknown as Date },
+ );
+ expect(transcript).not.toContain('Generated:');
+ });
+
+ it('falls back to the current time when generatedAt is omitted', () => {
+ const before = new Date().toISOString();
+ const transcript = formatAssistantTranscript({
+ messages: [{ id: 'a1', role: 'assistant', content: 'Hi', timestamp }],
+ });
+ const after = new Date().toISOString();
+ const generatedLine = transcript.split('\n').find((line) => line.startsWith('Generated:'));
+ expect(generatedLine).toBeDefined();
+ const iso = (generatedLine ?? '').replace('Generated: ', '');
+ expect(iso >= before).toBe(true);
+ expect(iso <= after).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatToolOutput — reachable through formatCompletedTool when includeToolOutput is true
+// ---------------------------------------------------------------------------
+
+describe('formatToolOutput truncation and normalization branches', () => {
+ it('returns empty for whitespace-only output', () => {
+ const transcript = render(
+ [
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: readToolInput('true'),
+ output: ' \n ',
+ success: true,
+ },
+ },
+ ]),
+ ],
+ { includeToolOutput: true },
+ );
+ expect(transcript).toContain('[tool:read]');
+ // No ellipsis is appended because formatToolOutput short-circuits to ''
+ expect(transcript).not.toContain('...');
+ });
+
+ it('preserves six lines without an ellipsis', () => {
+ const output = ['one', 'two', 'three', 'four', 'five', 'six'].join('\n');
+ const transcript = render(
+ [
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: readToolInput('echo x'),
+ output,
+ success: true,
+ },
+ },
+ ]),
+ ],
+ { includeToolOutput: true },
+ );
+ expect(transcript).toContain('six');
+ expect(transcript).not.toContain('...');
+ });
+
+ it('appends an ellipsis when output exceeds six lines', () => {
+ const output = ['1', '2', '3', '4', '5', '6', '7', '8'].join('\n');
+ const transcript = render(
+ [
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: readToolInput('echo x'),
+ output,
+ success: true,
+ },
+ },
+ ]),
+ ],
+ { includeToolOutput: true },
+ );
+ expect(transcript).toContain('...');
+ // Line 6 is included in the preview; line 7 is not
+ expect(transcript).toContain('\n6');
+ expect(transcript).not.toContain('\n7');
+ });
+
+ it('truncates each line to 160 characters', () => {
+ const longLine = 'B'.repeat(200);
+ const transcript = render(
+ [
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: readToolInput('echo x'),
+ output: longLine,
+ success: true,
+ },
+ },
+ ]),
+ ],
+ { includeToolOutput: true },
+ );
+ expect(transcript).toContain('B'.repeat(160));
+ expect(transcript).not.toContain('B'.repeat(161));
+ });
+
+ it('normalizes lone carriage returns to newlines', () => {
+ const transcript = render(
+ [
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: readToolInput('echo x'),
+ output: 'alpha\r\nbravo\rcharlie',
+ success: true,
+ },
+ },
+ ]),
+ ],
+ { includeToolOutput: true },
+ );
+ expect(transcript).toContain('alpha');
+ expect(transcript).toContain('bravo');
+ expect(transcript).toContain('charlie');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatCompletedTool — reachable through streamEvents tool events and fallback toolCalls
+// ---------------------------------------------------------------------------
+
+describe('formatCompletedTool status and summary branches', () => {
+ it('reports a failed status when success is false', () => {
+ const transcript = render([
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: readToolInput('ls /dev | wc -l'),
+ output: 'permission denied',
+ success: false,
+ },
+ },
+ ]),
+ ]);
+ expect(transcript).toContain('failed');
+ expect(transcript).not.toContain('completed');
+ });
+
+ it('omits the summary segment when parseToolInputSummary returns empty', () => {
+ const transcript = render([
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: '',
+ output: '',
+ success: true,
+ },
+ },
+ ]),
+ ]);
+ // compactText joins the bare label and status with " - "
+ expect(transcript).toContain('[tool:read] - completed');
+ // No command preview since input is empty
+ expect(transcript).not.toContain('$');
+ });
+
+ it('does not include tool output when includeToolOutput is not set', () => {
+ const transcript = render([
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: readToolInput('echo x'),
+ output: 'sensitive-output-data',
+ success: true,
+ },
+ },
+ ]),
+ ]);
+ expect(transcript).not.toContain('sensitive-output-data');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatCanceledTool — reachable through tool_cancel stream events
+// ---------------------------------------------------------------------------
+
+describe('formatCanceledTool fallback and reason branches', () => {
+ it('falls back to the action label when no parsed summary is available', () => {
+ const transcript = render([
+ assistantWithEvents([
+ {
+ type: 'tool_cancel',
+ toolId: 't1',
+ toolCancel: {
+ id: 't1',
+ name: 'pulse_read',
+ input: '',
+ },
+ },
+ ]),
+ ]);
+ expect(transcript).toContain('[tool:read] Preparing read...');
+ expect(transcript).toContain('skipped');
+ expect(transcript).not.toContain('reason:');
+ });
+
+ it('omits the reason line when reason is only whitespace', () => {
+ const transcript = render([
+ assistantWithEvents([
+ {
+ type: 'tool_cancel',
+ toolId: 't2',
+ toolCancel: {
+ id: 't2',
+ name: 'pulse_read',
+ input: readToolInput('ls /dev'),
+ reason: ' ',
+ },
+ },
+ ]),
+ ]);
+ expect(transcript).toContain('skipped');
+ expect(transcript).not.toContain('reason:');
+ });
+
+ it('includes the command preview alongside the skipped status', () => {
+ const transcript = render([
+ assistantWithEvents([
+ {
+ type: 'tool_cancel',
+ toolId: 't3',
+ toolCancel: {
+ id: 't3',
+ name: 'pulse_read',
+ input: readToolInput('ls /dev'),
+ },
+ },
+ ]),
+ ]);
+ expect(transcript).toContain('$ ls /dev');
+ expect(transcript).toContain('skipped');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// hasRenderableEvent — uncovered switch arms: tool, pending_tool, content, default
+// ---------------------------------------------------------------------------
+
+describe('hasRenderableEvent uncovered switch arms', () => {
+ it('treats a tool event as renderable only when a tool payload exists', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ assistantWithEvents([
+ {
+ type: 'tool',
+ tool: { name: 'pulse_read', input: '', output: '', success: true },
+ },
+ ]),
+ ]),
+ ).toBe(true);
+ expect(hasAssistantTranscriptContent([assistantWithEvents([{ type: 'tool' }])])).toBe(false);
+ });
+
+ it('treats a pending_tool event as renderable only when a pendingTool payload exists', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ assistantWithEvents([
+ {
+ type: 'pending_tool',
+ pendingTool: { id: 'p1', name: 'pulse_read', input: '' },
+ },
+ ]),
+ ]),
+ ).toBe(true);
+ expect(hasAssistantTranscriptContent([assistantWithEvents([{ type: 'pending_tool' }])])).toBe(
+ false,
+ );
+ });
+
+ it('treats a content event as renderable only when visible content is non-empty', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ assistantWithEvents([{ type: 'content', content: 'Visible answer' }]),
+ ]),
+ ).toBe(true);
+ expect(
+ hasAssistantTranscriptContent([assistantWithEvents([{ type: 'content', content: ' ' }])]),
+ ).toBe(false);
+ expect(hasAssistantTranscriptContent([assistantWithEvents([{ type: 'content' }])])).toBe(false);
+ });
+
+ it('returns false for an unknown event type via the default arm', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ assistantWithEvents([{ type: 'bogus' } as unknown as StreamDisplayEvent]),
+ ]),
+ ).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// hasTranscriptMessageContent — uncovered branches beyond user/empty-content
+// ---------------------------------------------------------------------------
+
+describe('hasTranscriptMessageContent uncovered branches', () => {
+ it('detects an assistant message with only an error', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ { id: 'a1', role: 'assistant', content: '', timestamp, error: 'Turn failed' },
+ ]),
+ ).toBe(true);
+ });
+
+ it('detects an assistant message with only persisted tool calls', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ {
+ id: 'a2',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ toolCalls: [{ name: 'pulse_read', input: '', output: '', success: true }],
+ },
+ ]),
+ ).toBe(true);
+ });
+
+ it('detects an assistant message with only pending tools', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ {
+ id: 'a3',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ pendingTools: [{ id: 'p1', name: 'pulse_read', input: '' }],
+ },
+ ]),
+ ).toBe(true);
+ });
+
+ it('detects an assistant message with only pending approvals', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ {
+ id: 'a4',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ pendingApprovals: [
+ { toolId: 't1', toolName: '', command: '', runOnHost: false },
+ ],
+ },
+ ]),
+ ).toBe(true);
+ });
+
+ it('detects an assistant message with only pending questions', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ {
+ id: 'a5',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ pendingQuestions: [{ questionId: 'q1', questions: [] }],
+ },
+ ]),
+ ).toBe(true);
+ });
+
+ it('detects an assistant message with renderable stream events', () => {
+ expect(
+ hasAssistantTranscriptContent([
+ assistantWithEvents([{ type: 'content', content: 'Streamed answer' }]),
+ ]),
+ ).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// appendMessageMetadata — uncovered branches
+// ---------------------------------------------------------------------------
+
+describe('appendMessageMetadata uncovered branches', () => {
+ it('skips all metadata when includeAssistantMetadata is explicitly false', () => {
+ const transcript = render(
+ [
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Answer',
+ timestamp,
+ model: 'openrouter:deepseek/deepseek-chat',
+ delivery: 'queued',
+ isStreaming: true,
+ },
+ ],
+ { includeAssistantMetadata: false },
+ );
+ expect(transcript).not.toContain('Time:');
+ expect(transcript).not.toContain('Model:');
+ expect(transcript).not.toContain('Delivery:');
+ expect(transcript).not.toContain('State:');
+ });
+
+ it('emits queued delivery and streaming state metadata', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Answer',
+ timestamp,
+ delivery: 'queued',
+ isStreaming: true,
+ },
+ ]);
+ expect(transcript).toContain('Delivery: queued');
+ expect(transcript).toContain('State: streaming');
+ });
+
+ it('emits Time but not Model metadata for a user message', () => {
+ const transcript = render([
+ { id: 'u1', role: 'user', content: 'Hello', timestamp },
+ ]);
+ expect(transcript).toContain('Time:');
+ expect(transcript).not.toContain('Model:');
+ });
+
+ it('does not push a metadata block when no metadata fields are populated', () => {
+ const transcript = render([
+ {
+ id: 'u1',
+ role: 'user',
+ content: 'Hello',
+ timestamp: undefined as unknown as Date,
+ },
+ ]);
+ expect(transcript).toContain('Hello');
+ expect(transcript).not.toContain('Time:');
+ expect(transcript).not.toContain('Model:');
+ expect(transcript).not.toContain('Delivery:');
+ expect(transcript).not.toContain('State:');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// appendAssistantStreamEvents — fallback loops, guard-false arms, error/interruption
+// ---------------------------------------------------------------------------
+
+describe('appendAssistantStreamEvents fallback and guard branches', () => {
+ it('renders persisted pendingTools when no pending_tool stream event is present', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ pendingTools: [
+ {
+ id: 'p1',
+ name: 'pulse_read',
+ input: readToolInput('ls /dev'),
+ },
+ ],
+ },
+ ]);
+ expect(transcript).toContain('[tool:read]');
+ expect(transcript).toContain('pending');
+ });
+
+ it('renders persisted pendingApprovals when no approval stream event is present', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ pendingApprovals: [
+ {
+ toolId: 't1',
+ toolName: 'pulse_run_command',
+ command: 'systemctl restart nginx',
+ description: 'Restart nginx',
+ runOnHost: true,
+ },
+ ],
+ },
+ ]);
+ expect(transcript).toContain('[approval:cmd]');
+ expect(transcript).toContain('approval required');
+ });
+
+ it('renders persisted pendingQuestions when no question stream event is present', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ pendingQuestions: [
+ {
+ questionId: 'q1',
+ questions: [{ id: 'i1', type: 'text', question: 'Which host?' }],
+ },
+ ],
+ },
+ ]);
+ expect(transcript).toContain('[question] Which host?');
+ });
+
+ it('renders the error block for a failed turn', () => {
+ const transcript = render([
+ { id: 'a1', role: 'assistant', content: '', timestamp, error: 'Model timed out' },
+ ]);
+ expect(transcript).toContain('[error] Model timed out');
+ });
+
+ it('renders a stopped interruption notice', () => {
+ const transcript = render([
+ { id: 'a1', role: 'assistant', content: 'partial answer', timestamp, interruption: 'stopped' },
+ ]);
+ expect(transcript).toContain('[interrupted] Stopped by user');
+ });
+
+ it('renders a replaced interruption notice', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'partial answer',
+ timestamp,
+ interruption: 'replaced',
+ },
+ ]);
+ expect(transcript).toContain('[interrupted] Replaced by a later user message');
+ });
+
+ it('skips thinking events when includeThinking is not enabled', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Public answer',
+ timestamp,
+ streamEvents: [{ type: 'thinking', thinking: 'Private reasoning' }],
+ },
+ ]);
+ expect(transcript).toContain('Public answer');
+ expect(transcript).not.toContain('[thinking]');
+ expect(transcript).not.toContain('Private reasoning');
+ });
+
+ it('does not set toolAppended when a tool event lacks a payload, allowing toolCalls fallback', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ streamEvents: [{ type: 'tool' }],
+ toolCalls: [
+ {
+ name: 'pulse_read',
+ input: readToolInput('ls /dev'),
+ output: '',
+ success: true,
+ },
+ ],
+ },
+ ]);
+ // The guard `if (event.tool)` was false, so the fallback toolCalls loop fires
+ expect(transcript).toContain('[tool:read]');
+ expect(transcript).toContain('completed');
+ });
+
+ it('does not render a pending tool when a pending_tool event lacks a payload', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Visible content',
+ timestamp,
+ streamEvents: [{ type: 'pending_tool' }],
+ },
+ ]);
+ expect(transcript).toContain('Visible content');
+ expect(transcript).not.toContain('[tool:');
+ });
+
+ it('does not render a canceled tool when a tool_cancel event lacks a payload', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Visible content',
+ timestamp,
+ streamEvents: [{ type: 'tool_cancel' }],
+ },
+ ]);
+ expect(transcript).toContain('Visible content');
+ expect(transcript).not.toContain('skipped');
+ expect(transcript).not.toContain('[tool:');
+ });
+
+ it('does not render an approval when an approval event lacks a payload', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Visible content',
+ timestamp,
+ streamEvents: [{ type: 'approval' }],
+ },
+ ]);
+ expect(transcript).toContain('Visible content');
+ expect(transcript).not.toContain('[approval:');
+ });
+
+ it('does not render a question when a question event lacks a payload', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Visible content',
+ timestamp,
+ streamEvents: [{ type: 'question' }],
+ },
+ ]);
+ expect(transcript).toContain('Visible content');
+ expect(transcript).not.toContain('[question]');
+ });
+
+ it('silently ignores unknown event types via the default arm', () => {
+ const transcript = render([
+ {
+ id: 'a1',
+ role: 'assistant',
+ content: 'Visible content',
+ timestamp,
+ streamEvents: [{ type: 'bogus' } as unknown as StreamDisplayEvent],
+ },
+ ]);
+ expect(transcript).toContain('Visible content');
+ expect(transcript).not.toContain('[bogus]');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatAssistantTranscript — structural edge cases
+// ---------------------------------------------------------------------------
+
+describe('formatAssistantTranscript structural edge cases', () => {
+ it('returns empty string when no messages have content', () => {
+ expect(formatAssistantTranscript({ messages: [] })).toBe('');
+ expect(
+ formatAssistantTranscript({
+ messages: [{ id: 'a1', role: 'assistant', content: '', timestamp }],
+ }),
+ ).toBe('');
+ });
+
+ it('skips messages that have no renderable content but includes those that do', () => {
+ const transcript = render([
+ { id: 'empty', role: 'assistant', content: '', timestamp },
+ { id: 'user-1', role: 'user', content: 'Hello world', timestamp },
+ ]);
+ expect(transcript).not.toContain('## User\n\n\nHello world');
+ expect(transcript).toContain('## User');
+ expect(transcript).toContain('Hello world');
+ // The empty assistant message is skipped entirely
+ expect(transcript).not.toContain('## Pulse Assistant');
+ });
+
+ it('omits Session lines when session has no title or id', () => {
+ const transcript = render([{ id: 'u1', role: 'user', content: 'Hi', timestamp }], {
+ session: {},
+ });
+ expect(transcript).not.toContain('Session:');
+ expect(transcript).not.toContain('Session ID:');
+ });
+
+ it('collapses three or more consecutive newlines into two', () => {
+ const transcript = render([
+ { id: 'u1', role: 'user', content: 'A\n\n\n\n\nB', timestamp },
+ ]);
+ expect(transcript).not.toMatch(/\n{3,}/);
+ expect(transcript).toContain('A');
+ expect(transcript).toContain('B');
+ });
+});
diff --git a/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov.test.ts b/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov.test.ts
new file mode 100644
index 0000000000..0a0f2ade07
--- /dev/null
+++ b/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov.test.ts
@@ -0,0 +1,198 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getAlertResourceMetricDisplayValue,
+ type AlertResourceTableResourceLike,
+ type AlertResourceThresholdMap,
+} from '../alertResourceTableModel';
+
+function makeResource(
+ overrides: Partial<AlertResourceTableResourceLike> = {},
+): AlertResourceTableResourceLike {
+ return {
+ id: 'res-1',
+ name: 'Test VM',
+ ...overrides,
+ };
+}
+
+describe('getAlertResourceMetricDisplayValue — extract() branch coverage', () => {
+ describe('extract over editingThresholds (isEditing = true)', () => {
+ it('returns the edited numeric value when present', () => {
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', { cpu: 42 }, true)).toBe(42);
+ });
+
+ it('returns literal 0 for an edited value of 0 (no falsy collapse)', () => {
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', { cpu: 0 }, true)).toBe(0);
+ });
+
+ it('parses an edited numeric string into a number', () => {
+ const edited = { cpu: '42' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(42);
+ });
+
+ it('coerces an edited empty string to 0 via Number()', () => {
+ const edited = { cpu: '' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(0);
+ });
+
+ it('coerces an edited boolean true to 1 via Number()', () => {
+ const edited = { cpu: true } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(1);
+ });
+
+ it('coerces an edited boolean false to 0 via Number()', () => {
+ const edited = { cpu: false } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(0);
+ });
+
+ it('coerces a single-element numeric array via Number()', () => {
+ const edited = { cpu: [42] } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(42);
+ });
+
+ it('coerces an empty array to 0 via Number()', () => {
+ const edited = { cpu: [] } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(0);
+ });
+
+ it('propagates a numeric NaN edited value through the typeof-number branch', () => {
+ const edited = { cpu: NaN } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ const result = getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true);
+ expect(Number.isNaN(result)).toBe(true);
+ });
+
+ it('propagates a numeric Infinity edited value through the typeof-number branch', () => {
+ const edited = { cpu: Infinity } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(Infinity);
+ });
+
+ it('falls back to defaults when edited value is null', () => {
+ const edited = { cpu: null } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(75);
+ });
+
+ it('falls back to defaults when edited value is a non-numeric string', () => {
+ const edited = { cpu: 'not-a-number' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(75);
+ });
+
+ it('falls back to defaults when edited value is a multi-element array (Number -> NaN)', () => {
+ const edited = { cpu: [1, 2] } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(75);
+ });
+
+ it('falls back to defaults when edited value is a plain object (Number -> NaN)', () => {
+ const edited = { cpu: { v: 1 } } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(75);
+ });
+
+ it('falls back to defaults when metric is absent from editingThresholds', () => {
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', {}, true)).toBe(75);
+ });
+
+ it('falls back to defaults when editingThresholds is undefined', () => {
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', undefined, true)).toBe(75);
+ });
+
+ it('returns 0 when neither edited value nor defaults are usable', () => {
+ const resource = makeResource();
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', {}, true)).toBe(0);
+ });
+
+ it('returns 0 when defaults value is explicitly undefined', () => {
+ const resource = makeResource({ defaults: { cpu: undefined } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', {}, true)).toBe(0);
+ });
+ });
+
+ describe('extract over live thresholds (isEditing = false)', () => {
+ it('returns the live numeric value when present', () => {
+ const resource = makeResource({ thresholds: { cpu: 80 }, defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(80);
+ });
+
+ it('returns literal 0 for a live value of 0 (no falsy collapse, skips defaults)', () => {
+ const resource = makeResource({ thresholds: { cpu: 0 }, defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('parses a live numeric string into a number', () => {
+ const thresholds = { cpu: '80' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds, defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(80);
+ });
+
+ it('coerces a live empty string to 0 via Number()', () => {
+ const thresholds = { cpu: '' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds, defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('falls back to defaults when live value is null', () => {
+ const thresholds = { cpu: null } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds, defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(75);
+ });
+
+ it('falls back to defaults when live value is a non-numeric string', () => {
+ const thresholds = { cpu: 'oops' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds, defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(75);
+ });
+
+ it('falls back to defaults when metric is absent from thresholds', () => {
+ const resource = makeResource({ thresholds: {}, defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(75);
+ });
+
+ it('falls back to defaults when thresholds is undefined', () => {
+ const resource = makeResource({ defaults: { cpu: 75 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(75);
+ });
+
+ it('parses a numeric-string default when falling back', () => {
+ const defaults = { cpu: '60' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(60);
+ });
+
+ it('returns 0 when no usable thresholds or defaults exist', () => {
+ const resource = makeResource();
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('returns 0 when defaults value is null', () => {
+ const defaults = { cpu: null } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('returns 0 when defaults value is a non-numeric string', () => {
+ const defaults = { cpu: 'nope' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('returns 0 when defaults value is explicitly undefined', () => {
+ const resource = makeResource({ defaults: { cpu: undefined } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerServiceModel.branchcov.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerServiceModel.branchcov.test.ts
new file mode 100644
index 0000000000..18349aadbe
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerServiceModel.branchcov.test.ts
@@ -0,0 +1,574 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildPbsActiveTasks,
+ buildPbsJobHealthEvidenceModel,
+ getPbsActivitySummary,
+} from '@/components/Infrastructure/resourceDetailDrawerServiceModel';
+import type { PBSPlatformData } from '@/components/Infrastructure/resourceDetailMappers';
+import type {
+ PBSBackupJob,
+ PBSGarbageJob,
+ PBSJobHealthEvidence,
+ PBSPruneJob,
+ PBSSyncJob,
+ PBSVerifyJob,
+} from '@/types/api';
+
+// The target helpers (formatPbsBackupWorkload, formatPbsEvidenceSource,
+// formatPbsEvidenceFamily, buildPbsEvidenceContext, buildPbsEvidenceFreshnessLabel,
+// buildPbsTaskLabel, normalizePbsTaskStatus, isPbsTaskStatusActive) are module-private
+// and never exported. They are exercised here exclusively through the three exported
+// entry points that consume them: buildPbsActiveTasks, getPbsActivitySummary, and
+// buildPbsJobHealthEvidenceModel. No private symbol is imported.
+
+const ACTIVE = 'running';
+
+const backupJob = (overrides: Partial<PBSBackupJob> = {}): PBSBackupJob => ({
+ id: 'bk-1',
+ store: 'fast',
+ type: 'vm',
+ vmid: '100',
+ lastBackup: '',
+ nextRun: '',
+ status: ACTIVE,
+ error: '',
+ ...overrides,
+});
+
+const syncJob = (overrides: Partial<PBSSyncJob> = {}): PBSSyncJob => ({
+ id: 'sync-1',
+ store: 'fast',
+ remote: 'offsite',
+ status: ACTIVE,
+ lastSync: '',
+ nextRun: '',
+ error: '',
+ ...overrides,
+});
+
+const verifyJob = (overrides: Partial<PBSVerifyJob> = {}): PBSVerifyJob => ({
+ id: 'verify-1',
+ store: 'fast',
+ status: ACTIVE,
+ lastVerify: '',
+ nextRun: '',
+ error: '',
+ ...overrides,
+});
+
+const pruneJob = (overrides: Partial<PBSPruneJob> = {}): PBSPruneJob => ({
+ id: 'prune-1',
+ store: 'fast',
+ status: ACTIVE,
+ lastPrune: '',
+ nextRun: '',
+ error: '',
+ ...overrides,
+});
+
+const garbageJob = (overrides: Partial<PBSGarbageJob> = {}): PBSGarbageJob => ({
+ id: 'gc-1',
+ store: 'fast',
+ status: ACTIVE,
+ lastGarbage: '',
+ nextRun: '',
+ removedBytes: 0,
+ error: '',
+ ...overrides,
+});
+
+const evidence = (overrides: Partial<PBSJobHealthEvidence> = {}): PBSJobHealthEvidence => ({
+ id: 'ev-1',
+ family: 'backup',
+ store: 'fast',
+ confidence: 'direct',
+ ...overrides,
+});
+
+// Locate a single active task by id; avoids over-asserting on ordering extras.
+const taskWithId = (pbs: PBSPlatformData | undefined, id: string) =>
+ buildPbsActiveTasks(pbs).find((task) => task.id === id);
+
+const evidenceWithId = (pbs: PBSPlatformData | undefined, id: string) =>
+ buildPbsJobHealthEvidenceModel(pbs).entries.find((entry) => entry.id === id);
+
+describe('isPbsTaskStatusActive / normalizePbsTaskStatus (via buildPbsActiveTasks)', () => {
+ it.each([
+ ['empty string', ''],
+ ['whitespace only', ' '],
+ ['inactive token "ok"', 'ok'],
+ ['inactive token "failed"', 'failed'],
+ ['inactive token "stopped"', 'stopped'],
+ ['unrecognized token', 'flurbo'],
+ ['uppercase inactive "SUCCESS"', 'SUCCESS'],
+ ])('excludes a backup job whose status is not active (%s)', (_label, status) => {
+ const pbs: PBSPlatformData = { backupJobs: [backupJob({ id: 'bk', status })] };
+ expect(buildPbsActiveTasks(pbs).find((task) => task.id === 'bk')).toBeUndefined();
+ });
+
+ it.each([
+ ['running', 'running', 'Running'],
+ ['queued', 'queued', 'Queued'],
+ ['pending', 'pending', 'Pending'],
+ ['underscore-delimited active token', 'in_progress', 'In Progress'],
+ ['hyphen-delimited active token', 'in-progress', 'In Progress'],
+ ['uppercase status', 'RUNNING', 'Running'],
+ ['whitespace-padded status', ' starting ', 'Starting'],
+ ])('includes a backup job whose normalized status is active (%s)', (_label, status, label) => {
+ const pbs: PBSPlatformData = { backupJobs: [backupJob({ id: 'bk', status })] };
+ expect(taskWithId(pbs, 'bk')?.statusLabel).toBe(label);
+ });
+
+ it('treats an undefined status as inactive (guard branch)', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', status: undefined as unknown as string })],
+ };
+ expect(buildPbsActiveTasks(pbs).find((task) => task.id === 'bk')).toBeUndefined();
+ });
+
+ it('lets an inactive token override an active token in the same status (precedence)', () => {
+ // "running ok" contains both an active ("running") and an inactive ("ok") token;
+ // the inactive check short-circuits first, so the job is excluded.
+ const pbs: PBSPlatformData = { backupJobs: [backupJob({ id: 'bk', status: 'running ok' })] };
+ expect(buildPbsActiveTasks(pbs).find((task) => task.id === 'bk')).toBeUndefined();
+ });
+});
+
+describe('buildPbsTaskLabel (via buildPbsActiveTasks / buildPbsJobHealthEvidenceModel)', () => {
+ it('suffixes the task type with the job id when an id is present', () => {
+ const pbs: PBSPlatformData = { verifyJobs: [verifyJob({ id: 'verify-9' })] };
+ expect(taskWithId(pbs, 'verify-9')?.label).toBe('Verify verify-9');
+ });
+
+ it('returns the bare task type when the id trims to empty', () => {
+ const pbs: PBSPlatformData = { pruneJobs: [pruneJob({ id: ' ' })] };
+ const tasks = buildPbsActiveTasks(pbs);
+ expect(tasks).toHaveLength(1);
+ // id was whitespace-only, so the entry is keyed on the trimmed-empty id and the
+ // label drops the suffix entirely.
+ expect(tasks[0]?.label).toBe('Prune');
+ });
+
+ it('uses the "Garbage Collection" task type for garbage jobs', () => {
+ const pbs: PBSPlatformData = { garbageJobs: [garbageJob({ id: 'gc-1' })] };
+ expect(taskWithId(pbs, 'gc-1')?.label).toBe('Garbage Collection gc-1');
+ });
+});
+
+describe('formatPbsBackupWorkload (via backup task context)', () => {
+ it('renders "VM <vmid>" for vm workloads', () => {
+ const pbs: PBSPlatformData = { backupJobs: [backupJob({ id: 'bk', type: 'vm', vmid: '100' })] };
+ expect(taskWithId(pbs, 'bk')?.context).toBe('fast · VM 100');
+ });
+
+ it('renders "Container <vmid>" for ct workloads', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', type: 'ct', vmid: '200', store: 'archive' })],
+ };
+ expect(taskWithId(pbs, 'bk')?.context).toBe('archive · Container 200');
+ });
+
+ it('title-cases an unrecognized workload type via normalizeDelimitedLabel', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', type: 'storage', vmid: '300' })],
+ };
+ expect(taskWithId(pbs, 'bk')?.context).toBe('fast · Storage 300');
+ });
+
+ it('keeps the type label only when vmid is empty', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', type: 'vm', vmid: '', store: 'archive' })],
+ };
+ expect(taskWithId(pbs, 'bk')?.context).toBe('archive · VM');
+ });
+
+ it('falls back to the "Workload" label when only vmid is present', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', type: '', vmid: '400' })],
+ };
+ expect(taskWithId(pbs, 'bk')?.context).toBe('fast · Workload 400');
+ });
+
+ it('drops the workload segment entirely when both type and vmid are empty', () => {
+ // formatPbsBackupWorkload returns null, so context reduces to just the store.
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', type: '', vmid: '', store: 'fast' })],
+ };
+ expect(taskWithId(pbs, 'bk')?.context).toBe('fast');
+ });
+
+ it('produces a null context when store, type and vmid are all empty', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', type: '', vmid: '', store: '' })],
+ };
+ expect(taskWithId(pbs, 'bk')?.context).toBeNull();
+ });
+
+ it('normalizes a UPPERCASE type to its canonical label', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [backupJob({ id: 'bk', type: 'CT', vmid: '500' })],
+ };
+ expect(taskWithId(pbs, 'bk')?.context).toBe('fast · Container 500');
+ });
+});
+
+describe('buildPbsActiveTasks entry-point guards', () => {
+ it('returns an empty array for undefined pbs', () => {
+ expect(buildPbsActiveTasks(undefined)).toEqual([]);
+ });
+
+ it('returns an empty array when no job arrays are present', () => {
+ expect(buildPbsActiveTasks({})).toEqual([]);
+ });
+
+ it('handles null job arrays defensively (coalesces to empty)', () => {
+ const pbs = {
+ backupJobs: undefined,
+ syncJobs: null,
+ verifyJobs: undefined,
+ pruneJobs: null,
+ garbageJobs: undefined,
+ } as unknown as PBSPlatformData;
+ expect(buildPbsActiveTasks(pbs)).toEqual([]);
+ });
+
+ it('surfaces a trimmed job error and omits it when blank', () => {
+ const pbs: PBSPlatformData = {
+ backupJobs: [
+ backupJob({ id: 'bk-err', error: ' boom ' }),
+ backupJob({ id: 'bk-clean', error: '' }),
+ backupJob({ id: 'bk-ws', error: ' ' }),
+ ],
+ };
+ const tasks = buildPbsActiveTasks(pbs);
+ expect(taskWithId(pbs, 'bk-err')?.error).toBe('boom');
+ expect(taskWithId(pbs, 'bk-clean')?.error).toBeUndefined();
+ expect(taskWithId(pbs, 'bk-ws')?.error).toBeUndefined();
+ expect(tasks).toHaveLength(3);
+ });
+
+ it('includes active verify, prune and garbage tasks with store-only context', () => {
+ const pbs: PBSPlatformData = {
+ verifyJobs: [verifyJob({ id: 'v', store: 'vstore' })],
+ pruneJobs: [pruneJob({ id: 'p', store: 'pstore' })],
+ garbageJobs: [garbageJob({ id: 'g', store: 'gstore' })],
+ };
+ expect(taskWithId(pbs, 'v')).toEqual({
+ id: 'v',
+ label: 'Verify v',
+ context: 'vstore',
+ statusLabel: 'Running',
+ error: undefined,
+ });
+ expect(taskWithId(pbs, 'p')?.context).toBe('pstore');
+ expect(taskWithId(pbs, 'g')?.context).toBe('gstore');
+ });
+
+ it('renders a sync task without a remote as store-only context', () => {
+ const pbs: PBSPlatformData = { syncJobs: [syncJob({ id: 's', remote: '' })] };
+ expect(taskWithId(pbs, 's')?.context).toBe('fast');
+ });
+});
+
+describe('getPbsActivitySummary', () => {
+ it('returns a null label and zero count for undefined pbs', () => {
+ expect(getPbsActivitySummary(undefined)).toEqual({
+ label: null,
+ detail: null,
+ activeTaskCount: 0,
+ });
+ });
+
+ it('returns a null label when there are no jobs and no active tasks', () => {
+ expect(getPbsActivitySummary({})).toEqual({
+ label: null,
+ detail: null,
+ activeTaskCount: 0,
+ });
+ });
+
+ it('reports "N jobs" with no detail when jobs exist but none are active', () => {
+ const pbs: PBSPlatformData = {
+ backupJobCount: 2,
+ verifyJobCount: 1,
+ backupJobs: [backupJob({ id: 'a', status: 'ok' })],
+ };
+ expect(getPbsActivitySummary(pbs)).toEqual({
+ label: '3 jobs',
+ detail: null,
+ activeTaskCount: 0,
+ });
+ });
+
+ it('omits the total detail when active count equals total job count', () => {
+ const pbs: PBSPlatformData = {
+ backupJobCount: 1,
+ backupJobs: [backupJob({ id: 'only', status: 'running' })],
+ };
+ expect(getPbsActivitySummary(pbs)).toEqual({
+ label: '1 active',
+ detail: null,
+ activeTaskCount: 1,
+ });
+ });
+
+ it('includes the total detail when more jobs exist than are active', () => {
+ const pbs: PBSPlatformData = {
+ backupJobCount: 2,
+ backupJobs: [
+ backupJob({ id: 'run', status: 'running' }),
+ backupJob({ id: 'idle', status: 'ok' }),
+ ],
+ };
+ expect(getPbsActivitySummary(pbs)).toEqual({
+ label: '1 active',
+ detail: '2 total',
+ activeTaskCount: 1,
+ });
+ });
+
+ it('counts active tasks across every job family for the summary', () => {
+ const pbs: PBSPlatformData = {
+ backupJobCount: 1,
+ syncJobCount: 1,
+ verifyJobCount: 1,
+ pruneJobCount: 1,
+ garbageJobCount: 1,
+ backupJobs: [backupJob({ id: 'b', status: 'running' })],
+ syncJobs: [syncJob({ id: 's', status: 'queued' })],
+ verifyJobs: [verifyJob({ id: 'v', status: 'starting' })],
+ pruneJobs: [pruneJob({ id: 'p', status: 'in progress' })],
+ garbageJobs: [garbageJob({ id: 'g', status: 'pending' })],
+ };
+ expect(getPbsActivitySummary(pbs)).toEqual({
+ label: '5 active',
+ detail: null,
+ activeTaskCount: 5,
+ });
+ });
+});
+
+describe('formatPbsEvidenceFamily (via evidence label)', () => {
+ it.each([
+ ['backup', 'Backup'],
+ ['sync', 'Sync'],
+ ['verify', 'Verify'],
+ ['prune', 'Prune'],
+ ['garbage', 'Garbage collection'],
+ ['BACKUP', 'Backup'],
+ // NOTE: 'garbage-collection' normalizes to 'garbage collection', which does
+ // NOT equal the exact token 'garbage', so it bypasses the canonical branch
+ // and falls through to the generic title-case path — yielding 'Collection'
+ // with a capital C instead of the canonical lowercase 'c'. See GLM_REPORT.md.
+ ['garbage-collection', 'Garbage Collection'],
+ ])('maps family %s to %s', (family, expected) => {
+ const pbs: PBSPlatformData = { jobHealthEvidence: [evidence({ id: 'fam', family })] };
+ expect(evidenceWithId(pbs, 'fam')?.label).toBe(`${expected} fam`);
+ });
+
+ it('title-cases an unrecognized family', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'fam', family: 're-index' })],
+ };
+ expect(evidenceWithId(pbs, 'fam')?.label).toBe('Re Index fam');
+ });
+
+ it('falls back to "Job" when the family is empty', () => {
+ const pbs: PBSPlatformData = { jobHealthEvidence: [evidence({ id: 'fam', family: '' })] };
+ expect(evidenceWithId(pbs, 'fam')?.label).toBe('Job fam');
+ });
+
+ it('drops the id suffix when the evidence id trims to empty', () => {
+ const pbs: PBSPlatformData = { jobHealthEvidence: [evidence({ id: ' ', family: 'sync' })] };
+ expect(buildPbsJobHealthEvidenceModel(pbs).entries[0]?.label).toBe('Sync');
+ });
+});
+
+describe('formatPbsEvidenceSource (via evidence sourceLabel)', () => {
+ it('returns "Observed backup task history" for backup family with task history', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({ id: 'src', family: 'backup', evidenceSource: 'pbs-task-history' }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('Observed backup task history');
+ });
+
+ it('returns the generic "Observed task history" for non-backup task history', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({ id: 'src', family: 'verify', evidenceScope: 'task-history' }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('Observed task history');
+ });
+
+ it('returns "Configured PBS job" for the configured-job scope', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'src', evidenceScope: 'configured-job' })],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('Configured PBS job');
+ });
+
+ it('returns "Configured PBS job" when the source mentions job config', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'src', evidenceSource: 'pbs job config reader' })],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('Configured PBS job');
+ });
+
+ it('returns "Partial PBS read" for the partial-read scope', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'src', evidenceScope: 'partial-read' })],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('Partial PBS read');
+ });
+
+ it('title-cases a free-form source as the fallback', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'src', evidenceSource: 'pbs-datastore-scan' })],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('Pbs Datastore Scan');
+ });
+
+ it('falls back to "PBS evidence" when source and scope are empty', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'src', evidenceSource: '', evidenceScope: '' })],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('PBS evidence');
+ });
+
+ it('prefers configured-job over partial-read when both signals appear', () => {
+ // configured-job is checked before partial-read in source precedence.
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({ id: 'src', evidenceScope: 'configured job', evidenceSource: 'partial read' }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'src')?.sourceLabel).toBe('Configured PBS job');
+ });
+});
+
+describe('buildPbsEvidenceContext (via evidence context)', () => {
+ it('joins store, remote, namespace and worker-id when all are present', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({
+ id: 'ctx',
+ store: 'fast',
+ remote: 'offsite',
+ namespace: 'tenant-a',
+ 'worker-id': 'w1',
+ }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'ctx')?.context).toBe(
+ 'fast · Remote offsite · Namespace tenant-a · Worker w1',
+ );
+ });
+
+ it('renders only the remote segment when store is absent', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'ctx', store: '', remote: 'offsite' })],
+ };
+ expect(evidenceWithId(pbs, 'ctx')?.context).toBe('Remote offsite');
+ });
+
+ it('returns null when every context segment is absent', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({ id: 'ctx', store: '', remote: '', namespace: '', 'worker-id': '' }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'ctx')?.context).toBeNull();
+ });
+});
+
+describe('buildPbsEvidenceFreshnessLabel (via evidence freshnessLabel)', () => {
+ it('prefers the ISO last-run-end time from freshness', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({
+ id: 'fr',
+ freshness: { observedAt: '2026-05-01T08:00:00Z', lastRunEndTime: '2026-04-20T21:30:00Z' },
+ 'last-run-endtime': 1776717000,
+ }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'fr')?.freshnessLabel).toBe('Last run 2026-04-20T21:30:00Z');
+ });
+
+ it('falls back to the unix last-run-endtime when the ISO time is absent', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({ id: 'fr', 'last-run-endtime': 1776717000 }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'fr')?.freshnessLabel).toBe('Last run 2026-04-20T20:30:00Z');
+ });
+
+ it('reports "Task ended" from the unix task-endtime when no last run is present', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'fr', 'task-endtime': 1700000000 })],
+ };
+ expect(evidenceWithId(pbs, 'fr')?.freshnessLabel).toBe('Task ended 2023-11-14T22:13:20Z');
+ });
+
+ it('reports "Next run" from the unix next-run when nothing earlier is present', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [evidence({ id: 'fr', 'next-run': 1800000000 })],
+ };
+ expect(evidenceWithId(pbs, 'fr')?.freshnessLabel).toBe('Next run 2027-01-15T08:00:00Z');
+ });
+
+ it('reports "Observed" from the freshness observedAt as the final fallback', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({ id: 'fr', freshness: { observedAt: '2026-05-01T08:00:00Z' } }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'fr')?.freshnessLabel).toBe('Observed 2026-05-01T08:00:00Z');
+ });
+
+ it('returns null when no freshness signal of any kind is present', () => {
+ const pbs: PBSPlatformData = { jobHealthEvidence: [evidence({ id: 'fr' })] };
+ expect(evidenceWithId(pbs, 'fr')?.freshnessLabel).toBeNull();
+ });
+
+ it('treats a non-finite unix last-run-endtime as absent and falls through', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidence: [
+ evidence({
+ id: 'fr',
+ 'last-run-endtime': Number.NaN,
+ 'task-endtime': 1700000000,
+ }),
+ ],
+ };
+ expect(evidenceWithId(pbs, 'fr')?.freshnessLabel).toBe('Task ended 2023-11-14T22:13:20Z');
+ });
+});
+
+describe('buildPbsJobHealthEvidenceModel aggregation', () => {
+ it('returns a zero-evidence model for undefined pbs', () => {
+ expect(buildPbsJobHealthEvidenceModel(undefined)).toEqual({
+ evidenceCount: 0,
+ visibleCount: 0,
+ countLabel: null,
+ entries: [],
+ });
+ });
+
+ it('uses the greater of the declared count and the visible entries', () => {
+ const pbs: PBSPlatformData = {
+ jobHealthEvidenceCount: 5,
+ jobHealthEvidence: [evidence({ id: 'a' }), evidence({ id: 'b' })],
+ };
+ expect(buildPbsJobHealthEvidenceModel(pbs)).toMatchObject({
+ evidenceCount: 5,
+ visibleCount: 2,
+ countLabel: '5 evidence records',
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.branchcov.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.branchcov.test.ts
new file mode 100644
index 0000000000..ccff3af114
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.branchcov.test.ts
@@ -0,0 +1,625 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildDisk,
+ buildMemory,
+ buildTemperatureRows,
+ toAgentDisks,
+ toNodeFromProxmox,
+ type AgentDiskInfo,
+ type PlatformData,
+} from '@/components/Infrastructure/resourceDetailMappers';
+import type { Disk, HostSensorSummary, Memory as MemoryType } from '@/types/api';
+import type { Resource, ResourceMetric } from '@/types/resource';
+
+/**
+ * Branch-coverage suite for the currently-uncovered functions in
+ * resourceDetailMappers.ts. Several targets (asString, getPreferredHostLabel,
+ * formatGPUStatsLabel, formatPowerWatts, buildTypedGPUTemperatureKeys) are
+ * module-private, so they are driven exclusively through the exported entry
+ * points (toNodeFromProxmox, buildTemperatureRows) and asserted on observable
+ * return values — never re-implemented or imported directly.
+ */
+
+const baseProxmoxResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'resource:host:hash-1',
+ type: 'agent',
+ name: 'tower',
+ displayName: 'Tower',
+ platformId: 'tower',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ cpu: { current: 12 },
+ memory: { current: 0.25, total: 1024, used: 256, free: 768 },
+ disk: { current: 0.25, total: 2048, used: 512, free: 1536 },
+ platformData: {
+ proxmox: { nodeName: 'pve-node-1' },
+ agent: { agentId: 'agent-canonical' },
+ },
+ ...overrides,
+ }) as unknown as Resource;
+
+describe('buildMemory', () => {
+ it('prefers metric values over fallback values', () => {
+ const metric: ResourceMetric = { current: 0.5, total: 100, used: 50, free: 50 };
+ const fallback: Partial<MemoryType> = { total: 999, used: 1, free: 2, usage: 0.9 };
+
+ expect(buildMemory(metric, fallback)).toEqual({ total: 100, used: 50, free: 50, usage: 0.5 });
+ });
+
+ it('falls back to the fallback memory when no metric is given', () => {
+ const fallback: Partial<MemoryType> = { total: 200, used: 80, free: 120, usage: 0.4 };
+
+ expect(buildMemory(undefined, fallback)).toEqual({
+ total: 200,
+ used: 80,
+ free: 120,
+ usage: 0.4,
+ });
+ });
+
+ it('computes usage from total>0 and ignores fallback.usage', () => {
+ const fallback: Partial<MemoryType> = { usage: 0.99 };
+
+ expect(buildMemory({ current: 0, total: 100, used: 25 }, fallback)).toEqual({
+ total: 100,
+ used: 25,
+ free: 75,
+ usage: 0.25,
+ });
+ });
+
+ it('returns fallback.usage when total is 0 and metric is absent', () => {
+ const fallback: Partial<MemoryType> = { usage: 0.42 };
+
+ expect(buildMemory(undefined, fallback).usage).toBe(0.42);
+ });
+
+ it('defaults every field to 0 with no metric and no fallback', () => {
+ expect(buildMemory()).toEqual({ total: 0, used: 0, free: 0, usage: 0 });
+ });
+
+ it('computes free as max(total - used, 0) when free is missing everywhere', () => {
+ expect(buildMemory({ current: 0.3, total: 100, used: 30 }).free).toBe(70);
+ });
+
+ it('clamps free to 0 when used exceeds total and free is missing', () => {
+ expect(buildMemory({ current: 1, total: 10, used: 30 }).free).toBe(0);
+ });
+
+ it('uses metric.free over computed free even when fallback.free exists', () => {
+ expect(
+ buildMemory({ current: 0, total: 100, used: 10, free: 5 }, { free: 90 }).free,
+ ).toBe(5);
+ });
+});
+
+describe('buildDisk', () => {
+ it('prefers metric values and carries fallback identity fields', () => {
+ const metric: ResourceMetric = { current: 0.5, total: 100, used: 50, free: 50 };
+ const fallback: Partial<Disk> = {
+ total: 9,
+ used: 9,
+ free: 9,
+ mountpoint: '/',
+ type: 'ext4',
+ device: 'sda1',
+ };
+
+ expect(buildDisk(metric, fallback)).toEqual({
+ total: 100,
+ used: 50,
+ free: 50,
+ usage: 0.5,
+ mountpoint: '/',
+ type: 'ext4',
+ device: 'sda1',
+ });
+ });
+
+ it('falls back to fallback disk when no metric is given', () => {
+ const fallback: Partial<Disk> = { total: 200, used: 80, free: 120, usage: 0.4 };
+
+ expect(buildDisk(undefined, fallback)).toEqual({
+ total: 200,
+ used: 80,
+ free: 120,
+ usage: 0.4,
+ mountpoint: undefined,
+ type: undefined,
+ device: undefined,
+ });
+ });
+
+ it('computes usage from total>0 and ignores fallback.usage', () => {
+ expect(buildDisk({ current: 0, total: 200, used: 50 }, { usage: 0.99 }).usage).toBe(0.25);
+ });
+
+ it('returns fallback.usage when total is 0 and metric is absent', () => {
+ expect(buildDisk(undefined, { usage: 0.42 }).usage).toBe(0.42);
+ });
+
+ it('defaults every field to 0 with no metric and no fallback', () => {
+ expect(buildDisk()).toEqual({
+ total: 0,
+ used: 0,
+ free: 0,
+ usage: 0,
+ mountpoint: undefined,
+ type: undefined,
+ device: undefined,
+ });
+ });
+
+ it('computes free as max(total - used, 0) when free is missing everywhere', () => {
+ expect(buildDisk({ current: 0.3, total: 100, used: 30 }).free).toBe(70);
+ });
+
+ it('clamps free to 0 when used exceeds total and free is missing', () => {
+ expect(buildDisk({ current: 1, total: 10, used: 30 }).free).toBe(0);
+ });
+});
+
+describe('toAgentDisks', () => {
+ it('returns undefined for undefined input', () => {
+ expect(toAgentDisks(undefined)).toBeUndefined();
+ });
+
+ it('returns undefined for an empty array', () => {
+ expect(toAgentDisks([])).toBeUndefined();
+ });
+
+ it('returns undefined for null input (defensive guard)', () => {
+ expect(toAgentDisks(null as unknown as AgentDiskInfo[])).toBeUndefined();
+ });
+
+ it('maps a fully-populated disk', () => {
+ const disks: AgentDiskInfo[] = [
+ {
+ device: 'sda1',
+ mountpoint: '/',
+ filesystem: 'ext4',
+ type: 'ssd',
+ total: 100,
+ used: 25,
+ free: 75,
+ },
+ ];
+
+ expect(toAgentDisks(disks)).toEqual([
+ {
+ total: 100,
+ used: 25,
+ free: 75,
+ usage: 0.25,
+ mountpoint: '/',
+ type: 'ext4',
+ device: 'sda1',
+ },
+ ]);
+ });
+
+ it('computes usage = used/total when total > 0', () => {
+ expect(toAgentDisks([{ total: 8, used: 2 }])?.[0].usage).toBe(0.25);
+ });
+
+ it('reports usage 0 when total is 0', () => {
+ expect(toAgentDisks([{ total: 0, used: 5 }])?.[0].usage).toBe(0);
+ });
+
+ it('defaults total/used to 0 when missing', () => {
+ expect(toAgentDisks([{}])?.[0]).toEqual({
+ total: 0,
+ used: 0,
+ free: 0,
+ usage: 0,
+ mountpoint: undefined,
+ type: undefined,
+ device: undefined,
+ });
+ });
+
+ it('computes free as max(total - used, 0) when free is missing', () => {
+ expect(toAgentDisks([{ total: 100, used: 30 }])?.[0].free).toBe(70);
+ expect(toAgentDisks([{ total: 10, used: 30 }])?.[0].free).toBe(0);
+ });
+
+ it('falls back to device for mountpoint when mountpoint is absent', () => {
+ expect(toAgentDisks([{ device: 'nvme0n1' }])?.[0].mountpoint).toBe('nvme0n1');
+ });
+
+ it('prefers filesystem over type for the type field', () => {
+ expect(toAgentDisks([{ filesystem: 'zfs', type: 'hdd' }])?.[0].type).toBe('zfs');
+ });
+
+ it('uses type when filesystem is absent', () => {
+ expect(toAgentDisks([{ type: 'nvme' }])?.[0].type).toBe('nvme');
+ });
+
+ it('preserves order across multiple disks', () => {
+ const result = toAgentDisks([{ device: 'a' }, { device: 'b' }]);
+ expect(result?.map((d) => d.device)).toEqual(['a', 'b']);
+ });
+});
+
+describe('toNodeFromProxmox', () => {
+ it('returns null when platformData has no proxmox block', () => {
+ expect(
+ toNodeFromProxmox({ ...baseProxmoxResource(), platformData: { agent: {} } }),
+ ).toBeNull();
+ });
+
+ it('returns null when platformData is absent entirely', () => {
+ expect(toNodeFromProxmox({ ...baseProxmoxResource(), platformData: undefined })).toBeNull();
+ });
+
+ it('maps core fields from a populated proxmox resource', () => {
+ const node = toNodeFromProxmox(baseProxmoxResource());
+
+ expect(node).not.toBeNull();
+ expect(node?.id).toBe('resource:host:hash-1');
+ expect(node?.name).toBe('pve-node-1');
+ expect(node?.host).toBe('pve-node-1');
+ expect(node?.instance).toBe('tower');
+ expect(node?.status).toBe('online');
+ expect(node?.cpu).toBe(12);
+ expect(node?.memory).toEqual({ total: 1024, used: 256, free: 768, usage: 0.25 });
+ expect(node?.disk).toEqual({
+ total: 2048,
+ used: 512,
+ free: 1536,
+ usage: 0.25,
+ mountpoint: undefined,
+ type: undefined,
+ device: undefined,
+ });
+ });
+
+ it('formats lastSeen as an ISO string of the finite timestamp', () => {
+ const node = toNodeFromProxmox(baseProxmoxResource({ lastSeen: 1_700_000_000_000 }));
+ expect(node?.lastSeen).toBe(new Date(1_700_000_000_000).toISOString());
+ });
+
+ it('falls back to "now" when lastSeen is not finite', () => {
+ const before = Date.now();
+ const node = toNodeFromProxmox(
+ baseProxmoxResource({ lastSeen: Number.NaN }),
+ );
+ const after = Date.now();
+
+ expect(node?.lastSeen).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
+ const seenMs = Date.parse(node!.lastSeen);
+ expect(seenMs).toBeGreaterThanOrEqual(before - 1);
+ expect(seenMs).toBeLessThanOrEqual(after + 1);
+ });
+
+ it('prefers resource.uptime over proxmox.uptime', () => {
+ const node = toNodeFromProxmox(
+ baseProxmoxResource({
+ uptime: 111,
+ platformData: { proxmox: { nodeName: 'n', uptime: 222 } },
+ }),
+ );
+ expect(node?.uptime).toBe(111);
+ });
+
+ it('uses proxmox.uptime when resource.uptime is absent', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ uptime: undefined,
+ platformData: { proxmox: { nodeName: 'n', uptime: 222 } },
+ });
+ expect(node?.uptime).toBe(222);
+ });
+
+ it('defaults uptime to 0 when neither source provides it', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ uptime: undefined,
+ platformData: { proxmox: { nodeName: 'n' } },
+ });
+ expect(node?.uptime).toBe(0);
+ });
+
+ it('defaults kernelVersion and pveVersion to "Unknown"', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ platformData: { proxmox: { nodeName: 'n' } },
+ });
+ expect(node?.kernelVersion).toBe('Unknown');
+ expect(node?.pveVersion).toBe('Unknown');
+ });
+
+ it('defaults cpuInfo to Unknown/0 when cpuInfo is absent', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ platformData: { proxmox: { nodeName: 'n' } },
+ });
+ expect(node?.cpuInfo).toEqual({ model: 'Unknown', cores: 0, sockets: 0, mhz: '0' });
+ });
+
+ it('reads cpuInfo fields when present', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ platformData: {
+ proxmox: { nodeName: 'n', cpuInfo: { model: 'Xeon', cores: 8, sockets: 2 } },
+ },
+ });
+ expect(node?.cpuInfo).toEqual({ model: 'Xeon', cores: 8, sockets: 2, mhz: '0' });
+ });
+
+ it('defaults cpu to 0 when resource.cpu is absent', () => {
+ const node = toNodeFromProxmox({ ...baseProxmoxResource(), cpu: undefined });
+ expect(node?.cpu).toBe(0);
+ });
+
+ it('uses resource.id for instance when platformId is absent', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ platformId: undefined,
+ platformData: { proxmox: { nodeName: 'n' } },
+ } as unknown as Resource);
+ expect(node?.instance).toBe('resource:host:hash-1');
+ });
+
+ it('reports connectionHealth from resource.status', () => {
+ const node = toNodeFromProxmox(baseProxmoxResource({ status: 'offline' }));
+ expect(node?.connectionHealth).toBe('offline');
+ });
+
+ it('falls back connectionHealth to "unknown" when status is undefined', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ status: undefined,
+ platformData: { proxmox: { nodeName: 'n' } },
+ } as unknown as Resource);
+ expect(node?.connectionHealth).toBe('unknown');
+ });
+
+ describe('asString (via linkedAgentId resolution)', () => {
+ it('trims and returns a non-empty platformData.linkedAgentId', () => {
+ const platformData = {
+ proxmox: { nodeName: 'n' },
+ linkedAgentId: ' primary-link ',
+ } as unknown as PlatformData;
+ const node = toNodeFromProxmox({ ...baseProxmoxResource(), platformData });
+ expect(node?.linkedAgentId).toBe('primary-link');
+ });
+
+ it('returns undefined for an empty-string linkedAgentId and falls back', () => {
+ const platformData = {
+ proxmox: { nodeName: 'n' },
+ agent: { agentId: 'agent-canonical' },
+ linkedAgentId: '',
+ } as unknown as PlatformData;
+ const node = toNodeFromProxmox({ ...baseProxmoxResource(), platformData });
+ expect(node?.linkedAgentId).toBe('agent-canonical');
+ });
+
+ it('returns undefined for a whitespace-only linkedAgentId and falls back', () => {
+ const platformData = {
+ proxmox: { nodeName: 'n' },
+ agent: { agentId: 'agent-canonical' },
+ linkedAgentId: ' ',
+ } as unknown as PlatformData;
+ const node = toNodeFromProxmox({ ...baseProxmoxResource(), platformData });
+ expect(node?.linkedAgentId).toBe('agent-canonical');
+ });
+
+ it('returns undefined for a non-string linkedAgentId and falls back', () => {
+ const platformData = {
+ proxmox: { nodeName: 'n' },
+ agent: { agentId: 'agent-canonical' },
+ linkedAgentId: 12345,
+ } as unknown as PlatformData;
+ const node = toNodeFromProxmox({ ...baseProxmoxResource(), platformData });
+ expect(node?.linkedAgentId).toBe('agent-canonical');
+ });
+ });
+
+ describe('getPreferredHostLabel (via name/host when nodeName is absent)', () => {
+ it('uses identity.hostname when nodeName is absent (hostname branch)', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource(),
+ platformData: { proxmox: {} },
+ identity: { hostname: 'real-host' } as Resource['identity'],
+ });
+ expect(node?.name).toBe('real-host');
+ expect(node?.host).toBe('real-host');
+ });
+
+ it('falls back to resource.name when no hostname source resolves', () => {
+ const node = toNodeFromProxmox({
+ ...baseProxmoxResource({ name: 'fallback-name' }),
+ platformData: { proxmox: {} },
+ });
+ expect(node?.name).toBe('fallback-name');
+ });
+ });
+});
+
+describe('buildTypedGPUTemperatureKeys (observed via buildTemperatureRows)', () => {
+ it('excludes a typed gpu_nvidia_<id> temp entry when the GPU has a finite temperature', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ id: '0', temperatureCelsius: 63 }],
+ temperatureCelsius: { gpu_nvidia_0: 63, cpu_package: 41 },
+ });
+
+ const labels = rows.map((r) => r.label);
+ expect(labels).not.toContain('Nvidia 0'); // gpu_nvidia_0 excluded from sensor temps
+ expect(labels).toContain('Package');
+ });
+
+ it('keeps a gpu_nvidia_<id> temp entry when the GPU lacks a finite temperature', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ id: '0' }],
+ temperatureCelsius: { gpu_nvidia_0: 70 },
+ });
+
+ // No GPU stats row (nothing to render) but the raw temp row remains.
+ expect(rows.map((r) => r.label)).toContain('Nvidia 0');
+ expect(rows[0].value).toBe('70°C');
+ });
+
+ it('keeps a gpu_nvidia_<id> temp entry when GPU temperature is non-finite', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ id: '0', temperatureCelsius: Number.NaN }],
+ temperatureCelsius: { gpu_nvidia_0: 70 },
+ });
+
+ expect(rows.map((r) => r.label)).toContain('Nvidia 0');
+ });
+
+ it('does not register a typed key for a GPU with an empty id', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ id: '', temperatureCelsius: 50 }],
+ temperatureCelsius: { gpu_nvidia_0: 70 },
+ });
+
+ // Empty id => no typed key => the temp entry survives.
+ expect(rows.map((r) => r.label)).toContain('Nvidia 0');
+ });
+
+ it('does not register a typed key for a GPU with a whitespace-only id', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ id: ' ', temperatureCelsius: 50 }],
+ temperatureCelsius: { gpu_nvidia_1: 70 },
+ });
+
+ expect(rows.map((r) => r.label)).toContain('Nvidia 1');
+ });
+});
+
+describe('formatGPUStatsLabel (observed via buildTemperatureRows GPU rows)', () => {
+ it('renders "GPU <id>" when the GPU has a trimmed id', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ id: '2', name: 'RTX 4090' }],
+ });
+ expect(rows.map((r) => r.label)).toContain('GPU 2');
+ });
+
+ it('falls back to "GPU <index+1>" when id is undefined', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ name: 'Integrated' }],
+ });
+ expect(rows.map((r) => r.label)).toContain('GPU 1');
+ });
+
+ it('falls back to "GPU <index+1>" when id is whitespace-only', () => {
+ const rows = buildTemperatureRows({
+ gpu: [{ id: ' ', name: 'Integrated' }, { id: '5', name: 'Discrete' }],
+ });
+ const labels = rows.map((r) => r.label);
+ expect(labels).toEqual(['GPU 1', 'GPU 5']);
+ });
+});
+
+describe('formatPowerWatts (observed via buildTemperatureRows power rows)', () => {
+ const findPower = (sensors: HostSensorSummary, label: string) =>
+ buildTemperatureRows(sensors).find((r) => r.label === label);
+
+ it('formats a sub-100 value with one decimal', () => {
+ expect(findPower({ powerWatts: { cpu: 82.4 } }, 'CPU Power')?.value).toBe('82.4 W');
+ });
+
+ it('formats a value >= 100 with locale grouping and no decimal', () => {
+ expect(findPower({ powerWatts: { cpu: 1500 } }, 'CPU Power')?.value).toBe('1,500 W');
+ });
+
+ it('treats exactly 100 as the >= 100 branch', () => {
+ expect(findPower({ powerWatts: { cpu: 100 } }, 'CPU Power')?.value).toBe('100 W');
+ });
+
+ it('drops the row for a non-finite value (empty string filters out)', () => {
+ expect(findPower({ powerWatts: { cpu: Number.NaN } }, 'CPU Power')).toBeUndefined();
+ expect(findPower({ powerWatts: { cpu: Number.POSITIVE_INFINITY } }, 'CPU Power')).toBeUndefined();
+ });
+});
+
+describe('buildTemperatureRows (remaining uncovered branches)', () => {
+ it('returns an empty array when sensors is undefined', () => {
+ expect(buildTemperatureRows(undefined)).toEqual([]);
+ });
+
+ it('returns an empty array when sensors has no populated sections', () => {
+ expect(buildTemperatureRows({})).toEqual([]);
+ });
+
+ it('omits the thermal row when thermalState exists but has no pressure', () => {
+ const rows = buildTemperatureRows({ thermalState: { source: 'pmset' } });
+ expect(rows).toEqual([]);
+ });
+
+ it('emits a thermal row whose valueTitle omits "via <source>" when source is absent', () => {
+ const rows = buildTemperatureRows({ thermalState: { pressure: 'nominal' } });
+ expect(rows).toEqual([
+ { label: 'Thermal pressure', value: 'Nominal', valueTitle: 'Nominal' },
+ ]);
+ });
+
+ it('filters out limitsPercent entries >= 100 and non-finite entries', () => {
+ const rows = buildTemperatureRows({
+ thermalState: {
+ limitsPercent: { cpu_speed_limit: 100, scheduler_limit: Number.NaN, thermal_limit: 80 },
+ },
+ });
+ expect(rows.map((r) => r.label)).toEqual(['Limit']);
+ });
+
+ it('skips a GPU row whose rendered value is empty', () => {
+ const rows = buildTemperatureRows({ gpu: [{ id: '0' }] });
+ expect(rows).toEqual([]);
+ });
+
+ it('filters out non-finite temperatureCelsius entries', () => {
+ const rows = buildTemperatureRows({
+ temperatureCelsius: { cpu_package: 41, gpu_die: Number.NaN },
+ });
+ expect(rows.map((r) => r.label)).toEqual(['Package']);
+ });
+
+ it('filters out non-finite additional entries', () => {
+ const rows = buildTemperatureRows({
+ additional: { vrm_temp: 55.6, psu_temp: Number.NaN },
+ });
+ expect(rows.map((r) => r.label)).toEqual(['VRM Temp']);
+ });
+
+ describe('smart disks', () => {
+ it('renders a healthy, active disk row', () => {
+ const rows = buildTemperatureRows({
+ smart: [{ device: 'sda', temperature: 42 }],
+ });
+ expect(rows).toEqual([
+ { label: 'Disk sda', value: '42°C', valueTitle: '42.0°C' },
+ ]);
+ });
+
+ it('skips standby disks', () => {
+ const rows = buildTemperatureRows({
+ smart: [{ device: 'sdb', temperature: 42, standby: true }],
+ });
+ expect(rows).toEqual([]);
+ });
+
+ it('skips disks with a non-finite temperature', () => {
+ const rows = buildTemperatureRows({
+ smart: [{ device: 'sdc', temperature: Number.NaN }],
+ });
+ expect(rows).toEqual([]);
+ });
+
+ it('sorts multiple disks by device name', () => {
+ const rows = buildTemperatureRows({
+ smart: [
+ { device: 'sdc', temperature: 30 },
+ { device: 'sda', temperature: 40 },
+ { device: 'sdb', temperature: 50 },
+ ],
+ });
+ expect(rows.map((r) => r.label)).toEqual(['Disk sda', 'Disk sdb', 'Disk sdc']);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureImportPlanModel.branchcov.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureImportPlanModel.branchcov.test.ts
new file mode 100644
index 0000000000..c9c01ebecf
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureImportPlanModel.branchcov.test.ts
@@ -0,0 +1,552 @@
+/**
+ * Branch-coverage tests for the unexported helpers inside
+ * infrastructureImportPlanModel. None of the target helpers
+ * (coverageLabel, hostnameFromEndpoint, endpointFromCandidate,
+ * credentialLabel, nodeTypeToMonitoredSource, nodeTypeToResourceType,
+ * versionFromCandidate, candidateLabel) are exported, so every branch is
+ * driven through the sole exported entry point `buildNodeImportPlan` and
+ * asserted via the resulting plan fields.
+ */
+import { describe, expect, it } from 'vitest';
+import type { ProbeCandidate } from '@/api/connections';
+import {
+ getNodeModalDefaultFormData,
+ type NodeModalFormData,
+ type NodeModalNodeType,
+} from '@/utils/nodeModalPresentation';
+import type { DiscoveredServer } from '../infrastructureSettingsModel';
+import {
+ buildNodeImportPlan,
+ type NodeImportPlan,
+ type NodeImportPlanCandidate,
+} from '../infrastructureImportPlanModel';
+
+// ---- Fixtures ---------------------------------------------------------------
+
+const makeServer = (overrides: Partial<DiscoveredServer> = {}): DiscoveredServer => ({
+ type: 'pve',
+ ip: '10.0.0.10',
+ hostname: 'tower.local',
+ port: 8006,
+ version: 'Proxmox VE',
+ release: '9.0',
+ ...overrides,
+});
+
+const makeProbe = (overrides: Partial<ProbeCandidate> = {}): ProbeCandidate => ({
+ type: 'pve',
+ host: 'https://probe.local:8006',
+ port: 8006,
+ hints: { product: 'Proxmox VE', version: '9.0' },
+ ...overrides,
+});
+
+const makeForm = (
+ nodeType: NodeModalNodeType,
+ overrides: Partial<NodeModalFormData> = {},
+): NodeModalFormData => ({
+ ...getNodeModalDefaultFormData(nodeType),
+ ...overrides,
+});
+
+const discoveryCandidate = (server: DiscoveredServer): NodeImportPlanCandidate => ({
+ kind: 'discovery',
+ server,
+});
+
+const probeCandidate = (candidate: ProbeCandidate): NodeImportPlanCandidate => ({
+ kind: 'probe',
+ candidate,
+});
+
+// ---- nodeTypeToMonitoredSource + nodeTypeToResourceType --------------------
+// pve -> 'proxmox'/'agent' and pbs -> 'pbs'/'pbs' are exercised by the sibling
+// test file. Here we cover the pmg arms of both switches.
+
+describe('nodeTypeToMonitoredSource / nodeTypeToResourceType (pmg arm)', () => {
+ it("maps pmg to the 'pmg' monitored source and resource type", () => {
+ const plan = buildNodeImportPlan(
+ 'pmg',
+ makeForm('pmg', { name: 'mail', host: 'https://mail.local:8006' }),
+ discoveryCandidate(makeServer({ type: 'pmg', hostname: 'mail.local', port: 8006 })),
+ );
+
+ expect(plan).not.toBeNull();
+ expect(plan?.source).toBe('pmg');
+ expect(plan?.previewRequest?.candidate.type).toBe('pmg');
+ });
+});
+
+// ---- hostnameFromEndpoint ---------------------------------------------------
+
+describe('hostnameFromEndpoint (via plan.hostname)', () => {
+ it("returns an empty hostname when the endpoint is empty", () => {
+ // formData.host empty AND probe host empty => endpoint '' => hostname ''.
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: '' }),
+ probeCandidate(makeProbe({ host: '' })),
+ );
+
+ expect(plan?.endpoint).toBe('');
+ expect(plan?.hostname).toBe('');
+ });
+
+ it("parses a scheme-less host by implicitly prepending https://", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'tower.local:8006' }),
+ probeCandidate(makeProbe()),
+ );
+
+ // formData.host wins over candidate; endpoint keeps the scheme-less form.
+ expect(plan?.endpoint).toBe('tower.local:8006');
+ expect(plan?.hostname).toBe('tower.local');
+ });
+
+ it("falls back to manual host stripping when the URL cannot be parsed", () => {
+ // 'bad:host' makes `new URL('https://bad:host')` throw (invalid port); the
+ // catch arm strips any scheme, drops the path, then drops the port.
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'bad:host' }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.hostname).toBe('bad');
+ });
+});
+
+// ---- endpointFromCandidate --------------------------------------------------
+// Only reached when formData.host is empty/whitespace, because
+// `normalizeEndpoint(formData.host) || endpointFromCandidate(candidate)`.
+
+describe('endpointFromCandidate (via plan.endpoint with empty formData.host)', () => {
+ it("normalizes (trims) the probe candidate host", () => {
+ const plan = buildNodeImportPlan(
+ 'pbs',
+ makeForm('pbs', { host: '' }),
+ probeCandidate(makeProbe({ type: 'pbs', host: ' https://backup.local:8007 ', port: 8007 })),
+ );
+
+ expect(plan?.endpoint).toBe('https://backup.local:8007');
+ });
+
+ it("prefers the discovery server hostname when present", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { host: '' }),
+ discoveryCandidate(makeServer({ hostname: 'host.local', ip: '10.0.0.20', port: 8006 })),
+ );
+
+ expect(plan?.endpoint).toBe('https://host.local:8006');
+ });
+
+ it("falls back to the IP when the discovery hostname is an empty string", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { host: '' }),
+ discoveryCandidate(makeServer({ hostname: '', ip: '10.0.0.20', port: 8006 })),
+ );
+
+ expect(plan?.endpoint).toBe('https://10.0.0.20:8006');
+ });
+
+ it("falls back to the IP when the discovery hostname is undefined", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { host: '' }),
+ discoveryCandidate(makeServer({ hostname: undefined, ip: '10.0.0.20', port: 8006 })),
+ );
+
+ expect(plan?.endpoint).toBe('https://10.0.0.20:8006');
+ });
+});
+
+// ---- versionFromCandidate ---------------------------------------------------
+
+describe('versionFromCandidate (via plan.detectedVersion)', () => {
+ it("joins product and version hints for a probe candidate", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe({ hints: { product: 'Proxmox VE', version: '9.1' } })),
+ );
+
+ expect(plan?.detectedVersion).toBe('Proxmox VE 9.1');
+ });
+
+ it("returns only the product when the version hint is absent", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe({ hints: { product: 'Proxmox VE' } })),
+ );
+
+ expect(plan?.detectedVersion).toBe('Proxmox VE');
+ });
+
+ it("returns only the version when the product hint is absent", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe({ hints: { version: '9.1' } })),
+ );
+
+ expect(plan?.detectedVersion).toBe('9.1');
+ });
+
+ it("uses the generic fallback when hints are missing entirely", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe({ hints: undefined })),
+ );
+
+ expect(plan?.detectedVersion).toBe('Detected API endpoint');
+ });
+
+ it("uses the generic fallback when both hints trim to empty", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe({ hints: { product: ' ', version: '' } })),
+ );
+
+ expect(plan?.detectedVersion).toBe('Detected API endpoint');
+ });
+
+ it("joins server version and release for a discovery candidate", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ discoveryCandidate(makeServer({ version: 'Proxmox VE', release: '8.4' })),
+ );
+
+ expect(plan?.detectedVersion).toBe('Proxmox VE 8.4');
+ });
+
+ it("returns only the server version when release is undefined", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ discoveryCandidate(makeServer({ version: 'Proxmox VE', release: undefined })),
+ );
+
+ expect(plan?.detectedVersion).toBe('Proxmox VE');
+ });
+
+ it("returns only the release when version is empty", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ discoveryCandidate(makeServer({ version: '', release: '9.0' })),
+ );
+
+ expect(plan?.detectedVersion).toBe('9.0');
+ });
+
+ it("returns an empty detected version when both version and release are empty", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ discoveryCandidate(makeServer({ version: '', release: '' })),
+ );
+
+ expect(plan?.detectedVersion).toBe('');
+ });
+});
+
+// ---- candidateLabel ---------------------------------------------------------
+
+describe('candidateLabel (via plan.candidateLabel and steps[0].detail)', () => {
+ it("describes a probe candidate with its host", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe({ host: 'https://detected.local:8006' })),
+ );
+
+ expect(plan?.candidateLabel).toBe('Detected API probe at https://detected.local:8006');
+ // buildSteps feeds the candidate summary into the first step detail.
+ expect(plan?.steps[0]?.detail).toBe(plan?.candidateLabel);
+ });
+
+ it("describes a discovery candidate using its hostname", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ discoveryCandidate(makeServer({ hostname: 'node7.local', ip: '10.0.0.5', port: 8006 })),
+ );
+
+ expect(plan?.candidateLabel).toBe('Discovery candidate at node7.local:8006');
+ });
+
+ it("falls back to the IP in the discovery label when hostname is empty", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ discoveryCandidate(makeServer({ hostname: '', ip: '10.0.0.5', port: 8006 })),
+ );
+
+ expect(plan?.candidateLabel).toBe('Discovery candidate at 10.0.0.5:8006');
+ });
+
+ it("falls back to the IP in the discovery label when hostname is undefined", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ discoveryCandidate(makeServer({ hostname: undefined, ip: '10.0.0.5', port: 8006 })),
+ );
+
+ expect(plan?.candidateLabel).toBe('Discovery candidate at 10.0.0.5:8006');
+ });
+});
+
+// ---- credentialLabel --------------------------------------------------------
+
+describe('credentialLabel (via plan.credentialLabel and steps[1].detail)', () => {
+ it("emits the password-validation message when authType is password", () => {
+ // authType === 'password' short-circuits ahead of setupMode.
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local', authType: 'password', setupMode: 'auto' }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.credentialLabel).toBe(
+ 'Validate username and password credentials before saving.',
+ );
+ expect(plan?.steps[1]?.detail).toBe(plan?.credentialLabel);
+ });
+
+ it("emits the API-token message for token + manual setup", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local', authType: 'token', setupMode: 'manual' }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.credentialLabel).toBe('Validate the supplied API token before saving.');
+ });
+
+ it("emits the agent handoff message for token + agent setup", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local', authType: 'token', setupMode: 'agent' }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.credentialLabel).toBe(
+ 'Run the Host Telemetry Agent handoff; Pulse will add the source after the agent reports.',
+ );
+ });
+
+ it("emits the inventory-setup fallback for token + auto setup", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local', authType: 'token', setupMode: 'auto' }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.credentialLabel).toBe(
+ 'Run the API Inventory setup handoff; Pulse will add the source after setup completes.',
+ );
+ });
+});
+
+// ---- coverageLabel ----------------------------------------------------------
+
+describe('coverageLabel (via plan.coverageLabel)', () => {
+ it("lists only the SMART-disks collector when it is the sole enabled PVE collector", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', {
+ name: 'x',
+ host: 'https://x.local',
+ monitorVMs: false,
+ monitorContainers: false,
+ monitorStorage: false,
+ monitorBackups: false,
+ monitorPhysicalDisks: true,
+ }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.coverageLabel).toBe('SMART disks');
+ });
+
+ it("joins a selected subset of PVE collectors in declared order", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', {
+ name: 'x',
+ host: 'https://x.local',
+ monitorVMs: true,
+ monitorContainers: false,
+ monitorStorage: true,
+ monitorBackups: false,
+ monitorPhysicalDisks: false,
+ }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.coverageLabel).toBe('VMs, storage');
+ });
+
+ it("reports no Proxmox collectors when every PVE toggle is off", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', {
+ name: 'x',
+ host: 'https://x.local',
+ monitorVMs: false,
+ monitorContainers: false,
+ monitorStorage: false,
+ monitorBackups: false,
+ monitorPhysicalDisks: false,
+ }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.coverageLabel).toBe('No Proxmox collectors selected');
+ });
+
+ it("reports no PBS collectors when every PBS toggle is off", () => {
+ const plan = buildNodeImportPlan(
+ 'pbs',
+ makeForm('pbs', {
+ name: 'x',
+ host: 'https://x.local',
+ monitorDatastores: false,
+ monitorSyncJobs: false,
+ monitorVerifyJobs: false,
+ monitorPruneJobs: false,
+ monitorGarbageJobs: false,
+ }),
+ probeCandidate(makeProbe({ type: 'pbs' })),
+ );
+
+ expect(plan?.coverageLabel).toBe('No PBS collectors selected');
+ });
+
+ it("lists the default PMG collectors in declared order", () => {
+ const plan = buildNodeImportPlan(
+ 'pmg',
+ makeForm('pmg', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe({ type: 'pmg' })),
+ );
+
+ // default PMG form: mail stats + queues + quarantine on, domain stats off.
+ expect(plan?.coverageLabel).toBe('mail stats, queues, quarantine');
+ });
+
+ it("reports no PMG collectors when every PMG toggle is off", () => {
+ const plan = buildNodeImportPlan(
+ 'pmg',
+ makeForm('pmg', {
+ name: 'x',
+ host: 'https://x.local',
+ monitorMailStats: false,
+ monitorQueues: false,
+ monitorQuarantine: false,
+ monitorDomainStats: false,
+ }),
+ probeCandidate(makeProbe({ type: 'pmg' })),
+ );
+
+ expect(plan?.coverageLabel).toBe('No PMG collectors selected');
+ });
+});
+
+// ---- buildNodeImportPlan guards + wiring -----------------------------------
+
+describe('buildNodeImportPlan guards and wiring', () => {
+ it("returns null when the candidate is null", () => {
+ const plan = buildNodeImportPlan('pve', makeForm('pve'), null);
+
+ expect(plan).toBeNull();
+ });
+
+ it("returns null when the candidate is undefined", () => {
+ const plan = buildNodeImportPlan('pve', makeForm('pve'), undefined);
+
+ expect(plan).toBeNull();
+ });
+
+ it("omits the preview request when both endpoint and derived name are empty", () => {
+ // Empty formData.host + empty probe host => endpoint '' => hostname ''.
+ // Empty name => deriveNameFromHost('') === '' => name ''.
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: '', host: '' }),
+ probeCandidate(makeProbe({ host: '' })),
+ ) as NodeImportPlan;
+
+ expect(plan.previewRequest).toBeNull();
+ });
+
+ it("derives the node name from the endpoint host when formData.name is empty", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: '', host: 'https://node7.local:8006' }),
+ probeCandidate(makeProbe()),
+ );
+
+ expect(plan?.name).toBe('node7.local');
+ // name + endpoint both truthy => preview request is populated.
+ expect(plan?.previewRequest?.candidate.name).toBe('node7.local');
+ expect(plan?.previewRequest?.candidate.resource_id).toBe('node7.local');
+ });
+
+ it("composes the signature from source, candidate, version, name, endpoint, auth, setup, coverage", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', {
+ name: 'tower',
+ host: 'https://tower.local:8006',
+ authType: 'token',
+ setupMode: 'manual',
+ monitorVMs: true,
+ monitorContainers: false,
+ monitorStorage: false,
+ monitorBackups: false,
+ monitorPhysicalDisks: false,
+ }),
+ discoveryCandidate(makeServer({ version: 'Proxmox VE', release: '9.0' })),
+ );
+
+ expect(plan?.signature).toBe(
+ [
+ 'proxmox',
+ 'Discovery candidate at tower.local:8006',
+ 'Proxmox VE 9.0',
+ 'tower',
+ 'https://tower.local:8006',
+ 'token',
+ 'manual',
+ 'VMs',
+ ].join('|'),
+ );
+ });
+
+ it("emits the five canonical steps in order", () => {
+ const plan = buildNodeImportPlan(
+ 'pve',
+ makeForm('pve', { name: 'x', host: 'https://x.local' }),
+ probeCandidate(makeProbe()),
+ ) as NodeImportPlan;
+
+ expect(plan.steps.map((s) => s.id)).toEqual([
+ 'candidate',
+ 'credentials',
+ 'dry-run',
+ 'approval',
+ 'verification',
+ ]);
+ // The dry-run/approval/verification details are static strings.
+ expect(plan.steps[2]?.detail).toBe(
+ 'Preview whether this source creates a new monitored system or attaches to an existing one.',
+ );
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureOperationsModel.branchcov.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureOperationsModel.branchcov.test.ts
new file mode 100644
index 0000000000..f2f5a9f07f
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureOperationsModel.branchcov.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from 'vitest';
+import { getPowerShellInstallProfileEnvFromFlags } from '../infrastructureOperationsModel';
+
+describe('getPowerShellInstallProfileEnvFromFlags', () => {
+ it('returns an empty array for an empty flags list', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags([])).toEqual([]);
+ });
+
+ it('translates --enable-docker into the PULSE_ENABLE_DOCKER assignment', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--enable-docker'])).toEqual([
+ `$env:PULSE_ENABLE_DOCKER="true"`,
+ ]);
+ });
+
+ it('translates --disable-host into the PULSE_ENABLE_HOST=false assignment', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--disable-host'])).toEqual([
+ `$env:PULSE_ENABLE_HOST="false"`,
+ ]);
+ });
+
+ it('translates --enable-kubernetes into the PULSE_ENABLE_KUBERNETES assignment', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--enable-kubernetes'])).toEqual([
+ `$env:PULSE_ENABLE_KUBERNETES="true"`,
+ ]);
+ });
+
+ it('translates --enable-proxmox into the PULSE_ENABLE_PROXMOX assignment', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--enable-proxmox'])).toEqual([
+ `$env:PULSE_ENABLE_PROXMOX="true"`,
+ ]);
+ });
+
+ it('preserves flag order across a multi-flag profile (docker profile)', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--enable-docker', '--disable-host'])).toEqual([
+ `$env:PULSE_ENABLE_DOCKER="true"`,
+ `$env:PULSE_ENABLE_HOST="false"`,
+ ]);
+ });
+
+ it('reads the proxmox type from the combined "--proxmox-type <value>" token (default branch)', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type pve'])).toEqual([
+ `$env:PULSE_PROXMOX_TYPE="pve"`,
+ ]);
+ });
+
+ it('trims surrounding whitespace from a combined proxmox-type value', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type pbs '])).toEqual([
+ `$env:PULSE_PROXMOX_TYPE="pbs"`,
+ ]);
+ });
+
+ it('ignores a combined "--proxmox-type " token with an empty value', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type '])).toEqual([]);
+ });
+
+ it('ignores a combined "--proxmox-type" token followed by only whitespace', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type '])).toEqual([]);
+ });
+
+ it('reads the proxmox type from the split "--proxmox-type" then next-token form', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type', 'pve'])).toEqual([
+ `$env:PULSE_PROXMOX_TYPE="pve"`,
+ ]);
+ });
+
+ it('trims the next token in the split form', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type', ' pbs '])).toEqual([
+ `$env:PULSE_PROXMOX_TYPE="pbs"`,
+ ]);
+ });
+
+ it('skips the proxmox-type assignment when "--proxmox-type" is the last token', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type'])).toEqual([]);
+ });
+
+ it('skips the proxmox-type assignment when the next token is an empty string', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type', ''])).toEqual([]);
+ });
+
+ it('skips the proxmox-type assignment when the next token is whitespace-only and does not consume it', () => {
+ // The whitespace token is NOT consumed (index is only advanced inside the
+ // truthy branch), so it is itself processed by the default arm on the next
+ // iteration and also yields nothing.
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type', ' '])).toEqual([]);
+ });
+
+ it('consumes the next token as the proxmox type even when it resembles another flag', () => {
+ // The split form greedily eats the following token as the type value,
+ // so the flag-like "--enable-docker" is swallowed rather than processed.
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type', '--enable-docker'])).toEqual([
+ `$env:PULSE_PROXMOX_TYPE="--enable-docker"`,
+ ]);
+ });
+
+ it('ignores unknown flags entirely', () => {
+ expect(
+ getPowerShellInstallProfileEnvFromFlags(['--bogus', '--enable-kubernetes', 'who-knows']),
+ ).toEqual([`$env:PULSE_ENABLE_KUBERNETES="true"`]);
+ });
+
+ it('produces both assignments for the proxmox-pve profile flags', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--enable-proxmox', '--proxmox-type pve'])).toEqual(
+ [`$env:PULSE_ENABLE_PROXMOX="true"`, `$env:PULSE_PROXMOX_TYPE="pve"`],
+ );
+ });
+
+ it('produces both assignments for the proxmox-pbs profile flags', () => {
+ expect(getPowerShellInstallProfileEnvFromFlags(['--enable-proxmox', '--proxmox-type pbs'])).toEqual(
+ [`$env:PULSE_ENABLE_PROXMOX="true"`, `$env:PULSE_PROXMOX_TYPE="pbs"`],
+ );
+ });
+
+ it('does not recognize the "--proxmox-type=<value>" equals form', () => {
+ // Neither the exact `--proxmox-type` case nor the default
+ // `startsWith('--proxmox-type ')` (space) arm matches the equals form,
+ // so it silently yields no assignment.
+ expect(getPowerShellInstallProfileEnvFromFlags(['--proxmox-type=pve'])).toEqual([]);
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadSelectors.branchcov.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadSelectors.branchcov.test.ts
new file mode 100644
index 0000000000..1aff3e37ec
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadSelectors.branchcov.test.ts
@@ -0,0 +1,830 @@
+import { describe, expect, it } from 'vitest';
+import type { Node } from '@/types/api';
+import type { WorkloadGuest } from '@/types/workloads';
+import {
+ buildWorkloadSummaryGroupScope,
+ buildWorkloadSummaryGroupScopeMap,
+ createWorkloadSortComparator,
+ filterWorkloads,
+ getDiskUsagePercent,
+ getWorkloadGroupKey,
+ getWorkloadGroupLabel,
+ groupWorkloads,
+} from '@/components/Workloads/workloadSelectors';
+
+const makeGuest = (i: number, overrides?: Partial<WorkloadGuest>): WorkloadGuest => ({
+ id: `guest-${i}`,
+ vmid: 100 + i,
+ name: `workload-${i}`,
+ node: `node-${i % 5}`,
+ instance: `cluster-${i % 3}`,
+ status: 'running',
+ type: 'vm',
+ cpu: (i % 100) / 100,
+ cpus: 2,
+ memory: { total: 4096, used: ((i % 80) / 100) * 4096, free: 0, usage: (i % 80) / 100 },
+ disk: { total: 102400, used: ((i % 60) / 100) * 102400, free: 0, usage: (i % 60) / 100 },
+ networkIn: i * 100,
+ networkOut: i * 50,
+ diskRead: i * 10,
+ diskWrite: i * 5,
+ uptime: i * 3600,
+ template: false,
+ lastBackup: 0,
+ tags: [],
+ lock: '',
+ lastSeen: new Date().toISOString(),
+ workloadType: 'vm',
+ ...overrides,
+});
+
+const makeNode = (id: string, instance: string, name: string): Node => ({
+ id,
+ name,
+ displayName: name,
+ instance,
+ host: `${name}.local`,
+ status: 'online',
+ type: 'pve',
+ cpu: 0,
+ memory: { total: 1, used: 0, free: 1, usage: 0 },
+ disk: { total: 1, used: 0, free: 1, usage: 0 },
+ uptime: 1,
+ loadAverage: [0, 0, 0],
+ kernelVersion: 'test',
+ pveVersion: 'test',
+ cpuInfo: { model: 'test', cores: 1, sockets: 1, mhz: '1' },
+ lastSeen: new Date().toISOString(),
+ connectionHealth: 'online',
+});
+
+describe('workloadSelectors (branch coverage)', () => {
+ describe('createWorkloadSortComparator', () => {
+ it('sorts by memory usage in both directions and falls back to 0 for null memory', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'high',
+ name: 'high-mem',
+ memory: { total: 100, used: 80, free: 20, usage: 0.8 },
+ }),
+ makeGuest(2, {
+ id: 'low',
+ name: 'low-mem',
+ memory: { total: 100, used: 10, free: 90, usage: 0.1 },
+ }),
+ makeGuest(3, {
+ id: 'null',
+ name: 'null-mem',
+ memory: null as unknown as WorkloadGuest['memory'],
+ }),
+ ];
+
+ const memAsc = createWorkloadSortComparator('memory', 'asc');
+ const memDesc = createWorkloadSortComparator('memory', 'desc');
+
+ expect(memAsc).not.toBeNull();
+ expect(memDesc).not.toBeNull();
+
+ // null-mem (0) < low-mem (0.1) < high-mem (0.8)
+ expect([...guests].sort(memAsc!).map((g) => g.id)).toEqual(['null', 'low', 'high']);
+ expect([...guests].sort(memDesc!).map((g) => g.id)).toEqual(['high', 'low', 'null']);
+ });
+
+ it('treats memory.usage of 0 as 0 via the || fallback', () => {
+ const guests = [
+ makeGuest(1, { id: 'a', name: 'alpha', cpu: 0.5, memory: { total: 100, used: 0, free: 100, usage: 0 } }),
+ makeGuest(2, { id: 'b', name: 'beta', cpu: 0.5, memory: { total: 100, used: 50, free: 50, usage: 0.5 } }),
+ ];
+
+ const memAsc = createWorkloadSortComparator('memory', 'asc');
+ expect([...guests].sort(memAsc!).map((g) => g.id)).toEqual(['a', 'b']);
+ });
+
+ it('sorts by disk usage percent via getDiskUsagePercent', () => {
+ const guests = [
+ makeGuest(1, { id: 'big', name: 'big-disk', disk: { total: 100, used: 90, free: 10, usage: 0.9 } }),
+ makeGuest(2, { id: 'small', name: 'small-disk', disk: { total: 100, used: 10, free: 90, usage: 0.1 } }),
+ ];
+
+ const diskAsc = createWorkloadSortComparator('disk', 'asc');
+ const diskDesc = createWorkloadSortComparator('disk', 'desc');
+
+ expect([...guests].sort(diskAsc!).map((g) => g.id)).toEqual(['small', 'big']);
+ expect([...guests].sort(diskDesc!).map((g) => g.id)).toEqual(['big', 'small']);
+ });
+
+ it('sorts by diskIo and clamps negative read/write values to 0', () => {
+ const guests = [
+ makeGuest(1, { id: 'positive', name: 'p', diskRead: 100, diskWrite: 50 }),
+ makeGuest(2, { id: 'negative', name: 'n', diskRead: -40, diskWrite: -20 }),
+ ];
+
+ const ioAsc = createWorkloadSortComparator('diskIo', 'asc');
+ // negative -> max(0,-40)+max(0,-20) = 0; positive -> 150
+ expect([...guests].sort(ioAsc!).map((g) => g.id)).toEqual(['negative', 'positive']);
+ });
+
+ it('sorts by netIo in both directions', () => {
+ const guests = [
+ makeGuest(1, { id: 'busy', name: 'busy-net', networkIn: 200, networkOut: 100 }),
+ makeGuest(2, { id: 'quiet', name: 'quiet-net', networkIn: 5, networkOut: 3 }),
+ ];
+
+ const netAsc = createWorkloadSortComparator('netIo', 'asc');
+ const netDesc = createWorkloadSortComparator('netIo', 'desc');
+
+ expect([...guests].sort(netAsc!).map((g) => g.id)).toEqual(['quiet', 'busy']);
+ expect([...guests].sort(netDesc!).map((g) => g.id)).toEqual(['busy', 'quiet']);
+ });
+
+ it('sorts by a generic string key (status) via the else branch', () => {
+ const guests = [
+ makeGuest(1, { id: 'a', name: 'alpha', status: 'stopped' }),
+ makeGuest(2, { id: 'b', name: 'beta', status: 'running' }),
+ ];
+
+ const statusAsc = createWorkloadSortComparator('status', 'asc');
+ // 'running' < 'stopped' alphabetically
+ expect([...guests].sort(statusAsc!).map((g) => g.id)).toEqual(['b', 'a']);
+ });
+ });
+
+ describe('filterWorkloads', () => {
+ it('statusMode running keeps only guests whose status is exactly running', () => {
+ const guests = [
+ makeGuest(1, { id: 'r1', status: 'running', type: 'vm', workloadType: 'vm' }),
+ makeGuest(2, { id: 'r2', status: 'warning', type: 'vm', workloadType: 'vm' }),
+ makeGuest(3, { id: 'r3', status: 'stopped', type: 'vm', workloadType: 'vm' }),
+ ];
+
+ const result = filterWorkloads({
+ guests,
+ viewMode: 'all',
+ statusMode: 'running',
+ searchTerm: '',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ });
+
+ expect(result.map((g) => g.id)).toEqual(['r1']);
+ });
+
+ it('filters pods by kubernetes namespace in pod view mode', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'pod-a',
+ name: 'api',
+ type: 'pod',
+ workloadType: 'pod',
+ instance: 'ctx-a',
+ node: 'worker-1',
+ contextLabel: 'ctx-a',
+ namespace: 'payments',
+ status: 'running',
+ }),
+ makeGuest(2, {
+ id: 'pod-b',
+ name: 'web',
+ type: 'pod',
+ workloadType: 'pod',
+ instance: 'ctx-a',
+ node: 'worker-2',
+ contextLabel: 'ctx-a',
+ namespace: 'default',
+ status: 'running',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ guests,
+ viewMode: 'pod',
+ statusMode: 'all',
+ searchTerm: '',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ selectedKubernetesNamespace: 'payments',
+ });
+
+ expect(result.map((g) => g.id)).toEqual(['pod-a']);
+ });
+
+ it('filters vms by cluster name in vm view mode', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'vm-a',
+ name: 'vm-a',
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst-a',
+ node: 'node-a',
+ clusterName: 'prod-cluster',
+ }),
+ makeGuest(2, {
+ id: 'vm-b',
+ name: 'vm-b',
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst-b',
+ node: 'node-b',
+ clusterName: 'dev-cluster',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ guests,
+ viewMode: 'vm',
+ statusMode: 'all',
+ searchTerm: '',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ selectedCluster: 'prod-cluster',
+ });
+
+ expect(result.map((g) => g.id)).toEqual(['vm-a']);
+ });
+
+ it('filters app-containers by runtime in container view mode', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'c-docker',
+ name: 'redis',
+ type: 'app-container',
+ workloadType: 'app-container',
+ containerRuntime: 'docker',
+ contextLabel: 'host-a',
+ node: '',
+ instance: '',
+ }),
+ makeGuest(2, {
+ id: 'c-podman',
+ name: 'nginx',
+ type: 'app-container',
+ workloadType: 'app-container',
+ containerRuntime: 'podman',
+ contextLabel: 'host-b',
+ node: '',
+ instance: '',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ guests,
+ viewMode: 'app-container',
+ statusMode: 'all',
+ searchTerm: '',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ containerRuntime: 'docker',
+ });
+
+ expect(result.map((g) => g.id)).toEqual(['c-docker']);
+ });
+
+ it('does not apply containerRuntime filter when viewMode is not a container mode', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'c1',
+ name: 'redis',
+ type: 'app-container',
+ workloadType: 'app-container',
+ containerRuntime: 'docker',
+ contextLabel: 'host-a',
+ }),
+ makeGuest(2, {
+ id: 'c2',
+ name: 'nginx',
+ type: 'app-container',
+ workloadType: 'app-container',
+ containerRuntime: 'podman',
+ contextLabel: 'host-b',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ guests,
+ viewMode: 'all',
+ statusMode: 'all',
+ searchTerm: '',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ containerRuntime: 'docker',
+ });
+
+ // Both returned: isContainerWorkloadViewMode('all') is false
+ expect(result.map((g) => g.id)).toEqual(['c1', 'c2']);
+ });
+
+ it('excludes pods from host-hint filtering even when contextLabel matches', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'pod-x',
+ name: 'api-pod',
+ type: 'pod',
+ workloadType: 'pod',
+ instance: 'ctx',
+ node: 'worker',
+ contextLabel: 'edge-host',
+ namespace: 'default',
+ status: 'running',
+ }),
+ makeGuest(2, {
+ id: 'docker-x',
+ name: 'redis',
+ type: 'app-container',
+ workloadType: 'app-container',
+ contextLabel: 'edge-host',
+ node: '',
+ instance: '',
+ status: 'running',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ guests,
+ viewMode: 'all',
+ statusMode: 'all',
+ searchTerm: '',
+ selectedNode: null,
+ selectedHostHint: 'edge',
+ selectedKubernetesContext: null,
+ });
+
+ // Pod excluded (resolveWorkloadType === 'pod' -> false), app-container kept
+ expect(result.map((g) => g.id)).toEqual(['docker-x']);
+ });
+
+ it('returns all guests unchanged when search term is only commas and spaces', () => {
+ const guests = [makeGuest(1), makeGuest(2)];
+
+ const result = filterWorkloads({
+ guests,
+ viewMode: 'all',
+ statusMode: 'all',
+ searchTerm: ' , , ',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ });
+
+ expect(result).toBe(guests);
+ });
+
+ it('matches workload text search across displayId and clusterName candidates', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'g1',
+ name: 'alpha',
+ displayId: 'display-uniq-001',
+ type: 'vm',
+ workloadType: 'vm',
+ status: 'running',
+ }),
+ makeGuest(2, {
+ id: 'g2',
+ name: 'beta',
+ clusterName: 'cluster-uniq-002',
+ type: 'vm',
+ workloadType: 'vm',
+ status: 'running',
+ }),
+ makeGuest(3, {
+ id: 'g3',
+ name: 'gamma',
+ type: 'vm',
+ workloadType: 'vm',
+ status: 'running',
+ }),
+ ];
+
+ const byDisplay = filterWorkloads({
+ guests,
+ viewMode: 'all',
+ statusMode: 'all',
+ searchTerm: 'display-uniq-001',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ });
+ expect(byDisplay.map((g) => g.id)).toEqual(['g1']);
+
+ const byCluster = filterWorkloads({
+ guests,
+ viewMode: 'all',
+ statusMode: 'all',
+ searchTerm: 'cluster-uniq-002',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ });
+ expect(byCluster.map((g) => g.id)).toEqual(['g2']);
+ });
+
+ it('matches workload text search across platformScopes, dockerHostId, kubernetesAgentId, and containerId candidates', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'scope-guest',
+ name: 'sc',
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformScopes: ['truenas', 'scope-uniq-aaa'],
+ status: 'running',
+ }),
+ makeGuest(2, {
+ id: 'docker-guest',
+ name: 'dk',
+ type: 'app-container',
+ workloadType: 'app-container',
+ dockerHostId: 'host-uniq-bbb',
+ status: 'running',
+ }),
+ makeGuest(3, {
+ id: 'k8s-guest',
+ name: 'k8',
+ type: 'pod',
+ workloadType: 'pod',
+ kubernetesAgentId: 'agent-uniq-ccc',
+ instance: 'ctx',
+ node: 'worker',
+ contextLabel: 'ctx',
+ namespace: 'default',
+ status: 'running',
+ }),
+ makeGuest(4, {
+ id: 'cid-guest',
+ name: 'cd',
+ type: 'app-container',
+ workloadType: 'app-container',
+ containerId: 'containerid-uniq-ddd',
+ status: 'running',
+ }),
+ ];
+
+ const baseParams = {
+ viewMode: 'all' as const,
+ statusMode: 'all',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+ };
+
+ expect(
+ filterWorkloads({ ...baseParams, guests, searchTerm: 'scope-uniq-aaa' }).map((g) => g.id),
+ ).toEqual(['scope-guest']);
+
+ expect(
+ filterWorkloads({ ...baseParams, guests, searchTerm: 'host-uniq-bbb' }).map((g) => g.id),
+ ).toEqual(['docker-guest']);
+
+ expect(
+ filterWorkloads({ ...baseParams, guests, searchTerm: 'agent-uniq-ccc' }).map((g) => g.id),
+ ).toEqual(['k8s-guest']);
+
+ expect(
+ filterWorkloads({ ...baseParams, guests, searchTerm: 'containerid-uniq-ddd' }).map((g) => g.id),
+ ).toEqual(['cid-guest']);
+ });
+ });
+
+ describe('getDiskUsagePercent', () => {
+ it('treats usage of exactly 1 as a ratio (100) not a percentage', () => {
+ expect(
+ getDiskUsagePercent(makeGuest(1, { disk: { total: 100, used: 100, free: 0, usage: 1 } })),
+ ).toBe(100);
+ });
+
+ it('returns 0 for usage of 0 and clamps negative usage to 0', () => {
+ expect(
+ getDiskUsagePercent(makeGuest(1, { disk: { total: 100, used: 0, free: 100, usage: 0 } })),
+ ).toBe(0);
+ expect(
+ getDiskUsagePercent(makeGuest(2, { disk: { total: 100, used: 0, free: 100, usage: -5 } })),
+ ).toBe(0);
+ });
+
+ it('falls back to used/total when usage is non-finite (Infinity)', () => {
+ expect(
+ getDiskUsagePercent(
+ makeGuest(1, { disk: { total: 200, used: 50, free: 150, usage: Infinity } }),
+ ),
+ ).toBe(25);
+ });
+
+ it('clamps used/total result above 100 to 100', () => {
+ expect(
+ getDiskUsagePercent(
+ makeGuest(1, { disk: { total: 100, used: 150, free: 0, usage: NaN } }),
+ ),
+ ).toBe(100);
+ });
+
+ it('returns null when total is 0 in the used/total fallback', () => {
+ expect(
+ getDiskUsagePercent(
+ makeGuest(1, { disk: { total: 0, used: 50, free: 0, usage: NaN } }),
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null when usage is non-numeric and used/total is invalid', () => {
+ expect(
+ getDiskUsagePercent(
+ makeGuest(1, {
+ disk: {
+ total: 0,
+ used: 0,
+ free: 0,
+ usage: 'n/a' as unknown as number,
+ },
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null when guest or disk is null/undefined', () => {
+ expect(getDiskUsagePercent(null as unknown as WorkloadGuest)).toBeNull();
+ expect(getDiskUsagePercent(undefined as unknown as WorkloadGuest)).toBeNull();
+ expect(
+ getDiskUsagePercent(
+ makeGuest(1, { disk: undefined as unknown as WorkloadGuest['disk'] }),
+ ),
+ ).toBeNull();
+ });
+ });
+
+ describe('getWorkloadGroupKey', () => {
+ it('uses instance-node for system-container type', () => {
+ const guest = makeGuest(1, {
+ type: 'lxc',
+ workloadType: 'system-container',
+ instance: 'inst-1',
+ node: 'node-1',
+ });
+ expect(getWorkloadGroupKey(guest)).toBe('inst-1-node-1');
+ });
+
+ it('falls back through contextLabel -> node -> instance -> namespace -> id', () => {
+ // contextLabel empty, node empty -> instance
+ const byInstance = makeGuest(1, {
+ id: 'fallback-1',
+ type: 'app-container',
+ workloadType: 'app-container',
+ contextLabel: '',
+ node: '',
+ instance: 'inst-only',
+ namespace: 'ns-only',
+ });
+ expect(getWorkloadGroupKey(byInstance)).toBe('app-container:inst-only');
+
+ // contextLabel + node + instance empty -> namespace
+ const byNamespace = makeGuest(2, {
+ id: 'fallback-2',
+ type: 'app-container',
+ workloadType: 'app-container',
+ contextLabel: '',
+ node: '',
+ instance: '',
+ namespace: 'ns-only',
+ });
+ expect(getWorkloadGroupKey(byNamespace)).toBe('app-container:ns-only');
+
+ // everything empty -> id
+ const byId = makeGuest(3, {
+ id: 'last-resort-id',
+ type: 'app-container',
+ workloadType: 'app-container',
+ contextLabel: '',
+ node: '',
+ instance: '',
+ namespace: '',
+ });
+ expect(getWorkloadGroupKey(byId)).toBe('app-container:last-resort-id');
+ });
+ });
+
+ describe('getWorkloadGroupLabel', () => {
+ it('returns plural label for vm prefix when guests array is empty', () => {
+ expect(getWorkloadGroupLabel('vm:ctx-vm', [])).toEqual({ type: 'VMs', name: 'ctx-vm' });
+ });
+
+ it('returns plural label for system-container prefix when guests array is empty', () => {
+ expect(getWorkloadGroupLabel('system-container:ctx-lxc', [])).toEqual({
+ type: 'LXC',
+ name: 'ctx-lxc',
+ });
+ });
+
+ it('returns plural label for pod prefix when guests array is empty', () => {
+ expect(getWorkloadGroupLabel('pod:ctx-pod', [])).toEqual({ type: 'Pods', name: 'ctx-pod' });
+ });
+
+ it('uses normalizedNodeName and groupTypeLabel when provided', () => {
+ const guests = [makeGuest(1, { type: 'vm', workloadType: 'vm' })];
+ expect(getWorkloadGroupLabel('any-key', guests, ' my-host ', ' HostBadge ')).toEqual({
+ type: 'HostBadge',
+ name: 'my-host',
+ });
+ });
+
+ it('returns cluster as type and node as name for vm guest with both', () => {
+ const guests = [
+ makeGuest(1, {
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst-a',
+ node: 'pve1',
+ clusterName: 'my-cluster',
+ }),
+ ];
+ // groupKey = 'inst-a-pve1' (no colon) -> prefix not recognized -> first guest fallback
+ expect(getWorkloadGroupLabel('', guests)).toEqual({ type: 'my-cluster', name: 'pve1' });
+ });
+
+ it('returns empty type and node name for vm guest with node but no cluster', () => {
+ const guests = [
+ makeGuest(1, {
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst-a',
+ node: 'pve2',
+ clusterName: '',
+ }),
+ ];
+ expect(getWorkloadGroupLabel('', guests)).toEqual({ type: '', name: 'pve2' });
+ });
+
+ it('falls through to context-only when guests empty and prefix is unrecognized', () => {
+ expect(getWorkloadGroupLabel('plainkey', [])).toEqual({ type: '', name: 'plainkey' });
+ });
+ });
+
+ describe('buildWorkloadSummaryGroupScope', () => {
+ it('returns null when all guests produce empty canonical IDs', () => {
+ const guest = makeGuest(1, { id: '', type: 'app-container', workloadType: 'app-container' });
+ expect(buildWorkloadSummaryGroupScope('grp', [guest], { type: 'T', name: 'N' })).toBeNull();
+ });
+
+ it('builds singular label for a single guest', () => {
+ const guest = makeGuest(1, {
+ id: 'cid-1',
+ type: 'app-container',
+ workloadType: 'app-container',
+ });
+ const scope = buildWorkloadSummaryGroupScope('grp', [guest], { type: 'Container', name: 'frigate' });
+ expect(scope).not.toBeNull();
+ expect(scope!.label).toBe('frigate · Container (1 workload)');
+ expect(scope!.seriesIds).toEqual(['cid-1']);
+ });
+
+ it('builds plural label and deduplicates canonical IDs for multiple guests', () => {
+ const guests = [
+ makeGuest(1, { id: 'dup-id', type: 'app-container', workloadType: 'app-container' }),
+ makeGuest(2, { id: 'dup-id', type: 'app-container', workloadType: 'app-container' }),
+ ];
+ const scope = buildWorkloadSummaryGroupScope('grp', guests, { type: 'C', name: 'host' });
+ expect(scope).not.toBeNull();
+ expect(scope!.label).toBe('host · C (2 workloads)');
+ expect(scope!.seriesIds).toEqual(['dup-id']); // deduped
+ });
+
+ it('uses workload count alone when label name and type are both empty', () => {
+ const guest = makeGuest(1, { id: 'x-1', type: 'app-container', workloadType: 'app-container' });
+ const scope = buildWorkloadSummaryGroupScope('grp', [guest], { type: '', name: '' });
+ expect(scope).not.toBeNull();
+ expect(scope!.label).toBe('1 workload');
+ });
+
+ it('trims the groupId for the scope id', () => {
+ const guest = makeGuest(1, { id: 'x-2', type: 'app-container', workloadType: 'app-container' });
+ const scope = buildWorkloadSummaryGroupScope(' padded-grp ', [guest], { type: 'T', name: 'N' });
+ expect(scope).not.toBeNull();
+ expect(scope!.id).toBe('padded-grp');
+ });
+ });
+
+ describe('buildWorkloadSummaryGroupScopeMap', () => {
+ it('returns an empty map when groupingMode is flat', () => {
+ const result = buildWorkloadSummaryGroupScopeMap({
+ guests: [makeGuest(1)],
+ nodes: [],
+ groupingMode: 'flat',
+ sortComparator: null,
+ });
+ expect(result.size).toBe(0);
+ });
+
+ it('resolves node display name via buildNodeByInstance for the group label', () => {
+ const guests = [
+ makeGuest(1, { type: 'vm', workloadType: 'vm', instance: 'cluster-a', node: 'node-a' }),
+ ];
+ const nodes = [makeNode('n1', 'cluster-a', 'node-a')];
+
+ const result = buildWorkloadSummaryGroupScopeMap({
+ guests,
+ nodes,
+ groupingMode: 'grouped',
+ sortComparator: null,
+ });
+
+ // groupKey = 'cluster-a-node-a' matches node via instance-name key
+ // getNodeDisplayName -> 'node-a' -> label includes it
+ const scope = result.get('cluster-a-node-a');
+ expect(scope).toBeDefined();
+ expect(scope!.label).toBe('node-a (1 workload)');
+ expect(scope!.seriesIds).toEqual(['cluster-a:node-a:101']);
+ });
+
+ it('falls back to lowercase badge key when exact-case lookup misses', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'c-1',
+ name: 'frigate',
+ type: 'app-container',
+ workloadType: 'app-container',
+ contextLabel: 'Frigate', // capital F -> groupKey 'app-container:Frigate'
+ }),
+ ];
+
+ const result = buildWorkloadSummaryGroupScopeMap({
+ guests,
+ nodes: [],
+ groupingMode: 'grouped',
+ sortComparator: null,
+ groupLabelBadges: {
+ 'app-container:frigate': { label: 'Docker' }, // lowercase key
+ },
+ });
+
+ // badge found via lowercase fallback -> label includes 'Docker'
+ const scope = result.get('app-container:Frigate');
+ expect(scope).toBeDefined();
+ expect(scope!.label).toBe('Frigate · Docker (1 workload)');
+ });
+
+ it('omits groups whose scope is null (empty canonical IDs)', () => {
+ const guests = [
+ makeGuest(1, { id: '', type: 'app-container', workloadType: 'app-container' }),
+ ];
+
+ const result = buildWorkloadSummaryGroupScopeMap({
+ guests,
+ nodes: [],
+ groupingMode: 'grouped',
+ sortComparator: null,
+ });
+
+ expect(result.size).toBe(0);
+ });
+ });
+
+ describe('groupWorkloads', () => {
+ it('sorts the single flat group when a comparator is provided', () => {
+ const guests = [
+ makeGuest(1, { id: 'b-id', name: 'beta', instance: 'x', node: 'y', type: 'vm', workloadType: 'vm' }),
+ makeGuest(2, { id: 'a-id', name: 'alpha', instance: 'x', node: 'y', type: 'vm', workloadType: 'vm' }),
+ ];
+
+ const comparator = createWorkloadSortComparator('name', 'asc');
+ const result = groupWorkloads(guests, 'flat', comparator);
+
+ expect(Object.keys(result)).toEqual(['']);
+ expect(result[''].map((g) => g.id)).toEqual(['a-id', 'b-id']);
+ });
+
+ it('groups without sorting when comparator is null in grouped mode', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'b-id',
+ name: 'beta',
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst',
+ node: 'nd',
+ }),
+ makeGuest(2, {
+ id: 'a-id',
+ name: 'alpha',
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst',
+ node: 'nd',
+ }),
+ ];
+
+ const result = groupWorkloads(guests, 'grouped', null);
+
+ expect(Object.keys(result)).toEqual(['inst-nd']);
+ // Original insertion order preserved (no comparator)
+ expect(result['inst-nd'].map((g) => g.id)).toEqual(['b-id', 'a-id']);
+ });
+
+ it('returns an empty object for empty guests in grouped mode', () => {
+ const result = groupWorkloads([], 'grouped', null);
+ expect(Object.keys(result)).toEqual([]);
+ });
+ });
+});
diff --git a/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov.test.ts b/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov.test.ts
new file mode 100644
index 0000000000..261ba5b018
--- /dev/null
+++ b/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildAlertTrends,
+ buildSelectedBucketDetails,
+ MS_PER_HOUR,
+ type AlertTrendSeries,
+} from '../alertHistoryModel';
+
+// ---------------------------------------------------------------------------
+// buildSelectedBucketDetails — branch coverage for the null guard and the
+// value-returning path (including same-day vs cross-day range labels routed
+// through formatAlertBucketRange).
+// ---------------------------------------------------------------------------
+
+describe('buildSelectedBucketDetails', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0); // Sun Mar 22 2026 12:00:00 UTC
+
+ // --- null guard ----------------------------------------------------------
+
+ it('returns null when selectedBarIndex is null', () => {
+ const trends = buildAlertTrends([], '24h', now);
+ expect(buildSelectedBucketDetails(null, trends, 'en-US')).toBeNull();
+ });
+
+ it('returns null for null index even with an empty trends series', () => {
+ const emptyTrends: AlertTrendSeries = {
+ buckets: [],
+ max: 0,
+ bucketSize: 1,
+ bucketTimes: [],
+ rangeStart: now,
+ rangeHours: 0,
+ };
+ expect(buildSelectedBucketDetails(null, emptyTrends, 'en-US')).toBeNull();
+ });
+
+ // --- value path: index resolution & numeric start/end -------------------
+
+ it('resolves the first bucket (index 0) using real 24h trends', () => {
+ const trends = buildAlertTrends([], '24h', now);
+ const details = buildSelectedBucketDetails(0, trends, 'en-US');
+
+ expect(details).not.toBeNull();
+ const expectedStart = trends.bucketTimes[0];
+ expect(details!.start).toBe(expectedStart);
+ expect(details!.end).toBe(expectedStart + trends.bucketSize * MS_PER_HOUR);
+ expect(details!.end - details!.start).toBe(MS_PER_HOUR);
+ });
+
+ it('resolves a middle bucket using real 24h trends', () => {
+ const trends = buildAlertTrends([], '24h', now);
+ const mid = Math.floor(trends.bucketTimes.length / 2);
+ const details = buildSelectedBucketDetails(mid, trends, 'en-US');
+
+ expect(details).not.toBeNull();
+ expect(details!.start).toBe(trends.bucketTimes[mid]);
+ expect(details!.end).toBe(trends.bucketTimes[mid] + MS_PER_HOUR);
+ });
+
+ it('resolves the last bucket using real 24h trends', () => {
+ const trends = buildAlertTrends([], '24h', now);
+ const last = trends.bucketTimes.length - 1;
+ const details = buildSelectedBucketDetails(last, trends, 'en-US');
+
+ expect(details).not.toBeNull();
+ expect(details!.start).toBe(trends.bucketTimes[last]);
+ expect(details!.end).toBe(trends.bucketTimes[last] + MS_PER_HOUR);
+ });
+
+ it('honours a larger bucketSize (24h) when computing end', () => {
+ const start = Date.UTC(2026, 2, 22, 0, 0, 0);
+ const trends: AlertTrendSeries = {
+ buckets: [0],
+ max: 1,
+ bucketSize: 24,
+ bucketTimes: [start],
+ rangeStart: start,
+ rangeHours: 24,
+ };
+ const details = buildSelectedBucketDetails(0, trends, 'en-US');
+
+ expect(details).not.toBeNull();
+ expect(details!.start).toBe(start);
+ expect(details!.end).toBe(start + 24 * MS_PER_HOUR);
+ expect(details!.end - details!.start).toBe(24 * MS_PER_HOUR);
+ });
+
+ // --- rangeLabel formatting routed through formatAlertBucketRange --------
+
+ it('produces a same-day range label (en-dash separator) for an intra-day bucket', () => {
+ // Bucket 0 of a 24h/1h trend starts at Mar 21 12:00 UTC, ends 13:00 UTC.
+ const trends = buildAlertTrends([], '24h', now);
+ const details = buildSelectedBucketDetails(0, trends, 'en-US');
+
+ expect(details).not.toBeNull();
+ expect(typeof details!.rangeLabel).toBe('string');
+ expect(details!.rangeLabel.length).toBeGreaterThan(0);
+ // Same-day arm uses an en-dash, never the cross-day arrow.
+ expect(details!.rangeLabel).toContain('\u2013'); // –
+ expect(details!.rangeLabel).not.toContain('\u2192'); // →
+ expect(details!.rangeLabel).toContain('Mar');
+ expect(details!.rangeLabel).toContain('21');
+ });
+
+ it('produces a cross-day range label (arrow separator) when the bucket spans midnight', () => {
+ // 6-hour bucket starting 22:00 Mar 22, ending 04:00 Mar 23 → different days.
+ const crossDayStart = Date.UTC(2026, 2, 22, 22, 0, 0);
+ const trends: AlertTrendSeries = {
+ buckets: [0],
+ max: 1,
+ bucketSize: 6,
+ bucketTimes: [crossDayStart],
+ rangeStart: crossDayStart,
+ rangeHours: 6,
+ };
+ const details = buildSelectedBucketDetails(0, trends, 'en-US');
+
+ expect(details).not.toBeNull();
+ expect(details!.start).toBe(crossDayStart);
+ expect(details!.end).toBe(crossDayStart + 6 * MS_PER_HOUR);
+ // Cross-day arm uses the arrow separator.
+ expect(details!.rangeLabel).toContain('\u2192'); // →
+ expect(details!.rangeLabel).not.toContain('\u2013'); // –
+ // Both calendar days should appear.
+ expect(details!.rangeLabel).toContain('22');
+ expect(details!.rangeLabel).toContain('23');
+ });
+
+ it('passes the locale through to the underlying formatter (en-GB)', () => {
+ const trends = buildAlertTrends([], '24h', now);
+ const usDetails = buildSelectedBucketDetails(0, trends, 'en-US');
+ const gbDetails = buildSelectedBucketDetails(0, trends, 'en-GB');
+
+ expect(usDetails).not.toBeNull();
+ expect(gbDetails).not.toBeNull();
+ // Numeric start/end are locale-independent.
+ expect(gbDetails!.start).toBe(usDetails!.start);
+ expect(gbDetails!.end).toBe(usDetails!.end);
+ // Both share the month abbreviation but may differ in time formatting.
+ expect(gbDetails!.rangeLabel).toContain('Mar');
+ });
+});
diff --git a/frontend-modern/src/features/kubernetes/__tests__/kubernetesPageModel.branchcov.test.ts b/frontend-modern/src/features/kubernetes/__tests__/kubernetesPageModel.branchcov.test.ts
new file mode 100644
index 0000000000..ffe41de26e
--- /dev/null
+++ b/frontend-modern/src/features/kubernetes/__tests__/kubernetesPageModel.branchcov.test.ts
@@ -0,0 +1,826 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import {
+ buildKubernetesIncidentRows,
+ compareKubernetesEvents,
+ compareKubernetesPods,
+ filterKubernetesResources,
+ kubernetesResourceSearchHaystack,
+ mapKubernetesNodeStatus,
+ mapKubernetesPodStatus,
+} from '../kubernetesPageModel';
+
+const makeResource = (resource: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource => ({
+ name: resource.id,
+ displayName: resource.id,
+ platformId: 'lab',
+ platformType: 'kubernetes',
+ sourceType: 'agent',
+ sources: ['kubernetes'],
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...resource,
+});
+
+describe('mapKubernetesPodStatus — uncovered branches', () => {
+ it('returns success for a Running pod with no containers', () => {
+ expect(
+ mapKubernetesPodStatus(
+ makeResource({
+ id: 'running-bare',
+ type: 'pod',
+ kubernetes: { podPhase: 'Running' },
+ }),
+ ),
+ ).toEqual({ variant: 'success', label: 'Running' });
+ });
+
+ it('returns success for Succeeded phase', () => {
+ expect(
+ mapKubernetesPodStatus(
+ makeResource({
+ id: 'succeeded',
+ type: 'pod',
+ kubernetes: { podPhase: 'Succeeded' },
+ }),
+ ),
+ ).toEqual({ variant: 'success', label: 'Succeeded' });
+ });
+
+ it('returns muted for Unknown phase', () => {
+ expect(
+ mapKubernetesPodStatus(
+ makeResource({
+ id: 'unknown-phase',
+ type: 'pod',
+ kubernetes: { podPhase: 'Unknown' },
+ }),
+ ),
+ ).toEqual({ variant: 'muted', label: 'Unknown' });
+ });
+
+ it('returns muted Unknown when no phase fields are set at all', () => {
+ expect(mapKubernetesPodStatus(makeResource({ id: 'bare-pod', type: 'pod' }))).toEqual({
+ variant: 'muted',
+ label: 'Unknown',
+ });
+ });
+
+ it('capitalises an unrecognised non-empty phase via eventTypeLabel fallback', () => {
+ expect(
+ mapKubernetesPodStatus(
+ makeResource({
+ id: 'terminating',
+ type: 'pod',
+ kubernetes: { podPhase: 'Terminating' },
+ }),
+ ),
+ ).toEqual({ variant: 'muted', label: 'Terminating' });
+ });
+
+ it('falls back to kubernetes.phase when podPhase is absent', () => {
+ expect(
+ mapKubernetesPodStatus(
+ makeResource({
+ id: 'phase-fallback',
+ type: 'pod',
+ kubernetes: { phase: 'Running' },
+ }),
+ ),
+ ).toEqual({ variant: 'success', label: 'Running' });
+ });
+
+ it('escalates terminated non-ready containers to danger with "Container error" label when reason is absent', () => {
+ expect(
+ mapKubernetesPodStatus(
+ makeResource({
+ id: 'term-noreason',
+ type: 'pod',
+ kubernetes: {
+ podPhase: 'Running',
+ podContainers: [{ ready: false, state: 'terminated' }],
+ },
+ }),
+ ),
+ ).toEqual({ variant: 'danger', label: 'Container error' });
+ });
+
+ it('does not flag a terminated but ready container as fatal', () => {
+ expect(
+ mapKubernetesPodStatus(
+ makeResource({
+ id: 'term-ready',
+ type: 'pod',
+ kubernetes: {
+ podPhase: 'Running',
+ podContainers: [{ ready: true, state: 'terminated' }],
+ },
+ }),
+ ),
+ ).toEqual({ variant: 'success', label: 'Running' });
+ });
+});
+
+describe('mapKubernetesNodeStatus — uncovered branches', () => {
+ it('maps running and healthy statuses to success when ready is undefined', () => {
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({ id: 'n-running', type: 'k8s-node', status: 'running' }),
+ ),
+ ).toEqual({ variant: 'success', label: 'Ready' });
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({
+ id: 'n-healthy',
+ type: 'k8s-node',
+ status: 'healthy' as unknown as Resource['status'],
+ }),
+ ),
+ ).toEqual({ variant: 'success', label: 'Ready' });
+ });
+
+ it('maps stopped and failed statuses to danger when ready is undefined', () => {
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({ id: 'n-stopped', type: 'k8s-node', status: 'stopped' }),
+ ),
+ ).toEqual({ variant: 'danger', label: 'NotReady' });
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({
+ id: 'n-failed',
+ type: 'k8s-node',
+ status: 'failed' as unknown as Resource['status'],
+ }),
+ ),
+ ).toEqual({ variant: 'danger', label: 'NotReady' });
+ });
+
+ it('maps degraded, warning, and pending statuses to warning when ready is undefined', () => {
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({ id: 'n-degraded', type: 'k8s-node', status: 'degraded' }),
+ ),
+ ).toEqual({ variant: 'warning', label: 'Degraded' });
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({ id: 'n-warning', type: 'k8s-node', status: 'warning' }),
+ ),
+ ).toEqual({ variant: 'warning', label: 'Degraded' });
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({
+ id: 'n-pending',
+ type: 'k8s-node',
+ status: 'pending' as unknown as Resource['status'],
+ }),
+ ),
+ ).toEqual({ variant: 'warning', label: 'Degraded' });
+ });
+
+ it('returns muted Unknown for an unrecognised status with no ready flag', () => {
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({ id: 'n-unknown', type: 'k8s-node', status: 'unknown' }),
+ ),
+ ).toEqual({ variant: 'muted', label: 'Unknown' });
+ });
+
+ it('returns muted Unknown for paused status (not handled by the node mapper)', () => {
+ expect(
+ mapKubernetesNodeStatus(
+ makeResource({ id: 'n-paused', type: 'k8s-node', status: 'paused' }),
+ ),
+ ).toEqual({ variant: 'muted', label: 'Unknown' });
+ });
+});
+
+describe('kubernetesResourceSearchHaystack', () => {
+ it('collects kubernetes-specific fields into a lowercase haystack', () => {
+ const resource = makeResource({
+ id: 'pod-full',
+ type: 'pod',
+ name: 'my-pod',
+ displayName: 'My Pod',
+ parentName: 'parent-dep',
+ tags: ['team-payments', 'env-prod'],
+ agent: { hostname: 'agent-host' },
+ canonicalIdentity: {
+ displayName: 'checkout-api',
+ hostname: 'ci-host',
+ primaryId: 'pri-1',
+ aliases: ['alias-1'],
+ },
+ kubernetes: {
+ clusterId: 'prod-cluster-id',
+ clusterName: 'Production',
+ namespace: 'payments',
+ podName: 'checkout-abc',
+ podPhase: 'Running',
+ nodeName: 'worker-1',
+ ownerKind: 'Deployment',
+ ownerName: 'checkout',
+ image: 'ghcr.io/app:v1',
+ resourceKind: 'Pod',
+ externalIps: ['1.2.3.4'],
+ addresses: ['10.0.0.1'],
+ podContainers: [
+ { name: 'main', image: 'ghcr.io/app:v1', state: 'running', reason: '' },
+ ],
+ },
+ });
+
+ const haystack = kubernetesResourceSearchHaystack(resource);
+ expect(haystack).toBe(haystack.toLowerCase());
+ expect(haystack).toContain('my-pod');
+ expect(haystack).toContain('production');
+ expect(haystack).toContain('payments');
+ expect(haystack).toContain('checkout-abc');
+ expect(haystack).toContain('worker-1');
+ expect(haystack).toContain('team-payments');
+ expect(haystack).toContain('env-prod');
+ expect(haystack).toContain('main');
+ expect(haystack).toContain('1.2.3.4');
+ expect(haystack).toContain('10.0.0.1');
+ expect(haystack).toContain('checkout-api');
+ expect(haystack).toContain('pri-1');
+ expect(haystack).toContain('alias-1');
+ expect(haystack).toContain('agent-host');
+ });
+
+ it('returns a minimal haystack for a bare resource', () => {
+ const haystack = kubernetesResourceSearchHaystack(makeResource({ id: 'bare', type: 'pod' }));
+ expect(haystack).toBe('bare bare bare lab kubernetes');
+ });
+
+ it('filters out whitespace-only and undefined values', () => {
+ const haystack = kubernetesResourceSearchHaystack(
+ makeResource({
+ id: 'pod-ws',
+ type: 'pod',
+ name: ' ',
+ displayName: ' ',
+ }),
+ );
+ expect(haystack).toBe('pod-ws lab kubernetes');
+ });
+
+ it('includes podContainer name, image, state, and reason when defined', () => {
+ const haystack = kubernetesResourceSearchHaystack(
+ makeResource({
+ id: 'pod-containers',
+ type: 'pod',
+ kubernetes: {
+ podPhase: 'Running',
+ podContainers: [
+ { name: 'sidecar', image: 'busybox:latest', state: 'running', reason: '' },
+ { name: 'main', image: 'app:v2', state: 'waiting', reason: 'ImagePullBackOff' },
+ ],
+ },
+ }),
+ );
+ expect(haystack).toContain('sidecar');
+ expect(haystack).toContain('busybox:latest');
+ expect(haystack).toContain('main');
+ expect(haystack).toContain('imagepullbackoff');
+ });
+});
+
+describe('displayName fallback chain (via compareKubernetesPods)', () => {
+ const runningReady = {
+ podPhase: 'Running',
+ podContainers: [{ ready: true, state: 'running' }],
+ };
+
+ it('uses resource.displayName for tie-breaking when present', () => {
+ const zzz = makeResource({
+ id: 'id-zzz',
+ type: 'pod',
+ displayName: 'zzz-name',
+ kubernetes: runningReady,
+ });
+ const aaa = makeResource({
+ id: 'id-aaa',
+ type: 'pod',
+ displayName: 'aaa-name',
+ kubernetes: runningReady,
+ });
+ expect([zzz, aaa].sort(compareKubernetesPods).map((r) => r.id)).toEqual(['id-aaa', 'id-zzz']);
+ });
+
+ it('falls back to resource.name when displayName is empty', () => {
+ const zzz = makeResource({
+ id: 'id-zzz',
+ type: 'pod',
+ displayName: '',
+ name: 'zzz-fallback',
+ kubernetes: runningReady,
+ });
+ const aaa = makeResource({
+ id: 'id-aaa',
+ type: 'pod',
+ displayName: '',
+ name: 'aaa-fallback',
+ kubernetes: runningReady,
+ });
+ expect([zzz, aaa].sort(compareKubernetesPods).map((r) => r.id)).toEqual(['id-aaa', 'id-zzz']);
+ });
+
+ it('falls back to kubernetes.podName when displayName and name are empty', () => {
+ const zzz = makeResource({
+ id: 'id-zzz',
+ type: 'pod',
+ displayName: '',
+ name: '',
+ kubernetes: { ...runningReady, podName: 'zzz-pod' },
+ });
+ const aaa = makeResource({
+ id: 'id-aaa',
+ type: 'pod',
+ displayName: '',
+ name: '',
+ kubernetes: { ...runningReady, podName: 'aaa-pod' },
+ });
+ expect([zzz, aaa].sort(compareKubernetesPods).map((r) => r.id)).toEqual(['id-aaa', 'id-zzz']);
+ });
+
+ it('falls back to resource.id when all display fields are empty', () => {
+ const zzz = makeResource({
+ id: 'id-zzz',
+ type: 'pod',
+ displayName: '',
+ name: '',
+ kubernetes: runningReady,
+ });
+ const aaa = makeResource({
+ id: 'id-aaa',
+ type: 'pod',
+ displayName: '',
+ name: '',
+ kubernetes: runningReady,
+ });
+ expect([zzz, aaa].sort(compareKubernetesPods).map((r) => r.id)).toEqual(['id-aaa', 'id-zzz']);
+ });
+});
+
+describe('kubernetesIncidentResourceDisplayName (via buildKubernetesIncidentRows)', () => {
+ const incident = { code: 'k8s_x', severity: 'warning', summary: 'sig' };
+
+ it('falls through displayName then name then podName then id', () => {
+ const fromDisplay = buildKubernetesIncidentRows([
+ makeResource({ id: 'r1', type: 'pod', displayName: 'Display', incidents: [incident] }),
+ ]);
+ expect(fromDisplay[0].resourceName).toBe('Display');
+
+ const fromName = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'r2',
+ type: 'pod',
+ displayName: '',
+ name: 'Namey',
+ incidents: [incident],
+ }),
+ ]);
+ expect(fromName[0].resourceName).toBe('Namey');
+
+ const fromPodName = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'r3',
+ type: 'pod',
+ displayName: '',
+ name: '',
+ kubernetes: { podName: 'pod-xyz' },
+ incidents: [incident],
+ }),
+ ]);
+ expect(fromPodName[0].resourceName).toBe('pod-xyz');
+
+ const fromId = buildKubernetesIncidentRows([
+ makeResource({ id: 'r4', type: 'pod', displayName: '', name: '', incidents: [incident] }),
+ ]);
+ expect(fromId[0].resourceName).toBe('r4');
+ });
+});
+
+describe('kubernetesIncidentLabel (via buildKubernetesIncidentRows)', () => {
+ it('uses resource.incidentLabel when present', () => {
+ const rows = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'r1',
+ type: 'pod',
+ incidentLabel: 'Disk Pressure Alert',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 'sig' }],
+ }),
+ ]);
+ expect(rows[0].label).toBe('Disk Pressure Alert');
+ });
+
+ it('title-cases incident.code (stripping k8s_ prefix) when no incidentLabel', () => {
+ const withPrefix = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'r1',
+ type: 'pod',
+ incidents: [{ code: 'k8s_pod_crashloop', severity: 'warning', summary: 'sig' }],
+ }),
+ ]);
+ expect(withPrefix[0].label).toBe('Pod Crashloop');
+
+ const withoutPrefix = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'r2',
+ type: 'pod',
+ incidents: [{ code: 'custom_event', severity: 'warning', summary: 'sig' }],
+ }),
+ ]);
+ expect(withoutPrefix[0].label).toBe('Custom Event');
+ });
+
+ it('returns "Kubernetes Alert" when neither incidentLabel nor incident.code is set', () => {
+ const rows = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'r1',
+ type: 'pod',
+ incidents: [{ code: '', severity: 'warning', summary: 'sig' }],
+ }),
+ ]);
+ expect(rows[0].label).toBe('Kubernetes Alert');
+ });
+});
+
+describe('buildKubernetesIncidentRow field fallbacks (via buildKubernetesIncidentRows)', () => {
+ it('derives severity from incident, then resource, then defaults to info', () => {
+ const fromIncident = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'critical', summary: 's' }],
+ }),
+ ]);
+ expect(fromIncident[0].severity).toBe('critical');
+ expect(fromIncident[0].severityBucket).toBe('critical');
+
+ const fromResource = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidentSeverity: 'warning',
+ incidents: [{ code: 'k8s_x', severity: '', summary: 's' }],
+ }),
+ ]);
+ expect(fromResource[0].severity).toBe('warning');
+ expect(fromResource[0].severityBucket).toBe('warning');
+
+ const defaulted = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'c',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: '', summary: 's' }],
+ }),
+ ]);
+ expect(defaulted[0].severity).toBe('info');
+ expect(defaulted[0].severityBucket).toBe('info');
+ });
+
+ it('derives code from incident, then resource, then defaults to k8s_alert', () => {
+ const fromResource = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidentCode: 'custom_code',
+ incidents: [{ code: '', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(fromResource[0].code).toBe('custom_code');
+
+ const defaulted = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidents: [{ code: '', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(defaulted[0].code).toBe('k8s_alert');
+ });
+
+ it('derives summary from incident, then resource.incidentSummary, then kubernetesIncidentLabel', () => {
+ const fromIncident = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 'direct summary' }],
+ }),
+ ]);
+ expect(fromIncident[0].summary).toBe('direct summary');
+
+ const fromResource = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidentSummary: 'resource summary',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: '' }],
+ }),
+ ]);
+ expect(fromResource[0].summary).toBe('resource summary');
+
+ const fromLabel = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'c',
+ type: 'pod',
+ incidentLabel: 'Fallback Label',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: '' }],
+ }),
+ ]);
+ expect(fromLabel[0].summary).toBe('Fallback Label');
+ });
+
+ it('uses nativeId for the row key when present, else falls to code', () => {
+ const withNativeId = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidents: [
+ { code: 'k8s_x', severity: 'warning', summary: 's', nativeId: 'evt-42' },
+ ],
+ }),
+ ]);
+ expect(withNativeId[0].id).toBe('a:incident:evt-42:0');
+
+ const withoutNativeId = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidents: [{ code: 'k8s_y', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(withoutNativeId[0].id).toBe('b:incident:k8s_y:0');
+ });
+
+ it('derives source from incident.source, then incident.provider, then defaults to kubernetes', () => {
+ const fromSource = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidents: [
+ { code: 'k8s_x', severity: 'warning', summary: 's', source: 'prometheus' },
+ ],
+ }),
+ ]);
+ expect(fromSource[0].source).toBe('prometheus');
+
+ const fromProvider = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidents: [
+ { code: 'k8s_x', severity: 'warning', summary: 's', provider: 'datadog' },
+ ],
+ }),
+ ]);
+ expect(fromProvider[0].source).toBe('datadog');
+
+ const defaulted = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'c',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(defaulted[0].source).toBe('kubernetes');
+ });
+
+ it('derives category from resource.incidentCategory, defaulting to kubernetes-health', () => {
+ const custom = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidentCategory: 'custom-cat',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(custom[0].category).toBe('custom-cat');
+
+ const defaulted = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(defaulted[0].category).toBe('kubernetes-health');
+ });
+
+ it('derives action from resource.incidentAction, defaulting to the investigate prompt', () => {
+ const custom = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidentAction: 'Run kubectl describe',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(custom[0].action).toBe('Run kubectl describe');
+
+ const defaulted = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(defaulted[0].action).toBe('Investigate in Pulse alerts');
+ });
+
+ it('derives priority from resource.incidentPriority, falling back to severity rank times 1000', () => {
+ const explicit = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidentPriority: 42,
+ incidents: [{ code: 'k8s_x', severity: 'critical', summary: 's' }],
+ }),
+ ]);
+ expect(explicit[0].priority).toBe(42);
+
+ const critical = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'critical', summary: 's' }],
+ }),
+ ]);
+ expect(critical[0].priority).toBe(3000);
+
+ const info = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'c',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'info', summary: 's' }],
+ }),
+ ]);
+ expect(info[0].priority).toBe(1000);
+ });
+
+ it('passes through incident.startedAt to the row', () => {
+ const withStarted = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'pod',
+ incidents: [
+ { code: 'k8s_x', severity: 'warning', summary: 's', startedAt: '2026-01-01T00:00:00Z' },
+ ],
+ }),
+ ]);
+ expect(withStarted[0].startedAt).toBe('2026-01-01T00:00:00Z');
+
+ const withoutStarted = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'pod',
+ incidents: [{ code: 'k8s_x', severity: 'warning', summary: 's' }],
+ }),
+ ]);
+ expect(withoutStarted[0].startedAt).toBeUndefined();
+ });
+});
+
+describe('buildKubernetesRollupIncidentRow (via buildKubernetesIncidentRows)', () => {
+ it('synthesises a rollup row with id suffix :incident:rollup', () => {
+ const rows = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'node-x',
+ type: 'k8s-node',
+ incidentCount: 2,
+ incidentSeverity: 'critical',
+ }),
+ ]);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe('node-x:incident:rollup');
+ });
+
+ it('uses incidentSummary, then incidentLabel, then auto-generates a count-based summary', () => {
+ const fromSummary = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'a',
+ type: 'k8s-node',
+ incidentCount: 1,
+ incidentSummary: 'Disk pressure',
+ }),
+ ]);
+ expect(fromSummary[0].summary).toBe('Disk pressure');
+
+ const fromLabel = buildKubernetesIncidentRows([
+ makeResource({
+ id: 'b',
+ type: 'k8s-node',
+ incidentCount: 1,
+ incidentLabel: 'NodeNotReady',
+ }),
+ ]);
+ expect(fromLabel[0].summary).toBe('NodeNotReady');
+
+ const auto3 = buildKubernetesIncidentRows([
+ makeResource({ id: 'c', type: 'k8s-node', incidentCount: 3 }),
+ ]);
+ expect(auto3[0].summary).toBe('3 active Kubernetes alerts');
+
+ const auto1 = buildKubernetesIncidentRows([
+ makeResource({ id: 'd', type: 'k8s-node', incidentCount: 1 }),
+ ]);
+ expect(auto1[0].summary).toBe('1 active Kubernetes alert');
+ });
+
+ it('auto-generates a pluralised summary when count is 0 but rollup signal exists', () => {
+ const rows = buildKubernetesIncidentRows([
+ makeResource({ id: 'e', type: 'k8s-node', incidentCode: 'k8s_thing' }),
+ ]);
+ expect(rows[0].summary).toBe('1 active Kubernetes alerts');
+ });
+
+ it('defaults severity to info and code to k8s_alert when resource fields are absent', () => {
+ const rows = buildKubernetesIncidentRows([
+ makeResource({ id: 'f', type: 'k8s-node', incidentCount: 1 }),
+ ]);
+ expect(rows[0].severity).toBe('info');
+ expect(rows[0].severityBucket).toBe('info');
+ expect(rows[0].code).toBe('k8s_alert');
+ });
+});
+
+describe('parseKubernetesEventObservedTime edge cases (via compareKubernetesEvents)', () => {
+ it('returns 0 for events with no timestamp, breaking ties alphabetically by id', () => {
+ const a = makeResource({ id: 'event-a', type: 'k8s-event' });
+ const b = makeResource({ id: 'event-b', type: 'k8s-event' });
+ expect([b, a].sort(compareKubernetesEvents).map((r) => r.id)).toEqual(['event-a', 'event-b']);
+ });
+
+ it('returns 0 for malformed timestamp strings so newer valid events sort first', () => {
+ const bad = makeResource({
+ id: 'event-bad',
+ type: 'k8s-event',
+ kubernetes: { eventTime: 'not-a-date' },
+ });
+ const good = makeResource({
+ id: 'event-good',
+ type: 'k8s-event',
+ kubernetes: { eventTime: '2026-01-01T00:00:00Z' },
+ });
+ expect([bad, good].sort(compareKubernetesEvents).map((r) => r.id)).toEqual([
+ 'event-good',
+ 'event-bad',
+ ]);
+ });
+
+ it('treats whitespace-only eventTime as empty, falling through to firstSeen', () => {
+ const ws = makeResource({
+ id: 'ws',
+ type: 'k8s-event',
+ kubernetes: { eventTime: ' ', firstSeen: '2026-06-01T00:00:00Z' },
+ });
+ const older = makeResource({
+ id: 'older',
+ type: 'k8s-event',
+ kubernetes: { eventTime: '2026-01-01T00:00:00Z' },
+ });
+ expect([older, ws].sort(compareKubernetesEvents).map((r) => r.id)).toEqual(['ws', 'older']);
+ });
+});
+
+describe('mapResourceStatusToTriad (via filterKubernetesResources)', () => {
+ it('maps running to online and stopped to offline', () => {
+ const resources = [
+ makeResource({ id: 'r-running', type: 'pod', status: 'running' }),
+ makeResource({ id: 'r-stopped', type: 'pod', status: 'stopped' }),
+ ];
+ expect(filterKubernetesResources(resources, '', 'online').map((r) => r.id)).toEqual([
+ 'r-running',
+ ]);
+ expect(filterKubernetesResources(resources, '', 'offline').map((r) => r.id)).toEqual([
+ 'r-stopped',
+ ]);
+ });
+
+ it('maps paused to degraded', () => {
+ const resources = [makeResource({ id: 'r-paused', type: 'pod', status: 'paused' })];
+ expect(filterKubernetesResources(resources, '', 'degraded').map((r) => r.id)).toEqual([
+ 'r-paused',
+ ]);
+ });
+
+ it('maps unknown and empty statuses to the unknown triad, excluded from all specific filters', () => {
+ const resources = [
+ makeResource({ id: 'r-unknown', type: 'pod', status: 'unknown' }),
+ makeResource({
+ id: 'r-empty',
+ type: 'pod',
+ status: '' as unknown as Resource['status'],
+ }),
+ ];
+ expect(filterKubernetesResources(resources, '', 'online')).toEqual([]);
+ expect(filterKubernetesResources(resources, '', 'degraded')).toEqual([]);
+ expect(filterKubernetesResources(resources, '', 'offline')).toEqual([]);
+ expect(filterKubernetesResources(resources, '', 'all').map((r) => r.id)).toEqual([
+ 'r-unknown',
+ 'r-empty',
+ ]);
+ });
+});
diff --git a/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupRecoveryModel.branchcov.test.ts b/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupRecoveryModel.branchcov.test.ts
new file mode 100644
index 0000000000..9bcb78ea61
--- /dev/null
+++ b/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupRecoveryModel.branchcov.test.ts
@@ -0,0 +1,588 @@
+import { describe, expect, it } from 'vitest';
+
+import type { BackupTask, GuestSnapshot, PBSBackup } from '@/types/api';
+import type { Resource } from '@/types/resource';
+
+import {
+ buildProxmoxBackupRecoveryModel,
+ getWorkloadRecoveryPostureLabel,
+ type ProxmoxBackupRecoveryModel,
+ type WorkloadRecoveryPosture,
+} from '../proxmoxBackupRecoveryModel';
+
+// ---------------------------------------------------------------------------
+// Constants & helpers
+// ---------------------------------------------------------------------------
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const NOW = Date.parse('2026-07-10T00:00:00Z');
+const isoDaysAgo = (days: number): string => new Date(NOW - days * DAY_MS).toISOString();
+
+// ---------------------------------------------------------------------------
+// Fixture builders (same shapes as the sibling test files)
+// ---------------------------------------------------------------------------
+
+const workload = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: 'vm-100',
+ type: 'vm',
+ name: 'web-01',
+ displayName: 'web-01',
+ platformId: 'pve-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'running',
+ lastSeen: NOW,
+ proxmox: { vmid: 100, node: 'node-a' },
+ ...overrides,
+ }) as Resource;
+
+const pbsBackup = (overrides: Partial<PBSBackup> = {}): PBSBackup => ({
+ id: 'pbs/main/ns1/vm/100/2026-07-09T00:00:00Z',
+ instance: 'pbs',
+ datastore: 'main',
+ namespace: 'ns1',
+ backupType: 'vm',
+ vmid: '100',
+ backupTime: '2026-07-09T00:00:00Z',
+ size: 1_000_000,
+ protected: false,
+ verified: true,
+ files: ['index.json.blob'],
+ owner: 'backup@pbs',
+ ...overrides,
+});
+
+const snap = (overrides: Partial<GuestSnapshot> = {}): GuestSnapshot => ({
+ id: 'snap-100',
+ name: 'pre-upgrade',
+ node: 'node-a',
+ instance: 'inst-a',
+ type: 'vm',
+ vmid: 100,
+ time: '2026-07-09T00:00:00Z',
+ vmstate: false,
+ ...overrides,
+});
+
+const task = (overrides: Partial<BackupTask> = {}): BackupTask => ({
+ id: 'task-100',
+ node: 'node-a',
+ instance: 'inst-a',
+ type: 'vm',
+ vmid: 100,
+ status: 'OK',
+ startTime: isoDaysAgo(5),
+ ...overrides,
+});
+
+type ModelInput = Parameters<typeof buildProxmoxBackupRecoveryModel>[0];
+
+const buildModel = (input: Partial<ModelInput>): ProxmoxBackupRecoveryModel =>
+ buildProxmoxBackupRecoveryModel({
+ workloads: [],
+ pbsBackups: [],
+ archives: [],
+ snapshots: [],
+ tasks: [],
+ nowMs: NOW,
+ ...input,
+ });
+
+// ---------------------------------------------------------------------------
+// getWorkloadRecoveryPostureLabel — uncovered switch cases
+// (sibling tests already exercise 'current' and 'failed')
+// ---------------------------------------------------------------------------
+
+describe('getWorkloadRecoveryPostureLabel uncovered switch cases', () => {
+ it.each<[WorkloadRecoveryPosture, string]>([
+ ['aging', 'Aging'],
+ ['stale', 'Stale'],
+ ['snapshot-only', 'Snapshot only'],
+ ['uncovered', 'Uncovered'],
+ ['unverified', 'Unverified'],
+ ])('renders posture %s as %j', (posture, expected) => {
+ expect(getWorkloadRecoveryPostureLabel(posture)).toBe(expected);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildPosture — uncovered posture arms (private; exercised via the model).
+// Sibling tests cover 'current', 'uncovered', and the 'failed' posture when a
+// failed task started AFTER the recovery (startedMs >= createdMs).
+// ---------------------------------------------------------------------------
+
+describe('buildPosture uncovered arms (via buildProxmoxBackupRecoveryModel)', () => {
+ it('classifies a 14-day-old PBS recovery as "aging"', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ pbsBackups: [pbsBackup({ backupTime: isoDaysAgo(14) })],
+ });
+ expect(model.coverageRows[0].posture).toBe('aging');
+ expect(model.coverageRows[0].postureRank).toBe(4);
+ });
+
+ it('classifies a 45-day-old PBS recovery as "stale"', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ pbsBackups: [pbsBackup({ backupTime: isoDaysAgo(45) })],
+ });
+ expect(model.coverageRows[0].posture).toBe('stale');
+ expect(model.coverageRows[0].postureRank).toBe(2);
+ });
+
+ it('flags a recent unverified PBS recovery as "unverified"', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ pbsBackups: [pbsBackup({ backupTime: isoDaysAgo(1), verified: false })],
+ });
+ expect(model.coverageRows[0].posture).toBe('unverified');
+ expect(model.coverageRows[0].postureRank).toBe(2);
+ });
+
+ it('flags a guest-snapshot-only workload as "snapshot-only"', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ snapshots: [snap({})],
+ });
+ expect(model.coverageRows[0].posture).toBe('snapshot-only');
+ expect(model.coverageRows[0].postureRank).toBe(3);
+ expect(model.coverageRows[0].snapshotCount).toBe(1);
+ expect(model.coverageRows[0].pbsCount).toBe(0);
+ });
+
+ it('treats a failed task with an unparseable start time as the latest failure', () => {
+ // startedMs is undefined -> the `latestTask.startedMs === undefined` arm of
+ // the failedTask disjunction fires even though the recovery has a createdMs.
+ const model = buildModel({
+ workloads: [workload({})],
+ pbsBackups: [pbsBackup({ backupTime: isoDaysAgo(1) })],
+ tasks: [
+ task({
+ status: 'failed',
+ startTime: '',
+ type: 'vm',
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].posture).toBe('failed');
+ expect(model.coverageRows[0].postureRank).toBe(0);
+ expect(model.coverageRows[0].latestTask?.label).toBe('Failed');
+ expect(model.coverageRows[0].latestTask?.startedMs).toBeUndefined();
+ });
+
+ it('does not flag "failed" when a failed task predates the latest recovery', () => {
+ // failedTask is false because startedMs < latestRecovery.createdMs, so the
+ // failedTask conjunction is false and posture falls through to the age band.
+ const model = buildModel({
+ workloads: [workload({})],
+ pbsBackups: [pbsBackup({ backupTime: isoDaysAgo(1) })],
+ tasks: [
+ task({
+ status: 'failed',
+ startTime: isoDaysAgo(10),
+ type: 'vm',
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].posture).toBe('current');
+ expect(model.coverageRows[0].latestTask?.label).toBe('Failed');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// matchWorkloadByHints — all branches (private; exercised through tasks whose
+// type maps to "unknown", e.g. vzdump, forcing the hint-matching path).
+// ---------------------------------------------------------------------------
+
+describe('matchWorkloadByHints branches (via vzdump tasks)', () => {
+ it('returns the hint-matched candidate among several same-vmid workloads', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'vm-420a', proxmox: { vmid: 420, node: 'alpha' } }),
+ workload({ id: 'vm-420b', proxmox: { vmid: 420, node: 'beta' } }),
+ ],
+ tasks: [
+ task({
+ id: 't-420',
+ type: 'vzdump',
+ vmid: 420,
+ node: 'alpha',
+ instance: '',
+ status: 'OK',
+ }),
+ ],
+ });
+ const alpha = model.coverageRows.find((row) => row.workload.node === 'alpha');
+ const beta = model.coverageRows.find((row) => row.workload.node === 'beta');
+ expect(alpha?.latestTask?.label).toBe('OK');
+ expect(beta?.latestTask).toBeUndefined();
+ });
+
+ it('returns undefined when multiple candidates share a vmid but no hint matches', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'vm-430a', proxmox: { vmid: 430, node: 'alpha' } }),
+ workload({ id: 'vm-430b', proxmox: { vmid: 430, node: 'beta' } }),
+ ],
+ tasks: [
+ task({
+ id: 't-430',
+ type: 'vzdump',
+ vmid: 430,
+ node: 'gamma',
+ instance: '',
+ status: 'OK',
+ }),
+ ],
+ });
+ expect(model.coverageRows.every((row) => row.latestTask === undefined)).toBe(true);
+ });
+
+ it('falls back to the only candidate when its hints do not match', () => {
+ const model = buildModel({
+ workloads: [workload({ id: 'vm-440', proxmox: { vmid: 440, node: 'alpha' } })],
+ tasks: [
+ task({
+ id: 't-440',
+ type: 'vzdump',
+ vmid: 440,
+ node: 'gamma',
+ instance: '',
+ status: 'OK',
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].latestTask?.label).toBe('OK');
+ });
+
+ it('falls back to the only candidate when hints are all blank', () => {
+ const model = buildModel({
+ workloads: [workload({ id: 'vm-450', proxmox: { vmid: 450, node: 'alpha' } })],
+ tasks: [
+ task({
+ id: 't-450',
+ type: 'vzdump',
+ vmid: 450,
+ node: '',
+ instance: '',
+ status: 'OK',
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].latestTask?.label).toBe('OK');
+ });
+
+ it('yields no row when no candidate exists for the task vmid', () => {
+ const model = buildModel({
+ tasks: [
+ task({
+ id: 't-460',
+ type: 'vzdump',
+ vmid: 460,
+ node: 'alpha',
+ instance: '',
+ status: 'OK',
+ }),
+ ],
+ });
+ expect(model.coverageRows).toHaveLength(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// resourceBackupType — oci-container and unknown branches (private; via
+// candidate type). Sibling tests cover 'vm' and 'system-container'.
+// ---------------------------------------------------------------------------
+
+describe('resourceBackupType branches (via candidate type)', () => {
+ it('maps an oci-container resource to workload type "ct"', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'oci-560', type: 'oci-container', proxmox: { vmid: 560, node: 'n' } }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.type).toBe('ct');
+ expect(model.coverageRows[0].workload.typeLabel).toBe('LXC');
+ });
+
+ it('drops a non-workload resource type as an unknown candidate', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'storage-570', type: 'storage', proxmox: { vmid: 570, node: 'n' } }),
+ ],
+ });
+ expect(model.coverageRows).toHaveLength(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// resourceNode — nodeName / node / parentName / none arms (private; via
+// candidate node).
+// ---------------------------------------------------------------------------
+
+describe('resourceNode branches (via candidate node)', () => {
+ it('prefers proxmox.nodeName when present', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'vm-721', proxmox: { vmid: 721, nodeName: 'named-a' } }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.node).toBe('named-a');
+ });
+
+ it('falls back to proxmox.node when nodeName is absent', () => {
+ const model = buildModel({
+ workloads: [workload({ id: 'vm-722', proxmox: { vmid: 722, node: 'nodeonly' } })],
+ });
+ expect(model.coverageRows[0].workload.node).toBe('nodeonly');
+ });
+
+ it('falls back to parentName when no proxmox node field is set', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'vm-723', parentName: 'parent-x', proxmox: { vmid: 723 } }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.node).toBe('parent-x');
+ });
+
+ it('returns undefined when no node source is available', () => {
+ const model = buildModel({
+ workloads: [workload({ id: 'vm-724', proxmox: { vmid: 724 } })],
+ });
+ expect(model.coverageRows[0].workload.node).toBeUndefined();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// resourceInstance — meta / platformData / none arms (private; via candidate
+// instance).
+// ---------------------------------------------------------------------------
+
+describe('resourceInstance branches (via candidate instance)', () => {
+ it('reads the instance from proxmox meta when present', () => {
+ const model = buildModel({
+ workloads: [
+ workload({
+ id: 'vm-700',
+ proxmox: { vmid: 700, node: 'n', instance: 'meta-inst' },
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.instance).toBe('meta-inst');
+ });
+
+ it('reads the instance from platformData.proxmox when meta lacks it', () => {
+ const model = buildModel({
+ workloads: [
+ workload({
+ id: 'vm-701',
+ proxmox: { vmid: 701, node: 'n' },
+ platformData: { proxmox: { instance: 'plat-inst' } },
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.instance).toBe('plat-inst');
+ });
+
+ it('returns undefined when neither meta nor platformData carries an instance', () => {
+ const model = buildModel({
+ workloads: [workload({ id: 'vm-710', proxmox: { vmid: 710, node: 'n' } })],
+ });
+ expect(model.coverageRows[0].workload.instance).toBeUndefined();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildCandidateFromResource — null-returning guards (private; via row
+// presence).
+// ---------------------------------------------------------------------------
+
+describe('buildCandidateFromResource null guards', () => {
+ it('produces no row when the resource has no vmid', () => {
+ const model = buildModel({
+ workloads: [workload({ id: 'vm-noid', proxmox: { node: 'n' } })],
+ });
+ expect(model.coverageRows).toHaveLength(0);
+ });
+
+ it('produces no row when the resource vmid is zero', () => {
+ const model = buildModel({
+ workloads: [workload({ id: 'vm-zero', proxmox: { vmid: 0, node: 'n' } })],
+ });
+ expect(model.coverageRows).toHaveLength(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// taskLabel — success / completed / error / running / other / empty arms
+// (private; via latestTask.label). Sibling tests cover 'ok' and 'failed'.
+// ---------------------------------------------------------------------------
+
+describe('taskLabel branches (via latestTask.label)', () => {
+ const labelForStatus = (status: string): string | undefined => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'vm-600', proxmox: { vmid: 600, node: 'node-a', instance: 'inst-a' } }),
+ ],
+ pbsBackups: [pbsBackup({ id: 'pbs-600', vmid: '600', backupTime: isoDaysAgo(1) })],
+ tasks: [
+ task({
+ id: 't-600',
+ type: 'vm',
+ vmid: 600,
+ status,
+ startTime: isoDaysAgo(5),
+ }),
+ ],
+ });
+ return model.coverageRows[0]?.latestTask?.label;
+ };
+
+ it.each<[string, string]>([
+ ['success', 'OK'],
+ ['completed', 'OK'],
+ ['error', 'Failed'],
+ ['running', 'Running'],
+ ['WARNING', 'WARNING'],
+ ['', 'Unknown'],
+ ])('maps task status %j to label %j', (status, expected) => {
+ expect(labelForStatus(status)).toBe(expected);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildWorkloadLabel — no-name / name===vmid / name===fallback / differs arms
+// (private; via candidate label).
+// ---------------------------------------------------------------------------
+
+describe('buildWorkloadLabel branches (via candidate label)', () => {
+ it('falls back when the resource has no display name', () => {
+ const model = buildModel({
+ workloads: [
+ workload({
+ id: 'vm-510',
+ name: '',
+ displayName: '',
+ proxmox: { vmid: 510, node: 'n' },
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.label).toBe('VM 510');
+ expect(model.coverageRows[0].workload.name).toBeUndefined();
+ });
+
+ it('falls back when the resource name equals its vmid', () => {
+ const model = buildModel({
+ workloads: [
+ workload({
+ id: 'vm-520',
+ name: '520',
+ displayName: '520',
+ proxmox: { vmid: 520, node: 'n' },
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.label).toBe('VM 520');
+ });
+
+ it('falls back when the resource name equals the generated fallback', () => {
+ const model = buildModel({
+ workloads: [
+ workload({
+ id: 'vm-540',
+ name: 'VM 540',
+ displayName: 'VM 540',
+ proxmox: { vmid: 540, node: 'n' },
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.label).toBe('VM 540');
+ });
+
+ it('decorates a distinct name with the fallback in parentheses', () => {
+ const model = buildModel({
+ workloads: [
+ workload({
+ id: 'vm-550',
+ name: 'web-prod',
+ displayName: 'web-prod',
+ proxmox: { vmid: 550, node: 'n' },
+ }),
+ ],
+ });
+ expect(model.coverageRows[0].workload.label).toBe('web-prod (VM 550)');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildProxmoxBackupRecoveryModel — top-level summary, sort, and empty edges.
+// ---------------------------------------------------------------------------
+
+describe('buildProxmoxBackupRecoveryModel summary, sort, and empty edges', () => {
+ it('returns a fully empty model for empty inputs', () => {
+ const model = buildModel({});
+ expect(model.coverageRows).toHaveLength(0);
+ expect(model.recoverableArtifacts).toHaveLength(0);
+ expect(model.coverageSummary).toEqual({
+ totalWorkloads: 0,
+ current: 0,
+ attention: 0,
+ uncovered: 0,
+ withPBS: 0,
+ recoverableArtifacts: 0,
+ totalBytes: 0,
+ });
+ });
+
+ it('aggregates bytes, PBS-row, current, and attention counts', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'vm-840', proxmox: { vmid: 840, node: 'a' } }),
+ workload({ id: 'vm-830', proxmox: { vmid: 830, node: 'b' } }),
+ ],
+ pbsBackups: [
+ pbsBackup({ id: 'pbs-840', vmid: '840', backupTime: isoDaysAgo(1), size: 2_000 }),
+ pbsBackup({ id: 'pbs-830', vmid: '830', backupTime: isoDaysAgo(1), size: 5_000 }),
+ ],
+ });
+ expect(model.coverageSummary.totalBytes).toBe(7_000);
+ expect(model.coverageSummary.recoverableArtifacts).toBe(2);
+ expect(model.coverageSummary.withPBS).toBe(2);
+ expect(model.coverageSummary.current).toBe(2);
+ expect(model.coverageSummary.attention).toBe(0);
+ });
+
+ it('sorts rows by postureRank asc, then latestRecovery createdMs desc', () => {
+ const model = buildModel({
+ workloads: [
+ workload({ id: 'vm-840', proxmox: { vmid: 840, node: 'a' } }),
+ workload({ id: 'vm-830', proxmox: { vmid: 830, node: 'b' } }),
+ workload({ id: 'vm-850', proxmox: { vmid: 850, node: 'c' } }),
+ ],
+ pbsBackups: [
+ pbsBackup({ id: 'pbs-840', vmid: '840', backupTime: isoDaysAgo(1) }),
+ pbsBackup({ id: 'pbs-850', vmid: '850', backupTime: isoDaysAgo(2) }),
+ ],
+ });
+ // 830 has no recovery -> uncovered (rank 1) sorts first.
+ // 840 and 850 are current (rank 5); tie broken by newer recovery first.
+ expect(model.coverageRows.map((row) => row.workload.vmid)).toEqual(['830', '840', '850']);
+ expect(model.coverageSummary.uncovered).toBe(1);
+ });
+
+ it('sorts recoverable artifacts by createdMs desc', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ pbsBackups: [
+ pbsBackup({ id: 'pbs-old', vmid: '100', backupTime: isoDaysAgo(10) }),
+ pbsBackup({ id: 'pbs-new', vmid: '100', backupTime: isoDaysAgo(1) }),
+ ],
+ });
+ expect(model.recoverableArtifacts.map((artifact) => artifact.nativeId)).toEqual([
+ 'pbs-new',
+ 'pbs-old',
+ ]);
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.branchcov.test.ts b/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.branchcov.test.ts
new file mode 100644
index 0000000000..731b2021d1
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.branchcov.test.ts
@@ -0,0 +1,680 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import {
+ comparePhysicalDiskPresentation,
+ extractPhysicalDiskPresentationData,
+ getPhysicalDiskEmptyStatePresentation,
+ getPhysicalDiskHealthStatus,
+ getPhysicalDiskHostLabel,
+ getPhysicalDiskNormalizedHealth,
+ getPhysicalDiskRoleLabel,
+ hasPhysicalDiskSmartWarning,
+ matchesPhysicalDiskFilterState,
+ type PhysicalDiskPresentationData,
+} from '@/features/storageBackups/diskPresentation';
+
+function makeDiskData(
+ overrides: Partial<PhysicalDiskPresentationData> = {},
+): PhysicalDiskPresentationData {
+ return {
+ node: '',
+ instance: '',
+ devPath: '',
+ model: '',
+ serial: '',
+ wwn: '',
+ size: 0,
+ health: 'UNKNOWN',
+ riskReasons: [],
+ wearout: -1,
+ type: '',
+ temperature: 0,
+ rpm: 0,
+ used: '',
+ ...overrides,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// titleize (module-private — exercised via getPhysicalDiskRoleLabel)
+// ---------------------------------------------------------------------------
+
+describe('titleize via getPhysicalDiskRoleLabel', () => {
+ it('splits on hyphens and underscores within a storage role', () => {
+ expect(getPhysicalDiskRoleLabel(makeDiskData({ storageRole: 'hot-spare_pool' }))).toBe(
+ 'Hot Spare Pool',
+ );
+ });
+
+ it('collapses consecutive separators and filters empty parts', () => {
+ expect(getPhysicalDiskRoleLabel(makeDiskData({ storageRole: 'data__ pool' }))).toBe(
+ 'Data Pool',
+ );
+ });
+
+ it('returns empty string when both storageRole and type are absent', () => {
+ expect(getPhysicalDiskRoleLabel(makeDiskData({}))).toBe('');
+ });
+
+ it('title-cases an unrecognized disk type in the fallback path', () => {
+ expect(getPhysicalDiskRoleLabel(makeDiskData({ type: 'nvme-of' }))).toBe('Nvme Of disk');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskHealthFilterEmptyTitle (module-private — exercised via
+// getPhysicalDiskEmptyStatePresentation with diskCount > 0)
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskHealthFilterEmptyTitle via getPhysicalDiskEmptyStatePresentation', () => {
+ it.each([
+ ['healthy', 'No healthy disks found'],
+ ['warning', 'No warning disks found'],
+ ['critical', 'No critical disks found'],
+ ['offline', 'No offline disks found'],
+ ['unknown', 'No disks with unknown health'],
+ ] as const)(
+ 'returns dedicated title "%s" for healthFilter "%s" when disks exist but none match',
+ (filter, expectedTitle) => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: '',
+ diskCount: 3,
+ hasPVENodes: true,
+ healthFilter: filter,
+ });
+ expect(result.title).toBe(expectedTitle);
+ },
+ );
+
+ it('falls back to "No disks match these filters" when healthFilter is "all" and diskCount > 0', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: '',
+ diskCount: 2,
+ hasPVENodes: true,
+ });
+ expect(result.title).toBe('No disks match these filters');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// extractPhysicalDiskPresentationData
+// ---------------------------------------------------------------------------
+
+describe('extractPhysicalDiskPresentationData branch coverage', () => {
+ it('falls back to platformData.physicalDisk when resource.physicalDisk is absent', () => {
+ const resource = {
+ name: 'disk-1',
+ platformType: 'agent',
+ platformData: {
+ physicalDisk: {
+ devPath: '/dev/sda',
+ model: 'Foo Drive',
+ health: 'PASSED',
+ diskType: 'ssd',
+ },
+ },
+ } as unknown as Resource;
+
+ const data = extractPhysicalDiskPresentationData(resource);
+ expect(data.devPath).toBe('/dev/sda');
+ expect(data.model).toBe('Foo Drive');
+ expect(data.health).toBe('PASSED');
+ expect(data.type).toBe('ssd');
+ });
+
+ it('returns a shell with defaults when neither physicalDisk nor platformData.physicalDisk exist', () => {
+ const resource = { name: 'bare', platformType: 'agent' } as unknown as Resource;
+ const data = extractPhysicalDiskPresentationData(resource);
+
+ expect(data.devPath).toBe('');
+ expect(data.model).toBe('bare');
+ expect(data.serial).toBe('');
+ expect(data.wwn).toBe('');
+ expect(data.type).toBe('');
+ expect(data.size).toBe(0);
+ expect(data.health).toBe('UNKNOWN');
+ expect(data.wearout).toBe(-1);
+ expect(data.temperature).toBe(0);
+ expect(data.rpm).toBe(0);
+ expect(data.used).toBe('');
+ expect(data.riskReasons).toEqual([]);
+ expect(data.smartAttributes).toBeUndefined();
+ expect(data.riskLevel).toBeUndefined();
+ });
+
+ it('filters non-string, null, and empty-string summaries from risk.reasons', () => {
+ const resource = {
+ name: 'disk',
+ platformType: 'agent',
+ physicalDisk: {
+ risk: {
+ level: 'warning',
+ reasons: [
+ { summary: 'Valid reason' },
+ { summary: '' },
+ { summary: null },
+ { summary: 42 },
+ { notSummary: 'x' },
+ null,
+ ],
+ },
+ },
+ } as unknown as Resource;
+
+ const data = extractPhysicalDiskPresentationData(resource);
+ expect(data.riskLevel).toBe('warning');
+ expect(data.riskReasons).toEqual(['Valid reason']);
+ });
+
+ it('returns empty riskReasons when risk.reasons is not an array', () => {
+ const resource = {
+ name: 'disk',
+ platformType: 'agent',
+ physicalDisk: {
+ risk: { level: 'critical', reasons: 'not-an-array' },
+ },
+ } as unknown as Resource;
+
+ const data = extractPhysicalDiskPresentationData(resource);
+ expect(data.riskLevel).toBe('critical');
+ expect(data.riskReasons).toEqual([]);
+ });
+
+ it('returns empty riskReasons when risk is absent', () => {
+ const resource = {
+ name: 'disk',
+ platformType: 'agent',
+ physicalDisk: { health: 'PASSED' },
+ } as unknown as Resource;
+
+ const data = extractPhysicalDiskPresentationData(resource);
+ expect(data.riskReasons).toEqual([]);
+ expect(data.riskLevel).toBeUndefined();
+ });
+
+ it('extracts all SMART attributes when pd.smart is present', () => {
+ const resource = {
+ name: 'disk',
+ platformType: 'agent',
+ physicalDisk: {
+ smart: {
+ powerOnHours: 1000,
+ powerCycles: 50,
+ reallocatedSectors: 1,
+ pendingSectors: 2,
+ offlineUncorrectable: 3,
+ udmaCrcErrors: 4,
+ percentageUsed: 5,
+ availableSpare: 6,
+ mediaErrors: 7,
+ unsafeShutdowns: 8,
+ },
+ },
+ } as unknown as Resource;
+
+ const data = extractPhysicalDiskPresentationData(resource);
+ expect(data.smartAttributes).toEqual({
+ powerOnHours: 1000,
+ powerCycles: 50,
+ reallocatedSectors: 1,
+ pendingSectors: 2,
+ offlineUncorrectable: 3,
+ udmaCrcErrors: 4,
+ percentageUsed: 5,
+ availableSpare: 6,
+ mediaErrors: 7,
+ unsafeShutdowns: 8,
+ });
+ });
+
+ it('passes through optional storage fields and counters from physicalDisk', () => {
+ const resource = {
+ name: 'disk',
+ platformType: 'agent',
+ physicalDisk: {
+ storageRole: 'data',
+ storageGroup: 'array-1',
+ storageState: 'online',
+ spunDown: false,
+ readCount: 100,
+ writeCount: 200,
+ errorCount: 5,
+ sizeBytes: 1000000,
+ wearout: 80,
+ temperature: 35,
+ rpm: 7200,
+ used: 'ZFS',
+ },
+ } as unknown as Resource;
+
+ const data = extractPhysicalDiskPresentationData(resource);
+ expect(data.storageRole).toBe('data');
+ expect(data.storageGroup).toBe('array-1');
+ expect(data.storageState).toBe('online');
+ expect(data.spunDown).toBe(false);
+ expect(data.readCount).toBe(100);
+ expect(data.writeCount).toBe(200);
+ expect(data.errorCount).toBe(5);
+ expect(data.size).toBe(1000000);
+ expect(data.wearout).toBe(80);
+ expect(data.temperature).toBe(35);
+ expect(data.rpm).toBe(7200);
+ expect(data.used).toBe('ZFS');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// matchesPhysicalDiskFilterState
+// ---------------------------------------------------------------------------
+
+describe('matchesPhysicalDiskFilterState branch coverage', () => {
+ const baseResource = {
+ id: 'disk-1',
+ name: 'disk-1',
+ status: 'online',
+ platformType: 'proxmox-pve',
+ identity: { hostname: 'node1' },
+ } as unknown as Resource;
+ const baseDisk = makeDiskData({
+ node: 'node1',
+ health: 'PASSED',
+ type: 'ssd',
+ storageRole: 'cache',
+ storageGroup: 'tank',
+ });
+
+ it('returns false when sourceFilter does not match the disk source', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { sourceFilter: 'truenas' }),
+ ).toBe(false);
+ });
+
+ it('returns true when sourceFilter matches', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { sourceFilter: 'proxmox-pve' }),
+ ).toBe(true);
+ });
+
+ it('returns false when healthFilter does not match the disk health', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { healthFilter: 'critical' }),
+ ).toBe(false);
+ });
+
+ it('returns true when healthFilter "attention" matches a warning disk', () => {
+ const warningDisk = makeDiskData({ node: 'node1', health: 'PASSED', riskLevel: 'warning' });
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, warningDisk, { healthFilter: 'attention' }),
+ ).toBe(true);
+ });
+
+ it('returns false when roleFilter does not match', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { roleFilter: 'parity' }),
+ ).toBe(false);
+ });
+
+ it('returns true when roleFilter matches', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { roleFilter: 'cache' }),
+ ).toBe(true);
+ });
+
+ it('returns false when groupFilter does not match', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { groupFilter: 'mirror' }),
+ ).toBe(false);
+ });
+
+ it('returns true when groupFilter matches', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { groupFilter: 'tank' }),
+ ).toBe(true);
+ });
+
+ it('returns false when search term does not match any haystack field', () => {
+ expect(
+ matchesPhysicalDiskFilterState(baseResource, baseDisk, { searchTerm: 'nonexistent-term' }),
+ ).toBe(false);
+ });
+
+ it('returns true when all filters are default/empty', () => {
+ expect(matchesPhysicalDiskFilterState(baseResource, baseDisk, {})).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskNormalizedHealth
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskNormalizedHealth branch coverage', () => {
+ it('returns "offline" when resource.status is "offline" (checked before Healthy)', () => {
+ const resource = { status: 'offline' } as Resource;
+ const disk = makeDiskData({ health: 'PASSED' });
+ expect(getPhysicalDiskNormalizedHealth(resource, disk)).toBe('offline');
+ });
+
+ it('returns "critical" for Replace Now status', () => {
+ const resource = { status: 'online' } as Resource;
+ const disk = makeDiskData({ health: 'FAILED' });
+ expect(getPhysicalDiskNormalizedHealth(resource, disk)).toBe('critical');
+ });
+
+ it('returns "healthy" for Healthy status (PASSED health)', () => {
+ const resource = { status: 'online' } as Resource;
+ const disk = makeDiskData({ health: 'PASSED' });
+ expect(getPhysicalDiskNormalizedHealth(resource, disk)).toBe('healthy');
+ });
+
+ it('returns "healthy" for Healthy status (GOOD health)', () => {
+ const resource = { status: 'online' } as Resource;
+ const disk = makeDiskData({ health: 'GOOD' });
+ expect(getPhysicalDiskNormalizedHealth(resource, disk)).toBe('healthy');
+ });
+
+ it('returns "unknown" for an unrecognized health label', () => {
+ const resource = { status: 'online' } as Resource;
+ const disk = makeDiskData({ health: 'SOMETHING' });
+ expect(getPhysicalDiskNormalizedHealth(resource, disk)).toBe('unknown');
+ });
+
+ it('returns "healthy" for Online status before checking resource.status', () => {
+ const resource = { status: 'offline' } as Resource;
+ const disk = makeDiskData({
+ health: 'UNKNOWN',
+ storageRole: 'data',
+ storageGroup: 'unraid-array',
+ storageState: 'online',
+ });
+ expect(getPhysicalDiskNormalizedHealth(resource, disk)).toBe('healthy');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskHostLabel
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskHostLabel branch coverage', () => {
+ it('returns disk.node when set', () => {
+ expect(getPhysicalDiskHostLabel(makeDiskData({ node: 'tower' }), {} as Resource)).toBe('tower');
+ });
+
+ it('falls back to resource.parentName when disk.node is empty', () => {
+ expect(
+ getPhysicalDiskHostLabel(makeDiskData({ node: '' }), { parentName: 'pve-01' } as Resource),
+ ).toBe('pve-01');
+ });
+
+ it('returns empty string when both disk.node and parentName are empty', () => {
+ expect(
+ getPhysicalDiskHostLabel(makeDiskData({ node: '' }), { parentName: '' } as Resource),
+ ).toBe('');
+ });
+
+ it('trims whitespace from the resolved host label', () => {
+ expect(
+ getPhysicalDiskHostLabel(makeDiskData({ node: ' tower ' }), {} as Resource),
+ ).toBe('tower');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// comparePhysicalDiskPresentation
+// ---------------------------------------------------------------------------
+
+describe('comparePhysicalDiskPresentation branch coverage', () => {
+ const r = { name: 'd' } as Resource;
+
+ it('sorts critical risk (300) ahead of no risk (0)', () => {
+ const noneDisk = makeDiskData({ node: 'n', devPath: '/dev/sda' });
+ const criticalDisk = makeDiskData({ node: 'n', devPath: '/dev/sda', riskLevel: 'critical' });
+ expect(comparePhysicalDiskPresentation(r, criticalDisk, r, noneDisk)).toBeLessThan(0);
+ });
+
+ it('adds +50 priority for SMART warnings on top of warning risk', () => {
+ const warningWithSmart = makeDiskData({
+ node: 'n',
+ devPath: '/dev/sda',
+ riskLevel: 'warning',
+ smartAttributes: { reallocatedSectors: 1 },
+ });
+ const warningNoSmart = makeDiskData({ node: 'n', devPath: '/dev/sdb', riskLevel: 'warning' });
+ expect(comparePhysicalDiskPresentation(r, warningWithSmart, r, warningNoSmart)).toBeLessThan(0);
+ });
+
+ it('falls back to node localeCompare when priorities are equal', () => {
+ const diskA = makeDiskData({ node: 'alpha', devPath: '/dev/sda' });
+ const diskB = makeDiskData({ node: 'beta', devPath: '/dev/sda' });
+ expect(comparePhysicalDiskPresentation(r, diskA, r, diskB)).toBeLessThan(0);
+ });
+
+ it('falls back to devPath localeCompare when priority and node are equal', () => {
+ const diskA = makeDiskData({ node: 'n', devPath: '/dev/sda' });
+ const diskB = makeDiskData({ node: 'n', devPath: '/dev/sdb' });
+ expect(comparePhysicalDiskPresentation(r, diskA, r, diskB)).toBeLessThan(0);
+ });
+
+ it('falls back to resource.name when both devPaths are empty', () => {
+ const rA = { name: 'aaa' } as Resource;
+ const rB = { name: 'bbb' } as Resource;
+ const diskA = makeDiskData({ node: 'n', devPath: '' });
+ const diskB = makeDiskData({ node: 'n', devPath: '' });
+ expect(comparePhysicalDiskPresentation(rA, diskA, rB, diskB)).toBeLessThan(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// hasPhysicalDiskSmartWarning
+// ---------------------------------------------------------------------------
+
+describe('hasPhysicalDiskSmartWarning branch coverage', () => {
+ it('returns false when smartAttributes is undefined', () => {
+ expect(hasPhysicalDiskSmartWarning(makeDiskData({}))).toBe(false);
+ });
+
+ it('returns true when reallocatedSectors > 0', () => {
+ expect(
+ hasPhysicalDiskSmartWarning(makeDiskData({ smartAttributes: { reallocatedSectors: 5 } })),
+ ).toBe(true);
+ });
+
+ it('returns true when mediaErrors > 0', () => {
+ expect(
+ hasPhysicalDiskSmartWarning(makeDiskData({ smartAttributes: { mediaErrors: 3 } })),
+ ).toBe(true);
+ });
+
+ it('returns false when all warning counters are zero', () => {
+ expect(
+ hasPhysicalDiskSmartWarning(
+ makeDiskData({
+ smartAttributes: { reallocatedSectors: 0, pendingSectors: 0, mediaErrors: 0 },
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false when warning counters are undefined but other attrs exist', () => {
+ expect(
+ hasPhysicalDiskSmartWarning(makeDiskData({ smartAttributes: { powerOnHours: 1000 } })),
+ ).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskHealthStatus
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskHealthStatus branch coverage', () => {
+ it('returns Replace Now for critical riskLevel even when health is not FAILED', () => {
+ const disk = makeDiskData({ health: 'PASSED', riskLevel: 'critical', riskReasons: ['Bad'] });
+ expect(getPhysicalDiskHealthStatus(disk)).toEqual({
+ label: 'Replace Now',
+ summary: 'Bad',
+ tone: 'text-red-700 dark:text-red-300',
+ });
+ });
+
+ it('uses default summary for Replace Now when riskReasons is empty', () => {
+ const disk = makeDiskData({ health: 'FAILED', riskReasons: [] });
+ const status = getPhysicalDiskHealthStatus(disk);
+ expect(status.label).toBe('Replace Now');
+ expect(status.summary).toBe('Disk health has degraded to a critical state.');
+ });
+
+ it('returns Needs Attention for SMART warning without risk level (default summary)', () => {
+ const disk = makeDiskData({
+ health: 'PASSED',
+ smartAttributes: { reallocatedSectors: 1 },
+ });
+ const status = getPhysicalDiskHealthStatus(disk);
+ expect(status.label).toBe('Needs Attention');
+ expect(status.summary).toBe('SMART counters indicate elevated risk.');
+ expect(status.tone).toBe('text-amber-700 dark:text-amber-300');
+ });
+
+ it('returns Needs Attention with low-life SSD summary when wearout is between 0 and 10', () => {
+ const disk = makeDiskData({ health: 'PASSED', wearout: 5 });
+ const status = getPhysicalDiskHealthStatus(disk);
+ expect(status.label).toBe('Needs Attention');
+ expect(status.summary).toBe('SSD life is running low.');
+ });
+
+ it('uses riskReasons[0] for Needs Attention summary when available', () => {
+ const disk = makeDiskData({
+ health: 'PASSED',
+ riskLevel: 'warning',
+ riskReasons: ['Wear leveling exceeded.'],
+ });
+ expect(getPhysicalDiskHealthStatus(disk).summary).toBe('Wear leveling exceeded.');
+ });
+
+ it('returns Healthy for GOOD health', () => {
+ const disk = makeDiskData({ health: 'GOOD' });
+ expect(getPhysicalDiskHealthStatus(disk)).toEqual({
+ label: 'Healthy',
+ summary: 'No active disk-health issues.',
+ tone: 'text-base-content',
+ });
+ });
+
+ it('returns Healthy for PASSED health', () => {
+ const disk = makeDiskData({ health: 'PASSED' });
+ expect(getPhysicalDiskHealthStatus(disk).label).toBe('Healthy');
+ });
+
+ it('returns Unknown with "Health state is not reported." for unrecognized health', () => {
+ const disk = makeDiskData({ health: 'WEIRD' });
+ expect(getPhysicalDiskHealthStatus(disk)).toEqual({
+ label: 'Unknown',
+ summary: 'Health state is not reported.',
+ tone: 'text-base-content',
+ });
+ });
+
+ it('returns Unknown label for Unraid disk whose storageState is not "online"', () => {
+ const disk = makeDiskData({
+ health: 'UNKNOWN',
+ storageRole: 'data',
+ storageGroup: 'unraid-array',
+ storageState: 'spinning',
+ });
+ const status = getPhysicalDiskHealthStatus(disk);
+ expect(status.label).toBe('Unknown');
+ expect(status.summary).toBe('No active disk-health issues.');
+ });
+
+ it('does not classify wearout of 0 as low life (unreported boundary)', () => {
+ const disk = makeDiskData({ health: 'PASSED', wearout: 0 });
+ expect(getPhysicalDiskHealthStatus(disk).label).toBe('Healthy');
+ });
+
+ it('does not classify wearout of exactly 10 as low life (upper boundary)', () => {
+ const disk = makeDiskData({ health: 'PASSED', wearout: 10 });
+ expect(getPhysicalDiskHealthStatus(disk).label).toBe('Healthy');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskEmptyStatePresentation
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskEmptyStatePresentation branch coverage', () => {
+ it('includes searchMessage when searchTerm is provided', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: 'ssd',
+ diskCount: 5,
+ hasPVENodes: true,
+ });
+ expect(result.searchMessage).toBe('matching "ssd"');
+ });
+
+ it('returns null searchMessage when searchTerm is empty', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: '',
+ diskCount: 0,
+ hasPVENodes: false,
+ });
+ expect(result.searchMessage).toBeNull();
+ });
+
+ it('hides requirements when a scoped filter is active even if diskCount is 0', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: 'foo',
+ diskCount: 0,
+ hasPVENodes: true,
+ });
+ expect(result.showRequirements).toBe(false);
+ });
+
+ it('hides requirements when hasPVENodes is false', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: '',
+ diskCount: 0,
+ hasPVENodes: false,
+ });
+ expect(result.showRequirements).toBe(false);
+ });
+
+ it('builds filterMessages only for provided labels', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: '',
+ diskCount: 3,
+ hasPVENodes: true,
+ sourceFilterLabel: 'PVE',
+ });
+ expect(result.filterMessages).toEqual(['from PVE']);
+ });
+
+ it('returns null nodeMessage when selectedNodeName is null', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: '',
+ diskCount: 0,
+ hasPVENodes: false,
+ });
+ expect(result.nodeMessage).toBeNull();
+ });
+
+ it('includes all requirement fields when showRequirements is true', () => {
+ const result = getPhysicalDiskEmptyStatePresentation({
+ selectedNodeName: null,
+ searchTerm: '',
+ diskCount: 0,
+ hasPVENodes: true,
+ });
+ expect(result.showRequirements).toBe(true);
+ expect(result.requirementsTitle).toBe('Physical disk monitoring requirements:');
+ expect(result.requirementsNote).toBe(
+ 'Note: Both Pulse and Proxmox must have SMART monitoring enabled.',
+ );
+ expect(result.requirementsItems).toHaveLength(3);
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/storageAdapterCore.branchcov.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storageAdapterCore.branchcov.test.ts
new file mode 100644
index 0000000000..a35779afa3
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/storageAdapterCore.branchcov.test.ts
@@ -0,0 +1,277 @@
+import { describe, expect, it } from 'vitest';
+import type { StorageRecord } from '@/features/storageBackups/models';
+import {
+ canonicalStorageIdentityKey,
+ normalizeStorageResourceHealth,
+ resolveStoragePlatformFamily,
+} from '@/features/storageBackups/storageAdapterCore';
+
+const makeRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord => ({
+ id: 'storage-1',
+ name: 'tank',
+ category: 'pool',
+ health: 'healthy',
+ location: { label: 'pve1', scope: 'node' },
+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 60, usagePercent: 40 },
+ capabilities: ['capacity'],
+ source: {
+ platform: 'proxmox-pve',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'resource-storage',
+ },
+ observedAt: Date.now(),
+ ...overrides,
+});
+
+// ---------------------------------------------------------------------------
+// normalizeHealthValue (module-private — exercised via normalizeStorageResourceHealth)
+// ---------------------------------------------------------------------------
+
+describe('normalizeHealthValue via normalizeStorageResourceHealth', () => {
+ it('returns unknown when every signal is undefined or blank', () => {
+ expect(normalizeStorageResourceHealth(undefined, undefined, undefined)).toBe('unknown');
+ expect(normalizeStorageResourceHealth('', [], '')).toBe('unknown');
+ expect(normalizeStorageResourceHealth(' ', undefined, ' ')).toBe('unknown');
+ });
+
+ it.each([
+ 'online',
+ 'running',
+ 'available',
+ 'healthy',
+ 'ok',
+ 'optimal',
+ ])('maps exact healthy keyword %s to "healthy"', (status) => {
+ expect(normalizeStorageResourceHealth(status, undefined)).toBe('healthy');
+ });
+
+ it.each([
+ 'warning',
+ 'warn',
+ 'degraded',
+ 'health_warn',
+ ])('maps exact warning keyword %s to "warning"', (status) => {
+ expect(normalizeStorageResourceHealth(status, undefined)).toBe('warning');
+ });
+
+ it.each([
+ 'critical',
+ 'faulted',
+ 'failed',
+ 'error',
+ 'unhealthy',
+ 'health_crit',
+ 'health_err',
+ ])('maps exact critical keyword %s to "critical"', (status) => {
+ expect(normalizeStorageResourceHealth(status, undefined)).toBe('critical');
+ });
+
+ it.each(['offline', 'stopped', 'down', 'unavailable'])(
+ 'maps exact offline keyword %s to "offline"',
+ (status) => {
+ expect(normalizeStorageResourceHealth(status, undefined)).toBe('offline');
+ },
+ );
+
+ it('maps the exact literal "unknown" to "unknown"', () => {
+ expect(normalizeStorageResourceHealth('unknown', undefined)).toBe('unknown');
+ });
+
+ it('falls through to unknown when the status matches no keyword or substring arm', () => {
+ expect(normalizeStorageResourceHealth('quantum-state', undefined)).toBe('unknown');
+ });
+
+ it('maps substring (non-exact) critical signals to "critical"', () => {
+ expect(normalizeStorageResourceHealth('system fault detected', undefined)).toBe('critical');
+ expect(normalizeStorageResourceHealth('prefail warning', undefined)).toBe('critical');
+ });
+
+ it('maps substring (non-exact) warning signals to "warning"', () => {
+ // 'prewarn-state' includes 'warn' but matches no exact keyword nor any critical substring
+ expect(normalizeStorageResourceHealth('prewarn-state', undefined)).toBe('warning');
+ expect(normalizeStorageResourceHealth('mildly degraded-ish', undefined)).toBe('warning');
+ });
+
+ it('maps substring (non-exact) offline signals to "offline"', () => {
+ // 'system shutdown' includes 'down' (via shut**down**) but is not the exact keyword 'down'
+ expect(normalizeStorageResourceHealth('system shutdown', undefined)).toBe('offline');
+ });
+
+ it('maps substring (non-exact) healthy signals to "healthy"', () => {
+ // 'back online soon' includes 'online' but is not the exact keyword 'online'
+ expect(normalizeStorageResourceHealth('back online soon', undefined)).toBe('healthy');
+ });
+
+ it('normalizes case and surrounding whitespace before classification', () => {
+ expect(normalizeStorageResourceHealth('ONLINE', undefined)).toBe('healthy');
+ expect(normalizeStorageResourceHealth(' CriTiCal ', undefined)).toBe('critical');
+ expect(normalizeStorageResourceHealth('\tWarn\n', undefined)).toBe('warning');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// extractHealthTag (module-private — exercised via normalizeStorageResourceHealth)
+// ---------------------------------------------------------------------------
+
+describe('extractHealthTag via normalizeStorageResourceHealth', () => {
+ it('ignores a missing, empty, or non-health tag array and falls back to status', () => {
+ expect(normalizeStorageResourceHealth('online', undefined)).toBe('healthy');
+ expect(normalizeStorageResourceHealth('online', [])).toBe('healthy');
+ expect(normalizeStorageResourceHealth('critical', ['region:eu', 'tier:gold'])).toBe('critical');
+ });
+
+ it('reads the trimmed value of a "health:" tag and overrides the status', () => {
+ expect(normalizeStorageResourceHealth('online', ['health:warning'])).toBe('warning');
+ expect(normalizeStorageResourceHealth('online', ['health: Critical '])).toBe('critical');
+ });
+
+ it('uses the LAST health: tag when several are present', () => {
+ expect(
+ normalizeStorageResourceHealth('online', ['health:ok', 'health:critical']),
+ ).toBe('critical');
+ expect(
+ normalizeStorageResourceHealth('offline', ['health:critical', 'health:healthy']),
+ ).toBe('healthy');
+ });
+
+ it('matches the health: prefix case-insensitively after trimming each tag', () => {
+ expect(normalizeStorageResourceHealth('online', [' HEALTH:down '])).toBe('offline');
+ });
+});
+
+describe('normalizeStorageResourceHealth priority chain', () => {
+ it('prefers incidentSeverity over health tag over status', () => {
+ // incidentSeverity beats a health tag and the status
+ expect(
+ normalizeStorageResourceHealth('online', ['health:warning'], 'critical'),
+ ).toBe('critical');
+ // health tag beats status
+ expect(normalizeStorageResourceHealth('online', ['health:critical'])).toBe('critical');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// resolveStoragePlatformFamily
+// ---------------------------------------------------------------------------
+
+describe('resolveStoragePlatformFamily', () => {
+ it('defers to the platform support manifest for known platforms', () => {
+ // These resolve to a non-null storage family in the manifest.
+ expect(resolveStoragePlatformFamily('kubernetes')).toBe('container');
+ expect(resolveStoragePlatformFamily('docker')).toBe('container');
+ expect(resolveStoragePlatformFamily('proxmox-pve')).toBe('virtualization');
+ expect(resolveStoragePlatformFamily('aws')).toBe('cloud');
+ expect(resolveStoragePlatformFamily('truenas')).toBe('onprem');
+ });
+
+ it('lowercases the platform before resolving so casing does not matter', () => {
+ expect(resolveStoragePlatformFamily('KUBERNETES')).toBe('container');
+ expect(resolveStoragePlatformFamily('Proxmox-PVE')).toBe('virtualization');
+ });
+
+ it('falls back to "container" for unrecognized platforms containing kubernetes/docker', () => {
+ expect(resolveStoragePlatformFamily('my-kubernetes-cluster')).toBe('container');
+ expect(resolveStoragePlatformFamily('docker-swarm-x')).toBe('container');
+ });
+
+ it('falls back to "cloud" for unrecognized platforms containing "cloud"', () => {
+ expect(resolveStoragePlatformFamily('private-cloud-net')).toBe('cloud');
+ });
+
+ it('falls back to "virtualization" for unrecognized platforms containing proxmox/vmware/hyperv', () => {
+ expect(resolveStoragePlatformFamily('vmware-test-xyz')).toBe('virtualization');
+ expect(resolveStoragePlatformFamily('custom-hyperv-node')).toBe('virtualization');
+ expect(resolveStoragePlatformFamily('proxmox-unlisted-build')).toBe('virtualization');
+ });
+
+ it('falls back to "generic" when the value contains "generic" but is not a manifest id', () => {
+ // 'generic' itself has a manifest entry whose storage family is null, so it also reaches
+ // the substring arm; an unlisted variant exercises the same arm unambiguously.
+ expect(resolveStoragePlatformFamily('generic')).toBe('generic');
+ expect(resolveStoragePlatformFamily('generic-backup-target')).toBe('generic');
+ });
+
+ it('falls back to "onprem" for a value matching no manifest entry and no substring', () => {
+ expect(resolveStoragePlatformFamily('local-zfs-node')).toBe('onprem');
+ expect(resolveStoragePlatformFamily('')).toBe('onprem');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// canonicalStorageIdentityKey (also exercises module-private normalizeIdentityPart)
+// ---------------------------------------------------------------------------
+
+describe('canonicalStorageIdentityKey', () => {
+ it('joins trimmed/lowercased platform, location, name, and category', () => {
+ expect(canonicalStorageIdentityKey(makeRecord())).toBe('proxmox-pve|pve1|tank|pool');
+ });
+
+ it('trims and lowercases every identity part', () => {
+ expect(
+ canonicalStorageIdentityKey(
+ makeRecord({
+ source: { platform: ' TrueNAS ', family: 'onprem', origin: 'resource', adapterId: 'a' },
+ location: { label: ' TOWER ', scope: 'host' },
+ name: ' Tank ',
+ category: ' Dataset ' as unknown as StorageRecord['category'],
+ }),
+ ),
+ ).toBe('truenas|tower|tank|dataset');
+ });
+
+ it('defaults a missing platform to "generic"', () => {
+ expect(
+ canonicalStorageIdentityKey(
+ makeRecord({
+ source: { platform: '', family: 'onprem', origin: 'resource', adapterId: 'a' },
+ }),
+ ),
+ ).toBe('generic|pve1|tank|pool');
+ });
+
+ it('falls back to refs.platformEntityId when location.label is blank', () => {
+ expect(
+ canonicalStorageIdentityKey(
+ makeRecord({
+ location: { label: '', scope: 'node' },
+ refs: { platformEntityId: 'ent-9' },
+ }),
+ ),
+ ).toBe('proxmox-pve|ent-9|tank|pool');
+ });
+
+ it('uses "unknown-location" when both location.label and refs.platformEntityId are blank', () => {
+ expect(
+ canonicalStorageIdentityKey(
+ makeRecord({ location: { label: '', scope: 'node' }, refs: {} }),
+ ),
+ ).toBe('proxmox-pve|unknown-location|tank|pool');
+ // refs absent entirely as well
+ expect(
+ canonicalStorageIdentityKey(
+ makeRecord({ location: { label: ' ', scope: 'node' }, refs: undefined }),
+ ),
+ ).toBe('proxmox-pve|unknown-location|tank|pool');
+ });
+
+ it('falls back to the record id when name is blank', () => {
+ expect(canonicalStorageIdentityKey(makeRecord({ name: '' }))).toBe(
+ 'proxmox-pve|pve1|storage-1|pool',
+ );
+ });
+
+ it('uses "unknown-name" when both name and id are blank', () => {
+ expect(
+ canonicalStorageIdentityKey(makeRecord({ name: '', id: '' })),
+ ).toBe('proxmox-pve|pve1|unknown-name|pool');
+ });
+
+ it('defaults a missing category to "other"', () => {
+ expect(
+ canonicalStorageIdentityKey(
+ makeRecord({ category: '' as unknown as StorageRecord['category'] }),
+ ),
+ ).toBe('proxmox-pve|pve1|tank|other');
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/storageAdapters.branchcov.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storageAdapters.branchcov.test.ts
new file mode 100644
index 0000000000..093fd53b6b
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/storageAdapters.branchcov.test.ts
@@ -0,0 +1,751 @@
+import { describe, expect, it } from 'vitest';
+import type { State } from '@/types/api';
+import type { Resource } from '@/types/resource';
+import type {
+ StorageAdapter,
+ StorageAdapterContext,
+ StorageRecord,
+} from '@/features/storageBackups/models';
+import {
+ buildStorageRecords,
+ DEFAULT_STORAGE_ADAPTERS,
+} from '@/features/storageBackups/storageAdapters';
+
+// Minimal but complete State factory (mirrors the sibling storageAdapters.test.ts
+// baseState shape so the StorageAdapterContext.state contract always type-checks).
+const baseState = (overrides: Partial<State> = {}): State => ({
+ connectedInfrastructure: [],
+ metrics: [],
+ performance: {
+ apiCallDuration: {},
+ lastPollDuration: 0,
+ pollingStartTime: '',
+ totalApiCalls: 0,
+ failedApiCalls: 0,
+ cacheHits: 0,
+ cacheMisses: 0,
+ },
+ connectionHealth: {},
+ stats: { startTime: '', uptime: 0, pollingCycles: 0, webSocketClients: 0, version: 'dev' },
+ activeAlerts: [],
+ recentlyResolved: [],
+ lastUpdate: 0,
+ resources: [],
+ ...overrides,
+ pveTagColors: overrides.pveTagColors ?? {},
+ pveTagStyles: overrides.pveTagStyles ?? {},
+});
+
+// Full-required-fields Resource factory. `as Resource` is safe because every
+// required field (id, type, name, displayName, platformId, platformType,
+// sourceType, status, lastSeen) has a default; overrides may only widen values.
+const makeResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'storage-1',
+ type: 'storage',
+ name: 'local',
+ displayName: 'local',
+ platformId: 'cluster-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1731000000000,
+ platformData: {
+ type: 'dir',
+ node: 'pve1',
+ instance: 'cluster-a',
+ shared: false,
+ },
+ ...overrides,
+ }) as Resource;
+
+const ctx = (resources: Resource[]): StorageAdapterContext => ({
+ state: baseState(),
+ resources,
+});
+
+// A StorageRecord factory whose canonical identity (platform|location|name|category)
+// is held constant so two records collide inside buildStorageRecords and trigger
+// the private mergeStorageRecords(current, incoming).
+const makeRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord => ({
+ id: 'record-a',
+ name: 'tank',
+ category: 'pool',
+ health: 'healthy',
+ location: { label: 'pve1', scope: 'node' },
+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 60, usagePercent: 40 },
+ capabilities: ['capacity'],
+ source: {
+ platform: 'proxmox-pve',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'test-adapter',
+ },
+ observedAt: 1000,
+ ...overrides,
+});
+
+// Custom adapter that emits pre-built records so we can drive mergeStorageRecords
+// with precisely-controlled current/incoming payloads (the function is private,
+// reachable only when buildStorageRecords detects a duplicate canonical key).
+const recordAdapter = (records: StorageRecord[], id = 'test-adapter'): StorageAdapter => ({
+ id,
+ supports: () => true,
+ build: () => records,
+});
+
+// buildStorageRecords processes records in array order: the first colliding
+// record becomes `existing` (== `current` to merge), the next is `incoming`.
+// Both records share name/location/platform/category so they collide.
+const mergeTwo = (current: StorageRecord, incoming: StorageRecord): StorageRecord => {
+ const records = buildStorageRecords(ctx([]), [recordAdapter([current, incoming])]);
+ expect(records).toHaveLength(1);
+ return records[0];
+};
+
+const resourceAdapter = DEFAULT_STORAGE_ADAPTERS[0];
+
+describe('storageAdapters.branchcov - build (adapter) + supports + buildStorageRecords', () => {
+ it('supports() is true for a non-empty resources array and false for empty/non-array', () => {
+ expect(resourceAdapter.supports(ctx([makeResource()]))).toBe(true);
+ expect(resourceAdapter.supports(ctx([]))).toBe(false);
+ expect(
+ resourceAdapter.supports({
+ state: baseState(),
+ resources: undefined,
+ } as unknown as StorageAdapterContext),
+ ).toBe(false);
+ });
+
+ it('build() falls back to an empty array when ctx.resources is undefined (the `|| []` arm)', () => {
+ const result = resourceAdapter.build({
+ state: baseState(),
+ resources: undefined,
+ } as unknown as StorageAdapterContext);
+ expect(result).toEqual([]);
+ });
+
+ it('build() keeps storage and datastore resources but filters every other type', () => {
+ const resources: Resource[] = [
+ makeResource({ id: 's1', type: 'storage', name: 's1' }),
+ makeResource({ id: 'd1', type: 'datastore', name: 'd1' }),
+ makeResource({ id: 'v1', type: 'vm', name: 'v1' }),
+ makeResource({ id: 'a1', type: 'agent', name: 'a1' }),
+ ];
+ const result = resourceAdapter.build(ctx(resources));
+ expect(result.map((record) => record.id)).toEqual(['s1', 'd1']);
+ });
+
+ it('buildStorageRecords returns an empty array when the adapter list is empty', () => {
+ expect(buildStorageRecords(ctx([makeResource()]), [])).toEqual([]);
+ });
+
+ it('buildStorageRecords skips an adapter whose supports() is false', () => {
+ const neverSupports: StorageAdapter = {
+ id: 'never',
+ supports: () => false,
+ build: () => [makeRecord({ id: 'should-not-appear' })],
+ };
+ expect(buildStorageRecords(ctx([]), [neverSupports])).toEqual([]);
+ });
+
+ it('buildStorageRecords uses DEFAULT_STORAGE_ADAPTERS when no adapter list is supplied', () => {
+ const records = buildStorageRecords(ctx([makeResource({ id: 'only', name: 'only' })]));
+ expect(records).toHaveLength(1);
+ expect(records[0].id).toBe('only');
+ expect(records[0].source.adapterId).toBe('resource-storage');
+ });
+
+ it('buildStorageRecords threads records from multiple adapters, merging on collision', () => {
+ const a: StorageAdapter = recordAdapter(
+ [makeRecord({ id: 'from-a', incidentPriority: 1, incidentCategory: 'a' })],
+ 'adapter-a',
+ );
+ const b: StorageAdapter = recordAdapter(
+ [makeRecord({ id: 'from-b', incidentPriority: 9, incidentCategory: 'b' })],
+ 'adapter-b',
+ );
+ // Same canonical key -> merged; preferred is the higher-priority record (from-b).
+ const records = buildStorageRecords(ctx([]), [a, b]);
+ expect(records).toHaveLength(1);
+ expect(records[0].incidentPriority).toBe(9);
+ expect(records[0].incidentCategory).toBe('b');
+ });
+
+ it('buildStorageRecords keeps records apart when canonical keys differ', () => {
+ const rec1 = makeRecord({ id: 'r1', name: 'alpha' });
+ const rec2 = makeRecord({ id: 'r2', name: 'beta' });
+ const records = buildStorageRecords(ctx([]), [recordAdapter([rec1, rec2])]);
+ expect(records).toHaveLength(2);
+ expect(new Set(records.map((record) => record.name))).toEqual(new Set(['alpha', 'beta']));
+ });
+});
+
+describe('storageAdapters.branchcov - mapResourceStorageRecord (via resource adapter)', () => {
+ it('tolerates missing platformData and falls back to the resourceType-derived storage type', () => {
+ // No platformData, no storage -> `platformData || {}` arm; storageType falls
+ // through to the resourceType ('storage') because no pbs hint is present.
+ const resource = makeResource({
+ id: 'bare',
+ type: 'storage',
+ platformData: undefined,
+ });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records).toHaveLength(1);
+ expect(records[0].details?.type).toBe('storage');
+ expect(records[0].details?.platform).toBe('proxmox-pve');
+ });
+
+ it('derives storageType from platformData.type when no enriched storage meta exists', () => {
+ const resource = makeResource({
+ id: 'lvm',
+ platformData: { type: 'lvm', node: 'pve1', instance: 'cluster-a' },
+ });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].details?.type).toBe('lvm');
+ });
+
+ it('uses resource.platformType when neither storage meta nor platformData declares a platform', () => {
+ const resource = makeResource({
+ id: 'plat-only',
+ platformData: { node: 'pve2', instance: 'cluster-a' },
+ });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].details?.platform).toBe('proxmox-pve');
+ });
+
+ it('reports shared as undefined when neither storage meta nor platformData is boolean', () => {
+ const resource = makeResource({
+ id: 'shared-undef',
+ platformData: { type: 'dir', node: 'pve1', instance: 'cluster-a' },
+ });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].details?.shared).toBeUndefined();
+ });
+
+ it('reads shared from platformData.shared when storage meta is absent', () => {
+ const resource = makeResource({
+ id: 'shared-pd',
+ platformData: { type: 'dir', node: 'pve1', instance: 'cluster-a', shared: true },
+ });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].details?.shared).toBe(true);
+ });
+
+ it('reads shared from enriched storage meta, overriding platformData', () => {
+ const resource = {
+ ...makeResource({
+ id: 'shared-meta',
+ platformData: { type: 'dir', node: 'pve1', instance: 'cluster-a', shared: true },
+ }),
+ storage: { type: 'dir', shared: false },
+ } as Resource;
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].details?.shared).toBe(false);
+ });
+
+ it('uses Date.now() for observedAt when lastSeen is NaN (number but not finite)', () => {
+ const resource = makeResource({ id: 'nan-seen', lastSeen: Number.NaN });
+ const before = Date.now();
+ const records = resourceAdapter.build(ctx([resource]));
+ const after = Date.now();
+ expect(records[0].observedAt).toBeGreaterThanOrEqual(before);
+ expect(records[0].observedAt).toBeLessThanOrEqual(after);
+ });
+
+ it('uses Date.now() for observedAt when lastSeen is not a number at all', () => {
+ const resource = makeResource({
+ id: 'str-seen',
+ lastSeen: 'not-a-timestamp' as unknown as number,
+ });
+ const before = Date.now();
+ const records = resourceAdapter.build(ctx([resource]));
+ const after = Date.now();
+ expect(records[0].observedAt).toBeGreaterThanOrEqual(before);
+ expect(records[0].observedAt).toBeLessThanOrEqual(after);
+ });
+
+ it('uses the numeric lastSeen verbatim when it is a finite number', () => {
+ const resource = makeResource({ id: 'finite-seen', lastSeen: 9999999 });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].observedAt).toBe(9999999);
+ });
+
+ it('defaults incidentPriority to 0 when the resource does not declare one', () => {
+ const resource = makeResource({ id: 'no-prio' });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].incidentPriority).toBe(0);
+ });
+
+ it('classifies a non-shared VMware datastore with host scope and datastore category', () => {
+ const datastore = {
+ ...makeResource({
+ id: 'local-vmfs',
+ type: 'storage',
+ name: 'local-vmfs',
+ platformType: 'vmware-vsphere',
+ platformData: { sources: ['vmware-vsphere'] },
+ }),
+ storage: {
+ type: 'vmfs',
+ platform: 'vmware-vsphere',
+ topology: 'datastore',
+ shared: false,
+ },
+ vmware: { entityType: 'datastore' },
+ } as Resource;
+ const records = resourceAdapter.build(ctx([datastore]));
+ expect(records[0].category).toBe('datastore');
+ expect(records[0].location.scope).toBe('host');
+ });
+
+ it('classifies a plain proxmox storage resource with node scope', () => {
+ const resource = makeResource({ id: 'node-scope', platformData: { type: 'dir', node: 'pve1' } });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].location.scope).toBe('node');
+ });
+
+ it('classifies a PBS backup repository with cluster scope and backup-repository category', () => {
+ const resource = makeResource({
+ id: 'pbs-repo',
+ type: 'datastore',
+ name: 'pbs-store',
+ platformData: { type: 'pbs', node: 'pbs01', instance: 'pbs-cluster' },
+ });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].category).toBe('backup-repository');
+ expect(records[0].location.scope).toBe('cluster');
+ });
+
+ it('keeps warning health for an Unraid array that has an attention issue (disabled disks)', () => {
+ // normalizedHealth is 'warning' (incidentSeverity warning + status degraded),
+ // isUnraid is true (arrayState present), but hasUnraidStorageAttentionIssue
+ // is true (unraid_disabled_disks risk) -> the `!attention` guard is false,
+ // so health stays at the normalized 'warning' instead of being flipped.
+ const unraid = {
+ ...makeResource({
+ id: 'unraid-attention',
+ name: 'tower',
+ platformType: 'unraid',
+ status: 'degraded',
+ incidentSeverity: 'warning',
+ }),
+ storage: {
+ type: 'unraid-array',
+ platform: 'unraid',
+ topology: 'array',
+ arrayState: 'STARTED',
+ risk: {
+ level: 'critical',
+ reasons: [
+ {
+ code: 'unraid_disabled_disks',
+ severity: 'critical',
+ summary: 'Unraid array reports disabled disks',
+ },
+ ],
+ },
+ },
+ } as Resource;
+ const records = resourceAdapter.build(ctx([unraid]));
+ expect(records[0].health).toBe('warning');
+ });
+
+ it('uses resource.status as statusLabel for a non-Unraid resource', () => {
+ const resource = makeResource({ id: 'status-arm', status: 'running' });
+ const records = resourceAdapter.build(ctx([resource]));
+ expect(records[0].statusLabel).toBe('running');
+ expect(records[0].details?.status).toBe('running');
+ });
+});
+
+describe('storageAdapters.branchcov - mergeStorageRecords (via duplicate canonical keys)', () => {
+ it('selects current as preferred when current.incidentPriority >= incoming.incidentPriority', () => {
+ const current = makeRecord({ id: 'c1', incidentPriority: 5, incidentCategory: 'cur' });
+ const incoming = makeRecord({ id: 'i1', incidentPriority: 2, incidentCategory: 'inc' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.incidentPriority).toBe(5);
+ // incidentCategory is a spread-only top-level field -> preferred (current) wins.
+ expect(merged.incidentCategory).toBe('cur');
+ });
+
+ it('selects incoming as preferred when incoming.incidentPriority > current.incidentPriority', () => {
+ const current = makeRecord({ id: 'c2', incidentPriority: 2, incidentCategory: 'cur' });
+ const incoming = makeRecord({ id: 'i2', incidentPriority: 5, incidentCategory: 'inc' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.incidentPriority).toBe(5);
+ expect(merged.incidentCategory).toBe('inc');
+ });
+
+ it('breaks equal priorities in favour of current (the `>=` arm)', () => {
+ const current = makeRecord({ id: 'c3', incidentPriority: 3, incidentCategory: 'cur' });
+ const incoming = makeRecord({ id: 'i3', incidentPriority: 3, incidentCategory: 'inc' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.incidentCategory).toBe('cur');
+ });
+
+ it('treats undefined priorities as 0 and still prefers current', () => {
+ const current = makeRecord({ id: 'c4', incidentCategory: 'cur' });
+ const incoming = makeRecord({ id: 'i4', incidentCategory: 'inc' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.incidentCategory).toBe('cur');
+ });
+
+ it('deduplicates capabilities across both records preserving current-first order', () => {
+ const current = makeRecord({ id: 'c5', capabilities: ['capacity', 'health'] });
+ const incoming = makeRecord({ id: 'i5', capabilities: ['health', 'snapshots'] });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.capabilities).toEqual(['capacity', 'health', 'snapshots']);
+ });
+
+ it('falls back to [] for capabilities when either side is missing', () => {
+ const current = makeRecord({ id: 'c6', capabilities: undefined });
+ const incoming = makeRecord({ id: 'i6', capabilities: undefined });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.capabilities).toEqual([]);
+ });
+
+ it('promotes secondary.health when preferred.health is unknown but secondary is not', () => {
+ const current = makeRecord({ id: 'c7', incidentPriority: 1, health: 'unknown' });
+ const incoming = makeRecord({ id: 'i7', incidentPriority: 0, health: 'warning' });
+ // current preferred (1 >= 0); preferred.health 'unknown' && secondary 'warning' -> 'warning'.
+ const merged = mergeTwo(current, incoming);
+ expect(merged.health).toBe('warning');
+ });
+
+ it('keeps preferred.health when preferred.health is not unknown', () => {
+ const current = makeRecord({ id: 'c8', incidentPriority: 1, health: 'critical' });
+ const incoming = makeRecord({ id: 'i8', incidentPriority: 0, health: 'warning' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.health).toBe('critical');
+ });
+
+ it('keeps unknown when both preferred and secondary health are unknown', () => {
+ const current = makeRecord({ id: 'c9', incidentPriority: 1, health: 'unknown' });
+ const incoming = makeRecord({ id: 'i9', incidentPriority: 0, health: 'unknown' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.health).toBe('unknown');
+ });
+
+ it('falls back to secondary.statusLabel when preferred.statusLabel is empty', () => {
+ const current = makeRecord({
+ id: 'c10',
+ incidentPriority: 1,
+ statusLabel: '',
+ hostLabel: 'cur-host',
+ platformLabel: 'PVE',
+ platformKey: 'proxmox-pve',
+ topologyLabel: 'Pool',
+ });
+ const incoming = makeRecord({ id: 'i10', incidentPriority: 0, statusLabel: 'Online' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.statusLabel).toBe('Online');
+ });
+
+ it('keeps preferred.statusLabel when it is set', () => {
+ const current = makeRecord({ id: 'c11', incidentPriority: 1, statusLabel: 'Started' });
+ const incoming = makeRecord({ id: 'i11', incidentPriority: 0, statusLabel: 'Online' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.statusLabel).toBe('Started');
+ });
+
+ it('uses preferred protectionLabel when protectionReduced is set on preferred', () => {
+ const current = makeRecord({
+ id: 'c12',
+ incidentPriority: 0,
+ protectionReduced: true,
+ protectionLabel: 'Reduced',
+ });
+ const incoming = makeRecord({ id: 'i12', incidentPriority: 0, protectionLabel: 'OK' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.protectionLabel).toBe('Reduced');
+ });
+
+ it('falls back to secondary protectionLabel under the protection guard when preferred is empty', () => {
+ const current = makeRecord({
+ id: 'c13',
+ incidentPriority: 0,
+ protectionReduced: true,
+ protectionLabel: '',
+ });
+ const incoming = makeRecord({ id: 'i13', incidentPriority: 0, protectionLabel: 'OK' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.protectionLabel).toBe('OK');
+ });
+
+ it('uses secondary protectionLabel when preferred has no protection signals', () => {
+ const current = makeRecord({ id: 'c14', incidentPriority: 0, protectionLabel: '' });
+ const incoming = makeRecord({ id: 'i14', incidentPriority: 0, protectionLabel: 'Sec' });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.protectionLabel).toBe('Sec');
+ });
+
+ it('prefers preferred issueLabel/summary/action only when preferred.incidentPriority > 0', () => {
+ const current = makeRecord({
+ id: 'c15',
+ incidentPriority: 7,
+ issueLabel: 'CurIssue',
+ issueSummary: 'cur summary',
+ actionSummary: 'cur action',
+ });
+ const incoming = makeRecord({
+ id: 'i15',
+ incidentPriority: 0,
+ issueLabel: 'IncIssue',
+ issueSummary: 'inc summary',
+ actionSummary: 'inc action',
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.issueLabel).toBe('CurIssue');
+ expect(merged.issueSummary).toBe('cur summary');
+ expect(merged.actionSummary).toBe('cur action');
+ });
+
+ it('falls back to secondary issue fields when preferred.incidentPriority is 0', () => {
+ const current = makeRecord({
+ id: 'c16',
+ incidentPriority: 0,
+ issueLabel: '',
+ issueSummary: '',
+ actionSummary: '',
+ });
+ const incoming = makeRecord({
+ id: 'i16',
+ incidentPriority: 0,
+ issueLabel: 'IncIssue',
+ issueSummary: 'inc summary',
+ actionSummary: 'inc action',
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.issueLabel).toBe('IncIssue');
+ expect(merged.issueSummary).toBe('inc summary');
+ expect(merged.actionSummary).toBe('inc action');
+ });
+
+ it('promotes a meaningful secondary impactSummary over preferred "No dependent resources"', () => {
+ const current = makeRecord({
+ id: 'c17',
+ incidentPriority: 0,
+ impactSummary: 'No dependent resources',
+ });
+ const incoming = makeRecord({
+ id: 'i17',
+ incidentPriority: 0,
+ impactSummary: 'Affects 3 dependent resources',
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.impactSummary).toBe('Affects 3 dependent resources');
+ });
+
+ it('promotes a meaningful secondary impactSummary when preferred impactSummary is empty', () => {
+ const current = makeRecord({ id: 'c18', incidentPriority: 0, impactSummary: '' });
+ const incoming = makeRecord({
+ id: 'i18',
+ incidentPriority: 0,
+ impactSummary: 'Affects 2 vms',
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.impactSummary).toBe('Affects 2 vms');
+ });
+
+ it('keeps a meaningful preferred impactSummary over a meaningful secondary one', () => {
+ const current = makeRecord({
+ id: 'c19',
+ incidentPriority: 0,
+ impactSummary: 'Preferred impact',
+ });
+ const incoming = makeRecord({
+ id: 'i19',
+ incidentPriority: 0,
+ impactSummary: 'Secondary impact',
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.impactSummary).toBe('Preferred impact');
+ });
+
+ it('falls back to preferred impactSummary when secondary is "No dependent resources"', () => {
+ const current = makeRecord({
+ id: 'c20',
+ incidentPriority: 0,
+ impactSummary: 'Preferred impact',
+ });
+ const incoming = makeRecord({
+ id: 'i20',
+ incidentPriority: 0,
+ impactSummary: 'No dependent resources',
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.impactSummary).toBe('Preferred impact');
+ });
+
+ it('takes the max of consumer/protected/affected counts treating missing as 0', () => {
+ const current = makeRecord({
+ id: 'c21',
+ incidentPriority: 1,
+ consumerCount: 5,
+ protectedWorkloadCount: undefined,
+ affectedDatastoreCount: 2,
+ });
+ const incoming = makeRecord({
+ id: 'i21',
+ incidentPriority: 0,
+ consumerCount: undefined,
+ protectedWorkloadCount: 3,
+ affectedDatastoreCount: 4,
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.consumerCount).toBe(5);
+ expect(merged.protectedWorkloadCount).toBe(3);
+ expect(merged.affectedDatastoreCount).toBe(4);
+ });
+
+ it('defaults all counts to 0 when both sides omit them', () => {
+ const current = makeRecord({ id: 'c22', incidentPriority: 1 });
+ const incoming = makeRecord({ id: 'i22', incidentPriority: 0 });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.consumerCount).toBe(0);
+ expect(merged.protectedWorkloadCount).toBe(0);
+ expect(merged.affectedDatastoreCount).toBe(0);
+ });
+
+ it('ORs protectionReduced and rebuildInProgress across both records', () => {
+ const current = makeRecord({
+ id: 'c23',
+ incidentPriority: 1,
+ protectionReduced: false,
+ rebuildInProgress: true,
+ });
+ const incoming = makeRecord({
+ id: 'i23',
+ incidentPriority: 0,
+ protectionReduced: true,
+ rebuildInProgress: false,
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.protectionReduced).toBe(true);
+ expect(merged.rebuildInProgress).toBe(true);
+ });
+
+ it('prefers preferred.metricsTarget and falls back to secondary when preferred has none', () => {
+ const current = makeRecord({
+ id: 'c24',
+ incidentPriority: 1,
+ metricsTarget: { resourceType: 'storage', resourceId: 'preferred' },
+ });
+ const incoming = makeRecord({
+ id: 'i24',
+ incidentPriority: 0,
+ metricsTarget: { resourceType: 'storage', resourceId: 'secondary' },
+ });
+ expect(mergeTwo(current, incoming).metricsTarget).toEqual({
+ resourceType: 'storage',
+ resourceId: 'preferred',
+ });
+
+ const currentNoMt = makeRecord({ id: 'c24b', incidentPriority: 1 });
+ const incomingMt = makeRecord({
+ id: 'i24b',
+ incidentPriority: 0,
+ metricsTarget: { resourceType: 'storage', resourceId: 'secondary' },
+ });
+ expect(mergeTwo(currentNoMt, incomingMt).metricsTarget).toEqual({
+ resourceType: 'storage',
+ resourceId: 'secondary',
+ });
+ });
+
+ it('resolves refs.resourceId through metricsTarget then refs on both sides', () => {
+ // No metricsTarget on either side; preferred.refs.resourceId wins.
+ const current = makeRecord({
+ id: 'c25',
+ incidentPriority: 1,
+ refs: { resourceId: 'cur-id', platformEntityId: 'cur-pe' },
+ });
+ const incoming = makeRecord({
+ id: 'i25',
+ incidentPriority: 0,
+ refs: { resourceId: 'inc-id', platformEntityId: 'inc-pe' },
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.refs?.resourceId).toBe('cur-id');
+ expect(merged.refs?.platformEntityId).toBe('cur-pe');
+
+ // preferred.refs absent -> fall back to secondary.refs.
+ const mergedFallback = mergeTwo(
+ makeRecord({ id: 'c25b', incidentPriority: 1, metricsTarget: undefined }),
+ makeRecord({
+ id: 'i25b',
+ incidentPriority: 0,
+ refs: { resourceId: 'inc-id', platformEntityId: 'inc-pe' },
+ }),
+ );
+ expect(mergedFallback.refs?.resourceId).toBe('inc-id');
+ expect(mergedFallback.refs?.platformEntityId).toBe('inc-pe');
+ });
+
+ it('resolves refs.resourceId from metricsTarget before refs', () => {
+ const current = makeRecord({
+ id: 'c26',
+ incidentPriority: 1,
+ metricsTarget: { resourceType: 'storage', resourceId: 'mt-cur' },
+ refs: { resourceId: 'ref-cur' },
+ });
+ const incoming = makeRecord({ id: 'i26', incidentPriority: 0 });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.refs?.resourceId).toBe('mt-cur');
+ });
+
+ it('merges details with preferred overriding secondary, and tolerates missing details', () => {
+ // Both present -> preferred (current) keys win on conflict.
+ const current = makeRecord({
+ id: 'c27',
+ incidentPriority: 1,
+ details: { a: 'cur', b: 'cur', onlyCur: true },
+ });
+ const incoming = makeRecord({
+ id: 'i27',
+ incidentPriority: 0,
+ details: { b: 'inc', c: 'inc', onlyInc: true },
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.details).toEqual({ a: 'cur', b: 'cur', onlyCur: true, c: 'inc', onlyInc: true });
+
+ // Both absent -> {} (the `|| {}` fallbacks on both sides).
+ const mergedEmpty = mergeTwo(
+ makeRecord({ id: 'c27b', incidentPriority: 1, details: undefined }),
+ makeRecord({ id: 'i27b', incidentPriority: 0, details: undefined }),
+ );
+ expect(mergedEmpty.details).toEqual({});
+
+ // Preferred details absent -> secondary.details surface through.
+ const mergedSecondary = mergeTwo(
+ makeRecord({ id: 'c27c', incidentPriority: 1, details: undefined }),
+ makeRecord({ id: 'i27c', incidentPriority: 0, details: { from: 'secondary' } }),
+ );
+ expect(mergedSecondary.details).toEqual({ from: 'secondary' });
+ });
+
+ it('fills empty hostLabel/platformLabel/platformKey/topologyLabel from secondary', () => {
+ const current = makeRecord({
+ id: 'c28',
+ incidentPriority: 1,
+ hostLabel: '',
+ platformLabel: '',
+ platformKey: '',
+ topologyLabel: '',
+ });
+ const incoming = makeRecord({
+ id: 'i28',
+ incidentPriority: 0,
+ hostLabel: 'inc-host',
+ platformLabel: 'INC',
+ platformKey: 'inc-platform',
+ topologyLabel: 'IncTopo',
+ });
+ const merged = mergeTwo(current, incoming);
+ expect(merged.hostLabel).toBe('inc-host');
+ expect(merged.platformLabel).toBe('INC');
+ expect(merged.platformKey).toBe('inc-platform');
+ expect(merged.topologyLabel).toBe('IncTopo');
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/resourceBadgePresentation.branchcov.test.ts b/frontend-modern/src/utils/__tests__/resourceBadgePresentation.branchcov.test.ts
new file mode 100644
index 0000000000..85b7d34840
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourceBadgePresentation.branchcov.test.ts
@@ -0,0 +1,514 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getInfrastructureSystemIdentityBadges,
+ getInfrastructureSystemIdentitySortLabel,
+ getSourceBadge,
+ getTypeBadge,
+ getUnifiedSourceBadges,
+} from '@/utils/resourceBadgePresentation';
+import type { PlatformType, Resource, ResourceType, SourceType } from '@/types/resource';
+
+const makeResource = (overrides: Partial<Resource>): Resource => ({
+ id: 'resource-1',
+ type: 'agent',
+ name: 'host-1',
+ displayName: 'host-1',
+ platformId: 'host-1',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 1,
+ ...overrides,
+});
+
+const agentOnly = (agent: Record<string, unknown>): Partial<Resource> => ({
+ type: 'agent',
+ platformType: 'agent',
+ sourceType: 'agent',
+ sources: ['agent'],
+ platformData: { sources: ['agent'], agent },
+});
+
+describe('getTypeBadge — branch coverage', () => {
+ it('returns null for undefined', () => {
+ expect(getTypeBadge(undefined)).toBeNull();
+ });
+
+ it('returns null for empty string', () => {
+ expect(getTypeBadge('')).toBeNull();
+ });
+
+ it('returns null for null', () => {
+ expect(getTypeBadge(null as unknown as ResourceType)).toBeNull();
+ });
+
+ it('returns a canonical badge for a known resource type', () => {
+ const badge = getTypeBadge('pbs');
+ expect(badge).not.toBeNull();
+ expect(badge?.label).toBe('PBS');
+ });
+
+ it('returns a badge for an external/legacy type alias', () => {
+ const badge = getTypeBadge('proxmox-lxc');
+ expect(badge).not.toBeNull();
+ expect(badge?.label).toBe('LXC');
+ });
+
+ it('falls back to default presentation for an unrecognized type string', () => {
+ const badge = getTypeBadge('totally-fake-type');
+ expect(badge).not.toBeNull();
+ expect(badge?.label).toBe('totally-fake-type');
+ expect(badge?.title).toBe('totally-fake-type');
+ expect(badge?.classes).toContain('bg-surface-alt');
+ });
+});
+
+describe('getSourceBadge — branch coverage', () => {
+ it('returns null for undefined', () => {
+ expect(getSourceBadge(undefined)).toBeNull();
+ });
+
+ it('returns null for empty string', () => {
+ expect(getSourceBadge('' as unknown as SourceType)).toBeNull();
+ });
+
+ it('returns presentation badge for a known source type', () => {
+ const badge = getSourceBadge('api');
+ expect(badge).not.toBeNull();
+ expect(badge?.label).toBe('API');
+ expect(badge?.classes).toContain('bg-blue-100');
+ expect(badge?.title).toBe('api');
+ });
+
+ it('falls back to raw label and typeClasses for an unrecognized source type', () => {
+ const badge = getSourceBadge('custom-collector' as SourceType);
+ expect(badge).not.toBeNull();
+ expect(badge?.label).toBe('custom-collector');
+ expect(badge?.classes).toContain('bg-surface-alt');
+ expect(badge?.title).toBe('custom-collector');
+ });
+});
+
+describe('buildUnifiedSourceBadges (via getUnifiedSourceBadges) — branch coverage', () => {
+ it('returns an empty array for null', () => {
+ expect(getUnifiedSourceBadges(null)).toEqual([]);
+ });
+
+ it('returns an empty array for undefined', () => {
+ expect(getUnifiedSourceBadges(undefined)).toEqual([]);
+ });
+
+ it('returns an empty array for an empty array', () => {
+ expect(getUnifiedSourceBadges([])).toEqual([]);
+ });
+
+ it('normalizes alias keys to canonical platform badges', () => {
+ const badges = getUnifiedSourceBadges(['pve', 'pbs', 'pmg']);
+ expect(badges.map((b) => b.label)).toEqual(['PVE', 'PBS', 'PMG']);
+ });
+
+ it('normalizes vmware, k8s, and hyper-v aliases', () => {
+ const badges = getUnifiedSourceBadges(['vmware', 'k8s', 'hyper-v']);
+ expect(badges.map((b) => b.label)).toEqual(['vSphere', 'K8s', 'Hyper-V']);
+ });
+
+ it('handles generic source platform', () => {
+ const badges = getUnifiedSourceBadges(['generic']);
+ expect(badges).toHaveLength(1);
+ expect(badges[0]?.label).toBe('Generic');
+ });
+
+ it('handles presentation-only cloud platform sources', () => {
+ const badges = getUnifiedSourceBadges(['aws', 'azure', 'gcp']);
+ expect(badges.map((b) => b.label)).toEqual(['AWS', 'Azure', 'GCP']);
+ });
+});
+
+describe('withBadgeVersion (via getInfrastructureSystemIdentityBadges) — branch coverage', () => {
+ it('strips the Proxmox version wrapper format', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'debian',
+ osName: 'Proxmox VE',
+ osVersion: 'pve-manager/9.1.9/ee7bad0a3d1546c9',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'PVE 9.1.9',
+ ]);
+ });
+
+ it.each(['unknown', 'n/a', 'na', 'none', '-'] as const)(
+ 'treats sentinel version %s as empty so no suffix is appended',
+ (sentinelVersion) => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'linux',
+ osName: 'TrueNAS SCALE',
+ osVersion: sentinelVersion,
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'TrueNAS',
+ ]);
+ },
+ );
+
+ it('accepts a numeric version field from a storage facet', () => {
+ const resource = makeResource({
+ type: 'storage',
+ platformType: 'proxmox-pbs',
+ sourceType: 'api',
+ sources: ['pbs'],
+ platformData: {
+ sources: ['pbs'],
+ storage: { platform: 'pbs', type: 'pbs-datastore', topology: 'datastore' },
+ pbs: { version: 2 },
+ },
+ storage: {
+ platform: 'pbs',
+ type: 'pbs-datastore',
+ topology: 'datastore',
+ } as Resource['storage'],
+ });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'PBS 2',
+ ]);
+ });
+
+ it('keeps the title unchanged when the version already appears in the title', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'debian',
+ osName: 'Debian 12',
+ osVersion: '12',
+ }),
+ );
+ const badges = getInfrastructureSystemIdentityBadges(resource);
+ expect(badges[0]?.label).toBe('Debian 12');
+ expect(badges[0]?.title).toBe('Debian 12 12');
+ });
+
+ it('trims whitespace-padded version strings', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'linux',
+ osName: 'TrueNAS SCALE',
+ osVersion: ' 13.0 ',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'TrueNAS 13.0',
+ ]);
+ });
+});
+
+describe('getAgentSystemIdentityBadge (via getInfrastructureSystemIdentityBadges) — branch coverage', () => {
+ it('returns null when no agent record exists (falls through to platform badge)', () => {
+ const resource = makeResource({
+ type: 'storage',
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Agent']);
+ });
+
+ it('produces a badge from a hostProfile that is a valid platform but not an agent host profile', () => {
+ const resource = makeResource({
+ type: 'docker-host',
+ platformType: 'docker',
+ sourceType: 'hybrid',
+ platformData: {
+ sources: ['agent', 'docker'],
+ agent: {
+ platform: 'linux',
+ hostProfile: 'proxmox-pve',
+ osName: 'Proxmox VE',
+ osVersion: '8.2.4',
+ },
+ },
+ });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'PVE 8.2.4',
+ ]);
+ });
+
+ it('derives a known source from a raw platform key via normalizeSourcePlatformKey', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'linux',
+ osName: 'truenas',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['TrueNAS']);
+ });
+
+ it('derives a known source from manifest display tokens in the osName', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'linux',
+ osName: 'Synology DSM',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Synology']);
+ });
+
+ it.each([
+ ['Ubuntu 24.04.2 LTS', 'Ubuntu'],
+ ['Debian GNU/Linux 12', 'Debian'],
+ ['Rocky Linux 9.3', 'Rocky'],
+ ['Alpine Linux 3.19', 'Alpine'],
+ ['AlmaLinux 9.3', 'AlmaLinux'],
+ ['CentOS Stream 9', 'CentOS'],
+ ['RHEL 9.4', 'RHEL'],
+ ['Arch Linux', 'Arch'],
+ ['openSUSE Tumbleweed', 'openSUSE'],
+ ['SUSE Linux Enterprise', 'SUSE'],
+ ['macOS Sonoma 14.4', 'macOS'],
+ ['Windows Server 2022', 'Windows'],
+ ['FreeBSD 14.1', 'FreeBSD'],
+ ['Linux Mint 22', 'Linux'],
+ ] as const)('derives the OS label %s from osName via hostOsLabelPatterns', (osName, expected) => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'linux',
+ osName,
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([expected]);
+ });
+
+ it('derives the OS label from platform when osName is empty', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'freebsd',
+ osName: '',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['FreeBSD']);
+ });
+
+ it('returns null for an agent with no recognizable identity (falls through)', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'barbaz',
+ osName: 'Foobar OS',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Agent']);
+ });
+});
+
+describe('getKnownHostIdentitySource (via identity badges) — branch coverage', () => {
+ it('matches an agent host profile identity token in the second value', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'unknown-os',
+ osName: 'my unraid server',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Unraid']);
+ });
+
+ it('uses the second value when the first does not match', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'unknown-os',
+ osName: 'truenas',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['TrueNAS']);
+ });
+
+ it('excludes docker from host identity even when docker tokens are present', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: '',
+ osName: 'docker desktop',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Agent']);
+ });
+
+ it('excludes generic from host identity sources', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: 'generic',
+ osName: 'generic host',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Agent']);
+ });
+});
+
+describe('getHostIdentityAgentProfile (via identity badges) — branch coverage', () => {
+ it('matches the exact profile id', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: '',
+ osName: 'unraid',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Unraid']);
+ });
+
+ it('returns null for a whitespace-only value (falls through to other sources)', () => {
+ const resource = makeResource(
+ agentOnly({
+ platform: ' ',
+ osName: 'truenas',
+ }),
+ );
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['TrueNAS']);
+ });
+});
+
+describe('getStorageSystemIdentityBadge (via getInfrastructureSystemIdentityBadges) — branch coverage', () => {
+ it('returns a versioned badge for storage with a known platform and topology', () => {
+ const resource = makeResource({
+ type: 'storage',
+ platformType: 'truenas',
+ sourceType: 'api',
+ sources: ['truenas'],
+ platformData: {
+ sources: ['truenas'],
+ storage: { platform: 'truenas', type: 'zpool', topology: 'pool-0' },
+ truenas: { version: '13.0' },
+ },
+ storage: {
+ platform: 'truenas',
+ type: 'zpool',
+ topology: 'pool-0',
+ } as Resource['storage'],
+ });
+ const badges = getInfrastructureSystemIdentityBadges(resource);
+ expect(badges[0]?.label).toBe('TrueNAS 13.0');
+ expect(badges[0]?.title).toContain('pool-0');
+ });
+
+ it('hits the docker version switch case when storage platform is docker', () => {
+ const resource = makeResource({
+ type: 'storage',
+ platformType: 'docker',
+ sourceType: 'agent',
+ sources: ['docker'],
+ platformData: {
+ sources: ['docker'],
+ storage: { platform: 'docker', type: 'docker-volume' },
+ docker: { runtimeVersion: '24.0.7' },
+ },
+ storage: {
+ platform: 'docker',
+ type: 'docker-volume',
+ } as Resource['storage'],
+ });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'Docker / Podman 24.0.7',
+ ]);
+ });
+
+ it('returns null for storage with an unrecognized platform (falls through)', () => {
+ const resource = makeResource({
+ type: 'storage',
+ platformType: 'agent',
+ sourceType: 'agent',
+ sources: ['agent'],
+ platformData: {
+ sources: ['agent'],
+ storage: { platform: 'mystery-nas', type: 'mystery-array' },
+ },
+ storage: {
+ platform: 'mystery-nas',
+ type: 'mystery-array',
+ } as Resource['storage'],
+ });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual(['Agent']);
+ });
+});
+
+describe('getDockerHostOsIdentityBadge (via getInfrastructureSystemIdentityBadges) — branch coverage', () => {
+ const dockerHostNoAgent = (docker: Resource['docker']): Resource =>
+ makeResource({
+ type: 'docker-host',
+ platformType: 'docker',
+ sourceType: 'agent',
+ platformData: { sources: ['docker'] },
+ docker,
+ });
+
+ it('returns a known-source badge when docker.os matches an agent host profile token', () => {
+ const resource = dockerHostNoAgent({ os: 'Unraid OS 7.2.2', runtime: 'docker' });
+ const badges = getInfrastructureSystemIdentityBadges(resource);
+ expect(badges[0]?.label).toBe('Unraid');
+ expect(badges[0]?.title).toContain('Unraid OS 7.2.2');
+ });
+
+ it('returns an OS-label badge when docker.os matches a hostOsLabelPattern but no known source', () => {
+ const resource = dockerHostNoAgent({ os: 'Ubuntu Server 22.04 LTS', runtime: 'docker' });
+ const badges = getInfrastructureSystemIdentityBadges(resource);
+ expect(badges[0]?.label).toBe('Ubuntu');
+ expect(badges[0]?.title).toBe('Ubuntu Server 22.04 LTS');
+ });
+
+ it('returns null for an unrecognized docker os (falls through to docker platform badge)', () => {
+ const resource = dockerHostNoAgent({ os: 'MysteryOS 9000', runtime: 'docker' });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'Docker / Podman',
+ ]);
+ });
+
+ it('returns null when there is no docker facet (falls through to docker platform badge)', () => {
+ const resource = makeResource({
+ type: 'docker-host',
+ platformType: 'docker',
+ sourceType: 'agent',
+ platformData: { sources: ['docker'] },
+ });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'Docker / Podman',
+ ]);
+ });
+
+ it('returns null when docker.os is missing (falls through to docker platform badge)', () => {
+ const resource = dockerHostNoAgent({ runtime: 'docker' });
+ expect(getInfrastructureSystemIdentityBadges(resource).map((b) => b.label)).toEqual([
+ 'Docker / Podman',
+ ]);
+ });
+});
+
+describe('getInfrastructureSystemIdentitySortLabel — branch coverage', () => {
+ it('returns the first badge label when identity badges exist', () => {
+ const resource = makeResource({
+ type: 'k8s-node',
+ platformType: 'kubernetes',
+ sourceType: 'api',
+ sources: ['kubernetes'],
+ platformData: {
+ sources: ['kubernetes'],
+ kubernetes: { version: '1.28.4' },
+ },
+ });
+ expect(getInfrastructureSystemIdentitySortLabel(resource)).toBe('K8s 1.28.4');
+ });
+
+ it('returns empty string when no badges and platformType is falsy', () => {
+ const resource = makeResource({
+ type: 'storage',
+ platformType: '' as unknown as PlatformType,
+ sourceType: 'agent',
+ });
+ expect(getInfrastructureSystemIdentitySortLabel(resource)).toBe('');
+ });
+
+ it('returns the platform badge label when no system identity is found', () => {
+ const resource = makeResource({
+ type: 'agent',
+ platformType: 'truenas',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ });
+ expect(getInfrastructureSystemIdentitySortLabel(resource)).toBe('TrueNAS');
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/resourceIdentity.branchcov.test.ts b/frontend-modern/src/utils/__tests__/resourceIdentity.branchcov.test.ts
new file mode 100644
index 0000000000..8ee36439c4
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourceIdentity.branchcov.test.ts
@@ -0,0 +1,433 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Resource } from '@/types/resource';
+import type { Agent, Node } from '@/types/api';
+import {
+ getInfrastructureDiscoveryHostname,
+ getInfrastructureMetadataId,
+ getPreferredResourceDisplayName,
+ getPreferredResourceIP,
+ getPreferredWorkloadsAgentHint,
+ getPrimaryResourceIdentity,
+ getResourceIdentityAliases,
+ resolveGuestUrlWithIdentity,
+} from '@/utils/resourceIdentity';
+
+const makeResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'resource-1',
+ type: 'agent',
+ name: 'resource-1',
+ displayName: 'resource-1',
+ platformId: 'resource-1',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: Date.now(),
+ ...overrides,
+ }) as Resource;
+
+describe('getPrimaryResourceIdentity (branch coverage)', () => {
+ it('falls through a whitespace-only canonical primary id to lower-priority sources', () => {
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ canonicalIdentity: { primaryId: ' ' },
+ metricsTarget: { resourceType: 'docker-host', resourceId: 'docker-host-1' },
+ }),
+ ),
+ ).toBe('docker-host:docker-host-1');
+ });
+
+ it('skips the metrics identity when the metrics resource type is whitespace', () => {
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ metricsTarget: {
+ resourceType: ' ',
+ resourceId: 'x',
+ } as unknown as Resource['metricsTarget'],
+ discoveryTarget: {
+ resourceType: 'agent',
+ agentId: 'agent-1',
+ resourceId: 'agent-1',
+ },
+ }),
+ ),
+ ).toBe('agent:agent-1');
+ });
+
+ it('prefixes the kubernetes cluster id for k8s-cluster, k8s-node, and pod resources', () => {
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ type: 'k8s-cluster',
+ kubernetes: { clusterName: 'prod-eu' },
+ }),
+ ),
+ ).toBe('k8s:prod-eu');
+
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ type: 'k8s-node',
+ kubernetes: { context: 'worker-ctx' },
+ }),
+ ),
+ ).toBe('k8s:worker-ctx');
+
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ type: 'pod',
+ kubernetes: { clusterName: 'prod-eu' },
+ }),
+ ),
+ ).toBe('k8s:prod-eu');
+ });
+
+ it('falls back to the pbs and pmg instance ids under platformData', () => {
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ type: 'vm',
+ platformData: { pbs: { instanceId: 'pbs-inst-1' } },
+ }),
+ ),
+ ).toBe('pbs:pbs-inst-1');
+
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ type: 'vm',
+ platformData: { pmg: { instanceId: 'pmg-inst-1' } },
+ }),
+ ),
+ ).toBe('pmg:pmg-inst-1');
+ });
+
+ it('falls back to the raw resource id when no identity source resolves', () => {
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ id: 'lonely-vm',
+ type: 'vm',
+ }),
+ ),
+ ).toBe('lonely-vm');
+ });
+
+ it('does not emit a docker-host prefix when the docker runtime id is missing', () => {
+ expect(
+ getPrimaryResourceIdentity(
+ makeResource({
+ id: 'docker-host-bare',
+ type: 'docker-host',
+ }),
+ ),
+ ).toBe('docker-host-bare');
+ });
+});
+
+describe('getPreferredWorkloadsAgentHint (branch coverage)', () => {
+ it('returns undefined for resource types outside the docker/truenas/agent families', () => {
+ expect(
+ getPreferredWorkloadsAgentHint(makeResource({ type: 'vm' })),
+ ).toBeUndefined();
+ expect(
+ getPreferredWorkloadsAgentHint(makeResource({ type: 'k8s-cluster' })),
+ ).toBeUndefined();
+ });
+
+ it('falls back to the shared hostname when the docker hostname is absent', () => {
+ expect(
+ getPreferredWorkloadsAgentHint(
+ makeResource({
+ type: 'docker-host',
+ name: 'dock-01',
+ platformData: { docker: {} },
+ }),
+ ),
+ ).toBe('dock-01');
+ });
+
+ it('falls back to the shared hostname when the truenas hostname is absent', () => {
+ expect(
+ getPreferredWorkloadsAgentHint(
+ makeResource({
+ type: 'agent',
+ platformType: 'truenas',
+ name: 'nas-box',
+ platformData: { truenas: {} },
+ }),
+ ),
+ ).toBe('nas-box');
+ });
+
+ it('falls back to the shared hostname when the proxmox node name is absent', () => {
+ expect(
+ getPreferredWorkloadsAgentHint(
+ makeResource({
+ type: 'agent',
+ platformType: 'agent',
+ name: 'pve-host',
+ platformData: { proxmox: {} },
+ }),
+ ),
+ ).toBe('pve-host');
+ });
+});
+
+describe('getPreferredResourceIP (branch coverage)', () => {
+ it('prefers a routable IPv6 address over an unusable link-local IPv6', () => {
+ const resource = makeResource({
+ identity: { ips: ['fe80::1', '2001:db8::1'] },
+ });
+ expect(getPreferredResourceIP(resource)).toBe('2001:db8::1');
+ });
+
+ it('treats a loopback IPv4 as the only (unusable) candidate and still returns it', () => {
+ const resource = makeResource({ identity: { ips: ['127.0.0.1'] } });
+ expect(getPreferredResourceIP(resource)).toBe('127.0.0.1');
+ });
+
+ it('scores a public IPv4 above a carrier-grade NAT address', () => {
+ const resource = makeResource({ identity: { ips: ['100.64.0.1', '8.8.8.8'] } });
+ expect(getPreferredResourceIP(resource)).toBe('8.8.8.8');
+ });
+
+ it('returns a non-IP string untouched when it is the only candidate', () => {
+ const resource = makeResource({ identity: { ips: ['host-name'] } });
+ expect(getPreferredResourceIP(resource)).toBe('host-name');
+ });
+
+ it('normalizes bracketed, CIDR-suffixed, and zone-tagged interface addresses', () => {
+ const bracketed = makeResource({
+ agent: {
+ networkInterfaces: [{ name: 'eth0', addresses: ['[192.168.0.5]'] }],
+ },
+ });
+ expect(getPreferredResourceIP(bracketed)).toBe('192.168.0.5');
+
+ const cidr = makeResource({
+ agent: {
+ networkInterfaces: [{ name: 'eth0', addresses: ['10.0.0.9/24'] }],
+ },
+ });
+ expect(getPreferredResourceIP(cidr)).toBe('10.0.0.9');
+
+ const zoned = makeResource({
+ agent: {
+ networkInterfaces: [{ name: 'eth0', addresses: ['2001:db8::1%eth0'] }],
+ },
+ });
+ expect(getPreferredResourceIP(zoned)).toBe('2001:db8::1');
+ });
+
+ it('skips empty and whitespace-only interface addresses', () => {
+ const resource = makeResource({
+ agent: {
+ networkInterfaces: [{ name: 'eth0', addresses: ['', ' ', '\t'] }],
+ },
+ });
+ expect(getPreferredResourceIP(resource)).toBeUndefined();
+ });
+
+ it('penalizes virtual interfaces so a physical interface wins with the same family', () => {
+ const resource = makeResource({
+ agent: {
+ networkInterfaces: [
+ { name: 'docker0', addresses: ['172.18.0.1/16'] },
+ { name: 'eth0', addresses: ['172.18.0.1/24'] },
+ ],
+ },
+ });
+ expect(getPreferredResourceIP(resource)).toBe('172.18.0.1');
+ });
+});
+
+describe('getPreferredResourceDisplayName (branch coverage)', () => {
+ it('uses the canonical display name when the resource display name is empty', () => {
+ expect(
+ getPreferredResourceDisplayName(
+ makeResource({
+ displayName: '',
+ canonicalIdentity: { displayName: 'Canonical Label' },
+ }),
+ ),
+ ).toBe('Canonical Label');
+ });
+
+ it('follows the normal path when a policy does not require governed display', () => {
+ expect(
+ getPreferredResourceDisplayName(
+ makeResource({
+ displayName: 'Visible',
+ policy: { sensitivity: 'internal', routing: { scope: 'cloud-summary' } },
+ }),
+ ),
+ ).toBe('Visible');
+ });
+
+ it('falls all the way back to the primary resource identity when no label resolves', () => {
+ expect(
+ getPreferredResourceDisplayName(
+ makeResource({
+ id: 'identity-only',
+ type: 'vm',
+ name: '',
+ displayName: '',
+ platformId: '',
+ }),
+ ),
+ ).toBe('identity-only');
+ });
+});
+
+describe('getInfrastructureMetadataId (branch coverage)', () => {
+ const nodeWith = (overrides: Partial<Pick<Node, 'id' | 'name' | 'linkedAgentId'>>) =>
+ ({ id: 'node-1', name: 'pve1', ...overrides } as Pick<Node, 'id' | 'name' | 'linkedAgentId'>);
+
+ it('falls back to the node id when no agent and no linked agent id resolve', () => {
+ expect(getInfrastructureMetadataId(nodeWith({ linkedAgentId: undefined }))).toBe('node-1');
+ });
+
+ it('falls back to the node name when the id is empty and nothing else resolves', () => {
+ expect(
+ getInfrastructureMetadataId(nodeWith({ id: '', name: 'pve1', linkedAgentId: undefined })),
+ ).toBe('pve1');
+ });
+
+ it('falls through an agent whose metadata ids are all whitespace', () => {
+ const agent = {
+ id: ' ',
+ hostname: 'tower.local',
+ status: 'online',
+ lastSeen: Date.now(),
+ } as unknown as Agent;
+ expect(
+ getInfrastructureMetadataId(nodeWith({ linkedAgentId: 'agent-linked' }), agent),
+ ).toBe('agent-linked');
+ });
+});
+
+describe('getInfrastructureDiscoveryHostname / getAgentLikeDiscoveryHostname (branch coverage)', () => {
+ it('prefers the canonical hostname over discovery, agent, and platform hostnames', () => {
+ const agent = {
+ id: 'a1',
+ hostname: 'agent.host',
+ status: 'online',
+ lastSeen: Date.now(),
+ canonicalIdentity: { hostname: 'canonical.host' },
+ discoveryTarget: { resourceType: 'agent', agentId: 'a1', resourceId: 'a1', hostname: 'disc.host' },
+ platformData: { agent: { hostname: 'plat.host' } },
+ } as unknown as Agent;
+ expect(getInfrastructureDiscoveryHostname({ name: 'pve1' }, agent)).toBe('canonical.host');
+ });
+
+ it('falls back to the discovery target hostname when canonical is absent', () => {
+ const agent = {
+ id: 'a1',
+ hostname: 'agent.host',
+ status: 'online',
+ lastSeen: Date.now(),
+ discoveryTarget: { resourceType: 'agent', agentId: 'a1', resourceId: 'a1', hostname: 'disc.host' },
+ } as unknown as Agent;
+ expect(getInfrastructureDiscoveryHostname({ name: 'pve1' }, agent)).toBe('disc.host');
+ });
+
+ it('falls back to the agent hostname when canonical and discovery are absent', () => {
+ const agent = {
+ id: 'a1',
+ hostname: 'agent.host',
+ status: 'online',
+ lastSeen: Date.now(),
+ } as unknown as Agent;
+ expect(getInfrastructureDiscoveryHostname({ name: 'pve1' }, agent)).toBe('agent.host');
+ });
+
+ it('falls back to the platform agent hostname when no other hostname resolves', () => {
+ const agent = {
+ id: 'a1',
+ status: 'online',
+ lastSeen: Date.now(),
+ platformData: { agent: { hostname: 'plat.host' } },
+ } as unknown as Agent;
+ expect(getInfrastructureDiscoveryHostname({ name: 'pve1' }, agent)).toBe('plat.host');
+ });
+
+ it('returns the node name when no agent is provided', () => {
+ expect(getInfrastructureDiscoveryHostname({ name: 'pve1' })).toBe('pve1');
+ });
+});
+
+describe('resolveGuestUrlWithIdentity (branch coverage)', () => {
+ const withIP = (ip: string): Resource =>
+ makeResource({ identity: { ips: [ip] } });
+
+ it('substitutes the LAN IP into an http URL and preserves port and path', () => {
+ expect(resolveGuestUrlWithIdentity('http://pi:8006/console', withIP('192.168.0.2'))).toBe(
+ 'http://192.168.0.2:8006/console',
+ );
+ });
+
+ it('substitutes the LAN IP into a url that has no port', () => {
+ expect(resolveGuestUrlWithIdentity('https://pi', withIP('192.168.0.2'))).toBe(
+ 'https://192.168.0.2',
+ );
+ });
+
+ it('returns the original url when the scheme is not http or https', () => {
+ expect(resolveGuestUrlWithIdentity('ftp://pi', withIP('192.168.0.2'))).toBe('ftp://pi');
+ });
+
+ it('returns the original url when no protocol authority is present', () => {
+ expect(resolveGuestUrlWithIdentity('pi:8006', withIP('192.168.0.2'))).toBe('pi:8006');
+ });
+
+ it('returns the original url when the host is a bracketed IPv6 literal that the regex cannot capture', () => {
+ expect(resolveGuestUrlWithIdentity('https://[::1]:8006', withIP('192.168.0.2'))).toBe(
+ 'https://[::1]:8006',
+ );
+ });
+
+ it('returns the original bare-host url when every candidate address normalizes to empty', () => {
+ const resource = makeResource({
+ agent: { networkInterfaces: [{ name: 'eth0', addresses: ['', ' '] }] },
+ });
+ expect(resolveGuestUrlWithIdentity('https://pi:8006', resource)).toBe('https://pi:8006');
+ });
+});
+
+describe('dedupeTrimmedValues via getResourceIdentityAliases (branch coverage)', () => {
+ it('drops whitespace-only and empty alias values', () => {
+ expect(
+ getResourceIdentityAliases(
+ makeResource({
+ metricsTarget: { resourceType: 'docker-host', resourceId: ' ' },
+ discoveryTarget: {
+ resourceType: 'agent',
+ agentId: '',
+ resourceId: '',
+ },
+ identity: { hostname: '\t' },
+ }),
+ ),
+ ).toEqual([]);
+ });
+
+ it('deduplicates case-insensitively while keeping the first observed casing', () => {
+ expect(
+ getResourceIdentityAliases(
+ makeResource({
+ metricsTarget: { resourceType: 'docker-host', resourceId: 'Host-A' },
+ discoveryTarget: {
+ resourceType: 'agent',
+ agentId: 'agent-1',
+ resourceId: 'host-a',
+ },
+ }),
+ ),
+ ).toEqual(['Host-A', 'agent-1']);
+ });
+});