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.

147 KB
Raw Blame
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
import { Route, Router } from '@solidjs/router';
import { createSignal, type JSX } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { ProxmoxBackupsTable } from '../ProxmoxBackupsTable';
import {
  BACKUP_IDENTITY_NOW,
  identityGuest,
  identityArchive,
  identityPBS,
  identitySnapshot,
  identityTask,
} from '../__fixtures__/backupIdentity';
import { buildBackupServerRows, ProxmoxBackupServersTable } from '../ProxmoxBackupServersTable';
import {
  PLATFORM_TABLE_BODY_CLASS,
  PLATFORM_TABLE_HEADER_ROW_CLASS,
} from '@/features/platformPage/sharedPlatformPage';
import { TABLE_CARD_FRAME_CLASS } from '@/components/shared/TableCard';
import type { Resource } from '@/types/resource';
import type { ProtectionPosturesResponse } from '@/types/recovery';
import { protectionPolicy, protectionPosture } from '@/utils/__fixtures__/protectionPosture';
import { getRecoveryFullDateLabel } from '@/utils/recoveryDatePresentation';
import { eventBus } from '@/stores/events';
import { setKioskMode } from '@/utils/url';
import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
import { WebSocketContext, DarkModeContext, type WebSocketStore } from '@/contexts/appRuntime';

// ProxmoxBackupsTable reads URL search params (node/type scope filters), so it
// must render inside a Router context.
const renderInRouter = (component: () => JSX.Element) =>
  render(() => (
    <Router>
      <Route path="/*" component={component} />
    </Router>
  ));

const apiFetchMock = vi.hoisted(() => vi.fn());
const apiFetchJSONMock = vi.hoisted(() => vi.fn());

vi.mock('@/utils/apiClient', () => ({
  apiFetch: apiFetchMock,
  apiFetchJSON: apiFetchJSONMock,
}));

const jsonResponse = (payload: unknown) =>
  new Response(JSON.stringify(payload), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });

const pvePayload = {
  data: {
    guestSnapshots: [
      {
        id: 'snap-112',
        name: 'pre-upgrade',
        node: 'pve-a',
        instance: 'pve-a',
        type: 'ct',
        vmid: 112,
        time: '2026-05-25T01:00:00Z',
        vmstate: false,
      },
    ],
    storageBackups: [
      {
        id: 'archive-112',
        storage: 'local',
        node: 'pve-a',
        instance: 'pve-a',
        type: 'ct',
        vmid: 112,
        time: '2026-05-25T02:00:00Z',
        ctime: 1_769_390_400,
        size: 1_048_576,
        format: 'zst',
        protected: false,
        volid: 'local:backup/vzdump-lxc-112-2026_05_25-02_00_00.tar.zst',
        isPBS: false,
        verified: false,
      },
    ],
    backupTasks: [
      {
        id: 'task-112',
        node: 'pve-a',
        instance: 'pve-a',
        type: 'ct',
        vmid: 112,
        status: 'OK',
        startTime: '2026-05-25T02:00:00Z',
        endTime: '2026-05-25T02:05:00Z',
      },
    ],
  },
  meta: {
    totalBackupTasks: 1,
    totalStorageBackups: 1,
    totalGuestSnapshots: 1,
  },
};

const pbsPayload = {
  data: {
    backups: [
      {
        id: 'pbs-main/main/minipc/ct/112/2026-05-25T01:34:25Z',
        instance: 'pbs-main',
        datastore: 'main',
        namespace: 'minipc',
        backupType: 'ct',
        vmid: '112',
        backupTime: '2026-05-25T01:34:25Z',
        size: 8_589_934_592,
        protected: true,
        verified: true,
        files: ['index.json.blob', 'root.pxar.didx'],
        owner: 'backup@pbs',
      },
    ],
  },
  meta: { totalBackups: 1 },
};

function mockBackupAPIs(
  state: 'protected' | 'attention' = 'protected',
  pbsResponse: typeof pbsPayload = pbsPayload,
) {
  apiFetchMock.mockImplementation((url: string) => {
    if (url === '/api/backups/pbs') return Promise.resolve(jsonResponse(pbsResponse));
    if (url === '/api/backups/pve') return Promise.resolve(jsonResponse(pvePayload));
    return Promise.resolve(jsonResponse({}));
  });
  apiFetchJSONMock.mockResolvedValue({
    data: [
      {
        subjectResourceId: 'ct-112',
        state,
        lastAttemptAt: '2026-05-25T02:00:00Z',
        lastSuccessfulPointAt: '2026-05-25T01:34:25Z',
        lastVerifiedAt: '2026-05-25T01:34:25Z',
        freshness: 'current',
        verification: 'verified',
        coverage: 'complete',
        providerStates: [],
        repositoryResourceIds: [],
        evidenceIds: ['evidence-1'],
        reason: state === 'protected' ? 'recent-verified' : 'source-failed',
        explanation:
          state === 'protected'
            ? 'A current verified backup is available.'
            : 'A backup exists, but one of its backup sources has reported a failure.',
        evaluatedAt: '2026-05-25T02:05:00Z',
      },
    ],
    policy: {
      freshnessWindowSeconds: 604800,
      verificationWindowSeconds: 604800,
      requireVerification: true,
    },
  });
}

const workloadResource = {
  id: 'ct-112',
  type: 'system-container',
  name: 'pbs-docker',
  displayName: 'pbs-docker',
  platformId: 'pve-a',
  platformType: 'proxmox-pve',
  sourceType: 'api',
  status: 'running',
  lastSeen: Date.parse('2026-05-25T00:00:00Z'),
  proxmox: { vmid: 112, node: 'pve-a', instance: 'pve-a' },
} as Resource;

const pbsServerResource = {
  id: 'pbs-main',
  type: 'pbs',
  name: 'pbs-main',
  displayName: 'pbs-main',
  platformId: 'pbs-main',
  platformType: 'proxmox-pbs',
  sourceType: 'api',
  status: 'online',
  lastSeen: Date.parse('2026-05-25T00:00:00Z'),
  cpu: { current: 12 },
  memory: { current: 40, total: 8_000, used: 3_200, free: 4_800 },
  uptime: 86_400,
  pbs: {
    instanceId: 'pbs-main',
    version: '3.2.1',
    connectionHealth: 'healthy',
    datastores: [{ name: 'main', total: 10_000, used: 4_000, available: 6_000, usagePercent: 40 }],
  },
} as Resource;

const expectClassTokens = (element: Element | null, className: string): void => {
  expect(element).not.toBeNull();
  for (const token of className.split(/\s+/).filter(Boolean)) {
    expect(element).toHaveClass(token);
  }
};

const expectCanonicalPlatformTableShell = (table: HTMLElement): void => {
  expectClassTokens(table.querySelector('thead tr'), PLATFORM_TABLE_HEADER_ROW_CLASS);
  expectClassTokens(table.querySelector('tbody'), PLATFORM_TABLE_BODY_CLASS);
};

afterEach(() => {
  cleanup();
  vi.unstubAllGlobals();
  window.history.replaceState({}, '', '/');
  apiFetchMock.mockReset();
  apiFetchJSONMock.mockReset();
  resetCreateNonSuspendingQueryCacheForTest();
});

beforeEach(() => {
  vi.stubGlobal('scrollTo', vi.fn());
});

