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.

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

import { ProxmoxCoverageTable } from '../ProxmoxCoverageTable';
import { ProxmoxRecoverableTable } from '../ProxmoxRecoverableTable';
import { buildProxmoxBackupRecoveryModel } from '../proxmoxBackupRecoveryModel';
import {
  BACKUP_IDENTITY_NOW,
  identityArchive,
  identityGuest,
  identityTask,
} from '../__fixtures__/backupIdentity';
import type { WorkloadCoverageRow } from '../proxmoxBackupRecoveryModel';
import type { CoverageSortKey } from '../proxmoxBackupsTableModel';
import { protectionPosture } from '@/utils/__fixtures__/protectionPosture';

// Record drawers link to the object they are about, which needs a router.
const renderInRouter = (component: () => JSX.Element) =>
  render(() => (
    <Router>
      <Route path="/*" component={component} />
    </Router>
  ));

const row = {
  key: 'w1',
  workload: {
    key: 'w1',
    type: 'vm',
    typeLabel: 'VM',
    vmid: '100',
    label: 'web (VM 100)',
    name: 'web',
    node: 'pve1',
  },
  artifacts: [],
  pbsCount: 1,
  archiveCount: 0,
  snapshotCount: 0,
  posture: 'protected',
  postureRank: 0,
  protectionPosture: {
    subjectResourceId: 'resource:vm:100',
    state: 'protected',
    freshness: 'current',
    verification: 'verified',
    coverage: 'complete',
    providerStates: [
      {
        provider: 'proxmox-pbs',
        source: 'pbs-backup-enumeration',
        scope: 'pbs-main',
        jobState: 'success',
        historyCompleteness: 'complete',
        permissions: 'sufficient',
        evidenceIds: ['evidence-provider'],
      },
    ],
    repositoryResourceIds: [],
    evidenceIds: ['evidence-provider'],
    explanation: 'A current verified backup is available from complete provider history.',
    evaluatedAt: '2026-07-19T00:00:00Z',
  },
} as unknown as WorkloadCoverageRow;

const headerTexts = () =>
  [...document.querySelectorAll('thead th')].map((th) => th.textContent?.trim() ?? '');

afterEach(cleanup);

