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.

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

import { FindingsPanel } from '../FindingsPanel';
import { RELATIVE_TIME_TICK_MS } from '@/utils/relativeTimeClock';
import { notificationStore } from '@/stores/notifications';

const mockState = vi.hoisted(() => {
  const loadFindings = vi.fn();
  const loadPatrolFindings = vi.fn();
  const getResource = vi.fn((resourceId: string) =>
    resourceId === 'app-container:truenas-main:nextcloud'
      ? ({
          id: 'app-container:truenas-main:nextcloud',
          type: 'app-container',
          name: 'nextcloud',
          displayName: 'Nextcloud',
          parentId: 'truenas-main',
          parentName: 'TrueNAS Main',
          platformId: 'truenas-main',
          platformType: 'truenas',
          sourceType: 'api',
          status: 'running',
          lastSeen: Date.now(),
          platformData: {
            sources: ['truenas'],
          },
        } as const)
      : undefined,
  );

  const findings = [
    {
      id: 'finding-truenas-app',
      source: 'ai-patrol',
      resourceId: 'app-container:truenas-main:nextcloud',
      resourceName: 'Nextcloud',
      resourceType: 'app-container',
      category: 'reliability',
      severity: 'warning',
      title: 'Nextcloud failed readiness checks',
      description: 'Pulse Patrol detected repeated readiness probe failures.',
      impact: 'Nextcloud is unreachable for users until readiness recovers.',
      detectedAt: '2026-03-30T10:00:00Z',
      lastSeenAt: '2026-03-30T10:05:00Z',
      status: 'active',
    },
  ];
  const patrolFindings: Array<Record<string, unknown>> = [
    {
      id: 'finding-provider-issue',
      source: 'ai-patrol',
      resourceId: 'instance:node:100',
      resourceName: 'vm-100',
      resourceType: 'vm',
      alertIdentifier: 'instance:node:100::patrol/provider',
      category: 'reliability',
      severity: 'warning',
      title: 'Provider connection issue',
      description: 'Pulse Patrol could not complete provider analysis.',
      impact: 'Patrol cannot analyze infrastructure until provider setup is fixed.',
      detectedAt: '2026-03-30T11:00:00Z',
      lastSeenAt: '2026-03-30T11:05:00Z',
      status: 'active',
    },
  ];

  return {
    initialFindings: findings,
    initialPatrolFindings: patrolFindings,
    findings,
    findingsError: null as string | null,
    findingsLoading: false,
    patrolFindings,
    patrolFindingsError: null as string | null,
    patrolFindingsLoading: false,
    patrolPendingApprovals: [] as Array<{
      status: string;
      toolId: string;
      targetId: string;
      expiresAt?: string;
    }>,
    attentionFindingIds: [] as string[],
    approvalFindingIds: [] as string[],
    getResource,
    loadFindings,
    loadPatrolFindings,
    resolveFinding: vi.fn(async (_id: string) => true),
    reopenFinding: vi.fn(async (_id: string) => true),
    copyToClipboard: vi.fn(async (_text: string) => true),
  };
});

vi.mock('@/utils/clipboard', () => ({
  copyToClipboard: (text: string) => mockState.copyToClipboard(text),
}));

vi.mock('@solidjs/router', () => ({
  A: (props: { href: string; children?: JSX.Element; [key: string]: unknown }) => (
    <a href={props.href} aria-label={props['aria-label'] as string} onClick={props.onClick as any}>
      {props.children}
    </a>
  ),
  useLocation: () => ({ hash: '' }),
}));

vi.mock('@/components/shared/Card', () => ({
  Card: (props: { children?: JSX.Element }) => <div>{props.children}</div>,
}));

vi.mock('@/components/patrol', () => ({
  InvestigationSection: () => null,
  ApprovalSection: () => null,
}));

vi.mock('@/stores/notifications', () => ({
  notificationStore: {
    success: vi.fn(),
    error: vi.fn(),
  },
}));

vi.mock('@/hooks/useResources', () => ({
  useResources: () => ({
    get: mockState.getResource,
  }),
}));

vi.mock('@/stores/aiIntelligence', () => ({
  aiIntelligenceStore: {
    get findings() {
      return mockState.findings;
    },
    get findingsLoading() {
      return mockState.findingsLoading;
    },
    get findingsError() {
      return mockState.findingsError;
    },
    get patrolFindings() {
      return mockState.patrolFindings;
    },
    get patrolFindingsLoading() {
      return mockState.patrolFindingsLoading;
    },
    get patrolFindingsError() {
      return mockState.patrolFindingsError;
    },
    get findingsNeedingAttention() {
      return [];
    },
    get patrolFindingsNeedingAttention() {
      return mockState.patrolFindings.filter((finding) =>
        mockState.attentionFindingIds.includes(finding.id as string),
      );
    },
    get findingsWithPendingApprovals() {
      return [];
    },
    get patrolFindingsWithPendingApprovals() {
      return mockState.patrolFindings.filter((finding) =>
        mockState.approvalFindingIds.includes(finding.id as string),
      );
    },
    get needsAttentionCount() {
      return 0;
    },
    get patrolNeedsAttentionCount() {
      return 0;
    },
    get pendingApprovalCount() {
      return 0;
    },
    get patrolPendingApprovalCount() {
      return 0;
    },
    get patrolPendingApprovals() {
      return mockState.patrolPendingApprovals;
    },
    findingsSignal: () => mockState.findings,
    patrolFindingsSignal: () => mockState.patrolFindings,
    loadFindings: mockState.loadFindings,
    loadPatrolFindings: mockState.loadPatrolFindings,
    resolveFinding: (id: string) => mockState.resolveFinding(id),
    reopenFinding: (id: string) => mockState.reopenFinding(id),
  },
}));

