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.

27.9 KB
Raw Blame
import { useLocation } from '@solidjs/router';
import { Show, createEffect, createMemo, createSignal, type Accessor } from 'solid-js';
import StorageSurface from '@/components/Storage/Storage';
import { WorkloadsFilter } from '@/components/Workloads/WorkloadsFilter';
import { WorkloadsSurface } from '@/components/Workloads/WorkloadsSurface';
import { useWorkloadsState } from '@/components/Workloads/useWorkloadsState';
import { workloadNodeScopeId } from '@/components/Workloads/workloadTopology';
import { nodeFromResource } from '@/utils/resourceStateAdapters';
import {
  PlatformHostScopedTableTitle,
  createPlatformHostScopeFocus,
} from '@/features/platformPage/PlatformHostScope';
import {
  DEFAULT_WORKLOADS_METRIC_DISPLAY_MODE,
  getWorkloadsMetricFilterProps,
  type WorkloadsStatusOption,
  type WorkloadsMemoryDisplayBasis,
  type WorkloadsMetricDisplayMode,
} from '@/components/Workloads/workloadsFilterModel';
import {
  WORKLOAD_TABLE_HISTORY_DEFAULT_RANGE,
  isWorkloadTableMetricHistoryRange,
  type WorkloadTableMetricHistoryRange,
} from '@/components/Workloads/workloadMetricHistoryModel';
import {
  buildInfrastructureAgentUpdatesPath,
  buildInfrastructureWorkspacePath,
} from '@/components/Settings/infrastructureWorkspaceModel';
import {
  collectOutdatedAgentHosts,
  formatAgentVersionDisplay,
} from '@/features/platformPage/agentVersion';
import { getPlatformIcon } from '@/features/platformPage/platformIcon';
import { PlatformOutdatedAgentNotice } from '@/features/platformPage/PlatformOutdatedAgentNotice';
import { PlatformOutdatedSensorSetupNotice } from '@/features/platformPage/PlatformOutdatedSensorSetupNotice';
import {
  PLATFORM_ESTATE_COUNTS_STORAGE_KEY,
  buildProxmoxEstateTopology,
  deserializePlatformEstateCountsVisibility,
} from '@/features/platformPage/platformEstateOverviewModel';
import { collectOutdatedSensorSetupNodes } from '@/features/platformPage/sensorSetup';
import { usePersistentSignal } from '@/hooks/usePersistentSignal';
import { useObservedElementWidth } from '@/hooks/useObservedElementWidth';
import { STORAGE_KEYS } from '@/utils/localStorage';
import {
  PlatformErrorState,
  PlatformSectionTabs,
  PlatformTableEmptyState,
  PlatformTableLoadingState,
} from '@/features/platformPage/sharedPlatformPage';
import { ProxmoxBackupsTable } from './ProxmoxBackupsTable';
import { ProxmoxBackupJobsSection } from './ProxmoxBackupJobsCard';
import { ProxmoxCephTable } from './ProxmoxCephTable';
import { ProxmoxMailGatewayTable } from './ProxmoxMailGatewayTable';
import { ProxmoxNodesTable } from './ProxmoxNodesTable';
import { ProxmoxReplicationTable, fetchReplicationJobs } from './ProxmoxReplicationTable';
import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
import { getAPIReadAccessErrorMessage } from '@/utils/apiAccessError';
import { useUnifiedResources } from '@/hooks/useUnifiedResources';
import { useWebSocket } from '@/contexts/appRuntime';
import { useAlertsActivation } from '@/stores/alertsActivation';
import { getAlertsForResource } from '@/utils/alerts';
import type { ReplicationJob } from '@/types/api';
import type { Resource } from '@/types/resource';
import { updateStore } from '@/stores/updates';
import {
  PROXMOX_TAB_SPECS,
  buildProxmoxPageModel,
  buildVisibleProxmoxTabSpecsFromCounts,
  type ProxmoxPageModel,
  type ProxmoxPageTabId,
} from './proxmoxPageModel';

