Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

test(frontend): branch coverage for 9 pure modules (GLM wave 0712 batch 3)

rcourtman8f6888b7a4f0
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceHealthPresentation.branchcov0712.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceHealthPresentation.branchcov0712.test.ts
new file mode 100644
index 0000000000..8c62cbb71c
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceHealthPresentation.branchcov0712.test.ts
@@ -0,0 +1,239 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import { getResourceHealthIssuePresentation } from '../resourceHealthPresentation';
+
+/**
+ * Branch-coverage suite for the still-uncovered branches in
+ * resourceHealthPresentation.ts. `compactHealthLabel` is module-private, so it
+ * is driven exclusively through the exported `getResourceHealthIssuePresentation`
+ * (by placing the probe string in `incidentSummary`, which becomes `primary`),
+ * asserting on the observable `compactLabel` — never re-implemented or imported
+ * directly.
+ */
+
+const makeResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'agent-tower',
+ type: 'agent',
+ name: 'Tower',
+ displayName: 'Tower',
+ platformId: 'tower',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'degraded',
+ lastSeen: Date.now(),
+ ...overrides,
+ }) as Resource;
+
+/**
+ * Push `primary` as the sole summary (via `incidentSummary`) on a degraded
+ * resource and return the resulting `compactLabel`. Throws if the presentation
+ * resolves to null so a branch misconfiguration surfaces as a test failure
+ * rather than a silent `undefined` assertion.
+ */
+const compactLabelFor = (primary: string): string => {
+ const result = getResourceHealthIssuePresentation(makeResource({ incidentSummary: primary }));
+ if (!result) throw new Error(`expected non-null presentation for primary: ${primary}`);
+ return result.compactLabel;
+};
+
+describe('compactHealthLabel (via getResourceHealthIssuePresentation)', () => {
+ it('returns "Parity unavailable" when both "parity protection" and "unavailable" appear', () => {
+ expect(compactLabelFor('Parity protection unavailable')).toBe('Parity unavailable');
+ });
+
+ it('returns "Parity missing" when both "parity" and "missing" appear (no "protection")', () => {
+ expect(compactLabelFor('Parity disk missing')).toBe('Parity missing');
+ });
+
+ it('returns "Array check running" when "array is running check" appears', () => {
+ expect(compactLabelFor('The array is running check now')).toBe('Array check running');
+ });
+
+ it('returns the summary unchanged when it is short (<= 34) and keyword-free', () => {
+ expect(compactLabelFor('Disk failure detected')).toBe('Disk failure detected');
+ });
+
+ it('returns the summary unchanged at the exact 34-character boundary', () => {
+ const exact = 'b'.repeat(34);
+ expect(compactLabelFor(exact)).toBe(exact);
+ });
+
+ it('truncates keyword-free summaries longer than 34 characters to 31 chars + "..."', () => {
+ expect(compactLabelFor('a'.repeat(40))).toBe(`${'a'.repeat(31)}...`);
+ });
+
+ it('prefers the "without parity protection" keyword over the truncation branch', () => {
+ // Length > 34 but contains the keyword -> keyword label wins, no truncation.
+ const longKeyword = `without parity protection${'X'.repeat(40)}`;
+ expect(compactLabelFor(longKeyword)).toBe('No parity');
+ });
+});
+
+describe('getResourceHealthIssuePresentation', () => {
+ it('normalizes a whitespace-padded uppercase status to a recognized attention status', () => {
+ // The runtime payload may carry a non-canonical status string even though
+ // the TS type is strict, so cast to exercise the defensive trim().toLowerCase().
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ status: ' DEGRADED ' as unknown as Resource['status'],
+ incidentSummary: 'Normalized status hit',
+ }),
+ );
+ // ' DEGRADED ' is not in ATTENTION_STATUSES; only trim().toLowerCase()
+ // (-> 'degraded') yields a match, so a non-null result proves normalization.
+ expect(result?.primary).toBe('Normalized status hit');
+ });
+
+ it('returns null when status is undefined (the `|| ""` empty-string arm)', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({ status: undefined, incidentSummary: 'Present but ignored' }),
+ );
+ expect(result).toBeNull();
+ });
+
+ it('returns null when there are no summaries even with an attention status', () => {
+ const result = getResourceHealthIssuePresentation(makeResource({ status: 'warning' }));
+ expect(result).toBeNull();
+ });
+
+ it('returns null for a non-attention status when summaries are present', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({ status: 'paused', incidentSummary: 'Ignored when paused' }),
+ );
+ expect(result).toBeNull();
+ });
+
+ it('dedupes a case-insensitive duplicate of primary at push time (never reaches details or title)', () => {
+ // pushUnique drops 'DISK FAILURE' against the already-pushed primary
+ // 'Disk failure' before it can become a detail, so neither `details` nor
+ // `title` contain the duplicate. (Consequence: the `details.filter(...)`
+ // guard in the return statement is never able to remove anything — see
+ // GLM_REPORT.md suspected-dead-code note.)
+ const result = getResourceHealthIssuePresentation(
+ makeResource({ incidentSummary: 'Disk failure', incidentLabel: 'DISK FAILURE' }),
+ );
+ expect(result).toStrictEqual({
+ primary: 'Disk failure',
+ compactLabel: 'Disk failure',
+ details: [],
+ title: 'Disk failure',
+ });
+ });
+
+ it('keeps a non-matching detail in both `details` and `title`', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({ incidentSummary: 'Primary issue', incidentLabel: 'Secondary issue' }),
+ );
+ expect(result?.details).toStrictEqual(['Secondary issue']);
+ expect(result?.title).toBe('Primary issue · Secondary issue');
+ });
+
+ it('dedupes case-insensitive equal summaries, keeping only the first occurrence', () => {
+ // 'BETA' duplicates 'Beta' (already pushed) -> dropped by pushUnique before
+ // it could become a second detail.
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ incidentSummary: 'Alpha',
+ incidentLabel: 'Beta',
+ storage: { postureSummary: 'BETA' },
+ }),
+ );
+ expect(result?.details).toStrictEqual(['Beta']);
+ expect(result?.title).toBe('Alpha · Beta');
+ });
+
+ it('skips whitespace-only summaries so they never become the primary', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({ incidentSummary: ' ', incidentLabel: 'Real issue' }),
+ );
+ expect(result?.primary).toBe('Real issue');
+ });
+
+ it('surfaces reasons from resource.storage.risk', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ storage: {
+ risk: {
+ level: 'critical',
+ reasons: [{ code: 'storage_down', severity: 'critical', summary: 'Storage risk reason A' }],
+ },
+ },
+ }),
+ );
+ expect(result?.primary).toBe('Storage risk reason A');
+ });
+
+ it('surfaces reasons from agent.storageRisk', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ agent: {
+ storageRisk: {
+ level: 'critical',
+ reasons: [{ code: 'agent_disk', severity: 'critical', summary: 'Agent storage risk reason' }],
+ },
+ },
+ }),
+ );
+ expect(result?.primary).toBe('Agent storage risk reason');
+ });
+
+ it('surfaces all four agent.unraid storage summaries (posture primary, rest as details)', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ agent: {
+ unraid: {
+ postureSummary: 'Unraid posture',
+ riskSummary: 'Unraid risk',
+ protectionSummary: 'Unraid protection',
+ rebuildSummary: 'Unraid rebuild',
+ },
+ },
+ }),
+ );
+ expect(result?.primary).toBe('Unraid posture');
+ expect(result?.details).toStrictEqual(['Unraid risk', 'Unraid protection', 'Unraid rebuild']);
+ });
+
+ it('surfaces all four resource.storage summaries (posture primary, rest as details)', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ storage: {
+ postureSummary: 'Storage posture',
+ riskSummary: 'Storage risk',
+ protectionSummary: 'Storage protection',
+ rebuildSummary: 'Storage rebuild',
+ },
+ }),
+ );
+ expect(result?.primary).toBe('Storage posture');
+ expect(result?.details).toStrictEqual(['Storage risk', 'Storage protection', 'Storage rebuild']);
+ });
+
+ it('surfaces all four agent storage summaries (posture primary, rest as details)', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ agent: {
+ storagePostureSummary: 'Agent posture',
+ storageRiskSummary: 'Agent risk',
+ protectionSummary: 'Agent protection',
+ rebuildSummary: 'Agent rebuild',
+ },
+ }),
+ );
+ expect(result?.primary).toBe('Agent posture');
+ expect(result?.details).toStrictEqual(['Agent risk', 'Agent protection', 'Agent rebuild']);
+ });
+
+ it('prefers incidentSummary as primary over storage and agent summaries (push order)', () => {
+ const result = getResourceHealthIssuePresentation(
+ makeResource({
+ incidentSummary: 'Top priority',
+ storage: { postureSummary: 'Storage summary' },
+ agent: { storagePostureSummary: 'Agent summary' },
+ }),
+ );
+ expect(result?.primary).toBe('Top priority');
+ expect(result?.details).toStrictEqual(['Storage summary', 'Agent summary']);
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/vmwareConnectionFailurePresentation.branchcov0712.test.ts b/frontend-modern/src/components/Settings/__tests__/vmwareConnectionFailurePresentation.branchcov0712.test.ts
new file mode 100644
index 0000000000..8fe026d40c
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/vmwareConnectionFailurePresentation.branchcov0712.test.ts
@@ -0,0 +1,302 @@
+/**
+ * Branch-coverage tests for vmwareConnectionFailurePresentation.
+ *
+ * `normalizeOptionalText` is module-private (not exported); it is only
+ * reachable through the exported `buildVMwareConnectionFailurePresentation`.
+ * Each of its arms (optional-chain short-circuit on null/undefined, the
+ * `.trim()` invocation arm on a real string, and the ternary's truthy vs
+ * falsy operands when trim() yields a non-empty vs empty result) is driven
+ * here through the observable `code` / `category` / `message` output fields
+ * and through which `switch` arm the normalized category routes to.
+ *
+ * The exported builder's own branches — every `switch` arm, the default
+ * fall-through, the `vmware_invalid_config` code guard, the message `??`
+ * fallback, and the three `default* ?? <literal>` coalescences in the final
+ * return — are each exercised with concrete object-shape assertions.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ buildVMwareConnectionFailurePresentation,
+ type VMwareConnectionFailurePresentation,
+} from '../vmwareConnectionFailurePresentation';
+
+// The module-private input interface is not exported; derive it from the
+// single exported builder so the fixture stays in sync with the real type.
+type VMwareFailureInput = Parameters<typeof buildVMwareConnectionFailurePresentation>[0];
+
+const makeInput = (overrides: Partial<VMwareFailureInput> = {}): VMwareFailureInput => ({
+ fallback: 'Fallback message',
+ ...overrides,
+});
+
+// ---- normalizeOptionalText (private) ---------------------------------------
+//
+// `normalizeOptionalText = (value) => { const trimmed = value?.trim(); return trimmed ? trimmed : undefined; }`
+// Branches:
+// (a) value is null/undefined -> `?.` short-circuits, trimmed is undefined, ternary falsy -> undefined
+// (b) value is a non-empty string -> `.trim()` invoked, result non-empty, ternary truthy -> trimmed value
+// (c) value is whitespace-only -> `.trim()` invoked, result '' empty, ternary falsy -> undefined
+// (d) value is '' empty string -> `.trim()` invoked, result '' empty, ternary falsy -> undefined
+// All four are observable through the builder's `code` / `category` / `message` fields.
+
+describe('normalizeOptionalText (private) via buildVMwareConnectionFailurePresentation', () => {
+ it('short-circuits the optional chain for an undefined value (code -> undefined)', () => {
+ const out = buildVMwareConnectionFailurePresentation(makeInput({ code: undefined }));
+ expect(out.code).toBeUndefined();
+ });
+
+ it('short-circuits the optional chain for a null value (category -> undefined, routes to switch default)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ category: null, code: 'irrelevant_code' }),
+ );
+ expect(out.category).toBeUndefined();
+ // category undefined hits the switch `default` arm, code is not the magic
+ // value, so the final-return defaults are observed.
+ expect(out.title).toBe('VMware connection test failed');
+ expect(out.tone).toBe('danger');
+ });
+
+ it('trims a non-empty padded string and returns the trimmed value for code', () => {
+ const out = buildVMwareConnectionFailurePresentation(makeInput({ code: ' AUTH_001 ' }));
+ expect(out.code).toBe('AUTH_001');
+ });
+
+ it('returns undefined for a whitespace-only code (trim() -> "" -> falsy ternary)', () => {
+ const out = buildVMwareConnectionFailurePresentation(makeInput({ code: ' \t ' }));
+ expect(out.code).toBeUndefined();
+ });
+
+ it('returns undefined for an empty-string code', () => {
+ const out = buildVMwareConnectionFailurePresentation(makeInput({ code: '' }));
+ expect(out.code).toBeUndefined();
+ });
+
+ it('trims a padded category and routes the normalized value to the matching switch arm', () => {
+ const out = buildVMwareConnectionFailurePresentation(makeInput({ category: ' tls ' }));
+ expect(out.category).toBe('tls');
+ expect(out.title).toBe('TLS validation failed');
+ });
+});
+
+// ---- buildVMwareConnectionFailurePresentation: switch arms ------------------
+
+describe('buildVMwareConnectionFailurePresentation — each named category switch arm', () => {
+ it.each<{
+ category: NonNullable<VMwareFailureInput['category']>;
+ title: string;
+ tone: VMwareConnectionFailurePresentation['tone'];
+ guidance: string;
+ }>([
+ {
+ category: 'unsupported_version',
+ title: 'Unsupported vCenter version',
+ tone: 'warning',
+ guidance:
+ 'Use a supported vCenter release within the current VI JSON phase-1 floor, then retry this connection test.',
+ },
+ {
+ category: 'tls',
+ title: 'TLS validation failed',
+ tone: 'warning',
+ guidance:
+ 'Install a trusted certificate for vCenter, or enable Skip TLS verification only for controlled lab environments.',
+ },
+ {
+ category: 'auth',
+ title: 'Authentication failed',
+ tone: 'danger',
+ guidance: 'Verify the username, password, and account scope in vCenter before retrying.',
+ },
+ {
+ category: 'permission',
+ title: 'Permissions are insufficient',
+ tone: 'warning',
+ guidance:
+ 'Grant the minimum VMware read privileges required for phase-1 inventory and health reads, then retry.',
+ },
+ {
+ category: 'network',
+ title: 'Pulse could not reach vCenter',
+ tone: 'danger',
+ guidance:
+ 'Confirm DNS, reachability, port 443, and any firewall rules from the Pulse server to vCenter.',
+ },
+ ])(
+ 'returns the exact presentation for category "$category"',
+ ({ category, title, tone, guidance }) => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ code: 'CODE_1', category, message: 'Real message' }),
+ );
+ expect(out).toStrictEqual({
+ code: 'CODE_1',
+ category,
+ guidance,
+ message: 'Real message',
+ title,
+ tone,
+ });
+ },
+ );
+
+ it('passes the normalized code/category/message through verbatim for a known category', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ code: ' NET_503 ', category: ' network ', message: ' timed out ' }),
+ );
+ expect(out).toStrictEqual({
+ code: 'NET_503',
+ category: 'network',
+ guidance:
+ 'Confirm DNS, reachability, port 443, and any firewall rules from the Pulse server to vCenter.',
+ message: 'timed out',
+ title: 'Pulse could not reach vCenter',
+ tone: 'danger',
+ });
+ });
+});
+
+// ---- buildVMwareConnectionFailurePresentation: switch default fall-through --
+//
+// A category that is not one of the five named values (including the
+// normalized-undefined case) falls through the switch's `default -> break`
+// and continues to the `vmware_invalid_config` guard / final return.
+
+describe('buildVMwareConnectionFailurePresentation — switch default fall-through', () => {
+ it('falls through the switch for an unknown category string', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ category: 'unknown_blob', code: 'CODE_X' }),
+ );
+ expect(out.category).toBe('unknown_blob');
+ // code is not the magic value -> final return with defaults.
+ expect(out.title).toBe('VMware connection test failed');
+ expect(out.tone).toBe('danger');
+ expect(out.guidance).toBe(
+ 'Review the vCenter endpoint and credentials, then retry the connection test.',
+ );
+ });
+});
+
+// ---- buildVMwareConnectionFailurePresentation: vmware_invalid_config guard --
+
+describe('buildVMwareConnectionFailurePresentation — vmware_invalid_config code guard', () => {
+ it('returns the invalid-config presentation when the normalized code matches (guard true arm)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ code: 'vmware_invalid_config', category: 'unknown_blob' }),
+ );
+ expect(out).toStrictEqual({
+ code: 'vmware_invalid_config',
+ category: 'unknown_blob',
+ guidance: 'Review the host, port, username, and password fields before retrying.',
+ message: 'Fallback message',
+ title: 'Connection configuration is invalid',
+ tone: 'danger',
+ });
+ });
+
+ it('trims the code before comparing against the magic value', () => {
+ // normalizeOptionalText trims first, so ' vmware_invalid_config ' still
+ // satisfies the guard.
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ code: ' vmware_invalid_config ', category: 'mystery' }),
+ );
+ expect(out.code).toBe('vmware_invalid_config');
+ expect(out.title).toBe('Connection configuration is invalid');
+ });
+
+ it('skips the guard when the code is some other value (guard false arm -> final return)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ code: 'some_other_code', category: 'mystery' }),
+ );
+ expect(out.title).toBe('VMware connection test failed');
+ expect(out.tone).toBe('danger');
+ });
+});
+
+// ---- buildVMwareConnectionFailurePresentation: message ?? fallback ----------
+
+describe('buildVMwareConnectionFailurePresentation — message ?? fallback', () => {
+ it('uses the normalized message when it is a non-empty string (?? left operand)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ category: 'tls', message: ' vCenter rejected the cert ', fallback: 'Unused' }),
+ );
+ expect(out.message).toBe('vCenter rejected the cert');
+ });
+
+ it('falls back to input.fallback when message is null (?? right operand)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ category: 'tls', message: null, fallback: 'Fallback message' }),
+ );
+ expect(out.message).toBe('Fallback message');
+ });
+
+ it('falls back to input.fallback when message is undefined', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ category: 'tls', message: undefined, fallback: 'Fallback message' }),
+ );
+ expect(out.message).toBe('Fallback message');
+ });
+
+ it('falls back to input.fallback when message is empty (normalizeOptionalText -> undefined)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ category: 'tls', message: ' ', fallback: 'Fallback message' }),
+ );
+ expect(out.message).toBe('Fallback message');
+ });
+});
+
+// ---- buildVMwareConnectionFailurePresentation: final-return default* ?? ----
+//
+// The final return uses three nullish coalescences:
+// guidance: input.defaultGuidance ?? '<hardcoded>'
+// title: input.defaultTitle ?? '<hardcoded>'
+// tone: input.defaultTone ?? 'danger'
+
+describe('buildVMwareConnectionFailurePresentation — final-return default* coalescences', () => {
+ it('uses the hardcoded defaults when none of defaultGuidance/defaultTitle/defaultTone is supplied (all ?? right operands)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({ category: 'mystery', code: 'CODE_Y' }),
+ );
+ expect(out).toStrictEqual({
+ code: 'CODE_Y',
+ category: 'mystery',
+ guidance:
+ 'Review the vCenter endpoint and credentials, then retry the connection test.',
+ message: 'Fallback message',
+ title: 'VMware connection test failed',
+ tone: 'danger',
+ });
+ });
+
+ it('honours caller-supplied defaultGuidance/defaultTitle/defaultTone (all ?? left operands)', () => {
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({
+ category: 'mystery',
+ code: 'CODE_Z',
+ defaultGuidance: 'Custom guidance body.',
+ defaultTitle: 'Custom title',
+ defaultTone: 'warning',
+ }),
+ );
+ expect(out).toStrictEqual({
+ code: 'CODE_Z',
+ category: 'mystery',
+ guidance: 'Custom guidance body.',
+ message: 'Fallback message',
+ title: 'Custom title',
+ tone: 'warning',
+ });
+ });
+
+ it('treats empty-string default* values as present (?? is nullish, not falsy)', () => {
+ // '' is not null/undefined, so the left operand wins even though it is falsy.
+ const out = buildVMwareConnectionFailurePresentation(
+ makeInput({
+ category: 'mystery',
+ code: 'CODE_W',
+ defaultGuidance: '',
+ defaultTitle: '',
+ }),
+ );
+ expect(out.guidance).toBe('');
+ expect(out.title).toBe('');
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadFilterConfigModel.branchcov0712.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadFilterConfigModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..e8d2dabf4e
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadFilterConfigModel.branchcov0712.test.ts
@@ -0,0 +1,475 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ buildWorkloadsClusterFilterConfig,
+ buildWorkloadsContainerRuntimeFilterConfig,
+ buildWorkloadsHostFilterConfig,
+ buildWorkloadsNamespaceFilterConfig,
+ buildWorkloadsPlatformFilterConfig,
+ WORKLOADS_CLUSTER_ALL_OPTION_LABEL,
+ WORKLOADS_CONTAINER_RUNTIME_ALL_OPTION_LABEL,
+ WORKLOADS_KUBERNETES_CONTEXT_ALL_OPTION_LABEL,
+ WORKLOADS_KUBERNETES_CONTEXT_FILTER_LABEL,
+ WORKLOADS_NAMESPACE_ALL_OPTION_LABEL,
+ WORKLOADS_NODE_ALL_OPTION_LABEL,
+ WORKLOADS_PLATFORM_ALL_OPTION_LABEL,
+} from '../workloadFilterConfigModel';
+
+describe('workloadFilterConfigModel branch coverage', () => {
+ describe('buildWorkloadsContainerRuntimeFilterConfig', () => {
+ it('returns undefined when off the workloads route and embedded scope filters are disallowed', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsContainerRuntimeFilterConfig({
+ isWorkloadsRoute: false,
+ viewMode: 'container',
+ containerRuntime: 'docker',
+ runtimeOptions: ['docker', 'podman'],
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for non-container view modes even on the workloads route', () => {
+ const onChange = vi.fn();
+
+ for (const viewMode of ['pod', 'all', 'vm'] as const) {
+ expect(
+ buildWorkloadsContainerRuntimeFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode,
+ containerRuntime: 'docker',
+ runtimeOptions: ['docker', 'podman'],
+ onChange,
+ }),
+ ).toBeUndefined();
+ }
+ });
+
+ it('returns undefined when fewer than two runtime options are available', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsContainerRuntimeFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode: 'container',
+ containerRuntime: 'docker',
+ runtimeOptions: [],
+ onChange,
+ }),
+ ).toBeUndefined();
+
+ expect(
+ buildWorkloadsContainerRuntimeFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode: 'container',
+ containerRuntime: 'docker',
+ runtimeOptions: ['docker'],
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('builds a full runtime config for the system-container view mode', () => {
+ const onChange = vi.fn();
+
+ const result = buildWorkloadsContainerRuntimeFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode: 'system-container',
+ containerRuntime: 'podman',
+ runtimeOptions: ['docker', 'podman'],
+ onChange,
+ });
+
+ expect(result).toEqual({
+ id: 'workloads-container-runtime-filter',
+ label: 'Runtime',
+ value: 'podman',
+ options: [
+ { value: '', label: WORKLOADS_CONTAINER_RUNTIME_ALL_OPTION_LABEL },
+ { value: 'docker', label: 'docker' },
+ { value: 'podman', label: 'podman' },
+ ],
+ onChange,
+ });
+ expect(result?.onChange).toBe(onChange);
+ });
+ });
+
+ describe('buildWorkloadsPlatformFilterConfig', () => {
+ it('returns undefined when off the workloads route and embedded scope filters are disallowed', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsPlatformFilterConfig({
+ isWorkloadsRoute: false,
+ selectedPlatform: 'docker',
+ platformOptions: [{ value: 'docker', label: 'Docker' }],
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined when no platform options are available', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsPlatformFilterConfig({
+ isWorkloadsRoute: true,
+ selectedPlatform: 'docker',
+ platformOptions: [],
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for a single platform option with a blank selection', () => {
+ const onChange = vi.fn();
+ const singleOption = [{ value: 'docker', label: 'Docker' }];
+
+ expect(
+ buildWorkloadsPlatformFilterConfig({
+ isWorkloadsRoute: true,
+ selectedPlatform: null,
+ platformOptions: singleOption,
+ onChange,
+ }),
+ ).toBeUndefined();
+
+ expect(
+ buildWorkloadsPlatformFilterConfig({
+ isWorkloadsRoute: true,
+ selectedPlatform: ' ',
+ platformOptions: singleOption,
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('builds a config for a single platform option when a selection is present', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsPlatformFilterConfig({
+ isWorkloadsRoute: true,
+ selectedPlatform: 'docker',
+ platformOptions: [{ value: 'docker', label: 'Docker' }],
+ onChange,
+ }),
+ ).toEqual({
+ id: 'workloads-platform-filter',
+ label: 'Platform',
+ value: 'docker',
+ options: [
+ { value: '', label: WORKLOADS_PLATFORM_ALL_OPTION_LABEL },
+ { value: 'docker', label: 'Docker' },
+ ],
+ onChange,
+ });
+ });
+
+ it('builds a config via embedded scope, coercing a null platform to an empty value', () => {
+ const onChange = vi.fn();
+
+ const result = buildWorkloadsPlatformFilterConfig({
+ isWorkloadsRoute: false,
+ allowEmbeddedScopeFilters: true,
+ selectedPlatform: null,
+ platformOptions: [
+ { value: 'docker', label: 'Docker' },
+ { value: 'truenas', label: 'TrueNAS' },
+ ],
+ onChange,
+ });
+
+ expect(result).toEqual({
+ id: 'workloads-platform-filter',
+ label: 'Platform',
+ value: '',
+ options: [
+ { value: '', label: WORKLOADS_PLATFORM_ALL_OPTION_LABEL },
+ { value: 'docker', label: 'Docker' },
+ { value: 'truenas', label: 'TrueNAS' },
+ ],
+ onChange,
+ });
+ expect(result?.onChange).toBe(onChange);
+ });
+ });
+
+ describe('buildWorkloadsHostFilterConfig', () => {
+ it('returns undefined when off the workloads route and embedded scope filters are disallowed', () => {
+ const onContextChange = vi.fn();
+ const onNodeChange = vi.fn();
+
+ expect(
+ buildWorkloadsHostFilterConfig({
+ isWorkloadsRoute: false,
+ viewMode: 'vm',
+ selectedKubernetesContext: null,
+ kubernetesContextOptions: [],
+ selectedNode: 'node-a',
+ workloadNodeOptions: [{ value: 'node-a', label: 'node-a' }],
+ onContextChange,
+ onNodeChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('builds a kubernetes context config with a null context and empty options for pod view mode', () => {
+ const onContextChange = vi.fn();
+ const onNodeChange = vi.fn();
+
+ const result = buildWorkloadsHostFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode: 'pod',
+ selectedKubernetesContext: null,
+ kubernetesContextOptions: [],
+ selectedNode: 'ignored',
+ workloadNodeOptions: [{ value: 'ignored', label: 'ignored' }],
+ onContextChange,
+ onNodeChange,
+ });
+
+ expect(result).toEqual({
+ id: 'workloads-k8s-context-filter',
+ label: WORKLOADS_KUBERNETES_CONTEXT_FILTER_LABEL,
+ value: '',
+ options: [{ value: '', label: WORKLOADS_KUBERNETES_CONTEXT_ALL_OPTION_LABEL }],
+ onChange: onContextChange,
+ });
+ expect(result?.onChange).toBe(onContextChange);
+ });
+
+ it('builds a node config with a null node and empty options for non-pod view modes', () => {
+ const onContextChange = vi.fn();
+ const onNodeChange = vi.fn();
+
+ const result = buildWorkloadsHostFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode: 'container',
+ selectedKubernetesContext: 'ignored',
+ kubernetesContextOptions: ['ignored'],
+ selectedNode: null,
+ workloadNodeOptions: [],
+ onContextChange,
+ onNodeChange,
+ });
+
+ expect(result).toEqual({
+ id: 'workloads-node-filter',
+ label: 'Node',
+ value: '',
+ options: [{ value: '', label: WORKLOADS_NODE_ALL_OPTION_LABEL }],
+ onChange: onNodeChange,
+ });
+ expect(result?.onChange).toBe(onNodeChange);
+ });
+
+ it('builds configs via embedded scope for both pod and node view modes', () => {
+ const onContextChange = vi.fn();
+ const onNodeChange = vi.fn();
+
+ const podResult = buildWorkloadsHostFilterConfig({
+ isWorkloadsRoute: false,
+ allowEmbeddedScopeFilters: true,
+ viewMode: 'pod',
+ selectedKubernetesContext: 'ctx-a',
+ kubernetesContextOptions: ['ctx-a'],
+ selectedNode: null,
+ workloadNodeOptions: [],
+ onContextChange,
+ onNodeChange,
+ });
+
+ expect(podResult).toEqual({
+ id: 'workloads-k8s-context-filter',
+ label: WORKLOADS_KUBERNETES_CONTEXT_FILTER_LABEL,
+ value: 'ctx-a',
+ options: [
+ { value: '', label: WORKLOADS_KUBERNETES_CONTEXT_ALL_OPTION_LABEL },
+ { value: 'ctx-a', label: 'ctx-a' },
+ ],
+ onChange: onContextChange,
+ });
+
+ const nodeResult = buildWorkloadsHostFilterConfig({
+ isWorkloadsRoute: false,
+ allowEmbeddedScopeFilters: true,
+ viewMode: 'vm',
+ selectedKubernetesContext: null,
+ kubernetesContextOptions: [],
+ selectedNode: 'node-1',
+ workloadNodeOptions: [{ value: 'node-1', label: 'node-1' }],
+ onContextChange,
+ onNodeChange,
+ });
+
+ expect(nodeResult).toEqual({
+ id: 'workloads-node-filter',
+ label: 'Node',
+ value: 'node-1',
+ options: [
+ { value: '', label: WORKLOADS_NODE_ALL_OPTION_LABEL },
+ { value: 'node-1', label: 'node-1' },
+ ],
+ onChange: onNodeChange,
+ });
+ });
+ });
+
+ describe('buildWorkloadsNamespaceFilterConfig', () => {
+ it('returns undefined when off the workloads route and embedded scope filters are disallowed', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsNamespaceFilterConfig({
+ isWorkloadsRoute: false,
+ viewMode: 'pod',
+ selectedNamespace: 'default',
+ namespaceOptions: ['default'],
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for non-pod view modes', () => {
+ const onChange = vi.fn();
+
+ for (const viewMode of ['vm', 'container', 'all'] as const) {
+ expect(
+ buildWorkloadsNamespaceFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode,
+ selectedNamespace: 'default',
+ namespaceOptions: ['default', 'kube-system'],
+ onChange,
+ }),
+ ).toBeUndefined();
+ }
+ });
+
+ it('builds a config via embedded scope, coercing a null namespace to an empty value', () => {
+ const onChange = vi.fn();
+
+ const result = buildWorkloadsNamespaceFilterConfig({
+ isWorkloadsRoute: false,
+ allowEmbeddedScopeFilters: true,
+ viewMode: 'pod',
+ selectedNamespace: null,
+ namespaceOptions: ['default', 'kube-system'],
+ onChange,
+ });
+
+ expect(result).toEqual({
+ id: 'workloads-k8s-namespace-filter',
+ label: 'Namespace',
+ value: '',
+ options: [
+ { value: '', label: WORKLOADS_NAMESPACE_ALL_OPTION_LABEL },
+ { value: 'default', label: 'default' },
+ { value: 'kube-system', label: 'kube-system' },
+ ],
+ onChange,
+ });
+ expect(result?.onChange).toBe(onChange);
+ });
+ });
+
+ describe('buildWorkloadsClusterFilterConfig', () => {
+ it('returns undefined when off the workloads route and embedded scope filters are disallowed', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsClusterFilterConfig({
+ isWorkloadsRoute: false,
+ viewMode: 'vm',
+ selectedCluster: 'cluster-a',
+ clusterOptions: ['cluster-a'],
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined for non-vm view modes', () => {
+ const onChange = vi.fn();
+
+ for (const viewMode of ['pod', 'container', 'all'] as const) {
+ expect(
+ buildWorkloadsClusterFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode,
+ selectedCluster: 'cluster-a',
+ clusterOptions: ['cluster-a', 'cluster-b'],
+ onChange,
+ }),
+ ).toBeUndefined();
+ }
+ });
+
+ it('returns undefined when no cluster options are available', () => {
+ const onChange = vi.fn();
+
+ expect(
+ buildWorkloadsClusterFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode: 'vm',
+ selectedCluster: 'cluster-a',
+ clusterOptions: [],
+ onChange,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('builds a full cluster config for vm view mode, coercing a null cluster to an empty value', () => {
+ const onChange = vi.fn();
+
+ const result = buildWorkloadsClusterFilterConfig({
+ isWorkloadsRoute: true,
+ viewMode: 'vm',
+ selectedCluster: null,
+ clusterOptions: ['cluster-a', 'cluster-b'],
+ onChange,
+ });
+
+ expect(result).toEqual({
+ id: 'workloads-vmware-cluster-filter',
+ label: 'Cluster',
+ value: '',
+ options: [
+ { value: '', label: WORKLOADS_CLUSTER_ALL_OPTION_LABEL },
+ { value: 'cluster-a', label: 'cluster-a' },
+ { value: 'cluster-b', label: 'cluster-b' },
+ ],
+ onChange,
+ });
+ expect(result?.onChange).toBe(onChange);
+ });
+
+ it('builds a cluster config via embedded scope', () => {
+ const onChange = vi.fn();
+
+ const result = buildWorkloadsClusterFilterConfig({
+ isWorkloadsRoute: false,
+ allowEmbeddedScopeFilters: true,
+ viewMode: 'vm',
+ selectedCluster: 'cluster-a',
+ clusterOptions: ['cluster-a'],
+ onChange,
+ });
+
+ expect(result).toEqual({
+ id: 'workloads-vmware-cluster-filter',
+ label: 'Cluster',
+ value: 'cluster-a',
+ options: [
+ { value: '', label: WORKLOADS_CLUSTER_ALL_OPTION_LABEL },
+ { value: 'cluster-a', label: 'cluster-a' },
+ ],
+ onChange,
+ });
+ expect(result?.onChange).toBe(onChange);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/shared/__tests__/buttonModel.branchcov0712.test.ts b/frontend-modern/src/components/shared/__tests__/buttonModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..27cb8e1744
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/buttonModel.branchcov0712.test.ts
@@ -0,0 +1,406 @@
+import { describe, expect, it } from 'vitest';
+import {
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES,
+ BUTTON_SIZE_CLASSES,
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES,
+ COPY_VALUE_BUTTON_SIZE_CLASSES,
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES,
+ ACTION_ICON_BUTTON_SIZE_CLASSES,
+ getButtonClass,
+ getCopyValueButtonClass,
+ getActionIconButtonClass,
+} from '@/components/shared/buttonModel';
+import type {
+ ButtonVariant,
+ ButtonSize,
+ CopyValueButtonVariant,
+ CopyValueButtonSize,
+ ActionIconButtonTone,
+ ActionIconButtonSize,
+} from '@/components/shared/buttonModel';
+
+describe('buttonModel.branchcov2', () => {
+ describe('getButtonClass', () => {
+ it('uses the default parameter when called with no arguments (variant=secondary, size=md)', () => {
+ // Drives the `options: ButtonClassOptions = {}` default-parameter arm
+ // and both `??` right arms (variant -> 'secondary', size -> 'md').
+ expect(getButtonClass()).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.secondary,
+ BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('uses the ?? right arms for variant and size when called with an empty options object', () => {
+ expect(getButtonClass({})).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.secondary,
+ BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('selects the explicit variant and size when provided (?? left arms)', () => {
+ expect(
+ getButtonClass({ variant: 'primary', size: 'lg' }),
+ ).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.primary,
+ BUTTON_SIZE_CLASSES.lg,
+ ].join(' '),
+ );
+ });
+
+ it.each<ButtonVariant>([
+ 'primary',
+ 'primaryFlat',
+ 'warning',
+ 'warningSolid',
+ 'info',
+ 'success',
+ 'successOutline',
+ 'successGhost',
+ 'secondary',
+ 'danger',
+ 'dangerOutline',
+ 'dangerGhost',
+ 'ghost',
+ 'outline',
+ ])('resolves the %s variant from BUTTON_VARIANT_CLASSES', (variant) => {
+ expect(getButtonClass({ variant })).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES[variant],
+ BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it.each<ButtonSize>([
+ 'xs',
+ 'sm',
+ 'mdCompact',
+ 'settingsAction',
+ 'settingsActionXs',
+ 'md',
+ 'lg',
+ 'icon',
+ 'iconMd',
+ ])('resolves the %s size from BUTTON_SIZE_CLASSES', (size) => {
+ expect(getButtonClass({ size })).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.secondary,
+ BUTTON_SIZE_CLASSES[size],
+ ].join(' '),
+ );
+ });
+
+ it('appends options.class verbatim when it is a non-empty string', () => {
+ expect(getButtonClass({ class: 'mt-4 w-full' })).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.secondary,
+ BUTTON_SIZE_CLASSES.md,
+ 'mt-4 w-full',
+ ].join(' '),
+ );
+ });
+
+ it('drops an empty-string options.class via .filter(Boolean)', () => {
+ // Defensive branch: empty string is falsy and must not contribute a
+ // trailing space to the joined output.
+ expect(getButtonClass({ class: '' })).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.secondary,
+ BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('drops an unknown variant lookup (undefined) via .filter(Boolean)', () => {
+ // Defensive branch: a malformed variant key resolves to undefined in the
+ // Record lookup at runtime; filter(Boolean) must remove it so no stray
+ // 'undefined' token or double space appears.
+ const bogus = 'not-a-real-variant' as unknown as ButtonVariant;
+ expect(getButtonClass({ variant: bogus })).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('drops an unknown size lookup (undefined) via .filter(Boolean)', () => {
+ const bogus = 'not-a-real-size' as unknown as ButtonSize;
+ expect(getButtonClass({ size: bogus })).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.secondary,
+ ].join(' '),
+ );
+ });
+
+ it('combines an explicit variant, size, and class together', () => {
+ expect(
+ getButtonClass({ variant: 'danger', size: 'icon', class: 'rounded-full' }),
+ ).toBe(
+ [
+ BUTTON_BASE_CLASS,
+ BUTTON_VARIANT_CLASSES.danger,
+ BUTTON_SIZE_CLASSES.icon,
+ 'rounded-full',
+ ].join(' '),
+ );
+ });
+ });
+
+ describe('getCopyValueButtonClass', () => {
+ it('uses the default parameter when called with no arguments (variant=neutral, size=md)', () => {
+ // `options = {}` default-parameter arm + both `??` right arms.
+ expect(getCopyValueButtonClass()).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.neutral,
+ COPY_VALUE_BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('uses the ?? right arms when called with an empty options object', () => {
+ expect(getCopyValueButtonClass({})).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.neutral,
+ COPY_VALUE_BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('selects the explicit variant and size when provided (?? left arms)', () => {
+ expect(
+ getCopyValueButtonClass({ variant: 'accent', size: 'sm' }),
+ ).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.accent,
+ COPY_VALUE_BUTTON_SIZE_CLASSES.sm,
+ ].join(' '),
+ );
+ });
+
+ it.each<CopyValueButtonVariant>(['neutral', 'ghost', 'accent', 'chip'])(
+ 'resolves the %s variant from COPY_VALUE_BUTTON_VARIANT_CLASSES',
+ (variant) => {
+ expect(getCopyValueButtonClass({ variant })).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES[variant],
+ COPY_VALUE_BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ },
+ );
+
+ it.each<CopyValueButtonSize>(['xs', 'sm', 'md', 'lg', 'chip'])(
+ 'resolves the %s size from COPY_VALUE_BUTTON_SIZE_CLASSES',
+ (size) => {
+ expect(getCopyValueButtonClass({ size })).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.neutral,
+ COPY_VALUE_BUTTON_SIZE_CLASSES[size],
+ ].join(' '),
+ );
+ },
+ );
+
+ it('appends options.class verbatim when it is a non-empty string', () => {
+ expect(getCopyValueButtonClass({ class: 'ml-1' })).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.neutral,
+ COPY_VALUE_BUTTON_SIZE_CLASSES.md,
+ 'ml-1',
+ ].join(' '),
+ );
+ });
+
+ it('drops an empty-string options.class via .filter(Boolean)', () => {
+ expect(getCopyValueButtonClass({ class: '' })).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.neutral,
+ COPY_VALUE_BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('drops an unknown variant lookup (undefined) via .filter(Boolean)', () => {
+ const bogus = 'nope' as unknown as CopyValueButtonVariant;
+ expect(getCopyValueButtonClass({ variant: bogus })).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it('drops an unknown size lookup (undefined) via .filter(Boolean)', () => {
+ const bogus = 'xl' as unknown as CopyValueButtonSize;
+ expect(getCopyValueButtonClass({ size: bogus })).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.neutral,
+ ].join(' '),
+ );
+ });
+
+ it('combines an explicit variant, size, and class together', () => {
+ expect(
+ getCopyValueButtonClass({ variant: 'chip', size: 'chip', class: 'tag-cls' }),
+ ).toBe(
+ [
+ COPY_VALUE_BUTTON_BASE_CLASS,
+ COPY_VALUE_BUTTON_VARIANT_CLASSES.chip,
+ COPY_VALUE_BUTTON_SIZE_CLASSES.chip,
+ 'tag-cls',
+ ].join(' '),
+ );
+ });
+ });
+
+ describe('getActionIconButtonClass', () => {
+ it('uses the default parameter when called with no arguments (tone=neutral, size=sm)', () => {
+ // `options = {}` default-parameter arm + both `??` right arms
+ // (tone -> 'neutral', size -> 'sm').
+ expect(getActionIconButtonClass()).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.neutral,
+ ACTION_ICON_BUTTON_SIZE_CLASSES.sm,
+ ].join(' '),
+ );
+ });
+
+ it('uses the ?? right arms when called with an empty options object', () => {
+ expect(getActionIconButtonClass({})).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.neutral,
+ ACTION_ICON_BUTTON_SIZE_CLASSES.sm,
+ ].join(' '),
+ );
+ });
+
+ it('selects the explicit tone and size when provided (?? left arms)', () => {
+ expect(
+ getActionIconButtonClass({ tone: 'primary', size: 'md' }),
+ ).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.primary,
+ ACTION_ICON_BUTTON_SIZE_CLASSES.md,
+ ].join(' '),
+ );
+ });
+
+ it.each<ActionIconButtonTone>([
+ 'neutral',
+ 'muted',
+ 'outline',
+ 'outlineSelected',
+ 'primary',
+ 'accent',
+ 'accentGhost',
+ 'success',
+ 'warningGhost',
+ 'warningOutline',
+ 'infoGhost',
+ 'danger',
+ ])('resolves the %s tone from ACTION_ICON_BUTTON_TONE_CLASSES', (tone) => {
+ expect(getActionIconButtonClass({ tone })).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES[tone],
+ ACTION_ICON_BUTTON_SIZE_CLASSES.sm,
+ ].join(' '),
+ );
+ });
+
+ it.each<ActionIconButtonSize>(['2xs', 'xs', 'sm', 'md', 'lg'])(
+ 'resolves the %s size from ACTION_ICON_BUTTON_SIZE_CLASSES',
+ (size) => {
+ expect(getActionIconButtonClass({ size })).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.neutral,
+ ACTION_ICON_BUTTON_SIZE_CLASSES[size],
+ ].join(' '),
+ );
+ },
+ );
+
+ it('appends options.class verbatim when it is a non-empty string', () => {
+ expect(getActionIconButtonClass({ class: 'self-end' })).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.neutral,
+ ACTION_ICON_BUTTON_SIZE_CLASSES.sm,
+ 'self-end',
+ ].join(' '),
+ );
+ });
+
+ it('drops an empty-string options.class via .filter(Boolean)', () => {
+ expect(getActionIconButtonClass({ class: '' })).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.neutral,
+ ACTION_ICON_BUTTON_SIZE_CLASSES.sm,
+ ].join(' '),
+ );
+ });
+
+ it('drops an unknown tone lookup (undefined) via .filter(Boolean)', () => {
+ const bogus = 'hyper' as unknown as ActionIconButtonTone;
+ expect(getActionIconButtonClass({ tone: bogus })).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_SIZE_CLASSES.sm,
+ ].join(' '),
+ );
+ });
+
+ it('drops an unknown size lookup (undefined) via .filter(Boolean)', () => {
+ const bogus = '3xl' as unknown as ActionIconButtonSize;
+ expect(getActionIconButtonClass({ size: bogus })).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.neutral,
+ ].join(' '),
+ );
+ });
+
+ it('combines an explicit tone, size, and class together', () => {
+ expect(
+ getActionIconButtonClass({ tone: 'danger', size: 'xs', class: 'ring-2' }),
+ ).toBe(
+ [
+ ACTION_ICON_BUTTON_BASE_CLASS,
+ ACTION_ICON_BUTTON_TONE_CLASSES.danger,
+ ACTION_ICON_BUTTON_SIZE_CLASSES.xs,
+ 'ring-2',
+ ].join(' '),
+ );
+ });
+ });
+});
diff --git a/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0712.test.ts b/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..164384562e
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0712.test.ts
@@ -0,0 +1,300 @@
+import { describe, expect, it } from 'vitest';
+import {
+ filterCommandPaletteCommands,
+ type CommandPaletteModalCommand,
+} from '@/components/shared/commandPaletteModel';
+
+// Branch-coverage suite focused on the still-uncovered
+// `filterCommandPaletteCommands` export of commandPaletteModel.ts. Every
+// assertion is a concrete equality/strict-equality check against the real
+// return shape so it pins the exact branch taken (no truthiness-only checks).
+//
+// Branch map under test:
+// 1. `if (!normalizedQuery) return commands` — empty/whitespace early-return.
+// Notably this returns the *same array reference* as the input.
+// 2. `command.description ?? ''` — present arm vs absent arm.
+// 3. `command.shortcut ?? ''` — present arm vs absent arm.
+// 4. `...(command.keywords ?? [])` — present arm (spread) vs absent arm.
+// 5. `return haystack.includes(normalizedQuery)` — match arm vs no-match arm.
+// 6. Query normalization: lowercase, trim, and internal-whitespace collapse
+// (delegated to `normalizeCommandPaletteQuery`).
+// 7. Haystack normalization: `.join(' ').toLowerCase().replace(/\s+/g, '')`
+// — internal whitespace is removed from the haystack too.
+
+function makeCommand(
+ overrides: Partial<CommandPaletteModalCommand> = {},
+): CommandPaletteModalCommand {
+ return {
+ id: 'cmd-1',
+ label: 'Go to Proxmox',
+ description: '/proxmox',
+ shortcut: 'g p',
+ keywords: ['proxmox', 'pve', 'backups'],
+ action: () => {},
+ ...overrides,
+ };
+}
+
+describe('commandPaletteModel.branchcov2', () => {
+ describe('filterCommandPaletteCommands', () => {
+ describe('empty-query early return (`!normalizedQuery` arm)', () => {
+ it('returns the exact same array reference for a literally empty query', () => {
+ const commands = [makeCommand()];
+ // The early `return commands` hands back the SAME array, not a copy.
+ expect(filterCommandPaletteCommands(commands, '')).toBe(commands);
+ });
+
+ it('returns the same array reference for a whitespace-only query (normalizes to empty)', () => {
+ const commands = [makeCommand(), makeCommand({ id: 'cmd-2' })];
+ // ' ' -> normalizeCommandPaletteQuery -> '' -> falsy -> early return.
+ expect(filterCommandPaletteCommands(commands, ' ')).toBe(commands);
+ });
+
+ it('returns the same array reference for a query that is only internal whitespace + tabs/newlines', () => {
+ const commands = [makeCommand()];
+ // '\t \n' trims to '' and is therefore falsy.
+ expect(filterCommandPaletteCommands(commands, '\t \n')).toBe(commands);
+ });
+
+ it('returns the full input unchanged (contents identical) when query is empty', () => {
+ const commands = [
+ makeCommand({ id: 'a' }),
+ makeCommand({ id: 'b' }),
+ makeCommand({ id: 'c' }),
+ ];
+ const result = filterCommandPaletteCommands(commands, '');
+ expect(result).toStrictEqual(commands);
+ expect(result.map((c) => c.id)).toStrictEqual(['a', 'b', 'c']);
+ });
+ });
+
+ describe('`description ?? ""` arm', () => {
+ it('matches a query that only appears in description when description is present', () => {
+ // description '/proxmox' is the only field containing the substring.
+ const command = makeCommand({
+ label: 'Unrelated Label',
+ shortcut: 'x y',
+ keywords: ['nothing', 'here'],
+ description: '/unique-desc-token',
+ });
+ const result = filterCommandPaletteCommands([command], '/unique-desc-token');
+ expect(result).toStrictEqual([command]);
+ });
+
+ it('does NOT leak "undefined" into the haystack when description is absent', () => {
+ // If the `?? ''` arm were broken (e.g. raw `command.description`), the
+ // string 'undefined' would appear in the haystack and a query of
+ // 'undefined' would falsely match. Pin the absent-description arm.
+ const command: CommandPaletteModalCommand = {
+ id: 'no-desc',
+ label: 'Go to Docker',
+ shortcut: 'g d',
+ keywords: ['docker'],
+ action: () => {},
+ // description intentionally omitted
+ };
+ const result = filterCommandPaletteCommands([command], 'undefined');
+ expect(result).toStrictEqual([]);
+ });
+ });
+
+ describe('`shortcut ?? ""` arm', () => {
+ it('matches a query that only appears in shortcut when shortcut is present', () => {
+ // After normalization both query 'gp' and haystack collapse the
+ // shortcut 'g p' into 'gp', so the substring matches there and only
+ // there (label/description/keywords avoid the literal 'gp' run).
+ const command = makeCommand({
+ label: 'Alpha',
+ description: 'beta',
+ keywords: ['gamma', 'delta'],
+ shortcut: 'g p',
+ });
+ const result = filterCommandPaletteCommands([command], 'gp');
+ expect(result).toStrictEqual([command]);
+ });
+
+ it('does NOT leak "undefined" into the haystack when shortcut is absent', () => {
+ const command: CommandPaletteModalCommand = {
+ id: 'no-shortcut',
+ label: 'Go to Kubernetes',
+ description: '/k8s',
+ keywords: ['k8s'],
+ action: () => {},
+ // shortcut intentionally omitted
+ };
+ const result = filterCommandPaletteCommands([command], 'undefined');
+ expect(result).toStrictEqual([]);
+ });
+ });
+
+ describe('`...(command.keywords ?? [])` arm', () => {
+ it('matches a query that only appears in a keyword when keywords are present', () => {
+ const command = makeCommand({
+ label: 'Alpha',
+ description: 'beta',
+ shortcut: 'g g',
+ keywords: ['gamma', 'delta', 'unique-kw-token'],
+ });
+ const result = filterCommandPaletteCommands([command], 'unique-kw-token');
+ expect(result).toStrictEqual([command]);
+ });
+
+ it('does NOT throw and does NOT match "undefined" when keywords are absent', () => {
+ // If the `?? []` arm were broken, spreading `undefined` would throw at
+ // runtime; if it coerced wrongly, 'undefined' would match. Pin both.
+ const command: CommandPaletteModalCommand = {
+ id: 'no-keywords',
+ label: 'Go to TrueNAS',
+ description: '/truenas',
+ shortcut: 'g n',
+ action: () => {},
+ // keywords intentionally omitted
+ };
+ const result = filterCommandPaletteCommands([command], 'undefined');
+ expect(result).toStrictEqual([]);
+ });
+
+ it('still matches on the label when keywords are absent (proves spread-of-empty is harmless)', () => {
+ const command: CommandPaletteModalCommand = {
+ id: 'no-keywords-2',
+ label: 'Go to TrueNAS',
+ description: '/truenas',
+ shortcut: 'g n',
+ action: () => {},
+ };
+ const result = filterCommandPaletteCommands([command], 'truenas');
+ expect(result).toStrictEqual([command]);
+ });
+ });
+
+ describe('match vs no-match arms of `haystack.includes`', () => {
+ it('returns an empty array when the query matches no command', () => {
+ const commands = [
+ makeCommand({ id: 'a' }),
+ makeCommand({ id: 'b', label: 'Go to Docker' }),
+ ];
+ const result = filterCommandPaletteCommands(commands, 'zzz-nope-zzz');
+ expect(result).toStrictEqual([]);
+ });
+
+ it('selects only the matching commands from a mixed input (filter subset arm)', () => {
+ const proxmox = makeCommand({ id: 'prox' });
+ const docker = makeCommand({ id: 'docker', label: 'Go to Docker' });
+ const k8s = makeCommand({
+ id: 'k8s',
+ label: 'Go to Kubernetes',
+ description: '/k8s',
+ shortcut: 'g k',
+ keywords: ['k8s'],
+ });
+ const result = filterCommandPaletteCommands(
+ [proxmox, docker, k8s],
+ 'docker',
+ );
+ expect(result).toStrictEqual([docker]);
+ });
+
+ it('preserves input order when multiple commands match', () => {
+ const a = makeCommand({ id: 'a', keywords: ['shared', 'alpha'] });
+ const b = makeCommand({ id: 'b', keywords: ['shared', 'beta'] });
+ const c = makeCommand({ id: 'c', keywords: ['unrelated'] });
+ const result = filterCommandPaletteCommands([a, b, c], 'shared');
+ expect(result).toStrictEqual([a, b]);
+ });
+
+ it('matches on the label substring', () => {
+ const command = makeCommand({ label: 'Go to Settings' });
+ const result = filterCommandPaletteCommands([command], 'settings');
+ expect(result).toStrictEqual([command]);
+ });
+ });
+
+ describe('query normalization (lowercase / trim / whitespace collapse)', () => {
+ it('matches case-insensitively (uppercase query vs lowercase haystack)', () => {
+ const command = makeCommand({ label: 'Go to Proxmox' });
+ // Query 'PROXMOX' -> normalize -> 'proxmox' -> matches label.
+ const result = filterCommandPaletteCommands([command], 'PROXMOX');
+ expect(result).toStrictEqual([command]);
+ });
+
+ it('collapses internal whitespace in the query before matching', () => {
+ const command = makeCommand({
+ label: 'Go to Proxmox',
+ description: '/proxmox',
+ shortcut: 'g p',
+ keywords: ['proxmox'],
+ });
+ // 'Go To' normalizes to 'goto'; the label haystack also collapses to
+ // 'gotopromox...' so 'goto' is a substring of the collapsed haystack.
+ const result = filterCommandPaletteCommands([command], 'Go To');
+ expect(result).toStrictEqual([command]);
+ });
+
+ it('trims leading/trailing whitespace from the query before matching', () => {
+ const command = makeCommand({ label: 'Go to Patrol' });
+ const result = filterCommandPaletteCommands([command], ' patrol ');
+ expect(result).toStrictEqual([command]);
+ });
+ });
+
+ describe('haystack whitespace collapse (`.join(" ").replace(/\\s+/g, "")` arm)', () => {
+ it('matches a query whose letters span the label after the label internal spaces are removed', () => {
+ // Label 'Go to Machines' -> haystack join -> 'go to machines...' ->
+ // whitespace stripped -> 'gotomachines...'. Query 'gotomachines' hits.
+ const command: CommandPaletteModalCommand = {
+ id: 'machines',
+ label: 'Go to Machines',
+ description: '/standalone',
+ shortcut: 'g s',
+ keywords: ['machines'],
+ action: () => {},
+ };
+ const result = filterCommandPaletteCommands([command], 'gotomachines');
+ expect(result).toStrictEqual([command]);
+ });
+
+ it('matches a multi-word keyword after internal whitespace collapse', () => {
+ // Keyword 'needs attention' contains a space; in the haystack it is
+ // joined then stripped to 'needsattention'.
+ const command: CommandPaletteModalCommand = {
+ id: 'patrol',
+ label: 'Go to Patrol',
+ description: '/patrol',
+ shortcut: 'g r',
+ keywords: ['needs attention', 'patrol'],
+ action: () => {},
+ };
+ // Query 'needsattention' only matches because the haystack strips the
+ // internal space inside the keyword.
+ const result = filterCommandPaletteCommands([command], 'needsattention');
+ expect(result).toStrictEqual([command]);
+ });
+ });
+
+ describe('combined: all optional fields populated on every command', () => {
+ it('uses the real values of all present fields (present-arms of every ??)', () => {
+ const commands: CommandPaletteModalCommand[] = [
+ {
+ id: 'full-1',
+ label: 'Go to vSphere',
+ description: '/vmware',
+ shortcut: 'g v',
+ keywords: ['vmware', 'vsphere', 'networks'],
+ action: () => {},
+ },
+ {
+ id: 'full-2',
+ label: 'Go to Alerts',
+ description: '/alerts',
+ shortcut: 'g a',
+ keywords: ['alarms', 'notifications'],
+ action: () => {},
+ },
+ ];
+ // Match against full-2 via its description-only token.
+ const result = filterCommandPaletteCommands(commands, '/alerts');
+ expect(result).toStrictEqual([commands[1]]);
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/components/shared/__tests__/statusBadgeModel.branchcov0712.test.ts b/frontend-modern/src/components/shared/__tests__/statusBadgeModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..df41f11d53
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/statusBadgeModel.branchcov0712.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+import type { StatusBadgeProps } from '@/components/shared/statusBadgeModel';
+import { getStatusBadgeTitle } from '@/components/shared/statusBadgeModel';
+
+// Minimal valid props; every optional title field defaults to undefined so each
+// test can populate only the ones it needs to drive a specific branch.
+function makeProps(overrides: Partial<StatusBadgeProps> = {}): StatusBadgeProps {
+ return {
+ isEnabled: false,
+ ...overrides,
+ };
+}
+
+describe('statusBadgeModel.branchcov2', () => {
+ describe('getStatusBadgeTitle', () => {
+ describe('disabled === true (first branch — three-level ?? cascade)', () => {
+ it('returns titleWhenDisabled when set (first ?? short-circuits)', () => {
+ const props = makeProps({
+ isEnabled: false,
+ titleWhenDisabled: 'Locked',
+ titleDisabled: 'Off',
+ titleEnabled: 'On',
+ });
+ expect(getStatusBadgeTitle(props, true)).toBe('Locked');
+ });
+
+ it('falls back to titleDisabled when titleWhenDisabled is absent (second ??)', () => {
+ const props = makeProps({
+ isEnabled: false,
+ titleDisabled: 'Off',
+ titleEnabled: 'On',
+ });
+ expect(getStatusBadgeTitle(props, true)).toBe('Off');
+ });
+
+ it('falls back to titleEnabled when titleWhenDisabled and titleDisabled are both absent (third ??)', () => {
+ const props = makeProps({
+ isEnabled: true,
+ titleEnabled: 'On',
+ });
+ expect(getStatusBadgeTitle(props, true)).toBe('On');
+ });
+
+ it('returns the empty string when none of the title fields are set (final ?? default)', () => {
+ const props = makeProps({ isEnabled: false });
+ expect(getStatusBadgeTitle(props, true)).toBe('');
+ });
+ });
+
+ describe('disabled === false (else branch — isEnabled ternary)', () => {
+ it('returns titleEnabled when isEnabled is true and titleEnabled is set', () => {
+ const props = makeProps({
+ isEnabled: true,
+ titleEnabled: 'On',
+ });
+ expect(getStatusBadgeTitle(props, false)).toBe('On');
+ });
+
+ it('returns the empty string when isEnabled is true but titleEnabled is absent (?? default)', () => {
+ const props = makeProps({ isEnabled: true });
+ expect(getStatusBadgeTitle(props, false)).toBe('');
+ });
+
+ it('returns titleDisabled when isEnabled is false and titleDisabled is set', () => {
+ const props = makeProps({
+ isEnabled: false,
+ titleDisabled: 'Off',
+ });
+ expect(getStatusBadgeTitle(props, false)).toBe('Off');
+ });
+
+ it('returns the empty string when isEnabled is false and titleDisabled is absent (?? default)', () => {
+ const props = makeProps({ isEnabled: false });
+ expect(getStatusBadgeTitle(props, false)).toBe('');
+ });
+
+ it('ignores titleWhenDisabled entirely on the !disabled branch', () => {
+ const props = makeProps({
+ isEnabled: true,
+ titleWhenDisabled: 'Locked',
+ titleEnabled: 'On',
+ });
+ expect(getStatusBadgeTitle(props, false)).toBe('On');
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/features/platformPage/__tests__/sensorSetup.branchcov0712.test.ts b/frontend-modern/src/features/platformPage/__tests__/sensorSetup.branchcov0712.test.ts
new file mode 100644
index 0000000000..9f2b1ecd91
--- /dev/null
+++ b/frontend-modern/src/features/platformPage/__tests__/sensorSetup.branchcov0712.test.ts
@@ -0,0 +1,206 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import { collectOutdatedSensorSetupNodes } from '../sensorSetup';
+
+// Branch-coverage tests for the two UNEXPORTED helpers inside sensorSetup.ts:
+// - getNodeName (3-way `||` fallback chain + `.trim()`)
+// - isSMARTOnlyDiskWithoutTemperature (no-meta guard, diskType normalize,
+// SMART-set membership, `temperature ?? 0`)
+// Both helpers are private, so every case drives them through the public
+// `collectOutdatedSensorSetupNodes` and asserts the concrete observable shape.
+//
+// Conventions mirror the sibling `sensorSetup.test.ts` fixtures. Disks are
+// linked to nodes either by `platformData.proxmox.nodeName` (the name-matching
+// path, used to prove `getNodeName` resolution) or by `parentId` (which makes
+// `matchesPhysicalDiskNode` short-circuit true, used to isolate the SMART-only
+// predicate from name resolution).
+
+type LegacyNodeOver = {
+ id?: string;
+ name?: string;
+ proxmox?: Partial<Resource['proxmox']>;
+};
+
+const legacyNode = (over: LegacyNodeOver = {}): Resource =>
+ ({
+ id: over.id ?? 'node-1',
+ name: over.name ?? '',
+ displayName: over.name ?? '',
+ type: 'node',
+ proxmox: {
+ temperatureDetails: { available: true, legacySensorsFormat: true },
+ ...(over.proxmox ?? {}),
+ },
+ }) as unknown as Resource;
+
+type DiskOver = {
+ id?: string;
+ parentId?: string;
+ nodeName?: string;
+ diskType?: string;
+ temperature?: number;
+ noMeta?: boolean;
+};
+
+const disk = (over: DiskOver = {}): Resource =>
+ ({
+ id: over.id ?? 'disk-1',
+ name: 'disk',
+ displayName: 'disk',
+ type: 'physical_disk',
+ parentId: over.parentId,
+ physicalDisk: over.noMeta
+ ? undefined
+ : {
+ diskType: over.diskType,
+ temperature: over.temperature,
+ },
+ platformData: over.nodeName ? { proxmox: { nodeName: over.nodeName } } : {},
+ }) as unknown as Resource;
+
+describe('getNodeName (via collectOutdatedSensorSetupNodes)', () => {
+ it('falls back to proxmox.nodeName when proxmox.node is absent', () => {
+ const node = legacyNode({ id: 'n-nodeName', proxmox: { nodeName: 'bravo' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ // Disk resolves to the node by the nodeName-derived identity, proving
+ // getNodeName returned 'bravo' (not '' and not node.name).
+ [disk({ id: 'd1', nodeName: 'bravo', diskType: 'sata', temperature: 0 })],
+ );
+ expect(result).toStrictEqual([{ id: 'n-nodeName', name: 'bravo' }]);
+ });
+
+ it('falls back to the resource name when both proxmox.node and nodeName are absent', () => {
+ const node = legacyNode({ id: 'n-name', name: 'charlie' });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({ id: 'd2', nodeName: 'charlie', diskType: 'sata', temperature: 0 })],
+ );
+ expect(result).toStrictEqual([{ id: 'n-name', name: 'charlie' }]);
+ });
+
+ it('trims surrounding whitespace from proxmox.node before using it as the node identity', () => {
+ const node = legacyNode({ id: 'n-trim', proxmox: { node: ' delta ' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ // matchesPhysicalDiskNode lowercases/trims both sides, so 'delta' must be
+ // the trimmed getNodeName output for the disk to match.
+ [disk({ id: 'd3', nodeName: 'delta', diskType: 'sata', temperature: 0 })],
+ );
+ expect(result).toStrictEqual([{ id: 'n-trim', name: 'delta' }]);
+ });
+
+ it('returns the empty string when every name source is blank, observable via a parentId-linked disk', () => {
+ // No proxmox.node, no proxmox.nodeName, name is whitespace -> getNodeName
+ // hits the final `|| ''` arm and trims to ''. The disk is matched by
+ // parentId so matchesPhysicalDiskNode short-circuits true regardless of the
+ // (empty) name, letting the flagged node surface with name: ''.
+ const node = legacyNode({ id: 'n-empty', name: ' ' });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({ id: 'd4', parentId: 'n-empty', diskType: 'sata', temperature: 0 })],
+ );
+ expect(result).toStrictEqual([{ id: 'n-empty', name: '' }]);
+ });
+});
+
+describe('isSMARTOnlyDiskWithoutTemperature (via collectOutdatedSensorSetupNodes)', () => {
+ it('returns false for a disk with no physicalDisk metadata, so the node is not flagged', () => {
+ // Disk is linked to the node by parentId (match guaranteed true); the only
+ // reason the node drops out is the `if (!meta) return false` guard.
+ const node = legacyNode({ id: 'n-nometa', proxmox: { node: 'pve' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({ id: 'd-nometa', parentId: 'n-nometa', noMeta: true })],
+ );
+ expect(result).toStrictEqual([]);
+ });
+
+ it('returns false when diskType is missing, so a matched disk does not flag the node', () => {
+ // diskType undefined -> `(meta.diskType || '')` -> '' not in the SMART-only
+ // set. parentId link isolates the cause to the diskType check.
+ const node = legacyNode({ id: 'n-notype', proxmox: { node: 'pve' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({ id: 'd-notype', parentId: 'n-notype', temperature: 0 })],
+ );
+ expect(result).toStrictEqual([]);
+ });
+
+ it('normalizes a whitespace-padded uppercase SAS diskType and flags the node', () => {
+ // Exercises `diskType.trim().toLowerCase()` -> 'sas' (in the SMART-only
+ // set) and temperature 0 -> `(0 ?? 0) <= 0` true.
+ const node = legacyNode({ id: 'n-sas', proxmox: { node: 'pve' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({
+ id: 'd-sas',
+ parentId: 'n-sas',
+ diskType: ' SAS ',
+ temperature: 0,
+ })],
+ );
+ expect(result).toStrictEqual([{ id: 'n-sas', name: 'pve' }]);
+ });
+
+ it('uses 0 in place of an undefined temperature and flags the node', () => {
+ // temperature is omitted entirely -> `(meta.temperature ?? 0)` takes the
+ // nullish right-hand side (0) -> `<= 0` true.
+ const node = legacyNode({ id: 'n-undef-temp', proxmox: { node: 'pve' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({ id: 'd-undef-temp', parentId: 'n-undef-temp', diskType: 'sata' })],
+ );
+ expect(result).toStrictEqual([{ id: 'n-undef-temp', name: 'pve' }]);
+ });
+
+ it('uses 0 in place of an explicit null temperature and flags the node', () => {
+ // Deliberately-malformed payload: temperature typed as number | undefined
+ // but carrying null. The `?? 0` coalesces it to 0 -> `<= 0` true.
+ const node = legacyNode({ id: 'n-null-temp', proxmox: { node: 'pve' } });
+ const nullTempDisk = {
+ id: 'd-null-temp',
+ name: 'disk',
+ displayName: 'disk',
+ type: 'physical_disk',
+ parentId: 'n-null-temp',
+ physicalDisk: { diskType: 'sata', temperature: null },
+ } as unknown as Resource;
+ const result = collectOutdatedSensorSetupNodes([node], [nullTempDisk]);
+ expect(result).toStrictEqual([{ id: 'n-null-temp', name: 'pve' }]);
+ });
+
+ it('flags the node for a SATA disk reporting a negative temperature', () => {
+ // Concrete negative value exercises the `<= 0` true arm (not the ?? arm).
+ const node = legacyNode({ id: 'n-neg-temp', proxmox: { node: 'pve' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({ id: 'd-neg-temp', parentId: 'n-neg-temp', diskType: 'sata', temperature: -5 })],
+ );
+ expect(result).toStrictEqual([{ id: 'n-neg-temp', name: 'pve' }]);
+ });
+
+ it('does not flag the node when a SMART-only disk reports a positive temperature', () => {
+ // SAS at 41 degrees -> `(41 ?? 0) <= 0` is false.
+ const node = legacyNode({ id: 'n-warm', proxmox: { node: 'pve' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [disk({ id: 'd-warm', parentId: 'n-warm', diskType: 'sas', temperature: 41 })],
+ );
+ expect(result).toStrictEqual([]);
+ });
+
+ it('evaluates the no-meta guard on the first disk but still flags the node via a second matching disk', () => {
+ // Drives the `!meta` branch on d-bad, then `.some()` advances to d-good
+ // which is SMART-only without a temperature -> node flagged.
+ const node = legacyNode({ id: 'n-mixed', proxmox: { node: 'pve' } });
+ const result = collectOutdatedSensorSetupNodes(
+ [node],
+ [
+ disk({ id: 'd-bad', parentId: 'n-mixed', noMeta: true }),
+ disk({ id: 'd-good', parentId: 'n-mixed', diskType: 'sata', temperature: 0 }),
+ ],
+ );
+ expect(result).toStrictEqual([{ id: 'n-mixed', name: 'pve' }]);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/resourceSourceHealth.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/resourceSourceHealth.branchcov0712.test.ts
new file mode 100644
index 0000000000..93d8c49624
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourceSourceHealth.branchcov0712.test.ts
@@ -0,0 +1,163 @@
+/**
+ * Branch-coverage tests for resourceSourceHealth.ts — second pass.
+ *
+ * Focused exclusively on branches of `getResourceSourceStatus` and the
+ * module-private `normalizeStatus` that the sibling
+ * resourceSourceHealth.test.ts does not yet reach.
+ *
+ * `normalizeStatus` is not exported, so it is exercised through
+ * `getResourceSourceHealth` (its only caller) with status values chosen to
+ * drive each arm of its `typeof value === 'string'` guard — non-string
+ * primitives/objects and whitespace/case-mixed strings the sibling test never
+ * feeds in.
+ *
+ * Fixtures mirror the sibling test's `as Resource` cast pattern.
+ */
+import { describe, expect, it } from 'vitest';
+
+import type { Resource } from '@/types/resource';
+import { getResourceSourceHealth, getResourceSourceStatus } from '@/utils/resourceSourceHealth';
+
+const makeResource = (platformData: Record<string, unknown>): Resource =>
+ ({
+ id: 'resource-1',
+ type: 'agent',
+ name: 'resource-1',
+ displayName: 'resource-1',
+ platformId: 'lab',
+ platformType: 'vmware-vsphere',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ platformData,
+ }) as Resource;
+
+const withSourceStatus = (sourceStatus: unknown): Resource => makeResource({ sourceStatus });
+
+describe('getResourceSourceStatus (branch coverage)', () => {
+ it('returns undefined when the source argument is an empty string (early guard)', () => {
+ // `normalizeSourcePlatformKey('') || ''.trim().toLowerCase()` -> '' -> !normalizedSource.
+ const resource = withSourceStatus({ truenas: { status: 'online' } });
+ expect(getResourceSourceStatus(resource, '')).toBeUndefined();
+ });
+
+ it('returns undefined when the source argument is only whitespace (early guard)', () => {
+ // normalizeSourcePlatformKey(' ') -> null; ' '.trim().toLowerCase() -> ''.
+ const resource = withSourceStatus({ truenas: { status: 'online' } });
+ expect(getResourceSourceStatus(resource, ' ')).toBeUndefined();
+ });
+
+ it('returns the full status entry when the source is a known platform id (truthy || arm)', () => {
+ // normalizeSourcePlatformKey('truenas') -> 'truenas' (truthy) short-circuits the ||.
+ const resource = withSourceStatus({ truenas: { status: 'online', lastSeen: 5 } });
+ expect(getResourceSourceStatus(resource, 'truenas')).toStrictEqual({
+ status: 'online',
+ lastSeen: 5,
+ });
+ });
+
+ it('matches a sourceStatus key written as a platform alias (key-side normalize arm)', () => {
+ // key 'vmware' normalizes to 'vmware-vsphere', matching source 'vmware-vsphere'.
+ const resource = withSourceStatus({ vmware: { status: 'healthy', error: null } });
+ expect(getResourceSourceStatus(resource, 'vmware-vsphere')).toStrictEqual({
+ status: 'healthy',
+ error: null,
+ });
+ });
+
+ it('matches an unknown source key through the trim/lowercase fallback (both || falsy arms)', () => {
+ // source and key are both unknown to the manifest, so both fall to `.trim().toLowerCase()`.
+ // Also exercises the loop `continue` for a non-matching preceding key ('truenas').
+ const resource = withSourceStatus({
+ truenas: { status: 'online' },
+ 'Custom-Source': { status: 'offline', error: 'timeout' },
+ });
+ expect(getResourceSourceStatus(resource, 'custom-source')).toStrictEqual({
+ status: 'offline',
+ error: 'timeout',
+ });
+ });
+
+ it('returns undefined when no sourceStatus key matches the requested source (loop fall-through)', () => {
+ // Loop iterates 'truenas' (normalizes to 'truenas' !== 'docker'), then the bottom return.
+ const resource = withSourceStatus({ truenas: { status: 'online' } });
+ expect(getResourceSourceStatus(resource, 'docker')).toBeUndefined();
+ });
+
+ it('returns undefined when platformData has no sourceStatus field (optional-chain arm)', () => {
+ // resource.platformData?.sourceStatus -> undefined -> asRecord(undefined) -> undefined.
+ expect(getResourceSourceStatus(makeResource({}), 'truenas')).toBeUndefined();
+ });
+
+ it('returns undefined when sourceStatus is a primitive string (asRecord reject arm)', () => {
+ // typeof 'truenas' === 'string' -> asRecord returns undefined -> !sourceStatus guard.
+ expect(getResourceSourceStatus(withSourceStatus('truenas'), 'truenas')).toBeUndefined();
+ });
+
+ it('returns undefined when sourceStatus is null (asRecord falsy guard)', () => {
+ // `value && typeof value === 'object'` — null is falsy, so asRecord returns undefined.
+ expect(getResourceSourceStatus(withSourceStatus(null), 'truenas')).toBeUndefined();
+ });
+
+ it('returns undefined when sourceStatus is an array with no matching keys', () => {
+ // asRecord([]) returns the array (typeof 'object'), Object.entries([]) is empty,
+ // the loop never matches and the function falls through to `return undefined`.
+ expect(getResourceSourceStatus(withSourceStatus([]), 'truenas')).toBeUndefined();
+ });
+
+ it('returns undefined when the matched status value is itself a primitive', () => {
+ // Loop matches 'custom-source', but asRecord('flat-status') -> undefined (string),
+ // which is then cast and returned as undefined.
+ const resource = withSourceStatus({ 'custom-source': 'flat-status' });
+ expect(getResourceSourceStatus(resource, 'custom-source')).toBeUndefined();
+ });
+});
+
+describe('normalizeStatus — exercised via getResourceSourceHealth (branch coverage)', () => {
+ // normalizeStatus is module-private and only reachable through getResourceSourceHealth.
+
+ it('normalizes a whitespace-padded, case-mixed status into a connected keyword', () => {
+ // typeof === 'string' arm with non-trivial trim()+toLowerCase(): ' ONLINE ' -> 'online'.
+ const resource = withSourceStatus({ truenas: { status: ' ONLINE ' } });
+ expect(getResourceSourceHealth(resource, 'truenas')).toBe('connected');
+ });
+
+ it.each(['ONLINE', 'Running', 'HEALTHY', 'Connected', 'Ok'])(
+ 'recognizes every connected keyword after case normalization (%s)',
+ (status) => {
+ // String arm + Set hit for each member of CONNECTED_SOURCE_STATUSES via upper/mixed case.
+ const resource = withSourceStatus({ truenas: { status } });
+ expect(getResourceSourceHealth(resource, 'truenas')).toBe('connected');
+ },
+ );
+
+ it('treats an empty status string as impaired (string arm yields empty normalized value)', () => {
+ // ''.trim().toLowerCase() -> '' which is not in the connected set.
+ const resource = withSourceStatus({ truenas: { status: '' } });
+ expect(getResourceSourceHealth(resource, 'truenas')).toBe('impaired');
+ });
+
+ it('treats a numeric status as impaired (non-string arm returns empty string)', () => {
+ // typeof 123 !== 'string' -> '' -> not connected.
+ const resource = withSourceStatus({ truenas: { status: 123 } });
+ expect(getResourceSourceHealth(resource, 'truenas')).toBe('impaired');
+ });
+
+ it('treats a boolean status as impaired (non-string arm)', () => {
+ // typeof true === 'boolean' !== 'string' -> ''.
+ const resource = withSourceStatus({ truenas: { status: true } });
+ expect(getResourceSourceHealth(resource, 'truenas')).toBe('impaired');
+ });
+
+ it('treats an object status as impaired (non-string arm)', () => {
+ // typeof {} === 'object' !== 'string' -> ''.
+ const resource = withSourceStatus({ truenas: { status: { healthy: true } } });
+ expect(getResourceSourceHealth(resource, 'truenas')).toBe('impaired');
+ });
+
+ it('treats a null status as impaired (typeof null === "object", non-string arm)', () => {
+ // null hits the non-string arm even though typeof null === 'object', yielding ''.
+ const resource = withSourceStatus({ truenas: { status: null } });
+ expect(getResourceSourceHealth(resource, 'truenas')).toBe('impaired');
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/routeStateNavigation.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/routeStateNavigation.branchcov0712.test.ts
new file mode 100644
index 0000000000..0984ee6865
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/routeStateNavigation.branchcov0712.test.ts
@@ -0,0 +1,179 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ ROUTE_STATE_REPLACE_OPTIONS,
+ createRouteStateNavigateScheduler,
+} from '@/utils/routeStateNavigation';
+import {
+ clearPendingAppShellRestoreTop,
+ readPendingAppShellRestoreTop,
+} from '@/utils/appShellScrollRestoration';
+
+describe('routeStateNavigation – branch coverage (schedule / clearScrollRestoreWork / applyScrollRestore)', () => {
+ const scrollToSpy = vi.fn();
+ let currentScrollX = 24;
+ let currentScrollY = 320;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ clearPendingAppShellRestoreTop();
+ scrollToSpy.mockReset();
+ currentScrollX = 24;
+ currentScrollY = 320;
+ Object.defineProperty(window, 'scrollX', {
+ configurable: true,
+ get: () => currentScrollX,
+ });
+ Object.defineProperty(window, 'scrollY', {
+ configurable: true,
+ get: () => currentScrollY,
+ });
+ // Default to a non-jsdom UA so applyScrollRestore reaches window.scrollTo;
+ // the jsdom-guard test overrides this locally.
+ Object.defineProperty(window.navigator, 'userAgent', {
+ configurable: true,
+ value: 'Mozilla/5.0',
+ });
+ Object.defineProperty(window.history, 'scrollRestoration', {
+ configurable: true,
+ value: 'auto',
+ writable: true,
+ });
+ scrollToSpy.mockImplementation((x: number, y: number) => {
+ currentScrollX = x;
+ currentScrollY = y;
+ });
+ window.scrollTo = scrollToSpy as typeof window.scrollTo;
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe('schedule', () => {
+ it('returns early when the pending target is an empty string (!target branch)', () => {
+ const navigate = vi.fn();
+ const scheduler = createRouteStateNavigateScheduler(navigate, () => '/proxmox/backups');
+
+ scheduler.schedule('');
+ vi.runAllTimers();
+
+ expect(navigate).not.toHaveBeenCalled();
+ expect(scrollToSpy).not.toHaveBeenCalled();
+ scheduler.cleanup();
+ });
+
+ it('fires a plain replace without scroll restoration when the target is a different pathname (restoreScroll null arm)', () => {
+ const navigate = vi.fn();
+ // currentPath stays on the scheduling pathname so the stale-pathname
+ // guard does not drop the rewrite, but the target pathname differs —
+ // driving the `isSamePathnameNavigation(...) ? {...} : null` ternary
+ // into its null arm and reaching the bare navigate() at the bottom.
+ const scheduler = createRouteStateNavigateScheduler(navigate, () => '/proxmox/storage');
+
+ scheduler.schedule('/proxmox/overview?type=vm');
+ vi.runAllTimers();
+
+ expect(navigate).toHaveBeenCalledWith('/proxmox/overview?type=vm', ROUTE_STATE_REPLACE_OPTIONS);
+ expect(scrollToSpy).not.toHaveBeenCalled();
+ // scrollRestoration is only flipped to 'manual' inside the restoreScroll
+ // block, so the null arm leaves it untouched.
+ expect(window.history.scrollRestoration).toBe('auto');
+ scheduler.cleanup();
+ });
+
+ it('does not capture app-shell scroll when the shell is present but already at the top', () => {
+ const navigate = vi.fn();
+ let currentPath = '/proxmox/overview?type=app-container';
+ const scheduler = createRouteStateNavigateScheduler(navigate, () => currentPath);
+ const shell = document.createElement('div');
+ shell.className = 'app-scroll-shell';
+ shell.scrollTop = 0;
+ document.body.appendChild(shell);
+
+ scheduler.schedule('/proxmox/overview?type=app-container&resource=agent-1');
+ vi.runAllTimers();
+
+ // shell is truthy but `shell.scrollTop > 0` is false → short-circuits past
+ // schedulePendingAppShellRestoreTop.
+ expect(readPendingAppShellRestoreTop()).toBe(null);
+
+ shell.remove();
+ scheduler.cleanup();
+ });
+ });
+
+ describe('clearScrollRestoreWork (exercised via cleanup)', () => {
+ it('clears pending scroll-restore timeouts and animation frames registered by a same-path rewrite', () => {
+ const navigate = vi.fn();
+ let currentPath = '/proxmox/overview?type=app-container';
+ const scheduler = createRouteStateNavigateScheduler(navigate, () => currentPath);
+
+ // Capture the exact animation-frame handle the scheduler registers so we
+ // can assert clearScrollRestoreWork cancels that precise handle. Vitest's
+ // fake timers hand back Node Timeout-like opaque handles (not plain
+ // numbers), so we compare by identity rather than by numeric type.
+ const registeredRafHandles: unknown[] = [];
+ const underlyingRaf = window.requestAnimationFrame.bind(window);
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => {
+ const handle = underlyingRaf(cb);
+ registeredRafHandles.push(handle);
+ return handle;
+ });
+
+ scheduler.schedule('/proxmox/overview?type=app-container&resource=agent-9');
+ // Fire the outer setTimeout(0) only. This runs the restoreScroll block,
+ // registering two scroll-restore timeouts (delay 0 and 120) and a rAF
+ // chain, but — per the coalescing semantics — does not yet flush the
+ // inner 0ms timeout. The immediate applyScrollRestore fires once.
+ vi.advanceTimersByTime(0);
+ expect(scrollToSpy).toHaveBeenCalledTimes(1);
+ expect(registeredRafHandles).toHaveLength(1);
+
+ const clearTimeoutSpy = vi.spyOn(window, 'clearTimeout');
+ const cancelAnimSpy = vi.spyOn(window, 'cancelAnimationFrame');
+
+ scheduler.cleanup();
+
+ // clearScrollRestoreWork iterates the two pending timeout handles
+ // (the `typeof window !== 'undefined'` → window.clearTimeout arm) and
+ // cancels the pending animation frame (the window.cancelAnimationFrame arm),
+ // passing the exact handle that requestAnimationFrame returned.
+ expect(clearTimeoutSpy.mock.calls).toHaveLength(2);
+ expect(clearTimeoutSpy.mock.calls[0]).toHaveLength(1);
+ expect(clearTimeoutSpy.mock.calls[1]).toHaveLength(1);
+ expect(cancelAnimSpy.mock.calls).toHaveLength(1);
+ expect(cancelAnimSpy.mock.calls[0][0]).toBe(registeredRafHandles[0]);
+
+ // The deferred scroll-restore work was cancelled, so flushing the
+ // remaining timers produces no further scrollTo calls.
+ vi.runAllTimers();
+ expect(scrollToSpy).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('applyScrollRestore', () => {
+ it('skips window.scrollTo when running under a jsdom user agent (jsdom guard branch)', () => {
+ const navigate = vi.fn();
+ let currentPath = '/proxmox/overview?type=app-container';
+ const scheduler = createRouteStateNavigateScheduler(navigate, () => currentPath);
+
+ Object.defineProperty(window.navigator, 'userAgent', {
+ configurable: true,
+ value: 'Mozilla/5.0 (linux) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/24.1.0',
+ });
+
+ scheduler.schedule('/proxmox/overview?type=app-container&resource=guest-7');
+ vi.runAllTimers();
+
+ // navigate still fires (it happens before applyScrollRestore), but every
+ // applyScrollRestore invocation returns early at the jsdom guard.
+ expect(navigate).toHaveBeenCalledWith(
+ '/proxmox/overview?type=app-container&resource=guest-7',
+ ROUTE_STATE_REPLACE_OPTIONS,
+ );
+ expect(scrollToSpy).not.toHaveBeenCalled();
+ scheduler.cleanup();
+ });
+ });
+});