describe('ProxmoxBackupsTable', () => {
  it('does not treat a runtime service identity as a second backup reader', () => {
    // The actual producer uses Name=main, ID=pbs-main. A separate configured
    // reader may itself be named pbs-main; its snapshots cannot fill main.
    const emptyReader = {
      ...pbsServerResource,
      name: 'main',
      pbs: { ...pbsServerResource.pbs!, instanceId: 'pbs-main' },
    } as Resource;
    const other = pbsPayload.data.backups;
    expect(buildBackupServerRows([emptyReader], other)[0].backupCount).toBe(0);
    expect(buildBackupServerRows([pbsServerResource], other)[0].backupCount).toBe(1);
  });

  it.each([
    { used: 9_500, usagePercent: 0, expected: '95.0%', tone: 'text-red-600' },
    { used: 8_000, usagePercent: 20, expected: '80.0%', tone: 'text-amber-600' },
    { used: 0, usagePercent: 95, expected: '0.0%', tone: 'text-base-content' },
    { used: 10_000, usagePercent: undefined, expected: '100.0%', tone: 'text-red-600' },
  ])(
    'keeps datastore fullness and warning consistent with used bytes: $used/$usagePercent',
    async ({ used, usagePercent, expected, tone }) => {
      mockBackupAPIs();
      const [servers, setServers] = createSignal<Resource[]>([
        {
          ...pbsServerResource,
          pbs: {
            ...pbsServerResource.pbs!,
            datastores: [{ name: 'main', total: 10_000, used, usagePercent }],
          },
        },
      ]);
      const { container } = renderInRouter(() => (
        <ProxmoxBackupsTable emptyIcon={<span />} servers={servers()} />
      ));
      await screen.findByText(expected);
      const table = container.querySelector('[data-proxmox-backups-table="servers"]')!;
      const usedColumn = Array.from(table.querySelectorAll('th')).findIndex(
        (head) => head.textContent?.trim() === 'Used',
      );
      const usedCell = () =>
        table.querySelector('tbody tr:not([data-backup-server-group])')!.querySelectorAll('td')[
          usedColumn
        ];
      expect(within(usedCell()).getByText(expected).parentElement).toHaveClass(tone);

      // Reconciled polling updates must recompute the same row, not retain the
      // previous percentage or borrow one from the provider's optional field.
      setServers([pbsServerResource]);
      await within(usedCell()).findByText('40.0%');
      expect(within(usedCell()).queryByText(expected)).not.toBeInTheDocument();
      expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pbs')).toHaveLength(1);
    },
  );

  it.each([
    { total: 0, used: 0, status: 'available', expected: 'Unknown' },
    { total: 10_000, used: -1, status: 'available', expected: 'Unknown' },
    { total: 10_000, used: 9_500, status: 'unavailable', expected: 'Unavailable' },
    { total: 10_000, used: 9_500, status: 'unrecognised', expected: 'Unknown' },
  ])(
    'does not let an optional percentage establish admitted capacity: $total/$used/$status',
    async ({ total, used, status, expected }) => {
      mockBackupAPIs();
      renderInRouter(() => (
        <ProxmoxBackupsTable
          emptyIcon={<span />}
          servers={[
            {
              ...pbsServerResource,
              pbs: {
                ...pbsServerResource.pbs!,
                datastores: [{ name: 'main', total, used, status, usagePercent: 95 }],
              },
            },
          ]}
        />
      ));
      await screen.findByText(expected);
      expect(screen.queryByText('95.0%')).not.toBeInTheDocument();
    },
  );

  it('keeps successful backup inventory independent of unavailable datastore capacity', async () => {
    mockBackupAPIs();
    window.history.replaceState({}, '', '/proxmox/backups/date');
    const failed = {
      ...pbsServerResource,
      pbs: {
        ...pbsServerResource.pbs!,
        datastores: [
          {
            name: 'main',
            total: 0,
            used: 0,
            available: 0,
            usagePercent: 0,
            status: 'unavailable',
            error: 'PRIVATE_PROVIDER_ERROR_SENTINEL',
          },
        ],
      },
    } as Resource;
    const [servers, setServers] = createSignal([failed]);
    const { container } = renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[workloadResource]}
        servers={servers()}
      />
    ));
    // The router mounts its page asynchronously. Wait for the capacity notice
    // before binding page-level queries to the server table.
    await screen.findByText('Unavailable');
    const table = container.querySelector('[data-proxmox-backups-table="servers"]') as HTMLElement;
    const backupCount = () => {
      const index = Array.from(table.querySelectorAll('th')).findIndex(
        (head) => head.getAttribute('aria-label') === 'Backups',
      );
      return table
        .querySelector('tbody tr:not([data-backup-server-group])')!
        .querySelectorAll('td')[index].textContent;
    };
    await within(table).findByText('Unavailable');
    await waitFor(() => expect(backupCount()).toBe('1'));
    await screen.findAllByText('Verified');
    expect(container.innerHTML).not.toContain('PRIVATE_PROVIDER_ERROR_SENTINEL');
    expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pbs')).toHaveLength(1);

    setServers([pbsServerResource]);
    await waitFor(() => expect(within(table).queryByText('Unavailable')).not.toBeInTheDocument());
    expect(backupCount()).toBe('1');
    expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pbs')).toHaveLength(1);
  });

  it('groups datastore rows under one header row per server', async () => {
    mockBackupAPIs();
    const twoStores = {
      ...pbsServerResource,
      pbs: {
        ...pbsServerResource.pbs!,
        datastores: [
          ...pbsServerResource.pbs!.datastores!,
          { name: 'offsite', total: 20_000, used: 5_000, available: 15_000, usagePercent: 25 },
        ],
      },
    } as Resource;
    const { container } = renderInRouter(() => (
      <WebSocketContext.Provider value={{ activeAlerts: {} } as unknown as WebSocketStore}>
        <DarkModeContext.Provider value={() => false}>
          <ProxmoxBackupsTable
            emptyIcon={<span />}
            workloads={[workloadResource]}
            servers={[twoStores]}
          />
        </DarkModeContext.Provider>
      </WebSocketContext.Provider>
    ));
    await screen.findByText('offsite');
    const table = container.querySelector('[data-proxmox-backups-table="servers"]') as HTMLElement;
    const columns = Array.from(table.querySelectorAll('col')).map((col) =>
      col.getAttribute('data-proxmox-backups-column'),
    );
    const dataRows = () =>
      Array.from(table.querySelectorAll('tbody tr')).filter(
        (row) => row.querySelectorAll('td').length === columns.length,
      );
    const cellText = (row: number, column: string) => {
      expect(columns).toContain(column);
      return dataRows()[row].querySelectorAll('td')[columns.indexOf(column)].textContent?.trim();
    };

    // Two datastores of one server read as two datastores, not two servers:
    // one header row names the server and counts its datastores, and each row
    // under it leads with its datastore name. There is no separate server
    // column. Host CPU, memory, uptime and version are in the server's drawer.
    const groups = Array.from(table.querySelectorAll('[data-backup-server-group]'));
    expect(groups).toHaveLength(1);
    expect(groups[0]).toHaveTextContent('pbs-main');
    expect(groups[0]).toHaveTextContent('2 datastores');
    expect(dataRows()).toHaveLength(2);
    expect(columns[0]).toBe('datastore');
    expect(columns).not.toContain('server');
    const datastoreNames = Array.from(table.querySelectorAll('[data-backup-server-datastore]')).map(
      (name) => name.textContent,
    );
    expect(datastoreNames).toEqual(['main', 'offsite']);
    expect(within(table).getAllByText('pbs-main')).toHaveLength(1);
    // Connection health is the server's: its header shows it, its rows do not.
    expect(columns).not.toContain('status');
    expect(
      within(groups[0] as HTMLElement).getByRole('img', { name: 'Healthy' }),
    ).toBeInTheDocument();
    expect(table.querySelector('[data-backup-servers-title]')).toHaveTextContent('Backup servers1');
    expect(
      columns.filter((column) => ['version', 'cpu', 'memory', 'uptime'].includes(column ?? '')),
    ).toEqual([]);
    expect(cellText(0, 'datastore')).toBe('main');
    expect(cellText(1, 'datastore')).toBe('offsite');
    expect(cellText(1, 'used')).toContain('25');
    const offsite = within(table).getByRole('button', {
      name: 'Expand details for pbs-main · datastore offsite',
    });
    expect(
      within(table).getByRole('button', {
        name: 'Expand details for pbs-main · datastore main',
      }),
    ).not.toBe(offsite);
    fireEvent.click(offsite);
    const selected = screen.getByRole('region', { name: 'Selected PBS datastore' });
    expect(within(selected).getByRole('heading')).toHaveTextContent('offsite');
    expect(selected).toHaveTextContent('on pbs-main');
    expect(within(selected).getByText('Capacity').closest('tr')).toHaveTextContent('25.0%');
    // The surrounding scan table is nowrap; the interpretation must wrap too,
    // not only the four fields protected by DetailSectionTable.wrapValues.
    expect(within(selected).getByText(/Backup entries can include running/)).toHaveClass(
      'whitespace-normal',
    );
  });

  it('uses a corroborated PBS host link for Backups History despite a PVE-only name collision', () => {
    const pbs = {
      ...pbsServerResource,
      name: 'backup-connection',
      displayName: 'Backup connection',
      metricsTarget: { resourceType: 'agent', resourceId: 'pbs-service' },
      pbs: {
        ...pbsServerResource.pbs!,
        hostname: '10.0.0.5',
        nodeName: undefined,
        linkedAgentId: 'agent-uuid',
      },
    } as Resource;
    const host = {
      ...workloadResource,
      id: 'host-merged-with-pve',
      type: 'agent',
      name: 'different-hostname',
      sources: ['proxmox', 'agent'],
      agent: { agentId: 'agent-uuid', hostname: 'different-hostname' },
      metricsTarget: { resourceType: 'agent', resourceId: 'agent-uuid' },
    } as Resource;
    const pveOnly = {
      ...host,
      id: 'pve-only',
      name: 'backup-connection',
      agent: undefined,
      sources: ['proxmox'],
      metricsTarget: { resourceType: 'agent', resourceId: 'pve-only' },
    } as Resource;

    const row = buildBackupServerRows([pbs, pveOnly, host])[0];
    expect(row.resource.id).toBe(pbs.id);
    expect(row.resource.pbs?.linkedAgentId).toBe('agent-uuid');
    expect(row.resource.metricsTarget).toEqual({ resourceType: 'agent', resourceId: 'agent-uuid' });
    expect(row.resource.agent?.agentId).toBe('agent-uuid');
  });

  it('shows Checking until the canonical posture request resolves', async () => {
    mockBackupAPIs();
    let resolvePosture: ((value: unknown) => void) | undefined;
    apiFetchJSONMock.mockReturnValue(
      new Promise((resolve) => {
        resolvePosture = resolve;
      }),
    );
    window.history.replaceState({}, '', '/?view=coverage');

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findAllByText('pbs-docker');
    expect(screen.getAllByText('Checking').length).toBeGreaterThan(0);

    resolvePosture?.({
      data: [
        {
          subjectResourceId: 'ct-112',
          state: 'protected',
          freshness: 'current',
          verification: 'verified',
          coverage: 'complete',
          providerStates: [],
          repositoryResourceIds: [],
          evidenceIds: ['evidence-1'],
          explanation: 'A current verified backup is available.',
          evaluatedAt: '2026-05-25T02:05:00Z',
        },
      ],
      policy: {
        freshnessWindowSeconds: 604800,
        verificationWindowSeconds: 604800,
        requireVerification: true,
      },
    });

    await waitFor(() =>
      expect(
        screen
          .getAllByTitle('A current verified backup is available.')
          .some((element) => element.textContent === 'Protected'),
      ).toBe(true),
    );
    expect(screen.queryByText('Checking')).not.toBeInTheDocument();
  });

  it('defaults to coverage when protection needs attention and keeps the dated feed one click away', async () => {
    mockBackupAPIs('attention');

    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[workloadResource]}
        servers={[pbsServerResource]}
      />
    ));

    await screen.findAllByText('pbs-docker');
    expect(screen.getByRole('link', { name: /coverage/i })).toHaveAttribute('aria-current', 'page');

    await fireEvent.click(screen.getByRole('link', { name: /by date/i }));

    // The chronological feed remains available for forensic review: one row
    // per restore point, sourced and located.
    expect(screen.getAllByText('pbs-docker').length).toBeGreaterThan(1);
    expect(screen.getByRole('columnheader', { name: /location/i })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: /source/i })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: /type/i })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: /target id/i })).toBeInTheDocument();
    expect(screen.getAllByText('LXC').length).toBeGreaterThan(0);
    expect(screen.getAllByText('PBS').length).toBeGreaterThan(0);
    expect(screen.getByText('2 PBS files')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /pbs backups/i })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /pve backup files/i })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /guest snapshots/i })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Archives' })).not.toBeInTheDocument();
    expect(screen.getByText('main / minipc')).toBeInTheDocument();
    expect(
      screen.getByRole('cell', {
        name: `${getRecoveryFullDateLabel('2026-05-25')} 3 entries`,
      }),
    ).toBeInTheDocument();
    const tables = screen.getAllByRole('table');
    expect(tables).toHaveLength(2);
    for (const table of tables) {
      expectCanonicalPlatformTableShell(table);
    }
    expect(apiFetchMock).toHaveBeenCalledWith('/api/backups/pbs', {
      signal: expect.any(AbortSignal),
    });
    expect(apiFetchMock).toHaveBeenCalledWith('/api/backups/pve', {
      signal: expect.any(AbortSignal),
    });
    expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
    const postureURL = new URL(apiFetchJSONMock.mock.calls[0][0], 'https://pulse.invalid');
    expect(postureURL.pathname).toBe('/api/recovery/postures');
    expect(postureURL.searchParams.getAll('resourceId')).toEqual(['ct-112']);
  });

  it('names a backup storage Pulse cannot read once, above the coverage list', async () => {
    mockBackupAPIs('protected');
    const response = await apiFetchJSONMock();
    response.data[0].coverage = 'partial';
    response.data[0].providerStates = [
      {
        provider: 'proxmox-pve',
        source: 'pve-backup-enumeration',
        scope: 'homelab',
        jobState: 'warning',
        historyCompleteness: 'partial',
        permissions: 'unknown',
        evidenceIds: ['evidence-2'],
        unreadScopes: [{ kind: 'storage', node: 'delly', storage: 'pbs-energy-offsite' }],
      },
    ];
    apiFetchJSONMock.mockResolvedValue(response);

    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[workloadResource]}
        servers={[pbsServerResource]}
      />
    ));

    const notice = await screen.findByText(
      'Pulse cannot read pbs-energy-offsite on delly, so it cannot confirm the backups stored there. Check that the storage is reachable from Proxmox.',
    );
    expect(notice).toHaveAttribute('role', 'status');
    expect(document.querySelectorAll('[data-unread-backup-sources]')).toHaveLength(1);
  });

  it('offers By date / Coverage views and no legacy sub-tab tree', async () => {
    mockBackupAPIs();

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findAllByText('pbs-docker');

    const healthSummary = screen.getByText(/^\d+ completed restore point/);
    // Restore-point totals sit in the header strip from sm up; a phone keeps
    // the protected count and reason rows.
    expect(healthSummary.parentElement).toHaveClass('hidden', 'sm:inline');

    // The two route-backed sections exist...
    expect(screen.getByRole('navigation', { name: /backup views/i })).toBeInTheDocument();
    expect(screen.getByRole('link', { name: /by date/i })).toHaveAttribute(
      'href',
      '/proxmox/backups/date',
    );
    expect(screen.getByRole('link', { name: /coverage/i })).toHaveAttribute(
      'href',
      '/proxmox/backups/coverage',
    );
    // ...and the old four-tab + sub-tab tree does not.
    expect(screen.queryByRole('button', { name: /source details/i })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /job history/i })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /pbs artifacts/i })).not.toBeInTheDocument();
  });

  it('hydrates the complete saved-view filter state from the URL and clears it atomically', async () => {
    mockBackupAPIs();
    window.history.replaceState(
      {},
      '',
      '/?view=date&q=pbs-docker&source=pbs&location=pbs%3Apbs-main%3Amain&node=pve-a&type=ct&day=2026-01-01',
    );

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findAllByText('pbs-docker');
    expect(screen.getByRole('link', { name: /by date/i })).toHaveAttribute('aria-current', 'page');
    expect(screen.getByPlaceholderText(/search backups by workload/i)).toHaveValue('pbs-docker');
    expect(screen.getByRole('button', { name: /pbs backups/i })).toHaveAttribute(
      'aria-pressed',
      'true',
    );
    // An old bookmark's day no longer narrows the list; Clear filters drops it.
    expect(screen.queryByRole('button', { name: /clear date filter/i })).not.toBeInTheDocument();
    expect(
      screen.getByRole('button', { name: 'Backup location: PBS · pbs-main / main' }),
    ).toBeInTheDocument();

    await fireEvent.click(screen.getByRole('button', { name: /clear filters/i }));

    await waitFor(() => {
      const params = new URLSearchParams(window.location.search);
      expect(params.get('view')).toBeNull();
      expect(params.get('q')).toBeNull();
      expect(params.get('source')).toBeNull();
      expect(params.get('location')).toBeNull();
      expect(params.get('node')).toBeNull();
      expect(params.get('type')).toBeNull();
      expect(params.get('day')).toBeNull();
    });
    expect(screen.getByPlaceholderText(/search backups by workload/i)).toHaveValue('');
  });

  it('filters restore points and coverage by PBS server and datastore', async () => {
    window.history.replaceState({}, '', '/proxmox/backups/date');
    const offsitePayload = {
      ...pbsPayload,
      data: {
        backups: [
          ...pbsPayload.data.backups,
          {
            ...pbsPayload.data.backups[0],
            id: 'pbs-offsite/offsite/minipc/ct/112/2026-05-24T01:34:25Z',
            instance: 'pbs-offsite',
            datastore: 'offsite',
            backupTime: '2026-05-24T01:34:25Z',
          },
        ],
      },
    };
    mockBackupAPIs('protected', offsitePayload);

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findByText('offsite / minipc');
    const filterSelect = screen.getByRole('combobox', { name: 'Filter' });
    const offsiteOption = screen.getByRole('option', {
      name: 'Backup location: PBS · pbs-offsite / offsite',
    }) as HTMLOptionElement;
    await fireEvent.change(filterSelect, { target: { value: offsiteOption.value } });

    await waitFor(() =>
      expect(new URLSearchParams(window.location.search).get('location')).toBe(
        '["pbs","pbs-offsite","offsite"]',
      ),
    );
    expect(screen.getByText('offsite / minipc')).toBeInTheDocument();
    expect(screen.queryByText('main / minipc')).not.toBeInTheDocument();
    expect(
      screen.getByRole('button', { name: 'Backup location: PBS · pbs-offsite / offsite' }),
    ).toBeInTheDocument();

    await fireEvent.click(screen.getByRole('link', { name: /coverage/i }));
    await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
    expect(new URLSearchParams(window.location.search).get('location')).toBe(
      '["pbs","pbs-offsite","offsite"]',
    );
    expect(screen.getAllByText('pbs-docker').length).toBeGreaterThan(0);
    await fireEvent.click(screen.getByRole('button', { name: /expand details for pbs-docker/i }));
    expect(screen.getByText('offsite / minipc')).toBeInTheDocument();
    expect(screen.queryByText('main / minipc')).not.toBeInTheDocument();
  });

  it('clears incompatible URL facets when switching backup views', async () => {
    mockBackupAPIs();
    window.history.replaceState({}, '', '/?view=date&source=pbs&day=2026-05-25');

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findAllByText('pbs-docker');
    await fireEvent.click(screen.getByRole('link', { name: /coverage/i }));

    await waitFor(() => {
      const params = new URLSearchParams(window.location.search);
      expect(window.location.pathname).toBe('/proxmox/backups/coverage');
      expect(params.get('view')).toBeNull();
      expect(params.get('source')).toBeNull();
      expect(params.get('day')).toBeNull();
    });

    await fireEvent.click(screen.getByRole('button', { name: /^protected$/i }));
    await waitFor(() =>
      expect(new URLSearchParams(window.location.search).get('posture')).toBe('protected'),
    );

    await fireEvent.click(screen.getByRole('link', { name: /by date/i }));
    await waitFor(() => {
      const params = new URLSearchParams(window.location.search);
      expect(window.location.pathname).toBe('/proxmox/backups/date');
      expect(params.get('view')).toBeNull();
      expect(params.get('posture')).toBeNull();
    });
  });

  it('lists a failed PBS sync as a datastore problem while the guest stays protected (#1815)', async () => {
    mockBackupAPIs();
    window.history.replaceState({}, '', '/proxmox/backups/coverage');
    const scrollIntoView = vi.fn();
    const prototype = HTMLElement.prototype as { scrollIntoView?: (arg?: unknown) => void };
    const original = prototype.scrollIntoView;
    prototype.scrollIntoView = scrollIntoView;
    try {
      const server = {
        ...pbsServerResource,
        pbs: {
          ...pbsServerResource.pbs!,
          jobHealthEvidence: [
            {
              id: 's-main',
              family: 'sync',
              store: 'main',
              remote: 'pbs-offsite',
              enabled: true,
              confidence: 'config-last-run',
              posture: 'critical',
              postureReason: 'last-run-failed',
            },
          ],
        },
      } as Resource;
      renderInRouter(() => (
        <ProxmoxBackupsTable
          emptyIcon={<span />}
          workloads={[workloadResource]}
          servers={[server]}
        />
      ));

      await waitFor(() =>
        expect(document.querySelector('[data-backup-verdict]')).toHaveTextContent(
          '1 of 1 protected',
        ),
      );
      const problems = within(screen.getByRole('list', { name: 'Datastores with failed jobs' }));
      const row = problems.getByRole('button', { name: 'Sync failed on 1 datastore: main' });
      expect(row).toHaveTextContent('Sync failed');
      expect(row).toHaveAttribute('title', 'Show in Backup servers: main');
      // The datastore problem is not a guest: no guest exception appears.
      expect(
        screen.queryByRole('list', { name: 'Backups that are not protected' }),
      ).toBeEmptyDOMElement();

      fireEvent.click(row);
      expect(scrollIntoView).toHaveBeenCalledTimes(1);
      expect(scrollIntoView.mock.contexts[0]).toBe(
        document.querySelector('[data-backup-servers-section]'),
      );
    } finally {
      prototype.scrollIntoView = original;
    }
  });

  it('states the verdict and names each exception group by its reason', async () => {
    mockBackupAPIs('attention');
    window.history.replaceState({}, '', '/proxmox/backups/date');

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    const verdict = await waitFor(() => {
      const element = document.querySelector('[data-backup-verdict]');
      expect(element).toHaveTextContent('0 of 1 protected');
      return element!;
    });
    expect(verdict).toHaveAttribute('data-backup-verdict', 'attention');
    const exceptions = within(screen.getByRole('list', { name: 'Backups that are not protected' }));
    const group = exceptions.getByRole('button', { name: '1 last backup failed' });
    expect(group).toHaveTextContent('Last backup failed');
    // The hover title says where a click goes and previews the names; the
    // filtered Coverage table lists them all.
    expect(group).toHaveAttribute('title', 'Show in Coverage: pbs-docker (LXC 112)');
    expect(group).not.toHaveTextContent('pbs-docker');
    // A trailing chevron marks the row as one that opens something.
    expect(group.querySelector('svg.lucide-chevron-right')).not.toBeNull();
    // The old posture bar and per-posture counts are gone: the sentence is the answer.
    expect(screen.queryByRole('button', { name: '1 attention' })).toBeNull();
  });

  it('places a page-owned summary beside Backup health', async () => {
    mockBackupAPIs('attention');
    window.history.replaceState({}, '', '/proxmox/backups/date');

    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[workloadResource]}
        summaryAside={<section data-backup-jobs="complete">Backup jobs</section>}
      />
    ));

    const verdict = await waitFor(() => {
      const element = document.querySelector('[data-backup-verdict]');
      expect(element).toHaveTextContent('0 of 1 protected');
      return element!;
    });
    const aside = document.querySelector('[data-backup-jobs]')!;
    const grid = aside.parentElement!;
    // Same summary grid as the health card, which goes two-up from xl only
    // while the jobs card renders.
    expect(grid).toContainElement(verdict as HTMLElement);
    expect(grid.className).toContain('xl:[&:has([data-backup-jobs])]:grid-cols-');
  });

  it('answers health first, then the backup servers, then the restore points', async () => {
    mockBackupAPIs('attention');
    window.history.replaceState({}, '', '/proxmox/backups/date');

    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[workloadResource]}
        servers={[pbsServerResource]}
      />
    ));

    const verdict = await waitFor(() => {
      const element = document.querySelector('[data-backup-verdict]');
      expect(element).toHaveTextContent('0 of 1 protected');
      return element!;
    });
    const servers = document.querySelector('[data-proxmox-backups-table="servers"]')!;
    const restorePoints = document.querySelector<HTMLElement>('[data-backup-restore-points]')!;
    const follows = (first: Node, second: Node) =>
      Boolean(first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING);
    expect(follows(verdict, servers)).toBe(true);
    expect(follows(servers, restorePoints)).toBe(true);
    // The view tabs head the restore points; health and jobs belong to the page.
    expect(within(restorePoints).getByRole('navigation', { name: 'Backup views' })).toBeTruthy();
    expect(restorePoints.contains(verdict)).toBe(false);
    expect(restorePoints.contains(servers)).toBe(false);
  });

  it('brings the restore points into view after an exception tap only when they are below the fold', async () => {
    mockBackupAPIs('attention');
    window.history.replaceState({}, '', '/proxmox/backups/date');
    const scrollIntoView = vi.fn();
    const prototype = HTMLElement.prototype as { scrollIntoView?: (arg?: unknown) => void };
    const original = prototype.scrollIntoView;
    prototype.scrollIntoView = scrollIntoView;
    try {
      renderInRouter(() => (
        <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
      ));
      await waitFor(() =>
        expect(document.querySelector('[data-backup-verdict]')).toHaveTextContent(
          '0 of 1 protected',
        ),
      );
      const restorePoints = document.querySelector<HTMLElement>('[data-backup-restore-points]')!;
      const top = vi.spyOn(restorePoints, 'getBoundingClientRect');
      const group = () =>
        within(screen.getByRole('list', { name: 'Backups that are not protected' })).getByRole(
          'button',
          { name: '1 last backup failed' },
        );
      const reason = () => new URLSearchParams(window.location.search).get('reason');
      const settle = async () => {
        await Promise.resolve();
        await Promise.resolve();
      };
      const belowFold = { top: window.innerHeight + 300 } as DOMRect;

      // From By date, below the fold (phone): the tap lands on the filtered
      // Coverage list and brings the restore points into view.
      top.mockReturnValue(belowFold);
      await fireEvent.click(group());
      await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
      expect(reason()).toBe('source-failed');
      await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(1));
      expect(scrollIntoView.mock.contexts[0]).toBe(restorePoints);
      expect(scrollIntoView).toHaveBeenCalledWith(expect.objectContaining({ block: 'start' }));

      // Clearing the filter never scrolls, even with the list below the fold.
      await fireEvent.click(group());
      await waitFor(() => expect(reason()).toBeNull());
      await settle();
      expect(scrollIntoView).toHaveBeenCalledTimes(1);

      // On Coverage with the list already on screen (desktop): no scroll.
      top.mockReturnValue({ top: 120 } as DOMRect);
      await fireEvent.click(group());
      await waitFor(() => expect(reason()).toBe('source-failed'));
      await settle();
      expect(scrollIntoView).toHaveBeenCalledTimes(1);

      // On Coverage below the fold: selecting again reveals the list.
      await fireEvent.click(group());
      await waitFor(() => expect(reason()).toBeNull());
      top.mockReturnValue(belowFold);
      await fireEvent.click(group());
      await waitFor(() => expect(reason()).toBe('source-failed'));
      await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(2));
      expect(scrollIntoView.mock.contexts[1]).toBe(restorePoints);
    } finally {
      if (original) prototype.scrollIntoView = original;
      else delete prototype.scrollIntoView;
    }
  });

  it('lets a backup exception group filter Coverage to those workloads', async () => {
    // "17 attention" was text: finding which workloads it counted took the
    // Filters sheet on a phone. A group is one tap to exactly its workloads.
    mockBackupAPIs('attention');
    window.history.replaceState({}, '', '/proxmox/backups/date');

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    // Keep accessible-role queries in the exception list so unrelated table
    // rows do not add lookup work to the unchanged five-second test budget.
    const exceptions = within(
      await screen.findByRole('list', { name: 'Backups that are not protected' }),
    );
    const group = await exceptions.findByRole('button', {
      name: '1 last backup failed',
    });
    expect(group).toHaveAttribute('aria-pressed', 'false');
    // Health bars fill with the metric bar colours every other Pulse bar uses.
    expect(group.querySelector('.progress-fill')).toHaveClass('bg-metric-warning-bg');

    await fireEvent.click(group);
    await waitFor(() => {
      expect(window.location.pathname).toBe('/proxmox/backups/coverage');
      expect(new URLSearchParams(window.location.search).get('reason')).toBe('source-failed');
    });
    expect(new URLSearchParams(window.location.search).get('posture')).toBeNull();
    expect(exceptions.getByRole('button', { name: '1 last backup failed' })).toHaveAttribute(
      'aria-pressed',
      'true',
    );
    expect(group).toHaveAttribute('title', 'Clear this filter in Coverage');
    expect(screen.getAllByText('pbs-docker').length).toBeGreaterThan(0);

    // Toggling off keeps the same focused control rather than rebuilding it.
    const pressed = exceptions.getByRole('button', { name: '1 last backup failed' });
    expect(pressed).toBe(group);
    pressed.focus();
    await fireEvent.click(pressed);
    await waitFor(() =>
      expect(new URLSearchParams(window.location.search).get('reason')).toBeNull(),
    );
    expect(window.location.pathname).toBe('/proxmox/backups/coverage');
    expect(pressed).toHaveAttribute('aria-pressed', 'false');
    expect(pressed).toHaveFocus();
  });

  it('drops an exception group when a posture is chosen, so the two never narrow to nothing', async () => {
    mockBackupAPIs('attention');
    window.history.replaceState({}, '', '/proxmox/backups/coverage?reason=source-failed');

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findByRole('button', {
      name: '1 last backup failed',
      pressed: true,
    });
    await fireEvent.click(screen.getByRole('button', { name: /^protected$/i }));
    await waitFor(() => {
      const params = new URLSearchParams(window.location.search);
      expect(params.get('posture')).toBe('protected');
      expect(params.get('reason')).toBeNull();
    });
  });

  it('applies an exception group from the bare Backups route on the Coverage route', async () => {
    mockBackupAPIs('attention');
    window.history.replaceState({}, '', '/proxmox/backups');

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await fireEvent.click(await screen.findByRole('button', { name: '1 last backup failed' }));
    await waitFor(() => {
      expect(window.location.pathname).toBe('/proxmox/backups/coverage');
      expect(new URLSearchParams(window.location.search).get('reason')).toBe('source-failed');
    });
  });

  it('switches to Coverage showing posture, and keeps per-source evidence in the row expansion', async () => {
    mockBackupAPIs();

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findAllByText('pbs-docker');
    await fireEvent.click(screen.getByRole('link', { name: /coverage/i }));

    // Coverage is the posture view; the server-owned workload posture reads
    // "Protected".
    expect(screen.getByRole('columnheader', { name: /posture/i })).toBeInTheDocument();
    expect(screen.getAllByText('Protected').length).toBeGreaterThan(0);

    // Per-source detail is one click down inside the workload's row.
    const disclosure = screen.getByRole('button', { name: /expand details for pbs-docker/i });
    await fireEvent.click(disclosure);
    expect(screen.getByText('Restore evidence')).toBeInTheDocument();
    expect(screen.getAllByText('PVE file').length).toBeGreaterThan(0);
    expect(screen.getAllByText('Snapshot').length).toBeGreaterThan(0);
    // The drawer keeps the shared detail shell, whose phone width is capped
    // at the table's visible area; a padding override once dropped that cap.
    const detailCell = document.getElementById(disclosure.getAttribute('aria-controls') ?? '');
    expect(detailCell?.firstElementChild?.className).toContain('max-w-[100cqi]');
  });

  it('keeps retained snapshot posture distinct from the raw list and a readable peer', async () => {
    const retainedGuest = {
      ...workloadResource,
      id: 'ct-111',
      name: 'database-a',
      displayName: 'database-a',
      proxmox: { ...workloadResource.proxmox!, vmid: 111 },
    } as Resource;
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse(
          url === '/api/backups/pve'
            ? { data: { ...pvePayload.data, storageBackups: [], backupTasks: [] } }
            : { data: { backups: [] } },
        ),
      ),
    );
    const explanation =
      'Only snapshots were found. A snapshot is not a separate backup, so it does not count.';
    apiFetchJSONMock.mockResolvedValue({
      data: [retainedGuest, workloadResource].map((guest) => ({
        subjectResourceId: guest.id,
        state: 'unprotected',
        coverage: 'none',
        freshness: 'unknown',
        verification: 'unknown',
        providerStates: [
          {
            provider: 'proxmox-pve',
            source: 'pve-backup-enumeration',
            scope: 'pve-a',
            jobState: 'success',
            historyCompleteness: 'complete',
            permissions: 'sufficient',
            evidenceIds: [],
          },
        ],
        repositoryResourceIds: [],
        evidenceIds: [],
        explanation,
        evaluatedAt: '2026-05-25T02:05:00Z',
      })),
      policy: protectionPolicy,
    });
    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[retainedGuest, workloadResource]} />
    ));

    await screen.findAllByText('pbs-docker');
    await fireEvent.click(screen.getByRole('link', { name: /coverage/i }));
    await fireEvent.click(screen.getByRole('button', { name: /expand details for database-a/i }));
    const detail = screen.getByTestId('proxmox-coverage-detail');
    await within(detail).findByText(explanation);
    expect(within(detail).getByText('History Complete')).toBeInTheDocument();
    expect(within(detail).getByRole('status')).toHaveTextContent(
      'No restore-point details are visible in the current list. The posture above may use previously recorded evidence.',
    );
    expect(within(detail).queryByText('Restore evidence')).not.toBeInTheDocument();
    expect(within(detail).queryByText('pre-upgrade')).not.toBeInTheDocument();
    expect(detail).not.toHaveTextContent('No restore points reported');

    await fireEvent.click(screen.getByRole('button', { name: /expand details for pbs-docker/i }));
    const peer = screen.getByTestId('proxmox-coverage-detail');
    expect(within(peer).getByText('Restore evidence')).toBeInTheDocument();
    expect(peer.querySelector('[data-coverage-evidence-detail]')).toHaveTextContent(
      'Metadata: pre-upgrade',
    );
    expect(within(peer).queryByRole('status')).not.toBeInTheDocument();
    expect(
      screen.queryByText('previously recorded evidence', { exact: false }),
    ).not.toBeInTheDocument();
  });

  it('keeps coverage evidence expanded across repeated workload snapshots', async () => {
    mockBackupAPIs();
    const [workloads, setWorkloads] = createSignal<readonly Resource[]>([workloadResource]);
    renderInRouter(() => <ProxmoxBackupsTable emptyIcon={<span />} workloads={workloads()} />);

    await screen.findAllByText('pbs-docker');
    await fireEvent.click(screen.getByRole('link', { name: /coverage/i }));
    await fireEvent.click(screen.getByRole('button', { name: /expand details for pbs-docker/i }));

    const toggle = screen.getByRole('button', { name: /collapse details for pbs-docker/i });
    toggle.focus();

    for (let snapshot = 1; snapshot <= 3; snapshot += 1) {
      const name = `pbs-docker-snapshot-${snapshot}`;
      setWorkloads([{ ...workloadResource, name, displayName: name }]);

      // Assert the new snapshot reached the rendered table, rather than merely
      // checking that a stale expanded row survived.
      await screen.findAllByText(name);
      expect(screen.getByRole('button', { name: /collapse details for pbs-docker/i })).toBe(toggle);
      expect(toggle).toHaveFocus();
      expect(screen.getByRole('columnheader', { name: /posture/i })).toBeInTheDocument();
      expect(screen.getByText('Restore evidence')).toBeInTheDocument();
      expect(screen.getAllByText('PVE file').length).toBeGreaterThan(0);
      expect(screen.getAllByText('Snapshot').length).toBeGreaterThan(0);
    }
  });

  it('filters the backup feed by search term', async () => {
    mockBackupAPIs();

    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

    await screen.findAllByText('pbs-docker');
    await fireEvent.click(screen.getByRole('link', { name: /by date/i }));

    const searchInput = screen.getByPlaceholderText(/search backups by workload/i);
    await fireEvent.input(searchInput, { target: { value: 'no-such-guest' } });

    expect(screen.queryByText('pbs-docker')).not.toBeInTheDocument();
    const emptyStateHeading = screen.getByRole('heading', {
      name: /no recoverable artifacts match current filters/i,
    });
    expect(emptyStateHeading).toBeInTheDocument();
    expect(
      screen.getByText('Adjust the search or filters to see more artifacts.'),
    ).toBeInTheDocument();
    expectClassTokens(
      emptyStateHeading.closest(`.${TABLE_CARD_FRAME_CLASS}`),
      TABLE_CARD_FRAME_CLASS,
    );
    expect(emptyStateHeading.closest('.border-dashed')).not.toBeNull();
  });
});

