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.

55.5 KB
Raw Blame
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ChartsAPI } from '@/api/charts';
import type { Alert } from '@/types/api';
import type { Resource, ResourceType } from '@/types/resource';
import Storage from '@/components/Storage/Storage';
import { ROUTE_STATE_REPLACE_OPTIONS } from '@/utils/routeStateNavigation';
// Pool and disk drawers load their charts lazily; warm the module so a cold
// transform does not outlast the tests' waits.
import '@/components/Workloads/GuestDrawerHistory';

// Stub ResizeObserver for jsdom (used by HistoryChart in pool detail panels)
if (typeof globalThis.ResizeObserver === 'undefined') {
  globalThis.ResizeObserver = class ResizeObserver {
    observe() {}
    unobserve() {}
    disconnect() {}
  } as unknown as typeof ResizeObserver;
}

// Stub HTMLCanvasElement.getContext for jsdom (used by HistoryChart canvas rendering)
if (typeof HTMLCanvasElement.prototype.getContext === 'function') {
  const fakeGradient = { addColorStop: () => {} };
  const fakeContext = {
    setTransform: () => {},
    clearRect: () => {},
    beginPath: () => {},
    moveTo: () => {},
    lineTo: () => {},
    stroke: () => {},
    fill: () => {},
    fillText: () => {},
    measureText: () => ({ width: 0 }),
    createLinearGradient: () => fakeGradient,
    setLineDash: () => {},
    save: () => {},
    restore: () => {},
    arc: () => {},
    closePath: () => {},
  };
  HTMLCanvasElement.prototype.getContext = function () {
    return fakeContext as unknown as ReturnType<typeof HTMLCanvasElement.prototype.getContext>;
  } as typeof HTMLCanvasElement.prototype.getContext;
}

let mockLocationSearch = '';
let mockLocationPath = '/proxmox/storage';
// Most tests read a location snapshot; set liveLocation to follow in-app navigation.
let liveLocation = false;
const [locationVersion, setLocationVersion] = createSignal(0);
const navigateSpy = vi.fn();

let wsConnected = true;
let wsInitialDataReceived = true;
let wsReconnecting = false;
let wsActiveAlerts: Record<string, Alert> = {};
let wsState: any = {
  resources: [] as Resource[],
  storage: [],
  pbs: [],
};
const reconnectSpy = vi.fn();

let hookResources: Resource[] = [];
// Bump to deliver hookResources as a live update to an already rendered page.
const [hookResourcesVersion, setHookResourcesVersion] = createSignal(0);
let hookLoading = false;
let hookError: unknown = undefined;
let alertsDetectionEnabled = true;

const setStorageFilter = (filterLabel: string, optionLabel: string) => {
  const existingChip = queryStorageChip(filterLabel);
  if (existingChip) {
    fireEvent.click(existingChip);
    const listbox = screen.getByRole('listbox', { name: filterLabel });
    fireEvent.click(within(listbox).getByRole('option', { name: optionLabel }));
    return;
  }
  const inlineGroup = screen.queryByRole('group', { name: filterLabel });
  if (inlineGroup) {
    fireEvent.click(within(inlineGroup).getByRole('button', { name: optionLabel }));
    return;
  }
  const addFilter = screen.getByRole('combobox', { name: 'Filter' });
  const option = within(addFilter).getByRole('option', {
    name: `${filterLabel}: ${optionLabel}`,
  }) as HTMLOptionElement;
  fireEvent.change(addFilter, { target: { value: option.value } });
};

const queryStorageChip = (label: string): HTMLButtonElement | null => {
  const triggers = Array.from(
    document.querySelectorAll<HTMLButtonElement>('button[aria-haspopup="listbox"]'),
  );
  for (const trigger of triggers) {
    const text = (trigger.textContent || '').trim();
    if (text.startsWith(`${label}:`)) return trigger;
  }
  return null;
};

const openStorageViewOptions = () => {
  expect(screen.queryByLabelText('Sort by')).not.toBeInTheDocument();
  fireEvent.click(screen.getByRole('button', { name: 'View' }));
  return screen.getByRole('region', { name: 'View preferences' });
};

const setStorageViewOption = (dialog: HTMLElement, label: string, value: string) => {
  fireEvent.change(within(dialog).getByLabelText(label), { target: { value } });
};

const getStorageChipOptions = async (label: string): Promise<string[]> => {
  const chip = queryStorageChip(label);
  if (!chip) throw new Error(`No chip found for filter "${label}"`);
  fireEvent.click(chip);
  const listbox = await screen.findByRole('listbox', { name: label });
  const options = Array.from(listbox.querySelectorAll<HTMLButtonElement>('button[role="option"]'));
  return options.map((opt) => (opt.textContent || '').trim());
};