// Each workflow hydrates only the source-scoped resource families it consumes.
// Backups reuse the Overview guest snapshot and add PBS servers and standalone
// host telemetry, without downloading the same large guest inventory twice.
const PROXMOX_RESOURCE_QUERY_BY_TAB: Record<ProxmoxPageTabId, string> = {
  overview: 'type=agent,vm,system-container,oci-container&source=proxmox',
  storage: 'type=agent,pbs,storage,physical_disk,ceph&source=proxmox,pbs,agent',
  replication: 'type=agent&source=proxmox',
  backups: 'type=pbs,agent&source=pbs',
  ceph: 'type=ceph&source=proxmox',
  mail: 'type=pmg&source=pmg',
};

const PROXMOX_PLATFORM_FILTER = 'proxmox-all';
const PROXMOX_WORKLOAD_STATUS_STORAGE_SCOPE = 'proxmox';
const PROXMOX_WORKLOAD_EXCLUDED_TYPES = ['app-container'] as const;
const PHONE_MOUNTED_TAB_LIMIT = 2;
const REPLICATION_JOBS_POLL_MS = 30_000;
const NO_REPLICATION_JOBS: ReplicationJob[] = [];
const VALID_TABS = new Set<ProxmoxPageTabId>(PROXMOX_TAB_SPECS.map((tab) => tab.id));
const PROXMOX_WORKLOAD_STATUS_OPTIONS: readonly WorkloadsStatusOption[] = [
  { value: 'all', label: 'All' },
  { value: 'running', label: 'Running' },
  { value: 'degraded', label: 'Attention' },
  { value: 'stopped', label: 'Stopped' },
];

const ProxmoxIcon = getPlatformIcon('proxmox');
const proxmoxIcon = () => <ProxmoxIcon class="h-6 w-6 text-slate-400" />;
const EMPTY_PROXMOX_PAGE_MODEL = buildProxmoxPageModel([]);