describe('ProxmoxCoverageTable column visibility', () => {
  it('gives a phone row its full name, keeping the VM id only for namesakes', () => {
    const guest = (key: string, name: string, vmid: string, node: string) =>
      ({
        ...row,
        key,
        workload: { ...row.workload, key, name, vmid, node, label: `${name} (VM ${vmid})` },
      }) as WorkloadCoverageRow;
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[
          guest('a', 'checkout-web-02', '101', 'pve1'),
          guest('b', 'db', '200', 'pve1'),
          guest('c', 'db', '201', 'pve2'),
        ]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        layoutWidth={() => 375}
        showTaskColumn
      />
    ));
    const nameCell = (name: RegExp) => screen.getByRole('button', { name }).closest('td')!;
    // A unique name stands alone, so the narrow column holds it in full; its
    // disclosure label still names the VM.
    expect(nameCell(/Expand details for checkout-web-02/)).toHaveTextContent(/^checkout-web-02$/);
    expect(
      screen.getByRole('button', { name: /Expand details for checkout-web-02 \(VM 101\)/ }),
    ).toBeInTheDocument();
    // Namesakes keep the id that tells them apart.
    expect(nameCell(/Expand details for db \(VM 200\)/)).toHaveTextContent('VM 200');
    expect(nameCell(/Expand details for db \(VM 201\)/)).toHaveTextContent('VM 201');
  });

  it("keeps a namesake's VM id on a phone when a filter hides its twin, across letter case", () => {
    const guest = (key: string, name: string, vmid: string) =>
      ({
        ...row,
        key,
        workload: { ...row.workload, key, name, vmid, label: `${name} (VM ${vmid})` },
      }) as WorkloadCoverageRow;
    const all = [guest('b', 'DB', '200'), guest('c', 'db ', '201'), guest('d', 'web', '300')];
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[all[0], all[2]]}
        identityRows={all}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        layoutWidth={() => 375}
        showTaskColumn
      />
    ));
    const nameCell = (name: RegExp) => screen.getByRole('button', { name }).closest('td')!;
    // "DB" and "db " are the same name to a reader; the filtered-out twin
    // still counts, so the visible one keeps its id.
    expect(nameCell(/Expand details for DB \(VM 200\)/)).toHaveTextContent('VM 200');
    expect(nameCell(/Expand details for web \(VM 300\)/)).toHaveTextContent(/^web$/);
  });

  it('keeps a visible native phone disclosure through row activation and refresh [visible-coverage-disclosure]', () => {
    const [rows, setRows] = createSignal([row]);
    const [expanded, setExpanded] = createSignal<string | null>(null);
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={rows()}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={expanded()}
        onToggleExpand={(key) => setExpanded(expanded() === key ? null : key)}
        layoutWidth={() => 320}
        showTaskColumn
      />
    ));

    const toggle = screen.getByRole('button', { name: /Expand details for web/ });
    const summary = toggle.closest('tr')!;
    // CSS hit testing is covered by the actual-App browser proof. Keep the
    // Coverage opt-out explicit: row tapping must not hide its native control.
    expect(toggle).not.toHaveClass('sr-only');
    expect(toggle).toHaveClass('h-9', 'w-9');
    fireEvent.click(toggle);
    expect(expanded()).toBe(row.key);
    expect(toggle).toHaveAttribute('aria-expanded', 'true');
    expect(document.getElementById(toggle.getAttribute('aria-controls')!)).toBeInTheDocument();

    toggle.focus();
    const panel = screen.getByTestId('proxmox-coverage-detail');
    setRows([{ ...row, pbsCount: 2 }]);
    expect(screen.getByTestId('proxmox-coverage-detail')).toBe(panel);
    expect(toggle).toHaveFocus();
    fireEvent.keyDown(toggle, { key: ' ' });
    expect(expanded()).toBeNull();
    fireEvent.keyDown(toggle, { key: 'Enter' });
    expect(expanded()).toBe(row.key);

    fireEvent.click(within(summary).getByText('web', { exact: true }));
    expect(expanded()).toBeNull();
    fireEvent.click(within(summary).getByText('web', { exact: true }));
    expect(expanded()).toBe(row.key);
    expect(screen.getAllByTestId('proxmox-coverage-detail')).toHaveLength(1);
  });

  // This functional fixture renders four successive dense task-card previews.
  // Like the full-history consumer test, give its JSDOM work an explicit budget;
  // this is not a production render-time or query-latency assertion.
  it('resets a deliberate task preview when another workload is opened, not on a refresh', () => {
    const tasks = Array.from({ length: 24 }, (_, index) =>
      identityTask({ id: `candidate-${index}`, startTime: 'invalid' }),
    );
    const model = buildProxmoxBackupRecoveryModel({
      workloads: [identityGuest('east-100', 'east', 'pve-1')],
      tasks,
      pbsBackups: [],
      archives: [],
      snapshots: [],
      nowMs: BACKUP_IDENTITY_NOW,
    });
    const first = model.coverageRows[0];
    const second = {
      ...first,
      key: 'second',
      workload: { ...first.workload, key: 'second', name: 'second' },
    };
    const [expanded, setExpanded] = createSignal<string | null>(first.key);
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[first, second]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={expanded()}
        onToggleExpand={(key) => setExpanded(expanded() === key ? null : key)}
        showTaskColumn
      />
    ));
    fireEvent.click(screen.getByRole('button', { name: 'Show 8 more possible latest tasks' }));
    expect(screen.getByTestId('proxmox-coverage-detail')).toHaveTextContent(
      'Showing 16 of 24 possible latest tasks.',
    );
    setExpanded(second.key);
    expect(screen.getByTestId('proxmox-coverage-detail')).toHaveTextContent(
      'Showing 8 of 24 possible latest tasks.',
    );
    setExpanded(null);
    setExpanded(first.key);
    expect(screen.getByTestId('proxmox-coverage-detail')).toHaveTextContent(
      'Showing 8 of 24 possible latest tasks.',
    );
  }, 15_000);

  it('keeps malformed assessment dates unknown instead of normalising them or borrowing a clock', () => {
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[
          {
            ...row,
            protectionPosture: {
              ...row.protectionPosture!,
              evaluatedAt: '2026-09-31T10:00:00Z',
              lastSuccessfulPointAt: '2026-10-28T10:00:00',
              lastVerifiedAt: null,
            },
          },
        ]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={row.key}
        onToggleExpand={() => {}}
        showTaskColumn={false}
      />
    ));
    const panel = screen.getByTestId('proxmox-coverage-detail');
    for (const label of ['Evaluated', 'Latest successful point']) {
      expect(within(panel).getByText(label, { exact: true })).toHaveClass('whitespace-normal');
      const value = within(panel).getByText(label, { exact: true }).closest('tr')!;
      expect(value).toHaveTextContent('Unknown');
      expect(value.querySelector('time')).toBeNull();
    }
    expect(within(panel).getByText('Last verified').closest('tr')).toHaveTextContent(
      'Not reported',
    );
    expect(within(panel).getByRole('img', { name: 'Protected' })).toBeInTheDocument();
  });

  it('keeps uncertain archive evidence inspectable without changing server posture or its owner', async () => {
    const model = buildProxmoxBackupRecoveryModel({
      workloads: [identityGuest('east-100', 'east', 'pve-1')],
      pbsBackups: [],
      snapshots: [],
      tasks: [],
      nowMs: BACKUP_IDENTITY_NOW,
      archives: [
        ...Array.from({ length: 12 }, (_, index) => identityArchive({ id: `dated-${index}` })),
        identityArchive({ id: 'unknown', time: '2026-09-31T10:00:00Z', storage: 'undated-disk' }),
      ],
    });
    const current = model.coverageRows[0];
    // The keyed store reconciles a frame in place. A later HTTP read supplies
    // an independent frame, not the now-mutated original object.
    const restoredRows = structuredClone(model.coverageRows);
    const [rows, setRows] = createSignal(model.coverageRows);
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={rows()}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={current.key}
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 390}
      />
    ));
    const panel = screen.getByTestId('proxmox-coverage-detail');
    const evidence = () =>
      within(within(panel).getByText('Restore evidence').closest('div')!.parentElement!).getByRole(
        'table',
      );
    expect(evidence().querySelectorAll('tbody > tr')).toHaveLength(8);
    expect(evidence()).toHaveTextContent('undated-disk');
    expect(panel).toHaveTextContent('1 entry has an unavailable or future date');
    expect(current.workload.resourceId).toBe('east-100');
    expect(current.posture).toBe('unknown');
    fireEvent.click(within(panel).getByRole('button', { name: 'Show 5 more evidence entries' }));
    expect(evidence().querySelectorAll('tbody > tr')).toHaveLength(13);
    expect(
      within(panel).getByRole('button', { name: 'All 13 evidence entries shown' }),
    ).toHaveAttribute('aria-disabled', 'true');
    expect(model.coverageRows[0]).toBe(current);
    const more = within(panel).getByRole('button', { name: 'All 13 evidence entries shown' });
    more.focus();
    setRows([{ ...current, artifacts: [current.artifacts[0]] }]);
    await waitFor(() => expect(more).toHaveTextContent('All 1 evidence entry shown'));
    expect(document.activeElement).toBe(more);
    setRows([{ ...current, artifacts: [] }]);
    await waitFor(() => expect(more).toHaveTextContent('All 0 evidence entries shown'));
    expect(panel).not.toHaveTextContent('Restore evidence');
    expect(document.activeElement).toBe(more);
    setRows(restoredRows);
    await waitFor(() => expect(evidence().querySelectorAll('tbody > tr')).toHaveLength(13));
    expect(document.activeElement).toBe(more);
  });

  it('keeps full-width identity columns alongside the workload connection', () => {
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[row]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 1_200}
      />
    ));

    const headers = headerTexts();
    expect(headers).toContain('Workload');
    expect(headers).toContain('Type');
    expect(headers).toContain('Target ID');
    expect(headers).toContain('Node');
    expect(headers).toContain('Posture▲');
    expect(headers).toContain('Last backup');
    // Per-source ages are expansion detail at every width.
    expect(headers).not.toContain('PBS backup');
    expect(headers).not.toContain('Guest snapshot');
    expect(headers).not.toContain('PVE file');
    expect(headers).not.toContain('Task');
    // Full width retains its dedicated identity cells. The connection remains
    // in the name cell at every width, including explicit unknown scope.
    expect(document.body.textContent).toContain('VM');
    expect(document.body.textContent).toContain('100');
    expect(document.body.textContent).toContain('pve1');
    expect(document.body.textContent).not.toContain('ID 100');
    expect(document.body.textContent).not.toContain('Node pve1');
  });

  it('keeps posture, backup age and job visible in compact rows', () => {
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[row]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={true}
        layoutWidth={() => 330}
      />
    ));

    expect(headerTexts()).toEqual(['Workload', 'Posture▲', 'Age', 'Job']);
    expect(document.body.textContent).toContain('Prot.');
    expect(document.body.textContent).not.toContain('VM 100 · pve1');
  });

  it('names the reason in a compact row, not just the state', () => {
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[
          {
            ...row,
            posture: 'attention',
            protectionPosture: {
              ...protectionPosture('vm:100'),
              state: 'attention',
              reason: 'stale',
            },
          },
        ]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={true}
        layoutWidth={() => 330}
      />
    ));

    expect(document.body.textContent).toContain('Overdue');
    expect(document.body.textContent).not.toContain('Attn.');
    // The short word is for sighted phone users; assistive tech gets the full
    // state and explanation in its place.
    const word = screen.getByText('Overdue');
    expect(word).toHaveAttribute('aria-hidden', 'true');
    expect(word.parentElement?.querySelector('.sr-only')?.textContent).toMatch(
      /^Needs attention: ./,
    );
  });

  it.each([330, 600, 1200])(
    'keeps backup locations readable as locations at %ipx without using them as nodes',
    (width) => {
      const model = buildProxmoxBackupRecoveryModel({
        workloads: [],
        pbsBackups: [],
        snapshots: [],
        tasks: [],
        nowMs: BACKUP_IDENTITY_NOW,
        archives: [
          identityArchive({
            node: '',
            instance: 'reader-only',
            storage: 'long-repository-'.repeat(8),
          }),
        ],
      });
      const current = model.coverageRows[0];
      renderInRouter(() => (
        <ProxmoxCoverageTable
          rows={[current]}
          hasAnyRows
          emptyIcon={<span />}
          emptyTitle=""
          emptyDescription=""
          sortKey={() => 'posture'}
          sortDirection={() => 'asc'}
          onSort={() => {}}
          expandedKey={current.key}
          onToggleExpand={() => {}}
          showTaskColumn={false}
          layoutWidth={() => width}
        />
      ));
      const detail = screen.getByTestId('proxmox-coverage-detail');
      const location = detail.querySelector('[data-coverage-evidence-location]')!;
      expect(location).toHaveTextContent('long-repository-'.repeat(8));
      expect(location).toHaveClass('whitespace-normal', 'wrap-anywhere');
      if (width < 480)
        expect(location.textContent).toBe(`Location: ${current.artifacts[0].location}`);
      expect(within(detail).getByText('Node', { exact: true }).closest('tr')).toHaveTextContent(
        'Not reported',
      );
      expect(detail.querySelectorAll('[data-coverage-evidence-location]')).toHaveLength(1);
    },
  );

  it('keeps provider evidence in the workload drill-down instead of every table row', () => {
    const completedWithWarning: WorkloadCoverageRow = {
      ...row,
      latestTask: {
        id: 'task-with-warning',
        label: 'OK',
        status: 'OK',
        startedAt: '2026-07-18T23:00:00Z',
        startedMs: Date.parse('2026-07-18T23:00:00Z'),
        error: 'Provider reported completion with a warning',
      },
    };
    const { unmount } = renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[completedWithWarning]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 1_200}
      />
    ));

    expect(document.body.textContent).not.toContain('Provider evidence');
    expect(document.body.textContent).not.toContain(completedWithWarning.latestTask!.error);
    expect(document.body.textContent).not.toContain(
      'A current verified backup is available from complete provider history.',
    );
    unmount();

    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[completedWithWarning]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey="w1"
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 1_200}
      />
    ));

    expect(document.body.textContent).toContain('Provider evidence');
    expect(document.body.textContent).toContain('Proxmox Backup Server');
    expect(document.body.textContent).toContain('History Complete');
    expect(document.body.textContent).toContain('Access Sufficient');
    const task = screen.getByText('Latest task', { selector: 'th' }).closest('tbody')!;
    expect(task).toHaveTextContent('OK');
    expect(task).toHaveTextContent(completedWithWarning.latestTask!.error!);
    expect(task).toHaveTextContent('task-with-warning');
    expect(task).toHaveTextContent('Not reported');
    expect(
      within(task).getByText('Task status does not verify a restore or guest responsiveness.'),
    ).toHaveClass('whitespace-normal');
    // A reported OK does not erase a provider warning or override protection.
    expect(screen.getByText(completedWithWarning.latestTask!.error!)).toHaveClass(
      'whitespace-pre-wrap',
      'wrap-anywhere',
    );
  });

  it('keeps each provider scope beside its own access and history evidence', () => {
    const scoped = {
      ...row,
      protectionPosture: {
        ...row.protectionPosture!,
        providerStates: [
          row.protectionPosture!.providerStates[0],
          {
            ...row.protectionPosture!.providerStates[0],
            scope: 'pbs-other-estate',
            jobState: 'unknown',
            historyCompleteness: 'unavailable',
            permissions: 'denied',
          },
        ],
      },
    } as WorkloadCoverageRow;
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[scoped]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey="w1"
        onToggleExpand={() => {}}
        showTaskColumn={false}
      />
    ));

    const readable = screen.getByText('Scope pbs-main').closest('tr')!;
    const denied = screen.getByText('Scope pbs-other-estate').closest('tr')!;
    expect(readable).not.toBe(denied);
    expect(within(readable).getByText('Access Sufficient')).toBeVisible();
    expect(within(readable).getByText('History Complete')).toBeVisible();
    expect(within(denied).getByText('Access Denied')).toBeVisible();
    expect(within(denied).getByText('History Unavailable')).toBeVisible();
    expect(within(denied).queryByText('Access Sufficient')).not.toBeInTheDocument();
  });

  it.each(['', '   ', undefined])(
    'names absent scope %j Unknown instead of guessing the guest node',
    (scope) => {
      const unscoped = {
        ...row,
        protectionPosture: {
          ...row.protectionPosture!,
          providerStates: [{ ...row.protectionPosture!.providerStates[0], scope }],
        },
      } as WorkloadCoverageRow;
      renderInRouter(() => (
        <ProxmoxCoverageTable
          rows={[unscoped]}
          hasAnyRows
          emptyIcon={<span />}
          emptyTitle=""
          emptyDescription=""
          sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
          sortDirection={() => 'asc'}
          onSort={() => {}}
          expandedKey="w1"
          onToggleExpand={() => {}}
          showTaskColumn={false}
        />
      ));

      const provider = screen.getByText('Scope Unknown').closest('tr')!;
      expect(within(provider).getByText('Access Sufficient')).toBeVisible();
      expect(provider).not.toHaveTextContent('pve1');
    },
  );

  it('renders a long markup-like scope as wrapping text, not HTML or a link', () => {
    const scope = '<img src=x onerror=alert(1)>' + 'a'.repeat(200);
    const scoped = {
      ...row,
      protectionPosture: {
        ...row.protectionPosture!,
        providerStates: [{ ...row.protectionPosture!.providerStates[0], scope: ` ${scope} ` }],
      },
    };
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[scoped]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey="w1"
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 320}
      />
    ));

    const label = screen.getByText(`Scope ${scope}`);
    expect(label).toHaveClass('whitespace-normal', 'wrap-anywhere');
    expect(label.querySelector('img, a')).toBeNull();
  });

  it('heads the workload drawer with its posture and links to the workload', async () => {
    const onToggleExpand = vi.fn();
    const linked = {
      ...row,
      workload: { ...row.workload, resourceId: 'vm-100-resource' },
      artifacts: [
        {
          id: 'pbs-1',
          nativeId: 'pbs-1',
          sourceKind: 'pbs',
          sourceLabel: 'PBS',
          workload: row.workload,
          createdAt: '2026-07-18T23:00:00Z',
          createdMs: Date.parse('2026-07-18T23:00:00Z'),
          location: 'pbs-main:datastore-with-a-very-long-namespace/that-must-wrap',
          detail: 'vm/100/2026-07-18T23:00:00Z',
          protected: false,
          verified: true,
        },
      ],
    } as unknown as WorkloadCoverageRow;
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[linked]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey="w1"
        onToggleExpand={onToggleExpand}
        showTaskColumn={false}
        layoutWidth={() => 1_600}
      />
    ));

    const panel = screen.getByTestId('proxmox-coverage-detail');
    expect(within(panel).getByRole('heading', { level: 2, name: /web/ })).toBeInTheDocument();
    expect(
      within(panel).getByText(
        'A current verified backup is available from complete provider history.',
      ),
    ).toBeInTheDocument();
    expect(within(panel).getByRole('link', { name: 'Open web' })).toHaveAttribute(
      'href',
      '/proxmox/overview?resource=vm-100-resource',
    );
    // Restore evidence leads; provider quality is a section, not a grid.
    expect(within(panel).getByText('Restore evidence')).toBeInTheDocument();
    // `.table-fixed td` forces nowrap on cells, so the wrap lives on the span.
    const location = panel.querySelector('[data-coverage-evidence-location]');
    expect(location).toHaveClass('whitespace-normal', 'wrap-anywhere');
    expect(location).not.toHaveClass('truncate');
    expect(panel.querySelector('[data-coverage-evidence-detail]')).toHaveClass(
      'whitespace-pre-line',
      'wrap-anywhere',
    );
    // An age/source pair is not the point's identity. The open evidence keeps
    // the full identifier and metadata readable rather than only on hover.
    expect(panel.querySelector('[data-coverage-evidence-detail]')).toHaveTextContent(
      'Identifier: pbs-1',
    );
    expect(panel.querySelector('[data-coverage-evidence-detail]')).toHaveTextContent(
      'Reported date: 2026-07-18T23:00:00Z',
    );
    expect(panel.querySelector('[data-coverage-evidence-detail]')).toHaveTextContent(
      'Metadata: vm/100/2026-07-18T23:00:00Z',
    );
    // The source label wraps in the drawer too; a long snapshot name is not cut.
    expect(within(panel).getByText('PBS', { selector: 'td span' })).toHaveClass(
      'whitespace-normal',
    );
    expect(panel.querySelector('.grid')).toBeNull();
    expect(within(panel).getByText('Provider evidence', { selector: 'th' })).toBeInTheDocument();

    await fireEvent.click(within(panel).getByRole('button', { name: 'Collapse web details' }));
    expect(onToggleExpand).toHaveBeenCalledWith('w1');
  });

  it('states an empty restore-point list in a shared notice', () => {
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[{ ...row, posture: 'unprotected' } as WorkloadCoverageRow]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey="w1"
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 1_200}
      />
    ));

    const notice = screen.getByRole('status');
    expect(notice).toHaveTextContent(
      'No restore-point details are visible in the current list. The posture above may use previously recorded evidence.',
    );
    expect(notice.className).toContain('border-amber-300');
    // No registry match, so nothing to link to.
    expect(screen.queryByRole('link')).not.toBeInTheDocument();
  });

  it('windows large coverage result sets while keeping one continuous table', () => {
    const rows = Array.from({ length: 600 }, (_, index) => ({
      ...row,
      key: `w${index}`,
      workload: {
        ...row.workload,
        key: `w${index}`,
        vmid: String(100 + index),
        label: `workload-${index}`,
        name: `workload-${index}`,
      },
    })) as WorkloadCoverageRow[];

    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={rows}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 1_200}
      />
    ));

    expect(
      document.querySelectorAll(
        '[data-proxmox-backups-table="coverage"] [data-platform-window-spacer]',
      ),
    ).toHaveLength(2);
    expect(document.querySelectorAll('[data-proxmox-backup-row="coverage"]')).toHaveLength(140);
    expect(document.body.textContent).toContain('workload-0');
    expect(document.body.textContent).not.toContain('workload-599');
  });

  it('marks an empty evidence cell with a short label and the full reason on hover', () => {
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[row]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={true}
        layoutWidth={() => 1_200}
      />
    ));

    // The cell says None and the full reason sits on hover, so it cannot
    // truncate to "No PBS backup or PVE b…".
    const empty = (title: string) => document.querySelector(`td span[title="${title}"]`);
    for (const title of ['No PBS backup or PVE backup file', 'No recent task']) {
      expect(empty(title)).toHaveTextContent(/^None$/);
    }
  });

  it('explains snapshot-only and unrated rows in plain words', () => {
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[
          { ...row, key: 'snapshot-only', snapshotCount: 2 },
          { ...row, key: 'unrated', posture: 'not-evaluated', protectionPosture: undefined },
        ]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={true}
        layoutWidth={() => 1_200}
      />
    ));

    const titles = [...document.querySelectorAll('td span[title]')].map((span) =>
      span.getAttribute('title'),
    );
    expect(titles).toContain(
      'No PBS backup or PVE backup file. A guest snapshot is not a separate backup, so it does not count.',
    );
    expect(titles).toContain(
      'This backup does not match a guest Pulse currently monitors, so it is not rated.',
    );
    expect(titles.join(' ')).not.toMatch(/canonical|provider evidence|independent recovery/);
  });

  it('keeps a long node name truncating inside its own column', () => {
    // A capped inline-block sat above the row's text line; a block span fills
    // the fixed-layout cell and ends in an ellipsis there.
    const node = 'pve-production-rack-04-node-17.example.internal';
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[{ ...row, workload: { ...row.workload, node } }] as WorkloadCoverageRow[]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={(() => 'posture') as Accessor<CoverageSortKey>}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={null}
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => 1_200}
      />
    ));

    const span = document.querySelector(`td span[title="${node}"]`);
    expect(span).toHaveTextContent(node);
    expect(span?.parentElement?.children).toHaveLength(1);
    expect(span?.getAttribute('class')).toBe('block truncate');
    expect(span?.closest('table')).toHaveClass('table-fixed');
  });
});