const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
  const url =
    typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
  if (url.includes('/api/license/entitlements')) {
    return new Response(JSON.stringify({ entitlements: [] }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  }
  if (url.includes('/api/metrics-store/history')) {
    return new Response(JSON.stringify({ points: [] }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  }
  return new Response(JSON.stringify({}), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
});

let nodeResources: Resource[] = [
  {
    id: 'node-1',
    type: 'agent',
    name: 'pve1',
    displayName: 'pve1',
    platformId: 'cluster-main',
    platformType: 'proxmox-pve',
    sourceType: 'api',
    status: 'online',
    uptime: 1000,
    lastSeen: Date.now(),
    platformData: { proxmox: { instance: 'cluster-main' } },
  },
  {
    id: 'node-2',
    type: 'agent',
    name: 'pve2',
    displayName: 'pve2',
    platformId: 'cluster-main',
    platformType: 'proxmox-pve',
    sourceType: 'api',
    status: 'online',
    uptime: 1000,
    lastSeen: Date.now(),
    platformData: { proxmox: { instance: 'cluster-main' } },
  },
];

type StorageResourceOptions = {
  platformId?: string;
  platformType?: string;
  status?: string;
  total?: number;
  used?: number;
  free?: number;
  current?: number;
  storageType?: string;
  content?: string;
  shared?: boolean;
  parentId?: string;
  parentName?: string;
  includePlatformNode?: boolean;
  platformData?: Record<string, unknown>;
  storage?: Resource['storage'];
  pbs?: Resource['pbs'];
  incidentCategory?: Resource['incidentCategory'];
  incidentSeverity?: Resource['incidentSeverity'];
  incidentPriority?: number;
  incidentLabel?: Resource['incidentLabel'];
  incidentSummary?: Resource['incidentSummary'];
  incidentImpactSummary?: Resource['incidentImpactSummary'];
  incidentAction?: Resource['incidentAction'];
  metricsTarget?: Resource['metricsTarget'];
};

const buildStorageResource = (
  id: string,
  name: string,
  node: string,
  options: StorageResourceOptions = {},
): Resource => ({
  id,
  type: 'storage',
  name,
  displayName: name,
  platformId: options.platformId || 'cluster-main',
  platformType: (options.platformType || 'proxmox-pve') as Resource['platformType'],
  sourceType: 'api',
  parentId: options.parentId,
  parentName: options.parentName,
  status: (options.status || 'online') as Resource['status'],
  incidentCategory: options.incidentCategory,
  incidentSeverity: options.incidentSeverity,
  incidentPriority: options.incidentPriority,
  incidentLabel: options.incidentLabel,
  incidentSummary: options.incidentSummary,
  incidentImpactSummary: options.incidentImpactSummary,
  incidentAction: options.incidentAction,
  metricsTarget: options.metricsTarget,
  storage: options.storage,
  pbs: options.pbs,
  disk: {
    current: options.current ?? 50,
    total: options.total ?? 1_000,
    used: options.used ?? 500,
    free: options.free ?? 500,
  },
  lastSeen: Date.now(),
  platformData: {
    ...(options.includePlatformNode === false ? {} : { node }),
    type: options.storageType || 'lvm',
    content: options.content || 'images,rootdir',
    shared: options.shared ?? false,
    ...(options.platformData || {}),
  },
});

const buildPhysicalDiskResource = (
  id: string,
  parentId: string | null,
  nodeName: string,
  instance = 'cluster-main',
): Resource => ({
  id,
  type: 'physical_disk',
  name: `/dev/${id}`,
  displayName: `/dev/${id}`,
  platformId: instance,
  platformType: 'proxmox-pve',
  sourceType: 'api',
  parentId: parentId ?? undefined,
  status: 'online',
  lastSeen: Date.now(),
  identity: { hostname: nodeName },
  canonicalIdentity: { hostname: nodeName },
  platformData: {
    ...(parentId ? { proxmox: { nodeName, instance } } : {}),
    physicalDisk: {
      devPath: `/dev/${id}`,
      model: 'Test Disk',
      health: 'PASSED',
    },
  },
});

const buildAlert = (
  id: string,
  resourceId: string,
  level: Alert['level'],
  acknowledged = false,
): Alert => ({
  id,
  type: 'storage-capacity',
  level,
  resourceId,
  resourceName: resourceId,
  node: 'pve1',
  instance: 'cluster-main',
  message: 'alert',
  value: 95,
  threshold: 90,
  startTime: '2026-02-08T00:00:00Z',
  acknowledged,
});

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

vi.mock('@/contexts/appRuntime', () => ({
  useWebSocket: () => ({
    state: wsState,
    activeAlerts: wsActiveAlerts,
    connected: () => wsConnected,
    initialDataReceived: () => wsInitialDataReceived,
    reconnecting: () => wsReconnecting,
    reconnect: reconnectSpy,
  }),
}));

vi.mock('@/stores/alertsActivation', () => ({
  useAlertsActivation: () => ({
    detectionEnabled: () => alertsDetectionEnabled,
    getMetricThresholds: () => ({ warning: 80, critical: 85 }),
  }),
}));

vi.mock('@/hooks/useUnifiedResources', () => ({
  useStorageRecoveryResources: () => ({
    resources: () => hookResources,
    loading: () => hookLoading,
    error: () => hookError,
    refetch: vi.fn(),
    mutate: vi.fn(),
  }),
  useUnifiedResources: (options?: { cacheKey?: string }) => ({
    resources: () => {
      hookResourcesVersion();
      return options?.cacheKey === 'storage-page'
        ? [...nodeResources, ...hookResources]
        : nodeResources;
    },
    loading: () => (options?.cacheKey === 'storage-page' ? hookLoading : false),
    error: () => (options?.cacheKey === 'storage-page' ? hookError : undefined),
    refetch: vi.fn(),
    mutate: vi.fn(),
  }),
}));

vi.mock('@/hooks/useResources', () => ({
  useResources: () => ({
    resources: () => nodeResources,
    infra: () => nodeResources,
    workloads: () => [],
    byType: (type: ResourceType) => nodeResources.filter((r) => r.type === type),
    byPlatform: () => [],
    filtered: () => [],
    get: (id: string) => nodeResources.find((r) => r.id === id),
    children: () => [],
    statusCounts: () => ({}),
    topByCpu: () => [],
    topByMemory: () => [],
    hasResources: () => nodeResources.length > 0,
  }),
}));

vi.mock('@/components/Storage/DiskList', () => ({
  DiskList: (props: { nodes: Resource[]; selectedNode: string | null; searchTerm: string }) => (
    <div data-testid="disk-list">
      disk-view:{props.selectedNode || 'all'}:{props.searchTerm || ''}
    </div>
  ),
}));

describe('Storage', () => {
  beforeEach(() => {
    vi.stubGlobal('fetch', fetchMock);
    fetchMock.mockClear();
    mockLocationPath = '/proxmox/storage';
    mockLocationSearch = '';
    liveLocation = false;
    navigateSpy.mockReset();

    wsConnected = true;
    wsInitialDataReceived = true;
    wsReconnecting = false;
    wsActiveAlerts = {};
    alertsDetectionEnabled = true;
    reconnectSpy.mockReset();
    wsState = {
      resources: [],
      storage: [],
      pbs: [],
    };
    nodeResources = [
      {
        id: 'node-1',
        type: 'agent',
        name: 'pve1',
        displayName: 'pve1',
        platformId: 'cluster-main',
        platformType: 'proxmox-pve',
        sourceType: 'api',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { proxmox: { instance: 'cluster-main' } },
      },
      {
        id: 'node-2',
        type: 'agent',
        name: 'pve2',
        displayName: 'pve2',
        platformId: 'cluster-main',
        platformType: 'proxmox-pve',
        sourceType: 'api',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { proxmox: { instance: 'cluster-main' } },
      },
    ];
    hookResources = [];
    hookLoading = false;
    hookError = undefined;
  });

  afterEach(() => {
    cleanup();
  });

  it('renders pools from v2 resources and filters by selected node', () => {
    hookResources = [
      buildStorageResource('storage-1', 'Local-LVM-PVE1', 'pve1', {
        parentId: 'node-1',
        parentName: 'pve1',
        includePlatformNode: false,
      }),
      buildStorageResource('storage-2', 'Local-LVM-PVE2', 'pve2', {
        parentId: 'node-2',
        parentName: 'pve2',
        includePlatformNode: false,
      }),
    ];

    render(() => <Storage />);

    expect(screen.getByText('Local-LVM-PVE1')).toBeInTheDocument();
    expect(screen.getByText('Local-LVM-PVE1')).toBeInTheDocument();
    expect(screen.getByText('Local-LVM-PVE2')).toBeInTheDocument();

    setStorageFilter('Node', 'pve1');

    expect(screen.getByText('Local-LVM-PVE1')).toBeInTheDocument();
    expect(screen.queryByText('Local-LVM-PVE2')).not.toBeInTheDocument();
  });

  it('gives a platform embed the canonical toolbar with source and node scope locked', async () => {
    mockLocationSearch = '?node=node-2&source=truenas';
    hookResources = [
      buildStorageResource('storage-1', 'Local-LVM-PVE1', 'pve1', {
        parentId: 'node-1',
        parentName: 'pve1',
        includePlatformNode: false,
      }),
      buildStorageResource('storage-2', 'Local-LVM-PVE2', 'pve2', {
        parentId: 'node-2',
        parentName: 'pve2',
        includePlatformNode: false,
      }),
      buildStorageResource('storage-3', 'Tank-TrueNAS', 'truenas-1', {
        platformId: 'truenas-main',
        platformType: 'truenas',
      }),
    ];

    render(() => (
      <Storage
        forcedSourceFilter="proxmox-all"
        suppressNodeFilter
        filterAriaLabel="Proxmox storage filters"
        filterSearchPlaceholder="Search Proxmox storage by pool, datastore, node, or device"
      />
    ));

    // No prop opts the embed into the toolbar or keeps it out of the view tabs.
    expect(screen.getByRole('group', { name: 'Proxmox storage filters' })).toBeInTheDocument();
    expect(
      screen.getByPlaceholderText('Search Proxmox storage by pool, datastore, node, or device'),
    ).toBeInTheDocument();
    expect(screen.getByRole('tablist', { name: 'Storage view' })).toBeInTheDocument();

    // The forced source outranks the URL source, and the URL node resets to all.
    await waitFor(() => {
      expect(screen.getByText('Local-LVM-PVE1')).toBeInTheDocument();
      expect(screen.getByText('Local-LVM-PVE2')).toBeInTheDocument();
    });
    expect(screen.queryByText('Tank-TrueNAS')).not.toBeInTheDocument();
    expect(navigateSpy.mock.calls.some(([path]) => String(path).includes('source='))).toBe(false);

    // Neither lock surfaces as a chip, an Add filter option, or a clear action.
    expect(queryStorageChip('Source')).toBeNull();
    expect(queryStorageChip('Node')).toBeNull();
    const addFilter = screen.getByRole('combobox', { name: 'Filter' });
    expect(within(addFilter).getByRole('option', { name: 'Status: Warning' })).toBeInTheDocument();
    expect(
      within(addFilter).queryByRole('option', { name: /^(Source|Node):/ }),
    ).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Clear filters' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /charts/i })).not.toBeInTheDocument();

    const viewOptions = openStorageViewOptions();
    expect(within(viewOptions).getByLabelText('Group by')).toBeInTheDocument();
    expect(within(viewOptions).getByLabelText('Sort by')).toBeInTheDocument();
  });

  it('renders per-pool growth from the shared storage summary history contract', async () => {
    const gib = 1024 * 1024 * 1024;
    const storageSummarySpy = vi.spyOn(ChartsAPI, 'getStorageSummaryCharts').mockResolvedValue({
      pools: {
        'pool:alpha': {
          name: 'Alpha-Store',
          usage: [
            { timestamp: Date.now() - 86_400_000, value: 40 },
            { timestamp: Date.now(), value: 44 },
          ],
          used: [
            { timestamp: Date.now() - 86_400_000, value: 100 * gib },
            { timestamp: Date.now(), value: 140 * gib },
          ],
          avail: [
            { timestamp: Date.now() - 86_400_000, value: 150 * gib },
            { timestamp: Date.now(), value: 110 * gib },
          ],
        },
        'pool:beta': {
          name: 'Beta-Store',
          usage: [
            { timestamp: Date.now() - 86_400_000, value: 72 },
            { timestamp: Date.now(), value: 68 },
          ],
          used: [
            { timestamp: Date.now() - 86_400_000, value: 220 * gib },
            { timestamp: Date.now(), value: 200 * gib },
          ],
          avail: [
            { timestamp: Date.now() - 86_400_000, value: 80 * gib },
            { timestamp: Date.now(), value: 100 * gib },
          ],
        },
      },
      disks: {},
      stats: {
        oldestDataTimestamp: Date.now() - 86_400_000,
      },
    });

    hookResources = [
      buildStorageResource('storage-display-alpha', 'Alpha-Store', 'pve1', {
        total: 250 * gib,
        used: 140 * gib,
        free: 110 * gib,
        current: 56,
        metricsTarget: {
          resourceType: 'storage',
          resourceId: 'pool:alpha',
        },
      }),
      buildStorageResource('storage-display-beta', 'Beta-Store', 'pve2', {
        total: 300 * gib,
        used: 200 * gib,
        free: 100 * gib,
        current: 67,
        metricsTarget: {
          resourceType: 'storage',
          resourceId: 'pool:beta',
        },
      }),
    ];

    render(() => <Storage />);

    expect(await screen.findByRole('columnheader', { name: 'Growth (24h)' })).toBeInTheDocument();
    const storageContentSurface = screen.getByTestId('storage-content-surface');
    expect(await within(storageContentSurface).findByText(/\+40(?:\.0)? GB/)).toBeInTheDocument();
    expect(within(storageContentSurface).getByText(/-20(?:\.0)? GB/)).toBeInTheDocument();
    expect(storageSummarySpy).toHaveBeenCalledWith('24h', expect.any(AbortSignal), {
      nodeId: undefined,
    });

    storageSummarySpy.mockRestore();
  });

  it('renders plain compact table headings and supports View sort/group controls', async () => {
    hookResources = [
      buildStorageResource('storage-1', 'Alpha-Store', 'pve1', {
        current: 20,
        used: 200,
        free: 800,
        total: 1_000,
        storageType: 'dir',
        status: 'online',
      }),
      buildStorageResource('storage-2', 'Beta-Store', 'pve1', {
        current: 80,
        used: 800,
        free: 200,
        total: 1_000,
        storageType: 'zfspool',
        status: 'degraded',
        incidentSeverity: 'warning',
        incidentPriority: 60,
        incidentLabel: 'Protection Reduced',
        incidentSummary: 'Pool redundancy is reduced.',
        incidentAction: 'Replace affected member disk',
        storage: {
          platform: 'proxmox',
          topology: 'pool',
          protection: 'raidz',
          protectionReduced: true,
          protectionSummary: 'Protection Reduced',
          consumerImpactSummary: 'Affects 2 dependent resources.',
        },
      }),
    ];

    render(() => <Storage />);

    expect(screen.getByRole('table')).toHaveAttribute('data-storage-table', 'pools');
    expect(screen.getByRole('table')).toHaveAttribute('data-storage-layout', 'compact');
    expect(screen.getByRole('columnheader', { name: 'Storage' })).toBeInTheDocument();
    expect(screen.queryByRole('columnheader', { name: 'Source' })).not.toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: 'Protection' })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: 'Type' })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: 'Host' })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: 'Usage' })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: 'State' })).toBeInTheDocument();
    expect(screen.getAllByText('pve1').length).toBeGreaterThan(0);
    expect(screen.getAllByText('Protection Reduced').length).toBeGreaterThan(0);
    expect(
      screen
        .getAllByText('Protection Reduced')
        .some((element) => element.getAttribute('title') === 'Pool redundancy is reduced.'),
    ).toBe(true);

    const usageHeader = screen.getByRole('columnheader', { name: 'Usage' });
    expect(within(usageHeader).queryByRole('button')).not.toBeInTheDocument();
    expect(usageHeader).not.toHaveAttribute('aria-sort');
    expect(screen.queryByRole('button', { name: /^Sort .* column/ })).not.toBeInTheDocument();
    expect(
      screen.getAllByRole('columnheader').some((header) => /[▲▼]/.test(header.textContent ?? '')),
    ).toBe(false);

    const viewOptions = openStorageViewOptions();
    setStorageViewOption(viewOptions, 'Sort by', 'usage');
    expect((within(viewOptions).getByLabelText('Sort by') as HTMLSelectElement).value).toBe(
      'usage',
    );

    await waitFor(() => {
      const orderedRowIds = Array.from(document.querySelectorAll('tr[data-row-id]')).map((row) =>
        row.getAttribute('data-row-id'),
      );
      expect(orderedRowIds.slice(0, 2)).toEqual(['storage-2', 'storage-1']);
    });

    fireEvent.click(within(viewOptions).getByRole('button', { name: 'Sort direction' }));

    await waitFor(() => {
      const orderedRowIds = Array.from(document.querySelectorAll('tr[data-row-id]')).map((row) =>
        row.getAttribute('data-row-id'),
      );
      expect(orderedRowIds.slice(0, 2)).toEqual(['storage-1', 'storage-2']);
    });

    setStorageViewOption(viewOptions, 'Group by', 'status');

    // Group headers now show just the key name (without prefix)
    expect(screen.getAllByText('degraded').length).toBeGreaterThan(0);
    expect(screen.getAllByText('online').length).toBeGreaterThan(0);
  });

  it('round-trips managed storage query params through canonical URL state', async () => {
    hookResources = [
      buildStorageResource('storage-1', 'Ceph-Store', 'pve1', { storageType: 'cephfs' }),
    ];
    nodeResources = [...nodeResources, buildPhysicalDiskResource('sdb', 'node-2', 'pve2')];
    mockLocationSearch =
      '?tab=disks&q=ceph&group=status&source=proxmox-pve&status=warning&node=node-2&sort=usage&order=desc&from=proxmox-overview';

    render(() => <Storage />);

    await waitFor(() => {
      expect(navigateSpy).toHaveBeenCalled();
    });

    const [initialPath, initialOptions] = navigateSpy.mock.calls.at(-1) as [
      string,
      { replace?: boolean },
    ];
    const initialParams = new URLSearchParams(initialPath.split('?')[1] || '');
    expect(initialParams.get('tab')).toBe('disks');
    expect(initialParams.get('q')).toBe('ceph');
    expect(initialParams.get('group')).toBe('status');
    expect(initialParams.get('source')).toBe('proxmox-pve');
    expect(initialParams.get('sort')).toBe('usage');
    expect(initialParams.get('order')).toBeNull();
    expect(initialParams.get('status')).toBe('warning');
    expect(initialParams.get('node')).toBe('node-2');
    expect(initialParams.get('from')).toBe('proxmox-overview');
    expect(initialParams.get('search')).toBeNull();
    expect(initialOptions?.replace).toBe(true);
    expect(screen.getByRole('tab', { name: 'Physical Disks' })).toHaveAttribute(
      'aria-selected',
      'true',
    );
    // Menu filter state surfaces as chips on the FilterBar. The seven-state
    // Status catalog remains in Add filter, while grouping and sort stay in
    // the shared View popover.
    expect(queryStorageChip('Node')).toHaveTextContent('Node:pve2');
    const viewOptions = openStorageViewOptions();
    expect((within(viewOptions).getByLabelText('Sort by') as HTMLSelectElement).value).toBe(
      'usage',
    );

    // Grouping controls are only shown on the Pools view.
    fireEvent.click(screen.getByRole('tab', { name: 'Storage' }));
    expect((within(viewOptions).getByLabelText('Group by') as HTMLSelectElement).value).toBe(
      'status',
    );
    expect(queryStorageChip('Source')).toHaveTextContent('Source:PVE');
    expect(screen.queryByRole('group', { name: 'Status' })).not.toBeInTheDocument();
    expect(queryStorageChip('Status')).toHaveTextContent('Status:Warning');

    setStorageViewOption(viewOptions, 'Group by', 'type');

    await waitFor(() => {
      const [nextPath] = navigateSpy.mock.calls.at(-1) as [string];
      const nextParams = new URLSearchParams(nextPath.split('?')[1] || '');
      expect(nextParams.get('group')).toBe('type');
    });

    setStorageFilter('Status', 'Healthy');

    await waitFor(() => {
      const [nextPath] = navigateSpy.mock.calls.at(-1) as [string];
      const nextParams = new URLSearchParams(nextPath.split('?')[1] || '');
      expect(nextParams.get('status')).toBe('available');
    });
  });

  it('restores view and filters from URL params', () => {
    hookResources = [buildStorageResource('storage-1', 'Node-Store', 'pve1')];
    nodeResources = [...nodeResources, buildPhysicalDiskResource('sdb', 'node-2', 'pve2')];
    mockLocationSearch = '?tab=disks&node=node-2&q=ceph&source=proxmox-pve';

    render(() => <Storage />);

    expect(screen.getByTestId('disk-list')).toHaveTextContent('disk-view:node-2:ceph');
    expect(screen.getByRole('tab', { name: 'Physical Disks' })).toHaveAttribute(
      'aria-selected',
      'true',
    );
    expect(queryStorageChip('Node')).toHaveTextContent('Node:pve2');
  });

  it('trims whitespace-padded storage URL params back to canonical state', async () => {
    hookResources = [buildStorageResource('storage-1', 'Node-Store', 'pve1')];
    nodeResources = [...nodeResources, buildPhysicalDiskResource('sdb', 'node-2', 'pve2')];
    mockLocationSearch =
      '?tab=%20disks%20&node=%20node-2%20&q=%20ceph%20&source=%20proxmox-pve%20&group=%20status%20&sort=%20usage%20&order=%20asc%20&status=%20available%20';

    render(() => <Storage />);

    await waitFor(() => {
      expect(navigateSpy).toHaveBeenCalled();
    });

    const [nextPath, nextOptions] = navigateSpy.mock.calls.at(-1) as [
      string,
      { replace?: boolean; scroll?: boolean },
    ];
    const nextParams = new URLSearchParams(nextPath.split('?')[1] || '');
    expect(nextParams.get('tab')).toBe('disks');
    expect(nextParams.get('node')).toBe('node-2');
    expect(nextParams.get('q')).toBe('ceph');
    expect(nextParams.get('source')).toBe('proxmox-pve');
    expect(nextParams.get('group')).toBe('status');
    expect(nextParams.get('sort')).toBe('usage');
    expect(nextParams.get('order')).toBe('asc');
    expect(nextParams.get('status')).toBe('available');
    expect(nextOptions?.replace).toBe(true);
    expect(nextOptions?.scroll).toBe(false);

    expect(screen.getByRole('tab', { name: 'Physical Disks' })).toHaveAttribute(
      'aria-selected',
      'true',
    );
    expect(queryStorageChip('Node')).toHaveTextContent('Node:pve2');
    const viewOptions = openStorageViewOptions();
    expect((within(viewOptions).getByLabelText('Sort by') as HTMLSelectElement).value).toBe(
      'usage',
    );
  });

  it('canonicalizes source aliases in storage URL params back to owned option values', async () => {
    hookResources = [buildStorageResource('storage-1', 'Node-Store', 'pve1')];
    mockLocationSearch = '?source=%20PVE%20';

    render(() => <Storage />);

    await waitFor(() => {
      expect(navigateSpy).toHaveBeenCalledWith(
        '/proxmox/storage?source=proxmox-pve',
        ROUTE_STATE_REPLACE_OPTIONS,
      );
    });

    expect(queryStorageChip('Source')).toHaveTextContent('Source:PVE');
  });

  it('collapses explicit all node sentinels in storage URL params back to canonical unset state', async () => {
    hookResources = [buildStorageResource('storage-1', 'Node-Store', 'pve1')];
    mockLocationSearch = '?node=%20ALL%20';

    render(() => <Storage />);

    await waitFor(() => {
      expect(navigateSpy).toHaveBeenCalledWith('/proxmox/storage', ROUTE_STATE_REPLACE_OPTIONS);
    });

    // Default Node selection ("all") collapses to no chip on the FilterBar.
    expect(queryStorageChip('Node')).toBeNull();
  });

  it('toggles a storage group from its header row without pinning a group scope', async () => {
    hookResources = [
      buildStorageResource('storage-1', 'Node-Store', 'pve1'),
      buildStorageResource('storage-2', 'Edge-Store', 'pve2'),
    ];
    mockLocationSearch = '?group=node';

    render(() => <Storage />);

    await waitFor(() => {
      expect(document.querySelector('tr[data-summary-group-id="storage:node:pve1"]')).toBeTruthy();
    });
    const groupRow = document.querySelector(
      'tr[data-summary-group-id="storage:node:pve1"]',
    ) as HTMLTableRowElement;

    fireEvent.pointerEnter(groupRow, { pointerType: 'mouse' });
    expect(document.querySelector('tr[data-summary-group-member-active]')).toBeNull();
    expect(groupRow).not.toHaveAttribute('data-summary-row-active');

    fireEvent.click(groupRow);

    await waitFor(() => {
      expect(screen.queryByText('Node-Store')).not.toBeInTheDocument();
    });
    expect(screen.getByRole('button', { name: 'Expand pve1' })).toBeInTheDocument();
    expect(screen.getByText('Edge-Store')).toBeInTheDocument();
    expect(
      within(screen.getByTestId('storage-content-surface')).queryByRole('button', {
        name: 'Clear selection',
      }),
    ).not.toBeInTheDocument();

    fireEvent.click(groupRow);

    await waitFor(() => {
      expect(screen.getByText('Node-Store')).toBeInTheDocument();
    });
    expect(screen.getByRole('button', { name: 'Collapse pve1' })).toBeInTheDocument();
    for (const [path] of navigateSpy.mock.calls) {
      expect(String(path)).not.toContain('summaryGroup');
    }
  });

  it('keeps an open pool open when another group header is clicked', async () => {
    hookResources = [
      buildStorageResource('storage-1', 'Node-Store', 'pve1'),
      buildStorageResource('storage-2', 'Edge-Store', 'pve2'),
    ];
    mockLocationSearch = '?group=node';

    render(() => <Storage />);

    fireEvent.click(await screen.findByRole('button', { name: 'Expand Node-Store' }));
    await waitFor(() => {
      expect(document.querySelector('tr[data-inline-detail-for]')).toBeTruthy();
    });

    fireEvent.click(
      document.querySelector('tr[data-summary-group-id="storage:node:pve2"]') as HTMLElement,
    );

    await waitFor(() => {
      expect(screen.queryByText('Edge-Store')).not.toBeInTheDocument();
    });
    expect(screen.getByRole('button', { name: 'Collapse Node-Store' })).toBeInTheDocument();
    expect(document.querySelector('tr[data-inline-detail-for]')).toBeTruthy();
  });

  it('reopens the collapsed group of a pool focused by an in-app storage link', async () => {
    liveLocation = true;
    hookResources = [
      buildStorageResource('storage-ceph-link', 'Ceph-Link-Store', 'pve1', {
        storageType: 'cephfs',
      }),
      buildStorageResource('storage-other', 'Other-Store', 'pve2'),
    ];
    mockLocationSearch = '?group=node';

    render(() => <Storage />);

    fireEvent.click(await screen.findByRole('button', { name: 'Collapse pve1' }));
    await waitFor(() => {
      expect(screen.queryByText('Ceph-Link-Store')).not.toBeInTheDocument();
    });

    mockLocationSearch = '?group=node&resource=storage-ceph-link';
    setLocationVersion((version) => version + 1);

    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'Collapse pve1' })).toBeInTheDocument();
      // The open pool's drawer names it too; the row's name comes first.
      const poolRow = screen
        .getAllByText('Ceph-Link-Store')[0]
        .closest('tr[data-summary-series-id]');
      expect(
        document
          .querySelector('tr[data-inline-detail-for]')
          ?.getAttribute('data-inline-detail-for'),
      ).toBe(poolRow?.getAttribute('data-summary-series-id'));
    });
    expect(screen.getAllByRole('tab', { name: 'Storage' })[0]).toHaveAttribute(
      'aria-selected',
      'true',
    );
  });

  it('does not scroll back to an open pool when a live update rebuilds the pools', async () => {
    const scrollTo = vi.fn();
    const originalScrollTo = Object.getOwnPropertyDescriptor(window, 'scrollTo');
    Object.defineProperty(window, 'scrollTo', { configurable: true, value: scrollTo });
    hookResources = [
      buildStorageResource('storage-1', 'Node-Store', 'pve1'),
      buildStorageResource('storage-2', 'Edge-Store', 'pve2'),
    ];
    mockLocationSearch = '?group=node';

    try {
      render(() => <Storage />);

      fireEvent.click(await screen.findByRole('button', { name: 'Expand Node-Store' }));
      await waitFor(() => {
        expect(document.querySelector('tr[data-inline-detail-for]')).toBeTruthy();
        expect(scrollTo).toHaveBeenCalled();
      });
      // Count only once the reveal's settle frames stop scrolling.
      let previousScrolls = -1;
      while (scrollTo.mock.calls.length !== previousScrolls) {
        previousScrolls = scrollTo.mock.calls.length;
        await new Promise((resolve) => setTimeout(resolve, 50));
      }
      const scrollsAfterFocus = scrollTo.mock.calls.length;

      hookResources = hookResources.map((resource) => ({ ...resource, lastSeen: Date.now() }));
      setHookResourcesVersion((version) => version + 1);
      await new Promise((resolve) => setTimeout(resolve, 100));

      expect(screen.getByRole('button', { name: 'Collapse Node-Store' })).toBeInTheDocument();
      expect(scrollTo).toHaveBeenCalledTimes(scrollsAfterFocus);
    } finally {
      if (originalScrollTo) {
        Object.defineProperty(window, 'scrollTo', originalScrollTo);
      }
    }
  });

  it('keeps the group of an open pool collapsed across live updates', async () => {
    hookResources = [
      buildStorageResource('storage-1', 'Node-Store', 'pve1'),
      buildStorageResource('storage-2', 'Edge-Store', 'pve2'),
    ];
    mockLocationSearch = '?group=node';

    render(() => <Storage />);

    fireEvent.click(await screen.findByRole('button', { name: 'Expand Node-Store' }));
    await waitFor(() => {
      expect(document.querySelector('tr[data-inline-detail-for]')).toBeTruthy();
    });

    fireEvent.click(screen.getByRole('button', { name: 'Collapse pve1' }));
    await new Promise((resolve) => setTimeout(resolve, 100));

    expect(screen.queryByText('Node-Store')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Expand pve1' })).toBeInTheDocument();

    hookResources = hookResources.map((resource) => ({ ...resource, lastSeen: Date.now() }));
    setHookResourcesVersion((version) => version + 1);
    await new Promise((resolve) => setTimeout(resolve, 100));

    expect(screen.queryByText('Node-Store')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Expand pve1' })).toBeInTheDocument();
  });

  it('ignores a summaryGroup param left in a storage URL', async () => {
    hookResources = [
      buildStorageResource('storage-1', 'Node-Store', 'pve1'),
      buildStorageResource('storage-2', 'Edge-Store', 'pve2'),
    ];
    mockLocationSearch = '?group=node&summaryGroup=storage%3Anode%3Apve1';

    render(() => <Storage />);

    await waitFor(() => {
      expect(screen.getByText('Node-Store')).toBeInTheDocument();
    });
    expect(screen.getByText('Edge-Store')).toBeInTheDocument();
    expect(document.querySelector('tr[data-summary-group-member-active]')).toBeNull();
    expect(document.querySelector('tr[data-summary-row-active="true"]')).toBeNull();
    expect(
      within(screen.getByTestId('storage-content-surface')).queryByRole('button', {
        name: 'Clear selection',
      }),
    ).not.toBeInTheDocument();
  });

  it('keeps a storage pool row closed when a drag selects its text', async () => {
    hookResources = [buildStorageResource('storage-1', 'Node-Store', 'pve1')];

    render(() => <Storage />);

    const name = await screen.findByText('Node-Store');
    const range = document.createRange();
    range.selectNodeContents(name);
    const selection = document.getSelection()!;
    selection.removeAllRanges();
    selection.addRange(range);
    try {
      fireEvent.mouseDown(name, { clientX: 4, clientY: 8 });
      fireEvent.click(name, { clientX: 80, clientY: 8 });
      expect(screen.getByRole('button', { name: 'Expand Node-Store' })).toHaveAttribute(
        'aria-expanded',
        'false',
      );

      fireEvent.mouseDown(name, { clientX: 40, clientY: 8 });
      fireEvent.click(name, { clientX: 40, clientY: 8 });
      expect(await screen.findByRole('button', { name: 'Collapse Node-Store' })).toHaveAttribute(
        'aria-expanded',
        'true',
      );
    } finally {
      selection.removeAllRanges();
    }
  });

  it('uses canonical storage metrics target ids for expanded pool history charts', async () => {
    const metricsHistorySpy = vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue({
      resourceType: 'storage',
      resourceId: 'pool:tank',
      range: '24h',
      start: Date.now() - 24 * 60 * 60 * 1000,
      end: Date.now(),
      metrics: { usage: [] },
      source: 'store',
    });

    hookResources = [
      buildStorageResource('storage-truenas-display', 'tank', 'truenas01', {
        platformId: 'truenas-1',
        platformType: 'truenas',
        storageType: 'zfs-pool',
        parentName: 'truenas01',
        includePlatformNode: false,
        metricsTarget: {
          resourceType: 'storage',
          resourceId: 'pool:tank',
        },
        storage: {
          type: 'zfs-pool',
          platform: 'truenas',
          topology: 'pool',
          isZfs: true,
        },
      }),
    ];

    render(() => <Storage />);

    fireEvent.click(screen.getByRole('button', { name: 'Expand tank' }));

    // The pool drawer charts its capacity at the drawer's 24h default.
    await waitFor(() => {
      expect(metricsHistorySpy).toHaveBeenCalledWith(
        expect.objectContaining({
          resourceType: 'storage',
          resourceId: 'pool:tank',
          range: '24h',
        }),
      );
    });

    metricsHistorySpy.mockRestore();
  });

  it('applies alert highlight styling for rows with active unacknowledged alerts', async () => {
    hookResources = [buildStorageResource('storage-alerted', 'Alerted-Store', 'pve1')];
    wsActiveAlerts = {
      'alert-1': buildAlert('alert-1', 'storage-alerted', 'critical'),
    };

    render(() => <Storage />);

    await waitFor(() => {
      const row = screen.getByText('Alerted-Store').closest('tr');
      expect(row).toHaveAttribute('data-alert-state', 'unacknowledged');
      expect(row).toHaveAttribute('data-alert-severity', 'critical');
      expect(row).not.toHaveAttribute('style');
      expect(row?.className).toContain('shadow-[inset_4px_0_0_0_#ef4444]');
    });
  });

  it('marks acknowledged-only alert rows with parity state attributes', async () => {
    hookResources = [buildStorageResource('storage-acked', 'Acknowledged-Store', 'pve1')];
    wsActiveAlerts = {
      'alert-1': buildAlert('alert-1', 'storage-acked', 'warning', true),
    };

    render(() => <Storage />);

    await waitFor(() => {
      const row = screen.getByText('Acknowledged-Store').closest('tr');
      expect(row).toHaveAttribute('data-alert-state', 'acknowledged');
      expect(row).toHaveAttribute('data-alert-severity', 'none');
      expect(row).not.toHaveAttribute('style');
      expect(row?.className).toContain('shadow-[inset_4px_0_0_0_rgba(156,163,175,0.8)]');
    });
  });

  it('supports resource deep-links by highlighting rows', async () => {
    hookResources = [
      buildStorageResource('storage-ceph-link', 'Ceph-Link-Store', 'pve1', {
        storageType: 'cephfs',
      }),
      buildStorageResource('storage-other', 'Other-Store', 'pve2'),
    ];
    mockLocationSearch = '?resource=storage-ceph-link';

    render(() => <Storage />);

    await waitFor(() => {
      const row = document.querySelector('tr[data-row-id="storage-ceph-link"]');
      expect(row).toHaveAttribute('data-resource-highlighted', 'true');
      expect(document.querySelector('tr[data-row-id="storage-other"]')).toHaveAttribute(
        'data-resource-highlighted',
        'false',
      );
    });
  });

  it('opens a deep-linked pool only once its Storage tab is showing', async () => {
    // The Proxmox page keeps Storage mounted behind its other tabs, whose
    // guest links also use ?resource=.
    hookResources = [
      buildStorageResource('storage-zfs-link', 'Zfs-Link-Store', 'pve1'),
      buildStorageResource('storage-other', 'Other-Store', 'pve2'),
    ];
    mockLocationSearch = '?resource=storage-zfs-link';
    const [routeActive, setRouteActive] = createSignal(false);

    render(() => <Storage routeActive={routeActive()} />);

    const poolRow = (await screen.findByText('Zfs-Link-Store')).closest(
      'tr[data-summary-series-id]',
    );
    expect(document.querySelector('tr[data-inline-detail-for]')).toBeNull();
    expect(poolRow).toHaveAttribute('data-resource-highlighted', 'false');

    setRouteActive(true);

    await waitFor(() => {
      expect(
        document
          .querySelector('tr[data-inline-detail-for]')
          ?.getAttribute('data-inline-detail-for'),
      ).toBe(poolRow?.getAttribute('data-summary-series-id'));
      expect(poolRow).toHaveAttribute('data-resource-highlighted', 'true');
    });
  });

  it('restores canonical TrueNAS source filters from the storage route', async () => {
    nodeResources = [
      {
        id: 'truenas-main',
        type: 'agent',
        name: 'TrueNAS Main',
        displayName: 'TrueNAS Main',
        platformId: 'truenas-main',
        platformType: 'truenas',
        sourceType: 'hybrid',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        canonicalIdentity: { hostname: 'truenas-main' },
        platformData: { sources: ['agent', 'truenas'] },
      } as Resource,
      {
        id: 'pve-main',
        type: 'agent',
        name: 'PVE Main',
        displayName: 'PVE Main',
        platformId: 'cluster-main',
        platformType: 'proxmox-pve',
        sourceType: 'hybrid',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        canonicalIdentity: { hostname: 'pve-main' },
        platformData: { proxmox: { instance: 'cluster-main' }, sources: ['agent', 'proxmox-pve'] },
      } as Resource,
    ];
    hookResources = [
      buildStorageResource('storage-truenas-display', 'tank', 'truenas-main', {
        platformId: 'truenas-1',
        platformType: 'truenas',
        parentId: 'truenas-main',
        parentName: 'truenas-main',
        includePlatformNode: false,
        storageType: 'zfs-pool',
        storage: {
          platform: 'truenas',
          type: 'zfs-pool',
          topology: 'pool',
          isZfs: true,
        },
      }),
      buildStorageResource('storage-pve-main', 'local-zfs', 'pve-main', {
        parentId: 'pve-main',
        parentName: 'pve-main',
        includePlatformNode: false,
        storage: {
          platform: 'proxmox-pve',
          type: 'zfspool',
          topology: 'pool',
          isZfs: true,
        },
      }),
    ];
    mockLocationSearch = '?source=truenas&node=truenas-main';

    render(() => <Storage />);

    await waitFor(() => {
      expect(queryStorageChip('Source')).toHaveTextContent('Source:TrueNAS');
    });

    expect(queryStorageChip('Node')).toHaveTextContent('Node:TrueNAS Main');
    expect(await getStorageChipOptions('Source')).toEqual(['All sources', 'PVE', 'TrueNAS']);
    expect(screen.getByText('tank')).toBeInTheDocument();
    expect(screen.queryByText('local-zfs')).not.toBeInTheDocument();
  });

  it('canonicalizes whitespace-padded resource deep-links without dropping other params', async () => {
    hookResources = [
      buildStorageResource('storage-ceph-link', 'Ceph-Link-Store', 'pve1', {
        storageType: 'cephfs',
      }),
      buildStorageResource('storage-other', 'Other-Store', 'pve2'),
    ];
    mockLocationSearch = '?resource=%20storage-ceph-link%20&from=proxmox-overview';

    render(() => <Storage />);

    await waitFor(() => {
      expect(navigateSpy).toHaveBeenCalled();
    });

    const [nextPath, nextOptions] = navigateSpy.mock.calls.at(-1) as [
      string,
      { replace?: boolean },
    ];
    const nextParams = new URLSearchParams(nextPath.split('?')[1] || '');
    expect(nextParams.get('resource')).toBe('storage-ceph-link');
    expect(nextParams.get('from')).toBe('proxmox-overview');
    expect(nextOptions?.replace).toBe(true);

    await waitFor(() => {
      const row = document.querySelector('tr[data-row-id="storage-ceph-link"]');
      expect(row).toHaveAttribute('data-resource-highlighted', 'true');
    });
  });

  it('shows zfs health indicators when unified storage resources carry pool errors', async () => {
    hookResources = [
      buildStorageResource('storage-zfs', 'local-zfs', 'pve1', {
        platformId: 'cluster-main',
        storageType: 'zfspool',
        current: 60,
        used: 600,
        free: 400,
        total: 1_000,
        platformData: {
          zfsPool: {
            name: 'rpool',
            state: 'DEGRADED',
            status: 'Degraded',
            scan: 'none',
            readErrors: 1,
            writeErrors: 0,
            checksumErrors: 2,
            devices: [
              {
                name: 'sda',
                type: 'disk',
                state: 'DEGRADED',
                readErrors: 1,
                writeErrors: 0,
                checksumErrors: 2,
              },
            ],
          },
        },
      }),
    ];

    render(() => <Storage />);

    // zpool's upper-case state is presented titleized, like every other state.
    await waitFor(() => {
      expect(screen.getAllByText('Degraded').length).toBeGreaterThan(0);
    });
    expect(screen.getAllByText('Degraded')[0]).toHaveAttribute(
      'title',
      '1 read, 2 checksum errors',
    );
  });

  it('keeps the storage content card in loading mode while the route is still fetching its first dataset', () => {
    hookLoading = true;
    wsConnected = false;
    wsInitialDataReceived = false;

    render(() => <Storage />);

    expect(screen.getByText('Loading storage resources...')).toBeInTheDocument();
    expect(
      screen.queryByText('Waiting for storage data from connected platforms.'),
    ).not.toBeInTheDocument();
  });

  it('keeps storage content visible when the websocket stream is reconnecting but REST data is healthy', () => {
    hookResources = [buildStorageResource('storage-1', 'Node-Store', 'pve1')];
    wsConnected = false;
    wsInitialDataReceived = false;
    wsReconnecting = true;

    render(() => <Storage />);

    expect(screen.getByText('Node-Store')).toBeInTheDocument();
    expect(screen.queryByText('Reconnecting to backend data stream…')).not.toBeInTheDocument();
  });

  it('suppresses stale-data disconnect banners when storage resources are still available', () => {
    hookResources = [buildStorageResource('storage-1', 'Node-Store', 'pve1')];
    wsConnected = false;
    wsInitialDataReceived = true;
    wsReconnecting = false;

    render(() => <Storage />);

    expect(screen.getByText('Node-Store')).toBeInTheDocument();
    expect(
      screen.queryByText('Storage data stream disconnected. Data may be stale.'),
    ).not.toBeInTheDocument();
  });

  it('switches to physical disks view', () => {
    render(() => <Storage />);

    fireEvent.click(screen.getByRole('tab', { name: 'Physical Disks' }));

    expect(screen.getByTestId('disk-list')).toBeInTheDocument();
  });

  it('limits physical disk node filter options to hosts with disk resources', () => {
    nodeResources = [
      {
        id: 'node-1',
        type: 'agent',
        name: 'pve1',
        displayName: 'pve1',
        platformId: 'cluster-main',
        platformType: 'proxmox-pve',
        sourceType: 'api',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { proxmox: { instance: 'cluster-main' } },
      },
      {
        id: 'agent-standalone',
        type: 'agent',
        name: 'mini',
        displayName: 'mini',
        platformId: 'agent-mini',
        platformType: 'agent',
        sourceType: 'agent',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { agent: { agentId: 'agent-mini', hostname: 'mini' } },
      },
      buildPhysicalDiskResource('sda', null, 'pve1'),
    ];

    render(() => <Storage />);

    fireEvent.click(screen.getAllByRole('tab', { name: 'Physical Disks' })[0]!);

    // The direct Filter selector lists nodes that have disk resources.
    // Hosts without disk resources (e.g. 'mini') are filtered out.
    const addFilter = screen.getByRole('combobox', { name: 'Filter' });
    const optionLabels = Array.from(addFilter.querySelectorAll<HTMLOptionElement>('option'))
      .map((option) => (option.textContent || '').trim())
      .filter((text) => text.startsWith('Node: '))
      .map((text) => text.replace(/^Node: /, ''));
    expect(optionLabels).toContain('pve1');
    expect(optionLabels).not.toContain('mini');
  });

  it('resets stale disk node selections that do not map to a physical disk parent', async () => {
    mockLocationSearch = '?tab=disks&node=agent-standalone';
    nodeResources = [
      {
        id: 'node-1',
        type: 'agent',
        name: 'pve1',
        displayName: 'pve1',
        platformId: 'cluster-main',
        platformType: 'proxmox-pve',
        sourceType: 'api',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { proxmox: { instance: 'cluster-main' } },
      },
      {
        id: 'agent-standalone',
        type: 'agent',
        name: 'mini',
        displayName: 'mini',
        platformId: 'agent-mini',
        platformType: 'agent',
        sourceType: 'agent',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { agent: { agentId: 'agent-mini', hostname: 'mini' } },
      },
      buildPhysicalDiskResource('sda', 'node-1', 'pve1'),
    ];

    render(() => <Storage />);

    await waitFor(() => {
      expect(screen.getByTestId('disk-list')).toHaveTextContent('disk-view:all:');
    });
    // Stale node selection collapses to default ("all"), so no Node chip
    // remains.
    expect(queryStorageChip('Node')).toBeNull();
  });

  it('renders the storage view as canonical subtabs', () => {
    render(() => <Storage />);

    expect(screen.getAllByRole('tablist', { name: 'Storage view' })[0]).toBeInTheDocument();
    expect(screen.getAllByRole('tab', { name: 'Storage' })[0]).toHaveAttribute(
      'aria-selected',
      'true',
    );
    expect(screen.getAllByRole('tab', { name: 'Physical Disks' })[0]).toHaveAttribute(
      'aria-selected',
      'false',
    );
  });

  it('keeps the storage view selector available in a platform-page embed', async () => {
    mockLocationPath = '/proxmox/storage';
    hookResources = [
      buildPhysicalDiskResource('sda', 'node-1', 'pve1'),
      buildStorageResource('storage-1', 'Local-LVM-PVE1', 'pve1'),
    ];

    render(() => <Storage forcedSourceFilter="proxmox-pve" />);

    const viewTabs = screen.getByRole('tablist', { name: 'Storage view' });
    expect(within(viewTabs).getByRole('tab', { name: 'Storage' })).toHaveAttribute(
      'aria-selected',
      'true',
    );
    expect(screen.queryByTestId('storage-summary')).not.toBeInTheDocument();

    fireEvent.click(within(viewTabs).getByRole('tab', { name: 'Physical Disks' }));

    await waitFor(() => {
      expect(screen.getByTestId('disk-list')).toHaveTextContent('disk-view:all:');
    });
    expect(within(viewTabs).getByRole('tab', { name: 'Physical Disks' })).toHaveAttribute(
      'aria-selected',
      'true',
    );
  });

  it('passes platform-owned filter copy into embedded storage controls', () => {
    mockLocationPath = '/vmware/storage';
    nodeResources = [
      {
        id: 'host-esxi-01',
        type: 'agent',
        name: 'esxi-01',
        displayName: 'esxi-01',
        platformId: 'vcenter-main',
        platformType: 'vmware-vsphere',
        sourceType: 'api',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { sources: ['vmware-vsphere'] },
      } as Resource,
      {
        id: 'host-esxi-02',
        type: 'agent',
        name: 'esxi-02',
        displayName: 'esxi-02',
        platformId: 'vcenter-main',
        platformType: 'vmware-vsphere',
        sourceType: 'api',
        status: 'online',
        uptime: 1000,
        lastSeen: Date.now(),
        platformData: { sources: ['vmware-vsphere'] },
      } as Resource,
    ];
    hookResources = [
      buildStorageResource('vsphere-datastore', 'vsan-prod', 'esxi-01', {
        platformType: 'vmware-vsphere',
        parentName: 'esxi-01',
        storage: {
          type: 'datastore',
          topology: 'datastore',
          nodes: ['esxi-01'],
        },
      }),
      buildStorageResource('vsphere-archive', 'archive-cold', 'esxi-02', {
        platformType: 'vmware-vsphere',
        parentName: 'esxi-02',
        storage: {
          platform: 'vmware-vsphere',
          type: 'datastore',
          topology: 'datastore',
          nodes: ['esxi-02'],
        },
      }),
    ];

    render(() => (
      <Storage
        forcedSourceFilter="vmware-vsphere"
        suppressNodeFilter
        filterAriaLabel="vSphere datastore filters"
        filterSearchPlaceholder="Search vSphere datastores by name, host, or capacity group"
        filterSearchEmptyMessage="Recent vSphere datastore searches appear here."
      />
    ));

    expect(screen.getByRole('group', { name: 'vSphere datastore filters' })).toBeInTheDocument();
    expect(
      screen.getByPlaceholderText('Search vSphere datastores by name, host, or capacity group'),
    ).toBeInTheDocument();
    const addFilter = screen.getByRole('combobox', { name: 'Filter' });
    expect(within(addFilter).getByRole('option', { name: 'Status: Warning' })).toBeInTheDocument();
    expect(within(addFilter).queryByRole('option', { name: /^Source:/ })).not.toBeInTheDocument();

    fireEvent.input(
      screen.getByPlaceholderText('Search vSphere datastores by name, host, or capacity group'),
      { target: { value: 'esxi-02' } },
    );

    expect(screen.queryByText('vsan-prod')).not.toBeInTheDocument();
    expect(screen.getByText('archive-cold')).toBeInTheDocument();
  });

  it('shows loading placeholder when pool resources are loading', () => {
    hookLoading = true;

    render(() => <Storage />);

    expect(screen.getByText('Loading storage resources...')).toBeInTheDocument();
  });

  it('GA contract: storage route state stays on the owning platform storage path', async () => {
    hookResources = [
      buildStorageResource('storage-ga', 'GA-Store', 'pve1', { status: 'degraded' }),
    ];
    mockLocationPath = '/proxmox/storage';
    mockLocationSearch = '?source=proxmox-pve&status=warning';

    render(() => <Storage />);

    await waitFor(() => {
      expect(screen.getByText('GA-Store')).toBeInTheDocument();
    });

    const path =
      navigateSpy.mock.calls.length > 0
        ? (navigateSpy.mock.calls.at(-1) as [string])[0]
        : `${mockLocationPath}${mockLocationSearch}`;
    expect(path.startsWith('/proxmox/storage')).toBe(true);
    expect(path).not.toContain('/proxmox/storage-v2');
    const params = new URLSearchParams(path.split('?')[1] || '');
    expect(params.get('source')).toBe('proxmox-pve');
    expect(params.get('status')).toBe('warning');
  });
});