const emptyPVE = { data: { backupTasks: [], storageBackups: [], guestSnapshots: [] } };
const emptyPBS = { data: { backups: [] } };
const readPvePayload = { data: { ...pvePayload.data, guestSnapshots: [] } };
const deferred = <T,>() => {
  let resolve!: (value: T) => void;
  const promise = new Promise<T>((res) => (resolve = res));
  return { promise, resolve };
};
const mountBackupReadState = () =>
  renderInRouter(() => (
    <ProxmoxBackupsTable
      emptyIcon={<span />}
      workloads={[workloadResource]}
      servers={[pbsServerResource]}
    />
  ));
const recoverableRows = () => document.querySelectorAll('[data-proxmox-backup-row="recoverable"]');
const serverTable = () => document.querySelector('[data-proxmox-backups-table="servers"]')!;
const sourceCalls = (source: 'pve' | 'pbs') =>
  apiFetchMock.mock.calls.filter(([url]) => url === `/api/backups/${source}`);

describe('backup read recovery keeps keyboard position', () => {
  beforeEach(() => window.history.replaceState({}, '', '/proxmox/backups/coverage?q=backup#proof'));
  afterEach(() => {
    setKioskMode(false);
    window.sessionStorage.removeItem('pulse_kiosk_mode');
  });

  const acceptedPosture = { data: [protectionPosture('ct-112')], policy: protectionPolicy };
  const setup = (source: 'pve' | 'pbs' | 'posture') => {
    let read = Promise.resolve(new Response('{}', { status: 503 }));
    apiFetchMock.mockImplementation((url: string) =>
      url.endsWith(`/${source}`)
        ? read
        : Promise.resolve(jsonResponse(url.endsWith('/pve') ? readPvePayload : pbsPayload)),
    );
    apiFetchJSONMock.mockImplementation(() =>
      source === 'posture'
        ? read.then(async (response) => {
            if (!response.ok) throw new Error('Synthetic unavailable posture');
            return response.json();
          })
        : Promise.resolve(acceptedPosture),
    );
    return {
      mount: () => mountBackupReadState(),
      pending: () => {
        const pending = deferred<Response>();
        read = pending.promise;
        return (success = true) =>
          pending.resolve(
            success
              ? jsonResponse(
                  source === 'posture'
                    ? acceptedPosture
                    : source === 'pve'
                      ? readPvePayload
                      : pbsPayload,
                )
              : new Response('{}', { status: 503 }),
          );
      },
      label:
        source === 'posture'
          ? 'Retry protection posture'
          : `Retry ${source.toUpperCase()} inventory`,
    };
  };

  it.each(['pve', 'pbs', 'posture'] as const)(
    'keeps %s retry focused while pending and after failure, then hands successful recovery to the active view',
    async (source) => {
      const fixture = setup(source);
      fixture.mount();
      const retry = await screen.findByRole('button', { name: fixture.label });
      retry.focus();
      let finish = fixture.pending();
      fireEvent.click(retry);
      expect(retry).toHaveFocus();
      expect(retry).toHaveAttribute('aria-disabled', 'true');
      const count = apiFetchMock.mock.calls.length + apiFetchJSONMock.mock.calls.length;
      fireEvent.click(retry);
      expect(apiFetchMock.mock.calls.length + apiFetchJSONMock.mock.calls.length).toBe(count);
      finish(false);
      await waitFor(() => expect(retry).toHaveAttribute('aria-disabled', 'false'));
      expect(retry).toHaveFocus();
      finish = fixture.pending();
      fireEvent.click(retry);
      finish();
      await waitFor(() => expect(screen.getByRole('link', { name: 'Coverage' })).toHaveFocus());
      expect(screen.queryByRole('button', { name: fixture.label })).toBeNull();
      expect(window.location.pathname + window.location.search + window.location.hash).toBe(
        '/proxmox/backups/coverage?q=backup#proof',
      );
    },
  );

  it('retains retry focus when a new notice follows a successful read and later polling failure', async () => {
    vi.useFakeTimers({
      now: BACKUP_IDENTITY_NOW,
      toFake: ['Date', 'setInterval', 'clearInterval'],
    });
    try {
      const fixture = setup('pbs');
      fixture.mount();
      const first = await screen.findByRole('button', { name: fixture.label });
      let finish = fixture.pending();
      fireEvent.click(first);
      finish();
      await waitFor(() => expect(first).not.toBeInTheDocument());
      finish = fixture.pending();
      await vi.advanceTimersByTimeAsync(30_000);
      finish(false);
      const later = await screen.findByRole('button', { name: fixture.label });
      later.focus();
      finish = fixture.pending();
      fireEvent.click(later);
      expect(later).toHaveFocus();
      finish();
      await waitFor(() => expect(later).not.toBeInTheDocument());
      await waitFor(() => expect(screen.getByRole('link', { name: 'Coverage' })).toHaveFocus());
      expect(window.location.pathname + window.location.search + window.location.hash).toBe(
        '/proxmox/backups/coverage?q=backup#proof',
      );
    } finally {
      vi.useRealTimers();
    }
  });

  it.each(['pve', 'pbs', 'posture'] as const)(
    'does not steal focus moved away from the %s retry',
    async (source) => {
      const fixture = setup(source);
      fixture.mount();
      const retry = await screen.findByRole('button', { name: fixture.label });
      retry.focus();
      const finish = fixture.pending();
      fireEvent.click(retry);
      const search = screen.getByPlaceholderText(
        'Search backups by workload, node, source, or status',
      );
      search.focus();
      finish();
      await waitFor(() => expect(retry).not.toBeInTheDocument());
      expect(search).toHaveFocus();
    },
  );

  it('hands whole-inventory Refresh focus to inspection when either source recovers', async () => {
    apiFetchMock.mockResolvedValue(new Response('{}', { status: 503 }));
    apiFetchJSONMock.mockResolvedValue(acceptedPosture);
    mountBackupReadState();
    const refresh = await screen.findByRole('button', { name: 'Refresh' });
    refresh.focus();
    const pve = deferred<Response>();
    const pbs = deferred<Response>();
    apiFetchMock.mockImplementation((url: string) =>
      url.endsWith('/pve') ? pve.promise : pbs.promise,
    );
    fireEvent.click(refresh);
    fireEvent.click(refresh);
    expect(sourceCalls('pve')).toHaveLength(2);
    expect(sourceCalls('pbs')).toHaveLength(2);
    pve.resolve(jsonResponse(readPvePayload));
    await waitFor(() => expect(screen.getByRole('link', { name: 'Coverage' })).toHaveFocus());
    expect(screen.getByRole('button', { name: 'Retry PBS inventory' })).toBeInTheDocument();
    pbs.resolve(jsonResponse(pbsPayload));
    await waitFor(() =>
      expect(screen.queryByRole('button', { name: 'Retry PBS inventory' })).toBeNull(),
    );
    expect(screen.getByRole('link', { name: 'Coverage' })).toHaveFocus();
  });

  it('uses the named inspection region when kiosk mode hides the view links', async () => {
    setKioskMode(true);
    const fixture = setup('pbs');
    fixture.mount();
    const retry = await screen.findByRole('button', { name: fixture.label });
    retry.focus();
    const finish = fixture.pending();
    fireEvent.click(retry);
    finish();
    await waitFor(() =>
      expect(screen.getByRole('region', { name: 'Backup inspection' })).toHaveFocus(),
    );
    expect(screen.queryByRole('navigation', { name: 'Backup views' })).toBeNull();
  });

  it('never restores focus after the inspection has been unmounted', async () => {
    const fixture = setup('pbs');
    const mounted = fixture.mount();
    const retry = await screen.findByRole('button', { name: fixture.label });
    retry.focus();
    const finish = fixture.pending();
    fireEvent.click(retry);
    mounted.unmount();
    const outside = document.createElement('button');
    document.body.append(outside);
    outside.focus();
    finish();
    await Promise.resolve();
    await Promise.resolve();
    expect(outside).toHaveFocus();
    outside.remove();
  });
});

