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 API-client modules

rcourtman6628d7e606fa
diff --git a/frontend-modern/src/api/__tests__/agentProfiles.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/agentProfiles.branchcov0718.test.ts
new file mode 100644
index 0000000000..0db434b035
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/agentProfiles.branchcov0718.test.ts
@@ -0,0 +1,515 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import {
+ AgentProfilesAPI,
+ INVALID_AGENT_PROFILE_SUGGESTION_MESSAGE,
+ INVALID_AGENT_PROFILE_SCHEMA_MESSAGE,
+ INVALID_AGENT_PROFILE_VALIDATION_MESSAGE,
+ type AgentProfile,
+} from '../agentProfiles';
+import { apiFetchJSON, apiFetch } from '@/utils/apiClient';
+import {
+ assertAPIResponseOK,
+ assertAPIResponseOKOrAllowedStatus,
+ assertAPIResponseOKOrThrowStatus,
+ arrayOrEmpty,
+ isAPIErrorStatus,
+ objectArrayFieldOrEmpty,
+ parseRequiredJSON,
+ parseRequiredAPIResponse,
+ withAPIErrorStatusFallback,
+ withAPIErrorStatusNull,
+} from '../responseUtils';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+ apiFetch: vi.fn(),
+}));
+
+vi.mock('../responseUtils', () => ({
+ assertAPIResponseOK: vi.fn(),
+ assertAPIResponseOKOrAllowedStatus: vi.fn(),
+ assertAPIResponseOKOrThrowStatus: vi.fn(),
+ arrayOrEmpty: vi.fn(),
+ isAPIErrorStatus: vi.fn(),
+ objectArrayFieldOrEmpty: vi.fn(),
+ parseRequiredAPIResponse: vi.fn(),
+ parseRequiredJSON: vi.fn(),
+ withAPIErrorStatusFallback: vi.fn(),
+ withAPIErrorStatusNull: vi.fn(),
+}));
+
+describe('AgentProfilesAPI branch coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(isAPIErrorStatus).mockImplementation((error, expectedStatus) => {
+ return (error as { status?: number } | null)?.status === expectedStatus;
+ });
+ vi.mocked(assertAPIResponseOK).mockResolvedValue(undefined);
+ vi.mocked(assertAPIResponseOKOrAllowedStatus).mockResolvedValue(undefined);
+ vi.mocked(assertAPIResponseOKOrThrowStatus).mockResolvedValue(undefined);
+ vi.mocked(arrayOrEmpty).mockImplementation((value) =>
+ Array.isArray(value) ? (value as never[]) : [],
+ );
+ vi.mocked(objectArrayFieldOrEmpty).mockImplementation((value, field) => {
+ if (!value || typeof value !== 'object') {
+ return [];
+ }
+ const fieldValue = (value as Record<string, unknown>)[field];
+ return Array.isArray(fieldValue) ? (fieldValue as never[]) : [];
+ });
+ vi.mocked(parseRequiredJSON).mockImplementation(async (response) => {
+ const text = await response.text();
+ return JSON.parse(text);
+ });
+ vi.mocked(withAPIErrorStatusFallback).mockImplementation(
+ async (request, fallbackStatus, fallbackValue) => {
+ try {
+ return await request;
+ } catch (error) {
+ if ((error as { status?: number } | null)?.status === fallbackStatus) {
+ return fallbackValue;
+ }
+ throw error;
+ }
+ },
+ );
+ vi.mocked(withAPIErrorStatusNull).mockImplementation(async (request, nullStatus) => {
+ try {
+ return await request;
+ } catch (error) {
+ if ((error as { status?: number } | null)?.status === nullStatus) {
+ return null;
+ }
+ throw error;
+ }
+ });
+ vi.mocked(parseRequiredAPIResponse).mockReset();
+ });
+
+ function lastFetchCall(): [string, RequestInit] {
+ const calls = vi.mocked(apiFetch).mock.calls as unknown as [string, RequestInit][];
+ if (calls.length === 0) {
+ throw new Error('apiFetch was not called');
+ }
+ return calls[calls.length - 1];
+ }
+
+ function jsonResponse(body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ describe('getProfile', () => {
+ it('URL-encodes the profile id when it contains path-unsafe characters', async () => {
+ const profile: AgentProfile = {
+ id: 'a/b c',
+ name: 'Profile',
+ config: {},
+ created_at: '',
+ updated_at: '',
+ };
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(profile);
+
+ const result = await AgentProfilesAPI.getProfile('a/b c');
+
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/admin/profiles/a%2Fb%20c');
+ expect(result).toEqual(profile);
+ });
+
+ it('returns null when withAPIErrorStatusNull yields null without throwing', async () => {
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(null as unknown as AgentProfile);
+
+ const result = await AgentProfilesAPI.getProfile('p1');
+
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/admin/profiles/p1');
+ expect(result).toBeNull();
+ });
+
+ it('preserves optional description and version fields when present', async () => {
+ const fullProfile = {
+ id: 'p1',
+ name: 'Profile',
+ description: 'a description',
+ config: { a: 1 },
+ version: 7,
+ created_at: '2024-01-01',
+ updated_at: '2024-01-02',
+ };
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(fullProfile as unknown as AgentProfile);
+
+ const result = await AgentProfilesAPI.getProfile('p1');
+
+ expect(result).toEqual(fullProfile);
+ });
+ });
+
+ describe('createProfile', () => {
+ it('sends body with description when description is provided', async () => {
+ const mockResponse = { ok: true, status: 201 } as unknown as Response;
+ vi.mocked(apiFetch).mockResolvedValueOnce(mockResponse);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ id: 'p1',
+ name: 'N',
+ config: { x: 1 },
+ created_at: '',
+ updated_at: '',
+ });
+
+ await AgentProfilesAPI.createProfile('N', { x: 1 }, 'desc');
+
+ const [path, opts] = lastFetchCall();
+ expect(path).toBe('/api/admin/profiles/');
+ expect(opts.method).toBe('POST');
+ expect(opts.headers).toEqual({ 'Content-Type': 'application/json' });
+ expect(JSON.parse(opts.body as string)).toEqual({
+ name: 'N',
+ description: 'desc',
+ config: { x: 1 },
+ });
+ });
+
+ it('omits description from POST body when description is absent', async () => {
+ const mockResponse = { ok: true, status: 201 } as unknown as Response;
+ vi.mocked(apiFetch).mockResolvedValueOnce(mockResponse);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ id: 'p1',
+ name: 'N',
+ config: {},
+ created_at: '',
+ updated_at: '',
+ });
+
+ await AgentProfilesAPI.createProfile('N', {});
+
+ const [, opts] = lastFetchCall();
+ const body = JSON.parse(opts.body as string);
+ expect(body).toEqual({ name: 'N', config: {} });
+ expect(body).not.toHaveProperty('description');
+ });
+ });
+
+ describe('updateProfile', () => {
+ it('sends PUT to URL-encoded id with id+name+description+config in body', async () => {
+ const mockResponse = { ok: true, status: 200 } as unknown as Response;
+ vi.mocked(apiFetch).mockResolvedValueOnce(mockResponse);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ id: 'a/b',
+ name: 'N',
+ config: {},
+ created_at: '',
+ updated_at: '',
+ });
+
+ await AgentProfilesAPI.updateProfile('a/b', 'N', {}, 'a description');
+
+ const [path, opts] = lastFetchCall();
+ expect(path).toBe('/api/admin/profiles/a%2Fb');
+ expect(opts.method).toBe('PUT');
+ expect(opts.headers).toEqual({ 'Content-Type': 'application/json' });
+ expect(JSON.parse(opts.body as string)).toEqual({
+ id: 'a/b',
+ name: 'N',
+ description: 'a description',
+ config: {},
+ });
+ });
+
+ it('omits description from PUT body when description is absent', async () => {
+ const mockResponse = { ok: true, status: 200 } as unknown as Response;
+ vi.mocked(apiFetch).mockResolvedValueOnce(mockResponse);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ id: 'p1',
+ name: 'N',
+ config: {},
+ created_at: '',
+ updated_at: '',
+ });
+
+ await AgentProfilesAPI.updateProfile('p1', 'N', { y: 2 });
+
+ const [, opts] = lastFetchCall();
+ const body = JSON.parse(opts.body as string);
+ expect(body).toEqual({ id: 'p1', name: 'N', config: { y: 2 } });
+ expect(body).not.toHaveProperty('description');
+ });
+ });
+
+ describe('deleteProfile', () => {
+ it('URL-encodes the profile id in the DELETE path', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({
+ ok: true,
+ status: 204,
+ } as unknown as Response);
+
+ await AgentProfilesAPI.deleteProfile('a b/c');
+
+ const [path, opts] = lastFetchCall();
+ expect(path).toBe('/api/admin/profiles/a%20b%2Fc');
+ expect(opts.method).toBe('DELETE');
+ });
+ });
+
+ describe('unassignProfile', () => {
+ it('URL-encodes the agent id in the DELETE path', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({
+ ok: true,
+ status: 204,
+ } as unknown as Response);
+
+ await AgentProfilesAPI.unassignProfile('agent x/y');
+
+ const [path, opts] = lastFetchCall();
+ expect(path).toBe('/api/admin/profiles/assignments/agent%20x%2Fy');
+ expect(opts.method).toBe('DELETE');
+ });
+ });
+
+ describe('suggestProfile', () => {
+ it('sends the request object as the JSON body', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({ ok: true, status: 200 } as unknown as Response);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ name: 'n',
+ description: 'd',
+ config: {},
+ rationale: [],
+ });
+
+ await AgentProfilesAPI.suggestProfile({ prompt: 'make it fast' });
+
+ const [path, opts] = lastFetchCall();
+ expect(path).toBe('/api/admin/profiles/suggestions');
+ expect(opts.method).toBe('POST');
+ expect(opts.headers).toEqual({ 'Content-Type': 'application/json' });
+ expect(JSON.parse(opts.body as string)).toEqual({ prompt: 'make it fast' });
+ });
+
+ it('throws when parsed suggestion is not a record', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({ ok: true, status: 200 } as unknown as Response);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce('not-a-record' as never);
+
+ await expect(AgentProfilesAPI.suggestProfile({ prompt: 'x' })).rejects.toThrow(
+ INVALID_AGENT_PROFILE_SUGGESTION_MESSAGE,
+ );
+ });
+
+ it('throws when name field is missing from parsed suggestion', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({ ok: true, status: 200 } as unknown as Response);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ description: 'd',
+ config: {},
+ rationale: [],
+ });
+
+ await expect(AgentProfilesAPI.suggestProfile({ prompt: 'x' })).rejects.toThrow(
+ INVALID_AGENT_PROFILE_SUGGESTION_MESSAGE,
+ );
+ });
+
+ it('throws when description field is missing from parsed suggestion', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({ ok: true, status: 200 } as unknown as Response);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ name: 'n',
+ config: {},
+ rationale: [],
+ });
+
+ await expect(AgentProfilesAPI.suggestProfile({ prompt: 'x' })).rejects.toThrow(
+ INVALID_AGENT_PROFILE_SUGGESTION_MESSAGE,
+ );
+ });
+
+ it('throws when rationale contains a non-string entry', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({ ok: true, status: 200 } as unknown as Response);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ name: 'n',
+ description: 'd',
+ config: {},
+ rationale: ['ok', 42],
+ });
+
+ await expect(AgentProfilesAPI.suggestProfile({ prompt: 'x' })).rejects.toThrow(
+ INVALID_AGENT_PROFILE_SUGGESTION_MESSAGE,
+ );
+ });
+
+ it('parses multi-entry rationale as a string array on the happy path', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce({ ok: true, status: 200 } as unknown as Response);
+ vi.mocked(parseRequiredAPIResponse).mockResolvedValueOnce({
+ name: 'n',
+ description: 'd',
+ config: { k: 1 },
+ rationale: ['reason 1', 'reason 2'],
+ });
+
+ const result = await AgentProfilesAPI.suggestProfile({ prompt: 'x' });
+
+ expect(result).toEqual({
+ name: 'n',
+ description: 'd',
+ config: { k: 1 },
+ rationale: ['reason 1', 'reason 2'],
+ });
+ });
+ });
+
+ describe('getConfigSchema', () => {
+ it('preserves optional Min/Max/Pattern/Enum fields when present', async () => {
+ const schema = [
+ {
+ Key: 'cpu',
+ Type: 'number',
+ Description: 'CPU',
+ Default: 4,
+ Required: true,
+ Min: 1,
+ Max: 10,
+ Pattern: '^\\d+$',
+ Enum: ['a', 'b'],
+ },
+ ];
+ vi.mocked(apiFetch).mockResolvedValueOnce(jsonResponse(schema));
+
+ const result = await AgentProfilesAPI.getConfigSchema();
+
+ expect(result).toEqual([
+ {
+ key: 'cpu',
+ type: 'number',
+ description: 'CPU',
+ defaultValue: 4,
+ required: true,
+ min: 1,
+ max: 10,
+ pattern: '^\\d+$',
+ enum: ['a', 'b'],
+ },
+ ]);
+ });
+
+ it('returns undefined for optional Min/Max/Pattern/Enum when absent', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(
+ jsonResponse([{ Key: 'k', Type: 'string', Description: 'D', Required: false }]),
+ );
+
+ const result = await AgentProfilesAPI.getConfigSchema();
+
+ expect(result).toEqual([
+ {
+ key: 'k',
+ type: 'string',
+ description: 'D',
+ defaultValue: undefined,
+ required: false,
+ min: undefined,
+ max: undefined,
+ pattern: undefined,
+ enum: undefined,
+ },
+ ]);
+ });
+
+ it('treats null Enum as absent (undefined)', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(
+ jsonResponse([
+ { Key: 'k', Type: 'string', Description: 'D', Required: false, Enum: null },
+ ]),
+ );
+
+ const result = await AgentProfilesAPI.getConfigSchema();
+
+ expect(result[0].enum).toBeUndefined();
+ });
+
+ it('throws when an Enum entry is not a string', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(
+ jsonResponse([
+ {
+ Key: 'k',
+ Type: 'string',
+ Description: 'D',
+ Required: false,
+ Enum: ['ok', 5],
+ },
+ ]),
+ );
+
+ await expect(AgentProfilesAPI.getConfigSchema()).rejects.toThrow(
+ INVALID_AGENT_PROFILE_SCHEMA_MESSAGE,
+ );
+ });
+
+ it('throws when a schema definition entry is not a record', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(jsonResponse(['not-a-record']));
+
+ await expect(AgentProfilesAPI.getConfigSchema()).rejects.toThrow(
+ INVALID_AGENT_PROFILE_SCHEMA_MESSAGE,
+ );
+ });
+ });
+
+ describe('validateConfig', () => {
+ it('sends config object as the JSON body', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(jsonResponse({ Valid: true }));
+
+ await AgentProfilesAPI.validateConfig({ cpu_limit: 4 });
+
+ const [path, opts] = lastFetchCall();
+ expect(path).toBe('/api/admin/profiles/validate');
+ expect(opts.method).toBe('POST');
+ expect(opts.headers).toEqual({ 'Content-Type': 'application/json' });
+ expect(JSON.parse(opts.body as string)).toEqual({ cpu_limit: 4 });
+ });
+
+ it('returns empty errors array when Errors field is undefined', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(jsonResponse({ Valid: true, Warnings: [] }));
+
+ const result = await AgentProfilesAPI.validateConfig({});
+
+ expect(result).toEqual({ valid: true, errors: [], warnings: [] });
+ expect(objectArrayFieldOrEmpty).toHaveBeenCalledWith(
+ { Valid: true, Warnings: [] },
+ 'Warnings',
+ );
+ expect(objectArrayFieldOrEmpty).not.toHaveBeenCalledWith(
+ expect.anything(),
+ 'Errors',
+ );
+ });
+
+ it('returns empty warnings array when Warnings field is undefined', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(jsonResponse({ Valid: false, Errors: [] }));
+
+ const result = await AgentProfilesAPI.validateConfig({});
+
+ expect(result).toEqual({ valid: false, errors: [], warnings: [] });
+ });
+
+ it('throws when Valid is present but not a boolean', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(jsonResponse({ Valid: 'true' }));
+
+ await expect(AgentProfilesAPI.validateConfig({})).rejects.toThrow(
+ INVALID_AGENT_PROFILE_VALIDATION_MESSAGE,
+ );
+ });
+
+ it('maps Errors and Warnings items to { key, message }', async () => {
+ vi.mocked(apiFetch).mockResolvedValueOnce(
+ jsonResponse({
+ Valid: false,
+ Errors: [{ Key: 'cpu', Message: 'too high' }],
+ Warnings: [{ Key: 'mem', Message: 'low' }],
+ }),
+ );
+
+ const result = await AgentProfilesAPI.validateConfig({ cpu: 99 });
+
+ expect(result).toEqual({
+ valid: false,
+ errors: [{ key: 'cpu', message: 'too high' }],
+ warnings: [{ key: 'mem', message: 'low' }],
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/ai.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/ai.branchcov0718.test.ts
new file mode 100644
index 0000000000..44c0facc34
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/ai.branchcov0718.test.ts
@@ -0,0 +1,475 @@
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+ apiFetch: vi.fn(),
+}));
+
+vi.mock('@/utils/logger', () => ({
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+import { AIAPI } from '@/api/ai';
+import { apiFetch, apiFetchJSON } from '@/utils/apiClient';
+
+// Branch-coverage companion to ai.test.ts. Covers the request-shaping and
+// response-handling of the currently-uncovered AIAPI request functions:
+// testConnection, resetCostHistory, exportCostHistory, getAnomalies,
+// getLearningStatus, analyzeKubernetesCluster, approveRemediationPlan,
+// executeRemediationPlan, rollbackRemediationPlan, getCircuitBreakerStatus.
+// Each test asserts the concrete request (final path + query string + method +
+// body) and the concrete parsed result for happy paths and each optional /
+// default-parameter branch arm.
+describe('AIAPI branch coverage (request shaping + response handling)', () => {
+ const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+ const apiFetchMock = vi.mocked(apiFetch);
+
+ beforeEach(() => {
+ apiFetchJSONMock.mockReset();
+ apiFetchMock.mockReset();
+ });
+
+ // --------------------------------------------
+ // testConnection
+ // --------------------------------------------
+ describe('testConnection', () => {
+ it('POSTs /api/ai/test with no body and returns the parsed AITestResult verbatim', async () => {
+ const payload = { success: true, message: 'ok', provider: 'zai', model: 'glm-4.6' };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.testConnection();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/test', { method: 'POST' });
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('surfaces a failed-connection payload without altering the diagnostic shape', async () => {
+ const payload = {
+ success: false,
+ message: 'auth failed',
+ provider: 'zai',
+ cause: 'provider_auth',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.testConnection();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/test', { method: 'POST' });
+ expect(result).toStrictEqual(payload);
+ });
+ });
+
+ // --------------------------------------------
+ // resetCostHistory
+ // --------------------------------------------
+ describe('resetCostHistory', () => {
+ it('POSTs an empty JSON object to /api/ai/cost/reset and returns the ok + backup_file payload', async () => {
+ const payload = { ok: true, backup_file: '/var/lib/pulse/cost-backup-2026.json' };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.resetCostHistory();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/cost/reset', {
+ method: 'POST',
+ body: JSON.stringify({}),
+ });
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('returns the { ok } arm verbatim when the backend omits backup_file', async () => {
+ // The backup_file field is optional on the return type; cover the
+ // branch where the backend confirms reset but produces no backup path.
+ const payload = { ok: true };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.resetCostHistory();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/cost/reset', {
+ method: 'POST',
+ body: JSON.stringify({}),
+ });
+ expect(result).toStrictEqual({ ok: true });
+ expect('backup_file' in result).toBe(false);
+ });
+ });
+
+ // --------------------------------------------
+ // exportCostHistory
+ // --------------------------------------------
+ describe('exportCostHistory', () => {
+ it('uses apiFetch (not apiFetchJSON) and defaults to days=30 format=csv', async () => {
+ const stub = new Response('date,cost\n2026-01-01,1.23\n', { status: 200 });
+ apiFetchMock.mockResolvedValueOnce(stub);
+
+ const result = await AIAPI.exportCostHistory();
+
+ // Default-parameter branch: both args take their defaults.
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/cost/export?days=30&format=csv', {
+ method: 'GET',
+ });
+ // The Response object is returned untouched — no JSON parsing.
+ expect(result).toBe(stub);
+ expect(apiFetchJSONMock).not.toHaveBeenCalled();
+ });
+
+ it('forwards a custom days value while keeping the csv default format', async () => {
+ const stub = new Response('', { status: 200 });
+ apiFetchMock.mockResolvedValueOnce(stub);
+
+ await AIAPI.exportCostHistory(7);
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/cost/export?days=7&format=csv', {
+ method: 'GET',
+ });
+ });
+
+ it('forwards an explicit json format while keeping the days default', async () => {
+ const stub = new Response('[]', { status: 200, headers: { 'Content-Type': 'application/json' } });
+ apiFetchMock.mockResolvedValueOnce(stub);
+
+ await AIAPI.exportCostHistory(30, 'json');
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/cost/export?days=30&format=json', {
+ method: 'GET',
+ });
+ });
+
+ it('forwards both custom days and json format together', async () => {
+ const stub = new Response('{}', { status: 200 });
+ apiFetchMock.mockResolvedValueOnce(stub);
+
+ await AIAPI.exportCostHistory(14, 'json');
+
+ // URLSearchParams preserves insertion order: days first, then format.
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/cost/export?days=14&format=json', {
+ method: 'GET',
+ });
+ });
+
+ it('encodes special characters inside the days value via URLSearchParams', async () => {
+ // URLSearchParams always stringifies the numeric arg; this guards the
+ // stringification path for an edge-case fractional window.
+ apiFetchMock.mockResolvedValueOnce(new Response('', { status: 200 }));
+
+ await AIAPI.exportCostHistory(0.5, 'csv');
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/cost/export?days=0.5&format=csv', {
+ method: 'GET',
+ });
+ });
+ });
+
+ // --------------------------------------------
+ // getAnomalies
+ // --------------------------------------------
+ describe('getAnomalies', () => {
+ it('omits the query string when resourceId is undefined (no-arg branch)', async () => {
+ const payload = { anomalies: [], count: 0 };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.getAnomalies();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/intelligence/anomalies');
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('appends ?resource_id=<encoded> when a resourceId is supplied', async () => {
+ const payload = {
+ anomalies: [{ resource_id: 'vm-1', metric: 'cpu', score: 0.92 }],
+ count: 1,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.getAnomalies('vm-1');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/intelligence/anomalies?resource_id=vm-1',
+ );
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('treats an explicit undefined arg identically to the no-arg branch', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ anomalies: [], count: 0 } as any);
+
+ await AIAPI.getAnomalies(undefined);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/intelligence/anomalies');
+ });
+
+ it('URL-encodes special characters in the resource id', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ anomalies: [], count: 0 } as any);
+
+ await AIAPI.getAnomalies('node/1?filter=all');
+
+ // encodeURIComponent('node/1?filter=all') === 'node%2F1%3Ffilter%3Dall'
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/intelligence/anomalies?resource_id=node%2F1%3Ffilter%3Dall',
+ );
+ });
+
+ it('drops the query string for an empty-string resourceId (falsy branch)', async () => {
+ // The ternary `resourceId ? ... : ''` treats '' as falsy, so an empty
+ // string must NOT append a query string.
+ apiFetchJSONMock.mockResolvedValueOnce({ anomalies: [], count: 0 } as any);
+
+ await AIAPI.getAnomalies('');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/intelligence/anomalies');
+ });
+ });
+
+ // --------------------------------------------
+ // getLearningStatus
+ // --------------------------------------------
+ describe('getLearningStatus', () => {
+ it('GETs /api/ai/intelligence/learning and returns the parsed status verbatim', async () => {
+ const payload = {
+ state: 'learning',
+ resources_baselined: 42,
+ resources_total: 100,
+ percent_complete: 42,
+ started_at: '2026-07-01T00:00:00Z',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.getLearningStatus();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/intelligence/learning');
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('round-trips a completed-state payload with optional fields absent', async () => {
+ const payload = { state: 'completed', resources_baselined: 100, resources_total: 100 };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.getLearningStatus();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/intelligence/learning');
+ expect(result).toStrictEqual(payload);
+ expect('percent_complete' in result).toBe(false);
+ });
+ });
+
+ // --------------------------------------------
+ // analyzeKubernetesCluster
+ // --------------------------------------------
+ describe('analyzeKubernetesCluster', () => {
+ it('POSTs { cluster_id } to /api/ai/kubernetes/analyze and returns the parsed response verbatim', async () => {
+ const payload = {
+ execution_id: 'exec-1',
+ plan_id: 'plan-1',
+ status: 'success' as const,
+ steps_completed: 3,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.analyzeKubernetesCluster('prod-cluster-1');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/kubernetes/analyze', {
+ method: 'POST',
+ body: JSON.stringify({ cluster_id: 'prod-cluster-1' }),
+ });
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('preserves snake_case cluster ids verbatim in the request body', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ execution_id: 'exec-2',
+ plan_id: 'plan-2',
+ status: 'success',
+ steps_completed: 1,
+ } as any);
+
+ await AIAPI.analyzeKubernetesCluster('us_east_1/prod');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/kubernetes/analyze', {
+ method: 'POST',
+ body: JSON.stringify({ cluster_id: 'us_east_1/prod' }),
+ });
+ });
+ });
+
+ // --------------------------------------------
+ // approveRemediationPlan
+ // --------------------------------------------
+ describe('approveRemediationPlan', () => {
+ it('POSTs { plan_id } to /api/ai/remediation/approve and returns success + execution', async () => {
+ const payload = { success: true, execution: { id: 'exec-9' } };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.approveRemediationPlan('plan-42');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/remediation/approve', {
+ method: 'POST',
+ body: JSON.stringify({ plan_id: 'plan-42' }),
+ });
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('returns the success-only arm when the backend omits execution', async () => {
+ // The execution field is optional on the return type; cover the branch
+ // where approval succeeds but no execution is materialized yet.
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ const result = await AIAPI.approveRemediationPlan('plan-43');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/remediation/approve', {
+ method: 'POST',
+ body: JSON.stringify({ plan_id: 'plan-43' }),
+ });
+ expect(result).toStrictEqual({ success: true });
+ expect('execution' in result).toBe(false);
+ });
+
+ it('forwards a failed-approval payload without normalization', async () => {
+ const payload = { success: false };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.approveRemediationPlan('plan-44');
+
+ expect(result).toStrictEqual({ success: false });
+ });
+ });
+
+ // --------------------------------------------
+ // executeRemediationPlan
+ // --------------------------------------------
+ describe('executeRemediationPlan', () => {
+ it('POSTs { execution_id } to /api/ai/remediation/execute and returns the full result', async () => {
+ const payload = {
+ execution_id: 'exec-7',
+ plan_id: 'plan-7',
+ status: 'success' as const,
+ steps_completed: 4,
+ step_results: [
+ {
+ step: 1,
+ success: true,
+ output: 'ok',
+ duration_ms: 12,
+ run_at: '2026-07-18T12:00:00Z',
+ },
+ ],
+ started_at: '2026-07-18T12:00:00Z',
+ completed_at: '2026-07-18T12:00:01Z',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.executeRemediationPlan('exec-7');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/remediation/execute', {
+ method: 'POST',
+ body: JSON.stringify({ execution_id: 'exec-7' }),
+ });
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('round-trips a partial-status result with optional step_results absent', async () => {
+ const payload = {
+ execution_id: 'exec-8',
+ plan_id: 'plan-8',
+ status: 'partial' as const,
+ steps_completed: 2,
+ error: 'step 3 failed',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.executeRemediationPlan('exec-8');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/remediation/execute', {
+ method: 'POST',
+ body: JSON.stringify({ execution_id: 'exec-8' }),
+ });
+ expect(result).toStrictEqual(payload);
+ expect('step_results' in result).toBe(false);
+ });
+ });
+
+ // --------------------------------------------
+ // rollbackRemediationPlan
+ // --------------------------------------------
+ describe('rollbackRemediationPlan', () => {
+ it('POSTs { execution_id } to /api/ai/remediation/rollback and returns { success }', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ const result = await AIAPI.rollbackRemediationPlan('exec-7');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/remediation/rollback', {
+ method: 'POST',
+ body: JSON.stringify({ execution_id: 'exec-7' }),
+ });
+ expect(result).toStrictEqual({ success: true });
+ });
+
+ it('forwards a failed rollback payload without normalization', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: false } as any);
+
+ const result = await AIAPI.rollbackRemediationPlan('exec-9');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/remediation/rollback', {
+ method: 'POST',
+ body: JSON.stringify({ execution_id: 'exec-9' }),
+ });
+ expect(result).toStrictEqual({ success: false });
+ });
+ });
+
+ // --------------------------------------------
+ // getCircuitBreakerStatus
+ // --------------------------------------------
+ describe('getCircuitBreakerStatus', () => {
+ it('GETs /api/ai/circuit/status and returns a closed-breaker payload verbatim', async () => {
+ const payload = {
+ state: 'closed' as const,
+ can_patrol: true,
+ consecutive_failures: 0,
+ total_successes: 128,
+ total_failures: 1,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.getCircuitBreakerStatus();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/circuit/status');
+ expect(result).toStrictEqual(payload);
+ });
+
+ it('round-trips an open-breaker payload that blocks patrol', async () => {
+ const payload = {
+ state: 'open' as const,
+ can_patrol: false,
+ consecutive_failures: 5,
+ total_successes: 100,
+ total_failures: 10,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.getCircuitBreakerStatus();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/circuit/status');
+ expect(result).toStrictEqual(payload);
+ expect(result.can_patrol).toBe(false);
+ });
+
+ it('round-trips a half-open breaker probe state', async () => {
+ const payload = {
+ state: 'half-open' as const,
+ can_patrol: true,
+ consecutive_failures: 0,
+ total_successes: 100,
+ total_failures: 5,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await AIAPI.getCircuitBreakerStatus();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/circuit/status');
+ expect(result.state).toBe('half-open');
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/aiChat.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/aiChat.branchcov0718.test.ts
new file mode 100644
index 0000000000..efcd5614b9
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/aiChat.branchcov0718.test.ts
@@ -0,0 +1,323 @@
+/**
+ * Branch-coverage tests for currently-uncovered AIChatAPI methods and the
+ * chat() stream's onTrailingParseError handler:
+ * - AIChatAPI.getStatus
+ * - AIChatAPI.createSession
+ * - AIChatAPI.deleteSession
+ * - AIChatAPI.abortSession
+ * - AIChatAPI.denyCommand (reason present vs default)
+ * - AIChatAPI.listAgents
+ * - AIChatAPI.forkSession
+ * - chat()'s onTrailingParseError callback (parseable vs unparseable trailing
+ * buffer)
+ *
+ * The transport is mocked with the same harness used by aiChat.test.ts
+ * (vi.mock('@/utils/apiClient', ...) plus vi.mock('@/utils/logger', ...)).
+ * These tests intentionally do NOT re-assert anything aiChat.test.ts already
+ * covers (listSessions normalization, renameSession, undo/redo, steerSession,
+ * summarizeSession, chat happy-path streaming, fixtures, etc.).
+ *
+ * Branch arms exercised here:
+ * - getStatus returns the apiFetchJSON payload cast to AIStatus
+ * - createSession issues a bare POST with no body and no Content-Type
+ * - deleteSession routes through apiFetch (NOT apiFetchJSON), DELETE method
+ * - deleteSession URL-encodes '/' in the session id (encodeURIComponent arm)
+ * - abortSession routes through apiFetch, POST to the /abort suffix
+ * - abortSession URL-encodes '/' in the session id before appending /abort
+ * - denyCommand truthy-reason branch -> body uses the supplied reason
+ * - denyCommand falsy-reason branch -> body falls back to 'User skipped':
+ * * no second argument supplied
+ * * empty-string reason
+ * - denyCommand URL-encodes '/' in the approval id
+ * - listAgents returns the apiFetchJSON payload cast to Agent[]
+ * - forkSession POSTs to the /fork suffix and URL-encodes the session id
+ * - onTrailingParseError parseable arm: a trailing 'data:' line without a
+ * terminating blank line is parsed and dispatched; onEvent receives the
+ * terminal event and the synthetic close-error is NOT emitted
+ * - onTrailingParseError unparseable arm: a trailing 'data:' line that fails
+ * to parse as JSON triggers logger.warn('[AI Chat] Could not parse
+ * remaining buffer') and then the onComplete handler surfaces the
+ * synthetic 'closed before the response finished' interruption
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+ apiFetch: vi.fn(),
+}));
+
+vi.mock('@/utils/logger', () => ({
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+import { AIChatAPI } from '@/api/aiChat';
+import { apiFetch, apiFetchJSON } from '@/utils/apiClient';
+import { logger } from '@/utils/logger';
+
+describe('AIChatAPI branch coverage', () => {
+ const apiFetchMock = vi.mocked(apiFetch);
+ const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+
+ beforeEach(() => {
+ apiFetchMock.mockReset();
+ apiFetchJSONMock.mockReset();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ describe('getStatus', () => {
+ it('GETs /api/ai/status through apiFetchJSON and returns the AIStatus payload verbatim', async () => {
+ const status = { running: true, engine: 'pulse-assistant' };
+ apiFetchJSONMock.mockResolvedValueOnce(status);
+
+ await expect(AIChatAPI.getStatus()).resolves.toEqual(status);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/status');
+ expect(apiFetchMock).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('createSession', () => {
+ it('POSTs to /api/ai/sessions with no body and no headers (only method)', async () => {
+ const created = {
+ id: 'session-7',
+ title: 'New Chat',
+ created_at: '2026-07-18T10:00:00Z',
+ updated_at: '2026-07-18T10:00:00Z',
+ message_count: 0,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(created);
+
+ await expect(AIChatAPI.createSession()).resolves.toEqual(created);
+
+ // The module passes ONLY { method: 'POST' } — no body, no Content-Type.
+ // (apiFetchJSON adds its own Content-Type downstream; that is the
+ // wrapper's concern, not the module's, so it is not asserted here.)
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/sessions', {
+ method: 'POST',
+ });
+ });
+ });
+
+ describe('deleteSession', () => {
+ it('issues a plain DELETE through apiFetch (no JSON parsing) and resolves void', async () => {
+ // deleteSession uses apiFetch, NOT apiFetchJSON, because the backend
+ // returns 204 No Content. Asserting the resolved value is undefined
+ // confirms the function swallows the response rather than returning it.
+ apiFetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await expect(AIChatAPI.deleteSession('session-1')).resolves.toBeUndefined();
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/sessions/session-1', {
+ method: 'DELETE',
+ });
+ expect(apiFetchJSONMock).not.toHaveBeenCalled();
+ });
+
+ it('URL-encodes slash-bearing session ids in the path', async () => {
+ apiFetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await AIChatAPI.deleteSession('session/root');
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/sessions/session%2Froot', {
+ method: 'DELETE',
+ });
+ });
+ });
+
+ describe('abortSession', () => {
+ it('POSTs to the /abort suffix through apiFetch and resolves void', async () => {
+ apiFetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await expect(AIChatAPI.abortSession('session-1')).resolves.toBeUndefined();
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/sessions/session-1/abort', {
+ method: 'POST',
+ });
+ expect(apiFetchJSONMock).not.toHaveBeenCalled();
+ });
+
+ it('URL-encodes slash-bearing session ids before appending /abort', async () => {
+ apiFetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await AIChatAPI.abortSession('session/root');
+
+ // Only the session id segment is encoded — the literal '/abort' suffix
+ // must remain unencoded so the backend route still matches.
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/sessions/session%2Froot/abort', {
+ method: 'POST',
+ });
+ });
+ });
+
+ describe('denyCommand', () => {
+ it('posts the supplied reason body to the deny endpoint', async () => {
+ const result = { denied: true, message: 'Command denied.' };
+ apiFetchJSONMock.mockResolvedValueOnce(result);
+
+ await expect(AIChatAPI.denyCommand('approval-1', 'Wrong host')).resolves.toEqual(
+ result,
+ );
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/approvals/approval-1/deny', {
+ method: 'POST',
+ body: JSON.stringify({ reason: 'Wrong host' }),
+ });
+ });
+
+ it('substitutes the "User skipped" default when no reason is provided', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ denied: true, message: 'ok' });
+
+ await AIChatAPI.denyCommand('approval-1');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/approvals/approval-1/deny', {
+ method: 'POST',
+ body: JSON.stringify({ reason: 'User skipped' }),
+ });
+ });
+
+ it('treats an empty-string reason as absent (falls back to the default)', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ denied: true, message: 'ok' });
+
+ await AIChatAPI.denyCommand('approval-1', '');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/approvals/approval-1/deny', {
+ method: 'POST',
+ body: JSON.stringify({ reason: 'User skipped' }),
+ });
+ });
+
+ it('URL-encodes slash-bearing approval ids in the path', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ denied: true, message: 'ok' });
+
+ await AIChatAPI.denyCommand('approval/with/slash');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/approvals/approval%2Fwith%2Fslash/deny',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+ });
+
+ describe('listAgents', () => {
+ it('GETs /api/ai/agents and returns the parsed agent array verbatim', async () => {
+ const agents = [
+ {
+ name: 'build',
+ mode: 'subagent',
+ native: true,
+ model: { providerID: 'openrouter', modelID: 'deepseek/deepseek-chat' },
+ },
+ { name: 'code', mode: 'primary', hidden: false },
+ ];
+ apiFetchJSONMock.mockResolvedValueOnce(agents);
+
+ await expect(AIChatAPI.listAgents()).resolves.toEqual(agents);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/agents');
+ });
+ });
+
+ describe('forkSession', () => {
+ it('POSTs to the /fork suffix through apiFetchJSON and returns the forked session', async () => {
+ const forked = {
+ id: 'session-fork',
+ title: 'Fork of session/root',
+ created_at: '2026-07-18T11:00:00Z',
+ updated_at: '2026-07-18T11:00:00Z',
+ message_count: 4,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(forked);
+
+ await expect(AIChatAPI.forkSession('session/root')).resolves.toEqual(forked);
+
+ // The session id is encoded; the literal '/fork' suffix is not.
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/sessions/session%2Froot/fork',
+ { method: 'POST' },
+ );
+ });
+ });
+
+ describe('chat() onTrailingParseError arm', () => {
+ // Stream chunks are authored WITHOUT a trailing '\n\n' so that
+ // consumeJSONEventStream leaves them in `buffer` at EOF, which is exactly
+ // what activates the trailing-buffer branch in src/api/streaming.ts. The
+ // aiChat.ts onTrailingParseError callback is then either bypassed (when the
+ // trailing line parses) or invoked (when it does not).
+
+ it('parses a trailing "data:" line with no terminator as a final event and skips the synthetic close error', async () => {
+ const encoder = new TextEncoder();
+ const read = vi
+ .fn()
+ .mockResolvedValueOnce({
+ done: false,
+ value: encoder.encode('data: {"type":"done","data":{"session_id":"s-1"}}'),
+ })
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ const releaseLock = vi.fn();
+ const onEvent = vi.fn();
+
+ apiFetchMock.mockResolvedValueOnce({
+ ok: true,
+ body: { getReader: () => ({ read, releaseLock }) },
+ } as unknown as Response);
+
+ await AIChatAPI.chat('hello', undefined, undefined, onEvent);
+
+ // The trailing line is parsed by the trailing-buffer arm and dispatched
+ // as a normal event; because 'done' is terminal the stream early-returns
+ // and the onComplete synthetic-close error must NOT fire.
+ expect(onEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'done',
+ data: { session_id: 's-1' },
+ }),
+ );
+ const errorCalls = onEvent.mock.calls.filter(([event]) => event.type === 'error');
+ expect(errorCalls).toHaveLength(0);
+ expect(logger.warn).not.toHaveBeenCalledWith('[AI Chat] Could not parse remaining buffer');
+ expect(releaseLock).toHaveBeenCalledTimes(1);
+ });
+
+ it('invokes onTrailingParseError (and surfaces a synthetic close error) when the trailing line is unparseable', async () => {
+ const encoder = new TextEncoder();
+ const read = vi
+ .fn()
+ .mockResolvedValueOnce({
+ done: false,
+ value: encoder.encode('data: not valid json'),
+ })
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ const releaseLock = vi.fn();
+ const onEvent = vi.fn();
+
+ apiFetchMock.mockResolvedValueOnce({
+ ok: true,
+ body: { getReader: () => ({ read, releaseLock }) },
+ } as unknown as Response);
+
+ await AIChatAPI.chat('hello', undefined, undefined, onEvent);
+
+ // The unparseable trailing line triggers aiChat.ts's onTrailingParseError
+ // handler, whose only effect is a logger.warn call.
+ expect(logger.warn).toHaveBeenCalledWith('[AI Chat] Could not parse remaining buffer');
+ // Because the trailing parse failed, no terminal event was delivered and
+ // onComplete fires, surfacing the synthetic "closed before the response
+ // finished" interruption that lets the user retry the turn.
+ expect(onEvent).toHaveBeenCalledWith({
+ type: 'error',
+ data: { message: expect.stringContaining('closed before the response finished') },
+ });
+ expect(releaseLock).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/connections.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/connections.branchcov0718.test.ts
new file mode 100644
index 0000000000..572684ab36
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/connections.branchcov0718.test.ts
@@ -0,0 +1,275 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { ConnectionsAPI, type Connection, type ConnectionSystem } from '../connections';
+import { apiFetch, apiFetchJSON } from '@/utils/apiClient';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetch: vi.fn(),
+ apiFetchJSON: vi.fn(),
+}));
+
+const mockedApiFetchJSON = vi.mocked(apiFetchJSON);
+const mockedApiFetch = vi.mocked(apiFetch);
+
+const minimalConnection = (overrides: Partial<Connection> = {}): Connection => ({
+ id: 'pve:node1',
+ type: 'pve',
+ name: 'node1',
+ address: 'https://pve.lab:8006',
+ state: 'active',
+ stateReason: '',
+ enabled: true,
+ surfaces: ['vms'],
+ scope: { vms: true },
+ lastSeen: null,
+ lastError: null,
+ source: 'manual',
+ capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
+ ...overrides,
+});
+
+const minimalSystem = (overrides: Partial<ConnectionSystem> = {}): ConnectionSystem => ({
+ id: 'pve:node1',
+ type: 'pve',
+ components: [{ connectionId: 'pve:node1', type: 'pve', role: 'primary' }],
+ ...overrides,
+});
+
+describe('ConnectionsAPI — branch coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('list() envelope normalization', () => {
+ it('normalizes a wire envelope that only carries systems (connections omitted -> [])', async () => {
+ const systems = [minimalSystem()];
+ mockedApiFetchJSON.mockResolvedValueOnce({ systems } as unknown);
+
+ const result = await ConnectionsAPI.list();
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/connections');
+ expect(result).toEqual({ connections: [], systems });
+ });
+
+ it('normalizes a wire envelope that only carries connections (systems omitted -> [])', async () => {
+ const connections = [minimalConnection()];
+ mockedApiFetchJSON.mockResolvedValueOnce({ connections } as unknown);
+
+ const result = await ConnectionsAPI.list();
+
+ expect(result).toEqual({ connections, systems: [] });
+ });
+ });
+
+ describe('probe() request shaping', () => {
+ it('POSTs an empty-string address verbatim as {"address":""} to /api/connections/probe', async () => {
+ const wire = { candidates: [], probedMs: 0 };
+ mockedApiFetchJSON.mockResolvedValueOnce(wire);
+
+ const result = await ConnectionsAPI.probe('');
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/connections/probe', {
+ method: 'POST',
+ body: JSON.stringify({ address: '' }),
+ });
+ expect(result).toEqual(wire);
+ });
+
+ it('JSON-escapes an address that contains a double quote and backslash without corrupting the body', async () => {
+ const address = 'host"name\\path';
+ mockedApiFetchJSON.mockResolvedValueOnce({ candidates: [], probedMs: 1 });
+
+ await ConnectionsAPI.probe(address);
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/connections/probe', {
+ method: 'POST',
+ body: JSON.stringify({ address }),
+ });
+ });
+ });
+
+ describe('setEnabled() routing by connection type', () => {
+ it('pve connection PUTs the full type-prefixed id (encoded) to /api/config/nodes with enabled body', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.setEnabled('pve:node/1', true);
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/config/nodes/pve%3Anode%2F1', {
+ method: 'PUT',
+ body: JSON.stringify({ enabled: true }),
+ });
+ });
+
+ it('pbs connection PUTs the full type-prefixed id (encoded) to /api/config/nodes', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.setEnabled('pbs:store/1', false);
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/config/nodes/pbs%3Astore%2F1', {
+ method: 'PUT',
+ body: JSON.stringify({ enabled: false }),
+ });
+ });
+
+ it('pmg connection PUTs the full type-prefixed id (encoded) to /api/config/nodes', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.setEnabled('pmg:mail/1', true);
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/config/nodes/pmg%3Amail%2F1', {
+ method: 'PUT',
+ body: JSON.stringify({ enabled: true }),
+ });
+ });
+
+ it('vmware connection PUTs only the suffix (encoded) to /api/vmware/connections', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.setEnabled('vmware:vcenter/1', true);
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/vmware/connections/vcenter%2F1', {
+ method: 'PUT',
+ body: JSON.stringify({ enabled: true }),
+ });
+ });
+
+ it('truenas connection PUTs only the suffix (encoded) to /api/truenas/connections', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.setEnabled('truenas:box/1', true);
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/truenas/connections/box%2F1', {
+ method: 'PUT',
+ body: JSON.stringify({ enabled: true }),
+ });
+ });
+
+ it('throws Pause-not-supported for an agent connection id', async () => {
+ await expect(ConnectionsAPI.setEnabled('agent:mini-pc', false)).rejects.toThrow(
+ 'Pause is not supported for agent connections',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ });
+
+ it('throws Pause-not-supported for a docker connection id', async () => {
+ await expect(ConnectionsAPI.setEnabled('docker:runtime/1', true)).rejects.toThrow(
+ 'Pause is not supported for docker connections',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ });
+
+ it('throws Pause-not-supported for a kubernetes connection id', async () => {
+ await expect(ConnectionsAPI.setEnabled('kubernetes:cluster/1', false)).rejects.toThrow(
+ 'Pause is not supported for kubernetes connections',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ });
+
+ it('throws Unknown-connection-type for an unrecognized prefix', async () => {
+ await expect(ConnectionsAPI.setEnabled('foo:bar', true)).rejects.toThrow(
+ 'Unknown connection type: foo',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ });
+
+ it('rejects an id with no colon separator before reaching the type switch', async () => {
+ await expect(ConnectionsAPI.setEnabled('pve-no-colon', true)).rejects.toThrow(
+ 'Invalid connection id: pve-no-colon',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ });
+
+ it('rejects an id whose suffix is empty (trailing colon)', async () => {
+ await expect(ConnectionsAPI.setEnabled('pve:', false)).rejects.toThrow(
+ 'Invalid connection id (empty suffix): pve:',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('remove() routing by connection type', () => {
+ it('pve connection DELETEs the full type-prefixed id (encoded) at /api/config/nodes', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.remove('pve:node/1');
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/config/nodes/pve%3Anode%2F1', {
+ method: 'DELETE',
+ });
+ });
+
+ it('vmware connection DELETEs only the suffix (encoded) at /api/vmware/connections', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.remove('vmware:vcenter/1');
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/vmware/connections/vcenter%2F1', {
+ method: 'DELETE',
+ });
+ });
+
+ it('truenas connection DELETEs only the suffix (encoded) at /api/truenas/connections', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
+
+ await ConnectionsAPI.remove('truenas:box/1');
+
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/truenas/connections/box%2F1', {
+ method: 'DELETE',
+ });
+ });
+
+ it('agent connection delegates to MonitoringAPI.deleteAgent with the suffix path', async () => {
+ mockedApiFetch.mockResolvedValueOnce({
+ ok: true,
+ text: () => Promise.resolve(''),
+ } as unknown as Response);
+
+ await ConnectionsAPI.remove('agent:mini-pc');
+
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ expect(mockedApiFetch).toHaveBeenCalledWith(
+ '/api/agents/agent/mini-pc',
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ });
+
+ it('throws Remove-not-yet-supported for a docker connection id', async () => {
+ await expect(ConnectionsAPI.remove('docker:runtime/1')).rejects.toThrow(
+ 'Remove is not yet supported for docker connections',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ expect(mockedApiFetch).not.toHaveBeenCalled();
+ });
+
+ it('throws Remove-not-yet-supported for a kubernetes connection id', async () => {
+ await expect(ConnectionsAPI.remove('kubernetes:cluster/1')).rejects.toThrow(
+ 'Remove is not yet supported for kubernetes connections',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ expect(mockedApiFetch).not.toHaveBeenCalled();
+ });
+
+ it('throws Unknown-connection-type for an unrecognized prefix on remove', async () => {
+ await expect(ConnectionsAPI.remove('foo:bar')).rejects.toThrow(
+ 'Unknown connection type: foo',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ expect(mockedApiFetch).not.toHaveBeenCalled();
+ });
+
+ it('rejects a remove id with no colon separator', async () => {
+ await expect(ConnectionsAPI.remove('pve-no-colon')).rejects.toThrow(
+ 'Invalid connection id: pve-no-colon',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ expect(mockedApiFetch).not.toHaveBeenCalled();
+ });
+
+ it('rejects a remove id with an empty suffix', async () => {
+ await expect(ConnectionsAPI.remove('vmware:')).rejects.toThrow(
+ 'Invalid connection id (empty suffix): vmware:',
+ );
+ expect(mockedApiFetchJSON).not.toHaveBeenCalled();
+ expect(mockedApiFetch).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/license.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/license.branchcov0718.test.ts
new file mode 100644
index 0000000000..8ba3bf5f18
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/license.branchcov0718.test.ts
@@ -0,0 +1,236 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { LicenseAPI } from '../license';
+import { apiFetchJSON } from '@/utils/apiClient';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+describe('LicenseAPI branch coverage (status / features / activate / clear)', () => {
+ const mock = vi.mocked(apiFetchJSON);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('getStatus', () => {
+ it('GETs the canonical license status endpoint and returns the parsed body untouched', async () => {
+ const status = {
+ valid: true,
+ tier: 'pro',
+ plan_version: 'pro-v1',
+ email: '[email protected]',
+ expires_at: '2027-01-01T00:00:00Z',
+ is_lifetime: false,
+ days_remaining: 180,
+ features: ['relay', 'audit_logging'],
+ max_guests: 25,
+ in_grace_period: false,
+ grace_period_end: null,
+ };
+ mock.mockResolvedValueOnce(status);
+
+ const result = await LicenseAPI.getStatus();
+
+ expect(mock).toHaveBeenCalledTimes(1);
+ // Status reads are a plain GET — no options object is forwarded.
+ expect(mock).toHaveBeenCalledWith('/api/license/status');
+ // The function performs no normalization: the parsed payload is returned verbatim.
+ expect(result).toStrictEqual(status);
+ });
+
+ it('returns a lifetime/community payload verbatim when optional fields are absent', async () => {
+ const status = {
+ valid: true,
+ tier: 'community',
+ is_lifetime: true,
+ days_remaining: 0,
+ features: [],
+ };
+ mock.mockResolvedValueOnce(status);
+
+ const result = await LicenseAPI.getStatus();
+
+ expect(mock).toHaveBeenCalledWith('/api/license/status');
+ // Optional fields (plan_version, email, expires_at, max_guests, in_grace_period, grace_period_end)
+ // are absent on the response and remain absent on the return value.
+ expect(result).toStrictEqual(status);
+ expect('email' in result).toBe(false);
+ expect('expires_at' in result).toBe(false);
+ });
+
+ it('propagates transport errors from a non-ok status response', async () => {
+ mock.mockRejectedValueOnce(new Error('license status unavailable'));
+
+ await expect(LicenseAPI.getStatus()).rejects.toThrow('license status unavailable');
+ expect(mock).toHaveBeenCalledWith('/api/license/status');
+ });
+ });
+
+ describe('getFeatures', () => {
+ it('GETs the features endpoint and returns the parsed feature map untouched', async () => {
+ const features = {
+ license_status: 'active',
+ features: { relay: true, audit_logging: true, sso: false },
+ upgrade_url: '/settings/billing',
+ };
+ mock.mockResolvedValueOnce(features);
+
+ const result = await LicenseAPI.getFeatures();
+
+ expect(mock).toHaveBeenCalledTimes(1);
+ expect(mock).toHaveBeenCalledWith('/api/license/features');
+ expect(result).toStrictEqual(features);
+ });
+
+ it('preserves an empty feature map without coalescing it to a default', async () => {
+ const features = {
+ license_status: 'expired',
+ features: {},
+ upgrade_url: '',
+ };
+ mock.mockResolvedValueOnce(features);
+
+ const result = await LicenseAPI.getFeatures();
+
+ expect(mock).toHaveBeenCalledWith('/api/license/features');
+ // The function does not default-empty feature maps — an empty object stays empty.
+ expect(result.features).toStrictEqual({});
+ expect(result.upgrade_url).toBe('');
+ });
+
+ it('propagates transport errors from a non-ok features response', async () => {
+ mock.mockRejectedValueOnce(new Error('features endpoint down'));
+
+ await expect(LicenseAPI.getFeatures()).rejects.toThrow('features endpoint down');
+ expect(mock).toHaveBeenCalledWith('/api/license/features');
+ });
+ });
+
+ describe('activateLicense', () => {
+ it('POSTs the license key to /activate under the license_key body field', async () => {
+ const activationResponse = {
+ success: true,
+ message: 'License activated',
+ status: {
+ valid: true,
+ tier: 'pro',
+ is_lifetime: false,
+ days_remaining: 365,
+ features: ['relay'],
+ },
+ };
+ mock.mockResolvedValueOnce(activationResponse);
+
+ const result = await LicenseAPI.activateLicense('PULSE-PRO-AAAA-BBBB-CCCC');
+
+ expect(mock).toHaveBeenCalledTimes(1);
+ // Asserts the exact request shape: POST to the fixed activate path with a
+ // JSON body that wraps the raw key under `license_key` (NOT `key`, NOT `licenseKey`).
+ expect(mock).toHaveBeenCalledWith('/api/license/activate', {
+ method: 'POST',
+ body: JSON.stringify({ license_key: 'PULSE-PRO-AAAA-BBBB-CCCC' }),
+ });
+ expect(result).toStrictEqual(activationResponse);
+ // The nested `status` object is passed through untouched (no normalization).
+ expect(result.status).toMatchObject({ tier: 'pro', days_remaining: 365 });
+ });
+
+ it('returns the bare success flag when status/message are absent on the response', async () => {
+ const activationResponse = { success: true };
+ mock.mockResolvedValueOnce(activationResponse);
+
+ const result = await LicenseAPI.activateLicense('K');
+
+ expect(mock).toHaveBeenCalledWith('/api/license/activate', {
+ method: 'POST',
+ body: JSON.stringify({ license_key: 'K' }),
+ });
+ // Optional `status` / `message` fields are absent — function does not synthesize defaults.
+ expect(result).toStrictEqual({ success: true });
+ expect('status' in result).toBe(false);
+ expect('message' in result).toBe(false);
+ });
+
+ it('still POSTs an empty-string key as {"license_key":""} rather than omitting the body field', async () => {
+ mock.mockResolvedValueOnce({ success: false, message: 'empty key' });
+
+ await LicenseAPI.activateLicense('');
+
+ // Empty-string input exercises the unconditional body-construction arm:
+ // there is no `if (licenseKey)` guard, so even "" is serialized.
+ expect(mock).toHaveBeenCalledWith('/api/license/activate', {
+ method: 'POST',
+ body: JSON.stringify({ license_key: '' }),
+ });
+ });
+
+ it('passes keys containing JSON-significant characters through JSON.stringify untouched', async () => {
+ mock.mockResolvedValueOnce({ success: true });
+
+ // Backslash, double-quote and newline would be encoded by JSON.stringify,
+ // confirming the body is built via JSON.stringify({ license_key }) and not naive concat.
+ const trickyKey = 'a"b\\c\n';
+ await LicenseAPI.activateLicense(trickyKey);
+
+ expect(mock).toHaveBeenCalledWith('/api/license/activate', {
+ method: 'POST',
+ body: JSON.stringify({ license_key: trickyKey }),
+ });
+ // Re-derive the encoded form to assert the on-the-wire body, not just call args.
+ expect(JSON.stringify({ license_key: trickyKey })).toBe('{"license_key":"a\\"b\\\\c\\n"}');
+ });
+
+ it('propagates transport errors from a non-ok activate response (rejection invalidates nothing locally)', async () => {
+ mock.mockRejectedValueOnce(new Error('invalid license key'));
+
+ await expect(LicenseAPI.activateLicense('garbage')).rejects.toThrow('invalid license key');
+ expect(mock).toHaveBeenCalledWith('/api/license/activate', {
+ method: 'POST',
+ body: JSON.stringify({ license_key: 'garbage' }),
+ });
+ });
+ });
+
+ describe('clearLicense', () => {
+ it('POSTs an empty JSON object body to /clear and returns the parsed response', async () => {
+ const clearResponse = { success: true, message: 'License cleared' };
+ mock.mockResolvedValueOnce(clearResponse);
+
+ const result = await LicenseAPI.clearLicense();
+
+ expect(mock).toHaveBeenCalledTimes(1);
+ // Distinct body arm from activateLicense: literal `{}` is serialized (not `{ license_key }`).
+ // The body string is exactly two characters — proves no fields are leaked in.
+ expect(mock).toHaveBeenCalledWith('/api/license/clear', {
+ method: 'POST',
+ body: '{}',
+ });
+ expect(result).toStrictEqual(clearResponse);
+ });
+
+ it('returns a bare success:false response verbatim without synthesizing a message', async () => {
+ const clearResponse = { success: false };
+ mock.mockResolvedValueOnce(clearResponse);
+
+ const result = await LicenseAPI.clearLicense();
+
+ expect(mock).toHaveBeenCalledWith('/api/license/clear', {
+ method: 'POST',
+ body: '{}',
+ });
+ expect(result).toStrictEqual({ success: false });
+ expect('message' in result).toBe(false);
+ });
+
+ it('propagates transport errors from a non-ok clear response', async () => {
+ mock.mockRejectedValueOnce(new Error('clear forbidden'));
+
+ await expect(LicenseAPI.clearLicense()).rejects.toThrow('clear forbidden');
+ expect(mock).toHaveBeenCalledWith('/api/license/clear', {
+ method: 'POST',
+ body: '{}',
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/monitoredSystemLedger.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/monitoredSystemLedger.branchcov0718.test.ts
new file mode 100644
index 0000000000..8cb6471859
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/monitoredSystemLedger.branchcov0718.test.ts
@@ -0,0 +1,383 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ MonitoredSystemLedgerAPI,
+ normalizeMonitoredSystemLedgerExplainResponse,
+ normalizeMonitoredSystemLedgerPreviewResponse,
+ normalizeMonitoredSystemLedgerResponse,
+} from '../monitoredSystemLedger';
+import { apiFetchJSON } from '@/utils/apiClient';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+type RawLedgerResponse = Parameters<typeof normalizeMonitoredSystemLedgerResponse>[0];
+type RawPreviewResponse = Parameters<typeof normalizeMonitoredSystemLedgerPreviewResponse>[0];
+type RawExplainResponse = Parameters<typeof normalizeMonitoredSystemLedgerExplainResponse>[0];
+
+describe('MonitoredSystemLedgerAPI branch coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('explain() request shaping', () => {
+ it('posts an empty-object body when invoked with no arguments (default param {})', async () => {
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({
+ ledger: { systems: [], total: 0 },
+ });
+
+ await MonitoredSystemLedgerAPI.explain();
+
+ expect(apiFetchJSON).toHaveBeenCalledWith(
+ '/api/license/monitored-system-ledger/explain',
+ { method: 'POST', body: '{}' },
+ );
+ });
+
+ it('serializes both candidate and replacement objects into the POST body', async () => {
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({
+ ledger: { systems: [], total: 0 },
+ });
+
+ const request = {
+ candidate: {
+ source: 'vmware',
+ hostname: 'esxi-01.lab.local',
+ resource_id: 'vc-1',
+ active: true,
+ },
+ replacement: { resource_id: 'vc-2', hostname: 'esxi-02.lab.local' },
+ };
+ await MonitoredSystemLedgerAPI.explain(request);
+
+ const [path, opts] = vi.mocked(apiFetchJSON).mock.calls[0]!;
+ expect(path).toBe('/api/license/monitored-system-ledger/explain');
+ expect(opts).toEqual({ method: 'POST', body: JSON.stringify(request) });
+ expect(JSON.parse((opts as { body: string }).body)).toEqual(request);
+ });
+ });
+
+ describe('preview() request shaping', () => {
+ it('serializes the full candidate and replacement when every optional field is populated', async () => {
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({
+ current_count: 0,
+ projected_count: 1,
+ additional_count: 1,
+ effect: 'creates_new',
+ current_systems: [],
+ projected_systems: [],
+ });
+
+ const request = {
+ candidate: {
+ source: 'proxmox',
+ type: 'proxmox-node',
+ name: 'pve-01',
+ hostname: 'pve-01.local',
+ host_url: 'https://pve-01.local:8006',
+ agent_id: 'agent-7',
+ machine_id: 'mach-7',
+ resource_id: 'res-7',
+ active: true,
+ },
+ replacement: {
+ source: 'agent',
+ name: 'tower',
+ hostname: 'tower.local',
+ host_url: 'https://tower.local',
+ agent_id: 'agent-9',
+ machine_id: 'mach-9',
+ resource_id: 'res-9',
+ },
+ };
+ await MonitoredSystemLedgerAPI.preview(request);
+
+ const [path, opts] = vi.mocked(apiFetchJSON).mock.calls[0]!;
+ expect(path).toBe('/api/license/monitored-system-ledger/preview');
+ expect(opts).toEqual({ method: 'POST', body: JSON.stringify(request) });
+ });
+ });
+
+ describe('transport error propagation', () => {
+ it('rethrows the underlying apiFetchJSON rejection verbatim', async () => {
+ const error = new Error('network down');
+ vi.mocked(apiFetchJSON).mockRejectedValueOnce(error);
+
+ await expect(MonitoredSystemLedgerAPI.getLedger()).rejects.toBe(error);
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/license/monitored-system-ledger');
+ });
+ });
+
+ describe('normalizeMonitoredSystemLedgerResponse', () => {
+ it('substitutes an empty systems array when the response omits systems entirely', () => {
+ const raw = { total: 0 } as unknown as RawLedgerResponse;
+
+ const result = normalizeMonitoredSystemLedgerResponse(raw);
+
+ expect(result.systems).toEqual([]);
+ expect(result.total).toBe(0);
+ });
+ });
+
+ describe('normalizeMonitoredSystemLedgerPreviewResponse', () => {
+ it('defaults both current_systems and projected_systems to empty arrays when absent', () => {
+ const raw = {
+ current_count: 0,
+ projected_count: 0,
+ additional_count: 0,
+ effect: 'no_change',
+ } as unknown as RawPreviewResponse;
+
+ const result = normalizeMonitoredSystemLedgerPreviewResponse(raw);
+
+ expect(result.current_systems).toEqual([]);
+ expect(result.projected_systems).toEqual([]);
+ expect(result.current_system).toBeNull();
+ expect(result.projected_system).toBeNull();
+ });
+
+ it('returns null for current_system when more than one current_systems entry exists and current_system is null', () => {
+ const raw = {
+ current_count: 2,
+ projected_count: 2,
+ additional_count: 0,
+ effect: 'no_change',
+ current_systems: [
+ { name: 'A', type: 'host', status: 'online', source: 'agent' },
+ { name: 'B', type: 'host', status: 'online', source: 'docker' },
+ ],
+ current_system: null,
+ } as unknown as RawPreviewResponse;
+
+ const result = normalizeMonitoredSystemLedgerPreviewResponse(raw);
+
+ expect(result.current_system).toBeNull();
+ expect(result.current_systems).toHaveLength(2);
+ });
+
+ it('infers projected_system from a sole projected_systems entry when projected_system is null', () => {
+ const raw = {
+ current_count: 0,
+ projected_count: 1,
+ additional_count: 1,
+ effect: 'creates_new',
+ projected_systems: [
+ { name: 'Projected', type: 'host', status: 'unknown', source: 'agent' },
+ ],
+ projected_system: null,
+ } as unknown as RawPreviewResponse;
+
+ const result = normalizeMonitoredSystemLedgerPreviewResponse(raw);
+
+ expect(result.projected_system).toBe(result.projected_systems[0]);
+ expect(result.projected_system?.name).toBe('Projected');
+ });
+ });
+
+ describe('normalizeMonitoredSystemLedgerExplainResponse', () => {
+ it('synthesizes an empty ledger when the response omits ledger entirely', () => {
+ const raw = { preview: null } as unknown as RawExplainResponse;
+
+ const result = normalizeMonitoredSystemLedgerExplainResponse(raw);
+
+ expect(result.ledger.systems).toEqual([]);
+ expect(result.ledger.total).toBe(0);
+ expect(result.preview).toBeNull();
+ });
+
+ it('returns a null preview when preview is explicitly null', () => {
+ const raw = {
+ ledger: { systems: [], total: 0 },
+ preview: null,
+ } as unknown as RawExplainResponse;
+
+ const result = normalizeMonitoredSystemLedgerExplainResponse(raw);
+
+ expect(result.preview).toBeNull();
+ expect(result.ledger.total).toBe(0);
+ });
+
+ it('returns a null preview when preview is undefined', () => {
+ const raw = {
+ ledger: { systems: [], total: 0 },
+ } as unknown as RawExplainResponse;
+
+ const result = normalizeMonitoredSystemLedgerExplainResponse(raw);
+
+ expect(result.preview).toBeNull();
+ });
+ });
+
+ describe('entry / status / signal normalization arms', () => {
+ it('falls back to status-keyed copy and an empty reasons array when status_explanation is absent', () => {
+ const raw = {
+ systems: [{ name: 'N', type: 'host', status: 'warning', source: 'agent' }],
+ total: 1,
+ } as unknown as RawLedgerResponse;
+
+ const [entry] = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(entry.status_explanation.summary).toBe(
+ 'At least one included top-level collection path is degraded, so Pulse marks this monitored system as warning.',
+ );
+ expect(entry.status_explanation.reasons).toEqual([]);
+ });
+
+ it('coerces a missing entry status to unknown and uses the unknown fallback summary', () => {
+ const raw = {
+ systems: [{ name: 'N', type: 'host', source: 'agent' }],
+ total: 1,
+ } as unknown as RawLedgerResponse;
+
+ const [entry] = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(entry.status).toBe('unknown');
+ expect(entry.status_explanation.summary).toBe(
+ 'Pulse cannot determine a canonical runtime status for this monitored system yet.',
+ );
+ });
+
+ it('defaults a missing status_reason.reported_at to an empty string', () => {
+ const raw = {
+ systems: [
+ {
+ name: 'N',
+ type: 'host',
+ status: 'online',
+ source: 'agent',
+ status_explanation: {
+ summary: 's',
+ reasons: [
+ {
+ kind: 'k',
+ name: 'n',
+ type: 'host',
+ source: 'agent',
+ status: 'online',
+ summary: 'sum',
+ },
+ ],
+ },
+ },
+ ],
+ total: 1,
+ } as unknown as RawLedgerResponse;
+
+ const [entry] = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(entry.status_explanation.reasons[0]!.reported_at).toBe('');
+ });
+
+ it('coerces a missing status_reason.status to unknown', () => {
+ const raw = {
+ systems: [
+ {
+ name: 'N',
+ type: 'host',
+ status: 'online',
+ source: 'agent',
+ status_explanation: {
+ summary: 's',
+ reasons: [
+ {
+ kind: 'k',
+ name: 'n',
+ type: 'host',
+ source: 'agent',
+ summary: 'sum',
+ },
+ ],
+ },
+ },
+ ],
+ total: 1,
+ } as unknown as RawLedgerResponse;
+
+ const [entry] = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(entry.status_explanation.reasons[0]!.status).toBe('unknown');
+ });
+
+ it('derives latest_included_signal from entry fields when the signal is entirely absent', () => {
+ const raw = {
+ systems: [
+ { name: 'Cluster', type: 'kubernetes-cluster', status: 'online', source: 'kubernetes' },
+ ],
+ total: 1,
+ } as unknown as RawLedgerResponse;
+
+ const [entry] = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(entry.latest_included_signal).toEqual({
+ name: 'Cluster',
+ type: 'kubernetes-cluster',
+ source: 'kubernetes',
+ at: '',
+ });
+ });
+
+ it('drops the latest_included_signal source when entry.source is "multiple" and the signal omits source', () => {
+ const raw = {
+ systems: [{ name: 'Multi', type: 'host', status: 'online', source: 'multiple' }],
+ total: 1,
+ } as unknown as RawLedgerResponse;
+
+ const [entry] = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(entry.latest_included_signal.source).toBeUndefined();
+ expect(entry.latest_included_signal.name).toBe('Multi');
+ });
+
+ it('falls back to "Unnamed source" and "system" when both the signal and entry name/type are blank', () => {
+ const raw = {
+ systems: [{ name: '', type: '', status: 'online', source: '' }],
+ total: 1,
+ } as unknown as RawLedgerResponse;
+
+ const [entry] = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(entry.latest_included_signal.name).toBe('Unnamed source');
+ expect(entry.latest_included_signal.type).toBe('system');
+ expect(entry.latest_included_signal.source).toBeUndefined();
+ expect(entry.latest_included_signal.at).toBe('');
+ });
+
+ it('lowercases a recognized latest_included_signal source and drops an unrecognized source', () => {
+ const raw = {
+ systems: [
+ {
+ name: 'NAS',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'truenas',
+ latest_included_signal: {
+ name: 'nas1',
+ type: 'truenas-system',
+ source: 'TrueNAS',
+ at: '2026-01-01T00:00:00Z',
+ },
+ },
+ {
+ name: 'Other',
+ type: 'host',
+ status: 'online',
+ source: 'agent',
+ latest_included_signal: {
+ name: 'x',
+ type: 'host',
+ source: 'not-a-real-source',
+ at: '2026-01-01T00:00:00Z',
+ },
+ },
+ ],
+ total: 2,
+ } as unknown as RawLedgerResponse;
+
+ const systems = normalizeMonitoredSystemLedgerResponse(raw).systems;
+
+ expect(systems[0]!.latest_included_signal.source).toBe('truenas');
+ expect(systems[1]!.latest_included_signal.source).toBeUndefined();
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/notifications.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/notifications.branchcov0718.test.ts
new file mode 100644
index 0000000000..0e1706c0e1
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/notifications.branchcov0718.test.ts
@@ -0,0 +1,347 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+import { NotificationsAPI } from '@/api/notifications';
+import type {
+ AppriseConfig,
+ EmailConfig,
+ NotificationTestRequest,
+ Webhook,
+} from '@/api/notifications';
+import { apiFetchJSON } from '@/utils/apiClient';
+
+const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+
+// Pull the JSON body out of a recorded apiFetchJSON(url, opts) call so we can
+// assert the exact request shape the module built — not just "was called".
+const parseBody = (call: unknown[]): unknown => {
+ const opts = call[1] as { body?: string } | undefined;
+ return opts?.body ? JSON.parse(opts.body) : undefined;
+};
+
+describe('NotificationsAPI — branch coverage (0718)', () => {
+ beforeEach(() => {
+ apiFetchJSONMock.mockReset();
+ });
+
+ describe('getAppriseConfig', () => {
+ it('GETs /apprise with no options and returns the parsed payload verbatim', async () => {
+ const payload: AppriseConfig = {
+ enabled: true,
+ mode: 'http',
+ targets: ['tgram://abc'],
+ serverUrl: 'https://apprise.local',
+ apiKey: 'k',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await NotificationsAPI.getAppriseConfig();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/apprise');
+ expect(result).toEqual(payload);
+ });
+ });
+
+ describe('updateAppriseConfig', () => {
+ it('PUTs to /apprise serializing the config object verbatim (no field rewrite)', async () => {
+ const config: AppriseConfig = {
+ enabled: true,
+ mode: 'cli',
+ targets: ['mailto://a@b', 'tgram://c'],
+ cliPath: '/usr/bin/apprise',
+ timeoutSeconds: 15,
+ serverUrl: 'https://apprise.local',
+ configKey: 'pulse',
+ apiKey: 'secret',
+ apiKeyHeader: 'X-Api-Key',
+ skipTlsVerify: false,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(config as any);
+
+ const result = await NotificationsAPI.updateAppriseConfig(config);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/apprise', {
+ method: 'PUT',
+ body: JSON.stringify(config),
+ });
+ expect(parseBody(apiFetchJSONMock.mock.calls[0])).toEqual(config);
+ expect(result).toEqual(config);
+ });
+
+ it('forwards a minimal config (only the required field) untouched', async () => {
+ const minimal: AppriseConfig = { enabled: false };
+ apiFetchJSONMock.mockResolvedValueOnce(minimal as any);
+
+ await NotificationsAPI.updateAppriseConfig(minimal);
+
+ expect(apiFetchJSONMock.mock.calls[0][0]).toBe('/api/notifications/apprise');
+ expect(parseBody(apiFetchJSONMock.mock.calls[0])).toEqual({ enabled: false });
+ });
+ });
+
+ describe('updateEmailConfig', () => {
+ const baseConfig: EmailConfig = {
+ enabled: true,
+ provider: 'smtp',
+ server: 'smtp.example.com',
+ port: 587,
+ username: 'ops',
+ password: 'pw',
+ tls: true,
+ startTLS: false,
+ };
+
+ it('PUTs to /email WITHOUT rateLimit when rateLimit is undefined', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ const result = await NotificationsAPI.updateEmailConfig(baseConfig);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/email', {
+ method: 'PUT',
+ body: expect.any(String),
+ });
+ const body = parseBody(apiFetchJSONMock.mock.calls[0]);
+ // The "rateLimit is undefined" branch: key must be absent entirely.
+ expect(body).not.toHaveProperty('rateLimit');
+ // All other fields pass through with their original names (no rename).
+ expect(body).toEqual({
+ enabled: true,
+ server: 'smtp.example.com',
+ port: 587,
+ username: 'ops',
+ password: 'pw',
+ tls: true,
+ startTLS: false,
+ provider: 'smtp',
+ });
+ expect(result).toEqual({ success: true });
+ });
+
+ it('PUTs to /email WITH rateLimit=0 (rateLimit present-vs-absent branch keeps falsy-but-defined)', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ await NotificationsAPI.updateEmailConfig({ ...baseConfig, rateLimit: 0 });
+
+ const body = parseBody(apiFetchJSONMock.mock.calls[0]);
+ // The `!== undefined` check preserves 0 — distinct from the omit branch.
+ expect(body).toHaveProperty('rateLimit', 0);
+ });
+
+ it('PUTs to /email WITH rateLimit when set to a positive integer', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ await NotificationsAPI.updateEmailConfig({ ...baseConfig, rateLimit: 120 });
+
+ const body = parseBody(apiFetchJSONMock.mock.calls[0]);
+ expect(body).toHaveProperty('rateLimit', 120);
+ });
+ });
+
+ describe('createWebhook', () => {
+ it('POSTs to /webhooks with the webhook payload serialized verbatim', async () => {
+ const webhook: Omit<Webhook, 'id'> = {
+ name: 'PagerDuty',
+ url: 'https://events.pagerduty.com/v2/enqueue',
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: 'Token T' },
+ enabled: true,
+ service: 'pagerduty',
+ customFields: { routing_key: 'abc' },
+ mention: '@everyone',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce({ id: 'wh-1', ...webhook } as any);
+
+ const result = await NotificationsAPI.createWebhook(webhook);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/webhooks', {
+ method: 'POST',
+ body: JSON.stringify(webhook),
+ });
+ expect(parseBody(apiFetchJSONMock.mock.calls[0])).toEqual(webhook);
+ expect(result).toEqual({ id: 'wh-1', ...webhook });
+ });
+ });
+
+ describe('updateWebhook', () => {
+ it('PUTs to /webhooks/:id with the partial body verbatim', async () => {
+ const partial: Partial<Webhook> = { enabled: false, mention: '<@123>' };
+ apiFetchJSONMock.mockResolvedValueOnce({ id: 'wh-7', ...partial } as any);
+
+ const result = await NotificationsAPI.updateWebhook('wh-7', partial);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/webhooks/wh-7', {
+ method: 'PUT',
+ body: JSON.stringify(partial),
+ });
+ expect(result).toEqual({ id: 'wh-7', enabled: false, mention: '<@123>' });
+ });
+
+ it('URL-encodes special characters in the webhook id path segment', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ id: 'a/b c?x=1' } as any);
+
+ await NotificationsAPI.updateWebhook('a/b c?x=1', { enabled: true });
+
+ // encodeURIComponent branch — '/', '?', '=', and space all encoded.
+ const expectedPath = `/api/notifications/webhooks/${encodeURIComponent('a/b c?x=1')}`;
+ expect(apiFetchJSONMock.mock.calls[0][0]).toBe(expectedPath);
+ expect(apiFetchJSONMock.mock.calls[0][0]).toBe(
+ '/api/notifications/webhooks/a%2Fb%20c%3Fx%3D1',
+ );
+ expect(parseBody(apiFetchJSONMock.mock.calls[0])).toEqual({ enabled: true });
+ });
+ });
+
+ describe('getEmailProviders', () => {
+ it('GETs /email-providers with no options and returns the parsed list verbatim', async () => {
+ const providers = [
+ {
+ id: 'gmail',
+ name: 'Gmail',
+ smtpHost: 'smtp.gmail.com',
+ smtpPort: 587,
+ tls: true,
+ startTLS: false,
+ authRequired: true,
+ instructions: 'Use an app password.',
+ },
+ ];
+ apiFetchJSONMock.mockResolvedValueOnce(providers as any);
+
+ const result = await NotificationsAPI.getEmailProviders();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/email-providers');
+ expect(result).toBe(providers);
+ });
+ });
+
+ describe('testNotification', () => {
+ it('includes config and omits webhookId for a config-only email test', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true, message: 'sent' } as any);
+
+ const config = { server: 'smtp.x', port: 25 };
+ const result = await NotificationsAPI.testNotification({
+ type: 'email',
+ config,
+ });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/test', {
+ method: 'POST',
+ body: JSON.stringify({ method: 'email', config }),
+ });
+ expect(result).toEqual({ success: true, message: 'sent' });
+ });
+
+ it('includes webhookId and omits config for a webhook-id-only test', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: false, message: 'no webhook' } as any);
+
+ await NotificationsAPI.testNotification({
+ type: 'webhook',
+ webhookId: 'wh-9',
+ });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/test', {
+ method: 'POST',
+ body: JSON.stringify({ method: 'webhook', webhookId: 'wh-9' }),
+ });
+ });
+
+ it('includes BOTH config and webhookId when both are supplied', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ const appriseCfg: AppriseConfig = {
+ enabled: true,
+ mode: 'cli',
+ targets: ['tgram://x'],
+ };
+ await NotificationsAPI.testNotification({
+ type: 'apprise',
+ config: appriseCfg,
+ webhookId: 'wh-1',
+ });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/test', {
+ method: 'POST',
+ body: JSON.stringify({
+ method: 'apprise',
+ config: appriseCfg,
+ webhookId: 'wh-1',
+ }),
+ });
+ });
+
+ it('omits BOTH config and webhookId when neither is supplied', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ await NotificationsAPI.testNotification({ type: 'email' });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/test', {
+ method: 'POST',
+ body: JSON.stringify({ method: 'email' }),
+ });
+ });
+
+ it('treats a falsy config value as absent (truthy-check branch)', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true } as any);
+
+ // NotificationTestRequest.config is typed as object-only; cast an
+ // empty string through `unknown` to exercise the `if (request.config)`
+ // falsy branch without leaving a tsc error.
+ const req = {
+ type: 'email',
+ config: '',
+ } as unknown as NotificationTestRequest;
+ await NotificationsAPI.testNotification(req);
+
+ const body = parseBody(apiFetchJSONMock.mock.calls[0]);
+ expect(body).toEqual({ method: 'email' });
+ expect(body).not.toHaveProperty('config');
+ });
+
+ it('propagates transport errors unchanged (non-ok response arm)', async () => {
+ const err = new Error('boom');
+ apiFetchJSONMock.mockRejectedValueOnce(err);
+
+ await expect(NotificationsAPI.testNotification({ type: 'email' })).rejects.toBe(err);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/test', {
+ method: 'POST',
+ body: JSON.stringify({ method: 'email' }),
+ });
+ });
+ });
+
+ describe('testWebhook', () => {
+ it('POSTs to /webhooks/test with the webhook payload serialized verbatim', async () => {
+ const webhook: Omit<Webhook, 'id'> = {
+ name: 'Slack',
+ url: 'https://hooks.slack.com/services/x',
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ enabled: true,
+ service: 'slack',
+ mention: '<@channel>',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true, message: 'ok' } as any);
+
+ const result = await NotificationsAPI.testWebhook(webhook);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/notifications/webhooks/test',
+ {
+ method: 'POST',
+ body: JSON.stringify(webhook),
+ },
+ );
+ expect(parseBody(apiFetchJSONMock.mock.calls[0])).toEqual(webhook);
+ expect(result).toEqual({ success: true, message: 'ok' });
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/patrol.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/patrol.branchcov0718.test.ts
new file mode 100644
index 0000000000..750f8307f6
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/patrol.branchcov0718.test.ts
@@ -0,0 +1,352 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+import {
+ acknowledgeFinding,
+ snoozeFinding,
+ dismissFinding,
+ setFindingNote,
+ getPatrolAutonomySettings,
+ getInvestigation,
+ getInvestigationMessages,
+ reinvestigateFinding,
+} from '@/api/patrol';
+import { apiFetchJSON } from '@/utils/apiClient';
+
+describe('patrol api — uncovered branch coverage', () => {
+ const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+
+ beforeEach(() => {
+ apiFetchJSONMock.mockReset();
+ apiFetchJSONMock.mockResolvedValue({ success: true, message: 'ok' } as any);
+ });
+
+ describe('acknowledgeFinding', () => {
+ it('POSTs the canonical finding_id body to /api/ai/patrol/acknowledge', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ success: true,
+ message: 'Finding acknowledged',
+ } as any);
+
+ const result = await acknowledgeFinding('finding-ack-1');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/acknowledge', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-ack-1' }),
+ });
+ expect(result).toEqual({ success: true, message: 'Finding acknowledged' });
+ });
+
+ it('passes the finding id through verbatim (no trimming / encoding at the client)', async () => {
+ await acknowledgeFinding(' raw-id-with-spaces ');
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/acknowledge', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: ' raw-id-with-spaces ' }),
+ });
+ });
+
+ it('propagates transport rejections (non-ok response) to the caller', async () => {
+ const transportError = new Error('Request failed with status 404');
+ apiFetchJSONMock.mockRejectedValueOnce(transportError);
+
+ await expect(acknowledgeFinding('missing')).rejects.toBe(transportError);
+ });
+ });
+
+ describe('snoozeFinding', () => {
+ it('POSTs finding_id + duration_hours to /api/ai/patrol/snooze', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ success: true,
+ message: 'Snoozed for 24h',
+ } as any);
+
+ const result = await snoozeFinding('finding-snooze', 24);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/snooze', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-snooze', duration_hours: 24 }),
+ });
+ expect(result).toEqual({ success: true, message: 'Snoozed for 24h' });
+ });
+
+ it('serializes the 7-day duration (168h) without unit conversion', async () => {
+ await snoozeFinding('finding-7d', 168);
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/snooze', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-7d', duration_hours: 168 }),
+ });
+ });
+
+ it('passes fractional durations through untouched (no integer rounding at the client)', async () => {
+ // The client does no validation/normalization on duration_hours — it is
+ // serialized verbatim. Pinning this so a future "round to integer"
+ // refactor surfaces here rather than silently changing wire shape.
+ await snoozeFinding('finding-half', 0.5);
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/snooze', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-half', duration_hours: 0.5 }),
+ });
+ });
+
+ it('passes a zero duration through (the backend, not the client, owns validation)', async () => {
+ await snoozeFinding('finding-zero', 0);
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/snooze', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-zero', duration_hours: 0 }),
+ });
+ });
+ });
+
+ describe('dismissFinding', () => {
+ it('omits the optional note field entirely when note is not supplied (JSON.stringify drops undefined)', async () => {
+ // Body shape with note===undefined: { finding_id, reason, note: undefined }
+ // JSON.stringify elides undefined-valued keys, so the wire body is just
+ // { finding_id, reason }. This is the absent-note branch.
+ apiFetchJSONMock.mockResolvedValueOnce({
+ success: true,
+ message: 'Dismissed',
+ } as any);
+
+ const result = await dismissFinding('finding-1', 'not_an_issue');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/dismiss', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-1', reason: 'not_an_issue' }),
+ });
+ expect(result).toEqual({ success: true, message: 'Dismissed' });
+ });
+
+ it('includes note as a real string field when supplied (present-note branch)', async () => {
+ await dismissFinding('finding-2', 'expected_behavior', 'planned maintenance window');
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/dismiss', {
+ method: 'POST',
+ body: JSON.stringify({
+ finding_id: 'finding-2',
+ reason: 'expected_behavior',
+ note: 'planned maintenance window',
+ }),
+ });
+ });
+
+ it('keeps an empty-string note on the wire (distinct from absent note)', async () => {
+ // Empty string is a value, not undefined — JSON.stringify keeps `"note":""`.
+ // The two branches must produce distinct wire shapes.
+ await dismissFinding('finding-3', 'will_fix_later', '');
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/dismiss', {
+ method: 'POST',
+ body: JSON.stringify({
+ finding_id: 'finding-3',
+ reason: 'will_fix_later',
+ note: '',
+ }),
+ });
+ });
+
+ it('round-trips the will_fix_later reason verbatim (the only reason with a remind_at side-effect)', async () => {
+ await dismissFinding('finding-wfl', 'will_fix_later', 'next change window');
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/dismiss', {
+ method: 'POST',
+ body: JSON.stringify({
+ finding_id: 'finding-wfl',
+ reason: 'will_fix_later',
+ note: 'next change window',
+ }),
+ });
+ });
+ });
+
+ describe('setFindingNote', () => {
+ it('POSTs finding_id + note to /api/ai/patrol/findings/note', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ success: true,
+ message: 'Note saved',
+ } as any);
+
+ const result = await setFindingNote('finding-note', 'manual triage: low priority');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/findings/note', {
+ method: 'POST',
+ body: JSON.stringify({
+ finding_id: 'finding-note',
+ note: 'manual triage: low priority',
+ }),
+ });
+ expect(result).toEqual({ success: true, message: 'Note saved' });
+ });
+
+ it('sends an empty-string note to clear an existing note (the documented clear branch)', async () => {
+ // Per the JSDoc: "empty string to clear". The client does NOT convert
+ // "" into an absent field — it sends note:"" so the backend can
+ // distinguish "clear my note" from "I never sent one".
+ await setFindingNote('finding-clear', '');
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/ai/patrol/findings/note', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-clear', note: '' }),
+ });
+ });
+ });
+
+ describe('getPatrolAutonomySettings', () => {
+ it('GETs /api/ai/patrol/autonomy and returns the parsed settings verbatim', async () => {
+ const payload = {
+ autonomy_level: 'approval',
+ requested_autonomy_level: 'full',
+ effective_autonomy_level: 'approval',
+ full_mode_unlocked: false,
+ autopilot_acknowledgement: {
+ code: 'acknowledgement_required',
+ active: false,
+ currentVersion: 3,
+ acceptedScope: [],
+ acceptedLimits: {
+ policyAllowlistRequired: true,
+ emergencyStopHonored: true,
+ approvalFloorsHonored: true,
+ verificationReconciledWhenSupported: true,
+ evidenceClassDisclosed: true,
+ inconclusiveOutcomeAllowed: false,
+ executionSuccessIsNotOutcomeTruth: true,
+ },
+ },
+ investigation_budget: 15,
+ investigation_timeout_sec: 300,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(payload as any);
+
+ const result = await getPatrolAutonomySettings();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/autonomy');
+ expect(result).toEqual(payload);
+ // The numeric budget/timeout fields must round-trip unchanged so the
+ // slider UI does not silently clamp on the way back from the server.
+ expect(result.investigation_budget).toBe(15);
+ expect(result.investigation_timeout_sec).toBe(300);
+ });
+ });
+
+ describe('getInvestigation', () => {
+ it('GETs /api/ai/findings/:id/investigation and returns the parsed record', async () => {
+ const investigation = {
+ id: 'inv-1',
+ finding_id: 'finding-inv',
+ session_id: 'sess-1',
+ status: 'completed',
+ started_at: '2026-07-18T00:00:00Z',
+ completed_at: '2026-07-18T00:05:00Z',
+ turn_count: 4,
+ outcome: 'fix_verified',
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(investigation as any);
+
+ const result = await getInvestigation('finding-inv');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/findings/finding-inv/investigation',
+ );
+ expect(result).toEqual(investigation);
+ expect(result.outcome).toBe('fix_verified');
+ });
+
+ it('URL-encodes finding ids that contain path separators', async () => {
+ // The finding id is interpolated into the path with encodeURIComponent.
+ // A slash in the id MUST be percent-encoded, otherwise it would split
+ // the path into a different route.
+ await getInvestigation('tenant/find%');
+
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith(
+ '/api/ai/findings/tenant%2Ffind%25/investigation',
+ );
+ });
+ });
+
+ describe('getInvestigationMessages', () => {
+ it('GETs /api/ai/findings/:id/investigation/messages and returns the parsed envelope', async () => {
+ const envelope = {
+ investigation_id: 'inv-1',
+ session_id: 'sess-1',
+ messages: [
+ {
+ id: 'msg-1',
+ role: 'user',
+ content: 'why is disk full?',
+ timestamp: '2026-07-18T00:00:01Z',
+ },
+ {
+ id: 'msg-2',
+ role: 'assistant',
+ content: 'logs in /var/log grew 40GB',
+ reasoning_content: 'checked du output',
+ timestamp: '2026-07-18T00:00:05Z',
+ },
+ ],
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(envelope as any);
+
+ const result = await getInvestigationMessages('finding-msg');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/findings/finding-msg/investigation/messages',
+ );
+ expect(result).toEqual(envelope);
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1]?.reasoning_content).toBe('checked du output');
+ });
+
+ it('URL-encodes the finding id segment (separate from the messages suffix)', async () => {
+ await getInvestigationMessages('org/find#1');
+
+ // '#' and '/' must both be encoded so neither splits the path nor
+ // starts a fragment.
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith(
+ '/api/ai/findings/org%2Ffind%231/investigation/messages',
+ );
+ });
+ });
+
+ describe('reinvestigateFinding', () => {
+ it('POSTs to /api/ai/findings/:id/reinvestigate with no body', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ success: true,
+ message: 'Reinvestigation queued',
+ } as any);
+
+ const result = await reinvestigateFinding('finding-re');
+
+ // Note: no body key is set — this is the no-body branch (unlike the
+ // other finding mutations which always carry a JSON body).
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/findings/finding-re/reinvestigate',
+ { method: 'POST' },
+ );
+ expect(result).toEqual({ success: true, message: 'Reinvestigation queued' });
+ });
+
+ it('URL-encodes the finding id before interpolating into the path', async () => {
+ await reinvestigateFinding('tenant/finding 1');
+
+ // space -> %20, slash -> %2F
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith(
+ '/api/ai/findings/tenant%2Ffinding%201/reinvestigate',
+ { method: 'POST' },
+ );
+ });
+
+ it('propagates transport errors (e.g. 409 conflict from an in-flight reinvestigation)', async () => {
+ const conflict = new Error('Request failed with status 409');
+ apiFetchJSONMock.mockRejectedValueOnce(conflict);
+
+ await expect(reinvestigateFinding('in-flight')).rejects.toBe(conflict);
+ });
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/vmware.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/vmware.branchcov0718.test.ts
new file mode 100644
index 0000000000..956d276de4
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/vmware.branchcov0718.test.ts
@@ -0,0 +1,240 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { apiFetchJSON } from '@/utils/apiClient';
+import { VMwareAPI } from '@/api/vmware';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+const mockedApiFetchJSON = vi.mocked(apiFetchJSON);
+
+const rawEntry = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
+ name: 'esxi-01',
+ type: 'host',
+ status: 'online',
+ source: 'vmware',
+ ...overrides,
+});
+
+const basePreviewResponse = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
+ current_count: 1,
+ projected_count: 1,
+ additional_count: 0,
+ effect: 'attaches_existing',
+ current_systems: [rawEntry()],
+ projected_systems: [rawEntry({ name: 'esxi-01-projected' })],
+ current_system: null,
+ projected_system: null,
+ ...overrides,
+});
+
+const fullInput = {
+ name: 'lab-vcenter',
+ host: 'vcsa.lab.local',
+ port: 443,
+ username: '[email protected]',
+ password: 'secret',
+ insecureSkipVerify: true,
+ enabled: true,
+ monitorVms: true,
+ monitorHosts: false,
+ monitorDatastores: true,
+};
+
+describe('VMwareAPI.previewConnection — branch coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('POSTs the full serialized input (every optional field present) to /api/vmware/connections/preview and normalizes the response', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(basePreviewResponse() as never);
+
+ const result = await VMwareAPI.previewConnection(fullInput);
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/preview', {
+ method: 'POST',
+ body: JSON.stringify(fullInput),
+ });
+ expect(result.effect).toBe('attaches_existing');
+ expect(result.current_count).toBe(1);
+ expect(result.projected_count).toBe(1);
+ // explicit current_system/projected_system are null; with single-entry lists
+ // the normalizer falls back to the singleton entry.
+ expect(result.current_system?.name).toBe('esxi-01');
+ expect(result.projected_system?.name).toBe('esxi-01-projected');
+ expect(result.current_systems).toHaveLength(1);
+ expect(result.projected_systems).toHaveLength(1);
+ });
+
+ it('serializes a host-only input to {"host": ...} (every optional field absent branch)', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(basePreviewResponse() as never);
+
+ await VMwareAPI.previewConnection({ host: 'vcsa.lab.local' });
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/preview', {
+ method: 'POST',
+ body: JSON.stringify({ host: 'vcsa.lab.local' }),
+ });
+ });
+
+ it('preserves an empty host string verbatim in the serialized body (empty-input branch)', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(basePreviewResponse() as never);
+
+ await VMwareAPI.previewConnection({ host: '' });
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/preview', {
+ method: 'POST',
+ body: JSON.stringify({ host: '' }),
+ });
+ });
+
+ it('selects the single current/projected system when explicit singletons are null', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(
+ basePreviewResponse({
+ current_systems: [rawEntry({ name: 'only-current' })],
+ projected_systems: [rawEntry({ name: 'only-projected' })],
+ current_system: null,
+ projected_system: null,
+ }) as never,
+ );
+
+ const result = await VMwareAPI.previewConnection({ host: 'h' });
+
+ expect(result.current_system?.name).toBe('only-current');
+ expect(result.projected_system?.name).toBe('only-projected');
+ });
+
+ it('nulls current/projected system when both lists are empty and no explicit singleton is provided', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(
+ basePreviewResponse({
+ current_count: 0,
+ projected_count: 0,
+ current_systems: [],
+ projected_systems: [],
+ current_system: null,
+ projected_system: null,
+ }) as never,
+ );
+
+ const result = await VMwareAPI.previewConnection({ host: 'h' });
+
+ expect(result.current_system).toBeNull();
+ expect(result.projected_system).toBeNull();
+ });
+
+ it('nulls current/projected system when lists carry multiple entries', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(
+ basePreviewResponse({
+ current_systems: [rawEntry({ name: 'a' }), rawEntry({ name: 'b' })],
+ projected_systems: [rawEntry({ name: 'c' }), rawEntry({ name: 'd' })],
+ current_system: null,
+ projected_system: null,
+ }) as never,
+ );
+
+ const result = await VMwareAPI.previewConnection({ host: 'h' });
+
+ expect(result.current_system).toBeNull();
+ expect(result.projected_system).toBeNull();
+ });
+
+ it('normalizes explicitly provided current_system and projected_system singletons over the list fallback', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(
+ basePreviewResponse({
+ current_systems: [rawEntry({ name: 'list-current' })],
+ projected_systems: [rawEntry({ name: 'list-projected' })],
+ current_system: rawEntry({ name: 'explicit-current' }),
+ projected_system: rawEntry({ name: 'explicit-projected' }),
+ }) as never,
+ );
+
+ const result = await VMwareAPI.previewConnection({ host: 'h' });
+
+ expect(result.current_system?.name).toBe('explicit-current');
+ expect(result.projected_system?.name).toBe('explicit-projected');
+ });
+
+ it('propagates transport errors from a non-ok response untouched (error arm)', async () => {
+ const transportError = new Error('Request failed with status 502');
+ mockedApiFetchJSON.mockRejectedValueOnce(transportError);
+
+ await expect(VMwareAPI.previewConnection({ host: 'h' })).rejects.toBe(transportError);
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/preview', {
+ method: 'POST',
+ body: JSON.stringify({ host: 'h' }),
+ });
+ });
+});
+
+describe('VMwareAPI.previewSavedConnection — branch coverage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('URL-encodes the id and POSTs the serialized input body to <id>/preview (input-present branch)', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(basePreviewResponse() as never);
+
+ await VMwareAPI.previewSavedConnection('conn/1', fullInput);
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/conn%2F1/preview', {
+ method: 'POST',
+ body: JSON.stringify(fullInput),
+ });
+ });
+
+ it('omits the body entirely when input is undefined (input-absent branch)', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(basePreviewResponse() as never);
+
+ await VMwareAPI.previewSavedConnection('conn-1');
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/conn-1/preview', {
+ method: 'POST',
+ });
+ // Belt-and-braces: confirm no body key was attached by the spread.
+ const [, options] = mockedApiFetchJSON.mock.calls[0]!;
+ expect(options).toEqual({ method: 'POST' });
+ });
+
+ it('serializes a host-only input body and URL-encodes a slash-containing id', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(basePreviewResponse() as never);
+
+ await VMwareAPI.previewSavedConnection('site/a', { host: 'vcsa.lab.local' });
+
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/site%2Fa/preview', {
+ method: 'POST',
+ body: JSON.stringify({ host: 'vcsa.lab.local' }),
+ });
+ });
+
+ it('normalizes the preview response on the saved-connection route (multi-entry list -> null singleton)', async () => {
+ mockedApiFetchJSON.mockResolvedValueOnce(
+ basePreviewResponse({
+ effect: 'removes_existing',
+ current_count: 2,
+ projected_count: 1,
+ current_systems: [rawEntry({ name: 'cur' }), rawEntry({ name: 'cur2' })],
+ projected_systems: [rawEntry({ name: 'proj' })],
+ current_system: null,
+ projected_system: null,
+ }) as never,
+ );
+
+ const result = await VMwareAPI.previewSavedConnection('conn-1');
+
+ expect(result.effect).toBe('removes_existing');
+ expect(result.current_count).toBe(2);
+ expect(result.projected_count).toBe(1);
+ expect(result.current_system).toBeNull();
+ expect(result.projected_system?.name).toBe('proj');
+ });
+
+ it('propagates transport errors from a non-ok response untouched (error arm)', async () => {
+ const transportError = new Error('Request failed with status 404');
+ mockedApiFetchJSON.mockRejectedValueOnce(transportError);
+
+ await expect(VMwareAPI.previewSavedConnection('conn-1')).rejects.toBe(transportError);
+ expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/vmware/connections/conn-1/preview', {
+ method: 'POST',
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/securityScorePresentation.branchcov0718.test.ts b/frontend-modern/src/utils/__tests__/securityScorePresentation.branchcov0718.test.ts
new file mode 100644
index 0000000000..39275a1121
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/securityScorePresentation.branchcov0718.test.ts
@@ -0,0 +1,337 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getSecurityHardeningActions,
+ getSecurityNetworkAccessSubtitle,
+ getSecurityPostureItems,
+ getSecurityScorePresentation,
+ getSecurityWarningPresentation,
+} from '@/utils/securityScorePresentation';
+
+// Branch-coverage companion to securityScorePresentation.test.ts.
+//
+// The sibling suite already exercises one sample per score band (92 / 65 / 25),
+// the public+unauthenticated red warning, the auth-disabled message, the
+// 2-item missing-controls list, the "off" arm of shouldShowGlobalSecurityWarning,
+// both critical/recommended configure-https severities, and a fully-secured
+// posture items snapshot.
+//
+// This file targets the RESIDUAL arms:
+// 1. Score-threshold boundaries (exactly 80, exactly 50, just-below 80, 49, 0).
+// 2. formatList branches: 1-item, 3-item oxford-comma, and 0-item (default
+// "Review the remaining..." message retained).
+// 3. The publicAccess+authenticated arm of the warning message
+// ("reachable from a public network and is still missing ...").
+// 4. The non-Moderate posture arm in the warning background/border ternary
+// (Strong or Weak score still yields a RED background, not yellow).
+// 5. The `unprotectedExportAllowed` second operand of the
+// `!exportProtected || unprotectedExportAllowed` guard in
+// getSecurityHardeningActions, plus the empty-actions case.
+// 6. The "Not configured" / "HTTP only" / "Not enabled" / "Unprotected"
+// negative description arms of every getSecurityPostureItems entry.
+// 7. The publicAccess=true && isPrivateNetwork=true arm of
+// getSecurityNetworkAccessSubtitle (returns "Private" because
+// !isPrivateNetwork is false).
+
+describe('securityScorePresentation — branch coverage (batch 0718)', () => {
+ describe('getSecurityScorePresentation — boundary values for the 80/50 thresholds', () => {
+ it('treats score === 80 as the start of the Strong band (>=80 boundary)', () => {
+ const out = getSecurityScorePresentation(80);
+ expect(out).toMatchObject({ label: 'Strong', icon: 'shield-check' });
+ // Pin every tone field so a silent class rename fails loudly.
+ expect(out.tone).toEqual({
+ headerBg: 'bg-emerald-50 dark:bg-emerald-950',
+ headerBorder: 'border-b border-emerald-200 dark:border-emerald-800',
+ iconWrap: 'bg-emerald-100 dark:bg-emerald-900',
+ icon: 'text-emerald-700 dark:text-emerald-300',
+ subtitle: 'text-emerald-700 dark:text-emerald-300',
+ score: 'text-emerald-800 dark:text-emerald-200',
+ badge: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300',
+ });
+ });
+
+ it('treats score === 79 as Moderate (one below the Strong boundary)', () => {
+ expect(getSecurityScorePresentation(79)).toMatchObject({
+ label: 'Moderate',
+ icon: 'shield',
+ });
+ expect(getSecurityScorePresentation(79).tone.badge).toBe(
+ 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',
+ );
+ });
+
+ it('treats score === 50 as Moderate (>=50 boundary, after >=80 fails)', () => {
+ expect(getSecurityScorePresentation(50)).toMatchObject({
+ label: 'Moderate',
+ icon: 'shield',
+ });
+ expect(getSecurityScorePresentation(50).tone.headerBg).toBe('bg-amber-50 dark:bg-amber-950');
+ });
+
+ it('treats score === 49 as Weak (one below the Moderate boundary)', () => {
+ expect(getSecurityScorePresentation(49)).toMatchObject({
+ label: 'Weak',
+ icon: 'shield-alert',
+ });
+ expect(getSecurityScorePresentation(49).tone.headerBorder).toBe(
+ 'border-b border-rose-200 dark:border-rose-800',
+ );
+ });
+
+ it('treats score === 0 (zero input) as Weak', () => {
+ const out = getSecurityScorePresentation(0);
+ expect(out).toMatchObject({ label: 'Weak', icon: 'shield-alert' });
+ expect(out.tone.score).toBe('text-rose-800 dark:text-rose-200');
+ expect(out.tone.iconWrap).toBe('bg-rose-100 dark:bg-rose-900');
+ });
+ });
+
+ describe('getSecurityWarningPresentation — formatList + message arms', () => {
+ it('formats a 3-item missing-controls list with an Oxford comma', () => {
+ // auth=true, public=false, all three controls missing.
+ const out = getSecurityWarningPresentation({
+ score: 60,
+ publicAccess: false,
+ hasAuthentication: true,
+ apiTokenConfigured: false,
+ exportProtected: false,
+ hasHTTPS: false,
+ });
+ expect(out.message).toBe(
+ 'Authentication is enabled, but this Pulse instance is still missing HTTPS, an API token, and protected exports.',
+ );
+ // Score 60 -> Moderate posture -> yellow tone.
+ expect(out.background).toBe('bg-yellow-50 dark:bg-yellow-900');
+ expect(out.border).toBe('border-yellow-200 dark:border-yellow-800');
+ expect(out.messageClass).toBe('text-base-content');
+ });
+
+ it('formats a single missing control without a trailing conjunction (items.length <= 1 arm)', () => {
+ // Only HTTPS missing; token + export present.
+ const out = getSecurityWarningPresentation({
+ score: 60,
+ publicAccess: false,
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ hasHTTPS: false,
+ });
+ expect(out.message).toBe(
+ 'Authentication is enabled, but this Pulse instance is still missing HTTPS.',
+ );
+ });
+
+ it('keeps the default review message when authentication is enabled and no controls are missing', () => {
+ // The `else if (missingControls.length > 0)` arm is FALSE, so the
+ // initial default message is preserved.
+ const out = getSecurityWarningPresentation({
+ score: 40,
+ publicAccess: false,
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ hasHTTPS: true,
+ });
+ expect(out.message).toBe(
+ 'Review the remaining security settings before using this instance for live infrastructure.',
+ );
+ // Weak score (40 < 50) -> non-Moderate arm -> red tone despite auth ok.
+ expect(out.background).toBe('bg-red-50 dark:bg-red-900');
+ expect(out.border).toBe('border-red-200 dark:border-red-800');
+ });
+
+ it('uses the public-reachability message arm when publicAccess && hasAuthentication', () => {
+ const out = getSecurityWarningPresentation({
+ score: 60,
+ publicAccess: true,
+ hasAuthentication: true,
+ apiTokenConfigured: false,
+ exportProtected: true,
+ hasHTTPS: false,
+ });
+ expect(out.message).toBe(
+ 'This Pulse instance is reachable from a public network and is still missing HTTPS and an API token.',
+ );
+ });
+
+ it('returns a red (non-Moderate) tone even for a Strong score in the missing-controls path', () => {
+ // Subtle: a Strong score (>=80) with auth enabled but one missing control
+ // still lands on the red ternary arm because posture.label !== 'Moderate'.
+ const out = getSecurityWarningPresentation({
+ score: 85,
+ publicAccess: false,
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ hasHTTPS: false,
+ });
+ expect(out.message).toBe(
+ 'Authentication is enabled, but this Pulse instance is still missing HTTPS.',
+ );
+ expect(out.background).toBe('bg-red-50 dark:bg-red-900');
+ expect(out.border).toBe('border-red-200 dark:border-red-800');
+ });
+ });
+
+ describe('getSecurityHardeningActions — residual guard and empty-result arms', () => {
+ it('returns an empty array when the posture is fully hardened (every guard false)', () => {
+ expect(
+ getSecurityHardeningActions({
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ unprotectedExportAllowed: false,
+ hasHTTPS: true,
+ hasAuditLogging: true,
+ requiresAuth: true,
+ publicAccess: false,
+ isPrivateNetwork: true,
+ }),
+ ).toEqual([]);
+ });
+
+ it('fires protect-exports via the unprotectedExportAllowed operand even when exportProtected is true', () => {
+ // The `!status.exportProtected || status.unprotectedExportAllowed`
+ // guard's second operand is the only one that can be true here.
+ const actions = getSecurityHardeningActions({
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ unprotectedExportAllowed: true,
+ hasHTTPS: true,
+ hasAuditLogging: true,
+ requiresAuth: true,
+ publicAccess: false,
+ isPrivateNetwork: true,
+ });
+ expect(actions.map((a) => a.key)).toEqual(['protect-exports']);
+ expect(actions[0]).toMatchObject({ key: 'protect-exports', severity: 'critical' });
+ expect(actions[0].title).toBe('Protect exports');
+ expect(actions[0].description).toContain('Backup and export flows');
+ });
+ });
+
+ describe('getSecurityPostureItems — negative description and enabled=false arms', () => {
+ it('renders every "Not configured" / "HTTP only" / "Not enabled" description for an all-false posture', () => {
+ const items = getSecurityPostureItems({
+ hasAuthentication: false,
+ ssoEnabled: false,
+ hasProxyAuth: false,
+ apiTokenConfigured: false,
+ exportProtected: false,
+ unprotectedExportAllowed: false,
+ hasHTTPS: false,
+ hasAuditLogging: false,
+ requiresAuth: false,
+ publicAccess: false,
+ isPrivateNetwork: true,
+ });
+ // Seven canonical items in declared order.
+ expect(items.map((i) => i.key)).toEqual([
+ 'password',
+ 'oidc',
+ 'proxy',
+ 'token',
+ 'export',
+ 'https',
+ 'audit',
+ ]);
+ const byKey = Object.fromEntries(items.map((i) => [i.key, i]));
+ expect(byKey.password).toMatchObject({
+ label: 'Password login',
+ enabled: false,
+ description: 'Not configured',
+ critical: true,
+ });
+ expect(byKey.oidc).toMatchObject({
+ label: 'Single sign-on',
+ enabled: false,
+ description: 'Not configured',
+ critical: false,
+ });
+ expect(byKey.proxy).toMatchObject({
+ label: 'Proxy auth',
+ enabled: false,
+ description: 'Not configured',
+ critical: false,
+ });
+ expect(byKey.token).toMatchObject({
+ label: 'API token',
+ enabled: false,
+ description: 'Not configured',
+ critical: false,
+ });
+ // exportProtected=false AND unprotectedExportAllowed=false: enabled flag is
+ // `exportProtected && !unprotectedExportAllowed` = false, and the
+ // description falls through to the else ('Token + passphrase required').
+ expect(byKey.export).toMatchObject({
+ label: 'Export protection',
+ enabled: false,
+ description: 'Token + passphrase required',
+ critical: true,
+ });
+ expect(byKey.https).toMatchObject({
+ label: 'HTTPS',
+ enabled: false,
+ description: 'HTTP only',
+ critical: true,
+ });
+ expect(byKey.audit).toMatchObject({
+ label: 'Audit log',
+ enabled: false,
+ description: 'Not enabled',
+ critical: false,
+ });
+ });
+
+ it('marks export as Unprotected (enabled=false) when unprotectedExportAllowed is true', () => {
+ const items = getSecurityPostureItems({
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ unprotectedExportAllowed: true,
+ hasHTTPS: true,
+ hasAuditLogging: true,
+ requiresAuth: true,
+ });
+ const exportItem = items.find((i) => i.key === 'export');
+ expect(exportItem).toBeDefined();
+ // `exportProtected && !unprotectedExportAllowed` = true && !true = false.
+ expect(exportItem).toMatchObject({
+ enabled: false,
+ description: 'Unprotected',
+ critical: true,
+ });
+ });
+ });
+
+ describe('getSecurityNetworkAccessSubtitle — public+private overlap arm', () => {
+ it('returns "Private network access" when publicAccess is true but isPrivateNetwork is also true', () => {
+ // The `!isPrivateNetwork` operand flips the AND to false.
+ expect(
+ getSecurityNetworkAccessSubtitle({
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ hasAuditLogging: true,
+ requiresAuth: true,
+ publicAccess: true,
+ isPrivateNetwork: true,
+ }),
+ ).toBe('Private network access');
+ });
+
+ it('returns "Private network access" when publicAccess is false (isPrivateNetwork operand never evaluated)', () => {
+ expect(
+ getSecurityNetworkAccessSubtitle({
+ hasAuthentication: true,
+ apiTokenConfigured: true,
+ exportProtected: true,
+ hasAuditLogging: true,
+ requiresAuth: true,
+ publicAccess: false,
+ isPrivateNetwork: false,
+ }),
+ ).toBe('Private network access');
+ });
+ });
+});