Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Add branch-coverage tests for action-audit, monitoring and onboarding clients

rcourtmaned82d6cd87d6
diff --git a/frontend-modern/src/api/__tests__/actionAudit.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/actionAudit.branchcov0718.test.ts
new file mode 100644
index 0000000000..677fccee6e
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/actionAudit.branchcov0718.test.ts
@@ -0,0 +1,186 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+import { ActionAuditAPI } from '@/api/actionAudit';
+import { apiFetchJSON } from '@/utils/apiClient';
+import type { ActionAuditRecord, ActionVerificationResult } from '@/types/actionAudit';
+
+const baseAudit: ActionAuditRecord = {
+ id: 'action-1',
+ createdAt: '2026-04-29T12:00:00Z',
+ updatedAt: '2026-04-29T12:01:00Z',
+ state: 'completed',
+ request: {
+ requestId: 'req-1',
+ resourceId: 'vm:42',
+ capabilityName: 'restart',
+ reason: 'Restart after patching',
+ requestedBy: 'agent:ops',
+ },
+ plan: {
+ actionId: 'action-1',
+ requestId: 'req-1',
+ allowed: true,
+ requiresApproval: true,
+ approvalPolicy: 'admin',
+ rollbackAvailable: true,
+ },
+};
+
+describe('ActionAuditAPI listActionAudits branch coverage', () => {
+ const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+
+ beforeEach(() => {
+ apiFetchJSONMock.mockReset();
+ });
+
+ // Covers:
+ // - buildActionAuditQuery() empty-query arm (`return query ? \`?${query}\` : ''`)
+ // - normalizeSince undefined arm (first `||` clause short-circuits)
+ // - normalizeLimit undefined arm (not finite)
+ // - normalizeActionAuditListResponse count-absent arm (count -> audits.length)
+ // - normalizeActionAuditListResponse resourceId-absent + no fallback arm
+ it('omits the query string entirely when no filter options are given and derives count from audits.length', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ audits: [baseAudit, { ...baseAudit, id: 'action-2' }],
+ });
+
+ const result = await ActionAuditAPI.listActionAudits();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/audit/actions', {
+ cache: 'no-store',
+ });
+ expect(result.available).toBe(true);
+ expect(result.count).toBe(2);
+ expect(result.resourceId).toBeUndefined();
+ expect(result.audits).toHaveLength(2);
+ });
+
+ // Covers normalizeSince `since instanceof Date` true arm (uses the Date directly
+ // instead of constructing `new Date(since)`).
+ it('encodes a Date instance since filter into an ISO query parameter', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ audits: [], count: 0 });
+
+ await ActionAuditAPI.listActionAudits({
+ since: new Date('2026-04-29T11:00:00Z'),
+ });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/audit/actions?since=2026-04-29T11%3A00%3A00.000Z',
+ { cache: 'no-store' },
+ );
+ });
+
+ // Covers:
+ // - normalizeSince ``${since}`.trim() === ''` true arm (empty-string since dropped)
+ // - normalizeLimit `(limit ?? 0) <= 0` arm (limit=0 dropped)
+ it('drops an empty-string since and a zero limit, leaving only the trimmed resourceId in the query', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ audits: [], count: 0, resourceId: 'vm:42' });
+
+ await ActionAuditAPI.listActionAudits({
+ resourceId: 'vm:42',
+ since: '',
+ limit: 0,
+ });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/audit/actions?resourceId=vm%3A42',
+ { cache: 'no-store' },
+ );
+ });
+
+ // Covers normalizeSince invalid-date arm:
+ // `Number.isFinite(date.getTime()) ? date.toISOString() : undefined` false branch.
+ it('drops a non-parseable since string from the query instead of emitting an Invalid Date', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ audits: [], count: 0 });
+
+ await ActionAuditAPI.listActionAudits({ since: 'not-a-real-date' });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/audit/actions', {
+ cache: 'no-store',
+ });
+ });
+
+ // Covers normalizeLimit Math.trunc arm (`return Math.trunc(limit ?? 0)`).
+ it('truncates a positive fractional limit when building the query', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ audits: [], count: 0 });
+
+ await ActionAuditAPI.listActionAudits({ limit: 4.9 });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/audit/actions?limit=4', {
+ cache: 'no-store',
+ });
+ });
+
+ // Covers normalizeActionAuditListResponse fallbackResourceId arm:
+ // when raw.resourceId is absent/blank, fall back to the trimmed caller-supplied resourceId.
+ it('falls back to the trimmed input resourceId when the response omits resourceId', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ audits: [baseAudit],
+ count: 1,
+ });
+
+ const result = await ActionAuditAPI.listActionAudits({ resourceId: ' vm:42 ' });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/audit/actions?resourceId=vm%3A42',
+ { cache: 'no-store' },
+ );
+ expect(result.resourceId).toBe('vm:42');
+ });
+
+ // Covers normalizeActionAuditRecord no-result arm:
+ // verification present at top level but `audit.result` is undefined -> the
+ // `audit.result ? {...} : audit.result` ternary takes the false branch.
+ it('promotes a top-level verification onto an audit that has no result block, leaving result undefined', async () => {
+ const verification: ActionVerificationResult = {
+ ran: true,
+ success: true,
+ command: "systemctl is-active 'workload'",
+ output: 'active',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce({
+ audits: [
+ {
+ ...baseAudit,
+ id: 'action-verify-noresult',
+ verification,
+ },
+ ],
+ count: 1,
+ });
+
+ const result = await ActionAuditAPI.listActionAudits({ resourceId: 'vm:42' });
+
+ expect(result.audits).toHaveLength(1);
+ expect(result.audits[0].verification).toEqual(verification);
+ expect(result.audits[0].result).toBeUndefined();
+ });
+
+ // Covers the catch block in listActionAudits:
+ // - 401 and 403 share the unavailable arm with the already-covered 402
+ // - a status outside ACTION_AUDIT_UNAVAILABLE_STATUSES (500) takes the rethrow arm.
+ it('treats 401 and 403 as unavailable but rethrows a 500', async () => {
+ apiFetchJSONMock
+ .mockRejectedValueOnce(Object.assign(new Error('Unauthorized'), { status: 401 }))
+ .mockRejectedValueOnce(Object.assign(new Error('Forbidden'), { status: 403 }))
+ .mockRejectedValueOnce(Object.assign(new Error('Boom'), { status: 500 }));
+
+ await expect(ActionAuditAPI.listActionAudits({ resourceId: 'vm:42' })).resolves.toEqual({
+ audits: [],
+ available: false,
+ count: 0,
+ resourceId: 'vm:42',
+ });
+ await expect(ActionAuditAPI.listActionAudits({ resourceId: 'vm:42' })).resolves.toEqual({
+ audits: [],
+ available: false,
+ count: 0,
+ resourceId: 'vm:42',
+ });
+ await expect(ActionAuditAPI.listActionAudits({ resourceId: 'vm:42' })).rejects.toThrow('Boom');
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/monitoring.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/monitoring.branchcov0718.test.ts
new file mode 100644
index 0000000000..7261a44cd8
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/monitoring.branchcov0718.test.ts
@@ -0,0 +1,203 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { MonitoringAPI } from '../monitoring';
+import { apiFetch } from '@/utils/apiClient';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetch: vi.fn(),
+ apiFetchJSON: vi.fn(),
+}));
+
+describe('MonitoringAPI branch coverage (optional query params / empty-input guards / null-shape arms)', () => {
+ const fetchMock = vi.mocked(apiFetch);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('deleteDockerRuntime — query-string assembly branches', () => {
+ it('joins both hide and force flags in insertion order when both are present', async () => {
+ // Exercises the combined branch where BOTH `if (options.hide)` and
+ // `if (options.force)` arms fire. URLSearchParams iterates in insertion
+ // order, so the on-the-wire query is `hide=true&force=true` (not the
+ // reverse) and the `?` prefix is appended because `query` is non-empty.
+ fetchMock.mockResolvedValueOnce({ ok: true, status: 204 } as unknown as Response);
+
+ const result = await MonitoringAPI.deleteDockerRuntime('agent-1', {
+ hide: true,
+ force: true,
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/agents/docker/runtimes/agent-1?hide=true&force=true',
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ // 204 is in the allowed-status set ([204, 404]) -> empty default payload.
+ expect(result).toEqual({});
+ });
+
+ it('applies encodeURIComponent to agentIds containing path/space characters', async () => {
+ // Exercises the encodeURIComponent branch on the path segment: a raw `/`
+ // would otherwise be interpreted as a path separator and a raw space
+ // would break the URL, so both must be percent-encoded.
+ fetchMock.mockResolvedValueOnce({ ok: true, status: 204 } as unknown as Response);
+
+ await MonitoringAPI.deleteDockerRuntime('agent/with space');
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/agents/docker/runtimes/agent%2Fwith%20space',
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ });
+
+ it('omits the query string entirely when options is the explicit empty object', async () => {
+ // Exercises the falsy-query arm of `query ? \`?${query}\` : ''` — passing
+ // an explicit `{}` produces an empty URLSearchParams and the URL must
+ // have no trailing `?`. (Distinct from the default-undefined call already
+ // covered in monitoring.test.ts.)
+ fetchMock.mockResolvedValueOnce({ ok: true, status: 204 } as unknown as Response);
+
+ await MonitoringAPI.deleteDockerRuntime('agent-1', {});
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/agents/docker/runtimes/agent-1',
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ });
+ });
+
+ describe('lookupAgent — query-param / null-shape branches', () => {
+ it('builds a hostname-only query string when only hostname is supplied', async () => {
+ // Exercises the `if (params.hostname)` arm in isolation (id arm untaken)
+ // and confirms the resulting URL carries `?hostname=...` with no `id=`.
+ fetchMock.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ success: true,
+ agent: {
+ id: 'agent-h',
+ hostname: 'host.local',
+ status: 'online',
+ connected: true,
+ lastSeen: '2026-02-03T04:05:06Z',
+ },
+ }),
+ { status: 200 },
+ ),
+ );
+
+ const result = await MonitoringAPI.lookupAgent({ hostname: 'host.local' });
+
+ expect(fetchMock).toHaveBeenCalledWith('/api/agents/agent/lookup?hostname=host.local');
+ expect(result?.agent?.id).toBe('agent-h');
+ // coerceTimestampMillis parses the ISO string into epoch millis.
+ expect(result?.agent?.lastSeen).toBe(Date.parse('2026-02-03T04:05:06Z'));
+ });
+
+ it('joins id and hostname in insertion order when both are supplied', async () => {
+ // Exercises BOTH `if (params.id)` and `if (params.hostname)` arms together.
+ // Insertion order is id-first, so the query is `id=...&hostname=...`.
+ fetchMock.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ success: true,
+ agent: {
+ id: 'agent-1',
+ hostname: 'host.local',
+ status: 'online',
+ connected: true,
+ lastSeen: '2026-02-03T04:05:06Z',
+ },
+ }),
+ { status: 200 },
+ ),
+ );
+
+ await MonitoringAPI.lookupAgent({ id: 'agent-1', hostname: 'host.local' });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/agents/agent/lookup?id=agent-1&hostname=host.local',
+ );
+ });
+
+ it('rejects with the canonical message and skips the transport when no identifier is supplied', async () => {
+ // Exercises the `if (!search.toString())` guard arm — an empty params
+ // object yields an empty URLSearchParams, so the function must throw
+ // BEFORE issuing any request.
+ await expect(MonitoringAPI.lookupAgent({})).rejects.toThrow(
+ 'Provide an agent identifier or hostname to look up.',
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('returns null when the parsed payload omits the agent identity object', async () => {
+ // Exercises the `if (!identity) return null` arm. The response parses to
+ // a truthy object (so the earlier `if (!data)` arm is NOT taken), but the
+ // nested `agent` field is absent — the function must still resolve null.
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ success: true }), { status: 200 }),
+ );
+
+ const result = await MonitoringAPI.lookupAgent({ id: 'agent-x' });
+
+ expect(fetchMock).toHaveBeenCalledWith('/api/agents/agent/lookup?id=agent-x');
+ expect(result).toBeNull();
+ });
+ });
+
+ describe('agent-management — empty-input guard arms', () => {
+ it('deleteAgent throws the canonical message and skips the transport for an empty agentId', async () => {
+ // Exercises the `if (!agentId)` guard arm in deleteAgent — no DELETE may
+ // be issued against a missing identifier.
+ await expect(MonitoringAPI.deleteAgent('')).rejects.toThrow(
+ 'Agent ID is required to remove an agent.',
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('allowHostAgentReenroll throws the canonical message and skips the transport for an empty agentId', async () => {
+ // Exercises the `if (!agentId)` guard arm in allowHostAgentReenroll.
+ await expect(MonitoringAPI.allowHostAgentReenroll('')).rejects.toThrow(
+ 'Agent ID is required to allow reconnect.',
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('updateAgentConfig throws the canonical message and skips the transport for an empty agentId', async () => {
+ // Exercises the `if (!agentId)` guard arm in updateAgentConfig — the
+ // PATCH body is never built or sent.
+ await expect(
+ MonitoringAPI.updateAgentConfig('', { commandsEnabled: true }),
+ ).rejects.toThrow('Agent ID is required to update agent config.');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('unlinkAgent throws the canonical message and skips the transport for an empty agentId', async () => {
+ // Exercises the `if (!agentId)` guard arm in unlinkAgent — the POST
+ // unlink body is never built or sent.
+ await expect(MonitoringAPI.unlinkAgent('')).rejects.toThrow(
+ 'Agent ID is required to unlink an agent.',
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('deleteAgent — body-read error swallow arm', () => {
+ it('resolves successfully when consuming the response body throws after a 2xx delete', async () => {
+ // Exercises the `try { await response.text() } catch (_err)` swallow arm.
+ // The deletion already succeeded (ok:true), so a body-read failure must
+ // NOT propagate — the connection-pool reuse comment in source documents
+ // this contract; this test pins it.
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ status: 204,
+ text: () => Promise.reject(new Error('body stream aborted')),
+ } as unknown as Response);
+
+ await expect(MonitoringAPI.deleteAgent('agent-1')).resolves.toBeUndefined();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/agents/agent/agent-1',
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/onboarding.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/onboarding.branchcov0718.test.ts
new file mode 100644
index 0000000000..05db3848c5
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/onboarding.branchcov0718.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { OnboardingAPI, OnboardingNotReadyError } from '../onboarding';
+import { apiErrorFromResponse, apiFetch } from '@/utils/apiClient';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiErrorFromResponse: vi.fn(),
+ apiFetch: vi.fn(),
+}));
+
+describe('OnboardingAPI – branch coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('getQRPayload – 409 fall-through arms', () => {
+ it('delegates to apiErrorFromResponse when a 409 body carries a non-readiness code', async () => {
+ const response = new Response(
+ JSON.stringify({ code: 'some_other_code', message: 'unrelated conflict' }),
+ { status: 409 },
+ );
+ const parsedError = new Error('parsed non-readiness conflict');
+ vi.mocked(apiFetch).mockResolvedValueOnce(response);
+ vi.mocked(apiErrorFromResponse).mockResolvedValueOnce(parsedError);
+
+ await expect(OnboardingAPI.getQRPayload('token-123')).rejects.toBe(parsedError);
+
+ expect(apiErrorFromResponse).toHaveBeenCalledWith(response);
+ });
+
+ it('delegates to apiErrorFromResponse when a 409 body is not parseable JSON (readJSON swallows the parse failure)', async () => {
+ const response = new Response('<not-json>', { status: 409 });
+ const parsedError = new Error('parsed unparseable conflict');
+ vi.mocked(apiFetch).mockResolvedValueOnce(response);
+ vi.mocked(apiErrorFromResponse).mockResolvedValueOnce(parsedError);
+
+ await expect(OnboardingAPI.getQRPayload()).rejects.toBe(parsedError);
+
+ expect(apiErrorFromResponse).toHaveBeenCalledWith(response);
+ });
+
+ it('delegates to apiErrorFromResponse when a 409 body is valid JSON but not an object', async () => {
+ const response = new Response(JSON.stringify('a plain string'), { status: 409 });
+ const parsedError = new Error('parsed non-object conflict');
+ vi.mocked(apiFetch).mockResolvedValueOnce(response);
+ vi.mocked(apiErrorFromResponse).mockResolvedValueOnce(parsedError);
+
+ await expect(OnboardingAPI.getQRPayload()).rejects.toBe(parsedError);
+
+ expect(apiErrorFromResponse).toHaveBeenCalledWith(response);
+ });
+ });
+
+ describe('OnboardingNotReadyError – message/diagnostics fallback arms', () => {
+ it('uses response.error for the message when response.message is absent', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ code: 'onboarding_not_ready',
+ error: 'Relay has not published its fingerprint yet.',
+ }),
+ { status: 409 },
+ ),
+ );
+
+ await expect(OnboardingAPI.getQRPayload('token-123')).rejects.toMatchObject({
+ name: 'OnboardingNotReadyError',
+ code: 'onboarding_not_ready',
+ status: 409,
+ message: 'Relay has not published its fingerprint yet.',
+ } satisfies Partial<OnboardingNotReadyError>);
+ });
+
+ it('falls back to the default readiness message when neither message nor error is present', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ code: 'onboarding_not_ready',
+ }),
+ { status: 409 },
+ ),
+ );
+
+ await expect(OnboardingAPI.getQRPayload()).rejects.toMatchObject({
+ name: 'OnboardingNotReadyError',
+ code: 'onboarding_not_ready',
+ status: 409,
+ message: 'Pulse Mobile pairing is not ready yet.',
+ } satisfies Partial<OnboardingNotReadyError>);
+ });
+
+ it('defaults diagnostics to an empty array when the response omits them', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ code: 'onboarding_not_ready',
+ message: 'No diagnostics attached.',
+ }),
+ { status: 409 },
+ ),
+ );
+
+ let caught: OnboardingNotReadyError | undefined;
+ try {
+ await OnboardingAPI.getQRPayload('token-123');
+ } catch (err) {
+ caught = err as OnboardingNotReadyError;
+ }
+
+ expect(caught).toBeInstanceOf(OnboardingNotReadyError);
+ expect(caught?.code).toBe('onboarding_not_ready');
+ expect(caught?.status).toBe(409);
+ expect(caught?.diagnostics).toEqual([]);
+ });
+ });
+
+});
diff --git a/frontend-modern/src/features/actions/__tests__/aptActionPresentation.branchcov0718.test.ts b/frontend-modern/src/features/actions/__tests__/aptActionPresentation.branchcov0718.test.ts
new file mode 100644
index 0000000000..c768340e2b
--- /dev/null
+++ b/frontend-modern/src/features/actions/__tests__/aptActionPresentation.branchcov0718.test.ts
@@ -0,0 +1,386 @@
+import { describe, expect, it } from 'vitest';
+import type {
+ ActionAuditApprovalPolicy,
+ ActionAuditRecord,
+ ActionExecutionStatus,
+ ActionPolicyAuthorityFactor,
+ ActionPolicyReasonCode,
+ ActionVerificationTruthStatus,
+} from '@/types/actionAudit';
+import { getAPTActionPresentation } from '../aptActionPresentation';
+
+interface MakeAuditOptions {
+ capabilityName?: string;
+ summary?: string;
+ execution?: ActionExecutionStatus;
+ verification?: ActionVerificationTruthStatus;
+ reasonCodes?: ActionPolicyReasonCode[];
+ approvalPolicy?: ActionAuditApprovalPolicy;
+ requiresApproval?: boolean;
+ params?: Record<string, unknown>;
+ withResult?: boolean;
+}
+
+const makeAudit = ({
+ capabilityName = 'install_os_updates',
+ summary,
+ execution = 'inconclusive',
+ verification = 'inconclusive',
+ reasonCodes = ['capability_auto_elevated'],
+ approvalPolicy,
+ requiresApproval,
+ params,
+ withResult = true,
+}: MakeAuditOptions = {}): ActionAuditRecord => {
+ const policy: ActionAuditApprovalPolicy =
+ approvalPolicy ?? (reasonCodes.includes('capability_auto_elevated') ? 'admin' : 'none');
+ const needsApproval = requiresApproval ?? reasonCodes.includes('capability_auto_elevated');
+ const authority: ActionPolicyAuthorityFactor = {
+ kind: 'capability_registry',
+ sourceId: `capability-registry:${capabilityName}`,
+ status: 'consulted',
+ scope: { orgId: 'org-1', resourceId: 'proxmox:node:pve-1', capabilityName },
+ reasonCodes,
+ };
+ return {
+ id: 'apt-action',
+ createdAt: '2026-07-18T10:00:00Z',
+ updatedAt: '2026-07-18T10:01:00Z',
+ state: 'completed',
+ request: {
+ requestId: 'apt-request',
+ resourceId: 'proxmox:node:pve-1',
+ capabilityName,
+ params,
+ reason: 'Resolve the current Patrol finding',
+ requestedBy: 'pulse_patrol',
+ },
+ plan: {
+ actionId: 'apt-action',
+ requestId: 'apt-request',
+ allowed: true,
+ requiresApproval: needsApproval,
+ approvalPolicy: policy,
+ rollbackAvailable: false,
+ policyDecision: {
+ version: 1,
+ status: 'resolved',
+ decisionId: 'decision',
+ actionId: 'apt-action',
+ scope: { orgId: 'org-1', resourceId: 'proxmox:node:pve-1', capabilityName },
+ approvalRequirement: {
+ version: 1,
+ floor: policy,
+ quorum: 1,
+ disallowRequester: false,
+ },
+ planningAllowed: true,
+ requiresApproval: needsApproval,
+ authorities: [authority],
+ },
+ },
+ result: withResult
+ ? {
+ success: execution === 'succeeded',
+ actionResultV2: {
+ version: 2,
+ execution: { status: execution, summary },
+ verification: { status: verification, evidenceClass: 'agent_attested' },
+ compensation: { support: 'unavailable', status: 'not_available' },
+ },
+ }
+ : undefined,
+ verificationOutcome: { status: 'unknown' },
+ };
+};
+
+describe('getAPTActionPresentation — residual branch coverage', () => {
+ describe('isAPTAction false arm — returns undefined (L107)', () => {
+ it('returns undefined for a capability name that is neither APT capability', () => {
+ expect(
+ getAPTActionPresentation(makeAudit({ capabilityName: 'restart_service' })),
+ ).toBeUndefined();
+ });
+ });
+
+ describe('safetyPosture: Server policy controlled fallback (L144)', () => {
+ it('falls through to Server policy controlled when no auto reason code is present', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({ reasonCodes: ['tenant_mode_monitor'] }),
+ );
+ expect(presentation?.safetyPosture).toBe('Server policy controlled');
+ });
+
+ it('still classifies as Server policy controlled when authorities carry an unrelated reason code', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({ reasonCodes: ['resource_window_closed'] }),
+ );
+ expect(presentation?.safetyPosture).toBe('Server policy controlled');
+ });
+ });
+
+ describe('approvalPosture: Explicit approval required arm (L148-149)', () => {
+ it('demands explicit approval when the plan requiresApproval but the floor is not admin', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ reasonCodes: ['tenant_mode_assisted'],
+ approvalPolicy: 'mfa',
+ requiresApproval: true,
+ }),
+ );
+ expect(presentation?.approvalPosture).toBe('Explicit approval required');
+ });
+
+ it('also reaches the explicit-approval arm under a dry_run_only policy that still requires approval', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ reasonCodes: ['capability_dry_run_only'],
+ approvalPolicy: 'dry_run_only',
+ requiresApproval: true,
+ }),
+ );
+ expect(presentation?.approvalPosture).toBe('Explicit approval required');
+ });
+ });
+
+ describe('nextStep default arm with no result envelope at all (L119)', () => {
+ it('keeps the initial server-policy nextStep when result is entirely absent', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({ reasonCodes: ['capability_auto_elevated'], withResult: false }),
+ );
+ expect(presentation?.nextStep).toBe(
+ 'Review the server policy and exact scope before making a decision.',
+ );
+ expect(presentation?.facts).toEqual([]);
+ });
+ });
+
+ describe('nextStep generic-rescan fallback inside actionResultV2 (L134)', () => {
+ it('renders the generic rescan nextStep for a healthy, non-confirmed, non-recovery update', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ summary:
+ 'APT package updates: phase=verify; 4 pending before, 4 pending after; package manager health: healthy; recovery required: false; reboot required: false',
+ verification: 'contradicted',
+ }),
+ );
+ expect(presentation?.nextStep).toBe(
+ 'Review the separate execution and verification results, then rescan before creating another plan.',
+ );
+ });
+
+ it('also reaches the generic-rescan fallback for a cleanup whose rescan is not required', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ capabilityName: 'clean_package_cache',
+ reasonCodes: ['capability_auto_low_risk'],
+ summary:
+ 'APT package cache: phase=verify; 100 bytes before, 0 bytes after, 100 bytes reclaimed; rollback available: false; rescan required: false',
+ verification: 'inconclusive',
+ }),
+ );
+ expect(presentation?.nextStep).toBe(
+ 'Review the separate execution and verification results, then rescan before creating another plan.',
+ );
+ });
+ });
+
+ describe('nextStep confirmed arm for cleanup (L125)', () => {
+ it('directs a confirmed cleanup to the measured-rescan nextStep rather than reboot wording', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ capabilityName: 'clean_package_cache',
+ reasonCodes: ['capability_auto_low_risk'],
+ summary:
+ 'APT package cache: phase=complete; 100 bytes before, 0 bytes after, 100 bytes reclaimed; rollback available: false; rescan required: false',
+ execution: 'succeeded',
+ verification: 'confirmed',
+ }),
+ );
+ expect(presentation?.nextStep).toBe(
+ 'Review the measured space reclaimed. Create another cleanup plan only if a fresh scan still shows pressure.',
+ );
+ });
+ });
+
+ describe('formatPhase untaken arms reachable through the summary parsers', () => {
+ it('renders the preflight phase for an update plan', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ summary:
+ 'APT package updates: phase=preflight; 4 pending before, 4 pending after; package manager health: healthy; recovery required: false; reboot required: false',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Last phase reached',
+ value: 'Safety check before changes',
+ });
+ });
+
+ it('renders the refresh phase for an update plan', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ summary:
+ 'APT package updates: phase=refresh; 4 pending before, 4 pending after; package manager health: healthy; recovery required: false; reboot required: false',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Last phase reached',
+ value: 'Refresh update information',
+ });
+ });
+
+ it('renders the preflight phase for a cleanup plan and a No rescan fact', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ capabilityName: 'clean_package_cache',
+ reasonCodes: ['capability_auto_low_risk'],
+ summary:
+ 'APT package cache: phase=preflight; 100 bytes before, 100 bytes after, 0 bytes reclaimed; rollback available: false; rescan required: false',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Last phase reached',
+ value: 'Safety check before changes',
+ });
+ expect(presentation?.facts).toContainEqual({
+ label: 'Fresh rescan required',
+ value: 'No',
+ });
+ });
+
+ it('renders the complete phase for a cleanup plan', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ capabilityName: 'clean_package_cache',
+ reasonCodes: ['capability_auto_low_risk'],
+ summary:
+ 'APT package cache: phase=complete; 100 bytes before, 0 bytes after, 100 bytes reclaimed; rollback available: false; rescan required: false',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Last phase reached',
+ value: 'Completed workflow',
+ });
+ });
+
+ it('renders the verify phase for a cleanup plan', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ capabilityName: 'clean_package_cache',
+ reasonCodes: ['capability_auto_low_risk'],
+ summary:
+ 'APT package cache: phase=verify; 100 bytes before, 0 bytes after, 100 bytes reclaimed; rollback available: false; rescan required: false',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Last phase reached',
+ value: 'Check the result',
+ });
+ });
+
+ it('renders No reboot required when reboot required is false on an update plan', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ summary:
+ 'APT package updates: phase=complete; 2 pending before, 0 pending after; package manager health: healthy; recovery required: false; reboot required: false',
+ execution: 'succeeded',
+ verification: 'confirmed',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Reboot required',
+ value: 'No',
+ });
+ });
+
+ it('renders No recovery required as a fact value distinct from the Yes arm', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ summary:
+ 'APT package updates: phase=install; 6 pending before, 0 pending after; package manager health: healthy; recovery required: false; reboot required: false',
+ execution: 'succeeded',
+ verification: 'confirmed',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Recovery required',
+ value: 'No',
+ });
+ });
+ });
+
+ describe('parseCount boundary — zero counts are accepted, not treated as missing', () => {
+ it('accepts zero pending before and zero pending after on an update plan', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ summary:
+ 'APT package updates: phase=complete; 0 pending before, 0 pending after; package manager health: healthy; recovery required: false; reboot required: false',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({ label: 'Updates before', value: '0' });
+ expect(presentation?.facts).toContainEqual({ label: 'Updates remaining', value: '0' });
+ });
+
+ it('accepts a zero-byte cleanup that reclaims nothing', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({
+ capabilityName: 'clean_package_cache',
+ reasonCodes: ['capability_auto_low_risk'],
+ summary:
+ 'APT package cache: phase=complete; 0 bytes before, 0 bytes after, 0 bytes reclaimed; rollback available: false; rescan required: false',
+ }),
+ );
+ expect(presentation?.facts).toContainEqual({
+ label: 'Downloaded package data before',
+ value: '0 B',
+ });
+ expect(presentation?.facts).toContainEqual({
+ label: 'Space reclaimed',
+ value: '0 B',
+ });
+ });
+ });
+
+ describe('hasExactEmptyParameters — undefined params are treated as valid empty', () => {
+ it('treats an absent params field as valid empty parameters', () => {
+ const presentation = getAPTActionPresentation(
+ makeAudit({ reasonCodes: ['capability_auto_elevated'] }),
+ );
+ expect(presentation?.parametersValid).toBe(true);
+ expect(presentation?.parameterAuthority).toContain('accepts no command, path');
+ });
+ });
+
+ describe('title arms', () => {
+ it('uses the install title for install_os_updates', () => {
+ expect(getAPTActionPresentation(makeAudit())?.title).toBe('Install operating system updates');
+ });
+
+ it('uses the cleanup title for clean_package_cache', () => {
+ expect(
+ getAPTActionPresentation(
+ makeAudit({ capabilityName: 'clean_package_cache', reasonCodes: ['capability_auto_low_risk'] }),
+ )?.title,
+ ).toBe('Clear downloaded package data');
+ });
+ });
+
+ describe('authorityBoundary arms', () => {
+ it('bounds the install capability away from package removal and reboot', () => {
+ expect(getAPTActionPresentation(makeAudit())?.authorityBoundary).toBe(
+ 'The agent may refresh update information and install the complete approved update set. It cannot remove packages or reboot the host.',
+ );
+ });
+
+ it('bounds the cleanup capability to downloaded package data only', () => {
+ expect(
+ getAPTActionPresentation(
+ makeAudit({ capabilityName: 'clean_package_cache', reasonCodes: ['capability_auto_low_risk'] }),
+ )?.authorityBoundary,
+ ).toBe(
+ 'The agent may clear only downloaded package data on the pressured filesystem. It cannot choose paths, remove installed packages, or reboot the host.',
+ );
+ });
+ });
+});