describe('independent Proxmox backup inventory reads', () => {
  beforeEach(() => {
    window.history.replaceState({}, '', '/proxmox/backups/date');
    apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });
  });

  const duplicateCases = [
    ['pve', 'backupTasks'],
    ['pve', 'storageBackups'],
    ['pve', 'guestSnapshots'],
    ['pbs', 'backups'],
  ] as const;
  const duplicated = (source: 'pve' | 'pbs', key: string, conflicting = false) => {
    const data: Record<string, unknown> = {
      ...(source === 'pbs' ? pbsPayload.data : pvePayload.data),
    };
    const [row] = data[key] as Record<string, unknown>[];
    data[key] = [
      row,
      conflicting
        ? { ...row, instance: 'UNACCEPTED_CONNECTION', status: 'failed', size: 2 ** 40 }
        : row,
    ];
    return { data };
  };

  it.each(duplicateCases)(
    'rejects an initial duplicate %s %s collection without hiding the independent source',
    async (source, key) => {
      apiFetchMock.mockImplementation((url: string) =>
        Promise.resolve(
          jsonResponse(
            url.endsWith(`/${source}`)
              ? duplicated(source, key)
              : source === 'pve'
                ? pbsPayload
                : readPvePayload,
          ),
        ),
      );
      mountBackupReadState();
      await screen.findByText(/The response format is invalid/);
      await waitFor(() => expect(recoverableRows()).toHaveLength(1));
      expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
      expect(screen.getByText(/The response format is invalid/)).toHaveTextContent(
        'Counts are incomplete.',
      );
      expect(
        screen.getByRole('button', { name: `Retry ${source.toUpperCase()} inventory` }),
      ).toBeEnabled();
      expect(document.querySelectorAll('[data-testid="proxmox-recoverable-detail"]')).toHaveLength(
        0,
      );
    },
  );

  it.each(duplicateCases)(
    'withdraws ambiguous %s %s on refresh, preserves independent details and recovers only through valid reads',
    async (source, key) => {
      let bad = false;
      apiFetchMock.mockImplementation((url: string) =>
        Promise.resolve(
          jsonResponse(
            bad && url.endsWith(`/${source}`)
              ? duplicated(source, key, true)
              : url.endsWith('/pbs')
                ? pbsPayload
                : pvePayload,
          ),
        ),
      );
      vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
      try {
        mountBackupReadState();
        await waitFor(() => expect(recoverableRows()).toHaveLength(3));
        const affected = [...recoverableRows()].find((row) =>
          row.textContent?.includes(source === 'pve' ? 'PVE file' : 'PBS'),
        )! as HTMLElement;
        fireEvent.click(within(affected).getByRole('button', { name: /expand details/i }));
        await screen.findByTestId('proxmox-recoverable-detail');
        bad = true;
        await vi.advanceTimersByTimeAsync(30_000);
        await screen.findByText(/The response format is invalid/);
        expect(recoverableRows()).toHaveLength(source === 'pve' ? 1 : 2);
        expect(screen.queryByTestId('proxmox-recoverable-detail')).not.toBeInTheDocument();
        expect(document.body).not.toHaveTextContent('UNACCEPTED_CONNECTION');
        expect(screen.getByText(/The response format is invalid/)).toHaveTextContent(
          'Counts are incomplete.',
        );
        const independent = recoverableRows()[0] as HTMLElement;
        fireEvent.click(within(independent).getByRole('button', { name: /expand details/i }));
        const detail = await screen.findByTestId('proxmox-recoverable-detail');
        const accepted = detail.textContent;
        const other = source === 'pve' ? 'pbs' : 'pve';
        const before = sourceCalls(other).length;
        const retry = screen.getByRole('button', {
          name: `Retry ${source.toUpperCase()} inventory`,
        });
        bad = false;
        fireEvent.click(retry);
        await waitFor(() => expect(retry).not.toBeInTheDocument());
        expect(sourceCalls(other)).toHaveLength(before);
        expect(recoverableRows()).toHaveLength(3);
        expect(screen.getByTestId('proxmox-recoverable-detail')).toHaveTextContent(accepted!);
        bad = true;
        await vi.advanceTimersByTimeAsync(30_000);
        await screen.findByText(/The response format is invalid/);
        expect(recoverableRows()).toHaveLength(source === 'pve' ? 1 : 2);
        expect(screen.getByTestId('proxmox-recoverable-detail')).toBe(detail);
        expect(detail.textContent).toBe(accepted);
        expect(document.body).not.toHaveTextContent('UNACCEPTED_CONNECTION');
      } finally {
        vi.useRealTimers();
      }
    },
  );

  it.each(['pve', 'pbs'] as const)(
    'keeps malformed HTTP200 %s responses source-local and recovers with an isolated retry',
    async (source) => {
      const bad = source === 'pbs' ? { data: { backups: [null] } } : { data: {} };
      let response = Promise.resolve(jsonResponse(bad));
      apiFetchMock.mockImplementation((url) =>
        url.endsWith(`/${source}`)
          ? response
          : Promise.resolve(jsonResponse(source === 'pve' ? pbsPayload : readPvePayload)),
      );
      mountBackupReadState();
      await screen.findByText(/The response format is invalid/);
      await waitFor(() => expect(recoverableRows()).toHaveLength(1));
      expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
      expect(screen.queryByRole('alert')).not.toBeInTheDocument();
      if (source === 'pbs') expect(serverTable()).toHaveTextContent('Unavailable');
      const pending = deferred<Response>();
      response = pending.promise;
      const retry = screen.getByRole('button', { name: `Retry ${source.toUpperCase()} inventory` });
      fireEvent.click(retry);
      expect(retry).toHaveAttribute('aria-disabled', 'true');
      expect(screen.getByText(/The response format is invalid/)).toBeInTheDocument();
      expect(recoverableRows()).toHaveLength(1);
      pending.resolve(jsonResponse(source === 'pbs' ? pbsPayload : readPvePayload));
      await waitFor(() => expect(recoverableRows()).toHaveLength(2));
      expect(screen.queryByText(/The response format is invalid/)).not.toBeInTheDocument();
      expect(sourceCalls(source === 'pbs' ? 'pve' : 'pbs')).toHaveLength(1);
    },
  );

  it('does not infer empty PBS inventory from a missing data envelope', async () => {
    apiFetchMock.mockImplementation((url) =>
      Promise.resolve(jsonResponse(url.endsWith('/pbs') ? {} : emptyPVE)),
    );
    mountBackupReadState();
    await screen.findByText('Backup inventory is incomplete');
    expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
    expect(serverTable()).toHaveTextContent('Unavailable');
  });

  it('keeps undecodable successful bodies out of user-facing diagnostics', async () => {
    apiFetchMock.mockImplementation((url) =>
      Promise.resolve(
        url.endsWith('/pbs')
          ? new Response('SYNTHETIC_PRIVATE_BODY_DO_NOT_DISPLAY', { status: 200 })
          : jsonResponse(readPvePayload),
      ),
    );
    mountBackupReadState();
    await screen.findByText(/The response format is invalid/);
    await waitFor(() => expect(recoverableRows()).toHaveLength(1));
    expect(document.body).not.toHaveTextContent('SYNTHETIC_PRIVATE_BODY_DO_NOT_DISPLAY');
  });

  it('accepts Go nil PVE collections as explicitly observed empty inventory', async () => {
    apiFetchMock.mockImplementation((url) =>
      Promise.resolve(
        jsonResponse(
          url.endsWith('/pbs')
            ? emptyPBS
            : { data: { backupTasks: null, storageBackups: null, guestSnapshots: null } },
        ),
      ),
    );
    mountBackupReadState();
    await screen.findByText('No backups yet');
    expect(screen.queryByText(/inventory is unavailable/)).not.toBeInTheDocument();
    expect(
      within(serverTable() as HTMLElement).getByText('0', { exact: true }),
    ).toBeInTheDocument();
  });

  it('does not present an unread PBS inventory as empty or a measured zero', async () => {
    const pending = deferred<Response>();
    apiFetchMock.mockImplementation((url) =>
      url.endsWith('/pbs') ? pending.promise : Promise.resolve(jsonResponse(emptyPVE)),
    );
    mountBackupReadState();
    await screen.findByText(/PBS backup inventory is loading/);
    expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
    await screen.findByText('Backup inventory is incomplete');
    expect(serverTable()).toHaveTextContent('Loading');
    pending.resolve(jsonResponse(emptyPBS));
    await screen.findByText('No backups yet');
    expect(serverTable()).not.toHaveTextContent('Loading');
    expect(
      within(serverTable() as HTMLElement).getByText('0', { exact: true }),
    ).toBeInTheDocument();
  });

  it('shows fulfilled PBS evidence without waiting for PVE', async () => {
    const pending = deferred<Response>();
    apiFetchMock.mockImplementation((url) =>
      url.endsWith('/pve') ? pending.promise : Promise.resolve(jsonResponse(pbsPayload)),
    );
    mountBackupReadState();
    await screen.findByText(/PVE backup inventory is loading/);
    await waitFor(() => expect(recoverableRows()).toHaveLength(1));
    expect(screen.getByText(/1 completed restore point read/)).toBeInTheDocument();
    pending.resolve(jsonResponse(readPvePayload));
    await waitFor(() => expect(recoverableRows()).toHaveLength(2));
    expect(screen.queryByText(/inventory is loading/)).not.toBeInTheDocument();
  });

  it('keeps a source failure actionable even before the other read settles', async () => {
    const pending = deferred<Response>();
    apiFetchMock.mockImplementation((url) =>
      url.endsWith('/pve') ? pending.promise : Promise.resolve(new Response('{}', { status: 503 })),
    );
    mountBackupReadState();
    await screen.findByText(/PBS backup inventory is unavailable/);
    expect(screen.getByText(/PVE backup inventory is loading/)).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Retry PBS inventory' })).toBeEnabled();
    expect(screen.getByText('Backup inventory is incomplete')).toBeInTheDocument();
    expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
    pending.resolve(jsonResponse(readPvePayload));
    await waitFor(() => expect(recoverableRows()).toHaveLength(1));
  });

  it.each(['pve', 'pbs'] as const)(
    'contains a %s failure, preserves the other source and retries only the failed source',
    async (source) => {
      let response = Promise.resolve(new Response('{}', { status: 503 }));
      apiFetchMock.mockImplementation((url) =>
        url.endsWith(`/${source}`)
          ? response
          : Promise.resolve(jsonResponse(source === 'pve' ? pbsPayload : readPvePayload)),
      );
      mountBackupReadState();
      await screen.findByText(
        new RegExp(`${source.toUpperCase()} backup inventory is unavailable`),
      );
      expect(screen.queryByRole('alert')).not.toBeInTheDocument();
      // A failed source can now be actionable before the independent read
      // settles. Wait for that read's evidence, not the failure notice.
      await waitFor(() => expect(recoverableRows()).toHaveLength(1));
      if (source === 'pbs') expect(serverTable()).toHaveTextContent('Unavailable');
      const retry = screen.getByRole('button', { name: `Retry ${source.toUpperCase()} inventory` });
      const pending = deferred<Response>();
      response = pending.promise;
      fireEvent.click(retry);
      expect(retry).toHaveAttribute('aria-disabled', 'true');
      fireEvent.click(retry);
      expect(sourceCalls(source)).toHaveLength(2);
      expect(recoverableRows()).toHaveLength(1);
      expect(screen.getByText(/inventory is unavailable/)).toBeInTheDocument();
      pending.resolve(jsonResponse(source === 'pbs' ? pbsPayload : readPvePayload));
      await waitFor(() => expect(recoverableRows()).toHaveLength(2));
      expect(screen.queryByText(/inventory is unavailable/)).not.toBeInTheDocument();
      expect(sourceCalls(source === 'pbs' ? 'pve' : 'pbs')).toHaveLength(1);
    },
  );

  it('keeps known PBS health and unknown counts usable while both inventories are loading', async () => {
    const pve = deferred<Response>();
    const pbs = deferred<Response>();
    apiFetchMock.mockImplementation((url) => (url.endsWith('/pbs') ? pbs.promise : pve.promise));
    mountBackupReadState();
    expect(serverTable()).toHaveTextContent('pbs-main');
    expect(serverTable()).toHaveTextContent('Loading');
    expect(serverTable()).toHaveTextContent('40.0%');
    expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
    await screen.findByText(/PVE backup inventory is loading/);
    expect(screen.getByText(/PBS backup inventory is loading/)).toBeInTheDocument();
    const originalServerTable = serverTable();
    pve.resolve(jsonResponse(emptyPVE));
    pbs.resolve(jsonResponse(emptyPBS));
    await screen.findByText('No backups yet');
    expect(serverTable()).toBe(originalServerTable);
    expect(
      within(serverTable() as HTMLElement).getByText('0', { exact: true }),
    ).toBeInTheDocument();
  });

  it.each(['pve', 'pbs', 'both'] as const)(
    'keeps separately known PBS identity and health mounted through %s inventory failure and recovery',
    async (failed) => {
      apiFetchMock.mockImplementation((url) =>
        Promise.resolve(
          failed === 'both' || url.endsWith(`/${failed}`)
            ? new Response('{}', { status: 503 })
            : jsonResponse(url.endsWith('/pbs') ? emptyPBS : emptyPVE),
        ),
      );
      mountBackupReadState();
      const originalServerTable = serverTable();
      await screen.findByText(
        new RegExp(`${failed === 'pve' ? 'PVE' : 'PBS'} backup inventory is unavailable`),
      );
      expect(serverTable()).toBe(originalServerTable);
      expect(serverTable()).toHaveTextContent('pbs-main');
      expect(serverTable()).toHaveTextContent('40.0%');
      if (failed === 'pve') {
        await within(serverTable() as HTMLElement).findByText('0', { exact: true });
      } else {
        expect(serverTable()).toHaveTextContent('Unavailable');
      }
      expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
      if (failed === 'both') {
        expect(screen.getByText('Could not load Proxmox backup inventory')).toBeInTheDocument();
        expect(screen.getByText(/PVE backup inventory is unavailable/)).toBeInTheDocument();
        expect(screen.queryByText(/completed restore points/)).not.toBeInTheDocument();
      }
      apiFetchMock.mockImplementation((url) =>
        Promise.resolve(jsonResponse(url.endsWith('/pbs') ? pbsPayload : readPvePayload)),
      );
      if (failed === 'both') fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
      else
        fireEvent.click(
          screen.getByRole('button', { name: `Retry ${failed.toUpperCase()} inventory` }),
        );
      await waitFor(() =>
        expect(screen.queryByText(/inventory is unavailable/)).not.toBeInTheDocument(),
      );
      expect(serverTable()).toBe(originalServerTable);
      expect(serverTable()).not.toHaveTextContent('Unavailable');
      // Read the count from the body: the title strip counts servers too.
      expect(
        within(serverTable().querySelector('tbody') as HTMLElement).getByText(
          failed === 'pve' ? '0' : '1',
          { exact: true },
        ),
      ).toBeInTheDocument();
    },
  );

  it('retries both failed inventories and allows the first recovered source to render', async () => {
    apiFetchMock.mockResolvedValue(new Response('{}', { status: 500 }));
    mountBackupReadState();
    await screen.findByText('Could not load Proxmox backup inventory');
    expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
    const pending = deferred<Response>();
    apiFetchMock.mockImplementation((url) =>
      url.endsWith('/pve') ? pending.promise : Promise.resolve(jsonResponse(pbsPayload)),
    );
    fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
    await screen.findByText(/PVE backup inventory is unavailable/);
    await waitFor(() => expect(recoverableRows()).toHaveLength(1));
    pending.resolve(jsonResponse(readPvePayload));
    await waitFor(() => expect(recoverableRows()).toHaveLength(2));
    expect(sourceCalls('pve')).toHaveLength(2);
    expect(sourceCalls('pbs')).toHaveLength(2);
  });

  it('does not turn a rejected empty source into proof that no backups exist', async () => {
    apiFetchMock.mockImplementation((url) =>
      Promise.resolve(
        url.endsWith('/pbs') ? new Response('{}', { status: 403 }) : jsonResponse(emptyPVE),
      ),
    );
    mountBackupReadState();
    await screen.findByText(/PBS backup inventory is unavailable/);
    expect(screen.getByText('Backup inventory is incomplete')).toBeInTheDocument();
    expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
    expect(serverTable()).toHaveTextContent('Unavailable');
    expect(screen.getByText(/Access denied/)).toBeInTheDocument();
  });

  it.each([401, 403])(
    'withdraws the old organisation before a new %s PBS denial',
    async (status) => {
      apiFetchMock.mockImplementation((url) =>
        Promise.resolve(jsonResponse(url.endsWith('/pbs') ? pbsPayload : readPvePayload)),
      );
      mountBackupReadState();
      await waitFor(() => expect(recoverableRows()).toHaveLength(2));
      const pending = deferred<Response>();
      apiFetchMock.mockImplementation((url) =>
        url.endsWith('/pbs') ? pending.promise : Promise.resolve(jsonResponse(emptyPVE)),
      );
      eventBus.emit('org_switched', 'other-fixture-org');
      expect(recoverableRows()).toHaveLength(0);
      await screen.findByText(/PBS backup inventory is loading/);
      expect(screen.queryByText('No backups yet')).not.toBeInTheDocument();
      pending.resolve(new Response('{}', { status }));
      await screen.findByText(/PBS backup inventory is unavailable/);
      expect(recoverableRows()).toHaveLength(0);
      expect(serverTable()).toHaveTextContent('Unavailable');
    },
  );

  it('aborts replaced org reads and ignores a late earlier response', async () => {
    const old = deferred<Response>();
    apiFetchMock.mockImplementation((url) =>
      url.endsWith('/pbs') ? old.promise : Promise.resolve(jsonResponse(emptyPVE)),
    );
    mountBackupReadState();
    await waitFor(() => expect(sourceCalls('pbs')).toHaveLength(1));
    const oldSignal = sourceCalls('pbs')[0][1].signal as AbortSignal;
    apiFetchMock.mockImplementation((url) =>
      Promise.resolve(jsonResponse(url.endsWith('/pbs') ? emptyPBS : emptyPVE)),
    );
    eventBus.emit('org_switched', 'other-fixture-org');
    expect(oldSignal.aborted).toBe(true);
    await screen.findByText('No backups yet');
    old.resolve(jsonResponse(pbsPayload));
    await old.promise;
    await waitFor(() => expect(recoverableRows()).toHaveLength(0));
    expect(
      within(serverTable() as HTMLElement).getByText('0', { exact: true }),
    ).toBeInTheDocument();
  });

  it('aborts pending reads on disposal and leaves no org-switch readers', async () => {
    const pending = deferred<Response>();
    apiFetchMock.mockReturnValue(pending.promise);
    const view = mountBackupReadState();
    await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2));
    const signals = apiFetchMock.mock.calls.map(([, options]) => options.signal as AbortSignal);
    view.unmount();
    expect(signals.every((signal) => signal.aborted)).toBe(true);
    eventBus.emit('org_switched', 'after-disposal');
    expect(apiFetchMock).toHaveBeenCalledTimes(2);
    pending.resolve(jsonResponse(emptyPVE));
  });
});

