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.

32.3 KB
Raw Blame
import { describe, expect, it } from 'vitest';
import { existsSync, readFileSync } from 'node:fs';
import * as ts from 'typescript';
import agentsMachinesTableSource from '@/features/standalone/AgentsMachinesTable.tsx?raw';
import agentMachineTableModelSource from '@/features/standalone/agentMachineTableModel.ts?raw';
import standalonePageSurfaceSource from '@/features/standalone/StandalonePageSurface.tsx?raw';
import dockerAlertsTableSource from '@/features/docker/DockerAlertsTable.tsx?raw';
import dockerConfigsTableSource from '@/features/docker/DockerConfigsTable.tsx?raw';
import dockerHostsTableSource from '@/features/docker/DockerHostsTable.tsx?raw';
import dockerImagesTableSource from '@/features/docker/DockerImagesTable.tsx?raw';
import dockerNetworksTableSource from '@/features/docker/DockerNetworksTable.tsx?raw';
import dockerPageSurfaceSource from '@/features/docker/DockerPageSurface.tsx?raw';
import dockerSecretsTableSource from '@/features/docker/DockerSecretsTable.tsx?raw';
import dockerServicesTableSource from '@/features/docker/DockerServicesTable.tsx?raw';
import dockerStorageUsageTableSource from '@/features/docker/DockerStorageUsageTable.tsx?raw';
import dockerSwarmNodesTableSource from '@/features/docker/DockerSwarmNodesTable.tsx?raw';
import dockerTasksTableSource from '@/features/docker/DockerTasksTable.tsx?raw';
import dockerVolumesTableSource from '@/features/docker/DockerVolumesTable.tsx?raw';
import kubernetesAlertsTableSource from '@/features/kubernetes/KubernetesAlertsTable.tsx?raw';
import kubernetesAutoscalingTableSource from '@/features/kubernetes/KubernetesAutoscalingTable.tsx?raw';
import kubernetesClustersTableSource from '@/features/kubernetes/KubernetesClustersTable.tsx?raw';
import kubernetesConfigTableSource from '@/features/kubernetes/KubernetesConfigTable.tsx?raw';
import dockerContainerTableModelSource from '@/features/docker/dockerContainerTableModel.ts?raw';
import kubernetesControllersTableSource from '@/features/kubernetes/KubernetesControllersTable.tsx?raw';
import kubernetesDeploymentsTableSource from '@/features/kubernetes/KubernetesDeploymentsTable.tsx?raw';
import kubernetesEventsTableSource from '@/features/kubernetes/KubernetesEventsTable.tsx?raw';
import kubernetesNetworkingTableSource from '@/features/kubernetes/KubernetesNetworkingTable.tsx?raw';
import kubernetesNodesTableSource from '@/features/kubernetes/KubernetesNodesTable.tsx?raw';
import kubernetesPageSurfaceSource from '@/features/kubernetes/KubernetesPageSurface.tsx?raw';
import kubernetesPodsTableSource from '@/features/kubernetes/KubernetesPodsTable.tsx?raw';
import kubernetesPolicyTableSource from '@/features/kubernetes/KubernetesPolicyTable.tsx?raw';
import kubernetesServicesTableSource from '@/features/kubernetes/KubernetesServicesTable.tsx?raw';
import kubernetesStorageTableSource from '@/features/kubernetes/KubernetesStorageTable.tsx?raw';
import proxmoxCoverageTableSource from '@/features/proxmox/ProxmoxCoverageTable.tsx?raw';
import proxmoxRecoverableTableSource from '@/features/proxmox/ProxmoxRecoverableTable.tsx?raw';
import proxmoxMailGatewayDrawerSource from '@/features/proxmox/ProxmoxMailGatewayDrawer.tsx?raw';
import proxmoxPageSurfaceSource from '@/features/proxmox/ProxmoxPageSurface.tsx?raw';
import proxmoxReplicationTableSource from '@/features/proxmox/ProxmoxReplicationTable.tsx?raw';
import truenasAlertsTableSource from '@/features/truenas/TrueNASAlertsTable.tsx?raw';
import truenasAppsTableSource from '@/features/truenas/TrueNASAppsTable.tsx?raw';
import truenasNetworkSharesTableSource from '@/features/truenas/TrueNASNetworkSharesTable.tsx?raw';
import truenasPageSurfaceSource from '@/features/truenas/TrueNASPageSurface.tsx?raw';
import truenasProtectionTableSource from '@/features/truenas/TrueNASProtectionTable.tsx?raw';
import truenasStorageTopologyTableSource from '@/features/truenas/TrueNASStorageTopologyTable.tsx?raw';
import truenasSystemsTableSource from '@/features/truenas/TrueNASSystemsTable.tsx?raw';
import truenasVirtualMachinesTableSource from '@/features/truenas/TrueNASVirtualMachinesTable.tsx?raw';
import vmwarePageSurfaceSource from '@/features/vmware/VmwarePageSurface.tsx?raw';
import vsphereActivityTableSource from '@/features/vmware/VsphereActivityTable.tsx?raw';
import vsphereAlertsTableSource from '@/features/vmware/VsphereAlertsTable.tsx?raw';
import vsphereHostsTableSource from '@/features/vmware/VsphereHostsTable.tsx?raw';
import vsphereNetworksTableSource from '@/features/vmware/VsphereNetworksTable.tsx?raw';
import storageSurfaceSource from '@/components/Storage/Storage.tsx?raw';
import useWorkloadsStateSource from '@/components/Workloads/useWorkloadsState.ts?raw';
import workloadsSurfaceSource from '@/components/Workloads/WorkloadsSurface.tsx?raw';
import { render, screen } from '@solidjs/testing-library';
import { PlatformResourceCounter } from '../sharedPlatformPage';

