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.

47.8 KB
Raw Blame
import { describe, expect, it } from 'vitest';
import type { RecoveryPoint } from '@/types/recovery';
import type { AlertConfig } from '@/types/alerts';
import type { Resource } from '@/types/resource';
import { resolveTrueNASDiskTemperatureDisplayThresholds } from '@/utils/metricThresholds';
import {
  TRUENAS_TAB_SPECS,
  buildTrueNASPageModel,
  buildTrueNASProtectionPosture,
  buildTrueNASServiceRows,
  buildTrueNASStorageChildCounts,
  buildTrueNASStorageTopologyRows,
  buildTrueNASSystemChildCounts,
  filterTrueNASApps,
  filterTrueNASIncidents,
  filterTrueNASProtectionPoints,
  filterTrueNASServices,
  filterTrueNASStorageTopologyRows,
  filterTrueNASStorageTopologyRowsByKind,
  filterTrueNASShares,
  filterTrueNASVMs,
  getTrueNASPageTabSpecs,
  getTrueNASResourceDisplayStatus,
  getTrueNASStorageDotStatus,
  getTrueNASStorageIssue,
  mapTrueNASAppStatus,
  mapTrueNASIncidentSeverity,
  mapTrueNASProtectionKind,
  mapTrueNASProtectionStatus,
  mapTrueNASServiceStatus,
  mapTrueNASShareStatus,
  mapTrueNASStorageStatus,
  mapTrueNASVMStatus,
  sortTrueNASProtectionPoints,
} from '../truenasPageModel';