describe('backup-date-evidence connected inventory', () => {
  const now = Date.parse('2026-10-04T12:00:00Z');
  beforeEach(() => {
    vi.useFakeTimers({ toFake: ['Date'] });
    vi.setSystemTime(now);
  });
  afterEach(() => vi.useRealTimers());
  const coverageRow = () =>
    document.querySelector('[data-proxmox-backup-row="coverage"]')! as HTMLElement;
  const lastBackupCell = () => {
    const row = coverageRow();
    const table = row.closest('table')!;
    const index = [...table.querySelectorAll('thead th')].findIndex((cell) =>
      /Last backup/.test(cell.textContent ?? ''),
    );
    expect(index).toBeGreaterThanOrEqual(0);
    return row.querySelectorAll('td')[index] as HTMLElement;
  };
  const supply = (date: string, withOlderArchive = false) => {
    mockBackupAPIs(); // actual posture client stays independent
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse(
          url.endsWith('/pbs')
            ? { data: { backups: [{ ...pbsPayload.data.backups[0], backupTime: date }] } }
            : {
                data: {
                  backupTasks: [],
                  guestSnapshots: [],
                  storageBackups: withOlderArchive ? pvePayload.data.storageBackups : [],
                },
              },
        ),
      ),
    );
  };
  const mount = () =>
    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));

  it('[regression] keeps focus when a reported date moves the open point to another day group', async () => {
    vi.useFakeTimers({ now, toFake: ['Date', 'setInterval', 'clearInterval'] });
    window.history.replaceState({}, '', '/?view=date');
    supply('2026-10-04T11:59:00Z', true);
    mount();
    const toggle = await screen.findByRole('button', { name: /Expand details.*PBS backup/ });
    await fireEvent.click(toggle);
    toggle.focus();
    const panel = screen.getByTestId('proxmox-recoverable-detail');
    supply('not-a-date', true);
    await vi.advanceTimersByTimeAsync(30_000);
    await waitFor(() =>
      expect(within(panel).getByText('Reported date').closest('tr')).toHaveTextContent(
        'not-a-date',
      ),
    );
    expect(within(panel).getByText('Created').closest('tr')).toHaveTextContent('Unknown');
    expect(screen.getByTestId('proxmox-recoverable-detail')).toBe(panel);
    expect(toggle).toHaveFocus();
  });

  it.each(['not-a-date', '0001-01-01T00:00:00Z', '2026-10-04T12:00:01Z'])(
    '[regression] By date exposes the reported %s without granting it an age',
    async (date) => {
      window.history.replaceState({}, '', '/?view=date');
      supply(date);
      mount();
      const toggle = await screen.findByRole('button', { name: /Expand details.*Identifier:/ });
      await fireEvent.click(toggle);
      const panel = screen.getByTestId('proxmox-recoverable-detail');
      expect(within(panel).getByText('Reported date').closest('tr')).toHaveTextContent(date);
      expect(within(panel).getByText('Created').closest('tr')).toHaveTextContent('Unknown');
      expect(apiFetchMock).toHaveBeenCalledTimes(2);
    },
  );

  it.each(['not-a-date', '0001-01-01T00:00:00Z', '2026-10-04T12:00:01Z'])(
    '[regression] Coverage preserves %s uncertainty instead of absence or healthy age',
    async (date) => {
      window.history.replaceState({}, '', '/?view=coverage');
      supply(date);
      mount();
      await waitFor(() => expect(lastBackupCell()).toHaveTextContent('Unknown'));
      expect(lastBackupCell().textContent).not.toContain('None');
      expect(within(lastBackupCell()).getByText('Unknown')).toHaveClass('text-amber-600');
      expect(within(coverageRow()).getByText('Protected')).toBeInTheDocument();
      await fireEvent.click(within(coverageRow()).getByRole('button'));
      expect(document.querySelector('[data-inline-detail-for]')).toHaveTextContent('Unknown');
      expect(document.body).not.toHaveTextContent('Invalid Date');
    },
  );

  it('[regression] all-locations Coverage does not advertise an older known backup as the latest', async () => {
    window.history.replaceState({}, '', '/?view=coverage');
    supply('not-a-date', true);
    mount();
    await waitFor(() => expect(lastBackupCell()).toHaveTextContent('Unknown'));
    const calls = apiFetchMock.mock.calls.length;
    const filter = screen.getByRole('combobox', { name: 'Filter' });
    const option = screen.getByRole('option', {
      name: 'Backup location: PVE file · pve-a / local',
    }) as HTMLOptionElement;
    await fireEvent.change(filter, { target: { value: option.value } });
    await waitFor(() => expect(lastBackupCell()).not.toHaveTextContent('Unknown'));
    expect(lastBackupCell()).not.toHaveTextContent('None');
    expect(apiFetchMock).toHaveBeenCalledTimes(calls); // filtering is not another read
  });

  it('[regression] location-scoped Coverage preserves unknown chronology, not a known older point', async () => {
    window.history.replaceState({}, '', '/?view=coverage&location=pbs%3Apbs-main%3Amain');
    supply('2026-10-04T12:00:01Z', true);
    mount();
    await waitFor(() => expect(lastBackupCell()).toHaveTextContent('Unknown'));
  });

  it('[regression] By date retains future artifacts with an unknown age', async () => {
    window.history.replaceState({}, '', '/?view=date');
    supply('2026-10-04T12:00:01Z', true);
    mount();
    await waitFor(() =>
      expect(document.querySelectorAll('[data-proxmox-backup-row="recoverable"]')).toHaveLength(2),
    );
    const future = [...document.querySelectorAll('[data-proxmox-backup-row="recoverable"]')].find(
      (row) => row.textContent?.includes('PBS'),
    )! as HTMLElement;
    expect(within(future).getByText('Unknown')).toHaveAccessibleName(/Unknown age/);
  });

  it('[regression] new inventory after page mount uses its observation time and clears age uncertainty', async () => {
    window.history.replaceState({}, '', '/?view=coverage');
    supply('not-a-date', true);
    mount();
    await waitFor(() => expect(lastBackupCell()).toHaveTextContent('Unknown'));
    vi.setSystemTime(now + 120000);
    supply('2026-10-04T12:01:00Z', true);
    eventBus.emit('org_switched', 'date-replacement');
    await waitFor(() => expect(lastBackupCell()).toHaveTextContent('1m ago'));
    expect(lastBackupCell()).not.toHaveTextContent('None');
    expect(lastBackupCell()).not.toHaveTextContent('Unknown');
    expect(within(coverageRow()).getByText('Protected')).toBeInTheDocument();
  });
});

describe('backup-identity: connected Coverage and By date', () => {
  const mockIdentityAPIs = () => {
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse({
          data:
            url === '/api/backups/pve'
              ? {
                  storageBackups: [identityArchive()],
                  guestSnapshots: [identitySnapshot()],
                  backupTasks: [identityTask()],
                }
              : { backups: [identityPBS()] },
        }),
      ),
    );
    apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });
    vi.spyOn(Date, 'now').mockReturnValue(BACKUP_IDENTITY_NOW);
  };
  afterEach(() => vi.restoreAllMocks());

  it.each([
    ['pbs-100', 'pbs:pbs-100'],
    ['FILE-100', 'archive:file-100'],
    ['snapshot-100', 'snapshot:snapshot-100'],
    ['local:backup/vzdump-qemu-100.vma.zst', 'archive:file-100'],
  ])('retains the searched point and scoped owner across views: %s', async (query, pointID) => {
    mockIdentityAPIs();
    window.history.replaceState({}, '', '/proxmox/backups/date');
    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[
          identityGuest('west-100', 'west', 'pve-10'),
          identityGuest('east-100', 'east', 'pve-1'),
        ]}
      />
    ));
    await waitFor(() => expect(recoverableRows()).toHaveLength(3));
    const search = screen.getByPlaceholderText(/search backups by workload/i);
    fireEvent.input(search, { target: { value: query } });
    await waitFor(() => expect(recoverableRows()).toHaveLength(1));
    expect(recoverableRows()[0]).toHaveTextContent('east-100');
    fireEvent.click(
      within(recoverableRows()[0] as HTMLElement).getByRole('button', {
        name: /expand details/i,
      }),
    );
    const detail = await screen.findByTestId('proxmox-recoverable-detail');
    expect(detail).toHaveAttribute('data-inline-detail-for', pointID);

    fireEvent.click(screen.getByRole('link', { name: 'Coverage' }));
    await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
    expect(new URLSearchParams(window.location.search).get('q')).toBe(query);
    const rows = () => document.querySelectorAll('[data-proxmox-backup-row="coverage"]');
    await waitFor(() => expect(rows()).toHaveLength(1));
    expect(rows()[0]).toHaveTextContent('east-100');
    expect(rows()[0]).not.toHaveTextContent('west-100');
    // Lookup narrows the workload list, not its assessment or restore history.
    fireEvent.click(
      within(rows()[0] as HTMLElement).getByRole('button', { name: /expand details/i }),
    );
    const coverage = await screen.findByTestId('proxmox-coverage-detail');
    expect(coverage).toHaveTextContent('PBS');
    expect(coverage).toHaveTextContent('PVE file');
    expect(coverage).toHaveTextContent('Snapshot');
    expect(screen.getByRole('button', { name: '2 status unknown' })).toBeInTheDocument();
    expect(apiFetchMock).toHaveBeenCalledTimes(2);

    fireEvent.input(search, { target: { value: 'absent-native-point' } });
    await waitFor(() => expect(rows()).toHaveLength(0));
    fireEvent.input(search, { target: { value: '' } });
    await waitFor(() => expect(rows()).toHaveLength(2));
    expect(apiFetchMock).toHaveBeenCalledTimes(2);
  });

  it('keeps all three artifacts and the successful task with the scoped owner through reorder and display rename', async () => {
    mockIdentityAPIs();
    window.history.replaceState({}, '', '/proxmox/backups/coverage');
    const east = identityGuest('east-100', 'east', 'pve-1');
    const west = identityGuest('west-100', 'west', 'pve-10');
    const [workloads, setWorkloads] = createSignal([west, east]);
    const { container } = renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={workloads()} />
    ));
    const rowFor = (name: string) =>
      Array.from(container.querySelectorAll('[data-proxmox-backup-row="coverage"]')).find((row) =>
        row.textContent?.includes(name),
      ) as HTMLElement;
    await waitFor(() => expect(rowFor('east-100')).toHaveTextContent('OK'));
    expect(rowFor('west-100')).not.toHaveTextContent('OK');
    expect(within(rowFor('west-100')).getByTitle('No recent task')).toBeInTheDocument();
    const toggle = within(rowFor('east-100')).getByRole('button', { name: /expand details/i });
    await fireEvent.click(toggle);
    const detailID = toggle.getAttribute('aria-controls')!;
    await waitFor(() => expect(document.getElementById(detailID)).toHaveTextContent('Snapshot'));
    expect(document.getElementById(detailID)).toHaveTextContent('PVE file');
    expect(document.getElementById(detailID)).toHaveTextContent('PBS');
    setWorkloads([east, { ...west, proxmox: { ...west.proxmox!, nodeDisplayName: 'pve-1' } }]);
    await waitFor(() => expect(rowFor('east-100')).toHaveTextContent('OK'));
    expect(within(rowFor('east-100')).getByRole('button', { name: /collapse details/i })).toBe(
      toggle,
    );
    expect(rowFor('west-100')).not.toHaveTextContent('OK');
    expect(document.getElementById(detailID)).toHaveTextContent('PVE file');
    expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pve')).toHaveLength(1);
    expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pbs')).toHaveLength(1);
  });

  it('withdraws ambiguous PBS ownership without losing the artifact, PVE owner or server posture', async () => {
    mockIdentityAPIs();
    window.history.replaceState({}, '', '/proxmox/backups/date');
    const east = identityGuest('east-100', 'east', 'pve-1');
    const west = identityGuest('west-100', 'west', 'pve-10');
    const [workloads, setWorkloads] = createSignal([west, east]);
    const { container } = renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={workloads()} />
    ));
    const artifacts = () =>
      Array.from(container.querySelectorAll('[data-proxmox-backup-row="recoverable"]'));
    await waitFor(() => expect(artifacts()).toHaveLength(3));
    expect(artifacts().every((row) => row.textContent?.includes('east-100'))).toBe(true);
    setWorkloads([identityGuest('west-100', 'west', 'pve-1'), east]);
    await waitFor(() =>
      expect(artifacts().filter((row) => row.textContent?.includes('east-100'))).toHaveLength(2),
    );
    const unresolved = artifacts().find((row) => !row.textContent?.includes('east-100'))!;
    expect(unresolved).toHaveTextContent('VM 100');
    expect(unresolved).toHaveTextContent('PBS');
    expect(artifacts()).toHaveLength(3);
    await fireEvent.click(screen.getByRole('link', { name: 'Coverage' }));
    await fireEvent.click(screen.getByRole('button', { name: /1 unmatched backup/ }));
    await waitFor(() =>
      expect(screen.getByText('Not evaluated', { exact: true })).toBeInTheDocument(),
    );
    expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pve')).toHaveLength(1);
    expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pbs')).toHaveLength(1);
  });
});

describe('Coverage qualifies missing restore evidence through the consuming API hooks', () => {
  const posture = {
    subjectResourceId: workloadResource.id,
    state: 'unprotected',
    freshness: 'unknown',
    verification: 'unknown',
    coverage: 'none',
    providerStates: [
      {
        provider: 'proxmox-pbs',
        source: 'pbs-backup-enumeration',
        scope: 'pbs-main',
        jobState: 'success',
        historyCompleteness: 'complete',
        permissions: 'sufficient',
        evidenceIds: [],
      },
    ],
    repositoryResourceIds: [],
    evidenceIds: [],
    explanation: 'Pulse sees the full history and no backup in it can count.',
    evaluatedAt: '2026-10-23T12:00:00Z',
  };
  const mount = () => {
    window.history.replaceState({}, '', '/proxmox/backups/coverage');
    return renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));
  };
  const rowElement = () =>
    document.querySelector('[data-proxmox-backup-row="coverage"]') as HTMLElement;
  const open = async () => {
    await waitFor(() => expect(rowElement()).not.toBeNull());
    fireEvent.click(within(rowElement()).getByRole('button', { name: /expand details/i }));
    return screen.findByTestId('proxmox-coverage-detail');
  };

  beforeEach(() => {
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(jsonResponse(url.endsWith('/pve') ? emptyPVE : emptyPBS)),
    );
    apiFetchJSONMock.mockResolvedValue({ data: [posture], policy: protectionPolicy });
  });

  it.each(['partial', 'unavailable'])(
    'does not mistake HTTP200 inventories beside %s provider history for absence',
    async (historyCompleteness) => {
      apiFetchJSONMock.mockResolvedValue({
        data: [
          {
            ...posture,
            state: 'unknown',
            coverage: 'unknown',
            providerStates: [{ ...posture.providerStates[0], historyCompleteness }],
          },
        ],
        policy: protectionPolicy,
      });
      mount();
      const detail = await open();
      await waitFor(() => expect(detail).toHaveTextContent('not confirmed complete'));
      expect(rowElement()).not.toHaveTextContent('None');
      expect(detail).not.toHaveTextContent('No restore points reported');
      expect(detail).not.toHaveTextContent('Restore evidence');
    },
  );

  it('qualifies a failed raw source, then accepts an isolated successful empty retry', async () => {
    let failed = true;
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        url.endsWith('/pbs') && failed
          ? new Response('', { status: 503 })
          : jsonResponse(url.endsWith('/pve') ? emptyPVE : emptyPBS),
      ),
    );
    mount();
    const retry = await screen.findByRole('button', { name: 'Retry PBS inventory' });
    const detail = await open();
    await waitFor(() => expect(detail).toHaveTextContent('not confirmed complete'));
    expect(rowElement()).not.toHaveTextContent('None');
    failed = false;
    fireEvent.click(retry);
    await waitFor(() =>
      expect(detail).toHaveTextContent(
        'No restore-point details are visible in the current list. The posture above may use previously recorded evidence.',
      ),
    );
    expect(within(rowElement()).getByTitle('No PBS backup or PVE backup file')).toHaveTextContent(
      'None',
    );
    expect(sourceCalls('pve')).toHaveLength(1);
    expect(sourceCalls('pbs')).toHaveLength(2);
  });

  it('keeps a failed posture read unknown even when both raw inventories are accepted empty', async () => {
    apiFetchJSONMock.mockRejectedValue(new Error('synthetic posture read failed'));
    mount();
    const detail = await open();
    await screen.findByText(/Protection posture is unavailable/);
    expect(detail).toHaveTextContent('not confirmed complete');
    expect(rowElement()).not.toHaveTextContent('None');
  });

  it('keeps an independently visible backup and its date beside partial provider history', async () => {
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(jsonResponse(url.endsWith('/pve') ? emptyPVE : pbsPayload)),
    );
    apiFetchJSONMock.mockResolvedValue({
      data: [
        {
          ...posture,
          state: 'attention',
          coverage: 'partial',
          lastSuccessfulPointAt: pbsPayload.data.backups[0].backupTime,
          providerStates: [
            {
              ...posture.providerStates[0],
              historyCompleteness: 'partial',
              permissions: 'partial',
            },
          ],
        },
      ],
      policy: protectionPolicy,
    });
    mount();
    const detail = await open();
    await waitFor(() => expect(detail).toHaveTextContent('Restore evidence'));
    expect(rowElement()).not.toHaveTextContent('None');
    expect(within(rowElement()).queryByLabelText(/Unknown age/)).not.toBeInTheDocument();
    expect(detail).toHaveTextContent('History Partial');
    expect(detail).toHaveTextContent('Access Partial');
    expect(detail).not.toHaveTextContent('No restore points');
  });
});