describe('Coverage provider-outcome-meaning', () => {
  const mount = (source: string, jobState = 'success', width = 320) =>
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[
          {
            ...row,
            protectionPosture: {
              ...row.protectionPosture!,
              providerStates: [{ ...row.protectionPosture!.providerStates[0], source, jobState }],
            },
          } as WorkloadCoverageRow,
        ]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={row.key}
        onToggleExpand={() => {}}
        showTaskColumn={false}
        layoutWidth={() => width}
      />
    ));

  it.each([
    ['pbs-backup-enumeration', 'PBS backup inventory'],
    ['pve-backup-enumeration', 'PVE backup inventory'],
    ['legacy-recovery-point', 'Retained restore point'],
    ['future-backup-enumeration', 'future-backup-enumeration'],
    ['', 'Unknown'],
    ['   ', 'Unknown'],
  ])('identifies %j without guessing a backup job result', (source, label) => {
    mount(` ${source} `);
    const panel = screen.getByTestId('proxmox-coverage-detail');
    expect(within(panel).getByText(`Source ${label}`)).toHaveClass(
      'whitespace-normal',
      'wrap-anywhere',
    );
    expect(within(panel).getByText('Reported outcome Success')).toBeVisible();
    expect(panel).not.toHaveTextContent('Job Success');
    // Source and outcome can come from different-aged inputs to the rollup.
    // Replacing Job with Collection would create another unsupported claim.
    expect(panel).not.toHaveTextContent('Collection Success');
    expect(panel).toHaveTextContent(
      'Provider evidence describes inventory reads or retained restore points, not a backup job result.',
    );
    expect(panel).toHaveTextContent('Task and restore-point states are shown separately.');
  });

  it.each(['success', 'warning', 'failed', 'running', 'unknown'])(
    'retains the reported %s without changing protection, history or access',
    (outcome) => {
      mount('pbs-backup-enumeration', outcome, 1200);
      const panel = screen.getByTestId('proxmox-coverage-detail');
      expect(panel).toHaveTextContent(
        `Reported outcome ${outcome.charAt(0).toUpperCase() + outcome.slice(1)}`,
      );
      expect(panel).toHaveTextContent('History Complete');
      expect(panel).toHaveTextContent('Access Sufficient');
      expect(within(panel).getByRole('img', { name: 'Protected' })).toBeInTheDocument();
    },
  );

  it.each([320, 1200])('keeps an unknown source literal and wrapping at %ipx', (width) => {
    const source = '<img src=x onerror=alert(1)>' + 'source-'.repeat(30);
    mount(source, 'unknown', width);
    const panel = screen.getByTestId('proxmox-coverage-detail');
    const label = within(panel).getByText(`Source ${source}`);
    expect(label).toHaveClass('whitespace-normal', 'wrap-anywhere');
    expect(label).not.toHaveClass('truncate');
    expect(label.querySelector('img, a')).toBeNull();
    expect(panel).toHaveTextContent('Reported outcome Unknown');
  });
});