describe('FindingsPanel resource links', () => {
  it('keeps an alert-mirrored finding selected in the shared Patrol review panel', async () => {
    const title = 'Disk pressure with unknown cause';
    mockState.patrolFindings = [
      {
        ...mockState.initialPatrolFindings[0],
        id: 'mirrored-finding',
        title,
        mirrorsAlertId: 'alert-1',
        mirrorsAlertType: 'disk',
        description: 'The disk is full. Its cause remains unknown.',
        investigationStatus: 'completed',
        investigationOutcome: 'needs_attention',
      },
    ];
    render(() => <FindingsPanel findingsSource="patrol" />);
    fireEvent.click(screen.getByText('1 finding mirrors an active alert'));
    const review = screen.getByRole('button', { name: `Review issue for ${title}` });
    fireEvent.click(review);
    const panel = await screen.findByRole('complementary', { name: `Review ${title}` });
    expect(panel).toHaveTextContent('The disk is full. Its cause remains unknown.');
    expect(screen.getByRole('button', { name: `Close review for ${title}` })).toHaveAttribute(
      'aria-expanded',
      'true',
    );
    fireEvent.click(screen.getByRole('button', { name: `Close review panel for ${title}` }));
    await waitFor(() =>
      expect(screen.queryByRole('complementary', { name: `Review ${title}` })).toBeNull(),
    );
    expect(screen.getByRole('button', { name: `Review issue for ${title}` })).toHaveAttribute(
      'aria-expanded',
      'false',
    );
  });

  const expectCollapsedFinding = (title: string) => {
    expect(screen.getByRole('button', { name: `Review issue for ${title}` })).toBeInTheDocument();
  };

  beforeEach(() => {
    mockState.findings = [...mockState.initialFindings];
    mockState.patrolFindings = [...mockState.initialPatrolFindings];
    mockState.loadFindings.mockClear();
    mockState.loadPatrolFindings.mockClear();
    mockState.getResource.mockClear();
    mockState.resolveFinding.mockClear().mockResolvedValue(true);
    mockState.reopenFinding.mockClear().mockResolvedValue(true);
    mockState.copyToClipboard.mockClear().mockResolvedValue(true);
    vi.mocked(notificationStore.success).mockClear();
    vi.mocked(notificationStore.error).mockClear();
    mockState.findingsLoading = false;
    mockState.findingsError = null;
    mockState.patrolFindingsLoading = false;
    mockState.patrolFindingsError = null;
    mockState.patrolPendingApprovals = [];

    if (typeof window.requestAnimationFrame !== 'function') {
      window.requestAnimationFrame = ((callback: FrameRequestCallback) =>
        window.setTimeout(
          () => callback(performance.now()),
          0,
        )) as typeof window.requestAnimationFrame;
    }
  });

  it('renders the finding body without legacy surface cross-jump links', async () => {
    render(() => <FindingsPanel />);

    await waitFor(() => expect(mockState.loadFindings).toHaveBeenCalled());

    fireEvent.click(
      screen.getByRole('button', {
        name: 'View details for Nextcloud failed readiness checks',
      }),
    );

    expect(
      screen.getByText('Nextcloud is unreachable for users until readiness recovers.'),
    ).toBeInTheDocument();
    // Broad cross-jump chips into /infrastructure and aggregate workspaces
    // were retired with the platform-first migration;
    // Patrol findings now stay in place inside the panel.
    expect(
      screen.queryByRole('link', { name: 'Open related infrastructure for Nextcloud' }),
    ).toBeNull();
    expect(screen.queryByRole('link', { name: 'Open related workloads for Nextcloud' })).toBeNull();
  });

  it('keeps Patrol runtime setup findings primary-action-only when expanded', async () => {
    mockState.patrolFindings = [
      {
        id: 'finding-provider-runtime',
        source: 'ai-patrol',
        resourceId: 'ai-service',
        resourceName: 'Pulse Patrol Service',
        resourceType: 'service',
        alertIdentifier: 'ai-service::patrol/runtime',
        category: 'runtime',
        severity: 'warning',
        title: 'Pulse Patrol: Provider billing or quota issue',
        description: 'Pulse Patrol could not maintain a healthy provider connection.',
        impact: 'Patrol cannot analyze infrastructure until provider setup is fixed.',
        detectedAt: '2026-03-30T11:00:00Z',
        lastSeenAt: '2026-03-30T11:05:00Z',
        status: 'active',
      },
    ];

    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(screen.getByRole('link', { name: 'Check Patrol model' })).toHaveAttribute(
      'href',
      '/settings/pulse-intelligence/patrol',
    );

    fireEvent.click(
      screen.getByRole('button', {
        name: 'Review issue for Provider billing or quota issue',
      }),
    );

    expect(screen.getByRole('link', { name: 'Check Patrol model' })).toHaveAttribute(
      'href',
      '/settings/pulse-intelligence/patrol',
    );
    expect(screen.queryByRole('button', { name: 'Open in Assistant' })).not.toBeInTheDocument();
    expect(screen.queryByText('Manage')).not.toBeInTheDocument();
    expect(screen.queryByText('Resolve or dismiss')).not.toBeInTheDocument();
  });

  it('keeps finding disclosure separate from inline manual controls', async () => {
    render(() => <FindingsPanel />);

    await waitFor(() => expect(mockState.loadFindings).toHaveBeenCalled());

    const disclosure = screen.getByRole('button', {
      name: 'View details for Nextcloud failed readiness checks',
    });
    const acknowledge = screen.getByRole('button', { name: 'Acknowledge' });

    expect(disclosure).not.toContainElement(acknowledge);

    fireEvent.click(disclosure);

    expect(
      screen.getByText('Nextcloud is unreachable for users until readiness recovers.'),
    ).toBeInTheDocument();
  });

  it('keeps Patrol queue rows free of inline triage controls until expanded', async () => {
    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    const disclosure = screen.getByRole('button', {
      name: 'Review issue for Provider connection issue',
    });

    expect(
      screen.getAllByRole('button', {
        name: 'Review issue for Provider connection issue',
      }),
    ).toHaveLength(1);
    expect(disclosure).toHaveTextContent('Review');
    expect(screen.queryByRole('button', { name: 'Acknowledge' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Snooze 24h' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Dismiss' })).not.toBeInTheDocument();

    fireEvent.click(disclosure);

    expect(
      screen.getByRole('button', {
        name: 'Close review for Provider connection issue',
      }),
    ).toHaveTextContent('Close');
    expect(
      screen.getByRole('complementary', { name: 'Review Provider connection issue' }),
    ).toBeInTheDocument();
    expect(screen.getByText('Resolve or dismiss')).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Open in Assistant' })).toBeNull();
    expect(screen.getByRole('button', { name: 'Acknowledge' })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Snooze 24h' })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Dismiss: Later' })).toBeInTheDocument();
  });

  it('keeps default Patrol workflow states out of collapsed issue badges', async () => {
    mockState.patrolFindings = [
      {
        id: 'finding-default-workflow',
        source: 'ai-patrol',
        resourceId: 'vm-101',
        resourceName: 'database-01',
        resourceType: 'vm',
        category: 'reliability',
        severity: 'warning',
        title: 'Database latency spike',
        description: 'Patrol saw the database latency threshold trip.',
        impact: 'Database-backed apps may respond slowly.',
        detectedAt: '2026-03-30T11:00:00Z',
        lastSeenAt: '2026-03-30T11:05:00Z',
        status: 'active',
        loopState: 'detected',
      },
    ];

    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(screen.getByText('warning')).toBeInTheDocument();
    expectCollapsedFinding('Database latency spike');
    expect(screen.queryByText('detected')).not.toBeInTheDocument();
    expect(screen.queryByText('Review finding')).not.toBeInTheDocument();
  });

  it('keeps Patrol process states out of collapsed issue badges', async () => {
    mockState.patrolFindings = [
      {
        id: 'finding-investigating',
        source: 'ai-patrol',
        resourceId: 'vm-101',
        resourceName: 'database-01',
        resourceType: 'vm',
        category: 'reliability',
        severity: 'warning',
        title: 'Database latency spike',
        description: 'Patrol saw the database latency threshold trip.',
        impact: 'Database-backed apps may respond slowly.',
        detectedAt: '2026-03-30T11:00:00Z',
        lastSeenAt: '2026-03-30T11:05:00Z',
        status: 'active',
        loopState: 'investigating',
        investigationStatus: 'running',
      },
      {
        id: 'finding-verifying',
        source: 'ai-patrol',
        resourceId: 'vm-102',
        resourceName: 'web-01',
        resourceType: 'vm',
        category: 'availability',
        severity: 'warning',
        title: 'Web service restart loop',
        description: 'Patrol saw repeated restarts.',
        detectedAt: '2026-03-30T11:01:00Z',
        lastSeenAt: '2026-03-30T11:06:00Z',
        status: 'active',
        investigationOutcome: 'fix_executed',
      },
    ];

    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expectCollapsedFinding('Database latency spike');
    expectCollapsedFinding('Web service restart loop');
    expect(screen.queryByText('Patrol investigating')).not.toBeInTheDocument();
    expect(screen.queryByText('Verify outcome')).not.toBeInTheDocument();
    expect(screen.queryByText('Review finding')).not.toBeInTheDocument();
  });

  it('shows pending Patrol approval as the user decision, not as a process badge', async () => {
    mockState.patrolFindings = [
      {
        id: 'finding-approval',
        source: 'ai-patrol',
        resourceId: 'vm-103',
        resourceName: 'worker-01',
        resourceType: 'vm',
        category: 'availability',
        severity: 'critical',
        title: 'Worker disk is full',
        description: 'Patrol found the worker disk is full.',
        detectedAt: '2026-03-30T11:02:00Z',
        lastSeenAt: '2026-03-30T11:07:00Z',
        status: 'active',
        investigationOutcome: 'fix_queued',
      },
    ];
    mockState.patrolPendingApprovals = [
      {
        status: 'pending',
        toolId: 'investigation_fix',
        targetId: 'finding-approval',
        expiresAt: '2999-01-01T00:00:00Z',
      },
    ];

    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(screen.getByText('Approval required')).toBeInTheDocument();
    const approvalAction = screen.getByRole('button', {
      name: 'Review issue for Worker disk is full',
    });
    expect(screen.queryByText('Review finding')).not.toBeInTheDocument();

    fireEvent.click(approvalAction);

    expect(
      screen.getByRole('button', {
        name: 'Close review for Worker disk is full',
      }),
    ).toHaveTextContent('Close');
  });

  it('keeps selected Patrol run issue rows simple and expandable', async () => {
    mockState.patrolFindings = [
      {
        id: 'finding-array-parity',
        source: 'ai-patrol',
        resourceId: 'storage:tower-array',
        resourceName: 'Tower Array',
        resourceType: 'storage',
        category: 'availability',
        severity: 'critical',
        title: 'Unraid array running without parity protection while at 86% capacity',
        description:
          'The Unraid array on Tower is running without parity protection while capacity is high.',
        impact: 'A disk failure before parity is rebuilt could cause unrecoverable data loss.',
        recommendation:
          'Verify the parity check is progressing and let it complete before making array changes.',
        evidence:
          'Checked array status via Unraid API: parity_status=check, capacity=85.9%, disk2=95.8%.',
        detectedAt: '2026-03-30T11:00:00Z',
        lastSeenAt: '2026-03-30T11:05:00Z',
        status: 'active',
        loopState: 'detected',
      },
      {
        id: 'finding-array-usage',
        source: 'ai-patrol',
        resourceId: 'storage:tower-array',
        resourceName: 'Tower Array',
        resourceType: 'storage',
        category: 'capacity',
        severity: 'warning',
        title: 'Storage pool Tower Array at 85.9% usage',
        description: 'Tower Array is nearing the configured storage capacity threshold.',
        detectedAt: '2026-03-30T11:01:00Z',
        lastSeenAt: '2026-03-30T11:05:00Z',
        status: 'active',
        loopState: 'detected',
      },
    ];

    render(() => (
      <FindingsPanel
        findingsSource="patrol"
        filterOverride="all"
        filterFindingIds={['finding-array-parity', 'finding-array-usage']}
        runSnapshot={{
          resources_checked: 72,
          scope_resource_ids: [],
          effective_scope_resource_ids: [],
          finding_ids: ['finding-array-parity', 'finding-array-usage'],
          status: 'critical',
          error_count: 0,
        }}
      />
    ));

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(screen.getByText('critical')).toBeInTheDocument();
    expect(screen.getByText('warning')).toBeInTheDocument();
    expectCollapsedFinding('Unraid array running without parity protection while at 86% capacity');
    expectCollapsedFinding('Storage pool Tower Array at 85.9% usage');
    expect(screen.queryByText('detected')).not.toBeInTheDocument();
    expect(screen.queryByText('Review finding')).not.toBeInTheDocument();

    const disclosure = screen.getByRole('button', {
      name: 'Review issue for Unraid array running without parity protection while at 86% capacity',
    });
    expect(disclosure).toHaveAttribute('aria-expanded', 'false');

    fireEvent.click(disclosure);

    expect(
      screen.getByRole('button', {
        name: 'Close review for Unraid array running without parity protection while at 86% capacity',
      }),
    ).toHaveAttribute('aria-expanded', 'true');
    expect(
      screen.getByText(
        'The Unraid array on Tower is running without parity protection while capacity is high.',
      ),
    ).toBeInTheDocument();
    expect(
      screen.getAllByText(
        'Verify the parity check is progressing and let it complete before making array changes.',
      ),
    ).toHaveLength(1);
    expect(screen.getByText('Recommended next step:')).toBeInTheDocument();
    expect(screen.getByText('What Pulse checked:')).toBeInTheDocument();
    expect(
      screen.getAllByText(
        'Checked array status via Unraid API: parity_status=check, capacity=85.9%, disk2=95.8%.',
      ),
    ).toHaveLength(1);
  });

  it('can render Patrol findings from the direct Patrol source', async () => {
    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(mockState.loadFindings).not.toHaveBeenCalled();
    expectCollapsedFinding('Provider connection issue');
  });

  it('toggles durable finding outcomes directly from an active Patrol row', async () => {
    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    const options = screen.getByRole('button', {
      name: 'Finding options for Provider connection issue',
    });
    expect(options).toHaveAttribute('aria-expanded', 'false');

    fireEvent.click(options);

    expect(options).toHaveAttribute('aria-expanded', 'true');
    expect(screen.getByText('Resolve or dismiss')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Dismiss: Not an issue' })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Remember as expected' })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Dismiss: Later' })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Create rule from this' })).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Create rule from this' }));
    expect(
      screen.getByRole('textbox', { name: 'Reason for suppression rule' }),
    ).toBeInTheDocument();
    expect(screen.getByRole('link', { name: 'Manage suppression rules' })).toHaveAttribute(
      'href',
      '/patrol/activity#patrol-suppression-rules',
    );
    expect(
      screen.getByText(/Reopen finding only undoes an individual dismissal/),
    ).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: /^Cancel$/ }));

    fireEvent.click(options);
    expect(options).toHaveAttribute('aria-expanded', 'false');
    expect(
      screen.queryByRole('complementary', { name: 'Review Provider connection issue' }),
    ).not.toBeInTheDocument();

    fireEvent.click(options);
    fireEvent.click(
      screen.getByRole('button', { name: 'Close review panel for Provider connection issue' }),
    );
    expect(options).toHaveAttribute('aria-expanded', 'false');
  });

  it('renders Patrol findings while the unified findings request is still loading', async () => {
    mockState.findingsLoading = true;
    mockState.patrolFindingsLoading = false;

    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(screen.queryByText('Loading findings...')).not.toBeInTheDocument();
    expectCollapsedFinding('Provider connection issue');
  });

  it('keeps loaded Patrol findings visible during a Patrol refresh', async () => {
    mockState.patrolFindingsLoading = true;

    render(() => <FindingsPanel findingsSource="patrol" />);

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(screen.queryByText('Loading findings...')).not.toBeInTheDocument();
    expectCollapsedFinding('Provider connection issue');
  });

  it('renders a selected Patrol run empty snapshot while Patrol findings are loading', async () => {
    mockState.patrolFindings = [];
    mockState.patrolFindingsLoading = true;

    render(() => (
      <FindingsPanel
        findingsSource="patrol"
        filterOverride="all"
        filterFindingIds={[]}
        runSnapshot={{
          resources_checked: 67,
          scope_resource_ids: ['node-a'],
          effective_scope_resource_ids: ['node-a'],
          finding_ids: [],
          status: 'error',
          error_count: 1,
        }}
      />
    ));

    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());

    expect(screen.queryByText('Loading findings...')).not.toBeInTheDocument();
    expect(screen.getByText('No findings recorded for this run')).toBeInTheDocument();
    expect(
      screen.getByText(
        'Checked 67 scoped resources. This run recorded no Patrol findings, but it ended with issues requiring review.',
      ),
    ).toBeInTheDocument();
  });

  describe('expanded finding detail and actions', () => {
    const providerIssue = () => mockState.initialPatrolFindings[0];
    const providerTitle = 'Provider connection issue';
    const expandRow = () =>
      fireEvent.click(screen.getByRole('button', { name: `Review issue for ${providerTitle}` }));

    const renderPatrol = async (props: Record<string, unknown> = {}) => {
      const view = render(() => <FindingsPanel findingsSource="patrol" {...props} />);
      await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
      return view;
    };
    const openOptions = async (props: Record<string, unknown> = {}) => {
      const view = await renderPatrol(props);
      fireEvent.click(screen.getByRole('button', { name: `Finding options for ${providerTitle}` }));
      return view;
    };

    it('shows the consequence, evidence, last fix and fill-up forecast in the expanded issue', async () => {
      mockState.patrolFindings = [
        {
          ...providerIssue(),
          key: 'apt-host-updates',
          impact: 'Writes fail once the pool is full.',
          evidence:
            'pending_updates=3 inventory=abc123 checked_at=2026-04-01T10:00:00Z received_at=2026-04-01T10:01:00Z reboot_required=false',
          previousResolvedFixSummary: 'Pruned old snapshots.',
          capacityForecast: { current_pct: 86, daily_change: 1.2, days_to_full: 5 },
        },
      ];
      await renderPatrol();
      expandRow();

      const panel = within(
        await screen.findByRole('complementary', { name: `Review ${providerTitle}` }),
      );
      expect(panel.getByText('Impact:').parentElement).toHaveTextContent(
        'Writes fail once the pool is full.',
      );
      const checked = panel.getByText('What Pulse checked:').parentElement;
      expect(checked).toHaveTextContent('3 operating system updates were pending');
      expect(checked).not.toHaveTextContent('inventory=');
      expect(panel.getByText('Last time this resolved:').parentElement).toHaveTextContent(
        'Pruned old snapshots.',
      );
      expect(panel.getByText('Filling up').parentElement).toHaveTextContent(
        '5 days to full at +1.2%/day · 86% used',
      );
      expect(panel.queryByText('Recommendation:')).not.toBeInTheDocument();
    });

    it('offers the plan-locked Pro handoff in the expanded issue', async () => {
      await renderPatrol({
        patrolProHandoff: () => ({ detail: 'Investigating fixes needs Pulse Pro.' }),
      });
      expandRow();

      expect(screen.getByText('Investigating fixes needs Pulse Pro.')).toBeInTheDocument();
    });

    it('puts confidence and regression count on a collapsed row only when they apply', async () => {
      mockState.findings = [
        {
          ...mockState.initialFindings[0],
          id: 'regressed',
          title: 'Regressed finding',
          investigationRecord: { confidence: 'high' },
          regressionCount: 2,
        },
        {
          ...mockState.initialFindings[0],
          id: 'fresh',
          title: 'Fresh finding',
          regressionCount: 0,
        },
      ] as unknown as typeof mockState.findings;
      render(() => <FindingsPanel />);
      await waitFor(() => expect(mockState.loadFindings).toHaveBeenCalled());

      expect(screen.getAllByText('high confidence')).toHaveLength(1);
      expect(screen.getAllByText('regressed 2×')).toHaveLength(1);
      expect(screen.queryByText(/regressed 0/)).not.toBeInTheDocument();
    });

    it('opens and closes a finding with Enter and Space', async () => {
      render(() => <FindingsPanel />);
      await waitFor(() => expect(mockState.loadFindings).toHaveBeenCalled());
      const impact = 'Nextcloud is unreachable for users until readiness recovers.';

      const title = 'Nextcloud failed readiness checks';
      fireEvent.keyDown(screen.getByRole('button', { name: `Open issue details for ${title}` }), {
        key: 'Enter',
      });
      expect(screen.getByText(impact)).toBeInTheDocument();

      fireEvent.keyDown(screen.getByRole('button', { name: `Close issue details for ${title}` }), {
        key: ' ',
      });
      expect(screen.queryByText(impact)).not.toBeInTheDocument();

      fireEvent.click(screen.getByRole('button', { name: `Open issue details for ${title}` }));
      expect(screen.getByText(impact)).toBeInTheDocument();
    });

    it('marks an active finding resolved through the store and says so', async () => {
      await openOptions();
      expect(screen.queryByRole('button', { name: 'Reopen finding' })).not.toBeInTheDocument();

      fireEvent.click(screen.getByRole('button', { name: 'Mark resolved' }));

      await waitFor(() =>
        expect(mockState.resolveFinding).toHaveBeenCalledWith('finding-provider-issue'),
      );
      await waitFor(() =>
        expect(notificationStore.success).toHaveBeenCalledWith('Finding marked resolved'),
      );
    });

    it('lets an operator reopen a dismissed finding', async () => {
      mockState.patrolFindings = [
        { ...providerIssue(), status: 'dismissed', dismissedReason: 'not_an_issue' },
      ];
      await renderPatrol({ filterOverride: 'all' });
      expandRow();
      expect(screen.queryByRole('button', { name: 'Mark resolved' })).not.toBeInTheDocument();

      fireEvent.click(screen.getByRole('button', { name: 'Reopen finding' }));

      await waitFor(() =>
        expect(mockState.reopenFinding).toHaveBeenCalledWith('finding-provider-issue'),
      );
      await waitFor(() =>
        expect(notificationStore.success).toHaveBeenCalledWith('Finding reopened'),
      );
    });

    it('attributes a dismissal made by an operator-set state to its cause', async () => {
      mockState.patrolFindings = [
        {
          ...providerIssue(),
          status: 'dismissed',
          dismissedReason: 'expected_behavior',
          lifecycle: [
            {
              at: '2026-04-03T00:00:00Z',
              type: 'dismissed',
              metadata: { operator_state_cause: 'maintenance_window' },
            },
          ],
        },
        {
          ...providerIssue(),
          id: 'manual-dismissal',
          title: 'Manually dismissed issue',
          status: 'dismissed',
          dismissedReason: 'expected_behavior',
          lifecycle: [
            { at: '2026-04-03T00:00:00Z', type: 'dismissed', metadata: { reason: 'expected' } },
          ],
        },
      ];
      await renderPatrol({ filterOverride: 'all' });

      const badges = screen.getAllByTitle(
        'Auto-suppressed by Pulse based on operator-set state for this resource.',
      );
      expect(badges).toHaveLength(1);
      expect(badges[0]).toHaveTextContent('auto: maintenance');
    });

    it('copies a finding summary and says whether it worked', async () => {
      await openOptions();

      fireEvent.click(screen.getByRole('button', { name: 'Copy summary' }));
      await waitFor(() => expect(mockState.copyToClipboard).toHaveBeenCalledTimes(1));
      expect(mockState.copyToClipboard.mock.calls[0][0]).toContain(providerTitle);
      await waitFor(() =>
        expect(notificationStore.success).toHaveBeenCalledWith('Finding summary copied'),
      );

      mockState.copyToClipboard.mockResolvedValueOnce(false);
      fireEvent.click(screen.getByRole('button', { name: 'Copy summary' }));
      await waitFor(() =>
        expect(notificationStore.error).toHaveBeenCalledWith('Could not copy finding summary'),
      );
    });

    it('will not offer a suppression rule for a finding with no concrete category', async () => {
      mockState.patrolFindings = [{ ...providerIssue(), category: '' }];
      await openOptions();

      const createRule = screen.getByRole('button', { name: 'Create rule from this' });
      expect(createRule).toBeDisabled();
      expect(createRule).toHaveAttribute(
        'title',
        'This finding is missing the resource or category needed for a scoped rule',
      );
    });

    it('tells the operator what each dismissal will do before they confirm', async () => {
      mockState.patrolFindings = [{ ...providerIssue(), regressionCount: 2 }];
      await openOptions();

      fireEvent.click(screen.getByRole('button', { name: 'Dismiss: Later' }));
      expect(screen.getByText(/Pulse will stay quiet on this for 7 days/)).toBeInTheDocument();
      expect(screen.queryByText(/this finding has regressed/)).not.toBeInTheDocument();

      fireEvent.click(screen.getByRole('button', { name: 'Remember as expected' }));
      expect(
        screen.getByText(/Pulse will keep this finding visible as acknowledged/),
      ).toBeInTheDocument();
      expect(screen.getByText(/this finding has regressed 2 times before/)).toBeInTheDocument();

      fireEvent.click(screen.getByRole('button', { name: 'Dismiss: Not an issue' }));
      expect(screen.getByText(/Pulse will permanently suppress/)).toBeInTheDocument();
      expect(screen.getByText(/this finding has regressed 2 times before/)).toBeInTheDocument();
    });

    // Pulse mirrors the backend's seven-day default, so the confirmation names the
    // date the finding comes back before the operator commits to it.
    it('names the date a will-fix-later dismissal comes back, seven days out', async () => {
      vi.useFakeTimers({ toFake: ['Date'] });
      vi.setSystemTime(new Date('2026-04-01T12:00:00Z'));
      try {
        await openOptions();
        fireEvent.click(screen.getByRole('button', { name: 'Dismiss: Later' }));

        const comesBack = new Date('2026-04-08T12:00:00Z').toLocaleDateString(undefined, {
          weekday: 'short',
          month: 'short',
          day: 'numeric',
        });
        const notice = screen.getByText(/Pulse will stay quiet on this for 7 days/);
        expect(notice).toHaveTextContent(
          `surface it again on ${comesBack} if it is still happening`,
        );
      } finally {
        vi.useRealTimers();
      }
    });

    it('does not warn about recurrence for a finding that has regressed only once', async () => {
      mockState.patrolFindings = [{ ...providerIssue(), regressionCount: 1 }];
      await openOptions();

      fireEvent.click(screen.getByRole('button', { name: 'Dismiss: Not an issue' }));

      expect(screen.getByText(/Pulse will permanently suppress/)).toBeInTheDocument();
      expect(screen.queryByText(/this finding has regressed/)).not.toBeInTheDocument();
    });

    it('keeps raw lifecycle history out of an active issue until history is asked for', async () => {
      mockState.patrolFindings = [
        {
          ...providerIssue(),
          lifecycle: [{ at: '2026-03-30T11:00:00Z', type: 'detected', message: 'Detected' }],
        },
      ];
      const first = await renderPatrol();
      expandRow();
      await screen.findByRole('complementary', { name: `Review ${providerTitle}` });
      expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
      first.unmount();

      await renderPatrol({ filterOverride: 'all' });
      expandRow();
      expect(await screen.findByText('Lifecycle')).toBeInTheDocument();
    });

    // Every other way into an issue keeps its history: a finding from the
    // general findings source, one that is no longer active, a Patrol run record,
    // and the resolved list.
    describe('lifecycle history stays visible where it is the point', () => {
      const lifecycle = [{ at: '2026-03-30T11:00:00Z', type: 'detected', message: 'Detected' }];

      it('shows it on a finding from the general findings source', async () => {
        mockState.findings = [
          { ...mockState.initialFindings[0], lifecycle },
        ] as unknown as typeof mockState.findings;
        render(() => <FindingsPanel />);
        await waitFor(() => expect(mockState.loadFindings).toHaveBeenCalled());

        fireEvent.click(
          screen.getByRole('button', {
            name: 'View details for Nextcloud failed readiness checks',
          }),
        );

        expect(await screen.findByText('Lifecycle')).toBeInTheDocument();
      });

      it('shows it on a Patrol finding that is no longer active', async () => {
        mockState.patrolFindings = [{ ...providerIssue(), status: 'dismissed', lifecycle }];
        mockState.attentionFindingIds = ['finding-provider-issue'];
        try {
          await renderPatrol({ filterOverride: 'attention' });
          expandRow();

          expect(await screen.findByText('Lifecycle')).toBeInTheDocument();
        } finally {
          mockState.attentionFindingIds = [];
        }
      });

      it('shows it on an active finding opened from a Patrol run record', async () => {
        mockState.patrolFindings = [{ ...providerIssue(), lifecycle }];
        await renderPatrol({
          filterFindingIds: ['finding-provider-issue'],
          runSnapshot: {
            resources_checked: 3,
            scope_resource_ids: [],
            effective_scope_resource_ids: [],
            finding_ids: ['finding-provider-issue'],
            status: 'critical',
            error_count: 0,
          },
        });
        expandRow();

        expect(await screen.findByText('Lifecycle')).toBeInTheDocument();
      });

      it('shows it in the resolved list', async () => {
        mockState.patrolFindings = [{ ...providerIssue(), status: 'resolved', lifecycle }];
        await renderPatrol({ filterOverride: 'resolved' });
        expandRow();

        expect(await screen.findByText('Lifecycle')).toBeInTheDocument();
      });
    });
  });
});