describe('Coverage withdraws failed protection assessments', () => {
  it.each(['duplicate', 'provider', 'policy', 'calendar', 'timezone', 'date-only'])(
    'treats HTTP200 malformed %s evidence as unavailable and preserves independent restore points',
    async (invalid) => {
      vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
      try {
        mockBackupAPIs();
        window.history.replaceState({}, '', '/proxmox/backups/coverage');
        renderInRouter(() => (
          <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
        ));
        const row = () =>
          document.querySelector('[data-proxmox-backup-row="coverage"]') as HTMLElement;
        await waitFor(() => expect(row()).toHaveTextContent('Protected'));
        fireEvent.click(within(row()).getByRole('button', { name: /expand details/i }));
        const detail = await screen.findByTestId('proxmox-coverage-detail');
        const accepted = (await apiFetchJSONMock.mock.results[0]
          .value) as ProtectionPosturesResponse;
        const privateValue = { private: 'SYNTHETIC_PRIVATE_VALUE' };
        const malformed = ['calendar', 'timezone', 'date-only'].includes(invalid)
          ? {
              ...accepted,
              data: [
                {
                  ...accepted.data[0],
                  evaluatedAt:
                    invalid === 'calendar'
                      ? '2026-09-31T10:00:00Z'
                      : invalid === 'timezone'
                        ? '2026-10-26T10:00:00'
                        : '2026-10-26',
                },
              ],
            }
          : invalid === 'duplicate'
            ? {
                ...accepted,
                data: [{ ...accepted.data[0], state: 'unprotected' }, accepted.data[0]],
              }
            : invalid === 'provider'
              ? { ...accepted, data: [{ ...accepted.data[0], providerStates: [privateValue] }] }
              : { ...accepted, policy: { ...accepted.policy, requireVerification: privateValue } };
        apiFetchJSONMock.mockResolvedValue(malformed);
        await vi.advanceTimersByTimeAsync(30_000);
        await screen.findByText(/Protection posture is unavailable/);
        expect(row()).toHaveTextContent('Unknown');
        expect(row()).not.toHaveTextContent('Protected');
        expect(screen.getByRole('button', { name: '1 status unknown' })).toBeInTheDocument();
        expect(detail).not.toHaveTextContent('A current verified backup is available.');
        expect(detail).toHaveTextContent('Restore evidence');
        expect(within(detail).getByText('PVE file', { exact: true })).toBeInTheDocument();
        expect(document.querySelector('[data-coverage-posture-rule]')).toBeNull();
        expect(document.body).not.toHaveTextContent('SYNTHETIC_PRIVATE_VALUE');

        const beforePVE = sourceCalls('pve').length;
        const beforePBS = sourceCalls('pbs').length;
        apiFetchJSONMock.mockResolvedValue(accepted);
        fireEvent.click(screen.getByRole('button', { name: 'Retry protection posture' }));
        await waitFor(() => expect(row()).toHaveTextContent('Protected'));
        expect(screen.queryByText(/Protection posture is unavailable/)).not.toBeInTheDocument();
        expect(sourceCalls('pve')).toHaveLength(beforePVE);
        expect(sourceCalls('pbs')).toHaveLength(beforePBS);
      } finally {
        vi.useRealTimers();
      }
    },
  );

  it('replaces retained healthy rows, counts and explanations with Unknown, then retries only posture', async () => {
    vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
    try {
      mockBackupAPIs();
      window.history.replaceState({}, '', '/proxmox/backups/coverage');
      renderInRouter(() => (
        <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
      ));
      const row = () =>
        document.querySelector('[data-proxmox-backup-row="coverage"]') as HTMLElement;
      await waitFor(() => expect(row()).toHaveTextContent('Protected'));
      const accepted = (await apiFetchJSONMock.mock.results[0].value) as ProtectionPosturesResponse;
      expect(document.querySelector('[data-backup-verdict]')).toHaveTextContent('1 of 1 protected');
      fireEvent.click(within(row()).getByRole('button', { name: /expand details/i }));
      const detail = await screen.findByTestId('proxmox-coverage-detail');
      expect(detail).toHaveTextContent('A current verified backup is available.');

      apiFetchJSONMock.mockRejectedValue(new Error('Synthetic posture refresh failed'));
      await vi.advanceTimersByTimeAsync(30_000);
      await screen.findByText(/Protection posture is unavailable/);
      expect(row()).toHaveTextContent('Unknown');
      expect(row()).not.toHaveTextContent('Protected');
      expect(document.querySelector('[data-backup-verdict]')).toHaveTextContent('0 of 1 protected');
      expect(screen.getByRole('button', { name: '1 status unknown' })).toBeInTheDocument();
      expect(detail).not.toHaveTextContent('A current verified backup is available.');
      expect(detail).not.toHaveTextContent('History Complete');
      expect(detail).toHaveTextContent('Restore evidence');
      expect(within(detail).getByText('PVE file', { exact: true })).toBeInTheDocument();
      expect(document.querySelector('[data-coverage-posture-rule]')).toBeNull();

      const pending = deferred<typeof accepted>();
      apiFetchJSONMock.mockReturnValue(pending.promise);
      const retry = screen.getByRole('button', { name: 'Retry protection posture' });
      fireEvent.click(retry);
      expect(retry).toHaveAttribute('aria-disabled', 'true');
      expect(retry).toHaveTextContent('Retrying');
      expect(row()).toHaveTextContent('Unknown');
      fireEvent.click(retry);
      expect(apiFetchJSONMock).toHaveBeenCalledTimes(3);
      pending.resolve({
        ...accepted,
        data: accepted.data.map((posture) => ({
          ...posture,
          state: 'attention',
          explanation: 'The current backup verification needs attention.',
        })),
      });
      await waitFor(() => expect(row()).toHaveTextContent(/attention/i));
      expect(detail).toHaveTextContent('The current backup verification needs attention.');
      expect(screen.queryByText(/Protection posture is unavailable/)).not.toBeInTheDocument();
      expect(screen.getByRole('button', { name: '1 needs attention' })).toBeInTheDocument();
      expect(document.querySelector('[data-coverage-posture-rule]')).not.toBeNull();
      expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pve')).toHaveLength(2);
      expect(apiFetchMock.mock.calls.filter(([url]) => url === '/api/backups/pbs')).toHaveLength(2);
    } finally {
      vi.useRealTimers();
    }
  });
});

describe('completed restore-point summary', () => {
  afterEach(() => vi.restoreAllMocks());

  const mountInventory = (incompleteOnly = false) => {
    vi.spyOn(Date, 'now').mockReturnValue(BACKUP_IDENTITY_NOW);
    const completedPBS = identityPBS({ id: 'complete', size: 2048 });
    const runningPBS = identityPBS({ id: 'running', inProgress: true, size: 1024 * 1024 });
    const failedPBS = identityPBS({
      id: 'failed',
      inProgress: true,
      writeActivityObserved: true,
      writeActive: false,
      size: 2 * 1024 * 1024,
    });
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse({
          data: url.endsWith('/pbs')
            ? { backups: [...(incompleteOnly ? [] : [completedPBS]), runningPBS, failedPBS] }
            : {
                storageBackups: incompleteOnly ? [] : [identityArchive({ size: 1024 })],
                guestSnapshots: incompleteOnly ? [] : [identitySnapshot()],
                backupTasks: [],
              },
        }),
      ),
    );
    apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });
    window.history.replaceState({}, '', '/proxmox/backups/date');
    return renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[identityGuest('east-100', 'east', 'pve-1')]}
      />
    ));
  };

  it('counts completed points while retaining running and failed rows for inspection', async () => {
    const { container } = mountInventory();
    await screen.findByText(/3 completed restore points · 1 running · 1 failed/);
    expect(container.querySelectorAll('[data-proxmox-backup-row="recoverable"]')).toHaveLength(5);
    expect(
      screen.getByRole('cell', { name: `${getRecoveryFullDateLabel('2026-10-04')} 5 entries` }),
    ).toBeInTheDocument();
    expect(screen.getAllByText('Running').length).toBeGreaterThan(0);
    expect(screen.getAllByText('Failed').length).toBeGreaterThan(0);
  });

  it('does not claim PBS restore coverage for an incomplete-only inventory', async () => {
    const { container } = mountInventory(true);
    const summary = await screen.findByText(/0 completed restore points · 1 running · 1 failed/);
    expect(summary).not.toHaveTextContent('with PBS backups');
    expect(container.querySelectorAll('[data-proxmox-backup-row="recoverable"]')).toHaveLength(2);
    expect(
      screen.getByRole('cell', { name: `${getRecoveryFullDateLabel('2026-10-04')} 2 entries` }),
    ).toBeInTheDocument();
    await fireEvent.click(screen.getByRole('link', { name: 'Coverage' }));
    expect(
      screen.getByText(/0 completed restore points · 1 running · 1 failed/),
    ).toBeInTheDocument();
  });
});

describe('restore points with unavailable sizes', () => {
  afterEach(() => vi.restoreAllMocks());

  const mountVolumeInventory = (mixed = false) => {
    vi.spyOn(Date, 'now').mockReturnValue(BACKUP_IDENTITY_NOW);
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse({
          data: url.endsWith('/pbs')
            ? {
                backups: [
                  identityPBS({ size: mixed ? 2048 : 0 }),
                  ...(mixed
                    ? [
                        identityPBS({
                          id: 'yesterday',
                          size: 0,
                          backupTime: '2026-10-03T10:00:00Z',
                        }),
                      ]
                    : []),
                  identityPBS({ id: 'running', size: 0, inProgress: true }),
                  identityPBS({ id: 'old', size: 0, backupTime: '2025-01-01T10:00:00Z' }),
                  identityPBS({ id: 'future', size: 0, backupTime: '2026-10-05T10:00:00Z' }),
                ],
              }
            : {
                storageBackups: [identityArchive({ size: mixed ? 1024 : 0 })],
                guestSnapshots: [identitySnapshot()],
                backupTasks: [],
              },
        }),
      ),
    );
    apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });
    window.history.replaceState({}, '', '/proxmox/backups/date');
    return renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[identityGuest('east-100', 'east', 'pve-1')]}
      />
    ));
  };

  it('[point-size] keeps unavailable size explicit without changing verification or completed counts', async () => {
    mountVolumeInventory();
    const toggle = await screen.findByRole('button', {
      name: /Expand details.*Identifier: pbs-100$/,
    });
    fireEvent.click(toggle);
    const panel = screen.getByTestId('proxmox-recoverable-detail');
    expect(within(panel).getByText('Size', { selector: 'td' }).closest('tr')).toHaveTextContent(
      'Unknown size',
    );
    expect(panel).toHaveTextContent(
      'No usable size was reported. Unknown does not mean this restore point is empty.',
    );
    expect(panel).not.toHaveTextContent('0 B');
    expect(within(panel).getAllByText('Verified')).toHaveLength(2);
    expect(document.body).toHaveTextContent('5 completed restore points');
    expect(document.body).toHaveTextContent('1 running');
  });
});

describe('mounted Proxmox backup inventory refresh', () => {
  beforeEach(() => {
    vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
    mockBackupAPIs();
    window.history.replaceState({}, '', '/proxmox/backups/coverage');
  });
  afterEach(() => vi.useRealTimers());

  it('refreshes both inventories and the same open evidence badge without losing focus', async () => {
    const pbs = structuredClone(pbsPayload);
    pbs.data.backups[0].protected = false;
    let nextPBS: unknown = pbs;
    let nextPVE: unknown = emptyPVE;
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(jsonResponse(url.endsWith('/pbs') ? nextPBS : nextPVE)),
    );
    const { unmount } = mountBackupReadState();
    const row = () => document.querySelector('[data-proxmox-backup-row="coverage"]') as HTMLElement;
    await waitFor(() => expect(row()).toHaveTextContent('Protected'));
    const disclosure = within(row()).getByRole('button', { name: /expand details/i });
    fireEvent.click(disclosure);
    disclosure.focus();
    const detail = await screen.findByTestId('proxmox-coverage-detail');
    const badge = within(detail).getByText('Verified', { exact: true });
    expect(badge).toHaveClass('bg-emerald-100');

    // The provider can revise verification of the same native point. New
    // successful PVE evidence arrives independently on that same bounded tick.
    nextPBS = { ...pbs, data: { backups: [{ ...pbs.data.backups[0], verified: false }] } };
    nextPVE = readPvePayload;
    await vi.advanceTimersByTimeAsync(30_000);
    await waitFor(() => expect(within(detail).getByText('Unverified')).toBe(badge));
    expect(badge).toHaveClass('bg-amber-100');
    expect(detail).toHaveTextContent('PVE file');
    expect(screen.getByTestId('proxmox-coverage-detail')).toBe(detail);
    expect(document.activeElement).toBe(disclosure);
    expect(document.body).toHaveTextContent('2 completed restore points');
    expect(sourceCalls('pbs')).toHaveLength(2);
    expect(sourceCalls('pve')).toHaveLength(2);

    nextPBS = {
      ...pbs,
      data: {
        backups: [
          {
            ...pbs.data.backups[0],
            inProgress: true,
            writeActivityObserved: true,
            writeActive: false,
          },
        ],
      },
    };
    await vi.advanceTimersByTimeAsync(30_000);
    await waitFor(() => expect(within(detail).getByText('Failed')).toBe(badge));
    expect(badge).toHaveClass('bg-red-100');
    expect(document.body).toHaveTextContent('1 completed restore point');
    expect(document.body).toHaveTextContent('1 failed');
    expect(document.activeElement).toBe(disclosure);

    nextPBS = pbs;
    await vi.advanceTimersByTimeAsync(30_000);
    await waitFor(() => expect(within(detail).getByText('Verified')).toBe(badge));
    expect(badge).toHaveClass('bg-emerald-100');
    expect(document.body).toHaveTextContent('2 completed restore points');
    expect(document.activeElement).toBe(disclosure);
    const calls = apiFetchMock.mock.calls.length;
    unmount();
    await vi.advanceTimersByTimeAsync(60_000);
    expect(apiFetchMock).toHaveBeenCalledTimes(calls);
  });

  it('does not overlap a slow poll, keeps the other source refreshing and aborts on disposal', async () => {
    let nextPBS = Promise.resolve(jsonResponse(pbsPayload));
    apiFetchMock.mockImplementation((url: string) =>
      url.endsWith('/pbs') ? nextPBS : Promise.resolve(jsonResponse(readPvePayload)),
    );
    const { unmount } = mountBackupReadState();
    await waitFor(() => expect(sourceCalls('pbs')).toHaveLength(1));
    const pending = deferred<Response>();
    nextPBS = pending.promise;
    await vi.advanceTimersByTimeAsync(30_000);
    const signal = sourceCalls('pbs')[1][1].signal as AbortSignal;
    expect(signal.aborted).toBe(false);
    await vi.advanceTimersByTimeAsync(60_000);
    expect(sourceCalls('pbs')).toHaveLength(2);
    expect(sourceCalls('pve')).toHaveLength(4);
    expect(signal.aborted).toBe(false);
    expect(document.body).not.toHaveTextContent('PBS backup inventory is unavailable');
    const calls = apiFetchMock.mock.calls.length;
    unmount();
    expect(signal.aborted).toBe(true);
    pending.resolve(jsonResponse(emptyPBS));
    await vi.advanceTimersByTimeAsync(30_000);
    expect(apiFetchMock).toHaveBeenCalledTimes(calls);
  });
});