export function ProxmoxPageSurface() {
  const location = useLocation();
  const { activeAlerts } = useWebSocket();
  const alertsActivation = useAlertsActivation();
  const phoneViewport = typeof window !== 'undefined' && window.innerWidth < 640;
  const requestedTab = createMemo<ProxmoxPageTabId>(() => {
    const segment = location.pathname.split('/').filter(Boolean)[1] as ProxmoxPageTabId | undefined;
    return segment && VALID_TABS.has(segment) ? segment : 'overview';
  });
  // List aggregations count the whole estate, not the query scope. The small
  // PMG row query returns source-scoped type facets for every Proxmox workflow
  // without hydrating each inactive section's inventory.
  const tabEvidence = useUnifiedResources({
    query: 'type=pmg&source=proxmox,pbs,pmg,agent',
    cacheKey: 'proxmox-tab-evidence',
    initialHydration: 'prefer-ws-then-rest',
  });
  createEffect(() => {
    // A fresh all-resources cache can seed rows but not source-filtered facets.
    // Force this compact query once instead of leaving the rail unresolved
    // until a websocket event happens to arrive.
    if (tabEvidence.facets?.() !== null) return;
    void Promise.resolve()
      .then(() => tabEvidence.refetch())
      .catch(() => undefined);
  });
  // Replication jobs come straight from /api/replication/jobs (they bypass
  // the unified-resource pipeline), so the surface owns the fetch: the job
  // count gates the Replication tab and the same data feeds the table. The
  // read polls in the background because the table's Last sync and Next sync
  // keep moving on the shared clock: a snapshot read once at mount would age
  // a job that keeps syncing and count it overdue. A failed poll keeps the
  // last jobs, so the tab does not vanish under the user.
  const replicationJobs = createNonSuspendingQuery({
    source: () => 'proxmox-pve',
    fetcher: (_source, signal) => fetchReplicationJobs(signal),
    initialValue: NO_REPLICATION_JOBS,
    pollMs: REPLICATION_JOBS_POLL_MS,
  });
  const replicationJobCount = createMemo(() => replicationJobs.value().length);
  // Replication presence is known once a read has succeeded. A failed read
  // before that says nothing, so a direct link holds on its error and Retry
  // instead of falling to Overview; a failed poll after that keeps the last
  // answer rather than reopening a route an empty read already closed. An
  // access denial withdraws that answer, so the link holds on the denial.
  const replicationJobsConfirmed = createMemo<boolean>((confirmed) => {
    if (!replicationJobs.resolvedOnce()) return false;
    const error = replicationJobs.error();
    if (getAPIReadAccessErrorMessage(error)) return false;
    return confirmed || !error;
  }, false);
  const visibleTabs = createMemo(() => {
    // An unknown snapshot is not evidence that every optional integration is
    // present. Never use estate-wide aggregations here: unrelated VMware VMs
    // or TrueNAS storage would otherwise advertise empty Proxmox sections.
    return buildVisibleProxmoxTabSpecsFromCounts(
      tabEvidence.facets?.()?.byType ?? {},
      replicationJobCount(),
    );
  });
  const visibleTabIds = createMemo(
    () => new Set<ProxmoxPageTabId>(visibleTabs().map((tab) => tab.id)),
  );
  const activeTab = createMemo<ProxmoxPageTabId>(() => {
    const requested = requestedTab();
    // Do not discard a direct link while counts are still unknown: its own
    // resource query must be allowed to hydrate before deciding it is absent.
    const countsUnknown =
      !tabEvidence.facets?.() || (requested === 'replication' && !replicationJobsConfirmed());
    return countsUnknown || visibleTabIds().has(requested) ? requested : 'overview';
  });
  const shouldHydrateTab = (tab: ProxmoxPageTabId) => activeTab() === tab;
  const overviewResources = useUnifiedResources({
    query: PROXMOX_RESOURCE_QUERY_BY_TAB.overview,
    cacheKey: 'proxmox-overview',
    enabled: () => shouldHydrateTab('overview') || shouldHydrateTab('backups'),
    realtimeEnabled: () => activeTab() === 'overview' || activeTab() === 'backups',
  });
  const storageResources = useUnifiedResources({
    query: PROXMOX_RESOURCE_QUERY_BY_TAB.storage,
    cacheKey: 'proxmox-storage-shell',
    enabled: () => shouldHydrateTab('storage'),
    realtimeEnabled: () => activeTab() === 'storage',
  });
  const replicationResources = useUnifiedResources({
    query: PROXMOX_RESOURCE_QUERY_BY_TAB.replication,
    cacheKey: 'proxmox-replication-shell',
    enabled: () => shouldHydrateTab('replication'),
    realtimeEnabled: () => activeTab() === 'replication',
  });
  const backupResources = useUnifiedResources({
    query: PROXMOX_RESOURCE_QUERY_BY_TAB.backups,
    cacheKey: 'proxmox-backups-shell',
    enabled: () => shouldHydrateTab('backups'),
    realtimeEnabled: () => activeTab() === 'backups',
  });
  const cephResources = useUnifiedResources({
    query: PROXMOX_RESOURCE_QUERY_BY_TAB.ceph,
    cacheKey: 'proxmox-ceph',
    enabled: () => shouldHydrateTab('ceph'),
    realtimeEnabled: () => activeTab() === 'ceph',
  });
  const mailResources = useUnifiedResources({
    query: PROXMOX_RESOURCE_QUERY_BY_TAB.mail,
    cacheKey: 'proxmox-mail',
    enabled: () => shouldHydrateTab('mail'),
    realtimeEnabled: () => activeTab() === 'mail',
  });
  const [mountedTabs, setMountedTabs] = createSignal<Set<ProxmoxPageTabId>>(
    new Set([requestedTab()]),
  );
  const mountTab = (tab: ProxmoxPageTabId) =>
    setMountedTabs((current) => {
      const mountedOrder = [...current];
      if (mountedOrder[mountedOrder.length - 1] === tab) return current;
      const next = new Set(current);
      // Refresh insertion order so the least-recently-used tab is evicted.
      next.delete(tab);
      next.add(tab);
      if (phoneViewport) {
        while (next.size > PHONE_MOUNTED_TAB_LIMIT) {
          const oldestTab = next.values().next().value as ProxmoxPageTabId | undefined;
          if (!oldestTab) break;
          next.delete(oldestTab);
        }
      }
      return next;
    });
  createEffect(() => {
    mountTab(activeTab());
  });
  const resourceState = createMemo(() => {
    switch (activeTab()) {
      case 'storage':
        return storageResources;
      case 'replication':
        return replicationResources;
      case 'backups':
        return backupResources;
      case 'ceph':
        return cephResources;
      case 'mail':
        return mailResources;
      default:
        return overviewResources;
    }
  });
  const loading = () =>
    activeTab() === 'backups'
      ? overviewResources.loading() || backupResources.loading()
      : resourceState().loading();
  const error = () =>
    activeTab() === 'backups'
      ? (overviewResources.error() ?? backupResources.error())
      : resourceState().error();
  const refetch = () =>
    activeTab() === 'backups'
      ? Promise.all([overviewResources.refetch(), backupResources.refetch()])
      : resourceState().refetch();
  const normalizeSnapshot = (snapshot: Resource[] | undefined) =>
    Array.isArray(snapshot) ? snapshot : [];
  const buildModel = (snapshot: Resource[] | undefined) =>
    buildProxmoxPageModel(normalizeSnapshot(snapshot));
  const overviewModel = createMemo(() => buildModel(overviewResources.resources()));
  const backupModel = createMemo(() =>
    buildModel(
      Array.from(
        new Map(
          [
            ...normalizeSnapshot(overviewResources.resources()),
            ...normalizeSnapshot(backupResources.resources()),
          ].map((resource) => [resource.id, resource]),
        ).values(),
      ),
    ),
  );
  const model = createMemo(() => {
    if (activeTab() === 'overview') return overviewModel();
    if (activeTab() === 'backups') return backupModel();
    return buildModel(resourceState().resources());
  });
  const agentUpdateTargetVersion = createMemo(
    () => updateStore.versionInfo()?.agentUpdateTargetVersion,
  );
  const outdatedAgentHosts = createMemo(() =>
    collectOutdatedAgentHosts(model().pveNodes, agentUpdateTargetVersion()),
  );
  const outdatedAgentUpdatePath = createMemo(() =>
    buildInfrastructureAgentUpdatesPath(outdatedAgentHosts().map((host) => host.agentId)),
  );
  const serverVersionDisplay = createMemo(() =>
    formatAgentVersionDisplay(agentUpdateTargetVersion()),
  );
  // The node carries the registry's verdict, so the notice reads the same on
  // every tab that lists nodes; no tab hydrates disks for it.
  const outdatedSensorSetupNodes = createMemo(() =>
    collectOutdatedSensorSetupNodes(model().pveNodes),
  );

  // The hosts table at the top and the embedded WorkloadsSurface below share
  // the bars/sparklines toggle (and the sparkline history range that ships
  // with it). Owning the persistent signals at the page level lets one
  // segmented control in the workloads filter drive both tables; the surface
  // accepts these as overrides so it skips its own internal persistent
  // signal and tracks the shared state directly.
  const [metricDisplayMode, setMetricDisplayMode] = usePersistentSignal<WorkloadsMetricDisplayMode>(
    STORAGE_KEYS.WORKLOADS_METRIC_DISPLAY_MODE,
    DEFAULT_WORKLOADS_METRIC_DISPLAY_MODE,
    {
      deserialize: (raw) =>
        raw === 'bars' || raw === 'sparklines' ? raw : DEFAULT_WORKLOADS_METRIC_DISPLAY_MODE,
    },
  );
  const [metricHistoryRange, setMetricHistoryRange] =
    usePersistentSignal<WorkloadTableMetricHistoryRange>(
      STORAGE_KEYS.WORKLOADS_METRIC_HISTORY_RANGE,
      WORKLOAD_TABLE_HISTORY_DEFAULT_RANGE,
      {
        deserialize: (raw) =>
          isWorkloadTableMetricHistoryRange(raw) ? raw : WORKLOAD_TABLE_HISTORY_DEFAULT_RANGE,
      },
    );
  const [memoryDisplayBasis, setMemoryDisplayBasis] =
    usePersistentSignal<WorkloadsMemoryDisplayBasis>(
      STORAGE_KEYS.WORKLOADS_MEMORY_DISPLAY_BASIS,
      'guest',
      {
        deserialize: (raw) => (raw === 'host' ? 'host' : 'guest'),
      },
    );
  const [inventoryCountsVisible, setInventoryCountsVisible] = usePersistentSignal(
    PLATFORM_ESTATE_COUNTS_STORAGE_KEY,
    true,
    { deserialize: deserializePlatformEstateCountsVisibility },
  );

  return (
    <div data-testid="proxmox-page" class="pulse-wide-data-surface space-y-3">
      <PlatformSectionTabs tabs={visibleTabs()} active={activeTab()} ariaLabel="Proxmox sections" />

      <Show
        when={!loading() || model().resources.length > 0}
        fallback={
          <PlatformTableLoadingState
            title="Loading Proxmox resources"
            description="Pulse is loading the Proxmox resource snapshot."
          />
        }
      >
        <Show
          when={!error()}
          fallback={
            <PlatformErrorState
              title="Could not load Proxmox resources"
              description="Refresh the resource snapshot or check the API connection state."
              onRefresh={() => void refetch()}
            />
          }
        >
          <Show
            when={model().resources.length > 0}
            fallback={
              <PlatformTableEmptyState
                icon={proxmoxIcon()}
                title="No Proxmox resources"
                description="Add Proxmox VE, Proxmox Backup Server, or Proxmox Mail Gateway in Settings to populate this platform page."
              />
            }
          >
            <PlatformOutdatedAgentNotice
              hosts={outdatedAgentHosts()}
              targetVersion={serverVersionDisplay()}
              missingLabel="fixes and node details"
              copyVariant="latest-detail"
              actionHref={outdatedAgentUpdatePath()}
              actionLabel="Open agent upgrade commands"
            />
            <PlatformOutdatedSensorSetupNotice
              nodes={outdatedSensorSetupNodes()}
              actionHref={buildInfrastructureWorkspacePath()}
            />
            <Show when={mountedTabs().has('overview')}>
              <div
                class="space-y-4"
                classList={{ hidden: activeTab() !== 'overview' }}
                aria-hidden={activeTab() !== 'overview' ? 'true' : undefined}
              >
                <ProxmoxOverview
                  model={overviewModel}
                  active={() => activeTab() === 'overview'}
                  metricDisplayMode={metricDisplayMode}
                  setMetricDisplayMode={setMetricDisplayMode}
                  metricHistoryRange={metricHistoryRange}
                  setMetricHistoryRange={setMetricHistoryRange}
                  memoryDisplayBasis={memoryDisplayBasis}
                  setMemoryDisplayBasis={setMemoryDisplayBasis}
                  resourceSnapshot={() =>
                    overviewResources.loading() && overviewModel().resources.length === 0
                      ? undefined
                      : overviewModel().resources
                  }
                  resourceSnapshotChange={overviewResources.resourceSnapshotChange}
                  resourceSnapshotRefetch={() => overviewResources.refetch()}
                  inventoryCountsVisible={inventoryCountsVisible}
                  setInventoryCountsVisible={setInventoryCountsVisible}
                />
              </div>
            </Show>
            <Show when={mountedTabs().has('storage')}>
              <div
                classList={{ hidden: activeTab() !== 'storage' }}
                aria-hidden={activeTab() !== 'storage' ? 'true' : undefined}
              >
                <StorageSurface
                  routeActive={activeTab() === 'storage'}
                  forcedSourceFilter={PROXMOX_PLATFORM_FILTER}
                  resourceSource={storageResources}
                  suppressNodeFilter
                  filterAriaLabel="Proxmox storage filters"
                  filterSearchPlaceholder="Search Proxmox storage by pool, datastore, node, or device"
                  filterSearchEmptyMessage="Recent Proxmox storage searches appear here."
                />
              </div>
            </Show>
            <Show when={activeTab() === 'replication'}>
              <ProxmoxReplicationTable
                jobs={replicationJobs.resolvedOnce() ? replicationJobs.value() : undefined}
                error={replicationJobs.error() ?? undefined}
                onRetry={() => void replicationJobs.refetch()}
                emptyIcon={<ProxmoxIcon class="h-6 w-6 text-slate-400" />}
                emptyTitle="No replication jobs"
                emptyDescription="Replication jobs appear here once PVE is configured to replicate guests between nodes."
              />
            </Show>
            <Show when={activeTab() === 'backups'}>
              <ProxmoxBackupsTable
                emptyIcon={<ProxmoxIcon class="h-6 w-6 text-slate-400" />}
                workloads={model().guests}
                servers={model().resources}
                summaryAside={<ProxmoxBackupJobsSection />}
                datastoreAlerts={(ids) =>
                  getAlertsForResource(ids, activeAlerts, alertsActivation.detectionEnabled())
                }
              />
            </Show>
            <Show when={activeTab() === 'ceph'}>
              <ProxmoxCephTable
                resources={model().ceph.filter((resource) => resource.type === 'ceph')}
                emptyIcon={<ProxmoxIcon class="h-6 w-6 text-slate-400" />}
                emptyTitle="No Ceph clusters"
                emptyDescription="Ceph clusters appear here once a Proxmox VE node reports cluster topology."
              />
            </Show>
            <Show when={activeTab() === 'mail'}>
              <ProxmoxMailGatewayTable
                resources={model().pmg}
                emptyTitle="No Proxmox Mail Gateway instances"
                emptyDescription="PMG instances appear here once a Proxmox Mail Gateway connection reports them."
              />
            </Show>
          </Show>
        </Show>
      </Show>
    </div>
  );
}