describe('FindingsPanel investigate action gating', () => {
  beforeEach(() => {
    mockState.patrolFindings = [
      {
        id: 'finding-provider-issue',
        source: 'ai-patrol',
        resourceId: 'instance:node:100',
        resourceName: 'vm-100',
        resourceType: 'vm',
        alertIdentifier: 'instance:node:100::patrol/provider',
        category: 'reliability',
        severity: 'warning',
        title: 'Provider connection issue',
        description: 'Pulse Patrol could not complete provider analysis.',
        impact: 'Patrol cannot analyze infrastructure until provider setup is fixed.',
        detectedAt: '2026-03-30T11:00:00Z',
        lastSeenAt: '2026-03-30T11:05:00Z',
        status: 'active',
      },
    ];
  });

  const expandRow = () =>
    fireEvent.click(
      screen.getByRole('button', { name: 'Review issue for Provider connection issue' }),
    );

  it('shows an Investigate action above Watch-only mode on an un-investigated patrol finding', async () => {
    render(() => <FindingsPanel findingsSource="patrol" autonomyLevel="approval" />);
    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
    expandRow();
    expect(screen.getByRole('button', { name: /Investigate/ })).toBeInTheDocument();
  });

  it('hides the Investigate action in Watch-only (monitor) mode', async () => {
    render(() => <FindingsPanel findingsSource="patrol" autonomyLevel="monitor" />);
    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
    expandRow();
    expect(screen.queryByRole('button', { name: /^Investigate$/ })).toBeNull();
  });

  it('renders the Watch-only mode nudge in the expanded row and fires its switch callback', async () => {
    const onSwitch = vi.fn();
    render(() => (
      <FindingsPanel
        findingsSource="patrol"
        autonomyLevel="monitor"
        patrolModeNudge={() => ({
          detail:
            'Watch only reports issues without preparing fixes. In Ask first mode, Patrol investigates and queues each fix for your approval.',
          actionLabel: 'Switch to Ask first',
        })}
        onPatrolModeNudgeAction={onSwitch}
      />
    ));
    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
    expandRow();
    const switchButton = screen.getByRole('button', { name: 'Switch to Ask first' });
    expect(
      screen.getByText(
        'Watch only reports issues without preparing fixes. In Ask first mode, Patrol investigates and queues each fix for your approval.',
      ),
    ).toBeInTheDocument();
    fireEvent.click(switchButton);
    expect(onSwitch).toHaveBeenCalledTimes(1);
  });

  it('disables the Watch-only mode nudge button while the switch is in flight', async () => {
    render(() => (
      <FindingsPanel
        findingsSource="patrol"
        autonomyLevel="monitor"
        patrolModeNudge={() => ({
          detail: 'Watch only reports issues without preparing fixes.',
          actionLabel: 'Switch to Ask first',
        })}
        patrolModeNudgeBusy
      />
    ));
    await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
    expandRow();
    const busyButton = screen.getByRole('button', { name: 'Switching…' });
    expect(busyButton).toBeDisabled();
  });
});

