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.

74.6 KB
Raw Blame
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Connection } from '@/api/connections';
import { TrueNASAPI } from '@/api/truenas';
import { VMwareAPI } from '@/api/vmware';
import { useTrueNASSettingsPanelState } from '../useTrueNASSettingsPanelState';
import { useVMwareSettingsPanelState } from '../useVMwareSettingsPanelState';
import { eventBus } from '@/stores/events';
import {
  agentAttachmentProblem,
  infrastructureRowMonitoringPath,
  type InfrastructureSystemMemberRow,
  type InfrastructureSystemRow,
} from '../connectionsTableModel';
import { InfrastructureWorkspace } from '../InfrastructureWorkspace';

const routeState = vi.hoisted(() => ({
  pathname: '/settings/infrastructure',
  search: '',
}));
const connectionState = vi.hoisted(() => {
  let connections: Connection[] = [];
  let observe = () => {};
  let notifyChanged = () => {};
  return {
    get connections() {
      observe();
      return connections;
    },
    set connections(value: Connection[]) {
      connections = value;
    },
    rows: null as InfrastructureSystemRow[] | null,
    setObserver(nextObserve: () => void, nextNotifyChanged: () => void) {
      observe = nextObserve;
      notifyChanged = nextNotifyChanged;
    },
    notifyChanged: () => notifyChanged(),
  };
});
const ledgerReadState = vi.hoisted(() => ({
  error: null as unknown,
  loading: false,
  reload: vi.fn(),
}));
const nodeCredentialSlotState = vi.hoisted(() => ({ mountCount: 0 }));
const savedCredentialSlotMounts = vi.hoisted(() => ({
  truenas: 0,
  vmware: 0,
  useRealSlots: false,
}));
const emptyFleetRow = vi.hoisted(
  () =>
    ({
      fleetSignals: [],
      fleetHighlights: [],
    }) as Pick<InfrastructureSystemRow, 'fleetSignals' | 'fleetHighlights'>,
);
const emptyFleetMember = vi.hoisted(
  () =>
    ({
      fleetSignals: [],
      fleetHighlights: [],
    }) as Pick<InfrastructureSystemMemberRow, 'fleetSignals' | 'fleetHighlights'>,
);
const navigateSpy = vi.hoisted(() => vi.fn());
const setEnableCommandsSpy = vi.hoisted(() => vi.fn());
const presentationPolicyIsReadOnlyMock = vi.hoisted(() => vi.fn(() => false));

const originalResizeObserver = globalThis.ResizeObserver;
let latestResizeObserverCallback: ResizeObserverCallback | null = null;

const installResizeObserverMock = () => {
  latestResizeObserverCallback = null;
  class MockResizeObserver {
    constructor(callback: ResizeObserverCallback) {
      latestResizeObserverCallback = callback;
    }

    observe() {}
    unobserve() {}
    disconnect() {}
  }

  Object.defineProperty(globalThis, 'ResizeObserver', {
    configurable: true,
    writable: true,
    value: MockResizeObserver,
  });
};

const emitResizeObserverWidth = (width: number) => {
  latestResizeObserverCallback?.(
    [{ contentRect: { width } } as ResizeObserverEntry],
    {} as ResizeObserver,
  );
};

const restoreResizeObserver = () => {
  if (originalResizeObserver) {
    Object.defineProperty(globalThis, 'ResizeObserver', {
      configurable: true,
      writable: true,
      value: originalResizeObserver,
    });
    return;
  }
  delete (globalThis as any).ResizeObserver;
};

vi.mock('@solidjs/router', async () => {
  const actual = await vi.importActual<typeof import('@solidjs/router')>('@solidjs/router');
  return {
    ...actual,
    useLocation: () => ({ pathname: routeState.pathname, search: routeState.search }),
    useNavigate: () => navigateSpy,
  };
});

vi.mock('@/stores/sessionPresentationPolicy', () => ({
  presentationPolicyIsReadOnly: () => presentationPolicyIsReadOnlyMock(),
}));

vi.mock('../useInfrastructureOperationsState', () => ({
  InfrastructureOperationsStateProvider: (props: { children: unknown }) => <>{props.children}</>,
  useInfrastructureOperationsContext: () => ({
    acknowledgeNoToken: vi.fn(),
    commandsUnlocked: () => true,
    confirmedNoToken: () => true,
    customCaPath: () => '',
    insecureMode: () => false,
    selectedAgentUrl: () => 'http://pulse',
    setEnableCommands: setEnableCommandsSpy,
    getAgentConnectionUpgradeCommand: (connection: Connection, installFlags: string[] = []) =>
      `upgrade ${connection.id}${installFlags.length > 0 ? ` ${installFlags.join(' ')}` : ''}`,
    getAgentConnectionUpgradeCommandRequiresToken: () => false,
    getUninstallCommand: () => 'curl -fsSL http://pulse/install.sh | bash -s -- --uninstall',
    getWindowsUninstallCommand: () =>
      '$env:PULSE_URL="http://pulse"; $env:PULSE_UNINSTALL="true"; iwr /install.ps1 | iex',
    handleGenerateToken: vi.fn(),
    isGeneratingToken: () => false,
    requiresToken: () => false,
    setTokenName: vi.fn(),
    tokenName: () => '',
  }),
}));

vi.mock('../useConnectionsLedger', () => ({
  useConnectionsLedger: () => ({
    connections: () => connectionState.connections,
    rows: () =>
      connectionState.rows ??
      connectionState.connections.map((connection) => ({
        id: connection.id,
        ownerType: connection.type,
        name: connection.name || connection.id,
        subtitle: connection.type === 'agent' ? 'via Pulse Agent' : 'via platform API',
        source: connection.type === 'agent' ? 'agent' : 'api',
        host: connection.address,
        coverageLabels: ['VMs'],
        statusLabel: connection.state === 'paused' ? 'Paused' : 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        lastErrorMessage: connection.lastError?.message,
        ...emptyFleetRow,
        enabled: connection.enabled,
        canEdit: ['pve', 'pbs', 'pmg', 'vmware', 'truenas'].includes(connection.type),
        canPause: connection.capabilities.supportsPause,
        canRemove: connection.type !== 'docker' && connection.type !== 'kubernetes',
        isAgent: connection.type === 'agent',
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection,
      })),
    findById: (id: string) =>
      connectionState.connections.find((connection) => connection.id === id),
    reload: ledgerReadState.reload,
    loading: () => ledgerReadState.loading,
    error: () => ledgerReadState.error,
    resolvedOnce: () => true,
  }),
}));

vi.mock('../useAgentFleetDiagnostics', () => ({
  useAgentFleetDiagnostics: () => ({
    data: () => ({
      generatedAt: 0,
      summary: { total: 0, healthy: 0, warning: 0, critical: 0, removed: 0 },
      agents: [],
    }),
    error: () => null,
    loading: () => false,
    reload: vi.fn(),
    resolvedOnce: () => false,
  }),
}));

vi.mock('../InfrastructureInstallerSection', () => ({
  InfrastructureInstallerSection: (props: { focus?: string }) => (
    <div data-testid="install-section" data-focus={props.focus}>
      install
    </div>
  ),
}));

vi.mock('../ConnectionEditor/CredentialSlots/NodeCredentialSlot', () => ({
  NodeCredentialSlot: (props: { nodeType: string }) => {
    nodeCredentialSlotState.mountCount += 1;
    return (
      <div data-testid="proxmox-section" data-node-type={props.nodeType}>
        <input aria-label="Authentication method" value="api" />
      </div>
    );
  },
}));

vi.mock('../ConnectionEditor/CredentialSlots/TrueNASCredentialSlot', async (importOriginal) => {
  const actual =
    await importOriginal<
      typeof import('../ConnectionEditor/CredentialSlots/TrueNASCredentialSlot')
    >();
  return {
    TrueNASCredentialSlot: (props: Parameters<typeof actual.TrueNASCredentialSlot>[0]) => {
      savedCredentialSlotMounts.truenas += 1;
      if (savedCredentialSlotMounts.useRealSlots)
        return <actual.TrueNASCredentialSlot {...props} />;
      return (
        <div data-testid="truenas-section" data-editing-id={props.editingConnection?.id}>
          <input aria-label="Synthetic credential draft" />
        </div>
      );
    },
  };
});

vi.mock('../ConnectionEditor/CredentialSlots/VMwareCredentialSlot', async (importOriginal) => {
  const actual =
    await importOriginal<
      typeof import('../ConnectionEditor/CredentialSlots/VMwareCredentialSlot')
    >();
  return {
    VMwareCredentialSlot: (props: Parameters<typeof actual.VMwareCredentialSlot>[0]) => {
      savedCredentialSlotMounts.vmware += 1;
      if (savedCredentialSlotMounts.useRealSlots) return <actual.VMwareCredentialSlot {...props} />;
      return (
        <div data-testid="vmware-section" data-editing-id={props.editingConnection?.id}>
          <input aria-label="Synthetic credential draft" />
        </div>
      );
    },
  };
});

