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.

97.2 KB
Raw Blame
import {
  For,
  Show,
  createMemo,
  createSignal,
  onCleanup,
  onMount,
  type Accessor,
  type Component,
} from 'solid-js';
import {
  AlertTriangle,
  ChevronDown,
  ChevronRight,
  Cpu,
  Plus,
  RotateCw,
  Search,
  SlidersHorizontal,
} from 'lucide-solid';
import { Button } from '@/components/shared/Button';
import { getAPIReadAccessErrorMessage } from '@/utils/apiAccessError';
import SettingsPanel from '@/components/shared/SettingsPanel';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/shared/Table';
import {
  getGroupedTableRowCellClass,
  getGroupedTableRowClass,
} from '@/components/shared/groupedTableRowPresentation';
import {
  connectionAgentVersionPresentation,
  infrastructureRowMonitoringPath,
  infrastructureSourcePresentation,
  surfaceLabel,
  type InfrastructureSourcePresentation,
  type InfrastructureSystemMemberRow,
  type InfrastructureSystemRow,
} from './connectionsTableModel';
import type { DiscoveredServer, DiscoveryScanStatus } from './infrastructureSettingsModel';
import {
  getInfrastructureEmptyStateDetail,
  getInfrastructureEmptyStateSummary,
  getInfrastructureOnboardingProductPresentation,
  getInfrastructureSourceManagerProducts,
  getInfrastructureSourcePickerItemForRouteStep,
  type InfrastructureOnboardingConnectionType,
  type InfrastructureSourcePickerRouteStep,
} from '@/utils/infrastructureOnboardingPresentation';
import { getAgentHostProfileFamily } from '@/utils/platformSupportManifest';
import { ClusterAgentDeployDialog } from './ClusterAgentDeployDialog';

interface InfrastructureSourceManagerProps {
  rows: Accessor<readonly InfrastructureSystemRow[]>;
  inventoryLoading?: boolean;
  inventoryError?: unknown;
  onRetryInventory?: () => void;
  discoveredNodes: Accessor<readonly DiscoveredServer[]>;
  discoveryEnabled: boolean;
  discoveryScanStatus: Accessor<DiscoveryScanStatus>;
  readOnly: boolean;
  onAddSource?: (type: InfrastructureOnboardingConnectionType) => void;
  onAddSourceStep?: (step: InfrastructureSourcePickerRouteStep) => void;
  onAddInfrastructure?: () => void;
  onRunDiscovery?: () => void;
  onOpenDiscoverySettings?: () => void;
  onOpenConnection?: (row: InfrastructureSystemRow) => void;
  onOpenAgentDoctor?: (agentIds?: string[]) => void;
  onReviewDiscoveredSource?: (server: DiscoveredServer) => void;
}

// A connected system's name opens the page that shows its data (#2905).
// Underlined at rest: touch users get no hover hint, and the user in #2905 was
// not looking for something to click.
const MONITORING_LINK_CLASS =
  'text-blue-700 underline decoration-blue-700/40 underline-offset-2 hover:decoration-current focus-visible:decoration-current dark:text-blue-300 dark:decoration-blue-300/40';

// Per-section 'Add' shortcuts are demoted to ghost text buttons so the
// primary '+ Add infrastructure' CTA at the top of the page stays visually
// dominant. They retain the 1-click shortcut for users adding another node
// to an existing platform without competing with the primary CTA.
const addSectionButtonClass =
  'inline-flex min-h-11 items-center justify-center gap-1 rounded-sm px-2 py-0.5 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-50 lg:min-h-0 dark:text-blue-300 dark:hover:bg-blue-950/30';
const discoveryRowClass =
  'border-b border-border-subtle bg-blue-50/30 hover:bg-blue-50/40 dark:bg-blue-950/10 dark:hover:bg-blue-950/20';
const discoveryScanTargetLabel = 'Proxmox VE, Proxmox Backup Server, and Proxmox Mail Gateway APIs';
// The system column shows just the name on a single line. The OS / version
// (standalone) or cluster identity (cluster) descriptor that used to sit on a
// second line moves into the name's hover title, so every row stays one line
// like the platform overview tables. Discovery rows already fold version into
// the name title the same way.
const rowSystemTitle = (row: InfrastructureSystemRow): string => {
  const detail = row.isCluster ? row.subtitle : row.identitySubtitle;
  return detail ? `${row.name} · ${detail}` : row.name;
};

const memberSystemTitle = (member: InfrastructureSystemMemberRow): string => {
  const details = [
    member.subtitle,
    member.nativeName && member.nativeName !== member.name
      ? `Proxmox node ${member.nativeName}`
      : undefined,
  ].filter(Boolean);
  return details.length > 0 ? `${member.name} · ${details.join(' · ')}` : member.name;
};
// The connected-systems table sets `min-w-[820px]`; switch to the card
// layout whenever the measured container can't fit that, otherwise the
// table renders but overflows horizontally inside the settings panel.
const CARD_LAYOUT_MAX_WIDTH_PX = 819;

const sortRows = (rows: readonly InfrastructureSystemRow[]): InfrastructureSystemRow[] =>
  [...rows].sort((left, right) => left.name.localeCompare(right.name));

const sortDiscoveredNodes = (nodes: readonly DiscoveredServer[]): DiscoveredServer[] =>
  [...nodes].sort((left, right) => {
    const leftLabel = (left.hostname || left.ip).toLowerCase();
    const rightLabel = (right.hostname || right.ip).toLowerCase();
    return leftLabel.localeCompare(rightLabel);
  });

const normalizeDiscoveryTimestamp = (value?: number): number | undefined => {
  if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
    return undefined;
  }

  return value < 1_000_000_000_000 ? value * 1000 : value;
};

const formatRelativeTimestamp = (value?: number): string | undefined => {
  const timestamp = normalizeDiscoveryTimestamp(value);
  if (!timestamp) return undefined;

  const diff = Math.max(0, Date.now() - timestamp);
  const sec = Math.floor(diff / 1000);
  if (sec < 60) return `${sec}s ago`;
  const min = Math.floor(sec / 60);
  if (min < 60) return `${min}m ago`;
  const hr = Math.floor(min / 60);
  if (hr < 24) return `${hr}h ago`;
  const days = Math.floor(hr / 24);
  return `${days}d ago`;
};

const discoverySubnetLabel = (status: DiscoveryScanStatus): string => {
  const subnet = status.subnet?.trim();
  if (!subnet || subnet.toLowerCase() === 'auto') {
    return 'auto-detected networks';
  }
  return subnet;
};

const discoveryErrorSummary = (errors?: readonly string[]): string | undefined => {
  const normalized = (errors ?? []).map((error) => error.trim()).filter(Boolean);
  if (normalized.length === 0) return undefined;
  if (normalized.length === 1) return normalized[0];
  return `${normalized.length} scan issues reported`;
};

const discoveredServerName = (server: DiscoveredServer): string =>
  server.hostname?.trim() || server.ip;

const discoveredServerEndpoint = (server: DiscoveredServer): string =>
  `https://${server.hostname?.trim() || server.ip}:${server.port}`;

const discoveredCoverageText = (server: DiscoveredServer): string => {
  const keys = getInfrastructureOnboardingProductPresentation(server.type).defaultSurfaceKeys;
  if (keys.length === 0) return '';
  return keys.map(surfaceLabel).join(', ');
};

const agentMethodTitleFor = (row: InfrastructureSystemRow): string | undefined => {
  const agentConnections = row.attachedConnections.filter(
    (connection) => connection.type === 'agent',
  );
  if (row.connection.type === 'agent') {
    agentConnections.unshift(row.connection);
  }
  if (agentConnections.length === 0) return undefined;
  if (agentConnections.length === 1) {
    return connectionAgentVersionPresentation(agentConnections[0])?.title ?? 'Pulse Agent attached';
  }
  return `${agentConnections.length} Pulse Agent attachments`;
};

const memberMethodTitleFor = (
  row: InfrastructureSystemRow,
  memberIndex: number,
): string | undefined => {
  const member = row.members[memberIndex];
  if (!member?.agentConnection) return undefined;
  return (
    connectionAgentVersionPresentation(member.agentConnection)?.title ??
    'Pulse Agent attached to cluster member'
  );
};

// Cluster member rows describe nodes reached through the cluster's single API
// connection. Repeating the connection-level "API" badge on every node reads
// as per-node API credentials (#1493), so member rows only badge sources that
// are actually node-local: an attached Pulse Agent. API-only members render a
// muted dash with an explanatory tooltip instead.
const MEMBER_SHARED_API_TITLE =
  "Monitored through the cluster's API connection. One connection covers every node in the cluster.";

const memberMethodPresentation = (
  member: InfrastructureSystemMemberRow,
): InfrastructureSourcePresentation | null => {
  if (member.source === 'api') return null;
  if (member.source === 'both') return infrastructureSourcePresentation('agent');
  return infrastructureSourcePresentation(member.source);
};