describe('FindingsPanel future times', () => {
  const hour = 60 * 60 * 1000;

  beforeEach(() => {
    mockState.findings = [...mockState.initialFindings];
    mockState.loadPatrolFindings.mockClear();
    mockState.findingsLoading = false;
    mockState.findingsError = null;
    mockState.patrolFindingsLoading = false;
    mockState.patrolFindingsError = null;
    mockState.patrolPendingApprovals = [];
  });

  it('counts reminders and snoozes down on the shared clock instead of reading just now', () => {
    vi.useFakeTimers({
      toFake: ['Date', 'setInterval', 'clearInterval'],
      now: Date.parse('2026-03-30T12:00:00Z'),
    });
    mockState.patrolFindings = [
      {
        ...mockState.initialPatrolFindings[0],
        id: 'finding-later',
        title: 'Backup job keeps slipping',
        status: 'dismissed',
        dismissedReason: 'will_fix_later',
        remindAt: '2026-04-06T12:00:00Z',
      },
      {
        ...mockState.initialPatrolFindings[0],
        id: 'finding-snoozed',
        title: 'Swap pressure on vm-100',
        status: 'snoozed',
        snoozedUntil: '2026-03-30T15:00:00Z',
      },
    ];

    try {
      render(() => <FindingsPanel findingsSource="patrol" filterOverride="resolved" />);

      const reminder = screen.getByText(/Reminding in 7d/);
      const snooze = screen.getByText(/snoozed, returns in 3h/);
      expect(reminder).toHaveAttribute(
        'title',
        expect.stringMatching(
          /^Reminder due .+\. Pulse brings this finding back on its first reminder check after that\.$/,
        ),
      );
      expect(snooze).toHaveAttribute('title', expect.stringMatching(/^Snoozed until /));
      expect(screen.queryByText(/just now/)).not.toBeInTheDocument();
      expect(screen.queryByRole('button', { name: /Overdue commitments/ })).not.toBeInTheDocument();

      // The findings are not re-read: only the shared clock moves.
      vi.advanceTimersByTime(2 * hour);
      expect(snooze).toHaveTextContent('snoozed, returns in 1h');

      vi.advanceTimersByTime(hour);
      expect(snooze).toHaveTextContent('snooze ended');

      vi.setSystemTime(Date.parse('2026-04-06T12:30:00Z'));
      vi.advanceTimersByTime(RELATIVE_TIME_TICK_MS);
      expect(reminder).toHaveTextContent('Reminder overdue');
      // The Overdue commitments chip reads the same clock as the label, with no
      // findings re-read.
      expect(screen.getByRole('button', { name: /Overdue commitments \(1\)/ })).toBeInTheDocument();
      expect(reminder).toHaveAttribute('title', expect.stringMatching(/^Reminder was due /));
    } finally {
      vi.useRealTimers();
    }
  });

  it('keeps overdue rows mounted across clock ticks and adds a reminder once it falls due', () => {
    vi.useFakeTimers({
      toFake: ['Date', 'setInterval', 'clearInterval'],
      now: Date.parse('2026-03-30T12:00:00Z'),
    });
    mockState.patrolFindings = [
      {
        ...mockState.initialPatrolFindings[0],
        id: 'finding-overdue',
        title: 'Certificate renewal keeps slipping',
        status: 'dismissed',
        dismissedReason: 'will_fix_later',
        remindAt: '2026-03-30T11:00:00Z',
      },
      {
        ...mockState.initialPatrolFindings[0],
        id: 'finding-due-soon',
        title: 'Backup job keeps slipping',
        status: 'dismissed',
        dismissedReason: 'will_fix_later',
        remindAt: '2026-03-30T12:10:00Z',
      },
    ];

    try {
      render(() => <FindingsPanel findingsSource="patrol" filterOverride="resolved" />);
      fireEvent.click(screen.getByRole('button', { name: /Overdue commitments \(1\)/ }));

      const review = screen.getByRole('button', {
        name: 'Review issue for Certificate renewal keeps slipping',
      });
      review.focus();
      expect(screen.queryByText('Backup job keeps slipping')).not.toBeInTheDocument();

      // A tick that moves no deadline past now leaves the rows alone.
      vi.advanceTimersByTime(RELATIVE_TIME_TICK_MS);
      expect(review.isConnected).toBe(true);
      expect(document.activeElement).toBe(review);

      // Once the second reminder falls due it joins the open Overdue filter
      // and the chip count, on the same clock as the row labels.
      vi.advanceTimersByTime(10 * 60 * 1000);
      expect(screen.getByText('Backup job keeps slipping')).toBeInTheDocument();
      expect(screen.getByRole('button', { name: /Overdue commitments \(2\)/ })).toBeInTheDocument();
    } finally {
      vi.useRealTimers();
    }
  });

  it('calls a reminder overdue only once the Overdue commitments list holds it', () => {
    vi.useFakeTimers({
      toFake: ['Date', 'setInterval', 'clearInterval'],
      now: Date.parse('2026-03-30T12:00:00Z'),
    });
    mockState.patrolFindings = [
      {
        ...mockState.initialPatrolFindings[0],
        id: 'finding-due',
        title: 'Certificate renewal keeps slipping',
        status: 'dismissed',
        dismissedReason: 'will_fix_later',
        remindAt: '2026-03-30T12:00:05Z',
      },
    ];
    const [filter, setFilter] = createSignal<'active' | 'resolved'>('active');

    try {
      render(() => <FindingsPanel findingsSource="patrol" filterOverride={filter()} />);
      expect(screen.queryByText('Certificate renewal keeps slipping')).not.toBeInTheDocument();

      // The deadline passes between ticks of the shared clock, and the row
      // first mounts before the next tick: it must not call itself overdue
      // while the chip and filter do not count it.
      vi.setSystemTime(Date.parse('2026-03-30T12:00:10Z'));
      setFilter('resolved');
      expect(screen.getByText('Certificate renewal keeps slipping')).toBeInTheDocument();
      expect(screen.getByText(/Reminder due/)).toBeInTheDocument();
      expect(screen.queryByText(/Reminder overdue/)).not.toBeInTheDocument();
      expect(screen.queryByRole('button', { name: /Overdue commitments/ })).not.toBeInTheDocument();

      // The next tick moves the label, the chip and the filter together.
      vi.advanceTimersByTime(RELATIVE_TIME_TICK_MS);
      expect(screen.getByText(/Reminder overdue/)).toBeInTheDocument();
      expect(screen.getByRole('button', { name: /Overdue commitments \(1\)/ })).toBeInTheDocument();
    } finally {
      vi.useRealTimers();
    }
  });
});