vi.mock('../AgentProfilesPanel', () => ({
  AgentProfilesPanel: () => <div data-testid="agent-profiles">profiles</div>,
}));

const connectionFixture = (overrides: Partial<Connection> = {}): Connection => ({
  id: 'pve:zeus',
  type: 'pve',
  name: 'zeus',
  address: 'https://10.0.0.1:8006',
  state: 'active',
  stateReason: '',
  enabled: true,
  surfaces: ['vms', 'containers'],
  scope: { vms: true, containers: true },
  lastSeen: new Date().toISOString(),
  lastError: null,
  source: 'manual',
  capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
  ...overrides,
});

const baseProps = () =>
  ({
    selectedAgent: () => 'pve',
    onSelectAgent: vi.fn(),
    initialLoadComplete: () => true,
    discoveryEnabled: () => false,
    discoveryMode: () => 'auto',
    discoverySubnetDraft: () => '',
    discoverySubnetError: () => undefined,
    discoveryScanStatus: () => ({ scanning: false }),
    discoveredNodes: () => [],
    savingDiscoverySettings: () => false,
    envOverrides: () => ({}),
    agentStateResources: () => [],
    pbsInstances: () => [],
    pmgInstances: () => [],
    pveNodes: () => [],
    pbsNodes: () => [],
    pmgNodes: () => [],
    trueNASSettings: {
      closeDialog: vi.fn(),
      connections: () => [],
    } as any,
    vmwareSettings: {
      closeDialog: vi.fn(),
      connections: () => [],
    } as any,
    temperatureMonitoringEnabled: () => false,
    triggerDiscoveryScan: vi.fn(),
    loadDiscoveredNodes: vi.fn(),
    handleDiscoveryEnabledChange: vi.fn(),
    handleDiscoveryModeChange: vi.fn(),
    setDiscoveryMode: vi.fn(),
    setDiscoverySubnetDraft: vi.fn(),
    setDiscoverySubnetError: vi.fn(),
    setLastCustomSubnet: vi.fn(),
    commitDiscoverySubnet: vi.fn(),
    parseSubnetList: vi.fn(() => []),
    normalizeSubnetList: vi.fn((value: string) => value),
    isValidCIDR: vi.fn(() => true),
    currentDraftSubnetValue: vi.fn(() => ''),
    discoverySubnetInputRef: vi.fn(),
    testNodeConnection: vi.fn(),
    requestDeleteNode: vi.fn(),
    refreshClusterNodes: vi.fn(),
    setShowNodeModal: vi.fn(),
    editingNode: () => null,
    setEditingNode: vi.fn(),
    setCurrentNodeType: vi.fn(),
    modalResetKey: () => 0,
    setModalResetKey: vi.fn(),
    isNodeModalVisible: () => false,
    securityStatus: () => null,
    resolveTemperatureMonitoringEnabled: () => false,
    temperatureMonitoringLocked: () => false,
    savingTemperatureSetting: () => false,
    handleTemperatureMonitoringChange: vi.fn(),
    disableDockerUpdateActions: () => false,
    disableDockerUpdateActionsLocked: () => false,
    savingDockerUpdateActions: () => false,
    handleDisableDockerUpdateActionsChange: vi.fn(),
    handleNodeTemperatureMonitoringChange: vi.fn(),
    saveNode: vi.fn(),
    showDeleteNodeModal: () => false,
    cancelDeleteNode: vi.fn(),
    deleteNode: vi.fn(),
    deleteNodeLoading: () => false,
    nodePendingDeleteLabel: () => '',
    nodePendingDeleteHost: () => '',
    nodePendingDeleteType: () => '',
    nodePendingDeleteTypeLabel: () => '',
  }) as any;