describe('Coverage absence requires readable, complete history', () => {
  const unknownTitle =
    'No completed backup is visible in the current list. Missing entries do not mean no backups exist. Expand this row to inspect the evidence.';
  const completePosture = row.protectionPosture!;
  const provider = completePosture.providerStates[0];
  const mount = (subject: WorkloadCoverageRow, historyReadIncomplete = false) =>
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={[subject]}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey="w1"
        onToggleExpand={() => {}}
        showTaskColumn={false}
        historyReadIncomplete={historyReadIncomplete}
        layoutWidth={() => 320}
      />
    ));

  it.each([
    ['partial history', { ...provider, historyCompleteness: 'partial' as const }],
    ['unavailable history', { ...provider, historyCompleteness: 'unavailable' as const }],
    ['unknown history', { ...provider, historyCompleteness: 'unknown' as const }],
    ['partial access', { ...provider, permissions: 'partial' as const }],
    ['denied access', { ...provider, permissions: 'denied' as const }],
    ['unknown access', { ...provider, permissions: 'unknown' as const }],
  ])('does not turn %s into confirmed absence', (_label, incompleteProvider) => {
    mount({
      ...row,
      posture: 'attention',
      protectionPosture: { ...completePosture, providerStates: [incompleteProvider] },
    });

    expect(screen.getByTitle(unknownTitle)).toHaveTextContent(/^Unknown$/);
    expect(screen.getByLabelText(`Unknown age. ${unknownTitle}`)).toBeInTheDocument();
    expect(screen.getByRole('status')).toHaveTextContent(
      'Restore-point history is not confirmed complete. Missing entries do not mean no backups exist.',
    );
    expect(document.body.textContent).not.toContain('No restore points found');
    expect(document.body.textContent).not.toContain('No restore points reported');
    // This copy qualifies the list; it does not synthesise a hidden archive.
    expect(screen.queryByText('Restore evidence')).not.toBeInTheDocument();
  });

  it.each([
    ['missing posture', undefined],
    ['no provider evidence', { ...completePosture, providerStates: [] }],
    ['unknown scope', { ...completePosture, coverage: 'unknown' as const }],
    ['partial scope', { ...completePosture, coverage: 'partial' as const }],
    [
      'one readable source beside an unreadable source',
      {
        ...completePosture,
        providerStates: [provider, { ...provider, historyCompleteness: 'unavailable' as const }],
      },
    ],
  ])('keeps %s unknown even when raw requests fulfilled', (_label, protectionPosture) => {
    mount({ ...row, protectionPosture });
    expect(screen.getByTitle(unknownTitle)).toHaveTextContent(/^Unknown$/);
    expect(screen.getByRole('status')).toHaveTextContent('not confirmed complete');
  });

  it('qualifies pending/failed reads even beside retained complete provider quality', () => {
    mount(row, true);
    expect(screen.getByTitle(unknownTitle)).toHaveTextContent(/^Unknown$/);
    expect(screen.getByRole('status')).toHaveTextContent('not confirmed complete');
  });

  it('keeps a known backup outside the raw list unknown, not None', () => {
    mount({
      ...row,
      protectionPosture: {
        ...completePosture,
        lastSuccessfulPointAt: '2026-10-23T00:00:00Z',
      },
    });
    expect(screen.getByTitle(unknownTitle)).toHaveTextContent(/^Unknown$/);
    expect(screen.getByRole('status')).toHaveTextContent(
      'No restore-point details are visible in the current list. The posture above may use previously recorded evidence.',
    );
    expect(screen.queryByText('Restore evidence')).not.toBeInTheDocument();
  });

  it('preserves accepted-empty history as a scoped empty observation', () => {
    mount({
      ...row,
      posture: 'unprotected',
      protectionPosture: { ...completePosture, state: 'unprotected', coverage: 'none' },
    });
    expect(screen.getByTitle('No PBS backup or PVE backup file')).toHaveTextContent(/^None$/);
    expect(screen.getByRole('status')).toHaveTextContent(
      'No restore-point details are visible in the current list. The posture above may use previously recorded evidence.',
    );
    expect(screen.queryByTitle(unknownTitle)).not.toBeInTheDocument();
  });

  it.each(['pve-backup-enumeration', 'pbs-backup-enumeration'])(
    'does not broaden complete %s into absence of retained snapshots',
    (source) => {
      const explanation =
        'Only snapshots were found. A snapshot is not a separate backup, so it does not count.';
      mount({
        ...row,
        posture: 'unprotected',
        protectionPosture: {
          ...completePosture,
          state: 'unprotected',
          coverage: 'none',
          explanation,
          providerStates: [{ ...provider, source }],
        },
      });

      expect(screen.getByText(explanation)).toBeInTheDocument();
      expect(screen.getByText('History Complete')).toBeInTheDocument();
      expect(screen.getByRole('status')).toHaveTextContent(
        'No restore-point details are visible in the current list. The posture above may use previously recorded evidence.',
      );
      expect(screen.getByTitle('No PBS backup or PVE backup file')).toHaveTextContent('None');
      // No lastSuccessfulPointAt is expected for a guest snapshot. Nor may the
      // notice synthesize a raw snapshot, date or completed backup from prose.
      expect(screen.queryByText('Restore evidence')).not.toBeInTheDocument();
      expect(document.body.textContent).not.toContain('No restore points reported');
    },
  );
});