interface SetupConfidenceAction {
  label: string;
  onClick: () => void;
}

interface ConfiguredSourceGroup {
  id: string;
  label: string;
  actionLabel: string;
  actionType: InfrastructureOnboardingConnectionType;
  actionStep?: InfrastructureSourcePickerRouteStep;
  rows: InfrastructureSystemRow[];
}

// A partial read is a warning on a reachable source; any other error is an
// outage and keeps the critical treatment.
const rowErrorBannerClass = (row: InfrastructureSystemRow): string =>
  row.lastErrorTone === 'warning'
    ? 'rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-900/25 dark:bg-amber-950/25 dark:text-amber-200'
    : 'rounded-md border border-rose-300 bg-rose-50 px-3 py-2 text-xs text-rose-800 dark:border-rose-900/25 dark:bg-rose-950/25 dark:text-rose-200';

const formatCount = (count: number, noun: string): string =>
  `${count} ${noun}${count === 1 ? '' : 's'}`;

const rowHasApiCoverage = (row: InfrastructureSystemRow): boolean =>
  row.source === 'api' ||
  row.source === 'both' ||
  row.members.some((member) => member.source === 'api' || member.source === 'both');

const rowHasAgentCoverage = (row: InfrastructureSystemRow): boolean =>
  row.source === 'agent' ||
  row.source === 'both' ||
  row.attachedConnections.some((connection) => connection.type === 'agent') ||
  row.members.some(
    (member) => member.source === 'agent' || member.source === 'both' || member.agentConnection,
  );

const memberHasAgentCoverage = (member: InfrastructureSystemMemberRow): boolean =>
  member.source === 'agent' || member.source === 'both' || Boolean(member.agentConnection);

const missingAgentMembers = (row: InfrastructureSystemRow): InfrastructureSystemMemberRow[] => {
  if (row.ownerType !== 'pve' || !row.isCluster) return [];
  return row.members.filter((member) => !memberHasAgentCoverage(member));
};

// A cluster is not fully covered when even one node lacks its local agent.
// Checking only the parent source hides onboarding as soon as the first member
// reports, which makes a partly instrumented cluster look complete.
const rowNeedsAgentCoverage = (row: InfrastructureSystemRow): boolean => {
  if (row.ownerType !== 'pve' || !rowHasApiCoverage(row)) return false;
  if (row.isCluster) return missingAgentMembers(row).length > 0;
  return !rowHasAgentCoverage(row);
};

const missingAgentTargetNames = (row: InfrastructureSystemRow): string[] => {
  if (!rowNeedsAgentCoverage(row)) return [];
  if (!row.isCluster) return [row.name];
  return missingAgentMembers(row).map((member) => member.name);
};

const missingAgentCoverageLabel = (row: InfrastructureSystemRow): string => {
  const count = missingAgentMembers(row).length;
  return row.isCluster
    ? `${formatCount(count, 'node')} ${count === 1 ? 'needs' : 'need'} host telemetry`
    : 'Host telemetry not installed';
};

const installAgentActionLabel = (row: InfrastructureSystemRow): string => {
  const count = missingAgentMembers(row).length;
  return row.isCluster
    ? `Install node agents on ${formatCount(count, 'uncovered node')} in ${row.name}`
    : `Install agent on ${row.name}`;
};

export const agentConnectionIDsForInfrastructureRow = (
  row: InfrastructureSystemRow,
  updatesOnly = false,
): string[] => {
  const connections = [
    row.connection,
    ...row.attachedConnections,
    ...row.members.map((member) => member.agentConnection).filter(Boolean),
  ];
  return Array.from(
    new Set(
      connections
        .filter(
          (connection) =>
            connection?.type === 'agent' &&
            (!updatesOnly ||
              Boolean(connection.agentUpdateAvailable) ||
              connection.fleet?.versionDrift === 'behind'),
        )
        .map((connection) => connection!.id),
    ),
  ).sort((left, right) => left.localeCompare(right));
};

const agentHostProfileRouteStep = (
  row: InfrastructureSystemRow,
): InfrastructureSourcePickerRouteStep | null => {
  if (row.connection.type !== 'agent') return null;
  const hostProfile = row.connection.agentIdentity?.hostProfile?.trim().toLowerCase();
  if (!hostProfile) return null;
  return getInfrastructureSourcePickerItemForRouteStep(hostProfile)?.routeStep ?? null;
};

const agentHostProfileGroupLabel = (row: InfrastructureSystemRow): string | null => {
  if (row.connection.type !== 'agent') return null;
  return getAgentHostProfileFamily(row.connection.agentIdentity?.hostProfile) ?? null;
};