describe('InfrastructureWorkspace', () => {
  beforeEach(() => {
    navigateSpy.mockReset();
    ledgerReadState.error = null;
    ledgerReadState.loading = false;
    ledgerReadState.reload.mockReset();
    presentationPolicyIsReadOnlyMock.mockReset();
    presentationPolicyIsReadOnlyMock.mockReturnValue(false);
    routeState.pathname = '/settings/infrastructure';
    routeState.search = '';
    connectionState.connections = [connectionFixture()];
    connectionState.rows = null;
    connectionState.setObserver(
      () => {},
      () => {},
    );
    nodeCredentialSlotState.mountCount = 0;
    savedCredentialSlotMounts.useRealSlots = false;
    savedCredentialSlotMounts.truenas = 0;
    savedCredentialSlotMounts.vmware = 0;
    Object.defineProperty(window, 'innerWidth', {
      configurable: true,
      writable: true,
      value: 1024,
    });
  });

  afterEach(() => {
    cleanup();
    vi.restoreAllMocks();
    restoreResizeObserver();
  });

  const renderWorkspace = (propOverrides: Record<string, unknown> = {}) =>
    render(() => (<InfrastructureWorkspace {...{ ...baseProps(), ...propOverrides }} />) as any);

  it('keeps a working provider active while its attached agent awaits a first report', async () => {
    const provider = connectionFixture();
    const agent = connectionFixture({ id: 'agent:waiting', type: 'agent', state: 'pending' });
    connectionState.rows = [
      {
        id: provider.id,
        ownerType: provider.type,
        name: provider.name,
        subtitle: 'via platform API and Pulse Agent',
        source: 'both',
        host: provider.address,
        coverageLabels: ['VMs'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        problem: agentAttachmentProblem(agent),
        enabled: true,
        canEdit: true,
        canPause: false,
        canRemove: true,
        isAgent: false,
        isCluster: false,
        attachedConnections: [agent],
        members: [],
        connection: provider,
      },
    ];
    renderWorkspace();
    await waitFor(() => expect(screen.getByText('Waiting for first report')).toBeInTheDocument());
    expect(screen.getAllByText('Active').length).toBeGreaterThan(0);
    expect(screen.queryByText('Unreachable')).toBeNull();
    expect(screen.getByRole('button', { name: /^Manage$/i })).toBeInTheDocument();
  });

  it('shows a partial read as a degraded source with a warning banner naming the reading', async () => {
    const provider = connectionFixture({ state: 'degraded' });
    connectionState.rows = [
      {
        id: provider.id,
        ownerType: provider.type,
        name: provider.name,
        subtitle: 'via platform API',
        source: 'api',
        host: provider.address,
        coverageLabels: ['VMs'],
        statusLabel: 'Degraded',
        statusClassName: 'bg-yellow-100',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        lastErrorMessage: 'Queue status could not be read: Server error.',
        lastErrorTone: 'warning',
        ...emptyFleetRow,
        enabled: true,
        canEdit: true,
        canPause: false,
        canRemove: true,
        isAgent: false,
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection: provider,
      },
    ];
    renderWorkspace();

    const banner = await screen.findByText('Queue status could not be read: Server error.');
    expect(banner.getAttribute('class')).toContain('bg-amber-50');
    expect(banner.getAttribute('class')).not.toContain('bg-rose-50');
    expect(screen.getAllByText('Degraded').length).toBeGreaterThan(0);
    expect(screen.queryByText('Unreachable')).toBeNull();
  });

  it('keeps an outage error banner critical', async () => {
    const provider = connectionFixture({ state: 'unreachable' });
    connectionState.rows = [
      {
        id: provider.id,
        ownerType: provider.type,
        name: provider.name,
        subtitle: 'via platform API',
        source: 'api',
        host: provider.address,
        coverageLabels: ['VMs'],
        statusLabel: 'Unreachable',
        statusClassName: 'bg-rose-100',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        lastErrorMessage: 'Connection refused.',
        lastErrorTone: 'critical',
        ...emptyFleetRow,
        enabled: true,
        canEdit: true,
        canPause: false,
        canRemove: true,
        isAgent: false,
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection: provider,
      },
    ];
    renderWorkspace();

    const banner = await screen.findByText('Connection refused.');
    expect(banner.getAttribute('class')).toContain('bg-rose-50');
  });

  it('renders the source manager landing without empty platform sections', async () => {
    renderWorkspace();

    // Card title shifted from 'Infrastructure systems' (which duplicated
    // the page header) to 'Connected systems' which describes the card's
    // contents distinctly. Card-level description was dropped because it
    // duplicated the page-level subtitle.
    await waitFor(() => expect(screen.getByText('Connected systems')).toBeInTheDocument());
    expect(screen.queryByRole('button', { name: /^Run discovery$/i })).toBeNull();
    expect(screen.getByRole('button', { name: /^Configure discovery$/i })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /^Add infrastructure$/i })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /^Detect address$/i })).toBeNull();
    // Row-level 'Install agent' surfaces per system that has API coverage
    // but no Pulse Agent yet. The fixture has one such system, so at least
    // one of these buttons should exist.
    expect(screen.getAllByRole('button', { name: /^Install agent$/i }).length).toBeGreaterThan(0);
    const readiness = screen.getByRole('region', {
      name: /Connection posture/i,
    });
    expect(within(readiness).getByText('Connection posture')).toBeInTheDocument();
    expect(within(readiness).getByText('1 system connected')).toBeInTheDocument();
    expect(within(readiness).getByText('All active')).toBeInTheDocument();
    expect(within(readiness).getByText('1 host has limited coverage')).toBeInTheDocument();
    expect(within(readiness).queryByText('Infrastructure coverage')).toBeNull();
    expect(within(readiness).queryByText('Fleet governance')).toBeNull();
    expect(within(readiness).getByRole('button', { name: /^Install agent$/i })).toBeInTheDocument();
    expect(screen.getByText('Proxmox VE')).toBeInTheDocument();
    expect(screen.getByText('Proxmox VE').closest('tr')?.className).toContain('grouped-table-row');
    expect(screen.queryByText('VMware vCenter')).toBeNull();
    expect(screen.queryByText('TrueNAS SCALE')).toBeNull();
    expect(screen.queryByText('Pulse Agent hosts')).toBeNull();
    expect(screen.getByRole('button', { name: /Add Proxmox VE/i })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /Add TrueNAS SCALE/i })).toBeNull();
    expect(screen.queryByRole('button', { name: /Install Pulse Agent/i })).toBeNull();
    expect(screen.getByRole('button', { name: /Manage/i })).toBeInTheDocument();
    expect(screen.queryByRole('heading', { name: 'Monitored systems' })).not.toBeInTheDocument();
  });

  it('routes first-run actions from the source manager guidance', async () => {
    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Connected systems')).toBeInTheDocument());

    // Row-level 'Install agent' replaced the global 'Install agents'
    // recommendation button; same routing target.
    fireEvent.click(screen.getAllByRole('button', { name: /^Install agent$/i })[0]);
    expect(navigateSpy).toHaveBeenLastCalledWith('/settings/infrastructure?add=linux-host', {
      scroll: false,
    });

    fireEvent.click(screen.getByRole('button', { name: /^Add infrastructure$/i }));
    expect(navigateSpy).toHaveBeenLastCalledWith('/settings/infrastructure?add=pick', {
      scroll: false,
    });

    expect(screen.queryByRole('button', { name: /^Monitor endpoint$/i })).toBeNull();
  });

  it('opens scoped Agent Doctor from a legacy agent update route', async () => {
    routeState.search = '?agentUpdates=1&agents=agent%3Aagent-zeus';
    const primaryConnection = connectionFixture();
    const attachedAgent = connectionFixture({
      id: 'agent:agent-zeus',
      type: 'agent',
      name: 'zeus-agent',
      address: 'zeus.lab',
      surfaces: ['host'],
      scope: { host: true },
      source: 'agent',
      agentVersion: '5.1.34',
      expectedAgentVersion: '6.0.0-rc.6',
      agentUpdateAvailable: true,
      agentIdentity: {
        hostname: 'zeus',
        platform: 'linux',
      },
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    const unrelatedStaleAgent = connectionFixture({
      id: 'agent:agent-other',
      type: 'agent',
      name: 'other-agent',
      address: 'other.lab',
      surfaces: ['host'],
      scope: { host: true },
      source: 'agent',
      agentVersion: '5.1.34',
      expectedAgentVersion: '6.0.0-rc.6',
      agentUpdateAvailable: true,
      agentIdentity: {
        hostname: 'other',
        platform: 'linux',
      },
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    connectionState.connections = [primaryConnection, attachedAgent, unrelatedStaleAgent];
    connectionState.rows = [
      {
        id: primaryConnection.id,
        ownerType: 'pve',
        name: 'homelab',
        subtitle: 'via platform API and Pulse Agent',
        source: 'both',
        host: primaryConnection.address,
        coverageLabels: ['VMs', 'Host telemetry'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 1,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: true,
        canPause: true,
        canRemove: true,
        isAgent: false,
        isCluster: false,
        attachedConnections: [attachedAgent, unrelatedStaleAgent],
        members: [],
        connection: primaryConnection,
      },
    ];

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Agent Doctor')).toBeInTheDocument());
    // The lone target opens on its own, headed by its name.
    expect(screen.getByRole('heading', { name: 'zeus' })).toBeInTheDocument();
    expect(screen.queryByText('other')).not.toBeInTheDocument();
    expect(screen.getAllByText('5.1.34').length).toBeGreaterThan(0);
    expect(screen.getAllByText('6.0.0-rc.6').length).toBeGreaterThan(0);
    expect(
      screen.getByText(/upgrade agent:agent-zeus --enable-proxmox --proxmox-type pve/),
    ).toBeInTheDocument();

    // The page replaces the workspace content and links back to Infrastructure.
    expect(screen.queryByText('Connected systems')).not.toBeInTheDocument();
    expect(screen.getByRole('link', { name: 'Infrastructure' })).toHaveAttribute(
      'href',
      '/settings/infrastructure',
    );
  });

  it('renders the Agent Doctor page on its routed path', async () => {
    routeState.pathname = '/settings/infrastructure/agent-doctor';
    routeState.search = '';

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Agent Doctor')).toBeInTheDocument());
    expect(screen.queryByText('Connected systems')).not.toBeInTheDocument();
    expect(screen.getByRole('link', { name: 'Infrastructure' })).toHaveAttribute(
      'href',
      '/settings/infrastructure',
    );
  });

  it('filters the Agent Doctor table by clicking a status chip', async () => {
    routeState.pathname = '/settings/infrastructure/agent-doctor';
    routeState.search = '';
    const staleAgent = connectionFixture({
      id: 'agent:agent-zeus',
      type: 'agent',
      name: 'zeus-agent',
      address: 'zeus.lab',
      surfaces: ['host'],
      scope: { host: true },
      source: 'agent',
      agentVersion: '5.1.34',
      expectedAgentVersion: '6.0.0-rc.6',
      agentUpdateAvailable: true,
      agentIdentity: { hostname: 'zeus', platform: 'linux' },
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    const unreachableAgent = connectionFixture({
      id: 'agent:agent-apollo',
      type: 'agent',
      name: 'apollo-agent',
      address: 'apollo.lab',
      state: 'unreachable',
      surfaces: ['host'],
      scope: { host: true },
      source: 'agent',
      agentVersion: '6.0.0-rc.6',
      agentIdentity: { hostname: 'apollo', platform: 'linux' },
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    connectionState.connections = [staleAgent, unreachableAgent];
    connectionState.rows = [staleAgent, unreachableAgent].map((connection) => ({
      id: connection.id,
      ownerType: 'agent' as const,
      name: connection.name,
      subtitle: 'via Pulse Agent',
      source: 'agent' as const,
      host: connection.address,
      coverageLabels: ['Host telemetry'],
      statusLabel: 'Active',
      statusClassName: 'bg-green-100 text-green-800',
      agentUpdateCount: 0,
      lastActivityText: '1m ago',
      ...emptyFleetRow,
      enabled: true,
      canEdit: true,
      canPause: false,
      canRemove: true,
      isAgent: true,
      isCluster: false,
      attachedConnections: [],
      members: [],
      connection,
    }));

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('zeus')).toBeInTheDocument());
    expect(screen.getByText('apollo')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Copy diagnostic report' })).toBeInTheDocument();

    const attentionChip = screen.getByRole('button', { name: '1 Needs attention' });
    fireEvent.click(attentionChip);
    expect(attentionChip).toHaveAttribute('aria-pressed', 'true');
    expect(screen.getByText('zeus')).toBeInTheDocument();
    expect(screen.queryByText('apollo')).not.toBeInTheDocument();

    fireEvent.click(attentionChip);
    expect(attentionChip).toHaveAttribute('aria-pressed', 'false');
    expect(screen.getByText('apollo')).toBeInTheDocument();
  });

  it('does not invent scoped update commands when the backend publishes no agent target', async () => {
    routeState.search = '?agentUpdates=1&agents=agent%3Aagent-zeus';
    const primaryConnection = connectionFixture();
    const attachedAgent = connectionFixture({
      id: 'agent:agent-zeus',
      type: 'agent',
      name: 'zeus-agent',
      address: 'zeus.lab',
      surfaces: ['host'],
      scope: { host: true },
      source: 'agent',
      agentVersion: '5.1.34',
      agentUpdateAvailable: false,
      agentIdentity: {
        hostname: 'zeus',
        platform: 'linux',
      },
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    connectionState.connections = [primaryConnection, attachedAgent];
    connectionState.rows = [
      {
        id: primaryConnection.id,
        ownerType: 'pve',
        name: 'homelab',
        subtitle: 'via platform API and Pulse Agent',
        source: 'both',
        host: primaryConnection.address,
        coverageLabels: ['VMs', 'Host telemetry'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: true,
        canPause: true,
        canRemove: true,
        isAgent: false,
        isCluster: false,
        attachedConnections: [attachedAgent],
        members: [],
        connection: primaryConnection,
      },
    ];

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Agent Doctor')).toBeInTheDocument());
    expect(screen.getByRole('heading', { name: 'zeus' })).toBeInTheDocument();
    expect(screen.getAllByText('5.1.34').length).toBeGreaterThan(0);
    // With no published target there is no target version or command to guess at.
    expect(screen.queryByText(/upgrade agent:agent-zeus/)).not.toBeInTheDocument();
  });

  it('keeps source groups in the catalog order instead of count order', async () => {
    const pveConnection = connectionFixture({
      id: 'pve:zeus',
      type: 'pve',
      name: 'zeus',
      address: 'https://10.0.0.1:8006',
    });
    const towerAgent = connectionFixture({
      id: 'agent:tower',
      type: 'agent',
      name: 'Tower',
      address: 'Tower',
      source: 'agent',
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    const miniAgent = connectionFixture({
      id: 'agent:mini',
      type: 'agent',
      name: 'Mini',
      address: 'Mini',
      source: 'agent',
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });

    connectionState.connections = [pveConnection, towerAgent, miniAgent];
    connectionState.rows = [
      {
        id: pveConnection.id,
        ownerType: 'pve',
        name: 'zeus',
        subtitle: 'via platform API',
        source: 'api',
        host: pveConnection.address,
        coverageLabels: ['VMs'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: true,
        canPause: true,
        canRemove: true,
        isAgent: false,
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection: pveConnection,
      },
      {
        id: towerAgent.id,
        ownerType: 'agent',
        name: 'Tower',
        subtitle: 'via Pulse Agent',
        source: 'agent',
        host: 'Tower',
        coverageLabels: ['Host telemetry'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: false,
        canPause: false,
        canRemove: true,
        isAgent: true,
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection: towerAgent,
      },
      {
        id: miniAgent.id,
        ownerType: 'agent',
        name: 'Mini',
        subtitle: 'via Pulse Agent',
        source: 'agent',
        host: 'Mini',
        coverageLabels: ['Host telemetry'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: false,
        canPause: false,
        canRemove: true,
        isAgent: true,
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection: miniAgent,
      },
    ];

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Proxmox VE')).toBeInTheDocument());
    const pveGroup = screen.getByText('Proxmox VE');
    const hostGroup = screen.getByText('Pulse Agent hosts');
    expect(pveGroup.compareDocumentPosition(hostGroup) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(
      Node.DOCUMENT_POSITION_FOLLOWING,
    );
  });

  it('switches the source manager layout from measured container width during live resize', async () => {
    installResizeObserverMock();
    Object.defineProperty(window, 'innerWidth', {
      configurable: true,
      writable: true,
      value: 1180,
    });

    renderWorkspace();

    await waitFor(() =>
      expect(screen.getByRole('columnheader', { name: 'System' })).toBeInTheDocument(),
    );

    emitResizeObserverWidth(640);

    await waitFor(() =>
      expect(screen.queryByRole('columnheader', { name: 'System' })).not.toBeInTheDocument(),
    );
    expect(screen.getByText('Proxmox VE')).toBeInTheDocument();
    expect(screen.getByText('zeus')).toBeInTheDocument();
    expect(screen.getByText('Active')).toBeInTheDocument();
  });

  it('forwards an unavailable ledger and its read-only retry instead of onboarding', async () => {
    connectionState.connections = [];
    connectionState.rows = [];
    ledgerReadState.error = { status: 503 };
    presentationPolicyIsReadOnlyMock.mockReturnValue(true);
    renderWorkspace();

    expect(screen.getByRole('alert')).toHaveTextContent('Connected systems unavailable');
    expect(screen.queryByText('0 systems connected')).not.toBeInTheDocument();
    expect(screen.queryByText('Start monitoring infrastructure')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    expect(ledgerReadState.reload).toHaveBeenCalledTimes(1);
  });

  it('retries saved node configuration alongside the connection list for an administrator', () => {
    connectionState.connections = [];
    connectionState.rows = [];
    ledgerReadState.error = { status: 503 };
    const refreshNodes = vi.fn();
    const unsubscribe = eventBus.on('refresh_nodes', refreshNodes);
    try {
      renderWorkspace();
      fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
      expect(ledgerReadState.reload).toHaveBeenCalledTimes(1);
      expect(refreshNodes).toHaveBeenCalledTimes(1);
    } finally {
      unsubscribe();
    }
  });

  it('keeps onboarding copy visible in the empty infrastructure state', async () => {
    connectionState.connections = [];
    connectionState.rows = [];

    renderWorkspace();

    await waitFor(() =>
      expect(screen.getByText('Start monitoring infrastructure')).toBeInTheDocument(),
    );
    expect(
      screen.getByText('Choose an infrastructure source to start monitoring your environment.'),
    ).toBeInTheDocument();
    expect(screen.getByText(/Supported source types include TrueNAS SCALE/i)).toBeInTheDocument();
    expect(
      screen.getByText(/VMware vCenter is available as a preview platform/i),
    ).toBeInTheDocument();
    expect(screen.getByText(/Pulse Agent hosts/i)).toBeInTheDocument();
  });

  it('offers one way to add the first system and lets the source list wrap', async () => {
    connectionState.connections = [];
    connectionState.rows = [];

    renderWorkspace();

    await waitFor(() =>
      expect(screen.getByText('Start monitoring infrastructure')).toBeInTheDocument(),
    );
    // The page-header button is the only add action; a second one for the same
    // job, and its repeated sentence, read as two different choices.
    expect(
      screen.getAllByRole('button', { name: /^Add (infrastructure|your first system)$/i }),
    ).toHaveLength(1);
    expect(screen.queryByText('Add your first system')).not.toBeInTheDocument();
    expect(
      screen.queryByText('Add a platform, host, NAS, or cluster to start monitoring.'),
    ).not.toBeInTheDocument();
    // The cell hosting this prose sits in a `.table-fixed` table whose global
    // rule forces nowrap, so the wrapper itself has to opt back into wrapping.
    expect(screen.getByText('Start monitoring infrastructure').parentElement).toHaveClass(
      'whitespace-normal',
    );
  });

  it('does not claim a scan time or a configured state before discovery has ever run', async () => {
    connectionState.connections = [];
    connectionState.rows = [];

    renderWorkspace({
      discoveryEnabled: () => false,
      discoveryScanStatus: () => ({ scanning: false }),
    });

    await waitFor(() =>
      expect(screen.getByRole('region', { name: 'Discover Proxmox systems' })).toBeInTheDocument(),
    );
    const band = screen.getByRole('region', { name: 'Discover Proxmox systems' });
    expect(band).toHaveTextContent('Off');
    expect(band).not.toHaveTextContent(/Last scanned/i);
    expect(band).not.toHaveTextContent(/Not configured/i);
  });

  it('says there is no scan result yet when discovery is on but has none', async () => {
    connectionState.connections = [];
    connectionState.rows = [];

    renderWorkspace({
      discoveryEnabled: () => true,
      discoveryScanStatus: () => ({ scanning: false }),
    });

    const band = await screen.findByRole('region', { name: 'Discover Proxmox systems' });
    expect(band).toHaveTextContent('No scan result yet');
    expect(band).not.toHaveTextContent(/Last scanned/i);
  });

  it('routes discovery actions from the manager and shows discovered candidates in the matching platform group', async () => {
    const triggerDiscoveryScan = vi.fn();
    renderWorkspace({
      discoveryEnabled: () => true,
      discoveredNodes: () => [
        {
          ip: '10.0.0.55',
          port: 8006,
          type: 'pve',
          version: '8.2.2',
          hostname: 'discovered-pve.lab',
        },
      ],
      discoveryScanStatus: () => ({ scanning: false, lastResultAt: Date.now() }),
      triggerDiscoveryScan,
    });

    await waitFor(() => expect(screen.getByText('discovered-pve.lab')).toBeInTheDocument());
    expect(screen.getByText('Discovered')).toBeInTheDocument();
    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(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=pve', {
      scroll: false,
    });

    fireEvent.click(screen.getByRole('button', { name: /Run discovery/i }));
    expect(triggerDiscoveryScan).toHaveBeenCalledTimes(1);

    fireEvent.click(screen.getByRole('button', { name: /^Settings$/i }));
    expect(screen.getByRole('dialog', { name: /Discovery settings/i })).toBeInTheDocument();
    expect(
      screen.getByText(/Configure the saved network scope and background scan behavior/i),
    ).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: /^Review$/i }));
    expect(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=pve', {
      scroll: false,
    });
  });

  it('hides discovered candidates already represented by the unified connections ledger member aliases', async () => {
    connectionState.rows = [
      {
        id: 'pve:homelab',
        ownerType: 'pve',
        name: 'homelab',
        subtitle: 'Cluster · 1 node',
        source: 'api',
        host: undefined,
        coverageLabels: ['VMs', 'Containers', 'Storage', 'Backups'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '3s ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: true,
        canPause: true,
        canRemove: true,
        isAgent: false,
        isCluster: true,
        attachedConnections: [],
        members: [
          {
            id: 'node-pi',
            name: 'pi',
            subtitle: 'Primary node',
            source: 'agent',
            host: 'https://pi:8006',
            hostAliases: ['pi', '192.168.0.2'],
            coverageLabels: ['Host telemetry'],
            statusLabel: 'Active',
            statusClassName: 'bg-green-100 text-green-800',
            lastActivityText: '3s ago',
            ...emptyFleetMember,
            primary: true,
          },
        ],
        connection: connectionFixture({
          id: 'pve:homelab',
          name: 'homelab',
          address: 'https://pi:8006',
        }),
      },
    ];

    renderWorkspace({
      discoveredNodes: () => [
        {
          ip: '192.168.0.2',
          port: 8006,
          type: 'pve',
          version: '8.2.2',
        },
      ],
      discoveryScanStatus: () => ({ scanning: false, lastResultAt: Date.now() }),
    });

    await waitFor(() => expect(screen.getByText('homelab')).toBeInTheDocument());
    expect(screen.queryByText('192.168.0.2')).not.toBeInTheDocument();
    expect(screen.queryByText('Discovered')).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /^Review$/i })).toBeNull();
  });

  it('opens a type-specific add route from the matching platform section', () => {
    renderWorkspace();

    fireEvent.click(screen.getByRole('button', { name: /Add Proxmox VE/i }));

    expect(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=pve', {
      scroll: false,
    });
  });

  it('opens the platform picker from the Add infrastructure action', () => {
    renderWorkspace();

    fireEvent.click(screen.getByRole('button', { name: /^Add infrastructure$/i }));

    expect(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=pick', {
      scroll: false,
    });
  });

  it('renders the route-backed picker dialog when the pick query is present', async () => {
    routeState.search = '?add=pick';
    renderWorkspace();

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    const dialog = screen.getByRole('dialog');
    expect(dialog).toHaveAccessibleName('Add infrastructure');
    expect(dialog).toHaveAccessibleDescription(
      'Choose the system, device, host, or service you want Pulse to monitor.',
    );
    expect(dialog).toHaveAttribute('aria-labelledby', 'infrastructure-add-dialog-title');
    expect(dialog).toHaveAttribute('aria-describedby', 'infrastructure-add-dialog-description');
    expect(screen.getAllByText('Add infrastructure').length).toBeGreaterThan(0);
    expect(
      screen.getByText('Choose the system, device, host, or service you want Pulse to monitor.'),
    ).toBeInTheDocument();
    expect(
      within(dialog).getByPlaceholderText('Search sources, devices, services...'),
    ).toBeInTheDocument();
    expect(
      within(dialog).getByRole('button', { name: /Detect API platform/i }),
    ).toBeInTheDocument();
    expect(within(dialog).queryByRole('button', { name: /Monitor network endpoint/i })).toBeNull();
    expect(within(dialog).getByText('Choose how Pulse should connect')).toBeInTheDocument();
    expect(within(dialog).getByText('Or pick a specific source')).toBeInTheDocument();
    expect(within(dialog).queryByText('Agent telemetry')).toBeNull();
    expect(within(dialog).queryByText('API inventory')).toBeNull();
    expect(within(dialog).getByRole('button', { name: /TrueNAS SCALE/i })).toBeInTheDocument();
    expect(within(dialog).getByText('Unraid')).toBeInTheDocument();
  });

  it('routes the picker detect action into the detect dialog', async () => {
    routeState.search = '?add=pick';
    renderWorkspace();

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    // Primary path button now contains description text, so match by
    // accessible-name prefix.
    fireEvent.click(
      within(screen.getByRole('dialog')).getByRole('button', { name: /Detect API platform/i }),
    );

    expect(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=detect', {
      scroll: false,
    });
  });

  it('routes the picker source cards into direct type-specific dialogs', async () => {
    routeState.search = '?add=pick';
    renderWorkspace();

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    fireEvent.click(
      within(screen.getByRole('dialog')).getByRole('button', { name: /TrueNAS SCALE/i }),
    );

    expect(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=truenas', {
      scroll: false,
    });
  });

  it('renders the detect dialog as a secondary utility flow', async () => {
    routeState.search = '?add=detect';
    renderWorkspace();

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    expect(screen.getByText('Detect API platform')).toBeInTheDocument();
    expect(
      screen.getByText(
        'Probe a management API endpoint and let Pulse open the matching credential flow when it recognizes the platform.',
      ),
    ).toBeInTheDocument();
    expect(
      within(screen.getByRole('dialog')).getByRole('button', { name: /Back to source types/i }),
    ).toBeInTheDocument();
    expect(
      within(screen.getByRole('dialog')).getByRole('button', { name: /Probe API endpoint/i }),
    ).toBeInTheDocument();
  });

  it('renders the route-backed agent dialog when the agent query is present', async () => {
    routeState.search = '?add=agent';
    renderWorkspace();

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    expect(screen.getAllByText('Add Pulse Agent').length).toBeGreaterThan(0);
    expect(screen.getByTestId('install-section')).toBeInTheDocument();
    expect(screen.getByTestId('install-section')).toHaveAttribute('data-focus', 'agent');
  });

  it('tailors agent-backed catalog routes to the selected system', async () => {
    routeState.search = '?add=unraid';
    renderWorkspace();

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    expect(screen.getAllByText('Add Unraid').length).toBeGreaterThan(0);
    expect(screen.getByTestId('install-section')).toHaveAttribute('data-focus', 'unraid');
  });

  it('renders a direct type route before the add dialog mounts', async () => {
    routeState.search = '?add=truenas';
    renderWorkspace();

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    expect(screen.getByTestId('truenas-section')).toBeInTheDocument();
  });

  it('does not render the agentless availability target route from the infrastructure workspace', async () => {
    routeState.search = '?add=availability';
    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Connected systems')).toBeInTheDocument());
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
  });

  it('recovers unavailable saved node settings inside the existing manage dialog', async () => {
    const [savedNodes, setSavedNodes] = createSignal<any[]>([]);
    const refresh = vi.fn(() => setSavedNodes([{ name: 'zeus', host: 'https://10.0.0.1:8006' }]));
    const unsubscribe = eventBus.on('refresh_nodes', refresh);
    try {
      renderWorkspace({ pveNodes: savedNodes });
      fireEvent.click(await screen.findByRole('button', { name: 'Manage' }));
      const dialog = screen.getByRole('dialog');
      expect(within(dialog).getByRole('alert')).toHaveTextContent(
        'Saved configuration for zeus is unavailable',
      );
      expect(dialog).not.toHaveTextContent('removed');
      expect(within(dialog).queryByTestId('proxmox-section')).toBeNull();
      fireEvent.click(within(dialog).getByRole('button', { name: 'Retry saved configuration' }));
      expect(refresh).toHaveBeenCalledTimes(1);
      expect(ledgerReadState.reload).toHaveBeenCalledTimes(1);
      await waitFor(() =>
        expect(within(dialog).getByTestId('proxmox-section')).toBeInTheDocument(),
      );
      expect(screen.getByRole('dialog')).toBe(dialog);
      expect(dialog).toHaveAccessibleName('Manage zeus');
    } finally {
      unsubscribe();
    }
  });

  it.each([
    ['truenas', 401],
    ['truenas', 403],
    ['truenas', 404],
    ['truenas', 503],
    ['truenas', 200],
    ['vmware', 401],
    ['vmware', 403],
    ['vmware', 404],
    ['vmware', 503],
    ['vmware', 200],
  ] as const)(
    'keeps the real %s consumer open after read status %s withdraws its draft and recovers afresh',
    async (type, status) => {
      savedCredentialSlotMounts.useRealSlots = true;
      const api = type === 'truenas' ? TrueNASAPI : VMwareAPI;
      const saved = {
        id: 'source-1',
        name: 'Saved source',
        host: 'source.example.invalid',
        username: 'monitor',
        apiKey: '********',
        password: '********',
        useHttps: true,
        insecureSkipVerify: false,
        fingerprint: 'SHA256:synthetic-pin',
        enabled: true,
        monitorVms: true,
        monitorHosts: true,
        monitorDatastores: true,
        monitorDatasets: true,
        monitorPools: true,
        monitorReplication: true,
      };
      const list = vi.spyOn(api, 'listConnections').mockImplementation(async () => [{ ...saved }]);
      const update = vi.spyOn(api, 'updateConnection');
      const remove = vi.spyOn(api, 'deleteConnection');
      const create = vi.spyOn(api, 'createConnection');
      connectionState.connections = [
        connectionFixture({ id: `${type}:source-1`, type, name: 'Saved source' }),
      ];
      let state!:
        | ReturnType<typeof useTrueNASSettingsPanelState>
        | ReturnType<typeof useVMwareSettingsPanelState>;
      render(() => {
        state = type === 'truenas' ? useTrueNASSettingsPanelState() : useVMwareSettingsPanelState();
        return (
          <InfrastructureWorkspace
            {...baseProps()}
            {...{ [type === 'truenas' ? 'trueNASSettings' : 'vmwareSettings']: state }}
          />
        );
      });
      await waitFor(() => expect(state.connections()).toHaveLength(1));
      fireEvent.click(await screen.findByRole('button', { name: 'Manage' }));
      const dialog = screen.getByRole('dialog');
      const name = within(dialog).getByRole('textbox', { name: 'Name' });
      const storedSecretPlaceholder =
        type === 'truenas'
          ? 'Saved API key retained unless replaced'
          : 'Saved password retained unless replaced';
      const secret = within(dialog).getByPlaceholderText(storedSecretPlaceholder);
      fireEvent.input(name, { target: { value: 'Unconfirmed name' } });
      fireEvent.input(secret, { target: { value: 'synthetic-unsaved-secret' } });
      await state.loadConnections();
      expect(within(dialog).getByRole('textbox', { name: 'Name' })).toBe(name);
      expect(name).toHaveValue('Unconfirmed name');
      expect(secret).toHaveValue('synthetic-unsaved-secret');
      if (status === 200) list.mockResolvedValueOnce([]);
      else list.mockRejectedValueOnce({ status, message: 'synthetic private failure' });
      await state.loadConnections();
      await waitFor(() => expect(within(dialog).queryByRole('textbox')).toBeNull());
      expect(screen.getByRole('dialog')).toBe(dialog);
      expect(within(dialog).getByRole('alert')).toHaveTextContent('is unavailable');
      expect(dialog).not.toHaveTextContent('synthetic private failure');
      expect(state.form()).toMatchObject({ name: '', password: '' });
      expect(state.dialogOpen()).toBe(false);
      expect(within(dialog).queryByRole('button', { name: 'Save changes' })).toBeNull();
      expect(within(dialog).queryByRole('button', { name: 'Test connection' })).toBeNull();
      fireEvent.click(within(dialog).getByRole('button', { name: 'Retry saved configuration' }));
      await waitFor(() =>
        expect(within(dialog).getByRole('textbox', { name: 'Name' })).toHaveValue('Saved source'),
      );
      const recoveredSecret = within(dialog).getByPlaceholderText(storedSecretPlaceholder);
      expect(recoveredSecret).toHaveValue('');
      expect(recoveredSecret).toHaveAttribute(
        'placeholder',
        type === 'truenas'
          ? 'Saved API key retained unless replaced'
          : 'Saved password retained unless replaced',
      );
      expect(screen.getByRole('dialog')).toBe(dialog);
      expect(state.form()).toMatchObject({
        host: saved.host,
        username: saved.username,
        insecureSkipVerify: false,
        ...(type === 'truenas'
          ? {
              useHttps: true,
              fingerprint: saved.fingerprint,
              monitorPools: true,
              monitorDatasets: true,
              monitorReplication: true,
            }
          : { monitorVms: true, monitorHosts: true, monitorDatastores: true }),
      });
      expect(update).not.toHaveBeenCalled();
      expect(remove).not.toHaveBeenCalled();
      expect(create).not.toHaveBeenCalled();
    },
  );

  describe.each([
    ['truenas', 'TrueNAS', 'trueNASSettings'],
    ['vmware', 'VMware', 'vmwareSettings'],
  ] as const)('%s saved configuration', (type, platform, propName) => {
    it.each([401, 403, 503, 404, 200])(
      'keeps a %s unavailable read distinct from removal and explicitly recovers the same source',
      async (status) => {
        connectionState.connections = [
          connectionFixture({ id: `${type}:source-1`, type, name: 'Saved source' }),
        ];
        const [connections, setConnections] = createSignal<any[]>([]);
        const [loading, setLoading] = createSignal(false);
        const loadConnections = vi.fn(() => setLoading(true));
        renderWorkspace({
          [propName]: {
            closeDialog: vi.fn(),
            connections,
            loading,
            loadingError: () => (status === 200 ? null : `HTTP ${status}: private detail`),
            featureDisabled: () => status === 404,
            loadConnections,
          },
        });
        fireEvent.click(await screen.findByRole('button', { name: 'Manage' }));
        const dialog = screen.getByRole('dialog');
        expect(within(dialog).getByRole('alert')).toHaveTextContent(
          `Saved ${platform} configuration for Saved source is unavailable`,
        );
        expect(dialog).toHaveTextContent('does not confirm removal');
        expect(dialog).not.toHaveTextContent('already been removed');
        expect(dialog).not.toHaveTextContent('private detail');
        expect(within(dialog).queryByTestId(`${type}-section`)).toBeNull();
        expect(loadConnections).not.toHaveBeenCalled();
        const retry = within(dialog).getByRole('button', { name: 'Retry saved configuration' });
        fireEvent.click(retry);
        expect(retry).toBeDisabled();
        expect(within(dialog).getByRole('status')).toHaveTextContent(
          `Reading saved ${platform} configuration for Saved source`,
        );
        expect(loadConnections).toHaveBeenCalledTimes(1);
        // A completed empty read, or a namesake with another ID, still cannot
        // establish that this selected connection was removed.
        setLoading(false);
        setConnections([{ id: 'another-source', name: 'Saved source' }]);
        expect(within(dialog).queryByTestId(`${type}-section`)).toBeNull();
        expect(within(dialog).getByRole('alert')).toBeInTheDocument();
        fireEvent.click(retry);
        setConnections([{ id: 'source-1', name: 'Saved source' }]);
        setLoading(false);
        await waitFor(() =>
          expect(within(dialog).getByTestId(`${type}-section`)).toHaveAttribute(
            'data-editing-id',
            'source-1',
          ),
        );
        expect(screen.getByRole('dialog')).toBe(dialog);
        expect(loadConnections).toHaveBeenCalledTimes(2);
        expect(ledgerReadState.reload).not.toHaveBeenCalled();
      },
    );

    it('reacts to withdrawn inventory without remounting an unchanged credential draft on polls', async () => {
      connectionState.connections = [
        connectionFixture({ id: `${type}:source-1`, type, name: 'Saved source' }),
      ];
      const [connections, setConnections] = createSignal<any[]>([{ id: 'source-1' }]);
      const [loading, setLoading] = createSignal(false);
      renderWorkspace({
        [propName]: { closeDialog: vi.fn(), connections, loading, loadConnections: vi.fn() },
      });
      fireEvent.click(await screen.findByRole('button', { name: 'Manage' }));
      const dialog = screen.getByRole('dialog');
      const draft = within(dialog).getByRole('textbox', { name: 'Synthetic credential draft' });
      fireEvent.input(draft, { target: { value: 'synthetic-unsaved-secret' } });
      setLoading(true);
      setConnections([{ id: 'source-1' }]);
      setLoading(false);
      expect(within(dialog).getByRole('textbox')).toBe(draft);
      expect(draft).toHaveValue('synthetic-unsaved-secret');
      expect(savedCredentialSlotMounts[type]).toBe(1);
      setConnections([]);
      expect(within(dialog).queryByRole('textbox')).toBeNull();
      expect(within(dialog).getByRole('alert')).toHaveTextContent('is unavailable');
      expect(screen.getByRole('dialog')).toBe(dialog);
    });

    it('reports an initial pending read and recovers without closing Manage', async () => {
      connectionState.connections = [
        connectionFixture({ id: `${type}:source-1`, type, name: 'Saved source' }),
      ];
      const [connections, setConnections] = createSignal<any[]>([]);
      const [loading, setLoading] = createSignal(true);
      renderWorkspace({
        [propName]: { closeDialog: vi.fn(), connections, loading, loadConnections: vi.fn() },
      });
      fireEvent.click(await screen.findByRole('button', { name: 'Manage' }));
      const dialog = screen.getByRole('dialog');
      expect(within(dialog).getByRole('status')).toHaveTextContent(`Reading saved ${platform}`);
      expect(
        within(dialog).getByRole('button', { name: 'Retry saved configuration' }),
      ).toBeDisabled();
      setConnections([{ id: 'source-1' }]);
      setLoading(false);
      await waitFor(() =>
        expect(within(dialog).getByTestId(`${type}-section`)).toBeInTheDocument(),
      );
      expect(screen.getByRole('dialog')).toBe(dialog);
    });
  });

  it('opens the manage dialog directly from an existing source card', async () => {
    renderWorkspace({
      pveNodes: () => [{ name: 'zeus', host: 'https://10.0.0.1:8006' } as any],
    });

    await waitFor(() =>
      expect(screen.getByRole('button', { name: /^Manage$/i })).toBeInTheDocument(),
    );
    const manageButton = screen.getByRole('button', { name: /^Manage$/i });
    manageButton.focus();
    fireEvent.click(manageButton);

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    const dialog = screen.getByRole('dialog');
    expect(dialog).toHaveAccessibleName('Manage zeus');
    expect(dialog).toHaveAccessibleDescription('Proxmox VE · https://10.0.0.1:8006');
    expect(dialog).toHaveAttribute('aria-labelledby', 'infrastructure-edit-dialog-title');
    expect(dialog).toHaveAttribute('aria-describedby', 'infrastructure-edit-dialog-description');
    expect(screen.getByText('Manage zeus')).toBeInTheDocument();
    expect(screen.getByTestId('proxmox-section')).toBeInTheDocument();

    const focusSpy = vi.spyOn(manageButton, 'focus');
    fireEvent.click(screen.getByRole('button', { name: 'Close edit infrastructure dialog' }));
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
    await new Promise((resolve) => window.setTimeout(resolve, 300));
    expect(focusSpy).toHaveBeenCalledTimes(1);
    expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });
    expect(manageButton).toHaveFocus();
  });

  it('does not steal focus back to Manage after the operator moves on', async () => {
    renderWorkspace({
      pveNodes: () => [{ name: 'zeus', host: 'https://10.0.0.1:8006' } as any],
    });

    const manageButton = await screen.findByRole('button', { name: /^Manage$/i });
    fireEvent.click(manageButton);
    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());

    fireEvent.click(screen.getByRole('button', { name: 'Close edit infrastructure dialog' }));
    const nextAction = screen.getByRole('button', { name: /^Add infrastructure$/i });
    nextAction.focus();

    await new Promise((resolve) => window.setTimeout(resolve, 300));
    expect(nextAction).toHaveFocus();
  });

  it('returns focus to a Manage control recreated by a connection poll', async () => {
    const [revision, setRevision] = createSignal(0);
    connectionState.setObserver(revision, () => setRevision((value) => value + 1));
    renderWorkspace({
      pveNodes: () => [{ name: 'zeus', host: 'https://10.0.0.1:8006' } as any],
    });

    const originalManageButton = await screen.findByRole('button', { name: /^Manage$/i });
    fireEvent.click(originalManageButton);
    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());

    connectionState.connections = [
      connectionFixture({ lastSeen: new Date(Date.now() + 15_000).toISOString() }),
    ];
    connectionState.notifyChanged();
    await waitFor(() =>
      expect(screen.getByRole('button', { name: /^Manage$/i })).not.toBe(originalManageButton),
    );
    const replacementManageButton = screen.getByRole('button', { name: /^Manage$/i });

    fireEvent.click(screen.getByRole('button', { name: 'Close edit infrastructure dialog' }));
    await new Promise((resolve) => window.setTimeout(resolve, 300));
    expect(replacementManageButton).toHaveFocus();
  });

  it('keeps the mounted node editor across connection-ledger refreshes', async () => {
    const [revision, setRevision] = createSignal(0);
    connectionState.setObserver(revision, () => setRevision((value) => value + 1));
    renderWorkspace({
      pveNodes: () => [{ id: 'pve-0', type: 'pve', name: 'zeus' } as any],
    });

    fireEvent.click(await screen.findByRole('button', { name: /^Manage$/i }));
    const method = await screen.findByRole('textbox', { name: 'Authentication method' });
    fireEvent.input(method, { target: { value: 'agent' } });
    expect(method).toHaveValue('agent');

    connectionState.connections = [
      connectionFixture({
        address: 'https://10.0.0.2:8006',
        lastSeen: new Date(Date.now() + 15_000).toISOString(),
      }),
    ];
    connectionState.notifyChanged();

    await waitFor(() =>
      expect(screen.getByRole('textbox', { name: 'Authentication method' })).toHaveValue('agent'),
    );
    expect(screen.getByRole('dialog')).toHaveAccessibleDescription(
      'Proxmox VE · https://10.0.0.2:8006',
    );
    expect(nodeCredentialSlotState.mountCount).toBe(1);
  });

  it('shows standalone agent identity in the landing row and the agent detail drawer', async () => {
    const towerAgent = connectionFixture({
      id: 'agent:tower',
      type: 'agent',
      name: 'Tower',
      address: 'Tower',
      surfaces: ['host'],
      scope: { host: true } as any,
      source: 'agent',
      agentVersion: '6.0.3',
      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 },
    });

    connectionState.connections = [towerAgent];
    connectionState.rows = [
      {
        id: towerAgent.id,
        ownerType: 'agent',
        name: 'Tower',
        subtitle: 'via Pulse Agent',
        identitySubtitle: 'Unraid 7.1.0',
        source: 'agent',
        host: '192.168.0.10',
        coverageLabels: ['Host telemetry'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '0s ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: false,
        canPause: false,
        canRemove: true,
        isAgent: true,
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection: towerAgent,
      },
    ];

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Unraid')).toBeInTheDocument());
    expect(screen.queryByText('Pulse Agent hosts')).toBeNull();
    expect(screen.getByText('Tower')).toBeInTheDocument();
    // Identity and network coordinates stay available through the managed
    // detail flow without competing with health and coverage in the ledger.
    expect(screen.getByTitle('Tower · Unraid 7.1.0')).toBeInTheDocument();
    expect(screen.queryByText('192.168.0.10')).toBeNull();
    fireEvent.click(screen.getByRole('button', { name: /^Add Unraid$/i }));
    expect(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=unraid', {
      scroll: false,
    });
    expect(towerAgent.agentIdentity?.hostProfile).toBe('unraid');
    expect(towerAgent.agentIdentity?.platform).toBe('linux');

    fireEvent.click(screen.getByRole('button', { name: /^Manage$/i }));

    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    expect(screen.getByText('Pulse Agent version')).toBeInTheDocument();
    expect(screen.getByText('6.0.3')).toBeInTheDocument();
    expect(screen.getByText('Operating system')).toBeInTheDocument();
    expect(screen.getAllByText('Unraid 7.1.0').length).toBeGreaterThan(0);
    expect(screen.getByText('Reported hostname')).toBeInTheDocument();
    expect(screen.getByText('tower')).toBeInTheDocument();
    expect(screen.getByText('Reported IP')).toBeInTheDocument();
    expect(screen.getAllByText('192.168.0.10').length).toBeGreaterThan(0);
    expect(screen.getByText('Kernel')).toBeInTheDocument();
    expect(screen.getByText('6.12.0')).toBeInTheDocument();
    expect(screen.getByText('Architecture')).toBeInTheDocument();
    expect(screen.getByText('x86_64')).toBeInTheDocument();
    expect(screen.getByText('Remote commands')).toBeInTheDocument();
    expect(screen.getAllByText('Enabled').length).toBeGreaterThan(0);
  });

  it('hands an agent without command access the host-side step and the preset installer', async () => {
    const towerAgent = connectionFixture({
      id: 'agent:tower',
      type: 'agent',
      name: 'Tower',
      address: 'Tower',
      surfaces: ['host', 'docker'],
      scope: { host: true } as any,
      source: 'agent',
      agentVersion: '6.0.3',
      agentIdentity: { hostname: 'tower', platform: 'linux' },
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });

    connectionState.connections = [towerAgent];
    connectionState.rows = [
      {
        id: towerAgent.id,
        ownerType: 'agent',
        name: 'Tower',
        subtitle: 'via Pulse Agent',
        source: 'agent',
        host: 'tower',
        coverageLabels: ['Host telemetry'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '0s ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: false,
        canPause: false,
        canRemove: true,
        isAgent: true,
        isCluster: false,
        attachedConnections: [],
        members: [],
        connection: towerAgent,
      },
    ];

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('Tower')).toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: /^Manage$/i }));
    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());

    const section = screen.getByRole('region', { name: 'Remote commands' });
    expect(section).toHaveTextContent('Remote commands are off');
    expect(section).toHaveTextContent('Command access is granted on the host, not from Pulse');
    expect(section).toHaveTextContent('Allow Pulse to run commands on this host');

    navigateSpy.mockClear();
    fireEvent.click(within(section).getByRole('button', { name: 'Get install command' }));
    expect(setEnableCommandsSpy).toHaveBeenCalledWith(true);
    expect(navigateSpy).toHaveBeenCalledWith('/settings/infrastructure?add=agent', {
      scroll: false,
    });
  });

  it('shows attached Pulse Agent augmentation details on a grouped platform source', async () => {
    const primaryConnection = connectionFixture();
    const attachedAgent = connectionFixture({
      id: 'agent:zeus',
      type: 'agent',
      name: 'zeus-agent',
      address: 'zeus.lab',
      surfaces: ['host'],
      scope: { host: true } as any,
      lastSeen: new Date().toISOString(),
      agentVersion: '6.0.0',
      expectedAgentVersion: '6.0.3',
      agentUpdateAvailable: true,
      capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
    });

    connectionState.connections = [primaryConnection, attachedAgent];
    connectionState.rows = [
      {
        id: primaryConnection.id,
        ownerType: 'pve',
        name: primaryConnection.name || primaryConnection.id,
        subtitle: 'via platform API and Pulse Agent',
        source: 'both',
        host: primaryConnection.address,
        coverageLabels: ['VMs', 'Host telemetry'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 1,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        enabled: true,
        canEdit: true,
        canPause: true,
        canRemove: true,
        isAgent: false,
        isCluster: false,
        attachedConnections: [attachedAgent],
        members: [],
        connection: primaryConnection,
      },
    ];

    renderWorkspace({
      pveNodes: () => [{ name: 'zeus', host: 'https://10.0.0.1:8006' } as any],
    });

    await waitFor(() =>
      expect(screen.getByRole('button', { name: /^Manage$/i })).toBeInTheDocument(),
    );
    fireEvent.click(screen.getByRole('button', { name: /^Manage$/i }));

    expect(screen.getByText('Agent update')).toBeInTheDocument();
    await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
    expect(screen.getByText('Pulse Agent augmentation')).toBeInTheDocument();
    expect(screen.getByText('zeus-agent')).toBeInTheDocument();
    expect(screen.getByText('Update available')).toBeInTheDocument();
    expect(screen.getByText('6.0.0 -> 6.0.3')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /Copy uninstall command/i })).toBeInTheDocument();
  });

  it('renders Proxmox cluster rows under the cluster moniker instead of a sibling standalone host row', async () => {
    const primaryConnection = connectionFixture();
    const dellyAgent = connectionFixture({
      id: 'agent:agent-delly',
      type: 'agent',
      name: 'delly',
      address: 'delly',
      surfaces: ['host'],
      scope: { host: true },
      source: 'agent',
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    const minipcAgent = connectionFixture({
      id: 'agent:agent-minipc',
      type: 'agent',
      name: 'minipc',
      address: 'minipc',
      surfaces: ['host'],
      scope: { host: true },
      source: 'agent',
      capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
    });
    const passiveAgentConfigSignals: InfrastructureSystemRow['fleetSignals'] = [
      {
        key: 'config-drift',
        label: 'Config pending',
        detail: 'Pulse has not received a comparable applied agent configuration fingerprint yet',
        tone: 'warning',
      },
      {
        key: 'rollout',
        label: 'Rollout pending',
        detail: 'waiting for the agent to report an applied configuration fingerprint',
        tone: 'warning',
      },
    ];
    connectionState.connections = [primaryConnection, dellyAgent, minipcAgent];
    connectionState.rows = [
      {
        id: primaryConnection.id,
        ownerType: 'pve',
        name: 'homelab',
        subtitle: 'Cluster · 2 nodes',
        source: 'api',
        host: undefined,
        coverageLabels: ['VMs', 'Containers', 'Storage', 'Backups'],
        statusLabel: 'Active',
        statusClassName: 'bg-green-100 text-green-800',
        agentUpdateCount: 0,
        lastActivityText: '1m ago',
        ...emptyFleetRow,
        fleetSignals: passiveAgentConfigSignals,
        fleetHighlights: [],
        enabled: true,
        canEdit: true,
        canPause: true,
        canRemove: true,
        isAgent: false,
        isCluster: true,
        attachedConnections: [dellyAgent, minipcAgent],
        members: [
          {
            id: 'node-delly',
            nodeIdentity: 'homelab-delly',
            name: 'Render East',
            nativeName: 'delly',
            subtitle: 'Primary node',
            source: 'agent',
            host: 'https://delly:8006',
            coverageLabels: ['Host telemetry'],
            statusLabel: 'Active',
            statusClassName: 'bg-green-100 text-green-800',
            lastActivityText: '1m ago',
            ...emptyFleetMember,
            fleetSignals: passiveAgentConfigSignals,
            fleetHighlights: [],
            primary: true,
            agentConnection: dellyAgent,
          },
          {
            id: 'node-minipc',
            name: 'minipc',
            subtitle: 'Cluster member',
            source: 'agent',
            host: 'https://minipc:8006',
            coverageLabels: ['Host telemetry'],
            statusLabel: 'Active',
            statusClassName: 'bg-green-100 text-green-800',
            lastActivityText: '1m ago',
            ...emptyFleetMember,
            fleetSignals: passiveAgentConfigSignals,
            fleetHighlights: [],
            primary: false,
            agentConnection: minipcAgent,
          },
        ],
        connection: primaryConnection,
      },
    ];

    renderWorkspace();

    await waitFor(() => expect(screen.getByText('homelab')).toBeInTheDocument());
    const readiness = screen.getByRole('region', {
      name: /Connection posture/i,
    });
    expect(within(readiness).queryByText(/needs attention/i)).toBeNull();
    // Cluster and member descriptors moved into the system name's tooltip to
    // keep table rows single-line.
    expect(screen.getByTitle('homelab · Cluster · 2 nodes')).toBeInTheDocument();
    expect(screen.queryByText('Fleet OK')).toBeNull();
    expect(screen.queryByTitle('Render East · Primary node · Proxmox node delly')).toBeNull();
    fireEvent.click(screen.getByRole('button', { name: 'Show 2 nodes for homelab' }));
    expect(
      screen.getByTitle('Render East · Primary node · Proxmox node delly'),
    ).toBeInTheDocument();
    expect(screen.getAllByText('Agent').length).toBeGreaterThan(0);
    expect(screen.getByText('Render East')).toBeInTheDocument();
    expect(screen.getByText('minipc')).toBeInTheDocument();
    expect(screen.queryByText('Remote control disabled')).toBeNull();
    expect(screen.queryByText('Config pending')).toBeNull();
    expect(screen.queryByText('Rollout pending')).toBeNull();
    expect(screen.getAllByText('Host telemetry').length).toBeGreaterThan(0);
    expect(screen.queryByText('Pulse Agent hosts')).toBeNull();
    expect(screen.getAllByText('Render East')).toHaveLength(1);
    expect(screen.getAllByText('minipc')).toHaveLength(1);
  });

  it('hides the add flow and source-manager actions in read-only mode', () => {
    presentationPolicyIsReadOnlyMock.mockReturnValue(true);
    routeState.search = '?add=agent';
    renderWorkspace();

    expect(screen.queryByRole('button', { name: /Detect address/i })).toBeNull();
    expect(screen.queryByRole('button', { name: /Add Proxmox VE/i })).toBeNull();
    expect(screen.queryByRole('button', { name: /^Manage$/i })).toBeNull();
    expect(screen.queryByRole('dialog')).toBeNull();
    expect(screen.queryByTestId('install-section')).toBeNull();
    expect(screen.getByText('Connected systems')).toBeInTheDocument();
    expect(screen.queryByRole('heading', { name: 'Monitored systems' })).not.toBeInTheDocument();
  });
});