describe('FindingsPanel resource scope', () => {
  const finding = (
    id: string,
    title: string,
    resource: { resourceId: string; resourceName: string },
    extra: Record<string, unknown> = {},
  ) => ({ ...mockState.initialPatrolFindings[0], id, title, ...resource, ...extra });
  const web = { resourceId: 'docker:host-1/web', resourceName: 'afs-web' };
  const db = { resourceId: 'vm-db', resourceName: 'db-01' };
  const overdue = {
    status: 'dismissed',
    dismissedReason: 'will_fix_later',
    remindAt: '2026-01-01T00:00:00Z',
  };
  const reviewButtons = () =>
    screen
      .getAllByRole('button', { name: /^Review issue for / })
      .map((button) => button.getAttribute('aria-label') ?? button.textContent);

  beforeEach(() => {
    mockState.patrolFindingsLoading = false;
    mockState.patrolFindingsError = null;
    mockState.patrolPendingApprovals = [];
    mockState.patrolFindings = [
      finding('web-disk', 'Web disk is filling', web),
      finding('web-restart', 'Web container keeps restarting', web),
      finding('web-later', 'Web certificate renewal slipping', web, overdue),
      finding('db-backup', 'Database backup is stale', db),
      finding('db-later', 'Database patching slipping', db, overdue),
    ];
    mockState.attentionFindingIds = ['web-disk', 'web-restart', 'db-backup'];
    mockState.approvalFindingIds = ['web-restart', 'db-backup'];
  });

  afterEach(() => {
    mockState.attentionFindingIds = [];
    mockState.approvalFindingIds = [];
  });

  it("counts only the scoped resource's findings in the filter chips", () => {
    render(() => (
      <FindingsPanel
        findingsSource="patrol"
        resourceId="docker:host-1/web"
        filterOverride="active"
      />
    ));

    expect(reviewButtons()).toHaveLength(2);
    expect(screen.getByRole('button', { name: /^Needs Attention \(2\)$/ })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /^Overdue commitments \(1\)$/ })).toBeInTheDocument();

    // Each chip opens exactly the rows it counted.
    fireEvent.click(screen.getByRole('button', { name: /^Approvals \(1\)$/ }));
    expect(reviewButtons()).toEqual(['Review issue for Web container keeps restarting']);
    fireEvent.click(screen.getByRole('button', { name: /^Overdue commitments \(1\)$/ }));
    expect(reviewButtons()).toEqual(['Review issue for Web certificate renewal slipping']);
  });

  it('counts every finding when the panel is not scoped to a resource', () => {
    render(() => <FindingsPanel findingsSource="patrol" filterOverride="active" />);

    expect(screen.getByRole('button', { name: /^Needs Attention \(3\)$/ })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /^Approvals \(2\)$/ })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /^Overdue commitments \(2\)$/ })).toBeInTheDocument();
  });

  it('keeps the filter bar for a scoped resource with no findings', () => {
    render(() => (
      <FindingsPanel findingsSource="patrol" resourceId="vm-quiet" filterOverride="active" />
    ));

    expect(screen.queryAllByRole('button', { name: /^Review issue for / })).toHaveLength(0);
    // Resolved and All stay reachable; no chip counts another resource's work.
    for (const name of [/^Active$/, /^All$/, /^Resolved$/]) {
      expect(screen.getByRole('button', { name })).toBeInTheDocument();
    }
    expect(screen.queryByRole('button', { name: /^Needs Attention/ })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /^Approvals/ })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /^Overdue commitments/ })).not.toBeInTheDocument();
  });
});