const scrollingModel = () =>
  buildProxmoxBackupRecoveryModel({
    workloads: Array.from({ length: 170 }, (_, i) =>
      identityGuest(`guest-${i}`, 'east', 'pve-1', { vmid: 100 + i }),
    ),
    archives: Array.from({ length: 170 }, (_, i) =>
      identityArchive({
        id: `archive-${i}`,
        vmid: 100 + i,
        ctime: BACKUP_IDENTITY_NOW / 1000 - i * 60,
      }),
    ),
    snapshots: [],
    pbsBackups: [],
    tasks: [],
    nowMs: BACKUP_IDENTITY_NOW,
  });

describe('backup evidence native scrolling', () => {
  afterEach(() => {
    vi.restoreAllMocks();
    vi.unstubAllGlobals();
  });
  it.each([
    ['coverage', 390],
    ['coverage', 1365],
    ['date', 390],
    ['date', 1365],
  ] as const)(
    'keeps a tall %s drawer and its scroll extent at %ipx, including after a live snapshot',
    async (view, width) => {
      let scrollTop = 0;
      const drawerHeight = 4800;
      vi.stubGlobal('innerWidth', width);
      vi.stubGlobal('innerHeight', 120);
      vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (
        this: Element,
      ) {
        const top =
          this.getAttribute('data-platform-window-spacer') === 'top' ||
          this.hasAttribute('data-proxmox-backups-table')
            ? -scrollTop
            : 0;
        const height = this.hasAttribute('data-inline-detail-row') ? drawerHeight : 32;
        return {
          x: 0,
          y: top,
          top,
          left: 0,
          right: width,
          bottom: top + height,
          width,
          height,
          toJSON: () => ({}),
        } as DOMRect;
      });
      const initial = scrollingModel();
      const [rows, setRows] = createSignal(initial.coverageRows);
      const [artifacts, setArtifacts] = createSignal(initial.recoverableArtifacts);
      const [expanded, setExpanded] = createSignal<string | null>(null);
      const { container } = renderInRouter(() =>
        view === 'coverage' ? (
          <ProxmoxCoverageTable
            rows={rows()}
            hasAnyRows
            emptyIcon={<span />}
            emptyTitle="No guests"
            emptyDescription="No guests"
            sortKey={() => 'workload'}
            sortDirection={() => 'asc'}
            onSort={() => {}}
            expandedKey={expanded()}
            onToggleExpand={(key) => setExpanded((current) => (current === key ? null : key))}
            showTaskColumn={false}
            layoutWidth={() => width}
          />
        ) : (
          <ProxmoxRecoverableTable
            artifacts={artifacts()}
            hasAnyArtifacts
            emptyIcon={<span />}
            emptyTitle="No backups"
            emptyDescription="No backups"
            sortKey={() => 'created'}
            sortDirection={() => 'desc'}
            onSort={() => {}}
            sizeMaxBytes={1024}
            groupByDay
            layoutWidth={() => width}
          />
        ),
      );
      const rowSelector = `[data-proxmox-backup-row="${view === 'coverage' ? 'coverage' : 'recoverable'}"]`;
      const mountedCount = () => container.querySelectorAll(rowSelector).length;
      const budget = width < 640 ? 36 : 140;
      expect(mountedCount()).toBeLessThanOrEqual(budget);
      expect(mountedCount()).toBeGreaterThan(0);
      const first = container.querySelector(rowSelector)!;
      const disclosure = first.querySelector<HTMLButtonElement>('button[aria-controls]')!;
      await fireEvent.click(disclosure);
      const detail = await screen.findByTestId(
        view === 'coverage' ? 'proxmox-coverage-detail' : 'proxmox-recoverable-detail',
      );
      disclosure.focus();
      // The whole logical row includes the expanded panel. Scrolling inside
      // it must not advance the runway as if its pixels were 118 summary rows.
      scrollTop = 3800;
      await fireEvent.scroll(window);
      expect(detail).toBeInTheDocument();
      expect(disclosure).toHaveFocus();

      const refreshed = scrollingModel();
      refreshed.coverageRows[0]!.workload.name = 'refreshed-guest';
      refreshed.recoverableArtifacts[0]!.workload.name = 'refreshed-guest';
      setRows(refreshed.coverageRows);
      setArtifacts(refreshed.recoverableArtifacts);
      await waitFor(() => {
        expect(container.querySelector(rowSelector)?.querySelector('button')).toBe(disclosure);
        expect(disclosure).toHaveFocus();
        expect(detail).toBeInTheDocument();
        expect(first).toHaveTextContent('refreshed-guest');
      });

      scrollTop = drawerHeight + 3200;
      await fireEvent.scroll(window);
      await waitFor(() => expect(first).not.toBeInTheDocument());
      const spacer = container.querySelector<HTMLElement>('[data-platform-window-spacer="top"]')!;
      expect(parseFloat(spacer.style.height)).toBeGreaterThan(drawerHeight);
      expect(mountedCount()).toBeLessThanOrEqual(budget);

      scrollTop = 0;
      await fireEvent.scroll(window);
      await waitFor(() =>
        expect(
          screen.getByTestId(
            view === 'coverage' ? 'proxmox-coverage-detail' : 'proxmox-recoverable-detail',
          ),
        ).toBeInTheDocument(),
      );
      const table = container.querySelector('table')!;
      const columns = table.querySelectorAll(':scope > thead th').length;
      for (const cell of table.querySelectorAll<HTMLTableCellElement>(
        '[data-platform-window-spacer] > td',
      )) {
        expect(cell.colSpan).toBe(columns);
      }

      // Full-result filtering can shrink a previously scrolled estate below
      // the mounted budget. No old spacers or stale selected panel survive.
      setRows(refreshed.coverageRows.slice(-1));
      setArtifacts(refreshed.recoverableArtifacts.slice(-1));
      await waitFor(() => {
        expect(mountedCount()).toBe(1);
        expect(container.querySelector('[data-platform-window-spacer]')).toBeNull();
        expect(detail).not.toBeInTheDocument();
      });
    },
  );
});