const makeResource = (resource: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource => ({
  name: resource.id,
  displayName: resource.id,
  platformId: 'lab',
  platformType: 'truenas',
  sourceType: 'api',
  status: 'online',
  lastSeen: 1_700_000_000_000,
  ...resource,
});

const makeRecoveryPoint = (
  point: Partial<RecoveryPoint> & Pick<RecoveryPoint, 'id' | 'kind' | 'mode'>,
): RecoveryPoint => ({
  outcome: 'success',
  platform: 'truenas',
  startedAt: '2026-05-20T00:00:00Z',
  completedAt: '2026-05-20T00:00:00Z',
  ...point,
});

describe('truenasPageModel', () => {
  it('declares the native TrueNAS section set around API facets', () => {
    expect(TRUENAS_TAB_SPECS.map((tab) => tab.id)).toEqual([
      'overview',
      'storage',
      'services',
      'apps',
      'vms',
      'shares',
      'protection',
    ]);
  });

  it('separates volume topology rows from physical disk rows', () => {
    const rows = buildTrueNASStorageTopologyRows([
      makeResource({
        id: 'tank',
        type: 'storage',
        storage: { topology: 'pool', platform: 'truenas' },
      }),
      makeResource({
        id: 'tank-media',
        type: 'storage',
        parentId: 'tank',
        storage: { topology: 'dataset', platform: 'truenas' },
      }),
      makeResource({ id: 'sda', type: 'physical_disk', parentId: 'tank' }),
    ]);

    expect(filterTrueNASStorageTopologyRowsByKind(rows, 'all')).toHaveLength(3);
    expect(filterTrueNASStorageTopologyRowsByKind(rows, 'volumes').map((row) => row.kind)).toEqual([
      'pool',
      'dataset',
    ]);
    expect(filterTrueNASStorageTopologyRowsByKind(rows, 'disks').map((row) => row.kind)).toEqual([
      'disk',
    ]);
  });

  it('shows TrueNAS workflow tabs only when their native facet has inventory', () => {
    const systemOnlyModel = buildTrueNASPageModel([
      makeResource({ id: 'truenas-system', type: 'agent' }),
    ]);
    const inventoryModel = buildTrueNASPageModel([
      makeResource({
        id: 'truenas-system',
        type: 'agent',
        truenas: { services: [{ id: '1', service: 'smb', enabled: true, state: 'RUNNING' }] },
      }),
      makeResource({ id: 'truenas-vm', type: 'vm' }),
      makeResource({ id: 'truenas-app', type: 'app-container' }),
      makeResource({ id: 'truenas-share', type: 'network-share' }),
      makeResource({
        id: 'truenas-pool',
        type: 'storage',
        storage: { topology: 'pool', platform: 'truenas' },
      }),
    ]);

    expect(getTrueNASPageTabSpecs(systemOnlyModel).map((tab) => tab.id)).toEqual([
      'overview',
      'protection',
    ]);
    expect(
      getTrueNASPageTabSpecs(inventoryModel, { hasProtectionInventory: true }).map((tab) => tab.id),
    ).toEqual(['overview', 'storage', 'services', 'apps', 'vms', 'shares', 'protection']);
  });

  it('keeps TrueNAS workflow tabs visible from source-scoped facets on partial routes', () => {
    const activeRouteModel = buildTrueNASPageModel([
      makeResource({ id: 'truenas-system', type: 'agent' }),
    ]);

    expect(
      getTrueNASPageTabSpecs(activeRouteModel, {
        typeCounts: {
          storage: 2,
          'app-container': 1,
          vm: 2,
          'network-share': 3,
        },
      }).map((tab) => tab.id),
    ).toEqual(['overview', 'storage', 'apps', 'vms', 'shares', 'protection']);
  });

  it('buckets systems, workloads, and native storage inventory by TrueNAS API facet', () => {
    const model = buildTrueNASPageModel([
      makeResource({
        id: 'truenas-system',
        type: 'agent',
        truenas: { services: [{ id: '1', service: 'smb', enabled: true, state: 'RUNNING' }] },
      }),
      makeResource({ id: 'truenas-vm', type: 'vm' }),
      makeResource({ id: 'truenas-app', type: 'app-container' }),
      makeResource({ id: 'truenas-share', type: 'network-share' }),
      makeResource({
        id: 'truenas-pool',
        type: 'storage',
        storage: { topology: 'pool', platform: 'truenas' },
      }),
      makeResource({
        id: 'truenas-dataset',
        type: 'storage',
        storage: { topology: 'dataset', platform: 'truenas' },
      }),
      makeResource({ id: 'truenas-disk', type: 'physical_disk' }),
      makeResource({ id: 'docker-host', type: 'agent', platformType: 'docker' }),
      makeResource({ id: 'pve-node', type: 'agent', platformType: 'proxmox-pve' }),
    ]);

    expect(model.systems.map((r) => r.id)).toEqual(['truenas-system']);
    expect(model.shares.map((r) => r.id)).toEqual(['truenas-share']);
    expect(model.vms.map((r) => r.id)).toEqual(['truenas-vm']);
    expect(model.apps.map((r) => r.id)).toEqual(['truenas-app']);
    expect(model.services.map((row) => row.service.service)).toEqual(['smb']);
    expect(model.pools.map((r) => r.id)).toEqual(['truenas-pool']);
    expect(model.datasets.map((r) => r.id)).toEqual(['truenas-dataset']);
    expect(model.disks.map((r) => r.id)).toEqual(['truenas-disk']);
    expect(model.resources.map((r) => r.id).sort()).toEqual(
      [
        'truenas-app',
        'truenas-dataset',
        'truenas-disk',
        'truenas-pool',
        'truenas-share',
        'truenas-system',
        'truenas-vm',
      ].sort(),
    );
  });

  it('counts overview inventory from each TrueNAS system hierarchy', () => {
    const primary = makeResource({
      id: 'system-primary',
      type: 'agent',
      name: 'nas-primary',
      truenas: {
        services: [
          { id: '1', service: 'smb', enabled: true, state: 'RUNNING' },
          { id: '2', service: 'ssh', enabled: false, state: 'STOPPED' },
        ],
      },
    });
    const backup = makeResource({
      id: 'system-backup',
      type: 'agent',
      name: 'nas-backup',
      truenas: { services: [{ id: '1', service: 'nfs', enabled: true, state: 'RUNNING' }] },
    });
    const primaryPool = makeResource({
      id: 'primary-pool-tank',
      type: 'storage',
      name: 'tank',
      parentId: primary.id,
      storage: { topology: 'pool', platform: 'truenas' },
    });
    const backupPool = makeResource({
      id: 'backup-pool-tank',
      type: 'storage',
      name: 'tank',
      parentId: backup.id,
      storage: { topology: 'pool', platform: 'truenas' },
    });
    const primaryDataset = makeResource({
      id: 'primary-dataset-media',
      type: 'storage',
      name: 'tank/media',
      parentId: primaryPool.id,
      storage: { topology: 'dataset', platform: 'truenas' },
    });
    const backupDataset = makeResource({
      id: 'backup-dataset-media',
      type: 'storage',
      name: 'tank/media',
      parentId: backupPool.id,
      storage: { topology: 'dataset', platform: 'truenas' },
    });

    const counts = buildTrueNASSystemChildCounts(
      [
        primary,
        backup,
        primaryPool,
        backupPool,
        primaryDataset,
        backupDataset,
        makeResource({ id: 'primary-share', type: 'network-share', parentId: primaryDataset.id }),
        makeResource({ id: 'backup-share', type: 'network-share', parentId: backupDataset.id }),
        makeResource({ id: 'primary-disk', type: 'physical_disk', parentId: primaryPool.id }),
        makeResource({ id: 'backup-disk', type: 'physical_disk', parentId: backupPool.id }),
        makeResource({ id: 'primary-vm', type: 'vm', parentId: primary.id }),
        makeResource({ id: 'backup-vm', type: 'vm', parentId: backup.id }),
        makeResource({ id: 'primary-app', type: 'app-container', parentId: primary.id }),
        makeResource({ id: 'backup-app', type: 'app-container', parentId: backup.id }),
      ],
      [primary, backup],
    );

    expect(counts.get(primary.id)).toEqual({
      pools: 1,
      datasets: 1,
      shares: 1,
      vms: 1,
      apps: 1,
      disks: 1,
      services: 2,
    });
    expect(counts.get(backup.id)).toEqual({
      pools: 1,
      datasets: 1,
      shares: 1,
      vms: 1,
      apps: 1,
      disks: 1,
      services: 1,
    });
  });

  it('keeps the single-system inventory fallback for older unparented TrueNAS resources', () => {
    const system = makeResource({
      id: 'system-primary',
      type: 'agent',
      truenas: { services: [{ id: '1', service: 'smb', enabled: true, state: 'RUNNING' }] },
    });
    const counts = buildTrueNASSystemChildCounts(
      [
        system,
        makeResource({ id: 'pool-tank', type: 'storage', storage: { topology: 'pool' } }),
        makeResource({ id: 'dataset-media', type: 'storage', storage: { topology: 'dataset' } }),
        makeResource({ id: 'share-media', type: 'network-share' }),
        makeResource({ id: 'disk-sda', type: 'physical_disk' }),
        makeResource({ id: 'vm-windows', type: 'vm' }),
        makeResource({ id: 'app-nextcloud', type: 'app-container' }),
      ],
      [system],
    );

    expect(counts.get(system.id)).toEqual({
      pools: 1,
      datasets: 1,
      shares: 1,
      vms: 1,
      apps: 1,
      disks: 1,
      services: 1,
    });
  });

  it('counts unparented TrueNAS inventory in mixed single-system snapshots', () => {
    const system = makeResource({
      id: 'system-primary',
      type: 'agent',
      truenas: { services: [{ id: '1', service: 'smb', enabled: true, state: 'RUNNING' }] },
    });
    const pool = makeResource({
      id: 'pool-tank',
      type: 'storage',
      parentId: system.id,
      storage: { topology: 'pool', platform: 'truenas' },
    });
    const dataset = makeResource({
      id: 'dataset-media',
      type: 'storage',
      parentId: pool.id,
      storage: { topology: 'dataset', platform: 'truenas' },
    });

    const counts = buildTrueNASSystemChildCounts(
      [
        system,
        pool,
        dataset,
        makeResource({ id: 'share-media', type: 'network-share' }),
        makeResource({ id: 'disk-sda', type: 'physical_disk' }),
        makeResource({ id: 'vm-windows', type: 'vm' }),
        makeResource({ id: 'app-nextcloud', type: 'app-container' }),
      ],
      [system],
    );

    expect(counts.get(system.id)).toEqual({
      pools: 1,
      datasets: 1,
      shares: 1,
      vms: 1,
      apps: 1,
      disks: 1,
      services: 1,
    });
  });

  it('builds and filters native TrueNAS service rows from system metadata', () => {
    const system = makeResource({
      id: 'system-primary',
      type: 'agent',
      name: 'nas-primary',
      truenas: {
        hostname: 'nas-primary',
        services: [
          { id: '1', service: 'smb', enabled: true, state: 'RUNNING', pids: [2418, 2420] },
          { id: '2', service: 'ssh', enabled: false, state: 'STOPPED' },
          { id: '3', service: 'smartd', enabled: true, state: 'STOPPED' },
        ],
      },
    });

    const rows = buildTrueNASServiceRows([system]);

    expect(rows.map((row) => row.service.service)).toEqual(['smartd', 'ssh', 'smb']);
    expect(mapTrueNASServiceStatus(rows[0])).toBe('stopped');
    expect(mapTrueNASServiceStatus(rows[1])).toBe('disabled');
    expect(mapTrueNASServiceStatus(rows[2])).toBe('running');
    expect(
      mapTrueNASServiceStatus({
        ...rows[2],
        system: {
          ...system,
          platformData: { sourceStatus: { truenas: { status: 'offline' } } },
        },
      }),
    ).toBe('attention');
    expect(filterTrueNASServices(rows, 'nas-primary', 'all')).toHaveLength(3);
    expect(filterTrueNASServices(rows, 'smb', 'running').map((row) => row.service.service)).toEqual(
      ['smb'],
    );
    expect(filterTrueNASServices(rows, '', 'disabled').map((row) => row.service.service)).toEqual([
      'ssh',
    ]);
  });

  it('builds a native TrueNAS storage topology with pool child counts', () => {
    const system = makeResource({ id: 'system-primary', type: 'agent' });
    const pool = makeResource({
      id: 'pool-tank',
      type: 'storage',
      name: 'tank',
      parentId: system.id,
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },
    });
    const dataset = makeResource({
      id: 'dataset-media',
      type: 'storage',
      name: 'tank/media',
      parentId: pool.id,
      storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media' },
    });
    const share = makeResource({
      id: 'share-media',
      type: 'network-share',
      parentId: dataset.id,
      truenas: {
        share: {
          id: 'smb-1',
          name: 'Media',
          protocol: 'SMB',
          path: '/mnt/tank/media',
          dataset: 'tank/media',
        },
      },
    });
    const disk = makeResource({
      id: 'disk-sda',
      type: 'physical_disk',
      name: 'sda',
      parentId: pool.id,
      physicalDisk: {
        devPath: '/dev/sda',
        serial: 'serial-123',
        sizeBytes: 2_000_000_000_000,
        health: 'PASSED',
      },
    });

    const counts = buildTrueNASStorageChildCounts([system, pool, dataset, share, disk]);
    const rows = buildTrueNASStorageTopologyRows([system, pool, dataset, share, disk]);

    expect(counts.get(pool.id)).toEqual({ datasets: 1, shares: 1, disks: 1 });
    expect(counts.get(dataset.id)).toEqual({ datasets: 0, shares: 1, disks: 0 });
    expect(rows.map((row) => row.id)).toEqual([
      'pool:pool-tank',
      'dataset:dataset-media',
      'disk:disk-sda',
    ]);
    expect(rows.map((row) => row.depth)).toEqual([0, 1, 1]);
    expect(rows[1]?.parentRowId).toBe('pool:pool-tank');
    expect(rows[2]?.parentRowId).toBe('pool:pool-tank');
  });

  it('infers TrueNAS storage topology ownership from native pool and dataset labels', () => {
    const archivePool = makeResource({
      id: 'pool-archive',
      type: 'storage',
      name: 'archive',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },
    });
    const tankPool = makeResource({
      id: 'pool-tank',
      type: 'storage',
      name: 'tank',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },
    });
    const dataset = makeResource({
      id: 'dataset-media',
      type: 'storage',
      name: 'tank/media',
      storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media' },
    });
    const share = makeResource({
      id: 'share-media',
      type: 'network-share',
      truenas: {
        share: {
          id: 'smb-1',
          name: 'Media',
          protocol: 'SMB',
          path: '/mnt/tank/media',
          dataset: 'tank/media',
        },
      },
    });
    const disk = makeResource({
      id: 'disk-sda',
      type: 'physical_disk',
      name: 'sda',
      physicalDisk: {
        storageGroup: 'tank',
        devPath: '/dev/sda',
        serial: 'serial-123',
        health: 'PASSED',
      },
    });

    const resources = [archivePool, tankPool, dataset, share, disk];
    const counts = buildTrueNASStorageChildCounts(resources);
    const rows = buildTrueNASStorageTopologyRows(resources);

    expect(counts.get(archivePool.id)).toEqual({ datasets: 0, shares: 0, disks: 0 });
    expect(counts.get(tankPool.id)).toEqual({ datasets: 1, shares: 1, disks: 1 });
    expect(counts.get(dataset.id)).toEqual({ datasets: 0, shares: 1, disks: 0 });
    expect(rows.map((row) => row.id)).toEqual([
      'pool:pool-archive',
      'pool:pool-tank',
      'dataset:dataset-media',
      'disk:disk-sda',
    ]);
    expect(rows[2]?.parentRowId).toBe('pool:pool-tank');
    expect(rows[3]?.parentRowId).toBe('pool:pool-tank');
  });

  it('nests TrueNAS datasets under the closest dataset path ancestor', () => {
    const pool = makeResource({
      id: 'pool-tank',
      type: 'storage',
      name: 'tank',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },
    });
    const media = makeResource({
      id: 'dataset-media',
      type: 'storage',
      name: 'tank/media',
      storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media' },
    });
    const photos = makeResource({
      id: 'dataset-photos',
      type: 'storage',
      name: 'tank/media/photos',
      storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media/photos' },
    });
    const raw = makeResource({
      id: 'dataset-raw',
      type: 'storage',
      name: 'tank/media/photos/raw',
      storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media/photos/raw' },
    });
    const share = makeResource({
      id: 'share-raw',
      type: 'network-share',
      truenas: {
        share: {
          id: 'smb-raw',
          name: 'Raw Photos',
          protocol: 'SMB',
          path: '/mnt/tank/media/photos/raw',
          dataset: 'tank/media/photos/raw',
        },
      },
    });

    const resources = [pool, raw, media, photos, share];
    const counts = buildTrueNASStorageChildCounts(resources);
    const rows = buildTrueNASStorageTopologyRows(resources);

    expect(counts.get(pool.id)).toEqual({ datasets: 3, shares: 1, disks: 0 });
    expect(counts.get(media.id)).toEqual({ datasets: 2, shares: 1, disks: 0 });
    expect(counts.get(photos.id)).toEqual({ datasets: 1, shares: 1, disks: 0 });
    expect(counts.get(raw.id)).toEqual({ datasets: 0, shares: 1, disks: 0 });
    expect(rows.map((row) => [row.id, row.depth, row.parentRowId])).toEqual([
      ['pool:pool-tank', 0, undefined],
      ['dataset:dataset-media', 1, 'pool:pool-tank'],
      ['dataset:dataset-photos', 2, 'dataset:dataset-media'],
      ['dataset:dataset-raw', 3, 'dataset:dataset-photos'],
    ]);
    expect(filterTrueNASStorageTopologyRows(rows, 'raw', 'all').map((row) => row.id)).toEqual([
      'pool:pool-tank',
      'dataset:dataset-media',
      'dataset:dataset-photos',
      'dataset:dataset-raw',
    ]);
  });

  it('keeps pool ancestors visible when filtering matching storage children', () => {
    const pool = makeResource({
      id: 'pool-tank',
      type: 'storage',
      name: 'tank',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },
    });
    const degradedPool = makeResource({
      id: 'pool-archive',
      type: 'storage',
      name: 'archive',
      status: 'online',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'DEGRADED' },
    });
    const disk = makeResource({
      id: 'disk-sdb',
      type: 'physical_disk',
      name: 'sdb',
      parentId: pool.id,
      physicalDisk: {
        devPath: '/dev/sdb',
        serial: 'serial-degraded',
        health: 'DEGRADED',
      },
    });

    expect(mapTrueNASStorageStatus(degradedPool)).toBe('attention');
    expect(mapTrueNASStorageStatus(disk)).toBe('attention');

    const staleConnectionPool = makeResource({
      id: 'pool-stale',
      type: 'storage',
      name: 'stale',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },
      platformData: { sourceStatus: { truenas: { status: 'stale' } } },
    });

    expect(getTrueNASResourceDisplayStatus(staleConnectionPool)).toBe('degraded');
    expect(mapTrueNASStorageStatus(staleConnectionPool)).toBe('attention');

    const rows = buildTrueNASStorageTopologyRows([pool, degradedPool, disk]);
    expect(
      filterTrueNASStorageTopologyRows(rows, 'serial-degraded', 'attention').map((row) => row.id),
    ).toEqual(['pool:pool-tank', 'disk:disk-sdb']);
  });

  it('does not flag unknown disk health as attention', () => {
    // The TrueNAS disk API has no SMART/health field, so "unknown" is the
    // normal state of a healthy disk, not a warning signal (#1573).
    const unknownDisk = makeResource({
      id: 'disk-unknown',
      type: 'physical_disk',
      name: 'ada0',
      status: 'unknown',
      physicalDisk: { devPath: '/dev/ada0', serial: 'serial-unknown', health: 'UNKNOWN' },
    });
    expect(mapTrueNASStorageStatus(unknownDisk)).toBe('unknown');

    const healthyByState = makeResource({
      id: 'disk-online',
      type: 'physical_disk',
      name: 'ada1',
      status: 'online',
      physicalDisk: { devPath: '/dev/ada1', serial: 'serial-online', health: 'PASSED' },
    });
    expect(mapTrueNASStorageStatus(healthyByState)).toBe('healthy');
  });

  it('flags a disk whose current reading reaches its alert trigger', () => {
    // Disk risk carries no heat, so a hot disk stays `online`; the page judges
    // it by the alert disk temperature thresholds, as Physical Disks does.
    const resolveFactory = (disk: Pick<Resource, 'id' | 'physicalDisk'>) =>
      resolveTrueNASDiskTemperatureDisplayThresholds(null, disk.physicalDisk?.diskType, disk.id);
    const hotDisk = makeResource({
      id: 'disk-hot',
      type: 'physical_disk',
      name: 'sda',
      status: 'online',
      physicalDisk: {
        devPath: '/dev/sda',
        serial: 'serial-hot',
        diskType: 'sata',
        health: 'UNKNOWN',
        temperature: 56,
      },
    });
    expect(mapTrueNASStorageStatus(hotDisk, resolveFactory)).toBe('attention');
    expect(getTrueNASStorageIssue(hotDisk, resolveFactory)).toEqual({
      status: 'attention',
      label: 'Attention',
      reasons: ['Disk temperature is 56°C, at or above its 55°C alert threshold.'],
    });
    // A cool sibling that sorts first by name: heat moves the hot disk ahead
    // of it, and the status filter splits them.
    const coolDisk = makeResource({
      ...hotDisk,
      id: 'disk-cool',
      name: 'ada0',
      physicalDisk: { ...hotDisk.physicalDisk!, serial: 'serial-cool', temperature: 40 },
    });
    const rows = buildTrueNASStorageTopologyRows([coolDisk, hotDisk], resolveFactory);
    expect(rows.map((row) => row.id)).toEqual(['disk:disk-hot', 'disk:disk-cool']);
    expect(buildTrueNASStorageTopologyRows([coolDisk, hotDisk]).map((row) => row.id)).toEqual([
      'disk:disk-cool',
      'disk:disk-hot',
    ]);
    expect(
      filterTrueNASStorageTopologyRows(rows, '', 'attention', resolveFactory).map((row) => row.id),
    ).toEqual(['disk:disk-hot']);
    expect(
      filterTrueNASStorageTopologyRows(rows, '', 'healthy', resolveFactory).map((row) => row.id),
    ).toEqual(['disk:disk-cool']);

    // Native TrueNAS alert text leads, and the heat reason stays listed.
    const hotWithIncident = makeResource({
      ...hotDisk,
      incidents: [{ code: 'truenas_smart', severity: 'info', summary: 'SMART test scheduled' }],
    });
    expect(getTrueNASStorageIssue(hotWithIncident, resolveFactory)?.reasons).toEqual([
      'SMART test scheduled',
      'Disk temperature is 56°C, at or above its 55°C alert threshold.',
    ]);

    // An NVMe at 63C is under its 70C trigger.
    const warmNVMe = makeResource({
      ...hotDisk,
      id: 'disk-nvme',
      physicalDisk: { ...hotDisk.physicalDisk!, diskType: 'nvme', temperature: 63 },
    });
    expect(mapTrueNASStorageStatus(warmNVMe, resolveFactory)).toBe('healthy');
    // A trigger the user raised, alerting switched off, and a retained reading
    // are never heat.
    expect(mapTrueNASStorageStatus(hotDisk, () => ({ warning: 55, critical: 60 }))).toBe('healthy');
    expect(mapTrueNASStorageStatus(hotDisk, () => null)).toBe('healthy');
    const retained = makeResource({
      ...hotDisk,
      physicalDisk: {
        ...hotDisk.physicalDisk!,
        collection: { temperature: { state: 'unavailable', source: 'truenas', reason: 'stale' } },
      },
    });
    expect(mapTrueNASStorageStatus(retained, resolveFactory)).toBe('healthy');
  });

  it('judges disk heat by the override and TrueNAS-wide value its alert uses', () => {
    const config = {
      enabled: true,
      guestDefaults: {},
      nodeDefaults: {},
      agentDefaults: { diskTemperature: { trigger: 55, clear: 50 } },
      diskTempByType: { nvme: { trigger: 70, clear: 65 }, sata: { trigger: 55, clear: 50 } },
      storageDefault: { trigger: 85, clear: 80 },
      overrides: { 'disk-raised': { temperature: { trigger: 75, clear: 70 } } },
    } as AlertConfig;
    const resolveWith = (cfg: AlertConfig) => (disk: Pick<Resource, 'id' | 'physicalDisk'>) =>
      resolveTrueNASDiskTemperatureDisplayThresholds(cfg, disk.physicalDisk?.diskType, disk.id);
    const nvmeDisk = (id: string, temperature: number) =>
      makeResource({
        id,
        type: 'physical_disk',
        name: id,
        status: 'online',
        physicalDisk: {
          devPath: `/dev/${id}`,
          serial: `serial-${id}`,
          diskType: 'nvme',
          health: 'UNKNOWN',
          temperature,
        },
      });

    // At 72C an NVMe is past its 70C type trigger, but the disk whose own
    // override raised its alert to 75C will not alert, so it is not heat.
    const plain = nvmeDisk('disk-plain', 72);
    const raised = nvmeDisk('disk-raised', 72);
    expect(mapTrueNASStorageStatus(plain, resolveWith(config))).toBe('attention');
    expect(mapTrueNASStorageStatus(raised, resolveWith(config))).toBe('healthy');
    expect(getTrueNASStorageIssue(raised, resolveWith(config))).toBeNull();
    expect(
      getTrueNASStorageIssue(nvmeDisk('disk-raised', 76), resolveWith(config))?.reasons,
    ).toEqual(['Disk temperature is 76°C, at or above its 75°C alert threshold.']);

    // A TrueNAS-wide 62C applies to every disk without its own override.
    const trueNASWide = {
      ...config,
      truenasDiskDefaults: { temperature: { trigger: 62, clear: 57 } },
    } as AlertConfig;
    const warm = nvmeDisk('disk-warm', 64);
    expect(mapTrueNASStorageStatus(warm, resolveWith(config))).toBe('healthy');
    expect(getTrueNASStorageIssue(warm, resolveWith(trueNASWide))?.reasons).toEqual([
      'Disk temperature is 64°C, at or above its 62°C alert threshold.',
    ]);
    expect(mapTrueNASStorageStatus(raised, resolveWith(trueNASWide))).toBe('healthy');
    // Switched off TrueNAS-wide, no disk without an override is heat.
    const trueNASOff = {
      ...config,
      truenasDiskDefaults: { temperature: { trigger: 0, clear: 0 } },
    } as AlertConfig;
    expect(mapTrueNASStorageStatus(plain, resolveWith(trueNASOff))).toBe('healthy');
    expect(getTrueNASStorageDotStatus(plain, resolveWith(trueNASOff))).toBe('online');
    expect(getTrueNASStorageDotStatus(plain, resolveWith(config))).toBe('warning');
  });

  it('renders expected receive-side replication readonly posture as healthy', () => {
    const replicatedDataset = makeResource({
      id: 'dataset-replica',
      type: 'storage',
      name: 'backup/replicas',
      status: 'online',
      tags: ['truenas', 'dataset', 'zfs', 'state:replication-readonly'],
      storage: { topology: 'dataset', platform: 'truenas' },
    });

    expect(mapTrueNASStorageStatus(replicatedDataset)).toBe('healthy');
    const row = buildTrueNASStorageTopologyRows([replicatedDataset])[0];
    expect(row?.kind).toBe('dataset');
    expect(row && mapTrueNASStorageStatus(row.resource)).toBe('healthy');
  });

  it('explains non-healthy storage with TrueNAS alert text first and stays silent when healthy', () => {
    const healthyPool = makeResource({
      id: 'pool-tank',
      type: 'storage',
      name: 'tank',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },
    });
    expect(getTrueNASStorageIssue(healthyPool)).toBeNull();

    const poolRisk = {
      level: 'warning',
      reasons: [
        { code: 'zfs_pool_state', severity: 'warning', summary: 'ZFS pool archive is DEGRADED' },
      ],
    };
    // A pool carries its own alert plus the disk alerts the provider copies onto it.
    const degradedPool = makeResource({
      id: 'pool-archive',
      type: 'storage',
      name: 'archive',
      status: 'warning',
      incidents: [
        {
          code: 'truenas_volume_status',
          severity: 'warning',
          summary: 'Pool archive is DEGRADED: one member of mirror-0 is faulted.',
        },
        {
          code: 'truenas_smart',
          severity: 'warning',
          summary: 'Device /dev/sdc has SMART test failures.',
        },
      ],
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'DEGRADED', risk: poolRisk },
    });
    expect(getTrueNASStorageIssue(degradedPool)).toEqual({
      status: 'attention',
      label: 'Attention',
      reasons: [
        'Pool archive is DEGRADED: one member of mirror-0 is faulted.',
        'Device /dev/sdc has SMART test failures.',
      ],
    });

    // Without a TrueNAS alert, Pulse's own risk summary explains the row.
    const riskOnlyPool = makeResource({
      id: 'pool-risk',
      type: 'storage',
      name: 'archive',
      status: 'warning',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'DEGRADED', risk: poolRisk },
    });
    expect(getTrueNASStorageIssue(riskOnlyPool)?.reasons).toEqual(['ZFS pool archive is DEGRADED']);

    const failingDisk = makeResource({
      id: 'disk-sdc',
      type: 'physical_disk',
      name: 'sdc',
      status: 'warning',
      incidents: [
        {
          code: 'truenas_smart',
          severity: 'warning',
          summary: 'Device /dev/sdc has SMART test failures.',
        },
        {
          code: 'truenas_smart',
          severity: 'warning',
          summary: 'Device  /dev/sdc has SMART test failures',
        },
      ],
      physicalDisk: {
        devPath: '/dev/sdc',
        health: 'DEGRADED',
        risk: {
          level: 'warning',
          reasons: [
            {
              code: 'truenas_disk_state',
              severity: 'warning',
              summary: 'TrueNAS disk sdc is DEGRADED',
            },
          ],
        },
      },
    });
    // The repeat differs only in spacing and its full stop, so it folds in, and
    // the derived disk-state summary waits behind the native alert.
    expect(getTrueNASStorageIssue(failingDisk)?.reasons).toEqual([
      'Device /dev/sdc has SMART test failures.',
    ]);

    const readOnlyDataset = makeResource({
      id: 'dataset-cold',
      type: 'storage',
      name: 'archive/cold',
      status: 'warning',
      tags: ['truenas', 'dataset', 'zfs', 'state:readonly'],
      storage: { topology: 'dataset', platform: 'truenas' },
    });
    expect(getTrueNASStorageIssue(readOnlyDataset)?.reasons).toEqual(['Dataset is read-only']);

    // The provider raises its own incident for a locked dataset, which wins
    // over the state tag instead of being repeated by it.
    const lockedDataset = makeResource({
      id: 'dataset-vault',
      type: 'storage',
      name: 'vault/secrets',
      status: 'offline',
      tags: ['truenas', 'dataset', 'zfs', 'state:locked'],
      incidents: [
        {
          code: 'zfs_dataset_locked',
          severity: 'warning',
          summary: 'ZFS dataset vault/secrets is locked and unavailable',
        },
      ],
      storage: { topology: 'dataset', platform: 'truenas' },
    });
    expect(getTrueNASStorageIssue(lockedDataset)).toEqual({
      status: 'offline',
      label: 'Offline',
      reasons: ['ZFS dataset vault/secrets is locked and unavailable'],
    });
    const lockedWithoutIncident = makeResource({
      id: 'dataset-vault-tag',
      type: 'storage',
      name: 'vault/keys',
      status: 'offline',
      tags: ['truenas', 'dataset', 'zfs', 'state:locked'],
      storage: { topology: 'dataset', platform: 'truenas' },
    });
    expect(getTrueNASStorageIssue(lockedWithoutIncident)?.reasons).toEqual(['Dataset is locked']);

    const bareDegradedPool = makeResource({
      id: 'pool-bare',
      type: 'storage',
      name: 'bare',
      storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'degraded' },
    });
    expect(getTrueNASStorageIssue(bareDegradedPool)?.reasons).toEqual(['Pool state DEGRADED']);

    // Stale TrueNAS data is the cause even when the pool also has other news.
    const staleConnectionPool = makeResource({
      id: 'pool-stale',
      type: 'storage',
      name: 'stale',
      storage: {
        topology: 'pool',
        platform: 'truenas',
        zfsPoolState: 'ONLINE',
        risk: {
          level: 'info',
          reasons: [
            {
              code: 'zfs_scan_running',
              severity: 'info',
              summary: 'ZFS pool stale scrub is running',
            },
          ],
        },
      },
      platformData: { sourceStatus: { truenas: { status: 'stale' } } },
    });
    expect(getTrueNASStorageIssue(staleConnectionPool)?.reasons).toEqual([
      'TrueNAS has not updated this recently',
      'ZFS pool stale scrub is running',
    ]);

    const unknownDisk = makeResource({
      id: 'disk-unknown',
      type: 'physical_disk',
      name: 'ada0',
      status: 'unknown',
      physicalDisk: { devPath: '/dev/ada0', health: 'UNKNOWN' },
    });
    expect(getTrueNASStorageIssue(unknownDisk)).toEqual({
      status: 'unknown',
      label: 'Unknown',
      reasons: ['TrueNAS has not reported a state for this'],
    });

    const silentOfflinePool = makeResource({
      id: 'pool-gone',
      type: 'storage',
      name: 'gone',
      status: 'offline',
      storage: { topology: 'pool', platform: 'truenas' },
    });
    expect(getTrueNASStorageIssue(silentOfflinePool)?.reasons).toEqual([
      'Offline, and TrueNAS gave no reason',
    ]);
  });

  it('filters apps using native TrueNAS app.query metadata', () => {
    const nextcloud = makeResource({
      id: 'app-nextcloud',
      type: 'app-container',
      parentName: 'truenas-main',
      truenas: {
        hostname: 'truenas-main',
        app: {
          id: 'nextcloud',
          name: 'Nextcloud',
          state: 'RUNNING',
          humanVersion: '29.0.7',
          images: ['docker.io/library/nextcloud:29.0.7'],
          usedPorts: [
            {
              containerPort: 443,
              protocol: 'tcp',
              hostPorts: [{ hostPort: 30443, hostIp: '0.0.0.0' }],
            },
          ],
          volumes: [{ source: '/mnt/tank/apps/nextcloud', destination: '/var/www/html' }],
        },
      },
    });
    const adguard = makeResource({
      id: 'app-adguard',
      type: 'app-container',
      status: 'offline',
      truenas: {
        app: {
          id: 'adguard',
          name: 'AdGuard Home',
          state: 'STOPPED',
          images: ['docker.io/adguard/adguardhome:v0.107'],
        },
      },
    });

    expect(mapTrueNASAppStatus(nextcloud)).toBe('running');
    expect(mapTrueNASAppStatus(adguard)).toBe('stopped');
    expect(
      mapTrueNASAppStatus({
        ...nextcloud,
        platformData: { sourceStatus: { truenas: { status: 'offline' } } },
      }),
    ).toBe('attention');
    expect(filterTrueNASApps([nextcloud, adguard], '30443', 'all').map((r) => r.id)).toEqual([
      'app-nextcloud',
    ]);
    expect(
      filterTrueNASApps([nextcloud, adguard], 'adguardhome', 'stopped').map((r) => r.id),
    ).toEqual(['app-adguard']);
  });

  it('filters VMs using native TrueNAS vm.query metadata', () => {
    const windows = makeResource({
      id: 'vm-windows',
      type: 'vm',
      truenas: {
        hostname: 'truenas-main',
        vm: {
          id: '42',
          name: 'windows-lab',
          description: 'Build validation workstation',
          state: 'RUNNING',
          bootloader: 'UEFI',
          cpuMode: 'HOST-PASSTHROUGH',
          uuid: 'vm-uuid-1',
        },
      },
    });
    const ubuntu = makeResource({
      id: 'vm-ubuntu',
      type: 'vm',
      status: 'offline',
      truenas: {
        vm: {
          id: '43',
          name: 'ubuntu-build',
          state: 'STOPPED',
          machineType: 'q35',
        },
      },
    });

    expect(mapTrueNASVMStatus(windows)).toBe('running');
    expect(mapTrueNASVMStatus(ubuntu)).toBe('stopped');
    expect(
      mapTrueNASVMStatus({
        ...windows,
        platformData: { sourceStatus: { truenas: { status: 'error' } } },
      }),
    ).toBe('attention');
    expect(filterTrueNASVMs([windows, ubuntu], 'passthrough', 'running').map((r) => r.id)).toEqual([
      'vm-windows',
    ]);
    expect(filterTrueNASVMs([windows, ubuntu], 'q35', 'stopped').map((r) => r.id)).toEqual([
      'vm-ubuntu',
    ]);
  });

  it('filters shares using native TrueNAS SMB and NFS metadata', () => {
    const media = makeResource({
      id: 'share-media',
      type: 'network-share',
      truenas: {
        hostname: 'truenas-main',
        share: {
          id: 'smb-1',
          name: 'Media',
          protocol: 'SMB',
          path: '/mnt/tank/media',
          dataset: 'tank/media',
          enabled: true,
          browsable: true,
          auditEnabled: true,
          aliases: ['media'],
        },
      },
    });
    const archive = makeResource({
      id: 'share-archive',
      type: 'network-share',
      status: 'offline',
      truenas: {
        share: {
          id: 'nfs-2',
          name: 'Archive',
          protocol: 'NFS',
          path: '/mnt/tank/archive',
          dataset: 'tank/archive',
          enabled: false,
          readOnly: true,
          networks: ['10.10.20.0/24'],
          security: ['SYS'],
        },
      },
    });

    expect(mapTrueNASShareStatus(media)).toBe('active');
    expect(mapTrueNASShareStatus(archive)).toBe('disabled');
    expect(
      mapTrueNASShareStatus({
        ...media,
        platformData: { sourceStatus: { truenas: { status: 'unknown' } } },
      }),
    ).toBe('attention');
    expect(filterTrueNASShares([media, archive], 'audit', 'active').map((r) => r.id)).toEqual([
      'share-media',
    ]);
    expect(
      filterTrueNASShares([media, archive], '10.10.20.0/24', 'disabled').map((r) => r.id),
    ).toEqual(['share-archive']);
  });

  it('derives native TrueNAS alert rows from resource incidents', () => {
    const system = makeResource({
      id: 'truenas-system',
      type: 'agent',
      incidentCount: 2,
      incidentSeverity: 'critical',
      incidentLabel: 'Storage Health Issue',
      incidentAction: 'Investigate storage health immediately',
      incidents: [
        {
          provider: 'truenas',
          nativeId: 'alert-system',
          code: 'truenas_volume_status',
          severity: 'CRITICAL',
          source: 'VolumeStatus',
          summary: 'Pool tank is FAULTED',
          startedAt: '2026-05-20T12:00:00Z',
        },
      ],
    });
    const disk = makeResource({
      id: 'truenas-disk-sda',
      type: 'physical_disk',
      parentName: 'tank',
      incidentCount: 1,
      incidentSeverity: 'warning',
      incidentLabel: 'Disk Health Issue',
      incidents: [
        {
          provider: 'truenas',
          nativeId: 'alert-smart',
          code: 'truenas_smart',
          severity: 'WARNING',
          source: 'SMART',
          summary: 'Device /dev/sda has unreadable sectors',
        },
      ],
    });
    const poolRollup = makeResource({
      id: 'truenas-pool-archive',
      type: 'storage',
      incidentCount: 1,
      incidentSeverity: 'warning',
      incidentCode: 'truenas_scrub',
      incidentLabel: 'Scrub Issue',
      incidentSummary: 'Last scrub found checksum errors',
    });
    const dockerIncident = makeResource({
      id: 'docker-host',
      type: 'agent',
      platformType: 'docker',
      incidentCount: 1,
      incidentSummary: 'Docker incident should not appear',
    });

    const model = buildTrueNASPageModel([system, disk, poolRollup, dockerIncident]);

    expect(model.incidents.map((incident) => incident.resourceId)).toEqual([
      'truenas-system',
      'truenas-disk-sda',
      'truenas-pool-archive',
    ]);
    expect(model.incidents[0]).toMatchObject({
      severityBucket: 'critical',
      code: 'truenas_volume_status',
      summary: 'Pool tank is FAULTED',
      action: 'Investigate storage health immediately',
    });
    expect(model.incidents[2]).toMatchObject({
      id: 'truenas-pool-archive:incident:rollup',
      code: 'truenas_scrub',
      summary: 'Last scrub found checksum errors',
    });
    expect(mapTrueNASIncidentSeverity('WARNING')).toBe('warning');
    expect(
      filterTrueNASIncidents(model.incidents, 'smart', 'warning').map(
        (incident) => incident.resourceId,
      ),
    ).toEqual(['truenas-disk-sda']);
  });

  it('classifies and filters TrueNAS protection points from canonical recovery payloads', () => {
    const snapshot = makeRecoveryPoint({
      id: 'snapshot-tank-apps',
      kind: 'snapshot',
      mode: 'snapshot',
      display: {
        itemLabel: 'tank/apps',
        detailsSummary: 'auto-20260331-0600',
        nodeHostLabel: 'truenas-main',
      },
      itemRef: { type: 'truenas-dataset', name: 'tank/apps', id: 'tank/apps' },
      details: {
        dataset: 'tank/apps',
        fullName: 'tank/apps@auto-20260331-0600',
        hostname: 'truenas-main',
        snapshot: 'auto-20260331-0600',
      },
    });
    const replication = makeRecoveryPoint({
      id: 'replicate-tank-apps',
      kind: 'backup',
      mode: 'remote',
      outcome: 'running',
      display: {
        itemLabel: 'tank/apps',
        repositoryLabel: 'vault/compliance/tank_apps',
        detailsSummary: 'replicate-tank-apps (tank/apps@auto-20260331-0600)',
      },
      repositoryRef: {
        type: 'truenas-dataset',
        name: 'vault/compliance/tank_apps',
        id: 'vault/compliance/tank_apps',
      },
      details: {
        direction: 'PUSH',
        lastSnapshot: 'tank/apps@auto-20260331-0600',
        lastState: 'RUNNING',
        sourceDatasets: ['tank/apps'],
        targetDataset: 'vault/compliance/tank_apps',
        taskId: 'rep-task-tank-apps',
        taskName: 'replicate-tank-apps',
      },
    });
    const legacyReplication = makeRecoveryPoint({
      id: 'legacy-task',
      kind: 'other',
      mode: 'local',
      outcome: 'warning',
      details: {
        targetDataset: 'offsite/archive_backups',
        taskName: 'replicate-archive-backups',
      },
    });

    expect(mapTrueNASProtectionKind(snapshot)).toBe('snapshot');
    expect(mapTrueNASProtectionKind(replication)).toBe('replication');
    expect(mapTrueNASProtectionKind(legacyReplication)).toBe('replication');
    expect(mapTrueNASProtectionStatus(replication)).toBe('running');
    expect(mapTrueNASProtectionStatus(legacyReplication)).toBe('warning');
    expect(buildTrueNASProtectionPosture([snapshot, replication, legacyReplication])).toEqual({
      healthy: 1,
      warning: 1,
      failed: 0,
      running: 1,
      unknown: 0,
      attention: 1,
    });

    expect(
      filterTrueNASProtectionPoints(
        [snapshot, replication, legacyReplication],
        'vault',
        'running',
      ).map((point) => point.id),
    ).toEqual(['replicate-tank-apps']);
    expect(
      filterTrueNASProtectionPoints(
        [snapshot, replication, legacyReplication],
        'auto-20260331',
        'all',
      ).map((point) => point.id),
    ).toEqual(['snapshot-tank-apps', 'replicate-tank-apps']);
    expect(
      filterTrueNASProtectionPoints(
        [snapshot, replication, legacyReplication],
        'replication',
        'all',
      ).map((point) => point.id),
    ).toEqual(['replicate-tank-apps', 'legacy-task']);
    expect(
      filterTrueNASProtectionPoints(
        [snapshot, replication, legacyReplication],
        '',
        'attention',
      ).map((point) => point.id),
    ).toEqual(['legacy-task']);
  });

  it('orders TrueNAS protection points by latest recovery timestamp', () => {
    const older = makeRecoveryPoint({
      id: 'older-snapshot',
      kind: 'snapshot',
      mode: 'snapshot',
      completedAt: '2026-05-19T00:00:00Z',
    });
    const newer = makeRecoveryPoint({
      id: 'newer-replication',
      kind: 'backup',
      mode: 'remote',
      completedAt: '2026-05-21T00:00:00Z',
    });

    expect(sortTrueNASProtectionPoints([older, newer]).map((point) => point.id)).toEqual([
      'newer-replication',
      'older-snapshot',
    ]);
  });

  it('orders failed and warning protection events ahead of newer routine activity', () => {
    const healthy = makeRecoveryPoint({
      id: 'newer-healthy-snapshot',
      kind: 'snapshot',
      mode: 'snapshot',
      outcome: 'success',
      completedAt: '2026-05-21T00:00:00Z',
    });
    const warning = makeRecoveryPoint({
      id: 'warning-replication',
      kind: 'backup',
      mode: 'remote',
      outcome: 'warning',
      completedAt: '2026-05-19T00:00:00Z',
    });
    const failed = makeRecoveryPoint({
      id: 'failed-replication',
      kind: 'backup',
      mode: 'remote',
      outcome: 'failed',
      completedAt: '2026-05-18T00:00:00Z',
    });

    expect(
      sortTrueNASProtectionPoints([healthy, warning, failed]).map((point) => point.id),
    ).toEqual(['failed-replication', 'warning-replication', 'newer-healthy-snapshot']);
  });

  it('deduplicates a native alert projected onto multiple resources and keeps the most specific subject', () => {
    const nativeIncident = {
      provider: 'truenas',
      nativeId: 'native-volume-status',
      code: 'truenas_volume_status',
      severity: 'critical',
      source: 'VolumeStatus',
      summary: 'Pool tank is DEGRADED',
    };
    const rows = buildTrueNASPageModel([
      makeResource({
        id: 'nas-a',
        type: 'agent',
        incidents: [nativeIncident],
      }),
      makeResource({
        id: 'tank',
        type: 'storage',
        incidents: [nativeIncident],
      }),
      makeResource({
        id: 'sdb',
        type: 'physical_disk',
        displayName: 'sdb',
        incidents: [nativeIncident],
      }),
    ]).incidents;

    expect(rows).toHaveLength(1);
    expect(rows[0]).toEqual(
      expect.objectContaining({
        resourceId: 'sdb',
        resourceName: 'sdb',
        code: 'truenas_volume_status',
      }),
    );
  });
});