export const InfrastructureSourceManager: Component<InfrastructureSourceManagerProps> = (props) => {
  let layoutContainerRef: HTMLDivElement | undefined;
  const products = createMemo(() => getInfrastructureSourceManagerProducts());
  const inventoryReadUncertain = () => Boolean(props.inventoryLoading || props.inventoryError);
  const infrastructureRows = createMemo(() =>
    props.rows().filter((row) => row.ownerType !== 'availability'),
  );

  const groupedConfiguredRows = createMemo(() => {
    const next = new Map<InfrastructureOnboardingConnectionType, InfrastructureSystemRow[]>();
    for (const product of products()) {
      next.set(product.type, []);
    }

    for (const row of infrastructureRows()) {
      const productRows = next.get(row.ownerType as InfrastructureOnboardingConnectionType);
      if (!productRows) continue;
      productRows.push(row);
    }

    for (const [type, rows] of next.entries()) {
      next.set(type, sortRows(rows));
    }

    return next;
  });

  const groupedDiscoveredRows = createMemo(() => {
    const next = new Map<InfrastructureOnboardingConnectionType, DiscoveredServer[]>();
    for (const product of products()) {
      next.set(product.type, []);
    }

    // A failed inventory cannot establish that a discovered system is new.
    for (const server of inventoryReadUncertain() ? [] : props.discoveredNodes()) {
      const productRows = next.get(server.type as InfrastructureOnboardingConnectionType);
      if (!productRows) continue;
      productRows.push(server);
    }

    for (const [type, rows] of next.entries()) {
      next.set(type, sortDiscoveredNodes(rows));
    }

    return next;
  });

  const sortedProducts = createMemo(() =>
    products().filter((product) => {
      const configuredCount = groupedConfiguredRows().get(product.type)?.length ?? 0;
      const discoveredCount = groupedDiscoveredRows().get(product.type)?.length ?? 0;
      return configuredCount + discoveredCount > 0;
    }),
  );

  const configuredSourceGroupsForProduct = (
    product: ReturnType<typeof getInfrastructureSourceManagerProducts>[number],
    rows: readonly InfrastructureSystemRow[],
  ): ConfiguredSourceGroup[] => {
    if (product.type !== 'agent') {
      return [
        {
          id: product.type,
          label: product.label,
          actionLabel: product.actionLabel,
          actionType: product.type,
          rows: [...rows],
        },
      ];
    }

    const profileGroups = new Map<string, ConfiguredSourceGroup>();
    const genericRows: InfrastructureSystemRow[] = [];

    for (const row of rows) {
      const profileLabel = agentHostProfileGroupLabel(row);
      const profileStep = agentHostProfileRouteStep(row);
      if (!profileLabel || !profileStep) {
        genericRows.push(row);
        continue;
      }

      const existing = profileGroups.get(profileStep);
      if (existing) {
        existing.rows.push(row);
        continue;
      }

      profileGroups.set(profileStep, {
        id: `agent-profile:${profileStep}`,
        label: profileLabel,
        actionLabel: `Add ${profileLabel}`,
        actionType: product.type,
        actionStep: profileStep,
        rows: [row],
      });
    }

    return [
      ...Array.from(profileGroups.values()).sort((left, right) =>
        left.label.localeCompare(right.label),
      ),
      ...(genericRows.length > 0
        ? [
            {
              id: product.type,
              label: product.label,
              actionLabel: product.actionLabel,
              actionType: product.type,
              rows: genericRows,
            },
          ]
        : []),
    ];
  };

  const fallbackConfiguredGroupForProduct = (
    product: ReturnType<typeof getInfrastructureSourceManagerProducts>[number],
  ): ConfiguredSourceGroup => ({
    id: product.type,
    label: product.label,
    actionLabel: product.actionLabel,
    actionType: product.type,
    rows: [],
  });

  const visibleSourceGroupsForProduct = (
    product: ReturnType<typeof getInfrastructureSourceManagerProducts>[number],
    configuredGroups: readonly ConfiguredSourceGroup[],
    hasDiscoveredRows: boolean,
  ): ConfiguredSourceGroup[] => {
    const groups = [...configuredGroups];
    const hasFallbackGroup = groups.some((group) => group.id === product.type);
    if (groups.length === 0 || (hasDiscoveredRows && !hasFallbackGroup)) {
      groups.push(fallbackConfiguredGroupForProduct(product));
    }
    return groups;
  };

  const handleGroupAddSource = (group: ConfiguredSourceGroup) => {
    if (group.actionStep && props.onAddSourceStep) {
      props.onAddSourceStep(group.actionStep);
      return;
    }
    props.onAddSource?.(group.actionType);
  };

  const handleInstallAgentShortcut = () => {
    if (props.onAddSourceStep) {
      props.onAddSourceStep('linux-host');
      return;
    }
    props.onAddSource?.('agent');
  };

  // Cluster members are installed in one step when a sibling already runs
  // the agent: Pulse asks that agent to install on its peers, so there is no
  // per-host token to copy. Clusters without a reporting agent, and standalone
  // hosts, keep the scoped manual installer.
  const [clusterDeploy, setClusterDeploy] = createSignal<{
    clusterName: string;
    nodeName?: string;
  } | null>(null);
  const canInstallFromCluster = (row: InfrastructureSystemRow): boolean =>
    !props.readOnly &&
    row.isCluster &&
    Boolean(row.clusterName) &&
    row.members.some((member) => Boolean(member.agentConnection));
  const handleInstallAgent = (
    row: InfrastructureSystemRow,
    member?: InfrastructureSystemMemberRow,
  ) => {
    if (canInstallFromCluster(row)) {
      setClusterDeploy({
        clusterName: row.clusterName!,
        nodeName: member?.nativeName || member?.name,
      });
      return;
    }
    handleInstallAgentShortcut();
  };

  const hasAnyConfigured = createMemo(() => infrastructureRows().length > 0);
  const hasAnyDiscovered = createMemo(() => props.discoveredNodes().length > 0);

  const rowInteractive = (row: InfrastructureSystemRow): boolean =>
    !props.readOnly && Boolean(props.onOpenConnection) && (row.canEdit || row.isAgent);

  const actionColumnVisible = () => !props.readOnly;
  // Actions holds Manage (about 96px with padding) and, on a row missing agent
  // coverage, an install button beside it. Reserving the wide column only when
  // a row shows that button leaves Health room for its state, the Agent update
  // badge and the last-seen time on one line.
  const actionColumnShowsInstall = createMemo(
    () =>
      Boolean(props.onAddSourceStep || props.onAddSource) &&
      infrastructureRows().some((row) => rowNeedsAgentCoverage(row)),
  );
  const lastDiscoveryResultText = createMemo(() =>
    formatRelativeTimestamp(props.discoveryScanStatus().lastResultAt),
  );
  const connectedSystemCount = createMemo(() => infrastructureRows().length);
  const agentConnectionIds = createMemo(() =>
    Array.from(
      new Set(infrastructureRows().flatMap((row) => agentConnectionIDsForInfrastructureRow(row))),
    ),
  );
  const discoveredCandidateCount = createMemo(() => props.discoveredNodes().length);
  // Scoped to Proxmox VE: PBS/PMG/TrueNAS/etc. are fully covered by their
  // own API and don't benefit from a paired agent in the way PVE hosts do
  // (where the agent adds temps, SMART, host identity). Counting them here
  // would create "Needs agent" pressure for systems that need nothing.
  const uncoveredAgentTargets = createMemo(() =>
    infrastructureRows().flatMap((row) => missingAgentTargetNames(row)),
  );
  const uncoveredAgentTargetCount = createMemo(() => uncoveredAgentTargets().length);
  // Counters read directly off the row state the user sees: a row is live
  // when its status is "Active" and needs attention when its derived
  // problem (or any member's) is non-empty. Going via signal predicates
  // duplicated the rollup logic and could disagree with what was rendered.
  const liveFleetSystemCount = createMemo(
    () => infrastructureRows().filter((row) => row.statusLabel === 'Active').length,
  );
  const fleetAttentionSystemCount = createMemo(
    () =>
      infrastructureRows().filter(
        (row) => Boolean(row.problem) || row.members.some((member) => member.problem),
      ).length,
  );
  // Outdated agents are maintenance rather than attention (see
  // FleetGovernanceSignal.maintenance); the band still counts them once.
  const agentUpdateTotal = createMemo(() =>
    infrastructureRows().reduce((total, row) => total + row.agentUpdateCount, 0),
  );
  const discoveryMonitorTitle = createMemo(() => {
    const status = props.discoveryScanStatus();
    if (status.scanning) return 'Scanning';
    if (discoveredCandidateCount() > 0) {
      return `${discoveredCandidateCount()} to review`;
    }
    if (!props.discoveryEnabled) return 'Off';
    if (discoveryErrorSummary(status.errors)) return 'Needs attention';
    return 'Ready';
  });
  const discoveryMonitorDetail = createMemo(() => {
    const status = props.discoveryScanStatus();
    const subnet = discoverySubnetLabel(status);
    const errors = discoveryErrorSummary(status.errors);
    if (status.scanning) {
      return `Pulse is scanning ${subnet} for ${discoveryScanTargetLabel}. Candidates appear below for review before anything is added.`;
    }
    if (discoveredCandidateCount() > 0) {
      return `${formatCount(discoveredCandidateCount(), 'candidate')} found on ${subnet}. Review and add credentials before Pulse starts monitoring it.`;
    }
    if (!props.discoveryEnabled) {
      return `Enable discovery to scan configured networks for ${discoveryScanTargetLabel}.`;
    }
    if (errors) {
      return errors;
    }
    if (lastDiscoveryResultText()) {
      return `Last scan checked ${subnet} ${lastDiscoveryResultText()} and found no unattached platform APIs.`;
    }
    return `Run discovery to look for unattached ${discoveryScanTargetLabel} on the configured networks.`;
  });
  const discoveryMonitorMeta = createMemo(() => {
    const status = props.discoveryScanStatus();
    if (status.scanning && status.lastScanStartedAt) {
      return `Started ${formatRelativeTimestamp(status.lastScanStartedAt) ?? 'just now'}`;
    }
    if (lastDiscoveryResultText()) return `Last scanned ${lastDiscoveryResultText()}`;
    // Off with no result says nothing more than the Off badge beside it. A
    // manual scan's result is not stored server-side, so after a reload "never
    // scanned" could be false; "no result yet" is true either way.
    return props.discoveryEnabled ? 'No scan result yet' : '';
  });
  // Follow-up action for systems that are already connected. With none
  // connected the page-header 'Add infrastructure' button is the one way in,
  // so this band offers nothing rather than a second button for the same job.
  const setupConfidenceAction = createMemo<SetupConfidenceAction | undefined>(() => {
    if (uncoveredAgentTargetCount() > 0 && (props.onAddSourceStep || props.onAddSource)) {
      // When every uncovered host sits in one cluster that can install from a
      // sibling, the summary action opens that one-step install directly.
      const uncoveredRows = infrastructureRows().filter((row) => rowNeedsAgentCoverage(row));
      const soleCluster =
        uncoveredRows.length === 1 && canInstallFromCluster(uncoveredRows[0])
          ? uncoveredRows[0]
          : undefined;
      return {
        label: uncoveredAgentTargetCount() === 1 ? 'Install agent' : 'Install agents',
        onClick: soleCluster ? () => handleInstallAgent(soleCluster) : handleInstallAgentShortcut,
      };
    }

    return undefined;
  });
  const [layoutWidth, setLayoutWidth] = createSignal(
    typeof window !== 'undefined' ? window.innerWidth : 1024,
  );
  const [expandedSystemIds, setExpandedSystemIds] = createSignal<ReadonlySet<string>>(new Set());

  const membersExpanded = (row: InfrastructureSystemRow): boolean =>
    expandedSystemIds().has(row.id);

  const toggleMembers = (row: InfrastructureSystemRow) => {
    setExpandedSystemIds((current) => {
      const next = new Set(current);
      if (next.has(row.id)) {
        next.delete(row.id);
      } else {
        next.add(row.id);
      }
      return next;
    });
  };

  const updateLayoutWidth = (width: number) => {
    if (!Number.isFinite(width) || width <= 0) return;
    setLayoutWidth(Math.round(width));
  };

  const measureLayoutWidth = () => {
    const width = layoutContainerRef?.getBoundingClientRect().width;
    if (typeof width === 'number') {
      updateLayoutWidth(width);
    }
  };

  onMount(() => {
    measureLayoutWidth();

    if (typeof ResizeObserver === 'undefined' || !layoutContainerRef) {
      const handleResize = () => measureLayoutWidth();
      window.addEventListener('resize', handleResize);
      onCleanup(() => window.removeEventListener('resize', handleResize));
      return;
    }

    const observer = new ResizeObserver((entries) => {
      const entryWidth = entries[0]?.contentRect.width;
      if (typeof entryWidth === 'number') {
        updateLayoutWidth(entryWidth);
        return;
      }
      measureLayoutWidth();
    });
    observer.observe(layoutContainerRef);
    onCleanup(() => observer.disconnect());
  });
  const useCardLayout = createMemo(() => layoutWidth() <= CARD_LAYOUT_MAX_WIDTH_PX);

  const discoveryMonitorBand = () => (
    <section
      aria-label="Discover Proxmox systems"
      aria-live="polite"
      class="border-t border-border px-4 py-3"
    >
      <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
        <div class="min-w-0 flex-1">
          <div class="text-[11px] font-medium uppercase tracking-[0.08em] text-muted">
            Optional setup
          </div>
          <div class="mt-1 flex flex-wrap items-center gap-2">
            <h3 class="flex items-center gap-2 text-sm font-semibold text-base-content">
              <Search class="h-4 w-4 text-blue-600 dark:text-blue-300" aria-hidden="true" />
              Discover Proxmox systems
            </h3>
            <span
              class={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${
                props.discoveryScanStatus().scanning
                  ? 'bg-blue-100 text-blue-800 dark:bg-blue-950/40 dark:text-blue-200'
                  : discoveryErrorSummary(props.discoveryScanStatus().errors)
                    ? 'bg-amber-100 text-amber-800 dark:bg-amber-950/40 dark:text-amber-200'
                    : props.discoveryEnabled
                      ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200'
                      : 'bg-surface-alt text-muted'
              }`}
            >
              {discoveryMonitorTitle()}
            </span>
            <Show when={discoveryMonitorMeta()}>
              <span class="text-xs text-muted">{discoveryMonitorMeta()}</span>
            </Show>
          </div>
          <p class="mt-1 max-w-4xl text-xs leading-5 text-muted">{discoveryMonitorDetail()}</p>
          <Show when={discoveryErrorSummary(props.discoveryScanStatus().errors)}>
            {(summary) => (
              <div class="mt-2 flex items-start gap-2 text-xs text-amber-800 dark:text-amber-200">
                <AlertTriangle class="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
                <span>{summary()}</span>
              </div>
            )}
          </Show>
        </div>

        <Show when={!props.readOnly}>
          <div class="flex flex-wrap gap-2 lg:justify-end">
            <Show when={discoveredCandidateCount() > 0 && props.onReviewDiscoveredSource}>
              <Button
                type="button"
                variant="primary"
                size="mdCompact"
                class="min-h-11 gap-2 lg:min-h-9"
                onClick={() => props.onReviewDiscoveredSource?.(props.discoveredNodes()[0])}
              >
                <Search class="h-4 w-4" aria-hidden="true" />
                {discoveredCandidateCount() === 1 ? 'Review candidate' : 'Review first candidate'}
              </Button>
            </Show>
            <Show when={props.discoveryEnabled && props.onRunDiscovery}>
              <Button
                type="button"
                variant={discoveredCandidateCount() > 0 ? 'secondary' : 'primary'}
                size="mdCompact"
                class="min-h-11 gap-2 lg:min-h-9"
                onClick={props.onRunDiscovery}
                disabled={props.discoveryScanStatus().scanning}
                title={`Scan configured networks for reachable ${discoveryScanTargetLabel}. Discovered candidates appear here for review before they are added.`}
              >
                <RotateCw
                  class={`h-4 w-4 ${props.discoveryScanStatus().scanning ? 'animate-spin' : ''}`}
                  aria-hidden="true"
                />
                {props.discoveryScanStatus().scanning ? 'Scanning...' : 'Run discovery'}
              </Button>
            </Show>
            <Show when={props.onOpenDiscoverySettings}>
              <Button
                type="button"
                variant="secondary"
                size="mdCompact"
                class="min-h-11 gap-2 lg:min-h-9"
                onClick={props.onOpenDiscoverySettings}
                title={`Configure which networks Pulse scans for ${discoveryScanTargetLabel}.`}
              >
                <SlidersHorizontal class="h-4 w-4" aria-hidden="true" />
                {props.discoveryEnabled ? 'Settings' : 'Configure discovery'}
              </Button>
            </Show>
          </div>
        </Show>
      </div>
    </section>
  );

  const setupSummaryBand = () => (
    <section aria-label="Connection posture" class="border-b border-border bg-surface px-4 py-3">
      <h3 class="sr-only">Connection posture</h3>
      <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div class="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-sm">
          <span class="font-semibold text-base-content">
            {formatCount(connectedSystemCount(), 'system')} connected
          </span>
          <Show when={connectedSystemCount() > 0}>
            <span aria-hidden="true" class="text-muted">
              ·
            </span>
            <span class="text-muted">
              {liveFleetSystemCount() === connectedSystemCount()
                ? 'All active'
                : `${formatCount(liveFleetSystemCount(), 'system')} active`}
            </span>
          </Show>
          <Show when={fleetAttentionSystemCount() > 0}>
            <span aria-hidden="true" class="text-muted">
              ·
            </span>
            <span class="font-medium text-amber-700 dark:text-amber-300">
              {formatCount(fleetAttentionSystemCount(), 'system')}{' '}
              {fleetAttentionSystemCount() === 1 ? 'needs' : 'need'} attention
            </span>
          </Show>
          <Show when={agentUpdateTotal() > 0}>
            <span aria-hidden="true" class="text-muted">
              ·
            </span>
            <span class="text-muted" data-infrastructure-agent-updates>
              {formatCount(agentUpdateTotal(), 'agent update')} available
            </span>
          </Show>
          <Show when={uncoveredAgentTargetCount() > 0}>
            <span aria-hidden="true" class="text-muted">
              ·
            </span>
            <span class="font-medium text-amber-700 dark:text-amber-300">
              {formatCount(uncoveredAgentTargetCount(), 'host')}{' '}
              {uncoveredAgentTargetCount() === 1 ? 'has' : 'have'} limited coverage
            </span>
          </Show>
        </div>
        <Show when={!props.readOnly}>
          <div class="flex flex-wrap gap-2 self-start sm:self-center">
            <Show when={agentConnectionIds().length > 0 && props.onOpenAgentDoctor}>
              <Button
                type="button"
                variant={fleetAttentionSystemCount() > 0 ? 'primary' : 'secondary'}
                size="mdCompact"
                onClick={() => props.onOpenAgentDoctor?.()}
                class="min-h-11 lg:min-h-9"
              >
                Open Agent Doctor
              </Button>
            </Show>
            <Show when={setupConfidenceAction()}>
              {(action) => (
                <Button
                  type="button"
                  variant="secondary"
                  size="mdCompact"
                  onClick={() => action().onClick()}
                  class="min-h-11 gap-2 lg:min-h-9"
                >
                  <Cpu class="h-4 w-4" />
                  {action().label}
                </Button>
              )}
            </Show>
          </div>
        </Show>
      </div>
    </section>
  );

  // Rendered inside a `.table-fixed` cell, whose global rule forces nowrap on
  // the cell itself (and a utility class on the cell loses to it), so the
  // wrapper resets wrapping: the prose below must wrap, not clip.
  const emptyStateContent = () => (
    <div class="mx-auto max-w-3xl space-y-2 whitespace-normal">
      <div class="text-sm font-semibold text-base-content">Start monitoring infrastructure</div>
      <p>{getInfrastructureEmptyStateSummary()}</p>
      <p class="text-xs leading-5 text-muted">{getInfrastructureEmptyStateDetail()}</p>
    </div>
  );

  const inventoryReadNotice = () => (
    <Show
      when={props.inventoryError}
      fallback={
        <Show when={props.inventoryLoading}>
          <div role="status" class="border-b border-border px-4 py-4 text-sm text-muted">
            {hasAnyConfigured()
              ? 'Refreshing connected systems...'
              : 'Loading connected systems...'}
          </div>
        </Show>
      }
    >
      <div
        role="alert"
        class="flex flex-col gap-3 border-b border-amber-300 bg-amber-50 px-4 py-4 text-sm text-amber-900 sm:flex-row sm:items-center sm:justify-between dark:border-amber-900/25 dark:bg-amber-950/25 dark:text-amber-200"
      >
        <div class="min-w-0 space-y-1">
          <p class="font-semibold">Connected systems unavailable</p>
          <p>
            {getAPIReadAccessErrorMessage(props.inventoryError) ??
              'Pulse could not read the connection list. Retry to check your saved systems.'}
          </p>
          <Show when={hasAnyConfigured()}>
            <p>Showing the last loaded list. Connection status may be out of date.</p>
          </Show>
        </div>
        <Show when={props.onRetryInventory}>
          <Button
            type="button"
            variant="secondary"
            size="mdCompact"
            class="min-h-11 shrink-0 self-start sm:self-center lg:min-h-9"
            disabled={props.inventoryLoading}
            onClick={() => props.onRetryInventory?.()}
          >
            {props.inventoryLoading ? 'Retrying...' : 'Retry'}
          </Button>
        </Show>
      </div>
    </Show>
  );

  return (
    <div ref={layoutContainerRef} class="min-w-0">
      <SettingsPanel
        title="Connected systems"
        noPadding
        action={
          !props.readOnly && props.onAddInfrastructure ? (
            <Button
              type="button"
              variant="primary"
              size="mdCompact"
              class="min-h-11 w-full gap-2 sm:w-auto lg:min-h-9"
              onClick={props.onAddInfrastructure}
            >
              <Plus class="h-4 w-4" />
              Add infrastructure
            </Button>
          ) : undefined
        }
      >
        {inventoryReadNotice()}
        <Show when={!inventoryReadUncertain()}>{setupSummaryBand()}</Show>

        <Show when={!useCardLayout() && (hasAnyConfigured() || !inventoryReadUncertain())}>
          <Table class="w-full min-w-[820px] table-fixed text-sm">
            <TableHeader class="">
              <TableRow>
                <TableHead class="w-[29%] py-1.5 pl-3 pr-3 text-left text-[11px] font-medium text-muted whitespace-nowrap">
                  System
                </TableHead>
                <TableHead class="w-[29%] px-3 py-1.5 text-left text-[11px] font-medium text-muted whitespace-nowrap">
                  Coverage
                </TableHead>
                <TableHead class="w-[27%] px-3 py-1.5 text-left text-[11px] font-medium text-muted whitespace-nowrap">
                  Health
                </TableHead>
                <Show when={actionColumnVisible()}>
                  <TableHead
                    class={`${actionColumnShowsInstall() ? 'w-48' : 'w-28'} px-3 py-1.5 text-right text-[11px] font-medium text-muted whitespace-nowrap`}
                  >
                    Actions
                  </TableHead>
                </Show>
              </TableRow>
            </TableHeader>

            <TableBody class="bg-surface">
              <For each={sortedProducts()}>
                {(product) => {
                  const configuredRows = () => groupedConfiguredRows().get(product.type) ?? [];
                  const configuredGroups = () =>
                    configuredSourceGroupsForProduct(product, configuredRows());
                  const discoveredRows = () => groupedDiscoveredRows().get(product.type) ?? [];
                  const visibleConfiguredGroups = () =>
                    visibleSourceGroupsForProduct(
                      product,
                      configuredGroups(),
                      discoveredRows().length > 0,
                    );
                  const groupRowClass = () =>
                    getGroupedTableRowClass('border-b border-border-subtle');

                  return (
                    <>
                      <For each={visibleConfiguredGroups()}>
                        {(group) => (
                          <>
                            <Show
                              when={actionColumnVisible()}
                              fallback={
                                <TableRow class={groupRowClass()}>
                                  <TableCell colspan={3} class={getGroupedTableRowCellClass()}>
                                    <div class="flex min-w-0 items-center gap-2">
                                      <span>{group.label}</span>
                                    </div>
                                  </TableCell>
                                </TableRow>
                              }
                            >
                              <TableRow class={groupRowClass()}>
                                <TableCell colspan={4} class={getGroupedTableRowCellClass()}>
                                  <div class="flex items-center justify-between gap-2 whitespace-nowrap">
                                    <span>{group.label}</span>
                                    <Show
                                      when={
                                        !props.readOnly &&
                                        Boolean(props.onAddSource || props.onAddSourceStep)
                                      }
                                    >
                                      <button
                                        type="button"
                                        onClick={() => handleGroupAddSource(group)}
                                        class={`${addSectionButtonClass} whitespace-nowrap`}
                                        aria-label={`Add ${group.label}`}
                                        title={group.actionLabel}
                                      >
                                        <Plus class="h-3.5 w-3.5" />
                                        Add
                                      </button>
                                    </Show>
                                  </div>
                                </TableCell>
                              </TableRow>
                            </Show>

                            <Show when={group.rows.length > 0}>
                              <For each={group.rows}>
                                {(row) => (
                                  <>
                                    <TableRow
                                      class={`border-b border-border-subtle ${
                                        row.isCluster ? '' : ''
                                      }`}
                                    >
                                      <TableCell class="py-1 pl-3 pr-3 align-middle">
                                        <div class="flex min-w-0 items-center gap-1.5">
                                          <Show
                                            when={infrastructureRowMonitoringPath(row)}
                                            fallback={
                                              <div
                                                class={`min-w-0 truncate text-[13px] ${
                                                  row.isCluster
                                                    ? 'font-medium text-base-content'
                                                    : ''
                                                }`}
                                                title={rowSystemTitle(row)}
                                              >
                                                {row.name}
                                              </div>
                                            }
                                          >
                                            {(path) => (
                                              <a
                                                href={path()}
                                                class={`${MONITORING_LINK_CLASS} min-w-0 truncate text-[13px] ${
                                                  row.isCluster ? 'font-medium' : ''
                                                }`}
                                                title={rowSystemTitle(row)}
                                              >
                                                {row.name}
                                              </a>
                                            )}
                                          </Show>
                                          {(() => {
                                            const presentation = infrastructureSourcePresentation(
                                              row.source,
                                            );
                                            const title =
                                              agentMethodTitleFor(row) ?? presentation.title;
                                            return (
                                              <span
                                                class={`${presentation.badgeClassName} shrink-0 whitespace-nowrap`}
                                                title={title}
                                              >
                                                {presentation.label}
                                              </span>
                                            );
                                          })()}
                                          <Show when={row.members.length > 0}>
                                            <button
                                              type="button"
                                              class="inline-flex shrink-0 items-center gap-0.5 whitespace-nowrap rounded-sm px-1 py-0.5 text-[11px] font-medium text-muted transition-colors hover:bg-surface-alt hover:text-base-content"
                                              aria-expanded={membersExpanded(row)}
                                              aria-label={`${membersExpanded(row) ? 'Hide' : 'Show'} ${formatCount(row.members.length, row.ownerType === 'vmware' ? 'host' : 'node')} for ${row.name}`}
                                              onClick={() => toggleMembers(row)}
                                            >
                                              <Show
                                                when={membersExpanded(row)}
                                                fallback={<ChevronRight class="h-3.5 w-3.5" />}
                                              >
                                                <ChevronDown class="h-3.5 w-3.5" />
                                              </Show>
                                              {formatCount(
                                                row.members.length,
                                                row.ownerType === 'vmware' ? 'host' : 'node',
                                              )}
                                            </button>
                                          </Show>
                                        </div>
                                      </TableCell>

                                      <TableCell class="px-3 py-1 align-middle">
                                        <Show
                                          when={row.coverageLabels.length > 0}
                                          fallback={
                                            <span class="text-xs text-muted" aria-hidden="true">
                                              —
                                            </span>
                                          }
                                        >
                                          <div
                                            class="whitespace-normal text-[12px] leading-4 text-muted"
                                            title={row.coverageLabels.join(', ')}
                                          >
                                            {row.coverageLabels.join(', ')}
                                          </div>
                                        </Show>
                                        <Show when={rowNeedsAgentCoverage(row)}>
                                          <div class="mt-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300">
                                            {missingAgentCoverageLabel(row)}
                                          </div>
                                        </Show>
                                      </TableCell>

                                      <TableCell class="px-3 py-1 align-middle">
                                        <div class="flex items-center gap-1.5 overflow-hidden whitespace-nowrap">
                                          <span
                                            class={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium whitespace-nowrap ${row.statusClassName}`}
                                          >
                                            {row.statusLabel}
                                          </span>
                                          <Show when={row.agentUpdateCount > 0}>
                                            <Show
                                              when={!props.readOnly && props.onOpenAgentDoctor}
                                              fallback={
                                                <span class="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium whitespace-nowrap text-amber-800 dark:bg-amber-900/25 dark:text-amber-200">
                                                  {row.agentUpdateCount === 1
                                                    ? 'Agent update'
                                                    : `${row.agentUpdateCount} updates`}
                                                </span>
                                              }
                                            >
                                              <button
                                                type="button"
                                                class="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium whitespace-nowrap text-amber-800 transition-colors hover:bg-amber-200 dark:bg-amber-900/25 dark:text-amber-200 dark:hover:bg-amber-800"
                                                onClick={() =>
                                                  props.onOpenAgentDoctor?.(
                                                    agentConnectionIDsForInfrastructureRow(
                                                      row,
                                                      true,
                                                    ),
                                                  )
                                                }
                                                aria-label={`${row.agentUpdateCount === 1 ? 'Agent update' : `${row.agentUpdateCount} updates`}: open Agent Doctor for ${row.name}`}
                                              >
                                                {row.agentUpdateCount === 1
                                                  ? 'Agent update'
                                                  : `${row.agentUpdateCount} updates`}
                                              </button>
                                            </Show>
                                          </Show>
                                          <span
                                            class="truncate text-[12px]"
                                            title={
                                              row.isCluster
                                                ? 'Oldest activity across cluster API and member agents'
                                                : undefined
                                            }
                                          >
                                            {row.lastActivityText}
                                          </span>
                                        </div>
                                      </TableCell>

                                      <Show when={actionColumnVisible()}>
                                        <TableCell class="px-3 py-1 align-middle text-right">
                                          <Show
                                            when={rowInteractive(row)}
                                            fallback={
                                              <span class="text-xs text-muted">Read only</span>
                                            }
                                          >
                                            <div class="-my-0.5 flex items-center justify-end gap-1.5">
                                              <Show
                                                when={
                                                  rowNeedsAgentCoverage(row) &&
                                                  Boolean(
                                                    props.onAddSourceStep || props.onAddSource,
                                                  )
                                                }
                                              >
                                                <Button
                                                  type="button"
                                                  variant="outline"
                                                  size="xs"
                                                  class="gap-1.5"
                                                  onClick={() => handleInstallAgent(row)}
                                                  aria-label={installAgentActionLabel(row)}
                                                  title={
                                                    row.isCluster
                                                      ? canInstallFromCluster(row)
                                                        ? 'Install Pulse Agent on the uncovered nodes from a node that already runs it.'
                                                        : 'Generate an installer command to run once on each uncovered Proxmox node.'
                                                      : 'Install Pulse Agent on this system to add node-local telemetry (temperatures, SMART, host identity).'
                                                  }
                                                >
                                                  <Cpu class="h-3.5 w-3.5" />
                                                  {row.isCluster
                                                    ? 'Install node agents'
                                                    : 'Install agent'}
                                                </Button>
                                              </Show>
                                              <Button
                                                type="button"
                                                variant="outline"
                                                size="xs"
                                                class="min-w-18"
                                                onClick={() => props.onOpenConnection?.(row)}
                                                data-infrastructure-manage-id={row.id}
                                              >
                                                Manage
                                              </Button>
                                            </div>
                                          </Show>
                                        </TableCell>
                                      </Show>
                                    </TableRow>

                                    <Show when={row.problem || row.lastErrorMessage}>
                                      <TableRow class="border-b border-border-subtle">
                                        <TableCell
                                          colspan={actionColumnVisible() ? 4 : 3}
                                          class="bg-surface px-3 pb-1.5 pt-0"
                                        >
                                          <Show when={row.problem}>
                                            {(problem) => (
                                              <div
                                                class={`text-[11px] italic ${
                                                  problem().tone === 'critical'
                                                    ? 'text-rose-700 dark:text-rose-300'
                                                    : 'text-amber-700 dark:text-amber-300'
                                                }`}
                                                title={problem().detail}
                                              >
                                                {problem().label}
                                              </div>
                                            )}
                                          </Show>
                                          <Show when={row.lastErrorMessage}>
                                            <div
                                              role="alert"
                                              class={`mt-1 ${rowErrorBannerClass(row)}`}
                                            >
                                              {row.lastErrorMessage}
                                            </div>
                                          </Show>
                                        </TableCell>
                                      </TableRow>
                                    </Show>

                                    <Show when={row.members.length > 0 && membersExpanded(row)}>
                                      <For each={row.members}>
                                        {(member, memberIndex) => {
                                          const memberPresentation =
                                            memberMethodPresentation(member);
                                          const memberSourceTitle = memberPresentation
                                            ? (memberMethodTitleFor(row, memberIndex()) ??
                                              memberPresentation.title)
                                            : MEMBER_SHARED_API_TITLE;
                                          return (
                                            <>
                                              <TableRow class="border-b border-border-subtle">
                                                <TableCell class="py-1 pl-3 pr-3 align-middle">
                                                  <div class="min-w-0 pl-4">
                                                    <div class="flex min-w-0 items-center gap-1.5">
                                                      <span class="h-1.5 w-1.5 shrink-0 rounded-full bg-border" />
                                                      <div
                                                        class="truncate text-[13px]"
                                                        title={memberSystemTitle(member)}
                                                      >
                                                        {member.name}
                                                      </div>
                                                      <Show when={memberPresentation}>
                                                        {(presentation) => (
                                                          <span
                                                            class={`${presentation().badgeClassName} shrink-0 whitespace-nowrap`}
                                                            title={memberSourceTitle}
                                                          >
                                                            {presentation().label}
                                                          </span>
                                                        )}
                                                      </Show>
                                                    </div>
                                                    <Show when={member.host}>
                                                      <div
                                                        class="mt-0.5 truncate pl-3.5 text-[11px] text-muted"
                                                        title={member.host}
                                                      >
                                                        {member.host}
                                                      </div>
                                                    </Show>
                                                  </div>
                                                </TableCell>

                                                <TableCell class="px-3 py-1 align-middle">
                                                  <Show
                                                    when={member.coverageLabels.length > 0}
                                                    fallback={
                                                      <span
                                                        class="text-xs text-muted"
                                                        aria-hidden="true"
                                                      >
                                                        —
                                                      </span>
                                                    }
                                                  >
                                                    <div
                                                      class="whitespace-normal text-[12px] leading-4 text-muted"
                                                      title={member.coverageLabels.join(', ')}
                                                    >
                                                      {member.coverageLabels.join(', ')}
                                                    </div>
                                                  </Show>
                                                </TableCell>

                                                <TableCell class="px-3 py-1 align-middle">
                                                  <div class="flex items-center gap-1.5 overflow-hidden whitespace-nowrap">
                                                    <span
                                                      class={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium whitespace-nowrap ${member.statusClassName}`}
                                                    >
                                                      {member.statusLabel}
                                                    </span>
                                                    <span class="truncate text-[12px]">
                                                      {member.lastActivityText}
                                                    </span>
                                                  </div>
                                                </TableCell>

                                                <Show when={actionColumnVisible()}>
                                                  <TableCell class="px-3 py-1 align-middle text-right">
                                                    <Show
                                                      when={
                                                        row.ownerType === 'pve' &&
                                                        !memberHasAgentCoverage(member) &&
                                                        Boolean(
                                                          props.onAddSourceStep ||
                                                          props.onAddSource,
                                                        )
                                                      }
                                                      fallback={
                                                        <span
                                                          class="text-xs text-muted"
                                                          aria-hidden="true"
                                                        >
                                                          —
                                                        </span>
                                                      }
                                                    >
                                                      <Button
                                                        type="button"
                                                        variant="outline"
                                                        size="xs"
                                                        class="gap-1.5"
                                                        onClick={() =>
                                                          handleInstallAgent(row, member)
                                                        }
                                                        aria-label={`Install agent on ${member.name}`}
                                                        title={
                                                          canInstallFromCluster(row)
                                                            ? `Install Pulse Agent on ${member.name} from a node that already runs it.`
                                                            : `Generate an installer command to run on ${member.name}.`
                                                        }
                                                      >
                                                        <Cpu class="h-3.5 w-3.5" />
                                                        Install agent
                                                      </Button>
                                                    </Show>
                                                  </TableCell>
                                                </Show>
                                              </TableRow>

                                              <Show when={member.problem}>
                                                {(problem) => (
                                                  <TableRow class="border-b border-border-subtle">
                                                    <TableCell
                                                      colspan={actionColumnVisible() ? 4 : 3}
                                                      class="pb-1.5 pl-9 pr-3 pt-0"
                                                    >
                                                      <div
                                                        class={`text-[11px] italic ${
                                                          problem().tone === 'critical'
                                                            ? 'text-rose-700 dark:text-rose-300'
                                                            : 'text-amber-700 dark:text-amber-300'
                                                        }`}
                                                        title={problem().detail}
                                                      >
                                                        {problem().label}
                                                      </div>
                                                    </TableCell>
                                                  </TableRow>
                                                )}
                                              </Show>
                                            </>
                                          );
                                        }}
                                      </For>
                                    </Show>
                                  </>
                                )}
                              </For>
                            </Show>

                            <Show when={group.id === product.type && discoveredRows().length > 0}>
                              <For each={discoveredRows()}>
                                {(server) => {
                                  return (
                                    <TableRow class={discoveryRowClass}>
                                      <TableCell class="py-1 pl-3 pr-3 align-middle">
                                        <div class="min-w-0">
                                          <div class="flex items-center gap-1.5">
                                            <div
                                              class="truncate text-[13px]"
                                              title={`${discoveredServerName(server)}${server.version ? ` · ${server.version}` : ''}`}
                                            >
                                              {discoveredServerName(server)}
                                            </div>
                                            <span
                                              class="inline-flex shrink-0 items-center rounded-full border border-dashed border-border bg-surface-alt px-2 py-0.5 text-[11px] font-medium text-muted whitespace-nowrap"
                                              title="Discovery candidate — review to attach a source"
                                            >
                                              Candidate
                                            </span>
                                          </div>
                                          <div
                                            class="mt-0.5 truncate text-[11px] text-muted"
                                            title={discoveredServerEndpoint(server)}
                                          >
                                            {discoveredServerEndpoint(server)}
                                          </div>
                                        </div>
                                      </TableCell>

                                      <TableCell class="px-3 py-1 align-middle">
                                        <div
                                          class="whitespace-normal text-[12px] leading-4 text-muted"
                                          title={discoveredCoverageText(server)}
                                        >
                                          {discoveredCoverageText(server)}
                                        </div>
                                      </TableCell>

                                      <TableCell class="px-3 py-1 align-middle">
                                        <div class="flex items-center gap-1.5 overflow-hidden whitespace-nowrap">
                                          <span class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-medium whitespace-nowrap text-blue-800 dark:bg-blue-950/40 dark:text-blue-200">
                                            Discovered
                                          </span>
                                          <span class="truncate text-[12px]">
                                            {lastDiscoveryResultText() ?? 'Waiting for scan'}
                                          </span>
                                        </div>
                                      </TableCell>

                                      <Show when={actionColumnVisible()}>
                                        <TableCell class="px-3 py-1 align-middle text-right">
                                          <Show
                                            when={props.onReviewDiscoveredSource}
                                            fallback={
                                              <span class="text-xs text-muted">Read only</span>
                                            }
                                          >
                                            <Button
                                              type="button"
                                              variant="outline"
                                              size="xs"
                                              class="min-w-18"
                                              onClick={() =>
                                                props.onReviewDiscoveredSource?.(server)
                                              }
                                            >
                                              Review
                                            </Button>
                                          </Show>
                                        </TableCell>
                                      </Show>
                                    </TableRow>
                                  );
                                }}
                              </For>
                            </Show>
                          </>
                        )}
                      </For>
                    </>
                  );
                }}
              </For>

              <Show when={!hasAnyConfigured() && !hasAnyDiscovered()}>
                <TableRow>
                  <TableCell
                    colspan={actionColumnVisible() ? 4 : 3}
                    class="px-4 py-8 text-center text-sm text-muted"
                  >
                    {emptyStateContent()}
                  </TableCell>
                </TableRow>
              </Show>
            </TableBody>
          </Table>
        </Show>

        <Show when={useCardLayout() && (hasAnyConfigured() || !inventoryReadUncertain())}>
          <div class="space-y-3 p-3">
            <For each={sortedProducts()}>
              {(product) => {
                const configuredRows = () => groupedConfiguredRows().get(product.type) ?? [];
                const configuredGroups = () =>
                  configuredSourceGroupsForProduct(product, configuredRows());
                const discoveredRows = () => groupedDiscoveredRows().get(product.type) ?? [];
                const visibleConfiguredGroups = () =>
                  visibleSourceGroupsForProduct(
                    product,
                    configuredGroups(),
                    discoveredRows().length > 0,
                  );

                return (
                  <For each={visibleConfiguredGroups()}>
                    {(group) => (
                      <section class="space-y-2">
                        <header class="flex items-center justify-between gap-2">
                          <h3 class="text-[14px] font-semibold text-base-content">{group.label}</h3>
                          <Show
                            when={
                              !props.readOnly && Boolean(props.onAddSource || props.onAddSourceStep)
                            }
                          >
                            <button
                              type="button"
                              onClick={() => handleGroupAddSource(group)}
                              class={`${addSectionButtonClass} whitespace-nowrap`}
                              aria-label={`Add ${group.label}`}
                              title={group.actionLabel}
                            >
                              <Plus class="h-3.5 w-3.5" />
                              Add
                            </button>
                          </Show>
                        </header>

                        <For each={group.rows}>
                          {(row) => {
                            const presentation = infrastructureSourcePresentation(row.source);
                            const sourceTitle = agentMethodTitleFor(row) ?? presentation.title;
                            return (
                              <article class="rounded-md border border-border-subtle bg-surface p-3 shadow-xs">
                                <header class="flex items-start justify-between gap-2">
                                  <div class="min-w-0 flex-1">
                                    <Show
                                      when={infrastructureRowMonitoringPath(row)}
                                      fallback={
                                        <div
                                          class="wrap-break-word text-[13px] font-medium text-base-content"
                                          title={row.name}
                                        >
                                          {row.name}
                                        </div>
                                      }
                                    >
                                      {(path) => (
                                        <a
                                          href={path()}
                                          class={`${MONITORING_LINK_CLASS} block wrap-break-word text-[13px] font-medium`}
                                          title={row.name}
                                        >
                                          {row.name}
                                        </a>
                                      )}
                                    </Show>
                                    <Show when={row.isCluster && row.subtitle}>
                                      <div class="mt-0.5 text-[11px] text-muted">
                                        {row.subtitle}
                                      </div>
                                    </Show>
                                    <Show when={!row.isCluster && row.identitySubtitle}>
                                      <div class="mt-0.5 text-[11px] text-muted">
                                        {row.identitySubtitle}
                                      </div>
                                    </Show>
                                    <Show when={row.members.length > 0}>
                                      <button
                                        type="button"
                                        class="mt-1 inline-flex min-h-11 items-center gap-0.5 rounded-sm px-1 py-0.5 text-[11px] font-medium text-muted transition-colors hover:bg-surface-alt hover:text-base-content lg:min-h-0"
                                        aria-expanded={membersExpanded(row)}
                                        aria-label={`${membersExpanded(row) ? 'Hide' : 'Show'} ${formatCount(row.members.length, row.ownerType === 'vmware' ? 'host' : 'node')} for ${row.name}`}
                                        onClick={() => toggleMembers(row)}
                                      >
                                        <Show
                                          when={membersExpanded(row)}
                                          fallback={<ChevronRight class="h-3.5 w-3.5" />}
                                        >
                                          <ChevronDown class="h-3.5 w-3.5" />
                                        </Show>
                                        {formatCount(
                                          row.members.length,
                                          row.ownerType === 'vmware' ? 'host' : 'node',
                                        )}
                                      </button>
                                    </Show>
                                  </div>
                                  <span
                                    class={`${presentation.badgeClassName} shrink-0`}
                                    title={sourceTitle}
                                  >
                                    {presentation.label}
                                  </span>
                                </header>

                                <Show when={row.coverageLabels.length > 0}>
                                  <div class="mt-1 text-[12px] leading-4 text-muted">
                                    {row.coverageLabels.join(', ')}
                                  </div>
                                </Show>
                                <Show when={rowNeedsAgentCoverage(row)}>
                                  <div class="mt-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300">
                                    {missingAgentCoverageLabel(row)}
                                  </div>
                                </Show>

                                <Show when={row.members.length > 0 && membersExpanded(row)}>
                                  <div class="mt-3 border-t border-border-subtle pt-2">
                                    <div class="text-[11px] font-medium uppercase tracking-[0.08em] text-muted">
                                      Cluster nodes
                                    </div>
                                    <div class="mt-2 space-y-2">
                                      <For each={row.members}>
                                        {(member, memberIndex) => {
                                          const memberPresentation =
                                            memberMethodPresentation(member);
                                          const memberSourceTitle = memberPresentation
                                            ? (memberMethodTitleFor(row, memberIndex()) ??
                                              memberPresentation.title)
                                            : MEMBER_SHARED_API_TITLE;
                                          return (
                                            <div class="rounded-md border border-border-subtle px-2.5 py-2">
                                              <div class="flex items-start justify-between gap-2">
                                                <div class="min-w-0 flex-1">
                                                  <div
                                                    class="wrap-break-word text-[13px] font-medium text-base-content"
                                                    title={member.name}
                                                  >
                                                    {member.name}
                                                  </div>
                                                  <div class="mt-0.5 text-[11px] text-muted">
                                                    {member.subtitle}
                                                  </div>
                                                </div>
                                                <Show when={memberPresentation}>
                                                  {(presentation) => (
                                                    <span
                                                      class={`${presentation().badgeClassName} shrink-0`}
                                                      title={memberSourceTitle}
                                                    >
                                                      {presentation().label}
                                                    </span>
                                                  )}
                                                </Show>
                                              </div>

                                              <Show when={member.host}>
                                                <div
                                                  class="mt-1 truncate text-[12px] text-muted"
                                                  title={member.host}
                                                >
                                                  {member.host}
                                                </div>
                                              </Show>

                                              <Show when={member.coverageLabels.length > 0}>
                                                <div class="mt-1 text-[12px] leading-4 text-muted">
                                                  {member.coverageLabels.join(', ')}
                                                </div>
                                              </Show>

                                              <div class="mt-2 flex flex-wrap items-center gap-1.5">
                                                <span
                                                  class={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium whitespace-nowrap ${member.statusClassName}`}
                                                >
                                                  {member.statusLabel}
                                                </span>
                                                <span class="text-[12px]">
                                                  {member.lastActivityText}
                                                </span>
                                              </div>
                                              <Show
                                                when={
                                                  !props.readOnly &&
                                                  row.ownerType === 'pve' &&
                                                  !memberHasAgentCoverage(member) &&
                                                  Boolean(
                                                    props.onAddSourceStep || props.onAddSource,
                                                  )
                                                }
                                              >
                                                <Button
                                                  type="button"
                                                  variant="outline"
                                                  size="xs"
                                                  class="mt-2 min-h-11 gap-1.5 lg:min-h-0"
                                                  onClick={() => handleInstallAgent(row, member)}
                                                  aria-label={`Install agent on ${member.name}`}
                                                  title={
                                                    canInstallFromCluster(row)
                                                      ? `Install Pulse Agent on ${member.name} from a node that already runs it.`
                                                      : `Generate an installer command to run on ${member.name}.`
                                                  }
                                                >
                                                  <Cpu class="h-3.5 w-3.5" />
                                                  Install agent
                                                </Button>
                                              </Show>
                                              <Show when={member.problem}>
                                                {(problem) => (
                                                  <div
                                                    class={`mt-1 text-[11px] italic ${
                                                      problem().tone === 'critical'
                                                        ? 'text-rose-700 dark:text-rose-300'
                                                        : 'text-amber-700 dark:text-amber-300'
                                                    }`}
                                                    title={problem().detail}
                                                  >
                                                    {problem().label}
                                                  </div>
                                                )}
                                              </Show>
                                            </div>
                                          );
                                        }}
                                      </For>
                                    </div>
                                  </div>
                                </Show>

                                <footer class="mt-2 border-t border-border-subtle pt-2">
                                  <div class="flex items-center justify-between gap-2">
                                    <div class="flex flex-wrap items-center gap-1.5">
                                      <span
                                        class={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium whitespace-nowrap ${row.statusClassName}`}
                                      >
                                        {row.statusLabel}
                                      </span>
                                      <Show when={row.agentUpdateCount > 0}>
                                        <Show
                                          when={!props.readOnly && props.onOpenAgentDoctor}
                                          fallback={
                                            <span class="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium text-amber-800 dark:bg-amber-900/25 dark:text-amber-200">
                                              {row.agentUpdateCount === 1
                                                ? 'Agent update'
                                                : `${row.agentUpdateCount} agent updates`}
                                            </span>
                                          }
                                        >
                                          <button
                                            type="button"
                                            class="inline-flex min-h-11 items-center rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium text-amber-800 transition-colors hover:bg-amber-200 lg:min-h-0 dark:bg-amber-900/25 dark:text-amber-200 dark:hover:bg-amber-800"
                                            onClick={() =>
                                              props.onOpenAgentDoctor?.(
                                                agentConnectionIDsForInfrastructureRow(row, true),
                                              )
                                            }
                                            aria-label={`${row.agentUpdateCount === 1 ? 'Agent update' : `${row.agentUpdateCount} agent updates`}: open Agent Doctor for ${row.name}`}
                                          >
                                            {row.agentUpdateCount === 1
                                              ? 'Agent update'
                                              : `${row.agentUpdateCount} agent updates`}
                                          </button>
                                        </Show>
                                      </Show>
                                      <span
                                        class="text-[12px]"
                                        title={
                                          row.isCluster
                                            ? 'Oldest activity across cluster API and member agents'
                                            : undefined
                                        }
                                      >
                                        {row.lastActivityText}
                                      </span>
                                    </div>
                                    <Show when={!props.readOnly && rowInteractive(row)}>
                                      <div class="flex flex-wrap justify-end gap-1.5">
                                        <Show
                                          when={
                                            rowNeedsAgentCoverage(row) &&
                                            Boolean(props.onAddSourceStep || props.onAddSource)
                                          }
                                        >
                                          <Button
                                            type="button"
                                            variant="outline"
                                            size="xs"
                                            class="min-h-11 gap-1.5 lg:min-h-0"
                                            onClick={() => handleInstallAgent(row)}
                                            aria-label={installAgentActionLabel(row)}
                                            title={
                                              row.isCluster
                                                ? canInstallFromCluster(row)
                                                  ? 'Install Pulse Agent on the uncovered nodes from a node that already runs it.'
                                                  : 'Generate an installer command to run once on each uncovered Proxmox node.'
                                                : 'Install Pulse Agent on this system to add node-local telemetry (temperatures, SMART, host identity).'
                                            }
                                          >
                                            <Cpu class="h-3.5 w-3.5" />
                                            {row.isCluster
                                              ? 'Install node agents'
                                              : 'Install agent'}
                                          </Button>
                                        </Show>
                                        <Button
                                          type="button"
                                          variant="outline"
                                          size="xs"
                                          class="min-h-11 min-w-18 shrink-0 lg:min-h-0"
                                          onClick={() => props.onOpenConnection?.(row)}
                                          data-infrastructure-manage-id={row.id}
                                        >
                                          Manage
                                        </Button>
                                      </div>
                                    </Show>
                                  </div>
                                  <Show when={row.problem}>
                                    {(problem) => (
                                      <div
                                        class={`mt-1 text-[11px] italic ${
                                          problem().tone === 'critical'
                                            ? 'text-rose-700 dark:text-rose-300'
                                            : 'text-amber-700 dark:text-amber-300'
                                        }`}
                                        title={problem().detail}
                                      >
                                        {problem().label}
                                      </div>
                                    )}
                                  </Show>
                                </footer>

                                <Show when={row.lastErrorMessage}>
                                  <div role="alert" class={`mt-2 ${rowErrorBannerClass(row)}`}>
                                    {row.lastErrorMessage}
                                  </div>
                                </Show>
                              </article>
                            );
                          }}
                        </For>

                        <Show when={group.id === product.type && discoveredRows().length > 0}>
                          <For each={discoveredRows()}>
                            {(server) => (
                              <article class="rounded-md border border-blue-200 bg-blue-50/50 p-3 shadow-xs dark:border-blue-900/25 dark:bg-blue-950/20">
                                <header class="flex items-start justify-between gap-2">
                                  <div
                                    class="min-w-0 flex-1 wrap-break-word text-[13px] font-medium text-base-content"
                                    title={`${discoveredServerName(server)}${server.version ? ` · ${server.version}` : ''}`}
                                  >
                                    {discoveredServerName(server)}
                                  </div>
                                  <span
                                    class="inline-flex shrink-0 items-center rounded-full border border-dashed border-border bg-surface-alt px-2 py-0.5 text-[11px] font-medium text-muted whitespace-nowrap"
                                    title="Discovery candidate — review to attach a source"
                                  >
                                    Candidate
                                  </span>
                                </header>

                                <div
                                  class="mt-1 truncate text-[12px] text-muted"
                                  title={discoveredServerEndpoint(server)}
                                >
                                  {discoveredServerEndpoint(server)}
                                </div>

                                <div class="mt-1 text-[12px] leading-4 text-muted">
                                  {discoveredCoverageText(server)}
                                </div>

                                <footer class="mt-2 flex items-center justify-between gap-2 border-t border-border-subtle pt-2">
                                  <div class="flex flex-wrap items-center gap-1.5">
                                    <span class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-medium text-blue-800 dark:bg-blue-950/40 dark:text-blue-200">
                                      Discovered
                                    </span>
                                    <span class="text-[12px]">
                                      {lastDiscoveryResultText() ?? 'Waiting for scan'}
                                    </span>
                                  </div>
                                  <Show when={!props.readOnly && props.onReviewDiscoveredSource}>
                                    <Button
                                      type="button"
                                      variant="outline"
                                      size="xs"
                                      class="min-h-11 min-w-18 shrink-0 lg:min-h-0"
                                      onClick={() => props.onReviewDiscoveredSource?.(server)}
                                    >
                                      Review
                                    </Button>
                                  </Show>
                                </footer>
                              </article>
                            )}
                          </For>
                        </Show>
                      </section>
                    )}
                  </For>
                );
              }}
            </For>

            <Show when={!hasAnyConfigured() && !hasAnyDiscovered()}>
              <div class="rounded-md border border-dashed border-border px-3 py-6 text-center text-sm text-muted">
                {emptyStateContent()}
              </div>
            </Show>
          </div>
        </Show>
        <Show when={!inventoryReadUncertain()}>{discoveryMonitorBand()}</Show>
        {/* Keyed so the dialog gets plain values: an install it started keeps
            running after close, and must not read a stale <Show> accessor. */}
        <Show when={clusterDeploy()} keyed>
          {(target) => (
            <ClusterAgentDeployDialog
              isOpen={true}
              clusterName={target.clusterName}
              preselectNodeName={target.nodeName}
              onClose={() => setClusterDeploy(null)}
              onUseInstaller={handleInstallAgentShortcut}
            />
          )}
        </Show>
      </SettingsPanel>
    </div>
  );
};

export default InfrastructureSourceManager;