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 16 pure modules (GLM wave 0712 batch 2)

rcourtman512606c40b94
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/aiCodeHighlight.branchcov0712.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/aiCodeHighlight.branchcov0712.test.ts
new file mode 100644
index 0000000000..80850983e1
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/aiCodeHighlight.branchcov0712.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it, vi } from 'vitest';
+import { highlightSettledCodeBlocks } from '../aiCodeHighlight';
+
+// Branch-coverage companion to aiCodeHighlight.test.ts. Targets the two
+// functions highlightSettledCodeBlocks (exported) and loadHighlighter
+// (module-private). loadHighlighter's branches are driven through the
+// public highlightSettledCodeBlocks entry point, or via vi.doMock +
+// dynamic import to obtain a fresh module instance with a controlled
+// highlight.js core.
+
+const makeContainer = (html: string): HTMLElement => {
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ return container;
+};
+
+// ---------------------------------------------------------------------------
+// highlightSettledCodeBlocks — ternary: `language && hljs.getLanguage(language)`
+// The sibling suite covers language='' (falsy short-circuit) and a registered
+// language (truthy getLanguage). This covers the remaining arm: language is
+// truthy but getLanguage returns undefined (unregistered grammar).
+// ---------------------------------------------------------------------------
+
+describe('highlightSettledCodeBlocks branch coverage — real highlighter', () => {
+ it('falls back to highlightAuto when the fence language is truthy but unregistered', async () => {
+ // 'rust' is not in the registered grammar set (bash/json/yaml/ini/sql/
+ // dockerfile/nginx/plaintext), so getLanguage('rust') returns undefined
+ // and the ternary takes the highlightAuto arm.
+ const container = makeContainer(
+ '<pre><code class="language-rust">{"name": "test", "count": 3}</code></pre>',
+ );
+ await highlightSettledCodeBlocks(container);
+
+ const code = container.querySelector('code') as HTMLElement;
+ expect(code.dataset.highlighted).toBe('true');
+ expect(code.classList.contains('hljs-highlighted')).toBe(true);
+ // highlightAuto (subset includes json) detected JSON and applied spans.
+ expect(code.innerHTML).toContain('<span');
+ expect(code.textContent).toBe('{"name": "test", "count": 3}');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// loadHighlighter — catch arm (import failure → null), cached-null on retry,
+// and the downstream `if (!hljs) return` early exit in highlightSettledCodeBlocks.
+// ---------------------------------------------------------------------------
+
+describe('loadHighlighter branch coverage — mocked core failures', () => {
+ it('catches when core.default is undefined, returns null, and caches the null promise', async () => {
+ vi.resetModules();
+ // Mock core to an object with no `default` — core.default is undefined,
+ // so hljs.registerLanguage throws inside the try, the catch arm logs
+ // and returns null, and highlightSettledCodeBlocks hits `if (!hljs)`.
+ vi.doMock('highlight.js/lib/core', () => ({}));
+
+ const { highlightSettledCodeBlocks: highlight } = await import('../aiCodeHighlight');
+
+ const c1 = makeContainer(
+ '<pre><code class="language-bash">echo "hello" # comment</code></pre>',
+ );
+ await highlight(c1);
+ const code1 = c1.querySelector('code') as HTMLElement;
+ // loadHighlighter catch → null → if (!hljs) return: block untouched.
+ expect(code1.dataset.highlighted).toBeUndefined();
+ expect(code1.classList.contains('hljs-highlighted')).toBe(false);
+ expect(code1.innerHTML).toBe('echo "hello" # comment');
+
+ // Second call: hljsPromise is cached (resolved with null) — the
+ // if (!hljsPromise) false arm returns the cached null without retrying.
+ const c2 = makeContainer('<pre><code class="language-json">{"a": 1}</code></pre>');
+ await highlight(c2);
+ const code2 = c2.querySelector('code') as HTMLElement;
+ expect(code2.dataset.highlighted).toBeUndefined();
+ expect(code2.innerHTML).toBe('{"a": 1}');
+ });
+
+ // -------------------------------------------------------------------------
+ // highlightSettledCodeBlocks — catch arm around the highlight call.
+ // A fake hljs whose highlight/highlightAuto throws exercises the catch
+ // block: sets data-highlighted='true' but NOT the hljs-highlighted class
+ // and leaves innerHTML untouched.
+ // -------------------------------------------------------------------------
+
+ it('marks a block highlighted without the class when hljs.highlight throws (language path)', async () => {
+ vi.resetModules();
+ const throwingHljs = {
+ registerLanguage: vi.fn(),
+ registerAliases: vi.fn(),
+ getLanguage: vi.fn(() => ({ name: 'bash' })),
+ highlight: vi.fn(() => {
+ throw new Error('highlight boom');
+ }),
+ highlightAuto: vi.fn(),
+ };
+ vi.doMock('highlight.js/lib/core', () => ({ default: throwingHljs }));
+
+ const { highlightSettledCodeBlocks: highlight } = await import('../aiCodeHighlight');
+ const container = makeContainer(
+ '<pre><code class="language-bash">echo hello</code></pre>',
+ );
+ await highlight(container);
+
+ const code = container.querySelector('code') as HTMLElement;
+ // Catch arm: data-highlighted set, class NOT added, innerHTML untouched.
+ expect(code.dataset.highlighted).toBe('true');
+ expect(code.classList.contains('hljs-highlighted')).toBe(false);
+ expect(code.innerHTML).toBe('echo hello');
+ expect(throwingHljs.highlight).toHaveBeenCalledTimes(1);
+ expect(throwingHljs.highlightAuto).not.toHaveBeenCalled();
+ });
+
+ it('marks a block highlighted without the class when hljs.highlightAuto throws (auto path)', async () => {
+ vi.resetModules();
+ const throwingHljs = {
+ registerLanguage: vi.fn(),
+ registerAliases: vi.fn(),
+ getLanguage: vi.fn(() => undefined),
+ highlight: vi.fn(),
+ highlightAuto: vi.fn(() => {
+ throw new Error('auto boom');
+ }),
+ };
+ vi.doMock('highlight.js/lib/core', () => ({ default: throwingHljs }));
+
+ const { highlightSettledCodeBlocks: highlight } = await import('../aiCodeHighlight');
+ // No language- class → fenceLanguage returns '' → falsy → highlightAuto.
+ const container = makeContainer('<pre><code>plain text here</code></pre>');
+ await highlight(container);
+
+ const code = container.querySelector('code') as HTMLElement;
+ expect(code.dataset.highlighted).toBe('true');
+ expect(code.classList.contains('hljs-highlighted')).toBe(false);
+ expect(code.innerHTML).toBe('plain text here');
+ expect(throwingHljs.highlightAuto).toHaveBeenCalledTimes(1);
+ expect(throwingHljs.highlight).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/workflowStarters.branchcov0712.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/workflowStarters.branchcov0712.test.ts
new file mode 100644
index 0000000000..48c0a2ff6a
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/workflowStarters.branchcov0712.test.ts
@@ -0,0 +1,363 @@
+import { describe, expect, it } from 'vitest';
+import type { AgentWorkflowPrompt } from '@/api/agentCapabilities';
+import {
+ getAssistantWorkflowStarters,
+ getAssistantWorkflowStarterResourceId,
+ getAssistantWorkflowStarterFindingId,
+} from '../workflowStarters';
+
+// Branch-coverage companion to workflowStarters.test.ts.
+// workflowStarterLabel, resolveWorkflowStarterArgument and
+// buildWorkflowStarterArguments are module-private, so each of their branches is
+// driven through the public entry points (getAssistantWorkflowStarters for the
+// builders; the two exported resolvers directly) and asserted against concrete
+// shapes/strings — never truthiness-only.
+
+const one = (prompts: AgentWorkflowPrompt[], context: Record<string, unknown> = {}) =>
+ getAssistantWorkflowStarters(prompts, context);
+
+// ---------------------------------------------------------------------------
+// workflowStarterLabel (private) — reached via getAssistantWorkflowStarters .label
+// ---------------------------------------------------------------------------
+
+describe('workflowStarterLabel branch coverage', () => {
+ it('returns the trimmed label when a label is present (normalizeIdentifier trim + truthy arm)', () => {
+ const [starter] = one([
+ { name: 'pulse_a', label: ' Spaced Label ', arguments: [] },
+ ]);
+ expect(starter.label).toBe('Spaced Label');
+ });
+
+ it('falls through a non-string label (typeof !== "string" arm) to the description', () => {
+ const [starter] = one([
+ {
+ name: 'pulse_a',
+ label: 12345 as unknown as string,
+ description: ' Use this description ',
+ arguments: [],
+ },
+ ]);
+ expect(starter.label).toBe('Use this description');
+ });
+
+ it('falls through an empty-string label to the description branch', () => {
+ const [starter] = one([
+ { name: 'pulse_a', label: '', description: 'Desc only', arguments: [] },
+ ]);
+ expect(starter.label).toBe('Desc only');
+ });
+
+ it('title-cases the name when neither label nor description is present (name-formatting arm)', () => {
+ const [starter] = one([{ name: 'pulse_triage_fleet', arguments: [] }]);
+ // pulse_ stripped, underscores -> spaces, first letters uppercased.
+ expect(starter.label).toBe('Triage Fleet');
+ });
+
+ it('title-cases a name that has no pulse_ prefix', () => {
+ const [starter] = one([{ name: 'investigate_resource', arguments: [] }]);
+ expect(starter.label).toBe('Investigate Resource');
+ });
+
+ it('title-cases a single-word name with no prefix and no underscores', () => {
+ const [starter] = one([{ name: 'triage', arguments: [] }]);
+ expect(starter.label).toBe('Triage');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getAssistantWorkflowStarterResourceId (exported)
+// ---------------------------------------------------------------------------
+
+describe('getAssistantWorkflowStarterResourceId branch coverage', () => {
+ it('returns the first non-empty resource id, skipping a blank earlier entry', () => {
+ expect(
+ getAssistantWorkflowStarterResourceId({
+ handoffResources: [{ id: ' ' }, { id: 'vm:2' }],
+ }),
+ ).toBe('vm:2');
+ });
+
+ it('skips a non-string resource id (typeof !== "string") and continues the loop', () => {
+ expect(
+ getAssistantWorkflowStarterResourceId({
+ handoffResources: [{ id: 99 as unknown as string }],
+ }),
+ ).toBe('');
+ });
+
+ it('falls back to handoffActions targetResourceId when no resource id resolves', () => {
+ expect(
+ getAssistantWorkflowStarterResourceId({
+ handoffActions: [{ targetResourceId: '' }, { targetResourceId: 'act-res' }],
+ }),
+ ).toBe('act-res');
+ });
+
+ it('falls back to targetId for a non-patrol target type when nothing else resolves', () => {
+ expect(getAssistantWorkflowStarterResourceId({ targetType: 'vm', targetId: 'vm-99' })).toBe(
+ 'vm-99',
+ );
+ });
+
+ it('rejects every patrol target type so a run/assessment/configuration id is not used', () => {
+ expect(getAssistantWorkflowStarterResourceId({ targetType: 'patrol-run', targetId: 'run-1' })).toBe('');
+ expect(
+ getAssistantWorkflowStarterResourceId({ targetType: 'patrol-assessment', targetId: 'a-1' }),
+ ).toBe('');
+ expect(
+ getAssistantWorkflowStarterResourceId({ targetType: 'patrol-configuration', targetId: 'c-1' }),
+ ).toBe('');
+ });
+
+ it('returns empty string when no targetId is set, even with a targetType', () => {
+ expect(getAssistantWorkflowStarterResourceId({})).toBe('');
+ expect(getAssistantWorkflowStarterResourceId({ targetType: 'vm' })).toBe('');
+ });
+
+ it('returns a targetId whose targetType is absent (empty type is not a patrol type)', () => {
+ expect(getAssistantWorkflowStarterResourceId({ targetId: 'only-id' })).toBe('only-id');
+ });
+
+ it('prefers a resource id over an action id and a target id', () => {
+ expect(
+ getAssistantWorkflowStarterResourceId({
+ handoffResources: [{ id: 'r-1' }],
+ handoffActions: [{ targetResourceId: 'a-1' }],
+ targetType: 'vm',
+ targetId: 't-1',
+ }),
+ ).toBe('r-1');
+ });
+
+ it('prefers an action id over a target id when no resource resolves', () => {
+ expect(
+ getAssistantWorkflowStarterResourceId({
+ handoffActions: [{ targetResourceId: 'a-1' }],
+ targetType: 'vm',
+ targetId: 't-1',
+ }),
+ ).toBe('a-1');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getAssistantWorkflowStarterFindingId (exported)
+// ---------------------------------------------------------------------------
+
+describe('getAssistantWorkflowStarterFindingId branch coverage', () => {
+ it('returns the direct findingId first', () => {
+ expect(getAssistantWorkflowStarterFindingId({ findingId: 'f-direct' })).toBe('f-direct');
+ });
+
+ it('skips a non-string direct findingId and falls through to actions', () => {
+ expect(
+ getAssistantWorkflowStarterFindingId({
+ findingId: 7 as unknown as string,
+ handoffActions: [{ findingId: 'f-act' }],
+ }),
+ ).toBe('f-act');
+ });
+
+ it('returns the first non-empty action findingId, skipping a blank earlier entry', () => {
+ expect(
+ getAssistantWorkflowStarterFindingId({
+ handoffActions: [{ findingId: ' ' }, { findingId: 'f-2' }],
+ }),
+ ).toBe('f-2');
+ });
+
+ it('falls back to context.context.findingId via the optional chain', () => {
+ expect(getAssistantWorkflowStarterFindingId({ context: { findingId: 'f-ctx' } })).toBe(
+ 'f-ctx',
+ );
+ });
+
+ it('returns empty string when context.context exists but has no findingId', () => {
+ expect(getAssistantWorkflowStarterFindingId({ context: { other: 'x' } })).toBe('');
+ });
+
+ it('returns empty string when no source resolves (optional chain short-circuits)', () => {
+ expect(getAssistantWorkflowStarterFindingId({})).toBe('');
+ expect(getAssistantWorkflowStarterFindingId({ context: undefined })).toBe('');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// resolveWorkflowStarterArgument (private) — reached via buildWorkflowStarterArguments
+// ---------------------------------------------------------------------------
+
+describe('resolveWorkflowStarterArgument branch coverage', () => {
+ it('routes "resourceId" through getAssistantWorkflowStarterResourceId', () => {
+ const [starter] = one(
+ [{ name: 'p', arguments: [{ name: 'resourceId', required: true }] }],
+ { handoffResources: [{ id: 'vm:7' }] },
+ );
+ expect(starter.arguments).toStrictEqual({ resourceId: 'vm:7' });
+ });
+
+ it('routes "finding_id" through getAssistantWorkflowStarterFindingId', () => {
+ const [starter] = one(
+ [{ name: 'p', arguments: [{ name: 'finding_id', required: true }] }],
+ { findingId: 'f-1' },
+ );
+ expect(starter.arguments).toStrictEqual({ finding_id: 'f-1' });
+ });
+
+ it('returns undefined for an unknown argument name (default arm), omitting an optional arg', () => {
+ const [starter] = one([{ name: 'p', arguments: [{ name: 'mystery', required: false }] }]);
+ expect(starter.arguments).toStrictEqual({});
+ });
+
+ it('returns undefined for an unknown argument name and drops the prompt when the arg is required', () => {
+ const starters = one([
+ { name: 'known', label: 'Keep', arguments: [] },
+ { name: 'dropped', label: 'Lose', arguments: [{ name: 'mystery', required: true }] },
+ ]);
+ expect(starters.map((s) => s.name)).toStrictEqual(['known']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildWorkflowStarterArguments (private) — reached via getAssistantWorkflowStarters
+// ---------------------------------------------------------------------------
+
+describe('buildWorkflowStarterArguments branch coverage', () => {
+ it('treats a missing arguments array as empty and returns {}', () => {
+ // No `arguments` field at all -> prompt.arguments ?? [] -> loop skipped.
+ const [starter] = one([{ name: 'p', label: 'L' }] as AgentWorkflowPrompt[]);
+ expect(starter.arguments).toStrictEqual({});
+ });
+
+ it('skips an argument whose name trims to empty', () => {
+ const [starter] = one([
+ { name: 'p', arguments: [{ name: ' ' }, { name: 'resourceId', required: false }] },
+ ]);
+ // Blank name is continue'd; resourceId optional with no value is omitted too.
+ expect(starter.arguments).toStrictEqual({});
+ });
+
+ it('keeps a resolved optional argument and includes the prompt', () => {
+ const [starter] = one(
+ [{ name: 'p', arguments: [{ name: 'resourceId', required: false }] }],
+ { handoffResources: [{ id: 'vm:1' }] },
+ );
+ expect(starter.arguments).toStrictEqual({ resourceId: 'vm:1' });
+ });
+
+ it('omits an unresolved optional argument but still includes the prompt with {}', () => {
+ const [starter] = one([
+ { name: 'p', arguments: [{ name: 'resourceId', required: false }] },
+ ]);
+ expect(starter).toMatchObject({ name: 'p' });
+ expect(starter.arguments).toStrictEqual({});
+ });
+
+ it('returns null (drops the prompt) when a required argument has no value', () => {
+ const starters = one([
+ { name: 'kept', label: 'K', arguments: [] },
+ { name: 'gone', label: 'G', arguments: [{ name: 'finding_id', required: true }] },
+ ]);
+ expect(starters.map((s) => s.name)).toStrictEqual(['kept']);
+ });
+
+ it('returns null when one optional arg resolves but a later required arg does not', () => {
+ const starters = one(
+ [
+ {
+ name: 'mixed',
+ arguments: [
+ { name: 'resourceId', required: false },
+ { name: 'finding_id', required: true },
+ ],
+ },
+ ],
+ { handoffResources: [{ id: 'vm:1' }] },
+ );
+ expect(starters).toStrictEqual([]);
+ });
+
+ it('keeps the prompt when every required argument resolves', () => {
+ const [starter] = one(
+ [
+ {
+ name: 'all',
+ arguments: [
+ { name: 'resourceId', required: true },
+ { name: 'finding_id', required: true },
+ ],
+ },
+ ],
+ { handoffResources: [{ id: 'vm:1' }], findingId: 'f-1' },
+ );
+ expect(starter.arguments).toStrictEqual({ resourceId: 'vm:1', finding_id: 'f-1' });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getAssistantWorkflowStarters (exported)
+// ---------------------------------------------------------------------------
+
+describe('getAssistantWorkflowStarters branch coverage', () => {
+ it('skips a prompt whose name trims to empty', () => {
+ const starters = one([
+ { name: '', label: 'Empty', arguments: [] },
+ { name: ' ', label: 'Blank', arguments: [] },
+ { name: 'kept', label: 'Kept', arguments: [] },
+ ]);
+ expect(starters.map((s) => s.name)).toStrictEqual(['kept']);
+ });
+
+ it('skips a duplicate name, keeping the first occurrence', () => {
+ const starters = one([
+ { name: 'dup', label: 'First', arguments: [] },
+ { name: 'dup', label: 'Second', arguments: [] },
+ ]);
+ expect(starters).toHaveLength(1);
+ expect(starters[0].label).toBe('First');
+ });
+
+ it('trims a padded name for both id and name', () => {
+ const [starter] = one([{ name: ' padded ', label: 'L', arguments: [] }]);
+ expect(starter.id).toBe('padded');
+ expect(starter.name).toBe('padded');
+ });
+
+ it('sets description to undefined when the description trims to empty', () => {
+ const [starter] = one([{ name: 'p', label: 'L', description: ' ', arguments: [] }]);
+ expect(starter.description).toBeUndefined();
+ });
+
+ it('sets description to undefined when description is absent', () => {
+ const [starter] = one([{ name: 'p', label: 'L', arguments: [] }]);
+ expect(starter.description).toBeUndefined();
+ });
+
+ it('keeps a concrete description string when present', () => {
+ const [starter] = one([{ name: 'p', label: 'L', description: 'A real desc', arguments: [] }]);
+ expect(starter.description).toBe('A real desc');
+ });
+
+ it('falls back to the workflow kind when presentationKind is absent (normalize non-string arm)', () => {
+ const [starter] = one([{ name: 'p', label: 'L', arguments: [] }] as AgentWorkflowPrompt[]);
+ expect(starter.kind).toBe('workflow');
+ });
+
+ it('falls back to the workflow kind for an undeclared presentationKind string', () => {
+ const [starter] = one([{ name: 'p', label: 'L', presentationKind: 'banana', arguments: [] }]);
+ expect(starter.kind).toBe('workflow');
+ });
+
+ it('produces a fully-shaped starter for a valid kind with no description', () => {
+ const starters = one([{ name: 'pulse_x', presentationKind: 'fleet', arguments: [] }]);
+ expect(starters).toStrictEqual([
+ {
+ id: 'pulse_x',
+ name: 'pulse_x',
+ label: 'X',
+ description: undefined,
+ kind: 'fleet',
+ arguments: {},
+ },
+ ]);
+ });
+});
diff --git a/frontend-modern/src/components/Alerts/__tests__/alertAssistantHandoffModel.branchcov0712.test.ts b/frontend-modern/src/components/Alerts/__tests__/alertAssistantHandoffModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..8b79306806
--- /dev/null
+++ b/frontend-modern/src/components/Alerts/__tests__/alertAssistantHandoffModel.branchcov0712.test.ts
@@ -0,0 +1,304 @@
+import { describe, expect, it } from 'vitest';
+import type { Alert } from '@/types/api';
+import { buildAlertAssistantHandoff } from '../alertAssistantHandoffModel';
+
+// `buildAlertAssistantHandoff` always populates briefing/context/handoffResources/
+// handoffContext, but its declared return type borrows `AIChatContext`, where those
+// fields are optional and `context` is `Record<string, unknown>`. The strict
+// tsconfig therefore flags direct deep access as possibly-undefined. We mirror the
+// concrete runtime shape in a local type and cast once so the assertions below stay
+// precise (`toBe`/`toEqual`) and type-safe — mirroring the sibling
+// incidentAssistantHandoffModel.branchcov2.test.ts convention.
+interface StrictBriefing {
+ sourceLabel: string;
+ title: string;
+ subject: string;
+ statusLabel: string;
+ detailLines: string[];
+ actionLabel: string;
+ safetyNote: string;
+}
+
+interface StrictAlertContext {
+ alertIdentifier: string;
+ alertType: string;
+ alertLevel: string;
+ alertMessage: string;
+ guestName: string;
+ node: string;
+ vmid?: number;
+}
+
+interface StrictHandoffContext {
+ targetType: string;
+ targetId: string;
+ autonomousMode: boolean;
+ handoffContext: string;
+ handoffResources: { id: string; name: string; type: string; node: string }[];
+ briefing: StrictBriefing;
+ context: StrictAlertContext;
+}
+
+interface StrictHandoff {
+ context: StrictHandoffContext;
+}
+
+const DEFAULT_NOW = new Date('2026-05-07T10:05:00.000Z');
+
+function makeAlert(overrides: Partial<Alert> = {}): Alert {
+ return {
+ id: 'alert-1',
+ type: 'cpu',
+ level: 'warning',
+ resourceId: 'vm-101',
+ resourceName: 'app-vm',
+ node: 'pve1',
+ nodeDisplayName: 'PVE Node 1',
+ instance: '',
+ message: 'CPU usage is high',
+ value: 82.5,
+ threshold: 80,
+ startTime: '2026-05-07T10:00:00.000Z',
+ acknowledged: false,
+ ...overrides,
+ };
+}
+
+function buildHandoff(
+ overrides: Partial<Alert> = {},
+ options: { now?: Date; resourceType?: string; vmid?: number } = {},
+): StrictHandoff {
+ return buildAlertAssistantHandoff({
+ alert: makeAlert(overrides),
+ now: options.now ?? DEFAULT_NOW,
+ resourceType: options.resourceType,
+ vmid: options.vmid,
+ }) as unknown as StrictHandoff;
+}
+
+// handoffContext renders the model overloads of formatAlertLevel /
+// formatAlertDuration (locale = DEFAULT_LOCALE 'en'); the briefing subject and
+// statusLabel render the no-locale overloads, which resolve to the active ('en')
+// locale in the jsdom test environment. Both surfaces therefore render English.
+
+describe('formatAlertDuration (exercised via buildAlertAssistantHandoff)', () => {
+ it('returns singular "1 min" for an exact 1-minute delta (durationMins === 1 true arm)', () => {
+ const handoff = buildHandoff(
+ { startTime: '2026-05-07T10:00:00.000Z' },
+ { now: new Date('2026-05-07T10:01:00.000Z') },
+ );
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active 1 min');
+ expect(handoff.context.handoffContext).toContain('Duration: 1 min');
+ });
+
+ it('returns plural "5 mins" for a multi-minute sub-hour delta (durationMins === 1 false arm)', () => {
+ const handoff = buildHandoff(
+ { startTime: '2026-05-07T10:00:00.000Z' },
+ { now: new Date('2026-05-07T10:05:00.000Z') },
+ );
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active 5 mins');
+ expect(handoff.context.handoffContext).toContain('Duration: 5 mins');
+ });
+
+ it('formats a >= 60min delta as "Xh Ym" (durationMins >= 60 arm)', () => {
+ const handoff = buildHandoff(
+ { startTime: '2026-05-07T10:00:00.000Z' },
+ { now: new Date('2026-05-07T11:05:00.000Z') },
+ );
+ // 65 minutes elapsed -> floor(65/60)=1 hour, 65%60=5 minutes.
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active 1h 5m');
+ expect(handoff.context.handoffContext).toContain('Duration: 1h 5m');
+ });
+
+ it('returns "0 mins" when now equals startTime (zero delta, plural arm)', () => {
+ const handoff = buildHandoff(
+ { startTime: '2026-05-07T10:00:00.000Z' },
+ { now: new Date('2026-05-07T10:00:00.000Z') },
+ );
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active 0 mins');
+ expect(handoff.context.handoffContext).toContain('Duration: 0 mins');
+ });
+
+ it('clamps a negative (now before startTime) delta to "0 mins" via Math.max(0, ...)', () => {
+ const handoff = buildHandoff(
+ { startTime: '2026-05-07T10:05:00.000Z' },
+ { now: new Date('2026-05-07T10:00:00.000Z') },
+ );
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active 0 mins');
+ expect(handoff.context.handoffContext).toContain('Duration: 0 mins');
+ });
+
+ it('returns "unknown duration" when startTime is unparseable (startedAt not finite)', () => {
+ const handoff = buildHandoff(
+ { startTime: 'not-a-valid-date' },
+ { now: new Date('2026-05-07T10:05:00.000Z') },
+ );
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active unknown duration');
+ expect(handoff.context.handoffContext).toContain('Duration: unknown duration');
+ });
+
+ it('returns "unknown duration" when now is an invalid Date (nowMs not finite)', () => {
+ const handoff = buildHandoff(
+ { startTime: '2026-05-07T10:00:00.000Z' },
+ { now: new Date('not-a-valid-date') },
+ );
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active unknown duration');
+ expect(handoff.context.handoffContext).toContain('Duration: unknown duration');
+ });
+});
+
+describe('formatAlertLevel (exercised via buildAlertAssistantHandoff)', () => {
+ it("renders 'Critical' for level='critical' (=== 'critical' true arm)", () => {
+ const handoff = buildHandoff({ level: 'critical' });
+ // subject template: '{level} {alertType} on {resourceName}'
+ expect(handoff.context.briefing.subject).toBe('Critical cpu on app-vm');
+ expect(handoff.context.briefing.statusLabel).toBe('Critical alert · Active 5 mins');
+ // handoffContext renders the model-level label (DEFAULT_LOCALE='en' overload).
+ expect(handoff.context.handoffContext).toContain('Alert Level: Critical');
+ expect(handoff.context.context.alertLevel).toBe('critical');
+ });
+
+ it("renders 'Info' for level='info' (=== 'info' true arm; level cast past the type union)", () => {
+ // Alert.level is typed 'warning' | 'critical'; the runtime String() comparison
+ // in formatAlertLevel still admits 'info', so we cast to reach that branch.
+ const handoff = buildHandoff({ level: 'info' as unknown as Alert['level'] });
+ expect(handoff.context.briefing.subject).toBe('Info cpu on app-vm');
+ expect(handoff.context.briefing.statusLabel).toBe('Info alert · Active 5 mins');
+ expect(handoff.context.handoffContext).toContain('Alert Level: Info');
+ });
+
+ it("renders 'Warning' for level='warning' (default fallback arm)", () => {
+ const handoff = buildHandoff({ level: 'warning' });
+ expect(handoff.context.briefing.subject).toBe('Warning cpu on app-vm');
+ expect(handoff.context.briefing.statusLabel).toBe('Warning alert · Active 5 mins');
+ expect(handoff.context.handoffContext).toContain('Alert Level: Warning');
+ });
+});
+
+describe('formatContextLine (exercised via buildAlertAssistantHandoff)', () => {
+ it('omits the "Message:" line when message is null (value === null branch)', () => {
+ const handoff = buildHandoff({ message: null as unknown as string });
+ expect(handoff.context.handoffContext).not.toContain('Message:');
+ // Briefing's message ternary (alert.message ? ...) also drops the line; with a
+ // metric cpu alert only currentMetric + node detailLines remain.
+ expect(handoff.context.briefing.detailLines).toEqual([
+ 'Current value 82.5%; threshold 80.0%',
+ 'Node: PVE Node 1',
+ ]);
+ });
+
+ it('omits the "Message:" line when message is undefined (value === undefined branch)', () => {
+ const handoff = buildHandoff({ message: undefined as unknown as string });
+ expect(handoff.context.handoffContext).not.toContain('Message:');
+ expect(handoff.context.briefing.detailLines).toEqual([
+ 'Current value 82.5%; threshold 80.0%',
+ 'Node: PVE Node 1',
+ ]);
+ });
+
+ it('omits the "Message:" line when message is empty string (trim -> empty -> undefined)', () => {
+ const handoff = buildHandoff({ message: '' });
+ expect(handoff.context.handoffContext).not.toContain('Message:');
+ expect(handoff.context.briefing.detailLines).toEqual([
+ 'Current value 82.5%; threshold 80.0%',
+ 'Node: PVE Node 1',
+ ]);
+ });
+
+ it('drops the "Message:" context line when message is whitespace-only (trim -> empty -> undefined)', () => {
+ const handoff = buildHandoff({ message: ' ' });
+ // formatContextLine trims to empty -> filtered out of handoffContext.
+ expect(handoff.context.handoffContext).not.toContain('Message:');
+ // Asymmetry: the briefing detail.message path does NOT trim, so the raw
+ // whitespace survives there as a literal "Message: " line.
+ expect(handoff.context.briefing.detailLines).toContain('Message: ');
+ });
+
+ it('renders the message line for a non-empty message (happy path)', () => {
+ const handoff = buildHandoff({ message: 'Disk almost full' });
+ expect(handoff.context.handoffContext).toContain('Message: Disk almost full');
+ expect(handoff.context.briefing.detailLines).toContain('Message: Disk almost full');
+ });
+
+ it('coerces a numeric message to a rendered "Message:" line (String(value) branch)', () => {
+ // Cast message to a number: formatContextLine runs String(value).trim() ->
+ // "42" -> "Message: 42". (resourceId can't be used here because the same value
+ // is consumed earlier by resolveAlertTargetType, which assumes a string and
+ // would throw before formatContextLine runs.)
+ const handoff = buildHandoff({ message: 42 as unknown as string });
+ expect(handoff.context.handoffContext).toContain('Message: 42');
+ expect(handoff.context.briefing.detailLines).toContain('Message: 42');
+ });
+});
+
+describe('buildAlertAssistantHandoff (node-label, metadata-chain & briefing ternaries)', () => {
+ it("falls back to alert.node when nodeDisplayName is undefined (|| chain 2nd arm)", () => {
+ const handoff = buildHandoff({ node: 'pve2', nodeDisplayName: undefined });
+ expect(handoff.context.handoffContext).toContain('Node: pve2');
+ expect(handoff.context.briefing.detailLines).toContain('Node: pve2');
+ // handoffResources always carries the raw node regardless of label resolution.
+ expect(handoff.context.handoffResources[0].node).toBe('pve2');
+ });
+
+ it("falls back to alert.node when nodeDisplayName is empty string (|| chain, '' falsy arm)", () => {
+ const handoff = buildHandoff({ node: 'pve2', nodeDisplayName: '' });
+ expect(handoff.context.handoffContext).toContain('Node: pve2');
+ expect(handoff.context.briefing.detailLines).toContain('Node: pve2');
+ });
+
+ it("yields empty nodeLabel when node is falsy (outer ternary false arm) -> drops the Node line", () => {
+ const handoff = buildHandoff({ node: '' });
+ expect(handoff.context.handoffContext).not.toContain('Node:');
+ expect(handoff.context.briefing.detailLines).not.toContain('Node:');
+ expect(handoff.context.context.node).toBe('');
+ expect(handoff.context.handoffResources[0].node).toBe('');
+ });
+
+ it("hits the metadata?.resourceType optional-chain false branch when metadata is undefined", () => {
+ // makeAlert has no metadata by default; type='cpu' -> targetType inferred from
+ // the 'vm-101' id via inferAlertTargetTypeFromResourceId.
+ const handoff = buildHandoff({ type: 'cpu' });
+ expect(handoff.context.targetType).toBe('vm');
+ expect(handoff.context.context.alertType).toBe('cpu');
+ });
+
+ it("hits the typeof metadata?.resourceType !== 'string' false branch for a non-string value", () => {
+ const handoff = buildHandoff({
+ type: 'cpu',
+ metadata: { resourceType: 5 },
+ });
+ // Non-string resourceType is ignored -> falls back to resourceId inference -> 'vm'.
+ expect(handoff.context.targetType).toBe('vm');
+ });
+
+ it("omits the currentMetric detailLine for a state alert (hasMetricValues false -> briefing ternary false arm)", () => {
+ const handoff = buildHandoff({ type: 'powered-off', value: 0, threshold: 0 });
+ expect(handoff.context.briefing.detailLines).toEqual([
+ 'Node: PVE Node 1',
+ 'Message: CPU usage is high',
+ ]);
+ // currentMetric ternary false -> currentValue/thresholdValue are '' ->
+ // formatContextLine trims them out of handoffContext too.
+ expect(handoff.context.handoffContext).not.toContain('Current Value:');
+ expect(handoff.context.handoffContext).not.toContain('Threshold:');
+ });
+
+ it("keeps the currentMetric detailLine for a metric alert (hasMetricValues true -> briefing ternary true arm)", () => {
+ const handoff = buildHandoff({ type: 'cpu', value: 92.5, threshold: 80 });
+ expect(handoff.context.briefing.detailLines).toContain('Current value 92.5%; threshold 80.0%');
+ expect(handoff.context.handoffContext).toContain('Current Value: 92.5%');
+ expect(handoff.context.handoffContext).toContain('Threshold: 80.0%');
+ });
+
+ it("leaves context.vmid undefined when vmid is not supplied", () => {
+ const handoff = buildHandoff();
+ // The source spreads `vmid` (shorthand) from the optional input, so the key
+ // exists but holds undefined when the caller omits it.
+ expect(handoff.context.context.vmid).toBeUndefined();
+ });
+
+ it("propagates vmid into context when supplied", () => {
+ const handoff = buildHandoff({}, { vmid: 101 });
+ expect(handoff.context.context.vmid).toBe(101);
+ });
+});
diff --git a/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov0712.test.ts b/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..ec619b4c05
--- /dev/null
+++ b/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov0712.test.ts
@@ -0,0 +1,782 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ alertResourceSupportsMetric,
+ flattenAlertResourceTableResources,
+ getAlertResourceColumnHeaderTooltip,
+ getAlertResourceColumnKind,
+ getAlertResourceEnabledDefault,
+ getAlertResourceLabel,
+ getAlertResourceMetricBounds,
+ getAlertResourceMetricDelayOverride,
+ getAlertResourceMetricDisplayValue,
+ getAlertResourceMetricStep,
+ hasAlertResourceTableRows,
+ hasCustomAlertResourceGlobalDefaults,
+ normalizeAlertResourceMetricKey,
+ type AlertResourceTableResourceLike,
+ type AlertResourceThresholdMap,
+} from '../alertResourceTableModel';
+
+function makeResource(
+ overrides: Partial<AlertResourceTableResourceLike> = {},
+): AlertResourceTableResourceLike {
+ return {
+ id: 'res-1',
+ name: 'Test VM',
+ ...overrides,
+ };
+}
+
+describe('flattenAlertResourceTableResources', () => {
+ it('returns flattened grouped resources when groupedResources is provided', () => {
+ const a = makeResource({ id: 'a', name: 'A' });
+ const b = makeResource({ id: 'b', name: 'B' });
+ const c = makeResource({ id: 'c', name: 'C' });
+ expect(flattenAlertResourceTableResources(undefined, { nodes: [a, b], agents: [c] })).toEqual([
+ a,
+ b,
+ c,
+ ]);
+ });
+
+ it('returns the resources array when groupedResources is undefined', () => {
+ const a = makeResource({ id: 'a', name: 'A' });
+ const b = makeResource({ id: 'b', name: 'B' });
+ expect(flattenAlertResourceTableResources([a, b])).toEqual([a, b]);
+ });
+
+ it('returns an empty array when both arguments are undefined', () => {
+ expect(flattenAlertResourceTableResources()).toEqual([]);
+ });
+
+ it('prefers groupedResources even when resources is also provided', () => {
+ const a = makeResource({ id: 'a', name: 'A' });
+ const b = makeResource({ id: 'b', name: 'B' });
+ expect(flattenAlertResourceTableResources([b], { group: [a] })).toEqual([a]);
+ });
+
+ it('returns an empty array for an empty groupedResources object (truthy but no values)', () => {
+ expect(flattenAlertResourceTableResources(undefined, {})).toEqual([]);
+ });
+});
+
+describe('hasAlertResourceTableRows', () => {
+ it('returns true when resources has entries (flatten length > 0)', () => {
+ expect(hasAlertResourceTableRows([makeResource({ id: 'a', name: 'A' })])).toBe(true);
+ });
+
+ it('returns true when groupedResources has keys even if all groups are empty arrays', () => {
+ expect(hasAlertResourceTableRows(undefined, { group: [] })).toBe(true);
+ });
+
+ it('returns true when only globalDefaults with a numeric value is provided', () => {
+ expect(hasAlertResourceTableRows(undefined, undefined, { cpu: 0 })).toBe(true);
+ });
+
+ it('returns false when nothing is provided', () => {
+ expect(hasAlertResourceTableRows()).toBe(false);
+ });
+
+ it('returns false when resources is empty, groupedResources is undefined, and globalDefaults is undefined', () => {
+ expect(hasAlertResourceTableRows([], undefined, undefined)).toBe(false);
+ });
+
+ it('returns true for an empty-object globalDefaults because Boolean({}) is truthy', () => {
+ expect(hasAlertResourceTableRows(undefined, undefined, {})).toBe(true);
+ });
+
+ it('returns true when groupedResources is non-empty and globalDefaults is also set', () => {
+ expect(hasAlertResourceTableRows(undefined, { g: [makeResource()] }, { cpu: 80 })).toBe(true);
+ });
+});
+
+describe('hasCustomAlertResourceGlobalDefaults', () => {
+ it('returns false when globalDefaults is undefined', () => {
+ expect(hasCustomAlertResourceGlobalDefaults(undefined, { cpu: 80 })).toBe(false);
+ });
+
+ it('returns false when factoryDefaults is undefined', () => {
+ expect(hasCustomAlertResourceGlobalDefaults({ cpu: 80 }, undefined)).toBe(false);
+ });
+
+ it('returns false when both are undefined', () => {
+ expect(hasCustomAlertResourceGlobalDefaults(undefined, undefined)).toBe(false);
+ });
+
+ it('returns false when all factory keys match the global values exactly', () => {
+ expect(
+ hasCustomAlertResourceGlobalDefaults({ cpu: 80, memory: 90 }, { cpu: 80, memory: 90 }),
+ ).toBe(false);
+ });
+
+ it('returns true when at least one factory key differs in global', () => {
+ expect(
+ hasCustomAlertResourceGlobalDefaults({ cpu: 75, memory: 90 }, { cpu: 80, memory: 90 }),
+ ).toBe(true);
+ });
+
+ it('returns false when a factory key is absent from globalDefaults (current is undefined)', () => {
+ expect(
+ hasCustomAlertResourceGlobalDefaults({ memory: 90 }, { cpu: 80, memory: 90 }),
+ ).toBe(false);
+ });
+
+ it('returns true when exactly one of many keys differs', () => {
+ expect(
+ hasCustomAlertResourceGlobalDefaults(
+ { cpu: 80, memory: 90, disk: 95 },
+ { cpu: 80, memory: 90, disk: 85 },
+ ),
+ ).toBe(true);
+ });
+
+ it('treats a global value of 0 as defined and custom when factory is non-zero', () => {
+ expect(hasCustomAlertResourceGlobalDefaults({ cpu: 0 }, { cpu: 80 })).toBe(true);
+ });
+
+ it('returns false when global value equals factory value of 0', () => {
+ expect(hasCustomAlertResourceGlobalDefaults({ cpu: 0 }, { cpu: 0 })).toBe(false);
+ });
+});
+
+describe('normalizeAlertResourceMetricKey', () => {
+ describe('Map direct hits', () => {
+ it.each([
+ ['cpu %', 'cpu'],
+ ['memory %', 'memory'],
+ ['disk %', 'disk'],
+ ['disk r mb/s', 'diskRead'],
+ ['disk w mb/s', 'diskWrite'],
+ ['net in mb/s', 'networkIn'],
+ ['net out mb/s', 'networkOut'],
+ ['usage %', 'usage'],
+ ['temp °c', 'temperature'],
+ ['temperature °c', 'temperature'],
+ ['temperature', 'temperature'],
+ ['restart count', 'restartCount'],
+ ['restart window', 'restartWindow'],
+ ['restart window (s)', 'restartWindow'],
+ ['memory warn %', 'memoryWarnPct'],
+ ['memory critical %', 'memoryCriticalPct'],
+ ['warning size (gib)', 'warningSizeGiB'],
+ ['critical size (gib)', 'criticalSizeGiB'],
+ ['disk temp °c', 'diskTemperature'],
+ ['backup', 'backup'],
+ ['snapshot', 'snapshot'],
+ ])('maps %s -> %s', (input, expected) => {
+ expect(normalizeAlertResourceMetricKey(input)).toBe(expected);
+ });
+ });
+
+ describe('trim and lowercase normalization before Map lookup', () => {
+ it('trims surrounding whitespace before lookup', () => {
+ expect(normalizeAlertResourceMetricKey(' cpu % ')).toBe('cpu');
+ });
+
+ it('lowercases before lookup', () => {
+ expect(normalizeAlertResourceMetricKey('CPU %')).toBe('cpu');
+ });
+
+ it('handles mixed case and surrounding whitespace together', () => {
+ expect(normalizeAlertResourceMetricKey(' Memory % ')).toBe('memory');
+ });
+ });
+
+ describe('replace fallback chain (unmapped inputs)', () => {
+ it('strips " %" suffix', () => {
+ expect(normalizeAlertResourceMetricKey('foo %')).toBe('foo');
+ });
+
+ it('strips " °c" suffix', () => {
+ expect(normalizeAlertResourceMetricKey('foo °c')).toBe('foo');
+ });
+
+ it('strips " mb/s" suffix', () => {
+ expect(normalizeAlertResourceMetricKey('foo mb/s')).toBe('foo');
+ });
+
+ it('maps "disk r" to "diskRead" via replace (not in Map)', () => {
+ expect(normalizeAlertResourceMetricKey('disk r')).toBe('diskRead');
+ });
+
+ it('maps "disk w" to "diskWrite" via replace', () => {
+ expect(normalizeAlertResourceMetricKey('disk w')).toBe('diskWrite');
+ });
+
+ it('maps "net in" to "networkIn" via replace', () => {
+ expect(normalizeAlertResourceMetricKey('net in')).toBe('networkIn');
+ });
+
+ it('maps "net out" to "networkOut" via replace', () => {
+ expect(normalizeAlertResourceMetricKey('net out')).toBe('networkOut');
+ });
+
+ it('returns the trimmed lowercased key unchanged when no pattern matches', () => {
+ expect(normalizeAlertResourceMetricKey('Foobar')).toBe('foobar');
+ });
+
+ it('chains multiple replaces: "disk r %" -> "diskRead"', () => {
+ expect(normalizeAlertResourceMetricKey('disk r %')).toBe('diskRead');
+ });
+ });
+});
+
+describe('getAlertResourceMetricBounds', () => {
+ it.each([
+ ['temperature', { min: -1, max: 150 }],
+ ['diskTemperature', { min: -1, max: 150 }],
+ ['diskRead', { min: -1, max: 10000 }],
+ ['diskWrite', { min: -1, max: 10000 }],
+ ['networkIn', { min: -1, max: 10000 }],
+ ['networkOut', { min: -1, max: 10000 }],
+ ['cpu', { min: -1, max: 100 }],
+ ['memory', { min: -1, max: 100 }],
+ ['disk', { min: -1, max: 100 }],
+ ['usage', { min: -1, max: 100 }],
+ ['memoryWarnPct', { min: -1, max: 100 }],
+ ['memoryCriticalPct', { min: -1, max: 100 }],
+ ['warningSizeGiB', { min: -1, max: 100000 }],
+ ['criticalSizeGiB', { min: -1, max: 100000 }],
+ ['restartCount', { min: -1, max: 50 }],
+ ['restartWindow', { min: -1, max: 86400 }],
+ ['unknownMetric', { min: -1, max: 10000 }],
+ ])('returns correct bounds for %s', (metric, expected) => {
+ expect(getAlertResourceMetricBounds(metric)).toStrictEqual(expected);
+ });
+});
+
+describe('getAlertResourceMetricStep', () => {
+ it.each([
+ ['diskRead', 'any'],
+ ['diskWrite', 'any'],
+ ['networkIn', 'any'],
+ ['networkOut', 'any'],
+ ['warningSizeGiB', 'any'],
+ ['criticalSizeGiB', 'any'],
+ ['cpu', 1],
+ ['temperature', 1],
+ ['unknownMetric', 1],
+ ])('returns correct step for %s', (metric, expected) => {
+ expect(getAlertResourceMetricStep(metric)).toBe(expected);
+ });
+});
+
+describe('getAlertResourceEnabledDefault', () => {
+ it.each([
+ ['diskRead', 100],
+ ['diskWrite', 100],
+ ['networkIn', 100],
+ ['networkOut', 100],
+ ['temperature', 80],
+ ['diskTemperature', 55],
+ ['restartCount', 3],
+ ['restartWindow', 300],
+ ['memoryWarnPct', 90],
+ ['memoryCriticalPct', 95],
+ ['cpu', 80],
+ ['memory', 80],
+ ['unknownMetric', 80],
+ ])('returns correct default for %s', (metric, expected) => {
+ expect(getAlertResourceEnabledDefault(metric)).toBe(expected);
+ });
+});
+
+describe('getAlertResourceMetricDelayOverride', () => {
+ it('returns undefined when metricDelaySeconds is undefined', () => {
+ expect(getAlertResourceMetricDelayOverride(undefined, 'cpu')).toBeUndefined();
+ });
+
+ it('returns the value for a normalized (trimmed+lowercased) key match', () => {
+ expect(getAlertResourceMetricDelayOverride({ cpu: 30 }, 'CPU')).toBe(30);
+ });
+
+ it('returns the value when the metric is already normalized', () => {
+ expect(getAlertResourceMetricDelayOverride({ cpu: 30 }, 'cpu')).toBe(30);
+ });
+
+ it('falls back to the original metric key when normalized lookup misses', () => {
+ expect(getAlertResourceMetricDelayOverride({ CPU: 45 } as Record<string, number>, 'CPU')).toBe(
+ 45,
+ );
+ });
+
+ it('returns undefined when neither normalized nor original key matches', () => {
+ expect(getAlertResourceMetricDelayOverride({ foo: 30 }, 'cpu')).toBeUndefined();
+ });
+
+ it('returns undefined when the looked-up value is NaN (not finite)', () => {
+ expect(getAlertResourceMetricDelayOverride({ cpu: NaN }, 'cpu')).toBeUndefined();
+ });
+
+ it('returns undefined when the looked-up value is Infinity (not finite)', () => {
+ expect(getAlertResourceMetricDelayOverride({ cpu: Infinity }, 'cpu')).toBeUndefined();
+ });
+
+ it('returns undefined when the value is not a number type', () => {
+ const corrupted = { cpu: '30' } as unknown as Record<string, number>;
+ expect(getAlertResourceMetricDelayOverride(corrupted, 'cpu')).toBeUndefined();
+ });
+
+ it('returns 0 for a valid finite value of 0', () => {
+ expect(getAlertResourceMetricDelayOverride({ cpu: 0 }, 'cpu')).toBe(0);
+ });
+
+ it('returns a negative finite value as-is', () => {
+ expect(getAlertResourceMetricDelayOverride({ cpu: -5 }, 'cpu')).toBe(-5);
+ });
+});
+
+describe('getAlertResourceColumnHeaderTooltip', () => {
+ it('returns the tooltip for an exact column match', () => {
+ expect(getAlertResourceColumnHeaderTooltip('cpu %')).toBe(
+ 'Percent CPU utilization allowed before an alert fires.',
+ );
+ });
+
+ it('returns the tooltip via normalized lookup when exact misses (case/whitespace)', () => {
+ expect(getAlertResourceColumnHeaderTooltip(' CPU % ')).toBe(
+ 'Percent CPU utilization allowed before an alert fires.',
+ );
+ });
+
+ it('returns undefined when no tooltip exists for the column', () => {
+ expect(getAlertResourceColumnHeaderTooltip('nonexistent column')).toBeUndefined();
+ });
+
+ it('returns the mail-queue tooltip for a known queue column', () => {
+ expect(getAlertResourceColumnHeaderTooltip('queue warn')).toBe(
+ 'Early warning when total mail queue exceeds this message count.',
+ );
+ });
+
+ it('returns the snapshot-size tooltip via normalized lookup (mixed case)', () => {
+ expect(getAlertResourceColumnHeaderTooltip('Warning Size (GiB)')).toBe(
+ 'Total snapshot size in GiB that raises a warning.',
+ );
+ });
+});
+
+describe('getAlertResourceColumnKind', () => {
+ it('returns "badge" for "backup"', () => {
+ expect(getAlertResourceColumnKind('backup')).toBe('badge');
+ });
+
+ it('returns "badge" for "snapshot"', () => {
+ expect(getAlertResourceColumnKind('snapshot')).toBe('badge');
+ });
+
+ it('returns "badge" for "Backup" (case-insensitive via normalize)', () => {
+ expect(getAlertResourceColumnKind('Backup')).toBe('badge');
+ });
+
+ it('returns "numeric-value" for a standard numeric metric', () => {
+ expect(getAlertResourceColumnKind('cpu %')).toBe('numeric-value');
+ });
+
+ it('returns "numeric-value" for an unmapped column', () => {
+ expect(getAlertResourceColumnKind('unknown')).toBe('numeric-value');
+ });
+});
+
+describe('alertResourceSupportsMetric', () => {
+ it('returns true when resourceType is undefined (any metric)', () => {
+ expect(alertResourceSupportsMetric(undefined, 'cpu')).toBe(true);
+ expect(alertResourceSupportsMetric(undefined, 'temperature')).toBe(true);
+ });
+
+ it('returns true for an empty-string resourceType', () => {
+ expect(alertResourceSupportsMetric('', 'cpu')).toBe(true);
+ });
+
+ describe('node / agent — throughput blocked', () => {
+ it('returns false for all throughput metrics on node', () => {
+ expect(alertResourceSupportsMetric('node', 'diskRead')).toBe(false);
+ expect(alertResourceSupportsMetric('node', 'diskWrite')).toBe(false);
+ expect(alertResourceSupportsMetric('node', 'networkIn')).toBe(false);
+ expect(alertResourceSupportsMetric('node', 'networkOut')).toBe(false);
+ });
+
+ it('returns true for cpu on node (falls through to default)', () => {
+ expect(alertResourceSupportsMetric('node', 'cpu')).toBe(true);
+ });
+
+ it('returns false for throughput on agent', () => {
+ expect(alertResourceSupportsMetric('agent', 'networkIn')).toBe(false);
+ });
+
+ it('returns true for memory on agent', () => {
+ expect(alertResourceSupportsMetric('agent', 'memory')).toBe(true);
+ });
+ });
+
+ describe('pbs — cpu/memory only', () => {
+ it('supports cpu and memory', () => {
+ expect(alertResourceSupportsMetric('pbs', 'cpu')).toBe(true);
+ expect(alertResourceSupportsMetric('pbs', 'memory')).toBe(true);
+ });
+
+ it('rejects disk and temperature', () => {
+ expect(alertResourceSupportsMetric('pbs', 'disk')).toBe(false);
+ expect(alertResourceSupportsMetric('pbs', 'temperature')).toBe(false);
+ });
+ });
+
+ describe('storage — usage only', () => {
+ it('supports usage', () => {
+ expect(alertResourceSupportsMetric('storage', 'usage')).toBe(true);
+ });
+
+ it('rejects cpu', () => {
+ expect(alertResourceSupportsMetric('storage', 'cpu')).toBe(false);
+ });
+ });
+
+ describe('kubernetesNamespace — nothing supported', () => {
+ it('returns false for all metrics', () => {
+ expect(alertResourceSupportsMetric('kubernetesNamespace', 'cpu')).toBe(false);
+ expect(alertResourceSupportsMetric('kubernetesNamespace', 'memory')).toBe(false);
+ });
+ });
+
+ describe('kubernetes cluster / deployment / pod', () => {
+ it('supports cpu/disk/throughput on kubernetesCluster', () => {
+ expect(alertResourceSupportsMetric('kubernetesCluster', 'cpu')).toBe(true);
+ expect(alertResourceSupportsMetric('kubernetesCluster', 'disk')).toBe(true);
+ expect(alertResourceSupportsMetric('kubernetesCluster', 'diskRead')).toBe(true);
+ });
+
+ it('rejects temperature on kubernetesCluster', () => {
+ expect(alertResourceSupportsMetric('kubernetesCluster', 'temperature')).toBe(false);
+ });
+
+ it('supports networkIn on kubernetesDeployment', () => {
+ expect(alertResourceSupportsMetric('kubernetesDeployment', 'networkIn')).toBe(true);
+ });
+
+ it('rejects restartCount on kubernetesDeployment', () => {
+ expect(alertResourceSupportsMetric('kubernetesDeployment', 'restartCount')).toBe(false);
+ });
+
+ it('supports disk on kubernetesPod', () => {
+ expect(alertResourceSupportsMetric('kubernetesPod', 'disk')).toBe(true);
+ });
+
+ it('rejects usage on kubernetesPod', () => {
+ expect(alertResourceSupportsMetric('kubernetesPod', 'usage')).toBe(false);
+ });
+ });
+
+ describe('kubernetesNode — cpu/memory/disk only', () => {
+ it('supports cpu/memory/disk', () => {
+ expect(alertResourceSupportsMetric('kubernetesNode', 'cpu')).toBe(true);
+ expect(alertResourceSupportsMetric('kubernetesNode', 'memory')).toBe(true);
+ expect(alertResourceSupportsMetric('kubernetesNode', 'disk')).toBe(true);
+ });
+
+ it('rejects diskRead', () => {
+ expect(alertResourceSupportsMetric('kubernetesNode', 'diskRead')).toBe(false);
+ });
+ });
+
+ describe('truenasSystem — extended set including temperature', () => {
+ it('supports temperature and cpu', () => {
+ expect(alertResourceSupportsMetric('truenasSystem', 'temperature')).toBe(true);
+ expect(alertResourceSupportsMetric('truenasSystem', 'cpu')).toBe(true);
+ });
+
+ it('rejects restartCount', () => {
+ expect(alertResourceSupportsMetric('truenasSystem', 'restartCount')).toBe(false);
+ });
+ });
+
+ describe('truenasPool / truenasDataset — usage only', () => {
+ it('supports usage on truenasPool', () => {
+ expect(alertResourceSupportsMetric('truenasPool', 'usage')).toBe(true);
+ });
+
+ it('rejects cpu on truenasPool', () => {
+ expect(alertResourceSupportsMetric('truenasPool', 'cpu')).toBe(false);
+ });
+
+ it('supports usage on truenasDataset', () => {
+ expect(alertResourceSupportsMetric('truenasDataset', 'usage')).toBe(true);
+ });
+
+ it('rejects temperature on truenasDataset', () => {
+ expect(alertResourceSupportsMetric('truenasDataset', 'temperature')).toBe(false);
+ });
+ });
+
+ describe('truenasDisk — temperature only', () => {
+ it('supports temperature', () => {
+ expect(alertResourceSupportsMetric('truenasDisk', 'temperature')).toBe(true);
+ });
+
+ it('rejects cpu', () => {
+ expect(alertResourceSupportsMetric('truenasDisk', 'cpu')).toBe(false);
+ });
+ });
+
+ describe('vmwareHost — no disk', () => {
+ it('supports cpu/memory/throughput', () => {
+ expect(alertResourceSupportsMetric('vmwareHost', 'cpu')).toBe(true);
+ expect(alertResourceSupportsMetric('vmwareHost', 'memory')).toBe(true);
+ expect(alertResourceSupportsMetric('vmwareHost', 'diskRead')).toBe(true);
+ });
+
+ it('rejects disk', () => {
+ expect(alertResourceSupportsMetric('vmwareHost', 'disk')).toBe(false);
+ });
+ });
+
+ describe('vmwareVm — disk + throughput', () => {
+ it('supports disk and networkOut', () => {
+ expect(alertResourceSupportsMetric('vmwareVm', 'disk')).toBe(true);
+ expect(alertResourceSupportsMetric('vmwareVm', 'networkOut')).toBe(true);
+ });
+
+ it('rejects temperature', () => {
+ expect(alertResourceSupportsMetric('vmwareVm', 'temperature')).toBe(false);
+ });
+ });
+
+ describe('vmwareDatastore — usage only', () => {
+ it('supports usage', () => {
+ expect(alertResourceSupportsMetric('vmwareDatastore', 'usage')).toBe(true);
+ });
+
+ it('rejects cpu', () => {
+ expect(alertResourceSupportsMetric('vmwareDatastore', 'cpu')).toBe(false);
+ });
+ });
+
+ describe('vmwareNetwork — nothing supported', () => {
+ it('returns false for any metric', () => {
+ expect(alertResourceSupportsMetric('vmwareNetwork', 'cpu')).toBe(false);
+ });
+ });
+
+ describe('dockerContainer — restart + memory-warn set', () => {
+ it('supports restart and memory-warn metrics', () => {
+ expect(alertResourceSupportsMetric('dockerContainer', 'restartCount')).toBe(true);
+ expect(alertResourceSupportsMetric('dockerContainer', 'restartWindow')).toBe(true);
+ expect(alertResourceSupportsMetric('dockerContainer', 'memoryWarnPct')).toBe(true);
+ expect(alertResourceSupportsMetric('dockerContainer', 'memoryCriticalPct')).toBe(true);
+ expect(alertResourceSupportsMetric('dockerContainer', 'cpu')).toBe(true);
+ expect(alertResourceSupportsMetric('dockerContainer', 'memory')).toBe(true);
+ });
+
+ it('rejects temperature and disk', () => {
+ expect(alertResourceSupportsMetric('dockerContainer', 'temperature')).toBe(false);
+ expect(alertResourceSupportsMetric('dockerContainer', 'disk')).toBe(false);
+ });
+ });
+
+ describe('unknown resource type — default true', () => {
+ it('returns true for any metric', () => {
+ expect(alertResourceSupportsMetric('mysteryType', 'cpu')).toBe(true);
+ expect(alertResourceSupportsMetric('mysteryType', 'anything')).toBe(true);
+ });
+ });
+});
+
+describe('getAlertResourceLabel', () => {
+ it('returns the displayName when present', () => {
+ const resource = makeResource({ displayName: 'Prod Web Server' });
+ expect(getAlertResourceLabel(resource)).toBe('Prod Web Server');
+ });
+
+ it('trims surrounding whitespace from displayName', () => {
+ const resource = makeResource({ displayName: ' Prod Web Server ' });
+ expect(getAlertResourceLabel(resource)).toBe('Prod Web Server');
+ });
+
+ it('falls back to name when displayName is absent', () => {
+ const resource = makeResource({ name: 'web-01' });
+ expect(getAlertResourceLabel(resource)).toBe('web-01');
+ });
+
+ it('falls through whitespace-only displayName to the name', () => {
+ const resource = makeResource({ name: 'node-7', displayName: ' ' });
+ expect(getAlertResourceLabel(resource)).toBe('node-7');
+ });
+});
+
+describe('parseAlertMetricNumber (exercised via getAlertResourceMetricDisplayValue)', () => {
+ it('passes a negative number through the typeof-number branch unchanged', () => {
+ const resource = makeResource({ thresholds: { cpu: -5 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(-5);
+ });
+
+ it('passes a float through the typeof-number branch unchanged', () => {
+ const resource = makeResource({ thresholds: { cpu: 42.5 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(42.5);
+ });
+
+ it('parses a whitespace-padded numeric string via Number() (finite branch -> number)', () => {
+ const thresholds = { cpu: ' 42 ' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(42);
+ });
+
+ it('returns 0 fallback for null (null branch -> undefined -> defaults -> 0)', () => {
+ const thresholds = { cpu: null } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('returns 0 fallback for a non-numeric string (Number() -> NaN -> undefined -> 0)', () => {
+ const thresholds = { cpu: 'nope' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+});
+
+describe('extract closure — optional-chain and metric-capture branch coverage', () => {
+ // The `extract` arrow closure lives inside getAlertResourceMetricDisplayValue:
+ // const extract = (source) => parseAlertMetricNumber(source?.[metric]);
+ // It is reachable only via getAlertResourceMetricDisplayValue. These tests target
+ // the closure's own branches (the `source?.[metric]` optional chain short-circuit
+ // and dynamic `metric` capture) plus the immediate decision arms that consume its
+ // return value, asserting a concrete number on every branch.
+
+ describe('optional-chain short-circuit (source is undefined)', () => {
+ it('short-circuits extract(editingThresholds) when it is undefined and falls through to defaults', () => {
+ const resource = makeResource({ defaults: { cpu: 77 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', undefined, true)).toBe(77);
+ });
+
+ it('short-circuits extract(editingThresholds) AND extract(defaults) when both are undefined in edit mode, returning 0', () => {
+ const resource = makeResource({ defaults: undefined });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', undefined, true)).toBe(0);
+ });
+
+ it('short-circuits extract(thresholds) when thresholds is undefined in live mode and falls through to defaults', () => {
+ const resource = makeResource({ thresholds: undefined, defaults: { cpu: 33 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(33);
+ });
+
+ it('short-circuits extract(thresholds) AND extract(defaults) when both are undefined in live mode, returning 0', () => {
+ const resource = makeResource({ thresholds: undefined, defaults: undefined });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+ });
+
+ describe('dynamic metric capture (extract reads source[metric] for arbitrary metric names)', () => {
+ it('reads the memory key from thresholds when metric is "memory"', () => {
+ const resource = makeResource({ thresholds: { memory: 64 }, defaults: { memory: 50 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'memory')).toBe(64);
+ });
+
+ it('reads the diskRead key from editingThresholds when metric is "diskRead"', () => {
+ const resource = makeResource({ defaults: { diskRead: 10 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'diskRead', { diskRead: 250 }, true)).toBe(
+ 250,
+ );
+ });
+
+ it('reads the networkOut key from thresholds for a multi-word metric name', () => {
+ const resource = makeResource({ thresholds: { networkOut: 5 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'networkOut')).toBe(5);
+ });
+
+ it('returns 0 when the metric key is absent from every source (closure indexes an undefined key)', () => {
+ const resource = makeResource({ thresholds: { cpu: 80 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'nonexistentMetric')).toBe(0);
+ });
+ });
+
+ describe('edit-mode decision arms consuming extract result', () => {
+ it('returns the edited value on the truthy arm of `edited !== undefined`', () => {
+ const resource = makeResource({ defaults: { cpu: 10 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', { cpu: 88 }, true)).toBe(88);
+ });
+
+ it('returns edited 0 (literal) and does not skip to defaults when extract(editingThresholds) is 0', () => {
+ const resource = makeResource({ defaults: { cpu: 10 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', { cpu: 0 }, true)).toBe(0);
+ });
+
+ it('falls to defaults on the falsy arm of `edited !== undefined` when edited value is null', () => {
+ const edited = { cpu: null } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults: { cpu: 44 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', edited, true)).toBe(44);
+ });
+
+ it('returns the defaults value on the truthy arm of `fallback !== undefined` in edit mode', () => {
+ const resource = makeResource({ defaults: { cpu: 12 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', {}, true)).toBe(12);
+ });
+
+ it('returns 0 on the falsy arm of `fallback !== undefined` in edit mode when defaults are absent', () => {
+ const resource = makeResource();
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', {}, true)).toBe(0);
+ });
+
+ it('returns 0 on the falsy arm of `fallback !== undefined` when defaults value is explicitly undefined', () => {
+ const resource = makeResource({ defaults: { cpu: undefined } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', {}, true)).toBe(0);
+ });
+ });
+
+ describe('live-mode decision arms consuming extract result', () => {
+ it('returns the live value on the truthy arm of `liveValue !== undefined` and skips defaults', () => {
+ const resource = makeResource({ thresholds: { cpu: 91 }, defaults: { cpu: 5 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(91);
+ });
+
+ it('returns live 0 (literal) and does not skip to defaults when extract(thresholds) is 0', () => {
+ const resource = makeResource({ thresholds: { cpu: 0 }, defaults: { cpu: 5 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('falls to defaults on the falsy arm of `liveValue !== undefined` when live value is a non-numeric string', () => {
+ const thresholds = { cpu: 'garbage' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ thresholds, defaults: { cpu: 55 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(55);
+ });
+
+ it('returns the defaults value on the truthy arm of `fallback !== undefined` in live mode', () => {
+ const resource = makeResource({ thresholds: {}, defaults: { cpu: 19 } });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(19);
+ });
+
+ it('returns 0 on the falsy arm of `fallback !== undefined` in live mode when defaults are absent', () => {
+ const resource = makeResource({ thresholds: {} });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+ });
+
+ describe('defaults-fallback coercion arms reached through extract (net-new vs the thresholds-only block above)', () => {
+ it('parses a numeric string from defaults via Number() finite arm', () => {
+ const defaults = { cpu: '12.5' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(12.5);
+ });
+
+ it('coerces a defaults empty string to 0 (Number("") === 0 finite arm)', () => {
+ const defaults = { cpu: '' } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('coerces a single-element numeric array from defaults via Number()', () => {
+ const defaults = { cpu: [7] } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(7);
+ });
+
+ it('returns 0 when a defaults multi-element array coerces to NaN (finite-check -> undefined -> 0)', () => {
+ const defaults = { cpu: [1, 2] } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+
+ it('returns 0 when a defaults plain object coerces to NaN (finite-check -> undefined -> 0)', () => {
+ const defaults = { cpu: { v: 1 } } as unknown as AlertResourceThresholdMap;
+ const resource = makeResource({ defaults });
+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/updatesSettingsModel.branchcov0712.test.ts b/frontend-modern/src/components/Settings/__tests__/updatesSettingsModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..5cc3ff1360
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/updatesSettingsModel.branchcov0712.test.ts
@@ -0,0 +1,487 @@
+/**
+ * Branch-coverage tests for the exported helpers in updatesSettingsModel.
+ * Each block targets a single function and drives both arms of every
+ * conditional / ternary / optional-chain / guard / early-return branch that is
+ * reachable from the public surface.
+ *
+ * Targets: buildUpdateInstallGuide, getUpdateChannelCardOptions,
+ * buildIdleDockerComposeCommand, buildIdleDockerUpdateCommand.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ buildIdleDockerComposeCommand,
+ buildIdleDockerUpdateCommand,
+ buildUpdateInstallGuide,
+ getUpdateChannelCardOptions,
+} from '../updatesSettingsModel';
+import type {
+ DockerUpdateCommands,
+ UpdateInfo,
+ UpdatePlan,
+ VersionInfo,
+} from '@/api/updates';
+
+// ---- Fixtures ---------------------------------------------------------------
+// Mirror the shapes used by the sibling UpdateInstallGuide.test.tsx so the two
+// files stay consistent. The model only consumes narrow Picks of these types.
+
+type VersionInfoPick = Pick<VersionInfo, 'deploymentType' | 'isDocker'>;
+type UpdateInfoPick = Pick<UpdateInfo, 'latestVersion' | 'dockerUpdate'>;
+type UpdatePlanPick = Pick<UpdatePlan, 'canAutoUpdate'>;
+
+const makeVersionInfo = (overrides: Partial<VersionInfoPick> = {}): VersionInfoPick => ({
+ deploymentType: 'systemd',
+ isDocker: false,
+ ...overrides,
+});
+
+const makeUpdateInfo = (overrides: Partial<UpdateInfoPick> = {}): UpdateInfoPick => ({
+ latestVersion: 'v6.0.5',
+ ...overrides,
+});
+
+const makeUpdatePlan = (overrides: Partial<UpdatePlanPick> = {}): UpdatePlanPick => ({
+ canAutoUpdate: false,
+ ...overrides,
+});
+
+const digest = 'sha256:' + 'ab'.repeat(32);
+const pinnedRef = `registry.pulserelay.pro/pulse/pulse-pro@${digest}`;
+const makeDockerUpdate = (
+ overrides: Partial<DockerUpdateCommands> = {},
+): DockerUpdateCommands => ({
+ version: 'v6.0.5',
+ image: 'registry.pulserelay.pro/pulse/pulse-pro',
+ imageDigest: digest,
+ loginCommand:
+ "printf '%s' '<activation-key>' | docker login registry.pulserelay.pro -u 'lic_test' --password-stdin",
+ composePullCommand: `PULSE_IMAGE='${pinnedRef}' docker compose pull`,
+ composeUpCommand: `PULSE_IMAGE='${pinnedRef}' docker compose up -d`,
+ ...overrides,
+});
+
+const PRO_STEP_CODE_CLASS =
+ 'block rounded-md border border-border bg-base p-3 font-mono text-sm text-green-400 whitespace-pre-wrap break-all';
+const SYSTEMD_DOWNLOAD_CODE_CLASS =
+ 'block rounded-md border border-border bg-base p-3 font-mono text-sm text-base-content whitespace-pre-wrap break-all';
+
+// ---- buildIdleDockerComposeCommand -----------------------------------------
+// Single return path; assert the exact constant.
+
+describe('buildIdleDockerComposeCommand', () => {
+ it('returns the community docker compose pull+up command', () => {
+ expect(buildIdleDockerComposeCommand()).toBe('docker compose pull && docker compose up -d');
+ });
+});
+
+// ---- buildIdleDockerUpdateCommand -------------------------------------------
+// Single return path; assert the exact constant.
+
+describe('buildIdleDockerUpdateCommand', () => {
+ it('returns the community docker pull/stop/rm command', () => {
+ expect(buildIdleDockerUpdateCommand()).toBe(
+ 'docker pull rcourtman/pulse:latest && docker stop pulse && docker rm pulse',
+ );
+ });
+});
+
+// ---- getUpdateChannelCardOptions --------------------------------------------
+// Branches: the `versionInfo?.isSourceBuild` optional chain. Four reachable
+// arms: input undefined (chain short-circuits -> disabled undefined), input
+// null (chain short-circuits -> disabled undefined), isSourceBuild true
+// (disabled true), isSourceBuild false (disabled false). The full option
+// shape (value/title/description/tone) is constant across all arms.
+
+describe('getUpdateChannelCardOptions', () => {
+ it('returns both options with disabled undefined when versionInfo is omitted (optional-chain short-circuit)', () => {
+ expect(getUpdateChannelCardOptions()).toStrictEqual([
+ {
+ value: 'stable',
+ title: 'Stable',
+ description: 'Production-ready releases for paid and self-hosted environments',
+ tone: 'success',
+ disabled: undefined,
+ },
+ {
+ value: 'rc',
+ title: 'Pre-release',
+ description: 'Early preview builds for staging, internal validation, and opt-in testers',
+ tone: 'accent',
+ disabled: undefined,
+ },
+ ]);
+ });
+
+ it('returns both options with disabled undefined when versionInfo is null (optional-chain short-circuit)', () => {
+ const options = getUpdateChannelCardOptions(null);
+ expect(options[0]?.disabled).toBeUndefined();
+ expect(options[1]?.disabled).toBeUndefined();
+ });
+
+ it('disables both options for a source build (isSourceBuild true arm)', () => {
+ const options = getUpdateChannelCardOptions({ isSourceBuild: true });
+ expect(options[0]?.disabled).toBe(true);
+ expect(options[1]?.disabled).toBe(true);
+ // value/tone are unaffected by the branch.
+ expect(options[0]?.value).toBe('stable');
+ expect(options[0]?.tone).toBe('success');
+ expect(options[1]?.value).toBe('rc');
+ expect(options[1]?.tone).toBe('accent');
+ });
+
+ it('leaves both options enabled for a packaged build (isSourceBuild false arm)', () => {
+ const options = getUpdateChannelCardOptions({ isSourceBuild: false });
+ expect(options[0]?.disabled).toBe(false);
+ expect(options[1]?.disabled).toBe(false);
+ // Titles/descriptions are the constant copy.
+ expect(options[0]?.title).toBe('Stable');
+ expect(options[1]?.title).toBe('Pre-release');
+ });
+});
+
+// ---- buildUpdateInstallGuide ------------------------------------------------
+// Branches covered below:
+// - !versionInfo guard (null and undefined -> null)
+// - introText ternary: canAutoUpdate truthy arm vs falsy/absent-plan arm
+// - proxmoxve deployment arm
+// - docker arm: deploymentType === 'docker' vs the (!deploymentType && isDocker) fallback
+// - docker arm: updateInfo?.dockerUpdate truthy (pro steps) vs absent
+// - pro steps inner: loginCommand present (note pushed) vs absent
+// - docker arm: isProRuntime true (pro-unavailable notice) vs community guidance
+// - systemd/manual arm (both OR operands)
+// - development arm
+// - final return null (unknown deploymentType, and undefined+!isDocker fallthrough)
+
+describe('buildUpdateInstallGuide', () => {
+ // -- !versionInfo guard ----------------------------------------------------
+
+ it('returns null when versionInfo is null (!versionInfo guard)', () => {
+ expect(
+ buildUpdateInstallGuide(null, makeUpdateInfo(), makeUpdatePlan(), 'v6.0.5', 'curl', false),
+ ).toBeNull();
+ });
+
+ it('returns null when versionInfo is undefined (!versionInfo guard)', () => {
+ expect(
+ buildUpdateInstallGuide(undefined, makeUpdateInfo(), makeUpdatePlan(), 'v6.0.5', 'curl', false),
+ ).toBeNull();
+ });
+
+ // -- introText ternary -----------------------------------------------------
+
+ it('uses the automatic-install intro when updatePlan.canAutoUpdate is true (ternary truthy arm)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'systemd' }),
+ makeUpdateInfo(),
+ makeUpdatePlan({ canAutoUpdate: true }),
+ 'v6.0.5',
+ 'curl -fsSL https://example.invalid/pulse.tar.gz',
+ false,
+ );
+ expect(guide?.introText).toBe(
+ 'Click "Install Update" above for automatic installation, or update manually:',
+ );
+ });
+
+ it('uses the manual-only intro when updatePlan.canAutoUpdate is false (ternary falsy arm)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'systemd' }),
+ makeUpdateInfo(),
+ makeUpdatePlan({ canAutoUpdate: false }),
+ 'v6.0.5',
+ 'curl -fsSL https://example.invalid/pulse.tar.gz',
+ false,
+ );
+ expect(guide?.introText).toBe('Follow these steps to update manually:');
+ });
+
+ it('uses the manual-only intro when updatePlan is null (optional-chain short-circuit -> falsy arm)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'systemd' }),
+ makeUpdateInfo(),
+ null,
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ expect(guide?.introText).toBe('Follow these steps to update manually:');
+ });
+
+ it('uses the manual-only intro when updatePlan is undefined (optional-chain short-circuit -> falsy arm)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'systemd' }),
+ makeUpdateInfo(),
+ undefined,
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ expect(guide?.introText).toBe('Follow these steps to update manually:');
+ });
+
+ // -- proxmoxve arm ---------------------------------------------------------
+
+ it('returns the proxmox LXC guide for the proxmoxve deployment arm', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'proxmoxve' }),
+ makeUpdateInfo({ latestVersion: 'v6.0.5' }),
+ makeUpdatePlan({ canAutoUpdate: false }),
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ expect(guide).toStrictEqual({
+ headerTitle: 'Update Available',
+ headerSummary: 'Version v6.0.5 is ready to install',
+ introText: 'Follow these steps to update manually:',
+ steps: [
+ { id: 'open-console', title: 'Open your Pulse LXC console' },
+ { id: 'run-update', title: 'Run the update command:', command: 'update' },
+ {
+ id: 'run-update-note',
+ title: '',
+ note: 'The script will automatically download and install the latest version.',
+ },
+ ],
+ });
+ });
+
+ // -- docker arm: pro steps (dockerUpdate present) --------------------------
+
+ it('returns digest-pinned pro docker steps when dockerUpdate is present (with login note)', () => {
+ const dockerUpdate = makeDockerUpdate();
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),
+ makeUpdateInfo({ dockerUpdate }),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ // The dockerUpdate arm overrides introText with the two-command copy.
+ expect(guide?.introText).toBe('Run these two commands on the Docker host to update:');
+ expect(guide?.steps).toHaveLength(3);
+ expect(guide?.steps[0]).toStrictEqual({
+ id: 'docker-pro-pull',
+ title: 'Pull the new Pulse Pro image (pinned to this release\u2019s digest)',
+ command: dockerUpdate.composePullCommand,
+ commandCodeClass: PRO_STEP_CODE_CLASS,
+ });
+ expect(guide?.steps[1]).toStrictEqual({
+ id: 'docker-pro-up',
+ title: 'Recreate the container on the new image',
+ command: dockerUpdate.composeUpCommand,
+ commandCodeClass: PRO_STEP_CODE_CLASS,
+ });
+ // loginCommand truthy arm: a third note step is pushed.
+ expect(guide?.steps[2]?.id).toBe('docker-pro-login-note');
+ expect(guide?.steps[2]?.title).toBe('');
+ expect(guide?.steps[2]?.note).toContain('sign in to the registry first');
+ expect(guide?.steps[2]?.note).toContain(dockerUpdate.loginCommand as string);
+ });
+
+ it('omits the login note step when dockerUpdate has no loginCommand (loginCommand falsy arm)', () => {
+ const dockerUpdate = makeDockerUpdate({ loginCommand: undefined });
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),
+ makeUpdateInfo({ dockerUpdate }),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ expect(guide?.steps).toHaveLength(2);
+ expect(guide?.steps.map((s) => s.id)).toStrictEqual(['docker-pro-pull', 'docker-pro-up']);
+ expect(guide?.steps.some((s) => s.id === 'docker-pro-login-note')).toBe(false);
+ });
+
+ it('reaches the pro steps arm via the (!deploymentType && isDocker) docker fallback, not just deploymentType==="docker"', () => {
+ // Empty/undefined deploymentType with isDocker true must still hit the
+ // docker branch via the second OR operand.
+ const dockerUpdate = makeDockerUpdate();
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: undefined, isDocker: true }),
+ makeUpdateInfo({ dockerUpdate }),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ expect(guide?.steps[0]?.id).toBe('docker-pro-pull');
+ expect(guide?.headerSummary).toBe('Version v6.0.5 is ready to install');
+ });
+
+ // -- docker arm: isProRuntime, no dockerUpdate -----------------------------
+
+ it('returns the pro-unavailable notice when isProRuntime and no dockerUpdate (isProRuntime true arm)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),
+ makeUpdateInfo({ dockerUpdate: undefined }),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ true,
+ );
+ expect(guide?.introText).toBe('Follow these steps to update:');
+ expect(guide?.steps).toHaveLength(1);
+ expect(guide?.steps[0]?.id).toBe('docker-pro-unavailable');
+ expect(guide?.steps[0]?.title).toBe('');
+ // Concrete substrings of the withhold-community-image notice.
+ expect(guide?.steps[0]?.note).toContain('Pulse Pro image');
+ expect(guide?.steps[0]?.note).toContain('Private Release Access');
+ expect(guide?.steps[0]?.note).toContain('Do not pull the public rcourtman/pulse image');
+ });
+
+ // -- docker arm: community guidance (not pro, no dockerUpdate) -------------
+
+ it('returns community docker guidance with the image tag interpolated when not pro and no dockerUpdate', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),
+ makeUpdateInfo({ dockerUpdate: undefined }),
+ makeUpdatePlan({ canAutoUpdate: true }),
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ // isProRuntime defaults to false too; verify the default-arg path.
+ expect(guide?.steps).toHaveLength(2);
+ expect(guide?.steps[0]).toStrictEqual({
+ id: 'docker-compose-update',
+ title: 'Pull the new image and recreate the container',
+ command: 'docker compose pull && docker compose up -d',
+ });
+ expect(guide?.steps[1]?.id).toBe('docker-manual-note');
+ // The dockerImageTag is interpolated into the non-compose note.
+ expect(guide?.steps[1]?.note).toContain('docker pull rcourtman/pulse:v6.0.5');
+ expect(guide?.steps[1]?.note).toContain('docker stop pulse && docker rm pulse');
+ // introText ternary truthy arm flows through to the community guide.
+ expect(guide?.introText).toBe(
+ 'Click "Install Update" above for automatic installation, or update manually:',
+ );
+ });
+
+ it('honours the isProRuntime default (false) when the trailing arg is omitted', () => {
+ // Calling with 5 args exercises the `isProRuntime = false` default.
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),
+ makeUpdateInfo({ dockerUpdate: undefined }),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ );
+ expect(guide?.steps[0]?.id).toBe('docker-compose-update');
+ });
+
+ // -- systemd / manual arm --------------------------------------------------
+
+ it('returns the systemd guide with the download command and code class (systemd arm)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'systemd' }),
+ makeUpdateInfo({ latestVersion: 'v6.1.0' }),
+ makeUpdatePlan({ canAutoUpdate: false }),
+ 'v6.1.0',
+ 'curl -fsSL https://example.invalid/pulse.tar.gz | tar',
+ false,
+ );
+ expect(guide).toStrictEqual({
+ headerTitle: 'Update Available',
+ headerSummary: 'Version v6.1.0 is ready to install',
+ introText: 'Follow these steps to update manually:',
+ steps: [
+ { id: 'systemd-stop', title: 'Stop the service', command: 'sudo systemctl stop pulse' },
+ {
+ id: 'systemd-download',
+ title: 'Download and extract the new version',
+ command: 'curl -fsSL https://example.invalid/pulse.tar.gz | tar',
+ commandCodeClass: SYSTEMD_DOWNLOAD_CODE_CLASS,
+ },
+ { id: 'systemd-start', title: 'Start the service', command: 'sudo systemctl start pulse' },
+ ],
+ });
+ });
+
+ it('returns the same systemd-shaped guide for the manual deployment arm (second OR operand)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'manual' }),
+ makeUpdateInfo(),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl-download',
+ false,
+ );
+ expect(guide?.steps.map((s) => s.id)).toStrictEqual([
+ 'systemd-stop',
+ 'systemd-download',
+ 'systemd-start',
+ ]);
+ expect(guide?.steps[1]?.command).toBe('curl-download');
+ expect(guide?.steps[1]?.commandCodeClass).toBe(SYSTEMD_DOWNLOAD_CODE_CLASS);
+ });
+
+ // -- development arm -------------------------------------------------------
+
+ it('returns the git/make development guide for the development arm', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'development' }),
+ makeUpdateInfo(),
+ makeUpdatePlan({ canAutoUpdate: false }),
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ expect(guide).toStrictEqual({
+ headerTitle: 'Update Available',
+ headerSummary: 'Version v6.0.5 is ready to install',
+ introText: 'Follow these steps to update manually:',
+ steps: [
+ { id: 'development-pull', title: 'Pull the latest changes', command: 'git pull origin main' },
+ { id: 'development-build', title: 'Rebuild and restart', command: 'make build && make run' },
+ ],
+ });
+ });
+
+ // -- final return null -----------------------------------------------------
+
+ it('returns null for an unrecognised non-empty deployment type (final fallthrough)', () => {
+ expect(
+ buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'kubernetes', isDocker: false }),
+ makeUpdateInfo(),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ false,
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null when deploymentType is absent and isDocker is false (docker OR fallback fails -> fallthrough)', () => {
+ expect(
+ buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: undefined, isDocker: false }),
+ makeUpdateInfo(),
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ false,
+ ),
+ ).toBeNull();
+ });
+
+ // -- suspected source-behaviour documentation ------------------------------
+ // When updateInfo is absent the headerSummary interpolates undefined, producing
+ // "Version undefined is ready to install". This test pins the current behaviour
+ // (see GLM_REPORT.md suspected-bug note). No source change is made here.
+
+ it('interpolates "undefined" into headerSummary when updateInfo is null (documented suspect behaviour)', () => {
+ const guide = buildUpdateInstallGuide(
+ makeVersionInfo({ deploymentType: 'proxmoxve' }),
+ null,
+ makeUpdatePlan(),
+ 'v6.0.5',
+ 'curl',
+ false,
+ );
+ expect(guide?.headerSummary).toBe('Version undefined is ready to install');
+ });
+});
diff --git a/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.branchcov0712.test.ts b/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.branchcov0712.test.ts
new file mode 100644
index 0000000000..8f153ccbef
--- /dev/null
+++ b/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.branchcov0712.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getHistoryRangeDays,
+ resolveHistoryRangeWithinLimit,
+ type HistoryRangeOption,
+} from '@/components/Storage/historyRangeAccess';
+import type { HistoryTimeRange } from '@/api/charts';
+
+const options: readonly HistoryRangeOption[] = [
+ { value: '30m', label: '30m' },
+ { value: '24h', label: '24h' },
+ { value: '7d', label: '7d' },
+ { value: '14d', label: '14d' },
+ { value: '30d', label: '30d' },
+ { value: '90d', label: '90d' },
+];
+
+describe('getHistoryRangeDays (branch coverage)', () => {
+ it('returns 0 when the range token does not match the <number><m|h|d> shape', () => {
+ // Hits the `!match` early-return guard from several malformed shapes.
+ expect(getHistoryRangeDays('' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays('abc' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays('12' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays('7w' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays('ms' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays(' 24h' as HistoryTimeRange)).toBe(0);
+ });
+
+ it('returns 0 when the numeric portion parses to a non-positive value', () => {
+ // `0m` matches the regex, but parseInt yields 0 which trips `value <= 0`.
+ expect(getHistoryRangeDays('0m' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays('0h' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays('0d' as HistoryTimeRange)).toBe(0);
+ expect(getHistoryRangeDays('00d' as HistoryTimeRange)).toBe(0);
+ });
+
+ it('converts minutes to a fractional day value', () => {
+ // `case 'm'` arm: value / (24 * 60).
+ expect(getHistoryRangeDays('30m')).toBeCloseTo(1 / 48);
+ expect(getHistoryRangeDays('1m' as HistoryTimeRange)).toBeCloseTo(1 / (24 * 60));
+ expect(getHistoryRangeDays('60m' as HistoryTimeRange)).toBeCloseTo(1 / 24);
+ });
+
+ it('converts hours to a fractional day value', () => {
+ // `case 'h'` arm: value / 24.
+ expect(getHistoryRangeDays('24h')).toBe(1);
+ expect(getHistoryRangeDays('12h' as HistoryTimeRange)).toBe(0.5);
+ expect(getHistoryRangeDays('1h' as HistoryTimeRange)).toBeCloseTo(1 / 24);
+ });
+
+ it('passes through whole-day values unchanged', () => {
+ // `case 'd'` arm: returns value verbatim.
+ expect(getHistoryRangeDays('7d')).toBe(7);
+ expect(getHistoryRangeDays('30d')).toBe(30);
+ expect(getHistoryRangeDays('90d')).toBe(90);
+ });
+});
+
+describe('resolveHistoryRangeWithinLimit (branch coverage)', () => {
+ it('returns the current range verbatim when it is already inside the unlocked set', () => {
+ // `available.some(...) === true` branch.
+ // With max 7d, the available set is ['30m','24h','7d']; '7d' is a member.
+ expect(resolveHistoryRangeWithinLimit('7d', options, 7)).toBe('7d');
+ // A locked current range that still happens to be unlocked (e.g. 24h at 7d cap).
+ expect(resolveHistoryRangeWithinLimit('24h', options, 7)).toBe('24h');
+ });
+
+ it('clamps down to the highest unlocked range when the current range is locked out', () => {
+ // `available.some(...) === false` then `available.length > 0` branch.
+ expect(resolveHistoryRangeWithinLimit('90d', options, 7)).toBe('7d');
+ expect(resolveHistoryRangeWithinLimit('30d', options, 1)).toBe('24h');
+ });
+
+ it('falls back to the first option when no option is unlocked but options exist', () => {
+ // `available.length === 0` then `options.length > 0` branch -> options[0].value.
+ // maxHistoryDays 0 excludes every standard option (30m alone is ~0.0208 days).
+ expect(resolveHistoryRangeWithinLimit('7d', options, 0)).toBe('30m');
+ expect(resolveHistoryRangeWithinLimit('90d', options, 0)).toBe('30m');
+ });
+
+ it("falls back to '24h' when both available and options are empty", () => {
+ // `available.length === 0` then `options.length === 0` branch -> literal '24h'.
+ expect(resolveHistoryRangeWithinLimit('7d', [], 7)).toBe('24h');
+ expect(resolveHistoryRangeWithinLimit('90d', [], 0)).toBe('24h');
+ });
+
+ it('clamps down to the last option when the available set is a strict subset', () => {
+ // Distinct from the first clamp test: a middle current range ('14d') locked
+ // out at max 1 day resolves to the highest unlocked ('24h'), exercising the
+ // `available[available.length - 1].value` indexing with a multi-element set.
+ expect(resolveHistoryRangeWithinLimit('14d', options, 1)).toBe('24h');
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/thresholdSliderModel.branchcov0712.test.ts b/frontend-modern/src/components/Workloads/__tests__/thresholdSliderModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..415a0144d9
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/thresholdSliderModel.branchcov0712.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/temperature', () => ({
+ formatTemperature: (value: number) => `${value}°C`,
+ getTemperatureSymbol: () => '°C',
+}));
+
+import { getThresholdSliderPosition } from '../thresholdSliderModel';
+
+describe('getThresholdSliderPosition (branch coverage 2)', () => {
+ describe('default bounds (min ?? 0 and max ?? 100 both fall through)', () => {
+ it('returns the in-range percent using the default 0-100 bounds (45 -> 45)', () => {
+ expect(getThresholdSliderPosition(45)).toBe(45);
+ });
+
+ it('returns 50 for the midpoint of the default bounds', () => {
+ expect(getThresholdSliderPosition(50)).toBe(50);
+ });
+
+ it('returns 0 at the minimum boundary (value === min -> percent 0, Math.max passthrough)', () => {
+ expect(getThresholdSliderPosition(0)).toBe(0);
+ });
+
+ it('returns 100 at the maximum boundary (value === max -> Math.min passthrough at 100)', () => {
+ expect(getThresholdSliderPosition(100)).toBe(100);
+ });
+ });
+
+ describe('custom bounds (both min and max provided, no ?? defaults used)', () => {
+ it('maps a value to a percent across a custom [50,100] range (60 -> 20)', () => {
+ expect(getThresholdSliderPosition(60, 50, 100)).toBe(20);
+ });
+
+ it('returns 0 when the value sits at the custom min', () => {
+ expect(getThresholdSliderPosition(50, 50, 100)).toBe(0);
+ });
+
+ it('returns 100 when the value sits at the custom max', () => {
+ expect(getThresholdSliderPosition(100, 50, 100)).toBe(100);
+ });
+
+ it('supports a negative min bound (0 over [-50,50] -> 50)', () => {
+ expect(getThresholdSliderPosition(0, -50, 50)).toBe(50);
+ });
+
+ it('returns a fractional percent when the range does not divide evenly (25 over [0,200] -> 12.5)', () => {
+ expect(getThresholdSliderPosition(25, 0, 200)).toBe(12.5);
+ });
+ });
+
+ describe('mixed default/custom bounds (only one ?? arm falls through)', () => {
+ it('uses the default min when min is undefined and a custom max is supplied (50 over [0,200] -> 25)', () => {
+ expect(getThresholdSliderPosition(50, undefined, 200)).toBe(25);
+ });
+
+ it('uses the default max when max is undefined and a custom min is supplied (75 over [50,100] -> 50)', () => {
+ expect(getThresholdSliderPosition(75, 50, undefined)).toBe(50);
+ });
+ });
+
+ describe('clamping arms of Math.max(0, Math.min(100, percent))', () => {
+ it('clamps a value above max down to 100 (Math.min(100, percent) -> 100)', () => {
+ expect(getThresholdSliderPosition(150)).toBe(100);
+ });
+
+ it('clamps a value far above a custom max down to 100', () => {
+ expect(getThresholdSliderPosition(999, 50, 100)).toBe(100);
+ });
+
+ it('clamps a value below min up to 0 (Math.max(0, percent) -> 0)', () => {
+ expect(getThresholdSliderPosition(-20)).toBe(0);
+ });
+
+ it('clamps a value below a custom min up to 0', () => {
+ expect(getThresholdSliderPosition(10, 50, 100)).toBe(0);
+ });
+ });
+
+ describe('degenerate range guard (range <= 0 early return)', () => {
+ it('returns 0 when min equals max (range === 0 boundary)', () => {
+ expect(getThresholdSliderPosition(50, 50, 50)).toBe(0);
+ });
+
+ it('returns 0 when min exceeds max (range strictly negative)', () => {
+ expect(getThresholdSliderPosition(50, 100, 50)).toBe(0);
+ });
+
+ it('returns 0 at the degenerate guard even when the value is below the min', () => {
+ expect(getThresholdSliderPosition(-100, 100, 100)).toBe(0);
+ });
+ });
+
+ describe('non-finite value (observed behavior)', () => {
+ it('propagates NaN through the clamp instead of coercing to 0 (robustness gap)', () => {
+ const result = getThresholdSliderPosition(Number.NaN, 0, 100);
+ expect(result).toBeNaN();
+ });
+ });
+});
diff --git a/frontend-modern/src/components/__tests__/updateVersion.branchcov0712.test.ts b/frontend-modern/src/components/__tests__/updateVersion.branchcov0712.test.ts
new file mode 100644
index 0000000000..585d60eb41
--- /dev/null
+++ b/frontend-modern/src/components/__tests__/updateVersion.branchcov0712.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildDockerImageTag,
+ buildLinuxAmd64DownloadCommand,
+ buildLinuxAmd64TarballName,
+ buildReleaseNotesUrl,
+} from '@/components/updateVersion';
+
+const GITHUB_RELEASES_BASE_URL = 'https://github.com/rcourtman/Pulse/releases';
+
+describe('buildReleaseNotesUrl branch coverage', () => {
+ it('returns the releases index URL when the version normalizes to empty (falsy-tag ternary arm)', () => {
+ expect(buildReleaseNotesUrl(undefined)).toBe(GITHUB_RELEASES_BASE_URL);
+ expect(buildReleaseNotesUrl(null)).toBe(GITHUB_RELEASES_BASE_URL);
+ expect(buildReleaseNotesUrl('')).toBe(GITHUB_RELEASES_BASE_URL);
+ expect(buildReleaseNotesUrl(' ')).toBe(GITHUB_RELEASES_BASE_URL);
+ expect(buildReleaseNotesUrl('\t\n')).toBe(GITHUB_RELEASES_BASE_URL);
+ // A bare leading "v" is stripped to "" by normalizeReleaseVersion, so the
+ // formatted tag is empty and the falsy arm is taken here too.
+ expect(buildReleaseNotesUrl('v')).toBe(GITHUB_RELEASES_BASE_URL);
+ expect(buildReleaseNotesUrl('V')).toBe(GITHUB_RELEASES_BASE_URL);
+ });
+
+ it('returns the tag-scoped URL when a version is present (truthy-tag ternary arm)', () => {
+ expect(buildReleaseNotesUrl('v5.1.0')).toBe(`${GITHUB_RELEASES_BASE_URL}/tag/v5.1.0`);
+ // No leading "v": normalize keeps it, format re-adds the prefix.
+ expect(buildReleaseNotesUrl('5.1.0')).toBe(`${GITHUB_RELEASES_BASE_URL}/tag/v5.1.0`);
+ // Surrounding whitespace is trimmed before formatting.
+ expect(buildReleaseNotesUrl(' v5.1.0 ')).toBe(`${GITHUB_RELEASES_BASE_URL}/tag/v5.1.0`);
+ // Uppercase "V" prefix is stripped case-insensitively.
+ expect(buildReleaseNotesUrl('V5.1.0')).toBe(`${GITHUB_RELEASES_BASE_URL}/tag/v5.1.0`);
+ });
+});
+
+describe('buildDockerImageTag branch coverage', () => {
+ it('falls back to "latest" when the version normalizes to empty (|| fallback arm)', () => {
+ expect(buildDockerImageTag(undefined)).toBe('latest');
+ expect(buildDockerImageTag(null)).toBe('latest');
+ expect(buildDockerImageTag('')).toBe('latest');
+ expect(buildDockerImageTag(' ')).toBe('latest');
+ expect(buildDockerImageTag('v')).toBe('latest');
+ expect(buildDockerImageTag('V')).toBe('latest');
+ });
+
+ it('returns the normalized version when present (truthy arm)', () => {
+ expect(buildDockerImageTag('v5.1.0')).toBe('5.1.0');
+ expect(buildDockerImageTag('5.1.0')).toBe('5.1.0');
+ expect(buildDockerImageTag(' v5.1.0 ')).toBe('5.1.0');
+ expect(buildDockerImageTag('V5.1.0')).toBe('5.1.0');
+ });
+});
+
+describe('buildLinuxAmd64TarballName branch coverage', () => {
+ it('returns the unversioned tarball name when the version normalizes to empty (falsy ternary arm)', () => {
+ expect(buildLinuxAmd64TarballName(undefined)).toBe('pulse-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName(null)).toBe('pulse-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName('')).toBe('pulse-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName(' ')).toBe('pulse-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName('v')).toBe('pulse-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName('V')).toBe('pulse-linux-amd64.tar.gz');
+ });
+
+ it('returns the versioned tarball name when a version is present (truthy ternary arm)', () => {
+ expect(buildLinuxAmd64TarballName('v5.1.0')).toBe('pulse-v5.1.0-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName('5.1.0')).toBe('pulse-v5.1.0-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName(' v5.1.0 ')).toBe('pulse-v5.1.0-linux-amd64.tar.gz');
+ expect(buildLinuxAmd64TarballName('V5.1.0')).toBe('pulse-v5.1.0-linux-amd64.tar.gz');
+ });
+});
+
+describe('buildLinuxAmd64DownloadCommand branch coverage', () => {
+ it('returns an empty string when the version normalizes to empty (early-return guard)', () => {
+ expect(buildLinuxAmd64DownloadCommand(undefined)).toBe('');
+ expect(buildLinuxAmd64DownloadCommand(null)).toBe('');
+ expect(buildLinuxAmd64DownloadCommand('')).toBe('');
+ expect(buildLinuxAmd64DownloadCommand(' ')).toBe('');
+ expect(buildLinuxAmd64DownloadCommand('v')).toBe('');
+ expect(buildLinuxAmd64DownloadCommand('V')).toBe('');
+ });
+
+ it('builds the full curl + tar command for a "v"-prefixed version (truthy-tag arm)', () => {
+ const expected =
+ 'curl -fL --retry 3 --retry-delay 2 -o pulse-v5.1.0-linux-amd64.tar.gz ' +
+ `${GITHUB_RELEASES_BASE_URL}/download/v5.1.0/pulse-v5.1.0-linux-amd64.tar.gz\n` +
+ 'sudo tar -xzf pulse-v5.1.0-linux-amd64.tar.gz -C /usr/local/bin pulse';
+ expect(buildLinuxAmd64DownloadCommand('v5.1.0')).toBe(expected);
+ });
+
+ it('uses a consistent tag and tarball name for an un-prefixed version (truthy-tag arm)', () => {
+ const expected =
+ 'curl -fL --retry 3 --retry-delay 2 -o pulse-v5.1.0-linux-amd64.tar.gz ' +
+ `${GITHUB_RELEASES_BASE_URL}/download/v5.1.0/pulse-v5.1.0-linux-amd64.tar.gz\n` +
+ 'sudo tar -xzf pulse-v5.1.0-linux-amd64.tar.gz -C /usr/local/bin pulse';
+ expect(buildLinuxAmd64DownloadCommand('5.1.0')).toBe(expected);
+ });
+
+ it('trims surrounding whitespace before building the command (truthy-tag arm)', () => {
+ const expected =
+ 'curl -fL --retry 3 --retry-delay 2 -o pulse-v5.1.0-linux-amd64.tar.gz ' +
+ `${GITHUB_RELEASES_BASE_URL}/download/v5.1.0/pulse-v5.1.0-linux-amd64.tar.gz\n` +
+ 'sudo tar -xzf pulse-v5.1.0-linux-amd64.tar.gz -C /usr/local/bin pulse';
+ expect(buildLinuxAmd64DownloadCommand(' v5.1.0 ')).toBe(expected);
+ });
+});
diff --git a/frontend-modern/src/components/shared/__tests__/dialogModel.branchcov0712.test.ts b/frontend-modern/src/components/shared/__tests__/dialogModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..1762abb1f5
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/dialogModel.branchcov0712.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from 'vitest';
+import type { DialogLayout } from '@/components/shared/dialogModel';
+import {
+ getDialogAlignmentClass,
+ getDialogPanelClass,
+ getDialogViewportClass,
+} from '@/components/shared/dialogModel';
+
+// Drive every branch of getDialogViewportClass, getDialogAlignmentClass, and
+// getDialogPanelClass. Each function is a single ternary keyed on
+// `layout === 'drawer-right'`; getDialogPanelClass adds a `panelClass ?? ...`
+// nullish-coalescing with its own inner drawer-vs-modal ternary, plus a final
+// `.trim()`. Every assertion is exact-string equality.
+
+describe('getDialogViewportClass', () => {
+ it("returns the 'p-0' padding arm for the drawer-right layout", () => {
+ expect(getDialogViewportClass('drawer-right')).toBe(
+ 'relative h-full overflow-y-auto pointer-events-none p-0',
+ );
+ });
+
+ it("returns the 'p-4 sm:p-6' padding arm for the modal layout", () => {
+ expect(getDialogViewportClass('modal')).toBe(
+ 'relative h-full overflow-y-auto pointer-events-none p-4 sm:p-6',
+ );
+ });
+
+ it("falls into the modal (else) arm for any value that isn't strictly 'drawer-right'", () => {
+ // Defensive: strict equality means a foreign string lands in the else arm,
+ // producing the same classes as 'modal'.
+ const foreign = 'drawer-left' as unknown as DialogLayout;
+ expect(getDialogViewportClass(foreign)).toBe(
+ 'relative h-full overflow-y-auto pointer-events-none p-4 sm:p-6',
+ );
+ });
+});
+
+describe('getDialogAlignmentClass', () => {
+ it('returns the stretch/right-justified arm for the drawer-right layout', () => {
+ expect(getDialogAlignmentClass('drawer-right')).toBe(
+ 'flex min-h-full items-stretch justify-end',
+ );
+ });
+
+ it('returns the centered arm for the modal layout', () => {
+ expect(getDialogAlignmentClass('modal')).toBe(
+ 'flex min-h-full items-start justify-center sm:items-center',
+ );
+ });
+
+ it("falls into the modal (else) arm for any value that isn't strictly 'drawer-right'", () => {
+ const foreign = 'bottom-sheet' as unknown as DialogLayout;
+ expect(getDialogAlignmentClass(foreign)).toBe(
+ 'flex min-h-full items-start justify-center sm:items-center',
+ );
+ });
+});
+
+describe('getDialogPanelClass', () => {
+ // The shared leading segment of every result, exactly as emitted by the
+ // template literal before the layout branch and panelClass slot.
+ const BASE =
+ 'relative flex min-h-0 w-full flex-col overflow-hidden bg-surface border border-border outline-none pointer-events-auto';
+ const DRAWER_BRANCH =
+ 'h-dvh max-w-[720px] rounded-none border-y-0 border-r-0 animate-slide-up sm:h-full sm:max-h-dvh sm:rounded-l-xl sm:border-y sm:border-r-0';
+ const MODAL_BRANCH = 'max-h-[calc(100dvh-2rem)] rounded-md animate-slide-up';
+
+ describe('layout ternary — drawer-right arm', () => {
+ it('emits the drawer branch and trims the trailing empty fallback when panelClass is undefined', () => {
+ // Exercises: layout === 'drawer-right' (true), panelClass ?? (true → '') arm,
+ // and the .trim() of the trailing whitespace left by the empty fallback.
+ expect(getDialogPanelClass('drawer-right')).toBe(`${BASE} ${DRAWER_BRANCH}`);
+ });
+
+ it('appends a provided panelClass after the drawer branch', () => {
+ // Exercises: layout === 'drawer-right' (true), panelClass ?? left arm (provided).
+ expect(getDialogPanelClass('drawer-right', 'w-[420px]')).toBe(
+ `${BASE} ${DRAWER_BRANCH} w-[420px]`,
+ );
+ });
+
+ it('treats an empty-string panelClass as a present value (?? left arm) yielding the same output as undefined', () => {
+ // ?? only fires for null/undefined, so '' is used verbatim. The trailing
+ // whitespace from the empty slot is then removed by .trim(), producing the
+ // same string as the undefined case above.
+ expect(getDialogPanelClass('drawer-right', '')).toBe(`${BASE} ${DRAWER_BRANCH}`);
+ });
+ });
+
+ describe('layout ternary — modal (else) arm', () => {
+ it('appends the max-w-lg fallback after the modal branch when panelClass is undefined', () => {
+ // Exercises: layout === 'drawer-right' (false), panelClass ?? (false → 'max-w-lg') arm.
+ expect(getDialogPanelClass('modal')).toBe(`${BASE} ${MODAL_BRANCH} max-w-lg`);
+ });
+
+ it('appends a provided panelClass after the modal branch', () => {
+ // Exercises: layout === 'drawer-right' (false), panelClass ?? left arm (provided).
+ expect(getDialogPanelClass('modal', 'max-w-2xl')).toBe(
+ `${BASE} ${MODAL_BRANCH} max-w-2xl`,
+ );
+ });
+
+ it('treats an empty-string panelClass as a present value, dropping the max-w-lg fallback (?? left arm)', () => {
+ // '' is non-nullish so ?? does not fire; the modal-only max-w-lg default
+ // is NOT appended. The trailing whitespace is removed by .trim().
+ expect(getDialogPanelClass('modal', '')).toBe(`${BASE} ${MODAL_BRANCH}`);
+ });
+ });
+
+ describe('layout ternary — defensive (foreign value falls into modal arm)', () => {
+ it('routes a non-DialogLayout string through the modal branch', () => {
+ // Strict equality with 'drawer-right' fails for any other string, so the
+ // else (modal) branch is taken for both the layout class and the panel
+ // fallback. Confirms the function has no hidden third arm.
+ const foreign = 'center' as unknown as DialogLayout;
+ expect(getDialogPanelClass(foreign)).toBe(`${BASE} ${MODAL_BRANCH} max-w-lg`);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/shared/__tests__/mobileNavBarModel.branchcov0712.test.ts b/frontend-modern/src/components/shared/__tests__/mobileNavBarModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..b6138e072c
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/mobileNavBarModel.branchcov0712.test.ts
@@ -0,0 +1,305 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildOrderedMobileNavTabs,
+ getMobileNavAlertBadgeCounts,
+ getMobileNavFadeState,
+ getMobileNavTabAriaLabel,
+ getMobileNavTabButtonClass,
+} from '@/components/shared/mobileNavBarModel';
+import type { MobileNavBarIcon, MobileNavBarUtilityTab } from '@/components/shared/mobileNavBarModel';
+
+// The icon is never rendered by these model-only tests; a cast stub satisfies
+// the Component type without pulling solid-js into a plain .ts file.
+const noopIcon = (() => null) as unknown as MobileNavBarIcon;
+
+// Defaults are tuned to the alerts-scoped functions so their tests stay minimal;
+// non-alerts tests override `id` explicitly.
+function makeUtilityTab(
+ overrides: Partial<MobileNavBarUtilityTab> = {},
+): MobileNavBarUtilityTab {
+ return {
+ id: 'alerts',
+ label: 'Alerts',
+ route: '/alerts',
+ tooltip: 'Alerts',
+ badge: null,
+ count: undefined,
+ breakdown: undefined,
+ icon: noopIcon,
+ ...overrides,
+ };
+}
+
+describe('mobileNavBarModel.branchcov2', () => {
+ describe('getMobileNavAlertBadgeCounts', () => {
+ it('returns null for a non-alerts tab via the id guard (true arm)', () => {
+ const tab = makeUtilityTab({ id: 'settings', count: 9 });
+ expect(getMobileNavAlertBadgeCounts(tab)).toBeNull();
+ });
+
+ it('returns null when count is undefined (!tab.count falsy arm)', () => {
+ expect(getMobileNavAlertBadgeCounts(makeUtilityTab({ count: undefined }))).toBeNull();
+ });
+
+ it('returns null when count is 0 (!tab.count falsy arm, zero is falsy)', () => {
+ expect(getMobileNavAlertBadgeCounts(makeUtilityTab({ count: 0 }))).toBeNull();
+ });
+
+ it('returns null when count is negative (tab.count <= 0 arm)', () => {
+ expect(getMobileNavAlertBadgeCounts(makeUtilityTab({ count: -4 }))).toBeNull();
+ });
+
+ it('returns zeros when breakdown is undefined (?. ?? 0 right arm for both fields)', () => {
+ const tab = makeUtilityTab({ count: 7, breakdown: undefined });
+ expect(getMobileNavAlertBadgeCounts(tab)).toStrictEqual({ critical: 0, warning: 0 });
+ });
+
+ it('returns the breakdown counts when both severities are defined (?. left arm)', () => {
+ const tab = makeUtilityTab({ count: 9, breakdown: { critical: 4, warning: 5 } });
+ expect(getMobileNavAlertBadgeCounts(tab)).toStrictEqual({ critical: 4, warning: 5 });
+ });
+
+ it('preserves an explicit zero critical via ?? (proves ?? is not ||)', () => {
+ const tab = makeUtilityTab({ count: 9, breakdown: { critical: 0, warning: 3 } });
+ expect(getMobileNavAlertBadgeCounts(tab)).toStrictEqual({ critical: 0, warning: 3 });
+ });
+
+ it('preserves an explicit zero warning via ?? (proves ?? is not ||)', () => {
+ const tab = makeUtilityTab({ count: 9, breakdown: { critical: 2, warning: 0 } });
+ expect(getMobileNavAlertBadgeCounts(tab)).toStrictEqual({ critical: 2, warning: 0 });
+ });
+
+ it('falls back to 0 when breakdown.critical is undefined despite breakdown being present', () => {
+ const tab = makeUtilityTab({
+ count: 5,
+ breakdown: {
+ critical: undefined,
+ warning: 2,
+ } as unknown as { critical: number; warning: number },
+ });
+ expect(getMobileNavAlertBadgeCounts(tab)).toStrictEqual({ critical: 0, warning: 2 });
+ });
+ });
+
+ describe('getMobileNavTabAriaLabel', () => {
+ it('returns the bare label for a non-alerts tab with no count (badges null + count falsy)', () => {
+ const tab = makeUtilityTab({ id: 'settings', label: 'Settings', count: undefined });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Settings');
+ });
+
+ it('returns the bare label when count is 0 (count && count > 0 false arm)', () => {
+ const tab = makeUtilityTab({ id: 'settings', label: 'Settings', count: 0 });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Settings');
+ });
+
+ it('uses countLabel when count > 0 (countLabel ?? right-side fallback NOT taken)', () => {
+ const tab = makeUtilityTab({
+ id: 'actions',
+ label: 'Actions',
+ count: 12,
+ countLabel: '12 pending',
+ });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Actions: 12 pending');
+ });
+
+ it('synthesizes "N items" when countLabel is absent (countLabel ?? right arm)', () => {
+ const tab = makeUtilityTab({
+ id: 'actions',
+ label: 'Actions',
+ count: 12,
+ countLabel: undefined,
+ });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Actions: 12 items');
+ });
+
+ it('returns the bare label for an alerts tab whose breakdown is all zeros (parts.length === 0 arm)', () => {
+ const tab = makeUtilityTab({
+ id: 'alerts',
+ label: 'Alerts',
+ count: 5,
+ breakdown: { critical: 0, warning: 0 },
+ });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Alerts');
+ });
+
+ it('lists only critical when warning is 0 (warning push guard false)', () => {
+ const tab = makeUtilityTab({
+ id: 'alerts',
+ label: 'Alerts',
+ count: 4,
+ breakdown: { critical: 3, warning: 0 },
+ });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Alerts: 3 critical');
+ });
+
+ it('lists only warning when critical is 0 (critical push guard false)', () => {
+ const tab = makeUtilityTab({
+ id: 'alerts',
+ label: 'Alerts',
+ count: 4,
+ breakdown: { critical: 0, warning: 2 },
+ });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Alerts: 2 warning');
+ });
+
+ it('joins both severities with a comma when both are > 0', () => {
+ const tab = makeUtilityTab({
+ id: 'alerts',
+ label: 'Alerts',
+ count: 10,
+ breakdown: { critical: 3, warning: 7 },
+ });
+ expect(getMobileNavTabAriaLabel(tab)).toBe('Alerts: 3 critical, 7 warning');
+ });
+ });
+
+ describe('buildOrderedMobileNavTabs', () => {
+ it('returns an empty array when given no tabs', () => {
+ expect(buildOrderedMobileNavTabs([], ['a', 'b'])).toStrictEqual([]);
+ });
+
+ it('reorders tabs to follow the priority list (priority id present -> push branch)', () => {
+ const tabs = [{ id: 'b' }, { id: 'a' }, { id: 'c' }];
+ expect(buildOrderedMobileNavTabs(tabs, ['a', 'b', 'c'])).toStrictEqual([
+ { id: 'a' },
+ { id: 'b' },
+ { id: 'c' },
+ ]);
+ });
+
+ it('skips priority ids absent from tabs (byId.get -> undefined -> if(tab) false arm)', () => {
+ const tabs = [{ id: 'a' }];
+ expect(buildOrderedMobileNavTabs(tabs, ['a', 'x', 'y'])).toStrictEqual([{ id: 'a' }]);
+ });
+
+ it('appends non-priority tabs after priority ones in original input order', () => {
+ const tabs = [{ id: 'extra1' }, { id: 'a' }, { id: 'extra2' }];
+ expect(buildOrderedMobileNavTabs(tabs, ['a'])).toStrictEqual([
+ { id: 'a' },
+ { id: 'extra1' },
+ { id: 'extra2' },
+ ]);
+ });
+
+ it('keeps all tabs in input order when none match the priority set', () => {
+ const tabs = [{ id: 'x' }, { id: 'y' }];
+ expect(buildOrderedMobileNavTabs(tabs, ['a', 'b'])).toStrictEqual([
+ { id: 'x' },
+ { id: 'y' },
+ ]);
+ });
+
+ it('preserves the full tab object (generic T) through reordering', () => {
+ const tabs = [
+ { id: 'kubernetes', kind: 'primary' },
+ { id: 'docker', kind: 'primary' },
+ ];
+ expect(buildOrderedMobileNavTabs(tabs, ['docker', 'kubernetes'])).toStrictEqual([
+ { id: 'docker', kind: 'primary' },
+ { id: 'kubernetes', kind: 'primary' },
+ ]);
+ });
+ });
+
+ describe('getMobileNavTabButtonClass', () => {
+ const BASE =
+ 'relative flex min-h-10 shrink-0 flex-col items-center gap-1 rounded-md px-2 py-1.5 text-[11px] font-medium transition-colors';
+ const ACTIVE = 'bg-blue-50 text-blue-700 dark:bg-blue-900 dark:text-blue-300';
+ const MUTED = 'text-muted';
+
+ it('emits the active palette when active, with no opacity when enabled is omitted', () => {
+ expect(getMobileNavTabButtonClass({ active: true })).toBe(`${BASE} ${ACTIVE}`);
+ });
+
+ it('emits text-muted when inactive (active ternary false arm)', () => {
+ expect(getMobileNavTabButtonClass({ active: false })).toBe(`${BASE} ${MUTED}`);
+ });
+
+ it('appends opacity-70 when enabled is strictly false on an active tab', () => {
+ expect(getMobileNavTabButtonClass({ active: true, enabled: false })).toBe(
+ `${BASE} ${ACTIVE} opacity-70`,
+ );
+ });
+
+ it('appends opacity-70 when enabled is strictly false on an inactive tab', () => {
+ expect(getMobileNavTabButtonClass({ active: false, enabled: false })).toBe(
+ `${BASE} ${MUTED} opacity-70`,
+ );
+ });
+
+ it('does not append opacity-70 when enabled is true (strict === false check)', () => {
+ expect(getMobileNavTabButtonClass({ active: true, enabled: true })).toBe(`${BASE} ${ACTIVE}`);
+ });
+ });
+
+ describe('getMobileNavFadeState', () => {
+ // Helper: jsdom reports 0 for all scroll geometry by default, so define the
+ // readonly scroll metrics as configurable own properties on the instance.
+ function makeScrollEl(props: {
+ scrollWidth: number;
+ clientWidth: number;
+ scrollLeft: number;
+ }): HTMLDivElement {
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollWidth', { configurable: true, value: props.scrollWidth });
+ Object.defineProperty(el, 'clientWidth', { configurable: true, value: props.clientWidth });
+ Object.defineProperty(el, 'scrollLeft', { configurable: true, value: props.scrollLeft });
+ return el;
+ }
+
+ it('returns both fades false when the element is undefined (early-return guard)', () => {
+ expect(getMobileNavFadeState(undefined)).toStrictEqual({
+ showLeftFade: false,
+ showRightFade: false,
+ });
+ });
+
+ it('returns both fades false when there is no scrollable overflow (maxScrollLeft <= 1)', () => {
+ const el = makeScrollEl({ scrollWidth: 100, clientWidth: 100, scrollLeft: 0 });
+ expect(getMobileNavFadeState(el)).toStrictEqual({
+ showLeftFade: false,
+ showRightFade: false,
+ });
+ });
+
+ it('shows only the right fade at the left edge (scrollLeft > 1 false)', () => {
+ const el = makeScrollEl({ scrollWidth: 200, clientWidth: 100, scrollLeft: 0 });
+ expect(getMobileNavFadeState(el)).toStrictEqual({
+ showLeftFade: false,
+ showRightFade: true,
+ });
+ });
+
+ it('treats scrollLeft === 1 as not past the left threshold (> 1 strict boundary)', () => {
+ const el = makeScrollEl({ scrollWidth: 200, clientWidth: 100, scrollLeft: 1 });
+ expect(getMobileNavFadeState(el)).toStrictEqual({
+ showLeftFade: false,
+ showRightFade: true,
+ });
+ });
+
+ it('shows both fades in the middle of the scroll range', () => {
+ const el = makeScrollEl({ scrollWidth: 200, clientWidth: 100, scrollLeft: 50 });
+ expect(getMobileNavFadeState(el)).toStrictEqual({
+ showLeftFade: true,
+ showRightFade: true,
+ });
+ });
+
+ it('shows only the left fade at the far-right edge (scrollLeft < maxScrollLeft - 1 false)', () => {
+ const el = makeScrollEl({ scrollWidth: 200, clientWidth: 100, scrollLeft: 100 });
+ expect(getMobileNavFadeState(el)).toStrictEqual({
+ showLeftFade: true,
+ showRightFade: false,
+ });
+ });
+
+ it('treats scrollLeft === maxScrollLeft - 1 as already at the right edge (< strict boundary)', () => {
+ const el = makeScrollEl({ scrollWidth: 200, clientWidth: 100, scrollLeft: 99 });
+ expect(getMobileNavFadeState(el)).toStrictEqual({
+ showLeftFade: true,
+ showRightFade: false,
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/components/shared/__tests__/webInterfaceUrlFieldModel.branchcov0712.test.ts b/frontend-modern/src/components/shared/__tests__/webInterfaceUrlFieldModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..84494c2fb9
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/webInterfaceUrlFieldModel.branchcov0712.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getWebInterfaceTargetLabel,
+ validateWebInterfaceCustomUrl,
+} from '@/components/shared/webInterfaceUrlFieldModel';
+import type { WebInterfaceUrlFieldProps } from '@/components/shared/webInterfaceUrlFieldModel';
+
+// Branch-coverage suite for the two still-uncovered pure helpers in
+// webInterfaceUrlFieldModel.ts. Every assertion is a concrete equality check
+// against the real return shape/string so it pins the exact branch taken.
+
+describe('webInterfaceUrlFieldModel.branchcov2', () => {
+ describe('validateWebInterfaceCustomUrl', () => {
+ it('returns null for an empty value (the `!value` early-return arm)', () => {
+ expect(validateWebInterfaceCustomUrl('')).toBeNull();
+ });
+
+ it('returns the parse-failure message for a non-URL string (catch arm)', () => {
+ expect(validateWebInterfaceCustomUrl('not-a-url')).toBe(
+ 'Enter a valid URL (for example: https://198.51.100.100:8080).',
+ );
+ });
+
+ it('returns the parse-failure message for a whitespace-only value (truthy string that URL rejects)', () => {
+ // ' ' is a truthy string so it bypasses the `!value` guard but still
+ // throws inside `new URL(...)`, exercising the catch arm via a different
+ // inbound state than a plain word.
+ expect(validateWebInterfaceCustomUrl(' ')).toBe(
+ 'Enter a valid URL (for example: https://198.51.100.100:8080).',
+ );
+ });
+
+ it('returns the parse-failure message for a bare scheme like "http://" (URL constructor throws)', () => {
+ expect(validateWebInterfaceCustomUrl('http://')).toBe(
+ 'Enter a valid URL (for example: https://198.51.100.100:8080).',
+ );
+ });
+
+ it('rejects an ftp:// URL via the protocol guard (neither http: nor https:)', () => {
+ expect(validateWebInterfaceCustomUrl('ftp://example.com')).toBe(
+ 'URL must start with http:// or https://.',
+ );
+ });
+
+ it('rejects a file:// URL via the protocol guard (different non-http arm of the &&)', () => {
+ expect(validateWebInterfaceCustomUrl('file:///etc/hostname')).toBe(
+ 'URL must start with http:// or https://.',
+ );
+ });
+
+ it('accepts a well-formed http:// URL with host + port (protocol guard pass, returns null)', () => {
+ expect(validateWebInterfaceCustomUrl('http://198.51.100.100:8080')).toBeNull();
+ });
+
+ it('accepts a well-formed https:// URL (https: arm of the protocol comparison)', () => {
+ expect(validateWebInterfaceCustomUrl('https://pve1.local:8006')).toBeNull();
+ });
+
+ it('accepts an uppercase HTTPS:// scheme because new URL normalizes the protocol', () => {
+ // Confirms the protocol equality check works against the lowercased
+ // protocol produced by the URL parser, not the raw input.
+ expect(validateWebInterfaceCustomUrl('HTTPS://example.com')).toBeNull();
+ });
+
+ it('accepts an IPv6 http URL (hostname populated, no protocol/hostname error)', () => {
+ expect(validateWebInterfaceCustomUrl('http://[2001:db8::1]/')).toBeNull();
+ });
+
+ // NOTE on the `if (!parsed.hostname)` branch (lines 37-39): the WHATWG URL
+ // parser throws for every http:/https: input that would otherwise yield an
+ // empty hostname (verified: 'http://', 'http:///', 'http://?q', 'http://[]',
+ // 'https://', ... all throw), and any input that parses to an empty hostname
+ // is always a non-http/https scheme (e.g. 'file:///x') which is caught by the
+ // earlier protocol guard. That branch is therefore unreachable from the
+ // public `(value: string) => ...` entry point under the real `URL` runtime,
+ // so it is left uncovered here rather than papered over with a cast that
+ // could not actually land inside the branch.
+ });
+
+ describe('getWebInterfaceTargetLabel', () => {
+ it('returns the trimmed targetLabel when present, overriding the kind default', () => {
+ // kind 'guest' would default to 'workload', so returning 'container-7'
+ // proves the explicit label wins.
+ expect(
+ getWebInterfaceTargetLabel('guest', ' container-7 '),
+ ).toBe('container-7');
+ });
+
+ it('returns the trimmed non-empty label even for agent kind (label still wins over default)', () => {
+ expect(getWebInterfaceTargetLabel('agent', '\tnginx\t')).toBe('nginx');
+ });
+
+ it('falls back to "agent" when the label is undefined and kind is agent (ternary true arm)', () => {
+ expect(getWebInterfaceTargetLabel('agent', undefined)).toBe('agent');
+ });
+
+ it('falls back to "workload" when the label is undefined and kind is guest (ternary false arm)', () => {
+ expect(getWebInterfaceTargetLabel('guest', undefined)).toBe('workload');
+ });
+
+ it('falls back to "workload" when the label is undefined and kind is docker (ternary false arm)', () => {
+ expect(getWebInterfaceTargetLabel('docker', undefined)).toBe('workload');
+ });
+
+ it('treats a whitespace-only label as empty and falls back to the agent default', () => {
+ // Exercises normalizeWebInterfaceUrl(' ').trim() === '' then the ternary.
+ expect(getWebInterfaceTargetLabel('agent', ' ')).toBe('agent');
+ });
+
+ it('treats an empty-string label as empty and falls back to the workload default for guest', () => {
+ expect(getWebInterfaceTargetLabel('guest', '')).toBe('workload');
+ });
+
+ it('treats a null label (via cast) as empty using normalizeWebInterfaceUrl\'s `value || ""` arm', () => {
+ // null is not a valid string; cast through unknown to satisfy strict
+ // null checks while still exercising the real `value || ''` fallback
+ // inside normalizeWebInterfaceUrl at runtime.
+ const nullLabel = null as unknown as Parameters<
+ typeof getWebInterfaceTargetLabel
+ >[1];
+ expect(getWebInterfaceTargetLabel('docker', nullLabel)).toBe('workload');
+ });
+
+ it('covers all three metadataKind values against the same empty-label input', () => {
+ const kinds: WebInterfaceUrlFieldProps['metadataKind'][] = [
+ 'guest',
+ 'agent',
+ 'docker',
+ ];
+ const results = kinds.map((k) => getWebInterfaceTargetLabel(k, undefined));
+ expect(results).toStrictEqual(['workload', 'agent', 'workload']);
+ });
+ });
+});
diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..8978d80333
--- /dev/null
+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, it } from 'vitest';
+
+import type { UIEmailConfig } from '../types';
+
+import { buildEmailConfigPayload } from '../alertDestinationsModel';
+
+// ---------------------------------------------------------------------------
+// Fixture — minimal valid UIEmailConfig. Tests override only the fields
+// relevant to the branch under examination.
+// ---------------------------------------------------------------------------
+
+function makeUIEmailConfig(overrides: Partial<UIEmailConfig> = {}): UIEmailConfig {
+ return {
+ enabled: true,
+ provider: 'smtp',
+ server: 'smtp.internal',
+ port: 587,
+ username: '[email protected]',
+ password: 'secret',
+ tls: true,
+ startTLS: true,
+ replyTo: '',
+ maxRetries: 3,
+ retryDelay: 60,
+ rateLimit: 0,
+ ...overrides,
+ };
+}
+
+describe('buildEmailConfigPayload — branch coverage (batch 2)', () => {
+ // -----------------------------------------------------------------------
+ // to: .map(trim) / .filter(length > 0)
+ // - filter true arm: entry.length > 0 → element kept
+ // - filter false arm: entry.length === 0 → element dropped
+ // - map no-op arm: already-trimmed string
+ // - map strip arm: leading/trailing/whitespace removed
+ // - zero-iteration path: empty input array
+ // -----------------------------------------------------------------------
+ describe('to array transformation', () => {
+ it('returns an empty to array when the input to list is empty', () => {
+ const result = buildEmailConfigPayload(makeUIEmailConfig({ to: [] }));
+ expect(result.to).toStrictEqual([]);
+ });
+
+ it('drops every recipient when all entries are whitespace-only', () => {
+ // Each entry is non-empty before trim but becomes '' after trim,
+ // exercising the `entry.length > 0 === false` filter arm for
+ // strings that only become empty *after* trimming.
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({ to: [' ', '\t', '\n'] }),
+ );
+ expect(result.to).toStrictEqual([]);
+ });
+
+ it('strips leading-only, trailing-only, and tab-padded whitespace independently', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({
+ to: [
+ ],
+ }),
+ );
+ expect(result.to).toStrictEqual([
+ ]);
+ });
+
+ it('preserves internal whitespace within recipient entries', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({ to: [' alice [email protected] '] }),
+ );
+ expect(result.to).toStrictEqual(['alice [email protected]']);
+ });
+
+ it('keeps a single already-trimmed entry without modification', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({ to: ['[email protected]'] }),
+ );
+ expect(result.to).toStrictEqual(['[email protected]']);
+ });
+
+ it('interleaves kept and dropped entries preserving original order', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({
+ to: ['', '[email protected]', ' ', ' [email protected] ', ''],
+ }),
+ );
+ expect(result.to).toStrictEqual(['[email protected]', '[email protected]']);
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // Exact payload shape — toStrictEqual verifies that UI-only fields
+ // (replyTo, maxRetries, retryDelay, rateLimit) are absent from the
+ // output and that falsy scalar values pass through unchanged.
+ // -----------------------------------------------------------------------
+ describe('payload shape', () => {
+ it('produces the exact EmailConfig shape with all falsy values preserved', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({
+ enabled: false,
+ provider: 'ses',
+ server: 'email.example.com',
+ port: 0,
+ username: '[email protected]',
+ password: '',
+ tls: false,
+ startTLS: false,
+ replyTo: '[email protected]',
+ maxRetries: 5,
+ retryDelay: 120,
+ rateLimit: 100,
+ }),
+ );
+ expect(result).toStrictEqual({
+ enabled: false,
+ provider: 'ses',
+ server: 'email.example.com',
+ port: 0,
+ username: '[email protected]',
+ password: '',
+ tls: false,
+ startTLS: false,
+ });
+ });
+
+ it('does not include rateLimit in the payload even when set in the UI config', () => {
+ // SUSPECTED SOURCE BUG: UIEmailConfig.rateLimit is required but
+ // buildEmailConfigPayload never forwards it to the backend payload.
+ // See GLM_REPORT.md.
+ const result = buildEmailConfigPayload(makeUIEmailConfig({ rateLimit: 100 }));
+ expect(result).not.toHaveProperty('rateLimit');
+ });
+
+ it('does not include replyTo, maxRetries, or retryDelay in the payload', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({
+ replyTo: '[email protected]',
+ maxRetries: 10,
+ retryDelay: 300,
+ }),
+ );
+ expect(result).not.toHaveProperty('replyTo');
+ expect(result).not.toHaveProperty('maxRetries');
+ expect(result).not.toHaveProperty('retryDelay');
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // Scalar passthrough — verify individual fields are forwarded verbatim,
+ // including edge values (zero port, empty password, empty from/server).
+ // -----------------------------------------------------------------------
+ describe('scalar passthrough', () => {
+ it('forwards a zero port unchanged', () => {
+ const result = buildEmailConfigPayload(makeUIEmailConfig({ port: 0 }));
+ expect(result.port).toBe(0);
+ });
+
+ it('forwards an empty password string unchanged', () => {
+ const result = buildEmailConfigPayload(makeUIEmailConfig({ password: '' }));
+ expect(result.password).toBe('');
+ });
+
+ it('forwards an empty from address unchanged', () => {
+ const result = buildEmailConfigPayload(makeUIEmailConfig({ from: '' }));
+ expect(result.from).toBe('');
+ });
+
+ it('forwards an empty server string unchanged', () => {
+ const result = buildEmailConfigPayload(makeUIEmailConfig({ server: '' }));
+ expect(result.server).toBe('');
+ });
+
+ it('forwards enabled, tls, and startTLS false values unchanged', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({ enabled: false, tls: false, startTLS: false }),
+ );
+ expect(result.enabled).toBe(false);
+ expect(result.tls).toBe(false);
+ expect(result.startTLS).toBe(false);
+ });
+
+ it('forwards enabled, tls, and startTLS true values unchanged', () => {
+ const result = buildEmailConfigPayload(
+ makeUIEmailConfig({ enabled: true, tls: true, startTLS: true }),
+ );
+ expect(result.enabled).toBe(true);
+ expect(result.tls).toBe(true);
+ expect(result.startTLS).toBe(true);
+ });
+ });
+});
diff --git a/frontend-modern/src/features/platformPage/__tests__/agentVersion.branchcov0712.test.ts b/frontend-modern/src/features/platformPage/__tests__/agentVersion.branchcov0712.test.ts
new file mode 100644
index 0000000000..22213dce5e
--- /dev/null
+++ b/frontend-modern/src/features/platformPage/__tests__/agentVersion.branchcov0712.test.ts
@@ -0,0 +1,213 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import { collectOutdatedAgentHosts, hostAgentConnectionID } from '../agentVersion';
+
+const host = (over: Partial<Resource>): Resource =>
+ ({ id: 'x', name: 'host', type: 'docker-host', ...over }) as Resource;
+
+describe('hostAgentConnectionID', () => {
+ it('returns undefined for a plain host with no agent id anywhere', () => {
+ expect(hostAgentConnectionID(host({}))).toBeUndefined();
+ });
+
+ it('passes through an already-prefixed agent meta id without re-prefixing', () => {
+ expect(
+ hostAgentConnectionID(host({ agent: { agentId: 'agent:abc-1' } as Resource['agent'] })),
+ ).toBe('agent:abc-1');
+ });
+
+ it('trims whitespace on the agent meta id before prefixing', () => {
+ expect(
+ hostAgentConnectionID(
+ host({ agent: { agentId: ' agent-delly ' } as Resource['agent'] }),
+ ),
+ ).toBe('agent:agent-delly');
+ });
+
+ it('falls back to kubernetes.agentId for a non-kubernetes platform row', () => {
+ expect(
+ hostAgentConnectionID(
+ host({ kubernetes: { agentId: 'agent-k8s' } as Resource['kubernetes'] }),
+ ),
+ ).toBe('agent:agent-k8s');
+ });
+
+ it('uses host.id for a type="agent" row with no agent meta id', () => {
+ expect(hostAgentConnectionID(host({ type: 'agent', id: 'agent-123' }))).toBe(
+ 'agent:agent-123',
+ );
+ });
+
+ it('uses an already-prefixed host.id for a type="agent" row without re-prefixing', () => {
+ expect(hostAgentConnectionID(host({ type: 'agent', id: 'agent:from-id' }))).toBe(
+ 'agent:from-id',
+ );
+ });
+
+ it('treats a k8s-cluster row as a kubernetes platform row', () => {
+ expect(
+ hostAgentConnectionID(
+ host({
+ type: 'k8s-cluster',
+ kubernetes: { agentId: 'agent:cluster-1' } as Resource['kubernetes'],
+ }),
+ ),
+ ).toBe('agent:cluster-1');
+ });
+
+ it('treats platformType="kubernetes" as a kubernetes platform row and prefixes a bare id', () => {
+ expect(
+ hostAgentConnectionID(
+ host({
+ type: 'docker-host',
+ platformType: 'kubernetes',
+ kubernetes: { agentId: 'node-9' } as Resource['kubernetes'],
+ }),
+ ),
+ ).toBe('agent:node-9');
+ });
+
+ it('treats a sources entry of "kubernetes" as a kubernetes platform row', () => {
+ expect(
+ hostAgentConnectionID(
+ host({
+ type: 'docker-host',
+ sources: ['kubernetes'],
+ kubernetes: { agentId: 'agent:src-1' } as Resource['kubernetes'],
+ }),
+ ),
+ ).toBe('agent:src-1');
+ });
+
+ it('falls through to agent meta when a kubernetes row has no cluster agent id', () => {
+ expect(
+ hostAgentConnectionID(
+ host({
+ type: 'k8s-node',
+ agent: { agentId: 'agent-host' } as Resource['agent'],
+ }),
+ ),
+ ).toBe('agent:agent-host');
+ });
+
+ it('trims whitespace on the kubernetes cluster agent id', () => {
+ expect(
+ hostAgentConnectionID(
+ host({
+ type: 'k8s-node',
+ kubernetes: { agentId: ' agent-k8s ' } as Resource['kubernetes'],
+ }),
+ ),
+ ).toBe('agent:agent-k8s');
+ });
+
+ it('returns undefined for a kubernetes node row with no ids at all', () => {
+ expect(hostAgentConnectionID(host({ type: 'k8s-node' }))).toBeUndefined();
+ });
+
+ it('tolerates a sparse resource object that only carries a type', () => {
+ const sparse = { type: 'docker-host' } as unknown as Parameters<
+ typeof hostAgentConnectionID
+ >[0];
+ expect(hostAgentConnectionID(sparse)).toBeUndefined();
+ });
+});
+
+describe('collectOutdatedAgentHosts', () => {
+ const server = 'v6.0.0-rc.6+git.151.gd8f5519ee';
+
+ it('skips a host whose reported version is present but unparseable', () => {
+ const hosts = [
+ host({ name: 'mystery', docker: { agentVersion: 'dev' } as Resource['docker'] }),
+ ];
+ expect(collectOutdatedAgentHosts(hosts, server)).toEqual([]);
+ });
+
+ it('does not flag a host whose version is ahead of the server', () => {
+ const hosts = [
+ host({ name: 'ahead', docker: { agentVersion: 'v6.1.0' } as Resource['docker'] }),
+ ];
+ expect(collectOutdatedAgentHosts(hosts, 'v6.0.0')).toEqual([]);
+ });
+
+ it('falls back to the resource id when the name is blank', () => {
+ const hosts = [
+ host({
+ id: 'host-7',
+ name: ' ',
+ docker: { agentVersion: 'v6.0.0-rc.5' } as Resource['docker'],
+ }),
+ ];
+ expect(collectOutdatedAgentHosts(hosts, server)).toEqual([
+ { name: 'host-7', version: 'v6.0.0-rc.5' },
+ ]);
+ });
+
+ it('uses the literal "host" when both name and id are blank', () => {
+ const hosts = [
+ host({
+ id: '',
+ name: '',
+ docker: { agentVersion: 'v6.0.0-rc.5' } as Resource['docker'],
+ }),
+ ];
+ expect(collectOutdatedAgentHosts(hosts, server)).toEqual([
+ { name: 'host', version: 'v6.0.0-rc.5' },
+ ]);
+ });
+
+ it('attaches the kubernetes cluster agent id for an outdated k8s node', () => {
+ const hosts = [
+ host({
+ name: 'knode-1',
+ type: 'k8s-node',
+ kubernetes: {
+ agentId: 'agent:cluster-1',
+ agentVersion: 'v6.0.0-rc.5',
+ } as Resource['kubernetes'],
+ }),
+ ];
+ expect(collectOutdatedAgentHosts(hosts, server)).toEqual([
+ { name: 'knode-1', version: 'v6.0.0-rc.5', agentId: 'agent:cluster-1' },
+ ]);
+ });
+
+ it('flags a type="agent" host using its host.id as the connection id', () => {
+ const hosts = [
+ host({
+ name: 'unified-1',
+ type: 'agent',
+ id: 'unified-1-id',
+ agent: { agentVersion: 'v6.0.0-rc.5' } as Resource['agent'],
+ }),
+ ];
+ expect(collectOutdatedAgentHosts(hosts, server)).toEqual([
+ { name: 'unified-1', version: 'v6.0.0-rc.5', agentId: 'agent:unified-1-id' },
+ ]);
+ });
+
+ it('omits the agentId field when the outdated host has no connection id', () => {
+ const hosts = [
+ host({
+ id: 'plain-1',
+ name: 'plain',
+ docker: { agentVersion: 'v6.0.0-rc.5' } as Resource['docker'],
+ }),
+ ];
+ const result = collectOutdatedAgentHosts(hosts, server);
+ expect(result).toEqual([{ name: 'plain', version: 'v6.0.0-rc.5' }]);
+ expect(result[0]).not.toHaveProperty('agentId');
+ });
+
+ it('returns an empty list for null and undefined server versions', () => {
+ const hosts = [
+ host({ name: 'tower', docker: { agentVersion: 'v6.0.0-rc.5' } as Resource['docker'] }),
+ ];
+ expect(collectOutdatedAgentHosts(hosts, null)).toEqual([]);
+ expect(collectOutdatedAgentHosts(hosts, undefined)).toEqual([]);
+ });
+
+ it('returns an empty list when there are no hosts', () => {
+ expect(collectOutdatedAgentHosts([], server)).toEqual([]);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/actionAuditPresentation.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/actionAuditPresentation.branchcov0712.test.ts
new file mode 100644
index 0000000000..c42178ea42
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/actionAuditPresentation.branchcov0712.test.ts
@@ -0,0 +1,392 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatActionApprovalPolicyLabel,
+ formatActionCapabilityLabel,
+ getActionAuditRecordStatePresentation,
+ getActionAuditRefusalPresentation,
+ getActionAuditResultPresentation,
+ getActionAuditStatePresentation,
+ getActionAuditVerification,
+ getActionAuditVerificationOutcomePresentation,
+ shouldRenderActionAuditVerification,
+} from '@/utils/actionAuditPresentation';
+
+// `getActionAuditResultMessage` is module-private (not exported); its branches
+// are exercised transitively through the failure path of
+// `getActionAuditResultPresentation`, which is the only caller.
+
+describe('actionAuditPresentation branch coverage (supplemental)', () => {
+ describe('getActionAuditStatePresentation', () => {
+ it('resolves every canonical lifecycle state that the sibling test omits', () => {
+ expect(getActionAuditStatePresentation('planned')).toStrictEqual({
+ label: 'Planned',
+ className: 'bg-surface-alt text-muted border-border',
+ });
+ expect(getActionAuditStatePresentation('approved')).toStrictEqual({
+ label: 'Approved',
+ className:
+ 'bg-blue-100 text-blue-800 border-blue-200 dark:bg-blue-900 dark:text-blue-200 dark:border-blue-700',
+ });
+ expect(getActionAuditStatePresentation('rejected')).toStrictEqual({
+ label: 'Rejected',
+ className:
+ 'bg-red-100 text-red-800 border-red-200 dark:bg-red-900 dark:text-red-200 dark:border-red-700',
+ });
+ expect(getActionAuditStatePresentation('executing')).toStrictEqual({
+ label: 'Executing',
+ className:
+ 'bg-sky-100 text-sky-800 border-sky-200 dark:bg-sky-900 dark:text-sky-200 dark:border-sky-700',
+ });
+ });
+
+ it('falls back to the Unknown badge for undefined and unrecognised states (?? arm)', () => {
+ const unknown = {
+ label: 'Unknown',
+ className: 'bg-surface-alt text-muted border-border',
+ };
+ expect(getActionAuditStatePresentation(undefined)).toStrictEqual(unknown);
+ expect(getActionAuditStatePresentation('frobnicated')).toStrictEqual(unknown);
+ });
+ });
+
+ describe('formatActionCapabilityLabel', () => {
+ it('returns the bare "Action" fallback for nullish and whitespace-only input', () => {
+ // `(capabilityName || '')` short-circuit on undefined, then trim -> empty -> early return.
+ expect(formatActionCapabilityLabel(undefined)).toBe('Action');
+ expect(formatActionCapabilityLabel(' ')).toBe('Action');
+ });
+
+ it('title-cases a single lowercase word without touching separators', () => {
+ expect(formatActionCapabilityLabel('reboot')).toBe('Reboot');
+ });
+
+ it('splits on hyphen runs the same way as underscores and dots', () => {
+ // Exercises the `/[._-]+/g` replace arm for the hyphen class.
+ expect(formatActionCapabilityLabel('restart-service')).toBe('Restart Service');
+ });
+
+ it('collapses consecutive separators and trims surrounding whitespace', () => {
+ // `a__b` -> replace -> `a b` -> split(/\s+/) -> ['a','b'].
+ expect(formatActionCapabilityLabel(' a__b ')).toBe('A B');
+ });
+
+ it('only re-cases the first character of each word, leaving the tail verbatim', () => {
+ // Documents the behaviour: slice(0,1).toUpperCase() + slice(1) preserves the
+ // rest verbatim, so 'updateContainer' becomes 'UpdateContainer' (camelCase
+ // tail is kept, not lowercased).
+ expect(formatActionCapabilityLabel('docker.updateContainer')).toBe(
+ 'Docker UpdateContainer',
+ );
+ });
+ });
+
+ describe('formatActionApprovalPolicyLabel', () => {
+ it('maps the "none" policy arm the sibling test skips', () => {
+ expect(formatActionApprovalPolicyLabel('none')).toBe('No approval');
+ });
+
+ it('trims before matching, so a padded canonical value still hits its case', () => {
+ expect(formatActionApprovalPolicyLabel(' none ')).toBe('No approval');
+ });
+
+ it('routes nullish/empty policy through the default arm onto "Policy"', () => {
+ // default -> formatActionCapabilityLabel(policy || 'Policy').
+ expect(formatActionApprovalPolicyLabel(undefined)).toBe('Policy');
+ expect(formatActionApprovalPolicyLabel('')).toBe('Policy');
+ });
+
+ it('title-cases an unknown policy name via the default arm', () => {
+ expect(formatActionApprovalPolicyLabel('break_glass')).toBe('Break Glass');
+ expect(formatActionApprovalPolicyLabel('custom-policy')).toBe('Custom Policy');
+ });
+ });
+
+ describe('getActionAuditResultMessage (via getActionAuditResultPresentation failure path)', () => {
+ it('uses result.output when errorMessage is absent (|| arm)', () => {
+ // Private helper branch: `result?.errorMessage || result?.output`.
+ const presentation = getActionAuditResultPresentation({
+ result: { success: false, output: 'stderr dump from executor' },
+ });
+ expect(presentation).toStrictEqual({
+ kind: 'failure',
+ label: 'Execution failed',
+ detail: 'stderr dump from executor',
+ className:
+ 'border-red-200 bg-red-50 text-red-800 dark:border-red-800 dark:bg-red-950/40 dark:text-red-300',
+ });
+ });
+
+ it('returns an empty message when neither errorMessage nor output is set', () => {
+ // Final `|| ''` fallback inside the helper, then `|| undefined` on detail.
+ const presentation = getActionAuditResultPresentation({
+ result: { success: false },
+ });
+ expect(presentation).toStrictEqual({
+ kind: 'failure',
+ label: 'Execution failed',
+ detail: undefined,
+ className:
+ 'border-red-200 bg-red-50 text-red-800 dark:border-red-800 dark:bg-red-950/40 dark:text-red-300',
+ });
+ });
+ });
+
+ describe('getActionAuditRefusalPresentation', () => {
+ it('returns undefined when there is no result at all (!audit.result arm)', () => {
+ expect(getActionAuditRefusalPresentation({})).toBeUndefined();
+ });
+
+ it('returns undefined when the result was successful (audit.result.success arm)', () => {
+ expect(
+ getActionAuditRefusalPresentation({ result: { success: true, output: 'ok' } }),
+ ).toBeUndefined();
+ });
+
+ it('matches a refusal prefix case-insensitively via the toLowerCase() normaliser', () => {
+ // normalizedMessage = message.toLowerCase(); 'PLAN_DRIFT:' lowercases to the prefix.
+ const presentation = getActionAuditRefusalPresentation({
+ result: { success: false, errorMessage: 'PLAN_DRIFT: policy version changed' },
+ });
+ expect(presentation).toStrictEqual({
+ prefix: 'plan_drift:',
+ label: 'Plan changed',
+ detail:
+ 'Pulse refused the action before dispatch because the approved plan no longer matched the current resource or policy state.',
+ recordedDetail: 'policy version changed',
+ className:
+ 'border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-800 dark:bg-rose-950/40 dark:text-rose-300',
+ });
+ });
+
+ it('drops recordedDetail when the message has no detail after the prefix', () => {
+ // `recordedDetail || undefined` falsy arm.
+ const presentation = getActionAuditRefusalPresentation({
+ result: { success: false, errorMessage: 'plan_drift:' },
+ });
+ expect(presentation?.recordedDetail).toBeUndefined();
+ expect(presentation?.label).toBe('Plan changed');
+ });
+
+ it('returns undefined when the failure message carries no recognised prefix', () => {
+ // ACTION_REFUSAL_PREFIXES.find() returns undefined -> second early return.
+ expect(
+ getActionAuditRefusalPresentation({
+ result: { success: false, errorMessage: 'totally unknown failure mode' },
+ }),
+ ).toBeUndefined();
+ });
+ });
+
+ describe('getActionAuditRecordStatePresentation', () => {
+ it('keeps the generic Failed badge when a failed result is not a refusal', () => {
+ // state === 'failed' && refusal -> falsey refusal -> falls through to state lookup.
+ expect(
+ getActionAuditRecordStatePresentation({
+ state: 'failed',
+ result: { success: false, errorMessage: 'executor exited with code 1' },
+ }),
+ ).toStrictEqual({
+ label: 'Failed',
+ className:
+ 'bg-red-100 text-red-800 border-red-200 dark:bg-red-900 dark:text-red-200 dark:border-red-700',
+ });
+ });
+
+ it('delegates to the state lookup for non-failed states', () => {
+ // state !== 'failed' -> skips the refusal check entirely.
+ expect(
+ getActionAuditRecordStatePresentation({ state: 'executing' }),
+ ).toStrictEqual({
+ label: 'Executing',
+ className:
+ 'bg-sky-100 text-sky-800 border-sky-200 dark:bg-sky-900 dark:text-sky-200 dark:border-sky-700',
+ });
+ });
+ });
+
+ describe('getActionAuditResultPresentation', () => {
+ it('returns undefined when the record has no result (!result arm)', () => {
+ expect(getActionAuditResultPresentation({})).toBeUndefined();
+ });
+
+ it('renders the success branch with a trimmed output detail', () => {
+ const presentation = getActionAuditResultPresentation({
+ result: { success: true, output: ' reloaded ' },
+ });
+ expect(presentation).toStrictEqual({
+ kind: 'success',
+ label: 'Result',
+ detail: 'reloaded',
+ className: 'border-border bg-surface text-base-content',
+ });
+ });
+
+ it('omits detail on the success branch when output is missing or blank', () => {
+ // `result.output?.trim() || undefined` -> undefined for absent and whitespace-only.
+ expect(
+ getActionAuditResultPresentation({ result: { success: true } })?.detail,
+ ).toBeUndefined();
+ expect(
+ getActionAuditResultPresentation({ result: { success: true, output: ' ' } })
+ ?.detail,
+ ).toBeUndefined();
+ });
+ });
+
+ describe('getActionAuditVerificationOutcomePresentation', () => {
+ it('returns undefined when there is no verification outcome (!status arm)', () => {
+ // outcome undefined -> status '' -> early return.
+ expect(getActionAuditVerificationOutcomePresentation({})).toBeUndefined();
+ expect(
+ getActionAuditVerificationOutcomePresentation({
+ verificationOutcome: { status: '' },
+ }),
+ ).toBeUndefined();
+ // whitespace-only status trims to '' and also returns undefined.
+ expect(
+ getActionAuditVerificationOutcomePresentation({
+ verificationOutcome: { status: ' ' },
+ }),
+ ).toBeUndefined();
+ });
+
+ it('normalises uppercase status to the canonical map key via toLowerCase()', () => {
+ // 'VERIFIED' must lowercase to the canonical 'verified' key and resolve to
+ // the same presentation. Asserting equality against the canonical result
+ // (rather than hard-coded copy) keeps this focused on the normalisation
+ // branch and robust to label/detail wording changes.
+ const canonical = getActionAuditVerificationOutcomePresentation({
+ verificationOutcome: { status: 'verified' },
+ });
+ expect(canonical).toBeDefined();
+ expect(
+ getActionAuditVerificationOutcomePresentation({
+ verificationOutcome: { status: 'VERIFIED' },
+ }),
+ ).toStrictEqual(canonical);
+ });
+
+ it('collapses a whitespace-only evidenceSummary to undefined', () => {
+ // `evidenceSummary?.trim()` -> '' -> `|| undefined`.
+ const presentation = getActionAuditVerificationOutcomePresentation({
+ verificationOutcome: { status: 'failed', evidenceSummary: ' ' },
+ });
+ expect(presentation?.evidenceSummary).toBeUndefined();
+ expect(presentation?.label).toBe('Verification failed');
+ });
+ });
+
+ describe('getActionAuditVerification', () => {
+ it('returns undefined when neither top-level nor result verification exists', () => {
+ // `audit.verification ?? audit.result?.verification` -> undefined ?? undefined.
+ expect(getActionAuditVerification({})).toBeUndefined();
+ expect(getActionAuditVerification({ result: { success: true } })).toBeUndefined();
+ });
+
+ it('prefers the top-level verification over the result-embedded one (?? left operand)', () => {
+ const top = { ran: true, success: true, command: 'top-level' };
+ const result = { ran: false, success: false, command: 'embedded' };
+ expect(
+ getActionAuditVerification({
+ verification: top,
+ result: { success: true, verification: result },
+ }),
+ ).toStrictEqual(top);
+ });
+ });
+
+ describe('shouldRenderActionAuditVerification', () => {
+ it('returns false when no verification object exists at all', () => {
+ // `undefined?.ran === true` -> false.
+ expect(shouldRenderActionAuditVerification({})).toBe(false);
+ });
+
+ it('returns true from the result-embedded fallback verification', () => {
+ // Exercises the ?? right operand of getActionAuditVerification plus the true arm.
+ expect(
+ shouldRenderActionAuditVerification({
+ result: { success: true, verification: { ran: true, success: true } },
+ }),
+ ).toBe(true);
+ });
+
+ it('uses strict equality against the boolean true (truthy non-boolean does not count)', () => {
+ // `ran` is typed boolean; we deliberately coerce a non-boolean to prove the
+ // `=== true` strictness rather than a truthiness check.
+ expect(
+ shouldRenderActionAuditVerification({
+ result: {
+ success: true,
+ verification: {
+ ran: 1 as unknown as boolean,
+ success: true,
+ },
+ },
+ }),
+ ).toBe(false);
+ });
+
+ it('suppresses the legacy verification UI once result.actionResultV2 is present (=== undefined false arm)', () => {
+ // The function's central purpose: when the v2 truth layer exists, the
+ // `audit.result?.actionResultV2 === undefined` guard is false, so the `&&`
+ // short-circuits to false even though a legacy verification ran. The prior
+ // tests only ever set actionResultV2-absent inputs, leaving this arm open.
+ expect(
+ shouldRenderActionAuditVerification({
+ verification: { ran: true, success: true },
+ result: {
+ success: true,
+ actionResultV2: {
+ version: 2,
+ execution: { status: 'succeeded' },
+ verification: { status: 'confirmed', evidenceClass: 'independent' },
+ compensation: { support: 'unavailable', status: 'not_needed' },
+ },
+ },
+ }),
+ ).toBe(false);
+ });
+
+ it('still suppresses when actionResultV2 is present but the legacy verification did not run', () => {
+ // Same false arm of the guard, now with ran === false to confirm the
+ // short-circuit dominates regardless of the verification value.
+ expect(
+ shouldRenderActionAuditVerification({
+ result: {
+ success: true,
+ verification: { ran: false, success: false },
+ actionResultV2: {
+ version: 2,
+ execution: { status: 'not_run' },
+ verification: { status: 'not_attempted', evidenceClass: 'none' },
+ compensation: { support: 'unavailable', status: 'not_attempted' },
+ },
+ },
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false when a result exists without actionResultV2 and no verification object at all', () => {
+ // guard true (actionResultV2 undefined), but getActionAuditVerification(audit)
+ // resolves to undefined -> `undefined?.ran === true` is false. Distinct from
+ // the empty-record case above because `result` is present here.
+ expect(
+ shouldRenderActionAuditVerification({ result: { success: true } }),
+ ).toBe(false);
+ });
+
+ it('lets the top-level verification precedence force a false render (ran=false shadows a ran=true result verification)', () => {
+ // getActionAuditVerification = audit.verification ?? audit.result?.verification:
+ // the top-level object wins, so its ran=false forces false even though the
+ // result-embedded verification ran. Documents the ?? left-operand behaviour
+ // in the shouldRender composition.
+ expect(
+ shouldRenderActionAuditVerification({
+ verification: { ran: false, success: false },
+ result: { success: true, verification: { ran: true, success: true } },
+ }),
+ ).toBe(false);
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/auditLogPresentation.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/auditLogPresentation.branchcov0712.test.ts
new file mode 100644
index 0000000000..4981e15bcc
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/auditLogPresentation.branchcov0712.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+import CheckCircle from 'lucide-solid/icons/check-circle';
+import XCircle from 'lucide-solid/icons/x-circle';
+import {
+ type AuditEventStatusPresentation,
+ getAuditEventStatusPresentation,
+} from '@/utils/auditLogPresentation';
+
+// `getAuditEventStatusPresentation` is a single ternary over a `boolean` parameter with
+// exactly two arms. The sibling `auditLogPresentation.test.ts` only asserts on
+// `className` via `toMatchObject`; here we additionally pin the full returned shape
+// (including the exact icon *reference*) and exercise the ternary's runtime truthiness
+// coercion by feeding non-boolean values through a `boolean`-typed parameter.
+
+describe('getAuditEventStatusPresentation (branch coverage)', () => {
+ describe('success arm (truthy)', () => {
+ it('returns the full success presentation: CheckCircle reference + emerald className', () => {
+ const result: AuditEventStatusPresentation = getAuditEventStatusPresentation(true);
+ expect(result).toStrictEqual({
+ icon: CheckCircle,
+ className: 'w-4 h-4 text-emerald-400',
+ });
+ });
+
+ it('exposes the exact CheckCircle component by reference (not a clone/wrapper)', () => {
+ expect(getAuditEventStatusPresentation(true).icon).toBe(CheckCircle);
+ });
+
+ it('selects the success arm for any truthy value (ternary uses JS truthiness)', () => {
+ // The parameter is statically `boolean`, but the ternary condition is plain
+ // truthiness; a truthy non-boolean therefore lands on the success arm.
+ const fromNumber = getAuditEventStatusPresentation(1 as unknown as boolean);
+ const fromNonEmptyString = getAuditEventStatusPresentation('true' as unknown as boolean);
+ expect(fromNumber).toStrictEqual({
+ icon: CheckCircle,
+ className: 'w-4 h-4 text-emerald-400',
+ });
+ expect(fromNonEmptyString.icon).toBe(CheckCircle);
+ expect(fromNonEmptyString.className).toBe('w-4 h-4 text-emerald-400');
+ });
+ });
+
+ describe('failure arm (falsy)', () => {
+ it('returns the full failure presentation: XCircle reference + rose className', () => {
+ const result: AuditEventStatusPresentation = getAuditEventStatusPresentation(false);
+ expect(result).toStrictEqual({
+ icon: XCircle,
+ className: 'w-4 h-4 text-rose-400',
+ });
+ });
+
+ it('exposes the exact XCircle component by reference (not a clone/wrapper)', () => {
+ expect(getAuditEventStatusPresentation(false).icon).toBe(XCircle);
+ });
+
+ it('selects the failure arm for a numeric falsy value (ternary uses JS truthiness)', () => {
+ expect(getAuditEventStatusPresentation(0 as unknown as boolean)).toStrictEqual({
+ icon: XCircle,
+ className: 'w-4 h-4 text-rose-400',
+ });
+ });
+
+ it('selects the failure arm for an empty string coerced through the boolean parameter', () => {
+ expect(getAuditEventStatusPresentation('' as unknown as boolean)).toStrictEqual({
+ icon: XCircle,
+ className: 'w-4 h-4 text-rose-400',
+ });
+ });
+
+ it('selects the failure arm for null coerced through the boolean parameter', () => {
+ expect(getAuditEventStatusPresentation(null as unknown as boolean)).toStrictEqual({
+ icon: XCircle,
+ className: 'w-4 h-4 text-rose-400',
+ });
+ });
+ });
+
+ describe('arm discrimination', () => {
+ it('returns mutually distinct icon references and classNames across the two arms', () => {
+ const success = getAuditEventStatusPresentation(true);
+ const failure = getAuditEventStatusPresentation(false);
+ expect(success.icon).not.toBe(failure.icon);
+ expect(success.className).not.toBe(failure.className);
+ });
+
+ it('returns a Solid callable component for the icon on both arms', () => {
+ expect(typeof getAuditEventStatusPresentation(true).icon).toBe('function');
+ expect(typeof getAuditEventStatusPresentation(false).icon).toBe('function');
+ });
+
+ it('returns only the `icon` and `className` keys (no extra enumerable fields)', () => {
+ expect(Object.keys(getAuditEventStatusPresentation(true)).sort()).toStrictEqual([
+ 'className',
+ 'icon',
+ ]);
+ expect(Object.keys(getAuditEventStatusPresentation(false)).sort()).toStrictEqual([
+ 'className',
+ 'icon',
+ ]);
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/patrolCapacityForecastPresentation.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/patrolCapacityForecastPresentation.branchcov0712.test.ts
new file mode 100644
index 0000000000..c192987c0a
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/patrolCapacityForecastPresentation.branchcov0712.test.ts
@@ -0,0 +1,206 @@
+import { describe, it, expect } from 'vitest';
+import type { CapacityForecast } from '@/api/patrol';
+import { presentCapacityForecast } from '../patrolCapacityForecastPresentation';
+
+describe('formatDays (exercised via presentCapacityForecast)', () => {
+ it("returns '1 day' for an exact single day", () => {
+ const out = presentCapacityForecast({
+ current_pct: 99,
+ daily_change: 0.5,
+ days_to_full: 1,
+ });
+ expect(out).toStrictEqual({
+ direction: 'Filling up',
+ detail: '1 day to full at +0.50%/day',
+ current: '99% used',
+ tone: 'critical',
+ });
+ });
+
+ it("formats '~N weeks' for days in the 14-29 range", () => {
+ const out = presentCapacityForecast({
+ current_pct: 70,
+ daily_change: 1,
+ days_to_full: 20,
+ });
+ expect(out!.detail).toBe('~3 weeks to full at +1.0%/day');
+ });
+
+ it('uses weeks rounding at the 14-day boundary', () => {
+ const out = presentCapacityForecast({
+ current_pct: 65,
+ daily_change: 1,
+ days_to_full: 14,
+ });
+ expect(out!.detail).toBe('~2 weeks to full at +1.0%/day');
+ });
+
+ it("formats '~1 month' when months round down to 1", () => {
+ const out = presentCapacityForecast({
+ current_pct: 60,
+ daily_change: 0.5,
+ days_to_full: 44,
+ });
+ expect(out!.detail).toBe('~1 month to full at +0.50%/day');
+ });
+
+ it("formats '~N months' for months between 2 and 11", () => {
+ const out = presentCapacityForecast({
+ current_pct: 40,
+ daily_change: 0.2,
+ days_to_full: 90,
+ });
+ expect(out!.detail).toBe('~3 months to full at +0.20%/day');
+ });
+
+ it("returns 'over a year' when months reach 12 or beyond", () => {
+ const out = presentCapacityForecast({
+ current_pct: 30,
+ daily_change: 0.1,
+ days_to_full: 400,
+ });
+ expect(out!.detail).toBe('over a year to full at +0.10%/day');
+ expect(out!.tone).toBe('info');
+ });
+});
+
+describe('formatRate (exercised via presentCapacityForecast)', () => {
+ it("omits the '+' sign and uses two decimals for a zero rate", () => {
+ const out = presentCapacityForecast({
+ current_pct: 80,
+ daily_change: 0,
+ days_to_full: 5,
+ });
+ expect(out!.detail).toBe('5 days to full at 0.00%/day');
+ });
+
+ it("uses '+' with two decimals for a small positive fractional rate", () => {
+ const out = presentCapacityForecast({
+ current_pct: 75,
+ daily_change: 0.5,
+ days_to_full: 6,
+ });
+ expect(out!.detail).toBe('6 days to full at +0.50%/day');
+ });
+
+ it("uses no sign and one decimal for a rate <= -1 (negative fill projection)", () => {
+ const out = presentCapacityForecast({
+ current_pct: 50,
+ daily_change: -2,
+ days_to_full: 10,
+ });
+ expect(out!.detail).toBe('~1 week to full at -2.0%/day');
+ });
+});
+
+describe('presentCapacityForecast', () => {
+ it('returns null for malformed falsy non-null inputs (defensive !fc guard)', () => {
+ expect(
+ presentCapacityForecast(0 as unknown as CapacityForecast),
+ ).toBeNull();
+ expect(
+ presentCapacityForecast('' as unknown as CapacityForecast),
+ ).toBeNull();
+ });
+
+ it("defaults daily_change to 0 via ?? when it is null", () => {
+ const out = presentCapacityForecast({
+ current_pct: 80,
+ days_to_full: 5,
+ daily_change: null,
+ } as unknown as CapacityForecast);
+ expect(out!.detail).toBe('5 days to full at 0.00%/day');
+ expect(out!.tone).toBe('critical');
+ });
+
+ it("defaults daily_change to 0 via ?? when it is undefined", () => {
+ const out = presentCapacityForecast({
+ current_pct: 80,
+ days_to_full: 5,
+ } as unknown as CapacityForecast);
+ expect(out!.detail).toBe('5 days to full at 0.00%/day');
+ });
+
+ it('rounds current_pct to the nearest whole percent (half-up)', () => {
+ const out = presentCapacityForecast({
+ current_pct: 86.5,
+ daily_change: 0,
+ days_to_full: -1,
+ });
+ expect(out!.current).toBe('87% used');
+ expect(out!.direction).toBe('Stable');
+ });
+
+ it('assigns critical tone at the days<=7 boundary (days=7)', () => {
+ const out = presentCapacityForecast({
+ current_pct: 90,
+ daily_change: 1,
+ days_to_full: 7,
+ });
+ expect(out!.tone).toBe('critical');
+ expect(out!.detail).toBe('~1 week to full at +1.0%/day');
+ });
+
+ it('assigns warning tone just above the critical boundary (days=8)', () => {
+ const out = presentCapacityForecast({
+ current_pct: 85,
+ daily_change: 1,
+ days_to_full: 8,
+ });
+ expect(out!.tone).toBe('warning');
+ });
+
+ it('assigns warning tone at the days<=30 boundary (days=30)', () => {
+ const out = presentCapacityForecast({
+ current_pct: 70,
+ daily_change: 0.5,
+ days_to_full: 30,
+ });
+ expect(out!.tone).toBe('warning');
+ expect(out!.detail).toBe('~1 month to full at +0.50%/day');
+ });
+
+ it('assigns info tone just above the warning boundary (days=31)', () => {
+ const out = presentCapacityForecast({
+ current_pct: 65,
+ daily_change: 0.5,
+ days_to_full: 31,
+ });
+ expect(out!.tone).toBe('info');
+ expect(out!.detail).toBe('~1 month to full at +0.50%/day');
+ });
+
+ it('renders Declining just below the -0.1 threshold', () => {
+ const out = presentCapacityForecast({
+ current_pct: 45,
+ daily_change: -0.11,
+ days_to_full: -1,
+ });
+ expect(out!.direction).toBe('Declining');
+ expect(out!.detail).toBe('usage falling +0.11%/day');
+ });
+
+ it('renders Stable at exactly -0.1 (boundary not < -0.1)', () => {
+ const out = presentCapacityForecast({
+ current_pct: 45,
+ daily_change: -0.1,
+ days_to_full: -1,
+ });
+ expect(out!.direction).toBe('Stable');
+ expect(out!.detail).toBe('no clear fill trend');
+ });
+
+ it('renders Declining with a one-decimal absolute rate for a large drop', () => {
+ const out = presentCapacityForecast({
+ current_pct: 20,
+ daily_change: -3,
+ days_to_full: -1,
+ });
+ expect(out).toStrictEqual({
+ direction: 'Declining',
+ detail: 'usage falling +3.0%/day',
+ current: '20% used',
+ tone: 'info',
+ });
+ });
+});