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.

13.8 KB
Raw Blame
import { describe, expect, it, vi, beforeEach } from 'vitest';
import {
  ConnectionsAPI,
  type Connection,
  type ConnectionSystem,
  type ProbeResponse,
} from '../connections';
import { apiFetchJSON } from '@/utils/apiClient';

vi.mock('@/utils/apiClient', () => ({
  apiFetchJSON: vi.fn(),
}));

const mockedApiFetchJSON = vi.mocked(apiFetchJSON);

describe('ConnectionsAPI', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('list() calls GET /api/connections and returns the canonical ledger envelope', async () => {
    const connections: Connection[] = [
      {
        id: 'pve-lab',
        type: 'pve',
        name: 'lab',
        address: 'https://pve.lab:8006',
        hostAliases: ['lab', '192.168.0.2'],
        state: 'active',
        stateReason: '',
        enabled: true,
        surfaces: ['vms', 'containers'],
        scope: { vms: true, containers: true },
        lastSeen: '2026-04-19T10:00:00Z',
        lastError: null,
        source: 'manual',
        capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
      },
    ];
    const systems: ConnectionSystem[] = [
      {
        id: 'pve-lab',
        type: 'pve',
        clusterName: 'homelab',
        components: [{ connectionId: 'pve-lab', type: 'pve', role: 'primary' }],
        members: [
          {
            id: 'node-lab',
            name: 'lab',
            endpoint: 'https://lab:8006',
            hostAliases: ['lab', '192.168.0.2'],
            state: 'active',
            lastSeen: '2026-04-23T12:00:00Z',
            primary: true,
          },
        ],
      },
    ];
    mockedApiFetchJSON.mockResolvedValueOnce({ connections, systems });

    const result = await ConnectionsAPI.list();

    expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/connections');
    expect(result).toEqual({ connections, systems });
  });

  it('list() keeps a degraded partial-read row and its error category', async () => {
    const connections: Connection[] = [
      {
        id: 'pmg:mail',
        type: 'pmg',
        name: 'mail',
        address: 'https://pmg.lan:8006',
        state: 'degraded',
        stateReason: 'pmg_queue_status failed on mail: API error 500',
        enabled: true,
        surfaces: ['queues'],
        scope: { queues: true },
        lastSeen: '2026-10-26T12:00:00Z',
        lastError: {
          at: '2026-10-26T12:00:00Z',
          message: 'pmg_queue_status failed on mail: API error 500',
          category: 'partial',
        },
        source: 'manual',
        capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
      },
    ];
    mockedApiFetchJSON.mockResolvedValueOnce({ connections, systems: [] });

    const result = await ConnectionsAPI.list();

    expect(result.connections[0]).toMatchObject({
      state: 'degraded',
      lastError: { category: 'partial' },
    });
  });

  it('list() normalizes missing fields to empty collections', async () => {
    mockedApiFetchJSON.mockResolvedValueOnce({} as { connections?: Connection[] });

    const result = await ConnectionsAPI.list();

    expect(result).toEqual({ connections: [], systems: [] });
  });

  it('list() preserves agent version metadata on agent-backed connections', async () => {
    const connections: Connection[] = [
      {
        id: 'agent:mini-pc',
        type: 'agent',
        name: 'mini-pc',
        address: 'mini-pc',
        state: 'active',
        stateReason: '',
        enabled: true,
        surfaces: ['host'],
        scope: { host: true },
        lastSeen: '2026-04-22T20:00:00Z',
        lastError: null,
        source: 'agent',
        agentVersion: '6.0.0',
        expectedAgentVersion: '6.0.3',
        agentUpdateAvailable: true,
        capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
      },
    ];
    mockedApiFetchJSON.mockResolvedValueOnce({ connections });

    const result = await ConnectionsAPI.list();

    expect(result.connections[0]).toMatchObject({
      agentVersion: '6.0.0',
      expectedAgentVersion: '6.0.3',
      agentUpdateAvailable: true,
    });
  });

  it('list() preserves integration provenance on integration-monitored machine rows', async () => {
    const connections: Connection[] = [
      {
        id: 'agent:vc-1:host:host-101',
        type: 'agent',
        name: 'esxi-01.lab.local',
        address: 'esxi-01.lab.local',
        state: 'active',
        stateReason: '',
        enabled: true,
        surfaces: ['host'],
        scope: { host: true },
        lastSeen: '2026-07-21T12:00:00Z',
        lastError: null,
        source: 'agent',
        integrationSource: 'vmware',
        capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
      },
    ];
    mockedApiFetchJSON.mockResolvedValueOnce({ connections });

    const result = await ConnectionsAPI.list();

    expect(result.connections[0].integrationSource).toBe('vmware');
  });

  it('list() preserves fleet governance metadata on connection rows', async () => {
    const connections: Connection[] = [
      {
        id: 'agent:mini-pc',
        type: 'agent',
        name: 'mini-pc',
        address: 'mini-pc',
        state: 'active',
        stateReason: '',
        enabled: true,
        surfaces: ['host'],
        scope: { host: true },
        lastSeen: '2026-04-22T20:00:00Z',
        lastError: null,
        source: 'agent',
        fleet: {
          enrollmentState: 'enrolled',
          livenessState: 'active',
          versionDrift: 'behind',
          adapterHealth: 'healthy',
          configRollout: 'reported',
          credentialStatus: 'verified',
          updateStatus: 'update-available',
          remoteControl: 'disconnected',
          configDrift: {
            status: 'drifted',
            desired: { version: 'host-agent-config/v1', hash: 'sha256:desired' },
            applied: { version: 'host-agent-config/v1', hash: 'sha256:applied' },
            reason: 'desired fingerprint differs from applied runtime',
          },
          rollout: {
            status: 'pending',
            stage: 'canary',
            reason: 'waiting for the agent to apply staged config',
          },
          credentialHealth: {
            status: 'verified',
            kind: 'agent-token',
            rotation: 'healthy',
            lastVerifiedAt: '2026-04-22T20:00:00Z',
          },
          commandPolicy: {
            status: 'blocked',
            desired: 'enabled',
            applied: 'enabled',
            enforcement: 'blocked',
            reason: 'agent command channel is not connected',
          },
        },
        capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
      },
    ];
    mockedApiFetchJSON.mockResolvedValueOnce({ connections });

    const result = await ConnectionsAPI.list();

    expect(result.connections[0]?.fleet).toEqual({
      enrollmentState: 'enrolled',
      livenessState: 'active',
      versionDrift: 'behind',
      adapterHealth: 'healthy',
      configRollout: 'reported',
      credentialStatus: 'verified',
      updateStatus: 'update-available',
      remoteControl: 'disconnected',
      configDrift: {
        status: 'drifted',
        desired: { version: 'host-agent-config/v1', hash: 'sha256:desired' },
        applied: { version: 'host-agent-config/v1', hash: 'sha256:applied' },
        reason: 'desired fingerprint differs from applied runtime',
      },
      rollout: {
        status: 'pending',
        stage: 'canary',
        reason: 'waiting for the agent to apply staged config',
      },
      credentialHealth: {
        status: 'verified',
        kind: 'agent-token',
        rotation: 'healthy',
        lastVerifiedAt: '2026-04-22T20:00:00Z',
      },
      commandPolicy: {
        status: 'blocked',
        desired: 'enabled',
        applied: 'enabled',
        enforcement: 'blocked',
        reason: 'agent command channel is not connected',
      },
    });
  });

  it('list() preserves pending agent config drift without an applied fingerprint', async () => {
    const connections: Connection[] = [
      {
        id: 'agent:mini-pc',
        type: 'agent',
        name: 'mini-pc',
        address: 'mini-pc',
        state: 'active',
        stateReason: '',
        enabled: true,
        surfaces: ['host'],
        scope: { host: true },
        lastSeen: '2026-04-22T20:00:00Z',
        lastError: null,
        source: 'agent',
        fleet: {
          enrollmentState: 'enrolled',
          livenessState: 'active',
          versionDrift: 'current',
          adapterHealth: 'healthy',
          configRollout: 'reported',
          credentialStatus: 'verified',
          updateStatus: 'current',
          remoteControl: 'enabled',
          configDrift: {
            status: 'pending',
            desired: { version: 'host-agent-config/v1', hash: 'sha256:desired' },
            reason:
              'Pulse has not received a comparable applied agent configuration fingerprint yet',
          },
          rollout: {
            status: 'pending',
            stage: 'pending',
            reason: 'waiting for the agent to report an applied configuration fingerprint',
          },
        },
        capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
      },
    ];
    mockedApiFetchJSON.mockResolvedValueOnce({ connections });

    const result = await ConnectionsAPI.list();

    expect(result.connections[0]?.fleet?.configDrift).toEqual({
      status: 'pending',
      desired: { version: 'host-agent-config/v1', hash: 'sha256:desired' },
      reason: 'Pulse has not received a comparable applied agent configuration fingerprint yet',
    });
    expect(result.connections[0]?.fleet?.rollout).toEqual({
      status: 'pending',
      stage: 'pending',
      reason: 'waiting for the agent to report an applied configuration fingerprint',
    });
  });

  it('list() preserves agent identity metadata on agent-backed connections', async () => {
    const connections: Connection[] = [
      {
        id: 'agent:tower',
        type: 'agent',
        name: 'Tower',
        address: 'Tower',
        state: 'active',
        stateReason: '',
        enabled: true,
        surfaces: ['host'],
        scope: { host: true },
        lastSeen: '2026-04-23T13:00:00Z',
        lastError: null,
        source: 'agent',
        agentIdentity: {
          hostname: 'tower',
          platform: 'linux',
          hostProfile: 'unraid',
          osName: 'Unraid',
          osVersion: '7.1.0',
          kernelVersion: '6.12.0',
          architecture: 'x86_64',
          reportIp: '192.168.0.10',
          commandsEnabled: true,
        },
        capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
      },
    ];
    mockedApiFetchJSON.mockResolvedValueOnce({ connections });

    const result = await ConnectionsAPI.list();

    expect(result.connections[0]).toMatchObject({
      agentIdentity: {
        hostname: 'tower',
        platform: 'linux',
        hostProfile: 'unraid',
        osName: 'Unraid',
        osVersion: '7.1.0',
        kernelVersion: '6.12.0',
        architecture: 'x86_64',
        reportIp: '192.168.0.10',
        commandsEnabled: true,
      },
    });
  });

  it('list() preserves canonical host alias metadata on connections and grouped members', async () => {
    mockedApiFetchJSON.mockResolvedValueOnce({
      connections: [
        {
          id: 'agent:pi',
          type: 'agent',
          name: 'pi',
          address: 'pi',
          hostAliases: ['pi', '192.168.0.2'],
          state: 'active',
          stateReason: '',
          enabled: true,
          surfaces: ['host'],
          scope: { host: true },
          lastSeen: '2026-04-23T13:00:00Z',
          lastError: null,
          source: 'agent',
          capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
        },
      ],
      systems: [
        {
          id: 'pve:pi',
          type: 'pve',
          components: [
            { connectionId: 'pve:pi', type: 'pve', role: 'primary' },
            { connectionId: 'agent:pi', type: 'agent', role: 'attachment' },
          ],
          members: [
            {
              id: 'pve:pi:member',
              name: 'pi',
              endpoint: 'https://pi:8006',
              hostAliases: ['pi', '192.168.0.2'],
              state: 'active',
            },
          ],
        },
      ],
    });

    const result = await ConnectionsAPI.list();

    expect(result.connections[0]?.hostAliases).toEqual(['pi', '192.168.0.2']);
    expect(result.systems[0]?.members?.[0]?.hostAliases).toEqual(['pi', '192.168.0.2']);
  });

  it('probe() POSTs the address JSON and returns the candidates envelope', async () => {
    const response: ProbeResponse = {
      candidates: [
        {
          type: 'pve',
          host: 'https://pve.lab:8006',
          port: 8006,
          hints: { product: 'Proxmox VE', version: '8.2.4' },
        },
      ],
      probedMs: 812,
    };
    mockedApiFetchJSON.mockResolvedValueOnce(response);

    const result = await ConnectionsAPI.probe('pve.lab');

    expect(mockedApiFetchJSON).toHaveBeenCalledWith('/api/connections/probe', {
      method: 'POST',
      body: JSON.stringify({ address: 'pve.lab' }),
    });
    expect(result).toEqual(response);
  });

  it('routes availability pause and remove actions to availability targets', async () => {
    mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
    await ConnectionsAPI.setEnabled('availability:sensor/1', false);
    expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/availability-targets/sensor%2F1', {
      method: 'PUT',
      body: JSON.stringify({ enabled: false }),
    });

    mockedApiFetchJSON.mockResolvedValueOnce({ success: true });
    await ConnectionsAPI.remove('availability:sensor/1');
    expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/availability-targets/sensor%2F1', {
      method: 'DELETE',
    });
  });
});