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: harvest the 2026-07-25 branch-coverage batch for pulse
rcourtmanc25d393fff81
diff --git a/frontend-modern/src/api/__tests__/agentCapabilities.branchcov0725am.test.ts b/frontend-modern/src/api/__tests__/agentCapabilities.branchcov0725am.test.tsnew file mode 100644index 0000000000..89361d3835--- /dev/null+++ b/frontend-modern/src/api/__tests__/agentCapabilities.branchcov0725am.test.ts@@ -0,0 +1,333 @@+import { describe, expect, it } from 'vitest';+import {+ AGENT_SURFACE_ID_PULSE_MCP,+ getAgentCapabilityErrorCodeSummaries,+ getAgentMCPClientExamples,+ getAgentMCPConfigFamilyByShape,+ getAgentMCPOperationsLoopReadiness,+ getAgentManifestSurfaceToolContract,+ getAgentManifestSurfaceToolContracts,+ getAgentSurfaceContractEntries,+ getAgentWorkflowPrompts,+ groupAgentCapabilitiesByManifestCategories,+ type AgentCapabilitiesManifest,+ type AgentCapability,+ type AgentCapabilityCategory,+ type AgentMCPAdapterContract,+ type AgentOperatorSurfaceContract,+ type AgentSurfaceContractComponent,+} from '../agentCapabilities';++const capability = (overrides: Partial<AgentCapability> = {}): AgentCapability => ({+ name: 'cap',+ category: 'context',+ description: 'desc',+ method: 'GET',+ path: '/api/cap',+ scope: 'monitoring:read',+ actionMode: 'read',+ approvalPolicy: 'scope_only',+ ...overrides,+});++const component = (+ overrides: Partial<AgentSurfaceContractComponent> = {},+): AgentSurfaceContractComponent => ({+ id: 'component_id',+ label: 'Component',+ description: 'component description',+ ...overrides,+});++const operatorSurface = (+ overrides: Partial<AgentOperatorSurfaceContract> = {},+): AgentOperatorSurfaceContract => ({+ id: 'pulse_assistant',+ label: 'Pulse Assistant',+ description: 'assistant surface',+ native: true,+ externalAdapter: false,+ ...overrides,+});++const adapter = (overrides: Partial<AgentMCPAdapterContract> = {}): AgentMCPAdapterContract => ({+ serverName: 'pulse',+ command: 'pulse-mcp',+ baseUrlFlag: '--base-url',+ defaultBaseUrl: 'http://localhost:7655',+ tokenEnv: 'PULSE_API_TOKEN',+ configFamilies: [],+ ...overrides,+});++const manifest = (+ overrides: Partial<AgentCapabilitiesManifest> = {},+): AgentCapabilitiesManifest => ({+ version: 'v1',+ surfaceContract: {+ core: component({ id: 'core', label: 'Core' }),+ proactiveEngine: component({ id: 'patrol', label: 'Patrol' }),+ operatorSurfaces: [],+ },+ surfaceToolContracts: [],+ mcpAdapter: adapter(),+ requiredScopes: [],+ categories: [],+ workflowPrompts: [],+ capabilities: [],+ ...overrides,+});++describe('agentCapabilities branch coverage 0725am', () => {+ describe('getAgentMCPConfigFamilyByShape (line 330)', () => {+ it('returns undefined for a whitespace-only shape so the lookup is skipped entirely', () => {+ const adapterWithFamilies = adapter({+ configFamilies: [+ { id: 'opencode', label: 'OpenCode', shape: 'opencode_mcp' },+ { id: 'claude-style', label: 'Claude', shape: 'mcp_servers' },+ ],+ });++ expect(getAgentMCPConfigFamilyByShape(adapterWithFamilies, ' ')).toBeUndefined();+ // contrast: a real shape still resolves, proving the early return is shape-gated+ expect(getAgentMCPConfigFamilyByShape(adapterWithFamilies, 'mcp_servers')?.id).toBe(+ 'claude-style',+ );+ });+ });++ describe('getAgentMCPClientExamples (line 344)', () => {+ it('falls back to the family label when a family has no usable clientLabels', () => {+ const manifestWithoutClientLabels = manifest({+ mcpAdapter: adapter({+ configFamilies: [+ { id: 'solo', label: 'Solo Client', shape: 'solo_shape' },+ { id: 'all-blank', label: 'All Blank', shape: 'blank_shape', clientLabels: [' ', ''] },+ ],+ }),+ });++ // both families fall through to the else-branch (line 344): one has no clientLabels at all,+ // the other's normalize away to an empty list+ expect(getAgentMCPClientExamples(manifestWithoutClientLabels)).toEqual([+ 'Solo Client',+ 'All Blank',+ ]);+ });+ });++ describe('groupAgentCapabilitiesByManifestCategories (line 442)', () => {+ it('treats a missing categories array as an empty iteration and still groups capabilities', () => {+ const manifestWithoutCategories = manifest({+ capabilities: [capability({ name: 'orphaned_cap', category: 'orphaned' })],+ categories: undefined as unknown as AgentCapabilityCategory[],+ });++ const sections = groupAgentCapabilitiesByManifestCategories(manifestWithoutCategories);++ // no manifest categories were iterated, so the capability surfaces via the unknown-category+ // fallback path with its raw category id as the section label+ expect(sections.map((section) => [section.id, section.label])).toEqual([+ ['orphaned', 'orphaned'],+ ]);+ expect(sections[0]?.entries.map((entry) => entry.name)).toEqual(['orphaned_cap']);+ });+ });++ describe('normalizeSurfaceAffordances via getAgentSurfaceContractEntries (line 508)', () => {+ it('returns an empty affordance object for an unknown but non-empty surface id', () => {+ const entries = getAgentSurfaceContractEntries(+ manifest({+ surfaceContract: {+ core: component({ id: 'c', label: 'C' }),+ proactiveEngine: component({ id: 'p', label: 'P' }),+ operatorSurfaces: [+ operatorSurface({+ id: 'ext_unknown',+ label: 'Ext Unknown',+ native: false,+ externalAdapter: true,+ }),+ operatorSurface({+ id: 'pulse_mcp',+ label: 'Known MCP',+ native: false,+ externalAdapter: true,+ }),+ ],+ },+ }),+ );++ // the unknown id takes the `?? {}` arm: no affordance badges are projected+ expect(entries[2]?.badges).toEqual(['External adapter']);+ // contrast: a known id (pulse_mcp) projects the full default affordance badge set+ expect(entries[3]?.badges).toEqual([+ 'External adapter',+ 'Actions',+ 'Resources',+ 'Prompts',+ 'Capability metadata',+ ]);+ });+ });++ describe('getAgentWorkflowPrompts (line 551)', () => {+ it('returns an empty array when the manifest itself is missing', () => {+ expect(getAgentWorkflowPrompts(undefined)).toEqual([]);+ });++ it('treats a missing workflowPrompts array as an empty iteration', () => {+ const manifestWithoutPrompts = {+ ...manifest(),+ workflowPrompts: undefined as unknown as AgentCapabilitiesManifest['workflowPrompts'],+ };++ expect(getAgentWorkflowPrompts(manifestWithoutPrompts)).toEqual([]);+ });+ });++ describe('getAgentMCPOperationsLoopReadiness (line 596)', () => {+ it('treats a missing surface tool contract as an empty tool-name set and reports every capability missing', () => {+ const readiness = getAgentMCPOperationsLoopReadiness(+ manifest({+ workflowPrompts: [{ name: 'pulse_operations_loop', label: 'Operations loop' }],+ }),+ );++ // contract is undefined -> `contract?.toolNames ?? []` takes the ?? arm; every patrol-control+ // capability name ends up in missingCapabilities and hasSurfaceTools is false.+ expect(readiness.hasSurfaceTools).toBe(false);+ expect(readiness.available).toBe(false);+ expect(readiness.missingCapabilities).toEqual([+ 'get_patrol_control_status',+ 'get_fleet_context',+ 'get_resource_context',+ 'list_findings',+ 'plan_action',+ 'decide_action',+ 'execute_action',+ 'resolve_finding',+ ]);+ });+ });++ describe('getAgentManifestSurfaceToolContract', () => {+ it('returns undefined when the manifest is missing (line 642)', () => {+ expect(+ getAgentManifestSurfaceToolContract(undefined, AGENT_SURFACE_ID_PULSE_MCP),+ ).toBeUndefined();+ });++ it('returns undefined when the surface id is whitespace (line 645)', () => {+ const manifestWithAdapterSurface = manifest({+ surfaceContract: {+ core: component({ id: 'c', label: 'C' }),+ proactiveEngine: component({ id: 'p', label: 'P' }),+ operatorSurfaces: [+ operatorSurface({+ id: AGENT_SURFACE_ID_PULSE_MCP,+ label: 'Pulse MCP',+ native: false,+ externalAdapter: true,+ }),+ ],+ },+ surfaceToolContracts: [+ {+ surfaceId: AGENT_SURFACE_ID_PULSE_MCP,+ surfaceLabel: 'Pulse MCP',+ toolSource: 'capability_manifest',+ toolNames: ['get_fleet_context'],+ },+ ],+ });++ expect(+ getAgentManifestSurfaceToolContract(manifestWithAdapterSurface, ' '),+ ).toBeUndefined();+ });++ it('falls back to the normalized surface id when the surface label is blank (line 655)', () => {+ const manifestWithBlankLabel = manifest({+ surfaceContract: {+ core: component({ id: 'c', label: 'C' }),+ proactiveEngine: component({ id: 'p', label: 'P' }),+ operatorSurfaces: [+ operatorSurface({+ id: AGENT_SURFACE_ID_PULSE_MCP,+ label: ' ',+ native: false,+ externalAdapter: true,+ affordances: { tools: true },+ }),+ ],+ },+ surfaceToolContracts: [+ {+ surfaceId: AGENT_SURFACE_ID_PULSE_MCP,+ toolSource: 'capability_manifest',+ toolNames: ['get_fleet_context'],+ capabilityNames: ['get_fleet_context'],+ },+ ],+ });++ const contract = getAgentManifestSurfaceToolContract(+ manifestWithBlankLabel,+ AGENT_SURFACE_ID_PULSE_MCP,+ );++ // surface.label?.trim() is empty -> falls back to normalizedSurfaceId ('pulse_mcp')+ expect(contract?.surfaceLabel).toBe(AGENT_SURFACE_ID_PULSE_MCP);+ expect(contract?.toolNames).toEqual(['get_fleet_context']);+ });+ });++ describe('getAgentManifestSurfaceToolContracts (line 664)', () => {+ it('treats a missing manifest as an empty surface iteration', () => {+ expect(getAgentManifestSurfaceToolContracts(undefined)).toEqual([]);+ });+ });++ describe('getAgentCapabilityErrorCodeSummaries', () => {+ it('returns an empty array when the manifest is missing (line 714)', () => {+ expect(getAgentCapabilityErrorCodeSummaries(undefined)).toEqual([]);+ });++ it('skips capabilities whose name trims to empty (line 719)', () => {+ const summaries = getAgentCapabilityErrorCodeSummaries(+ manifest({+ capabilities: [+ capability({ name: ' ', errorCodes: ['should_never_appear'] }),+ capability({ name: 'real_cap', errorCodes: ['real_code'] }),+ ],+ }),+ );++ // the whitespace-name capability is skipped at line 719, so its code never lands in a summary+ expect(summaries).toEqual([{ code: 'real_code', capabilityNames: ['real_cap'] }]);+ expect(summaries.some((summary) => summary.code === 'should_never_appear')).toBe(false);+ });++ it('treats a capability without an errorCodes list as an empty iteration (line 721)', () => {+ const { errorCodes: _omitted, ...capabilityWithoutErrorCodes } = capability({+ name: 'no_codes',+ });+ void _omitted;++ const summaries = getAgentCapabilityErrorCodeSummaries(+ manifest({+ capabilities: [+ capabilityWithoutErrorCodes as AgentCapability,+ capability({ name: 'with_codes', errorCodes: ['declared_code'] }),+ ],+ }),+ );++ // the capability without errorCodes contributes nothing (`capability.errorCodes ?? []` arm)+ // while the sibling capability still declares its code+ expect(summaries).toEqual([{ code: 'declared_code', capabilityNames: ['with_codes'] }]);+ });+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.branchcov0725am.test.tsx b/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.branchcov0725am.test.tsxnew file mode 100644index 0000000000..e1d59cec8c--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/useAuditLogPanelState.branchcov0725am.test.tsx@@ -0,0 +1,612 @@+import { createSignal } from 'solid-js';+import { renderHook, waitFor } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { apiFetch } from '@/utils/apiClient';+import { showSuccess } from '@/utils/toast';+import { useAuditLogPanelState, type AuditEvent } from '../useAuditLogPanelState';++// Reactive location search. The mock factory closes over the signal readers+// lazily (same pattern the sibling spec uses for `navigate`), so the filter+// createEffects inside the hook genuinely re-run when a setter mutates the URL.+const [readLocationSearch, writeLocationSearch] = createSignal('');++const panelState = vi.hoisted(() => ({+ license: {+ hasFeature: (feature: string): boolean => feature === 'audit_logging',+ runtimeLoaded: true,+ capabilityBlock: undefined as { reason?: string; action_url?: string } | undefined,+ },+ hideUpgradePrompts: false,+}));++const navigate = vi.hoisted(() => vi.fn());++vi.mock('@solidjs/router', () => ({+ useLocation: () => ({+ pathname: '/settings/security',+ get search() {+ return readLocationSearch();+ },+ }),+ useNavigate: () => navigate,+}));++vi.mock('@/stores/license', () => ({+ getRuntimeCapabilityBlock: () => panelState.license.capabilityBlock,+ hasFeature: (feature: string) => panelState.license.hasFeature(feature),+ loadRuntimeCapabilities: vi.fn().mockResolvedValue(undefined),+ runtimeCapabilitiesLoaded: () => panelState.license.runtimeLoaded,+}));++vi.mock('@/stores/licenseCommercial', () => ({+ getUpgradeActionDestination: () => ({ href: '/upgrade', external: false }),+}));++vi.mock('@/stores/sessionPresentationPolicy', () => ({+ presentationPolicyHidesUpgradePrompts: () => panelState.hideUpgradePrompts,+}));++vi.mock('@/utils/upgradeNavigation', () => ({+ resolveUpgradeDestination: (url?: string) => ({+ href: url ?? '/fallback',+ external: false,+ hardNavigation: false,+ newTab: false,+ preserveOpener: false,+ }),+}));++vi.mock('@/utils/toast', () => ({+ showSuccess: vi.fn(),+ showToast: vi.fn(),+ showWarning: vi.fn(),+}));++vi.mock('@/utils/apiClient', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/utils/apiClient')>();+ return {+ ...actual,+ apiFetch: vi.fn(),+ apiErrorFromResponse: vi.fn(),+ };+});++type Deferred<T> = {+ promise: Promise<T>;+ resolve: (value: T) => void;+};++const deferred = <T,>(): Deferred<T> => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });+ return { promise, resolve };+};++const JSON_HEADERS = { 'Content-Type': 'application/json' };++const signedEvent = (id: string): AuditEvent => ({+ id,+ timestamp: '2026-07-24T09:00:00Z',+ event: 'login',+ user: 'operator',+ ip: '127.0.0.1',+ path: '/api/auth',+ success: true,+ details: id,+ signature: `sig-${id}`,+});++const unsignedEvent = (id: string): AuditEvent => ({+ id,+ timestamp: '2026-07-24T09:00:00Z',+ event: 'login',+ user: 'operator',+ ip: '127.0.0.1',+ path: '/api/auth',+ success: true,+ details: id,+});++const auditListResponse = (events: AuditEvent[], total: number = events.length): Response =>+ new Response(JSON.stringify({ events, total, persistentLogging: false }), {+ status: 200,+ headers: JSON_HEADERS,+ });++const verifyResponse = (+ body: { available: boolean; verified?: boolean; message?: string },+ status = 200,+ statusText = '',+): Response => new Response(JSON.stringify(body), { status, statusText, headers: JSON_HEADERS });++const isVerifyCall = (url: unknown): boolean => typeof url === 'string' && url.includes('/verify');++const renderIdle = async (options: { featureEnabled?: boolean; locationSearch?: string } = {}) => {+ if (options.locationSearch !== undefined) writeLocationSearch(options.locationSearch);+ if (options.featureEnabled === false) panelState.license.hasFeature = () => false;+ const hook = renderHook(() => useAuditLogPanelState());+ await waitFor(() => expect(hook.result.loading()).toBe(false));+ return hook;+};++describe('useAuditLogPanelState branch coverage', () => {+ beforeEach(() => {+ window.localStorage.clear();+ writeLocationSearch('');+ panelState.license.hasFeature = (feature: string): boolean => feature === 'audit_logging';+ panelState.license.runtimeLoaded = true;+ panelState.license.capabilityBlock = undefined;+ panelState.hideUpgradePrompts = false;+ navigate.mockReset();+ navigate.mockImplementation((url: string) => {+ const q = String(url).indexOf('?');+ writeLocationSearch(q >= 0 ? String(url).slice(q + 1) : '');+ });+ vi.mocked(apiFetch).mockReset();+ vi.mocked(showSuccess).mockReset();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('URL filter setters + updateSearchParam', () => {+ it('setEventFilter writes an allowed event value into the search string', async () => {+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setEventFilter('login');+ expect(result.eventFilter()).toBe('login');+ expect(navigate).toHaveBeenLastCalledWith('/settings/security?event=login', {+ replace: true,+ });+ cleanup();+ });++ it('setEventFilter drops the event param when the value normalizes to empty', async () => {+ writeLocationSearch('event=login');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setEventFilter('');+ expect(result.eventFilter()).toBe('');+ // updateSearchParam must omit the '?' entirely once no params remain.+ expect(navigate).toHaveBeenLastCalledWith('/settings/security', { replace: true });+ cleanup();+ });++ it('setUserFilter writes a non-empty user value into the search string', async () => {+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setUserFilter('alice');+ expect(result.userFilter()).toBe('alice');+ expect(readLocationSearch()).toBe('user=alice');+ cleanup();+ });++ it('setUserFilter drops the user param when the value is empty', async () => {+ writeLocationSearch('user=alice');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setUserFilter('');+ expect(result.userFilter()).toBe('');+ expect(readLocationSearch()).toBe('');+ cleanup();+ });++ it('setSuccessFilter writes a non-default success value into the search string', async () => {+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setSuccessFilter('failed');+ expect(result.successFilter()).toBe('failed');+ expect(readLocationSearch()).toBe('success=failed');+ cleanup();+ });++ it('setSuccessFilter drops the success param when the value resolves to the default', async () => {+ writeLocationSearch('success=failed');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setSuccessFilter('all');+ expect(result.successFilter()).toBe('all');+ expect(readLocationSearch()).toBe('');+ cleanup();+ });++ it('setVerificationFilter writes a non-default verification value into the search string', async () => {+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setVerificationFilter('needs');+ expect(result.verificationFilter()).toBe('needs');+ expect(readLocationSearch()).toBe('verification=needs');+ cleanup();+ });++ it('setVerificationFilter drops the verification param when the value resolves to the default', async () => {+ writeLocationSearch('verification=needs');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.setVerificationFilter('all');+ expect(result.verificationFilter()).toBe('all');+ expect(readLocationSearch()).toBe('');+ cleanup();+ });+ });++ describe('activeFilterCount and activeFilterChips', () => {+ it('reports zero filters and no chips when the URL is clean', async () => {+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ expect(result.activeFilterCount()).toBe(0);+ expect(result.activeFilterChips()).toEqual([]);+ cleanup();+ });++ it('counts all four filters and emits one chip per active filter', async () => {+ writeLocationSearch('event=login&user=alice&success=failed&verification=needs');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ expect(result.activeFilterCount()).toBe(4);+ expect(result.activeFilterChips().map((chip) => chip.label)).toEqual([+ 'Event: login',+ 'User: alice',+ 'Success: failed',+ 'Verification: needs',+ ]);+ cleanup();+ });+ });++ describe('clearFilters', () => {+ it('clears every filter and toasts when filters were active', async () => {+ writeLocationSearch('event=login&user=alice');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ expect(result.activeFilterCount()).toBe(2);+ result.clearFilters();+ expect(showSuccess).toHaveBeenCalledWith('Audit filters cleared');+ expect(readLocationSearch()).toBe('');+ expect(result.activeFilterCount()).toBe(0);+ cleanup();+ });++ it('clears quietly without toasting when no filters were active', async () => {+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ result.clearFilters();+ expect(showSuccess).not.toHaveBeenCalled();+ expect(readLocationSearch()).toBe('');+ cleanup();+ });+ });++ describe('clearFilterChip', () => {+ it('clears the event filter when keyed on "event"', async () => {+ writeLocationSearch('event=login');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ expect(result.eventFilter()).toBe('login');+ result.clearFilterChip('event');+ expect(result.eventFilter()).toBe('');+ cleanup();+ });++ it('clears the user filter when keyed on "user"', async () => {+ writeLocationSearch('user=alice');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ expect(result.userFilter()).toBe('alice');+ result.clearFilterChip('user');+ expect(result.userFilter()).toBe('');+ cleanup();+ });++ it('clears the success filter when keyed on "success"', async () => {+ writeLocationSearch('success=failed');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ expect(result.successFilter()).toBe('failed');+ result.clearFilterChip('success');+ expect(result.successFilter()).toBe('all');+ cleanup();+ });++ it('clears the verification filter when keyed on "verification"', async () => {+ writeLocationSearch('verification=needs');+ const { result, cleanup } = await renderIdle({ featureEnabled: false });+ expect(result.verificationFilter()).toBe('needs');+ result.clearFilterChip('verification');+ expect(result.verificationFilter()).toBe('all');+ cleanup();+ });+ });++ describe('upgrade prompt and feature-gate accessors', () => {+ it('exposes upgrade prompts and the "View plans" label when audit logging is simply unlicensed', async () => {+ panelState.license.hasFeature = () => false;+ const { result, cleanup } = await renderIdle();+ expect(result.paidRuntimeRequired()).toBe(false);+ expect(result.showUpgradePrompts()).toBe(true);+ expect(result.showFeatureGateAction()).toBe(true);+ expect(result.upgradeActionLabel()).toBe('View plans');+ cleanup();+ });++ it('hides upgrade prompts and switches to the Pro download label when a paid runtime is required', async () => {+ panelState.license.hasFeature = () => false;+ panelState.license.capabilityBlock = {+ reason: 'paid_runtime_required',+ action_url: '/download',+ };+ const { result, cleanup } = await renderIdle();+ expect(result.paidRuntimeRequired()).toBe(true);+ expect(result.showUpgradePrompts()).toBe(false);+ expect(result.showFeatureGateAction()).toBe(true);+ expect(result.upgradeActionLabel()).toBe('Download Pulse Pro');+ cleanup();+ });++ it('hides the feature-gate action entirely when the presentation policy suppresses upgrade prompts', async () => {+ panelState.license.hasFeature = () => false;+ panelState.hideUpgradePrompts = true;+ const { result, cleanup } = await renderIdle();+ expect(result.showUpgradePrompts()).toBe(false);+ expect(result.showFeatureGateAction()).toBe(false);+ expect(result.upgradeActionLabel()).toBe('View plans');+ cleanup();+ });+ });++ describe('verifyEvent', () => {+ it('is a no-op when audit logging is disabled', async () => {+ panelState.license.hasFeature = () => false;+ vi.mocked(apiFetch).mockImplementation(async () => auditListResponse([]));+ const { result, cleanup } = await renderIdle();+ await result.verifyEvent(signedEvent('a'));+ expect(apiFetch).not.toHaveBeenCalled();+ expect(result.verifying()).toEqual({});+ expect(result.verification()['a']).toBeUndefined();+ cleanup();+ });++ it('is a no-op when the event carries no signature', async () => {+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) return verifyResponse({ available: true, verified: true });+ return auditListResponse([]);+ });+ const { result, cleanup } = await renderIdle();+ const callsBefore = vi.mocked(apiFetch).mock.calls.length;+ await result.verifyEvent(unsignedEvent('a'));+ expect(vi.mocked(apiFetch).mock.calls.length).toBe(callsBefore);+ expect(result.verification()['a']).toBeUndefined();+ cleanup();+ });++ it('records a "verified" status when the signature checks out', async () => {+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) {+ return verifyResponse({ available: true, verified: true, message: 'matched' });+ }+ return auditListResponse([]);+ });+ const { result, cleanup } = await renderIdle();+ const event = signedEvent('a');+ await result.verifyEvent(event);+ expect(result.verification()[event.id]).toEqual({ status: 'verified', message: 'matched' });+ expect(result.verifying()[event.id]).toBe(false);+ cleanup();+ });++ it('records an "unavailable" status when verification is not available for the event', async () => {+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) return verifyResponse({ available: false, message: 'no key' });+ return auditListResponse([]);+ });+ const { result, cleanup } = await renderIdle();+ const event = signedEvent('a');+ await result.verifyEvent(event);+ expect(result.verification()[event.id]).toEqual({+ status: 'unavailable',+ message: 'no key',+ });+ cleanup();+ });++ it('records a "failed" status when verification ran but the signature did not match', async () => {+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) {+ return verifyResponse({ available: true, verified: false, message: 'mismatch' });+ }+ return auditListResponse([]);+ });+ const { result, cleanup } = await renderIdle();+ const event = signedEvent('a');+ await result.verifyEvent(event);+ expect(result.verification()[event.id]).toEqual({ status: 'failed', message: 'mismatch' });+ cleanup();+ });++ it('records an "error" status when the verify endpoint returns a non-OK response', async () => {+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) {+ return verifyResponse({ available: true }, 500, 'Internal Server Error');+ }+ return auditListResponse([]);+ });+ const { result, cleanup } = await renderIdle();+ const event = signedEvent('a');+ await result.verifyEvent(event);+ expect(result.verification()[event.id]?.status).toBe('error');+ expect(result.verification()[event.id]?.message).toContain('Failed to verify signature');+ cleanup();+ });+ });++ describe('signed-event inspection (hasSignedEvents / hasResumeEvents / resumeCount)', () => {+ it('reports no signed events when every event lacks a signature', async () => {+ vi.mocked(apiFetch).mockResolvedValue(+ auditListResponse([unsignedEvent('a'), unsignedEvent('b')]),+ );+ const { result, cleanup } = await renderIdle();+ expect(result.hasSignedEvents()).toBe(false);+ expect(result.hasResumeEvents()).toBe(false);+ expect(result.resumeCount()).toBe(0);+ cleanup();+ });++ it('counts every unchecked signed event as resumable', async () => {+ vi.mocked(apiFetch).mockResolvedValue(+ auditListResponse([signedEvent('a'), unsignedEvent('b'), signedEvent('c')]),+ );+ const { result, cleanup } = await renderIdle();+ expect(result.hasSignedEvents()).toBe(true);+ expect(result.hasResumeEvents()).toBe(true);+ expect(result.resumeCount()).toBe(2);+ cleanup();+ });++ it('drops an event from the resume set once it verifies successfully', async () => {+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) return verifyResponse({ available: true, verified: true });+ return auditListResponse([signedEvent('a'), signedEvent('b')]);+ });+ const { result, cleanup } = await renderIdle();+ expect(result.resumeCount()).toBe(2);+ await result.verifyEvent(result.events()[0]);+ expect(result.resumeCount()).toBe(1);+ await result.verifyEvent(result.events()[1]);+ expect(result.resumeCount()).toBe(0);+ expect(result.hasResumeEvents()).toBe(false);+ cleanup();+ });++ it('keeps failed events resumable while treating unavailable ones as settled', async () => {+ let verifyCount = 0;+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) {+ verifyCount += 1;+ return verifyCount === 1+ ? verifyResponse({ available: true, verified: false })+ : verifyResponse({ available: false });+ }+ return auditListResponse([signedEvent('a'), signedEvent('b')]);+ });+ const { result, cleanup } = await renderIdle();+ expect(result.resumeCount()).toBe(2);+ await result.verifyEvent(result.events()[0]);+ expect(result.resumeCount()).toBe(2);+ await result.verifyEvent(result.events()[1]);+ expect(result.resumeCount()).toBe(1);+ cleanup();+ });+ });++ describe('verifyAllLabel', () => {+ it('reads "Verify All" while no batch verification is running', async () => {+ vi.mocked(apiFetch).mockResolvedValue(auditListResponse([signedEvent('a')]));+ const { result, cleanup } = await renderIdle();+ expect(result.verifyAllLabel()).toBe('Verify All');+ cleanup();+ });++ it('reports live progress while a batch verification is paused mid-flight', async () => {+ const firstVerify = deferred<Response>();+ let verifyCount = 0;+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) {+ verifyCount += 1;+ if (verifyCount === 1) return firstVerify.promise;+ return verifyResponse({ available: true, verified: true });+ }+ return auditListResponse([signedEvent('a'), signedEvent('b')]);+ });+ const { result, cleanup } = await renderIdle();+ result.verifyAll();+ expect(result.verifyAllLabel()).toBe('Verifying 0 of 2');+ firstVerify.resolve(verifyResponse({ available: true, verified: true }));+ await waitFor(() => expect(result.verifyingAll()).toBe(false));+ expect(result.verifyAllLabel()).toBe('Verify All');+ cleanup();+ });++ it('falls back to the ellipsis label when a fetch resets the verify-all total mid-flight', async () => {+ const firstVerify = deferred<Response>();+ let verifyCount = 0;+ vi.mocked(apiFetch).mockImplementation(async (url: string) => {+ if (isVerifyCall(url)) {+ verifyCount += 1;+ if (verifyCount === 1) return firstVerify.promise;+ return verifyResponse({ available: true, verified: true });+ }+ return auditListResponse([signedEvent('a'), signedEvent('b')]);+ });+ const { result, cleanup } = await renderIdle();+ result.verifyAll();+ expect(result.verifyAllLabel()).toBe('Verifying 0 of 2');+ result.refresh();+ expect(result.verifyAllLabel()).toBe('Verifying…');+ firstVerify.resolve(verifyResponse({ available: true, verified: true }));+ await waitFor(() => expect(result.verifyingAll()).toBe(false));+ cleanup();+ });+ });++ describe('paging accessors (hasNextPage / totalPages)', () => {+ it('clamps to a single page with no next page when there are no events', async () => {+ vi.mocked(apiFetch).mockResolvedValue(auditListResponse([]));+ const { result, cleanup } = await renderIdle();+ expect(result.totalPages()).toBe(1);+ expect(result.pageNumber()).toBe(1);+ expect(result.hasNextPage()).toBe(false);+ cleanup();+ });++ it('exposes a next page while on the first page of a multi-page set', async () => {+ vi.mocked(apiFetch).mockResolvedValue(+ auditListResponse(+ Array.from({ length: 100 }, (_, index) => unsignedEvent(`e${index}`)),+ 250,+ ),+ );+ const { result, cleanup } = await renderIdle();+ expect(result.totalPages()).toBe(3);+ expect(result.pageNumber()).toBe(1);+ expect(result.hasNextPage()).toBe(true);+ cleanup();+ });++ it('reports no next page while on the final page', async () => {+ window.localStorage.setItem('pulse-audit-page-offset', '200');+ vi.mocked(apiFetch).mockResolvedValue(+ auditListResponse(+ Array.from({ length: 50 }, (_, index) => unsignedEvent(`e${index}`)),+ 250,+ ),+ );+ const { result, cleanup } = await renderIdle();+ expect(result.pageNumber()).toBe(3);+ expect(result.totalPages()).toBe(3);+ expect(result.hasNextPage()).toBe(false);+ cleanup();+ });+ });++ describe('resetPaging (exercised via resetPreferences)', () => {+ it('zeroes the stored offset and clears the page input', async () => {+ window.localStorage.setItem('pulse-audit-page-offset', '200');+ vi.mocked(apiFetch).mockResolvedValue(auditListResponse([], 250));+ const { result, cleanup } = await renderIdle();+ expect(result.pageOffset()).toBe(200);+ result.setPageInput('3');+ expect(result.pageInput()).toBe('3');+ result.resetPreferences();+ expect(result.pageOffset()).toBe(0);+ expect(result.pageInput()).toBe('');+ expect(showSuccess).toHaveBeenCalledWith('Audit preferences reset');+ cleanup();+ });+ });++ describe('refetchFromFirstPage (exercised via the server-side filter effects)', () => {+ it('re-requests the audit list from offset zero when an event filter is applied', async () => {+ window.localStorage.setItem('pulse-audit-page-offset', '200');+ vi.mocked(apiFetch).mockResolvedValue(auditListResponse([], 250));+ const { result, cleanup } = await renderIdle();+ expect(result.pageOffset()).toBe(200);+ result.setEventFilter('login');+ await waitFor(() => {+ const lastURL = vi.mocked(apiFetch).mock.calls.at(-1)?.[0];+ expect(String(lastURL)).toContain('offset=0');+ });+ expect(result.eventFilter()).toBe('login');+ expect(result.pageOffset()).toBe(0);+ cleanup();+ });+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/useConnectionsLedger.branchcov0725am.test.ts b/frontend-modern/src/components/Settings/__tests__/useConnectionsLedger.branchcov0725am.test.tsnew file mode 100644index 0000000000..bc4404b92f--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/useConnectionsLedger.branchcov0725am.test.ts@@ -0,0 +1,376 @@+import { renderHook, waitFor } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ ConnectionsAPI,+ type Connection,+ type ConnectionSystem,+ type ConnectionType,+} from '@/api/connections';+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';+import { connectionToRow, useConnectionsLedger } from '../useConnectionsLedger';++// ---- Fixtures ---------------------------------------------------------------+// Mirrors the sibling branchcov suites: a minimal valid Connection factory and+// the shared hook harness (reset retained cache + restore mocks each case).++const connectionFixture = (overrides: Partial<Connection> = {}): Connection => ({+ id: 'pve:node-1',+ type: 'pve',+ name: 'node-1',+ address: 'https://node-1:8006',+ state: 'active',+ stateReason: '',+ enabled: true,+ surfaces: ['vms', 'containers'],+ scope: { vms: true, containers: true },+ lastSeen: '2026-07-22T12:00:00Z',+ lastError: null,+ source: 'manual',+ capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },+ ...overrides,+});++const useLedgerHarness = () => {+ beforeEach(() => {+ resetCreateNonSuspendingQueryCacheForTest();+ });+ afterEach(() => {+ resetCreateNonSuspendingQueryCacheForTest();+ vi.restoreAllMocks();+ });+};++const renderLedger = (connections: Connection[], systems: ConnectionSystem[]) => {+ vi.spyOn(ConnectionsAPI, 'list').mockResolvedValue({ connections, systems });+ return renderHook(() => useConnectionsLedger());+};++// ---- connectionToRow (subtitleFor / sourceFor fallback arms) ----------------++describe('connectionToRow (line 135: subtitleFor unknown-type fallback)', () => {+ it('falls back to the raw type string when the type is absent from CONNECTION_TYPE_LABELS', () => {+ // Every valid ConnectionType is a key in CONNECTION_TYPE_LABELS, so the+ // ?? primaryConnection.type arm can only fire for a type the label map+ // does not know — simulating a backend sending an unrecognised type string.+ const row = connectionToRow(+ connectionFixture({+ id: 'mystery:host',+ type: 'mystery' as unknown as ConnectionType,+ name: 'mystery-host',+ address: 'mystery-host',+ surfaces: [],+ scope: {},+ }),+ );+ expect(row.subtitle).toBe('via mystery');+ });+});++describe('connectionToRow (line 161: sourceFor configured-availability fallback)', () => {+ it('reports source "probe" from configured presence when an availability target is not contributing', () => {+ // A stale availability target is not active/paused, so the contributor arm+ // (line 156) is skipped and sourceFor falls through to the configured-+ // presence availability arm (line 161) — distinct from the existing spec+ // which uses an active (contributing) availability target hitting line 156.+ const row = connectionToRow(+ connectionFixture({+ id: 'availability:stale',+ type: 'availability',+ name: 'stale-target',+ address: 'stale-target',+ state: 'stale',+ surfaces: ['availability'],+ scope: { availability: true },+ }),+ );+ expect(row.source).toBe('probe');+ });+});++// ---- useConnectionsLedger (hook-driven arms) --------------------------------++describe('useConnectionsLedger (line 206: stableRecordEntries null-scope signature)', () => {+ useLedgerHarness();++ it('renders a row whose connection has a null scope', async () => {+ // connectionRowSignature calls stableRecordEntries(connection.scope).+ // With scope === null the ?? {} arm fires so Object.entries does not throw.+ // The sibling suite covers null scope via connectionToRow directly (which+ // exercises coverageLabelsFor), but never through the hook's signature+ // path — a distinct code site on line 206.+ const conn = connectionFixture({+ id: 'agent:null-scope',+ type: 'agent',+ name: 'null-scope',+ address: 'null-scope',+ state: 'active',+ surfaces: ['host'],+ scope: null as unknown as Connection['scope'],+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const { result } = renderLedger([conn], []);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // Null scope propagates: coverageLabelsFor also falls back to surfaces.+ expect(result.rows()[0].coverageLabels).toEqual(['Host telemetry']);+ });+});++describe('useConnectionsLedger (line 302: buildMemberRow member-lastSeen fallback)', () => {+ useLedgerHarness();++ beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-07-22T12:00:00.000Z'));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('derives member lastSeen from the paired agent when the member has none', async () => {+ // member.lastSeen ?? agentConnection?.lastSeen — the fallback arm fires+ // when the member omits lastSeen. The sibling suite always sets lastSeen+ // on every member, so the agent-fallback arm is cold without this case.+ const vmware = connectionFixture({+ id: 'vmware:vc',+ type: 'vmware',+ name: 'Lab vCenter',+ address: 'https://vcenter:443',+ surfaces: ['vms', 'hosts'],+ scope: { vms: true, hosts: true },+ });+ const attachedAgent = connectionFixture({+ id: 'agent:attached',+ type: 'agent',+ name: 'attached',+ address: 'attached',+ state: 'active',+ lastSeen: '2026-07-22T11:00:00Z',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const system: ConnectionSystem = {+ id: 'vmware:vc',+ type: 'vmware',+ components: [+ { connectionId: 'vmware:vc', type: 'vmware', role: 'primary' },+ { connectionId: 'agent:attached', type: 'agent', role: 'attachment' },+ ],+ members: [+ {+ id: 'host-1',+ name: 'esxi-01',+ state: 'active',+ lastSeen: null,+ agentConnectionId: 'agent:attached',+ },+ ],+ };+ const { result } = renderLedger([vmware, attachedAgent], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // member.lastSeen null → agentConnection.lastSeen (exactly 1h before pinned now).+ expect(result.rows()[0].members[0].lastActivityText).toBe('1h ago');+ });+});++describe('useConnectionsLedger (lines 543-544: fetcher nullish-field tolerance)', () => {+ useLedgerHarness();++ it('defaults to empty arrays when the list response omits connections and systems', async () => {+ // The fetcher does response.connections ?? [] / response.systems ?? [].+ // The sibling suites always supply both arrays; a malformed response that+ // omits them exercises both fallback arms.+ const listSpy = vi+ .spyOn(ConnectionsAPI, 'list')+ .mockResolvedValue({} as unknown as Awaited<ReturnType<typeof ConnectionsAPI.list>>);+ const { result } = renderHook(() => useConnectionsLedger());++ await waitFor(() => expect(listSpy).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(result.loading()).toBe(false));+ // Both ?? [] arms fire; the hook exposes arrays, not undefined.+ expect(result.connections()).toEqual([]);+ expect(result.rows()).toEqual([]);+ });+});++describe('useConnectionsLedger (line 584: clusterMemberHosts null-members tolerance)', () => {+ useLedgerHarness();++ it('collects no cluster-member hosts when a pve cluster system omits members', async () => {+ // The clusterMemberHosts loop guards with system.members ?? []. A pve+ // system with a clusterName but members === undefined exercises the ?? arm+ // instead of throwing "undefined is not iterable". The sibling suites+ // always provide members (or omit clusterName, hitting the `continue`).+ const primary = connectionFixture({+ id: 'pve:nomembers',+ name: 'nomembers',+ address: 'https://nomembers:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const system: ConnectionSystem = {+ id: 'pve:nomembers',+ type: 'pve',+ clusterName: 'empty-cluster',+ components: [{ connectionId: 'pve:nomembers', type: 'pve', role: 'primary' }],+ members: undefined,+ };+ const { result } = renderLedger([primary], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // rawMembers ?? [] → [] → no members built, isCluster stays false.+ expect(result.rows()[0].isCluster).toBe(false);+ expect(result.rows()[0].members).toEqual([]);+ });+});++describe('useConnectionsLedger (line 597: dedupe null-components tolerance)', () => {+ useLedgerHarness();++ it('dedupes an agent system whose components field is absent', async () => {+ // system.components?.length ?? 0 → 0 ≤ 1 → the standalone-agent dedupe+ // check runs even though components is undefined. The sibling suites+ // always supply components, so the ?? 0 arm is cold without this case.+ const pvePrimary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const dupAgent = connectionFixture({+ id: 'agent:nocomponents',+ type: 'agent',+ name: 'delly',+ address: 'delly',+ state: 'active',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const clusterSystem: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ {+ id: 'm-delly',+ name: 'delly',+ state: 'active',+ lastSeen: '2026-07-22T12:00:00Z',+ primary: true,+ },+ ],+ };+ const agentSystem: ConnectionSystem = {+ id: 'agent:nocomponents',+ type: 'agent',+ components: undefined as unknown as ConnectionSystem['components'],+ };+ const { result } = renderLedger([pvePrimary, dupAgent], [clusterSystem, agentSystem]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // components?.length ?? 0 → 0 ≤ 1 → dedupe runs; agent host matches member.+ expect(result.rows().some((row) => row.id === 'agent:nocomponents')).toBe(false);+ });+});++describe('useConnectionsLedger (line 602: dedupe via agentIdentity.hostname)', () => {+ useLedgerHarness();++ it('dedupes an agent whose agentIdentity.hostname matches a cluster member', async () => {+ // Exercises the non-short-circuit arm of primary?.agentIdentity?.hostname:+ // agentIdentity is defined and .hostname is read, then matched. The sibling+ // suites dedupe via name and hostAliases but never via agentIdentity.hostname+ // (their agents have no agentIdentity at all, so the ?. short-circuits).+ const pvePrimary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const identityAgent = connectionFixture({+ id: 'agent:identity',+ type: 'agent',+ name: 'unrelated-name',+ address: 'unrelated-addr',+ agentIdentity: { hostname: 'delly', platform: 'linux' },+ state: 'active',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const clusterSystem: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ {+ id: 'm-delly',+ name: 'delly',+ state: 'active',+ lastSeen: '2026-07-22T12:00:00Z',+ primary: true,+ },+ ],+ };+ const agentSystem: ConnectionSystem = {+ id: 'agent:identity',+ type: 'agent',+ components: [{ connectionId: 'agent:identity', type: 'agent', role: 'primary' }],+ };+ const { result } = renderLedger([pvePrimary, identityAgent], [clusterSystem, agentSystem]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // Neither name nor address match; agentIdentity.hostname is the hit.+ expect(result.rows().some((row) => row.id === 'agent:identity')).toBe(false);+ });++ it('evaluates dedupe candidates when the agent primary connection is absent', async () => {+ // Exercises the short-circuit arm of primary?.agentIdentity?.hostname (and+ // the sibling primary?. accesses on lines 600-601) when the agent system+ // references a connection that is not in the ledger. The existing orphan-+ // system spec drops a pve system; an agent orphan additionally enters the+ // line-597 dedupe block, which the pve path never reaches.+ const pvePrimary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const clusterSystem: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ {+ id: 'm-delly',+ name: 'delly',+ state: 'active',+ lastSeen: '2026-07-22T12:00:00Z',+ primary: true,+ },+ ],+ };+ const orphanAgentSystem: ConnectionSystem = {+ id: 'agent:missing',+ type: 'agent',+ components: [{ connectionId: 'agent:missing', type: 'agent', role: 'primary' }],+ };+ const { result } = renderLedger([pvePrimary], [clusterSystem, orphanAgentSystem]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // primary is undefined → all candidates undefined → dedupe fails →+ // systemToRow returns null → orphan dropped. Only the cluster survives.+ expect(result.rows()[0].id).toBe('pve:cluster');+ expect(result.rows().some((row) => row.id === 'agent:missing')).toBe(false);+ });+});diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsTableState.branchcov0725am.test.tsx b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsTableState.branchcov0725am.test.tsxnew file mode 100644index 0000000000..406b666be5--- /dev/null+++ b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsTableState.branchcov0725am.test.tsx@@ -0,0 +1,684 @@+import { createSignal } from 'solid-js';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render } from '@solidjs/testing-library';++import type { BackupAlertConfig, PMGThresholdDefaults, SnapshotAlertConfig } from '@/types/alerts';+import type { ThresholdsTableProps } from '@/features/alerts/thresholds/types';+import type { Resource as TableResource } from '@/features/alerts/thresholds/tableTypes';+import { useThresholdsTableState } from '../useThresholdsTableState';++// --- module-level state read lazily inside the vi.mock factories -----------------++let mockPathname = '/alerts/thresholds/proxmox';+let mockHash = '';+let mockAlertsEnabled = true;+let mockNodes: TableResource[] = [];++// Modeled as a real Solid signal so the hook's dockerIgnored sync `createEffect`+// reconciles against it exactly as it would against a live store.+const [dockerIgnoredStore, setDockerIgnoredStore] = createSignal<string[]>([]);+let metricTimeState: Record<string, Record<string, number>> = {};+let pmgThresholdsState: PMGThresholdDefaults = {};+let snapshotPrev: SnapshotAlertConfig = { enabled: false, warningDays: 3, criticalDays: 7 };+let backupPrev: BackupAlertConfig = {+ enabled: false,+ warningDays: 7,+ criticalDays: 14,+ freshHours: 24,+};++// Spies are (re)created inside buildProps so each test starts with a fresh call history.+let setHasUnsavedChangesSpy: ReturnType<typeof vi.fn>;+let setDockerIgnoredPrefixesSpy: ReturnType<typeof vi.fn>;+let resetDockerIgnoredPrefixesSpy: ReturnType<typeof vi.fn>;+let setSnapshotDefaultsSpy: ReturnType<typeof vi.fn>;+let setBackupDefaultsSpy: ReturnType<typeof vi.fn>;+let setPMGThresholdsSpy: ReturnType<typeof vi.fn>;+let setMetricTimeThresholdsSpy: ReturnType<typeof vi.fn>;++vi.mock('@solidjs/router', () => ({+ useLocation: () => ({ pathname: mockPathname, hash: mockHash }),+ useNavigate: () => vi.fn(),+}));++vi.mock('@/stores/alertsActivation', () => ({+ useAlertsActivation: () => ({ detectionEnabled: () => mockAlertsEnabled }),+}));++vi.mock('@/components/Alerts/Thresholds/hooks/useCollapsedSections', () => ({+ useCollapsedSections: () => ({+ collapseAll: vi.fn(),+ expandAll: vi.fn(),+ isCollapsed: () => false,+ setCollapsed: vi.fn(),+ toggleSection: vi.fn(),+ }),+}));++vi.mock('../useThresholdsData', () => ({+ useThresholdsData: () => ({+ agentDisksGroupedByAgent: () => ({}),+ agentGroupHeaderMeta: () => ({}),+ agentDisksWithOverrides: () => [],+ agentsWithOverrides: () => [],+ dockerContainersFlat: () => [],+ dockerContainersGroupedByHost: () => ({}),+ dockerHostGroupMeta: () => ({}),+ dockerHostsWithOverrides: () => [],+ guestsFlat: () => [],+ guestsGroupedByNode: () => ({}),+ guestGroupHeaderMeta: () => ({}),+ nodesWithOverrides: () => mockNodes,+ pbsServersWithOverrides: () => [],+ pmgGlobalDefaults: () => ({}),+ pmgServersWithOverrides: () => [],+ storageGroupedByNode: () => ({}),+ storageWithOverrides: () => [],+ totalDockerContainers: () => 0,+ }),+}));++vi.mock('../useThresholdsRecoveryDefaultsState', () => ({+ useThresholdsRecoveryDefaultsState: () => ({+ backupDefaultsRecord: () => ({}),+ backupFactoryConfig: () => ({ enabled: false }),+ backupFactoryDefaultsRecord: () => ({}),+ backupOverridesCount: () => 0,+ sanitizeBackupConfig: <T,>(value: T): T => value,+ sanitizeSnapshotConfig: <T,>(value: T): T => value,+ snapshotDefaultsRecord: () => ({}),+ snapshotFactoryConfig: () => ({ enabled: false }),+ snapshotFactoryDefaultsRecord: () => ({}),+ snapshotOverridesCount: () => 0,+ }),+}));++const buildProps = (opts: { withDockerReset?: boolean } = {}): ThresholdsTableProps => {+ resetDockerIgnoredPrefixesSpy = vi.fn(() => {+ setDockerIgnoredStore([]);+ });++ return {+ agentDefaults: {},+ agents: [],+ allGuests: () => [],+ allResources: [],+ backupDefaults: () => backupPrev,+ containerRuntimes: [],+ disableAllAgents: () => false,+ disableAllAgentsOffline: () => false,+ disableAllDockerContainers: () => false,+ disableAllDockerHosts: () => false,+ disableAllDockerHostsOffline: () => false,+ disableAllDockerServices: () => false,+ disableAllGuests: () => false,+ disableAllNodes: () => false,+ disableAllPBS: () => false,+ disableAllPMG: () => false,+ disableAllPMGOffline: () => false,+ disableAllStorage: () => false,+ dockerDefaults: {+ cpu: 80,+ disk: 90,+ memory: 85,+ memoryCriticalPct: 95,+ memoryWarnPct: 80,+ restartCount: 3,+ restartWindow: 10,+ serviceCriticalGapPercent: 15,+ serviceWarnGapPercent: 5,+ updateAlertDelayHours: 24,+ },+ dockerDisableConnectivity: () => false,+ dockerHosts: [],+ dockerIgnoredPrefixes: () => dockerIgnoredStore(),+ dockerPoweredOffSeverity: () => 'warning',+ factoryAgentDefaults: {},+ factoryDockerDefaults: {},+ factoryGuestDefaults: {},+ factoryNodeDefaults: {},+ factoryPBSDefaults: {},+ factoryStorageDefault: 85,+ guestDefaults: {},+ guestDisableConnectivity: () => false,+ guestPoweredOffSeverity: () => 'warning',+ guestTagBlacklist: () => [],+ guestTagWhitelist: () => [],+ ignoredGuestPrefixes: () => [],+ metricTimeThresholds: () => metricTimeState,+ nodeDefaults: {},+ nodes: [],+ overrides: () => [],+ pmgInstances: [],+ pmgThresholds: () => pmgThresholdsState,+ pbsDefaults: {},+ pbsInstances: [],+ rawOverridesConfig: () => ({}),+ setAgentDefaults: vi.fn(),+ setDisableAllAgents: vi.fn(),+ setDisableAllAgentsOffline: vi.fn(),+ setDisableAllDockerContainers: vi.fn(),+ setDisableAllDockerHosts: vi.fn(),+ setDisableAllDockerHostsOffline: vi.fn(),+ setDisableAllDockerServices: vi.fn(),+ setDisableAllGuests: vi.fn(),+ setDisableAllNodes: vi.fn(),+ setDisableAllPBS: vi.fn(),+ setDisableAllPMG: vi.fn(),+ setDisableAllPMGOffline: vi.fn(),+ setDisableAllStorage: vi.fn(),+ setBackupDefaults: (setBackupDefaultsSpy = vi.fn(+ (updater: BackupAlertConfig | ((prev: BackupAlertConfig) => BackupAlertConfig)) =>+ typeof updater === 'function' ? updater(backupPrev) : updater,+ )),+ setDockerDefaults: vi.fn(),+ setDockerDisableConnectivity: vi.fn(),+ setDockerIgnoredPrefixes: (setDockerIgnoredPrefixesSpy = vi.fn(+ (value: string[] | ((prev: string[]) => string[])) => {+ setDockerIgnoredStore(typeof value === 'function' ? value(dockerIgnoredStore()) : value);+ },+ )),+ setDockerPoweredOffSeverity: vi.fn(),+ setGuestDefaults: vi.fn(),+ setGuestDisableConnectivity: vi.fn(),+ setGuestPoweredOffSeverity: vi.fn(),+ setGuestTagBlacklist: vi.fn(),+ setGuestTagWhitelist: vi.fn(),+ setHasUnsavedChanges: (setHasUnsavedChangesSpy = vi.fn()),+ setIgnoredGuestPrefixes: vi.fn(),+ setMetricTimeThresholds: (setMetricTimeThresholdsSpy = vi.fn(+ (+ updater:+ | Record<string, Record<string, number>>+ | ((+ prev: Record<string, Record<string, number>>,+ ) => Record<string, Record<string, number>>),+ ) => {+ metricTimeState = typeof updater === 'function' ? updater(metricTimeState) : updater;+ },+ )),+ setNodeDefaults: vi.fn(),+ setOverrides: vi.fn(),+ setPMGThresholds: (setPMGThresholdsSpy = vi.fn(+ (updater: PMGThresholdDefaults | ((prev: PMGThresholdDefaults) => PMGThresholdDefaults)) => {+ pmgThresholdsState =+ typeof updater === 'function'+ ? (updater as (prev: PMGThresholdDefaults) => PMGThresholdDefaults)(pmgThresholdsState)+ : updater;+ },+ )),+ setRawOverridesConfig: vi.fn(),+ setSnapshotDefaults: (setSnapshotDefaultsSpy = vi.fn(+ (updater: SnapshotAlertConfig | ((prev: SnapshotAlertConfig) => SnapshotAlertConfig)) =>+ typeof updater === 'function' ? updater(snapshotPrev) : updater,+ )),+ setStorageDefault: vi.fn(),+ snapshotDefaults: () => snapshotPrev,+ storage: [],+ storageDefault: () => 85,+ timeThresholds: () => ({ agent: 0, guest: 0, node: 0, pbs: 0, storage: 0 }),+ ...(opts.withDockerReset ? { resetDockerIgnoredPrefixes: resetDockerIgnoredPrefixesSpy } : {}),+ } as unknown as ThresholdsTableProps;+};++const mount = (props: ThresholdsTableProps) => {+ let captured: ReturnType<typeof useThresholdsTableState> | undefined;+ const Harness = () => {+ captured = useThresholdsTableState(props);+ return null;+ };+ render(() => <Harness />);+ if (!captured) throw new Error('state was not captured');+ return captured;+};++beforeEach(() => {+ mockPathname = '/alerts/thresholds/proxmox';+ mockHash = '';+ mockAlertsEnabled = true;+ mockNodes = [];+ setDockerIgnoredStore([]);+ metricTimeState = {};+ pmgThresholdsState = {};+ snapshotPrev = { enabled: false, warningDays: 3, criticalDays: 7 };+ backupPrev = { enabled: false, warningDays: 7, criticalDays: 14, freshHours: 24 };+ localStorage.clear();+});++afterEach(() => {+ cleanup();+});++describe('useThresholdsTableState — branch coverage', () => {+ describe('handleDockerIgnoredChange', () => {+ it('writes the raw input, pushes the normalized prefixes, and flags unsaved changes', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.handleDockerIgnoredChange(' alpha \n\n beta \n');++ // The input signal is reconciled by the sync effect against the store the+ // handler just wrote; both sides ran real normalization to ['alpha','beta'].+ expect(captured.dockerIgnoredInput()).toBe('alpha\nbeta');+ expect(setDockerIgnoredPrefixesSpy).toHaveBeenCalledWith(['alpha', 'beta']);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });+ });++ describe('handleResetDockerIgnored', () => {+ it('uses the dedicated reset callback when one is provided (truthy arm)', () => {+ setDockerIgnoredStore(['stale-a', 'stale-b']);+ const props = buildProps({ withDockerReset: true });+ const captured = mount(props);++ captured.handleResetDockerIgnored();++ expect(resetDockerIgnoredPrefixesSpy).toHaveBeenCalledTimes(1);+ // The dedicated reset owns the store; setDockerIgnoredPrefixes must NOT also run.+ expect(setDockerIgnoredPrefixesSpy).not.toHaveBeenCalled();+ expect(captured.dockerIgnoredInput()).toBe('');+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('falls back to clearing via setDockerIgnoredPrefixes when no reset callback exists (falsy arm)', () => {+ const props = buildProps({ withDockerReset: false });+ const captured = mount(props);++ captured.handleResetDockerIgnored();++ expect(setDockerIgnoredPrefixesSpy).toHaveBeenCalledWith([]);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ expect(captured.dockerIgnoredInput()).toBe('');+ });+ });++ describe('hasActiveAlert', () => {+ it('returns false up-front when alert detection is disabled', () => {+ mockAlertsEnabled = false;+ const props = buildProps();+ props.activeAlerts = { 'r-cpu': {} } as unknown as ThresholdsTableProps['activeAlerts'];+ const captured = mount(props);++ // Detection gate short-circuits before the lookup even happens.+ expect(captured.hasActiveAlert('r', 'cpu')).toBe(false);+ });++ it('returns false when no activeAlerts map is supplied', () => {+ const props = buildProps();+ // activeAlerts intentionally left undefined.+ const captured = mount(props);++ expect(captured.hasActiveAlert('r', 'cpu')).toBe(false);+ });++ it('distinguishes present vs absent "<id>-<metric>" keys when enabled', () => {+ const props = buildProps();+ props.activeAlerts = {+ 'node-1-cpu': { id: 'x' },+ } as unknown as ThresholdsTableProps['activeAlerts'];+ const captured = mount(props);++ expect(captured.hasActiveAlert('node-1', 'cpu')).toBe(true);+ expect(captured.hasActiveAlert('node-1', 'memory')).toBe(false);+ expect(captured.hasActiveAlert('node-9', 'cpu')).toBe(false);+ });+ });++ describe('resourceMatchesOverrideFilter (via nodesWithOverrides memo + setOverrideFilter)', () => {+ it("'custom' filter keeps only resources carrying an override, connectivity-off, or severity flag", () => {+ mockNodes = [+ { id: 'a', name: 'a', hasOverride: true },+ { id: 'b', name: 'b', disableConnectivity: true },+ { id: 'c', name: 'c', poweredOffSeverity: 'critical' },+ { id: 'd', name: 'd' },+ ] as unknown as TableResource[];+ const props = buildProps();+ const captured = mount(props);++ captured.setOverrideFilter('custom');+ const visible = captured.nodesWithOverrides().map((r) => r.id);++ expect(visible).toEqual(['a', 'b', 'c']);+ });++ it("'disabled' filter keeps only disabled or connectivity-off resources", () => {+ mockNodes = [+ { id: 'a', name: 'a', disabled: true },+ { id: 'b', name: 'b', disableConnectivity: true },+ { id: 'c', name: 'c', hasOverride: true },+ { id: 'd', name: 'd' },+ ] as unknown as TableResource[];+ const props = buildProps();+ const captured = mount(props);++ captured.setOverrideFilter('disabled');+ const visible = captured.nodesWithOverrides().map((r) => r.id);++ // hasOverride alone is NOT enough for the 'disabled' filter.+ expect(visible).toEqual(['a', 'b']);+ });++ it("'all' filter (the default arm) keeps every resource regardless of flags", () => {+ mockNodes = [+ { id: 'a', name: 'a' },+ { id: 'b', name: 'b', disabled: true },+ ] as unknown as TableResource[];+ const props = buildProps();+ const captured = mount(props);++ captured.setOverrideFilter('all');+ expect(captured.nodesWithOverrides()).toHaveLength(2);+ });+ });++ describe('registerSection', () => {+ it('wires a newly registered section element so the #hash scroll effect scrolls it', () => {+ mockHash = '#pbs';+ const props = buildProps();+ const captured = mount(props);++ const element = { scrollIntoView: vi.fn() } as unknown as HTMLDivElement;+ // First registration: prev['pbs'] is undefined !== element -> new-entry arm.+ captured.registerSection('pbs')(element);++ expect(element.scrollIntoView).toHaveBeenCalledWith({ block: 'start' });+ });++ it('re-registering the same element is a no-op (same-reference arm)', () => {+ mockHash = '#pbs';+ const props = buildProps();+ const captured = mount(props);++ const element = { scrollIntoView: vi.fn() } as unknown as HTMLDivElement;+ captured.registerSection('pbs')(element);+ expect(element.scrollIntoView).toHaveBeenCalledTimes(1);++ // Same element -> registerSection returns prev unchanged (no spurious reactive update).+ captured.registerSection('pbs')(element);+ expect(element.scrollIntoView).toHaveBeenCalledTimes(1);+ });+ });++ describe('updateSnapshotDefaults', () => {+ it('applies a function updater against the previous snapshot config (function arm)', () => {+ const props = buildProps();+ const captured = mount(props);++ // The updater reads prev.criticalDays, proving it actually receives prev.+ captured.updateSnapshotDefaults((prev) => ({+ ...prev,+ warningDays: prev.criticalDays + 10,+ }));++ const result = setSnapshotDefaultsSpy.mock.results.at(-1)?.value as SnapshotAlertConfig;+ expect(result.warningDays).toBe(17); // 7 + 10+ expect(result.criticalDays).toBe(7); // preserved from prev+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('merges a partial object onto the previous config (object arm)', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.updateSnapshotDefaults({+ enabled: true,+ warningDays: 5,+ criticalDays: 9,+ });++ const result = setSnapshotDefaultsSpy.mock.results.at(-1)?.value as SnapshotAlertConfig;+ expect(result.warningDays).toBe(5);+ expect(result.criticalDays).toBe(9);+ expect(result.enabled).toBe(true);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });+ });++ describe('updateBackupDefaults', () => {+ it('applies a function updater against the previous backup config (function arm)', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.updateBackupDefaults((prev) => ({ ...prev, warningDays: prev.criticalDays * 2 }));++ const result = setBackupDefaultsSpy.mock.results.at(-1)?.value as BackupAlertConfig;+ expect(result.warningDays).toBe(28); // 14 * 2+ expect(result.criticalDays).toBe(14);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('merges a partial object onto the previous config (object arm)', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.updateBackupDefaults({ enabled: true, warningDays: 2, criticalDays: 4 });++ const result = setBackupDefaultsSpy.mock.results.at(-1)?.value as BackupAlertConfig;+ expect(result.warningDays).toBe(2);+ expect(result.criticalDays).toBe(4);+ expect(result.enabled).toBe(true);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });+ });++ describe('setPMGGlobalDefaults', () => {+ it('sanitizes a normalized value into the matching PMG column and flags unsaved changes (object arm + change)', () => {+ const props = buildProps();+ const captured = mount(props);++ // 'queue warn' is the normalized label for the queueTotalWarning column.+ captured.setPMGGlobalDefaults({ 'queue warn': 50 });++ expect(pmgThresholdsState.queueTotalWarning).toBe(50);+ expect(setPMGThresholdsSpy).toHaveBeenCalledTimes(1);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('accepts a function updater over the current normalized record (function arm)', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.setPMGGlobalDefaults((current) => ({ ...current, 'queue crit': 77 }));++ // 'queue crit' -> queueTotalCritical column; value is rounded.+ expect(pmgThresholdsState.queueTotalCritical).toBe(77);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('skips non-numeric / NaN entries without touching the column or flagging changes', () => {+ const props = buildProps();+ const captured = mount(props);++ // A string fails `typeof raw === 'number'`.+ captured.setPMGGlobalDefaults({ 'queue warn': 'nope' as unknown as number });+ // NaN passes typeof but fails `!Number.isNaN(raw)`.+ captured.setPMGGlobalDefaults({ 'queue crit': Number.NaN });++ expect(pmgThresholdsState.queueTotalWarning).toBeUndefined();+ expect(pmgThresholdsState.queueTotalCritical).toBeUndefined();+ expect(setHasUnsavedChangesSpy).not.toHaveBeenCalled();+ });++ it('does not flag unsaved changes when the sanitized value already matches the stored column', () => {+ // Seed the store so the incoming value matches -> "no change" arm.+ pmgThresholdsState = { queueTotalWarning: 50 };+ const props = buildProps();+ const captured = mount(props);++ captured.setPMGGlobalDefaults({ 'queue warn': 50 });++ expect(setHasUnsavedChangesSpy).not.toHaveBeenCalled();+ });++ it('clamps negative values to 0 and rounds decimals', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.setPMGGlobalDefaults({ 'queue warn': -7.4 });++ expect(pmgThresholdsState.queueTotalWarning).toBe(0);+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });+ });++ describe('hasSection', () => {+ it('reports a section present when its summary item survives the totals/tab filters', () => {+ const props = buildProps();+ props.nodes = [{ id: 'node-1' }] as unknown as ThresholdsTableProps['nodes'];+ const captured = mount(props);++ // 'nodes' item has total = props.nodes.length (1) and tab 'proxmox' (the active tab).+ expect(captured.hasSection('nodes')).toBe(true);+ });++ it('reports a section absent when there is no data to populate it', () => {+ const props = buildProps();+ const captured = mount(props);++ // No pbsInstances / no overrides -> pbs item filtered out of summaryItems.+ expect(captured.hasSection('pbs')).toBe(false);+ });+ });++ describe('startEditing / cancelEdit', () => {+ it('startEditing merges defaults with current thresholds and records the note when given', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.startEditing('res-1', { cpu: 90 }, { cpu: 80, memory: 70 }, 'a note');++ expect(captured.editingId()).toBe('res-1');+ // defaults spread first, currentThresholds win for shared keys; memory is retained from defaults.+ expect(captured.editingThresholds()).toEqual({ cpu: 90, memory: 70 });+ expect(captured.editingNote()).toBe('a note');+ });++ it('startEditing defaults the note to empty string when none is provided', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.startEditing('res-2', { cpu: 10 }, { cpu: 5 });++ expect(captured.editingNote()).toBe('');+ });++ it('cancelEdit clears the editing id, thresholds, and note', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.startEditing('res-3', { cpu: 90 }, { cpu: 80 }, 'temp');+ captured.cancelEdit();++ expect(captured.editingId()).toBeNull();+ expect(captured.editingThresholds()).toEqual({});+ expect(captured.editingNote()).toBe('');+ });+ });++ describe('handleBulkEdit / handleSaveBulkEdit', () => {+ it('handleBulkEdit stages ids/columns and opens the dialog', () => {+ const props = buildProps();+ const captured = mount(props);++ expect(captured.isBulkEditDialogOpen()).toBe(false);+ captured.handleBulkEdit(['id-a', 'id-b'], ['cpu', 'memory']);++ expect(captured.bulkEditIds()).toEqual(['id-a', 'id-b']);+ expect(captured.bulkEditColumns()).toEqual(['cpu', 'memory']);+ expect(captured.isBulkEditDialogOpen()).toBe(true);+ });++ it('handleSaveBulkEdit closes the dialog, clears the staged ids/columns, and persists', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.handleBulkEdit(['id-a'], ['cpu']);+ captured.handleSaveBulkEdit({ cpu: 88 });++ expect(captured.isBulkEditDialogOpen()).toBe(false);+ expect(captured.bulkEditIds()).toEqual([]);+ expect(captured.bulkEditColumns()).toEqual([]);+ // persistBulkEdit (real) always flags unsaved changes at the end of its run.+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });+ });++ describe('updateMetricDelay', () => {+ it('ignores a blank metric key without touching the store (early-return arm)', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.updateMetricDelay('node', ' ', 5);++ expect(setMetricTimeThresholdsSpy).not.toHaveBeenCalled();+ expect(setHasUnsavedChangesSpy).not.toHaveBeenCalled();+ });++ it('creates a fresh per-type override, rounding decimals (set + change + assign arms)', () => {+ const props = buildProps();+ const captured = mount(props);++ captured.updateMetricDelay('node', ' CPU ', 5.7);++ // metric is trimmed + lowercased; value is rounded (6) and stored under the type.+ expect(metricTimeState).toEqual({ node: { cpu: 6 } });+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('clamps negative values to 0 when they differ from the stored value', () => {+ metricTimeState = { node: { cpu: 5 } };+ const props = buildProps();+ const captured = mount(props);++ captured.updateMetricDelay('node', 'cpu', -3);++ expect(metricTimeState).toEqual({ node: { cpu: 0 } });+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('treats an identical value as a no-op (same-value return-prev arm)', () => {+ metricTimeState = { node: { cpu: 5 } };+ const props = buildProps();+ const captured = mount(props);++ captured.updateMetricDelay('node', 'cpu', 5);++ expect(metricTimeState).toEqual({ node: { cpu: 5 } });+ expect(setHasUnsavedChangesSpy).not.toHaveBeenCalled();+ });++ it('deletes the metric and drops the empty type key when the last override is removed', () => {+ metricTimeState = { node: { cpu: 5 } };+ const props = buildProps();+ const captured = mount(props);++ captured.updateMetricDelay('node', 'cpu', null);++ expect(metricTimeState).toEqual({});+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('deletes the metric but keeps the type key when sibling overrides remain', () => {+ metricTimeState = { node: { cpu: 5, memory: 8 } };+ const props = buildProps();+ const captured = mount(props);++ captured.updateMetricDelay('node', 'cpu', null);++ expect(metricTimeState).toEqual({ node: { memory: 8 } });+ expect(setHasUnsavedChangesSpy).toHaveBeenCalledWith(true);+ });++ it('treats deletion of a metric that was never set as a no-op', () => {+ metricTimeState = { node: { memory: 8 } };+ const props = buildProps();+ const captured = mount(props);++ captured.updateMetricDelay('node', 'cpu', null);++ expect(metricTimeState).toEqual({ node: { memory: 8 } });+ expect(setHasUnsavedChangesSpy).not.toHaveBeenCalled();+ });+ });+});diff --git a/frontend-modern/src/stores/__tests__/aiIntelligence.branchcov0725am.test.ts b/frontend-modern/src/stores/__tests__/aiIntelligence.branchcov0725am.test.tsnew file mode 100644index 0000000000..62ef0bc4b6--- /dev/null+++ b/frontend-modern/src/stores/__tests__/aiIntelligence.branchcov0725am.test.ts@@ -0,0 +1,892 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/api/ai', () => ({+ AIAPI: {+ getUnifiedFindings: vi.fn(),+ getRemediationPlans: vi.fn(),+ approveRemediationPlan: vi.fn(),+ executeRemediationPlan: vi.fn(),+ rollbackRemediationPlan: vi.fn(),+ getPendingApprovals: vi.fn(),+ approvePendingApproval: vi.fn(),+ denyPendingApproval: vi.fn(),+ getIntelligenceSummary: vi.fn(),+ getCorrelations: vi.fn(),+ },+}));++vi.mock('@/api/patrol', () => ({+ getPatrolFindings: vi.fn(),+ acknowledgeFinding: vi.fn(),+ snoozeFinding: vi.fn(),+ dismissFinding: vi.fn(),+ resolveFinding: vi.fn(),+ setFindingNote: vi.fn(),+}));++vi.mock('@/utils/logger', () => ({+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+}));++vi.mock('@/stores/sessionPresentationPolicy', () => ({+ presentationPolicyIsDemoMode: vi.fn(() => false),+}));++import { AIAPI } from '@/api/ai';+import {+ acknowledgeFinding as patrolAcknowledgeFinding,+ snoozeFinding as patrolSnoozeFinding,+ dismissFinding as patrolDismissFinding,+ setFindingNote as patrolSetFindingNote,+ getPatrolFindings,+} from '@/api/patrol';+import { aiIntelligenceStore } from '@/stores/aiIntelligence';+import { presentationPolicyIsDemoMode } from '@/stores/sessionPresentationPolicy';++function approvalExpiryInMinutes(minutesFromNow: number): string {+ return new Date(Date.now() + minutesFromNow * 60_000).toISOString();+}++function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((res) => {+ resolve = res;+ });+ return { promise, resolve };+}++describe('aiIntelligenceStore branch coverage (0725am)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useRealTimers();+ vi.mocked(presentationPolicyIsDemoMode).mockReturnValue(false);+ vi.mocked(getPatrolFindings).mockResolvedValue([]);+ });++ // ---------------------------------------------------------------+ // Loading / error getters (TRUE and FALSE states)+ // ---------------------------------------------------------------++ it('exposes findingsLoading true while loadFindings is in flight and false once settled', async () => {+ const { promise, resolve } = deferred<{ findings: unknown[] }>();+ vi.mocked(AIAPI.getUnifiedFindings).mockReturnValueOnce(promise as never);++ const pending = aiIntelligenceStore.loadFindings();+ expect(aiIntelligenceStore.findingsLoading).toBe(true);+ expect(aiIntelligenceStore.findingsError).toBeNull();++ resolve({ findings: [] });+ await pending;++ expect(aiIntelligenceStore.findingsLoading).toBe(false);+ });++ it('surfaces an Error.message through findingsError when loadFindings fails', async () => {+ vi.mocked(AIAPI.getUnifiedFindings).mockRejectedValueOnce(new Error('upstream 503'));++ await aiIntelligenceStore.loadFindings();++ expect(aiIntelligenceStore.findingsError).toBe('upstream 503');+ expect(aiIntelligenceStore.findingsLoading).toBe(false);+ });++ it('falls back to the canonical literal through findingsError for a non-Error rejection', async () => {+ vi.mocked(AIAPI.getUnifiedFindings).mockRejectedValueOnce('network down');++ await aiIntelligenceStore.loadFindings();++ expect(aiIntelligenceStore.findingsError).toBe('Failed to load findings');+ });++ it('returns early without populating findings when the unified findings response is null', async () => {+ // Covers the `if (!resp) return;` arm: no findings written, no error,+ // loading settled false.+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce(null as never);++ await aiIntelligenceStore.loadFindings();++ expect(aiIntelligenceStore.findings).toEqual([]);+ expect(aiIntelligenceStore.findingsError).toBeNull();+ expect(aiIntelligenceStore.findingsLoading).toBe(false);+ });++ it('exposes patrolFindingsLoading true while loadPatrolFindings is in flight and false once settled', async () => {+ const { promise, resolve } = deferred<unknown[]>();+ vi.mocked(getPatrolFindings).mockReturnValueOnce(promise as never);++ const pending = aiIntelligenceStore.loadPatrolFindings();+ expect(aiIntelligenceStore.patrolFindingsLoading).toBe(true);+ expect(aiIntelligenceStore.patrolFindingsError).toBeNull();++ resolve([]);+ await pending;++ expect(aiIntelligenceStore.patrolFindingsLoading).toBe(false);+ });++ it('surfaces an Error.message through patrolFindingsError when loadPatrolFindings fails', async () => {+ vi.mocked(getPatrolFindings).mockRejectedValueOnce(new Error('patrol 500'));++ await aiIntelligenceStore.loadPatrolFindings();++ expect(aiIntelligenceStore.patrolFindingsError).toBe('patrol 500');+ expect(aiIntelligenceStore.patrolFindingsLoading).toBe(false);+ });++ it('falls back to the canonical literal through patrolFindingsError for a non-Error rejection', async () => {+ vi.mocked(getPatrolFindings).mockRejectedValueOnce(42);++ await aiIntelligenceStore.loadPatrolFindings();++ expect(aiIntelligenceStore.patrolFindingsError).toBe('Failed to load Patrol findings');+ });++ it('exposes plansLoading true while loadRemediationPlans is in flight and false once settled', async () => {+ const { promise, resolve } = deferred<{ plans: unknown[] }>();+ vi.mocked(AIAPI.getRemediationPlans).mockReturnValueOnce(promise as never);++ const pending = aiIntelligenceStore.loadRemediationPlans();+ expect(aiIntelligenceStore.plansLoading).toBe(true);++ resolve({ plans: [] });+ await pending;++ expect(aiIntelligenceStore.plansLoading).toBe(false);+ });++ it('surfaces an Error.message through plansError when loadRemediationPlans fails', async () => {+ vi.mocked(AIAPI.getRemediationPlans).mockRejectedValueOnce(new Error('plans 502'));++ await aiIntelligenceStore.loadRemediationPlans();++ expect(aiIntelligenceStore.plansError).toBe('plans 502');+ expect(aiIntelligenceStore.plansLoading).toBe(false);+ });++ it('falls back to the canonical literal through plansError for a non-Error rejection', async () => {+ vi.mocked(AIAPI.getRemediationPlans).mockRejectedValueOnce('timeout');++ await aiIntelligenceStore.loadRemediationPlans();++ expect(aiIntelligenceStore.plansError).toBe('Failed to load remediation plans');+ });++ // ---------------------------------------------------------------+ // Remediation plan actions: approvePlan / executePlan / rollbackPlan+ // ---------------------------------------------------------------++ it('approvePlan returns true on success and rehydrates the plan list into the store', async () => {+ vi.mocked(AIAPI.approveRemediationPlan).mockResolvedValueOnce({ success: true });+ vi.mocked(AIAPI.getRemediationPlans).mockResolvedValueOnce({+ plans: [+ {+ id: 'plan-1',+ finding_id: 'finding-1',+ resource_id: 'vm-1',+ title: 'Restart service',+ description: 'Restart the agent',+ steps: [],+ risk_level: 'low',+ status: 'approved',+ created_at: '2026-07-01T00:00:00Z',+ },+ ],+ } as never);++ const ok = await aiIntelligenceStore.approvePlan('plan-1');++ expect(ok).toBe(true);+ expect(AIAPI.approveRemediationPlan).toHaveBeenCalledWith('plan-1');+ expect(aiIntelligenceStore.remediationPlans).toHaveLength(1);+ expect(aiIntelligenceStore.remediationPlans[0]).toMatchObject({+ id: 'plan-1',+ status: 'approved',+ });+ });++ it('approvePlan returns false and skips the plan reload when approval fails', async () => {+ vi.mocked(AIAPI.approveRemediationPlan).mockRejectedValueOnce(new Error('not allowed'));++ const ok = await aiIntelligenceStore.approvePlan('plan-x');++ expect(ok).toBe(false);+ expect(AIAPI.getRemediationPlans).not.toHaveBeenCalled();+ });++ it('executePlan returns the execution result and rehydrates the plan list on success', async () => {+ vi.mocked(AIAPI.executeRemediationPlan).mockResolvedValueOnce({+ execution_id: 'exec-1',+ plan_id: 'plan-1',+ status: 'success',+ steps_completed: 2,+ });+ vi.mocked(AIAPI.getRemediationPlans).mockResolvedValueOnce({+ plans: [+ {+ id: 'plan-1',+ finding_id: 'finding-1',+ resource_id: 'vm-1',+ title: 'Restart service',+ description: 'Restart the agent',+ steps: [],+ risk_level: 'low',+ status: 'completed',+ created_at: '2026-07-01T00:00:00Z',+ },+ ],+ } as never);++ const result = await aiIntelligenceStore.executePlan('exec-1');++ expect(result).toMatchObject({ execution_id: 'exec-1', status: 'success' });+ expect(AIAPI.executeRemediationPlan).toHaveBeenCalledWith('exec-1');+ expect(aiIntelligenceStore.remediationPlans[0]).toMatchObject({+ id: 'plan-1',+ status: 'completed',+ });+ });++ it('executePlan rethrows and does not reload plans when execution fails', async () => {+ vi.mocked(AIAPI.executeRemediationPlan).mockRejectedValueOnce(new Error('exec blew up'));++ await expect(aiIntelligenceStore.executePlan('exec-bad')).rejects.toThrow('exec blew up');+ expect(AIAPI.getRemediationPlans).not.toHaveBeenCalled();+ });++ it('rollbackPlan returns true and rehydrates the plan list on success', async () => {+ vi.mocked(AIAPI.rollbackRemediationPlan).mockResolvedValueOnce({ success: true });+ vi.mocked(AIAPI.getRemediationPlans).mockResolvedValueOnce({+ plans: [+ {+ id: 'plan-1',+ finding_id: 'finding-1',+ resource_id: 'vm-1',+ title: 'Restart service',+ description: 'Restart the agent',+ steps: [],+ risk_level: 'low',+ status: 'rolled_back',+ created_at: '2026-07-01T00:00:00Z',+ },+ ],+ } as never);++ const ok = await aiIntelligenceStore.rollbackPlan('exec-1');++ expect(ok).toBe(true);+ expect(AIAPI.rollbackRemediationPlan).toHaveBeenCalledWith('exec-1');+ expect(aiIntelligenceStore.remediationPlans[0]).toMatchObject({+ id: 'plan-1',+ status: 'rolled_back',+ });+ });++ it('rollbackPlan returns false and skips the plan reload when rollback fails', async () => {+ vi.mocked(AIAPI.rollbackRemediationPlan).mockRejectedValueOnce(new Error('no rollback'));++ const ok = await aiIntelligenceStore.rollbackPlan('exec-bad');++ expect(ok).toBe(false);+ expect(AIAPI.getRemediationPlans).not.toHaveBeenCalled();+ });++ // ---------------------------------------------------------------+ // Finding lifecycle actions+ // ---------------------------------------------------------------++ it('acknowledgeFinding returns true and refreshes the patrol finding status into the store', async () => {+ vi.mocked(patrolAcknowledgeFinding).mockResolvedValueOnce({ success: true, message: 'ok' });+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([+ {+ id: 'finding-ack',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:1',+ resource_name: 'node-1',+ resource_type: 'host',+ title: 'Disk pressure',+ description: 'Patrol flagged disk pressure.',+ detected_at: '2026-07-01T00:00:00Z',+ last_seen_at: '2026-07-01T00:05:00Z',+ resolved_at: '2026-07-01T00:10:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 0,+ },+ ]);++ const ok = await aiIntelligenceStore.acknowledgeFinding('finding-ack');++ expect(ok).toBe(true);+ expect(patrolAcknowledgeFinding).toHaveBeenCalledWith('finding-ack');+ expect(aiIntelligenceStore.patrolFindings).toHaveLength(1);+ expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({+ id: 'finding-ack',+ status: 'resolved',+ });+ });++ it('acknowledgeFinding returns false and performs no reload when the patrol call fails', async () => {+ vi.mocked(patrolAcknowledgeFinding).mockRejectedValueOnce(new Error('conflict'));++ const ok = await aiIntelligenceStore.acknowledgeFinding('finding-ack');++ expect(ok).toBe(false);+ expect(AIAPI.getUnifiedFindings).not.toHaveBeenCalled();+ expect(getPatrolFindings).not.toHaveBeenCalled();+ });++ it('snoozeFinding returns true and refreshes both finding sources on success', async () => {+ vi.mocked(patrolSnoozeFinding).mockResolvedValueOnce({ success: true, message: 'snoozed' });+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({+ findings: [+ {+ id: 'finding-snooze',+ source: 'ai-patrol',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:2',+ resource_name: 'node-2',+ resource_type: 'host',+ title: 'Disk pressure',+ description: 'Snoozed by operator.',+ detected_at: '2026-07-01T00:00:00Z',+ snoozed_until: '2026-07-02T00:00:00Z',+ status: 'snoozed',+ },+ ],+ } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);++ const ok = await aiIntelligenceStore.snoozeFinding('finding-snooze', 24);++ expect(ok).toBe(true);+ expect(patrolSnoozeFinding).toHaveBeenCalledWith('finding-snooze', 24);+ expect(aiIntelligenceStore.findings).toHaveLength(1);+ expect(aiIntelligenceStore.findings[0]).toMatchObject({+ id: 'finding-snooze',+ status: 'snoozed',+ });+ });++ it('snoozeFinding returns false and performs no reload when the patrol call fails', async () => {+ vi.mocked(patrolSnoozeFinding).mockRejectedValueOnce(new Error('nope'));++ const ok = await aiIntelligenceStore.snoozeFinding('finding-snooze', 24);++ expect(ok).toBe(false);+ expect(AIAPI.getUnifiedFindings).not.toHaveBeenCalled();+ });++ it('dismissFinding returns true and refreshes both finding sources on success', async () => {+ vi.mocked(patrolDismissFinding).mockResolvedValueOnce({ success: true, message: 'dismissed' });+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([+ {+ id: 'finding-dismiss',+ severity: 'info',+ category: 'reliability',+ resource_id: 'instance:node:3',+ resource_name: 'node-3',+ resource_type: 'host',+ title: 'Noisy check',+ description: 'Operator dismissed as expected.',+ detected_at: '2026-07-01T00:00:00Z',+ last_seen_at: '2026-07-01T00:05:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 0,+ dismissed_reason: 'expected_behavior',+ },+ ]);++ const ok = await aiIntelligenceStore.dismissFinding(+ 'finding-dismiss',+ 'expected_behavior',+ 'routine',+ );++ expect(ok).toBe(true);+ expect(patrolDismissFinding).toHaveBeenCalledWith(+ 'finding-dismiss',+ 'expected_behavior',+ 'routine',+ );+ expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({+ id: 'finding-dismiss',+ status: 'dismissed',+ dismissedReason: 'expected_behavior',+ });+ });++ it('dismissFinding returns false and performs no reload when the patrol call fails', async () => {+ vi.mocked(patrolDismissFinding).mockRejectedValueOnce(new Error('deny'));++ const ok = await aiIntelligenceStore.dismissFinding('finding-dismiss', 'not_an_issue');++ expect(ok).toBe(false);+ expect(getPatrolFindings).not.toHaveBeenCalled();+ });++ it('setFindingNote optimistically updates the note on both unified and patrol findings on success', async () => {+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({+ findings: [+ {+ id: 'finding-note',+ source: 'ai-patrol',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:4',+ resource_name: 'node-4',+ resource_type: 'host',+ title: 'Disk pressure',+ description: 'Add a note.',+ detected_at: '2026-07-01T00:00:00Z',+ },+ ],+ } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([+ {+ id: 'finding-note',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:4',+ resource_name: 'node-4',+ resource_type: 'host',+ title: 'Disk pressure',+ description: 'Add a note.',+ detected_at: '2026-07-01T00:00:00Z',+ last_seen_at: '2026-07-01T00:05:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 0,+ },+ ]);+ vi.mocked(patrolSetFindingNote).mockResolvedValueOnce({ success: true, message: 'saved' });++ await aiIntelligenceStore.loadFindings();+ await aiIntelligenceStore.loadPatrolFindings();+ expect(aiIntelligenceStore.findings[0].userNote).toBeUndefined();++ const ok = await aiIntelligenceStore.setFindingNote('finding-note', 'operator context');++ expect(ok).toBe(true);+ expect(patrolSetFindingNote).toHaveBeenCalledWith('finding-note', 'operator context');+ // No reload performed — the optimistic update is the only state change.+ expect(AIAPI.getUnifiedFindings).toHaveBeenCalledTimes(1);+ expect(getPatrolFindings).toHaveBeenCalledTimes(1);+ expect(aiIntelligenceStore.findings[0].userNote).toBe('operator context');+ expect(aiIntelligenceStore.patrolFindings[0].userNote).toBe('operator context');+ });++ it('setFindingNote returns false and leaves the local note unchanged when the patrol call fails', async () => {+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({+ findings: [+ {+ id: 'finding-note',+ source: 'ai-patrol',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:4',+ resource_name: 'node-4',+ resource_type: 'host',+ title: 'Disk pressure',+ description: 'Add a note.',+ detected_at: '2026-07-01T00:00:00Z',+ },+ ],+ } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);+ vi.mocked(patrolSetFindingNote).mockRejectedValueOnce(new Error('write failed'));++ await aiIntelligenceStore.loadFindings();+ await aiIntelligenceStore.loadPatrolFindings();++ const ok = await aiIntelligenceStore.setFindingNote('finding-note', 'never persisted');++ expect(ok).toBe(false);+ expect(aiIntelligenceStore.findings[0].userNote).toBeUndefined();+ });++ // ---------------------------------------------------------------+ // Investigation-fix approval actions+ // ---------------------------------------------------------------++ it('approvePendingApproval returns the decision result and clears the live approval after reload', async () => {+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([+ {+ id: 'approval-1',+ toolId: 'investigation_fix',+ command: 'systemctl restart pulse-agent',+ targetType: 'host',+ targetId: 'finding-queued',+ targetName: 'node-1',+ context: 'Restart the agent',+ riskLevel: 'medium',+ status: 'pending',+ requestedAt: '2026-07-01T00:01:00Z',+ expiresAt: approvalExpiryInMinutes(6),+ },+ ]);+ await aiIntelligenceStore.loadPendingApprovals();+ expect(aiIntelligenceStore.pendingApprovalCount).toBe(1);++ vi.mocked(AIAPI.approvePendingApproval).mockResolvedValueOnce({+ approved: true,+ executed: true,+ success: true,+ message: 'executed',+ });+ // Reloads after the decision return an empty approval set and empty findings.+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);++ const result = await aiIntelligenceStore.approvePendingApproval('approval-1');++ expect(result).toMatchObject({ approved: true, success: true, message: 'executed' });+ expect(AIAPI.approvePendingApproval).toHaveBeenCalledWith('approval-1');+ expect(aiIntelligenceStore.pendingApprovalCount).toBe(0);+ });++ it('approvePendingApproval returns null when the API rejects and leaves the approval live', async () => {+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([+ {+ id: 'approval-1',+ toolId: 'investigation_fix',+ command: 'systemctl restart pulse-agent',+ targetType: 'host',+ targetId: 'finding-queued',+ targetName: 'node-1',+ context: 'Restart the agent',+ riskLevel: 'medium',+ status: 'pending',+ requestedAt: '2026-07-01T00:01:00Z',+ expiresAt: approvalExpiryInMinutes(6),+ },+ ]);+ await aiIntelligenceStore.loadPendingApprovals();++ vi.mocked(AIAPI.approvePendingApproval).mockRejectedValueOnce(new Error('server refused'));++ const result = await aiIntelligenceStore.approvePendingApproval('approval-1');++ expect(result).toBeNull();+ // No reload ran, so the live approval is still counted.+ expect(aiIntelligenceStore.pendingApprovalCount).toBe(1);+ });++ it('approveInvestigationFix delegates to approvePendingApproval and casts the result on success', async () => {+ vi.mocked(AIAPI.approvePendingApproval).mockResolvedValueOnce({+ approved: true,+ executed: true,+ success: true,+ output: 'restarted',+ exit_code: 0,+ finding_id: 'finding-queued',+ message: 'executed',+ });+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);++ const result = await aiIntelligenceStore.approveInvestigationFix('approval-1');++ expect(result).not.toBeNull();+ expect(result).toMatchObject({+ approved: true,+ executed: true,+ success: true,+ exit_code: 0,+ finding_id: 'finding-queued',+ });+ expect(AIAPI.approvePendingApproval).toHaveBeenCalledWith('approval-1');+ });++ it('approveInvestigationFix returns null when the underlying approval fails', async () => {+ vi.mocked(AIAPI.approvePendingApproval).mockRejectedValueOnce(new Error('nope'));++ const result = await aiIntelligenceStore.approveInvestigationFix('approval-bad');++ expect(result).toBeNull();+ });++ it('denyPendingApproval returns true and clears the live approval after reload', async () => {+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([+ {+ id: 'approval-1',+ toolId: 'investigation_fix',+ command: 'systemctl restart pulse-agent',+ targetType: 'host',+ targetId: 'finding-queued',+ targetName: 'node-1',+ context: 'Restart the agent',+ riskLevel: 'medium',+ status: 'pending',+ requestedAt: '2026-07-01T00:01:00Z',+ expiresAt: approvalExpiryInMinutes(6),+ },+ ]);+ await aiIntelligenceStore.loadPendingApprovals();+ expect(aiIntelligenceStore.pendingApprovalCount).toBe(1);++ vi.mocked(AIAPI.denyPendingApproval).mockResolvedValueOnce({+ id: 'approval-1',+ status: 'denied',+ } as never);+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);++ const ok = await aiIntelligenceStore.denyPendingApproval('approval-1', 'too risky');++ expect(ok).toBe(true);+ expect(AIAPI.denyPendingApproval).toHaveBeenCalledWith('approval-1', 'too risky');+ expect(aiIntelligenceStore.pendingApprovalCount).toBe(0);+ });++ it('denyPendingApproval returns false and leaves the approval live when the API rejects', async () => {+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([+ {+ id: 'approval-1',+ toolId: 'investigation_fix',+ command: 'systemctl restart pulse-agent',+ targetType: 'host',+ targetId: 'finding-queued',+ targetName: 'node-1',+ context: 'Restart the agent',+ riskLevel: 'medium',+ status: 'pending',+ requestedAt: '2026-07-01T00:01:00Z',+ expiresAt: approvalExpiryInMinutes(6),+ },+ ]);+ await aiIntelligenceStore.loadPendingApprovals();++ vi.mocked(AIAPI.denyPendingApproval).mockRejectedValueOnce(new Error('deny failed'));++ const ok = await aiIntelligenceStore.denyPendingApproval('approval-1');++ expect(ok).toBe(false);+ expect(aiIntelligenceStore.pendingApprovalCount).toBe(1);+ });++ it('denyInvestigationFix delegates to denyPendingApproval and reports success', async () => {+ vi.mocked(AIAPI.denyPendingApproval).mockResolvedValueOnce({+ id: 'approval-1',+ status: 'denied',+ } as never);+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);++ const ok = await aiIntelligenceStore.denyInvestigationFix('approval-1', 'wrong call');++ expect(ok).toBe(true);+ expect(AIAPI.denyPendingApproval).toHaveBeenCalledWith('approval-1', 'wrong call');+ });++ it('denyInvestigationFix delegates the failure path and reports false', async () => {+ vi.mocked(AIAPI.denyPendingApproval).mockRejectedValueOnce(new Error('nope'));++ const ok = await aiIntelligenceStore.denyInvestigationFix('approval-bad');++ expect(ok).toBe(false);+ });++ // ---------------------------------------------------------------+ // Patrol-scoped derived getters + counts+ // ---------------------------------------------------------------++ it('patrolFindingsWithPendingApprovals mirrors live investigation_fix approvals scoped to patrol findings', async () => {+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([+ {+ id: 'patrol-queued',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:9',+ resource_name: 'node-9',+ resource_type: 'host',+ title: 'Queued Patrol fix',+ description: 'Patrol needs approval.',+ detected_at: '2026-07-01T00:00:00Z',+ last_seen_at: '2026-07-01T00:05:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 0,+ investigation_outcome: 'fix_queued',+ },+ ]);+ await aiIntelligenceStore.loadPatrolFindings();++ // No live approval yet: nothing surfaces.+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);+ await aiIntelligenceStore.loadPendingApprovals();+ expect(aiIntelligenceStore.patrolFindingsWithPendingApprovals).toEqual([]);++ // A live investigation_fix approval targeting the patrol finding promotes it.+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([+ {+ id: 'approval-patrol',+ toolId: 'investigation_fix',+ command: 'systemctl restart pulse-agent',+ targetType: 'host',+ targetId: 'patrol-queued',+ targetName: 'node-9',+ context: 'Restart the agent',+ riskLevel: 'medium',+ status: 'pending',+ requestedAt: '2026-07-01T00:01:00Z',+ expiresAt: approvalExpiryInMinutes(6),+ },+ ]);+ await aiIntelligenceStore.loadPendingApprovals();++ expect(aiIntelligenceStore.patrolFindingsWithPendingApprovals.map((f) => f.id)).toEqual([+ 'patrol-queued',+ ]);+ });++ it('patrolFindingsNeedingAttention surfaces queued-without-approval patrol findings and clears once approved', async () => {+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([+ {+ id: 'patrol-queued',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:9',+ resource_name: 'node-9',+ resource_type: 'host',+ title: 'Queued Patrol fix',+ description: 'Patrol needs approval.',+ detected_at: '2026-07-01T00:00:00Z',+ last_seen_at: '2026-07-01T00:05:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 0,+ investigation_outcome: 'fix_queued',+ },+ ]);+ await aiIntelligenceStore.loadPatrolFindings();++ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);+ await aiIntelligenceStore.loadPendingApprovals();+ expect(aiIntelligenceStore.patrolFindingsNeedingAttention.map((f) => f.id)).toEqual([+ 'patrol-queued',+ ]);++ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([+ {+ id: 'approval-patrol',+ toolId: 'investigation_fix',+ command: 'systemctl restart pulse-agent',+ targetType: 'host',+ targetId: 'patrol-queued',+ targetName: 'node-9',+ context: 'Restart the agent',+ riskLevel: 'medium',+ status: 'pending',+ requestedAt: '2026-07-01T00:01:00Z',+ expiresAt: approvalExpiryInMinutes(6),+ },+ ]);+ await aiIntelligenceStore.loadPendingApprovals();+ expect(aiIntelligenceStore.patrolFindingsNeedingAttention).toEqual([]);+ });++ it('needsAttentionCount tracks the unified needing-attention list length', async () => {+ // FALSE arm: empty unified findings -> zero needing attention.+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);+ await aiIntelligenceStore.loadFindings();+ expect(aiIntelligenceStore.needsAttentionCount).toBe(0);++ // TRUE arm: two active findings with attention outcomes.+ vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({+ findings: [+ {+ id: 'unified-failed-1',+ source: 'ai-patrol',+ severity: 'warning',+ category: 'performance',+ resource_id: 'instance:node:10',+ resource_name: 'node-10',+ resource_type: 'host',+ title: 'Fix failed',+ description: 'Patrol fix failed.',+ detected_at: '2026-07-01T00:00:00Z',+ status: 'active',+ investigation_outcome: 'fix_failed',+ },+ {+ id: 'unified-failed-2',+ source: 'ai-patrol',+ severity: 'critical',+ category: 'performance',+ resource_id: 'instance:node:11',+ resource_name: 'node-11',+ resource_type: 'host',+ title: 'Verification failed',+ description: 'Patrol could not verify the fix.',+ detected_at: '2026-07-01T00:00:00Z',+ status: 'active',+ investigation_outcome: 'fix_verification_failed',+ },+ ],+ } as never);+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);++ await aiIntelligenceStore.loadFindings();+ await aiIntelligenceStore.loadPendingApprovals();++ expect(aiIntelligenceStore.needsAttentionCount).toBe(2);+ expect(aiIntelligenceStore.needsAttentionCount).toBe(+ aiIntelligenceStore.findingsNeedingAttention.length,+ );+ });++ it('patrolNeedsAttentionCount tracks the patrol needing-attention list length', async () => {+ // FALSE arm: reset patrol findings to empty.+ await aiIntelligenceStore.loadPatrolFindings();+ expect(aiIntelligenceStore.patrolNeedsAttentionCount).toBe(0);++ // TRUE arm: one active patrol finding with a failed fix outcome.+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([+ {+ id: 'patrol-attention',+ severity: 'warning',+ category: 'reliability',+ resource_id: 'instance:node:12',+ resource_name: 'node-12',+ resource_type: 'host',+ title: 'Fix failed',+ description: 'Patrol fix failed.',+ detected_at: '2026-07-01T00:00:00Z',+ last_seen_at: '2026-07-01T00:05:00Z',+ auto_resolved: false,+ times_raised: 1,+ suppressed: false,+ investigation_attempts: 1,+ investigation_outcome: 'fix_failed',+ },+ ]);+ vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);++ await aiIntelligenceStore.loadPatrolFindings();+ await aiIntelligenceStore.loadPendingApprovals();++ expect(aiIntelligenceStore.patrolNeedsAttentionCount).toBe(1);+ expect(aiIntelligenceStore.patrolNeedsAttentionCount).toBe(+ aiIntelligenceStore.patrolFindingsNeedingAttention.length,+ );+ });+});diff --git a/frontend-modern/src/utils/__tests__/apiClient.branchcov0725am.test.ts b/frontend-modern/src/utils/__tests__/apiClient.branchcov0725am.test.tsnew file mode 100644index 0000000000..15d7b0f49c--- /dev/null+++ b/frontend-modern/src/utils/__tests__/apiClient.branchcov0725am.test.ts@@ -0,0 +1,639 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ apiFetch,+ apiFetchJSON,+ apiErrorFromResponse,+ clearApiToken,+ clearAuth,+ getApiToken,+ getOrgID,+ hasAuth,+ setApiToken,+ setOrgID,+} from '@/utils/apiClient';++const mockFetch = vi.fn();++const headersOf = (call: unknown): Record<string, string> => {+ const [, options] = call as [string, RequestInit];+ return options.headers as Record<string, string>;+};++const clearCsrfCookie = () => {+ document.cookie = 'pulse_csrf=; Path=/; Max-Age=0';+};++const clearSessionCookies = () => {+ document.cookie = 'pulse_session=; Path=/; Max-Age=0';+ document.cookie = '__Host-pulse_session=; Path=/; Max-Age=0';+};++describe('apiClient hasAuth', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ clearSessionCookies();+ });++ afterEach(() => {+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ clearSessionCookies();+ });++ it('returns true when an API token is configured', () => {+ setApiToken('a-valid-token');+ expect(hasAuth()).toBe(true);+ });++ it('returns true when a pulse_session cookie is present and no token is set', () => {+ clearApiToken();+ document.cookie = 'pulse_session=abc; Path=/';+ expect(hasAuth()).toBe(true);+ });++ it('returns true when a __Host-pulse_session cookie is present', () => {+ clearApiToken();+ // jsdom's cookie jar drops __Host- prefixed cookies over http:, so feed the+ // cookie string directly to exercise the name-matching arm against real parsing.+ const spy = vi+ .spyOn(document, 'cookie', 'get')+ .mockReturnValue('pulse_csrf=x; __Host-pulse_session=abc');+ expect(hasAuth()).toBe(true);+ spy.mockRestore();+ });++ it('returns false when neither token nor a session cookie is configured', () => {+ clearApiToken();+ expect(hasAuth()).toBe(false);+ });+});++describe('apiClient CSRF / 403 retry arms', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ });++ afterEach(() => {+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ });++ it('retries a 403 using the X-CSRF-Token response header', async () => {+ document.cookie = 'pulse_csrf=initial-token; Path=/';+ mockFetch+ .mockResolvedValueOnce(+ new Response('forbidden', {+ status: 403,+ headers: { 'X-CSRF-Token': 'refreshed-via-header' },+ }),+ )+ .mockResolvedValueOnce(new Response('{}', { status: 200 }));++ const response = await apiFetch('/api/data', { method: 'POST', body: '{}' });++ expect(response.status).toBe(200);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(headersOf(mockFetch.mock.calls[1])['X-CSRF-Token']).toBe('refreshed-via-header');+ });++ it('reloads the CSRF token from a newly-set cookie when the 403 has no X-CSRF-Token header', async () => {+ document.cookie = 'pulse_csrf=initial-token; Path=/';+ let firstCall = true;+ mockFetch.mockImplementation(async () => {+ if (firstCall) {+ firstCall = false;+ // Simulate the backend issuing a fresh CSRF cookie on the 403.+ document.cookie = 'pulse_csrf=new-from-cookie; Path=/';+ return new Response('forbidden', { status: 403 });+ }+ return new Response('{}', { status: 200 });+ });++ const response = await apiFetch('/api/data', { method: 'POST', body: '{}' });++ expect(response.status).toBe(200);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(headersOf(mockFetch.mock.calls[1])['X-CSRF-Token']).toBe('new-from-cookie');+ });++ it('returns the original 403 response when no refreshed token can be obtained', async () => {+ // No CSRF cookie anywhere, and ensureCSRFToken() is a no-op in test mode.+ mockFetch.mockResolvedValueOnce(new Response('forbidden', { status: 403 }));++ const response = await apiFetch('/api/data', { method: 'POST', body: '{}' });++ expect(response.status).toBe(403);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it('omits the X-CSRF-Token header on state-changing requests when no token is available', async () => {+ mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));++ await apiFetch('/api/data', { method: 'POST', body: '{}' });++ expect(headersOf(mockFetch.mock.calls[0])['X-CSRF-Token']).toBeUndefined();+ });++ it('treats an un-decodable CSRF cookie as no token', async () => {+ document.cookie = 'pulse_csrf=%; Path=/';+ mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));++ await apiFetch('/api/data', { method: 'POST', body: '{}' });++ expect(headersOf(mockFetch.mock.calls[0])['X-CSRF-Token']).toBeUndefined();+ });+});++describe('apiClient 401 handling arms', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ window.localStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ clearSessionCookies();+ });++ afterEach(() => {+ clearAuth();+ setOrgID(null);+ window.localStorage.clear();+ clearCsrfCookie();+ clearSessionCookies();+ });++ it('clears auth and signals logout on a 401 from a non-exempt API endpoint', async () => {+ setApiToken('some-token');+ const hrefSetter = vi.fn();+ const originalDesc = Object.getOwnPropertyDescriptor(window, 'location');+ Object.defineProperty(window, 'location', {+ configurable: true,+ value: {+ set href(v: string) {+ hrefSetter(v);+ },+ get href() {+ return '/';+ },+ pathname: '/',+ protocol: 'http:',+ search: '',+ toString: () => 'http://localhost/',+ },+ });++ try {+ mockFetch.mockResolvedValueOnce(new Response('unauthorized', { status: 401 }));++ const response = await apiFetch('/api/dashboard');++ expect(response.status).toBe(401);+ expect(hrefSetter).toHaveBeenCalledWith('/');+ expect(window.localStorage.getItem('just_logged_out')).toBe('true');+ expect(getApiToken()).toBeNull();+ } finally {+ if (originalDesc) {+ Object.defineProperty(window, 'location', originalDesc);+ }+ }+ });++ it('does not redirect when a 401 comes from an exempt endpoint', async () => {+ mockFetch.mockResolvedValueOnce(new Response('unauthorized', { status: 401 }));++ const response = await apiFetch('/api/security/status');++ expect(response.status).toBe(401);+ expect(window.localStorage.getItem('just_logged_out')).toBeNull();+ });+});++describe('apiClient org-scoping header arms', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ });++ afterEach(() => {+ clearAuth();+ setOrgID(null);+ });++ it('does not add API-specific headers for non-/api/ URLs', async () => {+ mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));+ setOrgID('acme');++ await apiFetch('https://example.com/external');++ const headers = headersOf(mockFetch.mock.calls[0]);+ expect(headers['X-Pulse-Org-ID']).toBeUndefined();+ expect(headers['X-Requested-With']).toBeUndefined();+ expect(headers['Accept']).toBeUndefined();+ });++ it('preserves a caller-supplied org header even when skipOrgContext is true', async () => {+ mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));++ await apiFetch('/api/data', {+ skipOrgContext: true,+ headers: { 'X-Pulse-Org-ID': 'custom-org' },+ });++ expect(headersOf(mockFetch.mock.calls[0])['X-Pulse-Org-ID']).toBe('custom-org');+ });++ it('defaults Accept to application/json for API requests when not supplied', async () => {+ mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));++ await apiFetch('/api/data');++ expect(headersOf(mockFetch.mock.calls[0])['Accept']).toBe('application/json');+ });++ it('preserves a caller-supplied Accept header on API requests', async () => {+ mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));++ await apiFetch('/api/data', { headers: { Accept: 'text/event-stream' } });++ expect(headersOf(mockFetch.mock.calls[0])['Accept']).toBe('text/event-stream');+ });++ it('does not retry a 400 that is not an invalid_org error', async () => {+ mockFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'validation_failed' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ }),+ );+ setOrgID('acme');++ const response = await apiFetch('/api/data', { method: 'POST', body: '{}' });++ expect(response.status).toBe(400);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(getOrgID()).toBe('acme');+ });++ it('does not retry an invalid_org 400 when org context is skipped (default org)', async () => {+ mockFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'invalid_org' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ }),+ );++ const response = await apiFetch('/api/data', {+ method: 'POST',+ body: '{}',+ skipOrgContext: true,+ });++ expect(response.status).toBe(400);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it('does not retry a 400 invalid_org response from a non-/api/ URL', async () => {+ mockFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'invalid_org' }), { status: 400 }),+ );++ const response = await apiFetch('https://example.com/api/data', { method: 'POST' });++ expect(response.status).toBe(400);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it('does not retry a 400 invalid_org response when a non-string body fails to parse', async () => {+ mockFetch.mockResolvedValueOnce(new Response('not-json', { status: 400 }));+ setOrgID('acme');++ const response = await apiFetch('/api/data', { method: 'POST', body: '{}' });++ expect(response.status).toBe(400);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(getOrgID()).toBe('acme');+ });+});++describe('apiClient fetchJSON serialization branches', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ });++ afterEach(() => {+ clearAuth();+ setOrgID(null);+ });++ it('returns null when the JSON response body is empty', async () => {+ mockFetch.mockResolvedValue(new Response('', { status: 200 }));++ const result = await apiFetchJSON('/api/data');++ expect(result).toBeNull();+ });++ it('throws an Invalid JSON response error when the body is not parseable', async () => {+ mockFetch.mockResolvedValue(+ new Response('not-json-at-all', {+ status: 200,+ headers: { 'Content-Type': 'text/plain' },+ }),+ );++ await expect(apiFetchJSON('/api/data')).rejects.toThrow('Invalid JSON response from server');+ });++ it('lets the caller override the Content-Type header', async () => {+ mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));++ await apiFetchJSON('/api/data', { headers: { 'Content-Type': 'text/plain' } });++ expect(headersOf(mockFetch.mock.calls[0])['Content-Type']).toBe('text/plain');+ });+});++describe('apiClient 429 Retry-After parsing arms', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ });++ afterEach(() => {+ vi.useRealTimers();+ clearAuth();+ setOrgID(null);+ });++ const retryAfterDefaultWait = async (retryAfterValue: string | null, systemTime?: Date) => {+ if (systemTime) vi.setSystemTime(systemTime);+ const headers: Record<string, string> = {};+ if (retryAfterValue !== null) headers['Retry-After'] = retryAfterValue;+ mockFetch+ .mockResolvedValueOnce(new Response('rate limited', { status: 429, headers }))+ .mockResolvedValueOnce(new Response('{}', { status: 200 }));++ const pending = apiFetch('/api/data');+ await Promise.resolve();+ await vi.advanceTimersByTimeAsync(999);+ expect(mockFetch, 'should not retry before the 1s default wait').toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);+ const response = await pending;+ expect(response.status).toBe(200);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ };++ it('uses the 1s default wait when no Retry-After header is present', async () => {+ await retryAfterDefaultWait(null);+ });++ it('uses the 1s default wait when Retry-After is only whitespace', async () => {+ await retryAfterDefaultWait(' ');+ });++ it('uses the 1s default wait when Retry-After is non-numeric and not a date', async () => {+ await retryAfterDefaultWait('banana');+ });++ it('uses the 1s default wait when numeric Retry-After exceeds the 120s cap', async () => {+ await retryAfterDefaultWait('200');+ });++ it('uses the 1s default wait when the HTTP-date Retry-After is in the past', async () => {+ await retryAfterDefaultWait('Tue, 10 Feb 2026 00:00:00 GMT', new Date('2026-02-11T00:00:00Z'));+ });++ it('uses the 1s default wait when the HTTP-date Retry-After is beyond the 120s cap', async () => {+ await retryAfterDefaultWait('Wed, 11 Feb 2026 00:05:00 GMT', new Date('2026-02-11T00:00:00Z'));+ });+});++describe('apiClient abort handling', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ });++ afterEach(() => {+ vi.useRealTimers();+ clearAuth();+ setOrgID(null);+ });++ it('rejects with AbortError without retrying when the signal is already aborted before the wait', async () => {+ mockFetch.mockResolvedValueOnce(+ new Response('{}', { status: 429, headers: { 'Retry-After': '1' } }),+ );++ const controller = new AbortController();+ controller.abort();++ await expect(apiFetch('/api/data', { signal: controller.signal })).rejects.toMatchObject({+ name: 'AbortError',+ });++ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+});++describe('apiClient org cookie decoding', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ global.fetch = mockFetch as unknown as typeof fetch;+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ clearCsrfCookie();+ document.cookie = 'pulse_org_id=; Path=/; Max-Age=0';+ });++ afterEach(() => {+ clearAuth();+ setOrgID(null);+ document.cookie = 'pulse_org_id=; Path=/; Max-Age=0';+ });++ it('returns null when the org cookie cannot be URL-decoded', () => {+ document.cookie = 'pulse_org_id=%; Path=/';+ expect(getOrgID()).toBeNull();+ });+});++describe('apiClient stored-auth size limits', () => {+ beforeEach(() => {+ window.sessionStorage.clear();+ clearAuth();+ setOrgID(null);+ });++ afterEach(() => {+ clearAuth();+ setOrgID(null);+ window.sessionStorage.clear();+ });++ it('discards an oversized stored auth payload on getApiToken', () => {+ clearApiToken();+ window.sessionStorage.setItem('pulse_auth', 'x'.repeat(17 * 1024));++ expect(getApiToken()).toBeNull();+ expect(window.sessionStorage.getItem('pulse_auth')).toBeNull();+ });++ it('drops an oversized pulse_auth payload during construction', async () => {+ window.sessionStorage.setItem('pulse_auth', 'x'.repeat(17 * 1024));+ vi.resetModules();+ const mod = await import('@/utils/apiClient');++ expect(mod.getApiToken()).toBeNull();+ expect(window.sessionStorage.getItem('pulse_auth')).toBeNull();+ });+});++describe('apiClient kiosk URL-token loading', () => {+ beforeEach(() => {+ window.sessionStorage.clear();+ window.history.replaceState({}, '', '/');+ });++ afterEach(() => {+ window.history.replaceState({}, '', '/');+ window.sessionStorage.clear();+ });++ it('loads an API token from a ?token= URL parameter and strips it from the URL', async () => {+ window.history.replaceState({}, '', '/?token=url-token&keep=1');+ vi.resetModules();+ const mod = await import('@/utils/apiClient');++ expect(mod.getApiToken()).toBe('url-token');+ expect(window.location.search).toBe('?keep=1');+ });++ it('strips an invalid ?token= value without storing it', async () => {+ // %0A decodes to a newline (control char) which sanitization rejects.+ window.history.replaceState({}, '', '/?token=bad%0Atoken');+ vi.resetModules();+ const mod = await import('@/utils/apiClient');++ expect(mod.getApiToken()).toBeNull();+ expect(window.location.search).toBe('');+ });+});++describe('apiClient structured error extraction arms', () => {+ it('extracts the first <pre> block from an HTML error response', async () => {+ const error = await apiErrorFromResponse(+ new Response('<html><body><pre>ValueError: bad input</pre></body></html>', { status: 500 }),+ );++ expect(error.message).toBe('ValueError: bad input');+ expect(error.status).toBe(500);+ });++ it('uses a status fallback message when the body is empty and no fallback is provided', async () => {+ const error = await apiErrorFromResponse(new Response('', { status: 502 }));++ expect(error.message).toBe('Request failed with status 502');+ expect(error.status).toBe(502);+ });++ it('preserves upgrade_url from structured commercial errors', async () => {+ const error = await apiErrorFromResponse(+ new Response(+ JSON.stringify({+ error: 'license_required',+ upgrade_url: 'https://shop.example.com/upgrade',+ }),+ { status: 402 },+ ),+ );++ expect(error.upgrade_url).toBe('https://shop.example.com/upgrade');+ });++ it('preserves a string detail field from structured errors', async () => {+ const error = await apiErrorFromResponse(+ new Response(JSON.stringify({ error: 'bad', detail: 'specific detail' }), { status: 400 }),+ );++ expect(error.detail).toBe('specific detail');+ });++ it('ignores non-string detail fields', async () => {+ const error = await apiErrorFromResponse(+ new Response(JSON.stringify({ error: 'bad', detail: { nested: true } }), { status: 400 }),+ );++ expect(error.detail).toBeUndefined();+ });++ it('falls back to the provided message when both message and error are non-strings', async () => {+ const error = await apiErrorFromResponse(+ new Response(JSON.stringify({ error: { nested: true } }), { status: 400 }),+ 'Fallback message',+ );++ expect(error.message).toBe('Fallback message');+ });++ it('drops error details when every entry fails sanitization', async () => {+ const error = await apiErrorFromResponse(+ new Response(JSON.stringify({ error: 'boom', details: { '': 'x' } }), { status: 400 }),+ );++ expect(error.details).toBeUndefined();+ });++ it('rejects error codes containing control characters', async () => {+ const error = await apiErrorFromResponse(+ new Response(JSON.stringify({ error: 'bad', code: 'bad\ncode' }), { status: 400 }),+ );++ expect(error.code).toBeUndefined();+ });++ it('omits all optional error fields when the response has none', async () => {+ const error = await apiErrorFromResponse(new Response('oops', { status: 500 }));++ expect(error.code).toBeUndefined();+ expect(error.detail).toBeUndefined();+ expect(error.details).toBeUndefined();+ expect(error.feature).toBeUndefined();+ expect(error.requiredScope).toBeUndefined();+ expect(error.upgrade_url).toBeUndefined();+ });+});diff --git a/frontend-modern/src/utils/__tests__/licensePresentation.branchcov0725am.test.ts b/frontend-modern/src/utils/__tests__/licensePresentation.branchcov0725am.test.tsnew file mode 100644index 0000000000..c724789307--- /dev/null+++ b/frontend-modern/src/utils/__tests__/licensePresentation.branchcov0725am.test.ts@@ -0,0 +1,309 @@+/**+ * Branch-coverage tests for licensePresentation.ts (0725am batch).+ *+ * Each `it` targets a distinct uncovered branch arm reported by a V8+ * branch-coverage run scoped to this module. Inputs that violate the+ * (required, non-optional) `tier` / `subscription_state` / `capabilities`+ * string fields are cast through `unknown` so TypeScript stays strict while+ * still exercising the module's `|| ''` / `|| []` defensive fallbacks.+ *+ * Does NOT modify the source module or any existing test file.+ */+import { describe, expect, it } from 'vitest';++import type { LicenseCommercialEntitlements } from '@/api/license';+import {+ formatLicensePlanVersion,+ getBillingAdminStateUpdateSuccessMessage,+ getBillingAdminTrialStatus,+ getOrganizationBillingLicenseStatusLabel,+ getSelfHostedActivationSuccessPresentation,+ getSelfHostedCurrentPlanPresentation,+ getSelfHostedPlanStatusPresentation,+ requiresPulseProRuntime,+} from '@/utils/licensePresentation';++/* ------------------------------------------------------------------ *+ * `(subscriptionState || '')` short-circuit '' arms+ *+ * A single current-plan call with an absent subscription_state drives the+ * `|| ''` fallback arm in four internal helpers at once:+ * line 662 getSelfHostedCurrentPlanPresentation (current.subscription_state)+ * line 400 getPatrolControlAction (subscriptionState arg)+ * line 194 isActiveOrGraceSubscription (subscriptionState arg)+ * line 338 isActivePaidRuntimeState (via requiresPulseProRuntime)+ *+ * The observable that DISTINGUISHES the '' arm: a grandfathered plan_version+ * is present, but because isActiveOrGraceSubscription('') === false the+ * 'Grandfathered price' badge is NOT pushed. The existing grace+grandfathered+ * spec pushes that badge (truthy arm); this test proves the falsy arm skips it.+ * ------------------------------------------------------------------ */++describe('getSelfHostedCurrentPlanPresentation - absent subscription_state hits the || "" fallback arms', () => {+ it('does not push the grandfathered-price badge when subscription_state is absent even with a grandfathered plan_version', () => {+ const result = getSelfHostedCurrentPlanPresentation({+ entitlements: {+ tier: 'pro',+ subscription_state: undefined,+ plan_version: 'v5_pro_monthly_grandfathered',+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],+ limits: [],+ upgrade_reasons: [],+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },+ } as unknown as LicenseCommercialEntitlements,+ displayableCapabilities: [+ 'Pulse Relay (Remote Access)',+ 'Patrol Applies Safe Fixes and Verifies the Result',+ ],+ });+ // isActiveOrGraceSubscription('') === false short-circuits the && so no+ // grandfathered badge is pushed despite the grandfathered plan_version.+ expect(result.supplementalBadges).not.toContain('Grandfathered price');+ expect(result.supplementalBadges).toEqual([]);+ // normalizedState '' is neither trial nor active/grace → final fallback.+ expect(result.body).toBe(+ 'Review the plan details below to confirm what this key enables on this instance.',+ );+ // getPatrolControlAction returns undefined for the '' state.+ expect(result.patrolControlAction).toBeUndefined();+ });+});++/* ------------------------------------------------------------------ *+ * requiresPulseProRuntime - direct '' arms (lines 338 and 351)+ * ------------------------------------------------------------------ */++describe('requiresPulseProRuntime - absent subscription_state (line 338)', () => {+ it('returns false when a Pro-tier entitlement has no subscription_state', () => {+ // isActivePaidRuntimeState(undefined) takes the `|| ''` arm and returns+ // false, so requiresPulseProRuntime is false even for an active-style tier.+ expect(+ requiresPulseProRuntime({+ tier: 'pro',+ subscription_state: undefined,+ } as unknown as Parameters<typeof requiresPulseProRuntime>[0]),+ ).toBe(false);+ });+});++describe('requiresPulseProRuntime - absent tier (line 351)', () => {+ it('returns false when the entitlement has no tier', () => {+ // (entitlements.tier || '') takes the `|| ''` arm → normalizedTier '' is+ // not in PRO_RUNTIME_REQUIRED_TIERS → false.+ expect(+ requiresPulseProRuntime({+ subscription_state: 'active',+ } as unknown as Parameters<typeof requiresPulseProRuntime>[0]),+ ).toBe(false);+ });+});++/* ------------------------------------------------------------------ *+ * formatLicensePlanVersion (lines 452, 453, 459)+ * ------------------------------------------------------------------ */++describe('formatLicensePlanVersion - absent value (lines 452 & 453)', () => {+ it('returns null for null and undefined input via the `|| ""` then early-return arms', () => {+ // line 452: (value || '') takes the '' arm for null/undefined.+ // line 453: !normalized is true → return null.+ expect(formatLicensePlanVersion(null)).toBeNull();+ expect(formatLicensePlanVersion(undefined)).toBeNull();+ });+});++describe('formatLicensePlanVersion - non-canonical value (line 459)', () => {+ it('falls through the grandfathered/legacy/cloud lookups to the title-case fallback', () => {+ // 'internal_beta_channel' is absent from every label map, so the+ // `if (canonical) return canonical;` arm at line 459 is the FALSE branch+ // (existing specs only exercise the truthy canonical arm via cloud_founding).+ expect(formatLicensePlanVersion('internal_beta_channel')).toBe('Internal Beta Channel');+ });+});++/* ------------------------------------------------------------------ *+ * getSelfHostedCurrentPlanPresentation - absent tier (line 663)+ * ------------------------------------------------------------------ */++describe('getSelfHostedCurrentPlanPresentation - absent tier (line 663)', () => {+ it('renders the Unknown plan label via the `|| ""` tier arm', () => {+ const result = getSelfHostedCurrentPlanPresentation({+ entitlements: {+ tier: undefined,+ subscription_state: 'active',+ capabilities: ['relay'],+ limits: [],+ upgrade_reasons: [],+ } as unknown as LicenseCommercialEntitlements,+ displayableCapabilities: ['Pulse Relay (Remote Access)'],+ });+ // (current.tier || '') → '' → getSelfHostedPlanLabel(undefined) === 'Unknown'.+ expect(result.title).toBe('Current plan: Unknown');+ // planDefinition null → getSelfHostedActivePlanSummary returns null → || fallback body.+ expect(result.body).toBe(+ 'Unknown is active on this instance. These capabilities are available right now.',+ );+ });+});++/* ------------------------------------------------------------------ *+ * getSelfHostedCurrentPlanPresentation - enterprise + community runtime+ * Line 758: includedExtrasLabel ternary `: undefined` arm.+ *+ * 'enterprise' is in PRO_RUNTIME_REQUIRED_TIERS (so requiresPulseProRuntime /+ * hasPulseProRuntimeMismatch fire) but has NO plan definition, so+ * getSelfHostedIncludedExtras returns [] → includedExtrasLabel falls to the+ * `undefined` arm. Existing runtime-mismatch specs use tier 'pro', whose plan+ * definition carries non-empty includedExtras ('Included extras' arm).+ * ------------------------------------------------------------------ */++describe('getSelfHostedCurrentPlanPresentation - empty extras on a runtime-mismatched tier (line 758)', () => {+ it('omits includedExtrasLabel when a Pro-runtime tier has no plan definition extras', () => {+ const result = getSelfHostedCurrentPlanPresentation({+ entitlements: {+ tier: 'enterprise',+ subscription_state: 'active',+ capabilities: ['relay', 'audit_logging', 'rbac', 'ai_autofix'],+ limits: [],+ upgrade_reasons: [],+ runtime: { build: 'community', label: 'Pulse Community runtime' },+ },+ displayableCapabilities: ['Pulse Relay (Remote Access)', 'Audit Logging'],+ });+ // includedExtras.length === 0 → the `: undefined` arm of the ternary.+ expect(result.includedExtrasLabel).toBeUndefined();+ expect(result.includedExtras).toEqual([]);+ // Confirms we are in the active+runtimeMismatch return block (line 753+).+ expect(result.supplementalBadges).toContain('Pro runtime missing');+ expect(result.privateRuntimeAction).toEqual({+ actionLabel: 'Open Pulse Pro downloads',+ actionUrl: 'https://pulserelay.pro/download.html',+ });+ });+});++/* ------------------------------------------------------------------ *+ * getSelfHostedPlanStatusPresentation (lines 855 & 861)+ * ------------------------------------------------------------------ */++describe('getSelfHostedPlanStatusPresentation - absent subscription_state (line 855)', () => {+ it('returns null when subscription_state is absent so normalizedState is ""', () => {+ // (entitlements.subscription_state || '') takes the '' arm, then the+ // active/grace/trial guard at line 856 rejects "" → return null.+ expect(+ getSelfHostedPlanStatusPresentation({+ tier: 'relay',+ subscription_state: undefined,+ capabilities: ['relay'],+ limits: [],+ upgrade_reasons: [],+ max_history_days: 14,+ } as unknown as LicenseCommercialEntitlements),+ ).toBeNull();+ });+});++describe('getSelfHostedPlanStatusPresentation - absent capabilities (line 861)', () => {+ it('treats an absent capabilities array as empty so every required capability is missing', () => {+ const result = getSelfHostedPlanStatusPresentation({+ tier: 'relay',+ subscription_state: 'active',+ capabilities: undefined,+ limits: [],+ upgrade_reasons: [],+ max_history_days: 14,+ } as unknown as LicenseCommercialEntitlements);+ expect(result).not.toBeNull();+ // (entitlements.capabilities || []) takes the [] arm → empty capability Set+ // → the remote-access item is fully 'missing'.+ const remoteAccess = result?.items.find((i) => i.label.includes('Remote access'));+ expect(remoteAccess).toMatchObject({+ state: 'missing',+ statusLabel: 'Needs attention',+ });+ });+});++/* ------------------------------------------------------------------ *+ * getSelfHostedActivationSuccessPresentation (lines 965 & 966)+ * ------------------------------------------------------------------ */++describe('getSelfHostedActivationSuccessPresentation - absent subscription_state (line 965)', () => {+ it('returns null when subscription_state is absent', () => {+ // (current.subscription_state || '') takes the '' arm; the active/grace+ // guard at line 971 then rejects "" → null.+ expect(+ getSelfHostedActivationSuccessPresentation({+ entitlements: {+ tier: 'pro',+ subscription_state: undefined,+ capabilities: ['relay', 'ai_autofix'],+ limits: [],+ upgrade_reasons: [],+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },+ } as unknown as LicenseCommercialEntitlements,+ displayableCapabilities: ['Patrol Applies Safe Fixes and Verifies the Result'],+ source: 'manual',+ }),+ ).toBeNull();+ });+});++describe('getSelfHostedActivationSuccessPresentation - absent tier (line 966)', () => {+ it('renders the Unknown plan label via the `|| ""` tier arm', () => {+ const result = getSelfHostedActivationSuccessPresentation({+ entitlements: {+ tier: undefined,+ subscription_state: 'active',+ capabilities: ['relay'],+ limits: [],+ upgrade_reasons: [],+ } as unknown as LicenseCommercialEntitlements,+ displayableCapabilities: ['Pulse Relay (Remote Access)'],+ source: 'manual',+ });+ expect(result).not.toBeNull();+ // (current.tier || '') → '' → getSelfHostedPlanLabel(undefined) === 'Unknown'.+ expect(result?.title).toBe('Unknown is now active');+ expect(result?.body).toBe(+ 'The license key was accepted and this instance is now running Unknown.',+ );+ });+});++/* ------------------------------------------------------------------ *+ * Small switch / ternary arms (lines 1251, 1259, 1294)+ * ------------------------------------------------------------------ */++describe('getOrganizationBillingLicenseStatusLabel - valid license outside grace (line 1251)', () => {+ it('returns Active for a valid license that is not in its grace period', () => {+ // Existing specs cover the `: 'Active'` falsy arm only via in_grace_period+ // being absent on a {valid:false} payload (which returns 'No License').+ // Here valid:true & in_grace_period:false takes the `: 'Active'` arm.+ expect(getOrganizationBillingLicenseStatusLabel({ valid: true, in_grace_period: false })).toBe(+ 'Active',+ );+ });+});++describe('getBillingAdminTrialStatus - absent subscription_state (line 1259)', () => {+ it('renders the started date as N/A when subscription_state is absent but a trial end exists', () => {+ // (state.subscription_state || '') takes the '' arm; with a trial_ends_at+ // present the 'No trial' guard is skipped and the started date renders N/A.+ const result = getBillingAdminTrialStatus({+ trial_ends_at: 1_700_000_000,+ } as never);+ expect(result).toContain('Trial (started N/A');+ expect(result).toContain('ends');+ expect(result).not.toContain('No trial');+ });+});++describe('getBillingAdminStateUpdateSuccessMessage - suspended (line 1294)', () => {+ it('returns the suspended message for the suspended arm of the ternary', () => {+ // Existing specs only exercise the `: 'Organization billing activated'`+ // arm (nextState 'active'); this hits the 'suspended' truthy arm.+ expect(getBillingAdminStateUpdateSuccessMessage('suspended')).toBe(+ 'Organization billing suspended',+ );+ });+});diff --git a/frontend-modern/src/utils/__tests__/resourceBadgePresentation.branchcov0725am.test.ts b/frontend-modern/src/utils/__tests__/resourceBadgePresentation.branchcov0725am.test.tsnew file mode 100644index 0000000000..638f1c540f--- /dev/null+++ b/frontend-modern/src/utils/__tests__/resourceBadgePresentation.branchcov0725am.test.ts@@ -0,0 +1,229 @@+import { describe, expect, it } from 'vitest';++import type { Resource } from '@/types/resource';+import {+ getContainerRuntimeBadgeForRuntime,+ getInfrastructurePlatformBadges,+ getInfrastructureSystemIdentityBadges,+ getInfrastructureSystemIdentitySortLabel,+ getPlatformBadge,+ getTypeBadge,+ getUnifiedSourceBadges,+} from '@/utils/resourceBadgePresentation';+import { getSourcePlatformPresentation } from '@/utils/sourcePlatforms';++// Scope note (see GLM_REPORT_fe2-resourcebadge.md):+//+// A V8 branch-coverage run of the three sibling specs, scoped to+// `resourceBadgePresentation.ts`, reports 24 source lines whose branch arm has+// zero hits: 115, 151, 158, 188, 189, 190, 204, 226, 229, 245, 271, 287, 387,+// 415, 420, 422, 437, 573, 585, 604, 608, 670, 701, 744.+//+// Every one of those arms is UNREACHABLE BY CONSTRUCTION. They are defensive+// fallbacks (`??`, `||`, early `return null`) whose left-hand operand can never+// be nullish/falsy at runtime, because of three invariants enforced upstream:+// (1) `getSourcePlatformBadge` returns null ONLY for empty input (it falls+// back to a title-cased label for any non-empty string);+// (2) `getResourceTypePresentation` returns null ONLY for falsy input and+// always populates `badgeClasses`;+// (3) every internal caller either guards against empty/falsy input first or+// passes values it has already trimmed/deduplicated.+//+// Per the task rules, an unreachable arm must NOT be covered by a fabricated+// test. Instead, the tests below exercise the exported entry points with+// ADVERSARIAL inputs (unknown platform strings, duplicate sources, malformed+// host-source ids, whitespace fields) that WOULD trigger each dead arm if it+// were reachable, and assert the real returned value. They demonstrate — on the+// real module — the invariant that keeps the arm dead, and are intentionally+// distinct from the canonical-value assertions the sibling specs already make.++const makeResource = (overrides: Partial<Resource> = {}): Resource =>+ ({+ id: 'resource-1',+ type: 'agent',+ name: 'host-1',+ displayName: 'host-1',+ platformId: 'host-1',+ platformType: 'agent',+ sourceType: 'agent',+ status: 'online',+ lastSeen: 1,+ ...overrides,+ }) as Resource;++describe('resourceBadgePresentation — dead-arm reachability characterization (branchcov0725am)', () => {+ it('getPlatformBadge resolves an arbitrary unknown platform string to a derived badge, so the `if (!sharedBadge) return null` arm at L204 cannot fire', () => {+ // getSourcePlatformBadge only returns null for empty input. Any non-empty+ // platform type yields a title-cased label, so `sharedBadge` at L203 is+ // always defined for the non-empty platformType that survived the L195+ // guard — the `return null` at L204 is dead even for wholly unknown values.+ const badge = getPlatformBadge('fictional-hypervisor-xyz' as never);+ expect(badge).not.toBeNull();+ expect(badge?.label).toBe('Fictional Hypervisor Xyz');+ expect(badge?.title).toBe('Fictional Hypervisor Xyz');+ });++ it('getTypeBadge supplies a default badgeClasses for an unknown type, so the `presentation.badgeClasses || typeClasses` arm at L229 cannot fire', () => {+ // getResourceTypePresentation always returns an object whose badgeClasses is+ // a non-empty string (DEFAULT_BADGE_CLASSES), so the `|| typeClasses`+ // fallback is dead. Distinguished from the sibling "totally-fake-type" test+ // by asserting the EXACT class string (the default tone) rather than a+ // substring, locking the contract that badgeClasses is always populated.+ const badge = getTypeBadge('invented-resource-kind');+ expect(badge).not.toBeNull();+ expect(badge?.label).toBe('invented-resource-kind');+ expect(badge?.classes).toBe(+ 'inline-flex items-center rounded px-2 py-0.5 text-[10px] font-medium whitespace-nowrap bg-surface-alt text-base-content',+ );+ });++ it('getInfrastructurePlatformBadges collapses duplicate agent entries to one, so the multi-source ternary `: normalized` arm at L245 cannot fire', () => {+ // normalizeUnifiedSourceKeys builds a Set, so ['agent','agent','agent']+ // collapses to ['agent'] (length 1) and returns at the `<= 1` guard (L240).+ // The `> 1` branch therefore only runs when at least one non-agent source is+ // present, which forces `platformSources.length > 0` to be true there — the+ // `platformSources.length > 0 ? platformSources : normalized` ternary never+ // evaluates its right operand.+ const badges = getInfrastructurePlatformBadges(['agent', 'agent', 'agent']);+ expect(badges).toHaveLength(1);+ expect(badges.map((b) => b.label)).toEqual(['Agent']);+ });++ it('getAgentSystemIdentityBadge resolves an arbitrary unknown hostProfile to a badge, so `badge?.label ?? profileFamily` (L415) and `badge?.classes ?? ...` (L420) never fall back', () => {+ // Inside the `if (hostProfile)` guard the value is non-empty, and+ // getSourcePlatformBadge never returns null for non-empty input, so `badge`+ // is always defined here — both `badge?.X ?? fallback` arms are dead. An+ // unrecognized hostProfile still resolves to a derived (title-cased) badge+ // rather than the profileFamily fallback.+ const badges = getInfrastructureSystemIdentityBadges(+ makeResource({+ type: 'agent',+ platformType: 'agent',+ sourceType: 'agent',+ sources: ['agent'],+ platformData: {+ sources: ['agent'],+ agent: { hostProfile: 'fictional-nas-xyz', osName: '' },+ },+ }),+ );+ expect(badges).toHaveLength(1);+ expect(badges[0]?.label).toBe('Fictional Nas Xyz');+ expect(badges[0]?.classes).toContain('inline-flex');+ });++ it('proxmoxLxcDockerBadge short-circuits a non-string hostSourceId before proxmoxLxcDockerVmid runs, so the vmid guard at L604 cannot fire', () => {+ // proxmoxLxcDockerBadge validates `typeof hostSourceId !== 'string'` (L614)+ // and `!startsWith(prefix)` (L615) itself and returns null; the inner+ // proxmoxLxcDockerVmid helper is therefore only ever called with an+ // already-valid string, making its own guard at L604 dead. A non-string id+ // never reaches the helper and falls through to the docker runtime badge.+ const badges = getInfrastructureSystemIdentityBadges(+ makeResource({+ type: 'docker-host',+ platformType: 'docker',+ sourceType: 'agent',+ sources: ['docker'],+ platformData: { sources: ['docker'] },+ docker: { hostSourceId: 12345 as unknown as string, runtime: 'docker' },+ }),+ );+ expect(badges.map((b) => b.label)).toEqual(['Docker / Podman']);+ });++ it('getInfrastructureSystemIdentitySortLabel derives a platform label for an unknown platformType, so the L701 truthy-stop of the `||` chain cannot fire', () => {+ // Reaching the L701 operand requires the identity badge list to be empty+ // (badges[0]?.label falsy). But the list is only empty when no identity at+ // all resolves — which requires platformType to be absent/falsy (a non-empty+ // platformType always yields a platform badge at L690). With a falsy+ // platformType, getPlatformBadge returns null, so L701's `?.label` is+ // always falsy when reached and never stops the chain. A non-empty (even+ // unknown) platformType instead produces a non-empty identity list, so the+ // sort label resolves at L700 and L701 is never reached.+ const label = getInfrastructureSystemIdentitySortLabel(+ makeResource({+ type: 'vm',+ platformType: 'fictional-hypervisor-xyz' as Resource['platformType'],+ sourceType: 'api',+ sources: [],+ }),+ );+ expect(label).toBe('Fictional Hypervisor Xyz');+ });++ it('treats a whitespace-only agent.platform as absent, so the `if (!normalized) return null` guards at L271/L287 in the host-identity helpers cannot fire', () => {+ // getKnownHostIdentitySource receives already-trimString'd values; a+ // whitespace platform is trimmed to '' and skipped via `if (!value) continue`+ // before getHostIdentityAgentProfile/getHostIdentityPlatform ever see it, so+ // the `value.trim().toLowerCase()` they compute is always non-empty. The+ // osName still resolves the identity.+ const badges = getInfrastructureSystemIdentityBadges(+ makeResource({+ type: 'agent',+ platformType: 'agent',+ sourceType: 'agent',+ sources: ['agent'],+ platformData: {+ sources: ['agent'],+ agent: { platform: ' ', osName: 'TrueNAS SCALE' },+ },+ }),+ );+ expect(badges.map((b) => b.label)).toEqual(['TrueNAS']);+ });++ it('getContainerRuntimeBadgeForRuntime reflects the real docker presentation tone (the `?? dockerRuntimeBadgeClasses` fallback at L744 is dead and indistinguishable)', () => {+ // getSourcePlatformPresentation('docker') is always defined and carries a+ // tone, so the `?.tone ?? dockerRuntimeBadgeClasses` fallback never fires.+ // (The fallback string is in fact byte-identical to the real docker tone, so+ // no test can distinguish the two paths by output — this asserts the badge+ // honors the presentation tone regardless.)+ const dockerTone = getSourcePlatformPresentation('docker')?.tone;+ const badge = getContainerRuntimeBadgeForRuntime('docker');+ expect(badge).not.toBeNull();+ expect(dockerTone).toBeTruthy();+ expect(badge?.classes.endsWith(dockerTone as string)).toBe(true);+ });+});++// Imported only to keep the characterization of buildUnifiedSourceBadges+// (L188/L189/L190) and the versioned-source path (L573/L670) explicit: every+// KnownSourcePlatform has a shared presentation, so `sharedBadge?.X ?? source`+// never falls back, and buildUnifiedSourceBadges always emits exactly one badge+// per source, so getVersionedSourceBadge never returns null.+describe('resourceBadgePresentation — shared-badge / versioned-source invariants', () => {+ it('every known source platform resolves a shared presentation badge, so the `?? source` fallbacks at L188/L189/L190 never fire', () => {+ // A presentation-only platform (synology-dsm) and the availability provider+ // both yield their presentation label/classes/title rather than the raw key+ // or the neutral tone, proving sharedBadge is never null for a known source.+ const synology = getUnifiedSourceBadges(['synology-dsm'])[0];+ expect(synology?.label).toBe('Synology');+ expect(synology?.classes).not.toContain('bg-surface-alt');++ const availability = getUnifiedSourceBadges(['availability'])[0];+ expect(availability?.label).toBe('Availability');+ expect(availability?.classes).not.toContain('bg-surface-alt');+ });++ it('a system source with no version data still yields an unversioned badge, so `: null` (L573) and `: []` (L670) never fire', () => {+ // buildUnifiedSourceBadges maps one badge per source unconditionally, so+ // getUnifiedSourceBadges([source])[0] is always defined and+ // getVersionedSourceBadge always returns a badge — even when no version+ // resolves anywhere. A hyper-v source with empty facets returns the+ // unversioned 'Hyper-V' badge rather than null/[].+ const badges = getInfrastructureSystemIdentityBadges(+ makeResource({+ type: 'vm',+ platformType: 'agent',+ sourceType: 'api',+ sources: ['microsoft-hyperv'],+ platformData: {+ sources: ['microsoft-hyperv'],+ 'microsoft-hyperv': {},+ platform: {},+ },+ }),+ );+ expect(badges.map((b) => b.label)).toEqual(['Hyper-V']);+ });+});diff --git a/internal/ai/modelboundary/sanitizer_branchcov0725am_test.go b/internal/ai/modelboundary/sanitizer_branchcov0725am_test.gonew file mode 100644index 0000000000..1f8a0f502c--- /dev/null+++ b/internal/ai/modelboundary/sanitizer_branchcov0725am_test.go@@ -0,0 +1,255 @@+package modelboundary++import (+ "reflect"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++// branchcov0725amByTypeOnlyProvider implements only+// UnifiedResourceProvider.GetByType and intentionally NOT allUnifiedResourceProvider.GetAll,+// forcing resourcePolicySanitizerResources down its per-type aggregation loop instead of the+// GetAll fast-path. The slice returned for each type is fully controlled so the dedup branch+// (same Type+ID emitted twice) can be exercised deterministically.+type branchcov0725amByTypeOnlyProvider struct {+ byType map[unifiedresources.ResourceType][]unifiedresources.Resource+}++func (p branchcov0725amByTypeOnlyProvider) GetByType(t unifiedresources.ResourceType) []unifiedresources.Resource {+ return append([]unifiedresources.Resource(nil), p.byType[t]...)+}++// TestBranchcov0725amSortStringsByLengthDesc drives both arms of the sort comparator:+// the equal-length tie branch (alphabetical ascending) and the length branch (descending by+// length), plus the empty / single / already-sorted degenerate inputs.+func TestBranchcov0725amSortStringsByLengthDesc(t *testing.T) {+ cases := []struct {+ name string+ in []string+ want []string+ }{+ {+ name: "nil slice unchanged",+ in: nil,+ want: nil,+ },+ {+ name: "empty non-nil slice unchanged",+ in: []string{},+ want: []string{},+ },+ {+ name: "single element unchanged",+ in: []string{"solo"},+ want: []string{"solo"},+ },+ {+ name: "ties broken alphabetically ascending",+ in: []string{"cat", "bat", "ant"},+ want: []string{"ant", "bat", "cat"},+ },+ {+ name: "distinct lengths sorted descending by length",+ in: []string{"a", "ccc", "bb"},+ want: []string{"ccc", "bb", "a"},+ },+ {+ name: "mixed distinct lengths and ties",+ in: []string{"z", "bbb", "aaa", "dddd"},+ want: []string{"dddd", "aaa", "bbb", "z"},+ },+ {+ name: "already sorted input is stable",+ in: []string{"dddd", "aaa", "bbb", "z"},+ want: []string{"dddd", "aaa", "bbb", "z"},+ },+ {+ name: "fully reverse input is sorted",+ in: []string{"z", "bbb", "aaa", "dddd"},+ want: []string{"dddd", "aaa", "bbb", "z"},+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := tc.in+ sortStringsByLengthDesc(got)+ if !reflect.DeepEqual(got, tc.want) {+ t.Fatalf("sortStringsByLengthDesc(%v) = %v, want %v", tc.in, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amResourcePolicySanitizerResources drives the per-type aggregation loop of+// resourcePolicySanitizerResources (the branch taken when the provider does NOT implement+// GetAll), including the Type+ID dedup continue and the final RefreshCanonicalMetadataSlice ++// resourcesWithPolicy return.+func TestBranchcov0725amResourcePolicySanitizerResources(t *testing.T) {+ t.Run("by_type_only_provider_dedups_and_refreshes_policy", func(t *testing.T) {+ vm := unifiedresources.Resource{+ ID: "vm-100",+ Type: unifiedresources.ResourceTypeVM,+ Name: "vm1",+ }+ // Duplicated VM entry with identical Type+ID: the second must be dropped by the+ // `seen` map (dedup continue branch).+ vmDup := unifiedresources.Resource{+ ID: "vm-100",+ Type: unifiedresources.ResourceTypeVM,+ Name: "vm1-duplicate-name",+ }+ agent := unifiedresources.Resource{+ ID: "agent/neo",+ Type: unifiedresources.ResourceTypeAgent,+ Name: "neo",+ }+ provider := branchcov0725amByTypeOnlyProvider{+ byType: map[unifiedresources.ResourceType][]unifiedresources.Resource{+ unifiedresources.ResourceTypeVM: {vm, vmDup},+ unifiedresources.ResourceTypeAgent: {agent},+ },+ }++ got := resourcePolicySanitizerResources(provider)++ if len(got) != 2 {+ t.Fatalf("expected 2 resources after dedup, got %d: %+v", len(got), got)+ }++ // ResourceTypeAgent is iterated before ResourceTypeVM, so the agent is collected first.+ if got[0].ID != "agent/neo" || got[0].Type != unifiedresources.ResourceTypeAgent {+ t.Fatalf("first resource = %+v, want agent/neo", got[0])+ }+ if got[1].ID != "vm-100" || got[1].Type != unifiedresources.ResourceTypeVM {+ t.Fatalf("second resource = %+v, want vm-100", got[1])+ }+ // The duplicate's name must not have survived dedup.+ if got[1].Name == "vm1-duplicate-name" {+ t.Fatalf("dedup did not drop the duplicate vm-100 entry: %+v", got[1])+ }+ // RefreshCanonicalMetadataSlice must have populated a non-nil Policy on each kept+ // resource (resourcesWithPolicy otherwise filters Policy==nil entries).+ for i, r := range got {+ if r.Policy == nil {+ t.Fatalf("resource %d (%s) has nil Policy after refresh", i, r.ID)+ }+ }+ })++ t.Run("by_type_only_empty_provider_returns_empty_non_nil", func(t *testing.T) {+ got := resourcePolicySanitizerResources(branchcov0725amByTypeOnlyProvider{})+ // resourcesWithPolicy allocates a non-nil empty slice even for no input.+ if got == nil {+ t.Fatalf("expected non-nil empty slice, got nil")+ }+ if len(got) != 0 {+ t.Fatalf("expected 0 resources, got %d: %+v", len(got), got)+ }+ })+}++// TestBranchcov0725amSanitizePromptSecretValue drives every type arm of sanitizePromptSecretValue+// that existing tests leave uncovered: the []string sensitive path, the full map[string]string+// arm (sensitive and non-sensitive sub-arms under both parent-sensitive and parent-non-sensitive),+// and the default (passthrough) arm. The string/sensitive path is also exercised at the+// RedactSensitiveValue length boundary: below minimum (empty), at the boundary (whitespace-only),+// and well above (real content -> [REDACTED]).+func TestBranchcov0725amSanitizePromptSecretValue(t *testing.T) {+ t.Run("string_sensitive_length_boundaries", func(t *testing.T) {+ cases := []struct {+ name string+ value string+ want string+ }{+ {name: "below_minimum_empty_returns_empty", value: "", want: ""},+ {name: "boundary_whitespace_only_preserved", value: " ", want: " "},+ {name: "well_above_real_value_redacted", value: "real-secret", want: "[REDACTED]"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := sanitizePromptSecretValue("password", tc.value, true)+ if got != tc.want {+ t.Fatalf("sanitizePromptSecretValue(string,%q,sensitive) = %#v, want %q", tc.value, got, tc.want)+ }+ })+ }+ })++ t.Run("string_slice_sensitive_redacts_each_element", func(t *testing.T) {+ got := sanitizePromptSecretValue("password", []string{"", "real-secret"}, true)+ want := []string{"", "[REDACTED]"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("got %#v, want %#v", got, want)+ }+ })++ t.Run("string_slice_non_sensitive_uses_text_path", func(t *testing.T) {+ // Under the non-sensitive arm, an OpenAI-shaped token is pattern-redacted but a plain+ // value is left intact — distinguishing the text path from the always-redacted+ // sensitive path.+ got := sanitizePromptSecretValue("tags", []string{"sk-aaaaaaaaaaaaaaaa", "plain"}, false)+ want := []string{"[REDACTED_PROVIDER_KEY]", "plain"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("got %#v, want %#v", got, want)+ }+ })++ t.Run("map_string_string_parent_sensitive_distinguishes_carrier_keys", func(t *testing.T) {+ // parent sensitiveValue=true: a value-carrier key ("value") and a sensitive key+ // ("password") both route to the sensitive-value redactor, while a non-carrier key+ // ("note") routes to the plain-text redactor.+ got := sanitizePromptSecretValue(+ "",+ map[string]string{"value": "carrier-secret", "password": "cred", "note": "keep-me"},+ true,+ ).(map[string]string)+ if got["value"] != "[REDACTED]" {+ t.Fatalf("carrier key 'value' = %q, want [REDACTED]", got["value"])+ }+ if got["password"] != "[REDACTED]" {+ t.Fatalf("sensitive key 'password' = %q, want [REDACTED]", got["password"])+ }+ if got["note"] != "keep-me" {+ t.Fatalf("non-carrier key 'note' = %q, want keep-me", got["note"])+ }+ })++ t.Run("map_string_string_parent_non_sensitive_skips_carrier_term", func(t *testing.T) {+ // parent sensitiveValue=false: the `sensitiveValue && carrier` term is false, so a+ // carrier key ("value") is NOT treated as sensitive and flows through the text path.+ got := sanitizePromptSecretValue(+ "",+ map[string]string{"value": "keep-this", "password": "cred"},+ false,+ ).(map[string]string)+ if got["value"] != "keep-this" {+ t.Fatalf("carrier key 'value' under non-sensitive parent = %q, want keep-this", got["value"])+ }+ if got["password"] != "[REDACTED]" {+ t.Fatalf("sensitive key 'password' = %q, want [REDACTED]", got["password"])+ }+ })++ t.Run("default_arm_passes_through_non_string_scalars", func(t *testing.T) {+ for _, v := range []interface{}{42, true, 3.14, nil} {+ got := sanitizePromptSecretValue("count", v, true)+ if !reflect.DeepEqual(got, v) {+ t.Fatalf("default passthrough for %#v = %#v, want identity", v, got)+ }+ }+ })++ t.Run("interface_slice_recurses_into_default_element", func(t *testing.T) {+ // A non-string element inside []interface{} recurses through sanitizePromptSecretValue+ // into the default (passthrough) arm while leaving string elements text-redacted.+ got := sanitizePromptSecretValue("items", []interface{}{"plain", 7}, false).([]interface{})+ if got[0] != "plain" {+ t.Fatalf("string element = %#v, want plain", got[0])+ }+ if got[1] != 7 {+ t.Fatalf("int element = %#v, want 7 (passthrough)", got[1])+ }+ })+}diff --git a/internal/ai/patrol_handoff_branchcov0725am_test.go b/internal/ai/patrol_handoff_branchcov0725am_test.gonew file mode 100644index 0000000000..ae7d1f9dd4--- /dev/null+++ b/internal/ai/patrol_handoff_branchcov0725am_test.go@@ -0,0 +1,405 @@+package ai++import (+ "strings"+ "testing"+)++// This file raises statement coverage of four partially-covered pure helpers+// in patrol_assistant_handoff.go:+//+// - formatPatrolRunDurationMs (line 214) -> pinned at every unit+// boundary + zero/negative.+// - patrolRunRuntimeFailureSummary (line 119) -> empty / summary-only /+// detail-only / combined /+// summary==detail / count+// arms, with truncation.+// - patrolRunScopeSummary (line 269) -> empty / single / multi /+// types / scoped-only /+// Effective-vs-Scope nil.+// - patrolRunCoverageSummary (line 229) -> empty / partial-of-scope /+// full scoped / unscoped /+// breakdown / nil-vs-empty.+//+// Every assertion pins the exact returned string so a behaviour change is+// caught. No existing test in this package calls these functions directly, so+// nothing here duplicates existing coverage.++// TestBranchcov0725amFormatPatrolRunDurationMs pins each unit boundary the+// formatter switches on. There is NO separate hours arm in the source: any+// duration >= 60s collapses to whole minutes, so one hour renders as "60m".+// That is exercised by the one_hour_renders_as_minutes case and called out in+// the report as a source observation (not a bug).+func TestBranchcov0725amFormatPatrolRunDurationMs(t *testing.T) {+ cases := []struct {+ name string+ ms int64+ want string+ }{+ // ms <= 0 arm (covers both zero and the negative boundary).+ {name: "zero_returns_empty", ms: 0, want: ""},+ {name: "negative_returns_empty", ms: -1, want: ""},++ // Sub-second arm: 0 < ms < 1000.+ {name: "one_millisecond", ms: 1, want: "1ms"},+ {name: "just_below_one_second", ms: 999, want: "999ms"},++ // Seconds arm: ms rounds up to 1..59 whole seconds.+ {name: "exactly_one_second_rounds_to_1s", ms: 1000, want: "1s"},+ {name: "just_above_one_second_still_1s", ms: 1001, want: "1s"},+ {name: "last_value_rendering_seconds", ms: 59499, want: "59s"}, // (59499+500)/1000 = 59++ // Minutes arm (seconds >= 60): rounds seconds to whole minutes.+ {name: "first_value_rendering_minutes", ms: 59500, want: "1m"}, // (60000/1000=60)->(60+30)/60=1+ {name: "rounds_down_to_1m", ms: 89499, want: "1m"}, // (89+30)/60 = 1+ {name: "rounds_up_to_2m", ms: 89500, want: "2m"}, // (90+30)/60 = 2++ // Hours: no dedicated arm exists; one hour renders as "60m".+ {name: "one_hour_renders_as_minutes", ms: 3600000, want: "60m"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := formatPatrolRunDurationMs(tc.ms)+ if got != tc.want {+ t.Fatalf("formatPatrolRunDurationMs(%d) = %q, want %q", tc.ms, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amPatrolRunRuntimeFailureSummary drives every return arm+// of patrolRunRuntimeFailureSummary with inputs that survive+// redaction/summarization deterministically, asserting the exact string.+func TestBranchcov0725amPatrolRunRuntimeFailureSummary(t *testing.T) {+ longDetail := strings.Repeat("a", 300) // falls through summarize to default redaction (no keyword match, no secrets)++ cases := []struct {+ name string+ run PatrolRunRecord+ want string+ }{+ {+ // Empty / no-data arm: nothing to report.+ name: "no_errors_returns_empty",+ run: PatrolRunRecord{},+ want: "",+ },+ {+ // Combined arm: distinct non-empty summary and detail ->+ // "summary: detail".+ name: "summary_and_distinct_detail_joined",+ run: PatrolRunRecord{+ ErrorSummary: "Patrol run hit a snag",+ ErrorDetail: "rate limit exceeded",+ },+ want: "Patrol run hit a snag: Provider rate limit reached. Wait for capacity or adjust provider limits before retrying.",+ },+ {+ // summary == detail arm: when summary and the summarized detail+ // are identical, the joined form is suppressed and the bare+ // summary is returned (no redundant duplication).+ name: "summary_equals_detail_returns_bare_summary",+ run: PatrolRunRecord{+ ErrorSummary: "upstream returned unexpected eof",+ ErrorDetail: "upstream returned unexpected eof",+ },+ want: "upstream returned unexpected eof",+ },+ {+ // Summary-only arm: detail empty -> return summary verbatim.+ name: "summary_only_no_detail",+ run: PatrolRunRecord{+ ErrorSummary: "Patrol hit a snag",+ },+ want: "Patrol hit a snag",+ },+ {+ // Detail-only arm: summary empty -> return summarized detail.+ name: "detail_only_no_summary",+ run: PatrolRunRecord{+ ErrorDetail: "rate limit exceeded",+ },+ want: "Provider rate limit reached. Wait for capacity or adjust provider limits before retrying.",+ },+ {+ // Combined arm with detail longer than the 260-char cap ->+ // detail is truncated to "<257 chars>...".+ name: "combined_detail_truncated_at_260",+ run: PatrolRunRecord{+ ErrorSummary: "Boom",+ ErrorDetail: longDetail,+ },+ want: "Boom: " + longDetail[:257] + "...",+ },+ {+ // ErrorCount arm, singular: no summary/detail, count == 1.+ name: "error_count_one_singular",+ run: PatrolRunRecord{+ ErrorCount: 1,+ },+ want: "1 Patrol runtime error recorded",+ },+ {+ // ErrorCount arm, plural: no summary/detail, count != 1.+ name: "error_count_many_plural",+ run: PatrolRunRecord{+ ErrorCount: 3,+ },+ want: "3 Patrol runtime errors recorded",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := patrolRunRuntimeFailureSummary(tc.run)+ if got != tc.want {+ t.Fatalf("patrolRunRuntimeFailureSummary = %q, want %q", got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amPatrolRunScopeSummary drives the empty, single-item,+// multi-item, types-only, scoped-only, and Effective-vs-Scope precedence arms+// of patrolRunScopeSummary.+func TestBranchcov0725amPatrolRunScopeSummary(t *testing.T) {+ cases := []struct {+ name string+ run PatrolRunRecord+ want string+ }{+ {+ // Empty / no-data arm.+ name: "no_scope_returns_empty",+ run: PatrolRunRecord{},+ want: "",+ },+ {+ // Single-item effective scope (suffix "").+ name: "single_effective_resource",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{"vm-1"},+ },+ want: "Scoped to 1 resource",+ },+ {+ // Multi-item effective scope (suffix "s").+ name: "multiple_effective_resources",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{"vm-1", "vm-2", "vm-3"},+ },+ want: "Scoped to 3 resources",+ },+ {+ // Effective nil -> falls back to ScopeResourceIDs (single).+ name: "effective_nil_falls_back_to_scope_single",+ run: PatrolRunRecord{+ ScopeResourceIDs: []string{"node-1"},+ },+ want: "Scoped to 1 resource",+ },+ {+ // Effective non-nil empty slice takes precedence over a populated+ // ScopeResourceIDs: scopedResourceCount becomes 0 so the types arm+ // is consulted instead. Pins the nil-vs-empty distinction.+ name: "effective_empty_overrides_populated_scope",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{},+ ScopeResourceIDs: []string{"a", "b"},+ ScopeResourceTypes: []string{"vm", "node"},+ },+ want: "Scoped to vm, node",+ },+ {+ // Types-only arm, single type.+ name: "types_only_single",+ run: PatrolRunRecord{+ ScopeResourceTypes: []string{"pbs"},+ },+ want: "Scoped to pbs",+ },+ {+ // Types-only arm, multi type.+ name: "types_only_multi",+ run: PatrolRunRecord{+ ScopeResourceTypes: []string{"vm", "node"},+ },+ want: "Scoped to vm, node",+ },+ {+ // ids take precedence over types when both are set.+ name: "ids_take_precedence_over_types",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{"vm-1"},+ ScopeResourceTypes: []string{"vm"},+ },+ want: "Scoped to 1 resource",+ },+ {+ // Scoped-only arm: Type == "scoped", no ids/types.+ name: "type_scoped_label",+ run: PatrolRunRecord{+ Type: "scoped",+ },+ want: "Scoped",+ },+ {+ // EqualFold: Type is matched case-insensitively after trim.+ name: "type_scoped_case_insensitive",+ run: PatrolRunRecord{+ Type: " SCOPED ",+ },+ want: "Scoped",+ },+ {+ // Non-scoped type with no ids/types -> empty.+ name: "non_scoped_type_returns_empty",+ run: PatrolRunRecord{+ Type: "patrol",+ },+ want: "",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := patrolRunScopeSummary(tc.run)+ if got != tc.want {+ t.Fatalf("patrolRunScopeSummary = %q, want %q", got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amPatrolRunCoverageSummary drives the empty, partial-of-+// scope, full-scoped (singular + plural), unscoped (singular + plural), and+// breakdown arms of patrolRunCoverageSummary, including the subtle+// nil-vs-empty scope distinction and the scoped-but-zero-checked fall-through.+func TestBranchcov0725amPatrolRunCoverageSummary(t *testing.T) {+ cases := []struct {+ name string+ run PatrolRunRecord+ want string+ }{+ {+ // Empty / no-data arm: nothing checked, no scope, no breakdown.+ name: "nothing_checked_returns_empty",+ run: PatrolRunRecord{},+ want: "",+ },+ {+ // Partial-of-scope arm: resourcesChecked > 0 and < scope count.+ name: "partial_of_scope",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{"a", "b", "c"},+ ResourcesChecked: 1,+ },+ want: "Checked 1 of 3 scoped resources",+ },+ {+ // Full scoped arm, singular: checked == scope == 1.+ name: "full_scoped_singular",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{"a"},+ ResourcesChecked: 1,+ },+ want: "Checked 1 scoped resource",+ },+ {+ // Full scoped arm, plural: checked == scope == 2.+ name: "full_scoped_plural",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{"a", "b"},+ ResourcesChecked: 2,+ },+ want: "Checked 2 scoped resources",+ },+ {+ // Effective nil -> scope count falls back to ScopeResourceIDs.+ name: "partial_of_scope_via_legacy_scope_ids",+ run: PatrolRunRecord{+ ScopeResourceIDs: []string{"a", "b", "c"},+ ResourcesChecked: 1,+ },+ want: "Checked 1 of 3 scoped resources",+ },+ {+ // Effective non-nil empty overrides a populated ScopeResourceIDs:+ // scope count becomes 0 so the unscoped "Checked N resource[s]"+ // arm fires instead. Pins nil-vs-empty for coverage.+ name: "effective_empty_treated_as_unscoped",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{},+ ScopeResourceIDs: []string{"a", "b"},+ ResourcesChecked: 1,+ },+ want: "Checked 1 resource",+ },+ {+ // Unscoped singular: no scope, checked == 1.+ name: "unscoped_singular",+ run: PatrolRunRecord{+ ResourcesChecked: 1,+ },+ want: "Checked 1 resource",+ },+ {+ // Unscoped plural: no scope, checked == 2.+ name: "unscoped_plural",+ run: PatrolRunRecord{+ ResourcesChecked: 2,+ },+ want: "Checked 2 resources",+ },+ {+ // Breakdown arm, single category.+ name: "breakdown_single",+ run: PatrolRunRecord{+ NodesChecked: 2,+ },+ want: "2 nodes",+ },+ {+ // Breakdown arm, multi category (joined with "; ").+ name: "breakdown_multi",+ run: PatrolRunRecord{+ NodesChecked: 2,+ GuestsChecked: 3,+ DockerChecked: 1,+ StorageChecked: 4,+ HostsChecked: 5,+ TrueNASChecked: 1,+ KubernetesChecked: 6,+ },+ want: "2 nodes; 3 VMs; 1 containers; 4 storage resources; 5 agents; 1 TrueNAS systems; 6 Kubernetes resources",+ },+ {+ // Subtle fall-through: scope is populated but resourcesChecked+ // is 0, so neither scoped inner-if fires and the breakdown join+ // is returned instead. Scoped zero-checked runs do NOT report+ // "Checked 0 of N"; see report for the source observation.+ name: "scoped_zero_checked_falls_through_to_breakdown",+ run: PatrolRunRecord{+ EffectiveScopeResourceIDs: []string{"a", "b"},+ ResourcesChecked: 0,+ NodesChecked: 1,+ },+ want: "1 nodes",+ },+ {+ // Negative ResourcesChecked is clamped to 0 via max(); with no+ // breakdown it yields the empty join.+ name: "negative_resources_checked_clamped_to_zero",+ run: PatrolRunRecord{+ ResourcesChecked: -5,+ },+ want: "",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := patrolRunCoverageSummary(tc.run)+ if got != tc.want {+ t.Fatalf("patrolRunCoverageSummary = %q, want %q", got, tc.want)+ }+ })+ }+}diff --git a/internal/ai/tools/tools_norm_branchcov0725am_test.go b/internal/ai/tools/tools_norm_branchcov0725am_test.gonew file mode 100644index 0000000000..86010daf52--- /dev/null+++ b/internal/ai/tools/tools_norm_branchcov0725am_test.go@@ -0,0 +1,621 @@+package tools++import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// This file raises measured branch coverage for three previously+// partially-covered functions in internal/ai/tools:+// - summarizeReportTypeForResource (tools_summarize.go) — pure switch over+// unified ResourceType; every mapped type plus the agent sub-classification+// and the unknown/default arm.+// - normalizeDiscoveryResourceRequest (tools_discovery.go) — arg normalisation+// with many distinct rejection reasons plus the accepting (success) path.+// - validateRoutingContext (tools_query.go) — routing-mismatch guard with one+// case per distinct early-return reason plus the blocking (accepting) case.+//+// It reuses the existing in-package fakes `mockResolvedContext` and `mockResource`+// (strict_resolution_test.go) and `stubDiscoveryProvider` (tools_discovery_test.go),+// and adds two small fakes below: a minimal unifiedresources.ReadState and a+// TelemetryCallback recorder.++// branchcov0725amReadState is a minimal ReadState whose only populated buckets+// are the Proxmox node/vm/container views that resolveResourceLocation and+// findRecentlyReferencedChildrenOnNode walk. Every other accessor returns nil,+// which is the documented empty-state contract.+type branchcov0725amReadState struct {+ nodes []*unifiedresources.NodeView+ vms []*unifiedresources.VMView+ containers []*unifiedresources.ContainerView+ hosts []*unifiedresources.HostView+}++func (f *branchcov0725amReadState) Nodes() []*unifiedresources.NodeView { return f.nodes }+func (f *branchcov0725amReadState) VMs() []*unifiedresources.VMView { return f.vms }+func (f *branchcov0725amReadState) Containers() []*unifiedresources.ContainerView {+ return f.containers+}+func (f *branchcov0725amReadState) Hosts() []*unifiedresources.HostView { return f.hosts }++func (f *branchcov0725amReadState) DockerHosts() []*unifiedresources.DockerHostView {+ return nil+}+func (f *branchcov0725amReadState) DockerContainers() []*unifiedresources.DockerContainerView {+ return nil+}+func (f *branchcov0725amReadState) StoragePools() []*unifiedresources.StoragePoolView {+ return nil+}+func (f *branchcov0725amReadState) PhysicalDisks() []*unifiedresources.PhysicalDiskView {+ return nil+}+func (f *branchcov0725amReadState) PBSInstances() []*unifiedresources.PBSInstanceView {+ return nil+}+func (f *branchcov0725amReadState) PMGInstances() []*unifiedresources.PMGInstanceView {+ return nil+}+func (f *branchcov0725amReadState) K8sClusters() []*unifiedresources.K8sClusterView { return nil }+func (f *branchcov0725amReadState) K8sNodes() []*unifiedresources.K8sNodeView { return nil }+func (f *branchcov0725amReadState) Pods() []*unifiedresources.PodView { return nil }+func (f *branchcov0725amReadState) K8sDeployments() []*unifiedresources.K8sDeploymentView {+ return nil+}+func (f *branchcov0725amReadState) Workloads() []*unifiedresources.WorkloadView {+ return nil+}+func (f *branchcov0725amReadState) Infrastructure() []*unifiedresources.InfrastructureView {+ return nil+}++// branchcov0725amTelemetry records the routing-mismatch telemetry call so the+// test can assert the real function invoked it with the expected labels.+type branchcov0725amTelemetry struct {+ routingMismatchCalls int+ lastTool string+ lastTargetKind string+ lastChildKind string+}++func (t *branchcov0725amTelemetry) RecordStrictResolutionBlock(_, _ string) {}+func (t *branchcov0725amTelemetry) RecordAutoRecoveryAttempt(_, _ string) {}+func (t *branchcov0725amTelemetry) RecordAutoRecoverySuccess(_, _ string) {}+func (t *branchcov0725amTelemetry) RecordRoutingMismatchBlock(tool, targetKind, childKind string) {+ t.routingMismatchCalls+++ t.lastTool = tool+ t.lastTargetKind = targetKind+ t.lastChildKind = childKind+}++// ---------------------------------------------------------------------------+// summarizeReportTypeForResource (tools_summarize.go:292)+//+// Pure switch over CanonicalResourceType(res.Type). The agent arm further+// classifies by the richest populated host payload (Agent -> "agent",+// Proxmox -> "node", Docker -> "docker-host", default -> "agent"). Every+// other mapped type returns a fixed string; unknown types return "".+// ---------------------------------------------------------------------------++func TestBranchcov0725amSummarizeReportTypeForResource(t *testing.T) {+ cases := []struct {+ name string+ res unifiedresources.Resource+ want string+ }{+ // --- ResourceTypeAgent: inner precedence switch, each arm. ---+ {+ name: "agent_with_agent_payload",+ res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent, Agent: &unifiedresources.AgentData{}},+ want: "agent",+ },+ {+ name: "agent_with_proxmox_payload_maps_to_node",+ res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent, Proxmox: &unifiedresources.ProxmoxData{}},+ want: "node",+ },+ {+ name: "agent_with_docker_payload_maps_to_docker_host",+ res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent, Docker: &unifiedresources.DockerData{}},+ want: "docker-host",+ },+ {+ name: "agent_with_no_host_payload_defaults_to_agent",+ res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent},+ want: "agent",+ },+ // Precedence is first-match: Agent beats Proxmox beats Docker.+ {+ name: "agent_with_agent_and_proxmex_picks_agent",+ res: unifiedresources.Resource{+ Type: unifiedresources.ResourceTypeAgent,+ Agent: &unifiedresources.AgentData{},+ Proxmox: &unifiedresources.ProxmoxData{},+ },+ want: "agent",+ },+ {+ name: "agent_with_proxmox_and_docker_picks_node",+ res: unifiedresources.Resource{+ Type: unifiedresources.ResourceTypeAgent,+ Proxmox: &unifiedresources.ProxmoxData{},+ Docker: &unifiedresources.DockerData{},+ },+ want: "node",+ },++ // --- Direct canonical-type arms (each maps to a fixed report type). ---+ {name: "vm", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeVM}, want: "vm"},+ {name: "system_container", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeSystemContainer}, want: "system-container"},+ {name: "app_container", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAppContainer}, want: "app-container"},+ {name: "k8s_cluster", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeK8sCluster}, want: "k8s"},+ {name: "storage", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypeStorage}, want: "storage"},+ {name: "pbs", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypePBS}, want: "pbs"},+ {name: "pmg", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypePMG}, want: "pmg"},+ {name: "physical_disk_maps_to_disk", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypePhysicalDisk}, want: "disk"},+ {name: "pod", res: unifiedresources.Resource{Type: unifiedresources.ResourceTypePod}, want: "pod"},++ // --- default arm: unknown / empty types return "". ---+ {name: "unknown_type_returns_empty", res: unifiedresources.Resource{Type: unifiedresources.ResourceType("widget")}, want: ""},+ {name: "empty_type_returns_empty", res: unifiedresources.Resource{Type: ""}, want: ""},++ // CanonicalResourceType normalises whitespace + case before the switch.+ {name: "padded_upper_vm_normalises", res: unifiedresources.Resource{Type: unifiedresources.ResourceType(" VM ")}, want: "vm"},+ {name: "padded_upper_agent_with_proxmex_normalises", res: unifiedresources.Resource{Type: unifiedresources.ResourceType(" Agent "), Proxmox: &unifiedresources.ProxmoxData{}}, want: "node"},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := summarizeReportTypeForResource(tc.res)+ assert.Equal(t, tc.want, got, "summarizeReportTypeForResource mismatch")+ })+ }+}++// ---------------------------------------------------------------------------+// normalizeDiscoveryResourceRequest (tools_discovery.go:242)+//+// The function implements a chain of distinct rejection reasons followed by+// the accepting (success) path. The table below drives every distinct error+// message and every success shape, asserting on the concrete error text, the+// ok flag, and the returned request struct (including the computed cliAccess).+// ---------------------------------------------------------------------------++func TestBranchcov0725amNormalizeDiscoveryResourceRequest_Rejections(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})++ cases := []struct {+ name string+ args map[string]interface{}+ wantOK bool+ wantErrHas string // substring expected in blocked.Content[0].Text+ wantErrIsEr bool+ }{+ // nil args: every type assertion on a nil map yields "".+ {name: "nil_args_resource_type_required", args: nil, wantOK: false, wantErrHas: "resource_type is required", wantErrIsEr: true},+ // Empty map: no keys at all.+ {name: "empty_map_resource_type_required", args: map[string]interface{}{}, wantOK: false, wantErrHas: "resource_type is required", wantErrIsEr: true},+ // Whitespace-only resource_type: CanonicalDiscoveryResourceType trims to "".+ {name: "whitespace_resource_type_required", args: map[string]interface{}{"resource_type": " ", "resource_id": "1", "target_id": "n1"}, wantOK: false, wantErrHas: "resource_type is required", wantErrIsEr: true},+ // Legacy "docker" token: duplicate spelling of app-container, explicitly unsupported here.+ {name: "legacy_docker_token_unsupported", args: map[string]interface{}{"resource_type": "docker", "resource_id": "c1", "target_id": "a1"}, wantOK: false, wantErrHas: "unsupported resource_type", wantErrIsEr: true},+ // Non-legacy but unsupported canonical type (passes the legacy check, fails isSupportedDiscoveryResourceType).+ {name: "k8s_cluster_unsupported", args: map[string]interface{}{"resource_type": "k8s-cluster", "resource_id": "1", "target_id": "n1"}, wantOK: false, wantErrHas: "unsupported resource_type", wantErrIsEr: true},+ // Valid type, missing resource_id.+ {name: "empty_resource_id_required", args: map[string]interface{}{"resource_type": "vm", "target_id": "n1"}, wantOK: false, wantErrHas: "resource_id is required", wantErrIsEr: true},+ // NOTE: resource_id is NOT trimmed before the required-check (unlike+ // target_id). A whitespace-only id passes that check, fails strconv.Atoi,+ // and falls through to the name-resolution branch, surfacing the+ // "could not resolve resource name" error instead. This case pins that+ // real behaviour; see the report for the trimming inconsistency.+ {name: "whitespace_resource_id_falls_through_to_name_resolution", args: map[string]interface{}{"resource_type": "vm", "resource_id": "\t ", "target_id": "n1"}, wantOK: false, wantErrHas: "could not resolve resource name", wantErrIsEr: true},+ // Valid type + id, missing target_id.+ {name: "empty_target_id_required", args: map[string]interface{}{"resource_type": "vm", "resource_id": "101"}, wantOK: false, wantErrHas: "target_id is required", wantErrIsEr: true},+ {name: "whitespace_target_id_required", args: map[string]interface{}{"resource_type": "vm", "resource_id": "101", "target_id": " "}, wantOK: false, wantErrHas: "target_id is required", wantErrIsEr: true},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ _, blocked, ok := exec.normalizeDiscoveryResourceRequest(tc.args)+ require.Equal(t, tc.wantOK, ok, "ok flag")+ require.True(t, blocked.IsError, "expected an error result for a rejection")+ require.Len(t, blocked.Content, 1, "expected exactly one content block")+ assert.Contains(t, blocked.Content[0].Text, tc.wantErrHas, "error message substring")+ })+ }+}++func TestBranchcov0725amNormalizeDiscoveryResourceRequest_ProviderNil(t *testing.T) {+ // discoveryProvider == nil short-circuits with a friendly text result (not IsError).+ exec := NewPulseToolExecutor(ExecutorConfig{})+ _, blocked, ok := exec.normalizeDiscoveryResourceRequest(map[string]interface{}{+ "resource_type": "vm", "resource_id": "1", "target_id": "n1",+ })+ require.False(t, ok)+ require.False(t, blocked.IsError, "the nil-provider message is advisory text, not an error")+ require.Len(t, blocked.Content, 1)+ assert.Contains(t, blocked.Content[0].Text, "Discovery service not available.")+}++func TestBranchcov0725amNormalizeDiscoveryResourceRequest_CurrentResourceNoContext(t *testing.T) {+ // A current_resource handle in any identity field forces resolveCurrentResource;+ // with no resolved context attached it must surface that specific error.+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})+ _, blocked, ok := exec.normalizeDiscoveryResourceRequest(map[string]interface{}{+ "resource_type": "current_resource",+ "resource_id": "1",+ "target_id": "n1",+ })+ require.False(t, ok)+ require.True(t, blocked.IsError)+ require.Len(t, blocked.Content, 1)+ assert.Contains(t, blocked.Content[0].Text, "current_resource")+}++func TestBranchcov0725amNormalizeDiscoveryResourceRequest_CurrentResourceResolved(t *testing.T) {+ // The accepting arm of the current_resource branch: an attached context+ // resolves the handle to canonical vm coordinates, which then flow through+ // the normal success path.+ res := &mockResource{+ resourceID: "vm:101",+ resourceType: "vm",+ kind: "vm",+ providerUID: "101",+ targetHost: "pve1",+ node: "pve1",+ }+ ctx := &mockResolvedContext{+ resources: map[string]ResolvedResourceInfo{"vm:101": res},+ aliases: map[string]ResolvedResourceInfo{"vm:101": res},+ }+ ctx.MarkExplicitAccess("vm:101")++ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})+ exec.SetResolvedContext(ctx)++ req, blocked, ok := exec.normalizeDiscoveryResourceRequest(map[string]interface{}{+ "resource_type": "current_resource",+ })+ require.True(t, ok, "expected success after resolving current_resource")+ require.False(t, blocked.IsError)+ assert.Equal(t, "vm", req.resourceType)+ assert.Equal(t, "101", req.resourceID)+ assert.Equal(t, "pve1", req.targetID)+}++func TestBranchcov0725amNormalizeDiscoveryResourceRequest_SuccessCanonical(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})++ cases := []struct {+ name string+ args map[string]interface{}+ want discoveryResourceRequest+ }{+ // agent: cliAccess uses targetID as the agent id.+ {+ name: "agent_numeric_success",+ args: map[string]interface{}{"resource_type": "agent", "resource_id": "host-1", "target_id": "node-a"},+ want: discoveryResourceRequest{+ resourceType: "agent",+ providerResourceType: "agent",+ resourceID: "host-1",+ targetID: "node-a",+ cliAccess: "Agent 'node-a'",+ },+ },+ // vm with a numeric VMID: no name resolution needed.+ {+ name: "vm_numeric_vmid_success",+ args: map[string]interface{}{"resource_type": "vm", "resource_id": "101", "target_id": "pve1"},+ want: discoveryResourceRequest{+ resourceType: "vm",+ providerResourceType: "vm",+ resourceID: "101",+ targetID: "pve1",+ cliAccess: "VM on node 'pve1' (VMID 101)",+ },+ },+ // system-container with a numeric VMID.+ {+ name: "system_container_numeric_vmid_success",+ args: map[string]interface{}{"resource_type": "system-container", "resource_id": "200", "target_id": "pve1"},+ want: discoveryResourceRequest{+ resourceType: "system-container",+ providerResourceType: "system-container",+ resourceID: "200",+ targetID: "pve1",+ cliAccess: "System container on node 'pve1' (VMID 200)",+ },+ },+ // Canonical app-container (provider type flips to "docker"); nil provider+ // means findCanonicalAppContainerResource is a no-op, so the id passes through.+ {+ name: "app_container_canonical_success",+ args: map[string]interface{}{"resource_type": "app-container", "resource_id": "cid1", "target_id": "agent-1"},+ want: discoveryResourceRequest{+ resourceType: "app-container",+ providerResourceType: "docker",+ resourceID: "cid1",+ targetID: "agent-1",+ cliAccess: "Docker container 'cid1' on target 'agent-1'",+ },+ },+ // Surrounding whitespace/case is canonicalised on every field; the+ // target_id is trimmed before the required-check.+ {+ name: "whitespace_and_case_canonicalised",+ args: map[string]interface{}{"resource_type": " VM ", "resource_id": "303", "target_id": " Pve1 "},+ want: discoveryResourceRequest{+ resourceType: "vm",+ providerResourceType: "vm",+ resourceID: "303",+ targetID: "Pve1",+ cliAccess: "VM on node 'Pve1' (VMID 303)",+ },+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ req, blocked, ok := exec.normalizeDiscoveryResourceRequest(tc.args)+ require.True(t, ok, "expected success; got error result %q", blockedText(blocked))+ require.False(t, blocked.IsError, "expected a clean (non-error) result on success")+ assert.Equal(t, tc.want, req, "normalised request struct")+ })+ }+}++// TestBranchcov0725amNormalizeDiscoveryResourceRequest_NameToVMIDResolution+// drives the system-container/vm name->VMID resolution branch (the strconv.Atoi+// failure path inside the function). A typed name on the matching node resolves+// to its VMID; the same name on a mismatched node, or an absent name, surfaces+// the specific "could not resolve resource name" error.+func TestBranchcov0725amNormalizeDiscoveryResourceRequest_NameToVMIDResolution(t *testing.T) {+ ct := unifiedresources.NewContainerView(&unifiedresources.Resource{+ Name: "myct", Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1", VMID: 200},+ })+ vm := unifiedresources.NewVMView(&unifiedresources.Resource{+ Name: "myvm", Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1", VMID: 101},+ })+ vmOtherNode := unifiedresources.NewVMView(&unifiedresources.Resource{+ Name: "offnode", Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve2", VMID: 999},+ })+ rs := &branchcov0725amReadState{+ vms: []*unifiedresources.VMView{&vm, &vmOtherNode},+ containers: []*unifiedresources.ContainerView{&ct},+ }++ t.Run("system_container_name_resolves_to_vmid", func(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})+ exec.readState = rs+ req, blocked, ok := exec.normalizeDiscoveryResourceRequest(map[string]interface{}{+ "resource_type": "system-container", "resource_id": "myct", "target_id": "pve1",+ })+ require.True(t, ok, blockedText(blocked))+ assert.Equal(t, "system-container", req.resourceType)+ assert.Equal(t, "200", req.resourceID, "name should resolve to VMID")+ assert.Equal(t, "pve1", req.targetID)+ })++ t.Run("vm_name_resolves_to_vmid", func(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})+ exec.readState = rs+ req, blocked, ok := exec.normalizeDiscoveryResourceRequest(map[string]interface{}{+ "resource_type": "vm", "resource_id": "myvm", "target_id": "pve1",+ })+ require.True(t, ok, blockedText(blocked))+ assert.Equal(t, "101", req.resourceID, "name should resolve to VMID")+ })++ t.Run("vm_name_on_wrong_node_not_resolved", func(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})+ exec.readState = rs+ _, blocked, ok := exec.normalizeDiscoveryResourceRequest(map[string]interface{}{+ "resource_type": "vm", "resource_id": "offnode", "target_id": "pve1",+ })+ require.False(t, ok)+ require.True(t, blocked.IsError)+ assert.Contains(t, blocked.Content[0].Text, "could not resolve resource name 'offnode' to a VMID on target 'pve1'")+ })++ t.Run("vm_name_absent_not_resolved", func(t *testing.T) {+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})+ exec.readState = rs+ _, blocked, ok := exec.normalizeDiscoveryResourceRequest(map[string]interface{}{+ "resource_type": "vm", "resource_id": "ghost", "target_id": "pve1",+ })+ require.False(t, ok)+ require.True(t, blocked.IsError)+ assert.Contains(t, blocked.Content[0].Text, "could not resolve resource name 'ghost' to a VMID on target 'pve1'")+ })+}++// blockedText returns the text payload of a CallToolResult for diagnostic+// assertion messages, or "<no content>" when empty.+func blockedText(r CallToolResult) string {+ if len(r.Content) == 0 {+ return "<no content>"+ }+ return r.Content[0].Text+}++// ---------------------------------------------------------------------------+// validateRoutingContext (tools_query.go:1985)+//+// One case per distinct early-return (not-blocked) reason, plus the accepting+// (blocking) case that returns an ErrRoutingMismatch. Each not-blocked case+// asserts IsBlocked()==false; the block case asserts the exact mismatch fields+// and that telemetry was recorded.+// ---------------------------------------------------------------------------++func TestBranchcov0725amValidateRoutingContext_NotBlocked(t *testing.T) {+ // Shared read state with one node "pve1", one container on pve1, one vm on pve1.+ pve1 := unifiedresources.NewNodeView(&unifiedresources.Resource{+ Name: "pve1", Type: unifiedresources.ResourceTypeAgent, Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1"},+ })+ jellyfinCT := unifiedresources.NewContainerView(&unifiedresources.Resource{+ Name: "jellyfin", Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1", VMID: 100},+ })+ winVM := unifiedresources.NewVMView(&unifiedresources.Resource{+ Name: "win10", Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1", VMID: 200},+ })+ rs := &branchcov0725amReadState{+ nodes: []*unifiedresources.NodeView{&pve1},+ containers: []*unifiedresources.ContainerView{&jellyfinCT},+ vms: []*unifiedresources.VMView{&winVM},+ }++ // A child that exists on pve1 but is NOT recently accessed (drives the+ // WasRecentlyAccessed==false arm inside findRecentlyReferencedChildrenOnNode).+ staleChild := &mockResource{+ resourceID: "system-container:100", resourceType: "system-container",+ kind: "system-container", providerUID: "100", node: "pve1",+ }+ staleCtx := &mockResolvedContext{+ resources: map[string]ResolvedResourceInfo{"system-container:100": staleChild},+ aliases: map[string]ResolvedResourceInfo{"jellyfin": staleChild, "system-container:100": staleChild},+ // lastAccessed deliberately nil: not recently accessed.+ }++ // A direct-alias target so GetResolvedResourceByAlias hits on the first lookup.+ directHost := &mockResource{resourceID: "agent:delly", kind: "agent"}+ directCtx := &mockResolvedContext{+ aliases: map[string]ResolvedResourceInfo{"delly": directHost},+ }++ cases := []struct {+ name string+ exec *PulseToolExecutor+ targetHost string+ }{+ {+ // Arm: !hasReadState() — no read state provider wired at all, so the+ // very first guard returns not-blocked regardless of context.+ name: "no_read_state_not_blocked",+ exec: &PulseToolExecutor{resolvedContext: staleCtx},+ targetHost: "pve1",+ },+ {+ // Arm: hasReadState() true but resolvedContext == nil.+ name: "nil_resolved_context_not_blocked",+ exec: &PulseToolExecutor{readState: rs},+ targetHost: "pve1",+ },+ {+ // Arm: targetHost resolves directly to a resource alias -> no mismatch.+ name: "direct_alias_match_not_blocked",+ exec: &PulseToolExecutor{readState: rs, resolvedContext: directCtx},+ targetHost: "delly",+ },+ {+ // Arm: resolveResourceLocation can't find the target -> !loc.Found.+ name: "location_not_found_not_blocked",+ exec: &PulseToolExecutor{readState: rs, resolvedContext: staleCtx},+ targetHost: "does-not-exist",+ },+ {+ // Arm: loc.Found but ResourceType != "node" (here a vm). Note "win10"+ // is intentionally absent from aliases so the direct-lookup is skipped.+ name: "location_found_but_not_node_not_blocked",+ exec: &PulseToolExecutor{readState: rs, resolvedContext: staleCtx},+ targetHost: "win10",+ },+ {+ // Arm: target is a node, a child exists on it, but the child was NOT+ // recently accessed -> len(recentChildren)==0.+ name: "node_no_recent_children_not_blocked",+ exec: &PulseToolExecutor{readState: rs, resolvedContext: staleCtx},+ targetHost: "pve1",+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ res := tc.exec.validateRoutingContext(tc.targetHost)+ assert.False(t, res.IsBlocked(), "this arm must not block")+ assert.Nil(t, res.RoutingError)+ })+ }+}++func TestBranchcov0725amValidateRoutingContext_BlocksSystemContainer(t *testing.T) {+ // Accepting case: target is a Proxmox node and a system-container child on+ // that node was recently referenced -> block with an ErrRoutingMismatch whose+ // fields name the offending child, and fire the telemetry callback.+ pve1 := unifiedresources.NewNodeView(&unifiedresources.Resource{+ Name: "pve1", Type: unifiedresources.ResourceTypeAgent, Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1"},+ })+ jellyfinCT := unifiedresources.NewContainerView(&unifiedresources.Resource{+ Name: "jellyfin", Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1", VMID: 100},+ })+ rs := &branchcov0725amReadState{+ nodes: []*unifiedresources.NodeView{&pve1},+ containers: []*unifiedresources.ContainerView{&jellyfinCT},+ }++ child := &mockResource{+ resourceID: "system-container:100", resourceType: "system-container",+ kind: "system-container", providerUID: "100", node: "pve1",+ }+ ctx := &mockResolvedContext{+ resources: map[string]ResolvedResourceInfo{"system-container:100": child},+ aliases: map[string]ResolvedResourceInfo{"jellyfin": child, "system-container:100": child},+ }+ ctx.MarkExplicitAccess("system-container:100")++ telemetry := &branchcov0725amTelemetry{}+ exec := &PulseToolExecutor{readState: rs, resolvedContext: ctx, telemetryCallback: telemetry}++ res := exec.validateRoutingContext("pve1")++ require.True(t, res.IsBlocked(), "expected the routing mismatch to block")+ require.NotNil(t, res.RoutingError)+ mm := res.RoutingError+ assert.Equal(t, "pve1", mm.TargetHost)+ assert.Equal(t, []string{"jellyfin"}, mm.MoreSpecificResources)+ assert.Equal(t, []string{"system-container:100"}, mm.MoreSpecificIDs)+ assert.Equal(t, []string{"system-container"}, mm.ChildKinds)+ assert.Contains(t, mm.Message, "target_host 'pve1' is a hypervisor node")+ assert.Contains(t, mm.Message, "jellyfin")+ assert.Equal(t, "routing_validation", telemetry.lastTool)+ assert.Equal(t, "node", telemetry.lastTargetKind)+ assert.Equal(t, "system-container", telemetry.lastChildKind)+ assert.Equal(t, 1, telemetry.routingMismatchCalls)+}++func TestBranchcov0725amValidateRoutingContext_BlocksVMChildWithoutTelemetry(t *testing.T) {+ // Drives the VM iteration arm of findRecentlyReferencedChildrenOnNode and the+ // telemetryCallback==nil arm of the block path: the block still fires, the+ // vm kind propagates into ChildKinds, and no telemetry is recorded.+ pve1 := unifiedresources.NewNodeView(&unifiedresources.Resource{+ Name: "pve1", Type: unifiedresources.ResourceTypeAgent, Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1"},+ })+ winVM := unifiedresources.NewVMView(&unifiedresources.Resource{+ Name: "win10", Proxmox: &unifiedresources.ProxmoxData{NodeName: "pve1", VMID: 200},+ })+ rs := &branchcov0725amReadState{+ nodes: []*unifiedresources.NodeView{&pve1},+ vms: []*unifiedresources.VMView{&winVM},+ }++ child := &mockResource{+ resourceID: "vm:200", resourceType: "vm", kind: "vm", providerUID: "200", node: "pve1",+ }+ ctx := &mockResolvedContext{+ resources: map[string]ResolvedResourceInfo{"vm:200": child},+ aliases: map[string]ResolvedResourceInfo{"win10": child, "vm:200": child},+ }+ ctx.MarkExplicitAccess("vm:200")++ exec := &PulseToolExecutor{readState: rs, resolvedContext: ctx}+ res := exec.validateRoutingContext("pve1")++ require.True(t, res.IsBlocked())+ require.NotNil(t, res.RoutingError)+ assert.Equal(t, []string{"win10"}, res.RoutingError.MoreSpecificResources)+ assert.Equal(t, []string{"vm"}, res.RoutingError.ChildKinds)+ assert.Equal(t, ErrCodeRoutingMismatch, res.RoutingError.Code())+}