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.

43.7 KB
Raw Blame
import {
  cleanup,
  fireEvent,
  render,
  renderHook,
  screen,
  waitFor,
  within,
} from '@solidjs/testing-library';
import { afterEach, describe, expect, it, vi } from 'vitest';
import infrastructureSourceManagerSource from '../InfrastructureSourceManager.tsx?raw';
import {
  InfrastructureSourceManager,
  agentConnectionIDsForInfrastructureRow,
} from '../InfrastructureSourceManager';
import {
  fleetGovernanceSignalsForConnection,
  primaryRowProblem,
  visibleFleetGovernanceSignals,
  type FleetGovernanceSignal,
  type InfrastructureSystemMemberRow,
  type InfrastructureSystemRow,
} from '../connectionsTableModel';
import type { Connection } from '@/api/connections';
import { eventBus } from '@/stores/events';
import { ConnectionsAPI } from '@/api/connections';
import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
import { useConnectionsLedger } from '../useConnectionsLedger';

const clusterDeployApi = vi.hoisted(() => ({
  getCandidates: vi.fn(),
  createPreflight: vi.fn(),
  getPreflight: vi.fn(),
  createJob: vi.fn(),
  getJob: vi.fn(),
}));

vi.mock('@/api/agentDeploy', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@/api/agentDeploy')>();
  return { ...actual, ClusterAgentDeployAPI: clusterDeployApi };
});

const connectionFixture = (overrides: Partial<Connection> = {}): Connection => ({
  id: 'agent:host-1',
  type: 'agent',
  name: 'host-1',
  address: 'host-1',
  state: 'active',
  stateReason: '',
  enabled: true,
  surfaces: ['host'],
  scope: { host: true },
  lastSeen: '2026-04-23T12:00:00Z',
  lastError: null,
  source: 'agent',
  capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
  ...overrides,
});

const signal = (overrides: Partial<FleetGovernanceSignal>): FleetGovernanceSignal => ({
  key: 'liveness',
  label: 'Fleet OK',
  detail: 'No fleet warnings.',
  tone: 'ok',
  ...overrides,
});

const row = (overrides: Partial<InfrastructureSystemRow> = {}): InfrastructureSystemRow => {
  const connection = overrides.connection ?? connectionFixture();
  const fleetSignals = overrides.fleetSignals ?? [
    signal({ key: 'liveness', label: 'Live', tone: 'ok' }),
  ];
  const fleetHighlights = overrides.fleetHighlights ?? [signal({})];
  return {
    id: connection.id,
    ownerType: connection.type,
    name: connection.name,
    subtitle: 'via Pulse Agent',
    source: 'agent',
    host: connection.address,
    coverageLabels: ['Host telemetry'],
    statusLabel: 'Active',
    statusClassName: 'bg-green-100 text-green-800',
    agentUpdateCount: 0,
    lastActivityText: '5s ago',
    fleetSignals,
    fleetHighlights,
    problem: overrides.problem ?? primaryRowProblem(fleetHighlights),
    enabled: connection.enabled,
    canEdit: false,
    canPause: false,
    canRemove: true,
    isAgent: connection.type === 'agent',
    isCluster: false,
    attachedConnections: [],
    members: [],
    connection,
    ...overrides,
  };
};

const member = (
  overrides: Partial<InfrastructureSystemMemberRow> = {},
): InfrastructureSystemMemberRow => {
  const fleetHighlights = overrides.fleetHighlights ?? [];
  return {
    id: overrides.id ?? 'member-1',
    name: overrides.name ?? 'member-1',
    subtitle: overrides.subtitle ?? 'Cluster member',
    source: overrides.source ?? 'agent',
    host: overrides.host ?? 'https://member-1:8006',
    coverageLabels: overrides.coverageLabels ?? ['Host telemetry'],
    statusLabel: overrides.statusLabel ?? 'Active',
    statusClassName: overrides.statusClassName ?? 'bg-green-100 text-green-800',
    lastActivityText: overrides.lastActivityText ?? '5s ago',
    fleetSignals: overrides.fleetSignals ?? [],
    fleetHighlights,
    problem: overrides.problem ?? primaryRowProblem(fleetHighlights),
    primary: overrides.primary ?? false,
    agentConnection: overrides.agentConnection,
  };
};