describe('backup location identity in the consuming views', () => {
  const supplyLocations = () => {
    mockBackupAPIs('protected', {
      ...pbsPayload,
      data: {
        backups: [
          { ...pbsPayload.data.backups[0], id: 'lower-case', datastore: 'main' },
          {
            ...pbsPayload.data.backups[0],
            id: 'upper-case',
            datastore: 'Main',
            backupTime: '2026-05-24T01:34:25Z',
          },
        ],
      },
    });
  };
  const points = () =>
    document.querySelectorAll<HTMLElement>('[data-proxmox-backup-row="recoverable"]');

  it('keeps case-sensitive repositories separate through date filtering, Coverage, details and reload', async () => {
    supplyLocations();
    window.history.replaceState({}, '', '/proxmox/backups/date');
    const mounted = renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));
    await screen.findByText('Main / minipc');
    const calls = apiFetchMock.mock.calls.length;
    const option = screen.getByRole('option', {
      name: 'Backup location: PBS · pbs-main / Main',
    }) as HTMLOptionElement;
    await fireEvent.change(screen.getByRole('combobox', { name: 'Filter' }), {
      target: { value: option.value },
    });
    await waitFor(() => expect(points()).toHaveLength(1));
    expect(screen.getByText('Main / minipc')).toBeInTheDocument();
    expect(screen.queryByText('main / minipc')).not.toBeInTheDocument();
    expect(points()[0].querySelector('[data-backup-source-connection]')).toHaveTextContent(
      'Connection: pbs-main',
    );
    fireEvent.input(screen.getByPlaceholderText(/Search backups by workload/), {
      target: { value: 'pbs-main' },
    });
    await waitFor(() => expect(points()).toHaveLength(1));
    fireEvent.click(within(points()[0]).getByRole('button', { name: /expand details/i }));
    const pointDetail = screen.getByTestId('proxmox-recoverable-detail');
    expect(within(pointDetail).getByText('Connection').closest('tr')).toHaveTextContent('pbs-main');
    const key = '["pbs","pbs-main","Main"]';
    await waitFor(() =>
      expect(new URLSearchParams(window.location.search).get('location')).toBe(key),
    );
    await fireEvent.click(screen.getByRole('link', { name: /coverage/i }));
    await fireEvent.click(
      await screen.findByRole('button', { name: /expand details for pbs-docker/i }),
    );
    const detail = screen.getByTestId('proxmox-coverage-detail');
    expect(within(detail).getByText('Main / minipc')).toBeInTheDocument();
    expect(within(detail).queryByText('main / minipc')).not.toBeInTheDocument();
    expect(detail.querySelector('[data-backup-source-connection]')).toHaveTextContent(
      'Connection: pbs-main',
    );
    expect(new URLSearchParams(window.location.search).get('location')).toBe(key);
    expect(apiFetchMock).toHaveBeenCalledTimes(calls);
    mounted.unmount();
    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));
    expect(
      await screen.findByRole('button', { name: 'Backup location: PBS · pbs-main / Main' }),
    ).toBeInTheDocument();
    await fireEvent.click(screen.getByRole('button', { name: /expand details for pbs-docker/i }));
    expect(screen.getByTestId('proxmox-coverage-detail')).not.toHaveTextContent('main / minipc');
  });

  it('does not interpret an ambiguous old saved location as both repositories, and lets the operator choose again', async () => {
    supplyLocations();
    window.history.replaceState({}, '', '/proxmox/backups/date?location=pbs%3Apbs-main%3Amain');
    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));
    expect(
      await screen.findByText(/saved backup location cannot be identified uniquely/),
    ).toHaveAttribute('role', 'status');
    expect(points()).toHaveLength(0);
    expect(
      screen.getByRole('button', { name: 'Backup location: Choose location' }),
    ).toBeInTheDocument();
    const calls = apiFetchMock.mock.calls.length;
    await fireEvent.click(screen.getByRole('button', { name: 'Backup location: Choose location' }));
    const menu = screen.getByRole('listbox', { name: 'Backup location' });
    await fireEvent.click(within(menu).getByRole('option', { name: 'PBS · pbs-main / Main' }));
    await waitFor(() => expect(points()).toHaveLength(1));
    expect(
      screen.queryByText(/saved backup location cannot be identified uniquely/),
    ).not.toBeInTheDocument();
    expect(screen.getByText('Main / minipc')).toBeInTheDocument();
    expect(screen.queryByText('main / minipc')).not.toBeInTheDocument();
    expect(apiFetchMock).toHaveBeenCalledTimes(calls);
    await fireEvent.click(screen.getByRole('button', { name: 'Remove Backup location filter' }));
    await waitFor(() => expect(points()).toHaveLength(4));
    await waitFor(() =>
      expect(new URLSearchParams(window.location.search).has('location')).toBe(false),
    );
  });

  it('keeps an absent saved location explicit without showing a raw URL value or another location', async () => {
    mockBackupAPIs();
    window.history.replaceState(
      {},
      '',
      '/proxmox/backups/coverage?location=SYNTHETIC_UNKNOWN_LOCATION',
    );
    renderInRouter(() => (
      <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
    ));
    expect(
      await screen.findByText(/saved backup location cannot be identified uniquely/),
    ).toBeInTheDocument();
    expect(document.querySelectorAll('[data-proxmox-backup-row="coverage"]')).toHaveLength(0);
    expect(document.body).not.toHaveTextContent('SYNTHETIC_UNKNOWN_LOCATION');
    expect(screen.queryByRole('note', { name: 'Backup location scope' })).not.toBeInTheDocument();
  });

  it('withdraws a legacy selection when refreshed inventory makes it ambiguous, without broadening an exact choice', async () => {
    vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
    try {
      mockBackupAPIs();
      const lower = { ...pbsPayload.data.backups[0], id: 'lower-case', datastore: 'main' };
      const upper = { ...lower, id: 'upper-case', datastore: 'Main' };
      let nextPBS = { data: { backups: [lower] } };
      apiFetchMock.mockImplementation((url: string) =>
        Promise.resolve(jsonResponse(url.endsWith('/pbs') ? nextPBS : emptyPVE)),
      );
      window.history.replaceState({}, '', '/proxmox/backups/date?location=pbs%3Apbs-main%3Amain');
      renderInRouter(() => (
        <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />
      ));
      await screen.findByRole('button', { name: 'Backup location: PBS · pbs-main / main' });
      expect(points()).toHaveLength(1);

      nextPBS = { data: { backups: [lower, upper] } };
      await vi.advanceTimersByTimeAsync(30_000);
      expect(
        await screen.findByText(/saved backup location cannot be identified uniquely/),
      ).toBeInTheDocument();
      expect(points()).toHaveLength(0);
      await fireEvent.click(
        screen.getByRole('button', { name: 'Backup location: Choose location' }),
      );
      await fireEvent.click(
        within(screen.getByRole('listbox', { name: 'Backup location' })).getByRole('option', {
          name: 'PBS · pbs-main / Main',
        }),
      );
      await waitFor(() => expect(points()).toHaveLength(1));
      expect(screen.getByText('Main / minipc')).toBeInTheDocument();
      expect(screen.queryByText('main / minipc')).not.toBeInTheDocument();
      await vi.advanceTimersByTimeAsync(30_000);
      expect(points()).toHaveLength(1);
      expect(new URLSearchParams(window.location.search).get('location')).toBe(
        '["pbs","pbs-main","Main"]',
      );
    } finally {
      vi.useRealTimers();
    }
  });
});

describe('location-scoped evidence keeps workload-wide protection explicit', () => {
  beforeEach(() => vi.useFakeTimers({ now: BACKUP_IDENTITY_NOW, toFake: ['Date'] }));
  afterEach(() => vi.useRealTimers());

  const scopeNote = () => screen.queryByRole('note', { name: 'Backup location scope' });
  const pointTable = (panel: HTMLElement) =>
    within(
      within(panel).getByText('Restore evidence', { exact: true }).closest('div')!.parentElement!,
    ).getByRole('table');
  const setup = (kind: 'stale' | 'running' | 'snapshot') => {
    const guest = identityGuest('east-100', 'east', 'pve-1');
    const pve = {
      data: {
        backupTasks: [identityTask({ status: 'running', id: 'whole-workload-task' })],
        storageBackups: [identityArchive({ storage: 'current-local' })],
        guestSnapshots: kind === 'snapshot' ? [identitySnapshot()] : [],
      },
    };
    const pbs = {
      data: {
        backups:
          kind === 'snapshot'
            ? []
            : [
                identityPBS({
                  datastore: 'offsite',
                  backupTime: '2026-09-04T10:00:00Z',
                  inProgress: kind === 'running',
                }),
              ],
      },
    };
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(jsonResponse(url.endsWith('/pbs') ? pbs : pve)),
    );
    const posture = {
      ...protectionPosture(guest.id),
      lastSuccessfulPointAt: '2026-10-04T11:00:00Z',
    };
    apiFetchJSONMock.mockResolvedValue({
      data: [posture, { ...protectionPosture('west-101'), state: 'unprotected' }],
      policy: protectionPolicy,
    });
    const key =
      kind === 'snapshot' ? '["snapshot","east","pve-1"]' : '["pbs","pbs-server","offsite"]';
    window.history.replaceState(
      {},
      '',
      `/proxmox/backups/coverage?location=${encodeURIComponent(key)}`,
    );
    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[
          guest,
          {
            ...identityGuest('west-101', 'west', 'pve-2'),
            proxmox: { vmid: 101, instance: 'west', node: 'pve-2' },
          },
        ]}
      />
    ));
    return {
      pbs,
      key,
      label: kind === 'snapshot' ? 'Snapshot · east / pve-1' : 'PBS · pbs-server / offsite',
    };
  };

  it.each(['stale', 'running', 'snapshot'] as const)(
    'qualifies %s selected evidence without recomputing protection, tasks or all-target counts',
    async (kind) => {
      const { label } = setup(kind);
      const note = await screen.findByRole('note', { name: 'Backup location scope' });
      expect(note).toHaveTextContent(label);
      expect(note).toHaveTextContent('Backup ages and restore evidence below use');
      expect(note).toHaveTextContent(
        'Protection assessments and task history are workload-wide, not a rating of this location.',
      );
      expect(document.querySelector('[data-backup-verdict]')).toHaveTextContent('1 of 2 protected');
      expect(screen.getByRole('button', { name: '1 not protected' })).toBeInTheDocument();
      const row = document.querySelector<HTMLElement>('[data-proxmox-backup-row="coverage"]')!;
      expect(document.querySelectorAll('[data-proxmox-backup-row="coverage"]')).toHaveLength(1);
      expect(row).toHaveTextContent('Protected');
      if (kind === 'stale')
        expect(row.querySelector('[title*="2026-09-04T10:00:00Z"]')).not.toBeNull();
      else expect(row).toHaveTextContent('Unknown');
      const toggle = within(row).getByRole('button', { name: /Expand details/ });
      fireEvent.click(toggle);
      const panel = screen.getByTestId('proxmox-coverage-detail');
      expect(within(panel).getByRole('note', { name: 'Restore evidence scope' })).toHaveTextContent(
        label,
      );
      expect(panel).toHaveTextContent('cover the whole workload, not just this location.');
      expect(panel).toHaveTextContent('A current verified backup is available.');
      expect(panel).toHaveTextContent('whole-workload-task');
      expect(pointTable(panel)).not.toHaveTextContent('current-local');
      expect(pointTable(panel).querySelectorAll('tbody > tr')).toHaveLength(1);
      expect(apiFetchMock).toHaveBeenCalledTimes(2);
      expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);

      fireEvent.click(screen.getByRole('button', { name: 'Remove Backup location filter' }));
      await waitFor(() => expect(scopeNote()).not.toBeInTheDocument());
      expect(screen.getByTestId('proxmox-coverage-detail')).toBe(panel);
      expect(
        within(panel).queryByRole('note', { name: 'Restore evidence scope' }),
      ).not.toBeInTheDocument();
      expect(pointTable(panel)).toHaveTextContent('current-local');
      expect(pointTable(panel).querySelectorAll('tbody > tr')).toHaveLength(2);
      expect(document.querySelector('[data-backup-verdict]')).toHaveTextContent('1 of 2 protected');
      expect(apiFetchMock).toHaveBeenCalledTimes(2);
      expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
    },
  );

  it('withdraws unresolved scope text on ordinary polling and restores only the inventory label', async () => {
    vi.useFakeTimers({
      now: BACKUP_IDENTITY_NOW,
      toFake: ['Date', 'setInterval', 'clearInterval'],
    });
    const { pbs, key, label } = setup('stale');
    await screen.findByRole('note', { name: 'Backup location scope' });
    const original = structuredClone(pbs.data.backups);
    pbs.data.backups = [];
    await vi.advanceTimersByTimeAsync(30_000);
    await screen.findByText(/saved backup location cannot be identified uniquely/);
    expect(scopeNote()).not.toBeInTheDocument();
    expect(document.querySelectorAll('[data-proxmox-backup-row="coverage"]')).toHaveLength(0);
    expect(document.body).not.toHaveTextContent('current-local');
    expect(new URLSearchParams(window.location.search).get('location')).toBe(key);
    pbs.data.backups = original;
    await vi.advanceTimersByTimeAsync(30_000);
    expect(await screen.findByRole('note', { name: 'Backup location scope' })).toHaveTextContent(
      label,
    );
    expect(
      screen.queryByText(/saved backup location cannot be identified uniquely/),
    ).not.toBeInTheDocument();
    expect(apiFetchMock).toHaveBeenCalledTimes(6);
    expect(apiFetchJSONMock).toHaveBeenCalledTimes(3);
  });
});

describe('restore point list follows the consuming inventory scope', () => {
  afterEach(() => vi.restoreAllMocks());

  const mountScopedInventory = (query = '') => {
    vi.spyOn(Date, 'now').mockReturnValue(BACKUP_IDENTITY_NOW);
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse({
          data: url.endsWith('/pbs')
            ? {
                backups: [
                  identityPBS(),
                  identityPBS({
                    id: 'upper',
                    datastore: 'Main',
                    verified: false,
                    backupTime: '2026-10-03T10:00:00Z',
                    size: 16384,
                  }),
                  identityPBS({ id: 'running', inProgress: true, size: 1048576 }),
                ],
              }
            : {
                storageBackups: [
                  identityArchive(),
                  identityArchive({ id: 'old', time: '2026-10-03T11:00:00Z', size: 4096 }),
                  identityArchive({
                    id: 'west',
                    instance: 'west',
                    node: 'pve-2',
                    vmid: 200,
                    type: 'ct',
                    time: '2026-10-03T11:00:00Z',
                    size: 8192,
                  }),
                ],
                guestSnapshots: [identitySnapshot()],
                backupTasks: [],
              },
        }),
      ),
    );
    apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });
    window.history.replaceState({}, '', `/proxmox/backups/date${query ? `?${query}` : ''}`);
    return renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[
          identityGuest('east-100', 'east', 'pve-1'),
          {
            ...identityGuest('west-200', 'west', 'pve-2', { vmid: 200 }),
            type: 'system-container',
          },
        ]}
      />
    ));
  };
  const rows = () => document.querySelectorAll('[data-proxmox-backup-row="recoverable"]');

  it.each([
    ['source', 'source=archive', 3],
    ['verified', 'source=verified', 1],
    ['unverified', 'source=unverified', 1],
    ['node', 'node=pve-2', 1],
    ['type', 'type=ct', 1],
    ['search', 'q=west-200', 1],
    ['combined', 'node=pve-1&type=vm&source=archive', 2],
    ['case-sensitive location', `location=${encodeURIComponent('["pbs","pbs-server","Main"]')}`, 1],
  ])('narrows the list by %s', async (_label, query, count) => {
    mountScopedInventory(String(query));
    await waitFor(() => expect(rows()).toHaveLength(Number(count)));
  });

  it.each(['q=no-such-workload', 'location=missing', 'location=pbs%3Apbs-server%3Amain'])(
    'shows no restore points for empty or unresolved %s',
    async (query) => {
      mountScopedInventory(query);
      await screen.findByText(/0 of 6 restore points/);
      expect(rows()).toHaveLength(0);
    },
  );

  it('counts restore points and lists running entries apart', async () => {
    mountScopedInventory('');
    await waitFor(() => expect(rows()).toHaveLength(7));
    expect(screen.getByText('6 restore points · 1 running')).toHaveAttribute('role', 'status');
  });
});