describe('infrastructureRowMonitoringPath', () => {
  // A PBS read as Active in this workspace while its servers sat under
  // Proxmox > Backups, and its user could not find it (#2905).
  it('sends each API-collected system to the page that shows its data', () => {
    expect(infrastructureRowMonitoringPath({ ownerType: 'pve' })).toBe('/proxmox/overview');
    expect(infrastructureRowMonitoringPath({ ownerType: 'pbs' })).toBe('/proxmox/backups');
    expect(infrastructureRowMonitoringPath({ ownerType: 'pmg' })).toBe('/proxmox/mail');
    expect(infrastructureRowMonitoringPath({ ownerType: 'vmware' })).toBe('/vmware/overview');
    expect(infrastructureRowMonitoringPath({ ownerType: 'truenas' })).toBe('/truenas/overview');
    expect(infrastructureRowMonitoringPath({ ownerType: 'docker' })).toBe('/docker/overview');
    expect(infrastructureRowMonitoringPath({ ownerType: 'kubernetes' })).toBe(
      '/kubernetes/overview',
    );
  });

  it('gives agent hosts and availability checks no single destination', () => {
    // An agent host shows on Proxmox, Machines or Kubernetes depending on
    // what it runs, so a fixed link would often be wrong.
    expect(infrastructureRowMonitoringPath({ ownerType: 'agent' })).toBeUndefined();
    expect(infrastructureRowMonitoringPath({ ownerType: 'availability' })).toBeUndefined();
  });
});