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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
test(coverage): pulse PURE branch-cov (16 presentation/model modules)
rcourtman533c3392bdef
diff --git a/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov0713.test.ts b/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov0713.test.tsnew file mode 100644index 0000000000..7ee3709d9e--- /dev/null+++ b/frontend-modern/src/components/Alerts/__tests__/alertResourceTableModel.branchcov0713.test.ts@@ -0,0 +1,356 @@+import { describe, expect, it } from 'vitest';++import {+ alertResourceSupportsMetric,+ buildAlertResourceEditPayload,+ flattenAlertResourceTableResources,+ getAlertResourceColumnHeaderTooltip,+ getAlertResourceColumnKind,+ getAlertResourceEnabledDefault,+ getAlertResourceLabel,+ getAlertResourceMetricBounds,+ getAlertResourceMetricDelayOverride,+ getAlertResourceMetricDisplayValue,+ getAlertResourceMetricStep,+ hasAlertResourceTableRows,+ hasCustomAlertResourceGlobalDefaults,+ isAlertResourceMetricOverridden,+ normalizeAlertResourceMetricKey,+ type AlertResourceTableResourceLike,+ type AlertResourceThresholdMap,+} from '../alertResourceTableModel';++function makeResource(+ overrides: Partial<AlertResourceTableResourceLike> = {},+): AlertResourceTableResourceLike {+ return {+ id: 'res-1',+ name: 'Test VM',+ ...overrides,+ };+}++describe('isAlertResourceMetricOverridden', () => {+ it('returns true when the metric has a positive numeric override', () => {+ const resource = makeResource({ thresholds: { cpu: 80 } });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(true);+ });++ it('returns true when the override is 0 (not collapsed by undefined/null guards)', () => {+ const resource = makeResource({ thresholds: { cpu: 0 } });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(true);+ });++ it('returns true for a negative override value', () => {+ const resource = makeResource({ thresholds: { cpu: -1 } });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(true);+ });++ it('returns true when the value is a non-null/undefined string', () => {+ const thresholds = { cpu: '90' } as unknown as AlertResourceThresholdMap;+ const resource = makeResource({ thresholds });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(true);+ });++ it('returns false when thresholds is undefined (optional-chain short-circuit)', () => {+ const resource = makeResource({ thresholds: undefined });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(false);+ });++ it('returns false when thresholds is an empty object', () => {+ const resource = makeResource({ thresholds: {} });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(false);+ });++ it('returns false when the metric is absent from a populated thresholds map', () => {+ const resource = makeResource({ thresholds: { memory: 90 } });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(false);+ });++ it('returns false when the metric value is explicitly undefined', () => {+ const resource = makeResource({ thresholds: { cpu: undefined } });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(false);+ });++ it('returns false when the metric value is null (second guard arm)', () => {+ const thresholds = { cpu: null } as unknown as AlertResourceThresholdMap;+ const resource = makeResource({ thresholds });+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(false);+ });++ it('checks a different metric than the one present', () => {+ const resource = makeResource({ thresholds: { cpu: 80 } });+ expect(isAlertResourceMetricOverridden(resource, 'memory')).toBe(false);+ expect(isAlertResourceMetricOverridden(resource, 'cpu')).toBe(true);+ });+});++describe('buildAlertResourceEditPayload', () => {+ it('returns shallow copies of thresholds and defaults plus the string note', () => {+ const resource = makeResource({+ thresholds: { cpu: 80, memory: 90 },+ defaults: { cpu: 70 },+ note: 'adjusted thresholds',+ });+ const payload = buildAlertResourceEditPayload(resource);+ expect(payload.thresholds).toEqual({ cpu: 80, memory: 90 });+ expect(payload.defaults).toEqual({ cpu: 70 });+ expect(payload.note).toBe('adjusted thresholds');+ });++ it('returns empty objects for thresholds and defaults when they are absent', () => {+ const payload = buildAlertResourceEditPayload(makeResource());+ expect(payload.thresholds).toEqual({});+ expect(payload.defaults).toEqual({});+ });++ it('returns undefined note when note is not set on the resource', () => {+ const payload = buildAlertResourceEditPayload(makeResource({ note: undefined }));+ expect(payload.note).toBeUndefined();+ });++ it('returns undefined note when note is a number (typeof string check fails)', () => {+ const resource = makeResource({ note: 42 as unknown as string });+ expect(buildAlertResourceEditPayload(resource).note).toBeUndefined();+ });++ it('preserves an empty-string note because typeof "" === "string"', () => {+ const resource = makeResource({ note: '' });+ expect(buildAlertResourceEditPayload(resource).note).toBe('');+ });++ it('produces a thresholds copy that is not a reference to the source', () => {+ const resource = makeResource({ thresholds: { cpu: 80 } });+ const payload = buildAlertResourceEditPayload(resource);+ payload.thresholds.cpu = 999;+ expect(resource.thresholds?.cpu).toBe(80);+ });++ it('produces a defaults copy that is not a reference to the source', () => {+ const resource = makeResource({ defaults: { cpu: 70 } });+ const payload = buildAlertResourceEditPayload(resource);+ payload.defaults.cpu = 999;+ expect(resource.defaults?.cpu).toBe(70);+ });++ it('copies empty thresholds and defaults objects into new object instances', () => {+ const resource = makeResource({ thresholds: {}, defaults: {} });+ const payload = buildAlertResourceEditPayload(resource);+ expect(payload.thresholds).toEqual({});+ expect(payload.defaults).toEqual({});+ expect(payload.thresholds).not.toBe(resource.thresholds);+ expect(payload.defaults).not.toBe(resource.defaults);+ });++ it('always returns an object with thresholds, defaults, and note keys', () => {+ const payload = buildAlertResourceEditPayload(makeResource());+ expect(Object.keys(payload).sort()).toEqual(['defaults', 'note', 'thresholds']);+ });+});++describe('hasAlertResourceTableRows — uncovered groupedResources arms', () => {+ it('returns true when groupedResources is empty-object and globalDefaults is populated', () => {+ expect(hasAlertResourceTableRows(undefined, {}, { cpu: 80 })).toBe(true);+ });++ it('returns false when groupedResources is empty-object and globalDefaults is undefined', () => {+ expect(hasAlertResourceTableRows(undefined, {}, undefined)).toBe(false);+ });++ it('returns true for empty-object groupedDefaults with empty-object globalDefaults', () => {+ expect(hasAlertResourceTableRows(undefined, {}, {})).toBe(true);+ });+});++describe('hasCustomAlertResourceGlobalDefaults — uncovered factoryDefaults arms', () => {+ it('returns false when factoryDefaults is an empty object (no keys to compare)', () => {+ expect(hasCustomAlertResourceGlobalDefaults({ cpu: 80 }, {})).toBe(false);+ });++ it('returns false when both arguments are empty objects', () => {+ expect(hasCustomAlertResourceGlobalDefaults({}, {})).toBe(false);+ });++ it('returns false when globalDefaults is an empty object but factoryDefaults has keys', () => {+ expect(hasCustomAlertResourceGlobalDefaults({}, { cpu: 80 })).toBe(false);+ });+});++describe('normalizeAlertResourceMetricKey — compound replace chains', () => {+ it('chains " %" strip with "disk w" replacement to produce "diskWrite"', () => {+ expect(normalizeAlertResourceMetricKey('disk w %')).toBe('diskWrite');+ });++ it('chains " %" strip with "net in" replacement to produce "networkIn"', () => {+ expect(normalizeAlertResourceMetricKey('net in %')).toBe('networkIn');+ });++ it('chains " %" strip with "net out" replacement to produce "networkOut"', () => {+ expect(normalizeAlertResourceMetricKey('net out %')).toBe('networkOut');+ });++ it('strips both " %" and " °c" suffixes in one pass', () => {+ expect(normalizeAlertResourceMetricKey('foo °c %')).toBe('foo');+ });++ it('strips " mb/s" from an unmapped key without further replacements', () => {+ expect(normalizeAlertResourceMetricKey('zzz mb/s')).toBe('zzz');+ });+});++describe('getAlertResourceMetricBounds — edge inputs', () => {+ it('returns the default bounds for an empty-string metric', () => {+ expect(getAlertResourceMetricBounds('')).toStrictEqual({ min: -1, max: 10000 });+ });++ it('returns the default bounds for a whitespace metric', () => {+ expect(getAlertResourceMetricBounds(' ')).toStrictEqual({ min: -1, max: 10000 });+ });+});++describe('getAlertResourceMetricStep — edge inputs', () => {+ it('returns 1 for an empty-string metric', () => {+ expect(getAlertResourceMetricStep('')).toBe(1);+ });++ it('returns 1 for a whitespace-only metric', () => {+ expect(getAlertResourceMetricStep(' ')).toBe(1);+ });+});++describe('getAlertResourceEnabledDefault — edge inputs', () => {+ it('returns the fallback of 80 for an empty-string metric', () => {+ expect(getAlertResourceEnabledDefault('')).toBe(80);+ });++ it('returns 55 for diskTemperature (distinct from temperature)', () => {+ expect(getAlertResourceEnabledDefault('diskTemperature')).toBe(55);+ });+});++describe('getAlertResourceMetricDelayOverride — uncovered normalization arms', () => {+ it('normalizes leading/trailing whitespace AND mixed case together', () => {+ expect(getAlertResourceMetricDelayOverride({ cpu: 42 }, ' CPU ')).toBe(42);+ });++ it('prefers the normalized-key value when both normalized and original keys exist', () => {+ const map = { cpu: 10, CPU: 20 } as Record<string, number>;+ expect(getAlertResourceMetricDelayOverride(map, 'CPU')).toBe(10);+ });++ it('returns undefined for a whitespace-only metric with no matching key', () => {+ expect(getAlertResourceMetricDelayOverride({ cpu: 30 }, ' ')).toBeUndefined();+ });+});++describe('getAlertResourceColumnHeaderTooltip — edge inputs', () => {+ it('returns undefined for an empty-string column', () => {+ expect(getAlertResourceColumnHeaderTooltip('')).toBeUndefined();+ });++ it('returns undefined for a whitespace-only column', () => {+ expect(getAlertResourceColumnHeaderTooltip(' ')).toBeUndefined();+ });+});++describe('getAlertResourceColumnKind — compound normalization edges', () => {+ it('returns "badge" for "Backup %" via compound strip-then-Map-miss path', () => {+ expect(getAlertResourceColumnKind('Backup %')).toBe('badge');+ });++ it('returns "badge" for "Snapshot" (case-insensitive Map hit)', () => {+ expect(getAlertResourceColumnKind('Snapshot')).toBe('badge');+ });+});++describe('alertResourceSupportsMetric — supplementary metric arms', () => {+ it('returns true for disk on node (non-throughput metric bypasses the node guard)', () => {+ expect(alertResourceSupportsMetric('node', 'disk')).toBe(true);+ });++ it('returns false for diskRead on agent (throughput blocked for agents)', () => {+ expect(alertResourceSupportsMetric('agent', 'diskRead')).toBe(false);+ });++ it('returns false for temperature on storage (only usage supported)', () => {+ expect(alertResourceSupportsMetric('storage', 'temperature')).toBe(false);+ });++ it('returns false for usage on kubernetesCluster (not in the cluster metric set)', () => {+ expect(alertResourceSupportsMetric('kubernetesCluster', 'usage')).toBe(false);+ });++ it('returns true for memory on kubernetesPod', () => {+ expect(alertResourceSupportsMetric('kubernetesPod', 'memory')).toBe(true);+ });++ it('returns true for diskWrite on vmwareVm', () => {+ expect(alertResourceSupportsMetric('vmwareVm', 'diskWrite')).toBe(true);+ });++ it('returns false for memory on vmwareDatastore (only usage)', () => {+ expect(alertResourceSupportsMetric('vmwareDatastore', 'memory')).toBe(false);+ });++ it('returns false for cpu on vmwareNetwork (nothing supported)', () => {+ expect(alertResourceSupportsMetric('vmwareNetwork', 'cpu')).toBe(false);+ });++ it('returns false for disk on dockerContainer (not in restart/memory set)', () => {+ expect(alertResourceSupportsMetric('dockerContainer', 'disk')).toBe(false);+ });++ it('returns false for diskRead on kubernetesNode (not in cpu/memory/disk set)', () => {+ expect(alertResourceSupportsMetric('kubernetesNode', 'diskRead')).toBe(false);+ });+});++describe('getAlertResourceLabel — uncovered displayName/name arms', () => {+ it('falls through an empty-string displayName to the name', () => {+ const resource = makeResource({ name: 'web-01', displayName: '' });+ expect(getAlertResourceLabel(resource)).toBe('web-01');+ });++ it('falls through absent displayName and empty-string name to the resource id', () => {+ const resource = makeResource({ id: 'vm-42', name: '' });+ expect(getAlertResourceLabel(resource)).toBe('vm-42');+ });+});++describe('getAlertResourceMetricDisplayValue — boolean defaults coercion', () => {+ it('coerces a defaults boolean true to 1 via Number() in live mode', () => {+ const defaults = { cpu: true } as unknown as AlertResourceThresholdMap;+ const resource = makeResource({ defaults });+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(1);+ });++ it('coerces a defaults boolean false to 0 via Number() in live mode', () => {+ const defaults = { cpu: false } as unknown as AlertResourceThresholdMap;+ const resource = makeResource({ defaults });+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu')).toBe(0);+ });++ it('coerces a defaults boolean true to 1 in edit mode when editingThresholds is empty', () => {+ const defaults = { cpu: true } as unknown as AlertResourceThresholdMap;+ const resource = makeResource({ defaults });+ expect(getAlertResourceMetricDisplayValue(resource, 'cpu', {}, true)).toBe(1);+ });+});++describe('flattenAlertResourceTableResources — nullish edge arms', () => {+ it('returns an empty array when resources is null (nullish coalescing treats null as nullish)', () => {+ const resources = null as unknown as AlertResourceTableResourceLike[];+ expect(flattenAlertResourceTableResources(resources)).toEqual([]);+ });++ it('falls back to resources when groupedResources is null (falsy, fails truthy guard)', () => {+ const a = makeResource({ id: 'a', name: 'A' });+ const grouped = null as unknown as Record<string, AlertResourceTableResourceLike[]>;+ expect(flattenAlertResourceTableResources([a], grouped)).toEqual([a]);+ });++ it('returns the single-item array from a single-key groupedResources', () => {+ const a = makeResource({ id: 'only', name: 'Only' });+ expect(flattenAlertResourceTableResources(undefined, { g: [a] })).toEqual([a]);+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0713.test.ts b/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0713.test.tsnew file mode 100644index 0000000000..035e2df632--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/apiTokenManagerModel.branchcov0713.test.ts@@ -0,0 +1,637 @@+import { describe, expect, it } from 'vitest';+import type { APITokenRecord } from '@/api/security';+import {+ API_SCOPE_OPTIONS,+ type APIScopeOption,+ AGENT_REPORT_SCOPE,+ AUDIT_READ_SCOPE,+ DOCKER_MANAGE_SCOPE,+ DOCKER_REPORT_SCOPE,+ MONITORING_READ_SCOPE,+ SETTINGS_READ_SCOPE,+ SETTINGS_WRITE_SCOPE,+} from '@/constants/apiScopes';+import type { Resource } from '@/types/resource';+import {+ API_TOKEN_DOCKER_MANAGE_PRESET_DESCRIPTION,+ API_TOKEN_DOCKER_MANAGE_PRESET_LABEL,+ API_TOKEN_DOCKER_REPORT_PRESET_DESCRIPTION,+ API_TOKEN_DOCKER_REPORT_PRESET_LABEL,+} from '@/utils/apiTokenPresentation';+import {+ API_TOKEN_AGENT_PRESET_ID,+ API_TOKEN_AUDIT_READ_PRESET_ID,+ API_TOKEN_DOCKER_MANAGE_PRESET_ID,+ API_TOKEN_DOCKER_REPORT_PRESET_ID,+ API_TOKEN_KIOSK_PRESET_ID,+ API_TOKEN_PATROL_EXTERNAL_AGENT_PRESET_LABEL,+ API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID,+ API_TOKEN_SETTINGS_ADMIN_PRESET_ID,+ API_TOKEN_SETTINGS_READ_PRESET_ID,+ API_TOKEN_WILDCARD_SCOPE,+ buildAgentTokenUsage,+ buildDockerTokenUsage,+ countWildcardTokens,+ dockerActionIdForResource,+ getAPITokenScopePresets,+ groupAPITokenScopes,+ revokedTokenIdForResource,+ sortAPITokensByCreatedAt,+ tokenIdForResource,+} from '../apiTokenManagerModel';++// ---- Fixtures ---------------------------------------------------------------+// Mirrors the sibling apiTokenManagerModel.branchcov0712.test.ts builders so+// every private reader under test (readPlatformString / readNestedPlatformField+// / readPlatformData) is driven only through the exported orchestrators.++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,+});++// ---- readPlatformString (private) via tokenIdForResource --------------------+//+// readPlatformString is module-private and ONLY reachable through+// tokenIdForResource / revokedTokenIdForResource (neither is exercised by the+// sibling tests). Placing `tokenId` at the TOP level of platformData makes+// readNestedPlatformField return it verbatim (the `field in platformData` arm),+// so readPlatformString receives the raw value and both of its+// typeof/length arms are exercised.++describe('readPlatformString (via tokenIdForResource)', () => {+ it('returns a non-empty string verbatim', () => {+ expect(+ tokenIdForResource(makeResource({ platformData: { tokenId: 'tok-abc' } })),+ ).toBe('tok-abc');+ });++ it('returns undefined for an empty string (length === 0)', () => {+ expect(+ tokenIdForResource(makeResource({ platformData: { tokenId: '' } })),+ ).toBeUndefined();+ });++ it('returns undefined for a whitespace-only string (still length > 0, not trimmed)', () => {+ // readPlatformString intentionally does NOT trim; a blank-but-non-empty+ // string is returned verbatim, proving it is distinct from the empty arm.+ expect(+ tokenIdForResource(makeResource({ platformData: { tokenId: ' ' } })),+ ).toBe(' ');+ });++ it.each([42, 0, true, false, null, ['array'], { k: 'v' }])(+ 'returns undefined for a non-string value (%s)',+ (value) => {+ expect(+ tokenIdForResource(+ makeResource({ platformData: { tokenId: value as unknown } as Record<string, unknown> }),+ ),+ ).toBeUndefined();+ },+ );+});++// ---- tokenIdForResource (exported composition) -----------------------------+//+// Drives the readNestedPlatformField fall-through arms specifically for the+// 'tokenId' field key, proving the exported wrapper honors the same+// top-level -> agent -> docker resolution graph as tokenRevokedAtForResource.++describe('tokenIdForResource', () => {+ it('resolves tokenId from platformData.agent when absent at the top level', () => {+ expect(+ tokenIdForResource(makeResource({ platformData: { agent: { tokenId: 'agent-tok' } } })),+ ).toBe('agent-tok');+ });++ it('resolves tokenId from platformData.docker when neither top-level nor agent carry it', () => {+ expect(+ tokenIdForResource(+ makeResource({ platformData: { agent: { x: 1 }, docker: { tokenId: 'docker-tok' } } }),+ ),+ ).toBe('docker-tok');+ });++ it('returns undefined when platformData is absent', () => {+ expect(tokenIdForResource(makeResource({ platformData: undefined }))).toBeUndefined();+ });++ it('returns undefined when the field is nowhere in the platformData graph', () => {+ expect(+ tokenIdForResource(+ makeResource({ platformData: { agent: { other: 1 }, docker: { other: 2 } } }),+ ),+ ).toBeUndefined();+ });+});++// ---- revokedTokenIdForResource ----------------------------------------------+//+// Same private-reader composition as tokenIdForResource but for the+// 'revokedTokenId' key. Not exercised by sibling tests.++describe('revokedTokenIdForResource', () => {+ it('returns a non-empty revokedTokenId string verbatim from the top level', () => {+ expect(+ revokedTokenIdForResource(+ makeResource({ platformData: { revokedTokenId: 'revoked-1' } }),+ ),+ ).toBe('revoked-1');+ });++ it('returns undefined for an empty-string revokedTokenId', () => {+ expect(+ revokedTokenIdForResource(makeResource({ platformData: { revokedTokenId: '' } })),+ ).toBeUndefined();+ });++ it.each([99, true, null, { k: 'v' }])(+ 'returns undefined for a non-string revokedTokenId (%s)',+ (value) => {+ expect(+ revokedTokenIdForResource(+ makeResource({+ platformData: { revokedTokenId: value as unknown } as Record<string, unknown>,+ }),+ ),+ ).toBeUndefined();+ },+ );++ it('resolves revokedTokenId from platformData.docker when not at the top level', () => {+ expect(+ revokedTokenIdForResource(+ makeResource({ platformData: { docker: { revokedTokenId: 'docker-revoked' } } }),+ ),+ ).toBe('docker-revoked');+ });++ it('returns undefined when platformData is absent', () => {+ expect(revokedTokenIdForResource(makeResource({ platformData: undefined }))).toBeUndefined();+ });+});++// ---- sortAPITokensByCreatedAt ----------------------------------------------++describe('sortAPITokensByCreatedAt', () => {+ it('returns an empty array unchanged', () => {+ expect(sortAPITokensByCreatedAt([])).toStrictEqual([]);+ });++ it('returns a single-element array unchanged', () => {+ const only = makeToken({ id: 'solo' });+ expect(sortAPITokensByCreatedAt([only])).toStrictEqual([only]);+ });++ it('sorts tokens newest-first when given oldest-first input', () => {+ const oldest = makeToken({ id: 'old', createdAt: '2026-01-01T00:00:00.000Z' });+ const middle = makeToken({ id: 'mid', createdAt: '2026-06-01T00:00:00.000Z' });+ const newest = makeToken({ id: 'new', createdAt: '2026-12-31T00:00:00.000Z' });+ expect(sortAPITokensByCreatedAt([oldest, middle, newest]).map((t) => t.id)).toStrictEqual([+ 'new',+ 'mid',+ 'old',+ ]);+ });++ it('keeps an already newest-first array in the same order', () => {+ const newest = makeToken({ id: 'new', createdAt: '2026-12-31T00:00:00.000Z' });+ const middle = makeToken({ id: 'mid', createdAt: '2026-06-01T00:00:00.000Z' });+ const oldest = makeToken({ id: 'old', createdAt: '2026-01-01T00:00:00.000Z' });+ expect(sortAPITokensByCreatedAt([newest, middle, oldest]).map((t) => t.id)).toStrictEqual([+ 'new',+ 'mid',+ 'old',+ ]);+ });++ it('preserves all elements when timestamps tie (count intact)', () => {+ const tied = makeToken({ id: 'tied', createdAt: '2026-05-05T00:00:00.000Z' });+ const alsoTied = makeToken({ id: 'also-tied', createdAt: '2026-05-05T00:00:00.000Z' });+ const result = sortAPITokensByCreatedAt([tied, alsoTied]);+ expect(result).toHaveLength(2);+ expect(new Set(result.map((t) => t.id))).toStrictEqual(new Set(['tied', 'also-tied']));+ });++ it('does not mutate the input array', () => {+ const oldest = makeToken({ id: 'old', createdAt: '2026-01-01T00:00:00.000Z' });+ const newest = makeToken({ id: 'new', createdAt: '2026-12-31T00:00:00.000Z' });+ const input = [oldest, newest];+ sortAPITokensByCreatedAt(input);+ expect(input.map((t) => t.id)).toStrictEqual(['old', 'new']);+ });++ it('returns a new array reference (not the input)', () => {+ const input = [makeToken()];+ expect(sortAPITokensByCreatedAt(input)).not.toBe(input);+ });+});++// ---- countWildcardTokens ----------------------------------------------------++describe('countWildcardTokens', () => {+ it('returns 0 for an empty token list', () => {+ expect(countWildcardTokens([])).toBe(0);+ });++ it('returns 0 when every token has non-wildcard scopes', () => {+ expect(+ countWildcardTokens([+ makeToken({ id: 'a', scopes: [MONITORING_READ_SCOPE] }),+ makeToken({ id: 'b', scopes: [DOCKER_REPORT_SCOPE, SETTINGS_READ_SCOPE] }),+ ]),+ ).toBe(0);+ });++ it('counts a token whose scopes are undefined (treated as wildcard)', () => {+ expect(+ countWildcardTokens([+ makeToken({ id: 'a', scopes: [MONITORING_READ_SCOPE] }),+ makeToken({ id: 'b', scopes: undefined as unknown as string[] }),+ ]),+ ).toBe(1);+ });++ it('counts a token whose scopes are an empty array', () => {+ expect(+ countWildcardTokens([+ makeToken({ id: 'a', scopes: [] }),+ makeToken({ id: 'b', scopes: [AUDIT_READ_SCOPE] }),+ ]),+ ).toBe(1);+ });++ it('counts a token whose scopes explicitly include the wildcard', () => {+ expect(+ countWildcardTokens([+ makeToken({ id: 'a', scopes: [API_TOKEN_WILDCARD_SCOPE] }),+ makeToken({ id: 'b', scopes: [API_TOKEN_WILDCARD_SCOPE, MONITORING_READ_SCOPE] }),+ ]),+ ).toBe(2);+ });++ it('counts the correct total across a mixed list', () => {+ expect(+ countWildcardTokens([+ makeToken({ id: 'scoped', scopes: [MONITORING_READ_SCOPE] }),+ makeToken({ id: 'undef', scopes: undefined as unknown as string[] }),+ makeToken({ id: 'empty', scopes: [] }),+ makeToken({ id: 'wild', scopes: [API_TOKEN_WILDCARD_SCOPE] }),+ makeToken({ id: 'wild2', scopes: [SETTINGS_READ_SCOPE, API_TOKEN_WILDCARD_SCOPE] }),+ makeToken({ id: 'scoped2', scopes: [AUDIT_READ_SCOPE, SETTINGS_WRITE_SCOPE] }),+ ]),+ ).toBe(4);+ });+});++// ---- groupAPITokenScopes ----------------------------------------------------++describe('groupAPITokenScopes', () => {+ it('returns every populated group in the canonical display order', () => {+ const groups = groupAPITokenScopes();+ expect(groups.map(([group]) => group)).toStrictEqual([+ 'Monitoring',+ 'AI',+ 'Agents',+ 'Settings',+ 'Security',+ ]);+ });++ it('places every API_SCOPE_OPTIONS entry into exactly one group, preserving source order', () => {+ const groups = groupAPITokenScopes();+ const byGroup = new Map<string, APIScopeOption[]>();+ for (const [group, options] of groups) byGroup.set(group, options);++ // Each canonical option must appear exactly once, in the same relative+ // order it has inside API_SCOPE_OPTIONS.+ for (const [group, options] of groups) {+ const expected = API_SCOPE_OPTIONS.filter((option) => option.group === group);+ expect(options).toStrictEqual(expected);+ expect(byGroup.get(group)).toBe(options);+ }+ });++ it('drops no group, because every shipped group has at least one option', () => {+ // The `.filter(([, options]) => options.length > 0)` guard is a no-op for+ // the shipped catalog; assert all five groups survive.+ expect(groupAPITokenScopes()).toHaveLength(5);+ });++ it('routes specific known scopes to their expected groups', () => {+ const groups = groupAPITokenScopes();+ const valuesFor = (group: string) =>+ groups.find(([g]) => g === group)?.[1].map((o) => o.value);+ expect(valuesFor('Monitoring')).toStrictEqual([MONITORING_READ_SCOPE, 'monitoring:write']);+ expect(valuesFor('Security')).toStrictEqual([AUDIT_READ_SCOPE]);+ expect(valuesFor('Agents')).toContain(DOCKER_REPORT_SCOPE);+ expect(valuesFor('Agents')).toContain(DOCKER_MANAGE_SCOPE);+ expect(valuesFor('Agents')).toContain(AGENT_REPORT_SCOPE);+ expect(valuesFor('Settings')).toStrictEqual([SETTINGS_READ_SCOPE, SETTINGS_WRITE_SCOPE]);+ });+});++// ---- dockerActionIdForResource (remaining resolution arms) -----------------+//+// Sibling tests already cover the docker.hostSourceId arm and the final+// fallback to resource.id. These cases drive every OTHER arm of the underlying+// getActionableDockerRuntimeIdFromResource short-circuit chain.++describe('dockerActionIdForResource (uncovered arms)', () => {+ it('returns discoveryTarget.resourceId for an app-container discovery target (early return)', () => {+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ discoveryTarget: {+ resourceType: 'app-container',+ agentId: 'dt-agent',+ resourceId: 'container-abc',+ },+ }),+ ),+ ).toBe('container-abc');+ });++ it('skips the early return when discoveryTarget.resourceType is not app-container', () => {+ // 'agent' is not an app-container type, so the early-return guard fails and+ // resolution continues down the hostSourceId chain -> resource.id fallback.+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ discoveryTarget: {+ resourceType: 'agent',+ agentId: 'dt-agent',+ resourceId: 'would-be-skipped',+ },+ }),+ ),+ ).toBe('fallback-id');+ });++ it('resolves from platformData.hostSourceId when docker.hostSourceId is absent', () => {+ expect(+ dockerActionIdForResource(+ makeResource({ id: 'fallback-id', platformData: { hostSourceId: 'pd-host-1' } }),+ ),+ ).toBe('pd-host-1');+ });++ it('resolves from resource.identity.machineId for a docker-host', () => {+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ type: 'docker-host',+ identity: { machineId: 'machine-xyz' },+ }),+ ),+ ).toBe('machine-xyz');+ });++ it('falls back to platformData.machineId for a docker-host when identity.machineId is absent', () => {+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ type: 'docker-host',+ platformData: { machineId: 'pd-machine-1' },+ }),+ ),+ ).toBe('pd-machine-1');+ });++ it('resolves from metricsTarget.resourceId for a docker-host when no machine id exists', () => {+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ type: 'docker-host',+ metricsTarget: { resourceType: 'docker-host', resourceId: 'metrics-rt-1' },+ }),+ ),+ ).toBe('metrics-rt-1');+ });++ it('skips the metricsTarget arm when metricsTarget.resourceType is not docker-host', () => {+ // metricsTarget points at an agent, so the resourceType guard fails and the+ // final docker-host discoveryTarget.agentId arm fires instead.+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ type: 'docker-host',+ metricsTarget: { resourceType: 'agent', resourceId: 'would-be-skipped' },+ discoveryTarget: { resourceType: 'agent', agentId: 'dt-agent-9', resourceId: 'dt-res' },+ }),+ ),+ ).toBe('dt-agent-9');+ });++ it('resolves from discoveryTarget.agentId for a docker-host (final arm)', () => {+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ type: 'docker-host',+ discoveryTarget: { resourceType: 'agent', agentId: 'dt-agent-9', resourceId: 'dt-res' },+ }),+ ),+ ).toBe('dt-agent-9');+ });++ it('fires the metricsTarget arm even for a non-docker-host type (only metricsTarget.resourceType is gated)', () => {+ // The metricsTarget ternary keys off metricsTarget.resourceType, NOT+ // resource.type, so a vm that reports a docker-host metrics target still+ // resolves to that metricsTarget.resourceId.+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ type: 'vm',+ metricsTarget: { resourceType: 'docker-host', resourceId: 'metrics-rt-9' },+ }),+ ),+ ).toBe('metrics-rt-9');+ });++ it('does not consult the docker-host-gated arms (machineId / discoveryTarget.agentId) for a non-docker-host type', () => {+ // Both identity.machineId and discoveryTarget.agentId ternaries short-circuit+ // to undefined when resource.type !== 'docker-host', so with no hostSourceId+ // and no docker-host metricsTarget the result is resource.id.+ expect(+ dockerActionIdForResource(+ makeResource({+ id: 'fallback-id',+ type: 'vm',+ identity: { machineId: 'would-be-skipped' },+ discoveryTarget: { resourceType: 'agent', agentId: 'also-skipped', resourceId: 'r' },+ }),+ ),+ ).toBe('fallback-id');+ });+});++// ---- getAPITokenScopePresets (structural verification) ---------------------+//+// Sibling tests only assert preset COUNT and the Pulse-Intelligence gating.+// These cases verify the full id/label/scopes/description contract of every+// shipped preset and the exact ordering, including the Pulse preset insertion.++describe('getAPITokenScopePresets (full structure)', () => {+ it('returns the seven base presets in canonical order with no pulse scopes', () => {+ const presets = getAPITokenScopePresets();+ expect(presets.map((p) => p.id)).toStrictEqual([+ API_TOKEN_KIOSK_PRESET_ID,+ API_TOKEN_AGENT_PRESET_ID,+ API_TOKEN_DOCKER_REPORT_PRESET_ID,+ API_TOKEN_DOCKER_MANAGE_PRESET_ID,+ API_TOKEN_SETTINGS_READ_PRESET_ID,+ API_TOKEN_SETTINGS_ADMIN_PRESET_ID,+ API_TOKEN_AUDIT_READ_PRESET_ID,+ ]);++ const byId = new Map(presets.map((p) => [p.id, p]));++ expect(byId.get(API_TOKEN_KIOSK_PRESET_ID)).toStrictEqual({+ id: API_TOKEN_KIOSK_PRESET_ID,+ label: 'Kiosk / Monitoring',+ scopes: [MONITORING_READ_SCOPE],+ description:+ 'Read-only access for wall displays. Use ?token=xxx&kiosk=1 in the URL to hide navigation and filters.',+ });+ expect(byId.get(API_TOKEN_AGENT_PRESET_ID)?.scopes).toStrictEqual([AGENT_REPORT_SCOPE]);+ expect(byId.get(API_TOKEN_DOCKER_REPORT_PRESET_ID)).toStrictEqual({+ id: API_TOKEN_DOCKER_REPORT_PRESET_ID,+ label: API_TOKEN_DOCKER_REPORT_PRESET_LABEL,+ scopes: [DOCKER_REPORT_SCOPE],+ description: API_TOKEN_DOCKER_REPORT_PRESET_DESCRIPTION,+ });+ expect(byId.get(API_TOKEN_DOCKER_MANAGE_PRESET_ID)).toStrictEqual({+ id: API_TOKEN_DOCKER_MANAGE_PRESET_ID,+ label: API_TOKEN_DOCKER_MANAGE_PRESET_LABEL,+ scopes: [DOCKER_REPORT_SCOPE, DOCKER_MANAGE_SCOPE],+ description: API_TOKEN_DOCKER_MANAGE_PRESET_DESCRIPTION,+ });+ expect(byId.get(API_TOKEN_SETTINGS_READ_PRESET_ID)?.scopes).toStrictEqual([+ SETTINGS_READ_SCOPE,+ ]);+ expect(byId.get(API_TOKEN_SETTINGS_ADMIN_PRESET_ID)?.scopes).toStrictEqual([+ SETTINGS_READ_SCOPE,+ SETTINGS_WRITE_SCOPE,+ ]);+ expect(byId.get(API_TOKEN_AUDIT_READ_PRESET_ID)?.scopes).toStrictEqual([AUDIT_READ_SCOPE]);+ });++ it('inserts the Pulse Intelligence preset at index 1 when required scopes are provided', () => {+ const presets = getAPITokenScopePresets(['monitoring:read', 'ai:execute']);+ expect(presets).toHaveLength(8);+ expect(presets[1]).toStrictEqual({+ id: API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID,+ label: API_TOKEN_PATROL_EXTERNAL_AGENT_PRESET_LABEL,+ scopes: ['monitoring:read', 'ai:execute'],+ description:+ 'Scopes for connected agents that read Pulse context and request Patrol work.',+ });+ // Base presets still follow in canonical order after the inserted preset.+ expect(presets.map((p) => p.id)).toStrictEqual([+ API_TOKEN_KIOSK_PRESET_ID,+ API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID,+ API_TOKEN_AGENT_PRESET_ID,+ API_TOKEN_DOCKER_REPORT_PRESET_ID,+ API_TOKEN_DOCKER_MANAGE_PRESET_ID,+ API_TOKEN_SETTINGS_READ_PRESET_ID,+ API_TOKEN_SETTINGS_ADMIN_PRESET_ID,+ API_TOKEN_AUDIT_READ_PRESET_ID,+ ]);+ });++ it('every preset exposes a non-empty id, label, and description', () => {+ const presets = getAPITokenScopePresets(['agent:report']);+ for (const preset of presets) {+ expect(preset.id.length).toBeGreaterThan(0);+ expect(preset.label.length).toBeGreaterThan(0);+ expect(preset.description.length).toBeGreaterThan(0);+ expect(Array.isArray(preset.scopes)).toBe(true);+ expect(preset.scopes.length).toBeGreaterThan(0);+ }+ });+});++// ---- buildDockerTokenUsage / buildAgentTokenUsage (multi-key accumulation) --+//+// Sibling tests only ever drive a single tokenId. These cases prove the map+// accumulates independent entries across DISTINCT tokenIds (the second+// appendUsageEntry "first entry for this key" arm exercised for a new key).++describe('buildDockerTokenUsage (multi-key accumulation)', () => {+ it('records separate entries for resources bound to different tokenIds', () => {+ 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: 't2' } },+ });+ expect(buildDockerTokenUsage([a, b])).toStrictEqual(+ new Map([+ ['t1', { count: 1, items: [{ id: 'rt-1', label: 'Docker One' }] }],+ ['t2', { count: 1, items: [{ id: 'rt-2', label: 'Docker Two' }] }],+ ]),+ );+ });+});++describe('buildAgentTokenUsage (multi-key accumulation)', () => {+ it('records separate entries for agent resources bound to different tokenIds', () => {+ 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: 't2' } },+ });+ expect(buildAgentTokenUsage([a, b])).toStrictEqual(+ new Map([+ ['t1', { count: 1, items: [{ id: 'a1', label: 'Agent One' }] }],+ ['t2', { count: 1, items: [{ id: 'a2', label: 'Agent Two' }] }],+ ]),+ );+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/reportingInventoryExportModel.branchcov0713.test.ts b/frontend-modern/src/components/Settings/__tests__/reportingInventoryExportModel.branchcov0713.test.tsnew file mode 100644index 0000000000..3da4e94461--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/reportingInventoryExportModel.branchcov0713.test.ts@@ -0,0 +1,190 @@+/**+ * Branch-coverage tests for the still-uncovered branches of+ * `parseVMInventoryExportDefinition` in reportingInventoryExportModel.+ *+ * The sibling `reportingInventoryExportModel.test.ts` already exercises the+ * happy-path parse and the empty-columns (`columns.length === 0`) arm. This+ * file targets every other guard: the top-level non-object rejection, each+ * field-level typeof / literal / Array.isArray arm in the big validation OR+ * chain, and each per-column guard inside the `.map` (null / primitive /+ * bad key / bad label / bad description), plus a multi-column round-trip to+ * drive the map's iteration arm with more than one element.+ *+ * Import path mirrors the sibling test (relative `../reportingInventoryExportModel`).+ */+import { describe, expect, it } from 'vitest';+import { parseVMInventoryExportDefinition } from '../reportingInventoryExportModel';++const INVALID = 'Invalid VM inventory export definition payload';+const expectInvalid = (input: unknown) =>+ expect(() => parseVMInventoryExportDefinition(input)).toThrow(INVALID);++// ---- Fixtures ---------------------------------------------------------------+// Plain (non-`as const`) builders so each test can spread + override a single+// field to drive exactly one branch under test. The parser's input is typed+// `unknown`, so malformed overrides need no cast.++const baseColumn = () => ({+ key: 'pool',+ label: 'Pool',+ description: 'Canonical Proxmox pool membership.',+});++const baseDefinition = () => ({+ id: 'vm_inventory',+ title: 'VM Inventory Export',+ description: 'Current-state VM inventory',+ format: 'csv',+ exportEndpoint: '/api/admin/reports/inventory/vms/export',+ filenamePrefix: 'vm-inventory',+ filenameDateStyle: 'utc_yyyymmdd',+ columns: [baseColumn()],+});++// ---- Top-level non-object guard --------------------------------------------++describe('parseVMInventoryExportDefinition — top-level input guard', () => {+ it('throws on a falsy input (null / undefined / empty-string / 0 / false)', () => {+ expectInvalid(null);+ expectInvalid(undefined);+ expectInvalid('');+ expectInvalid(0);+ expectInvalid(false);+ });++ it('throws on a truthy non-object primitive (string / number / boolean)', () => {+ expectInvalid('not-an-object');+ expectInvalid(42);+ expectInvalid(true);+ });+});++// ---- Field-level validation OR chain ---------------------------------------++describe('parseVMInventoryExportDefinition — field validation guards', () => {+ it('throws when id is not a string', () => {+ expectInvalid({ ...baseDefinition(), id: 123 });+ });++ it('throws when title is not a string', () => {+ expectInvalid({ ...baseDefinition(), title: null });+ });++ it('throws when description is not a string', () => {+ expectInvalid({ ...baseDefinition(), description: 7 });+ });++ it('throws when format is not exactly "csv" (wrong string and non-string arms)', () => {+ expectInvalid({ ...baseDefinition(), format: 'xlsx' });+ expectInvalid({ ...baseDefinition(), format: undefined });+ expectInvalid({ ...baseDefinition(), format: 1 });+ });++ it('throws when exportEndpoint is not a string', () => {+ expectInvalid({ ...baseDefinition(), exportEndpoint: null });+ });++ it('throws when filenamePrefix is not a string', () => {+ expectInvalid({ ...baseDefinition(), filenamePrefix: 5 });+ });++ it('throws when filenameDateStyle is not exactly "utc_yyyymmdd"', () => {+ expectInvalid({ ...baseDefinition(), filenameDateStyle: 'local_yyyy_mm_dd' });+ expectInvalid({ ...baseDefinition(), filenameDateStyle: undefined });+ });++ it('throws when columns is not an array (null and non-array arms)', () => {+ expectInvalid({ ...baseDefinition(), columns: null });+ expectInvalid({ ...baseDefinition(), columns: 'not-an-array' });+ expectInvalid({ ...baseDefinition(), columns: { length: 1 } });+ });+});++// ---- Per-column guards inside .map -----------------------------------------++describe('parseVMInventoryExportDefinition — per-column guards', () => {+ it('throws when a column entry is null (falsy arm)', () => {+ expectInvalid({ ...baseDefinition(), columns: [null] });+ });++ it('throws when a column entry is a primitive (typeof !== "object" arm)', () => {+ expectInvalid({ ...baseDefinition(), columns: ['not-an-object'] });+ expectInvalid({ ...baseDefinition(), columns: [42] });+ });++ it('throws when a column key is not a string', () => {+ expectInvalid({+ ...baseDefinition(),+ columns: [{ ...baseColumn(), key: 5 }],+ });+ });++ it('throws when a column label is not a string', () => {+ expectInvalid({+ ...baseDefinition(),+ columns: [{ ...baseColumn(), label: null }],+ });+ });++ it('throws when a column description is not a string', () => {+ expectInvalid({+ ...baseDefinition(),+ columns: [{ ...baseColumn(), description: true }],+ });+ });++ it('rejects the payload on the first bad column even when later columns are valid', () => {+ expectInvalid({+ ...baseDefinition(),+ columns: [null, baseColumn()],+ });+ });+});++// ---- Happy-path round-trip (multi-column map iteration) ---------------------++describe('parseVMInventoryExportDefinition — happy path', () => {+ it('round-trips a multi-column payload unchanged and hardcodes format "csv"', () => {+ const input = {+ ...baseDefinition(),+ columns: [+ { key: 'pool', label: 'Pool', description: 'Canonical Proxmox pool membership.' },+ { key: 'node', label: 'Node', description: 'Hosting Proxmox node.' },+ { key: 'status', label: 'Status', description: 'Current power state.' },+ ],+ };+ const parsed = parseVMInventoryExportDefinition(input);+ expect(parsed).toStrictEqual({+ id: 'vm_inventory',+ title: 'VM Inventory Export',+ description: 'Current-state VM inventory',+ format: 'csv',+ exportEndpoint: '/api/admin/reports/inventory/vms/export',+ filenamePrefix: 'vm-inventory',+ filenameDateStyle: 'utc_yyyymmdd',+ columns: [+ { key: 'pool', label: 'Pool', description: 'Canonical Proxmox pool membership.' },+ { key: 'node', label: 'Node', description: 'Hosting Proxmox node.' },+ { key: 'status', label: 'Status', description: 'Current power state.' },+ ],+ });+ });++ it('preserves empty-string text fields verbatim (string-typed but empty)', () => {+ const parsed = parseVMInventoryExportDefinition({+ ...baseDefinition(),+ id: '',+ title: '',+ description: '',+ exportEndpoint: '',+ filenamePrefix: '',+ columns: [{ key: '', label: '', description: '' }],+ });+ expect(parsed.id).toBe('');+ expect(parsed.title).toBe('');+ expect(parsed.description).toBe('');+ expect(parsed.exportEndpoint).toBe('');+ expect(parsed.filenamePrefix).toBe('');+ expect(parsed.columns[0]).toEqual({ key: '', label: '', description: '' });+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/settingsFeatureGates.branchcov0713.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsFeatureGates.branchcov0713.test.tsnew file mode 100644index 0000000000..e6e1c955f0--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/settingsFeatureGates.branchcov0713.test.ts@@ -0,0 +1,274 @@+/**+ * Branch-coverage tests for the still-uncovered surface of settingsFeatureGates:+ * - isFeatureLocked (exercised DIRECTLY; the sibling branchcov0712c suite only+ * reaches it indirectly through isTabLocked)+ * - getTabLockReason (not covered by any sibling test)+ * - isTabLocked (only the predicate short-circuit / invocation-ordering+ * aspect, which branchcov0712c does not assert; the return-+ * value matrix over every tab is already pinned there and+ * is intentionally NOT duplicated here)+ *+ * Every guard arm, the `every()` true/false outcomes, guard ORDERING (runtime+ * before features), and the exact tier-specific reason strings are pinned with+ * concrete inputs and assertions. No tautologies: reason strings are checked+ * against a hand-written per-tab snapshot, not by re-calling the helper.+ */+import { describe, expect, it } from 'vitest';++import type { SettingsTab } from '../settingsNavigationModel';+import { getTabLockReason, isFeatureLocked, isTabLocked, tabFeatureRequirements } from '../settingsFeatureGates';++// ---- Helpers ---------------------------------------------------------------+// Mirrors the `hasFeatures` factory used by the sibling branchcov0712c test so+// the invocation pattern and predicate semantics stay consistent across suites.++const hasFeatures =+ (features: string[]) =>+ (feature: string): boolean =>+ features.includes(feature);++// The complete set of tabs that carry feature requirements in+// `tabFeatureRequirements`. Driving every entry guarantees the+// `tabFeatureRequirements[tab]` lookup -> defined-array arm is exercised for+// each key, not just a representative sample.+const allGatedTabs = Object.entries(tabFeatureRequirements) as Array<+ [SettingsTab, string[]]+>;++/**+ * Wraps `hasFeatures` with a call-sink so tests can assert guard ORDERING —+ * specifically that `hasFeature` is NOT invoked once an earlier guard+ * (empty/unloaded tab) has already resolved the result. This is the branch+ * behavior the sibling suite does not check.+ */+const trackingHas =+ (granted: string[], sink: { calls: string[] }) =>+ (feature: string): boolean => {+ sink.calls.push(feature);+ return granted.includes(feature);+ };++// Hand-written snapshot of the exact reason string each gated tab must emit+// when its required feature is missing. Derived from reading+// `getFeatureMinTierLabel` (relay -> 'Relay', multi_tenant -> 'MSP',+// audit_logging -> 'Pro' fallback); NOT computed by calling the helper, so a+// change to either the tier map or the message template fails this loudly.+const EXPECTED_LOCK_REASON: Partial<Record<SettingsTab, string>> = {+ 'system-relay': 'This settings section requires Relay.',+ 'security-webhooks': 'This settings section requires Pro.',+ 'organization-overview': 'This settings section requires MSP.',+ 'organization-access': 'This settings section requires MSP.',+ 'organization-sharing': 'This settings section requires MSP.',+ 'organization-billing': 'This settings section requires MSP.',+ 'organization-billing-admin': 'This settings section requires MSP.',+};++// ---- isFeatureLocked (direct) ---------------------------------------------+// `isFeatureLocked` is the shared engine behind `isTabLocked`. The sibling+// suite only reaches it indirectly, so its three guards and the `every()`+// true/false outcomes are pinned here by calling it directly.++describe('isFeatureLocked - direct branch coverage', () => {+ // Guard 1, `!features` arm: `features` is `undefined`.+ it('returns false when features is undefined (first guard: !features)', () => {+ expect(isFeatureLocked(undefined, () => false, () => true)).toBe(false);+ });++ // Guard 1, `!features` arm: deliberately-malformed `null` input violates the+ // declared `string[] | undefined` type; cast through `unknown` to keep strict+ // mode clean. `!null` is true so the function must short-circuit to false.+ it('returns false when features is null (cast; !features covers nullish)', () => {+ const features = null as unknown as Parameters<typeof isFeatureLocked>[0];+ expect(isFeatureLocked(features, () => false, () => true)).toBe(false);+ });++ // Guard 1, `features.length === 0` arm.+ it('returns false when features is an empty array (length === 0 arm)', () => {+ expect(isFeatureLocked([], () => false, () => true)).toBe(false);+ });++ // Guard 2, `!runtimeCapabilitiesLoaded()` arm: populated features but the+ // license/capability state has not resolved yet -> must not lock.+ it('returns false when features are present but runtime is not loaded', () => {+ expect(isFeatureLocked(['relay'], () => false, () => false)).toBe(false);+ });++ // Guard 3, `every()` -> true arm: `!true === false` (unlocked).+ it('returns false when every required feature is held and runtime is loaded', () => {+ expect(+ isFeatureLocked(['relay', 'multi_tenant'], hasFeatures(['relay', 'multi_tenant']), () => true),+ ).toBe(false);+ });++ // Guard 3, `every()` -> false arm: `!false === true` (LOCKED). This is the+ // only branch that returns true.+ it('returns true when the first required feature is missing (every -> false)', () => {+ expect(isFeatureLocked(['relay', 'multi_tenant'], hasFeatures(['multi_tenant']), () => true)).toBe(+ true,+ );+ });++ it('returns true when only the first of several required features is held', () => {+ // every() -> false on a later element.+ expect(+ isFeatureLocked(+ ['relay', 'multi_tenant', 'audit_logging'],+ hasFeatures(['relay']),+ () => true,+ ),+ ).toBe(true);+ });++ it('returns true when a later required feature is missing while earlier ones are held', () => {+ // Pins that every() is not satisfied by a proper prefix.+ expect(+ isFeatureLocked(+ ['relay', 'multi_tenant', 'audit_logging'],+ hasFeatures(['relay', 'multi_tenant']),+ () => true,+ ),+ ).toBe(true);+ });++ // ---- short-circuit / guard ORDERING --------------------------------------+ it('does not invoke hasFeature when features is empty', () => {+ const sink = { calls: [] as string[] };+ isFeatureLocked([], trackingHas([], sink), () => true);+ expect(sink.calls).toEqual([]);+ });++ it('does not invoke hasFeature when runtime capabilities are unloaded (runtime guard before feature check)', () => {+ const sink = { calls: [] as string[] };+ const result = isFeatureLocked(['relay'], trackingHas(['relay'], sink), () => false);+ expect(result).toBe(false);+ expect(sink.calls).toEqual([]);+ });++ it('invokes hasFeature exactly once per required feature when runtime is loaded and all are held', () => {+ const sink = { calls: [] as string[] };+ isFeatureLocked(['a', 'b', 'c'], trackingHas(['a', 'b', 'c'], sink), () => true);+ expect(sink.calls).toEqual(['a', 'b', 'c']);+ });+});++// ---- isTabLocked - complementary short-circuit coverage --------------------+// branchcov0712c already pins the full (tab x feature x runtime) return-value+// matrix. This block adds the one aspect it does not assert: that `hasFeature`+// is bypassed entirely once an earlier guard resolves the result.++describe('isTabLocked - predicate short-circuit (complements branchcov0712c)', () => {+ it('does not invoke hasFeature for a non-gated tab (undefined lookup short-circuits before the feature check)', () => {+ const sink = { calls: [] as string[] };+ const result = isTabLocked('api', trackingHas([], sink), () => true);+ expect(result).toBe(false);+ expect(sink.calls).toEqual([]);+ });++ it('does not invoke hasFeature for a gated tab while runtime capabilities are unloaded', () => {+ const sink = { calls: [] as string[] };+ const result = isTabLocked('system-relay', trackingHas(['relay'], sink), () => false);+ expect(result).toBe(false);+ expect(sink.calls).toEqual([]);+ });++ it('invokes hasFeature for a gated tab exactly once its single required feature is reached (runtime loaded)', () => {+ const sink = { calls: [] as string[] };+ isTabLocked('system-relay', trackingHas(['relay'], sink), () => true);+ expect(sink.calls).toEqual(['relay']);+ });+});++// ---- getTabLockReason ------------------------------------------------------+// Not covered by any sibling test. Pins every guard, the `every()` unlocked+// arm, and the exact tier-specific reason string for the locked arm.++describe('getTabLockReason - branch coverage', () => {+ // Guard 1: tab NOT present in tabFeatureRequirements -> `undefined` -> null.+ it.each(+ [+ 'infrastructure-systems',+ 'system-general',+ 'system-network',+ 'api',+ 'support-diagnostics',+ 'security-overview',+ 'security-audit',+ ] as SettingsTab[],+ )('returns null for non-gated tab %s (lookup -> undefined)', (tab) => {+ expect(getTabLockReason(tab, hasFeatures([]), () => true)).toBeNull();+ });++ // Guard 1 via a deliberately-cast out-of-map id (no throw, concrete null).+ it('returns null for a cast tab id absent from tabFeatureRequirements', () => {+ const unknownTab = 'totally-not-a-real-tab' as unknown as SettingsTab;+ expect(getTabLockReason(unknownTab, hasFeatures([]), () => true)).toBeNull();+ });++ // Guard 2: `!runtimeCapabilitiesLoaded()` -> null for every gated tab.+ it.each(allGatedTabs)(+ 'returns null for gated tab %s while runtime capabilities are unloaded',+ (tab) => {+ expect(getTabLockReason(tab, hasFeatures([]), () => false)).toBeNull();+ },+ );++ // Guard 3: `requiredFeatures.every(hasFeature)` -> true -> null (unlocked).+ it.each(allGatedTabs)(+ 'returns null for gated tab %s when every required feature is held',+ (tab, required) => {+ expect(getTabLockReason(tab, hasFeatures(required), () => true)).toBeNull();+ },+ );++ // Locked arm: emits the tier-specific reason string. The expected snapshot is+ // hand-written (see EXPECTED_LOCK_REASON) so this fails if either the tier+ // label mapping or the message template drifts.+ it.each(allGatedTabs)(+ 'emits the exact tier-specific reason for %s when its required feature is missing',+ (tab) => {+ expect(getTabLockReason(tab, hasFeatures([]), () => true)).toBe(EXPECTED_LOCK_REASON[tab]);+ },+ );++ // ---- short-circuit / guard ORDERING --------------------------------------+ it('does not invoke hasFeature for a non-gated tab', () => {+ const sink = { calls: [] as string[] };+ getTabLockReason('api', trackingHas([], sink), () => true);+ expect(sink.calls).toEqual([]);+ });++ it('does not invoke hasFeature for a gated tab while runtime is unloaded (runtime guard before feature check)', () => {+ const sink = { calls: [] as string[] };+ getTabLockReason('system-relay', trackingHas([], sink), () => false);+ expect(sink.calls).toEqual([]);+ });++ it('invokes hasFeature exactly once for a single-requirement gated tab when runtime is loaded and the feature is held', () => {+ const sink = { calls: [] as string[] };+ getTabLockReason('system-relay', trackingHas(['relay'], sink), () => true);+ expect(sink.calls).toEqual(['relay']);+ });+});++// ---- cross-function consistency --------------------------------------------+// Pins that `getTabLockReason` and `isTabLocked` agree on every gated tab and+// every (runtime x feature) combination: a reason exists iff the tab is locked.++describe('getTabLockReason agrees with isTabLocked for every gated tab', () => {+ it.each(allGatedTabs)(+ '%s: reason is non-null iff isTabLocked is true across loaded/held x loaded/missing x unloaded',+ (tab, required) => {+ // loaded + missing -> LOCKED, reason present.+ expect(isTabLocked(tab, hasFeatures([]), () => true)).toBe(true);+ expect(getTabLockReason(tab, hasFeatures([]), () => true)).not.toBeNull();++ // loaded + held -> UNLOCKED, no reason.+ expect(isTabLocked(tab, hasFeatures(required), () => true)).toBe(false);+ expect(getTabLockReason(tab, hasFeatures(required), () => true)).toBeNull();++ // unloaded -> UNLOCKED regardless of features, no reason.+ expect(isTabLocked(tab, hasFeatures([]), () => false)).toBe(false);+ expect(getTabLockReason(tab, hasFeatures([]), () => false)).toBeNull();+ },+ );+});diff --git a/frontend-modern/src/components/Settings/__tests__/settingsNavVisibility.branchcov0713.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsNavVisibility.branchcov0713.test.tsnew file mode 100644index 0000000000..a77cfb29ca--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/settingsNavVisibility.branchcov0713.test.ts@@ -0,0 +1,264 @@+import { describe, expect, it, vi } from 'vitest';+import type { SettingsNavItem, SettingsTab } from '../settingsNavigationModel';+import {+ isSettingsNavItemLocked,+ shouldBlockSettingsRouteItem,+ shouldHideSettingsNavItem,+ type SettingsNavVisibilityContext,+} from '../settingsNavVisibility';++// Branch-coverage complement to `settingsNavVisibility.branchcov2.test.ts`.+// That sibling file already covers every branch that is reachable through REAL+// catalog items for `shouldHideSettingsNavItem` and `isSettingsNavItemLocked`,+// plus the hostedOnly / commercial-hidden-hidden / demo-unresolved /+// requiredCapability / hideWhenUnavailable arms of `shouldBlockSettingsRouteItem`.+//+// This file targets ONLY the branches the sibling file leaves open:+// 1. `shouldBlockSettingsRouteItem` real-catalog arms that the sibling skipped:+// - hideWhenOrganizationHidden {unresolved, hidesOrganizations} (L127-133)+// - hideWhenCommercialHidden {unresolved} (L137-139)+// - hideWhenDemoMode {isDemoMode} (L151-153)+// - requiredCapability {resolved + missing} (L168-172)+// 2. The `hideWhenReadOnly` gate (L87-95 in shouldHide, L156-164 in shouldBlock)+// which NO real catalog item declares, so it is only reachable by injecting+// a synthetic item shape through the real catalog module the target imports.+// 3. The `return isTabLocked(...)` -> true outcome of `isSettingsNavItemLocked`+// (unreachable for real items because every feature-gated catalog item also+// sets hideWhenUnavailable, short-circuiting at L193).++// Synthetic tab ids. No real SettingsTab literal matches these; cast at the+// type boundary so strict TS stays clean (matches the sibling file's+// UNKNOWN_TAB convention: `'<x>' as unknown as SettingsTab`).+const { READONLY_TAB, LOCKED_TAB } = vi.hoisted(() => ({+ READONLY_TAB: '__branchcov0713_readonly__' as unknown as SettingsTab,+ LOCKED_TAB: '__branchcov0713_locked__' as unknown as SettingsTab,+}));++// Inject synthetic item shapes by wrapping the REAL catalog module the target+// imports. Real tabs delegate to the real implementation unchanged, so every+// real-catalog assertion below exercises the genuine production lookup; only+// the two synthetic ids are overlaid with the gate shape under test.+vi.mock('../settingsNavCatalog', async (importActual) => {+ const actual = await importActual<typeof import('../settingsNavCatalog')>();+ return {+ ...actual,+ getSettingsNavItem: (+ tab: Parameters<typeof actual.getSettingsNavItem>[0],+ locale?: Parameters<typeof actual.getSettingsNavItem>[1],+ ): SettingsNavItem | undefined => {+ if (tab === READONLY_TAB || tab === LOCKED_TAB) {+ // Clone a fully-shaped real item that carries no other visibility+ // gates (system-general) and overlay the synthetic id (+ the gate+ // under test). Cloning a real item keeps the full SettingsNavItem+ // shape (icon/label/etc.) without fabricating any field.+ const base = actual.getSettingsNavItem('system-general', locale);+ if (!base) return undefined;+ if (tab === READONLY_TAB) return { ...base, id: tab, hideWhenReadOnly: true };+ return { ...base, id: tab };+ }+ return actual.getSettingsNavItem(tab, locale);+ },+ };+});++// `isSettingsNavItemLocked` calls `isTabLocked` from the real feature-gates+// module. Real tabs never reach the `return isTabLocked(...)` -> true outcome+// (every feature-gated tab also sets hideWhenUnavailable). For LOCKED_TAB only+// we force isTabLocked -> true so that outcome is exercised; every other tab+// delegates to the real implementation.+vi.mock('../settingsFeatureGates', async (importActual) => {+ const actual = await importActual<typeof import('../settingsFeatureGates')>();+ return {+ ...actual,+ isTabLocked: (+ tab: Parameters<typeof actual.isTabLocked>[0],+ hasFeature: Parameters<typeof actual.isTabLocked>[1],+ runtimeCapabilitiesLoaded: Parameters<typeof actual.isTabLocked>[2],+ ): boolean =>+ tab === LOCKED_TAB+ ? true+ : actual.isTabLocked(tab, hasFeature, runtimeCapabilitiesLoaded),+ };+});++// ---- Helpers ---------------------------------------------------------------+// Mirrors the sibling file's `hasFeatures` + `createContext` factories so each+// case only overrides the branch-relevant context field.++const hasFeatures =+ (features: string[]) =>+ (feature: string): boolean =>+ features.includes(feature);++const createContext = (+ overrides: Partial<SettingsNavVisibilityContext> = {},+): SettingsNavVisibilityContext => ({+ hasFeature: hasFeatures([]),+ runtimeCapabilitiesLoaded: () => true,+ hostedModeEnabled: false,+ ...overrides,+});++// ---- shouldHideSettingsNavItem: hideWhenReadOnly gate (L87-95) -------------+// No real catalog item sets `hideWhenReadOnly`; this gate is reachable only via+// the synthetic READONLY_TAB injected above.++describe('shouldHideSettingsNavItem - hideWhenReadOnly gate (L87-95)', () => {+ it('hides a read-only-gated item while presentation policy is unresolved', () => {+ expect(+ shouldHideSettingsNavItem(READONLY_TAB, createContext({ presentationPolicyResolved: false })),+ ).toBe(true);+ });++ it('hides a read-only-gated item when read-only presentation policy is active', () => {+ expect(+ shouldHideSettingsNavItem(+ READONLY_TAB,+ createContext({ presentationPolicyResolved: true, presentationPolicyIsReadOnly: true }),+ ),+ ).toBe(true);+ });++ it('falls through the read-only gate when policy is resolved and not read-only', () => {+ // Resolved + not read-only -> neither inner arm fires -> execution falls+ // past the gate, and with no other gates on the item the final `return+ // false` is reached.+ expect(+ shouldHideSettingsNavItem(+ READONLY_TAB,+ createContext({ presentationPolicyResolved: true, presentationPolicyIsReadOnly: false }),+ ),+ ).toBe(false);+ });+});++// ---- shouldBlockSettingsRouteItem ------------------------------------------+// Real-catalog arms the sibling file did not exercise, then the synthetic+// hideWhenReadOnly gate.++describe('shouldBlockSettingsRouteItem - hideWhenOrganizationHidden gate (L126-134)', () => {+ it('blocks an org-hidden route while presentation policy is unresolved', () => {+ expect(+ shouldBlockSettingsRouteItem(+ 'organization-overview',+ createContext({ presentationPolicyResolved: false }),+ ),+ ).toBe(true);+ });++ it('blocks an org-hidden route when organizations are hidden by presentation policy', () => {+ expect(+ shouldBlockSettingsRouteItem(+ 'organization-overview',+ createContext({+ presentationPolicyResolved: true,+ presentationPolicyHidesOrganizations: true,+ }),+ ),+ ).toBe(true);+ });+});++describe('shouldBlockSettingsRouteItem - hideWhenCommercialHidden unresolved arm (L136-139)', () => {+ it('blocks a commercial-hidden route while presentation policy is unresolved', () => {+ // system-billing carries only hideWhenCommercialHidden, so an unresolved+ // policy engages this gate before any feature/capability gate is consulted.+ expect(+ shouldBlockSettingsRouteItem('system-billing', createContext({ presentationPolicyResolved: false })),+ ).toBe(true);+ });+});++describe('shouldBlockSettingsRouteItem - hideWhenDemoMode isDemoMode arm (L146-153)', () => {+ it('blocks a demo-hidden route when demo mode is active', () => {+ // The sibling file only covered the unresolved arm for routing; this drives+ // the `presentationPolicyIsDemoMode` inner arm.+ expect(+ shouldBlockSettingsRouteItem(+ 'support-diagnostics',+ createContext({ presentationPolicyResolved: true, presentationPolicyIsDemoMode: true }),+ ),+ ).toBe(true);+ });+});++describe('shouldBlockSettingsRouteItem - requiredCapability resolved+missing (L166-172)', () => {+ it('blocks a capability-gated route when resolved and the capability is false', () => {+ expect(+ shouldBlockSettingsRouteItem(+ 'api',+ createContext({+ settingsCapabilitiesResolved: true,+ settingsCapabilities: { apiAccessRead: false },+ }),+ ),+ ).toBe(true);+ });++ it('blocks a capability-gated route when resolved but capabilities object is undefined', () => {+ // Optional-chain: context.settingsCapabilities?.[cap] -> undefined ->+ // undefined !== true -> block.+ expect(+ shouldBlockSettingsRouteItem(+ 'api',+ createContext({ settingsCapabilitiesResolved: true, settingsCapabilities: undefined }),+ ),+ ).toBe(true);+ });+});++describe('shouldBlockSettingsRouteItem - hideWhenReadOnly gate (L156-164)', () => {+ it('blocks a read-only-gated route while presentation policy is unresolved', () => {+ expect(+ shouldBlockSettingsRouteItem(+ READONLY_TAB,+ createContext({ presentationPolicyResolved: false }),+ ),+ ).toBe(true);+ });++ it('blocks a read-only-gated route when read-only presentation policy is active', () => {+ expect(+ shouldBlockSettingsRouteItem(+ READONLY_TAB,+ createContext({ presentationPolicyResolved: true, presentationPolicyIsReadOnly: true }),+ ),+ ).toBe(true);+ });++ it('does not block a read-only-gated route when resolved and not read-only', () => {+ expect(+ shouldBlockSettingsRouteItem(+ READONLY_TAB,+ createContext({ presentationPolicyResolved: true, presentationPolicyIsReadOnly: false }),+ ),+ ).toBe(false);+ });+});++// ---- isSettingsNavItemLocked ----------------------------------------------+// branchcov2 already covers every reachable branch (unknown tab, hideWhenUnavailable+// early return, no-features fall-through, runtime-capabilities-not-loaded). The+// only remaining outcome is `return isTabLocked(...)` -> true, which is+// unreachable for real catalog items. LOCKED_TAB supplies a non-hideWhenUnavailable+// item while the mocked isTabLocked forces the true result.++describe('isSettingsNavItemLocked - isTabLocked true outcome (L196)', () => {+ it('reports a non-hideWhenUnavailable tab as locked when isTabLocked returns true', () => {+ expect(+ isSettingsNavItemLocked(LOCKED_TAB, createContext({ hasFeature: hasFeatures([]) })),+ ).toBe(true);+ });++ it('does not lock when runtime capabilities are not loaded (isTabLocked short-circuits to false)', () => {+ // Contrast case: real delegation path. LOCKED_TAB forces isTabLocked -> true,+ // but we keep a real-tab sanity check that a non-gated tab stays unlocked+ // regardless of runtime state, confirming the gate is tab-specific.+ expect(+ isSettingsNavItemLocked(+ 'system-general',+ createContext({ runtimeCapabilitiesLoaded: () => false }),+ ),+ ).toBe(false);+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0713.test.ts b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0713.test.tsnew file mode 100644index 0000000000..43e6a23982--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0713.test.ts@@ -0,0 +1,253 @@+import { describe, expect, it } from 'vitest';++import type { Node, Temperature } from '@/types/api';++import { getNodeDrawerHistoryFallbackMetrics, getNodeDrawerHistoryTarget } from '../nodeDrawerModel';++const makeNode = (overrides: Partial<Node> = {}): Node => ({+ id: 'agent:pve-node-1',+ name: 'pve-node-1',+ instance: 'homelab',+ host: 'pve-node-1',+ status: 'online',+ type: 'agent',+ cpu: 0.42,+ memory: { total: 8000, used: 3200, free: 4800, usage: 40 },+ disk: { total: 10000, used: 4500, free: 5500, usage: 45 },+ networkIn: 1200,+ networkOut: 800,+ diskRead: 400,+ diskWrite: 300,+ uptime: 3600,+ loadAverage: [0.5],+ kernelVersion: '6.8.0',+ pveVersion: 'pve-manager/9.1.9',+ cpuInfo: { model: 'Ryzen', cores: 8, sockets: 1, mhz: '3200' },+ temperature: {+ cpuPackage: 62.5,+ cpuMax: 65,+ available: true,+ hasCPU: true,+ lastUpdate: new Date().toISOString(),+ },+ temperatureMonitoringEnabled: true,+ lastSeen: new Date().toISOString(),+ connectionHealth: 'online',+ isClusterMember: true,+ clusterName: 'homelab',+ linkedAgentId: '',+ ...overrides,+});++const makeTemp = (overrides: Partial<Temperature> = {}): Temperature => ({+ available: true,+ lastUpdate: new Date().toISOString(),+ ...overrides,+});++describe('nodeDrawerModel (branch coverage 0713)', () => {+ describe('getNodeDrawerHistoryTarget', () => {+ it('strips only the first agent: prefix when the value is double-prefixed', () => {+ // stripAgentPrefix runs a single startsWith + slice, so 'agent:agent:node-9'+ // collapses to 'agent:node-9' (one prefix removed), NOT 'node-9'.+ const node = makeNode({+ linkedAgentId: 'agent:agent:node-9',+ id: 'agent:pve-node-1',+ name: 'pve-node-1',+ });+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({+ resourceType: 'agent',+ resourceId: 'agent:node-9',+ });+ });++ it('preserves a realistic agent UUID after stripping the prefix', () => {+ // Happy path: long UUID round-trips through stripAgentPrefix without truncation.+ const uuid = '550e8400-e29b-41d4-a716-446655440000';+ const node = makeNode({+ linkedAgentId: `agent:${uuid}`,+ id: 'agent:pve-node-1',+ name: 'pve-node-1',+ });+ const result = getNodeDrawerHistoryTarget(node);+ expect(result).toStrictEqual({ resourceType: 'agent', resourceId: uuid });+ expect(result?.resourceId).toHaveLength(uuid.length);+ });++ it('is case-sensitive: a capitalised "Agent:" prefix is not stripped', () => {+ // String.prototype.startsWith is case-sensitive, so 'Agent:foo' survives intact.+ const node = makeNode({+ linkedAgentId: 'Agent:foo',+ id: 'agent:ignored',+ name: 'ignored',+ });+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({+ resourceType: 'agent',+ resourceId: 'Agent:foo',+ });+ });++ it('treats the truthy string "0" as a valid resourceId', () => {+ // '0' is a truthy string (unlike the number 0): the || chain selects it and+ // !'0' === false, so the success branch runs.+ const node = makeNode({+ linkedAgentId: '0',+ id: 'agent:ignored',+ name: 'ignored',+ });+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({+ resourceType: 'agent',+ resourceId: '0',+ });+ });++ it('trims whitespace on the id fallback arm when id has no agent: prefix', () => {+ // || arm 2 (id) + stripAgentPrefix false arm (no prefix) + .trim() -> 'node-7'.+ const node = makeNode({+ linkedAgentId: '',+ id: ' node-7 ',+ name: 'whatever',+ });+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({+ resourceType: 'agent',+ resourceId: 'node-7',+ });+ });++ it('returns null when the name fallback is whitespace-only', () => {+ // || arm 3 (name): ' ' is truthy so it is chosen, but .trim() -> '' -> !resourceId null.+ const node = makeNode({+ linkedAgentId: '',+ id: '',+ name: ' ',+ });+ expect(getNodeDrawerHistoryTarget(node)).toBeNull();+ });++ it('accepts a single-character unprefixed linkedAgentId', () => {+ // Minimal truthy input: one character, no prefix, no surrounding whitespace.+ const node = makeNode({+ linkedAgentId: 'a',+ id: 'agent:ignored',+ name: 'ignored',+ });+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({+ resourceType: 'agent',+ resourceId: 'a',+ });+ });++ it('falls through an absent linkedAgentId and empty id to a prefixed name', () => {+ // linkedAgentId is undefined (optional field) -> || arm 2 (id '') is falsy+ // -> || arm 3 (name 'agent:host-9') -> stripAgentPrefix true arm -> 'host-9'.+ const node = makeNode({+ linkedAgentId: undefined,+ id: '',+ name: 'agent:host-9',+ });+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({+ resourceType: 'agent',+ resourceId: 'host-9',+ });+ });+ });++ describe('getNodeDrawerHistoryFallbackMetrics', () => {+ it('returns temperature: undefined for an empty temperature object', () => {+ // temperature?.available on {} -> undefined -> !undefined === true -> null -> ?? undefined.+ const node = makeNode({ temperature: {} as unknown as Temperature });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: undefined,+ });+ });++ it('treats a truthy non-boolean available value (1) as available', () => {+ // !1 === false so the guard passes; cpuPackage 50 is the sole candidate.+ const node = makeNode({+ temperature: makeTemp({+ available: 1 as unknown as boolean,+ cpuPackage: 50,+ cpuMax: undefined,+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 50,+ });+ });++ it('returns cpuPackage when it is the largest of all valid sources', () => {+ // cpuPackage 95 > cpuMax 70 and core temps 80/60 -> Math.max selects cpuPackage.+ const node = makeNode({+ temperature: makeTemp({+ cpuPackage: 95,+ cpuMax: 70,+ cores: [+ { core: 0, temp: 80 },+ { core: 1, temp: 60 },+ ],+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 95,+ });+ });++ it('skips an Infinity core temp and returns the max of the finite cores', () => {+ // core temp Infinity -> Number.isFinite false -> skipped; Math.max(88, 72) === 88.+ const node = makeNode({+ temperature: makeTemp({+ cpuPackage: undefined,+ cpuMax: undefined,+ cores: [+ { core: 0, temp: 88 },+ { core: 1, temp: Number.POSITIVE_INFINITY },+ { core: 2, temp: 72 },+ ],+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 88,+ });+ });++ it('returns undefined when cores is an empty array and cpu fields are absent', () => {+ // Array.isArray([]) === true -> forEach runs zero times; candidates empty -> null.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: undefined, cpuMax: undefined, cores: [] }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: undefined,+ });+ });++ it('preserves Number.MAX_VALUE as a finite boundary candidate', () => {+ // Number.isFinite(MAX_VALUE) === true -> valid; sole candidate -> returned unchanged.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: Number.MAX_VALUE, cpuMax: undefined }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: Number.MAX_VALUE,+ });+ });++ it('returns cpuMax when cpuPackage is absent and cores are absent', () => {+ // cpuPackage undefined -> isValidTemperature false -> skipped; cpuMax 68 is the sole candidate.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: undefined, cpuMax: 68 }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 68,+ });+ });++ it('always returns an object with exactly the single key "temperature"', () => {+ // Shape contract: exactly one key regardless of the resolved value.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: 42, cpuMax: undefined }),+ });+ const result = getNodeDrawerHistoryFallbackMetrics(node);+ expect(Object.keys(result)).toEqual(['temperature']);+ expect(result.temperature).toBe(42);+ });+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/thresholdSliderModel.branchcov0713.test.ts b/frontend-modern/src/components/Workloads/__tests__/thresholdSliderModel.branchcov0713.test.tsnew file mode 100644index 0000000000..dac112ed4f--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/thresholdSliderModel.branchcov0713.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('@/utils/temperature', () => ({+ formatTemperature: (value: number | null | undefined) =>+ value === null || value === undefined || !Number.isFinite(value) ? '—' : `${value}°C`,+ getTemperatureSymbol: () => '°C',+}));++import type { ThresholdSliderMetricType } from '@/utils/thresholdSliderPresentation';+import {+ DEFAULT_THRESHOLD_SLIDER_MAX,+ DEFAULT_THRESHOLD_SLIDER_MIN,+ getThresholdSliderBounds,+ getThresholdSliderLabel,+ getThresholdSliderThumbTransform,+ getThresholdSliderTitle,+} from '../thresholdSliderModel';++// getThresholdSliderBounds declares both params as `number | undefined`. These+// aliases let us deliberately pass `null` (a nullish value the declared type+// excludes) through `as unknown as` so the `??` fallback arms are exercised+// without resorting to `any`.+type BoundsMin = Parameters<typeof getThresholdSliderBounds>[0];+type BoundsMax = Parameters<typeof getThresholdSliderBounds>[1];++const PERCENT_TYPES: readonly ThresholdSliderMetricType[] = ['cpu', 'memory', 'disk'];++describe('getThresholdSliderBounds (branch coverage 0713)', () => {+ describe('?? fallback arms', () => {+ it('falls back to both default constants when called with no arguments', () => {+ expect(getThresholdSliderBounds()).toEqual({+ min: DEFAULT_THRESHOLD_SLIDER_MIN,+ max: DEFAULT_THRESHOLD_SLIDER_MAX,+ });+ });++ it('uses the provided min and falls back to the default max', () => {+ expect(getThresholdSliderBounds(10)).toEqual({+ min: 10,+ max: DEFAULT_THRESHOLD_SLIDER_MAX,+ });+ });++ it('falls back to the default min and uses the provided max', () => {+ expect(getThresholdSliderBounds(undefined, 200)).toEqual({+ min: DEFAULT_THRESHOLD_SLIDER_MIN,+ max: 200,+ });+ });++ it('uses both provided bounds unchanged', () => {+ expect(getThresholdSliderBounds(10, 200)).toEqual({ min: 10, max: 200 });+ });++ it('returns exactly the {min, max} shape with no extra keys', () => {+ const bounds = getThresholdSliderBounds(5, 95);+ expect(Object.keys(bounds).sort()).toEqual(['max', 'min']);+ });+ });++ describe('null is treated as nullish by ?? (deliberate malformed input)', () => {+ it('falls back to both defaults when both bounds are null', () => {+ expect(+ getThresholdSliderBounds(null as unknown as BoundsMin, null as unknown as BoundsMax),+ ).toEqual({ min: DEFAULT_THRESHOLD_SLIDER_MIN, max: DEFAULT_THRESHOLD_SLIDER_MAX });+ });++ it('falls back to the default min when min is null but a real max is given', () => {+ expect(getThresholdSliderBounds(null as unknown as BoundsMin, 200)).toEqual({+ min: DEFAULT_THRESHOLD_SLIDER_MIN,+ max: 200,+ });+ });++ it('falls back to the default max when max is null but a real min is given', () => {+ expect(getThresholdSliderBounds(10, null as unknown as BoundsMax)).toEqual({+ min: 10,+ max: DEFAULT_THRESHOLD_SLIDER_MAX,+ });+ });+ });+});++describe('getThresholdSliderThumbTransform (branch coverage 0713)', () => {+ describe('position <= 1 arm -> translateX(0%)', () => {+ it.each([+ ['zero', 0],+ ['exactly 1 (low boundary, <=)', 1],+ ['negative', -5],+ ])('returns the left-edge transform for %s', (_label, position) => {+ expect(getThresholdSliderThumbTransform(position)).toBe('translateY(-50%) translateX(0%)');+ });+ });++ describe('middle arm (1 < position < 99) -> translateX(-50%)', () => {+ it.each([+ ['just above the low threshold', 2],+ ['the midpoint', 50],+ ['just below the high threshold', 98],+ ])('returns the centered transform for %s', (_label, position) => {+ expect(getThresholdSliderThumbTransform(position)).toBe('translateY(-50%) translateX(-50%)');+ });+ });++ describe('position >= 99 arm -> translateX(-100%)', () => {+ it.each([+ ['exactly 99 (high boundary, >=)', 99],+ ['100', 100],+ ['far above', 150],+ ])('returns the right-edge transform for %s', (_label, position) => {+ expect(getThresholdSliderThumbTransform(position)).toBe('translateY(-50%) translateX(-100%)');+ });+ });+});++describe('getThresholdSliderTitle (branch coverage 0713)', () => {+ describe("type === 'temperature' arm", () => {+ it('composes "Temperature: " + formatTemperature(value)', () => {+ expect(getThresholdSliderTitle('temperature', 72)).toBe('Temperature: 72°C');+ });++ it('delegates non-finite values to formatTemperature (NaN -> em-dash)', () => {+ expect(getThresholdSliderTitle('temperature', Number.NaN)).toBe('Temperature: —');+ });++ it('delegates null values to formatTemperature (null -> em-dash)', () => {+ expect(getThresholdSliderTitle('temperature', null as unknown as number)).toBe(+ 'Temperature: —',+ );+ });+ });++ describe('else arm (type.toUpperCase() + value%)', () => {+ it('uppercases each non-temperature metric type and appends the value percent', () => {+ expect(PERCENT_TYPES.map((t) => getThresholdSliderTitle(t, 50))).toEqual([+ 'CPU: 50%',+ 'MEMORY: 50%',+ 'DISK: 50%',+ ]);+ });++ it('renders 0% for a zero value', () => {+ expect(getThresholdSliderTitle('cpu', 0)).toBe('CPU: 0%');+ });++ it('does not guard NaN in the else arm (observed: "CPU: NaN%")', () => {+ expect(getThresholdSliderTitle('cpu', Number.NaN)).toBe('CPU: NaN%');+ });+ });+});++describe('getThresholdSliderLabel (branch coverage 0713)', () => {+ describe("type === 'temperature' arm", () => {+ it('interpolates the raw value + temperature symbol (does NOT call formatTemperature)', () => {+ expect(getThresholdSliderLabel('temperature', 72)).toBe('72°C');+ });++ it('renders 0°C for a zero value', () => {+ expect(getThresholdSliderLabel('temperature', 0)).toBe('0°C');+ });++ it('does not route NaN through formatTemperature (observed: "NaN°C", unlike the title)', () => {+ expect(getThresholdSliderLabel('temperature', Number.NaN)).toBe('NaN°C');+ });++ it('does not null-guard the raw interpolation (observed: "null°C")', () => {+ expect(getThresholdSliderLabel('temperature', null as unknown as number)).toBe('null°C');+ });+ });++ describe('else arm (value%)', () => {+ it('appends % for each non-temperature metric type', () => {+ expect(PERCENT_TYPES.map((t) => getThresholdSliderLabel(t, 50))).toEqual(['50%', '50%', '50%']);+ });++ it('renders 0% for a zero value', () => {+ expect(getThresholdSliderLabel('cpu', 0)).toBe('0%');+ });++ it('does not guard NaN in the else arm (observed: "NaN%")', () => {+ expect(getThresholdSliderLabel('cpu', Number.NaN)).toBe('NaN%');+ });+ });+});diff --git a/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0713.test.ts b/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0713.test.tsnew file mode 100644index 0000000000..4cc9cbb458--- /dev/null+++ b/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0713.test.ts@@ -0,0 +1,1098 @@+import { describe, expect, it } from 'vitest';+import type { PlatformNavigationVisibility } from '@/features/platformNavigation/platformNavigationModel';+import {+ buildCommandPaletteCommands,+ filterCommandPaletteCommands,+ normalizeCommandPaletteQuery,+ type CommandPaletteAssistantActions,+ type CommandPaletteCommandPaths,+ type CommandPaletteModalCommand,+} from '@/components/shared/commandPaletteModel';++// Branch-coverage suite for the three target exports of commandPaletteModel.ts:+//+// 1. buildCommandPaletteCommands — COMPLETELY uncovered by the sibling+// suites (branchcov0712 / branchcov0712c only test filterCommandPaletteCommands).+// Every branch is exercised here: the `if (options.assistantActions)`+// truthy/falsy arms, the `assistantOpenPresentation ?? {default}` LEFT vs+// RIGHT arm, each of the six `primaryPlatformNavigationIsVisible(...)`+// per-platform visible/not-visible arms, the always-pushed tail commands,+// and the wiring of every `action` closure (platform actions call+// `navigate(path)` with the correct path; assistant actions call the right+// assistantActions method).+// 2. normalizeCommandPaletteQuery — only exercised INDIRECTLY via the filter+// in the sibling suites. Here it is tested directly across every step of+// its `toLowerCase().trim().replace(/\s+/g, '')` pipeline and every+// whitespace class (\s = space, tab, newline, CR, FF, VT).+// 3. filterCommandPaletteCommands — heavily covered already; this file adds+// ONLY complementary input-class angles the siblings do not exercise:+// regex-metacharacter queries (treated literally by `.includes`), a query+// equal to the entire normalized haystack (full-match boundary), a query+// strictly longer than the haystack (no-match boundary), numeric-only+// queries, and a single special-char query that matches many descriptions.+//+// Every assertion is a concrete equality / strict-equality check against the+// real return shape — no tautologies, no truthiness-only checks, no mock+// echoes. Closure-based spies (rather than vi.fn) match the import style of the+// sibling commandPaletteModel test suites.++// --- fixtures ----------------------------------------------------------------++function makePaths(+ overrides: Partial<CommandPaletteCommandPaths> = {},+): CommandPaletteCommandPaths {+ return {+ standalonePath: '/standalone',+ proxmoxPath: '/proxmox',+ dockerPath: '/docker',+ kubernetesPath: '/kubernetes',+ kubernetesWorkloadsPath: '/kubernetes/workloads',+ trueNasPath: '/truenas',+ vmwarePath: '/vmware',+ vmwareNetworksPath: '/vmware/networks',+ ...overrides,+ };+}++function makeVisibility(+ overrides: Partial<PlatformNavigationVisibility> = {},+): PlatformNavigationVisibility {+ return {+ proxmox: false,+ docker: false,+ kubernetes: false,+ truenas: false,+ vmware: false,+ standalone: false,+ ...overrides,+ };+}++// Records every path handed to `navigate`. The build function must NOT call+// navigate itself (actions are lazy closures); only invoking an action should+// push to `calls`, and with the exact path string for that command.+function makeNavigateSpy() {+ const calls: string[] = [];+ const navigate = (path: string): void => {+ calls.push(path);+ };+ return { navigate, calls };+}++// Builds a fully-populated CommandPaletteAssistantActions where every method is+// independently spy-counted, so we can assert exactly which method a given+// assistant command's action fires.+function makeAssistantActions(): {+ actions: CommandPaletteAssistantActions;+ spies: Record<keyof CommandPaletteAssistantActions, number>;+} {+ const spies: Record<keyof CommandPaletteAssistantActions, number> = {+ open: 0,+ help: 0,+ newSession: 0,+ sessions: 0,+ models: 0,+ providers: 0,+ status: 0,+ undo: 0,+ redo: 0,+ };+ const actions: CommandPaletteAssistantActions = {+ open: () => {+ spies.open += 1;+ },+ help: () => {+ spies.help += 1;+ },+ newSession: () => {+ spies.newSession += 1;+ },+ sessions: () => {+ spies.sessions += 1;+ },+ models: () => {+ spies.models += 1;+ },+ providers: () => {+ spies.providers += 1;+ },+ status: () => {+ spies.status += 1;+ },+ undo: () => {+ spies.undo += 1;+ },+ redo: () => {+ spies.redo += 1;+ },+ };+ return { actions, spies };+}++// ===========================================================================+// 1. buildCommandPaletteCommands+// ===========================================================================++describe('commandPaletteModel.branchcov0713', () => {+ describe('buildCommandPaletteCommands', () => {+ describe('`if (options.assistantActions)` — falsy arm (no assistant block)', () => {+ it('omits every assistant-* command when assistantActions is absent', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ });+ const ids = commands.map((c) => c.id);+ expect(ids.filter((id) => id.startsWith('assistant-'))).toStrictEqual([]);+ });++ it('returns exactly the three always-pushed tail commands when nothing is visible and no assistant', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ });+ expect(commands.map((c) => c.id)).toStrictEqual([+ 'nav-alerts',+ 'nav-patrol',+ 'nav-settings',+ ]);+ });+ });++ describe('`if (options.assistantActions)` — truthy arm (nine assistant commands)', () => {+ it('prepends all nine assistant commands in the exact fixed order', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ // First nine entries are the assistant block, in source order.+ expect(commands.slice(0, 9).map((c) => c.id)).toStrictEqual([+ 'assistant-open',+ 'assistant-help',+ 'assistant-new-session',+ 'assistant-switch-session',+ 'assistant-switch-model',+ 'assistant-provider-settings',+ 'assistant-status',+ 'assistant-undo-last-turn',+ 'assistant-redo-last-turn',+ ]);+ });++ it('emits nine assistant + three tail = twelve commands when no platform is visible', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ expect(commands).toHaveLength(12);+ });++ it('pins the exact static labels/descriptions of the eight non-open assistant commands', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ const byId = new Map(commands.map((c) => [c.id, c]));+ expect(byId.get('assistant-help')?.label).toBe('Show Assistant commands');+ expect(byId.get('assistant-help')?.description).toBe('/help');+ expect(byId.get('assistant-new-session')?.label).toBe('New Assistant session');+ expect(byId.get('assistant-new-session')?.description).toBe('/new');+ expect(byId.get('assistant-switch-session')?.label).toBe('Switch Assistant session');+ expect(byId.get('assistant-switch-session')?.description).toBe('/sessions');+ expect(byId.get('assistant-switch-model')?.label).toBe('Switch Assistant model');+ expect(byId.get('assistant-switch-model')?.description).toBe('/models');+ expect(byId.get('assistant-provider-settings')?.label).toBe(+ 'Open Assistant provider settings',+ );+ expect(byId.get('assistant-provider-settings')?.description).toBe('/providers');+ expect(byId.get('assistant-status')?.label).toBe('Check Assistant status');+ expect(byId.get('assistant-status')?.description).toBe('/status');+ expect(byId.get('assistant-undo-last-turn')?.label).toBe('Undo last Assistant turn');+ expect(byId.get('assistant-undo-last-turn')?.description).toBe('/undo');+ expect(byId.get('assistant-redo-last-turn')?.label).toBe('Redo last Assistant turn');+ expect(byId.get('assistant-redo-last-turn')?.description).toBe('/redo');+ });+ });++ describe('`assistantOpenPresentation ?? {default}` — RIGHT (absent) arm', () => {+ it('falls back to the default label and description when presentation is omitted', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ // assistantOpenPresentation intentionally omitted+ });+ const open = commands.find((c) => c.id === 'assistant-open');+ expect(open?.label).toBe('Ask about this view');+ expect(open?.description).toBe('Use the current Pulse view as context');+ });+ });++ describe('`assistantOpenPresentation ?? {default}` — LEFT (present) arm', () => {+ it('uses the caller-provided label and description verbatim', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ assistantOpenPresentation: {+ label: 'Ask about the dashboard',+ description: 'Feed the current dashboard to the assistant',+ },+ });+ const open = commands.find((c) => c.id === 'assistant-open');+ expect(open?.label).toBe('Ask about the dashboard');+ expect(open?.description).toBe('Feed the current dashboard to the assistant');+ });++ it('does NOT contaminate the eight other assistant commands with the custom presentation', () => {+ // Only assistant-open consumes the presentation; the rest keep static copy.+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ assistantOpenPresentation: {+ label: 'Unique Presentation Label',+ description: 'unique-presentation-desc',+ },+ });+ const others = commands.filter(+ (c) => c.id.startsWith('assistant-') && c.id !== 'assistant-open',+ );+ expect(others).toHaveLength(8);+ for (const cmd of others) {+ expect(cmd.label).not.toBe('Unique Presentation Label');+ expect(cmd.description).not.toBe('unique-presentation-desc');+ }+ });+ });++ describe('per-platform `primaryPlatformNavigationIsVisible` — not-visible arm (every platform)', () => {+ it('emits zero nav-* platform commands (only the always-pushed tail) when all flags are false', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ });+ const navIds = commands+ .map((c) => c.id)+ .filter((id) => id.startsWith('nav-') && !['nav-alerts', 'nav-patrol', 'nav-settings'].includes(id));+ expect(navIds).toStrictEqual([]);+ });+ });++ describe('per-platform visible arm — selective single-platform visibility', () => {+ it('emits only nav-proxmox (of the platform commands) when only proxmox is visible', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({ proxmox: true }),+ navigate,+ });+ const platformIds = commands+ .map((c) => c.id)+ .filter((id) => id.startsWith('nav-') && !['nav-alerts', 'nav-patrol', 'nav-settings'].includes(id));+ expect(platformIds).toStrictEqual(['nav-proxmox']);+ });++ it('emits only nav-docker when only docker is visible', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({ docker: true }),+ navigate,+ });+ const platformIds = commands+ .map((c) => c.id)+ .filter((id) => id.startsWith('nav-') && !['nav-alerts', 'nav-patrol', 'nav-settings'].includes(id));+ expect(platformIds).toStrictEqual(['nav-docker']);+ });++ it('emits BOTH nav-kubernetes and nav-kubernetes-workloads when only kubernetes is visible', () => {+ // The kubernetes block pushes two commands inside one `if`.+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({ kubernetes: true }),+ navigate,+ });+ const platformIds = commands+ .map((c) => c.id)+ .filter((id) => id.startsWith('nav-') && !['nav-alerts', 'nav-patrol', 'nav-settings'].includes(id));+ expect(platformIds).toStrictEqual(['nav-kubernetes', 'nav-kubernetes-workloads']);+ });++ it('emits only nav-truenas when only truenas is visible', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({ truenas: true }),+ navigate,+ });+ const platformIds = commands+ .map((c) => c.id)+ .filter((id) => id.startsWith('nav-') && !['nav-alerts', 'nav-patrol', 'nav-settings'].includes(id));+ expect(platformIds).toStrictEqual(['nav-truenas']);+ });++ it('emits BOTH nav-vmware and nav-vmware-networks when only vmware is visible', () => {+ // The vmware block pushes two commands inside one `if`.+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({ vmware: true }),+ navigate,+ });+ const platformIds = commands+ .map((c) => c.id)+ .filter((id) => id.startsWith('nav-') && !['nav-alerts', 'nav-patrol', 'nav-settings'].includes(id));+ expect(platformIds).toStrictEqual(['nav-vmware', 'nav-vmware-networks']);+ });++ it('emits only nav-standalone when only standalone is visible', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({ standalone: true }),+ navigate,+ });+ const platformIds = commands+ .map((c) => c.id)+ .filter((id) => id.startsWith('nav-') && !['nav-alerts', 'nav-patrol', 'nav-settings'].includes(id));+ expect(platformIds).toStrictEqual(['nav-standalone']);+ });+ });++ describe('all platforms visible at once', () => {+ it('emits all eight platform commands in source order, followed by the three tail commands', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({+ proxmox: true,+ docker: true,+ kubernetes: true,+ truenas: true,+ vmware: true,+ standalone: true,+ }),+ navigate,+ });+ expect(commands.map((c) => c.id)).toStrictEqual([+ 'nav-proxmox',+ 'nav-docker',+ 'nav-kubernetes',+ 'nav-kubernetes-workloads',+ 'nav-truenas',+ 'nav-vmware',+ 'nav-vmware-networks',+ 'nav-standalone',+ 'nav-alerts',+ 'nav-patrol',+ 'nav-settings',+ ]);+ // 8 platform + 3 tail = 11.+ expect(commands).toHaveLength(11);+ });+ });++ describe('platform command `description` is sourced from `options.paths.*`', () => {+ it('flows each custom path string into the corresponding command description', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({+ proxmoxPath: '/custom/pve',+ dockerPath: '/custom/docker',+ kubernetesPath: '/custom/k8s',+ kubernetesWorkloadsPath: '/custom/k8s/wl',+ trueNasPath: '/custom/tn',+ vmwarePath: '/custom/vm',+ vmwareNetworksPath: '/custom/vm/net',+ standalonePath: '/custom/standalone',+ }),+ platformVisibility: makeVisibility({+ proxmox: true,+ docker: true,+ kubernetes: true,+ truenas: true,+ vmware: true,+ standalone: true,+ }),+ navigate,+ });+ const byId = new Map(commands.map((c) => [c.id, c]));+ expect(byId.get('nav-proxmox')?.description).toBe('/custom/pve');+ expect(byId.get('nav-docker')?.description).toBe('/custom/docker');+ expect(byId.get('nav-kubernetes')?.description).toBe('/custom/k8s');+ expect(byId.get('nav-kubernetes-workloads')?.description).toBe('/custom/k8s/wl');+ expect(byId.get('nav-truenas')?.description).toBe('/custom/tn');+ expect(byId.get('nav-vmware')?.description).toBe('/custom/vm');+ expect(byId.get('nav-vmware-networks')?.description).toBe('/custom/vm/net');+ expect(byId.get('nav-standalone')?.description).toBe('/custom/standalone');+ });++ it('uses the hardcoded descriptions for the always-pushed tail commands regardless of paths', () => {+ // alerts/patrol/settings descriptions are literals, not from options.paths.+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ });+ const byId = new Map(commands.map((c) => [c.id, c]));+ expect(byId.get('nav-alerts')?.description).toBe('/alerts');+ expect(byId.get('nav-patrol')?.description).toBe('/patrol');+ expect(byId.get('nav-settings')?.description).toBe('/settings');+ });+ });++ describe('command shortcuts (only platform + tail commands carry them)', () => {+ it('assigns the documented shortcut to each platform/tail command and none to assistant commands', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({+ proxmox: true,+ docker: true,+ kubernetes: true,+ truenas: true,+ vmware: true,+ standalone: true,+ }),+ navigate,+ assistantActions: actions,+ });+ const byId = new Map(commands.map((c) => [c.id, c]));+ expect(byId.get('nav-proxmox')?.shortcut).toBe('g p');+ expect(byId.get('nav-docker')?.shortcut).toBe('g d');+ expect(byId.get('nav-kubernetes')?.shortcut).toBe('g k');+ expect(byId.get('nav-kubernetes-workloads')?.shortcut).toBeUndefined();+ expect(byId.get('nav-truenas')?.shortcut).toBe('g n');+ expect(byId.get('nav-vmware')?.shortcut).toBe('g v');+ expect(byId.get('nav-vmware-networks')?.shortcut).toBeUndefined();+ expect(byId.get('nav-standalone')?.shortcut).toBe('g s');+ expect(byId.get('nav-alerts')?.shortcut).toBe('g a');+ expect(byId.get('nav-patrol')?.shortcut).toBe('g r');+ expect(byId.get('nav-settings')?.shortcut).toBe('g t');+ // Assistant commands deliberately have no shortcut property.+ for (const id of [+ 'assistant-open',+ 'assistant-help',+ 'assistant-new-session',+ 'assistant-redo-last-turn',+ ]) {+ expect(byId.get(id)?.shortcut).toBeUndefined();+ }+ });+ });++ describe('action closure wiring — navigate is NOT called during build', () => {+ it('leaves the navigate spy untouched after building (actions are lazy)', () => {+ const { navigate, calls } = makeNavigateSpy();+ buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({+ proxmox: true,+ docker: true,+ kubernetes: true,+ truenas: true,+ vmware: true,+ standalone: true,+ }),+ navigate,+ });+ expect(calls).toStrictEqual([]);+ });+ });++ describe('action closure wiring — platform actions invoke navigate with the exact path', () => {+ it('fires navigate with the proxmox path when nav-proxmox action runs', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({ proxmoxPath: '/pve/path' }),+ platformVisibility: makeVisibility({ proxmox: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-proxmox')!.action();+ expect(calls).toStrictEqual(['/pve/path']);+ });++ it('fires navigate with the docker path when nav-docker action runs', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({ dockerPath: '/docker/path' }),+ platformVisibility: makeVisibility({ docker: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-docker')!.action();+ expect(calls).toStrictEqual(['/docker/path']);+ });++ it('fires navigate with the kubernetes path for nav-kubernetes', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({ kubernetesPath: '/k8s/path' }),+ platformVisibility: makeVisibility({ kubernetes: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-kubernetes')!.action();+ expect(calls).toStrictEqual(['/k8s/path']);+ });++ it('fires navigate with the workloads path for nav-kubernetes-workloads (distinct from kubernetes root)', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({+ kubernetesPath: '/k8s',+ kubernetesWorkloadsPath: '/k8s/workloads',+ }),+ platformVisibility: makeVisibility({ kubernetes: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-kubernetes-workloads')!.action();+ expect(calls).toStrictEqual(['/k8s/workloads']);+ });++ it('fires navigate with the truenas path when nav-truenas action runs', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({ trueNasPath: '/tn/path' }),+ platformVisibility: makeVisibility({ truenas: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-truenas')!.action();+ expect(calls).toStrictEqual(['/tn/path']);+ });++ it('fires navigate with the vmware path for nav-vmware', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({ vmwarePath: '/vm/path' }),+ platformVisibility: makeVisibility({ vmware: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-vmware')!.action();+ expect(calls).toStrictEqual(['/vm/path']);+ });++ it('fires navigate with the vmware networks path for nav-vmware-networks (distinct from vmware root)', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({ vmwarePath: '/vm', vmwareNetworksPath: '/vm/networks' }),+ platformVisibility: makeVisibility({ vmware: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-vmware-networks')!.action();+ expect(calls).toStrictEqual(['/vm/networks']);+ });++ it('fires navigate with the standalone path when nav-standalone action runs', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths({ standalonePath: '/standalone/path' }),+ platformVisibility: makeVisibility({ standalone: true }),+ navigate,+ });+ commands.find((c) => c.id === 'nav-standalone')!.action();+ expect(calls).toStrictEqual(['/standalone/path']);+ });+ });++ describe('action closure wiring — always-pushed tail actions', () => {+ it('fires navigate with /alerts, /patrol, /settings respectively', () => {+ const { navigate, calls } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ });+ const byId = new Map(commands.map((c) => [c.id, c]));+ byId.get('nav-alerts')!.action();+ byId.get('nav-patrol')!.action();+ byId.get('nav-settings')!.action();+ expect(calls).toStrictEqual(['/alerts', '/patrol', '/settings']);+ });+ });++ describe('action closure wiring — assistant actions fire the correct method exactly once', () => {+ it('routes assistant-open -> assistantActions.open', () => {+ const { navigate } = makeNavigateSpy();+ const { actions, spies } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ commands.find((c) => c.id === 'assistant-open')!.action();+ expect(spies.open).toBe(1);+ // No other assistant method was invoked.+ expect(spies.help).toBe(0);+ expect(spies.newSession).toBe(0);+ });++ it('routes assistant-help -> assistantActions.help', () => {+ const { navigate } = makeNavigateSpy();+ const { actions, spies } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ commands.find((c) => c.id === 'assistant-help')!.action();+ expect(spies.help).toBe(1);+ expect(spies.open).toBe(0);+ });++ it('routes assistant-new-session -> newSession, assistant-switch-session -> sessions', () => {+ const { navigate } = makeNavigateSpy();+ const { actions, spies } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ commands.find((c) => c.id === 'assistant-new-session')!.action();+ commands.find((c) => c.id === 'assistant-switch-session')!.action();+ expect(spies.newSession).toBe(1);+ expect(spies.sessions).toBe(1);+ });++ it('routes assistant-switch-model -> models and assistant-provider-settings -> providers', () => {+ const { navigate } = makeNavigateSpy();+ const { actions, spies } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ commands.find((c) => c.id === 'assistant-switch-model')!.action();+ commands.find((c) => c.id === 'assistant-provider-settings')!.action();+ expect(spies.models).toBe(1);+ expect(spies.providers).toBe(1);+ });++ it('routes assistant-status -> status, assistant-undo-last-turn -> undo, assistant-redo-last-turn -> redo', () => {+ const { navigate } = makeNavigateSpy();+ const { actions, spies } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ commands.find((c) => c.id === 'assistant-status')!.action();+ commands.find((c) => c.id === 'assistant-undo-last-turn')!.action();+ commands.find((c) => c.id === 'assistant-redo-last-turn')!.action();+ expect(spies.status).toBe(1);+ expect(spies.undo).toBe(1);+ expect(spies.redo).toBe(1);+ });++ it('does NOT call navigate when an assistant action runs (assistant actions are independent of routing)', () => {+ const { navigate, calls } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ commands.find((c) => c.id === 'assistant-open')!.action();+ commands.find((c) => c.id === 'assistant-help')!.action();+ expect(calls).toStrictEqual([]);+ });+ });++ describe('keywords arrays are populated (spot-check representative commands)', () => {+ it('attaches the exact proxmox keyword set to nav-proxmox', () => {+ const { navigate } = makeNavigateSpy();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({ proxmox: true }),+ navigate,+ });+ expect(commands.find((c) => c.id === 'nav-proxmox')?.keywords).toStrictEqual([+ 'proxmox',+ 'pve',+ 'pbs',+ 'pmg',+ 'mail',+ 'backups',+ 'ceph',+ 'vm',+ 'lxc',+ ]);+ });++ it('attaches the seven-term keyword set to assistant-open', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility(),+ navigate,+ assistantActions: actions,+ });+ expect(commands.find((c) => c.id === 'assistant-open')?.keywords).toStrictEqual([+ 'assistant',+ 'ai',+ 'chat',+ 'ask',+ 'pulse',+ 'view',+ 'context',+ ]);+ });+ });++ describe('combined realistic build (assistant + all platforms visible)', () => {+ it('produces 9 assistant + 8 platform + 3 tail = 20 commands with unique ids', () => {+ const { navigate } = makeNavigateSpy();+ const { actions } = makeAssistantActions();+ const commands = buildCommandPaletteCommands({+ paths: makePaths(),+ platformVisibility: makeVisibility({+ proxmox: true,+ docker: true,+ kubernetes: true,+ truenas: true,+ vmware: true,+ standalone: true,+ }),+ navigate,+ assistantActions: actions,+ assistantOpenPresentation: { label: 'L', description: 'D' },+ });+ expect(commands).toHaveLength(20);+ const ids = commands.map((c) => c.id);+ expect(new Set(ids).size).toBe(ids.length);+ // First command is the customized assistant-open.+ expect(commands[0]).toMatchObject({ id: 'assistant-open', label: 'L', description: 'D' });+ // Last three are the always-pushed tail.+ expect(commands.slice(-3).map((c) => c.id)).toStrictEqual([+ 'nav-alerts',+ 'nav-patrol',+ 'nav-settings',+ ]);+ });+ });+ });++ // ===========================================================================+ // 2. normalizeCommandPaletteQuery+ // ===========================================================================++ describe('normalizeCommandPaletteQuery', () => {+ describe('empty / whitespace-only inputs (every arm of \\s collapses to empty)', () => {+ it('returns "" for the empty string', () => {+ expect(normalizeCommandPaletteQuery('')).toBe('');+ });++ it('returns "" for a single space', () => {+ expect(normalizeCommandPaletteQuery(' ')).toBe('');+ });++ it('returns "" for many spaces', () => {+ expect(normalizeCommandPaletteQuery(' ')).toBe('');+ });++ it('returns "" for a single tab', () => {+ expect(normalizeCommandPaletteQuery('\t')).toBe('');+ });++ it('returns "" for a single newline', () => {+ expect(normalizeCommandPaletteQuery('\n')).toBe('');+ });++ it('returns "" for a carriage return', () => {+ expect(normalizeCommandPaletteQuery('\r')).toBe('');+ });++ it('returns "" for a form feed / vertical tab (exotic \\s members)', () => {+ expect(normalizeCommandPaletteQuery('\f')).toBe('');+ expect(normalizeCommandPaletteQuery('\v')).toBe('');+ });++ it('returns "" for a mix of all whitespace kinds surrounding real text', () => {+ // trim() removes outer; replace removes inner -> empty remains.+ expect(normalizeCommandPaletteQuery(' \t\n\r\f\v ')).toBe('');+ });+ });++ describe('toLowerCase arm', () => {+ it('leaves an already-lowercase, whitespace-free string unchanged', () => {+ expect(normalizeCommandPaletteQuery('proxmox')).toBe('proxmox');+ });++ it('lowercases an all-uppercase string', () => {+ expect(normalizeCommandPaletteQuery('PROXMOX')).toBe('proxmox');+ });++ it('lowercases a mixed-case string', () => {+ expect(normalizeCommandPaletteQuery('GoToSettings')).toBe('gotosettings');+ });++ it('preserves characters with no case (digits)', () => {+ expect(normalizeCommandPaletteQuery('ROUTE42')).toBe('route42');+ });++ it('lowercases non-ASCII latin-1 letters', () => {+ expect(normalizeCommandPaletteQuery('ÉÀÇ')).toBe('éàç');+ });+ });++ describe('trim arm (leading/trailing whitespace)', () => {+ it('removes leading whitespace', () => {+ expect(normalizeCommandPaletteQuery(' hello')).toBe('hello');+ });++ it('removes trailing whitespace', () => {+ expect(normalizeCommandPaletteQuery('hello ')).toBe('hello');+ });++ it('removes leading and trailing whitespace, then the replace step also strips the inner space', () => {+ // ' go to ' -> trim -> 'go to' -> replace \s+ -> 'goto' (inner space gone too).+ expect(normalizeCommandPaletteQuery(' go to ')).toBe('goto');+ });++ it('removes leading/trailing tabs and newlines (not just spaces)', () => {+ expect(normalizeCommandPaletteQuery('\t\nhello\n\t')).toBe('hello');+ });+ });++ describe('replace(/\\s+/g, "") arm — internal whitespace removal', () => {+ it('removes a single internal space', () => {+ expect(normalizeCommandPaletteQuery('go to')).toBe('goto');+ });++ it('collapses a run of multiple internal spaces to nothing (not to a single space)', () => {+ // \s+ matches the whole run in one go; replacement is "" -> gone entirely.+ expect(normalizeCommandPaletteQuery('go to')).toBe('goto');+ });++ it('removes an internal tab', () => {+ expect(normalizeCommandPaletteQuery('go\tto')).toBe('goto');+ });++ it('removes an internal newline', () => {+ expect(normalizeCommandPaletteQuery('go\nto')).toBe('goto');+ });++ it('removes a mixed-kind internal whitespace run in one match', () => {+ expect(normalizeCommandPaletteQuery('go \t\n to')).toBe('goto');+ });++ it('removes every space in an all-spaces word', () => {+ expect(normalizeCommandPaletteQuery('g o t o')).toBe('goto');+ });+ });++ describe('preservation of non-whitespace content', () => {+ it('preserves punctuation (dots, slashes, dashes)', () => {+ expect(normalizeCommandPaletteQuery('/proxmox/pve')).toBe('/proxmox/pve');+ });++ it('preserves leading slash used by Pulse command descriptions', () => {+ expect(normalizeCommandPaletteQuery(' /Help ')).toBe('/help');+ });++ it('preserves digits adjacent to letters', () => {+ expect(normalizeCommandPaletteQuery('k8s')).toBe('k8s');+ });+ });++ describe('full-pipeline composition (all three steps in one input)', () => {+ it('applies trim, lowercase, and whitespace-removal together', () => {+ // ' /Go To Settings ' -> trim -> '/Go To Settings' -> lowercase+ // -> '/go to settings' -> replace \s+ -> '/gotosettings'+ expect(normalizeCommandPaletteQuery(' /Go To Settings ')).toBe('/gotosettings');+ });++ it('keeps a no-op pipeline stable (already-normalized input is returned verbatim)', () => {+ expect(normalizeCommandPaletteQuery('/alerts')).toBe('/alerts');+ });+ });+ });++ // ===========================================================================+ // 3. filterCommandPaletteCommands — COMPLEMENTARY input-class coverage only.+ // The sibling suites (branchcov0712 / branchcov0712c) already cover every+ // code branch (early return, every `??` arm, match/no-match, order,+ // case-folding, haystack collapse). This block adds ONLY novel input+ // classes that exercise those same branches through angles not yet+ // asserted, to guard against regressions in `.includes` semantics.+ // ===========================================================================++ describe('filterCommandPaletteCommands — complementary input-class coverage', () => {+ function makeCommand(+ overrides: Partial<CommandPaletteModalCommand> = {},+ ): CommandPaletteModalCommand {+ return {+ id: 'cmd-1',+ label: 'Go to Proxmox',+ description: '/proxmox',+ shortcut: 'g p',+ keywords: ['proxmox', 'pve', 'backups'],+ action: () => {},+ ...overrides,+ };+ }++ describe('regex metacharacters in the query are treated as LITERAL substrings', () => {+ // filterCommandPaletteCommands uses String.prototype.includes (not a+ // RegExp), so metacharacters must never act as wildcards. Pin that.+ it('does NOT treat ".*" as a match-all wildcard', () => {+ const commands = [+ makeCommand({ id: 'a', label: 'Alpha' }),+ makeCommand({ id: 'b', label: 'Beta' }),+ ];+ // No command literally contains the substring '.*' -> empty result.+ expect(filterCommandPaletteCommands(commands, '.*')).toStrictEqual([]);+ });++ it('does NOT treat "(.*)" as a regex group', () => {+ const command = makeCommand({ id: 'a', label: 'Alpha' });+ expect(filterCommandPaletteCommands([command], '(.*)')).toStrictEqual([]);+ });++ it('matches a command that LITERALLY contains a metacharacter substring', () => {+ // label 'a.b' contains the literal '.' -> query 'a.b' matches, but a+ // query of 'aXb' would not (proves it is not regex-based).+ const command = makeCommand({ id: 'dot', label: 'a.b' });+ expect(filterCommandPaletteCommands([command], 'a.b')).toStrictEqual([command]);+ expect(filterCommandPaletteCommands([command], 'aXb')).toStrictEqual([]);+ });++ it('matches a literal bracket/plus/pipe substring', () => {+ const command = makeCommand({+ id: 'meta',+ label: 'regex',+ description: '[a]+|b',+ shortcut: 'g g',+ keywords: ['x'],+ });+ expect(filterCommandPaletteCommands([command], '[a]+|b')).toStrictEqual([command]);+ });+ });++ describe('single-character queries that match many descriptions (the "/" case)', () => {+ it('returns every command whose haystack contains "/" for the query "/"', () => {+ // Most Pulse descriptions start with '/'; label/keyword usually do not.+ const a = makeCommand({ id: 'a', label: 'Alerts', description: '/alerts' });+ const b = makeCommand({ id: 'b', label: 'Patrol', description: '/patrol' });+ const c = makeCommand({+ id: 'c',+ label: 'NoSlash',+ description: 'plain',+ shortcut: 'g g',+ keywords: ['plain'],+ });+ const result = filterCommandPaletteCommands([a, b, c], '/');+ // After haystack collapse only a and b contain '/'.+ expect(result).toStrictEqual([a, b]);+ });+ });++ describe('numeric-only queries', () => {+ it('matches a command whose keyword is purely numeric', () => {+ const command = makeCommand({+ id: 'num',+ label: 'Box',+ description: '/box',+ shortcut: 'g g',+ keywords: ['42', 'box'],+ });+ expect(filterCommandPaletteCommands([command], '42')).toStrictEqual([command]);+ });++ it('matches a command whose label embeds digits', () => {+ const command = makeCommand({ id: 'k8s', label: 'Go to Kubernetes 8' });+ expect(filterCommandPaletteCommands([command], '8')).toStrictEqual([command]);+ });++ it('does not match when no field contains the digit', () => {+ const command = makeCommand({ id: 'no-num', label: 'Alpha', keywords: ['beta'] });+ expect(filterCommandPaletteCommands([command], '9')).toStrictEqual([]);+ });+ });++ describe('exact full-haystack boundary match', () => {+ it('matches when the normalized query equals the ENTIRE normalized haystack', () => {+ // label 'Go' + description '/px' + shortcut '' + keywords [] -> join ' '+ // -> 'Go /px ' -> lowercase -> 'go /px ' -> strip ws -> 'go/px'.+ // Query 'go/px' is exactly the whole haystack.+ const command: CommandPaletteModalCommand = {+ id: 'exact',+ label: 'Go',+ description: '/px',+ action: () => {},+ };+ expect(filterCommandPaletteCommands([command], 'go/px')).toStrictEqual([command]);+ });++ it('also matches a leading substring of that full haystack (substring arm)', () => {+ const command: CommandPaletteModalCommand = {+ id: 'exact2',+ label: 'Go',+ description: '/px',+ action: () => {},+ };+ expect(filterCommandPaletteCommands([command], 'go')).toStrictEqual([command]);+ });+ });++ describe('query strictly longer than the haystack (no-match boundary)', () => {+ it('returns [] when the query contains the whole haystack plus extra characters', () => {+ // Full normalized haystack is 'go/px'; query 'go/px/extra' is a strict+ // superset and therefore cannot be a substring of the haystack.+ const command: CommandPaletteModalCommand = {+ id: 'short',+ label: 'Go',+ description: '/px',+ action: () => {},+ };+ expect(filterCommandPaletteCommands([command], 'go/px/extra')).toStrictEqual([]);+ });++ it('returns [] when the haystack is the empty string (label-only absent) and query is non-empty', () => {+ // Malformed-but-typed fixture: label is the only non-empty field but we+ // blank it too, so the collapsed haystack is ''.+ const command = {+ id: 'empty-hay',+ label: '',+ action: () => {},+ } as unknown as CommandPaletteModalCommand;+ expect(filterCommandPaletteCommands([command], 'x')).toStrictEqual([]);+ });+ });+ });+});diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0713.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0713.test.tsnew file mode 100644index 0000000000..f465a3b2cc--- /dev/null+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0713.test.ts@@ -0,0 +1,669 @@+import { describe, expect, it } from 'vitest';++import type { AppriseConfig } from '@/api/notifications';+import type { UIAppriseConfig, UIEmailConfig } from '../types';++import {+ buildAppriseConfigPayload,+ buildEmailConfigPayload,+ normalizeAppriseConfig,+} from '../alertDestinationsModel';++// ---------------------------------------------------------------------------+// Fixtures — minimal valid UI configs. Tests override only the fields+// relevant to the branch under examination. Mirrors the helpers used by the+// sibling `branchcov0712` / `branchcov0712c` suites so conventions stay+// identical. Defaults match `createDefaultAppriseConfig` /+// `createDefaultEmailConfig` in ../helpers.ts.+// ---------------------------------------------------------------------------++function makeUIAppriseConfig(overrides: Partial<UIAppriseConfig> = {}): UIAppriseConfig {+ return {+ enabled: false,+ mode: 'cli',+ targetsText: '',+ cliPath: 'apprise',+ timeoutSeconds: 15,+ serverUrl: '',+ configKey: '',+ apiKey: '',+ apiKeyHeader: 'X-API-KEY',+ skipTlsVerify: false,+ ...overrides,+ };+}++function makeUIEmailConfig(overrides: Partial<UIEmailConfig> = {}): UIEmailConfig {+ return {+ enabled: true,+ provider: 'smtp',+ server: 'smtp.internal',+ port: 587,+ username: '[email protected]',+ password: 'secret',+ from: '[email protected]',+ to: ['[email protected]'],+ tls: true,+ startTLS: true,+ replyTo: '',+ maxRetries: 3,+ retryDelay: 60,+ rateLimit: 0,+ ...overrides,+ };+}++// Credential-shaped strings are built by interpolating a variable so the+// repo's gitleaks hook does not flag a hardcoded literal.+const fakeKey = 'k'.repeat(32);+const fakeToken = 't'.repeat(40);++describe('normalizeAppriseConfig — branch coverage (0713)', () => {+ // -----------------------------------------------------------------------+ // config?.enabled ?? false+ // - nullish coalescing: undefined / null → false (right arm)+ // - defined boolean → as-is (left arm)+ // -----------------------------------------------------------------------+ describe('enabled ?? false', () => {+ it('falls back to false when enabled is undefined', () => {+ const result = normalizeAppriseConfig({ enabled: undefined });+ expect(result.enabled).toBe(false);+ });++ it('falls back to false when the whole config is null', () => {+ const result = normalizeAppriseConfig(null);+ expect(result.enabled).toBe(false);+ });++ it('falls back to false when the whole config is undefined', () => {+ const result = normalizeAppriseConfig(undefined);+ expect(result.enabled).toBe(false);+ });++ it('preserves an explicit false', () => {+ const result = normalizeAppriseConfig({ enabled: false });+ expect(result.enabled).toBe(false);+ });++ it('preserves an explicit true', () => {+ const result = normalizeAppriseConfig({ enabled: true });+ expect(result.enabled).toBe(true);+ });+ });++ // -----------------------------------------------------------------------+ // config?.mode === 'http' ? 'http' : 'cli'+ // - strict-equality true arm: mode === 'http'+ // - strict-equality false arm: 'cli', undefined, junk string, etc.+ // -----------------------------------------------------------------------+ describe('mode ternary', () => {+ it("returns 'http' when mode is exactly 'http'", () => {+ const result = normalizeAppriseConfig({ mode: 'http' });+ expect(result.mode).toBe('http');+ });++ it("returns 'cli' when mode is exactly 'cli'", () => {+ const result = normalizeAppriseConfig({ mode: 'cli' });+ expect(result.mode).toBe('cli');+ });++ it("returns 'cli' when mode is undefined", () => {+ const result = normalizeAppriseConfig({ mode: undefined });+ expect(result.mode).toBe('cli');+ });++ it("returns 'cli' for an unrecognized mode string (false arm of strict equality)", () => {+ // 'mailto' is a real Apprise schema but not 'http'; the normalizer+ // collapses anything non-'http' to 'cli'. Cast because AppriseConfig+ // constrains mode to 'cli' | 'http'.+ const malformed = { mode: 'mailto' } as unknown as Parameters<+ typeof normalizeAppriseConfig+ >[0];+ const result = normalizeAppriseConfig(malformed);+ expect(result.mode).toBe('cli');+ });+ });++ // -----------------------------------------------------------------------+ // config?.cliPath || 'apprise' (and the same || pattern for the four+ // other scalar string fields). The || operator treats '' as falsy, so+ // an empty string and undefined both hit the right arm.+ // -----------------------------------------------------------------------+ describe("scalar string '||' fallbacks", () => {+ it("falls back cliPath to 'apprise' when empty or undefined", () => {+ expect(normalizeAppriseConfig({ cliPath: '' }).cliPath).toBe('apprise');+ expect(normalizeAppriseConfig({ cliPath: undefined }).cliPath).toBe('apprise');+ });++ it('forwards a custom cliPath verbatim', () => {+ expect(normalizeAppriseConfig({ cliPath: '/usr/local/bin/apprise' }).cliPath).toBe(+ '/usr/local/bin/apprise',+ );+ });++ it("falls back serverUrl to '' when empty or undefined", () => {+ expect(normalizeAppriseConfig({ serverUrl: '' }).serverUrl).toBe('');+ expect(normalizeAppriseConfig({ serverUrl: undefined }).serverUrl).toBe('');+ });++ it('forwards a custom serverUrl verbatim', () => {+ expect(normalizeAppriseConfig({ serverUrl: 'https://apprise.test' }).serverUrl).toBe(+ 'https://apprise.test',+ );+ });++ it("falls back configKey to '' when empty or undefined", () => {+ expect(normalizeAppriseConfig({ configKey: '' }).configKey).toBe('');+ expect(normalizeAppriseConfig({ configKey: undefined }).configKey).toBe('');+ });++ it('forwards a custom configKey verbatim', () => {+ expect(normalizeAppriseConfig({ configKey: 'primary' }).configKey).toBe('primary');+ });++ it("falls back apiKey to '' when empty or undefined", () => {+ expect(normalizeAppriseConfig({ apiKey: '' }).apiKey).toBe('');+ expect(normalizeAppriseConfig({ apiKey: undefined }).apiKey).toBe('');+ });++ it('forwards a custom apiKey verbatim', () => {+ expect(normalizeAppriseConfig({ apiKey: fakeKey }).apiKey).toBe(fakeKey);+ });++ it("falls back apiKeyHeader to 'X-API-KEY' when empty or undefined", () => {+ expect(normalizeAppriseConfig({ apiKeyHeader: '' }).apiKeyHeader).toBe('X-API-KEY');+ expect(normalizeAppriseConfig({ apiKeyHeader: undefined }).apiKeyHeader).toBe(+ 'X-API-KEY',+ );+ });++ it('forwards a custom apiKeyHeader verbatim', () => {+ expect(+ normalizeAppriseConfig({ apiKeyHeader: 'Authorization' }).apiKeyHeader,+ ).toBe('Authorization');+ });+ });++ // -----------------------------------------------------------------------+ // typeof config?.timeoutSeconds === 'number' && config.timeoutSeconds > 0+ // - guard true arm: positive number → forwarded+ // - guard false arm: non-number, 0, negative, NaN, Infinity(? — >0 is+ // true for Infinity, typeof number true, so Infinity IS forwarded),+ // undefined, empty string.+ // Note: Infinity is a number > 0 and passes the guard — pin this+ // surprising behaviour down so it cannot change silently.+ // -----------------------------------------------------------------------+ describe('timeoutSeconds guard', () => {+ it('forwards a positive integer', () => {+ expect(normalizeAppriseConfig({ timeoutSeconds: 30 }).timeoutSeconds).toBe(30);+ });++ it('forwards a positive fractional value', () => {+ expect(normalizeAppriseConfig({ timeoutSeconds: 0.5 }).timeoutSeconds).toBe(0.5);+ });++ it('falls back to 15 for zero (boundary: not > 0)', () => {+ expect(normalizeAppriseConfig({ timeoutSeconds: 0 }).timeoutSeconds).toBe(15);+ });++ it('falls back to 15 for a negative number', () => {+ expect(normalizeAppriseConfig({ timeoutSeconds: -5 }).timeoutSeconds).toBe(15);+ });++ it('falls back to 15 for NaN (typeof number but not > 0)', () => {+ const malformed = { timeoutSeconds: Number.NaN } as Partial<AppriseConfig>;+ expect(normalizeAppriseConfig(malformed).timeoutSeconds).toBe(15);+ });++ it('falls back to 15 for a non-number value', () => {+ const malformed = { timeoutSeconds: '30' } as unknown as Parameters<+ typeof normalizeAppriseConfig+ >[0];+ expect(normalizeAppriseConfig(malformed).timeoutSeconds).toBe(15);+ });++ it('falls back to 15 when undefined', () => {+ expect(normalizeAppriseConfig({ timeoutSeconds: undefined }).timeoutSeconds).toBe(15);+ });++ it('surprisingly forwards Infinity because typeof Infinity === "number" and Infinity > 0', () => {+ // Documents current behaviour: the guard checks typeof and > 0 but+ // not Number.isFinite, so Infinity leaks through. Pinned, not fixed.+ const malformed = { timeoutSeconds: Number.POSITIVE_INFINITY } as Partial<AppriseConfig>;+ expect(normalizeAppriseConfig(malformed).timeoutSeconds).toBe(+ Number.POSITIVE_INFINITY,+ );+ });+ });++ // -----------------------------------------------------------------------+ // Boolean(config?.skipTlsVerify)+ // - undefined / false → false+ // - true → true+ // - truthy non-bool → true (defensive: API may return 0/1 or a+ // string before strict typing lands)+ // - falsy non-bool → false+ // -----------------------------------------------------------------------+ describe('skipTlsVerify Boolean() coercion', () => {+ it('coerces undefined to false', () => {+ expect(normalizeAppriseConfig({ skipTlsVerify: undefined }).skipTlsVerify).toBe(false);+ });++ it('preserves an explicit false', () => {+ expect(normalizeAppriseConfig({ skipTlsVerify: false }).skipTlsVerify).toBe(false);+ });++ it('preserves an explicit true', () => {+ expect(normalizeAppriseConfig({ skipTlsVerify: true }).skipTlsVerify).toBe(true);+ });++ it('coerces a truthy non-boolean (1) to true', () => {+ const malformed = { skipTlsVerify: 1 } as unknown as Parameters<+ typeof normalizeAppriseConfig+ >[0];+ expect(normalizeAppriseConfig(malformed).skipTlsVerify).toBe(true);+ });++ it('coerces a falsy non-boolean (0) to false', () => {+ const malformed = { skipTlsVerify: 0 } as unknown as Parameters<+ typeof normalizeAppriseConfig+ >[0];+ expect(normalizeAppriseConfig(malformed).skipTlsVerify).toBe(false);+ });+ });++ // -----------------------------------------------------------------------+ // formatAppriseTargets(config?.targets)+ // helper: targets && targets.length > 0 ? targets.join('\n') : ''+ // - undefined → ''+ // - null → ''+ // - [] → ''+ // - ['a'] → 'a'+ // - ['a','b'] → 'a\nb'+ // -----------------------------------------------------------------------+ describe('targets → targetsText via formatAppriseTargets', () => {+ it("returns '' when targets is undefined", () => {+ expect(normalizeAppriseConfig({ targets: undefined }).targetsText).toBe('');+ });++ it("returns '' when targets is null", () => {+ const withNull = { targets: null } as unknown as Partial<AppriseConfig>;+ expect(normalizeAppriseConfig(withNull).targetsText).toBe('');+ });++ it("returns '' when targets is an empty array", () => {+ expect(normalizeAppriseConfig({ targets: [] }).targetsText).toBe('');+ });++ it("joins a single target without a trailing newline", () => {+ expect(+ normalizeAppriseConfig({ targets: ['mailto://[email protected]'] }).targetsText,+ ).toBe('mailto://[email protected]');+ });++ it("joins multiple targets with '\\n'", () => {+ expect(+ normalizeAppriseConfig({+ targets: ['mailto://[email protected]', 'tgram://bot/123'],+ }).targetsText,+ ).toBe('mailto://[email protected]\ntgram://bot/123');+ });+ });++ // -----------------------------------------------------------------------+ // Whole-object contract: feeding null / undefined must produce exactly the+ // createDefaultAppriseConfig() shape — every fallback arm firing at once.+ // -----------------------------------------------------------------------+ describe('whole-object defaults', () => {+ const expectedDefault: UIAppriseConfig = {+ enabled: false,+ mode: 'cli',+ targetsText: '',+ cliPath: 'apprise',+ timeoutSeconds: 15,+ serverUrl: '',+ configKey: '',+ apiKey: '',+ apiKeyHeader: 'X-API-KEY',+ skipTlsVerify: false,+ };++ it('returns the exact default shape for null input', () => {+ expect(normalizeAppriseConfig(null)).toStrictEqual(expectedDefault);+ });++ it('returns the exact default shape for undefined input', () => {+ expect(normalizeAppriseConfig(undefined)).toStrictEqual(expectedDefault);+ });++ it('returns the exact default shape for an empty object', () => {+ expect(normalizeAppriseConfig({})).toStrictEqual(expectedDefault);+ });+ });+});++describe('buildAppriseConfigPayload — branch coverage (0713)', () => {+ // -----------------------------------------------------------------------+ // config.mode passthrough — both union arms forwarded unchanged.+ // -----------------------------------------------------------------------+ describe('mode passthrough', () => {+ it("forwards mode 'http' unchanged", () => {+ expect(buildAppriseConfigPayload(makeUIAppriseConfig({ mode: 'http' })).mode).toBe(+ 'http',+ );+ });++ it("forwards mode 'cli' unchanged", () => {+ expect(buildAppriseConfigPayload(makeUIAppriseConfig({ mode: 'cli' })).mode).toBe(+ 'cli',+ );+ });+ });++ // -----------------------------------------------------------------------+ // config.enabled / config.skipTlsVerify passthrough — boolean forwarded+ // as-is (no coercion happens on the way out; that already happened on the+ // way in via normalizeAppriseConfig).+ // -----------------------------------------------------------------------+ describe('boolean passthrough', () => {+ it('forwards enabled true', () => {+ expect(buildAppriseConfigPayload(makeUIAppriseConfig({ enabled: true })).enabled).toBe(+ true,+ );+ });++ it('forwards enabled false', () => {+ expect(+ buildAppriseConfigPayload(makeUIAppriseConfig({ enabled: false })).enabled,+ ).toBe(false);+ });++ it('forwards skipTlsVerify true', () => {+ expect(+ buildAppriseConfigPayload(makeUIAppriseConfig({ skipTlsVerify: true }))+ .skipTlsVerify,+ ).toBe(true);+ });++ it('forwards skipTlsVerify false', () => {+ expect(+ buildAppriseConfigPayload(makeUIAppriseConfig({ skipTlsVerify: false }))+ .skipTlsVerify,+ ).toBe(false);+ });+ });++ // -----------------------------------------------------------------------+ // parseAppriseTargets(config.targetsText)+ // value.split(/\r?\n|,/).map(trim).filter(len>0 && firstOccurrence)+ // - empty / whitespace-only → []+ // - single line → [line]+ // - \n separated → split+ // - \r\n separated → split (the optional \r arm of the regex)+ // - comma separated → split+ // - mixed \n + , → split on both+ // - empty entries from adjacent separators → filtered+ // - leading/trailing whitespace per entry → trimmed+ // - duplicate entries after trim → deduped (first wins)+ // -----------------------------------------------------------------------+ describe('targetsText → targets via parseAppriseTargets', () => {+ it('returns [] for an empty targetsText', () => {+ expect(buildAppriseConfigPayload(makeUIAppriseConfig({ targetsText: '' })).targets).toStrictEqual([]);+ });++ it('returns [] for a whitespace-only targetsText (filtered after trim)', () => {+ expect(+ buildAppriseConfigPayload(makeUIAppriseConfig({ targetsText: ' \n ,' }))+ .targets,+ ).toStrictEqual([]);+ });++ it('returns a single-element array for a one-line targetsText', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({ targetsText: 'mailto://[email protected]' }),+ ).targets,+ ).toStrictEqual(['mailto://[email protected]']);+ });++ it('splits on bare-LF newlines', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({ targetsText: '[email protected]\[email protected]' }),+ ).targets,+ ).toStrictEqual(['[email protected]', '[email protected]']);+ });++ it('splits on CRLF newlines (exercises the optional \\r arm of /\\r?\\n/)', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({ targetsText: '[email protected]\r\[email protected]' }),+ ).targets,+ ).toStrictEqual(['[email protected]', '[email protected]']);+ });++ it('splits on commas', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({ targetsText: '[email protected],[email protected]' }),+ ).targets,+ ).toStrictEqual(['[email protected]', '[email protected]']);+ });++ it('splits on a mixture of newlines and commas', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({+ }),+ ).targets,+ });++ it('drops entries produced by adjacent/leading/trailing separators', () => {+ // Leading newline, trailing comma, double comma, blank line — all+ // yield empty trimmed entries that the filter removes.+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({+ }),+ ).targets,+ });++ it('trims whitespace around each entry before filtering', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({+ targetsText: ' [email protected] , \[email protected]\t',+ }),+ ).targets,+ ).toStrictEqual(['[email protected]', '[email protected]']);+ });++ it('dedupes identical entries after trimming, keeping the first occurrence', () => {+ // The two literal duplicates and the padded duplicate all trim to the+ // same string; only the first is kept.+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({+ }),+ ).targets,+ ).toStrictEqual(['[email protected]']);+ });++ it('treats differently-cased entries as distinct (no lowercasing)', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({ targetsText: '[email protected],[email protected]' }),+ ).targets,+ ).toStrictEqual(['[email protected]', '[email protected]']);+ });++ it('preserves internal whitespace within an entry (trim is ends-only)', () => {+ expect(+ buildAppriseConfigPayload(+ makeUIAppriseConfig({ targetsText: 'a [email protected]' }),+ ).targets,+ ).toStrictEqual(['a [email protected]']);+ });+ });++ // -----------------------------------------------------------------------+ // Scalar string/number passthrough — every remaining field is forwarded+ // verbatim. Drive each with a non-default, non-empty value (and the+ // boundary timeoutSeconds: 0) so the assertion cannot pass against the+ // fixture default by accident.+ // -----------------------------------------------------------------------+ describe('scalar passthrough', () => {+ it('forwards cliPath, serverUrl, configKey, apiKeyHeader verbatim', () => {+ const result = buildAppriseConfigPayload(+ makeUIAppriseConfig({+ cliPath: '/usr/local/bin/apprise',+ serverUrl: 'https://apprise.test',+ configKey: 'primary',+ apiKey: fakeKey,+ apiKeyHeader: 'Authorization',+ }),+ );+ expect(result.cliPath).toBe('/usr/local/bin/apprise');+ expect(result.serverUrl).toBe('https://apprise.test');+ expect(result.configKey).toBe('primary');+ expect(result.apiKey).toBe(fakeKey);+ expect(result.apiKeyHeader).toBe('Authorization');+ });++ it('forwards a positive timeoutSeconds verbatim', () => {+ expect(+ buildAppriseConfigPayload(makeUIAppriseConfig({ timeoutSeconds: 45 }))+ .timeoutSeconds,+ ).toBe(45);+ });++ it('forwards timeoutSeconds = 0 verbatim (no clamping on the way out)', () => {+ // buildAppriseConfigPayload performs no guard on timeoutSeconds —+ // the inbound normalizeAppriseConfig guard is the only place 0 is+ // rewritten. Pin this so a future clamp here would be noticed.+ expect(+ buildAppriseConfigPayload(makeUIAppriseConfig({ timeoutSeconds: 0 }))+ .timeoutSeconds,+ ).toBe(0);+ });+ });++ // -----------------------------------------------------------------------+ // Output contract — exact key set in declaration order. Catches any+ // future field added to UIAppriseConfig that fails to be forwarded, and+ // catches UI-only fields (targetsText) leaking into the API payload.+ // -----------------------------------------------------------------------+ describe('payload contract — exact key set', () => {+ it('emits exactly the 10 AppriseConfig keys and omits targetsText', () => {+ const result = buildAppriseConfigPayload(+ makeUIAppriseConfig({+ enabled: true,+ mode: 'http',+ targetsText: '[email protected]\[email protected]',+ cliPath: '/usr/bin/apprise',+ timeoutSeconds: 20,+ serverUrl: 'https://apprise.test',+ configKey: 'primary',+ apiKey: fakeKey,+ apiKeyHeader: 'X-API-KEY',+ skipTlsVerify: false,+ }),+ );+ expect(Object.keys(result)).toStrictEqual([+ 'enabled',+ 'mode',+ 'targets',+ 'cliPath',+ 'timeoutSeconds',+ 'serverUrl',+ 'configKey',+ 'apiKey',+ 'apiKeyHeader',+ 'skipTlsVerify',+ ]);+ expect(result).not.toHaveProperty('targetsText');+ });++ it('matches the exact AppriseConfig payload for a fully-populated input', () => {+ const result = buildAppriseConfigPayload(+ makeUIAppriseConfig({+ enabled: true,+ mode: 'http',+ targetsText: ' [email protected] , [email protected] ',+ cliPath: '/usr/bin/apprise',+ timeoutSeconds: 20,+ serverUrl: 'https://apprise.test',+ configKey: 'primary',+ apiKey: fakeKey,+ apiKeyHeader: 'X-API-KEY',+ skipTlsVerify: true,+ }),+ );+ expect(result).toStrictEqual({+ enabled: true,+ mode: 'http',+ targets: ['[email protected]', '[email protected]'],+ cliPath: '/usr/bin/apprise',+ timeoutSeconds: 20,+ serverUrl: 'https://apprise.test',+ configKey: 'primary',+ apiKey: fakeKey,+ apiKeyHeader: 'X-API-KEY',+ skipTlsVerify: true,+ });+ });+ });+});++// ---------------------------------------------------------------------------+// buildEmailConfigPayload — focused additions only.+// The sibling suites `branchcov0712` and `branchcov0712c` already exhaust+// the `to.map(trim)` / `to.filter(length>0)` arms, scalar passthrough for+// port/password/from/server/enabled/tls/startTLS/provider, the exact key+// set, and the malformed non-string entry. This block adds the few+// passthrough arms they leave open: `username` (empty + custom) and a+// realistic long credential-shaped password (the existing suites only use+// 'secret' or ''). No assertions are duplicated.+// ---------------------------------------------------------------------------+describe('buildEmailConfigPayload — branch coverage additions (0713)', () => {+ describe('username passthrough', () => {+ it('forwards an empty username unchanged', () => {+ const result = buildEmailConfigPayload(makeUIEmailConfig({ username: '' }));+ expect(result.username).toBe('');+ });++ it('forwards a custom username unchanged', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ username: 'svc-account@internal' }),+ );+ expect(result.username).toBe('svc-account@internal');+ });+ });++ describe('password passthrough with a realistic credential', () => {+ it('forwards a long token-shaped password verbatim and preserves it in the exact payload', () => {+ const password = `Bearer ${fakeToken}`;+ const result = buildEmailConfigPayload(makeUIEmailConfig({ password }));+ expect(result.password).toBe(password);+ // Confirm the long credential survives alongside a normal recipient+ // list — exercises the full payload build, not just one getter.+ expect(result).toStrictEqual({+ enabled: true,+ provider: 'smtp',+ server: 'smtp.internal',+ port: 587,+ username: '[email protected]',+ password,+ from: '[email protected]',+ to: ['[email protected]'],+ tls: true,+ startTLS: true,+ });+ });+ });+});diff --git a/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov0713.test.ts b/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov0713.test.tsnew file mode 100644index 0000000000..cf4ab896e3--- /dev/null+++ b/frontend-modern/src/features/alerts/__tests__/alertHistoryModel.branchcov0713.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from 'vitest';++import {+ MS_PER_HOUR,+ buildAlertAxisTicks,+ filterAlertHistoryItems,+ type AlertTrendSeries,+ type HistoryItem,+} from '../alertHistoryModel';++// ---------------------------------------------------------------------------+// Shared fixture — mirrors the shape used by the sibling branchcov suites so+// resource-type resolution and field access exercise the same paths the UI+// triggers. Only the fields under test are overridden per case.+// ---------------------------------------------------------------------------++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,+ };+}++// ---------------------------------------------------------------------------+// filterAlertHistoryItems — the only uncovered branch in the whole module for+// this function is the optional-chaining short-circuit on+// `item.resourceName?.toLowerCase()` (line 248). Every sibling test supplies a+// defined resourceName, so the `?.` never short-circuits and the trailing+// `?? ''` fallback is reached only via the (always-defined) toLowerCase result.+// Feeding items whose resourceName is nullish exercises the short-circuit arm+// and confirms the downstream `?? ''` keeps the matcher crash-free.+// ---------------------------------------------------------------------------++describe('filterAlertHistoryItems — resourceName optional-chaining arm', () => {+ it('short-circuits to "" for an undefined resourceName and still matches on the other fields', () => {+ const item = makeItem({+ id: 'no-name',+ resourceName: undefined,+ title: 'Disk Full',+ description: 'storage at 95%',+ node: 'px2',+ });++ // A term that only a (missing) resourceName could satisfy matches nothing,+ // proving the short-circuit yields "" rather than throwing.+ expect(filterAlertHistoryItems([item], 'all', 'vm-101')).toHaveLength(0);++ // Terms against the still-defined fields continue to match.+ expect(filterAlertHistoryItems([item], 'all', 'disk')).toHaveLength(1);+ expect(filterAlertHistoryItems([item], 'all', 'storage')).toHaveLength(1);+ expect(filterAlertHistoryItems([item], 'all', 'px2')).toHaveLength(1);++ // Unfiltered pass-through is unaffected.+ expect(filterAlertHistoryItems([item], 'all', '')).toHaveLength(1);+ });++ it('short-circuits identically for a null resourceName (null is nullish for ?.)', () => {+ const item = makeItem({+ id: 'null-name',+ resourceName: null as unknown as string,+ title: 'Memory',+ node: 'px9',+ });++ expect(filterAlertHistoryItems([item], 'all', 'memory')).toHaveLength(1);+ // A resourceName-shaped term cannot match because the field is nullish.+ expect(filterAlertHistoryItems([item], 'all', 'null-name')).toHaveLength(0);+ expect(filterAlertHistoryItems([item], 'all', 'whatever')).toHaveLength(0);+ });++ it('drops a row whose only populated searchable field is a nullish resourceName', () => {+ // resourceName nullish, every other searchable field blank/undefined.+ const item = makeItem({+ id: 'name-only',+ resourceName: undefined,+ title: '',+ description: '',+ node: '',+ });+ expect(filterAlertHistoryItems([item], 'all', 'name-only')).toHaveLength(0);+ expect(filterAlertHistoryItems([item], 'all', '')).toHaveLength(1);+ });+});++// ---------------------------------------------------------------------------+// buildAlertAxisTicks — two reachable uncovered branches remain here:+//+// 1. line 558 `trends.rangeHours ?? bucketHours`+// The `?? bucketHours` fallback is never taken because every sibling+// test (and the buildAlertTrends helper) always sets rangeHours to a+// concrete number. Forcing rangeHours to a nullish value exercises the+// fallback so totalHours resolves to bucketHours.+//+// 2. line 571 `(totalDurationMs || 1)`+// This defensive divisor is unreachable for any finite bucketSize > 0:+// the guard at line 553 already returns [] when bucketSize <= 0, and with+// a positive bucketSize the Math.max on lines 560-563 is strictly+// positive. It can only be engaged by a malformed (NaN) bucketSize,+// which slips past the `<= 0` guard because `NaN <= 0 === false`, making+// totalDurationMs = NaN (falsy) and forcing the `|| 1` arm.+//+// (The `unshift` first-tick arm at line 583 is genuinely dead code — see+// GLM_REPORT.md — and is not exercised here.)+// ---------------------------------------------------------------------------++describe('buildAlertAxisTicks — rangeHours ?? bucketHours fallback', () => {+ it('resolves totalHours to bucketHours when rangeHours is undefined', () => {+ const start = Date.UTC(2026, 2, 22, 0, 0, 0);+ const trends = {+ buckets: [0, 0],+ max: 1,+ bucketSize: 6,+ bucketTimes: [start, start + 6 * MS_PER_HOUR],+ rangeStart: start,+ rangeHours: undefined,+ } as unknown as AlertTrendSeries;++ const ticks = buildAlertAxisTicks(trends, 'en-US');++ // Structural invariants hold regardless of the fallback.+ expect(ticks.length).toBeGreaterThanOrEqual(2);+ expect(ticks[0].position).toBe(0);+ expect(ticks[0].align).toBe('start');+ expect(ticks[ticks.length - 1].position).toBe(1);+ expect(ticks[ticks.length - 1].align).toBe('end');++ // totalHours resolved to bucketHours=6 (<= 48) so the short-range+ // formatter is selected and every label is a non-empty string.+ for (const tick of ticks) {+ expect(typeof tick.label).toBe('string');+ expect(tick.label.length).toBeGreaterThan(0);+ }+ });++ it('resolves totalHours to bucketHours when rangeHours is null (null is nullish)', () => {+ const start = Date.UTC(2026, 2, 22, 0, 0, 0);+ const trends = {+ buckets: [0],+ max: 1,+ bucketSize: 24,+ bucketTimes: [start],+ rangeStart: start,+ rangeHours: null,+ } as unknown as AlertTrendSeries;++ const ticks = buildAlertAxisTicks(trends, 'en-US');++ // totalHours = (null ?? 24) = 24 → still within the short-range tier.+ expect(ticks[0].position).toBe(0);+ expect(ticks[ticks.length - 1].position).toBe(1);+ expect(ticks[0].label.length).toBeGreaterThan(0);+ });+});++describe('buildAlertAxisTicks — (totalDurationMs || 1) defensive divisor', () => {+ it('engages the || 1 fallback when a malformed NaN bucketSize makes totalDurationMs falsy', () => {+ const start = Date.UTC(2026, 2, 22, 0, 0, 0);+ // bucketSize = NaN bypasses the `bucketSize <= 0` guard (NaN <= 0 is false),+ // so totalDurationMs = Math.max(buckets.length * NaN * MS, NaN * MS) = NaN,+ // which is falsy and forces the `|| 1` divisor on line 571. rangeHours is+ // also nullish so line 558's `?? bucketHours` fallback engages too.+ const trends = {+ buckets: [0],+ max: 1,+ bucketSize: Number.NaN,+ bucketTimes: [start],+ rangeStart: start,+ rangeHours: undefined,+ } as unknown as AlertTrendSeries;++ const ticks = buildAlertAxisTicks(trends, 'en-US');++ // Despite the malformed input, positions stay clamped within [0, 1] and+ // the start/end anchors are still emitted.+ expect(ticks.length).toBeGreaterThanOrEqual(2);+ expect(ticks[0].position).toBe(0);+ expect(ticks[ticks.length - 1].position).toBe(1);++ // The end-tick timestamp is `start + NaN` = NaN; formatAlertAxisTickLabel+ // returns the em-dash placeholder for any non-finite timestamp, proving+ // the NaN propagated through the `|| 1` divisor rather than throwing.+ expect(ticks[ticks.length - 1].label).toBe('—');+ });+});diff --git a/frontend-modern/src/features/storageBackups/__tests__/storagePoolRowPresentation.branchcov0713.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storagePoolRowPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..f40ece44ac--- /dev/null+++ b/frontend-modern/src/features/storageBackups/__tests__/storagePoolRowPresentation.branchcov0713.test.ts@@ -0,0 +1,210 @@+import { describe, expect, it } from 'vitest';+import type { StorageCapacityDeltaPresentation } from '@/features/storageBackups/storageCapacityDeltaPresentation';+import type { StorageRecord } from '@/features/storageBackups/models';+import {+ buildStoragePoolRowModel,+ STORAGE_POOL_ROW_PLACEHOLDER_CLASS,+} from '@/features/storageBackups/storagePoolRowPresentation';++// Branch-coverage extension for `buildStoragePoolRowModel`.+//+// The sibling `storagePoolRowPresentation.test.ts` already pins the happy path+// (truthy capacity bytes, non-null capacityDelta, delegate-field wiring). This+// file targets ONLY the local branches inside `buildStoragePoolRowModel` that+// the happy path leaves unexecuted:+//+// totalBytes = record.capacity.totalBytes || 0 // `|| 0` falsy arm+// usedBytes = record.capacity.usedBytes || 0 // `|| 0` falsy arm+// freeBytes = record.capacity.freeBytes+// ?? (totalBytes > 0 // ternary true/false arms+// ? Math.max(totalBytes - usedBytes, 0) // Math.max arms+// : 0)+// capacityDeltaLabel: capacityDelta?.label ?? '—'+// capacityDeltaTitle: capacityDelta?.title ?? 'No used-capacity change...'+// capacityDeltaToneClass: capacityDelta?.toneClass ?? STORAGE_POOL_ROW_PLACEHOLDER_CLASS+//+// Minimal, fully-valid base record. The delegate helpers produce deterministic+// values for this base (zfsPool=null, hostLabel=location.label, topologyLabel=+// category, stateLabel='Available', etc.); those delegate branches are owned by+// rowPresentation / recordPresentation and are not re-tested here. We assert+// only the capacity-coercion and capacityDelta-defaulting outputs.++const baseRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord =>+ ({+ id: 'storage-1',+ name: 'tank',+ source: {+ platform: 'proxmox-pbs',+ family: 'onprem',+ origin: 'resource',+ adapterId: 'pbs-1',+ },+ category: 'pool',+ health: 'healthy',+ location: { label: 'pbs01', scope: 'host' },+ capacity: { totalBytes: 1000, usedBytes: 400, freeBytes: 600, usagePercent: 40 },+ capabilities: [],+ observedAt: 0,+ refs: {},+ ...overrides,+ }) as StorageRecord;++// ---------------------------------------------------------------------------+// capacity bytes coercion: `record.capacity.totalBytes || 0` and `usedBytes || 0`+// ---------------------------------------------------------------------------++describe('buildStoragePoolRowModel branch coverage — capacity byte coercion', () => {+ it('coerces null capacity bytes to 0 via the `|| 0` falsy arms', () => {+ const record = baseRecord({+ capacity: { totalBytes: null, usedBytes: null, freeBytes: null, usagePercent: null },+ });+ const model = buildStoragePoolRowModel(record);+ expect(model.totalBytes).toBe(0);+ expect(model.usedBytes).toBe(0);+ // freeBytes null -> `??` right arm; totalBytes(coerced 0) > 0 is false ->+ // ternary false arm -> literal 0 (NOT Math.max(0-0, 0)).+ expect(model.freeBytes).toBe(0);+ });++ it('coerces zero capacity bytes to 0 via the `|| 0` falsy arms (0 is falsy)', () => {+ // totalBytes: 0 is falsy, so `0 || 0` -> 0. Same for usedBytes. This is a+ // distinct input from null but exercises the same `|| 0` branch; pinning it+ // documents that the boundary value 0 is treated identically to null.+ const record = baseRecord({+ capacity: { totalBytes: 0, usedBytes: 0, freeBytes: 0, usagePercent: 0 },+ });+ const model = buildStoragePoolRowModel(record);+ expect(model.totalBytes).toBe(0);+ expect(model.usedBytes).toBe(0);+ // freeBytes 0 is NOT null/undefined, so the `??` LEFT arm fires and returns+ // 0 verbatim (NOT the derived total-used path).+ expect(model.freeBytes).toBe(0);+ });++ it('preserves a truthy usedBytes while totalBytes is null (asymmetric coercion)', () => {+ const record = baseRecord({+ capacity: { totalBytes: null, usedBytes: 500, freeBytes: null, usagePercent: null },+ });+ const model = buildStoragePoolRowModel(record);+ expect(model.totalBytes).toBe(0); // null -> 0+ expect(model.usedBytes).toBe(500); // truthy, preserved+ // totalBytes(coerced 0) > 0 false -> ternary false arm -> 0.+ expect(model.freeBytes).toBe(0);+ });+});++// ---------------------------------------------------------------------------+// freeBytes derivation: `freeBytes ?? (totalBytes > 0 ? Math.max(...) : 0)`+// ---------------------------------------------------------------------------++describe('buildStoragePoolRowModel branch coverage — freeBytes derivation', () => {+ it('uses the explicit freeBytes when present (`??` left arm), ignoring total-used', () => {+ const record = baseRecord({+ capacity: { totalBytes: 1000, usedBytes: 400, freeBytes: 500, usagePercent: 40 },+ });+ const model = buildStoragePoolRowModel(record);+ // total-used would be 600, but the explicit 500 wins via the `??` left arm.+ expect(model.freeBytes).toBe(500);+ expect(model.totalBytes).toBe(1000);+ expect(model.usedBytes).toBe(400);+ });++ it('derives freeBytes from total-used when freeBytes is null and the diff is positive (Math.max first-arg arm)', () => {+ const record = baseRecord({+ capacity: { totalBytes: 1000, usedBytes: 250, freeBytes: null, usagePercent: 25 },+ });+ const model = buildStoragePoolRowModel(record);+ // totalBytes 1000 > 0 -> ternary true arm -> Math.max(1000-250, 0) = 750.+ expect(model.freeBytes).toBe(750);+ });++ it('clamps freeBytes to 0 when usedBytes exceeds totalBytes (Math.max second-arg arm)', () => {+ const record = baseRecord({+ capacity: { totalBytes: 100, usedBytes: 250, freeBytes: null, usagePercent: null },+ });+ const model = buildStoragePoolRowModel(record);+ // totalBytes 100 > 0 -> ternary true arm -> Math.max(100-250, 0) = Math.max(-150, 0) = 0.+ expect(model.freeBytes).toBe(0);+ expect(model.totalBytes).toBe(100);+ expect(model.usedBytes).toBe(250);+ });++ it('returns 0 freeBytes at the diff===0 boundary (usedBytes === totalBytes, freeBytes null)', () => {+ const record = baseRecord({+ capacity: { totalBytes: 1000, usedBytes: 1000, freeBytes: null, usagePercent: 100 },+ });+ const model = buildStoragePoolRowModel(record);+ // Math.max(0, 0) = 0; both args equal, first-arg arm returns 0.+ expect(model.freeBytes).toBe(0);+ });++ it('short-circuits to 0 via the `totalBytes > 0` false arm when totalBytes coerces from null, even if usedBytes is huge', () => {+ // totalBytes null -> coerced 0 -> `0 > 0` false -> ternary false arm -> 0.+ // Pinning that the guard prevents entering the Math.max clamp path at all,+ // which matters because Math.max(0-10000, 0) would also yield 0 — the OUTPUT+ // is identical but the BRANCH is distinct.+ const record = baseRecord({+ capacity: { totalBytes: null, usedBytes: 10_000, freeBytes: null, usagePercent: null },+ });+ const model = buildStoragePoolRowModel(record);+ expect(model.freeBytes).toBe(0);+ });+});++// ---------------------------------------------------------------------------+// capacityDelta defaulting: `capacityDelta?.X ?? <default>`+// ---------------------------------------------------------------------------++describe('buildStoragePoolRowModel branch coverage — capacityDelta default branches', () => {+ it('applies the default capacityDelta fields when capacityDelta is explicitly null', () => {+ const model = buildStoragePoolRowModel(baseRecord(), null);+ expect(model.capacityDeltaLabel).toBe('—');+ expect(model.capacityDeltaTitle).toBe('No used-capacity change history available.');+ expect(model.capacityDeltaToneClass).toBe(STORAGE_POOL_ROW_PLACEHOLDER_CLASS);+ });++ it('applies the default capacityDelta fields when capacityDelta is omitted (default parameter)', () => {+ const model = buildStoragePoolRowModel(baseRecord());+ expect(model.capacityDeltaLabel).toBe('—');+ expect(model.capacityDeltaTitle).toBe('No used-capacity change history available.');+ expect(model.capacityDeltaToneClass).toBe(STORAGE_POOL_ROW_PLACEHOLDER_CLASS);+ });++ it('treats an explicitly-passed undefined capacityDelta as the default null (default parameter fires)', () => {+ // The signature `capacityDelta: StorageCapacityDeltaPresentation | null = null`+ // makes the parameter optional, so `undefined` activates the `= null` default.+ const model = buildStoragePoolRowModel(baseRecord(), undefined);+ expect(model.capacityDeltaLabel).toBe('—');+ expect(model.capacityDeltaTitle).toBe('No used-capacity change history available.');+ expect(model.capacityDeltaToneClass).toBe(STORAGE_POOL_ROW_PLACEHOLDER_CLASS);+ });++ it('passes through a shrinking capacityDelta (negative deltaBytes) label/title/toneClass', () => {+ const delta: StorageCapacityDeltaPresentation = {+ deltaBytes: -20 * 1024 * 1024 * 1024,+ label: '-20.00 GB',+ title: 'Used capacity shrank by 20.00 GB over 24h.',+ toneClass: 'text-emerald-600 dark:text-emerald-300',+ };+ const model = buildStoragePoolRowModel(baseRecord(), delta);+ expect(model.capacityDeltaLabel).toBe('-20.00 GB');+ expect(model.capacityDeltaTitle).toBe('Used capacity shrank by 20.00 GB over 24h.');+ expect(model.capacityDeltaToneClass).toBe('text-emerald-600 dark:text-emerald-300');+ });++ it('returns empty-string label/title/toneClass verbatim (`??` only defaults on null/undefined, not on "")', () => {+ // StorageCapacityDeltaPresentation declares these fields as `string`, so ''+ // is a fully-typed value — no cast needed. The `??` operator must NOT+ // substitute the defaults for empty strings.+ const delta: StorageCapacityDeltaPresentation = {+ deltaBytes: 0,+ label: '',+ title: '',+ toneClass: '',+ };+ const model = buildStoragePoolRowModel(baseRecord(), delta);+ expect(model.capacityDeltaLabel).toBe('');+ expect(model.capacityDeltaTitle).toBe('');+ expect(model.capacityDeltaToneClass).toBe('');+ });+});diff --git a/frontend-modern/src/utils/__tests__/agentCapabilityPresentation.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/agentCapabilityPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..de813ef227--- /dev/null+++ b/frontend-modern/src/utils/__tests__/agentCapabilityPresentation.branchcov0713.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest';++import {+ getAgentCapabilityBadgeClass,+ getAgentCapabilityLabel,+} from '@/utils/agentCapabilityPresentation';+import type { AgentCapability } from '@/utils/agentCapabilityPresentation';++// Full badge class strings are mirrored from the source module so assertions+// describe the documented Tailwind badge composition rather than echoing the+// function under test. These are the building blocks the module returns.+const PROXMOX_BADGE = 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-300';+const PBS_BADGE = 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-300';+const PMG_BADGE = 'bg-rose-100 text-rose-800 dark:bg-rose-900 dark:text-rose-300';+const TRUENAS_BADGE = 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-300';+const AVAILABILITY_BADGE = 'bg-sky-100 text-sky-800 dark:bg-sky-900 dark:text-sky-300';+const KUBERNETES_BADGE =+ 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-300';+const DEFAULT_BADGE = 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300';++describe('agentCapabilityPresentation branch coverage', () => {+ describe('getAgentCapabilityLabel', () => {+ // The sibling test already covers agent, docker, kubernetes, proxmox,+ // truenas and availability. These two cases close the remaining switch+ // arms that were previously uncovered.+ it('returns the canonical label for the pbs capability', () => {+ expect(getAgentCapabilityLabel('pbs')).toBe('PBS');+ });++ it('returns the canonical label for the pmg capability', () => {+ expect(getAgentCapabilityLabel('pmg')).toBe('PMG');+ });++ it('returns a distinct label for every member of the AgentCapability union', () => {+ const allCapabilities: AgentCapability[] = [+ 'agent',+ 'docker',+ 'kubernetes',+ 'proxmox',+ 'pbs',+ 'pmg',+ 'truenas',+ 'availability',+ ];+ const labels = new Set<string>();+ for (const capability of allCapabilities) {+ const label = getAgentCapabilityLabel(capability);+ expect(typeof label).toBe('string');+ expect(label.length).toBeGreaterThan(0);+ labels.add(label);+ }+ // Every capability must map to a unique, non-empty label.+ expect(labels.size).toBe(allCapabilities.length);+ });++ // The switch has no `default` clause, so a value outside the union (only+ // reachable at runtime via a cast) falls through every case and the+ // function implicitly returns undefined. This documents that runtime+ // behavior; the declared `string` return type is optimistic.+ it('returns undefined when an unrecognized value matches no switch case', () => {+ const unknown = 'not-a-real-capability' as unknown as AgentCapability;+ const result = getAgentCapabilityLabel(unknown);+ expect(result).toBeUndefined();+ });++ it('returns undefined for an empty string that matches no switch case', () => {+ const result = getAgentCapabilityLabel('' as unknown as AgentCapability);+ expect(result).toBeUndefined();+ });++ it('returns undefined for null coerced through the type layer', () => {+ const result = getAgentCapabilityLabel(null as unknown as AgentCapability);+ expect(result).toBeUndefined();+ });++ it('returns undefined for undefined coerced through the type layer', () => {+ const result = getAgentCapabilityLabel(undefined as unknown as AgentCapability);+ expect(result).toBeUndefined();+ });+ });++ describe('getAgentCapabilityBadgeClass', () => {+ // The sibling test covers proxmox, kubernetes, truenas, availability and+ // the default arm (via 'agent'). These cases close the remaining explicit+ // switch arms plus the other capability that routes to default.+ it('returns the orange-toned badge for the pbs capability', () => {+ expect(getAgentCapabilityBadgeClass('pbs')).toBe(PBS_BADGE);+ });++ it('returns the rose-toned badge for the pmg capability', () => {+ expect(getAgentCapabilityBadgeClass('pmg')).toBe(PMG_BADGE);+ });++ it('routes the docker capability to the default blue badge', () => {+ // 'docker' has no explicit case in the switch, so it must fall through to+ // the default arm rather than receiving a dedicated tone.+ expect(getAgentCapabilityBadgeClass('docker')).toBe(DEFAULT_BADGE);+ });++ it('returns the exact canonical badge class for every explicit switch arm', () => {+ expect(getAgentCapabilityBadgeClass('proxmox')).toBe(PROXMOX_BADGE);+ expect(getAgentCapabilityBadgeClass('pbs')).toBe(PBS_BADGE);+ expect(getAgentCapabilityBadgeClass('pmg')).toBe(PMG_BADGE);+ expect(getAgentCapabilityBadgeClass('truenas')).toBe(TRUENAS_BADGE);+ expect(getAgentCapabilityBadgeClass('availability')).toBe(AVAILABILITY_BADGE);+ expect(getAgentCapabilityBadgeClass('kubernetes')).toBe(KUBERNETES_BADGE);+ });++ it('routes both agent and docker capabilities to the same default badge tone', () => {+ // Neither 'agent' nor 'docker' has an explicit case; both must resolve to+ // the default arm and produce identical class strings.+ expect(getAgentCapabilityBadgeClass('agent')).toBe(DEFAULT_BADGE);+ expect(getAgentCapabilityBadgeClass('docker')).toBe(DEFAULT_BADGE);+ expect(getAgentCapabilityBadgeClass('agent')).toBe(getAgentCapabilityBadgeClass('docker'));+ });++ // The badge function DOES have a default clause, so unlike the label+ // function it always returns the default blue tone for any unrecognized+ // value rather than undefined.+ it('falls back to the default blue badge for an unrecognized value', () => {+ const unknown = 'not-a-real-capability' as unknown as AgentCapability;+ expect(getAgentCapabilityBadgeClass(unknown)).toBe(DEFAULT_BADGE);+ });++ it('falls back to the default blue badge for an empty string', () => {+ expect(getAgentCapabilityBadgeClass('' as unknown as AgentCapability)).toBe(DEFAULT_BADGE);+ });++ it('falls back to the default blue badge for null', () => {+ expect(getAgentCapabilityBadgeClass(null as unknown as AgentCapability)).toBe(DEFAULT_BADGE);+ });++ it('falls back to the default blue badge for undefined', () => {+ expect(getAgentCapabilityBadgeClass(undefined as unknown as AgentCapability)).toBe(+ DEFAULT_BADGE,+ );+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/auditLogPresentation.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/auditLogPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..83824973d9--- /dev/null+++ b/frontend-modern/src/utils/__tests__/auditLogPresentation.branchcov0713.test.ts@@ -0,0 +1,302 @@+import { describe, expect, it } from 'vitest';++import {+ type AuditVerificationStatus,+ getAuditEventStatusPresentation,+ getAuditEventTypeBadgeClass,+ getAuditLogEmptyState,+ getAuditLogFetchErrorMessage,+ getAuditLogFeatureGateCopy,+ getAuditLogLoadingState,+ getAuditVerificationBadgePresentation,+} from '@/utils/auditLogPresentation';++// Supplemental branch-coverage for `auditLogPresentation.ts`.+//+// `getAuditEventStatusPresentation` is already exhaustively covered by the+// sibling `auditLogPresentation.branchcov0712.test.ts` (both ternary arms,+// truthiness coercion, exact icon references, and enumerable-key shape), so it+// is intentionally not re-tested here. This file targets the remaining+// uncovered branches of the other six exported functions.++describe('getAuditEventTypeBadgeClass (branch coverage)', () => {+ it('matches known event types after trimming surrounding whitespace', () => {+ // Exercises the `(event ?? '').trim()` normalisation: padded input must+ // still resolve to the canonical case arm.+ expect(getAuditEventTypeBadgeClass(' login ')).toBe(+ 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',+ );+ expect(getAuditEventTypeBadgeClass('\tconfig_change\n')).toBe(+ 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',+ );+ expect(getAuditEventTypeBadgeClass(' startup ')).toBe(+ 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',+ );+ });++ it('routes the explicit oidc_token_refresh fallthrough case to the default badge', () => {+ // `case 'oidc_token_refresh':` has no body and falls through to default.+ expect(getAuditEventTypeBadgeClass('oidc_token_refresh')).toBe(+ 'bg-surface-alt text-base-content',+ );+ });++ it('routes an unrecognised event type through the default arm', () => {+ expect(getAuditEventTypeBadgeClass('something_new')).toBe(+ 'bg-surface-alt text-base-content',+ );+ });++ it('coerces undefined to an empty trimmed string and lands on the default arm', () => {+ expect(getAuditEventTypeBadgeClass(undefined)).toBe(+ 'bg-surface-alt text-base-content',+ );+ });++ it('honours the nullish-coalesce fallback for an explicit null argument', () => {+ // `(null ?? '').trim()` -> '' -> default case.+ expect(getAuditEventTypeBadgeClass(null)).toBe(+ 'bg-surface-alt text-base-content',+ );+ });++ it('treats whitespace-only input as empty after trimming', () => {+ expect(getAuditEventTypeBadgeClass(' ')).toBe(+ 'bg-surface-alt text-base-content',+ );+ });++ it('keeps the three coloured badges distinct from the default surface badge', () => {+ const login = getAuditEventTypeBadgeClass('login');+ const config = getAuditEventTypeBadgeClass('config_change');+ const startup = getAuditEventTypeBadgeClass('startup');+ const fallback = getAuditEventTypeBadgeClass('logout');+ expect(new Set([login, config, startup, fallback]).size).toBe(4);+ });+});++describe('getAuditVerificationBadgePresentation (branch coverage)', () => {+ it('returns the Not-checked badge for an explicit null state', () => {+ // The `!state` guard arm with null rather than undefined.+ expect(getAuditVerificationBadgePresentation(null)).toStrictEqual({+ label: 'Not checked',+ className: 'bg-surface-alt text-base-content',+ });+ });++ it('returns the Error badge for the error status case', () => {+ expect(getAuditVerificationBadgePresentation({ status: 'error' })).toStrictEqual({+ label: 'Error',+ className: 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200',+ });+ });++ it('returns the Unavailable badge for the unavailable status (default arm)', () => {+ // 'unavailable' is a valid AuditVerificationStatus but has no explicit case,+ // so it routes through the switch default.+ expect(getAuditVerificationBadgePresentation({ status: 'unavailable' })).toStrictEqual({+ label: 'Unavailable',+ className: 'bg-surface-alt text-base-content',+ });+ });++ it('routes a malformed status string through the default arm to Unavailable', () => {+ const bogus = { status: 'definitely-not-a-status' as unknown as AuditVerificationStatus };+ expect(getAuditVerificationBadgePresentation(bogus)).toStrictEqual({+ label: 'Unavailable',+ className: 'bg-surface-alt text-base-content',+ });+ });++ it('distinguishes the three outcome colours while sharing one neutral class', () => {+ const notChecked = getAuditVerificationBadgePresentation(undefined);+ const unavailable = getAuditVerificationBadgePresentation({ status: 'unavailable' });+ const verified = getAuditVerificationBadgePresentation({ status: 'verified' });+ const failed = getAuditVerificationBadgePresentation({ status: 'failed' });+ const errored = getAuditVerificationBadgePresentation({ status: 'error' });++ // The verified/failed/error outcomes each carry a distinct colour class.+ expect(new Set([verified.className, failed.className, errored.className]).size).toBe(3);+ // The "Not checked" (no state) and "Unavailable" (default arm) fallbacks+ // intentionally reuse the same neutral surface-alt class but keep+ // different labels.+ expect(notChecked.className).toBe(unavailable.className);+ expect(notChecked.className).toBe('bg-surface-alt text-base-content');+ expect(notChecked.label).toBe('Not checked');+ expect(unavailable.label).toBe('Unavailable');+ // Every coloured class differs from the neutral fallback.+ for (const coloured of [verified.className, failed.className, errored.className]) {+ expect(coloured).not.toBe(notChecked.className);+ }+ });+});++describe('getAuditLogLoadingState (branch coverage)', () => {+ it('returns the canonical loading copy as a readonly literal', () => {+ expect(getAuditLogLoadingState()).toStrictEqual({ text: 'Loading audit events…' });+ });++ it('always returns the same singleton shape across calls (deterministic)', () => {+ expect(getAuditLogLoadingState()).toEqual(getAuditLogLoadingState());+ });++ it('exposes only the text key', () => {+ expect(Object.keys(getAuditLogLoadingState())).toStrictEqual(['text']);+ });+});++describe('getAuditLogFetchErrorMessage (branch coverage)', () => {+ it('maps a bare HTTP 500 status (no message) to the internal-error copy', () => {+ // Exercises the `errorLike?.status === 500` operand of the || independently+ // of the message-regex operand.+ expect(getAuditLogFetchErrorMessage({ status: 500 })).toBe(+ 'Audit events could not be loaded because the server returned an internal error. Check the server logs, then refresh the audit log.',+ );+ });++ it('maps a matching message to the internal-error copy even without a 500 status', () => {+ // Regex operand of the || is true while status operand is absent.+ expect(+ getAuditLogFetchErrorMessage({ message: 'failed to fetch audit events: internal server error' }),+ ).toBe(+ 'Audit events could not be loaded because the server returned an internal error. Check the server logs, then refresh the audit log.',+ );+ });++ it('tolerates arbitrary whitespace between the prefix and "internal server error" via \\s*', () => {+ // The regex uses `\s*`; multiple spaces must still match.+ expect(+ getAuditLogFetchErrorMessage({+ message: 'Failed to fetch audit events: internal server error',+ }),+ ).toBe(+ 'Audit events could not be loaded because the server returned an internal error. Check the server logs, then refresh the audit log.',+ );+ });++ it('uses strict equality for status, so a numeric-looking string does not trigger the 500 arm', () => {+ // `'500' === 500` is false, and the message does not match the regex, so it+ // falls through to the Unknown-error fallback.+ expect(getAuditLogFetchErrorMessage({ status: '500' })).toBe('Unknown error');+ });++ it('returns the underlying message for a generic Error that matches no known code/regex', () => {+ // `error instanceof Error` -> error.message arm.+ expect(getAuditLogFetchErrorMessage(new Error('network unreachable'))).toBe(+ 'network unreachable',+ );+ });++ it('returns "Unknown error" for a non-Error primitive value', () => {+ expect(getAuditLogFetchErrorMessage('boom')).toBe('Unknown error');+ });++ it('returns "Unknown error" for null', () => {+ // null is not an Error and exposes no matching code/status/message.+ expect(getAuditLogFetchErrorMessage(null)).toBe('Unknown error');+ });++ it('returns "Unknown error" for undefined', () => {+ expect(getAuditLogFetchErrorMessage(undefined)).toBe('Unknown error');+ });++ it('returns "Unknown error" for a plain object with no recognised fields', () => {+ expect(getAuditLogFetchErrorMessage({})).toBe('Unknown error');+ });++ it('returns "Unknown error" for an object whose code/status are unrecognised', () => {+ expect(+ getAuditLogFetchErrorMessage({ code: 'something_else', status: 404, message: 'mystery' }),+ ).toBe('Unknown error');+ });++ it('prefers the code-based arms over the status-based arm when both are set', () => {+ // A busy code with a 500 status must return the busy copy, proving the+ // code checks short-circuit before the status/regex block.+ expect(getAuditLogFetchErrorMessage({ code: 'audit_store_busy', status: 500 })).toBe(+ 'Audit log storage is busy. Wait a moment, then refresh the audit log.',+ );+ });+});++describe('getAuditLogFeatureGateCopy (branch coverage)', () => {+ it('returns the default Audit Logging copy when called with no options', () => {+ // Exercises the default parameter value `{}` and the falsy arm.+ expect(getAuditLogFeatureGateCopy()).toStrictEqual({+ title: 'Audit Logging',+ body: 'Persistent, searchable audit logs with cryptographic signature verification.',+ });+ });++ it('returns the default copy for an empty options object', () => {+ expect(getAuditLogFeatureGateCopy({})).toStrictEqual({+ title: 'Audit Logging',+ body: 'Persistent, searchable audit logs with cryptographic signature verification.',+ });+ });++ it('falls back to the default copy when paidRuntimeRequired is explicitly false', () => {+ expect(getAuditLogFeatureGateCopy({ paidRuntimeRequired: false })).toStrictEqual({+ title: 'Audit Logging',+ body: 'Persistent, searchable audit logs with cryptographic signature verification.',+ });+ });++ it('returns the Pro-runtime copy when paidRuntimeRequired is truthy', () => {+ expect(getAuditLogFeatureGateCopy({ paidRuntimeRequired: true })).toStrictEqual({+ title: 'Pulse Pro runtime required',+ body: 'Your Pro license is active, but this install is running the community runtime. Install the private Pulse Pro runtime to use Audit Log and Audit Webhooks. Public GitHub releases and the public Docker image do not include those Pro runtime hooks.',+ });+ });++ it('produces a distinct title for the two arms', () => {+ const paid = getAuditLogFeatureGateCopy({ paidRuntimeRequired: true }).title;+ const community = getAuditLogFeatureGateCopy({ paidRuntimeRequired: false }).title;+ expect(paid).not.toBe(community);+ });+});++describe('getAuditLogEmptyState (branch coverage)', () => {+ it('returns the filtered description when at least one filter is active', () => {+ expect(getAuditLogEmptyState(1)).toStrictEqual({+ title: 'No audit events found',+ description: 'No events match your current filters. Try adjusting or clearing them.',+ });+ });++ it('returns the filtered description for a large filter count', () => {+ expect(getAuditLogEmptyState(42).description).toBe(+ 'No events match your current filters. Try adjusting or clearing them.',+ );+ });++ it('returns the unfiltered description when no filters are active (boundary zero)', () => {+ expect(getAuditLogEmptyState(0)).toStrictEqual({+ title: 'No audit events found',+ description: 'Audit logging is active, but no events have been recorded yet.',+ });+ });++ it('treats a negative count as no-filters (the > 0 guard is false)', () => {+ // Documents the guard's strict inequality: negatives route to the unfiltered arm.+ expect(getAuditLogEmptyState(-3).description).toBe(+ 'Audit logging is active, but no events have been recorded yet.',+ );+ });++ it('shares the same title across both arms but diverges on the description', () => {+ const filtered = getAuditLogEmptyState(2);+ const unfiltered = getAuditLogEmptyState(0);+ expect(filtered.title).toBe(unfiltered.title);+ expect(filtered.description).not.toBe(unfiltered.description);+ });+});++describe('getAuditEventStatusPresentation (already covered — guard)', () => {+ it('is exhaustively covered by the sibling branchcov0712 suite; both arms remain stable', () => {+ // Sanity guard so this target function is represented without duplicating+ // the sibling suite's detailed icon-reference / truthiness assertions.+ expect(getAuditEventStatusPresentation(true).className).toBe('w-4 h-4 text-emerald-400');+ expect(getAuditEventStatusPresentation(false).className).toBe('w-4 h-4 text-rose-400');+ });+});diff --git a/frontend-modern/src/utils/__tests__/canvasRenderQueue.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/canvasRenderQueue.branchcov0713.test.tsnew file mode 100644index 0000000000..61ef5d841d--- /dev/null+++ b/frontend-modern/src/utils/__tests__/canvasRenderQueue.branchcov0713.test.ts@@ -0,0 +1,233 @@+/**+ * Branch-coverage tests for canvasRenderQueue.ts — setupCanvasDPR pass.+ *+ * The sibling canvasRenderQueue.test.ts only exercises the+ * scheduleSparkline/flush rAF scheduler; it never touches setupCanvasDPR.+ * This file targets every branch of setupCanvasDPR:+ *+ * - `window.devicePixelRatio || 1`: the truthy arm (real DPR) and the falsy+ * fallback arm for both `undefined` and `0` (every value the `||` would+ * surrender to the right-hand `1`).+ * - `canvas.width !== targetWidth || canvas.height !== targetHeight`: the+ * short-circuit-left-truthy arm (only width differs), the left-falsy /+ * right-truthy arm (only height differs), the both-differ arm, and the+ * both-falsy arm (no resize needed).+ * - `if (needsResize)`: the resize block (mutates backing size + CSS size)+ * versus the skip arm.+ * - `if (!needsResize)`: the clearRect arm (canvas is cleared in logical+ * pixels) versus the skip arm (resize already wiped the canvas).+ * - `Math.round(w * dpr)` rounding on a fractional product, and the w=0/h=0+ * boundary.+ *+ * setupCanvasDPR reads `window.devicePixelRatio` at call time (not import+ * time), so a static import is safe regardless of the DPR stub in force.+ * jsdom does not implement CanvasRenderingContext2D, so the 2D context is a+ * minimal structural double carrying `setTransform`/`clearRect` spies cast+ * through the real type — the canvas element itself is a genuine+ * HTMLCanvasElement from document.createElement, so every width/height/style+ * assertion is against real DOM state.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { setupCanvasDPR } from '@/utils/canvasRenderQueue';++type CanvasAndCtx = {+ canvas: HTMLCanvasElement;+ ctx: CanvasRenderingContext2D;+ setTransform: ReturnType<typeof vi.fn>;+ clearRect: ReturnType<typeof vi.fn>;+};++/**+ * Build a real HTMLCanvasElement paired with a minimal 2D-context double.+ * jsdom returns null from getContext('2d'), so the context is a structural+ * stand-in carrying the two methods setupCanvasDPR actually calls.+ */+function makeCanvasAndCtx(): CanvasAndCtx {+ const canvas = document.createElement('canvas');+ const setTransform = vi.fn();+ const clearRect = vi.fn();+ const ctx = { setTransform, clearRect } as unknown as CanvasRenderingContext2D;+ return { canvas, ctx, setTransform, clearRect };+}++const originalDprDescriptor = Object.getOwnPropertyDescriptor(window, 'devicePixelRatio');++function setDevicePixelRatio(value: number | undefined): void {+ // Define as an own, configurable, writable value property so it shadows any+ // Window.prototype getter jsdom installs.+ Object.defineProperty(window, 'devicePixelRatio', {+ configurable: true,+ writable: true,+ value,+ });+}++describe('setupCanvasDPR (branch coverage)', () => {+ beforeEach(() => {+ // jsdom ships devicePixelRatio = 1; pin a known baseline per test.+ setDevicePixelRatio(1);+ });++ afterEach(() => {+ if (originalDprDescriptor) {+ Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor);+ } else {+ // No own descriptor to restore from -> drop our shadow and let the+ // prototype getter resurface.+ Reflect.deleteProperty(window, 'devicePixelRatio');+ }+ vi.restoreAllMocks();+ });++ it('resizes both dimensions and applies the DPR scale when nothing matches yet (dpr truthy arm, both-differ arm)', () => {+ setDevicePixelRatio(2);+ const { canvas, ctx, setTransform, clearRect } = makeCanvasAndCtx();++ // Fresh jsdom canvas is 300x150; targets at dpr 2 are 200x100.+ expect(canvas.width).toBe(300);+ expect(canvas.height).toBe(150);++ setupCanvasDPR(canvas, ctx, 100, 50);++ expect(canvas.width).toBe(200);+ expect(canvas.height).toBe(100);+ expect(canvas.style.width).toBe('100px');+ expect(canvas.style.height).toBe('50px');+ // Resize path is taken, so the explicit clear is skipped (resize wipes it).+ expect(setTransform).toHaveBeenCalledTimes(1);+ expect(setTransform).toHaveBeenCalledWith(2, 0, 0, 2, 0, 0);+ expect(clearRect).not.toHaveBeenCalled();+ });++ it('skips the resize and clears in logical pixels when backing size already matches (needsResize false + clearRect arm)', () => {+ setDevicePixelRatio(2);+ const { canvas, ctx, setTransform, clearRect } = makeCanvasAndCtx();++ // Pre-size the backing store to the exact dpr-scaled targets so neither+ // operand of the `||` is truthy.+ canvas.width = 200;+ canvas.height = 100;++ setupCanvasDPR(canvas, ctx, 100, 50);++ // No resize: backing size and CSS size are untouched.+ expect(canvas.width).toBe(200);+ expect(canvas.height).toBe(100);+ expect(canvas.style.width).toBe('');+ expect(canvas.style.height).toBe('');+ // setTransform always runs; clearRect runs because the resize did not.+ expect(setTransform).toHaveBeenCalledTimes(1);+ expect(setTransform).toHaveBeenCalledWith(2, 0, 0, 2, 0, 0);+ expect(clearRect).toHaveBeenCalledTimes(1);+ expect(clearRect).toHaveBeenCalledWith(0, 0, 100, 50);+ });++ it('falls back to dpr 1 when window.devicePixelRatio is undefined (|| falsy arm, undefined)', () => {+ setDevicePixelRatio(undefined);+ const { canvas, ctx, setTransform } = makeCanvasAndCtx();++ setupCanvasDPR(canvas, ctx, 100, 50);++ // dpr = undefined || 1 = 1, so targets equal the logical size verbatim.+ expect(canvas.width).toBe(100);+ expect(canvas.height).toBe(50);+ expect(canvas.style.width).toBe('100px');+ expect(setTransform).toHaveBeenCalledWith(1, 0, 0, 1, 0, 0);+ });++ it('falls back to dpr 1 when window.devicePixelRatio is 0 (|| falsy arm, numeric zero)', () => {+ setDevicePixelRatio(0);+ const { canvas, ctx, setTransform } = makeCanvasAndCtx();++ setupCanvasDPR(canvas, ctx, 80, 40);++ // 0 || 1 === 1; a naive `dpr` use would have produced 0x0 targets.+ expect(canvas.width).toBe(80);+ expect(canvas.height).toBe(40);+ expect(setTransform).toHaveBeenCalledWith(1, 0, 0, 1, 0, 0);+ });++ it('resizes when only the height differs while width already matches (|| left-falsy / right-truthy arm)', () => {+ setDevicePixelRatio(1);+ const { canvas, ctx, setTransform, clearRect } = makeCanvasAndCtx();++ canvas.width = 100; // matches targetWidth (100 * 1) -> left operand falsy.+ canvas.height = 777; // differs from targetHeight (50 * 1) -> right truthy.++ setupCanvasDPR(canvas, ctx, 100, 50);++ expect(canvas.width).toBe(100);+ expect(canvas.height).toBe(50);+ expect(canvas.style.width).toBe('100px');+ expect(canvas.style.height).toBe('50px');+ expect(setTransform).toHaveBeenCalledWith(1, 0, 0, 1, 0, 0);+ expect(clearRect).not.toHaveBeenCalled();+ });++ it('resizes when only the width differs while height already matches (|| left-truthy short-circuit arm)', () => {+ setDevicePixelRatio(1);+ const { canvas, ctx, clearRect } = makeCanvasAndCtx();++ canvas.width = 999; // differs from targetWidth (100 * 1) -> left truthy.+ canvas.height = 50; // matches targetHeight -> would be right operand.++ setupCanvasDPR(canvas, ctx, 100, 50);++ expect(canvas.width).toBe(100);+ expect(canvas.height).toBe(50);+ expect(canvas.style.width).toBe('100px');+ expect(canvas.style.height).toBe('50px');+ expect(clearRect).not.toHaveBeenCalled();+ });++ it('rounds fractional width*dpr and height*dpr products via Math.round', () => {+ setDevicePixelRatio(1.5);+ const { canvas, ctx } = makeCanvasAndCtx();++ // 101 * 1.5 = 151.5 -> rounds to 152 (Math.round rounds half up).+ setupCanvasDPR(canvas, ctx, 101, 101);++ expect(canvas.width).toBe(152);+ expect(canvas.height).toBe(152);+ expect(canvas.style.width).toBe('101px');+ expect(canvas.style.height).toBe('101px');+ });++ it('handles the zero-size boundary (w=0, h=0) without producing NaN', () => {+ setDevicePixelRatio(2);+ const { canvas, ctx, setTransform, clearRect } = makeCanvasAndCtx();++ setupCanvasDPR(canvas, ctx, 0, 0);++ expect(canvas.width).toBe(0);+ expect(canvas.height).toBe(0);+ expect(canvas.style.width).toBe('0px');+ expect(canvas.style.height).toBe('0px');+ expect(setTransform).toHaveBeenCalledWith(2, 0, 0, 2, 0, 0);+ expect(clearRect).not.toHaveBeenCalled();+ });++ it('re-resizes after a backing-store change on a subsequent call (idempotent second pass takes the clear path)', () => {+ setDevicePixelRatio(2);+ const { canvas, ctx, setTransform, clearRect } = makeCanvasAndCtx();++ // First call: fresh canvas -> resize path.+ setupCanvasDPR(canvas, ctx, 120, 60);+ expect(canvas.width).toBe(240);+ expect(canvas.height).toBe(120);+ expect(clearRect).not.toHaveBeenCalled();++ // Second call with the same logical size: backing store now matches ->+ // no resize, clearRect path.+ setTransform.mockClear();+ clearRect.mockClear();+ setupCanvasDPR(canvas, ctx, 120, 60);+ expect(canvas.width).toBe(240);+ expect(canvas.height).toBe(120);+ expect(setTransform).toHaveBeenCalledTimes(1);+ expect(setTransform).toHaveBeenCalledWith(2, 0, 0, 2, 0, 0);+ expect(clearRect).toHaveBeenCalledTimes(1);+ expect(clearRect).toHaveBeenCalledWith(0, 0, 120, 60);+ });+});diff --git a/frontend-modern/src/utils/__tests__/systemLogsPresentation.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/systemLogsPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..5d408a8e93--- /dev/null+++ b/frontend-modern/src/utils/__tests__/systemLogsPresentation.branchcov0713.test.ts@@ -0,0 +1,239 @@+/**+ * Branch-coverage tests for systemLogsPresentation.ts — second pass.+ *+ * Focused exclusively on the branches of the three target functions that the+ * sibling `systemLogsPresentation.test.ts` does not yet reach:+ * - getSystemLogLineClass (every uncovered pattern, precedence, substring+ * semantics, and the no-guard throw paths)+ * - getSystemLogStreamPresentation (ternary truthiness coercion via casts)+ * - getSystemLogBufferSummary (boundary / NaN / Infinity / coercion edges)+ *+ * The sibling test already covers ERROR pattern 0, WARN pattern 2, DEBUG+ * pattern 1, the default slate arm, the two canonical stream states, and one+ * buffer summary — those are intentionally NOT re-asserted here.+ *+ * `includesAny` is module-private (not exported); it has no other caller, so+ * it is exercised transitively through `getSystemLogLineClass` rather than+ * imported directly.+ */+import { describe, expect, it } from 'vitest';++import {+ getSystemLogBufferSummary,+ getSystemLogLineClass,+ getSystemLogStreamPresentation,+} from '@/utils/systemLogsPresentation';++describe('getSystemLogLineClass — branch coverage (batch 2)', () => {+ describe('ERROR_PATTERNS — every pattern reaches the red arm', () => {+ // Sibling already covers ERROR pattern 0 ('"level":"error"'); these cover+ // the remaining two patterns: 'ERR' and '[ERROR]'.+ it('matches the bare ERR token (error pattern 1)', () => {+ expect(getSystemLogLineClass('disk ERR timeout')).toBe('text-red-400');+ });++ it('matches the bracketed [ERROR] token (error pattern 2)', () => {+ expect(getSystemLogLineClass('[ERROR] connection refused')).toBe('text-red-400');+ });+ });++ describe('WARNING_PATTERNS — every pattern reaches the amber arm', () => {+ // Sibling already covers WARN pattern 2 ('[WARN]'); these cover patterns+ // 0 ('"level":"warn"') and 1 ('WRN').+ it('matches the JSON warn level (warning pattern 0)', () => {+ expect(getSystemLogLineClass('{"level":"warn","msg":"degraded"}')).toBe('text-amber-400');+ });++ it('matches the bare WRN token (warning pattern 1)', () => {+ expect(getSystemLogLineClass('WRN cache miss rate high')).toBe('text-amber-400');+ });+ });++ describe('DEBUG_PATTERNS — every pattern reaches the blue arm', () => {+ // Sibling already covers DEBUG pattern 1 ('DBG'); these cover patterns+ // 0 ('"level":"debug"') and 2 ('[DEBUG]').+ it('matches the JSON debug level (debug pattern 0)', () => {+ expect(getSystemLogLineClass('{"level":"debug","msg":"refresh"}')).toBe('text-blue-400');+ });++ it('matches the bracketed [DEBUG] token (debug pattern 2)', () => {+ expect(getSystemLogLineClass('[DEBUG] polling interval=30s')).toBe('text-blue-400');+ });+ });++ describe('if/else precedence — first matching severity wins', () => {+ it('prefers error over warn when a line contains both', () => {+ // ERROR_PATTERNS is checked first, so a combined line resolves to red.+ expect(getSystemLogLineClass('[ERROR] rolled back [WARN] stage')).toBe('text-red-400');+ });++ it('prefers error over debug when a line contains both', () => {+ expect(getSystemLogLineClass('[ERROR] and [DEBUG] trace attached')).toBe('text-red-400');+ });++ it('prefers warn over debug when a line contains both', () => {+ // ERROR_PATTERNS miss, WARNING_PATTERNS hit before DEBUG_PATTERNS.+ expect(getSystemLogLineClass('[WARN] retrying [DEBUG] attempt=2')).toBe('text-amber-400');+ });++ it('resolves to red when all three severities appear in one line', () => {+ expect(+ getSystemLogLineClass('[DEBUG] [WARN] [ERROR] boom ERR WRN DBG'),+ ).toBe('text-red-400');+ });+ });++ describe('substring matching via includesAny — no word-boundary anchoring', () => {+ it('matches ERR as a substring inside a larger word (TERROR)', () => {+ // value.includes('ERR') has no anchoring, so 'TERROR' hits the error arm.+ expect(getSystemLogLineClass('TERROR protocol mismatch')).toBe('text-red-400');+ });++ it('does NOT treat the word WARNING as a warn token (no WRN substring)', () => {+ // 'WARNING' contains neither 'WRN', '[WARN]', nor '"level":"warn"', so it+ // falls through every guard to the default slate arm.+ expect(getSystemLogLineClass('WARNING sustained cpu pressure')).toBe('text-slate-300');+ });++ it('matches ERR embedded mid-word after whitespace (TERROR prefixed)', () => {+ // Confirms the substring hit is position-independent.+ expect(getSystemLogLineClass('node TERROR fail')).toBe('text-red-400');+ });+ });++ describe('default arm — unmatched payloads fall through to slate', () => {+ it('returns the slate class for an empty string', () => {+ // No pattern matches '' -> default return.+ expect(getSystemLogLineClass('')).toBe('text-slate-300');+ });++ it('returns the slate class for a plain info line with no tokens', () => {+ // 'INFO' is not in any pattern list (patterns use ERR/WRN/DBG), so this+ // is a meaningful non-match that documents the gap.+ expect(getSystemLogLineClass('INFO request handled in 12ms')).toBe('text-slate-300');+ });+ });++ describe('missing input guard — non-string inputs throw (no null guard)', () => {+ // getSystemLogLineClass immediately calls log.includes(...) via includesAny+ // with no type guard, so null/undefined/number throw a TypeError at+ // runtime. These document the absence of a guard rather than a branch.+ it('throws a TypeError when log is null', () => {+ const log = null as unknown as Parameters<typeof getSystemLogLineClass>[0];+ expect(() => getSystemLogLineClass(log)).toThrow(TypeError);+ });++ it('throws a TypeError when log is undefined', () => {+ const log = undefined as unknown as Parameters<typeof getSystemLogLineClass>[0];+ expect(() => getSystemLogLineClass(log)).toThrow(TypeError);+ });++ it('throws a TypeError when log is a number (no .includes method)', () => {+ const log = 0 as unknown as Parameters<typeof getSystemLogLineClass>[0];+ expect(() => getSystemLogLineClass(log)).toThrow(TypeError);+ });+ });+});++describe('getSystemLogStreamPresentation — ternary truthiness coercion (batch 2)', () => {+ // The sibling test covers the canonical boolean true/false. These exercise+ // the ternary condition's truthiness evaluation when a non-boolean is+ // smuggled in through a cast — proving the condition is `paused ? ...` and+ // not `paused === true ? ...`.++ it('treats numeric 0 as falsy and selects the live presentation', () => {+ const paused = 0 as unknown as Parameters<typeof getSystemLogStreamPresentation>[0];+ const result = getSystemLogStreamPresentation(paused);+ expect(result.label).toBe('Streaming');+ expect(result.toggleTitle).toBe('Pause Stream');+ });++ it('treats empty string as falsy and selects the live presentation', () => {+ const paused = '' as unknown as Parameters<typeof getSystemLogStreamPresentation>[0];+ const result = getSystemLogStreamPresentation(paused);+ expect(result.label).toBe('Streaming');+ expect(result.toggleTitle).toBe('Pause Stream');+ });++ it('treats numeric 1 as truthy and selects the paused presentation', () => {+ const paused = 1 as unknown as Parameters<typeof getSystemLogStreamPresentation>[0];+ const result = getSystemLogStreamPresentation(paused);+ expect(result.label).toBe('Paused');+ expect(result.toggleTitle).toBe('Resume Stream');+ });++ it('treats a non-empty string as truthy and selects the paused presentation', () => {+ const paused = 'paused' as unknown as Parameters<typeof getSystemLogStreamPresentation>[0];+ const result = getSystemLogStreamPresentation(paused);+ expect(result.label).toBe('Paused');+ expect(result.toggleTitle).toBe('Resume Stream');+ });++ it('returns the distinct indicator class for each coerced arm', () => {+ // Locks the observable side-effect of the branch: live pulses emerald,+ // paused is a steady amber. Uses two different coerced truthy/falsy+ // values than the cases above to avoid pure duplication.+ const truthy = 'truthy' as unknown as Parameters<typeof getSystemLogStreamPresentation>[0];+ const falsy = NaN as unknown as Parameters<typeof getSystemLogStreamPresentation>[0];+ expect(getSystemLogStreamPresentation(truthy).indicatorClass).toBe('bg-amber-400');+ expect(getSystemLogStreamPresentation(falsy).indicatorClass).toBe('bg-emerald-400 animate-pulse');+ });+});++describe('getSystemLogBufferSummary — boundary & coercion edges (batch 2)', () => {+ // No control-flow branches exist here; coverage is gained by exercising the+ // template-literal interpolation at boundary values and for malformed inputs+ // that document the absence of any clamping / NaN guard.++ it('formats an empty buffer (logCount 0)', () => {+ expect(getSystemLogBufferSummary(0, 500)).toBe('Buffer: 0 / 500 lines');+ });++ it('formats a full buffer (logCount === maxLogs)', () => {+ expect(getSystemLogBufferSummary(500, 500)).toBe('Buffer: 500 / 500 lines');+ });++ it('formats a zero-capacity buffer (maxLogs 0)', () => {+ expect(getSystemLogBufferSummary(0, 0)).toBe('Buffer: 0 / 0 lines');+ });++ it('does not clamp a negative count (no guard)', () => {+ // Negative logCount survives untouched into the template literal.+ expect(getSystemLogBufferSummary(-5, 500)).toBe('Buffer: -5 / 500 lines');+ });++ it('does not clamp a count exceeding the maximum (no guard)', () => {+ // Over-capacity is rendered literally rather than being capped at maxLogs.+ expect(getSystemLogBufferSummary(750, 500)).toBe('Buffer: 750 / 500 lines');+ });++ it('interpolates NaN verbatim (no NaN guard)', () => {+ expect(getSystemLogBufferSummary(Number.NaN, 500)).toBe('Buffer: NaN / 500 lines');+ });++ it('interpolates Infinity verbatim (no finite guard)', () => {+ expect(getSystemLogBufferSummary(Number.POSITIVE_INFINITY, 500)).toBe(+ 'Buffer: Infinity / 500 lines',+ );+ });++ it('String()-coerces a smuggled string count via template interpolation', () => {+ const logCount = '42' as unknown as Parameters<typeof getSystemLogBufferSummary>[0];+ expect(getSystemLogBufferSummary(logCount, 500)).toBe('Buffer: 42 / 500 lines');+ });++ it('String()-coerces null to "null" with no guard', () => {+ const logCount = null as unknown as Parameters<typeof getSystemLogBufferSummary>[0];+ expect(getSystemLogBufferSummary(logCount, 500)).toBe('Buffer: null / 500 lines');+ });++ it('String()-coerces undefined to "undefined" with no guard', () => {+ const logCount = undefined as unknown as Parameters<typeof getSystemLogBufferSummary>[0];+ expect(getSystemLogBufferSummary(logCount, 500)).toBe('Buffer: undefined / 500 lines');+ });++ it('String()-coerces a smuggled string maximum via template interpolation', () => {+ const maxLogs = '1k' as unknown as Parameters<typeof getSystemLogBufferSummary>[1];+ expect(getSystemLogBufferSummary(10, maxLogs)).toBe('Buffer: 10 / 1k lines');+ });+});diff --git a/frontend-modern/src/utils/__tests__/unifiedAgentStatusPresentation.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/unifiedAgentStatusPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..0dd81f4116--- /dev/null+++ b/frontend-modern/src/utils/__tests__/unifiedAgentStatusPresentation.branchcov0713.test.ts@@ -0,0 +1,212 @@+import { describe, expect, it } from 'vitest';+import {+ getUnifiedAgentLookupStatusPresentation,+ getUnifiedAgentStatusPresentation,+ MONITORING_STOPPED_STATUS_LABEL,+ type UnifiedAgentMonitoringState,+} from '@/utils/unifiedAgentStatusPresentation';++// Branch-coverage companion to unifiedAgentStatusPresentation.test.ts.+// The sibling test already locks the two canonical happy paths+// (('active','online') and ('removed','offline')) plus both lookup arms.+// This file targets the remaining branches of the two exported functions:+// - the `state === 'removed'` guard's precedence over the connected check+// and its independence from healthStatus+// - every accepted connected token (online / running / healthy) plus the+// normalize step (trim + lowercase) inside isConnectedHealthStatus+// - the default (not-removed, not-connected) arm for both truthy and+// falsy healthStatus, including the reachable `|| 'unknown'` fallback+// - non-canonical state values falling through to the default arm+// - lookup edge inputs (truthy/falsy non-boolean values cast to boolean)++const REMOVED_BADGE = 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200';+const CONNECTED_BADGE = 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300';+const DEFAULT_BADGE = 'bg-surface-alt text-base-content';+const LOOKUP_CONNECTED_BADGE =+ 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300';+const LOOKUP_DISCONNECTED_BADGE =+ 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200';++describe('getUnifiedAgentStatusPresentation — branch coverage', () => {+ describe('state === "removed" guard', () => {+ it('takes precedence over a connected healthStatus (removed arm wins over connected arm)', () => {+ // 'online' would normally select the green connected badge, but the+ // removed guard returns first -> amber + "Monitoring stopped".+ const result = getUnifiedAgentStatusPresentation('removed', 'online');+ expect(result).toEqual({ badgeClass: REMOVED_BADGE, label: MONITORING_STOPPED_STATUS_LABEL });+ expect(result.badgeClass).not.toBe(CONNECTED_BADGE);+ expect(result.label).toBe('Monitoring stopped');+ });++ it('ignores an undefined healthStatus', () => {+ expect(getUnifiedAgentStatusPresentation('removed', undefined)).toEqual({+ badgeClass: REMOVED_BADGE,+ label: MONITORING_STOPPED_STATUS_LABEL,+ });+ });++ it('ignores a null healthStatus', () => {+ expect(getUnifiedAgentStatusPresentation('removed', null)).toEqual({+ badgeClass: REMOVED_BADGE,+ label: MONITORING_STOPPED_STATUS_LABEL,+ });+ });++ it('ignores an empty-string healthStatus', () => {+ expect(getUnifiedAgentStatusPresentation('removed', '')).toEqual({+ badgeClass: REMOVED_BADGE,+ label: MONITORING_STOPPED_STATUS_LABEL,+ });+ });+ });++ describe('connected arm (isConnectedHealthStatus === true)', () => {+ it.each(['online', 'running', 'healthy'] as const)(+ 'accepts the connected token "%s" and echoes it verbatim as the label',+ (token) => {+ expect(getUnifiedAgentStatusPresentation('active', token)).toEqual({+ badgeClass: CONNECTED_BADGE,+ label: token,+ });+ },+ );++ it('normalizes a cased/whitespace-padded "ONLINE" to the connected arm (trim + lowercase)', () => {+ // isConnectedHealthStatus normalizes via trim().toLowerCase(), so+ // ' ONLINE ' is recognized as connected. The label, however, is the+ // raw healthStatus argument (not the normalized form).+ const result = getUnifiedAgentStatusPresentation('active', ' ONLINE ');+ expect(result).toEqual({ badgeClass: CONNECTED_BADGE, label: ' ONLINE ' });+ });++ it('matches "Healthy" case-insensitively (lowercased to "healthy")', () => {+ expect(getUnifiedAgentStatusPresentation('active', 'Healthy')).toEqual({+ badgeClass: CONNECTED_BADGE,+ label: 'Healthy',+ });+ });++ it('does NOT treat a non-connected token ("offline") as connected', () => {+ // Proves the connected arm is skipped for an unrecognized status.+ const result = getUnifiedAgentStatusPresentation('active', 'offline');+ expect(result.badgeClass).not.toBe(CONNECTED_BADGE);+ expect(result.badgeClass).toBe(DEFAULT_BADGE);+ });+ });++ describe('default arm (not removed, not connected)', () => {+ it.each(['offline', 'degraded', 'unknown', 'error', 'warning'])(+ 'uses the surface-alt badge and echoes a truthy non-connected healthStatus "%s" as the label',+ (status) => {+ expect(getUnifiedAgentStatusPresentation('active', status)).toEqual({+ badgeClass: DEFAULT_BADGE,+ label: status,+ });+ },+ );++ it('falls back to the "unknown" label when healthStatus is undefined (reachable || right arm)', () => {+ expect(getUnifiedAgentStatusPresentation('active', undefined)).toEqual({+ badgeClass: DEFAULT_BADGE,+ label: 'unknown',+ });+ });++ it('falls back to the "unknown" label when healthStatus is null', () => {+ expect(getUnifiedAgentStatusPresentation('active', null)).toEqual({+ badgeClass: DEFAULT_BADGE,+ label: 'unknown',+ });+ });++ it('falls back to the "unknown" label when healthStatus is the empty string', () => {+ // '' is falsy, so `healthStatus || 'unknown'` yields 'unknown'.+ expect(getUnifiedAgentStatusPresentation('active', '')).toEqual({+ badgeClass: DEFAULT_BADGE,+ label: 'unknown',+ });+ });++ it('echoes a whitespace-only healthStatus verbatim (truthy, so || fallback is skipped)', () => {+ // ' ' is truthy even though it normalizes to '' (not connected),+ // so the raw whitespace becomes the label.+ const result = getUnifiedAgentStatusPresentation('active', ' ');+ expect(result).toEqual({ badgeClass: DEFAULT_BADGE, label: ' ' });+ expect(result.label).not.toBe('unknown');+ });++ it('routes a non-canonical state value to the default arm (only "removed" is special)', () => {+ // A state outside {'active','removed'} is not 'removed', so it falls+ // through to the connected/default logic.+ const result = getUnifiedAgentStatusPresentation('paused' as UnifiedAgentMonitoringState, 'offline');+ expect(result).toEqual({ badgeClass: DEFAULT_BADGE, label: 'offline' });+ });++ it('routes an empty-string state with no healthStatus to the default arm + "unknown" label', () => {+ expect(+ getUnifiedAgentStatusPresentation('' as UnifiedAgentMonitoringState, undefined),+ ).toEqual({ badgeClass: DEFAULT_BADGE, label: 'unknown' });+ });++ it('routes a non-canonical state with a connected healthStatus to the connected arm', () => {+ // Confirms the connected check is independent of the state value+ // (as long as state !== 'removed').+ expect(+ getUnifiedAgentStatusPresentation('paused' as UnifiedAgentMonitoringState, 'running'),+ ).toEqual({ badgeClass: CONNECTED_BADGE, label: 'running' });+ });+ });++ describe('return shape', () => {+ it('always returns exactly the {badgeClass,label} keys (no extra fields)', () => {+ const result = getUnifiedAgentStatusPresentation('active', 'online');+ expect(Object.keys(result).sort()).toEqual(['badgeClass', 'label']);+ });+ });+});++describe('getUnifiedAgentLookupStatusPresentation — branch coverage', () => {+ it('returns the green Connected presentation for a truthy boolean', () => {+ // Note: the lookup connected badge intentionally uses text-green-700+ // (distinct from the status connected badge's text-green-800).+ expect(getUnifiedAgentLookupStatusPresentation(true)).toEqual({+ badgeClass: LOOKUP_CONNECTED_BADGE,+ label: 'Connected',+ });+ });++ it('returns the amber "Not reporting yet" presentation for a falsy boolean', () => {+ expect(getUnifiedAgentLookupStatusPresentation(false)).toEqual({+ badgeClass: LOOKUP_DISCONNECTED_BADGE,+ label: 'Not reporting yet',+ });+ });++ it.each([+ ['0 (number)', 0],+ ['empty string', ''],+ ['null', null],+ ['undefined', undefined],+ ] as const)('routes a falsy non-boolean value (%s) to the not-connected arm', (_name, value) => {+ expect(+ getUnifiedAgentLookupStatusPresentation(value as unknown as boolean),+ ).toEqual({+ badgeClass: LOOKUP_DISCONNECTED_BADGE,+ label: 'Not reporting yet',+ });+ });++ it('routes a truthy non-boolean value (1) to the connected arm', () => {+ expect(+ getUnifiedAgentLookupStatusPresentation(1 as unknown as boolean),+ ).toEqual({+ badgeClass: LOOKUP_CONNECTED_BADGE,+ label: 'Connected',+ });+ });++ it('always returns exactly the {badgeClass,label} keys (no extra fields)', () => {+ const result = getUnifiedAgentLookupStatusPresentation(true);+ expect(Object.keys(result).sort()).toEqual(['badgeClass', 'label']);+ });+});