describe('pool identity boundary', () => {
  // Regression guard for 599c8e634: the producer briefly published the ZFS vdev
  // layout ("mirror", "raidz2") as storage.topology. TrueNAS pools arrive as
  // type 'storage', so `topology === 'pool'` is the only thing that identifies
  // them here — publishing a layout there dropped every pool off this page on
  // real hardware while every fixture (which omits vdevs) stayed green.
  it('recognises a pool that also reports a vdev layout', () => {
    const system = makeResource({ id: 'nas-a', type: 'agent', name: 'nas-a' });
    const pool = makeResource({
      id: 'pool-tank',
      type: 'storage',
      name: 'tank',
      parentId: system.id,
      storage: { topology: 'pool', vdevLayout: 'mirror', platform: 'truenas' },
    });
    const dataset = makeResource({
      id: 'dataset-media',
      type: 'storage',
      name: 'tank/media',
      parentId: pool.id,
      storage: { topology: 'dataset', platform: 'truenas' },
    });

    const rows = buildTrueNASStorageTopologyRows([system, pool, dataset]);
    const poolRow = rows.find((row) => row.resource.id === pool.id);

    expect(poolRow?.kind).toBe('pool');
    // The dataset must still hang off the pool rather than orphaning.
    const datasetRow = rows.find((row) => row.resource.id === dataset.id);
    expect(datasetRow?.parentRowId).toBe(poolRow?.id);
  });

  it('does not identify a pool by its vdev layout alone', () => {
    const system = makeResource({ id: 'nas-a', type: 'agent', name: 'nas-a' });
    // A pool whose topology carries a layout instead of the discriminator is
    // exactly the broken shape; assert it is NOT silently accepted, so the
    // producer contract stays the single place this is fixed.
    const malformed = makeResource({
      id: 'pool-tank',
      type: 'storage',
      name: 'tank',
      parentId: system.id,
      storage: { topology: 'mirror', platform: 'truenas' },
    });

    const rows = buildTrueNASStorageTopologyRows([system, malformed]);

    expect(rows.find((row) => row.resource.id === malformed.id)).toBeUndefined();
  });
});