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

rcourtman8321ed55c57a
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerIdentityModel.branchcov0712.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerIdentityModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..c59a912954
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerIdentityModel.branchcov0712.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildResourceDebugBundle } from '@/components/Infrastructure/resourceDetailDrawerIdentityModel';
+import type { PlatformData } from '@/components/Infrastructure/resourceDetailMappers';
+import type { Resource } from '@/types/resource';
+
+// Branch-coverage companion to resourceDetailDrawerIdentityModel.test.ts.
+// Drives the still-uncovered arms of buildResourceDebugBundle: the optional-
+// chain short-circuit when platformData is omitted (all eight `?.` accesses),
+// the "field present" arm for the source fields the sibling test leaves
+// undefined (agent/pbs/pmg/kubernetes/metrics), and resource.identity absent.
+// Each case pins a concrete shape rather than truthiness.
+
+type SourceStatusMap = NonNullable<PlatformData['sourceStatus']>;
+type DebugBundle = ReturnType<typeof buildResourceDebugBundle>;
+
+const baseResource = (overrides: Partial<Resource> = {}): Resource => ({
+ id: 'resource-1',
+ type: 'vm',
+ name: 'vm-101',
+ displayName: 'VM 101',
+ platformId: 'vm-101',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: Date.now(),
+ platformData: { sources: ['proxmox'] },
+ ...overrides,
+});
+
+const emptySourceStatus: SourceStatusMap = {};
+
+describe('buildResourceDebugBundle branch coverage', () => {
+ it('short-circuits every platformData?. field to undefined when platformData is omitted', () => {
+ const resource = baseResource({ identity: { hostname: 'vm-101.local' } });
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ sourceStatus: { proxmox: { status: 'online' } },
+ identityMatchInfo: { matchedBy: 'hostname' },
+ });
+
+ expect(bundle).toStrictEqual({
+ resource,
+ identity: {
+ resourceIdentity: { hostname: 'vm-101.local' },
+ matchInfo: { matchedBy: 'hostname' },
+ },
+ sources: {
+ sourceStatus: { proxmox: { status: 'online' } },
+ proxmox: undefined,
+ agent: undefined,
+ docker: undefined,
+ pbs: undefined,
+ pmg: undefined,
+ kubernetes: undefined,
+ vmware: undefined,
+ metrics: undefined,
+ },
+ });
+ });
+
+ it('passes every platformData subfield through when all eight sources are populated', () => {
+ // Covers the "field present" arm for agent/pbs/pmg/kubernetes/metrics,
+ // which the sibling test leaves undefined.
+ const resource = baseResource({ identity: { hostname: 'vm-101.local' } });
+ const proxmox = { nodeName: 'pve-1' };
+ const agent = { hostname: 'host-1' };
+ const docker = { runtime: 'docker' };
+ const pbs = { instanceId: 'pbs-1' };
+ const pmg = { instanceId: 'pmg-1' };
+ const kubernetes = { clusterName: 'k8s-1' };
+ const vmware = { connectionName: 'Lab VC' };
+ const metrics = { cpu: 42 };
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ platformData: { proxmox, agent, docker, pbs, pmg, kubernetes, vmware, metrics },
+ sourceStatus: { proxmox: { status: 'online' } },
+ identityMatchInfo: { matchedBy: 'hostname' },
+ });
+
+ expect(bundle.sources).toStrictEqual({
+ sourceStatus: { proxmox: { status: 'online' } },
+ proxmox,
+ agent,
+ docker,
+ pbs,
+ pmg,
+ kubernetes,
+ vmware,
+ metrics,
+ });
+ });
+
+ it('reports undefined resourceIdentity when the resource carries no identity', () => {
+ const resource = baseResource({});
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ sourceStatus: emptySourceStatus,
+ identityMatchInfo: null,
+ });
+
+ expect(bundle.identity.resourceIdentity).toBeUndefined();
+ expect(bundle.identity).toStrictEqual({
+ resourceIdentity: undefined,
+ matchInfo: null,
+ });
+ });
+
+ it('forwards a null identityMatchInfo verbatim and preserves the resource reference', () => {
+ const resource = baseResource({ identity: { machineId: 'machine-9' } });
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ sourceStatus: emptySourceStatus,
+ identityMatchInfo: null,
+ });
+
+ expect(bundle.identity.matchInfo).toBeNull();
+ expect(bundle.resource).toBe(resource);
+ expect(bundle.identity.resourceIdentity).toStrictEqual({ machineId: 'machine-9' });
+ });
+
+ it('forwards an undefined identityMatchInfo verbatim', () => {
+ const resource = baseResource({ identity: { ips: ['192.0.2.1'] } });
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ sourceStatus: emptySourceStatus,
+ identityMatchInfo: undefined,
+ });
+
+ expect(bundle.identity.matchInfo).toBeUndefined();
+ expect(bundle.identity.resourceIdentity).toStrictEqual({ ips: ['192.0.2.1'] });
+ });
+
+ it('forwards a primitive identityMatchInfo verbatim', () => {
+ const resource = baseResource({ identity: { hostname: 'vm-101.local' } });
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ sourceStatus: emptySourceStatus,
+ identityMatchInfo: 'hostname',
+ });
+
+ expect(bundle.identity.matchInfo).toBe('hostname');
+ });
+
+ it('passes an empty sourceStatus map through unchanged', () => {
+ const resource = baseResource({});
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ sourceStatus: emptySourceStatus,
+ identityMatchInfo: undefined,
+ });
+
+ expect(bundle.sources.sourceStatus).toStrictEqual({});
+ expect(Object.keys(bundle.sources.sourceStatus)).toEqual([]);
+ });
+
+ it('preserves a multi-entry sourceStatus map with lastSeen/error fields', () => {
+ const resource = baseResource({});
+ const sourceStatus: SourceStatusMap = {
+ proxmox: { status: 'online', lastSeen: 1_700_000_000_000 },
+ agent: { status: 'error', error: 'agent unreachable' },
+ };
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ sourceStatus,
+ identityMatchInfo: undefined,
+ });
+
+ expect(bundle.sources.sourceStatus).toStrictEqual(sourceStatus);
+ });
+
+ it('returns a platformData whose subfields are all undefined when platformData is an empty object', () => {
+ // platformData is defined (so the `?.` does not short-circuit) but every
+ // subfield is absent: the access arm returns undefined for each source.
+ const resource = baseResource({});
+
+ const bundle: DebugBundle = buildResourceDebugBundle({
+ resource,
+ platformData: { sources: ['proxmox'] },
+ sourceStatus: emptySourceStatus,
+ identityMatchInfo: undefined,
+ });
+
+ expect(bundle.sources).toStrictEqual({
+ sourceStatus: {},
+ proxmox: undefined,
+ agent: undefined,
+ docker: undefined,
+ pbs: undefined,
+ pmg: undefined,
+ kubernetes: undefined,
+ vmware: undefined,
+ metrics: undefined,
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0712.test.ts b/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..94af5a2ad8
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0712.test.ts
@@ -0,0 +1,747 @@
+import { describe, expect, it } from 'vitest';
+import type { APITokenRecord } from '@/api/security';
+import type { Resource, ResourceDiscoveryTarget } from '@/types/resource';
+import { DOCKER_REPORT_SCOPE } from '@/constants/apiScopes';
+import {
+ API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID,
+ agentActionIdForResource,
+ buildAgentTokenUsage,
+ buildDockerTokenUsage,
+ dockerActionIdForResource,
+ getAPITokenDialogName,
+ getAPITokenHint,
+ getAPITokenScopePresets,
+ hasAgentScopeResource,
+ matchesScopePreset,
+ tokenRevokedAtForResource,
+} from '../apiTokenManagerModel';
+
+// ---- Fixtures ---------------------------------------------------------------
+// Mirrors the sibling APITokenManager.test.tsx fixture builders so the private
+// helpers under test (readPlatformData / readNestedPlatformField /
+// readPlatformNumber / normalizePresetScopes / appendUsageEntry) are driven
+// through the single exported orchestrators that compose them.
+
+const makeResource = (overrides: Partial<Resource> = {}): Resource => ({
+ id: 'resource-1',
+ type: 'agent',
+ name: 'Resource One',
+ displayName: 'Resource One',
+ platformId: 'agent-1',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: Date.now(),
+ tags: [],
+ ...overrides,
+});
+
+const makeToken = (overrides: Partial<APITokenRecord> = {}): APITokenRecord => ({
+ id: 'token-1',
+ name: 'Runtime token',
+ prefix: 'pulse',
+ suffix: '1234',
+ createdAt: '2026-03-12T10:00:00.000Z',
+ lastUsedAt: '2026-03-12T11:00:00.000Z',
+ scopes: [DOCKER_REPORT_SCOPE],
+ ...overrides,
+});
+
+// ---- readPlatformNumber (private) via tokenRevokedAtForResource -------------
+//
+// readPlatformNumber is module-private and only reachable through
+// tokenRevokedAtForResource. Placing `tokenRevokedAt` at the TOP level of
+// platformData makes readNestedPlatformField return it verbatim (the
+// `field in platformData` arm), so readPlatformNumber receives the raw value
+// and every typeof/Number.isFinite arm is exercised.
+
+describe('readPlatformNumber (via tokenRevokedAtForResource)', () => {
+ it('returns a finite number verbatim', () => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({ platformData: { tokenRevokedAt: 1_700_000_000_000 } }),
+ ),
+ ).toBe(1_700_000_000_000);
+ });
+
+ it('returns 0 for a finite zero (not treated as missing)', () => {
+ expect(
+ tokenRevokedAtForResource(makeResource({ platformData: { tokenRevokedAt: 0 } })),
+ ).toBe(0);
+ });
+
+ it('returns a negative finite number verbatim', () => {
+ expect(
+ tokenRevokedAtForResource(makeResource({ platformData: { tokenRevokedAt: -42 } })),
+ ).toBe(-42);
+ });
+
+ it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(
+ 'returns undefined for a number that is not finite (%s)',
+ (value) => {
+ expect(
+ tokenRevokedAtForResource(makeResource({ platformData: { tokenRevokedAt: value } })),
+ ).toBeUndefined();
+ },
+ );
+
+ it.each(['1700000000000', '', [], { ms: 1 }, true, null])(
+ 'returns undefined for a non-number value (%s)',
+ (value) => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({ platformData: { tokenRevokedAt: value } as Record<string, unknown> }),
+ ),
+ ).toBeUndefined();
+ },
+ );
+});
+
+// ---- readPlatformData (private) via tokenRevokedAtForResource ---------------
+//
+// readPlatformData is module-private; its two arms (platformData absent ->
+// undefined; present -> unwrap-and-return) are both hit through
+// tokenRevokedAtForResource.
+
+describe('readPlatformData (via tokenRevokedAtForResource)', () => {
+ it('returns undefined when platformData is absent (no platformData key)', () => {
+ const resource = makeResource();
+ expect(resource.platformData).toBeUndefined();
+ expect(tokenRevokedAtForResource(resource)).toBeUndefined();
+ });
+
+ it('unwraps a populated platformData record so nested fields are reachable', () => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({ platformData: { tokenRevokedAt: 555, unrelated: true } }),
+ ),
+ ).toBe(555);
+ });
+});
+
+// ---- readNestedPlatformField (private) via tokenRevokedAtForResource --------
+//
+// readNestedPlatformField is module-private; every arm is driven via
+// tokenRevokedAtForResource by relocating `tokenRevokedAt` through the
+// platformData graph (top-level -> agent -> docker -> absent).
+
+describe('readNestedPlatformField (via tokenRevokedAtForResource)', () => {
+ it('returns the field directly from platformData when present at the top level', () => {
+ expect(
+ tokenRevokedAtForResource(makeResource({ platformData: { tokenRevokedAt: 111 } })),
+ ).toBe(111);
+ });
+
+ it('falls through to platformData.agent.<field> when not at the top level', () => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({ platformData: { agent: { tokenRevokedAt: 222 } } }),
+ ),
+ ).toBe(222);
+ });
+
+ it('falls through to platformData.docker.<field> when neither top-level nor agent has it', () => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({ platformData: { docker: { tokenRevokedAt: 333 } } }),
+ ),
+ ).toBe(333);
+ });
+
+ it('skips a non-object agent value and still resolves from docker', () => {
+ // agent is a truthy string, so `typeof agent === 'object'` is false and the
+ // agent branch is skipped; docker carries the field.
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({
+ platformData: { agent: 'not-an-object', docker: { tokenRevokedAt: 444 } },
+ }),
+ ),
+ ).toBe(444);
+ });
+
+ it('returns undefined when agent is an object without the field and docker is absent', () => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({ platformData: { agent: { unrelated: true } } }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined when docker is a non-object value (object guard skips it)', () => {
+ expect(
+ tokenRevokedAtForResource(makeResource({ platformData: { docker: 'oops' } })),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined when the field is nowhere in the platformData graph', () => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({
+ platformData: { agent: { other: 1 }, docker: { other: 2 } },
+ }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined when platformData itself is undefined', () => {
+ expect(tokenRevokedAtForResource(makeResource({ platformData: undefined }))).toBeUndefined();
+ });
+});
+
+// ---- tokenRevokedAtForResource (exported composition) ----------------------
+
+describe('tokenRevokedAtForResource', () => {
+ it('composes the three private readers to surface a revokedAt timestamp', () => {
+ expect(
+ tokenRevokedAtForResource(
+ makeResource({
+ platformData: { docker: { tokenId: 'tok', tokenRevokedAt: 9_999 } },
+ }),
+ ),
+ ).toBe(9_999);
+ });
+});
+
+// ---- hasAgentScopeResource --------------------------------------------------
+
+describe('hasAgentScopeResource', () => {
+ it('returns false for a docker-host even when it carries an agent facet (early return)', () => {
+ const dockerHostWithAgent = makeResource({
+ type: 'docker-host',
+ platformType: 'docker',
+ agent: { agentId: 'would-otherwise-match' },
+ });
+ expect(hasAgentScopeResource(dockerHostWithAgent)).toBe(false);
+ });
+
+ it.each(['agent', 'pbs', 'pmg'] as const)(
+ 'returns true for the canonical agent-scoped type %s',
+ (type) => {
+ expect(hasAgentScopeResource(makeResource({ type }))).toBe(true);
+ },
+ );
+
+ it('returns true for a non-canonical type that carries an agent facet', () => {
+ // 'vm' is not agent/pbs/pmg/docker-host, but resourceHasAgentFacet is true
+ // because resource.agent is set.
+ expect(
+ hasAgentScopeResource(
+ makeResource({ type: 'vm', platformType: 'proxmox-pve', agent: { agentId: 'vm-agent' } }),
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false for a non-canonical type with no agent facet', () => {
+ expect(
+ hasAgentScopeResource(
+ makeResource({ type: 'storage', platformType: 'proxmox-pve', agent: undefined }),
+ ),
+ ).toBe(false);
+ });
+});
+
+// ---- getAPITokenHint --------------------------------------------------------
+
+describe('getAPITokenHint', () => {
+ it('returns the em-dash placeholder for null', () => {
+ expect(getAPITokenHint(null)).toBe('—');
+ });
+
+ it('returns the em-dash placeholder for undefined', () => {
+ expect(getAPITokenHint(undefined)).toBe('—');
+ });
+
+ it('combines prefix and suffix with an ellipsis when both are present', () => {
+ expect(getAPITokenHint(makeToken({ prefix: 'pulse', suffix: '4321' }))).toBe('pulse…4321');
+ });
+
+ it('uses only the prefix when the suffix is blank', () => {
+ expect(getAPITokenHint(makeToken({ prefix: 'pulse', suffix: '' }))).toBe('pulse…');
+ });
+
+ it('falls back to the em-dash when only a suffix is present (prefix is falsy)', () => {
+ expect(getAPITokenHint(makeToken({ prefix: '', suffix: '9999' }))).toBe('—');
+ });
+
+ it('falls back to the em-dash when neither prefix nor suffix is present', () => {
+ expect(getAPITokenHint(makeToken({ prefix: '', suffix: '' }))).toBe('—');
+ });
+});
+
+// ---- getAPITokenDialogName --------------------------------------------------
+
+describe('getAPITokenDialogName', () => {
+ it('returns the trimmed name when the name has non-whitespace content', () => {
+ expect(getAPITokenDialogName(makeToken({ name: ' Container automation ' }))).toBe(
+ 'Container automation',
+ );
+ });
+
+ it('falls through when the name is only whitespace (trim() is empty -> falsy)', () => {
+ expect(getAPITokenDialogName(makeToken({ name: ' ', prefix: 'pulse', suffix: '1234' }))).toBe(
+ 'pulse…1234',
+ );
+ });
+
+ it('exercises the optional-chain arm when name is undefined at runtime', () => {
+ expect(
+ getAPITokenDialogName(
+ makeToken({ name: undefined as unknown as string, prefix: 'pulse', suffix: '' }),
+ ),
+ ).toBe('pulse…');
+ });
+
+ it('combines prefix and suffix when the name is blank and both are set', () => {
+ expect(getAPITokenDialogName(makeToken({ name: '', prefix: 'pl', suffix: 'xy' }))).toBe('pl…xy');
+ });
+
+ it('returns "untitled token" when name, prefix, and suffix are all blank', () => {
+ expect(getAPITokenDialogName(makeToken({ name: '', prefix: '', suffix: '' }))).toBe(
+ 'untitled token',
+ );
+ });
+});
+
+// ---- normalizePresetScopes (private) via getAPITokenScopePresets -----------
+//
+// normalizePresetScopes is module-private; its only caller is
+// getAPITokenScopePresets, which feeds the normalized result to the Pulse
+// Intelligence preset (and gates that preset on length > 0). Asserting that
+// preset's `scopes` and presence exercises every normalizePresetScopes branch:
+// trim(), filter(Boolean), Set dedup, and the scopes ?? [] fallback.
+
+describe('normalizePresetScopes (via getAPITokenScopePresets)', () => {
+ const PULSE_PRESET_ID = API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID;
+
+ it('adds no Pulse Intelligence preset when the required-scopes arg defaults to []', () => {
+ const presets = getAPITokenScopePresets();
+ expect(presets.find((preset) => preset.id === PULSE_PRESET_ID)).toBeUndefined();
+ expect(presets).toHaveLength(7);
+ });
+
+ it('adds no Pulse Intelligence preset when every provided scope is blank/whitespace', () => {
+ const presets = getAPITokenScopePresets(['', ' ', '\t']);
+ expect(presets.find((preset) => preset.id === PULSE_PRESET_ID)).toBeUndefined();
+ expect(presets).toHaveLength(7);
+ });
+
+ it('trims, deduplicates, and drops empties, preserving first-seen order', () => {
+ const presets = getAPITokenScopePresets([' b ', 'b', '', 'a']);
+ const pulsePreset = presets.find((preset) => preset.id === PULSE_PRESET_ID);
+ expect(pulsePreset?.scopes).toStrictEqual(['b', 'a']);
+ expect(presets).toHaveLength(8);
+ });
+
+ it('keeps a single non-empty scope after normalization', () => {
+ const presets = getAPITokenScopePresets([' monitoring:read ']);
+ expect(presets.find((preset) => preset.id === PULSE_PRESET_ID)?.scopes).toStrictEqual([
+ 'monitoring:read',
+ ]);
+ });
+});
+
+// ---- agentActionIdForResource -----------------------------------------------
+
+describe('agentActionIdForResource', () => {
+ it('returns the actionable agent id when an explicit agent id is resolvable', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ platformData: { agent: { agentId: 'agent-007' } },
+ }),
+ ),
+ ).toBe('agent-007');
+ });
+
+ it('falls back to resource.id when no agent id is resolvable anywhere', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({ id: 'fallback-id', type: 'vm', platformType: 'proxmox-pve' }),
+ ),
+ ).toBe('fallback-id');
+ });
+
+ // The branches below drive each still-uncovered resolution arm of
+ // getActionableAgentIdFromResource (the helper whose truthiness selects the
+ // first operand of agentActionIdForResource's `||`). Every case asserts the
+ // concrete string that agentActionIdForResource returns, proving which arm
+ // of the `||` fired and which source inside the helper won the short-circuit.
+
+ it('resolves from the top-level resource.agent.agentId facet (first explicit-id arm)', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({ id: 'fallback-id', agent: { agentId: 'facet-agent-1' } }),
+ ),
+ ).toBe('facet-agent-1');
+ });
+
+ it('resolves from platformData.agentId when no agent facet is present (third explicit-id arm)', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({ id: 'fallback-id', platformData: { agentId: 'pd-agent-2' } }),
+ ),
+ ).toBe('pd-agent-2');
+ });
+
+ it('resolves from platformData.linkedAgentId when agentId is absent (fourth explicit-id arm)', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({ id: 'fallback-id', platformData: { linkedAgentId: 'linked-3' } }),
+ ),
+ ).toBe('linked-3');
+ });
+
+ it('resolves from resource.kubernetes.agentId (fifth explicit-id arm)', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({ id: 'fallback-id', kubernetes: { agentId: 'k8s-agent-4' } }),
+ ),
+ ).toBe('k8s-agent-4');
+ });
+
+ it('resolves from platformData.kubernetes.agentId (sixth explicit-id arm)', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ platformData: { kubernetes: { agentId: 'pd-k8s-5' } },
+ }),
+ ),
+ ).toBe('pd-k8s-5');
+ });
+
+ it('prefers resource.agent.agentId over platformData.agent.agentId (short-circuit priority)', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ agent: { agentId: 'preferred' },
+ platformData: { agent: { agentId: 'shadowed' } },
+ }),
+ ),
+ ).toBe('preferred');
+ });
+
+ it('resolves from discoveryTarget.resourceId for an agent discovery target (getAgentDiscoveryResourceId resourceId arm)', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ discoveryTarget: {
+ resourceType: 'agent',
+ agentId: 'dt-agent',
+ resourceId: 'dt-resource-6',
+ },
+ }),
+ ),
+ ).toBe('dt-resource-6');
+ });
+
+ it('falls back to discoveryTarget.agentId inside getAgentDiscoveryResourceId when resourceId is blank', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ discoveryTarget: {
+ resourceType: 'agent',
+ agentId: 'dt-agent-7',
+ resourceId: ' ',
+ },
+ }),
+ ),
+ ).toBe('dt-agent-7');
+ });
+
+ it('normalizes a case-variant discovery resourceType ("AGENT") onto the agent arm', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ discoveryTarget: {
+ resourceType: 'AGENT' as unknown as ResourceDiscoveryTarget['resourceType'],
+ agentId: 'dt-agent-8',
+ resourceId: 'dt-resource-8',
+ },
+ }),
+ ),
+ ).toBe('dt-resource-8');
+ });
+
+ it('skips getAgentDiscoveryResourceId for a non-agent discovery target and falls through to discoveryTarget.agentId', () => {
+ // resourceType 'vm' fails isAgentDiscoveryResourceType, so
+ // getAgentDiscoveryResourceId returns undefined; the final arm of
+ // getActionableAgentIdFromResource reads discoveryTarget.agentId directly.
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ discoveryTarget: {
+ resourceType: 'vm',
+ agentId: 'vm-host-agent-9',
+ resourceId: 'vm-resource-9',
+ },
+ }),
+ ),
+ ).toBe('vm-host-agent-9');
+ });
+
+ it('treats whitespace-only explicit agent ids as missing and falls back to resource.id', () => {
+ // asTrimmedString returns undefined for every whitespace-only value, so
+ // every explicit-id arm is skipped and the `||` selects resource.id.
+ expect(
+ agentActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ agent: { agentId: ' ' },
+ platformData: { agent: { agentId: '\t' }, linkedAgentId: ' ' },
+ }),
+ ),
+ ).toBe('fallback-id');
+ });
+
+ it('returns resource.id when discoveryTarget is absent and no explicit agent id exists', () => {
+ expect(
+ agentActionIdForResource(
+ makeResource({ id: 'fallback-id', type: 'storage', platformType: 'generic' }),
+ ),
+ ).toBe('fallback-id');
+ });
+});
+
+// ---- dockerActionIdForResource ----------------------------------------------
+
+describe('dockerActionIdForResource', () => {
+ it('returns the docker runtime id when hostSourceId is resolvable', () => {
+ expect(
+ dockerActionIdForResource(
+ makeResource({
+ id: 'fallback-id',
+ type: 'docker-host',
+ platformType: 'docker',
+ platformData: { docker: { hostSourceId: 'docker-runtime-1' } },
+ }),
+ ),
+ ).toBe('docker-runtime-1');
+ });
+
+ it('falls back to resource.id when no docker runtime id is resolvable', () => {
+ expect(
+ dockerActionIdForResource(
+ makeResource({ id: 'fallback-id', platformData: { agent: { agentId: 'a1' } } }),
+ ),
+ ).toBe('fallback-id');
+ });
+});
+
+// ---- appendUsageEntry (private) via buildDockerTokenUsage / buildAgentTokenUsage
+//
+// appendUsageEntry is module-private; its three arms (first entry / duplicate
+// item-id no-op / new item-id append) are driven through the two exported
+// usage builders, which also exercise their own skip/iterate branches.
+
+describe('appendUsageEntry (via buildDockerTokenUsage)', () => {
+ it('returns an empty map for an empty resource list', () => {
+ expect(buildDockerTokenUsage([])).toStrictEqual(new Map());
+ });
+
+ it('skips resources that have no tokenId', () => {
+ const withoutToken = makeResource({
+ id: 'no-token',
+ type: 'docker-host',
+ platformType: 'docker',
+ displayName: 'No Token',
+ platformData: { docker: { hostSourceId: 'rt-9' } },
+ });
+ expect(buildDockerTokenUsage([withoutToken])).toStrictEqual(new Map());
+ });
+
+ it('creates a count=1 entry for the first resource with a given tokenId', () => {
+ const resource = makeResource({
+ id: 'd-1',
+ type: 'docker-host',
+ platformType: 'docker',
+ displayName: 'Docker One',
+ platformData: { docker: { hostSourceId: 'rt-1', tokenId: 't1' } },
+ });
+ expect(buildDockerTokenUsage([resource])).toStrictEqual(
+ new Map([['t1', { count: 1, items: [{ id: 'rt-1', label: 'Docker One' }] }]]),
+ );
+ });
+
+ it('appends a distinct item and increments the count for a shared tokenId', () => {
+ const a = makeResource({
+ id: 'd-1',
+ type: 'docker-host',
+ platformType: 'docker',
+ displayName: 'Docker One',
+ platformData: { docker: { hostSourceId: 'rt-1', tokenId: 't1' } },
+ });
+ const b = makeResource({
+ id: 'd-2',
+ type: 'docker-host',
+ platformType: 'docker',
+ displayName: 'Docker Two',
+ platformData: { docker: { hostSourceId: 'rt-2', tokenId: 't1' } },
+ });
+ expect(buildDockerTokenUsage([a, b])).toStrictEqual(
+ new Map([
+ [
+ 't1',
+ {
+ count: 2,
+ items: [
+ { id: 'rt-1', label: 'Docker One' },
+ { id: 'rt-2', label: 'Docker Two' },
+ ],
+ },
+ ],
+ ]),
+ );
+ });
+
+ it('no-ops when a second resource maps to an already-recorded item id (dedup)', () => {
+ // Both resources resolve to dockerActionId 'rt-shared' (same hostSourceId),
+ // so appendUsageEntry's duplicate-item guard keeps count at 1 and preserves
+ // the first-seen label.
+ const a = makeResource({
+ id: 'd-1',
+ type: 'docker-host',
+ platformType: 'docker',
+ displayName: 'Docker One',
+ platformData: { docker: { hostSourceId: 'rt-shared', tokenId: 't1' } },
+ });
+ const b = makeResource({
+ id: 'd-2',
+ type: 'docker-host',
+ platformType: 'docker',
+ displayName: 'Docker Two',
+ platformData: { docker: { hostSourceId: 'rt-shared', tokenId: 't1' } },
+ });
+ expect(buildDockerTokenUsage([a, b])).toStrictEqual(
+ new Map([
+ ['t1', { count: 1, items: [{ id: 'rt-shared', label: 'Docker One' }] }],
+ ]),
+ );
+ });
+});
+
+describe('appendUsageEntry (via buildAgentTokenUsage)', () => {
+ it('creates a count=1 entry for the first agent resource with a tokenId', () => {
+ const resource = makeResource({
+ id: 'a-1',
+ type: 'agent',
+ platformType: 'agent',
+ displayName: 'Agent One',
+ platformData: { agent: { agentId: 'a1', tokenId: 't1' } },
+ });
+ expect(buildAgentTokenUsage([resource])).toStrictEqual(
+ new Map([['t1', { count: 1, items: [{ id: 'a1', label: 'Agent One' }] }]]),
+ );
+ });
+
+ it('appends a distinct agent item and increments the count', () => {
+ const a = makeResource({
+ id: 'a-1',
+ type: 'agent',
+ platformType: 'agent',
+ displayName: 'Agent One',
+ platformData: { agent: { agentId: 'a1', tokenId: 't1' } },
+ });
+ const b = makeResource({
+ id: 'a-2',
+ type: 'agent',
+ platformType: 'agent',
+ displayName: 'Agent Two',
+ platformData: { agent: { agentId: 'a2', tokenId: 't1' } },
+ });
+ expect(buildAgentTokenUsage([a, b])).toStrictEqual(
+ new Map([
+ [
+ 't1',
+ {
+ count: 2,
+ items: [
+ { id: 'a1', label: 'Agent One' },
+ { id: 'a2', label: 'Agent Two' },
+ ],
+ },
+ ],
+ ]),
+ );
+ });
+
+ it('dedups agent resources that resolve to the same actionable agent id', () => {
+ const a = makeResource({
+ id: 'a-1',
+ type: 'agent',
+ platformType: 'agent',
+ displayName: 'Agent One',
+ platformData: { agent: { agentId: 'shared', tokenId: 't1' } },
+ });
+ const b = makeResource({
+ id: 'a-2',
+ type: 'agent',
+ platformType: 'agent',
+ displayName: 'Agent Two',
+ platformData: { agent: { agentId: 'shared', tokenId: 't1' } },
+ });
+ expect(buildAgentTokenUsage([a, b])).toStrictEqual(
+ new Map([['t1', { count: 1, items: [{ id: 'shared', label: 'Agent One' }] }]]),
+ );
+ });
+
+ it('skips agent resources that have no tokenId', () => {
+ const withoutToken = makeResource({
+ id: 'a-1',
+ type: 'agent',
+ platformType: 'agent',
+ displayName: 'Agent One',
+ platformData: { agent: { agentId: 'a1' } },
+ });
+ expect(buildAgentTokenUsage([withoutToken])).toStrictEqual(new Map());
+ });
+});
+
+// ---- matchesScopePreset -----------------------------------------------------
+
+describe('matchesScopePreset', () => {
+ it('matches regardless of input order for an exact non-empty set', () => {
+ expect(matchesScopePreset(['b', 'a'], ['a', 'b'])).toBe(true);
+ });
+
+ it('returns false when the selection is a strict subset of the preset', () => {
+ expect(matchesScopePreset(['a'], ['a', 'b'])).toBe(false);
+ });
+
+ it('returns false when the selection is a strict superset of the preset', () => {
+ expect(matchesScopePreset(['a', 'b', 'c'], ['a', 'b'])).toBe(false);
+ });
+
+ it('returns false for a disjoint set of the same length', () => {
+ expect(matchesScopePreset(['a'], ['b'])).toBe(false);
+ });
+
+ it('returns true for an empty preset against an empty selection', () => {
+ expect(matchesScopePreset([], [])).toBe(true);
+ });
+
+ it('returns true for an empty preset when the selection is just the wildcard', () => {
+ expect(matchesScopePreset(['*'], [])).toBe(true);
+ });
+
+ it('returns false for an empty preset when the selection has a non-wildcard scope', () => {
+ expect(matchesScopePreset(['monitoring:read'], [])).toBe(false);
+ });
+
+ it('ignores the wildcard when comparing against a non-empty preset that otherwise matches', () => {
+ // The '*' is filtered out before the length/equality check, so ['a','*']
+ // matches preset ['a'].
+ expect(matchesScopePreset(['a', '*'], ['a'])).toBe(true);
+ });
+
+ it('still returns false when a wildcard is present but the remaining scope does not match', () => {
+ expect(matchesScopePreset(['b', '*'], ['a'])).toBe(false);
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadAgentReadiness.branchcov0712.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadAgentReadiness.branchcov0712.test.ts
new file mode 100644
index 0000000000..669a099b1a
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadAgentReadiness.branchcov0712.test.ts
@@ -0,0 +1,232 @@
+import { describe, expect, it } from 'vitest';
+import type { ResourceDiscoveryTarget } from '@/types/resource';
+import type { WorkloadGuest } from '@/types/workloads';
+import {
+ getWorkloadActionAgentTitle,
+ hasExplicitWorkloadActionAgent,
+ isInGuestPulseAgentEligibleWorkload,
+} from '../workloadAgentReadiness';
+
+const makeGuest = (overrides?: Partial<WorkloadGuest>): WorkloadGuest =>
+ ({
+ id: 'guest-0',
+ vmid: 100,
+ name: 'workload-0',
+ node: 'pve',
+ instance: 'cluster-a',
+ status: 'running',
+ type: 'qemu',
+ cpu: 0.5,
+ cpus: 2,
+ memory: { total: 4096, used: 1024, free: 3072, usage: 0.25 },
+ disk: { total: 102400, used: 10240, free: 92160, usage: 0.1 },
+ networkIn: 100,
+ networkOut: 200,
+ diskRead: 10,
+ diskWrite: 5,
+ uptime: 3600,
+ template: false,
+ lastBackup: 0,
+ tags: [],
+ lock: '',
+ lastSeen: new Date().toISOString(),
+ workloadType: 'vm',
+ ...overrides,
+ }) as WorkloadGuest;
+
+const target = (
+ overrides: Partial<ResourceDiscoveryTarget> = {},
+): ResourceDiscoveryTarget => ({
+ resourceType: 'vm',
+ agentId: 'agent-1',
+ resourceId: 'resource-1',
+ ...overrides,
+});
+
+describe('workloadAgentReadiness (branch coverage)', () => {
+ describe('hasExplicitWorkloadActionAgent', () => {
+ it('returns false when discoveryTarget is absent (!target early-return arm)', () => {
+ const guest = makeGuest({ type: 'qemu', workloadType: 'vm' });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(false);
+ });
+
+ it('returns false for an app-container even with a complete target (workloadType !== vm && !== system-container; first && operand true)', () => {
+ const guest = makeGuest({
+ type: 'docker',
+ workloadType: 'app-container',
+ discoveryTarget: target({ resourceType: 'app-container' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(false);
+ });
+
+ it('returns false for a pod (workloadType !== vm && !== system-container; second && operand true)', () => {
+ const guest = makeGuest({
+ type: 'pod',
+ workloadType: 'pod',
+ discoveryTarget: target({ resourceType: 'pod' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(false);
+ });
+
+ it('returns false for a vm when agentId is blank (agentId length===0 arm)', () => {
+ const guest = makeGuest({
+ type: 'qemu',
+ workloadType: 'vm',
+ discoveryTarget: target({ resourceType: 'vm', agentId: ' ' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(false);
+ });
+
+ it('returns false for a vm when resourceId is blank (resourceId length===0 arm)', () => {
+ const guest = makeGuest({
+ type: 'qemu',
+ workloadType: 'vm',
+ discoveryTarget: target({ resourceType: 'vm', resourceId: '' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(false);
+ });
+
+ it('returns false when target.resourceType is "agent" (neither vm nor system-container)', () => {
+ const guest = makeGuest({
+ type: 'qemu',
+ workloadType: 'vm',
+ discoveryTarget: target({ resourceType: 'agent' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(false);
+ });
+
+ it('returns true for a vm with a complete vm resourceType target (vm continue + vm resourceType arm)', () => {
+ const guest = makeGuest({
+ type: 'qemu',
+ workloadType: 'vm',
+ discoveryTarget: target({ resourceType: 'vm' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(true);
+ });
+
+ it('returns true for a system-container with a system-container resourceType target (system-container continue + system-container resourceType arm)', () => {
+ const guest = makeGuest({
+ type: 'lxc',
+ workloadType: 'system-container',
+ discoveryTarget: target({ resourceType: 'system-container' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(true);
+ });
+
+ it('returns true for a vm whose target resourceType is system-container (resourceType OR second arm)', () => {
+ const guest = makeGuest({
+ type: 'qemu',
+ workloadType: 'vm',
+ discoveryTarget: target({ resourceType: 'system-container' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(true);
+ });
+
+ it('returns true for a system-container whose target resourceType is vm (resourceType OR first arm)', () => {
+ const guest = makeGuest({
+ type: 'lxc',
+ workloadType: 'system-container',
+ discoveryTarget: target({ resourceType: 'vm' }),
+ });
+ expect(hasExplicitWorkloadActionAgent(guest)).toBe(true);
+ });
+ });
+
+ describe('getWorkloadActionAgentTitle', () => {
+ it('interpolates the node when node is a non-empty string (truthy ternary arm)', () => {
+ const guest = makeGuest({ node: 'pve' });
+ expect(getWorkloadActionAgentTitle(guest)).toBe(
+ 'Discovery and governed actions use the Pulse Agent connected to pve.',
+ );
+ });
+
+ it('trims surrounding whitespace from node before interpolating', () => {
+ const guest = makeGuest({ node: ' pve-node ' });
+ expect(getWorkloadActionAgentTitle(guest)).toBe(
+ 'Discovery and governed actions use the Pulse Agent connected to pve-node.',
+ );
+ });
+
+ it('falls back to the parent-node title when node is an empty string (falsy ternary arm)', () => {
+ const guest = makeGuest({ node: '' });
+ expect(getWorkloadActionAgentTitle(guest)).toBe(
+ 'Discovery and governed actions use the connected parent node Pulse Agent.',
+ );
+ });
+
+ it('falls back to the parent-node title when node is whitespace-only (trim -> empty)', () => {
+ const guest = makeGuest({ node: ' ' });
+ expect(getWorkloadActionAgentTitle(guest)).toBe(
+ 'Discovery and governed actions use the connected parent node Pulse Agent.',
+ );
+ });
+
+ it('falls back to the parent-node title when node is undefined (|| "" coalesce arm)', () => {
+ const guest = makeGuest({ node: undefined });
+ expect(getWorkloadActionAgentTitle(guest)).toBe(
+ 'Discovery and governed actions use the connected parent node Pulse Agent.',
+ );
+ });
+ });
+
+ describe('isInGuestPulseAgentEligibleWorkload', () => {
+ it('returns false for a vm template (template === true short-circuits before the vm arm)', () => {
+ const guest = makeGuest({ type: 'qemu', workloadType: 'vm', template: true });
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(false);
+ });
+
+ it('returns false for a system-container template (template guard precedes the system-container branch)', () => {
+ const guest = makeGuest({
+ type: 'lxc',
+ workloadType: 'system-container',
+ template: true,
+ });
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(false);
+ });
+
+ it('returns true for a non-template vm (workloadType === "vm" arm)', () => {
+ const guest = makeGuest({ type: 'qemu', workloadType: 'vm', template: false });
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(true);
+ });
+
+ it('returns true for a regular lxc system-container (isOciSystemContainer false -> !false === true)', () => {
+ const guest = makeGuest({
+ type: 'lxc',
+ workloadType: 'system-container',
+ template: false,
+ });
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(true);
+ });
+
+ it('returns false for an oci-container (type === "oci-container" -> isOciSystemContainer true -> !true === false)', () => {
+ const guest = makeGuest({
+ type: 'oci-container',
+ workloadType: 'system-container',
+ template: false,
+ });
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(false);
+ });
+
+ it('returns false for a system-container flagged isOci via the isOci flag (second isOciSystemContainer OR arm)', () => {
+ const guest = {
+ ...makeGuest({ type: 'lxc', workloadType: 'system-container', template: false }),
+ isOci: true,
+ } as WorkloadGuest;
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(false);
+ });
+
+ it('returns false for an app-container (default return-false arm)', () => {
+ const guest = makeGuest({
+ type: 'docker',
+ workloadType: 'app-container',
+ template: false,
+ });
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(false);
+ });
+
+ it('returns false for a pod (default return-false arm)', () => {
+ const guest = makeGuest({ type: 'pod', workloadType: 'pod', template: false });
+ expect(isInGuestPulseAgentEligibleWorkload(guest)).toBe(false);
+ });
+ });
+});
diff --git a/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov0712.test.ts b/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov0712.test.ts
new file mode 100644
index 0000000000..1f62f098d3
--- /dev/null
+++ b/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov0712.test.ts
@@ -0,0 +1,1086 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Alert } from '@/types/api';
+import type { Resource } from '@/types/resource';
+
+import {
+ MS_PER_HOUR,
+ applyAlertHistoryWindow,
+ buildAlertHistoryItems,
+ buildAlertHistoryParams,
+ buildAlertRangeSummary,
+ buildAlertAxisTicks,
+ buildAlertTrends,
+ buildSelectedBucketDetails,
+ filterAlertHistoryItems,
+ formatAlertAxisTickLabel,
+ formatAlertBucketRange,
+ formatAlertHistoryDuration,
+ formatAlertHistoryGroupLabel,
+ getAlertBucketDurationLabel,
+ getAlertHistoryDaySuffix,
+ getIncidentRowKey,
+ groupAlertHistoryItems,
+ resolveAlertHistoryResourceType,
+ type AlertHistoryRange,
+ type AlertTrendSeries,
+ type HistoryItem,
+} from '../alertHistoryModel';
+
+// ---------------------------------------------------------------------------
+// Shared fixtures — keep these minimal but real-shaped so the production
+// code paths (resource-type resolution, severity filtering, etc.) exercise
+// the same branches the UI triggers.
+// ---------------------------------------------------------------------------
+
+function makeItem(overrides: Partial<HistoryItem> = {}): HistoryItem {
+ return {
+ id: 'alert-1',
+ source: 'alert',
+ status: 'resolved',
+ startTime: '2026-03-22T09:00:00.000Z',
+ duration: '1h',
+ resourceName: 'vm-101',
+ resourceType: 'VM',
+ severity: 'critical',
+ title: 'CPU High',
+ ...overrides,
+ };
+}
+
+function makeAlert(overrides: Partial<Alert> = {}): Alert {
+ return {
+ id: 'alert-1',
+ type: 'cpu',
+ level: 'critical',
+ resourceId: 'resource-1',
+ resourceName: 'vm-101',
+ node: 'px1',
+ instance: 'cpu',
+ message: 'CPU high',
+ value: 90,
+ threshold: 80,
+ startTime: '2026-03-22T09:00:00.000Z',
+ acknowledged: false,
+ ...overrides,
+ } as Alert;
+}
+
+function makeResource(overrides: Partial<Resource> = {}): Resource {
+ return {
+ id: 'resource-1',
+ type: 'vm',
+ name: 'vm-101',
+ displayName: 'vm-101',
+ ...overrides,
+ } as unknown as Resource;
+}
+
+// ---------------------------------------------------------------------------
+// buildAlertHistoryParams — exact limit/startTime for each switch arm.
+// ---------------------------------------------------------------------------
+
+describe('buildAlertHistoryParams', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0);
+
+ it('emits limit 2000 and a startTime exactly 24h before now for "24h"', () => {
+ expect(buildAlertHistoryParams('24h', now)).toStrictEqual({
+ limit: 2000,
+ startTime: new Date(now - 24 * MS_PER_HOUR).toISOString(),
+ });
+ });
+
+ it('emits limit 10000 and a startTime exactly 7d before now for "7d"', () => {
+ expect(buildAlertHistoryParams('7d', now)).toStrictEqual({
+ limit: 10000,
+ startTime: new Date(now - 7 * 24 * MS_PER_HOUR).toISOString(),
+ });
+ });
+
+ it('emits limit 10000 and a startTime exactly 30d before now for "30d"', () => {
+ expect(buildAlertHistoryParams('30d', now)).toStrictEqual({
+ limit: 10000,
+ startTime: new Date(now - 30 * 24 * MS_PER_HOUR).toISOString(),
+ });
+ });
+
+ it('emits limit 0 and no startTime for "all"', () => {
+ expect(buildAlertHistoryParams('all', now)).toStrictEqual({ limit: 0 });
+ });
+
+ it('falls back to limit 1000 with no startTime for an unrecognised range', () => {
+ expect(
+ buildAlertHistoryParams('bogus' as AlertHistoryRange, now),
+ ).toStrictEqual({ limit: 1000 });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatAlertHistoryDuration — negative-duration guard, now-fallback, and
+// the three magnitude arms at their boundaries.
+// ---------------------------------------------------------------------------
+
+describe('formatAlertHistoryDuration', () => {
+ it('returns "0m" when end is before start (negative duration)', () => {
+ expect(
+ formatAlertHistoryDuration('2026-03-22T10:00:00.000Z', '2026-03-22T09:00:00.000Z'),
+ ).toBe('0m');
+ });
+
+ it('uses the provided `now` when endTime is omitted', () => {
+ const start = '2026-03-22T09:00:00.000Z';
+ const now = Date.UTC(2026, 2, 22, 9, 30, 0);
+ expect(formatAlertHistoryDuration(start, undefined, now)).toBe('30m');
+ });
+
+ it('returns "0m" for a zero-length duration (start === end)', () => {
+ const start = '2026-03-22T09:00:00.000Z';
+ expect(formatAlertHistoryDuration(start, start)).toBe('0m');
+ });
+
+ it('formats the minute-only arm with leading minutes under one hour', () => {
+ expect(
+ formatAlertHistoryDuration('2026-03-22T09:00:00.000Z', '2026-03-22T09:05:00.000Z'),
+ ).toBe('5m');
+ });
+
+ it('renders the residual minutes even when hours divide evenly', () => {
+ // exactly 1 hour → minutes=60, hours=1, days=0 → "1h 0m"
+ expect(
+ formatAlertHistoryDuration('2026-03-22T09:00:00.000Z', '2026-03-22T10:00:00.000Z'),
+ ).toBe('1h 0m');
+ });
+
+ it('renders the residual hours even when days divide evenly', () => {
+ // exactly 1 day → minutes=1440, hours=24, days=1 → "1d 0h"
+ expect(
+ formatAlertHistoryDuration('2026-03-22T09:00:00.000Z', '2026-03-23T09:00:00.000Z'),
+ ).toBe('1d 0h');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatAlertBucketRange — same-day, cross-day, and cross-year (which forces
+// the `year: 'numeric'` option on the start formatter).
+// ---------------------------------------------------------------------------
+
+describe('formatAlertBucketRange', () => {
+ it('uses the en-dash separator and a single date for an intra-day bucket', () => {
+ const start = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const end = Date.UTC(2026, 2, 22, 13, 0, 0);
+ const label = formatAlertBucketRange(start, end, 'en-US');
+ expect(label).toContain('\u2013'); // –
+ expect(label).not.toContain('\u2192'); // →
+ expect(label).toContain('Mar 22');
+ expect(label.startsWith('Mar 22,')).toBe(true);
+ });
+
+ it('uses the arrow separator and both dates when the bucket spans midnight', () => {
+ const start = Date.UTC(2026, 2, 22, 22, 0, 0);
+ const end = Date.UTC(2026, 2, 23, 4, 0, 0);
+ const label = formatAlertBucketRange(start, end, 'en-US');
+ expect(label).toContain('\u2192'); // →
+ expect(label).not.toContain('\u2013'); // –
+ expect(label).toContain('Mar 22');
+ expect(label).toContain('Mar 23');
+ });
+
+ it('adds a year to the start segment when start and end fall in different years', () => {
+ const start = Date.UTC(2025, 11, 31, 22, 0, 0);
+ const end = Date.UTC(2026, 0, 1, 2, 0, 0);
+ const label = formatAlertBucketRange(start, end, 'en-US');
+ expect(label).toContain('2025');
+ expect(label).toContain('Dec 31');
+ expect(label).toContain('Jan 1');
+ expect(label).toContain('2026');
+ // Cross-day so the arrow separator is used.
+ expect(label).toContain('\u2192');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// resolveAlertHistoryResourceType — every early-return and fallback arm.
+// ---------------------------------------------------------------------------
+
+describe('resolveAlertHistoryResourceType', () => {
+ it('returns the metadata resourceType when it is a non-empty string', () => {
+ expect(
+ resolveAlertHistoryResourceType({
+ resourceName: 'vm-101',
+ metadata: { resourceType: 'Custom' },
+ resourceId: 'resource-1',
+ getResource: () => makeResource({ type: 'vm' }),
+ allResources: [makeResource({ type: 'vm' })],
+ }),
+ ).toBe('Custom');
+ });
+
+ it('falls through when metadata.resourceType is only whitespace', () => {
+ const result = resolveAlertHistoryResourceType({
+ resourceName: 'vm-101',
+ metadata: { resourceType: ' ' },
+ resourceId: 'resource-1',
+ getResource: () => makeResource({ type: 'vm' }),
+ allResources: [],
+ });
+ expect(result).toBe('VM');
+ });
+
+ it('falls through when metadata.resourceType is not a string (number)', () => {
+ const result = resolveAlertHistoryResourceType({
+ resourceName: 'vm-101',
+ metadata: { resourceType: 42 },
+ resourceId: 'resource-1',
+ getResource: () => makeResource({ type: 'vm' }),
+ allResources: [],
+ });
+ expect(result).toBe('VM');
+ });
+
+ it('falls through when metadata is undefined', () => {
+ const result = resolveAlertHistoryResourceType({
+ resourceName: 'vm-101',
+ metadata: undefined,
+ resourceId: 'resource-1',
+ getResource: () => makeResource({ type: 'vm' }),
+ allResources: [],
+ });
+ expect(result).toBe('VM');
+ });
+
+ it('resolves via getResource when resourceId is provided and the lookup hits', () => {
+ expect(
+ resolveAlertHistoryResourceType({
+ resourceName: 'whatever',
+ resourceId: 'resource-1',
+ getResource: (id) => (id === 'resource-1' ? makeResource({ type: 'vm' }) : undefined),
+ allResources: [],
+ }),
+ ).toBe('VM');
+ });
+
+ it('falls through to a name match when getResource returns undefined', () => {
+ const result = resolveAlertHistoryResourceType({
+ resourceName: 'vm-101',
+ resourceId: 'missing',
+ getResource: () => undefined,
+ allResources: [makeResource({ name: 'vm-101', type: 'vm' })],
+ });
+ expect(result).toBe('VM');
+ });
+
+ it('matches a resource by displayName when the name match misses', () => {
+ const result = resolveAlertHistoryResourceType({
+ resourceName: 'pretty-vm',
+ resourceId: 'missing',
+ getResource: () => undefined,
+ allResources: [
+ makeResource({ name: 'other', displayName: 'pretty-vm', type: 'app-container' }),
+ ],
+ });
+ expect(result).toBe('Container');
+ });
+
+ it('returns "Unknown" when no resolution path succeeds', () => {
+ expect(
+ resolveAlertHistoryResourceType({
+ resourceName: 'lonely',
+ resourceId: undefined,
+ getResource: () => undefined,
+ allResources: [],
+ }),
+ ).toBe('Unknown');
+ });
+
+ it('returns "Unknown" even with a resourceId when getResource misses and no name matches', () => {
+ expect(
+ resolveAlertHistoryResourceType({
+ resourceName: 'lonely',
+ resourceId: 'also-missing',
+ getResource: () => undefined,
+ allResources: [makeResource({ name: 'someone-else' })],
+ }),
+ ).toBe('Unknown');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildAlertHistoryItems — active vs history, acknowledged vs resolved, and
+// the active-id suppression of duplicate history rows.
+// ---------------------------------------------------------------------------
+
+describe('buildAlertHistoryItems', () => {
+ const getResource = (id: string): Resource | undefined =>
+ id === 'resource-1' ? makeResource({ id: 'resource-1', type: 'vm' }) : undefined;
+
+ it('returns an empty array when both activeAlerts and alertHistory are empty', () => {
+ expect(
+ buildAlertHistoryItems({
+ activeAlerts: {},
+ alertHistory: [],
+ getResource,
+ allResources: [],
+ }),
+ ).toStrictEqual([]);
+ });
+
+ it('marks active alerts with status "active" and acknowledged:false', () => {
+ const items = buildAlertHistoryItems({
+ activeAlerts: { 'alert-1': makeAlert({ id: 'alert-1', acknowledged: true }) },
+ alertHistory: [],
+ getResource,
+ allResources: [],
+ now: Date.UTC(2026, 2, 22, 10, 0, 0),
+ });
+ expect(items).toHaveLength(1);
+ expect(items[0]).toMatchObject({
+ id: 'alert-1',
+ status: 'active',
+ acknowledged: false,
+ resourceType: 'VM',
+ title: 'CPU',
+ });
+ // Active alerts carry no end time.
+ expect(items[0].endTime).toBeUndefined();
+ });
+
+ it('marks an unacknowledged historical alert as "resolved"', () => {
+ const items = buildAlertHistoryItems({
+ activeAlerts: {},
+ alertHistory: [
+ makeAlert({
+ id: 'h-1',
+ acknowledged: false,
+ lastSeen: '2026-03-22T09:30:00.000Z',
+ }),
+ ],
+ getResource,
+ allResources: [],
+ now: Date.UTC(2026, 2, 22, 10, 0, 0),
+ });
+ expect(items).toHaveLength(1);
+ expect(items[0]).toMatchObject({ id: 'h-1', status: 'resolved', acknowledged: false });
+ expect(items[0].endTime).toBe('2026-03-22T09:30:00.000Z');
+ });
+
+ it('marks an acknowledged historical alert as "acknowledged"', () => {
+ const items = buildAlertHistoryItems({
+ activeAlerts: {},
+ alertHistory: [
+ makeAlert({
+ id: 'h-2',
+ acknowledged: true,
+ lastSeen: '2026-03-22T09:30:00.000Z',
+ }),
+ ],
+ getResource,
+ allResources: [],
+ now: Date.UTC(2026, 2, 22, 10, 0, 0),
+ });
+ expect(items).toHaveLength(1);
+ expect(items[0]).toMatchObject({ id: 'h-2', status: 'acknowledged', acknowledged: true });
+ });
+
+ it('does not duplicate an alert that is present in both active and history', () => {
+ const items = buildAlertHistoryItems({
+ activeAlerts: { 'alert-1': makeAlert({ id: 'alert-1' }) },
+ alertHistory: [makeAlert({ id: 'alert-1', lastSeen: '2026-03-22T09:30:00.000Z' })],
+ getResource,
+ allResources: [],
+ now: Date.UTC(2026, 2, 22, 10, 0, 0),
+ });
+ expect(items).toHaveLength(1);
+ expect(items[0].status).toBe('active');
+ });
+
+ it('interleaves active and historical rows preserving both sets', () => {
+ const items = buildAlertHistoryItems({
+ activeAlerts: { 'a-1': makeAlert({ id: 'a-1' }) },
+ alertHistory: [makeAlert({ id: 'h-1', lastSeen: '2026-03-22T09:30:00.000Z' })],
+ getResource,
+ allResources: [],
+ now: Date.UTC(2026, 2, 22, 10, 0, 0),
+ });
+ expect(items.map((i) => i.id)).toEqual(['a-1', 'h-1']);
+ expect(items.map((i) => i.status)).toEqual(['active', 'resolved']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// filterAlertHistoryItems — pass-through identity, multi-field de-dupe, and
+// the undefined-field safe-access arms.
+// ---------------------------------------------------------------------------
+
+describe('filterAlertHistoryItems', () => {
+ it('returns the same array reference when no filter is applied', () => {
+ const items = [makeItem()];
+ expect(filterAlertHistoryItems(items, 'all', '')).toBe(items);
+ });
+
+ it('matches a search term against the title only when other fields are blank', () => {
+ const items = [
+ makeItem({ id: '1', title: 'CPU High', resourceName: 'x', description: '', node: '' }),
+ makeItem({ id: '2', title: 'Disk Full', resourceName: 'y', description: '', node: '' }),
+ ];
+ const result = filterAlertHistoryItems(items, 'all', 'cpu');
+ expect(result.map((i) => i.id)).toEqual(['1']);
+ });
+
+ it('returns a single item even when the term matches multiple of its fields', () => {
+ const items = [
+ makeItem({
+ id: '1',
+ resourceName: 'cpu-thing',
+ title: 'CPU',
+ description: 'cpu spike',
+ node: 'cpunode',
+ }),
+ ];
+ const result = filterAlertHistoryItems(items, 'all', 'cpu');
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('1');
+ });
+
+ it('safely filters items whose title/description/node are undefined', () => {
+ const item = makeItem({ id: 'u', title: undefined, description: undefined, node: undefined });
+ expect(filterAlertHistoryItems([item], 'all', '')).toHaveLength(1);
+ expect(filterAlertHistoryItems([item], 'all', 'missing')).toHaveLength(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildAlertTrends — exercises the `?? rawBucketSize` fallback by forcing a
+// range so wide that no nice bucket size is large enough.
+// ---------------------------------------------------------------------------
+
+describe('buildAlertTrends (nice-size fallback)', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0);
+
+ it('falls back to rawBucketSize when the range exceeds the largest nice value', () => {
+ // ~1801 days ago → rawRangeHours ≈ 43224 → rawBucketSize = ceil(43224/30) = 1441
+ // which is larger than the max nice value (1440), so `.find()` returns undefined
+ // and the `?? rawBucketSize` fallback engages.
+ const alerts = [
+ makeItem({ startTime: new Date(now - 1801 * 24 * MS_PER_HOUR).toISOString() }),
+ ];
+ const trends = buildAlertTrends(alerts, 'all', now);
+ expect(trends.bucketSize).toBe(1441);
+ expect(trends.rangeHours).toBe(30 * 1441);
+ expect(trends.buckets).toHaveLength(30);
+ });
+
+ it('caps the bucket count at maxBuckets (30) for a very wide range', () => {
+ const alerts = [
+ makeItem({ startTime: new Date(now - 5000 * 24 * MS_PER_HOUR).toISOString() }),
+ ];
+ const trends = buildAlertTrends(alerts, 'all', now);
+ expect(trends.buckets.length).toBeLessThanOrEqual(30);
+ expect(trends.rangeHours).toBe(trends.buckets.length * trends.bucketSize);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// applyAlertHistoryWindow — 24h/30d cutoff arms, selected-bar precedence
+// over an "all" timeFilter, and the id-equality tiebreaker.
+// ---------------------------------------------------------------------------
+
+describe('applyAlertHistoryWindow (cutoff + tiebreak arms)', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0);
+
+ it('applies the 24h cutoff when no bar is selected', () => {
+ const trends = buildAlertTrends([], '24h', now);
+ const items = [
+ makeItem({ id: 'within', startTime: new Date(now - MS_PER_HOUR).toISOString() }),
+ makeItem({ id: 'beyond', startTime: new Date(now - 25 * MS_PER_HOUR).toISOString() }),
+ ];
+ const result = applyAlertHistoryWindow({
+ filteredItems: items,
+ timeFilter: '24h',
+ selectedBarIndex: null,
+ trends,
+ now,
+ });
+ expect(result.map((i) => i.id)).toEqual(['within']);
+ });
+
+ it('applies the 30d cutoff when no bar is selected', () => {
+ const trends = buildAlertTrends([], '30d', now);
+ const items = [
+ makeItem({ id: 'within', startTime: new Date(now - 10 * 24 * MS_PER_HOUR).toISOString() }),
+ makeItem({ id: 'beyond', startTime: new Date(now - 60 * 24 * MS_PER_HOUR).toISOString() }),
+ ];
+ const result = applyAlertHistoryWindow({
+ filteredItems: items,
+ timeFilter: '30d',
+ selectedBarIndex: null,
+ trends,
+ now,
+ });
+ expect(result.map((i) => i.id)).toEqual(['within']);
+ });
+
+ it('prefers the selected bar over the timeFilter cutoff (timeFilter "all")', () => {
+ const trends = buildAlertTrends([], 'all', now);
+ const bucketIndex = 0;
+ const bucketStart = trends.bucketTimes[bucketIndex];
+ const bucketEnd = bucketStart + trends.bucketSize * MS_PER_HOUR;
+
+ const items = [
+ makeItem({ id: 'in-bucket', startTime: new Date(bucketStart + 1000).toISOString() }),
+ makeItem({ id: 'out-of-bucket', startTime: new Date(bucketEnd + MS_PER_HOUR).toISOString() }),
+ ];
+
+ const result = applyAlertHistoryWindow({
+ filteredItems: items,
+ timeFilter: 'all',
+ selectedBarIndex: bucketIndex,
+ trends,
+ now,
+ });
+ expect(result.map((i) => i.id)).toEqual(['in-bucket']);
+ });
+
+ it('returns 0 from the comparator when two items share both startTime and id', () => {
+ const trends = buildAlertTrends([], 'all', now);
+ const sharedStart = new Date(now - MS_PER_HOUR).toISOString();
+ // Identical id + startTime — the `a.id > b.id` branch is skipped and 0 is returned.
+ const items = [
+ makeItem({ id: 'same', startTime: sharedStart }),
+ makeItem({ id: 'same', startTime: sharedStart }),
+ ];
+ const result = applyAlertHistoryWindow({
+ filteredItems: items,
+ timeFilter: 'all',
+ selectedBarIndex: null,
+ trends,
+ now,
+ });
+ expect(result).toHaveLength(2);
+ expect(result.every((i) => i.id === 'same')).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getAlertHistoryDaySuffix — every ordinal arm including the 11–13 special case.
+// ---------------------------------------------------------------------------
+
+describe('getAlertHistoryDaySuffix', () => {
+ it('returns "st" for 1, 21, 31, 101', () => {
+ expect(getAlertHistoryDaySuffix(1)).toBe('st');
+ expect(getAlertHistoryDaySuffix(21)).toBe('st');
+ expect(getAlertHistoryDaySuffix(31)).toBe('st');
+ expect(getAlertHistoryDaySuffix(101)).toBe('st');
+ });
+
+ it('returns "nd" for 2, 22', () => {
+ expect(getAlertHistoryDaySuffix(2)).toBe('nd');
+ expect(getAlertHistoryDaySuffix(22)).toBe('nd');
+ });
+
+ it('returns "rd" for 3, 23', () => {
+ expect(getAlertHistoryDaySuffix(3)).toBe('rd');
+ expect(getAlertHistoryDaySuffix(23)).toBe('rd');
+ });
+
+ it('returns "th" for the default arm (e.g. 4, 25)', () => {
+ expect(getAlertHistoryDaySuffix(4)).toBe('th');
+ expect(getAlertHistoryDaySuffix(25)).toBe('th');
+ });
+
+ it('returns "th" for the 11–13 special case even though they end in 1/2/3', () => {
+ expect(getAlertHistoryDaySuffix(11)).toBe('th');
+ expect(getAlertHistoryDaySuffix(12)).toBe('th');
+ expect(getAlertHistoryDaySuffix(13)).toBe('th');
+ });
+
+ it('documents current behaviour for 111–113 (guard only covers 11–13)', () => {
+ // The 11–13 guard is `day >= 11 && day <= 13`, so 111/112/113 fall through
+ // to the `% 10` switch and are *not* special-cased. This pins the current
+ // output; see GLM_REPORT.md for the suspected source bug.
+ expect(getAlertHistoryDaySuffix(111)).toBe('st');
+ expect(getAlertHistoryDaySuffix(112)).toBe('nd');
+ expect(getAlertHistoryDaySuffix(113)).toBe('rd');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatAlertHistoryGroupLabel — direct calls for all three label arms.
+// ---------------------------------------------------------------------------
+
+describe('formatAlertHistoryGroupLabel', () => {
+ it('labels a date equal to todayStart with the "Today (...)" prefix', () => {
+ const todayStart = Date.UTC(2026, 2, 22);
+ const date = new Date(todayStart);
+ expect(formatAlertHistoryGroupLabel(date, todayStart, 0)).toBe('Today (March 22nd)');
+ });
+
+ it('labels a date equal to yesterdayStart with the "Yesterday (...)" prefix', () => {
+ const yesterdayStart = Date.UTC(2026, 2, 21);
+ const date = new Date(yesterdayStart);
+ expect(formatAlertHistoryGroupLabel(date, 0, yesterdayStart)).toBe('Yesterday (March 21st)');
+ });
+
+ it('uses the absolute "Month DaySuffix" label for any other date', () => {
+ const date = new Date(Date.UTC(2026, 0, 2));
+ // Neither todayStart nor yesterdayStart match.
+ expect(formatAlertHistoryGroupLabel(date, 0, 0)).toBe('January 2nd');
+ });
+
+ it('applies the correct suffix for an 11th day', () => {
+ const date = new Date(Date.UTC(2026, 0, 11));
+ expect(formatAlertHistoryGroupLabel(date, 0, 0)).toBe('January 11th');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getIncidentRowKey
+// ---------------------------------------------------------------------------
+
+describe('getIncidentRowKey', () => {
+ it('joins id and startTime with "::" into a stable composite key', () => {
+ expect(
+ getIncidentRowKey(
+ makeItem({ id: 'inc-9', startTime: '2026-03-22T09:00:00.000Z' }),
+ ),
+ ).toBe('inc-9::2026-03-22T09:00:00.000Z');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// groupAlertHistoryItems — multi-day grouping, add-to-existing arm, ordering.
+// ---------------------------------------------------------------------------
+
+describe('groupAlertHistoryItems', () => {
+ it('appends subsequent same-day alerts to an already-created group', () => {
+ const items = [
+ makeItem({ id: 'a', startTime: '2026-01-15T08:00:00.000Z' }),
+ makeItem({ id: 'b', startTime: '2026-01-15T20:00:00.000Z' }),
+ ];
+ const groups = groupAlertHistoryItems(items);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].alerts.map((a) => a.id)).toEqual(['a', 'b']);
+ });
+
+ it('produces one group per distinct calendar day, newest first', () => {
+ const items = [
+ makeItem({ id: 'oldest', startTime: '2026-01-10T08:00:00.000Z' }),
+ makeItem({ id: 'mid', startTime: '2026-02-10T08:00:00.000Z' }),
+ makeItem({ id: 'newest', startTime: '2026-03-10T08:00:00.000Z' }),
+ ];
+ const groups = groupAlertHistoryItems(items);
+ expect(groups.map((g) => g.alerts[0].id)).toEqual(['newest', 'mid', 'oldest']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getAlertBucketDurationLabel — every arm of the guard + day/hour formatters.
+// ---------------------------------------------------------------------------
+
+describe('getAlertBucketDurationLabel', () => {
+ it('returns the em-dash placeholder for non-finite input', () => {
+ expect(getAlertBucketDurationLabel(Number.NaN)).toBe('—');
+ });
+
+ it('returns the em-dash placeholder for zero and negative input', () => {
+ expect(getAlertBucketDurationLabel(0)).toBe('—');
+ expect(getAlertBucketDurationLabel(-3)).toBe('—');
+ });
+
+ it('uses the singular "1 day" form for exactly 24 hours', () => {
+ expect(getAlertBucketDurationLabel(24)).toBe('1 day');
+ });
+
+ it('uses the plural "N days" form for whole-day buckets > 24h', () => {
+ expect(getAlertBucketDurationLabel(48)).toBe('2 days');
+ expect(getAlertBucketDurationLabel(72)).toBe('3 days');
+ });
+
+ it('uses the singular "1 hour" form for exactly one hour', () => {
+ expect(getAlertBucketDurationLabel(1)).toBe('1 hour');
+ });
+
+ it('uses the plural "N hours" form for non-whole-day hour buckets', () => {
+ expect(getAlertBucketDurationLabel(6)).toBe('6 hours');
+ expect(getAlertBucketDurationLabel(12)).toBe('12 hours');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatAlertAxisTickLabel — invalid-timestamp guard, "Now" end tick, and the
+// three totalHours formatting tiers (with/without the hour option).
+// ---------------------------------------------------------------------------
+
+describe('formatAlertAxisTickLabel', () => {
+ it('returns the em-dash placeholder for a non-finite timestamp', () => {
+ expect(
+ formatAlertAxisTickLabel({
+ timestamp: Number.NaN,
+ bucketHours: 1,
+ totalHours: 24,
+ locale: 'en-US',
+ }),
+ ).toBe('—');
+ });
+
+ it('returns "Now" for an end tick within 0.75 * bucketHours of now', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0);
+ expect(
+ formatAlertAxisTickLabel({
+ timestamp: now - 10 * 60 * 1000, // 10 min ago, within 0.75h
+ bucketHours: 1,
+ totalHours: 24,
+ locale: 'en-US',
+ isEnd: true,
+ now,
+ }),
+ ).toBe('Now');
+ });
+
+ it('does NOT return "Now" for a non-end tick even when close to now', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const label = formatAlertAxisTickLabel({
+ timestamp: now - 10 * 60 * 1000,
+ bucketHours: 1,
+ totalHours: 24,
+ locale: 'en-US',
+ isEnd: false,
+ now,
+ });
+ expect(label).not.toBe('Now');
+ expect(label).toContain('Mar');
+ });
+
+ it('does NOT return "Now" for an end tick that is far from now', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const label = formatAlertAxisTickLabel({
+ timestamp: now - 20 * MS_PER_HOUR, // 20h ago, outside 0.75h window for 1h bucket
+ bucketHours: 1,
+ totalHours: 24,
+ locale: 'en-US',
+ isEnd: true,
+ now,
+ });
+ expect(label).not.toBe('Now');
+ expect(label).toContain('Mar');
+ });
+
+ it('uses month/day/hour/minute options for totalHours <= 48', () => {
+ const ts = Date.UTC(2026, 2, 22, 9, 30, 0);
+ const label = formatAlertAxisTickLabel({
+ timestamp: ts,
+ bucketHours: 1,
+ totalHours: 24,
+ locale: 'en-US',
+ });
+ // Short range includes the time-of-day.
+ expect(label).toContain('Mar 22');
+ expect(label).toContain('9:30');
+ expect(label).toMatch(/AM|PM/);
+ });
+
+ it('includes the hour for a mid-range total with a small bucket', () => {
+ const ts = Date.UTC(2026, 2, 22, 9, 30, 0);
+ const label = formatAlertAxisTickLabel({
+ timestamp: ts,
+ bucketHours: 6,
+ totalHours: 7 * 24, // 168h, <= 24*90 and bucketHours <= 12 → hour shown
+ locale: 'en-US',
+ });
+ expect(label).toContain('Mar 22');
+ // The mid-range branch sets only `hour` (no `minute`), so the time-of-day
+ // token is a bare hour like "09 AM" with no colon.
+ expect(label).toMatch(/09/);
+ expect(label).toMatch(/AM|PM/);
+ expect(label).not.toMatch(/\d{1,2}:\d{2}/);
+ });
+
+ it('omits the hour for a mid-range total with a large bucket and long span', () => {
+ const ts = Date.UTC(2026, 2, 22, 0, 0, 0);
+ const label = formatAlertAxisTickLabel({
+ timestamp: ts,
+ bucketHours: 24, // > 12
+ totalHours: 24 * 60, // 1440h: <= 24*90 (2160) but > 24*14 (336) → no hour
+ locale: 'en-US',
+ });
+ expect(label).toContain('Mar 22');
+ // No time-of-day token should appear.
+ expect(label).not.toMatch(/\d{1,2}:\d{2}/);
+ });
+
+ it('uses year/month/day options for very long ranges (totalHours > 24*90)', () => {
+ const ts = Date.UTC(2026, 2, 22, 0, 0, 0);
+ const label = formatAlertAxisTickLabel({
+ timestamp: ts,
+ bucketHours: 24,
+ totalHours: 24 * 120, // 2880h > 2160 → year branch
+ locale: 'en-US',
+ });
+ expect(label).toContain('2026');
+ expect(label).toContain('Mar 22');
+ // Year branch never includes time-of-day.
+ expect(label).not.toMatch(/\d{1,2}:\d{2}/);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildAlertRangeSummary — null guard, normal output shape, and the
+// `rangeHours ?? bucketHours` nullish-coalescing fallback.
+// ---------------------------------------------------------------------------
+
+describe('buildAlertRangeSummary', () => {
+ it('returns null when bucketTimes is empty', () => {
+ const trends: AlertTrendSeries = {
+ buckets: [],
+ max: 0,
+ bucketSize: 1,
+ bucketTimes: [],
+ rangeStart: 0,
+ rangeHours: 0,
+ };
+ expect(buildAlertRangeSummary(trends, 'en-US')).toBeNull();
+ });
+
+ it('returns null when bucketSize is zero', () => {
+ const trends: AlertTrendSeries = {
+ buckets: [1],
+ max: 1,
+ bucketSize: 0,
+ bucketTimes: [Date.UTC(2026, 2, 22)],
+ rangeStart: 0,
+ rangeHours: 1,
+ };
+ expect(buildAlertRangeSummary(trends, 'en-US')).toBeNull();
+ });
+
+ it('returns concrete startLabel/endLabel for a normal series', () => {
+ const start = Date.UTC(2026, 2, 22, 0, 0, 0);
+ const trends: AlertTrendSeries = {
+ buckets: [0, 0],
+ max: 1,
+ bucketSize: 6,
+ bucketTimes: [start, start + 6 * MS_PER_HOUR],
+ rangeStart: start,
+ rangeHours: 12,
+ };
+ const summary = buildAlertRangeSummary(trends, 'en-US');
+ expect(summary).not.toBeNull();
+ expect(summary!.startLabel).toContain('Mar 22');
+ expect(summary!.endLabel).toContain('Mar 22');
+ });
+
+ it('falls back to bucketHours when rangeHours is undefined', () => {
+ const start = Date.UTC(2026, 2, 22, 0, 0, 0);
+ const trends = {
+ buckets: [0],
+ max: 1,
+ bucketSize: 6,
+ bucketTimes: [start],
+ rangeStart: start,
+ rangeHours: undefined,
+ } as unknown as AlertTrendSeries;
+ // Should not throw; totalHours resolves to bucketHours (6) via the `??` arm.
+ const summary = buildAlertRangeSummary(trends, 'en-US');
+ expect(summary).not.toBeNull();
+ expect(typeof summary!.startLabel).toBe('string');
+ expect(summary!.startLabel.length).toBeGreaterThan(0);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildAlertAxisTicks — push-vs-replace last-tick arms and the align mapping.
+// (The first-tick `unshift` arm is suspected dead code — see GLM_REPORT.md.)
+// ---------------------------------------------------------------------------
+
+describe('buildAlertAxisTicks (last-tick + align arms)', () => {
+ const now = Date.UTC(2026, 2, 22, 12, 0, 0);
+
+ it('pushes a new last tick when the loop does not reach position 1', () => {
+ const trends = buildAlertTrends([], '24h', now);
+ const ticks = buildAlertAxisTicks(trends, 'en-US');
+ expect(ticks.length).toBeGreaterThanOrEqual(2);
+ expect(ticks[0].position).toBe(0);
+ expect(ticks[ticks.length - 1].position).toBe(1);
+ // First and last carry the start/end align markers.
+ expect(ticks[0].align).toBe('start');
+ expect(ticks[ticks.length - 1].align).toBe('end');
+ });
+
+ it('replaces the existing last tick when the loop already lands on position 1', () => {
+ // 2 bucket times, 1 bucket → loop hits index 0 and 1; index 1 maps to
+ // position 1.0, triggering the replace-last-tick branch.
+ const trends: AlertTrendSeries = {
+ buckets: [0],
+ max: 1,
+ bucketSize: 1,
+ bucketTimes: [now, now + MS_PER_HOUR],
+ rangeStart: now,
+ rangeHours: 1,
+ };
+ const ticks = buildAlertAxisTicks(trends, 'en-US');
+ expect(ticks).toHaveLength(2);
+ expect(ticks[1].position).toBe(1);
+ expect(ticks[1].align).toBe('end');
+ });
+
+ it('marks every non-edge tick as center-aligned', () => {
+ const trends = buildAlertTrends([], '30d', now);
+ const ticks = buildAlertAxisTicks(trends, 'en-US');
+ for (let i = 1; i < ticks.length - 1; i++) {
+ expect(ticks[i].align).toBe('center');
+ }
+ });
+
+ it('handles a single-bucket series by still emitting start and end ticks', () => {
+ const start = Date.UTC(2026, 2, 22, 0, 0, 0);
+ const trends: AlertTrendSeries = {
+ buckets: [0],
+ max: 1,
+ bucketSize: 6,
+ bucketTimes: [start],
+ rangeStart: start,
+ rangeHours: 6,
+ };
+ const ticks = buildAlertAxisTicks(trends, 'en-US');
+ expect(ticks.length).toBeGreaterThanOrEqual(2);
+ expect(ticks[0].position).toBe(0);
+ expect(ticks[ticks.length - 1].position).toBe(1);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildSelectedBucketDetails — null guard, the `0`-vs-null distinction,
+// exact {rangeLabel,start,end} shapes for every formatAlertBucketRange arm
+// (same-day, cross-day, cross-year), bucketSize 0, locale passthrough, and
+// the no-bounds-guard behaviour for out-of-range/negative indices.
+// ---------------------------------------------------------------------------
+
+describe('buildSelectedBucketDetails', () => {
+ function makeTrends(
+ bucketTimes: number[],
+ bucketSize: number,
+ overrides: Partial<AlertTrendSeries> = {},
+ ): AlertTrendSeries {
+ return {
+ buckets: bucketTimes.map(() => 0),
+ max: 1,
+ bucketSize,
+ bucketTimes,
+ rangeStart: bucketTimes[0] ?? 0,
+ rangeHours: bucketTimes.length * bucketSize,
+ ...overrides,
+ };
+ }
+
+ // --- null guard ----------------------------------------------------------
+
+ it('returns exactly null when selectedBarIndex is null', () => {
+ const trends = makeTrends([Date.UTC(2026, 2, 22, 12, 0, 0)], 1);
+ expect(buildSelectedBucketDetails(null, trends, 'en-US')).toBeNull();
+ });
+
+ it('treats index 0 as a valid bucket (not falsy-null) and returns a details object', () => {
+ const start = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const trends = makeTrends([start], 1);
+ const details = buildSelectedBucketDetails(0, trends, 'en-US');
+ expect(details).not.toBeNull();
+ expect(details!.start).toBe(start);
+ expect(details!.end).toBe(start + MS_PER_HOUR);
+ });
+
+ // --- exact full object shape for every formatting arm -------------------
+
+ it('returns the exact {rangeLabel,start,end} object for a same-day bucket', () => {
+ const start = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const trends = makeTrends([start], 1);
+ expect(buildSelectedBucketDetails(0, trends, 'en-US')).toStrictEqual({
+ rangeLabel: 'Mar 22, 12:00 PM – 1:00 PM',
+ start,
+ end: start + MS_PER_HOUR,
+ });
+ });
+
+ it('produces a cross-day rangeLabel with the arrow separator', () => {
+ const start = Date.UTC(2026, 2, 22, 22, 0, 0);
+ const trends = makeTrends([start], 6);
+ expect(buildSelectedBucketDetails(0, trends, 'en-US')).toStrictEqual({
+ rangeLabel: 'Mar 22, 10:00 PM → Mar 23, 2026, 4:00 AM',
+ start,
+ end: start + 6 * MS_PER_HOUR,
+ });
+ });
+
+ it('produces a cross-year rangeLabel that adds the year to the start segment', () => {
+ // Bucket spans New Year's Eve midnight → New Year's Day, crossing both day
+ // and year boundaries. formatAlertBucketRange must include the year on the
+ // start segment because start.getFullYear() !== end.getFullYear().
+ const start = Date.UTC(2025, 11, 31, 22, 0, 0);
+ const trends = makeTrends([start], 4);
+ expect(buildSelectedBucketDetails(0, trends, 'en-US')).toStrictEqual({
+ rangeLabel: 'Dec 31, 2025, 10:00 PM → Jan 1, 2026, 2:00 AM',
+ start,
+ end: start + 4 * MS_PER_HOUR,
+ });
+ });
+
+ // --- bucketSize edge -----------------------------------------------------
+
+ it('yields end === start when bucketSize is 0', () => {
+ const start = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const trends = makeTrends([start], 0);
+ const details = buildSelectedBucketDetails(0, trends, 'en-US');
+ expect(details).not.toBeNull();
+ expect(details!.start).toBe(start);
+ expect(details!.end).toBe(start);
+ expect(details!.rangeLabel).toBe('Mar 22, 12:00 PM – 12:00 PM');
+ });
+
+ // --- locale passthrough --------------------------------------------------
+
+ it('routes distinct locale formatting through to formatAlertBucketRange', () => {
+ const start = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const trends = makeTrends([start], 1);
+ const us = buildSelectedBucketDetails(0, trends, 'en-US');
+ const gb = buildSelectedBucketDetails(0, trends, 'en-GB');
+ expect(us!.rangeLabel).toBe('Mar 22, 12:00 PM – 1:00 PM');
+ expect(gb!.rangeLabel).toBe('22 Mar, 12:00 – 13:00');
+ expect(us!.rangeLabel).not.toBe(gb!.rangeLabel);
+ // Numeric fields are locale-independent.
+ expect(us!.start).toBe(gb!.start);
+ expect(us!.end).toBe(gb!.end);
+ });
+
+ // --- multi-bucket index resolution --------------------------------------
+
+ it('resolves a non-zero middle index against the correct bucketTimes entry', () => {
+ const t0 = Date.UTC(2026, 2, 22, 0, 0, 0);
+ const t1 = t0 + MS_PER_HOUR;
+ const t2 = t0 + 2 * MS_PER_HOUR;
+ const trends = makeTrends([t0, t1, t2], 1);
+ const details = buildSelectedBucketDetails(2, trends, 'en-US');
+ expect(details).not.toBeNull();
+ expect(details!.start).toBe(t2);
+ expect(details!.end).toBe(t2 + MS_PER_HOUR);
+ });
+
+ // --- no bounds guard: out-of-range / negative indices -------------------
+
+ it('produces undefined start and NaN end for an out-of-bounds index (no guard)', () => {
+ const start = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const trends = makeTrends([start], 1);
+ const details = buildSelectedBucketDetails(99, trends, 'en-US');
+ expect(details).not.toBeNull();
+ expect(details!.start).toBeUndefined();
+ expect(details!.end).toBeNaN();
+ // formatAlertBucketRange receives (undefined, NaN) and renders "Invalid Date".
+ expect(details!.rangeLabel).toBe('Invalid Date, Invalid Date → Invalid Date, Invalid Date');
+ });
+
+ it('produces undefined start and NaN end for a negative index', () => {
+ const start = Date.UTC(2026, 2, 22, 12, 0, 0);
+ const trends = makeTrends([start], 1);
+ const details = buildSelectedBucketDetails(-1, trends, 'en-US');
+ expect(details).not.toBeNull();
+ expect(details!.start).toBeUndefined();
+ expect(details!.end).toBeNaN();
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/alertSeverityPresentation.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/alertSeverityPresentation.branchcov0712.test.ts
new file mode 100644
index 0000000000..53c456e08a
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/alertSeverityPresentation.branchcov0712.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getAlertSeverityCompactLabel,
+ getAlertSeverityIndicator,
+ getAlertSeverityTextClass,
+} from '@/utils/alertSeverityPresentation';
+
+// `normalizeAlertSeverity` is a module-private (non-exported) helper, so its
+// branches are exercised indirectly through the exported wrappers below. Each
+// probe uses a wrapper whose output makes the normalized value observable.
+
+describe('alertSeverityPresentation — branch coverage (batch 2)', () => {
+ describe('getAlertSeverityIndicator — bucket ?? level / level ?? bucket', () => {
+ it('uses bucket for variant and level for label when both are provided', () => {
+ expect(getAlertSeverityIndicator('restart_loop', 'critical')).toStrictEqual({
+ variant: 'danger',
+ label: 'Restart Loop',
+ });
+ });
+
+ it('falls back to level for both variant and label when bucket is undefined', () => {
+ expect(getAlertSeverityIndicator('critical', undefined)).toStrictEqual({
+ variant: 'danger',
+ label: 'Critical',
+ });
+ });
+
+ it('falls back to level for both variant and label when bucket is null', () => {
+ expect(getAlertSeverityIndicator('warning', null)).toStrictEqual({
+ variant: 'warning',
+ label: 'Warning',
+ });
+ });
+
+ it('falls back to bucket for both variant and label when level is undefined', () => {
+ expect(getAlertSeverityIndicator(undefined, 'warning')).toStrictEqual({
+ variant: 'warning',
+ label: 'Warning',
+ });
+ });
+
+ it('falls back to bucket for both variant and label when level is null', () => {
+ expect(getAlertSeverityIndicator(null, 'info')).toStrictEqual({
+ variant: 'muted',
+ label: 'Info',
+ });
+ });
+
+ it('returns muted/Info defaults when both level and bucket are undefined', () => {
+ expect(getAlertSeverityIndicator(undefined, undefined)).toStrictEqual({
+ variant: 'muted',
+ label: 'Info',
+ });
+ });
+
+ it('returns muted/Info defaults when both level and bucket are null', () => {
+ expect(getAlertSeverityIndicator(null, null)).toStrictEqual({
+ variant: 'muted',
+ label: 'Info',
+ });
+ });
+
+ it('treats empty-string bucket as a real (non-nullish) value for variant', () => {
+ // `bucket ?? level`: '' is not nullish, so variant derives from '' →
+ // normalize('') === '' → default 'muted'. `level ?? bucket`: level is
+ // provided, so label still derives from level.
+ expect(getAlertSeverityIndicator('critical', '')).toStrictEqual({
+ variant: 'muted',
+ label: 'Critical',
+ });
+ });
+
+ it('treats empty-string level as a real (non-nullish) value for label', () => {
+ // `level ?? bucket`: '' is not nullish, so label derives from '' →
+ // formatAlertSeverityLabel('') returns the fallback 'Info'. `bucket ??
+ // level`: bucket is provided, so variant still derives from bucket.
+ expect(getAlertSeverityIndicator('', 'critical')).toStrictEqual({
+ variant: 'danger',
+ label: 'Info',
+ });
+ });
+ });
+
+ describe('getAlertSeverityTextClass — switch arms', () => {
+ it('returns the full critical text class for "critical"', () => {
+ expect(getAlertSeverityTextClass('critical')).toBe('text-red-600 dark:text-red-400');
+ });
+
+ it('returns the full warning text class for "warning"', () => {
+ expect(getAlertSeverityTextClass('warning')).toBe('text-amber-600 dark:text-amber-400');
+ });
+
+ it('falls through to the default blue class for "info" (no explicit info case)', () => {
+ expect(getAlertSeverityTextClass('info')).toBe('text-blue-600 dark:text-blue-400');
+ });
+
+ it('falls through to the default blue class for unknown severities', () => {
+ expect(getAlertSeverityTextClass('maintenance')).toBe('text-blue-600 dark:text-blue-400');
+ });
+ });
+
+ describe('normalizeAlertSeverity — nullish / trim / lowercase / coercion (via wrappers)', () => {
+ it('coerces undefined to empty string via the nullish-coalesce arm (default switch arm)', () => {
+ const level = undefined as unknown as Parameters<typeof getAlertSeverityTextClass>[0];
+ expect(getAlertSeverityTextClass(level)).toBe('text-blue-600 dark:text-blue-400');
+ });
+
+ it('coerces null to empty string via the nullish-coalesce arm (default switch arm)', () => {
+ const level = null as unknown as Parameters<typeof getAlertSeverityTextClass>[0];
+ expect(getAlertSeverityTextClass(level)).toBe('text-blue-600 dark:text-blue-400');
+ });
+
+ it('keeps an empty string as empty (non-nullish) hitting the default arm', () => {
+ expect(getAlertSeverityTextClass('')).toBe('text-blue-600 dark:text-blue-400');
+ });
+
+ it('trims surrounding whitespace then matches the critical arm', () => {
+ expect(getAlertSeverityTextClass(' critical ')).toBe('text-red-600 dark:text-red-400');
+ });
+
+ it('lowercases mixed-case input to match the warning arm', () => {
+ expect(getAlertSeverityTextClass('Warning')).toBe('text-amber-600 dark:text-amber-400');
+ });
+
+ it('String()-coerces a non-string number (0) to "0" hitting the default arm', () => {
+ const level = 0 as unknown as Parameters<typeof getAlertSeverityTextClass>[0];
+ expect(getAlertSeverityTextClass(level)).toBe('text-blue-600 dark:text-blue-400');
+ });
+ });
+
+ describe('getAlertSeverityCompactLabel — map hit vs uppercased fallback', () => {
+ it('returns mapped compact labels for the three known severities', () => {
+ expect(getAlertSeverityCompactLabel('critical')).toBe('CRIT');
+ expect(getAlertSeverityCompactLabel('warning')).toBe('WARN');
+ expect(getAlertSeverityCompactLabel('info')).toBe('INFO');
+ });
+
+ it('hits the map after normalizing whitespace and casing', () => {
+ expect(getAlertSeverityCompactLabel(' Critical ')).toBe('CRIT');
+ expect(getAlertSeverityCompactLabel('WARNING')).toBe('WARN');
+ });
+
+ it('falls back to the uppercased ORIGINAL level for unknown severities', () => {
+ expect(getAlertSeverityCompactLabel('maintenance')).toBe('MAINTENANCE');
+ });
+
+ it('preserves surrounding whitespace on the original level in the fallback', () => {
+ // The map lookup uses the trimmed/lowercased `normalized`, but the
+ // fallback uses the raw `level`, so whitespace survives uppercasing.
+ expect(getAlertSeverityCompactLabel(' maintenance ')).toBe(' MAINTENANCE ');
+ });
+
+ it('String()-coerces a non-string number (0) to "0" in the fallback path', () => {
+ const level = 0 as unknown as Parameters<typeof getAlertSeverityCompactLabel>[0];
+ expect(getAlertSeverityCompactLabel(level)).toBe('0');
+ });
+
+ it('coerces null to "NULL" in the fallback path', () => {
+ const level = null as unknown as Parameters<typeof getAlertSeverityCompactLabel>[0];
+ expect(getAlertSeverityCompactLabel(level)).toBe('NULL');
+ });
+
+ it('coerces undefined to "UNDEFINED" in the fallback path', () => {
+ const level = undefined as unknown as Parameters<typeof getAlertSeverityCompactLabel>[0];
+ expect(getAlertSeverityCompactLabel(level)).toBe('UNDEFINED');
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/reportableResourceTypes.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/reportableResourceTypes.branchcov0712.test.ts
new file mode 100644
index 0000000000..046fbddaff
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/reportableResourceTypes.branchcov0712.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it } from 'vitest';
+import type { ResourceType } from '@/types/resource';
+import type { ResourcePickerTypeFilter } from '@/utils/reportableResourceTypes';
+import {
+ matchesReportableResourceTypeFilter,
+ normalizeReportableResourceType,
+ reportableResourceTypeSortOrder,
+} from '@/utils/reportableResourceTypes';
+
+// Branch-coverage companion to reportableResourceTypes.test.ts. The sibling
+// suite only exercises a representative subset of each exported function; the
+// cases below drive the remaining arms of every conditional / early-return in
+// normalizeReportableResourceType and matchesReportableResourceTypeFilter, plus
+// the `?? 13` nullish-coalescing fallback in reportableResourceTypeSortOrder.
+// Assertions are on concrete outputs, matching the metricThresholds.branchcov2
+// convention.
+
+describe('normalizeReportableResourceType — branch coverage (branchcov2)', () => {
+ it("returns 'system-container' for both arms of the first guard's ||", () => {
+ // Sibling suite only exercises the oci-container arm; cover system-container too.
+ expect(normalizeReportableResourceType('system-container')).toBe('system-container');
+ expect(normalizeReportableResourceType('oci-container')).toBe('system-container');
+ });
+
+ it("normalizes 'app-container' through its dedicated guard", () => {
+ expect(normalizeReportableResourceType('app-container')).toBe('app-container');
+ });
+
+ it("normalizes 'docker-host' through its dedicated guard", () => {
+ expect(normalizeReportableResourceType('docker-host')).toBe('docker-host');
+ });
+
+ it("normalizes 'k8s-node' to 'node' (distinct from k8s-cluster's 'k8s' arm)", () => {
+ expect(normalizeReportableResourceType('k8s-node')).toBe('node');
+ expect(normalizeReportableResourceType('k8s-cluster')).toBe('k8s');
+ });
+
+ it('returns the type verbatim for every remaining default-arm type', () => {
+ // vm is covered by the sibling suite; add the other reportable types that
+ // fall through to `return type`.
+ const passthrough: ResourceType[] = [
+ 'agent',
+ 'vm',
+ 'pod',
+ 'pbs',
+ 'pmg',
+ 'storage',
+ 'datastore',
+ 'pool',
+ 'dataset',
+ 'network-share',
+ ];
+ for (const type of passthrough) {
+ expect(normalizeReportableResourceType(type)).toBe(type);
+ }
+ });
+});
+
+describe('matchesReportableResourceTypeFilter — branch coverage (branchcov2)', () => {
+ it("returns true unconditionally for the 'all' filter (first early-return)", () => {
+ expect(matchesReportableResourceTypeFilter({ type: 'vm' }, 'all')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'pbs' }, 'all')).toBe(true);
+ });
+
+ it('infrastructure filter: true for every INFRASTRUCTURE_TYPES member, false otherwise', () => {
+ // Sibling suite only asserts the true arm (agent); cover false arm + the rest.
+ expect(matchesReportableResourceTypeFilter({ type: 'agent' }, 'infrastructure')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'docker-host' }, 'infrastructure')).toBe(
+ true,
+ );
+ expect(matchesReportableResourceTypeFilter({ type: 'k8s-cluster' }, 'infrastructure')).toBe(
+ true,
+ );
+ expect(matchesReportableResourceTypeFilter({ type: 'k8s-node' }, 'infrastructure')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'pbs' }, 'infrastructure')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'pmg' }, 'infrastructure')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'vm' }, 'infrastructure')).toBe(false);
+ });
+
+ it('workloads filter: true for every WORKLOAD_TYPES member, false otherwise', () => {
+ expect(matchesReportableResourceTypeFilter({ type: 'vm' }, 'workloads')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'system-container' }, 'workloads')).toBe(
+ true,
+ );
+ expect(matchesReportableResourceTypeFilter({ type: 'app-container' }, 'workloads')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'oci-container' }, 'workloads')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'pod' }, 'workloads')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'agent' }, 'workloads')).toBe(false);
+ });
+
+ it('storage filter: true for every STORAGE_TYPES member, false otherwise', () => {
+ expect(matchesReportableResourceTypeFilter({ type: 'storage' }, 'storage')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'datastore' }, 'storage')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'pool' }, 'storage')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'dataset' }, 'storage')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'network-share' }, 'storage')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'agent' }, 'storage')).toBe(false);
+ });
+
+ it('recovery filter: true for both RECOVERY_TYPES (pbs AND datastore), false otherwise', () => {
+ // Sibling suite only asserts pbs->true; datastore is the other recovery type.
+ expect(matchesReportableResourceTypeFilter({ type: 'pbs' }, 'recovery')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'datastore' }, 'recovery')).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'vm' }, 'recovery')).toBe(false);
+ expect(matchesReportableResourceTypeFilter({ type: 'storage' }, 'recovery')).toBe(false);
+ });
+
+ it("returns true via the defensive fall-through for an unrecognized filter value", () => {
+ // No declared ResourcePickerTypeFilter reaches the final `return true`, so a
+ // bogus value is cast through unknown to satisfy strict mode while driving
+ // the branch at runtime.
+ const unknownFilter = 'everything-else' as unknown as ResourcePickerTypeFilter;
+ expect(matchesReportableResourceTypeFilter({ type: 'vm' }, unknownFilter)).toBe(true);
+ expect(matchesReportableResourceTypeFilter({ type: 'pbs' }, unknownFilter)).toBe(true);
+ });
+});
+
+describe('reportableResourceTypeSortOrder — branch coverage (branchcov2)', () => {
+ it('returns the exact SORT_ORDER bucket for each normalize-resolved type', () => {
+ // Sibling suite only asserts relative ordering (toBeLessThan); assert the
+ // concrete numbers so a SORT_ORDER edit is caught.
+ expect(reportableResourceTypeSortOrder('agent')).toBe(0);
+ expect(reportableResourceTypeSortOrder('docker-host')).toBe(1);
+ expect(reportableResourceTypeSortOrder('k8s-cluster')).toBe(2); // normalizes to 'k8s'
+ expect(reportableResourceTypeSortOrder('pbs')).toBe(3);
+ expect(reportableResourceTypeSortOrder('pmg')).toBe(4);
+ expect(reportableResourceTypeSortOrder('vm')).toBe(5);
+ expect(reportableResourceTypeSortOrder('system-container')).toBe(6);
+ expect(reportableResourceTypeSortOrder('oci-container')).toBe(6); // normalizes to 'system-container'
+ expect(reportableResourceTypeSortOrder('app-container')).toBe(7);
+ expect(reportableResourceTypeSortOrder('pod')).toBe(8);
+ expect(reportableResourceTypeSortOrder('storage')).toBe(9);
+ expect(reportableResourceTypeSortOrder('datastore')).toBe(10);
+ expect(reportableResourceTypeSortOrder('pool')).toBe(11);
+ expect(reportableResourceTypeSortOrder('dataset')).toBe(12);
+ expect(reportableResourceTypeSortOrder('network-share')).toBe(13);
+ });
+
+ it('uses the `?? 13` fallback for default-arm types absent from SORT_ORDER', () => {
+ // Valid ResourceType values that fall through normalize's default arm to
+ // their own string, which is not a SORT_ORDER key -> nullish fallback fires.
+ expect(reportableResourceTypeSortOrder('jail')).toBe(13);
+ expect(reportableResourceTypeSortOrder('ceph')).toBe(13);
+ expect(reportableResourceTypeSortOrder('network')).toBe(13);
+ expect(reportableResourceTypeSortOrder('network-endpoint')).toBe(13);
+ expect(reportableResourceTypeSortOrder('physical_disk')).toBe(13);
+ });
+
+ it("uses the `?? 13` fallback for 'k8s-node', which normalizes to the missing 'node' key", () => {
+ // k8s-node is a reportable type that normalizes to 'node', but 'node' is
+ // not a SORT_ORDER key, so the fallback fires and the node sorts alongside
+ // network-share (13) instead of grouping with k8s-cluster (2).
+ expect(reportableResourceTypeSortOrder('k8s-node')).toBe(13);
+ expect(reportableResourceTypeSortOrder('k8s-cluster')).toBe(2);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/theme.branchcov0712.test.ts b/frontend-modern/src/utils/__tests__/theme.branchcov0712.test.ts
new file mode 100644
index 0000000000..25f2528815
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/theme.branchcov0712.test.ts
@@ -0,0 +1,89 @@
+/**
+ * Branch-coverage tests for theme.ts — second pass.
+ *
+ * Scope: ONLY `getStoredThemePreference`. The sibling theme.test.ts exercises
+ * the happy path for this function; this file drives every remaining branch:
+ *
+ * - The `isThemePreference(explicitPreference)` truthy arm, for each of the
+ * three canonical values it accepts ('light', 'dark', 'system').
+ * - The falsy arm that falls back to 'system', reached through every path that
+ * `safeGet` + `isThemePreference` can produce a non-matching value:
+ * - nothing stored (null),
+ * - a non-canonical stored string,
+ * - an empty string,
+ * - `localStorage.getItem` throwing (safeGet catch arm),
+ * - an SSR context where `typeof window === 'undefined'` (safeGet early
+ * null-return arm).
+ *
+ * SSR arms are reached by stubbing `window` to undefined for a single
+ * assertion and restoring it inside a `finally`; the module guards on
+ * `typeof window === 'undefined'` before touching window, so the stub is safe
+ * as long as it is removed before any other code runs.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { STORAGE_KEYS } from '@/utils/localStorage';
+import { getStoredThemePreference } from '@/utils/theme';
+
+const THEME_KEY = STORAGE_KEYS.THEME_PREFERENCE;
+
+describe('getStoredThemePreference (branch coverage)', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ describe('isThemePreference truthy arm — returns each canonical value verbatim', () => {
+ it("returns 'light' when 'light' is stored", () => {
+ window.localStorage.setItem(THEME_KEY, 'light');
+ expect(getStoredThemePreference()).toBe('light');
+ });
+
+ it("returns 'dark' when 'dark' is stored", () => {
+ window.localStorage.setItem(THEME_KEY, 'dark');
+ expect(getStoredThemePreference()).toBe('dark');
+ });
+
+ it("returns 'system' when 'system' is stored (does NOT collapse to the fallback)", () => {
+ // Distinguishes the truthy 'system' arm from the falsy 'system' fallback:
+ // both yield 'system', but only the truthy arm reads the stored value.
+ window.localStorage.setItem(THEME_KEY, 'system');
+ expect(getStoredThemePreference()).toBe('system');
+ expect(window.localStorage.getItem(THEME_KEY)).toBe('system');
+ });
+ });
+
+ describe('falsy arm — falls back to system for every non-matching stored value', () => {
+ it("falls back to 'system' when nothing is stored (explicitPreference === null)", () => {
+ expect(window.localStorage.getItem(THEME_KEY)).toBeNull();
+ expect(getStoredThemePreference()).toBe('system');
+ });
+
+ it("falls back to 'system' for a non-canonical stored string", () => {
+ window.localStorage.setItem(THEME_KEY, 'banana');
+ expect(getStoredThemePreference()).toBe('system');
+ });
+
+ it("falls back to 'system' for an empty string (isThemePreference rejects '')", () => {
+ window.localStorage.setItem(THEME_KEY, '');
+ expect(getStoredThemePreference()).toBe('system');
+ });
+
+ it("falls back to 'system' when localStorage.getItem throws (safeGet catch arm)", () => {
+ const spy = vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
+ throw new Error('SecurityError');
+ });
+ expect(getStoredThemePreference()).toBe('system');
+ expect(spy).toHaveBeenCalledWith(THEME_KEY);
+ });
+
+ it("returns 'system' in an SSR context where window is undefined (safeGet early null arm)", () => {
+ vi.stubGlobal('window', undefined);
+ expect(getStoredThemePreference()).toBe('system');
+ });
+ });
+});