describe('bare Backups entry opens Coverage', () => {
  beforeEach(() => {
    vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
    window.history.replaceState({}, '', '/proxmox/backups');
    mockBackupAPIs();
  });
  afterEach(() => vi.useRealTimers());

  // waitFor's interval is frozen with the query timers. Drain the router's
  // promise-based transition before asserting native history, which need not
  // cause another DOM mutation for waitFor to observe.
  const settleNavigation = () => vi.advanceTimersByTimeAsync(1);

  const responseFor = (
    state: 'protected' | 'attention' | 'unknown',
  ): ProtectionPosturesResponse => ({
    data: [{ ...protectionPosture('ct-112'), state, explanation: `Observed ${state} posture.` }],
    policy: protectionPolicy,
  });
  // The health strip's settled reading for one assessed workload.
  const verdictShows = (state: 'protected' | 'attention') =>
    state === 'protected'
      ? expect(document.querySelector('[data-backup-verdict]')).toHaveTextContent(
          '1 of 1 protected',
        )
      : expect(screen.getByRole('button', { name: '1 needs attention' })).toBeInTheDocument();

  it.each([
    { initial: 'attention', next: 'protected', view: 'coverage', table: 'coverage' },
    { initial: 'protected', next: 'attention', view: 'coverage', table: 'coverage' },
    { initial: 'unknown', next: 'protected', view: 'coverage', table: 'coverage' },
    // An explicit By date route holds its workspace through the same polls.
    { initial: 'protected', next: 'attention', view: 'date', table: 'recoverable' },
  ] as const)(
    'keeps $view, its open evidence and focus when $initial becomes $next',
    async ({ initial, next, view, table }) => {
      let state: 'protected' | 'attention' | 'unknown' = initial;
      apiFetchJSONMock.mockImplementation(() => Promise.resolve(responseFor(state)));
      if (view === 'date') window.history.replaceState({}, '', '/proxmox/backups/date');
      const historyLength = window.history.length;
      mountBackupReadState();
      await settleNavigation();
      await waitFor(() => expect(window.location.pathname).toBe(`/proxmox/backups/${view}`));
      expect(window.history.length).toBe(historyLength);
      const row = document.querySelector(`[data-proxmox-backup-row="${table}"]`)!;
      const disclosure = within(row as HTMLElement).getByRole('button', {
        name: /expand details/i,
      });
      await fireEvent.click(disclosure);
      disclosure.focus();
      const detail = document.getElementById(disclosure.getAttribute('aria-controls')!);
      expect(detail).not.toBeNull();

      state = next;
      await vi.advanceTimersByTimeAsync(30_000);
      await waitFor(() => verdictShows(next));
      expect(window.location.pathname).toBe(`/proxmox/backups/${view}`);
      expect(
        screen.getByRole('link', { name: view === 'date' ? /by date/i : /coverage/i }),
      ).toHaveAttribute('aria-current', 'page');
      expect(document.getElementById(disclosure.getAttribute('aria-controls')!)).toBe(detail);
      expect(disclosure).toHaveAttribute('aria-expanded', 'true');
      expect(disclosure).toHaveFocus();
      expect(apiFetchJSONMock).toHaveBeenCalledTimes(2);
      expect(sourceCalls('pve')).toHaveLength(2);
      expect(sourceCalls('pbs')).toHaveLength(2);
    },
  );

  it('does not wait for the assessment, preserves common filters/hash and replaces rather than pushes', async () => {
    const pending = deferred<ProtectionPosturesResponse>();
    apiFetchJSONMock.mockReturnValue(pending.promise);
    window.history.replaceState(
      {},
      '',
      '/proxmox/backups/?q=pbs&node=pve-a&type=ct&operator=saved#evidence',
    );
    const historyLength = window.history.length;
    mountBackupReadState();
    await settleNavigation();
    await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
    pending.resolve(responseFor('attention'));
    await settleNavigation();
    expect(window.location.search).toBe('?q=pbs&node=pve-a&type=ct&operator=saved');
    expect(window.location.hash).toBe('#evidence');
    expect(window.history.length).toBe(historyLength);
    expect(screen.getByPlaceholderText(/search backups by workload/i)).toHaveValue('pbs');
    expect(document.querySelectorAll('[data-proxmox-backup-row="coverage"]')).toHaveLength(1);
  });

  it('keeps the initial failure workspace through retry and lets a later health action choose Coverage', async () => {
    apiFetchJSONMock.mockRejectedValueOnce(new Error('Posture unavailable'));
    apiFetchJSONMock.mockResolvedValue(responseFor('protected'));
    mountBackupReadState();
    await settleNavigation();
    await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
    await screen.findByText(/Protection posture is unavailable/);
    await fireEvent.click(screen.getByRole('button', { name: 'Retry protection posture' }));
    await waitFor(() => verdictShows('protected'));
    expect(window.location.pathname).toBe('/proxmox/backups/coverage');
    await fireEvent.click(screen.getByRole('link', { name: /by date/i }));
    await settleNavigation();
    expect(window.location.pathname).toBe('/proxmox/backups/date');
    apiFetchJSONMock.mockResolvedValue(responseFor('attention'));
    await vi.advanceTimersByTimeAsync(30_000);
    await fireEvent.click(await screen.findByRole('button', { name: '1 needs attention' }));
    await settleNavigation();
    await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
    expect(new URLSearchParams(window.location.search).get('reason')).toBe('attention');
  });

  it.each([
    '/proxmox/backups/date',
    '/proxmox/backups/coverage',
    '/proxmox/backups?view=date',
    '/proxmox/backups?view=coverage',
  ])('does not rewrite an explicit view: %s', async (path) => {
    window.history.replaceState({}, '', path);
    apiFetchJSONMock.mockResolvedValue(responseFor('attention'));
    mountBackupReadState();
    await settleNavigation();
    await screen.findByRole('button', { name: '1 needs attention' });
    expect(window.location.pathname + window.location.search).toBe(path);
  });

  it('does not apply an old default after the operator has explicitly chosen By date', async () => {
    const pending = deferred<ProtectionPosturesResponse>();
    apiFetchJSONMock.mockReturnValue(pending.promise);
    mountBackupReadState();
    await settleNavigation();
    await fireEvent.click(await screen.findByRole('link', { name: /by date/i }));
    pending.resolve(responseFor('attention'));
    await settleNavigation();
    await screen.findByRole('button', { name: '1 needs attention' });
    expect(window.location.pathname).toBe('/proxmox/backups/date');
    expect(screen.getByRole('link', { name: /by date/i })).toHaveAttribute('aria-current', 'page');
  });

  it('keeps a saved exception filter on Coverage once that group is empty', async () => {
    window.history.replaceState({}, '', '/proxmox/backups?reason=stale');
    apiFetchJSONMock.mockResolvedValue(responseFor('protected'));
    mountBackupReadState();
    await settleNavigation();
    await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
    expect(new URLSearchParams(window.location.search).get('reason')).toBe('stale');
  });

  it('opens Coverage for a readable empty inventory without requesting an unscoped assessment', async () => {
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(jsonResponse(url.endsWith('/pve') ? emptyPVE : emptyPBS)),
    );
    renderInRouter(() => <ProxmoxBackupsTable emptyIcon={<span />} workloads={[]} />);
    await settleNavigation();
    await waitFor(() => expect(window.location.pathname).toBe('/proxmox/backups/coverage'));
    expect(apiFetchJSONMock).not.toHaveBeenCalled();
    await screen.findByText('Nothing to check yet');
  });
});

describe('By-date restore-point scope', () => {
  afterEach(() => vi.useRealTimers());
  it('shows the workload connection independently of its backup reader before disclosure', async () => {
    vi.useFakeTimers({ now: BACKUP_IDENTITY_NOW, toFake: ['Date'] });
    window.history.replaceState({}, '', '/proxmox/backups/date');
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse({
          data:
            url === '/api/backups/pbs'
              ? { backups: [identityPBS({ instance: 'independent-pbs-reader' })] }
              : { backupTasks: [], storageBackups: [], guestSnapshots: [] },
        }),
      ),
    );
    apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });
    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[identityGuest('east-100', 'east', 'pve-1')]}
      />
    ));
    const toggle = await screen.findByRole('button', {
      name: /^Expand details for east-100 \(VM 100\) · PVE connection: east · PBS backup/,
    });
    // With one PVE connection and one reader the row stays a single line;
    // the disclosure still names both scopes before it is opened.
    expect(toggle).toHaveAccessibleName(/Backup connection: independent-pbs-reader/);
    const point = toggle.closest('tr')!;
    expect(point.querySelector('[data-backup-workload-connection]')).toBeNull();
    expect(point.querySelector('[data-backup-source-connection]')).toBeNull();
    expect(screen.queryByTestId('proxmox-recoverable-detail')).not.toBeInTheDocument();
    expect(apiFetchMock).toHaveBeenCalledTimes(2);
    vi.useRealTimers();
  });
});

describe('By date recovery evidence limits', () => {
  beforeEach(() => {
    vi.useFakeTimers({ now: BACKUP_IDENTITY_NOW, toFake: ['Date'] });
    window.history.replaceState({}, '', '/proxmox/backups/date');
    apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });
  });
  afterEach(() => vi.useRealTimers());

  it.each([
    {
      name: 'guest snapshot',
      pve: { ...emptyPVE.data, guestSnapshots: [identitySnapshot()] },
      pbs: [] as ReturnType<typeof identityPBS>[],
      explanation: /shares the guest's storage.*not a separate backup/,
    },
    {
      name: 'verified PBS backup',
      pve: emptyPVE.data,
      pbs: [identityPBS({ protected: true })],
      explanation: /Verified is the provider's reported backup check, not a tested restore/,
    },
    {
      name: 'unverified PBS backup',
      pve: emptyPVE.data,
      pbs: [identityPBS({ verified: false })],
      explanation: /not reported as verified.*does not establish a successful restore/,
    },
    {
      name: 'PVE file without verification',
      pve: { ...emptyPVE.data, storageBackups: [identityArchive({ protected: true })] },
      pbs: [],
      explanation: /verification is not reported.*does not establish a successful restore/,
    },
    {
      name: 'PBS-backed PVE file',
      pve: {
        ...emptyPVE.data,
        storageBackups: [identityArchive({ isPBS: true, verified: true })],
      },
      pbs: [],
      explanation: /Verified is the provider's reported backup check, not a tested restore/,
    },
    {
      name: 'running PBS backup',
      pve: emptyPVE.data,
      pbs: [identityPBS({ inProgress: true, writeActivityObserved: true, writeActive: true })],
      explanation: /incomplete and may still be in progress.*not a completed restore point/,
    },
    {
      name: 'incomplete PBS backup with unread write activity',
      pve: emptyPVE.data,
      pbs: [identityPBS({ inProgress: true })],
      explanation: /incomplete and may still be in progress.*not a completed restore point/,
    },
    {
      name: 'failed PBS backup',
      pve: emptyPVE.data,
      pbs: [identityPBS({ inProgress: true, writeActivityObserved: true, writeActive: false })],
      explanation: /No current writer is reported.*not a completed restore point/,
    },
    {
      name: 'running PVE file',
      pve: { ...emptyPVE.data, storageBackups: [identityArchive({ inProgress: true })] },
      pbs: [],
      explanation: /incomplete and may still be in progress.*not a completed restore point/,
    },
  ])('explains $name without claiming a tested recovery', async ({ pve, pbs, explanation }) => {
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(jsonResponse({ data: url.endsWith('/pbs') ? { backups: pbs } : pve })),
    );
    renderInRouter(() => (
      <ProxmoxBackupsTable
        emptyIcon={<span />}
        workloads={[identityGuest('guest-100', 'east', 'pve-1')]}
      />
    ));
    const toggle = await screen.findByRole('button', { name: /Expand details/ });
    fireEvent.click(toggle);
    const detail = screen.getByTestId('proxmox-recoverable-detail');
    const note = within(detail).getByRole('note', { name: 'Recovery evidence limits' });
    expect(note).toBeVisible();
    expect(note).toHaveTextContent(explanation);
    expect(note).toHaveTextContent(/do not establish that the guest has thawed/);
    expect(note).toHaveTextContent(/filesystems accept writes/);
    expect(note).toHaveClass('whitespace-normal', 'wrap-anywhere');
    const kept =
      pbs.some((point) => point.protected) || pve.storageBackups.some((point) => point.protected);
    expect(
      note.textContent?.includes('retention setting, not verification or workload protection'),
    ).toBe(kept);
    expect(apiFetchMock).toHaveBeenCalledTimes(2);
  });

  it('does not describe a host backup as a thawed guest', async () => {
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse(
          url.endsWith('/pbs')
            ? { data: { backups: [identityPBS({ backupType: 'host', vmid: 'host-proof' })] } }
            : emptyPVE,
        ),
      ),
    );
    renderInRouter(() => <ProxmoxBackupsTable emptyIcon={<span />} />);
    fireEvent.click(await screen.findByRole('button', { name: /Expand details/ }));
    const note = screen.getByRole('note', { name: 'Recovery evidence limits' });
    expect(note).toHaveTextContent(/not a tested restore/);
    expect(note).not.toHaveTextContent(/guest|thawed|filesystems/);
  });

  it('updates the same open point from verified to incomplete and recovered without stale assurance', async () => {
    vi.useFakeTimers({
      now: BACKUP_IDENTITY_NOW,
      toFake: ['Date', 'setInterval', 'clearInterval'],
    });
    let point = identityPBS({ protected: true });
    apiFetchMock.mockImplementation((url: string) =>
      Promise.resolve(
        jsonResponse(url.endsWith('/pbs') ? { data: { backups: [point] } } : emptyPVE),
      ),
    );
    renderInRouter(() => <ProxmoxBackupsTable emptyIcon={<span />} />);
    const toggle = await screen.findByRole('button', { name: /Expand details/ });
    fireEvent.click(toggle);
    toggle.focus();
    const detail = screen.getByTestId('proxmox-recoverable-detail');
    expect(within(detail).getByRole('note')).toHaveTextContent(/not a tested restore/);
    for (const [next, message] of [
      [
        identityPBS({ inProgress: true, writeActivityObserved: true, writeActive: true }),
        'incomplete and may still be in progress',
      ],
      [
        identityPBS({ inProgress: true, writeActivityObserved: true, writeActive: false }),
        'No current writer is reported',
      ],
      [identityPBS({ verified: false }), 'not reported as verified'],
      [identityPBS({ verified: true }), "provider's reported backup check"],
    ] as const) {
      point = next;
      await vi.advanceTimersByTimeAsync(30_000);
      await waitFor(() => expect(within(detail).getByRole('note')).toHaveTextContent(message));
      expect(screen.getByTestId('proxmox-recoverable-detail')).toBe(detail);
      expect(toggle).toHaveFocus();
      expect(within(detail).getByRole('note')).not.toHaveTextContent('retention setting');
      if (next.inProgress)
        expect(within(detail).getByRole('note')).not.toHaveTextContent(
          "provider's reported backup check",
        );
    }
    expect(apiFetchMock).toHaveBeenCalledTimes(10);
  });
});

describe('PBS inventory state column', () => {
  it('reserves readable count space without changing loading, failure or real zero', () => {
    const [state, setState] = createSignal<'loading' | 'unavailable' | 'available'>('loading');
    const { container } = render(() => (
      <ProxmoxBackupServersTable
        servers={[
          {
            id: 'pbs-readable',
            name: 'main',
            displayName: 'main',
            type: 'pbs',
            status: 'online',
            lastSeen: BACKUP_IDENTITY_NOW,
            platformId: 'proxmox-pbs',
            platformType: 'proxmox-pbs',
            sourceType: 'api',
            pbs: {
              instanceId: 'pbs-main',
              connectionHealth: 'healthy',
              datastores: [{ name: 'tank', total: 1000, used: 400 }],
            },
          },
        ]}
        backups={[]}
        backupInventoryState={state()}
        layoutWidth={() => 720}
      />
    ));
    const table = container.querySelector('table')!;
    const countColumn = table.querySelector<HTMLElement>(
      'col[data-proxmox-backups-column="backups"]',
    )!;
    // Datastore, used, jobs, then the count; the server header holds status.
    const cells = table
      .querySelector('tbody tr:not([data-backup-server-group])')!
      .querySelectorAll('td');
    expect(countColumn.style.width).toBe('13%');
    expect(cells[3]).toHaveTextContent(/^Loading$/);
    setState('unavailable');
    expect(cells[3]).toHaveTextContent(/^Unavailable$/);
    expect(cells[1]).toHaveTextContent('40.0%');
    expect(cells[1]).toHaveTextContent('400 B / 1000 B');
    setState('available');
    expect(cells[3]).toHaveTextContent(/^0$/);
    expect(countColumn.style.width).toBe('13%');
  });
});

describe('Coverage provider-outcome-meaning through parsed API reads', () => {
  it.each([
    ['proxmox-pbs', 'pbs-backup-enumeration', 'PBS backup inventory'],
    ['proxmox-pve', 'pve-backup-enumeration', 'PVE backup inventory'],
  ] as const)(
    'keeps %s inventory outcomes distinct from actual tasks and restore points through polling',
    async (provider, source, label) => {
      vi.useFakeTimers({
        now: BACKUP_IDENTITY_NOW,
        toFake: ['Date', 'setInterval', 'clearInterval'],
      });
      try {
        window.history.replaceState({}, '', '/proxmox/backups/coverage');
        const guest = identityGuest('east-100', 'east', 'pve-1');
        const assessment = protectionPosture(guest.id);
        assessment.state = 'unprotected';
        assessment.coverage = 'none';
        assessment.freshness = 'unknown';
        assessment.verification = 'unknown';
        assessment.explanation =
          'Pulse can see the full backup history, but found no successful, completed backup for this resource.';
        assessment.providerStates = [
          { ...assessment.providerStates[0], provider, source, scope: 'read-scope' },
        ];
        apiFetchMock.mockImplementation(async (url: string) =>
          jsonResponse({
            data:
              url === '/api/backups/pbs'
                ? {
                    backups: [
                      identityPBS({
                        inProgress: true,
                        writeActivityObserved: true,
                        writeActive: true,
                        verified: false,
                      }),
                    ],
                  }
                : {
                    storageBackups: [],
                    guestSnapshots: [],
                    backupTasks: [identityTask()],
                  },
          }),
        );
        apiFetchJSONMock.mockImplementation(async () => ({
          data: [structuredClone(assessment)],
          policy: protectionPolicy,
        }));
        renderInRouter(() => <ProxmoxBackupsTable emptyIcon={<span />} workloads={[guest]} />);
        const toggle = await screen.findByRole('button', { name: /Expand details for east-100/ });
        fireEvent.click(toggle);
        const panel = await screen.findByTestId('proxmox-coverage-detail');
        await waitFor(() => expect(panel).toHaveTextContent(`Source ${label}`));
        const task = within(panel).getByText('Latest task', { selector: 'th' }).closest('tbody')!;
        expect(within(task).getByText('OK', { exact: true })).toBeVisible();
        expect(panel).toHaveTextContent('Reported outcome Success');
        expect(panel).not.toHaveTextContent('Job Success');
        expect(within(panel).getByText('Running', { exact: true })).toBeVisible();
        expect(within(panel).getByRole('img', { name: 'Unprotected' })).toBeInTheDocument();
        expect(panel).toHaveTextContent('no successful, completed backup');

        toggle.focus();
        Object.assign(assessment.providerStates[0], {
          jobState: 'failed',
          historyCompleteness: 'unavailable',
          permissions: 'denied',
        });
        await vi.advanceTimersByTimeAsync(30_000);
        await waitFor(() => expect(panel).toHaveTextContent('Reported outcome Failed'));
        expect(panel).toHaveTextContent('History Unavailable');
        expect(panel).toHaveTextContent('Access Denied');
        expect(panel).not.toHaveTextContent('Reported outcome Success');
        expect(
          within(
            within(panel).getByText('Latest task', { selector: 'th' }).closest('tbody')!,
          ).getByText('OK', { exact: true }),
        ).toBeVisible();
        expect(within(panel).getByText('Running', { exact: true })).toBeVisible();
        expect(screen.getByTestId('proxmox-coverage-detail')).toBe(panel);
        expect(toggle).toHaveFocus();
        // No new read, test-job or mutation is needed to explain the evidence.
        expect(apiFetchMock).toHaveBeenCalledTimes(4);
        expect(apiFetchJSONMock).toHaveBeenCalledTimes(2);
        expect(new Set(apiFetchMock.mock.calls.map(([url]) => url))).toEqual(
          new Set(['/api/backups/pbs', '/api/backups/pve']),
        );
      } finally {
        vi.useRealTimers();
      }
    },
  );
});