const indexCssSource = readFileSync('src/index.css', 'utf8');

const overviewSurfaceSources = [
  standalonePageSurfaceSource,
  proxmoxPageSurfaceSource,
  dockerPageSurfaceSource,
  kubernetesPageSurfaceSource,
  truenasPageSurfaceSource,
  vmwarePageSurfaceSource,
];

type JsxTag = ts.JsxOpeningElement | ts.JsxSelfClosingElement;

function parseTsx(source: string): ts.SourceFile {
  return ts.createSourceFile('source.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
}

/** Every node under `root` (inclusive) that passes `test`, in source order. */
function findNodes<T extends ts.Node>(root: ts.Node, test: (node: ts.Node) => node is T): T[] {
  const found: T[] = [];
  const visit = (node: ts.Node) => {
    if (test(node)) found.push(node);
    ts.forEachChild(node, visit);
  };
  visit(root);
  return found;
}

function isJsxTag(node: ts.Node): node is JsxTag {
  return ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node);
}

function jsxTags(root: ts.Node, tag: string): JsxTag[] {
  return findNodes(root, isJsxTag).filter((node) => node.tagName.getText() === tag);
}

/** The single `<tag>` under `root`; throws unless there is exactly one. */
function onlyJsxTag(root: ts.Node, tag: string): JsxTag {
  const tags = jsxTags(root, tag);
  const [only] = tags;
  if (tags.length !== 1 || !only) throw new Error(`expected one <${tag}>, found ${tags.length}`);
  return only;
}

/** Source text of an attribute's value; a bare boolean attribute reads as `true`. */
function jsxAttr(tag: JsxTag, name: string): string | undefined {
  const attr = tag.attributes.properties.find(
    (prop): prop is ts.JsxAttribute => ts.isJsxAttribute(prop) && prop.name.getText() === name,
  );
  if (!attr) return undefined;
  if (!attr.initializer) return 'true';
  return ts.isJsxExpression(attr.initializer)
    ? attr.initializer.expression?.getText()
    : attr.initializer.getText();
}

function functionDecl(root: ts.Node, name: string): ts.FunctionDeclaration {
  const fn = findNodes(root, ts.isFunctionDeclaration).find((node) => node.name?.text === name);
  if (!fn) throw new Error(`function ${name} not found`);
  return fn;
}

/** Initializer text of every object property inside the first `callee(...)` call. */
function callProperties(root: ts.Node, callee: string): Map<string, string> {
  const call = findNodes(root, ts.isCallExpression).find(
    (node) => node.expression.getText() === callee,
  );
  const properties = new Map<string, string>();
  for (const property of call ? findNodes(call, ts.isPropertyAssignment) : []) {
    properties.set(property.name.getText(), property.initializer.getText());
  }
  return properties;
}

/** Tab id of the nearest enclosing `activeTab() === 'x'` / `mountedTabs().has('x')` gate. */
function enclosingTab(tag: ts.Node): string | undefined {
  for (let node = tag.parent; node; node = node.parent) {
    if (!ts.isJsxElement(node) || node.openingElement.tagName.getText() !== 'Show') continue;
    const gate = (jsxAttr(node.openingElement, 'when') ?? '').match(
      /^activeTab\(\) === '([a-z-]+)'$|^mountedTabs\(\)\.has\('([a-z-]+)'\)$/,
    );
    if (gate) return gate[1] ?? gate[2];
  }
  return undefined;
}