describe('indeterminate task order in the canonical Coverage consumer', () => {
  it.each([330, 1200])(
    'does not show a latest OK when a failed task cannot be ordered at %ipx',
    (width) => {
      const model = buildProxmoxBackupRecoveryModel({
        workloads: [identityGuest('east-100', 'east', 'pve-1')],
        pbsBackups: [],
        archives: [],
        snapshots: [],
        tasks: [
          identityTask({
            id: 'unknown-start',
            status: 'failed',
            startTime: '',
            error: 'retained failure',
          }),
          identityTask({ id: 'dated-ok' }),
        ],
        nowMs: BACKUP_IDENTITY_NOW,
      });
      const current = model.coverageRows[0];
      renderInRouter(() => (
        <ProxmoxCoverageTable
          rows={model.coverageRows}
          hasAnyRows
          emptyIcon={<span />}
          emptyTitle=""
          emptyDescription=""
          sortKey={() => 'posture'}
          sortDirection={() => 'asc'}
          onSort={() => {}}
          expandedKey={current.key}
          onToggleExpand={() => {}}
          showTaskColumn
          layoutWidth={() => width}
        />
      ));
      const summary = document.querySelector('[data-proxmox-backup-row="coverage"]')!;
      expect(summary).toHaveTextContent('Latest task: Unknown');
      expect(summary).not.toHaveTextContent('OK');
      const panel = screen.getByTestId('proxmox-coverage-detail');
      expect(within(panel).queryByText('Latest task', { selector: 'th', exact: true })).toBeNull();
      expect(
        within(panel).getByText('Task order', { selector: 'th', exact: true }),
      ).toBeInTheDocument();
      expect(
        within(panel).getByText('Possible latest task 1', { selector: 'th', exact: true }),
      ).toBeInTheDocument();
      expect(
        within(panel).getByText('Possible latest task 2', { selector: 'th', exact: true }),
      ).toBeInTheDocument();
      expect(panel).toHaveTextContent('unknown-start');
      expect(panel).toHaveTextContent('retained failure');
      expect(panel).toHaveTextContent('dated-ok');
      expect(panel).toHaveTextContent(
        'Task status does not verify a restore or guest responsiveness.',
      );
    },
  );
});