describe('InfrastructureSourceManager setup summary', () => {
  afterEach(() => {
    cleanup();
    resetCreateNonSuspendingQueryCacheForTest();
    vi.restoreAllMocks();
    Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1024 });
  });

  const renderReadState = (readOnly = false, withCandidate = false) => {
    const { result: ledger } = renderHook(() => useConnectionsLedger());
    const onOpenConnection = vi.fn();
    render(() => (
      <InfrastructureSourceManager
        rows={ledger.rows}
        inventoryLoading={!ledger.resolvedOnce() || ledger.loading()}
        inventoryError={ledger.error()}
        onRetryInventory={ledger.reload}
        discoveredNodes={() =>
          withCandidate ? [{ ip: '192.0.2.1', port: 8006, type: 'pve', version: '8.4' }] : []
        }
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={readOnly}
        onOpenConnection={onOpenConnection}
      />
    ));
    return { ledger, onOpenConnection };
  };

  it('distinguishes an unread list from empty and keeps a failed read visible during retry', async () => {
    let failFirst!: (error: unknown) => void;
    let recover!: (value: Awaited<ReturnType<typeof ConnectionsAPI.list>>) => void;
    const list = vi
      .spyOn(ConnectionsAPI, 'list')
      .mockImplementationOnce(
        () =>
          new Promise((_, reject) => {
            failFirst = reject;
          }),
      )
      .mockImplementationOnce(
        () =>
          new Promise((resolve) => {
            recover = resolve;
          }),
      );
    const { onOpenConnection } = renderReadState(false, true);
    expect(screen.getByRole('status')).toHaveTextContent('Loading connected systems...');
    expect(screen.queryByText('0 systems connected')).toBeNull();
    expect(screen.queryByText('Start monitoring infrastructure')).toBeNull();

    failFirst({ status: 503 });
    await waitFor(() =>
      expect(screen.getByRole('alert')).toHaveTextContent('Connected systems unavailable'),
    );
    expect(screen.queryByText('0 systems connected')).toBeNull();
    expect(screen.queryByText('Start monitoring infrastructure')).toBeNull();
    // Discovery cannot safely deduplicate candidates against unread inventory.
    expect(screen.queryByText('192.0.2.1')).toBeNull();
    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    expect(screen.getByRole('button', { name: 'Retrying...' })).toBeDisabled();
    expect(screen.getByRole('alert')).toHaveTextContent('Connected systems unavailable');
    expect(list).toHaveBeenCalledTimes(2);

    const saved = connectionFixture({
      id: 'pve:saved',
      type: 'pve',
      name: 'Saved scoped PVE',
      state: 'paused',
      enabled: false,
      address: 'https://saved.invalid:8006',
      scope: { vms: false, storage: true },
    });
    recover({ connections: [saved], systems: [] });
    await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
    expect(screen.getByText('Saved scoped PVE')).toBeInTheDocument();
    expect(screen.getByText('Paused')).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Manage' }));
    expect(onOpenConnection.mock.calls[0][0].connection).toEqual(saved);
    expect(list).toHaveBeenCalledTimes(2);
  });

  it('labels retained rows as old after a transient failure and restores posture only on success', async () => {
    const saved = connectionFixture({ name: 'Last saved host' });
    const list = vi
      .spyOn(ConnectionsAPI, 'list')
      .mockResolvedValue({ connections: [saved], systems: [] });
    const { ledger } = renderReadState();
    await waitFor(() => expect(screen.getByText('1 system connected')).toBeInTheDocument());
    list.mockRejectedValueOnce({ status: 503 });
    ledger.reload();
    await waitFor(() =>
      expect(screen.getByRole('alert')).toHaveTextContent(
        'Showing the last loaded list. Connection status may be out of date.',
      ),
    );
    expect(screen.getByText('Last saved host')).toBeInTheDocument();
    expect(screen.queryByText('All active')).toBeNull();
    expect(screen.queryByText('1 system connected')).toBeNull();
    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(screen.getByText('1 system connected')).toBeInTheDocument());
    expect(screen.queryByRole('alert')).toBeNull();
    expect(list).toHaveBeenCalledTimes(3);
  });

  it.each([401, 403])(
    'withdraws retained rows on HTTP %s without claiming absence',
    async (status) => {
      const list = vi.spyOn(ConnectionsAPI, 'list').mockResolvedValue({
        connections: [connectionFixture({ name: 'Private host' })],
        systems: [],
      });
      const { ledger } = renderReadState(true);
      await waitFor(() => expect(screen.getByText('Private host')).toBeInTheDocument());
      list.mockRejectedValueOnce({ status });
      ledger.reload();
      await waitFor(() =>
        expect(screen.getByRole('alert')).toHaveTextContent(
          status === 401 ? 'Sign in again' : 'Access denied',
        ),
      );
      expect(screen.queryByText('Private host')).toBeNull();
      expect(screen.queryByText('0 systems connected')).toBeNull();
      expect(screen.queryByText('Start monitoring infrastructure')).toBeNull();
      // Reading is still available without a configuration-write grant.
      expect(screen.getByRole('button', { name: 'Retry' })).toBeEnabled();
    },
  );

  it('withdraws the old organisation while its replacement is unread, then permits genuine empty onboarding', async () => {
    const list = vi.spyOn(ConnectionsAPI, 'list').mockResolvedValueOnce({
      connections: [connectionFixture({ name: 'Old org host' })],
      systems: [],
    });
    const { ledger } = renderReadState();
    await waitFor(() => expect(screen.getByText('Old org host')).toBeInTheDocument());
    list.mockRejectedValueOnce({ status: 503 });
    eventBus.emit('org_switched', 'org-b');
    expect(screen.queryByText('Old org host')).toBeNull();
    await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
    expect(ledger.rows()).toEqual([]);
    expect(screen.queryByText('0 systems connected')).toBeNull();
    list.mockResolvedValueOnce({ connections: [], systems: [] });
    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(screen.getByText('0 systems connected')).toBeInTheDocument());
    expect(screen.getByText('Start monitoring infrastructure')).toBeInTheDocument();
    expect(screen.queryByRole('alert')).toBeNull();
  });

  it('renders the canonical first-report label through the real connection ledger', async () => {
    resetCreateNonSuspendingQueryCacheForTest();
    vi.spyOn(ConnectionsAPI, 'list').mockResolvedValue({
      connections: [connectionFixture({ state: 'pending', name: 'Waiting host' })],
      systems: [],
    });
    const ledger = renderHook(() => useConnectionsLedger());
    await waitFor(() => expect(ledger.result.rows()).toHaveLength(1));
    const onOpenConnection = vi.fn();
    render(() => (
      <InfrastructureSourceManager
        rows={ledger.result.rows}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSource={vi.fn()}
        onAddInfrastructure={vi.fn()}
        onOpenConnection={onOpenConnection}
        onOpenAgentDoctor={vi.fn()}
      />
    ));
    expect(screen.getByText('Waiting for first report')).toBeInTheDocument();
    expect(screen.queryByText('Unreachable')).toBeNull();
    fireEvent.click(screen.getByRole('button', { name: /^Manage$/i }));
    expect(onOpenConnection).toHaveBeenCalled();
  });

  it('renders manual discovery as a visible operator action', () => {
    const onRunDiscovery = vi.fn();
    const onOpenDiscoverySettings = vi.fn();
    const onAddSourceStep = vi.fn();

    render(() => (
      <InfrastructureSourceManager
        rows={() => []}
        discoveredNodes={() => []}
        discoveryEnabled
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSourceStep={onAddSourceStep}
        onRunDiscovery={onRunDiscovery}
        onOpenDiscoverySettings={onOpenDiscoverySettings}
      />
    ));

    expect(screen.queryByRole('button', { name: /^Monitor endpoint$/i })).toBeNull();
    expect(onAddSourceStep).not.toHaveBeenCalled();
    const discovery = screen.getByRole('region', { name: /^Discover Proxmox systems$/i });
    expect(within(discovery).getByText('Ready')).toBeInTheDocument();
    expect(
      within(discovery).getByText(
        /Run discovery to look for unattached Proxmox VE, Proxmox Backup Server, and Proxmox Mail Gateway APIs/i,
      ),
    ).toBeInTheDocument();

    fireEvent.click(within(discovery).getByRole('button', { name: /^Run discovery$/i }));
    expect(onRunDiscovery).toHaveBeenCalledTimes(1);

    expect(within(discovery).getByRole('button', { name: /^Run discovery$/i })).toHaveClass(
      'min-h-11',
      'lg:min-h-9',
    );
    const discoverySettings = within(discovery).getByRole('button', { name: /^Settings$/i });
    expect(discoverySettings).toHaveClass('min-h-11', 'lg:min-h-9');
    fireEvent.click(discoverySettings);
    expect(onOpenDiscoverySettings).toHaveBeenCalledTimes(1);
  });

  it('keeps phone inventory actions touch-sized without changing desktop density', () => {
    render(() => (
      <InfrastructureSourceManager
        rows={() => [row()]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSource={vi.fn()}
        onAddInfrastructure={vi.fn()}
        onOpenConnection={vi.fn()}
        onOpenAgentDoctor={vi.fn()}
      />
    ));

    expect(screen.getByRole('button', { name: /^Add infrastructure$/i })).toHaveClass(
      'min-h-11',
      'lg:min-h-9',
    );
    expect(screen.getByRole('button', { name: /^Open Agent Doctor$/i })).toHaveClass(
      'min-h-11',
      'lg:min-h-9',
    );
    expect(screen.getByRole('button', { name: /^Add Pulse Agent hosts$/i })).toHaveClass(
      'min-h-11',
      'lg:min-h-0',
    );
    expect(infrastructureSourceManagerSource).toContain(
      'class="min-h-11 min-w-18 shrink-0 lg:min-h-0"',
    );
    // Desktop rows stay one 33px line like the platform tables: 4px cell
    // padding, a system line that never wraps its badges, and actions that
    // overhang the row.
    expect(infrastructureSourceManagerSource).toContain(
      '<TableCell class="py-1 pl-3 pr-3 align-middle">',
    );
    expect(infrastructureSourceManagerSource).not.toMatch(/<TableCell class="[^"]*py-1\.5/);
    expect(infrastructureSourceManagerSource).not.toContain(
      'flex min-w-0 flex-wrap items-center gap-1.5',
    );
    expect(infrastructureSourceManagerSource).toContain(
      '-my-0.5 flex items-center justify-end gap-1.5',
    );
  });

  it.each([1440, 390])('keeps visible Add and update labels in scoped names at %ipx', (width) => {
    Object.defineProperty(window, 'innerWidth', { configurable: true, value: width });
    const onAddSource = vi.fn();
    const onOpenAgentDoctor = vi.fn();
    const outdated = connectionFixture({ id: 'agent:outdated', agentUpdateAvailable: true });
    const second = connectionFixture({ id: 'agent:second', agentUpdateAvailable: true });
    const current = connectionFixture({ id: 'agent:current', agentUpdateAvailable: false });
    const rows = [
      row({
        id: 'fleet',
        name: 'Fleet alpha',
        agentUpdateCount: 2,
        connection: outdated,
        attachedConnections: [second, current],
      }),
    ];
    const view = render(() => (
      <InfrastructureSourceManager
        rows={() => rows}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSource={onAddSource}
        onOpenAgentDoctor={onOpenAgentDoctor}
      />
    ));
    const add = screen.getByRole('button', { name: 'Add Pulse Agent hosts' });
    expect(add).toHaveTextContent('Add');
    expect(add).toHaveAttribute('title', 'Install Pulse Agent');
    fireEvent.click(add);
    expect(onAddSource).toHaveBeenCalledExactlyOnceWith('agent');
    const label = width < 1024 ? '2 agent updates' : '2 updates';
    const update = screen.getByRole('button', {
      name: `${label}: open Agent Doctor for Fleet alpha`,
    });
    expect(update).toHaveTextContent(label);
    fireEvent.click(update);
    expect(onOpenAgentDoctor).toHaveBeenCalledExactlyOnceWith(['agent:outdated', 'agent:second']);
    view.unmount();
    render(() => (
      <InfrastructureSourceManager
        rows={() => rows}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly
        onAddSource={onAddSource}
        onOpenAgentDoctor={onOpenAgentDoctor}
      />
    ));
    expect(screen.queryByRole('button', { name: 'Add Pulse Agent hosts' })).not.toBeInTheDocument();
    expect(
      screen.queryByRole('button', { name: /open Agent Doctor for Fleet alpha/ }),
    ).not.toBeInTheDocument();
    expect(screen.getByText(label)).toBeInTheDocument();
  });

  it('keeps manual discovery observable while a scan is running', () => {
    const onRunDiscovery = vi.fn();

    render(() => (
      <InfrastructureSourceManager
        rows={() => []}
        discoveredNodes={() => []}
        discoveryEnabled
        discoveryScanStatus={() => ({
          scanning: true,
          subnet: '10.0.0.0/24',
          lastScanStartedAt: Date.now(),
        })}
        readOnly={false}
        onRunDiscovery={onRunDiscovery}
      />
    ));

    const discovery = screen.getByRole('region', { name: /^Discover Proxmox systems$/i });
    expect(within(discovery).getByText('Scanning')).toBeInTheDocument();
    expect(
      within(discovery).getByText(
        /Pulse is scanning 10\.0\.0\.0\/24 for Proxmox VE, Proxmox Backup Server, and Proxmox Mail Gateway APIs/i,
      ),
    ).toBeInTheDocument();
    expect(within(discovery).getByRole('button', { name: /^Scanning\.\.\.$/i })).toBeDisabled();
  });

  it('keeps discovered candidates in the discovery monitor instead of hiding them in the table', () => {
    const onReviewDiscoveredSource = vi.fn();
    const candidate = {
      ip: '10.0.0.55',
      port: 8006,
      type: 'pve' as const,
      version: '8.2.2',
      hostname: 'discovered-pve.lab',
    };

    render(() => (
      <InfrastructureSourceManager
        rows={() => []}
        discoveredNodes={() => [candidate]}
        discoveryEnabled
        discoveryScanStatus={() => ({ scanning: false, lastResultAt: Date.now() })}
        readOnly={false}
        onReviewDiscoveredSource={onReviewDiscoveredSource}
      />
    ));

    const discovery = screen.getByRole('region', { name: /^Discover Proxmox systems$/i });
    expect(within(discovery).getByText('1 to review')).toBeInTheDocument();
    expect(
      within(discovery).getByText(/Review and add credentials before Pulse starts monitoring it/i),
    ).toBeInTheDocument();

    fireEvent.click(within(discovery).getByRole('button', { name: /^Review candidate$/i }));
    expect(onReviewDiscoveredSource).toHaveBeenCalledWith(candidate);
    expect(screen.getByText('discovered-pve.lab')).toBeInTheDocument();
  });

  it('keeps setup status compact while preserving row-level attention signals', () => {
    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'availability:meter',
            ownerType: 'availability',
            name: 'MQTT power meter',
            subtitle: 'via availability probe',
            source: 'probe',
            host: 'power-meter-01.lab.local',
            coverageLabels: ['Availability'],
            connection: connectionFixture({
              id: 'availability:meter',
              type: 'availability',
              name: 'MQTT power meter',
              address: 'power-meter-01.lab.local',
              source: 'manual',
              surfaces: ['availability'],
              scope: { availability: true },
            }),
            fleetSignals: [signal({ key: 'liveness', label: 'Live', tone: 'ok' })],
            fleetHighlights: [],
          }),
          row({
            fleetSignals: [
              signal({ key: 'liveness', label: 'Live', tone: 'ok' }),
              signal({ key: 'remote-control', label: 'Remote control enabled', tone: 'info' }),
            ],
            fleetHighlights: [
              signal({ key: 'remote-control', label: 'Remote control enabled', tone: 'info' }),
            ],
          }),
          row({
            id: 'pve:lab',
            ownerType: 'pve',
            name: 'lab',
            source: 'api',
            connection: connectionFixture({
              id: 'pve:lab',
              type: 'pve',
              name: 'lab',
              source: 'manual',
              capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
            }),
            fleetSignals: [
              signal({ key: 'liveness', label: 'Unauthorized', tone: 'critical' }),
              signal({ key: 'credentials', label: 'Credentials invalid', tone: 'critical' }),
            ],
            fleetHighlights: [
              signal({ key: 'credentials', label: 'Credentials invalid', tone: 'critical' }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly
      />
    ));

    expect(screen.getByText('Connection posture')).toBeInTheDocument();
    expect(screen.getByText('2 systems connected')).toBeInTheDocument();
    expect(screen.queryByText('MQTT power meter')).toBeNull();
    expect(screen.getByText('All active')).toBeInTheDocument();
    expect(screen.getByText('1 system needs attention')).toBeInTheDocument();
    expect(screen.getByText('1 host has limited coverage')).toBeInTheDocument();
    expect(screen.queryByText('Fleet governance')).toBeNull();
    // The row now surfaces a single plain-English problem line under its
    // status badge instead of a chip-per-signal stack. Info-toned signals
    // (e.g. "Remote control enabled") aren't problems and don't render.
    expect(screen.getByText('Credentials invalid')).toBeInTheDocument();
    expect(screen.queryByText('Remote control enabled')).toBeNull();
  });

  it('does not count hidden passive agent config handshakes as setup attention', () => {
    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            fleetSignals: [
              signal({
                key: 'config-drift',
                label: 'Config pending',
                detail:
                  'Pulse has not received a comparable applied agent configuration fingerprint yet',
                tone: 'warning',
              }),
              signal({
                key: 'rollout',
                label: 'Rollout pending',
                detail: 'waiting for the agent to report an applied configuration fingerprint',
                tone: 'warning',
              }),
              signal({
                key: 'command-policy',
                label: 'Remote control disabled',
                tone: 'info',
              }),
            ],
            fleetHighlights: [
              signal({
                key: 'command-policy',
                label: 'Remote control disabled',
                tone: 'info',
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly
      />
    ));

    expect(screen.queryByText(/needs attention/i)).toBeNull();
    expect(screen.queryByText('Config pending')).toBeNull();
    expect(screen.queryByText('Rollout pending')).toBeNull();
  });

  it('keeps fleet version-drift update chips scoped to the affected agent', () => {
    const behindAgent = connectionFixture({
      id: 'agent:behind-host',
      agentUpdateAvailable: false,
      fleet: { versionDrift: 'behind' } as Connection['fleet'],
    });
    const behindRow = row({
      id: behindAgent.id,
      name: 'behind-host',
      agentUpdateCount: 1,
      connection: behindAgent,
    });
    const onOpenAgentDoctor = vi.fn();

    expect(agentConnectionIDsForInfrastructureRow(behindRow, true)).toEqual(['agent:behind-host']);

    render(() => (
      <InfrastructureSourceManager
        rows={() => [behindRow]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onOpenAgentDoctor={onOpenAgentDoctor}
      />
    ));

    fireEvent.click(
      screen.getByRole('button', { name: 'Agent update: open Agent Doctor for behind-host' }),
    );
    expect(onOpenAgentDoctor).toHaveBeenCalledWith(['agent:behind-host']);
  });

  it('flags an outdated agent once, as an update rather than as attention', () => {
    const outdated = connectionFixture({
      id: 'agent:outdated-host',
      name: 'outdated-host',
      agentUpdateAvailable: true,
      fleet: {
        enrollmentState: 'enrolled',
        livenessState: 'active',
        versionDrift: 'behind',
        adapterHealth: 'healthy',
        configRollout: 'reported',
        credentialStatus: 'verified',
        updateStatus: 'update-available',
        remoteControl: 'disabled',
      },
    });
    const fleetSignals = fleetGovernanceSignalsForConnection(outdated);
    const outdatedRow = row({
      connection: outdated,
      agentUpdateCount: 1,
      fleetSignals,
      fleetHighlights: visibleFleetGovernanceSignals(fleetSignals),
      problem: primaryRowProblem(visibleFleetGovernanceSignals(fleetSignals, Infinity)),
    });

    render(() => (
      <InfrastructureSourceManager
        rows={() => [outdatedRow]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onOpenAgentDoctor={vi.fn()}
      />
    ));

    expect(
      screen.getByRole('button', { name: 'Agent update: open Agent Doctor for outdated-host' }),
    ).toHaveTextContent('Agent update');
    expect(screen.queryByText('Version behind')).toBeNull();
    expect(screen.queryByText(/needs? attention/i)).toBeNull();
    expect(screen.getByText('1 agent update available')).toBeInTheDocument();
  });

  it('still counts actionable member posture when the cluster parent is healthy', () => {
    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'pve:homelab',
            ownerType: 'pve',
            name: 'homelab',
            source: 'both',
            isCluster: true,
            fleetSignals: [signal({ key: 'liveness', label: 'Live', tone: 'ok' })],
            fleetHighlights: [signal({ key: 'liveness', label: 'Fleet OK', tone: 'ok' })],
            members: [
              member({
                id: 'node-delly',
                name: 'delly',
                fleetSignals: [
                  signal({
                    key: 'config-drift',
                    label: 'Config drift',
                    detail: 'Desired and applied fingerprints differ.',
                    tone: 'warning',
                  }),
                ],
                fleetHighlights: [
                  signal({
                    key: 'config-drift',
                    label: 'Config drift',
                    detail: 'Desired and applied fingerprints differ.',
                    tone: 'warning',
                  }),
                ],
                primary: true,
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly
      />
    ));

    expect(screen.getByText('1 system needs attention')).toBeInTheDocument();
    // "Fleet OK" is no longer rendered as a synthetic ok-chip; an empty
    // problem line is the absence of trouble. The cluster-member row
    // surfaces its single actionable problem ("Config drift") with the
    // detail attached as a tooltip.
    expect(screen.queryByText('Fleet OK')).toBeNull();
    expect(screen.queryByText('Config drift')).toBeNull();
    fireEvent.click(screen.getByRole('button', { name: 'Show 1 node for homelab' }));
    expect(screen.getByText('Config drift')).toHaveAttribute(
      'title',
      'Desired and applied fingerprints differ.',
    );
  });

  it('shows one cluster API connection while retaining member reachability addresses', () => {
    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'pve:remote-cluster',
            ownerType: 'pve',
            name: 'Remote cluster',
            subtitle: 'Proxmox VE cluster',
            source: 'api',
            host: 'https://management.example.test:8006',
            isCluster: true,
            coverageLabels: ['Nodes', 'Guests', 'Storage'],
            connection: connectionFixture({
              id: 'pve:remote-cluster',
              type: 'pve',
              name: 'Remote cluster',
              address: 'https://management.example.test:8006',
              source: 'manual',
              surfaces: ['nodes', 'guests', 'storage'],
              scope: { nodes: true, guests: true, storage: true },
              capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
            }),
            members: [
              member({
                id: 'pve-a',
                name: 'pve-a',
                source: 'api',
                host: 'https://10.15.5.11:8006',
                coverageLabels: ['Cluster API'],
              }),
              member({
                id: 'pve-b',
                name: 'pve-b',
                source: 'api',
                host: 'https://10.15.5.12:8006',
                coverageLabels: ['Cluster API'],
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly
      />
    ));

    expect(screen.getAllByText('API')).toHaveLength(1);

    fireEvent.click(screen.getByRole('button', { name: 'Show 2 nodes for Remote cluster' }));

    expect(screen.getAllByText('API')).toHaveLength(1);
    expect(screen.getByText('https://10.15.5.11:8006')).toBeInTheDocument();
    expect(screen.getByText('https://10.15.5.12:8006')).toBeInTheDocument();
  });

  it('keeps onboarding visible for each uncovered member of a partly instrumented cluster', () => {
    const onAddSourceStep = vi.fn();
    const attachedAgent = connectionFixture({
      id: 'agent:pve-a',
      name: 'pve-a',
      address: 'pve-a',
    });

    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'pve:remote-cluster',
            ownerType: 'pve',
            name: 'Remote cluster',
            subtitle: 'Cluster · 2 nodes',
            source: 'both',
            coverageLabels: ['Nodes', 'Guests', 'Storage'],
            isCluster: true,
            canEdit: true,
            connection: connectionFixture({
              id: 'pve:remote-cluster',
              type: 'pve',
              name: 'Remote cluster',
              source: 'manual',
              capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
            }),
            attachedConnections: [attachedAgent],
            members: [
              member({
                id: 'pve-a',
                name: 'pve-a',
                source: 'both',
                agentConnection: attachedAgent,
              }),
              member({
                id: 'pve-b',
                name: 'pve-b',
                source: 'api',
                coverageLabels: [],
                agentConnection: undefined,
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSourceStep={onAddSourceStep}
        onOpenConnection={vi.fn()}
      />
    ));

    expect(screen.getByText('1 host has limited coverage')).toBeInTheDocument();
    expect(screen.getByText('1 node needs host telemetry')).toBeInTheDocument();
    const clusterInstallAction = screen.getByRole('button', {
      name: 'Install node agents on 1 uncovered node in Remote cluster',
    });
    expect(clusterInstallAction).toHaveTextContent('Install node agents');

    fireEvent.click(screen.getByRole('button', { name: 'Show 2 nodes for Remote cluster' }));
    expect(screen.queryByRole('button', { name: 'Install agent on pve-a' })).toBeNull();
    const installOnPveB = screen.getByRole('button', { name: 'Install agent on pve-b' });
    fireEvent.click(installOnPveB);

    expect(onAddSourceStep).toHaveBeenCalledWith('linux-host');
  });

  it('installs uncovered cluster members in one step when a sibling already runs the agent', async () => {
    clusterDeployApi.getCandidates.mockResolvedValue({
      clusterId: 'remote',
      clusterName: 'remote',
      sourceAgents: [{ agentId: 'agent-pve-a', nodeId: 'n-a', online: true }],
      nodes: [
        { nodeId: 'n-a', name: 'pve-a', ip: '10.15.5.11', hasAgent: true, deployable: false },
        { nodeId: 'n-b', name: 'pve-b', ip: '10.15.5.12', hasAgent: false, deployable: true },
      ],
    });
    const onAddSourceStep = vi.fn();
    const attachedAgent = connectionFixture({ id: 'agent:pve-a', name: 'pve-a', address: 'pve-a' });

    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'pve:remote-cluster',
            ownerType: 'pve',
            name: 'remote',
            clusterName: 'remote',
            subtitle: 'Cluster · 2 nodes',
            source: 'both',
            isCluster: true,
            canEdit: true,
            connection: connectionFixture({
              id: 'pve:remote-cluster',
              type: 'pve',
              name: 'remote',
              source: 'manual',
              capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
            }),
            attachedConnections: [attachedAgent],
            members: [
              member({
                id: 'pve-a',
                name: 'pve-a',
                source: 'both',
                agentConnection: attachedAgent,
              }),
              member({
                id: 'pve-b',
                name: 'pve-b',
                source: 'api',
                coverageLabels: [],
                agentConnection: undefined,
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSourceStep={onAddSourceStep}
        onOpenConnection={vi.fn()}
      />
    ));

    fireEvent.click(screen.getByRole('button', { name: 'Show 2 nodes for remote' }));
    fireEvent.click(screen.getByRole('button', { name: 'Install agent on pve-b' }));

    const dialog = await screen.findByRole('dialog', {
      name: 'Install Pulse Agent on remote nodes',
    });
    expect(await within(dialog).findByRole('checkbox', { name: /pve-b/ })).toBeChecked();
    expect(clusterDeployApi.getCandidates).toHaveBeenCalledWith('remote');
    expect(onAddSourceStep).not.toHaveBeenCalled();
  });

  it('keeps a started cluster install going after the dialog is closed', async () => {
    clusterDeployApi.getCandidates.mockResolvedValue({
      clusterId: 'remote',
      clusterName: 'remote',
      sourceAgents: [{ agentId: 'agent-pve-a', nodeId: 'n-a', online: true }],
      nodes: [
        { nodeId: 'n-a', name: 'pve-a', ip: '10.15.5.11', hasAgent: true, deployable: false },
        { nodeId: 'n-b', name: 'pve-b', ip: '10.15.5.12', hasAgent: false, deployable: true },
      ],
    });
    clusterDeployApi.createPreflight.mockResolvedValue({ preflightId: 'pf_r', status: 'running' });
    clusterDeployApi.getPreflight.mockResolvedValue({
      id: 'pf_r',
      clusterId: 'remote',
      status: 'succeeded',
      targets: [
        { id: 't1', nodeId: 'n-b', nodeName: 'pve-b', nodeIP: '10.15.5.12', status: 'ready' },
      ],
    });
    clusterDeployApi.createJob.mockResolvedValue({
      jobId: 'dep_r',
      acceptedTargets: ['n-b'],
      skippedTargets: [],
    });
    clusterDeployApi.getJob.mockResolvedValue({
      id: 'dep_r',
      clusterId: 'remote',
      status: 'failed',
      targets: [
        {
          id: 't2',
          nodeId: 'n-b',
          nodeName: 'pve-b',
          nodeIP: '10.15.5.12',
          status: 'failed_permanent',
        },
      ],
    });
    const attachedAgent = connectionFixture({ id: 'agent:pve-a', name: 'pve-a', address: 'pve-a' });

    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'pve:remote-cluster',
            ownerType: 'pve',
            name: 'remote',
            clusterName: 'remote',
            subtitle: 'Cluster · 2 nodes',
            source: 'both',
            isCluster: true,
            canEdit: true,
            connection: connectionFixture({
              id: 'pve:remote-cluster',
              type: 'pve',
              name: 'remote',
              source: 'manual',
              capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
            }),
            attachedConnections: [attachedAgent],
            members: [
              member({
                id: 'pve-a',
                name: 'pve-a',
                source: 'both',
                agentConnection: attachedAgent,
              }),
              member({
                id: 'pve-b',
                name: 'pve-b',
                source: 'api',
                coverageLabels: [],
                agentConnection: undefined,
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSourceStep={vi.fn()}
        onOpenConnection={vi.fn()}
      />
    ));

    fireEvent.click(screen.getByRole('button', { name: 'Show 2 nodes for remote' }));
    fireEvent.click(screen.getByRole('button', { name: 'Install agent on pve-b' }));
    const dialog = await screen.findByRole('dialog', {
      name: 'Install Pulse Agent on remote nodes',
    });
    fireEvent.click(await within(dialog).findByRole('button', { name: 'Install on 1 node' }));
    fireEvent.click(await within(dialog).findByRole('button', { name: 'Close' }));

    // The parent has unmounted the dialog; the run must still start the install
    // with the cluster it captured, rather than reading a stale accessor.
    expect(screen.queryByRole('dialog')).toBeNull();
    await waitFor(
      () =>
        expect(clusterDeployApi.createJob).toHaveBeenCalledWith('remote', 'agent-pve-a', 'pf_r', [
          'n-b',
        ]),
      { timeout: 6000 },
    );
  });

  it('offers the same uncovered-node onboarding in the narrow card layout', () => {
    Object.defineProperty(window, 'innerWidth', { configurable: true, value: 600 });
    const onAddSourceStep = vi.fn();

    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'pve:mobile-cluster',
            ownerType: 'pve',
            name: 'Mobile cluster',
            subtitle: 'Cluster · 1 node',
            source: 'api',
            coverageLabels: ['Nodes', 'Guests'],
            isCluster: true,
            canEdit: true,
            connection: connectionFixture({
              id: 'pve:mobile-cluster',
              type: 'pve',
              name: 'Mobile cluster',
              source: 'manual',
              capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
            }),
            members: [
              member({
                id: 'pve-mobile',
                name: 'pve-mobile',
                source: 'api',
                coverageLabels: [],
                agentConnection: undefined,
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled={false}
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly={false}
        onAddSourceStep={onAddSourceStep}
        onOpenConnection={vi.fn()}
      />
    ));

    fireEvent.click(screen.getByRole('button', { name: 'Show 1 node for Mobile cluster' }));
    const memberAction = screen.getByRole('button', { name: 'Install agent on pve-mobile' });
    expect(memberAction).toHaveClass('min-h-11');
    fireEvent.click(memberAction);

    expect(onAddSourceStep).toHaveBeenCalledWith('linux-host');
  });

  it('labels vSphere member composition as hosts, not cluster nodes', () => {
    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          row({
            id: 'vmware:vc-1',
            ownerType: 'vmware',
            name: 'Lab vCenter',
            source: 'api',
            subtitle: 'via VMware vCenter API',
            coverageLabels: ['VMs', 'Hosts', 'Datastores'],
            connection: connectionFixture({
              id: 'vmware:vc-1',
              type: 'vmware',
              name: 'Lab vCenter',
              address: 'https://vcenter.lab:443',
              source: 'manual',
              capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
            }),
            members: [
              member({
                id: 'vc-1:host:host-101',
                name: 'esxi-01.lab.local',
                subtitle: 'vSphere host',
                source: 'api',
                host: undefined,
                coverageLabels: [],
              }),
              member({
                id: 'vc-1:host:host-102',
                name: 'esxi-02.lab.local',
                subtitle: 'vSphere host',
                source: 'api',
                host: undefined,
                coverageLabels: [],
              }),
            ],
          }),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly
      />
    ));

    const toggle = screen.getByRole('button', { name: 'Show 2 hosts for Lab vCenter' });
    fireEvent.click(toggle);
    expect(screen.getByText('esxi-01.lab.local')).toBeInTheDocument();
    expect(screen.getByText('esxi-02.lab.local')).toBeInTheDocument();
    // Table mode carries the member subtitle in the row tooltip, same as
    // Proxmox cluster members.
    expect(screen.getByTitle('esxi-01.lab.local · vSphere host')).toBeInTheDocument();
    expect(screen.getByTitle('esxi-02.lab.local · vSphere host')).toBeInTheDocument();
  });

  it('links each connected API system to the page that shows its data', () => {
    // A PBS read as Active here while its servers sat under Proxmox > Backups,
    // and its user could not find it (#2905).
    const apiRow = (type: Connection['type'], id: string, name: string) =>
      row({
        id,
        ownerType: type,
        name,
        source: 'api',
        connection: connectionFixture({
          id,
          type,
          name,
          address: `https://${name}`,
          source: 'manual',
        }),
      });
    render(() => (
      <InfrastructureSourceManager
        rows={() => [
          apiRow('pbs', 'pbs:vault', 'backup-vault'),
          apiRow('pmg', 'pmg:mail', 'mail-gateway'),
          apiRow('vmware', 'vmware:vc-1', 'Lab vCenter'),
          row(),
        ]}
        discoveredNodes={() => []}
        discoveryEnabled
        discoveryScanStatus={() => ({ scanning: false })}
        readOnly
      />
    ));

    const hrefs = (name: string) =>
      screen.getAllByRole('link', { name }).map((link) => link.getAttribute('href'));
    expect(new Set(hrefs('backup-vault'))).toEqual(new Set(['/proxmox/backups']));
    expect(new Set(hrefs('mail-gateway'))).toEqual(new Set(['/proxmox/mail']));
    expect(new Set(hrefs('Lab vCenter'))).toEqual(new Set(['/vmware/overview']));
    // An agent host shows on a different page depending on what it runs.
    expect(screen.queryByRole('link', { name: 'host-1' })).toBeNull();
    expect(screen.getAllByText('host-1').length).toBeGreaterThan(0);
  });
});