describe('platform overview layout guardrails', () => {
  it('keeps Mail Gateway drawer tables prioritized for narrow inline details', () => {
    expect(proxmoxMailGatewayDrawerSource).toContain(
      '<PlatformDetailTable class="min-w-0 table-fixed text-xs">',
    );
    expect(proxmoxMailGatewayDrawerSource).toContain(
      'platform-table-mobile-w-10 platform-table-narrow-hidden md:w-[15%]',
    );
    expect(proxmoxMailGatewayDrawerSource).toContain(
      '<PlatformResponsiveTableLabel compact="Up" full="Uptime" />',
    );
    expect(proxmoxMailGatewayDrawerSource).toContain(
      '<PlatformResponsiveTableLabel compact="Ld" full="Load" />',
    );
    expect(proxmoxMailGatewayDrawerSource).toContain('platform-table-mobile-w-15 md:w-[30%]');
  });

  it('keeps Docker host optional Swarm column wide enough for its header', () => {
    expect(dockerHostsTableSource).toContain('Swarm role');
    expect(dockerHostsTableSource).toContain('md:w-[10%]');
  });

  it('keeps Docker phone tables dense with explicit shared identity sizing', () => {
    for (const source of [
      dockerAlertsTableSource,
      dockerConfigsTableSource,
      dockerHostsTableSource,
      dockerImagesTableSource,
      dockerVolumesTableSource,
      dockerNetworksTableSource,
      dockerStorageUsageTableSource,
      dockerSwarmNodesTableSource,
      dockerServicesTableSource,
      dockerTasksTableSource,
      dockerSecretsTableSource,
    ]) {
      expect(source).toContain('platform-table-mobile-w-30');
    }
    // The images phone row keeps image, size and the update verdict; host and
    // consumers move to the row expansion so the verdict is not clipped. In
    // the tablet band and at md the Update check column keeps the ~122px its
    // longest badge needs ("Update available", "Managed by Pulse"), taken
    // from Size in the band and from Host, Used by and Size at md.
    expect(dockerImagesTableSource).toMatch(
      /sortKey="image"[\s\S]{0,120}?class="platform-table-mobile-w-30 md:w-\[30%\]"\s*bandWidth=\{30\}/,
    );
    expect(dockerImagesTableSource).toMatch(
      /sortKey="size"[\s\S]{0,120}?class="platform-table-mobile-w-20 md:w-\[11%\]"\s*bandWidth=\{12\}/,
    );
    expect(dockerImagesTableSource).toMatch(
      /sortKey="host"[\s\S]{0,120}?class="platform-table-phone-hidden md:w-\[17%\]"\s*bandWidth=\{17\.5\}/,
    );
    expect(dockerImagesTableSource).toMatch(
      /sortKey="usedBy"[\s\S]{0,120}?class="platform-table-phone-hidden md:w-\[23%\]"\s*bandWidth=\{17\.5\}/,
    );
    expect(dockerImagesTableSource).toMatch(
      /sortKey="update"[\s\S]{0,120}?class="platform-table-mobile-w-25 md:w-\[19%\]"\s*bandWidth=\{23\}/,
    );
    expect(dockerServicesTableSource).toMatch(
      /sortKey="mode"[\s\S]{0,120}?class="platform-table-phone-hidden md:w-\[8%\]"/,
    );
    expect(dockerServicesTableSource).toMatch(
      /sortKey="update"[\s\S]{0,120}?class="platform-table-mobile-w-15 w-\[15%\] md:w-\[12%\]"/,
    );
    expect(dockerTasksTableSource).toMatch(
      /sortKey="service"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[18%\]"/,
    );
    expect(dockerTasksTableSource).toMatch(
      /sortKey="node"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[16%\]"/,
    );
    expect(dockerSwarmNodesTableSource).toMatch(
      /sortKey="reachability"[\s\S]{0,120}?class="platform-table-mobile-w-15 w-\[15%\] md:w-\[14%\]"/,
    );
    expect(dockerSwarmNodesTableSource).toMatch(
      /sortKey="memory"[\s\S]{0,120}?class="platform-table-mobile-w-15 w-\[15%\] md:w-\[10%\]"/,
    );
  });

  it('keeps Kubernetes phone identity readable while exposing operational context', () => {
    expect(kubernetesClustersTableSource).toContain(
      '-my-3 inline-flex min-h-11 items-center truncate',
    );
    expect(kubernetesNodesTableSource).toMatch(
      /sortKey="roles"[\s\S]{0,160}?class="platform-table-phone-hidden md:w-\[8%\]"/,
    );
    // Status names the node state on desktop; the dot carries it on phones.
    // Its badge must not clip (Degraded ~64px, Unschedulable ~89px), so Status
    // takes md room from CPU, whose bar has no sublabel, and the tablet band
    // sizes every header and Degraded at a 34rem table.
    expect(kubernetesNodesTableSource).toMatch(
      /sortKey="status"[\s\S]{0,120}?class="platform-table-phone-hidden md:w-\[10\.5%\]"\s*bandWidth=\{14\.6\}/,
    );
    expect(kubernetesNodesTableSource).toMatch(
      /sortKey="cpu"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[7\.5%\]"\s*bandWidth=\{9\.2\}/,
    );
    expect(kubernetesNodesTableSource).toMatch(
      /sortKey="memory"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[10%\]"\s*bandWidth=\{11\.8\}/,
    );
    expect(kubernetesNodesTableSource).toMatch(
      /sortKey="capacity"[\s\S]{0,120}?class="platform-table-mobile-w-10 md:w-\[16%\]"\s*bandWidth=\{13\.1\}/,
    );
    expect(kubernetesDeploymentsTableSource).toMatch(
      /sortKey="namespace"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[18%\]"/,
    );
    expect(kubernetesPodsTableSource).toMatch(
      /sortKey="scope"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[13%\]"/,
    );
    expect(kubernetesPodsTableSource).toMatch(
      /sortKey="node"[\s\S]{0,120}?class="platform-table-phone-hidden md:w-\[12%\]"/,
    );
    expect(kubernetesServicesTableSource).toMatch(
      /sortKey="scope"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[15%\]"/,
    );
    expect(kubernetesNetworkingTableSource).toMatch(
      /sortKey="scope"[\s\S]{0,120}?class="platform-table-mobile-w-20 md:w-\[14%\]"/,
    );
    expect(kubernetesStorageTableSource).toMatch(
      /sortKey="class"[\s\S]{0,120}?class="platform-table-mobile-w-20 md:w-\[10%\]"/,
    );
    expect(kubernetesConfigTableSource).toMatch(
      /sortKey="scope"[\s\S]{0,120}?class="platform-table-mobile-w-20 md:w-\[10%\]"/,
    );
    expect(kubernetesPolicyTableSource).toContain(
      "getPlatformTableHeadClassForKind('text')} platform-table-mobile-w-15 md:w-[12%]",
    );
  });

  it('keeps platform summary cells truncating inside their own column', () => {
    // A capped inline-block (max-w-52 truncate) ignored the column width, so a
    // long value spilled past a narrow cell without an ellipsis and sat above
    // the row's text line; a block span fills the cell and ellipsizes there.
    for (const source of [
      dockerConfigsTableSource,
      dockerImagesTableSource,
      dockerNetworksTableSource,
      dockerSecretsTableSource,
      dockerServicesTableSource,
      dockerTasksTableSource,
      dockerVolumesTableSource,
      proxmoxCoverageTableSource,
      proxmoxRecoverableTableSource,
      vsphereHostsTableSource,
      kubernetesAutoscalingTableSource,
      kubernetesConfigTableSource,
      kubernetesControllersTableSource,
      kubernetesEventsTableSource,
      kubernetesNetworkingTableSource,
      kubernetesNodesTableSource,
      kubernetesPolicyTableSource,
      kubernetesServicesTableSource,
      kubernetesStorageTableSource,
    ]) {
      expect(source).not.toMatch(/class="[^"]*\binline-block\b[^"]*\btruncate\b/);
      expect(source).not.toMatch(/class="[^"]*\btruncate\b[^"]*\binline-block\b/);
      // A block span that ellipsizes in its own cell, toned or not.
      expect(source).toMatch(/class=(?:"|\{`)block truncate\b/);
    }
    // Inside a drawer a phone cannot hover a clipped value, so the Mail
    // Gateway's domain and node names wrap in their cells instead.
    expect(proxmoxMailGatewayDrawerSource).not.toMatch(/class="[^"]*\btruncate\b/);
    expect(proxmoxMailGatewayDrawerSource).toContain('block whitespace-normal wrap-anywhere');
  });

  it('keeps long tablet headers from clipping', () => {
    // "Lifecycle / trust" outgrows its tablet-band column, so it keeps the
    // compact label it shows on phones through that band.
    expect(kubernetesConfigTableSource).toMatch(
      /compact="Status"\s+full="Lifecycle \/ trust"\s+compactInBand/,
    );
    // The Docker Restarts header cannot fit below a 720px table; the count
    // waits in the drawer there and a crash-looper says so in State.
    expect(dockerContainerTableModelSource).toMatch(/restarts: 'tablet',/);
  });

  it('keeps phone-priority visibility container-led and symmetric across table rows', () => {
    expect(indexCssSource).toContain(':is(th, td).platform-table-phone-hidden');
    expect(indexCssSource).toContain(':is(th, td).platform-table-phone-only');

    for (const source of [
      dockerAlertsTableSource,
      kubernetesAlertsTableSource,
      truenasAlertsTableSource,
      vsphereAlertsTableSource,
    ]) {
      expect(source).toMatch(/TableHead[\s\S]{0,160}?platform-table-phone-hidden/);
      expect(source).toMatch(
        /TableCell[\s\S]{0,160}?getPlatformTableCellClassForKind\('badge'\)[\s\S]{0,80}?platform-table-phone-hidden/,
      );
    }

    expect(dockerVolumesTableSource).toMatch(
      /sortKey="scope"[\s\S]{0,120}?platform-table-phone-hidden/,
    );
    expect(dockerVolumesTableSource).toMatch(
      /getPlatformTableCellClassForKind\('text'\)[\s\S]{0,100}?platform-table-phone-hidden[\s\S]{0,140}?dockerTextValue\(resource\.docker\?\.scope\)/,
    );
    // Desired is the denominator Ready already shows (2/2), so it waits for a
    // wide table rather than returning with the tablet tier.
    expect(kubernetesDeploymentsTableSource).toMatch(
      /sortKey="desired"[\s\S]{0,120}?class="hidden md:table-cell md:w-\[8%\]"/,
    );
    // On a phone Ready only shows 2/2 while Age needs room for "18h ago".
    expect(kubernetesDeploymentsTableSource).toMatch(
      /sortKey="ready"[\s\S]{0,120}?class="platform-table-mobile-w-10 md:w-\[7%\]"/,
    );
    expect(kubernetesDeploymentsTableSource).toMatch(
      /sortKey="age"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[8%\] platform-table-narrow-hidden"/,
    );
    expect(truenasVirtualMachinesTableSource).toMatch(
      /sortKey="state"[\s\S]{0,120}?platform-table-phone-hidden/,
    );
    expect(vsphereActivityTableSource).toMatch(
      /sortKey="state"[\s\S]{0,120}?platform-table-phone-hidden/,
    );
  });

  it('keeps remaining platform phone identity and actions usable', () => {
    expect(truenasStorageTopologyTableSource).toMatch(
      /sortKey="kind"[\s\S]{0,160}?platform-table-mobile-w-15 md:w-\[10%\]/,
    );
    expect(truenasStorageTopologyTableSource).toContain("return 'pl-6 sm:pl-11'");
    expect(truenasStorageTopologyTableSource).toMatch(
      /sortKey="resource"[\s\S]{0,120}?class="platform-table-mobile-w-30 md:w-\[32%\]"/,
    );
    expect(vsphereNetworksTableSource).toMatch(
      /sortKey="network"[\s\S]{0,120}?class="platform-table-mobile-w-30 md:w-\[20%\]"/,
    );
    expect(vsphereNetworksTableSource).toMatch(
      /sortKey="type"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[10%\]"/,
    );
    expect(agentsMachinesTableSource).toContain(
      'class="-my-2 min-h-11 min-w-11 sm:-my-0.5 sm:min-h-0 sm:min-w-0"',
    );
    expect(agentsMachinesTableSource).toContain(
      '-my-3 inline-flex min-h-11 max-w-full items-center',
    );
    expect(agentsMachinesTableSource).toContain(
      'flex min-h-11 w-full items-center gap-2 rounded-sm',
    );
  });

  it('keeps provider overview tables on their tuned layout widths', () => {
    for (const source of overviewSurfaceSources) {
      expect(source).toMatch(/<div[^>]*class="[^"]*\bspace-y-4\b[^"]*"/);
    }

    expect(dockerNetworksTableSource).toContain("attached: 'w-[25%]'");
    expect(dockerNetworksTableSource).toContain("driver: 'w-[15%]'");
    expect(dockerNetworksTableSource).toContain("attention: 'w-[15%]'");
    expect(truenasAppsTableSource).toContain('md:min-w-[960px]');
    // These classes are the TSX half of the container-query rebalancing in
    // src/index.css (th.truenas-app-*-column); jsdom cannot render container
    // queries, so renaming one silently kills the CSS.
    expect(truenasAppsTableSource).toContain('truenas-app-name-column');
    expect(truenasAppsTableSource).toContain('truenas-app-containers-column');
    expect(truenasAppsTableSource).toContain('truenas-app-updates-column');
    expect(truenasAppsTableSource).toContain(
      '<PlatformResponsiveTableLabel compact="Upd." full="Updates" />',
    );
    expect(truenasAppsTableSource).toContain(
      '<PlatformResponsiveTableLabel compact="A" full="App" />',
    );
    expect(truenasAppsTableSource).toContain(
      '<PlatformResponsiveTableLabel compact="I" full="Image" />',
    );
    expect(truenasNetworkSharesTableSource).toContain('md:min-w-[960px]');
    expect(truenasProtectionTableSource).toContain('md:min-w-[960px]');
    expect(truenasStorageTopologyTableSource).toContain('md:min-w-[960px]');
    expect(truenasVirtualMachinesTableSource).toContain('md:min-w-[960px]');
    expect(truenasVirtualMachinesTableSource).toMatch(
      /class="hidden sm:table-cell md:w-\[26%\]"[\s\S]{0,120}?Flags/,
    );
    expect(vsphereNetworksTableSource).toMatch(
      /sortKey="vms"[\s\S]{0,120}?class="platform-table-mobile-w-15 md:w-\[5%\]"/,
    );
    expect(proxmoxReplicationTableSource).toContain("guest: 'w-[20%]'");
    expect(proxmoxReplicationTableSource).toContain("fails: 'w-[4%]'");
  });

  it('keeps secondary overview tables from rendering duplicate standalone toolbars', () => {
    for (const source of [
      dockerPageSurfaceSource,
      kubernetesPageSurfaceSource,
      truenasPageSurfaceSource,
      vmwarePageSurfaceSource,
    ]) {
      expect(source).toContain('showToolbar={false}');
    }
  });

  it('keeps platform overview pages from rendering a duplicate WorkloadsFilter', () => {
    // Proxmox and vSphere overview pages render their own page-level
    // WorkloadsFilter above the embedded WorkloadsSurface so a single
    // toolbar drives both the page's top table and the workloads table.
    // The surface renders no filter of its own; one there would stack a
    // second toolbar wired to the same state (RC6 bug).
    expect(workloadsSurfaceSource).not.toContain('<WorkloadsFilter');
    expect(workloadsSurfaceSource).not.toContain("from './WorkloadsFilter'");
    const surfacesWithSharedToolbar: Array<[string, string]> = [
      ['ProxmoxPageSurface', proxmoxPageSurfaceSource],
      ['VmwarePageSurface', vmwarePageSurfaceSource],
    ];
    for (const [name, source] of surfacesWithSharedToolbar) {
      const filterCount = (source.match(/<WorkloadsFilter\b/g) ?? []).length;
      expect(filterCount, `${name} should render exactly one <WorkloadsFilter>`).toBe(1);
      expect(
        source.indexOf('<WorkloadsFilter'),
        `${name} filter precedes the surface`,
      ).toBeLessThan(source.indexOf('<WorkloadsSurface'));
    }
  });

  it('keeps canonical surface embeds to the tabs the platform-page contract names', () => {
    // The platform-page rule in frontend-primitives.md (mirrored by
    // cloud-paid, storage-recovery, unified-resources and
    // performance-and-scalability) names exactly these embeds:
    // WorkloadsSurface on the Proxmox and vSphere Overview tabs,
    // StorageSurface on the Proxmox Storage tab, and no Recovery surface.
    const proxmoxFile = parseTsx(proxmoxPageSurfaceSource);
    const truenasFile = parseTsx(truenasPageSurfaceSource);
    const expectedEmbeds: Array<[string, ts.SourceFile, { workloads: number; storage: number }]> = [
      [
        'StandalonePageSurface',
        parseTsx(standalonePageSurfaceSource),
        { workloads: 0, storage: 0 },
      ],
      ['ProxmoxPageSurface', proxmoxFile, { workloads: 1, storage: 1 }],
      ['DockerPageSurface', parseTsx(dockerPageSurfaceSource), { workloads: 0, storage: 0 }],
      [
        'KubernetesPageSurface',
        parseTsx(kubernetesPageSurfaceSource),
        { workloads: 0, storage: 0 },
      ],
      ['TrueNASPageSurface', truenasFile, { workloads: 0, storage: 0 }],
      ['VmwarePageSurface', parseTsx(vmwarePageSurfaceSource), { workloads: 1, storage: 0 }],
    ];
    for (const [name, file, expected] of expectedEmbeds) {
      expect(jsxTags(file, 'WorkloadsSurface').length, `${name} WorkloadsSurface embeds`).toBe(
        expected.workloads,
      );
      expect(jsxTags(file, 'StorageSurface').length, `${name} StorageSurface embeds`).toBe(
        expected.storage,
      );
      const recoveryEmbeds = findNodes(file, isJsxTag)
        .map((tag) => tag.tagName.getText())
        .filter((tag) => /^Recovery(?:Surface)?$/.test(tag));
      expect(recoveryEmbeds, `${name} must not embed a Recovery surface`).toEqual([]);
    }
    expect(existsSync('src/features/recovery')).toBe(false);
    expect(existsSync('src/components/Recovery')).toBe(false);

    // Neither surface has an embedded or table-only mode, and WorkloadsSurface
    // has no toolbar prop at all: it renders no toolbar, and the embedding page
    // renders the only one.
    const surfaceSources: Array<[string, string]> = [
      ['WorkloadsSurface', workloadsSurfaceSource],
      ['useWorkloadsState', useWorkloadsStateSource],
      ['Storage', storageSurfaceSource],
    ];
    for (const [name, source] of surfaceSources) {
      expect(source, `${name} must not declare an embed-mode prop`).not.toMatch(
        /\b(?:embedded|tableOnly|showFilterToolbar|suppressFilterToolbar)\??:/,
      );
      expect(source, `${name} must not read an embed-mode prop`).not.toMatch(
        /props\.(?:embedded|tableOnly|showFilterToolbar|suppressFilterToolbar)\b/,
      );
    }

    // WorkloadsSurface renders the state its page passes. It imports only that
    // state's type, so it has no hook to call and cannot build a second state.
    const workloadsSurfaceFile = parseTsx(workloadsSurfaceSource);
    const stateModuleImports = findNodes(workloadsSurfaceFile, ts.isImportDeclaration).filter(
      (node) =>
        ts.isStringLiteral(node.moduleSpecifier) &&
        node.moduleSpecifier.text === './useWorkloadsState',
    );
    expect(stateModuleImports.length).toBeGreaterThan(0);
    for (const node of stateModuleImports) {
      expect(node.importClause?.isTypeOnly, node.getText()).toBe(true);
    }
    expect(
      findNodes(workloadsSurfaceFile, ts.isCallExpression).map((call) => call.expression.getText()),
    ).not.toContain('useWorkloadsState');

    // Each Workloads embed sits on its page's Overview tab, owns the state and
    // the one toolbar, and locks the platform: the state is scoped to it and
    // the Platform chip never shows as a removable filter.
    const workloadsEmbedders: Array<[string, ts.SourceFile, string, string]> = [
      ['ProxmoxPageSurface', proxmoxFile, 'ProxmoxOverview', 'PROXMOX_PLATFORM_FILTER'],
      [
        'VmwarePageSurface',
        parseTsx(vmwarePageSurfaceSource),
        'VmwareOverview',
        'VMWARE_PLATFORM_FILTER',
      ],
    ];
    for (const [name, file, overview, platform] of workloadsEmbedders) {
      expect(enclosingTab(onlyJsxTag(file, overview)), `${name} overview tab`).toBe('overview');
      const overviewFn = functionDecl(file, overview);
      const state = callProperties(overviewFn, 'useWorkloadsState');
      expect(state.get('forcedPlatform'), name).toBe(platform);
      expect(state.get('suppressPlatformFilter'), name).toBe('true');
      const toolbar = onlyJsxTag(overviewFn, 'WorkloadsFilter');
      expect(jsxAttr(toolbar, 'platformFilter'), name).toBe('undefined');
      expect(jsxAttr(toolbar, 'forcedPlatform'), name).toBe(platform);
      const surface = onlyJsxTag(overviewFn, 'WorkloadsSurface');
      expect(jsxAttr(surface, 'state'), name).toBe('workloadsState');
      // The surface renders only that state; the scope it repeats for its
      // empty-state copy must be the scope the state was built with.
      const unquote = (text?: string) => text?.replace(/^(['"])(.*)\1$/, '$2');
      expect(jsxAttr(surface, 'forcedPlatform'), name).toBe(platform);
      expect(unquote(jsxAttr(surface, 'forcedViewMode')), name).toBe(
        unquote(state.get('forcedViewMode')),
      );
    }

    // StorageSurface sits on the Proxmox Storage tab with the source locked and
    // no forcedView, so Storage keeps its Storage / Physical Disks view tabs.
    const storageEmbed = onlyJsxTag(proxmoxFile, 'StorageSurface');
    expect(enclosingTab(storageEmbed)).toBe('storage');
    expect(jsxAttr(storageEmbed, 'forcedSourceFilter')).toBe('PROXMOX_PLATFORM_FILTER');
    expect(jsxAttr(storageEmbed, 'forcedView')).toBeUndefined();
    const storageControls = onlyJsxTag(parseTsx(storageSurfaceSource), 'StoragePageControls');
    expect(jsxAttr(storageControls, 'showViewTabs')).toBe('!props.forcedView');

    // TrueNAS storage and recovery rows render in TrueNAS-owned tables, and
    // the Proxmox Backups tab is a Proxmox-owned table.
    expect(enclosingTab(onlyJsxTag(truenasFile, 'TrueNASStorage'))).toBe('storage');
    onlyJsxTag(functionDecl(truenasFile, 'TrueNASStorage'), 'TrueNASStorageTopologyTable');
    expect(enclosingTab(onlyJsxTag(proxmoxFile, 'ProxmoxBackupsTable'))).toBe('backups');
    expect(callProperties(truenasFile, 'useRecoveryPoints').get('platform')).toBe(
      'TRUENAS_PLATFORM_FILTER',
    );
    const protectionHook = findNodes(truenasFile, ts.isVariableDeclaration).find(
      (declaration) => declaration.name.getText() === 'protection',
    );
    expect(protectionHook?.initializer?.getText()).toMatch(/^useRecoveryPoints\(/);
    const protectionTab = onlyJsxTag(truenasFile, 'TrueNASProtection');
    expect(enclosingTab(protectionTab)).toBe('protection');
    expect(jsxAttr(protectionTab, 'recoveryPoints')).toBe('protection');
    const protectionTable = onlyJsxTag(
      functionDecl(truenasFile, 'TrueNASProtection'),
      'TrueNASProtectionTable',
    );
    expect(jsxAttr(protectionTable, 'points')).toBe('props.recoveryPoints.points()');
  });

  it('keeps mobile host tables focused on useful operational columns', () => {
    // Assertions use the canonical kind-based helpers — either
    // getPlatformTableHeadClassForKind('<kind>') on a raw TableHead or the
    // kind="<kind>" prop on the shared PlatformSortableTableHead — so the
    // platform overview tables keep aligned metric and numeric columns
    // across providers.
    expect(dockerHostsTableSource).toMatch(/kind="name"[\s\S]{0,200}?Host/);
    expect(dockerHostsTableSource).toMatch(/kind="metric-bar"[\s\S]{0,200}?CPU/);
    expect(dockerHostsTableSource).toMatch(/kind="metric-bar"[\s\S]{0,300}?Memory/);
    expect(dockerHostsTableSource).toMatch(/kind="metric-bar"[\s\S]{0,200}?Disk/);

    expect(kubernetesClustersTableSource).toMatch(/kind="name"[\s\S]{0,200}?Cluster/);
    expect(kubernetesClustersTableSource).toMatch(
      /sortKey="nodes"[\s\S]{0,180}?<PlatformResponsiveTableLabel compact="Nds" full="Nodes" \/>/,
    );
    expect(kubernetesNodesTableSource).toMatch(/kind="name"[\s\S]{0,200}?Node/);
    expect(kubernetesNodesTableSource).toContain(
      '<span class="md:hidden">{compactCapacityLabel()}</span>',
    );

    expect(truenasSystemsTableSource).toMatch(/kind="name"[\s\S]{0,200}?System/);
    expect(truenasSystemsTableSource).toMatch(
      /<span class="md:hidden">\s*<PlatformTablePercentValue value={storagePercent\(\)} \/>\s*<\/span>/,
    );
    expect(vsphereHostsTableSource).toMatch(/kind="name"[\s\S]{0,200}?Host/);
    expect(vsphereHostsTableSource).toMatch(
      /sortKey="vms"[\s\S]{0,180}?class="platform-table-mobile-w-10 w-\[12%\] md:w-\[4%\]"[\s\S]{0,80}?VMs/,
    );
    // AgentsMachinesTable uses a column-config pattern: kind helpers are
    // applied dynamically in the table render, with labels living in the
    // model. Assert against the model's column declarations.
    expect(agentMachineTableModelSource).toMatch(
      /id:\s*'machine'[\s\S]{0,80}?label:\s*'Machine'[\s\S]{0,80}?kind:\s*'name'/,
    );
    expect(agentMachineTableModelSource).toMatch(
      /id:\s*'cpu'[\s\S]{0,80}?label:\s*'CPU'[\s\S]{0,80}?kind:\s*'metric-bar'/,
    );
    expect(agentMachineTableModelSource).toMatch(
      /id:\s*'memory'[\s\S]{0,80}?label:\s*'Memory'[\s\S]{0,80}?kind:\s*'metric-bar'/,
    );
    expect(agentMachineTableModelSource).toMatch(
      /id:\s*'disk'[\s\S]{0,80}?label:\s*'Disk'[\s\S]{0,80}?kind:\s*'metric-bar'/,
    );
  });
});

describe('PlatformResourceCounter', () => {
  it('keeps what it does not count in the same live status', () => {
    render(() =>
      PlatformResourceCounter({
        visible: 278,
        total: 2981,
        rowNoun: 'restore points',
        detail: '2 running',
      }),
    );
    expect(screen.getByRole('status')).toHaveTextContent('278 of 2981 restore points · 2 running');
  });

  it('shows only the count without a detail', () => {
    render(() => PlatformResourceCounter({ visible: 1, total: 1, rowNoun: 'targets' }));
    expect(screen.getAllByRole('status').at(-1)?.textContent?.trim()).toBe('1 target');
  });
});