describe('unknown duration in possible-latest task details', () => {
  it.each([320, 1200])('preserves both statuses and only the valid duration at %ipx', (width) => {
    const model = buildProxmoxBackupRecoveryModel({
      workloads: [identityGuest('east-100', 'east', 'pve-1')],
      pbsBackups: [],
      archives: [],
      snapshots: [],
      tasks: [
        identityTask({ id: 'future-end', endTime: '2026-10-04T12:05:00Z' }),
        identityTask({ id: 'reported-failure', status: 'failed', error: 'Retain this error' }),
      ],
      nowMs: BACKUP_IDENTITY_NOW,
    });
    renderInRouter(() => (
      <ProxmoxCoverageTable
        rows={model.coverageRows}
        hasAnyRows
        emptyIcon={<span />}
        emptyTitle=""
        emptyDescription=""
        sortKey={() => 'posture'}
        sortDirection={() => 'asc'}
        onSort={() => {}}
        expandedKey={model.coverageRows[0].key}
        onToggleExpand={() => {}}
        layoutWidth={() => width}
        showTaskColumn
      />
    ));
    const taskCard = (id: string) => screen.getByText(id, { exact: true }).closest('tbody')!;
    const duration = (card: HTMLElement) =>
      within(card).getByText('Duration', { exact: true, selector: 'td' }).closest('tr')!;
    expect(duration(taskCard('future-end'))).toHaveTextContent('Unknown');
    expect(taskCard('future-end')).toHaveTextContent('OK');
    expect(taskCard('future-end')).toHaveTextContent(
      'The reported timestamps or running status do not establish a completed duration.',
    );
    expect(duration(taskCard('reported-failure'))).toHaveTextContent('5m 0s');
    expect(taskCard('reported-failure')).toHaveTextContent('Failed');
    expect(taskCard('reported-failure')).toHaveTextContent('Retain this error');
    expect(screen.getByTestId('proxmox-coverage-detail')).toHaveTextContent('Task order');
    expect(model.coverageRows[0].posture).toBe('unknown');
  });
});