interface ProxmoxOverviewProps {
  model: Accessor<ProxmoxPageModel>;
  active: Accessor<boolean>;
  metricDisplayMode: Accessor<WorkloadsMetricDisplayMode>;
  setMetricDisplayMode: (value: WorkloadsMetricDisplayMode) => void;
  metricHistoryRange: Accessor<WorkloadTableMetricHistoryRange>;
  setMetricHistoryRange: (value: WorkloadTableMetricHistoryRange) => void;
  memoryDisplayBasis: Accessor<WorkloadsMemoryDisplayBasis>;
  setMemoryDisplayBasis: (value: WorkloadsMemoryDisplayBasis) => void;
  resourceSnapshot: Accessor<Resource[] | undefined>;
  resourceSnapshotChange: Accessor<{
    version: number;
    changedIds: ReadonlySet<string> | null;
  }>;
  resourceSnapshotRefetch: () => Promise<unknown>;
  inventoryCountsVisible: Accessor<boolean>;
  setInventoryCountsVisible: (visible: boolean) => void;
}

function ProxmoxOverview(props: ProxmoxOverviewProps) {
  const currentModel = createMemo(() => props.model?.() ?? EMPTY_PROXMOX_PAGE_MODEL);
  const overviewWidth = useObservedElementWidth();
  const workloadsState = useWorkloadsState({
    layoutWidth: overviewWidth.width,
    resourceSnapshot: props.resourceSnapshot,
    resourceSnapshotChange: props.resourceSnapshotChange,
    resourceSnapshotRefetch: props.resourceSnapshotRefetch,
    forcedPlatform: PROXMOX_PLATFORM_FILTER,
    excludedWorkloadTypes: PROXMOX_WORKLOAD_EXCLUDED_TYPES,
    showNestedExcludedWorkloads: true,
    suppressPlatformFilter: true,
    // The polymorphic 'info' column always holds the VMID on a pure-Proxmox
    // surface, so label it with the platform vocabulary instead of 'Info'.
    columnLabelOverrides: { info: 'ID' },
    statusModeStorageScope: PROXMOX_WORKLOAD_STATUS_STORAGE_SCOPE,
    metricDisplayMode: props.metricDisplayMode,
    onMetricDisplayModeChange: props.setMetricDisplayMode,
    metricHistoryRange: props.metricHistoryRange,
    onMetricHistoryRangeChange: props.setMetricHistoryRange,
    memoryDisplayBasis: props.memoryDisplayBasis,
    routeStateEnabled: props.active,
  });
  const showSharedFilterToolbar = createMemo(
    () =>
      workloadsState.surfaceConnected() &&
      workloadsState.surfaceInitialDataReceived() &&
      workloadsState.allGuests().length > 0,
  );
  const estateTopology = createMemo(() => buildProxmoxEstateTopology(currentModel().resources));
  // Use the same node identity as the workload table, including empty nodes.
  const nodeScopes = createMemo(
    () =>
      new Map(
        currentModel().pveNodes.map((resource) => {
          const node = nodeFromResource(resource);
          return [
            resource.id,
            workloadNodeScopeId({
              node: node?.name ?? resource.name,
              instance: node?.instance ?? '',
            }),
          ];
        }),
      ),
  );
  const selectedScope = () => workloadsState.selectedNode() || workloadsState.selectedHostHint();
  const selectedNode = createMemo(() =>
    currentModel().pveNodes.find((node) => nodeScopes().get(node.id) === selectedScope()),
  );
  const selectedNodeLabel = createMemo(() => {
    const scope = selectedScope();
    if (!scope) return null;
    return (
      selectedNode()?.name ||
      workloadsState.hostFilterConfig()?.options.find((option) => option.value === scope)?.label ||
      scope
    );
  });
  const guestsFocus = createPlatformHostScopeFocus();
  const showNodeGuests = (node: Resource) => {
    const scope = nodeScopes().get(node.id);
    if (!scope) return;
    const nextScope = selectedScope() === scope ? null : scope;
    workloadsState.handleNodeSelect(nextScope, nextScope ? 'pve' : null);
    if (nextScope) {
      requestAnimationFrame(() => {
        if (selectedScope() === nextScope) guestsFocus.reveal();
      });
    }
  };
  const clearNodeFilter = () => {
    workloadsState.handleNodeSelect(null, null);
    guestsFocus.focus();
  };

  return (
    <div ref={overviewWidth.setElement} class="pulse-wide-data-surface flex flex-col gap-4">
      <section>
        <ProxmoxNodesTable
          nodes={currentModel().pveNodes}
          guests={currentModel().guests}
          search={workloadsState.search}
          metricDisplayMode={props.metricDisplayMode}
          metricHistoryRange={props.metricHistoryRange}
          layoutWidth={overviewWidth.width}
          emptyIcon={<ProxmoxIcon class="h-6 w-6 text-slate-400" />}
          emptyTitle="No Proxmox VE nodes"
          emptyDescription="Proxmox VE nodes appear here once a PVE host reports inventory."
          topology={estateTopology()}
          inventoryCountsVisible={props.inventoryCountsVisible}
          onShowGuests={showNodeGuests}
          guestFilterNodeId={() => selectedNode()?.id ?? null}
        />
      </section>
      <section
        id="proxmox-guests-section"
        aria-label="Guests"
        class="space-y-3 scroll-mt-4"
        data-testid="proxmox-guests-section"
      >
        <Show when={showSharedFilterToolbar()}>
          <div data-summary-clear-ignore>
            <WorkloadsFilter
              search={workloadsState.search}
              setSearch={workloadsState.setSearch}
              viewMode={workloadsState.viewMode}
              setViewMode={workloadsState.setViewMode}
              statusMode={workloadsState.statusMode}
              setStatusMode={workloadsState.setStatusMode}
              groupingMode={workloadsState.groupingMode}
              setGroupingMode={workloadsState.setGroupingMode}
              setSortKey={workloadsState.setSortKey}
              setSortDirection={workloadsState.setSortDirection}
              onBeforeAutoFocus={workloadsState.handleBeforeAutoFocus}
              ariaLabel="Proxmox workload filters"
              searchPlaceholder="Search VMs and LXCs by name, VMID, node, or status"
              searchEmptyMessage="Recent Proxmox workload searches appear here."
              searchSuggestionWorkloads={workloadsState.allGuests}
              statusOptions={PROXMOX_WORKLOAD_STATUS_OPTIONS}
              inventoryStats={workloadsState.inventoryStats}
              inventoryCountsVisible={props.inventoryCountsVisible}
              setInventoryCountsVisible={props.setInventoryCountsVisible}
              columnVisibility={workloadsState.workloadsFilterColumnVisibility()}
              containerRuntimeFilter={workloadsState.containerRuntimeFilterConfig()}
              hostFilter={workloadsState.hostFilterConfig()}
              namespaceFilter={undefined}
              platformFilter={undefined}
              {...getWorkloadsMetricFilterProps(workloadsState)}
              memoryDisplayBasis={workloadsState.workloadMemoryDisplayBasis}
              setMemoryDisplayBasis={props.setMemoryDisplayBasis}
              forcedPlatform={PROXMOX_PLATFORM_FILTER}
              pinnedSelectionActive={() => Boolean(workloadsState.selectedGuestId())}
              onClearPinnedSelection={workloadsState.clearPinnedSummaryScope}
            />
          </div>
        </Show>
        <WorkloadsSurface
          state={workloadsState}
          forcedPlatform={PROXMOX_PLATFORM_FILTER}
          emptyStateTitle="No Proxmox workloads"
          emptyStateDescription="Proxmox VMs and LXCs appear here when inventory is available."
          tableTitle={
            <PlatformHostScopedTableTitle
              noun="Guests"
              hostLabel={selectedNodeLabel()}
              count={showSharedFilterToolbar() ? workloadsState.filteredGuests().length : null}
              clearLabel="Show all nodes"
              onClear={clearNodeFilter}
              headingId="proxmox-guests-heading"
              headingRef={guestsFocus.setHeading}
            />
          }
        />
      </section>
    </div>
  );
}

export default ProxmoxPageSurface;