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(frontend): branch-coverage tests for 10 more pure presentation/model modules
rcourtman71ad92ef71a7
diff --git a/frontend-modern/src/components/Alerts/__tests__/incidentAssistantHandoffModel.branchcov2.test.ts b/frontend-modern/src/components/Alerts/__tests__/incidentAssistantHandoffModel.branchcov2.test.tsnew file mode 100644index 0000000000..137cb0dcd7--- /dev/null+++ b/frontend-modern/src/components/Alerts/__tests__/incidentAssistantHandoffModel.branchcov2.test.ts@@ -0,0 +1,504 @@+import { describe, expect, it } from 'vitest';++import type { Incident, IncidentEvent } from '@/types/api';++import { buildAlertIncidentAssistantHandoff } from '../incidentAssistantHandoffModel';++// `buildAlertIncidentAssistantHandoff` always populates briefing/context/handoffResources,+// but its declared return type borrows `AIChatContext`, where those fields are optional and+// `context` is `Record<string, unknown>`. The strict tsconfig therefore flags direct deep+// access as possibly-undefined. We mirror the concrete runtime shape in a local type and+// cast once so the assertions below stay precise (`toBe`/`toEqual`) and type-safe.+interface SanitizedIncidentEvent {+ id: string;+ type: string;+ timestamp: string;+ summary: string;+}++interface StrictHandoffContext {+ targetType: string;+ targetId: string;+ autonomousMode: boolean;+ handoffContext: string;+ handoffResources: { id: string; name: string; type: string; node?: string }[];+ briefing: {+ sourceLabel: string;+ title: string;+ subject: string;+ statusLabel: string;+ detailLines: string[];+ evidence: string[];+ actionLabel: string;+ safetyNote: string;+ };+ context: {+ alertIncidentId: string;+ alertIdentifier: string;+ alertType: string;+ alertLevel: string;+ alertStatus: string;+ alertMessage?: string;+ resourceName: string;+ resourceType?: string;+ node?: string;+ instance?: string;+ openedAt: string;+ closedAt?: string;+ acknowledged: boolean;+ eventCount: number;+ eventSummaries: SanitizedIncidentEvent[];+ };+}++interface StrictHandoff {+ context: StrictHandoffContext;+}++const DEFAULT_NOW = new Date('2026-03-20T10:05:00Z');++function buildHandoff(incident: Incident, now: Date = DEFAULT_NOW): StrictHandoff {+ return buildAlertIncidentAssistantHandoff({ incident, now }) as unknown as StrictHandoff;+}++function makeIncident(overrides: Partial<Incident> = {}): Incident {+ return {+ id: 'incident-1',+ alertIdentifier: 'docker:app-1::docker-container-health',+ alertType: 'docker-container-health',+ level: 'critical',+ resourceId: 'docker:app-1',+ resourceName: 'checkout-api',+ resourceType: 'docker-container',+ node: 'edge-1',+ message: 'Container health check is failing',+ status: 'open',+ openedAt: '2026-03-20T10:00:00Z',+ acknowledged: false,+ events: [+ {+ id: 'event-1',+ type: 'command',+ timestamp: '2026-03-20T10:02:00Z',+ summary: 'systemctl restart checkout-api',+ },+ {+ id: 'event-2',+ type: 'ai_analysis',+ timestamp: '2026-03-20T10:03:00Z',+ summary: 'Health check failure correlated with recent deployment',+ },+ ],+ ...overrides,+ };+}++function makeEvent(overrides: Partial<IncidentEvent> = {}): IncidentEvent {+ return {+ id: 'event-x',+ type: 'note',+ timestamp: '2026-03-20T10:04:00Z',+ summary: 'Something happened',+ ...overrides,+ };+}++// With level='critical' + status='open', formatIncidentLabel yields 'Critical' / 'Open', so the+// briefing statusLabel prefix is constant: `${levelLabel} incident · ${statusLabel} · `.+const STATUS_PREFIX = 'Critical incident · Open · ';++describe('formatIncidentDuration (exercised via buildAlertIncidentAssistantHandoff)', () => {+ it('returns singular "1 min" for an exact 1-minute delta (durationMins === 1 true arm)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:00:00Z',+ closedAt: '2026-03-20T10:01:00Z',+ }),+ new Date('2026-03-20T11:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}1 min`);+ expect(handoff.context.handoffContext).toContain('Duration: 1 min');+ });++ it('returns plural "5 mins" for a multi-minute sub-hour delta (durationMins === 1 false arm)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:00:00Z',+ closedAt: '2026-03-20T10:05:00Z',+ }),+ new Date('2026-03-20T11:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}5 mins`);+ });++ it('returns "0 mins" when closedAt equals openedAt (zero delta, plural arm)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:00:00Z',+ closedAt: '2026-03-20T10:00:00Z',+ }),+ new Date('2026-03-20T11:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}0 mins`);+ });++ it('clamps a negative (closedAt before openedAt) delta to "0 mins" via Math.max(0, ...)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:05:00Z',+ closedAt: '2026-03-20T10:00:00Z',+ }),+ new Date('2026-03-20T11:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}0 mins`);+ });++ it('formats a sub-day >= 60min delta as "Xh Ym" (durationMins >= 60, durationHours < 24 arm)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:00:00Z',+ closedAt: '2026-03-20T11:05:00Z',+ }),+ new Date('2026-03-20T12:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}1h 5m`);+ });++ it('formats a multi-day delta as "Xd Yh" (durationHours >= 24 arm)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:00:00Z',+ closedAt: '2026-03-21T14:00:00Z',+ }),+ new Date('2026-03-22T10:00:00Z'),+ );+ // 28h elapsed -> floor(28/24)=1 day, 28%24=4 hours+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}1d 4h`);+ });++ it('returns "unknown duration" when openedAt is unparseable (openedMs not finite)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: 'not-a-valid-date',+ closedAt: '2026-03-20T11:00:00Z',+ }),+ new Date('2026-03-20T12:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}unknown duration`);+ expect(handoff.context.handoffContext).toContain('Duration: unknown duration');+ });++ it('returns "unknown duration" when closedAt is truthy but unparseable (closedMs not finite)', () => {+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:00:00Z',+ closedAt: 'not-a-valid-date',+ }),+ new Date('2026-03-20T12:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}unknown duration`);+ });++ it('falls back to `now` when closedAt is undefined (closedAt-falsy ternary arm, nonzero delta)', () => {+ const handoff = buildHandoff(+ makeIncident({ closedAt: undefined }),+ new Date('2026-03-20T10:05:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}5 mins`);+ });++ it('falls back to `now` yielding zero when closedAt is undefined and now === openedAt', () => {+ const handoff = buildHandoff(+ makeIncident({ closedAt: undefined }),+ new Date('2026-03-20T10:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}0 mins`);+ });++ it('uses closedAt (not now) when closedAt is present (closedAt-truthy ternary arm)', () => {+ // closedAt gives 5 mins; now is 1 hour after openedAt and would give 60 mins -> "1h 0m".+ const handoff = buildHandoff(+ makeIncident({+ openedAt: '2026-03-20T10:00:00Z',+ closedAt: '2026-03-20T10:05:00Z',+ }),+ new Date('2026-03-20T11:00:00Z'),+ );+ expect(handoff.context.briefing.statusLabel).toBe(`${STATUS_PREFIX}5 mins`);+ });+});++describe('sanitizeIncidentEventSummary (exercised via buildAlertIncidentAssistantHandoff)', () => {+ it('redacts a lowercase "command" type to the canned summary (includes(command) true)', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [makeEvent({ id: 'e1', type: 'command', summary: 'rm -rf /' })],+ }),+ );+ expect(handoff.context.context.eventSummaries[0].summary).toBe('Command event recorded');+ expect(handoff.context.briefing.evidence[0]).toBe('Command: Command event recorded');+ expect(JSON.stringify(handoff)).not.toContain('rm -rf');+ });++ it('redacts a title-cased "Command" type via toLowerCase() (case-insensitive command branch)', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [makeEvent({ id: 'e1', type: 'Command', summary: 'rm -rf /' })],+ }),+ );+ expect(handoff.context.context.eventSummaries[0].summary).toBe('Command event recorded');+ expect(JSON.stringify(handoff)).not.toContain('rm -rf');+ });++ it('redacts on a substring match "pre_command" (includes("command") substring arm)', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [makeEvent({ id: 'e1', type: 'pre_command', summary: 'secret-payload' })],+ }),+ );+ expect(handoff.context.context.eventSummaries[0].summary).toBe('Command event recorded');+ expect(handoff.context.briefing.evidence[0]).toBe('Pre Command: Command event recorded');+ expect(JSON.stringify(handoff)).not.toContain('secret-payload');+ });++ it('passes through a non-command summary that is non-empty after trim (length > 0 true arm)', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [makeEvent({ id: 'e1', type: 'note', summary: 'Server rebooted' })],+ }),+ );+ expect(handoff.context.context.eventSummaries[0].summary).toBe('Server rebooted');+ expect(handoff.context.briefing.evidence[0]).toBe('Note: Server rebooted');+ });++ it('trims surrounding whitespace on a non-command passthrough summary', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [makeEvent({ id: 'e1', type: 'note', summary: ' Server rebooted ' })],+ }),+ );+ expect(handoff.context.context.eventSummaries[0].summary).toBe('Server rebooted');+ });++ it('falls back to "Timeline event recorded" when a non-command summary is whitespace-only', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [makeEvent({ id: 'e1', type: 'note', summary: ' ' })],+ }),+ );+ expect(handoff.context.context.eventSummaries[0].summary).toBe('Timeline event recorded');+ expect(handoff.context.briefing.evidence[0]).toBe('Note: Timeline event recorded');+ });++ it('falls back to "Timeline event recorded" when a non-command summary is empty', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [makeEvent({ id: 'e1', type: 'note', summary: '' })],+ }),+ );+ expect(handoff.context.context.eventSummaries[0].summary).toBe('Timeline event recorded');+ });++ it('preserves id/type/timestamp of a sanitized command event (sanitizeIncidentEvents mapping)', () => {+ const handoff = buildHandoff(+ makeIncident({+ events: [+ makeEvent({+ id: 'evt-99',+ type: 'command_executed',+ timestamp: '2026-03-20T10:08:00Z',+ summary: 'whoami',+ }),+ ],+ }),+ );+ expect(handoff.context.context.eventSummaries[0]).toEqual({+ id: 'evt-99',+ type: 'command_executed',+ timestamp: '2026-03-20T10:08:00Z',+ summary: 'Command event recorded',+ });+ });+});++describe('formatContextLine (exercised via buildAlertIncidentAssistantHandoff)', () => {+ it('omits the "Node:" context line when node is undefined (value === undefined branch)', () => {+ const handoff = buildHandoff(makeIncident({ node: undefined }));+ expect(handoff.context.handoffContext).not.toContain('Node:');+ expect(handoff.context.briefing.detailLines).toEqual([+ '2 timeline events',+ 'Message: Container health check is failing',+ ]);+ });++ it('omits the "Instance:" context line when instance is undefined', () => {+ const handoff = buildHandoff(makeIncident({ instance: undefined }));+ expect(handoff.context.handoffContext).not.toContain('Instance:');+ });++ it('omits the "Message:" context line and briefing detailLine when message is undefined', () => {+ const handoff = buildHandoff(makeIncident({ message: undefined }));+ expect(handoff.context.handoffContext).not.toContain('Message:');+ expect(handoff.context.briefing.detailLines).toEqual([+ '2 timeline events',+ 'Node: edge-1',+ ]);+ });++ it('omits the "Node:" context line when node is an empty string (trim -> empty -> undefined)', () => {+ const handoff = buildHandoff(makeIncident({ node: '' }));+ expect(handoff.context.handoffContext).not.toContain('Node:');+ });++ it('omits the "Node:" context line when node is whitespace-only (trim -> empty)', () => {+ const handoff = buildHandoff(makeIncident({ node: ' ' }));+ expect(handoff.context.handoffContext).not.toContain('Node:');+ });++ it('renders "Node: edge-1" for a non-empty node string (happy path)', () => {+ const handoff = buildHandoff(makeIncident({ node: 'edge-1' }));+ expect(handoff.context.handoffContext).toContain('Node: edge-1');+ });++ it('coerces a numeric value to a rendered "Node: 42" line (String(value) branch)', () => {+ const handoff = buildHandoff(makeIncident({ node: 42 as unknown as string }));+ expect(handoff.context.handoffContext).toContain('Node: 42');+ expect(handoff.context.briefing.detailLines).toContain('Node: 42');+ });++ it('coerces a boolean value to a rendered "Instance: true" line (String(value) branch)', () => {+ const handoff = buildHandoff(makeIncident({ instance: true as unknown as string }));+ expect(handoff.context.handoffContext).toContain('Instance: true');+ });++ it('omits the "Closed At:" context line when closedAt is null (value === null branch)', () => {+ const handoff = buildHandoff(makeIncident({ closedAt: null as unknown as string }));+ expect(handoff.context.handoffContext).not.toContain('Closed At:');+ });++ it('renders the "Closed At:" context line when closedAt is a present string', () => {+ const handoff = buildHandoff(+ makeIncident({ closedAt: '2026-03-20T10:05:00Z' }),+ new Date('2026-03-20T11:00:00Z'),+ );+ expect(handoff.context.handoffContext).toContain('Closed At: 2026-03-20T10:05:00Z');+ });++ it('trims a whitespace-padded closedAt value to its inner text', () => {+ const handoff = buildHandoff(+ makeIncident({ closedAt: ' 2026-03-20T10:05:00Z ' as unknown as string }),+ new Date('2026-03-20T11:00:00Z'),+ );+ expect(handoff.context.handoffContext).toContain('Closed At: 2026-03-20T10:05:00Z');+ expect(handoff.context.handoffContext).not.toContain('Closed At: 2026-03-20T10:05:00Z');+ });+});++describe('buildAlertIncidentAssistantHandoff (resource-label, event-count & capping branches)', () => {+ it('uses resourceName first (|| chain 1st arm) and builds the full concrete handoff', () => {+ const handoff = buildHandoff(makeIncident(), new Date('2026-03-20T10:05:00Z'));+ // 1st arm of the resource-label || chain.+ expect(handoff.context.briefing.subject).toBe(+ 'Critical docker-container-health on checkout-api',+ );+ expect(handoff.context.handoffResources[0]).toEqual({+ id: 'docker:app-1',+ name: 'checkout-api',+ type: 'app-container',+ node: 'edge-1',+ });+ // Both node + message detailLines present (briefing ternary true arms).+ expect(handoff.context.briefing.detailLines).toEqual([+ '2 timeline events',+ 'Node: edge-1',+ 'Message: Container health check is failing',+ ]);+ // actionLabel + safetyNote concrete values.+ expect(handoff.context.briefing.actionLabel).toBe('Discuss incident incident-1');+ expect(handoff.context.briefing.safetyNote).toBe(+ 'Diagnostics and remediation require operator approval.',+ );+ // Top-level context scalars are concrete.+ expect(handoff.context.targetType).toBe('app-container');+ expect(handoff.context.targetId).toBe('docker:app-1');+ expect(handoff.context.autonomousMode).toBe(false);+ expect(handoff.context.context.alertIncidentId).toBe('incident-1');+ expect(handoff.context.context.acknowledged).toBe(false);+ expect(handoff.context.context.eventCount).toBe(2);+ });++ it('falls back to resourceId when resourceName is empty (|| chain, 2nd arm)', () => {+ const handoff = buildHandoff(makeIncident({ resourceName: '', resourceId: 'res-7' }));+ expect(handoff.context.briefing.subject).toBe('Critical docker-container-health on res-7');+ expect(handoff.context.handoffResources[0].name).toBe('res-7');+ expect(handoff.context.context.resourceName).toBe('res-7');+ expect(handoff.context.handoffContext).toContain('Resource: res-7');+ });++ it('falls back to "unknown resource" when both resourceName and resourceId are empty (|| chain, 3rd arm)', () => {+ const handoff = buildHandoff(makeIncident({ resourceName: '', resourceId: '' }));+ expect(handoff.context.briefing.subject).toBe(+ 'Critical docker-container-health on unknown resource',+ );+ expect(handoff.context.handoffResources[0].name).toBe('unknown resource');+ expect(handoff.context.context.resourceName).toBe('unknown resource');+ expect(handoff.context.handoffContext).toContain('Resource: unknown resource');+ });++ it('treats undefined events as an empty array (?? [] branch) -> "0 timeline events"', () => {+ const handoff = buildHandoff(makeIncident({ events: undefined }));+ expect(handoff.context.context.eventCount).toBe(0);+ expect(handoff.context.briefing.detailLines).toContain('0 timeline events');+ expect(handoff.context.briefing.evidence).toEqual([]);+ expect(handoff.context.context.eventSummaries).toEqual([]);+ expect(handoff.context.handoffContext).toContain('Timeline Summary: 0 timeline events');+ });++ it('uses the singular "1 timeline event" label when exactly one event is present', () => {+ const handoff = buildHandoff(makeIncident({ events: [makeEvent({ id: 'solo' })] }));+ expect(handoff.context.context.eventCount).toBe(1);+ expect(handoff.context.briefing.detailLines).toContain('1 timeline event');+ expect(handoff.context.handoffContext).toContain('Timeline Summary: 1 timeline event');+ });++ it('uses the plural "N timeline events" label for multiple events', () => {+ const handoff = buildHandoff(makeIncident());+ expect(handoff.context.briefing.detailLines).toContain('2 timeline events');+ });++ it('omits the Node detailLine when node is falsy (briefing ternary false arm)', () => {+ const handoff = buildHandoff(makeIncident({ node: undefined, message: undefined }));+ expect(handoff.context.briefing.detailLines).toEqual(['2 timeline events']);+ });++ it('caps briefing evidence at MAX_BRIEFING_EVENTS (3) when more than 3 events exist', () => {+ const events = Array.from({ length: 5 }, (_, i) =>+ makeEvent({ id: `e${i + 1}`, timestamp: '2026-03-20T10:02:00Z' }),+ );+ const handoff = buildHandoff(makeIncident({ events }));+ expect(handoff.context.briefing.evidence).toHaveLength(3);+ expect(handoff.context.context.eventCount).toBe(5);+ });++ it('caps context.eventSummaries and timeline lines at MAX_CONTEXT_EVENTS (8) when >8 events', () => {+ const events = Array.from({ length: 10 }, (_, i) =>+ makeEvent({ id: `e${i + 1}`, timestamp: '2026-03-20T10:02:00Z' }),+ );+ const handoff = buildHandoff(makeIncident({ events }));+ expect(handoff.context.context.eventSummaries).toHaveLength(8);+ expect(handoff.context.context.eventCount).toBe(10);+ expect(handoff.context.handoffContext).toContain('Timeline Event 1');+ expect(handoff.context.handoffContext).toContain('Timeline Event 8');+ expect(handoff.context.handoffContext).not.toContain('Timeline Event 9');+ });++ it('renders the fixed boundary footer lines in handoffContext', () => {+ const handoff = buildHandoff(makeIncident());+ expect(handoff.context.handoffContext).toContain(+ 'Timeline Boundary: Command events are summarized only; raw command details and output stay in the incident or governed approval surface.',+ );+ expect(handoff.context.handoffContext).toContain(+ 'Operator Boundary: This incident handoff is model-only context for explanation and review. Diagnostics, remediation, and any command execution require explicit operator approval.',+ );+ });+});diff --git a/frontend-modern/src/components/Infrastructure/__tests__/unifiedResourceTableModel.branchcov2.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/unifiedResourceTableModel.branchcov2.test.tsnew file mode 100644index 0000000000..e69fea5320--- /dev/null+++ b/frontend-modern/src/components/Infrastructure/__tests__/unifiedResourceTableModel.branchcov2.test.ts@@ -0,0 +1,340 @@+import { describe, expect, it } from 'vitest';+import type { Resource } from '@/types/resource';+import type { IODistributionStats } from '@/components/Infrastructure/infrastructureSelectors';+import {+ getOutlierEmphasis,+ getPBSTableRow,+ getPMGTableRow,+} from '@/components/Infrastructure/unifiedResourceTableModel';++/**+ * Branch-coverage suite for the still-uncovered exported functions in+ * unifiedResourceTableModel.ts: getPBSTableRow, getPMGTableRow, getOutlierEmphasis.+ * Each test drives a specific branch (guard, ternary arm, optional-chain outcome)+ * and asserts on the concrete returned shape — never truthiness alone.+ */++const makeResource = (overrides: Partial<Resource> & { id: string }): Resource =>+ ({+ type: 'agent',+ name: `name-${overrides.id}`,+ displayName: `Display ${overrides.id}`,+ platformId: `platform-${overrides.id}`,+ platformType: 'proxmox-pve',+ sourceType: 'hybrid',+ status: 'online',+ lastSeen: 1_700_000_000_000,+ platformData: {},+ ...overrides,+ }) as unknown as Resource;++const makeStats = (overrides: Partial<IODistributionStats> = {}): IODistributionStats => ({+ median: 0,+ mad: 0,+ max: 100,+ p97: 90,+ p99: 95,+ count: 10,+ ...overrides,+});++describe('getPBSTableRow', () => {+ it('returns null when resource.type is not pbs (guard)', () => {+ expect(getPBSTableRow(makeResource({ id: 'a', type: 'pmg' }))).toBeNull();+ expect(getPBSTableRow(makeResource({ id: 'b', type: 'agent' }))).toBeNull();+ });++ it('nulls every derived field when platformData has no pbs block (optional-chain miss)', () => {+ const row = getPBSTableRow(+ makeResource({ id: 'pbs-empty', type: 'pbs', status: 'online', platformData: {} }),+ );+ expect(row).toEqual({+ datastores: null,+ jobs: null,+ activity: null,+ activityDetail: null,+ activeTaskCount: 0,+ health: null,+ tone: 'ok',+ });+ });++ it('surfaces a positive datastoreCount and jobs total, trims health, and derives tone from health', () => {+ const row = getPBSTableRow(+ makeResource({+ id: 'pbs-full',+ type: 'pbs',+ status: 'degraded',+ platformData: {+ pbs: { datastoreCount: 3, backupJobCount: 2, connectionHealth: ' Healthy ' },+ },+ }),+ );+ expect(row).toEqual({+ datastores: 3,+ jobs: 2,+ activity: '2 jobs',+ activityDetail: null,+ activeTaskCount: 0,+ health: 'Healthy',+ tone: 'ok',+ });+ });++ it('nulls datastores/jobs for zero counts and maps whitespace health + offline status to a warning tone', () => {+ const row = getPBSTableRow(+ makeResource({+ id: 'pbs-zero',+ type: 'pbs',+ status: 'offline',+ platformData: { pbs: { datastoreCount: 0, connectionHealth: ' ' } },+ }),+ );+ expect(row).toEqual({+ datastores: null,+ jobs: null,+ activity: null,+ activityDetail: null,+ activeTaskCount: 0,+ health: null,+ tone: 'warning',+ });+ });+});++describe('getPMGTableRow', () => {+ it('returns null when resource.type is not pmg (guard)', () => {+ expect(getPMGTableRow(makeResource({ id: 'a', type: 'pbs' }))).toBeNull();+ expect(getPMGTableRow(makeResource({ id: 'b', type: 'agent' }))).toBeNull();+ });++ it('nulls every derived field when platformData has no pmg block (optional-chain miss)', () => {+ const row = getPMGTableRow(+ makeResource({ id: 'pmg-empty', type: 'pmg', status: 'online', platformData: {} }),+ );+ expect(row).toEqual({+ queue: null,+ deferred: null,+ hold: null,+ nodes: null,+ health: null,+ tone: 'ok',+ });+ });++ it('reports positive queue/deferred/hold/nodes and forces a warning tone when backlog > 0', () => {+ const row = getPMGTableRow(+ makeResource({+ id: 'pmg-full',+ type: 'pmg',+ status: 'online',+ platformData: {+ pmg: {+ queueTotal: 12,+ queueDeferred: 3,+ queueHold: 2,+ nodeCount: 4,+ connectionHealth: 'degraded',+ },+ },+ }),+ );+ expect(row).toEqual({+ queue: 12,+ deferred: 3,+ hold: 2,+ nodes: 4,+ health: 'degraded',+ tone: 'warning',+ });+ });++ it('nulls zero counts, trims whitespace health to null, and derives tone from status when backlog is 0', () => {+ const row = getPMGTableRow(+ makeResource({+ id: 'pmg-zero',+ type: 'pmg',+ status: 'warning',+ platformData: {+ pmg: {+ queueTotal: 5,+ queueDeferred: 0,+ queueHold: 0,+ nodeCount: 0,+ connectionHealth: ' ',+ },+ },+ }),+ );+ expect(row).toEqual({+ queue: 5,+ deferred: null,+ hold: null,+ nodes: null,+ health: null,+ tone: 'warning',+ });+ });++ it('nulls queue when queueTotal is explicitly 0 with a present pmg block', () => {+ const row = getPMGTableRow(+ makeResource({+ id: 'pmg-no-queue',+ type: 'pmg',+ status: 'online',+ platformData: { pmg: { queueTotal: 0, nodeCount: 1 } },+ }),+ );+ expect(row).toEqual({+ queue: null,+ deferred: null,+ hold: null,+ nodes: 1,+ health: null,+ tone: 'ok',+ });+ });+});++describe('getOutlierEmphasis', () => {+ describe('guard branch (!isFinite(value) || value <= 0 || stats.max <= 0)', () => {+ it('mutes a non-finite value (NaN)', () => {+ expect(getOutlierEmphasis(Number.NaN, makeStats({ max: 100 }))).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });++ it('mutes a non-finite value (Infinity)', () => {+ expect(getOutlierEmphasis(Number.POSITIVE_INFINITY, makeStats({ max: 100 }))).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });++ it('mutes a value of exactly 0', () => {+ expect(getOutlierEmphasis(0, makeStats({ max: 100 }))).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });++ it('mutes a negative value', () => {+ expect(getOutlierEmphasis(-5, makeStats({ max: 100 }))).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });++ it('mutes when stats.max is 0', () => {+ expect(getOutlierEmphasis(50, makeStats({ max: 0 }))).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });++ it('mutes when stats.max is negative', () => {+ expect(getOutlierEmphasis(50, makeStats({ max: -1 }))).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });+ });++ describe('small-sample branch (stats.count < 4)', () => {+ it('emphasizes when value/max ratio >= 0.995 (exact boundary)', () => {+ expect(getOutlierEmphasis(99.5, makeStats({ max: 100, count: 3 }))).toEqual({+ className: 'text-base-content font-medium',+ showOutlierHint: true,+ });+ });++ it('emphasizes a ratio of 1.0', () => {+ expect(getOutlierEmphasis(100, makeStats({ max: 100, count: 3 }))).toEqual({+ className: 'text-base-content font-medium',+ showOutlierHint: true,+ });+ });++ it('mutes when value/max ratio < 0.995', () => {+ expect(getOutlierEmphasis(80, makeStats({ max: 100, count: 3 }))).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });+ });++ describe('mad-positive branch (stats.count >= 4, stats.mad > 0)', () => {+ it('returns semibold for a severe outlier (modifiedZ >= 6.5 and value >= p99)', () => {+ // modifiedZ = 0.6745 * (200 - 50) / 2 = 50.5875 (>= 6.5); value 200 >= p99 180+ const stats = makeStats({ median: 50, mad: 2, max: 200, p97: 150, p99: 180, count: 10 });+ expect(getOutlierEmphasis(200, stats)).toEqual({+ className: 'text-base-content font-semibold',+ showOutlierHint: true,+ });+ });++ it('returns medium when modifiedZ is in [5.5, 6.5) and value >= p97 but < p99', () => {+ // modifiedZ = 0.6745 * (90 - 0) / 10 = 6.0705 (in [5.5, 6.5)); value 90 >= p97 80, < p99 200+ const stats = makeStats({ median: 0, mad: 10, max: 300, p97: 80, p99: 200, count: 10 });+ expect(getOutlierEmphasis(90, stats)).toEqual({+ className: 'text-base-content font-medium',+ showOutlierHint: true,+ });+ });++ it('mutes a non-outlier whose modifiedZ is below 5.5', () => {+ // modifiedZ = 0.6745 * (55 - 50) / 10 = 0.337 (< 5.5)+ const stats = makeStats({ median: 50, mad: 10, max: 200, p97: 80, p99: 180, count: 10 });+ expect(getOutlierEmphasis(55, stats)).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });++ it('falls through to medium when modifiedZ >= 6.5 but value < p99 (skips severe, hits moderate)', () => {+ // modifiedZ = 0.6745 * (70 - 50) / 2 = 6.745 (>= 6.5); value 70 >= p99 80 is FALSE;+ // value 70 >= p97 60 is TRUE -> moderate path.+ const stats = makeStats({ median: 50, mad: 2, max: 200, p97: 60, p99: 80, count: 10 });+ expect(getOutlierEmphasis(70, stats)).toEqual({+ className: 'text-base-content font-medium',+ showOutlierHint: true,+ });+ });+ });++ describe('mad-zero fallback branch (stats.count >= 4, stats.mad <= 0)', () => {+ it('returns semibold when value >= p99', () => {+ const stats = makeStats({ mad: 0, max: 300, p97: 120, p99: 150, count: 10 });+ expect(getOutlierEmphasis(200, stats)).toEqual({+ className: 'text-base-content font-semibold',+ showOutlierHint: true,+ });+ });++ it('returns medium when value >= p97 but < p99', () => {+ const stats = makeStats({ mad: 0, max: 300, p97: 120, p99: 150, count: 10 });+ expect(getOutlierEmphasis(130, stats)).toEqual({+ className: 'text-base-content font-medium',+ showOutlierHint: true,+ });+ });++ it('mutes a positive value below p97', () => {+ const stats = makeStats({ mad: 0, max: 300, p97: 120, p99: 150, count: 10 });+ expect(getOutlierEmphasis(50, stats)).toEqual({+ className: 'text-muted',+ showOutlierHint: false,+ });+ });++ it('honors an explicitly negative mad identically to mad === 0', () => {+ // Defensive: mad <= 0 takes the fallback path; -1 must behave like 0.+ const stats = makeStats({ mad: -1, max: 300, p97: 120, p99: 150, count: 10 });+ expect(getOutlierEmphasis(200, stats)).toEqual({+ className: 'text-base-content font-semibold',+ showOutlierHint: true,+ });+ });+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/reportingCatalogModel.branchcov2.test.ts b/frontend-modern/src/components/Settings/__tests__/reportingCatalogModel.branchcov2.test.tsnew file mode 100644index 0000000000..b451dc65fd--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/reportingCatalogModel.branchcov2.test.ts@@ -0,0 +1,603 @@+/**+ * Branch-coverage tests for the still-uncovered named helpers in+ * reportingCatalogModel:+ * parseReportingFormatDefinition, parseReportingRangeDefinition,+ * parseReportingPerformanceReportDefinition, parseReportingCatalog,+ * parseReportingLockedStateDefinition, parseReportingGuidanceDefinition.+ *+ * None of those six helpers are exported from the module, so every branch is+ * driven through the single exported entry point `parseReportingCatalog` —+ * the only public caller — exactly as the sibling `reportingCatalogModel.test.ts`+ * reaches them. Each block targets one helper and drives both arms (happy path+ * + each defensive throw) of every conditional / typeof / Number.isFinite /+ * Array.isArray guard, asserting concrete emitted shapes (never truthiness-only).+ *+ * Import path mirrors the sibling test (alias `@/...`).+ */+import { describe, expect, it } from 'vitest';+import {+ parseReportingCatalog,+ type ReportingCatalog,+} from '@/components/Settings/reportingCatalogModel';++type CatalogInput = Parameters<typeof parseReportingCatalog>[0];++const INVALID = 'Invalid reporting catalog payload';+const expectInvalid = (input: CatalogInput) =>+ expect(() => parseReportingCatalog(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.++const baseRange = () => ({+ key: '24h',+ label: 'Last 24 Hours',+ description: 'Daily review',+ windowHours: 24,+});++const basePerformanceReport = () => ({+ id: 'performance_reports',+ title: 'Performance Reports',+ description: 'Historical performance reporting',+ singleResourceEndpoint: '/api/admin/reports/generate',+ multiResourceEndpoint: '/api/admin/reports/generate-multi',+ singleFilenamePrefix: 'report',+ singleFilenameSubject: 'resource_id',+ multiFilenamePrefix: 'fleet-report',+ filenameDateStyle: 'utc_yyyymmdd',+ formats: [+ { value: 'pdf', label: 'PDF Report' },+ { value: 'csv', label: 'CSV Data' },+ ],+ defaultFormat: 'pdf',+ ranges: [baseRange()],+ defaultRange: '24h',+ multiResourceMax: 50,+ supportsMetricFilter: true,+ supportsCustomTitle: true,+});++const baseVmInventoryExport = () => ({+ id: 'vm_inventory',+ title: 'VM Inventory Export',+ description: 'Current-state 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.',+ },+ ],+});++const baseCatalog = () => ({+ id: 'advanced_reporting',+ title: 'Detailed Reporting',+ description: 'Canonical reporting surfaces',+ lockedState: {+ title: 'Advanced Reporting',+ description: 'Canonical locked reporting teaser',+ },+ guidance: {+ title: 'Advanced Insights',+ description: 'Catalog-owned reporting guidance',+ },+ performanceReport: basePerformanceReport(),+ vmInventoryExport: null,+});++// ---- parseReportingCatalog --------------------------------------------------++describe('parseReportingCatalog (entry-point branches)', () => {+ it('throws on a non-object input (null / undefined / primitive arms)', () => {+ expectInvalid(null);+ expectInvalid(undefined);+ expectInvalid('not-an-object');+ expectInvalid(42);+ expectInvalid(true);+ });++ it('throws when id is not a string', () => {+ expectInvalid({ ...baseCatalog(), id: 123 });+ });++ it('throws when title is not a string', () => {+ expectInvalid({ ...baseCatalog(), title: null });+ });++ it('throws when description is not a string', () => {+ expectInvalid({ ...baseCatalog(), description: 7 });+ });++ it('round-trips the full catalog shape when vmInventoryExport is null (null arm)', () => {+ const catalog = parseReportingCatalog(baseCatalog()) as ReportingCatalog;+ expect(catalog).toStrictEqual({+ id: 'advanced_reporting',+ title: 'Detailed Reporting',+ description: 'Canonical reporting surfaces',+ lockedState: {+ title: 'Advanced Reporting',+ description: 'Canonical locked reporting teaser',+ },+ guidance: {+ title: 'Advanced Insights',+ description: 'Catalog-owned reporting guidance',+ },+ performanceReport: basePerformanceReport(),+ vmInventoryExport: null,+ });+ // Explicit null-arm assertion.+ expect(catalog.vmInventoryExport).toBeNull();+ });++ it('parses the inventory export when vmInventoryExport is present (non-null arm)', () => {+ const catalog = parseReportingCatalog({+ ...baseCatalog(),+ vmInventoryExport: baseVmInventoryExport(),+ }) as ReportingCatalog;+ expect(catalog.vmInventoryExport).not.toBeNull();+ expect(catalog.vmInventoryExport).toStrictEqual({+ id: 'vm_inventory',+ title: 'VM Inventory Export',+ description: 'Current-state 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.',+ },+ ],+ });+ });+});++// ---- parseReportingLockedStateDefinition -----------------------------------++describe('parseReportingLockedStateDefinition (via catalog.lockedState)', () => {+ it('throws when lockedState is not an object (null / primitive arms)', () => {+ expectInvalid({ ...baseCatalog(), lockedState: null });+ expectInvalid({ ...baseCatalog(), lockedState: 'nope' });+ expectInvalid({ ...baseCatalog(), lockedState: 5 });+ });++ it('throws when lockedState.title is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ lockedState: { title: 9, description: 'ok' },+ });+ });++ it('throws when lockedState.description is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ lockedState: { title: 'Advanced Reporting', description: null },+ });+ });++ it('round-trips a fully-populated locked state', () => {+ const catalog = parseReportingCatalog({+ ...baseCatalog(),+ lockedState: { title: 'Locked', description: 'Teaser copy' },+ }) as ReportingCatalog;+ expect(catalog.lockedState).toStrictEqual({+ title: 'Locked',+ description: 'Teaser copy',+ });+ });+});++// ---- parseReportingGuidanceDefinition --------------------------------------++describe('parseReportingGuidanceDefinition (via catalog.guidance)', () => {+ it('throws when guidance is not an object (null / primitive arms)', () => {+ expectInvalid({ ...baseCatalog(), guidance: null });+ expectInvalid({ ...baseCatalog(), guidance: 'nope' });+ expectInvalid({ ...baseCatalog(), guidance: 5 });+ });++ it('throws when guidance.title is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ guidance: { title: 9, description: 'ok' },+ });+ });++ it('throws when guidance.description is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ guidance: { title: 'Advanced Insights', description: null },+ });+ });++ it('round-trips a fully-populated guidance block', () => {+ const catalog = parseReportingCatalog({+ ...baseCatalog(),+ guidance: { title: 'Guided', description: 'Helpful copy' },+ }) as ReportingCatalog;+ expect(catalog.guidance).toStrictEqual({+ title: 'Guided',+ description: 'Helpful copy',+ });+ });+});++// ---- parseReportingFormatDefinition ----------------------------------------++describe('parseReportingFormatDefinition (via performanceReport.formats[])', () => {+ it('throws when a format entry is not an object (null / primitive arms)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ formats: [null, { value: 'csv', label: 'CSV Data' }],+ },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ formats: ['pdf-only' as unknown as object, { value: 'csv', label: 'CSV Data' }],+ },+ });+ });++ it('throws when a format value is neither "pdf" nor "csv"', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ formats: [+ { value: 'xlsx', label: 'XLSX' },+ { value: 'csv', label: 'CSV Data' },+ ],+ defaultFormat: 'csv',+ },+ });+ });++ it('throws when a format label is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ formats: [+ { value: 'pdf', label: 42 },+ { value: 'csv', label: 'CSV Data' },+ ],+ },+ });+ });++ it('round-trips both pdf and csv format entries unchanged', () => {+ const catalog = parseReportingCatalog({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ formats: [+ { value: 'pdf', label: 'PDF Report' },+ { value: 'csv', label: 'CSV Data' },+ ],+ },+ }) as ReportingCatalog;+ expect(catalog.performanceReport.formats).toStrictEqual([+ { value: 'pdf', label: 'PDF Report' },+ { value: 'csv', label: 'CSV Data' },+ ]);+ });+});++// ---- parseReportingRangeDefinition -----------------------------------------++describe('parseReportingRangeDefinition (via performanceReport.ranges[])', () => {+ it('throws when a range entry is not an object (null / primitive arms)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [null],+ },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: ['24h' as unknown as object],+ },+ });+ });++ it('throws when key is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), key: 24 }],+ },+ });+ });++ it('throws when label is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), label: null }],+ },+ });+ });++ it('throws when description is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), description: 1 }],+ },+ });+ });++ it('throws when windowHours is not a number', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), windowHours: '24' }],+ },+ });+ });++ it('throws when windowHours is not finite (NaN / Infinity)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), windowHours: Number.NaN }],+ },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), windowHours: Number.POSITIVE_INFINITY }],+ },+ });+ });++ it('throws when windowHours is <= 0 (zero and negative arms)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), windowHours: 0 }],+ },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [{ ...baseRange(), windowHours: -12 }],+ },+ });+ });++ it('round-trips a fully-populated range unchanged', () => {+ const catalog = parseReportingCatalog({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ ranges: [+ {+ key: '7d',+ label: 'Last 7 Days',+ description: 'Weekly trend',+ windowHours: 168,+ },+ ],+ defaultRange: '7d',+ },+ }) as ReportingCatalog;+ expect(catalog.performanceReport.ranges).toStrictEqual([+ {+ key: '7d',+ label: 'Last 7 Days',+ description: 'Weekly trend',+ windowHours: 168,+ },+ ]);+ });+});++// ---- parseReportingPerformanceReportDefinition -----------------------------++describe('parseReportingPerformanceReportDefinition (via catalog.performanceReport)', () => {+ it('throws when performanceReport is not an object (null / primitive arms)', () => {+ expectInvalid({ ...baseCatalog(), performanceReport: null });+ expectInvalid({ ...baseCatalog(), performanceReport: 'nope' });+ });++ it('throws when id is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), id: 1 },+ });+ });++ it('throws when title is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), title: null },+ });+ });++ it('throws when description is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), description: 2 },+ });+ });++ it('throws when singleResourceEndpoint is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), singleResourceEndpoint: 3 },+ });+ });++ it('throws when multiResourceEndpoint is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), multiResourceEndpoint: null },+ });+ });++ it('throws when singleFilenamePrefix is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), singleFilenamePrefix: 4 },+ });+ });++ it('throws when singleFilenameSubject is not "resource_id"', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ singleFilenameSubject: 'resource_name',+ },+ });+ });++ it('throws when multiFilenamePrefix is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), multiFilenamePrefix: null },+ });+ });++ it('throws when filenameDateStyle is not "utc_yyyymmdd"', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ filenameDateStyle: 'local_yyyy_mm_dd',+ },+ });+ });++ it('throws when formats is not an array', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), formats: null },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), formats: 'pdf,csv' },+ });+ });++ it('throws when defaultFormat is neither "pdf" nor "csv"', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), defaultFormat: 'xlsx' },+ });+ });++ it('throws when ranges is not an array', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), ranges: null },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), ranges: '24h' },+ });+ });++ it('throws when defaultRange is not a string', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), defaultRange: 24 },+ });+ });++ it('throws when multiResourceMax is not a number', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), multiResourceMax: '50' },+ });+ });++ it('throws when multiResourceMax is not finite (NaN / Infinity)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), multiResourceMax: Number.NaN },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: {+ ...basePerformanceReport(),+ multiResourceMax: Number.POSITIVE_INFINITY,+ },+ });+ });++ it('throws when multiResourceMax is <= 0 (zero and negative arms)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), multiResourceMax: 0 },+ });+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), multiResourceMax: -5 },+ });+ });++ it('throws when supportsMetricFilter is not a boolean', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), supportsMetricFilter: 'yes' },+ });+ });++ it('throws when supportsCustomTitle is not a boolean', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), supportsCustomTitle: 1 },+ });+ });++ it('throws when the formats array is empty (length === 0 arm)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), formats: [] },+ });+ });++ it('throws when the ranges array is empty (length === 0 arm)', () => {+ expectInvalid({+ ...baseCatalog(),+ performanceReport: { ...basePerformanceReport(), ranges: [] },+ });+ });++ it('round-trips a fully-populated performance report unchanged', () => {+ const expected = basePerformanceReport();+ const catalog = parseReportingCatalog(baseCatalog()) as ReportingCatalog;+ expect(catalog.performanceReport).toStrictEqual(expected);+ // Spot-check the parsed literal unions.+ expect(catalog.performanceReport.defaultFormat).toBe('pdf');+ expect(catalog.performanceReport.defaultRange).toBe('24h');+ expect(catalog.performanceReport.singleFilenameSubject).toBe('resource_id');+ expect(catalog.performanceReport.filenameDateStyle).toBe('utc_yyyymmdd');+ });+});diff --git a/frontend-modern/src/features/docker/__tests__/dockerImagePresentation.branchcov2.test.ts b/frontend-modern/src/features/docker/__tests__/dockerImagePresentation.branchcov2.test.tsnew file mode 100644index 0000000000..3f556a5c10--- /dev/null+++ b/frontend-modern/src/features/docker/__tests__/dockerImagePresentation.branchcov2.test.ts@@ -0,0 +1,562 @@+import { describe, expect, it } from 'vitest';++import type { Resource } from '@/types/resource';++import { getDockerImageOperationalPresentation } from '../dockerImagePresentation';++const image = (overrides: Partial<Resource> = {}): Resource => ({+ id: 'docker-image:host:nginx',+ name: 'nginx',+ displayName: 'nginx:latest',+ platformId: 'docker-1',+ platformType: 'docker',+ sourceType: 'agent',+ sources: ['docker'],+ status: 'running',+ type: 'docker-image',+ lastSeen: 1_700_000_000_000,+ docker: { runtime: 'docker', image: 'nginx:latest', imageId: 'sha256:abc' },+ ...overrides,+});++const container = (overrides: Partial<Resource> = {}): Resource => ({+ id: 'app-container:docker-host:web',+ name: 'web',+ displayName: 'web',+ platformId: 'docker-1',+ platformType: 'docker',+ sourceType: 'agent',+ sources: ['docker'],+ status: 'running',+ type: 'app-container',+ lastSeen: 1_700_000_000_000,+ docker: { runtime: 'docker', agentId: 'agent-1', containerId: 'cid-web', image: 'nginx:latest' },+ ...overrides,+});++describe('dockerImagePresentation.branchcov2', () => {+ describe('imageIdentityTokens (exercised via consumer matching)', () => {+ it('matches a container whose docker.image equals the image docker.image token', () => {+ const result = getDockerImageOperationalPresentation(image(), [+ container({ docker: { runtime: 'docker', image: 'nginx:latest' } }),+ ]);+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('web');+ });++ it('matches a container whose docker.imageId equals the image docker.imageId token', () => {+ const result = getDockerImageOperationalPresentation(image(), [+ container({+ id: 'app-container:docker-host:by-digest',+ name: 'by-digest',+ docker: {+ runtime: 'docker',+ imageId: 'sha256:abc',+ },+ }),+ ]);+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('by-digest');+ });++ it('matches a container whose docker.image equals the image resource id', () => {+ const result = getDockerImageOperationalPresentation(+ image({ docker: { runtime: 'docker' } }),+ [+ container({+ id: 'app-container:docker-host:by-rid',+ name: 'by-rid',+ docker: { runtime: 'docker', image: 'docker-image:host:nginx' },+ }),+ ],+ );+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('by-rid');+ });++ it('matches a container whose docker.image equals the image resource name', () => {+ const result = getDockerImageOperationalPresentation(+ image({ name: 'nginx', docker: { runtime: 'docker' } }),+ [+ container({+ id: 'app-container:docker-host:by-name',+ name: 'by-name',+ docker: { runtime: 'docker', image: 'nginx' },+ }),+ ],+ );+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('by-name');+ });++ it('matches a container whose docker.image equals the image resource displayName', () => {+ const result = getDockerImageOperationalPresentation(+ image({ name: 'other', docker: { runtime: 'docker' } }),+ [+ container({+ id: 'app-container:docker-host:by-display',+ name: 'by-display',+ docker: { runtime: 'docker', image: 'nginx:latest' },+ }),+ ],+ );+ // displayName default is 'nginx:latest'+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('by-display');+ });++ it('matches a container whose docker.image equals one of docker.repoTags (spread arm)', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ repoTags: ['nginx:1.25', 'nginx:stable'],+ },+ }),+ [+ container({+ id: 'app-container:docker-host:by-tag',+ name: 'by-tag',+ docker: { runtime: 'docker', image: 'nginx:stable' },+ }),+ ],+ );+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('by-tag');+ });++ it('uses the ?? [] fallback when docker.repoTags is undefined', () => {+ // docker present but repoTags absent; a bogus tag must not match, real token must.+ const result = getDockerImageOperationalPresentation(image(), [+ container({+ id: 'app-container:docker-host:nope',+ name: 'nope',+ docker: { runtime: 'docker', image: 'never-a-token' },+ }),+ container({+ id: 'app-container:docker-host:real',+ name: 'real',+ docker: { runtime: 'docker', image: 'nginx:latest' },+ }),+ ]);+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('real');+ });++ it('still builds tokens from id/name/displayName when docker is absent entirely', () => {+ const result = getDockerImageOperationalPresentation(+ image({ name: 'standalone', displayName: 'standalone', docker: undefined }),+ [+ container({+ id: 'app-container:docker-host:by-name',+ name: 'by-name',+ docker: { runtime: 'docker', image: 'standalone' },+ }),+ ],+ );+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('by-name');+ });++ it('filters blank/whitespace identity values out of the token set', () => {+ // Every identity field blank/whitespace -> only docker.image provides a usable token.+ const result = getDockerImageOperationalPresentation(+ image({+ id: ' ',+ name: '',+ displayName: ' ',+ docker: { runtime: 'docker', image: 'only-token' },+ }),+ [+ // A container referencing the (blank) id/name must NOT match.+ container({+ id: 'app-container:docker-host:blank',+ name: 'blank',+ docker: { runtime: 'docker', image: ' ' },+ }),+ container({+ id: 'app-container:docker-host:hit',+ name: 'hit',+ docker: { runtime: 'docker', image: 'only-token' },+ }),+ ],+ );+ expect(result.consumerCount).toBe(1);+ expect(result.consumerSummary).toBe('hit');+ });++ it('ignores a container whose docker.image and docker.imageId are both blank', () => {+ const result = getDockerImageOperationalPresentation(image(), [+ container({+ id: 'app-container:docker-host:blank',+ name: 'blank',+ docker: { runtime: 'docker', image: ' ', imageId: '' },+ }),+ ]);+ expect(result.consumerCount).toBe(0);+ expect(result.consumerSummary).toBe('Unused');+ });+ });++ describe('resourceLabel (exercised via consumer labels)', () => {+ const imageWithToken = image({ docker: { runtime: 'docker', image: 'nginx:latest' } });++ it('prefers the trimmed resource name when present', () => {+ const result = getDockerImageOperationalPresentation(imageWithToken, [+ container({ name: ' web-app ', displayName: 'ignored', id: 'should-not-show' }),+ ]);+ expect(result.consumerSummary).toBe('web-app');+ });++ it('falls back to trimmed displayName when name is blank', () => {+ const result = getDockerImageOperationalPresentation(imageWithToken, [+ container({ name: ' ', displayName: ' Web App ', id: 'should-not-show' }),+ ]);+ expect(result.consumerSummary).toBe('Web App');+ });++ it('falls back to the raw resource id when name and displayName are both blank', () => {+ const result = getDockerImageOperationalPresentation(imageWithToken, [+ container({ name: '', displayName: ' ', id: 'app-container:docker-host:fallback' }),+ ]);+ // NOTE: resourceLabel returns resource.id untrimmed (asymmetric vs name/displayName).+ expect(result.consumerSummary).toBe('app-container:docker-host:fallback');+ });+ });++ describe('summarizeConsumers (exercised via consumerSummary)', () => {+ const tokenImage = image({ docker: { runtime: 'docker', image: 'nginx:latest' } });+ const matching = (name: string, id: string): Resource =>+ container({+ id,+ name,+ displayName: name,+ docker: { runtime: 'docker', image: 'nginx:latest' },+ });++ it('returns "Unused" when there are no consumers and reportedCount <= 0', () => {+ const result = getDockerImageOperationalPresentation(tokenImage, []);+ expect(result.consumerSummary).toBe('Unused');+ expect(result.consumerCount).toBe(0);+ });++ it('clamps a negative reportedCount to 0 and still returns "Unused"', () => {+ const result = getDockerImageOperationalPresentation(+ image({ docker: { runtime: 'docker', image: 'nginx:latest', imageContainers: -3 } }),+ [],+ );+ expect(result.consumerSummary).toBe('Unused');+ expect(result.consumerCount).toBe(0);+ });++ it('treats a missing imageContainers as 0 via ?? and returns "Unused"', () => {+ const result = getDockerImageOperationalPresentation(+ image({ docker: { runtime: 'docker', image: 'nginx:latest' } }),+ [],+ );+ expect(result.consumerSummary).toBe('Unused');+ });++ it('uses the singular form when reportedCount === 1 and no real consumers', () => {+ const result = getDockerImageOperationalPresentation(+ image({ docker: { runtime: 'docker', image: 'nginx:latest', imageContainers: 1 } }),+ [],+ );+ expect(result.consumerSummary).toBe('1 container');+ expect(result.consumerCount).toBe(1);+ });++ it('uses the plural form when reportedCount > 1 and no real consumers', () => {+ const result = getDockerImageOperationalPresentation(+ image({ docker: { runtime: 'docker', image: 'nginx:latest', imageContainers: 3 } }),+ [],+ );+ expect(result.consumerSummary).toBe('3 containers');+ expect(result.consumerCount).toBe(3);+ });++ it('renders a single consumer label verbatim', () => {+ const result = getDockerImageOperationalPresentation(tokenImage, [matching('web', 'c1')]);+ expect(result.consumerSummary).toBe('web');+ expect(result.consumerCount).toBe(1);+ });++ it('joins exactly two consumer labels with a comma', () => {+ const result = getDockerImageOperationalPresentation(tokenImage, [+ matching('web', 'c1'),+ matching('api', 'c2'),+ ]);+ expect(result.consumerSummary).toBe('web, api');+ expect(result.consumerCount).toBe(2);+ });++ it('collapses additional consumers beyond the first two into "+N" (extra > 0 arm)', () => {+ const result = getDockerImageOperationalPresentation(tokenImage, [+ matching('web', 'c1'),+ matching('api', 'c2'),+ matching('worker', 'c3'),+ ]);+ expect(result.consumerSummary).toBe('web, api +1');+ expect(result.consumerCount).toBe(3);+ });++ it('shows a growing +N count as extras increase (extra > 0 arm, N>1)', () => {+ const result = getDockerImageOperationalPresentation(tokenImage, [+ matching('web', 'c1'),+ matching('api', 'c2'),+ matching('worker', 'c3'),+ matching('scheduler', 'c4'),+ ]);+ expect(result.consumerSummary).toBe('web, api +2');+ expect(result.consumerCount).toBe(4);+ });++ it('reports a discrepancy when reportedCount exceeds the real consumer count', () => {+ // SUSPECTED SOURCE BUG: consumerCount (5) and the named summary ("web, api") disagree;+ // there is no "+3" accounting for the unrepresented containers.+ const result = getDockerImageOperationalPresentation(+ image({ docker: { runtime: 'docker', image: 'nginx:latest', imageContainers: 5 } }),+ [matching('web', 'c1'), matching('api', 'c2')],+ );+ expect(result.consumerCount).toBe(5);+ expect(result.consumerSummary).toBe('web, api');+ });+ });++ describe('getDockerImageOperationalPresentation (update-state branches)', () => {+ it('returns the danger branch when an updateStatus has a non-empty error', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { error: 'registry unreachable' },+ },+ }),+ [],+ );+ expect(result).toStrictEqual({+ consumerCount: 0,+ consumerSummary: 'Unused',+ updateLabel: 'Check failed',+ updateDetail: 'registry unreachable',+ updateTone: 'danger',+ });+ });++ it('trims the error text for updateDetail', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { error: ' boom ' },+ },+ }),+ [],+ );+ expect(result.updateLabel).toBe('Check failed');+ expect(result.updateDetail).toBe('boom');+ expect(result.updateTone).toBe('danger');+ });++ it('does NOT enter the danger branch when error is whitespace-only (falls through)', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { error: ' ', updateAvailable: true },+ },+ }),+ [],+ );+ expect(result.updateLabel).toBe('Update available');+ expect(result.updateTone).toBe('warning');+ });++ it('does NOT enter the danger branch when error is undefined (falls through)', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { updateAvailable: false },+ },+ }),+ [],+ );+ expect(result.updateLabel).toBe('Current');+ expect(result.updateTone).toBe('success');+ });++ it('returns the warning branch when some state has updateAvailable === true', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { updateAvailable: true },+ },+ }),+ [],+ );+ expect(result.updateLabel).toBe('Update available');+ expect(result.updateDetail).toBe(+ 'At least one running container is behind the latest reported digest.',+ );+ expect(result.updateTone).toBe('warning');+ });++ it('returns the success branch when some state has updateAvailable === false (and none true)', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { updateAvailable: false },+ },+ }),+ [],+ );+ expect(result.updateLabel).toBe('Current');+ expect(result.updateDetail).toBe('No newer digest was reported by the last image check.');+ expect(result.updateTone).toBe('success');+ });++ it('returns the muted branch when updateStatus is present but updateAvailable is undefined', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { currentDigest: 'sha256:1' },+ },+ }),+ [],+ );+ expect(result.updateLabel).toBe('Not checked');+ expect(result.updateDetail).toBe('No update comparison has been reported for this image.');+ expect(result.updateTone).toBe('muted');+ });++ it('returns the muted branch when there is no updateStatus at all', () => {+ const result = getDockerImageOperationalPresentation(image(), []);+ expect(result.updateLabel).toBe('Not checked');+ expect(result.updateTone).toBe('muted');+ });++ it('prefers the danger branch over updateAvailable === true (precedence)', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { updateAvailable: true, error: 'check blew up' },+ },+ }),+ [],+ );+ expect(result.updateLabel).toBe('Check failed');+ expect(result.updateTone).toBe('danger');+ });++ it('prefers updateAvailable === true over false across mixed states (some() short-circuit)', () => {+ const result = getDockerImageOperationalPresentation(+ image({+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { updateAvailable: false },+ },+ }),+ [+ container({+ name: 'stale',+ id: 'c1',+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { updateAvailable: true },+ },+ }),+ ],+ );+ expect(result.updateLabel).toBe('Update available');+ expect(result.updateTone).toBe('warning');+ });++ it('lets a matching container drive the danger branch even when the image has no error', () => {+ const result = getDockerImageOperationalPresentation(image(), [+ container({+ name: 'broken',+ id: 'c1',+ docker: {+ runtime: 'docker',+ image: 'nginx:latest',+ updateStatus: { error: 'container check failed' },+ },+ }),+ ]);+ expect(result.updateLabel).toBe('Check failed');+ expect(result.updateDetail).toBe('container check failed');+ expect(result.updateTone).toBe('danger');+ expect(result.consumerSummary).toBe('broken');+ });++ it('ignores a non-matching container updateStatus (not in consumers spread)', () => {+ const result = getDockerImageOperationalPresentation(image(), [+ container({+ name: 'unrelated',+ id: 'c1',+ docker: {+ runtime: 'docker',+ image: 'totally-different:image',+ updateStatus: { error: 'should-be-ignored' },+ },+ }),+ ]);+ // Container did not match image tokens -> its updateStatus is excluded.+ expect(result.updateLabel).toBe('Not checked');+ expect(result.updateTone).toBe('muted');+ expect(result.consumerCount).toBe(0);+ });++ it('uses the default empty containers array when the second argument is omitted', () => {+ const result = getDockerImageOperationalPresentation(image());+ expect(result).toStrictEqual({+ consumerCount: 0,+ consumerSummary: 'Unused',+ updateLabel: 'Not checked',+ updateDetail: 'No update comparison has been reported for this image.',+ updateTone: 'muted',+ });+ });++ it('computes consumerCount as max(reportedCount, consumers.length)', () => {+ const result = getDockerImageOperationalPresentation(+ image({ docker: { runtime: 'docker', image: 'nginx:latest', imageContainers: 2 } }),+ [+ container({+ name: 'a',+ id: 'c1',+ docker: { runtime: 'docker', image: 'nginx:latest' },+ }),+ container({+ name: 'b',+ id: 'c2',+ docker: { runtime: 'docker', image: 'nginx:latest' },+ }),+ container({+ name: 'c',+ id: 'c3',+ docker: { runtime: 'docker', image: 'nginx:latest' },+ }),+ ],+ );+ // reportedCount=2, real consumers=3 -> max wins on the count, summary shows all three.+ expect(result.consumerCount).toBe(3);+ expect(result.consumerSummary).toBe('a, b +1');+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/agentContextPresentation.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/agentContextPresentation.branchcov2.test.tsnew file mode 100644index 0000000000..1a25cbe0f4--- /dev/null+++ b/frontend-modern/src/utils/__tests__/agentContextPresentation.branchcov2.test.ts@@ -0,0 +1,517 @@+import { describe, expect, it } from 'vitest';+import type {+ AgentResourceContext,+ AgentResourceContextFact,+ AgentResourceContextRedaction,+ AgentResourceContextSection,+} from '@/api/agentContext';+import { formatAgentResourceContextForClipboard } from '@/utils/agentContextPresentation';++// `formatOptionalTime`, `formatProvenance`, `formatSectionHeader`, `formatFact`+// and `formatRedaction` are all module-private (not exported). Their branches+// are exercised transitively through `formatAgentResourceContextForClipboard`,+// which is the only public entry point — same approach the sibling+// `actionAuditPresentation.branchcov2` test takes for its private helper.++// Minimal valid context factory. Each test overrides only the fields it needs+// to drive a specific branch, keeping the intent of the assertion legible.+const baseContext = (overrides: Partial<AgentResourceContext> = {}): AgentResourceContext => ({+ canonicalId: 'host:node-1',+ resourceType: 'host',+ resourceName: 'node-1',+ activeFindings: [],+ pendingApprovals: [],+ recentActions: [],+ generatedAt: '2026-05-06T14:00:00Z',+ contextSections: [],+ ...overrides,+});++const baseSection = (overrides: Partial<AgentResourceContextSection> = {}): AgentResourceContextSection => ({+ id: 'runtime',+ title: 'Runtime',+ source: '',+ trustTier: '',+ generatedAt: '2026-05-06T14:00:00Z',+ facts: [],+ ...overrides,+});++describe('agentContextPresentation — branch coverage (branchcov2)', () => {+ describe('formatAgentResourceContextForClipboard — header branches', () => {+ it('falls back to canonicalId when resourceName is empty (|| right operand)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({ resourceName: '' }),+ );+ // resourceName '' is falsy -> `context.resourceName || context.canonicalId`+ // resolves to the canonical id.+ expect(text.startsWith('# Pulse resource context: host:node-1\n')).toBe(true);+ // And the resourceName must NOT appear as the header (it was empty).+ expect(text.startsWith('# Pulse resource context: \n')).toBe(false);+ });++ it('prefers resourceName when it is a non-empty string (|| left operand)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({ resourceName: 'pretty-name' }),+ );+ expect(text.startsWith('# Pulse resource context: pretty-name\n')).toBe(true);+ });++ it('omits the Technology line when context.technology is absent (if-false arm)', () => {+ const text = formatAgentResourceContextForClipboard(baseContext());+ expect(text).not.toContain('Technology:');+ // Sanity: the line that always follows the resource type is present.+ expect(text).toContain('Resource type: host');+ expect(text).toContain('Active findings: 0');+ });++ it('emits the Technology line when context.technology is set (if-true arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({ technology: 'docker' }),+ );+ expect(text).toContain('Technology: docker');+ });+ });++ describe('formatAgentResourceContextForClipboard — full-output shape', () => {+ it('renders the exact minimal document with no sections and no technology', () => {+ // Pins the entire string — header fallback, formatOptionalTime('') on+ // generatedAt, the unconditional counts block, the trailing trim + '\n'.+ const text = formatAgentResourceContextForClipboard({+ canonicalId: 'host:node-1',+ resourceType: 'host',+ resourceName: '',+ activeFindings: [],+ pendingApprovals: [],+ recentActions: [],+ generatedAt: '',+ contextSections: [],+ });++ expect(text).toBe(+ [+ '# Pulse resource context: host:node-1',+ '',+ 'Generated: ',+ 'Canonical ID: host:node-1',+ 'Resource type: host',+ 'Active findings: 0',+ 'Pending approvals: 0',+ 'Recent actions: 0',+ '',+ 'Context facts below are bounded, read-only Pulse context. Redacted values were withheld by policy.',+ '',+ ].join('\n').trim() + '\n',+ );+ });++ it('reflects non-zero counts verbatim from the three count arrays', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ activeFindings: [+ {+ id: 'f1',+ title: 't',+ severity: 'low',+ regressionCount: 0,+ },+ ],+ pendingApprovals: [+ { id: 'a1', riskLevel: 'low', requestedAt: 'x', expiresAt: 'y' },+ { id: 'a2', riskLevel: 'low', requestedAt: 'x', expiresAt: 'y' },+ ],+ recentActions: [+ {+ id: 'r1',+ capabilityName: 'c',+ state: 'done',+ success: true,+ createdAt: 'x',+ updatedAt: 'y',+ },+ ],+ }),+ );+ expect(text).toContain('Active findings: 1');+ expect(text).toContain('Pending approvals: 2');+ expect(text).toContain('Recent actions: 1');+ });+ });++ describe('formatOptionalTime (transitive via generatedAt / observedAt)', () => {+ it('returns ISO string for a valid timestamp (happy arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({ generatedAt: '2026-05-06T14:00:00Z' }),+ );+ // new Date(...).toISOString() normalises to the .000Z form.+ expect(text).toContain('Generated: 2026-05-06T14:00:00.000Z');+ });++ it('returns the raw value when it cannot be parsed as a date (NaN arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({ generatedAt: 'not-a-date' }),+ );+ expect(text).toContain('Generated: not-a-date');+ // and it must NOT have been coerced into an ISO string.+ expect(text).not.toContain('Generated: Invalid');+ });++ it('returns empty string for an empty timestamp (falsy arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({ generatedAt: '' }),+ );+ expect(text).toContain('Generated: \n');+ });++ it('returns empty string for an undefined timestamp (falsy arm, via cast)', () => {+ // `generatedAt` is typed `string`; deliberately pass `undefined` to hit+ // the same `!value` short-circuit that a missing backend field would.+ const text = formatAgentResourceContextForClipboard(+ baseContext({ generatedAt: undefined as unknown as string }),+ );+ expect(text).toContain('Generated: \n');+ });++ it('also normalises valid observedAt inside section headers and fact provenance', () => {+ // Drives formatOptionalTime through both formatSectionHeader and+ // formatProvenance, confirming the ISO normalisation is shared.+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ title: 'Sec',+ source: 's',+ trustTier: 't',+ observedAt: '2026-01-02T03:04:05Z',+ facts: [+ {+ label: 'L',+ value: 'V',+ observedAt: '2025-12-31T23:59:59Z',+ },+ ],+ }),+ ],+ }),+ );+ expect(text).toContain('## Sec (source=s, trust=t, observed=2026-01-02T03:04:05.000Z)');+ expect(text).toContain('- L: V (observed=2025-12-31T23:59:59.000Z)');+ });+ });++ describe('formatProvenance (transitive via facts)', () => {+ const sectionWithFacts = (facts: AgentResourceContextFact[]): AgentResourceContext =>+ baseContext({+ contextSections: [baseSection({ source: 's', trustTier: 't', facts })],+ });++ it('emits no provenance suffix when the fact has no optional fields (length===0 arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ sectionWithFacts([{ label: 'L', value: 'V' }]),+ );+ expect(text).toContain('- L: V\n');+ expect(text).not.toContain('- L: V (');+ });++ it('emits only source when only source is set', () => {+ const text = formatAgentResourceContextForClipboard(+ sectionWithFacts([{ label: 'L', value: 'V', source: 'agent' }]),+ );+ expect(text).toContain('- L: V (source=agent)\n');+ });++ it('emits only trust when only trustTier is set', () => {+ const text = formatAgentResourceContextForClipboard(+ sectionWithFacts([{ label: 'L', value: 'V', trustTier: 'verified' }]),+ );+ expect(text).toContain('- L: V (trust=verified)\n');+ });++ it('emits only observed when only observedAt is set', () => {+ const text = formatAgentResourceContextForClipboard(+ sectionWithFacts([{ label: 'L', value: 'V', observedAt: '2026-05-06T14:00:00Z' }]),+ );+ expect(text).toContain('- L: V (observed=2026-05-06T14:00:00.000Z)\n');+ });++ it('emits only redacted=true when only redacted is set', () => {+ const text = formatAgentResourceContextForClipboard(+ sectionWithFacts([{ label: 'L', value: 'V', redacted: true }]),+ );+ expect(text).toContain('- L: V (redacted=true)\n');+ });++ it('joins all four provenance parts with ", " in declared order (length>0 arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ sectionWithFacts([+ {+ label: 'L',+ value: 'V',+ source: 'agent',+ trustTier: 'verified',+ observedAt: '2026-05-06T14:00:00Z',+ redacted: true,+ },+ ]),+ );+ expect(text).toContain(+ '- L: V (source=agent, trust=verified, observed=2026-05-06T14:00:00.000Z, redacted=true)\n',+ );+ });++ it('treats falsy observedAt (invalid date) as raw text inside the provenance suffix', () => {+ // Combines the formatProvenance observedAt arm with the formatOptionalTime+ // NaN branch: `observed=not-a-date` is emitted verbatim.+ const text = formatAgentResourceContextForClipboard(+ sectionWithFacts([{ label: 'L', value: 'V', observedAt: 'garbage' }]),+ );+ expect(text).toContain('- L: V (observed=garbage)\n');+ });+ });++ describe('formatSectionHeader (transitive via sections)', () => {+ it('renders the plain header when no provenance fields are set (length===0 arm)', () => {+ // source and trustTier are typed as required strings, but empty strings+ // are falsy and exercise the `section.source ? ... : ''` arms.+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({ title: 'Bare', source: '', trustTier: '', facts: [{ label: 'L', value: 'V' }] }),+ ],+ }),+ );+ expect(text).toContain('## Bare\n');+ expect(text).not.toContain('## Bare (');+ });++ it('includes only source in the header when only source is non-empty', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({ title: 'S', source: 'unified', trustTier: '', facts: [{ label: 'L', value: 'V' }] }),+ ],+ }),+ );+ expect(text).toContain('## S (source=unified)\n');+ });++ it('includes only trust in the header when only trustTier is non-empty', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({ title: 'S', source: '', trustTier: 'runtime-observed', facts: [{ label: 'L', value: 'V' }] }),+ ],+ }),+ );+ expect(text).toContain('## S (trust=runtime-observed)\n');+ });++ it('includes only observed in the header when only observedAt is set', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ title: 'S',+ source: '',+ trustTier: '',+ observedAt: '2026-05-06T14:00:00Z',+ facts: [{ label: 'L', value: 'V' }],+ }),+ ],+ }),+ );+ expect(text).toContain('## S (observed=2026-05-06T14:00:00.000Z)\n');+ });++ it('joins all three header provenance parts with ", " in declared order (length>0 arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ title: 'S',+ source: 'unified',+ trustTier: 'runtime-observed',+ observedAt: '2026-05-06T14:00:00Z',+ facts: [{ label: 'L', value: 'V' }],+ }),+ ],+ }),+ );+ expect(text).toContain(+ '## S (source=unified, trust=runtime-observed, observed=2026-05-06T14:00:00.000Z)\n',+ );+ });+ });++ describe('formatRedaction (transitive via section.redactions)', () => {+ it('appends the reason with a " - " separator when reason is non-empty (if-true arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ facts: [{ label: 'L', value: 'V' }],+ redactions: [{ field: 'api-token', reason: 'secret' }],+ }),+ ],+ }),+ );+ expect(text).toContain('- Redaction: api-token - secret\n');+ });++ it('omits the separator and reason when reason is the empty string (if-false arm)', () => {+ // `reason` is typed as a required string; an empty string is a legal value+ // and exercises the falsy arm of `redaction.reason ? ... : ''` without+ // any cast.+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ facts: [{ label: 'L', value: 'V' }],+ redactions: [{ field: 'api-token', reason: '' }],+ }),+ ],+ }),+ );+ expect(text).toContain('- Redaction: api-token\n');+ expect(text).not.toContain('- Redaction: api-token -');+ });++ it('omits the separator when reason is undefined despite the typed contract (defensive arm)', () => {+ // Backend contract says reason is always present; this asserts the+ // defensive falsy branch still fires if the contract is violated.+ const redaction = {+ field: 'api-token',+ reason: undefined,+ } as unknown as AgentResourceContextRedaction;+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({ facts: [{ label: 'L', value: 'V' }], redactions: [redaction] }),+ ],+ }),+ );+ expect(text).toContain('- Redaction: api-token\n');+ expect(text).not.toContain('- Redaction: api-token -');+ });+ });++ describe('section iteration branches', () => {+ it('skips a section that has no facts and no redactions (continue arm, undefined redactions)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({ id: 'skip-me', title: 'Skipped', source: 's', trustTier: 't', redactions: undefined }),+ baseSection({+ id: 'keep-me',+ title: 'Kept',+ source: 's',+ trustTier: 't',+ facts: [{ label: 'L', value: 'V' }],+ }),+ ],+ }),+ );+ expect(text).not.toContain('Skipped');+ expect(text).toContain('## Kept');+ });++ it('skips a section that has empty facts and an empty redactions array (continue arm, [])', () => {+ // `!section.redactions?.length` is true for length 0 as well as undefined.+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({ id: 'skip-me', title: 'Skipped', source: 's', trustTier: 't', redactions: [] }),+ ],+ }),+ );+ expect(text).not.toContain('## Skipped');+ });++ it('keeps a section whose facts are empty but redactions are non-empty (renders header + redactions, no facts)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ id: 'redact-only',+ title: 'RedactOnly',+ source: 's',+ trustTier: 't',+ facts: [],+ redactions: [{ field: 'f', reason: 'r' }],+ }),+ ],+ }),+ );+ expect(text).toContain('## RedactOnly');+ expect(text).toContain('- Redaction: f - r');+ // And no fact bullet is emitted.+ expect(text).not.toMatch(/\n- [^R]/);+ });++ it('exercises the `?? []` right operand: facts present but redactions undefined', () => {+ // facts.length > 0 means the section is not skipped; `section.redactions`+ // is undefined, so the `?? []` fallback prevents a TypeError and the+ // redactions loop body is simply never entered.+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ id: 'facts-only',+ title: 'FactsOnly',+ source: 's',+ trustTier: 't',+ facts: [{ label: 'L', value: 'V' }],+ redactions: undefined,+ }),+ ],+ }),+ );+ expect(text).toContain('## FactsOnly');+ expect(text).toContain('- L: V\n');+ expect(text).not.toContain('Redaction:');+ });++ it('renders the summary line when section.summary is set (if-true arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ title: 'WithSummary',+ source: '',+ trustTier: '',+ summary: 'A short overview of the section.',+ facts: [{ label: 'L', value: 'V' }],+ }),+ ],+ }),+ );+ // Summary is emitted between the bare header and the first fact bullet.+ expect(text).toContain('## WithSummary\nA short overview of the section.\n- L: V\n');+ });++ it('omits any summary line when section.summary is absent (if-false arm)', () => {+ const text = formatAgentResourceContextForClipboard(+ baseContext({+ contextSections: [+ baseSection({+ title: 'NoSummary',+ source: '',+ trustTier: '',+ facts: [{ label: 'L', value: 'V' }],+ }),+ ],+ }),+ );+ expect(text).not.toContain('overview');+ expect(text).toContain('## NoSummary\n- L: V\n');+ });+ });++ describe('output termination', () => {+ it('always ends with a single trailing newline after trim', () => {+ const text = formatAgentResourceContextForClipboard(baseContext());+ expect(text.endsWith('\n')).toBe(true);+ expect(text.endsWith('\n\n')).toBe(false);+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/aiChatPresentation.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/aiChatPresentation.branchcov2.test.tsnew file mode 100644index 0000000000..dc3db8315d--- /dev/null+++ b/frontend-modern/src/utils/__tests__/aiChatPresentation.branchcov2.test.ts@@ -0,0 +1,187 @@+import { describe, expect, it } from 'vitest';+import { getAIChatProviderReadinessPresentation } from '@/utils/aiChatPresentation';++describe('getAIChatProviderReadinessPresentation (branch coverage)', () => {+ describe('status: checking', () => {+ it('falls back to the generic subject and generic body when routeLabel is absent', () => {+ expect(getAIChatProviderReadinessPresentation({ status: 'checking' })).toEqual({+ tone: 'checking',+ title: 'Verifying Selected model route',+ body: 'Pulse is checking the selected model route.',+ });+ });++ it('uses the route-label title and a suffix-free body when providerLabel matches "selected" case-insensitively', () => {+ expect(+ getAIChatProviderReadinessPresentation({+ status: 'checking',+ providerLabel: 'SELECTED',+ routeLabel: 'Acme: GPT-X',+ }),+ ).toEqual({+ tone: 'checking',+ title: 'Verifying selected model route',+ body: 'Pulse is checking Acme: GPT-X.',+ });+ });++ it('appends a provider suffix to the body when providerLabel is a distinct provider', () => {+ expect(+ getAIChatProviderReadinessPresentation({+ status: 'checking',+ providerLabel: 'Anthropic',+ routeLabel: 'Anthropic: Claude',+ }),+ ).toEqual({+ tone: 'checking',+ title: 'Verifying selected model route',+ body: 'Pulse is checking Anthropic: Claude through Anthropic.',+ });+ });++ it('treats a whitespace-only routeLabel as absent', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'checking',+ providerLabel: 'Groq',+ routeLabel: ' ',+ });+ expect(result.title).toBe('Verifying Groq provider route');+ expect(result.body).toBe('Pulse is checking the selected model route.');+ });+ });++ describe('status: ready', () => {+ it('prefers a trimmed summary for the body over the message', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'ready',+ summary: ' All systems go ',+ message: 'should be ignored',+ });+ expect(result.body).toBe('All systems go');+ });++ it('falls back to the message when the summary is whitespace-only', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'ready',+ summary: ' ',+ message: ' Reachable now ',+ });+ expect(result.body).toBe('Reachable now');+ });++ it('uses reachability copy with a provider suffix when no summary/message and routeLabel is present', () => {+ expect(+ getAIChatProviderReadinessPresentation({+ status: 'ready',+ providerLabel: 'Mistral',+ routeLabel: 'Mistral: Large',+ }),+ ).toEqual({+ tone: 'ready',+ title: 'Selected model route ready',+ body: 'Pulse can reach Mistral: Large through Mistral.',+ });+ });++ it('uses generic reachability copy and the default fallback subject title when routeLabel is absent', () => {+ expect(getAIChatProviderReadinessPresentation({ status: 'ready' })).toEqual({+ tone: 'ready',+ title: 'Selected model route ready',+ body: 'Pulse can reach the selected model route.',+ });+ });++ it('uses a provider-named fallback subject title when routeLabel is whitespace and providerLabel is distinct', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'ready',+ providerLabel: 'Groq',+ routeLabel: ' ',+ });+ expect(result.title).toBe('Groq provider route ready');+ expect(result.body).toBe('Pulse can reach the selected model route.');+ });+ });++ describe('status: error', () => {+ it('prefers a trimmed summary for the body over the message', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'error',+ summary: 'Connection refused',+ message: 'should be ignored',+ });+ expect(result.body).toBe('Connection refused');+ });++ it('falls back to the message when no summary is provided', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'error',+ message: 'Timed out',+ });+ expect(result.body).toBe('Timed out');+ });++ it('uses the canonical fallback body when neither summary nor message is provided', () => {+ expect(getAIChatProviderReadinessPresentation({ status: 'error' }).body).toBe(+ 'Pulse could not verify the selected model route.',+ );+ });++ it('exposes a trimmed recommendation and a provider-named fallback subject title', () => {+ expect(+ getAIChatProviderReadinessPresentation({+ status: 'error',+ providerLabel: 'Cohere',+ recommendation: ' Verify the API key. ',+ }),+ ).toEqual({+ tone: 'error',+ title: 'Cohere provider route issue',+ body: 'Pulse could not verify the selected model route.',+ recommendation: 'Verify the API key.',+ });+ });++ it('coerces a whitespace-only recommendation to undefined', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'error',+ recommendation: ' ',+ });+ expect(result.recommendation).toBeUndefined();+ });++ it('uses the default fallback subject title when routeLabel is absent and providerLabel defaults', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'error',+ providerLabel: ' ',+ });+ expect(result.tone).toBe('error');+ expect(result.title).toBe('Selected model route issue');+ });+ });++ describe('providerLabel defaulting and routeLabel trimming', () => {+ it('defaults an undefined providerLabel to "Selected"', () => {+ expect(getAIChatProviderReadinessPresentation({ status: 'ready' }).title).toBe(+ 'Selected model route ready',+ );+ });++ it('defaults a whitespace-only providerLabel to "Selected"', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'checking',+ providerLabel: ' ',+ });+ expect(result.title).toBe('Verifying Selected model route');+ expect(result.body).toBe('Pulse is checking the selected model route.');+ });++ it('trims a non-trivial providerLabel before building the suffix', () => {+ const result = getAIChatProviderReadinessPresentation({+ status: 'checking',+ providerLabel: ' DeepSeek ',+ routeLabel: 'DeepSeek: V4',+ });+ expect(result.body).toBe('Pulse is checking DeepSeek: V4 through DeepSeek.');+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/aiCostPresentation.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/aiCostPresentation.branchcov2.test.tsnew file mode 100644index 0000000000..d6349d81f0--- /dev/null+++ b/frontend-modern/src/utils/__tests__/aiCostPresentation.branchcov2.test.ts@@ -0,0 +1,401 @@+import { describe, expect, it } from 'vitest';+import type { AICostTargetPresentationInput } from '@/utils/aiCostPresentation';+import { getAICostTargetPresentation } from '@/utils/aiCostPresentation';++// `isOpaqueTargetId` and `readableTargetType` are module-private (non-exported)+// helpers, so they are exercised indirectly through the exported+// `getAICostTargetPresentation` entry point, asserting on their observable+// outputs (mirroring the sibling availabilityProbePresentation.branchcov2 and+// metricThresholds.branchcov2 conventions).+//+// `getAICostTargetPresentation` pre-trims `target_id`+// (`target.target_id?.trim() || ''`) and short-circuits the call site on a falsy+// result (`targetId && ...`), so `isOpaqueTargetId` is never reached with an+// empty/whitespace string through this entry point; its `if (!trimmed) return+// false` early-return arm is therefore not exercisable here.+//+// Likewise `readableTargetType` is only ever called with a non-empty `targetType`+// (`target.target_type?.trim() || 'usage'`), so its `normalized || 'usage'`+// nullish-coalesce right operand is not exercisable here. The 'usage' default+// still flows through when `target_type` is absent and yields+// `humanizeIdentifier('usage')`, which IS covered below.++const input = (+ overrides?: Partial<AICostTargetPresentationInput>,+): AICostTargetPresentationInput => ({+ target_type: undefined,+ target_id: undefined,+ ...overrides,+});++describe('isOpaqueTargetId — branch coverage (via getAICostTargetPresentation)', () => {+ describe('canonical UUID regex arm (returns true)', () => {+ it('classifies a lowercase UUID as opaque, forcing the resource-path plural label', () => {+ const id = '7f5941d9-a503-416d-b84e-5a46c9e1e11f';+ expect(getAICostTargetPresentation(input({ target_type: 'vm', target_id: id }))).toEqual({+ label: 'VMs',+ rawLabel: `vm:${id}`,+ });+ });++ it('classifies an uppercase UUID as opaque (regex is case-insensitive)', () => {+ const id = '7F5941D9-A503-416D-B84E-5A46C9E1E11F';+ expect(getAICostTargetPresentation(input({ target_type: 'vm', target_id: id }))).toEqual({+ label: 'VMs',+ rawLabel: `vm:${id}`,+ });+ });+ });++ describe('20+ hex-char regex arm (returns true)', () => {+ it('classifies a 20-char hex string as opaque (boundary value for {20,})', () => {+ const id = '0123456789abcdef0123'; // exactly 20 hex chars+ expect(id).toHaveLength(20);+ expect(getAICostTargetPresentation(input({ target_type: 'vm', target_id: id }))).toEqual({+ label: 'VMs',+ rawLabel: `vm:${id}`,+ });+ });++ it('classifies a 32-char hex string as opaque (the readable-path detail is dropped)', () => {+ const id = 'ed21e8612df6450fab4ebd4ae2502259';+ expect(+ getAICostTargetPresentation(input({ target_type: 'assistant_session', target_id: id })),+ ).toEqual({+ label: 'Assistant sessions',+ rawLabel: `assistant_session:${id}`,+ });+ });+ });++ describe('20+ hex-char regex arm falls through (returns false)', () => {+ it('does NOT classify a 19-char hex string as opaque (just under the {20,} threshold)', () => {+ const id = '0123456789abcdef012'; // 19 hex chars -> readable detail surfaces+ expect(id).toHaveLength(19);+ expect(+ getAICostTargetPresentation(input({ target_type: 'assistant_session', target_id: id })),+ ).toEqual({+ label: 'Assistant sessions',+ detail: id,+ rawLabel: `assistant_session:${id}`,+ });+ });+ });++ describe('long-alphanumeric fallback arm: length > 32 && allowed charset', () => {+ it('classifies a 33-char allowed-charset string (with non-hex letters) as opaque', () => {+ // 33 chars; contains 'g'/'z' (non-hex) so the UUID and 20+hex regexes miss,+ // but it matches ^[a-z0-9:_-]+$ and length > 32 -> opaque.+ const id = 'g0123456789012345678901234567890z';+ expect(id).toHaveLength(33);+ expect(getAICostTargetPresentation(input({ target_type: 'vm', target_id: id }))).toEqual({+ label: 'VMs',+ rawLabel: `vm:${id}`,+ });+ });++ it('treats ":" and "_" and "-" as allowed charset for the long-alphanumeric arm', () => {+ // 40 chars, no hex-only run (contains 'k','s','p','o','d',...) so the UUID+ // and 20+hex regexes miss; matches ^[a-z0-9:_-]+$ and length > 32 -> opaque.+ const id = 'k8s:pod_namespace_name-1234567890123456789';+ expect(id).toHaveLength(42);+ expect(getAICostTargetPresentation(input({ target_type: 'vm', target_id: id }))).toEqual({+ label: 'VMs',+ rawLabel: `vm:${id}`,+ });+ });++ it('does NOT classify a 32-char allowed-charset string as opaque (length > 32 is false at exactly 32)', () => {+ // 32 chars with a non-hex 'g' so neither UUID nor 20+hex match; length is+ // exactly 32 so the `length > 32` predicate is false -> readable.+ const id = 'g0123456789abcdef0123456789abcde';+ expect(id).toHaveLength(32);+ expect(+ getAICostTargetPresentation(input({ target_type: 'assistant_session', target_id: id })),+ ).toEqual({+ label: 'Assistant sessions',+ detail: id,+ rawLabel: `assistant_session:${id}`,+ });+ });++ it('does NOT classify a >32-char string as opaque when it contains a disallowed char', () => {+ // 34 chars; the '.' breaks ^[a-z0-9:_-]+$, so even though length > 32 the+ // charset predicate is false -> readable (short-circuits to false).+ const id = `${'a'.repeat(33)}.`;+ expect(id).toHaveLength(34);+ expect(+ getAICostTargetPresentation(input({ target_type: 'assistant_session', target_id: id })),+ ).toEqual({+ label: 'Assistant sessions',+ detail: id,+ rawLabel: `assistant_session:${id}`,+ });+ });+ });++ describe('short / readable identifiers (returns false)', () => {+ it('classifies a short numeric id as readable (resource path -> "VM 100")', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'vm', target_id: '100' }))).toEqual({+ label: 'VM 100',+ rawLabel: 'vm:100',+ });+ });++ it('classifies a hyphenated human name as readable (resource path -> "Container nginx-web")', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: 'container', target_id: 'nginx-web' })),+ ).toEqual({+ label: 'Container nginx-web',+ rawLabel: 'container:nginx-web',+ });+ });++ it('surfaces a readable id as `detail` on the non-resource path', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: 'patrol', target_id: 'nightly' })),+ ).toEqual({+ label: 'Patrol runs',+ detail: 'nightly',+ rawLabel: 'patrol:nightly',+ });+ });+ });+});++describe('readableTargetType — branch coverage (via getAICostTargetPresentation.label)', () => {+ describe('TARGET_TYPE_LABELS map hits', () => {+ it('maps "assistant_session" -> "Assistant sessions"', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'assistant_session' }))).toEqual({+ label: 'Assistant sessions',+ rawLabel: 'assistant_session',+ });+ });++ it('maps "chat" -> "Assistant sessions" (alias)', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'chat' }))).toEqual({+ label: 'Assistant sessions',+ rawLabel: 'chat',+ });+ });++ it('maps "discovery" -> "Discovery runs"', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'discovery' }))).toEqual({+ label: 'Discovery runs',+ rawLabel: 'discovery',+ });+ });++ it('maps "discovery_run" -> "Discovery runs"', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'discovery_run' }))).toEqual({+ label: 'Discovery runs',+ rawLabel: 'discovery_run',+ });+ });++ it('maps "patrol_session" -> "Patrol runs"', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'patrol_session' }))).toEqual({+ label: 'Patrol runs',+ rawLabel: 'patrol_session',+ });+ });++ it('maps "resource" -> "Resource checks"', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'resource' }))).toEqual({+ label: 'Resource checks',+ rawLabel: 'resource',+ });+ });++ it('maps "resource_context" -> "Resource checks"', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'resource_context' }))).toEqual({+ label: 'Resource checks',+ rawLabel: 'resource_context',+ });+ });+ });++ describe('trim + lowercase normalization before the map lookup', () => {+ it('normalizes whitespace and casing so " PATROL_RUN " still maps to "Patrol runs"', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: ' PATROL_RUN ' })),+ ).toEqual({+ label: 'Patrol runs',+ rawLabel: 'PATROL_RUN',+ });+ });+ });++ describe('map miss -> humanizeIdentifier fallback', () => {+ it('humanizes an unmapped snake_case type ("backup_job" -> "Backup Job")', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'backup_job' }))).toEqual({+ label: 'Backup Job',+ rawLabel: 'backup_job',+ });+ });++ it('humanizes an unmapped mixed snake/kebab type', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: 'vm-snapshot_task' })),+ ).toEqual({+ label: 'Vm Snapshot Task',+ rawLabel: 'vm-snapshot_task',+ });+ });+ });++ describe('default "usage" type (target_type absent or blank)', () => {+ it('falls back to "Usage" when target_type is undefined', () => {+ expect(getAICostTargetPresentation(input({}))).toEqual({+ label: 'Usage',+ rawLabel: 'usage',+ });+ });++ it('falls back to "Usage" when target_type is null', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: null })),+ ).toEqual({+ label: 'Usage',+ rawLabel: 'usage',+ });+ });++ it('falls back to "Usage" when target_type is whitespace-only', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: ' ' })),+ ).toEqual({+ label: 'Usage',+ rawLabel: 'usage',+ });+ });+ });+});++describe('getAICostTargetPresentation — branch coverage', () => {+ describe('RESOURCE_TYPE_PREFIXES resource path (early return, no `detail` field)', () => {+ it('returns "VM <id>" for vm + readable id (ternary true arm)', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'vm', target_id: '100' }))).toEqual({+ label: 'VM 100',+ rawLabel: 'vm:100',+ });+ });++ it('returns the plural "VMs" for vm + opaque id (ternary false arm via isOpaque)', () => {+ expect(+ getAICostTargetPresentation(+ input({ target_type: 'vm', target_id: '7f5941d9-a503-416d-b84e-5a46c9e1e11f' }),+ ),+ ).toEqual({+ label: 'VMs',+ rawLabel: 'vm:7f5941d9-a503-416d-b84e-5a46c9e1e11f',+ });+ });++ it('returns the plural "VMs" for vm + no id (ternary false arm via falsy targetId)', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'vm' }))).toEqual({+ label: 'VMs',+ rawLabel: 'vm',+ });+ });++ it('maps "container" to prefix "Container" with a readable id', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: 'container', target_id: 'web-1' })),+ ).toEqual({+ label: 'Container web-1',+ rawLabel: 'container:web-1',+ });+ });++ it('maps "lxc" to prefix "Container" (lxc alias) with the plural form when id is opaque', () => {+ expect(+ getAICostTargetPresentation(+ input({ target_type: 'lxc', target_id: '0123456789abcdef0123' }),+ ),+ ).toEqual({+ label: 'Containers',+ rawLabel: 'lxc:0123456789abcdef0123',+ });+ });++ it('lowercases target_type before the resource-prefix lookup ("VM" -> vm)', () => {+ expect(getAICostTargetPresentation(input({ target_type: 'VM', target_id: '7' }))).toEqual({+ label: 'VM 7',+ rawLabel: 'VM:7',+ });+ });++ it('never emits a `detail` field on the resource path', () => {+ const result = getAICostTargetPresentation(+ input({ target_type: 'vm', target_id: 'web-1' }),+ );+ expect(result).not.toHaveProperty('detail');+ });+ });++ describe('readable (non-resource) path — `detail` ternary', () => {+ it('emits detail = id for a readable id (ternary true arm)', () => {+ expect(+ getAICostTargetPresentation(+ input({ target_type: 'assistant_session', target_id: 'design-review' }),+ ),+ ).toEqual({+ label: 'Assistant sessions',+ detail: 'design-review',+ rawLabel: 'assistant_session:design-review',+ });+ });++ it('sets detail = undefined for an opaque id (ternary false arm via isOpaque)', () => {+ // NOTE: the readable path always returns a `detail` *key* (set to+ // `undefined` here), unlike the resource path which omits the key entirely.+ // This shape inconsistency is a suspected source quirk (see GLM_REPORT.md).+ const result = getAICostTargetPresentation(+ input({ target_type: 'assistant_session', target_id: '0123456789abcdef0123' }),+ );+ expect(result.label).toBe('Assistant sessions');+ expect(result.detail).toBeUndefined();+ expect(result.rawLabel).toBe('assistant_session:0123456789abcdef0123');+ });++ it('sets detail = undefined when there is no id (ternary false arm via falsy targetId)', () => {+ const result = getAICostTargetPresentation(input({ target_type: 'patrol_run' }));+ expect(result.label).toBe('Patrol runs');+ expect(result.detail).toBeUndefined();+ expect(result.rawLabel).toBe('patrol_run');+ });+ });++ describe('target_id coercion and rawLabel shaping', () => {+ it('coerces a null target_id to "" (no id, rawLabel has no colon)', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: 'patrol_run', target_id: null })),+ ).toEqual({+ label: 'Patrol runs',+ rawLabel: 'patrol_run',+ });+ });++ it('trims a padded target_id before shaping rawLabel and detail', () => {+ expect(+ getAICostTargetPresentation(+ input({ target_type: 'patrol_run', target_id: ' nightly ' }),+ ),+ ).toEqual({+ label: 'Patrol runs',+ detail: 'nightly',+ rawLabel: 'patrol_run:nightly',+ });+ });++ it('treats a whitespace-only target_id as absent (rawLabel has no colon)', () => {+ expect(+ getAICostTargetPresentation(input({ target_type: 'patrol_run', target_id: ' ' })),+ ).toEqual({+ label: 'Patrol runs',+ rawLabel: 'patrol_run',+ });+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/infrastructureOnboardingPresentation.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/infrastructureOnboardingPresentation.branchcov2.test.tsnew file mode 100644index 0000000000..efd33e4338--- /dev/null+++ b/frontend-modern/src/utils/__tests__/infrastructureOnboardingPresentation.branchcov2.test.ts@@ -0,0 +1,270 @@+import { describe, expect, it } from 'vitest';+import type { InfrastructureOnboardingConnectionType } from '@/utils/infrastructureOnboardingPresentation';+import {+ getInfrastructureAgentHostProfileSupportText,+ getInfrastructureGovernanceBadgeLabel,+ getInfrastructureOnboardingProductPresentation,+} from '@/utils/infrastructureOnboardingPresentation';++// DEFAULT_AGENT_SUPPORT_FLOOR is module-private in the source; restate the+// canonical shape so the manifest-null fallback arm of+// getInfrastructureOnboardingProductPresentation can be asserted concretely.+const DEFAULT_AGENT_SUPPORT_FLOOR = {+ setup: 'supported',+ visibility: 'supported',+ workloads: 'n/a',+ storage: 'supported',+ recovery: 'n/a',+ alerts: 'supported',+ assistantRead: 'supported',+ assistantControl: 'supported',+} as const;++describe('infrastructureOnboardingPresentation — branch coverage (branchcov2)', () => {+ describe('formatJoinedLabelList (via getInfrastructureAgentHostProfileSupportText)', () => {+ it('joins the multi-label (length >= 3) set with an Oxford comma', () => {+ // formatJoinedLabelList is module-private; its only public caller threads+ // the agent host-profile label set, which currently resolves to 5 labels.+ // This pins the >=3 arm: `${labels.slice(0, -1).join(', ')}, and ${last}`.+ expect(getInfrastructureAgentHostProfileSupportText()).toBe(+ 'Linux, macOS, Windows, FreeBSD, and Unraid host/appliance profiles',+ );+ });+ });++ describe('getInfrastructureGovernanceBadgeLabel', () => {+ it('returns null for the supported governance state regardless of readiness stage', () => {+ // governanceState === 'supported' early-return arm.+ expect(getInfrastructureGovernanceBadgeLabel('supported', 'supported')).toBeNull();+ // readinessStage is ignored on this arm.+ expect(getInfrastructureGovernanceBadgeLabel('supported', 'first-lab-ready')).toBeNull();+ });++ it('labels the presentation-only governance state explicitly', () => {+ // governanceState === 'presentation-only' arm — not exercised by the sibling test.+ expect(getInfrastructureGovernanceBadgeLabel('presentation-only', 'supported')).toBe(+ 'Presentation only',+ );+ expect(getInfrastructureGovernanceBadgeLabel('presentation-only', 'first-lab-ready')).toBe(+ 'Presentation only',+ );+ });++ it('returns "Preview" once a non-supported platform clears the first-lab readiness gate', () => {+ // readinessStage === 'first-lab-ready' arm for a state that is neither+ // 'supported' nor 'presentation-only'.+ expect(getInfrastructureGovernanceBadgeLabel('admitted', 'first-lab-ready')).toBe('Preview');+ });++ it('falls back to "Preview" for admitted platforms that are not first-lab-ready', () => {+ // Final default `return 'Preview'` arm — readinessStage is NOT+ // 'first-lab-ready'. Not exercised by the sibling test.+ expect(getInfrastructureGovernanceBadgeLabel('admitted', 'supported')).toBe('Preview');+ });+ });++ describe('governanceStateForType (via getInfrastructureOnboardingProductPresentation)', () => {+ it('reports "supported" for agent because it carries no sourcePlatformId', () => {+ // governanceStateForType's `if (!sourcePlatformId) return 'supported'` arm.+ // Reached because agent has no sourcePlatformId, so manifestEntry is null+ // and getInfrastructureOnboardingProductPresentation delegates to it.+ expect(getInfrastructureOnboardingProductPresentation('agent').governanceState).toBe(+ 'supported',+ );+ });++ it('reports "supported" for availability because it carries no sourcePlatformId', () => {+ expect(getInfrastructureOnboardingProductPresentation('availability').governanceState).toBe(+ 'supported',+ );+ });++ it('reads governance straight from the manifest for API-backed platforms', () => {+ // For these types manifestEntry is non-null, so governanceStateForType is+ // never invoked; governance comes from manifestEntry.governanceState.+ expect(getInfrastructureOnboardingProductPresentation('vmware').governanceState).toBe(+ 'admitted',+ );+ expect(getInfrastructureOnboardingProductPresentation('truenas').governanceState).toBe(+ 'supported',+ );+ expect(getInfrastructureOnboardingProductPresentation('pve').governanceState).toBe(+ 'supported',+ );+ expect(getInfrastructureOnboardingProductPresentation('pbs').governanceState).toBe(+ 'supported',+ );+ expect(getInfrastructureOnboardingProductPresentation('pmg').governanceState).toBe(+ 'supported',+ );+ });+ });++ describe('getInfrastructureOnboardingProductPresentation', () => {+ it('uses the manifest-null fallback chain for the agent product', () => {+ // agent has no sourcePlatformId, so manifestEntry is null and every+ // manifest-driven field falls through its ?? chain.+ const agent = getInfrastructureOnboardingProductPresentation('agent');+ expect(agent).toStrictEqual({+ type: 'agent',+ label: 'Pulse Agent',+ bestFor:+ 'Linux, macOS, Windows, FreeBSD, and Unraid host/appliance profiles where you want low-overhead node-local telemetry.',+ coverage: 'Low-overhead host telemetry, SMART, services, Docker, and Kubernetes',+ catalogDescription: 'Low-overhead host telemetry, services, Docker, Kubernetes',+ searchAliases: ['host', 'server', 'machine', 'node', 'ubuntu', 'debian', 'windows', 'mac'],+ sourceStrategy: 'agent',+ autoDetect: false,+ // governanceState: undefined ?? governanceStateForType('agent') -> 'supported'+ governanceState: 'supported',+ // readinessStage: undefined ?? 'supported'+ readinessStage: 'supported',+ // primaryMode: undefined ?? undefined ?? 'agent-backed' (final fallback arm)+ primaryMode: 'agent-backed',+ // canonicalProjections: undefined ?? undefined ?? ['agent'] (final fallback arm)+ canonicalProjections: ['agent'],+ // supportFloor: undefined ?? DEFAULT_AGENT_SUPPORT_FLOOR+ supportFloor: DEFAULT_AGENT_SUPPORT_FLOOR,+ defaultSurfaceKeys: ['host'],+ });+ });++ it('uses the presentation-side fallback values for the availability probe product', () => {+ // availability has no sourcePlatformId, so manifestEntry is null. Its+ // presentation DOES define primaryMode + canonicalProjections, so those+ // feed the middle arm of each ?? chain instead of the final defaults.+ const availability = getInfrastructureOnboardingProductPresentation('availability');+ expect(availability).toStrictEqual({+ type: 'availability',+ label: 'Network endpoint',+ bestFor: 'Devices that expose ICMP, TCP, or HTTP but cannot run Pulse Agent',+ coverage: 'Agentless availability checks and downtime alerts',+ catalogDescription: 'Ping, TCP port, and HTTP availability checks',+ searchAliases: [+ 'ping',+ 'icmp',+ 'tcp',+ 'http',+ 'endpoint',+ 'probe',+ 'port',+ 'website',+ 'ip address',+ 'mqtt',+ 'esphome',+ ],+ sourceStrategy: 'probe',+ autoDetect: false,+ governanceState: 'supported',+ readinessStage: 'supported',+ // primaryMode: undefined ?? presentation.primaryMode('api-backed')+ primaryMode: 'api-backed',+ // canonicalProjections: undefined ?? presentation.canonicalProjections+ canonicalProjections: ['network-endpoint'],+ supportFloor: DEFAULT_AGENT_SUPPORT_FLOOR,+ defaultSurfaceKeys: ['availability'],+ });+ });++ it('reads readiness, canonicalProjections and supportFloor from the manifest for vmware', () => {+ // vmware is admitted/first-lab-ready, exercising the manifest side of+ // every ?? (manifestEntry?.X is non-null for each field).+ const vmware = getInfrastructureOnboardingProductPresentation('vmware');+ expect(vmware.governanceState).toBe('admitted');+ expect(vmware.readinessStage).toBe('first-lab-ready');+ expect(vmware.primaryMode).toBe('api-backed');+ expect(vmware.canonicalProjections).toStrictEqual(['agent', 'vm', 'storage', 'network']);+ expect(vmware.supportFloor).toStrictEqual({+ setup: 'supported',+ visibility: 'supported',+ workloads: 'supported',+ storage: 'supported',+ recovery: 'n/a',+ alerts: 'supported',+ assistantRead: 'supported',+ assistantControl: 'read-only',+ });+ expect(vmware.searchAliases).toStrictEqual(['vsphere', 'esxi', 'vcenter', 'vmware cluster']);+ });++ it('pulls platform-specific manifest canonicalProjections for every supported API platform', () => {+ // Each platform exercises a distinct manifestEntry.canonicalProjections,+ // confirming the manifest side of the ?? is data-driven per type.+ expect(getInfrastructureOnboardingProductPresentation('truenas').canonicalProjections)+ .toStrictEqual([+ 'agent',+ 'vm',+ 'app-container',+ 'network-share',+ 'storage',+ 'physical-disk',+ ]);+ expect(getInfrastructureOnboardingProductPresentation('pve').canonicalProjections)+ .toStrictEqual(['agent', 'vm', 'system-container', 'storage', 'ceph', 'physical-disk']);+ expect(getInfrastructureOnboardingProductPresentation('pbs').canonicalProjections)+ .toStrictEqual(['pbs', 'storage']);+ expect(getInfrastructureOnboardingProductPresentation('pmg').canonicalProjections).toStrictEqual(+ ['pmg'],+ );+ });++ it('reads the manifest supportFloor for supported API platforms', () => {+ // pve assistantControl ('augmentation-only') and pbs workloads ('n/a')+ // differ from DEFAULT_AGENT_SUPPORT_FLOOR, pinning the manifest side of+ // the supportFloor ?? rather than the fallback.+ expect(getInfrastructureOnboardingProductPresentation('pve').supportFloor).toStrictEqual({+ setup: 'supported',+ visibility: 'supported',+ workloads: 'supported',+ storage: 'supported',+ recovery: 'supported',+ alerts: 'supported',+ assistantRead: 'supported',+ assistantControl: 'augmentation-only',+ });+ expect(getInfrastructureOnboardingProductPresentation('pbs').supportFloor).toStrictEqual({+ setup: 'supported',+ visibility: 'supported',+ workloads: 'n/a',+ storage: 'supported',+ recovery: 'supported',+ alerts: 'supported',+ assistantRead: 'supported',+ assistantControl: 'read-only',+ });+ });++ it('keeps the presentation searchAliases (never the [] fallback) for every type', () => {+ // The `presentation.searchAliases ?? []` expression: every product+ // defines searchAliases, so the [] fallback arm never fires for a valid+ // type. Pin each exact array to prove the presentation side is used.+ const expectedAliases: Record<InfrastructureOnboardingConnectionType, readonly string[]> = {+ agent: ['host', 'server', 'machine', 'node', 'ubuntu', 'debian', 'windows', 'mac'],+ availability: [+ 'ping',+ 'icmp',+ 'tcp',+ 'http',+ 'endpoint',+ 'probe',+ 'port',+ 'website',+ 'ip address',+ 'mqtt',+ 'esphome',+ ],+ pve: ['proxmox', 'pve', 'hypervisor', 'vm host', 'cluster'],+ pbs: ['backup', 'proxmox backup', 'pbs'],+ pmg: ['mail', 'email', 'gateway', 'proxmox mail', 'pmg'],+ truenas: ['nas', 'storage', 'zfs', 'truenas scale'],+ vmware: ['vsphere', 'esxi', 'vcenter', 'vmware cluster'],+ };+ const types = Object.keys(expectedAliases) as InfrastructureOnboardingConnectionType[];+ for (const type of types) {+ expect(getInfrastructureOnboardingProductPresentation(type).searchAliases).toStrictEqual(+ expectedAliases[type],+ );+ }+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/resourceChangePresentation.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/resourceChangePresentation.branchcov2.test.tsnew file mode 100644index 0000000000..e8cf35f6c1--- /dev/null+++ b/frontend-modern/src/utils/__tests__/resourceChangePresentation.branchcov2.test.ts@@ -0,0 +1,219 @@+import { describe, expect, it } from 'vitest';++import {+ formatResourceChangeHeadline,+ formatResourceChangeKind,+ getResourceChangeKindPresentation,+ getResourceChangeSourceAdapterPresentation,+ getResourceChangeSourceTypePresentation,+} from '@/utils/resourceChangePresentation';+import type { ResourceChange } from '@/types/resource';++const makeChange = (overrides: Partial<ResourceChange> = {}): ResourceChange => ({+ id: 'change-1',+ observedAt: '2026-03-18T12:00:00Z',+ resourceId: 'vm:42',+ kind: 'activity',+ sourceType: 'platform_event',+ confidence: 'high',+ ...overrides,+});++describe('formatResourceChangeKind (branch coverage)', () => {+ it('returns the canonical label for the remaining named switch arms', () => {+ expect(formatResourceChangeKind('state_transition')).toBe('State transition');+ expect(formatResourceChangeKind('restart')).toBe('Restart');+ expect(formatResourceChangeKind('capability_change')).toBe('Capability change');+ expect(formatResourceChangeKind('alert_acknowledged')).toBe('Alert acknowledged');+ expect(formatResourceChangeKind('alert_unacknowledged')).toBe('Alert unacknowledged');+ expect(formatResourceChangeKind('alert_resolved')).toBe('Alert resolved');+ expect(formatResourceChangeKind('command_executed')).toBe('Command executed');+ });++ it('humanizes an unmapped kind through the default switch arm', () => {+ expect(+ formatResourceChangeKind(+ 'custom_unmapped_kind' as unknown as Parameters<typeof formatResourceChangeKind>[0],+ ),+ ).toBe('Custom Unmapped Kind');+ });++ it('returns an empty string for an empty kind via the default arm fallback', () => {+ expect(+ formatResourceChangeKind(+ '' as unknown as Parameters<typeof formatResourceChangeKind>[0],+ ),+ ).toBe('');+ });+});++describe('getResourceChangeKindPresentation (branch coverage)', () => {+ it('returns the full strict shape for known kinds not already strictly asserted', () => {+ expect(getResourceChangeKindPresentation('state_transition')).toStrictEqual({+ label: 'State transition',+ plural: 'State transitions',+ className: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300',+ });+ expect(getResourceChangeKindPresentation('metric_anomaly')).toStrictEqual({+ label: 'Anomaly',+ plural: 'Anomalies',+ className: 'bg-rose-100 text-rose-700 dark:bg-rose-900 dark:text-rose-300',+ });+ expect(getResourceChangeKindPresentation('alert_unacknowledged')).toStrictEqual({+ label: 'Alert unacknowledged',+ plural: 'Alerts unacknowledged',+ className: 'bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300',+ });+ });++ it('falls back to a humanized presentation for an unknown kind (?? branch)', () => {+ expect(getResourceChangeKindPresentation('totally_unknown_kind')).toStrictEqual({+ label: 'Totally Unknown Kind',+ plural: 'Totally Unknown Kinds',+ className: 'bg-surface text-muted',+ });+ });++ it('falls back to the Unknown sentinel for an empty kind string', () => {+ expect(getResourceChangeKindPresentation('')).toStrictEqual({+ label: 'Unknown',+ plural: 'Unknowns',+ className: 'bg-surface text-muted',+ });+ });+});++describe('getResourceChangeSourceTypePresentation (branch coverage)', () => {+ it('returns the full strict shape for every canonical source type', () => {+ expect(getResourceChangeSourceTypePresentation('platform_event')).toStrictEqual({+ label: 'Platform event',+ plural: 'Platform events',+ className: 'bg-sky-100 text-sky-700 dark:bg-sky-900 dark:text-sky-300',+ });+ expect(getResourceChangeSourceTypePresentation('pulse_diff')).toStrictEqual({+ label: 'Pulse diff',+ plural: 'Pulse diffs',+ className: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-300',+ });+ expect(getResourceChangeSourceTypePresentation('heuristic')).toStrictEqual({+ label: 'Heuristic',+ plural: 'Heuristics',+ className: 'bg-rose-100 text-rose-700 dark:bg-rose-900 dark:text-rose-300',+ });+ expect(getResourceChangeSourceTypePresentation('user_action')).toStrictEqual({+ label: 'User action',+ plural: 'User actions',+ className: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300',+ });+ expect(getResourceChangeSourceTypePresentation('agent_action')).toStrictEqual({+ label: 'Agent action',+ plural: 'Agent actions',+ className: 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',+ });+ });++ it('falls back to a humanized presentation for an unknown source type (?? branch)', () => {+ expect(getResourceChangeSourceTypePresentation('mystery_source')).toStrictEqual({+ label: 'Mystery Source',+ plural: 'Mystery Sources',+ className: 'bg-surface text-muted',+ });+ });+});++describe('getResourceChangeSourceAdapterPresentation (branch coverage)', () => {+ it('returns the full strict shape for every canonical source adapter', () => {+ expect(getResourceChangeSourceAdapterPresentation('docker_adapter')).toStrictEqual({+ label: 'Docker adapter',+ plural: 'Docker adapters',+ className: 'bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300',+ });+ expect(getResourceChangeSourceAdapterPresentation('proxmox_adapter')).toStrictEqual({+ label: 'Proxmox adapter',+ plural: 'Proxmox adapters',+ className: 'bg-sky-100 text-sky-700 dark:bg-sky-900 dark:text-sky-300',+ });+ expect(getResourceChangeSourceAdapterPresentation('truenas_adapter')).toStrictEqual({+ label: 'TrueNAS adapter',+ plural: 'TrueNAS adapters',+ className: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300',+ });+ expect(getResourceChangeSourceAdapterPresentation('vmware_adapter')).toStrictEqual({+ label: 'VMware adapter',+ plural: 'VMware adapters',+ className: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900 dark:text-cyan-300',+ });+ expect(getResourceChangeSourceAdapterPresentation('agent:ops-helper')).toStrictEqual({+ label: 'Ops helper',+ plural: 'Ops helpers',+ className: 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',+ });+ });++ it('falls back to a humanized presentation for an unknown source adapter (?? branch)', () => {+ expect(getResourceChangeSourceAdapterPresentation('synology_adapter')).toStrictEqual({+ label: 'Synology Adapter',+ plural: 'Synology Adapters',+ className: 'bg-surface text-muted',+ });+ });+});++describe('formatResourceChangeHeadline (branch coverage)', () => {+ it('uses the from/to format for a restart change with both endpoints', () => {+ expect(+ formatResourceChangeHeadline(makeChange({ kind: 'restart', from: 'stopped', to: 'running' })),+ ).toBe('Restart: stopped → running');+ });++ it('prefers the from/to format over reason when both endpoints are present', () => {+ expect(+ formatResourceChangeHeadline(+ makeChange({+ kind: 'state_transition',+ from: 'running',+ to: 'restarting',+ reason: 'should be ignored',+ }),+ ),+ ).toBe('State transition: running → restarting');+ });++ it('falls through to the reason branch when a state_transition is missing the "to" endpoint', () => {+ expect(+ formatResourceChangeHeadline(+ makeChange({ kind: 'state_transition', from: 'running', reason: 'Rebooted by scheduler' }),+ ),+ ).toBe('State transition: Rebooted by scheduler');+ });++ it('falls back to the resourceId when a restart has neither endpoints nor a reason', () => {+ expect(+ formatResourceChangeHeadline(makeChange({ kind: 'restart', resourceId: 'vm:99' })),+ ).toBe('Restart: vm:99');+ });++ it('trims surrounding whitespace from a reason before composing the headline', () => {+ expect(+ formatResourceChangeHeadline(+ makeChange({ kind: 'activity', reason: ' Deployed version 2.1 ' }),+ ),+ ).toBe('Activity: Deployed version 2.1');+ });++ it('returns the reason verbatim when it case-insensitively already starts with the kind label', () => {+ expect(+ formatResourceChangeHeadline(+ makeChange({ kind: 'activity', reason: 'ACTIVITY: deployed v3' }),+ ),+ ).toBe('ACTIVITY: deployed v3');+ });++ it('falls back to the resourceId when no reason and no endpoints are present', () => {+ expect(+ formatResourceChangeHeadline(+ makeChange({ kind: 'config_update', resourceId: 'storage:pool:data' }),+ ),+ ).toBe('Config update: storage:pool:data');+ });+});diff --git a/frontend-modern/src/utils/__tests__/resourceDiscoveryReadiness.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/resourceDiscoveryReadiness.branchcov2.test.tsnew file mode 100644index 0000000000..1605b2bb43--- /dev/null+++ b/frontend-modern/src/utils/__tests__/resourceDiscoveryReadiness.branchcov2.test.ts@@ -0,0 +1,283 @@+import { describe, expect, it, vi } from 'vitest';+import {+ formatDiscoveryReadinessBriefingLine,+ formatReadinessAge,+ getDiscoveryReadinessPresentation,+} from '@/utils/resourceDiscoveryReadiness';+import type {+ ResourceDiscoveryReadiness,+ ResourceDiscoveryReadinessState,+} from '@/types/resource';++// `formatDiscoveryAge` (from @/api/discovery) is wall-clock dependent. Mock it+// deterministically so the `observedAt`-driven code paths assert concrete+// strings instead of "X minutes ago". Vitest hoists vi.mock above the imports.+vi.mock('@/api/discovery', () => ({+ formatDiscoveryAge: (updatedAt: string): string => `MOCKED_AGE:${updatedAt}`,+}));++type ReadinessArg = Parameters<typeof getDiscoveryReadinessPresentation>[0];+type AgeArg = Parameters<typeof formatReadinessAge>[0];++const makeReadiness = (+ overrides: Partial<ResourceDiscoveryReadiness> = {},+): ResourceDiscoveryReadiness => ({+ state: 'fresh',+ ...overrides,+});++// A value that is not part of the canonical readiness-state set; used to drive+// the `STATE_COPY[state] ?? fallback` arm. Cast through `unknown` so the strict+// tsconfig accepts it.+const UNKNOWN_STATE = 'bogus' as unknown as ResourceDiscoveryReadinessState;++describe('resourceDiscoveryReadiness — branch coverage (branchcov2)', () => {+ describe('formatReadinessAge', () => {+ it('returns an empty string for every rejected input (non-number / NaN / Infinity / negative)', () => {+ // typeof !== 'number'+ expect(formatReadinessAge()).toBe('');+ expect(formatReadinessAge(undefined)).toBe('');+ expect(formatReadinessAge(null as unknown as AgeArg)).toBe('');+ // Number.isFinite is false+ expect(formatReadinessAge(NaN)).toBe('');+ expect(formatReadinessAge(Infinity)).toBe('');+ expect(formatReadinessAge(-Infinity)).toBe('');+ // seconds < 0+ expect(formatReadinessAge(-1)).toBe('');+ expect(formatReadinessAge(-0.0001)).toBe('');+ });++ it('returns "under a minute old" for the sub-minute band including zero', () => {+ expect(formatReadinessAge(0)).toBe('under a minute old');+ expect(formatReadinessAge(59)).toBe('under a minute old');+ expect(formatReadinessAge(59.999)).toBe('under a minute old');+ });++ it('renders singular vs plural minutes', () => {+ // minutes === 1 (singular arm of the ternary)+ expect(formatReadinessAge(60)).toBe('1 minute old');+ // minutes !== 1 (plural arm)+ expect(formatReadinessAge(120)).toBe('2 minutes old');+ expect(formatReadinessAge(3540)).toBe('59 minutes old');+ });++ it('renders singular vs plural hours', () => {+ // hours === 1+ expect(formatReadinessAge(3600)).toBe('1 hour old');+ // hours !== 1+ expect(formatReadinessAge(7200)).toBe('2 hours old');+ expect(formatReadinessAge(82800)).toBe('23 hours old');+ });++ it('renders singular vs plural days', () => {+ // days === 1+ expect(formatReadinessAge(86400)).toBe('1 day old');+ // days !== 1+ expect(formatReadinessAge(172800)).toBe('2 days old');+ expect(formatReadinessAge(604800)).toBe('7 days old');+ });+ });++ describe('getDiscoveryReadinessPresentation — null/unknown arms', () => {+ it('returns null when readiness is absent and discovery is unsupported', () => {+ expect(getDiscoveryReadinessPresentation(null, false)).toBeNull();+ expect(getDiscoveryReadinessPresentation(undefined, false)).toBeNull();+ });++ it('returns a fully-shaped "unknown" presentation when readiness is absent but supported', () => {+ const expectedUnknown = {+ state: 'unknown',+ label: 'Discovery unknown',+ shortLabel: 'Unknown',+ statusLabel: 'Discovery unknown',+ title: 'Discovery status is not available for this resource yet.',+ detail: 'Discovery status unavailable',+ tone: 'muted',+ } as const;++ // explicit hasDiscoverySupport = true+ expect(getDiscoveryReadinessPresentation(undefined, true)).toStrictEqual(expectedUnknown);+ expect(getDiscoveryReadinessPresentation(null, true)).toStrictEqual(expectedUnknown);+ // default second argument is `true`+ expect(getDiscoveryReadinessPresentation(undefined)).toStrictEqual(expectedUnknown);+ expect(getDiscoveryReadinessPresentation(null)).toStrictEqual(expectedUnknown);+ });+ });++ describe('getDiscoveryReadinessPresentation — STATE_COPY routing', () => {+ it('maps every canonical state to its label/shortLabel/statusLabel/tone', () => {+ const cases: Array<{+ state: ResourceDiscoveryReadinessState;+ label: string;+ shortLabel: string;+ statusLabel: string;+ tone: string;+ }> = [+ { state: 'fresh', label: 'Discovery fresh', shortLabel: 'Fresh', statusLabel: 'Discovery fresh', tone: 'success' },+ { state: 'stale', label: 'Discovery stale', shortLabel: 'Stale', statusLabel: 'Discovery stale', tone: 'warning' },+ { state: 'missing', label: 'Not discovered', shortLabel: 'None', statusLabel: 'No discovery data', tone: 'muted' },+ { state: 'running', label: 'Discovery running', shortLabel: 'Running', statusLabel: 'Discovery running', tone: 'info' },+ { state: 'failed', label: 'Discovery failed', shortLabel: 'Failed', statusLabel: 'Discovery failed', tone: 'danger' },+ { state: 'unavailable', label: 'Discovery unavailable', shortLabel: 'Unavailable', statusLabel: 'Discovery unavailable', tone: 'warning' },+ { state: 'unsupported', label: 'Not supported', shortLabel: 'N/A', statusLabel: 'Discovery unsupported', tone: 'muted' },+ ];++ for (const { state, label, shortLabel, statusLabel, tone } of cases) {+ const presentation = getDiscoveryReadinessPresentation(makeReadiness({ state }));+ expect(presentation?.state).toBe(state);+ expect(presentation?.label).toBe(label);+ expect(presentation?.shortLabel).toBe(shortLabel);+ expect(presentation?.statusLabel).toBe(statusLabel);+ expect(presentation?.tone).toBe(tone);+ }+ });++ it('falls back to the unknown copy when the state is not canonical (STATE_COPY ?? fallback)', () => {+ const presentation = getDiscoveryReadinessPresentation(makeReadiness({ state: UNKNOWN_STATE }));+ expect(presentation).toStrictEqual({+ state: UNKNOWN_STATE,+ label: 'Discovery unknown',+ shortLabel: 'Unknown',+ statusLabel: 'Discovery unknown',+ // No reason/service/facts/observed => detail is empty => title === copy.label+ title: 'Discovery unknown',+ detail: '',+ tone: 'muted',+ });+ });+ });++ describe('getDiscoveryReadinessPresentation — details assembly', () => {+ it('joins reason, service, facts and observed age into title and detail', () => {+ const presentation = getDiscoveryReadinessPresentation(+ makeReadiness({+ state: 'fresh',+ reason: 'Within freshness window.',+ serviceName: 'Home Assistant',+ factCount: 7,+ ageSeconds: 120,+ }),+ );+ const expectedDetail =+ 'Within freshness window. · Service: Home Assistant · 7 facts · Observed 2 minutes old';+ expect(presentation?.detail).toBe(expectedDetail);+ expect(presentation?.title).toBe(`Discovery fresh: ${expectedDetail}`);+ });++ it('keeps only the reason line when service/facts/observed are absent', () => {+ const presentation = getDiscoveryReadinessPresentation(+ makeReadiness({ state: 'fresh', reason: 'Only reason.' }),+ );+ expect(presentation?.detail).toBe('Only reason.');+ expect(presentation?.title).toBe('Discovery fresh: Only reason.');+ });++ it('drops zero and negative fact counts via the `factCount && factCount > 0` guard', () => {+ expect(+ getDiscoveryReadinessPresentation(makeReadiness({ state: 'fresh', factCount: 0 }))?.detail,+ ).toBe('');+ expect(+ getDiscoveryReadinessPresentation(makeReadiness({ state: 'fresh', factCount: -3 }))?.detail,+ ).toBe('');+ });++ it('collapses title to copy.label when no detail lines survive filtering', () => {+ const presentation = getDiscoveryReadinessPresentation(makeReadiness({ state: 'failed' }));+ expect(presentation?.detail).toBe('');+ expect(presentation?.title).toBe('Discovery failed');+ });+ });++ describe('observedLabel (exercised via getDiscoveryReadinessPresentation)', () => {+ it('routes through formatDiscoveryAge when observedAt is truthy', () => {+ const presentation = getDiscoveryReadinessPresentation(+ makeReadiness({ state: 'fresh', observedAt: '2024-01-02T03:04:05Z' }),+ );+ expect(presentation?.detail).toBe('Observed MOCKED_AGE:2024-01-02T03:04:05Z');+ });++ it('prefers observedAt over ageSeconds when both are populated', () => {+ const presentation = getDiscoveryReadinessPresentation(+ makeReadiness({ state: 'fresh', observedAt: 'X', ageSeconds: 600 }),+ );+ expect(presentation?.detail).toBe('Observed MOCKED_AGE:X');+ });++ it('falls back to formatReadinessAge(ageSeconds) when observedAt is missing or empty', () => {+ expect(+ getDiscoveryReadinessPresentation(+ makeReadiness({ state: 'fresh', ageSeconds: 600 }),+ )?.detail,+ ).toBe('Observed 10 minutes old');+ // Empty string is falsy, so the observedAt branch is skipped.+ expect(+ getDiscoveryReadinessPresentation(+ makeReadiness({ state: 'fresh', observedAt: '', ageSeconds: 600 }),+ )?.detail,+ ).toBe('Observed 10 minutes old');+ });++ it('omits the Observed line entirely when neither observedAt nor a usable age are present', () => {+ // ageSeconds undefined => formatReadinessAge returns '' => observedLabel returns ''+ const presentation = getDiscoveryReadinessPresentation(+ makeReadiness({ state: 'fresh', reason: 'something' }),+ );+ expect(presentation?.detail).toBe('something');+ });+ });++ describe('formatDiscoveryReadinessBriefingLine', () => {+ it('returns an empty string when readiness is null/undefined (presentation is null)', () => {+ expect(formatDiscoveryReadinessBriefingLine(undefined)).toBe('');+ expect(formatDiscoveryReadinessBriefingLine(null as unknown as ReadinessArg)).toBe('');+ });++ it('joins statusLabel, service, observed and facts in canonical order', () => {+ expect(+ formatDiscoveryReadinessBriefingLine(+ makeReadiness({+ state: 'stale',+ serviceName: 'Home Assistant',+ factCount: 5,+ observedAt: '2024-01-02T03:04:05Z',+ }),+ ),+ ).toBe(+ 'Discovery data: Discovery stale, service Home Assistant, observed MOCKED_AGE:2024-01-02T03:04:05Z, 5 facts',+ );+ });++ it('emits only the statusLabel when no optional detail is present', () => {+ expect(formatDiscoveryReadinessBriefingLine(makeReadiness({ state: 'failed' }))).toBe(+ 'Discovery data: Discovery failed',+ );+ });++ it('emits the service branch alone when only serviceName is set', () => {+ expect(+ formatDiscoveryReadinessBriefingLine(makeReadiness({ state: 'failed', serviceName: 'SNMP' })),+ ).toBe('Discovery data: Discovery failed, service SNMP');+ });++ it('emits the observed branch alone when only observedAt is set', () => {+ expect(+ formatDiscoveryReadinessBriefingLine(makeReadiness({ state: 'failed', observedAt: 'X' })),+ ).toBe('Discovery data: Discovery failed, observed MOCKED_AGE:X');+ });++ it('emits the facts branch alone when only factCount is set', () => {+ expect(+ formatDiscoveryReadinessBriefingLine(makeReadiness({ state: 'failed', factCount: 3 })),+ ).toBe('Discovery data: Discovery failed, 3 facts');+ });++ it('drops zero and negative fact counts in the briefing details', () => {+ expect(+ formatDiscoveryReadinessBriefingLine(makeReadiness({ state: 'failed', factCount: 0 })),+ ).toBe('Discovery data: Discovery failed');+ expect(+ formatDiscoveryReadinessBriefingLine(makeReadiness({ state: 'failed', factCount: -2 })),+ ).toBe('Discovery data: Discovery failed');+ });+ });+});