describe('Coverage owned focus during live reordering', () => {
  function mountReordering(width = 1200, type: 'vm' | 'ct' = 'vm') {
    const makeRow = (key: string): WorkloadCoverageRow => ({
      ...structuredClone(row),
      key,
      workload: {
        ...row.workload,
        key,
        resourceId: key,
        type,
        typeLabel: type === 'vm' ? 'VM' : 'LXC',
        name: key,
        label: key,
      },
    });
    const initial = [makeRow('alpha'), makeRow('mike'), makeRow('zulu')];
    const [rows, setRows] = createSignal(initial);
    const [mounted, setMounted] = createSignal(true);
    const [expanded, setExpanded] = createSignal<string | null>('alpha');
    const rendered = renderInRouter(() => (
      <>
        <input aria-label="Outside Coverage" />
        <Show when={mounted()}>
          <ProxmoxCoverageTable
            rows={rows()}
            hasAnyRows
            emptyIcon={<span />}
            emptyTitle="No guests"
            emptyDescription="No guests"
            sortKey={() => 'posture'}
            sortDirection={() => 'asc'}
            onSort={() => {}}
            expandedKey={expanded()}
            onToggleExpand={(key) => setExpanded(expanded() === key ? null : key)}
            layoutWidth={() => width}
            showTaskColumn={false}
          />
        </Show>
      </>
    ));
    // A live posture change moves this same logical workload to the other end
    // of the sorted list. The table must not change that order to keep focus.
    const reorder = () => setRows(['zulu', 'mike', 'alpha'].map(makeRow));
    return { ...rendered, reorder, setRows, setMounted, makeRow };
  }

  it.each([
    [1200, 'vm'],
    [1200, 'ct'],
    [320, 'vm'],
    [320, 'ct'],
  ] as const)(
    'keeps the same %s px %s disclosure focused after row movement',
    async (width, type) => {
      const { container, reorder } = mountReordering(width, type);
      const disclosure = screen.getByRole('button', { name: /Collapse details for alpha/ });
      const panel = screen.getByTestId('proxmox-coverage-detail');
      const focus = vi.spyOn(disclosure, 'focus');
      disclosure.focus();
      focus.mockClear();
      reorder();
      await Promise.resolve();
      expect(
        [...container.querySelectorAll('[data-proxmox-backup-row="coverage"]')].map((element) =>
          element.querySelector('button')?.getAttribute('aria-label'),
        ),
      ).toEqual([
        expect.stringContaining('zulu'),
        expect.stringContaining('mike'),
        expect.stringContaining('alpha'),
      ]);
      expect(screen.getByRole('button', { name: /Collapse details for alpha/ })).toBe(disclosure);
      expect(screen.getByTestId('proxmox-coverage-detail')).toBe(panel);
      expect(disclosure).toHaveFocus();
      expect(focus).toHaveBeenCalledWith({ preventScroll: true });
      fireEvent.keyDown(disclosure, { key: 'Enter' });
      expect(screen.queryByTestId('proxmox-coverage-detail')).not.toBeInTheDocument();
      expect(disclosure).toHaveFocus();
    },
  );

  it('keeps a connected detail link focused rather than falling back to its disclosure', async () => {
    const { reorder } = mountReordering();
    const panel = screen.getByTestId('proxmox-coverage-detail');
    const link = within(panel).getAllByRole('link')[0]!;
    link.focus();
    reorder();
    await Promise.resolve();
    expect(link).toHaveFocus();
    expect(screen.getByTestId('proxmox-coverage-detail')).toBe(panel);
  });

  it.each([false, true])(
    'does not capture deliberate blur when retained rows do not move (append: %s)',
    async (append) => {
      const { setRows, makeRow } = mountReordering();
      const disclosure = screen.getByRole('button', { name: /Collapse details for alpha/ });
      disclosure.focus();
      setRows(['alpha', 'mike', 'zulu', ...(append ? ['new'] : [])].map(makeRow));
      disclosure.blur();
      await Promise.resolve();
      expect(document.body).toHaveFocus();
    },
  );

  it('does not reclaim focus already outside Coverage', async () => {
    const { reorder } = mountReordering();
    const outside = screen.getByRole('textbox', { name: 'Outside Coverage' });
    outside.focus();
    reorder();
    await Promise.resolve();
    expect(outside).toHaveFocus();
  });

  it.each([false, true])(
    'does not override an intervening focus choice (then blur: %s)',
    async (blur) => {
      const { reorder } = mountReordering();
      const disclosure = screen.getByRole('button', { name: /Collapse details for alpha/ });
      disclosure.focus();
      reorder();
      const outside = screen.getByRole('textbox', { name: 'Outside Coverage' });
      outside.focus();
      if (blur) outside.blur();
      await Promise.resolve();
      expect(document.activeElement).toBe(blur ? document.body : outside);
    },
  );

  it.each(['remove', 'depart'] as const)(
    'does not refocus a retired element after %s',
    async (kind) => {
      const { reorder, setRows, setMounted, makeRow } = mountReordering();
      const disclosure = screen.getByRole('button', { name: /Collapse details for alpha/ });
      disclosure.focus();
      reorder();
      if (kind === 'depart') setMounted(false);
      else setRows([makeRow('zulu')]);
      const focus = vi.spyOn(disclosure, 'focus');
      await Promise.resolve();
      expect(disclosure).not.toBeInTheDocument();
      expect(focus).not.toHaveBeenCalled();
    },
  );
});