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.

62.9 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest';
import {
  fireEvent,
  render as solidRender,
  screen,
  within,
  waitFor,
} from '@solidjs/testing-library';
import { createSignal, Suspense } from 'solid-js';
import { ChartsAPI, type AllMetricsHistoryResponse } from '@/api/charts';
import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';

import resourceDetailDrawerOverviewSource from '@/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx?raw';
import type { Resource } from '@/types/resource';
import { ResourceDetailDrawer } from '@/components/Infrastructure/ResourceDetailDrawer';

const render = (...args: Parameters<typeof solidRender>): ReturnType<typeof solidRender> => {
  const result = solidRender(...args);
  const details = result.container.querySelector<HTMLDetailsElement>(
    '[data-testid="resource-technical-details"]',
  );
  if (details) {
    details.open = true;
    fireEvent(details, new Event('toggle'));
  }
  const platformDetails = result.container.querySelector<HTMLDetailsElement>(
    '[data-testid="resource-platform-details"]',
  );
  if (platformDetails) {
    platformDetails.open = true;
    fireEvent(platformDetails, new Event('toggle'));
  }
  return result;
};

const facetBundleMock = vi.hoisted(() => ({
  getFacetBundle: vi.fn(),
}));

const aiIntelligenceMock = vi.hoisted(() => ({
  getResourceIntelligence: vi.fn().mockResolvedValue({
    resource_id: 'resource-1',
    health: {
      score: 92,
      grade: 'A',
      trend: 'stable',
      factors: [],
      prediction: 'Stable',
    },
    dependencies: ['storage-1'],
    dependents: ['vm-child'],
    correlations: [
      {
        source_id: 'storage-1',
        source_name: 'Storage 1',
        source_type: 'storage',
        target_id: 'resource-1',
        target_name: 'Host 1',
        target_type: 'vm',
        event_pattern: 'disk_full -> restart',
        occurrences: 2,
        avg_delay: 125000000000,
        confidence: 0.875,
        last_seen: '2026-03-01T00:15:00Z',
        description: 'Disk pressure often precedes restarts',
      },
    ],
    recent_changes: [],
    note_count: 3,
  }),
}));

const actionAuditMock = vi.hoisted(() => ({
  listActionAudits: vi.fn().mockResolvedValue({
    audits: [],
    count: 0,
    available: false,
  }),
}));

vi.mock('@/contexts/appRuntime', () => ({
  useWebSocket: () => ({
    activeAlerts: {},
    state: { pmg: [] as any[] },
    connected: () => true,
    initialDataReceived: () => true,
    reconnecting: () => false,
    reconnect: vi.fn(),
  }),
  useDarkMode: () => () => false,
}));

vi.mock('@/api/resources', () => ({
  ResourceAPI: {
    getFacetBundle: facetBundleMock.getFacetBundle,
  },
}));

vi.mock('@/api/ai', () => ({
  AIAPI: {
    getResourceIntelligence: aiIntelligenceMock.getResourceIntelligence,
  },
}));

vi.mock('@/api/actionAudit', () => ({
  ActionAuditAPI: {
    listActionAudits: actionAuditMock.listActionAudits,
  },
}));

// Stub the operator-state client so the drawer's
// ResourceOperatorStateSection does not fan out a real network call
// during this test. Returns no-state (null) by default — the resource
// has no operator overrides, which is the default posture.
vi.mock('@/api/resourceOperatorState', () => ({
  getResourceOperatorState: vi.fn().mockResolvedValue(null),
  setResourceOperatorState: vi.fn(),
  clearResourceOperatorState: vi.fn(),
}));

class ResizeObserverMock {
  constructor(_callback: ResizeObserverCallback) {}
  observe() {}
  unobserve() {}
  disconnect() {}
}

if (typeof globalThis.ResizeObserver === 'undefined') {
  vi.stubGlobal('ResizeObserver', ResizeObserverMock);
}

const baseResource = (overrides: Partial<Resource>): Resource => ({
  id: 'resource-1',
  type: 'agent',
  name: 'host-1',
  displayName: 'host-1',
  platformId: 'host-1',
  platformType: 'agent',
  sourceType: 'hybrid',
  status: 'online',
  lastSeen: Date.now(),
  platformData: { sources: ['agent'] },
  ...overrides,
});

describe('ResourceDetailDrawer change history section', () => {
  it('withdraws an open drawer live history reply on restart while preserving real stored history', async () => {
    resetCreateNonSuspendingQueryCacheForTest();
    const source = baseResource({
      id: 'restart-history',
      metricsTarget: { resourceType: 'agent', resourceId: 'restart-history' },
      sourceStatus: { agent: { status: 'online' } },
      cpu: { current: 12 },
    });
    const live: AllMetricsHistoryResponse = {
      resourceType: 'agent',
      resourceId: 'restart-history',
      range: '24h',
      start: 1_700_000_000_000,
      end: 1_700_000_060_000,
      source: 'live',
      metrics: { cpu: [{ timestamp: 1_700_000_060_000, value: 12, min: 12, max: 12 }] },
    };
    let resolveHistory!: (value: AllMetricsHistoryResponse) => void;
    const nextHistory = new Promise<AllMetricsHistoryResponse>((resolve) => {
      resolveHistory = resolve;
    });
    const read = vi
      .spyOn(ChartsAPI, 'getMetricsHistory')
      .mockResolvedValueOnce(live)
      .mockReturnValueOnce(nextHistory);
    const [resource, setResource] = createSignal(source);
    const view = render(() => <ResourceDetailDrawer resource={resource()} />);
    try {
      const history = view.container.querySelector('[data-testid="resource-metrics-history"]')!;
      await waitFor(() => expect(history).toHaveTextContent('Current'));
      setResource({
        ...source,
        status: 'unknown',
        sourceStatus: { agent: { status: 'pending' } },
        cpu: undefined,
      });
      await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
      expect(screen.getAllByText('Waiting for first report').length).toBeGreaterThan(0);
      expect(history).not.toHaveTextContent('Current');
      expect(history.querySelector('[data-history-current]')).toBeNull();
      resolveHistory({ ...live, source: 'store' });
      await waitFor(() => expect(history).toHaveTextContent('Latest stored'));
      expect(history).toHaveTextContent('12.0%');
      expect(history).not.toHaveTextContent('Current');
    } finally {
      view.unmount();
      read.mockRestore();
      resetCreateNonSuspendingQueryCacheForTest();
    }
  });

  it('keeps retained guest memory and paused filesystems out of current chart fallbacks', async () => {
    resetCreateNonSuspendingQueryCacheForTest();
    const source = baseResource({
      id: 'provenance-vm',
      type: 'vm',
      platformType: 'proxmox-pve',
      metricsTarget: { resourceType: 'vm', resourceId: 'fixture:pve:101' },
      memory: {
        current: 25,
        observation: {
          state: 'last-known',
          source: 'guest-agent-meminfo',
          observedAt: '2026-10-04T12:00:00Z',
        },
      },
      disk: { current: 50 },
      proxmox: { diskStatusReason: 'prev-vm-locked', backupInProgress: true },
    });
    const read = vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue({
      resourceType: 'vm',
      resourceId: 'fixture:pve:101',
      range: '24h',
      start: Date.parse('2026-10-04T12:00:00Z'),
      end: Date.parse('2026-10-05T00:00:00Z'),
      source: 'store',
      metrics: {},
    });
    const [resource, setResource] = createSignal(source);
    const view = render(() => (
      <ResourceDetailDrawer resource={resource()} presentation="table-row" />
    ));
    try {
      await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
      const chart = view.container.querySelector('[data-history-group="utilization"]')!;
      expect(chart.querySelector('[data-history-current="memory"]')).toBeNull();
      expect(chart.querySelector('[data-history-last-known="memory"]')).toHaveTextContent(
        '25.0%last known',
      );
      expect(chart.querySelector('[data-history-deferred="memory"]')).toHaveTextContent(
        '2026-10-04 12:00:00 UTC',
      );
      expect(chart.querySelector('[data-history-current="disk"]')).toBeNull();
      expect(chart.querySelector('[data-history-last-known="disk"]')).toHaveTextContent(
        '50.0%last known',
      );
      setResource({ ...source, lastSeen: Date.parse('2026-10-05T00:00:00Z') });
      expect(chart.querySelector('[data-history-deferred="memory"]')).not.toHaveTextContent(
        '2026-10-05',
      );
      setResource({
        ...source,
        memory: { current: 0, observation: { state: 'unavailable', source: 'status-mem' } },
        proxmox: { diskStatusReason: 'agent-busy' },
      });
      expect(chart.querySelector('[data-history-last-known]')).toBeNull();
      expect(chart).toHaveTextContent('Memory-');
      expect(chart).toHaveTextContent('Disk-');
      setResource({
        ...source,
        memory: {
          current: 0,
          observation: {
            state: 'current',
            source: 'status-mem',
            observedAt: '2026-10-04T13:00:00Z',
          },
        },
        proxmox: { diskStatusReason: '' },
      });
      expect(view.container.querySelector('[data-history-group="utilization"]')).toBe(chart);
      expect(chart.querySelector('[data-history-current="memory"]')).toHaveTextContent(
        '0.0%current',
      );
      expect(chart.querySelector('[data-history-current="disk"]')).toHaveTextContent(
        '50.0%current',
      );
      expect(chart.querySelector('[data-history-deferred]')).toBeNull();
      expect(chart.querySelector('path[data-history-series]')).toBeNull();
      expect(read).toHaveBeenCalledTimes(1);
    } finally {
      view.unmount();
      read.mockRestore();
      resetCreateNonSuspendingQueryCacheForTest();
    }
  });

  it('reactively withdraws stopped VM disk carriers without discarding the Overview charts or independent readings', async () => {
    resetCreateNonSuspendingQueryCacheForTest();
    const source = baseResource({
      id: 'native-power-vm',
      type: 'vm',
      platformType: 'proxmox-pve',
      metricsTarget: { resourceType: 'vm', resourceId: 'power:pve:101' },
      cpu: { current: 10 },
      memory: {
        current: 0,
        observation: { state: 'current', source: 'agent', observedAt: '2026-10-10T00:00:00Z' },
      },
      disk: { current: 90 },
      proxmox: { runtimeStatus: 'running' },
    });
    const read = vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue({
      resourceType: 'vm',
      resourceId: 'power:pve:101',
      range: '24h',
      start: Date.parse('2026-10-10T00:00:00Z'),
      end: Date.parse('2026-10-10T01:00:00Z'),
      source: 'store',
      metrics: {},
    });
    const [resource, setResource] = createSignal(source);
    const view = render(() => (
      <ResourceDetailDrawer resource={resource()} presentation="table-row" />
    ));
    try {
      await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
      const chart = view.container.querySelector('[data-history-group="utilization"]')!;
      expect(chart.querySelector('[data-history-current="disk"]')).toHaveTextContent(
        '90.0%current',
      );
      for (const diskStatusReason of ['', 'prev-agent-busy']) {
        setResource({
          ...source,
          lastSeen: source.lastSeen + 3600000,
          proxmox: { runtimeStatus: 'stopped', diskStatusReason },
        });
        expect(chart.querySelector('[data-history-current="disk"]')).toBeNull();
        expect(chart.querySelector('[data-history-last-known="disk"]')).toBeNull();
        expect(chart.querySelector('[data-history-deferred="disk"]')).toHaveTextContent(
          'Guest filesystem stats unavailable while the VM is stopped.',
        );
        expect(chart.querySelector('[data-history-current="memory"]')).toHaveTextContent(
          '0.0%current',
        );
        expect(chart.querySelector('[data-history-current="cpu"]')).toHaveTextContent(
          '10.0%current',
        );
      }
      setResource({ ...source, status: 'offline', disk: { current: 0 } });
      expect(chart.querySelector('[data-history-current="disk"]')).toHaveTextContent('0.0%current');
      expect(chart.querySelector('[data-history-deferred="disk"]')).toBeNull();
      expect(view.container.querySelector('[data-history-group="utilization"]')).toBe(chart);
      expect(chart.querySelector('path[data-history-series]')).toBeNull();
      expect(read).toHaveBeenCalledTimes(1);
      expect(screen.getByRole('tab', { name: 'Overview' })).toHaveAttribute(
        'aria-selected',
        'true',
      );
    } finally {
      view.unmount();
      read.mockRestore();
      resetCreateNonSuspendingQueryCacheForTest();
    }
  });

  it('keeps a PBS server CPU and qualified memory visible when its first history read fails', async () => {
    resetCreateNonSuspendingQueryCacheForTest();
    // The Backups page sends people here for PBS host figures, so a failed
    // history read must not take the server's own readings with it.
    const source = baseResource({
      id: 'pbs-history-down',
      type: 'pbs',
      name: 'pbs-main',
      displayName: 'PBS Main',
      platformId: 'pbs-main',
      platformType: 'proxmox-pbs',
      platformData: { sources: ['pbs'], pbs: { hostname: 'pbs-main.local' } },
      metricsTarget: { resourceType: 'agent', resourceId: 'pbs-main' },
      cpu: { current: 7 },
      memory: { current: 99, total: 8_000, used: 2_000 },
    });
    const read = vi
      .spyOn(ChartsAPI, 'getMetricsHistory')
      .mockRejectedValue(new Error('history store unavailable'));
    const [resource, setResource] = createSignal(source);
    const view = render(() => <ResourceDetailDrawer resource={resource()} />);
    try {
      const history = view.container.querySelector('[data-testid="resource-metrics-history"]')!;
      await waitFor(() => expect(history).toHaveTextContent('Failed to load history data'));
      expect(history.querySelector('[data-testid="guest-history-plot"]')).toBeNull();
      const readings = history.querySelector('[data-testid="guest-history-live-readings"]')!;
      expect(readings.querySelector('[data-live-reading="cpu"]')).toHaveTextContent(
        'CPU7.0%current',
      );
      // The byte pair is the measurement; the stale 99% selection is ignored.
      expect(readings.querySelector('[data-live-reading="memory"]')).toHaveTextContent(
        'Memory25.0%current',
      );

      setResource({ ...source, memory: { current: 99, total: 8_000, used: 0 } });
      expect(readings.querySelector('[data-live-reading="memory"]')).toHaveTextContent(
        'Memory0.0%current',
      );

      setResource({
        ...source,
        memory: {
          current: 40,
          observation: {
            state: 'last-known',
            source: 'status-mem',
            observedAt: '2026-10-04T12:00:00Z',
          },
        },
      });
      expect(readings.querySelector('[data-live-reading="memory"]')).toHaveTextContent(
        'Memory40.0%last known',
      );
      expect(readings.querySelector('[data-history-deferred="memory"]')).toHaveTextContent(
        '2026-10-04 12:00:00 UTC',
      );
      expect(readings.querySelector('[data-live-reading="cpu"]')).toHaveTextContent('7.0%current');
      expect(read).toHaveBeenCalled();
    } finally {
      view.unmount();
      read.mockRestore();
      resetCreateNonSuspendingQueryCacheForTest();
    }
  });

  it.each(['vm', 'system-container'] as const)(
    'keeps the mounted %s Overview charts on the selected filesystem producer',
    async (type) => {
      resetCreateNonSuspendingQueryCacheForTest();
      const disks = [{ mountpoint: '/', total: 100, used: 62, free: 38 }];
      const source = baseResource({
        id: 'linked-filesystem-guest',
        type,
        platformType: 'proxmox-pve',
        status: 'online',
        metricsTarget: { resourceType: type, resourceId: 'linked:pve:105' },
        cpu: { current: 10 },
        memory: {
          current: 0,
          observation: { state: 'current', source: 'agent', observedAt: '2026-10-12T00:00:00Z' },
        },
        disk: { current: 62 },
        proxmox: { runtimeStatus: 'running', diskStatusReason: 'agent-not-running' },
        agent: { agentId: 'in-guest', stale: false, disks },
      });
      const read = vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue({
        resourceType: type,
        resourceId: 'linked:pve:105',
        range: '24h',
        start: Date.parse('2026-10-12T00:00:00Z'),
        end: Date.parse('2026-10-12T01:00:00Z'),
        source: 'store',
        metrics: {},
      });
      const [resource, setResource] = createSignal(source);
      const view = render(() => (
        <ResourceDetailDrawer resource={resource()} presentation="table-row" />
      ));
      try {
        await waitFor(() => expect(read).toHaveBeenCalledTimes(1));
        const chart = view.container.querySelector('[data-history-group="utilization"]')!;
        expect(chart.querySelector('[data-history-current="disk"]')).toHaveTextContent(
          '62.0%current',
        );
        expect(chart.querySelector('[data-history-deferred="disk"]')).toBeNull();
        setResource({
          ...source,
          lastSeen: source.lastSeen + 3600000,
          agent: { ...source.agent, stale: true },
        });
        expect(chart.querySelector('[data-history-current="disk"]')).toBeNull();
        expect(chart.querySelector('[data-history-last-known="disk"]')).toHaveTextContent(
          '62.0%last known',
        );
        expect(chart.querySelector('[data-history-deferred="disk"]')).toHaveTextContent(
          'The Pulse Agent in this guest stopped reporting.',
        );
        setResource({
          ...source,
          proxmox: { runtimeStatus: 'running', disks, diskStatusReason: 'prev-vm-locked' },
        });
        if (type === 'vm') {
          expect(chart.querySelector('[data-history-last-known="disk"]')).toHaveTextContent(
            '62.0%last known',
          );
          expect(chart.querySelector('[data-history-deferred="disk"]')).toHaveTextContent(
            'VM operation lock',
          );
        } else {
          expect(chart.querySelector('[data-history-current="disk"]')).toHaveTextContent(
            '62.0%current',
          );
          expect(chart.querySelector('[data-history-deferred="disk"]')).toBeNull();
        }
        setResource({ ...source, proxmox: { runtimeStatus: 'stopped' } });
        expect(chart.querySelector('[data-history-current="disk"]')).toBeNull();
        expect(chart.querySelector('[data-history-last-known="disk"]')).toBeNull();
        expect(chart.querySelector('[data-history-deferred="disk"]')).toHaveTextContent(
          'unavailable',
        );
        setResource({ ...source, disk: { current: 0 }, status: 'offline' });
        expect(chart.querySelector('[data-history-current="disk"]')).toHaveTextContent(
          '0.0%current',
        );
        expect(chart.querySelector('[data-history-deferred="disk"]')).toBeNull();
        expect(chart.querySelector('[data-history-current="memory"]')).toHaveTextContent(
          '0.0%current',
        );
        expect(chart.querySelector('[data-history-current="cpu"]')).toHaveTextContent(
          '10.0%current',
        );
        expect(view.container.querySelector('[data-history-group="utilization"]')).toBe(chart);
        expect(chart.querySelector('path[data-history-series]')).toBeNull();
        expect(read).toHaveBeenCalledTimes(1);
      } finally {
        view.unmount();
        read.mockRestore();
        resetCreateNonSuspendingQueryCacheForTest();
      }
    },
  );

  it('keeps drawer history fetches out of the page-level suspense fallback', async () => {
    const pendingFacetBundle = new Promise(() => {});
    const pendingIntelligence = new Promise(() => {});
    facetBundleMock.getFacetBundle.mockImplementationOnce(() => pendingFacetBundle as never);
    aiIntelligenceMock.getResourceIntelligence.mockImplementationOnce(
      () => pendingIntelligence as never,
    );

    render(() => (
      <Suspense fallback={<div>Loading view...</div>}>
        <ResourceDetailDrawer resource={baseResource({ recentChanges: [] })} />
      </Suspense>
    ));

    await Promise.resolve();

    expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
    expect(screen.getByTestId('resource-technical-details')).toBeInTheDocument();
  });

  it('keeps table-row presentation focused on local resource details', async () => {
    facetBundleMock.getFacetBundle.mockClear();
    aiIntelligenceMock.getResourceIntelligence.mockClear();
    actionAuditMock.listActionAudits.mockClear();

    render(() => (
      <ResourceDetailDrawer
        resource={baseResource({
          id: 'agent:truenas-main',
          name: 'truenas-main',
          displayName: 'truenas-main',
          platformId: 'truenas-main',
          platformType: 'truenas',
          recentChanges: [],
        })}
        presentation="table-row"
      />
    ));

    await Promise.resolve();

    expect(screen.queryByText('Operator context')).not.toBeInTheDocument();
    expect(screen.getByText('Identity')).toBeInTheDocument();
    expect(screen.queryByText('Change history')).not.toBeInTheDocument();
    expect(screen.queryByText('Operator overrides')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('tab', { name: 'Manage' }));
    expect(screen.getByText('Operator overrides')).toBeInTheDocument();
    expect(screen.queryByText('Maintenance verification')).not.toBeInTheDocument();
    expect(screen.queryByText('Action history')).not.toBeInTheDocument();
    expect(screen.queryByText('Refreshing changes...')).not.toBeInTheDocument();
    expect(screen.queryByText('No events yet.')).not.toBeInTheDocument();
    expect(facetBundleMock.getFacetBundle).not.toHaveBeenCalled();
    expect(aiIntelligenceMock.getResourceIntelligence).not.toHaveBeenCalled();
    expect(actionAuditMock.listActionAudits).not.toHaveBeenCalled();
  });

  it('keeps compact timeline summary chips in overview while showing one embedded change history section', async () => {
    facetBundleMock.getFacetBundle.mockResolvedValueOnce({
      capabilities: [
        {
          name: 'restart',
          type: 'common',
          description: 'Restart the resource safely.',
          minimumApprovalLevel: 'admin',
        },
      ],
      relationships: [
        {
          sourceId: 'node:pve-1',
          targetId: 'vm:42',
          type: 'runs_on',
          confidence: 1,
          active: true,
          discoverer: 'proxmox_adapter',
          observedAt: '2026-03-18T12:00:00Z',
          lastSeenAt: '2026-03-18T12:05:00Z',
          metadata: {
            cluster: 'pve-prod',
            hypervisor: 'pve-1',
          },
        },
      ],
      recentChanges: [
        {
          id: 'change-1',
          observedAt: '2026-03-18T12:06:00Z',
          occurredAt: '2026-03-18T12:04:00Z',
          resourceId: 'vm:42',
          kind: 'restart',
          from: 'running',
          to: 'restarting',
          sourceType: 'platform_event',
          sourceAdapter: 'proxmox_adapter',
          confidence: 'high',
          actor: 'agent:oncall-helper',
          relatedResources: ['node:pve-1'],
          reason: 'Routine restart requested',
          metadata: {
            ticket: 'INC-1234',
            policy: 'routine-maintenance',
          },
        },
      ],
      counts: {
        recentChanges: 3,
        recentChangeKinds: {
          restart: 2,
          metric_anomaly: 1,
        },
        recentChangeSourceTypes: {
          platform_event: 1,
          pulse_diff: 2,
        },
        recentChangeSourceAdapters: {
          docker_adapter: 2,
          proxmox_adapter: 1,
        },
      },
    });

    const resource = baseResource({
      id: 'vm:42',
      type: 'vm',
      name: 'vm-42',
      displayName: 'VM 42',
      platformId: 'vm-42',
      platformType: 'proxmox-pve',
      tags: ['timeline-tag'],
      platformData: { sources: ['proxmox'] },
      relationships: [
        {
          sourceId: 'node:pve-1',
          targetId: 'vm:42',
          type: 'runs_on',
          confidence: 1,
          active: true,
          discoverer: 'proxmox_adapter',
          observedAt: '2026-03-18T12:00:00Z',
          lastSeenAt: '2026-03-18T12:05:00Z',
        },
      ],
    });

    render(() => (
      <ResourceDetailDrawer
        resource={resource}
        resolveResourceLabel={(resourceId) =>
          resourceId === 'node:pve-1'
            ? 'PVE Node 1'
            : resourceId === 'vm:42'
              ? 'VM 42'
              : resourceId === 'storage-1'
                ? 'Storage 1 alias'
                : resourceId === 'vm-child'
                  ? 'VM Child'
                  : resourceId
        }
      />
    ));

    await screen.findByText('Changes loaded');
    const changeHistorySection = screen.getByTestId('resource-change-history-section');
    expect(screen.queryByRole('button', { name: 'Discovery' })).toBeNull();
    expect(screen.queryByText('Summary')).toBeNull();
    expect(screen.queryByText('Operator context')).not.toBeInTheDocument();
    expect(screen.queryByText('Runtime')).toBeNull();
    expect(screen.getByText('Change history')).toBeInTheDocument();
    expect(screen.getByTestId('resource-secondary-sections').classList.contains('space-y-3')).toBe(
      true,
    );
    expect(
      screen
        .getByTestId('resource-technical-summary-section')
        .querySelectorAll('.bg-surface-hover.px-2.py-2').length,
    ).toBe(0);
    const summarySection = screen.getByTestId('resource-technical-summary-section');
    expect(summarySection.classList.contains('overflow-hidden')).toBe(true);
    expect(summarySection.querySelector('table')).toBeTruthy();
    expect(screen.getByTestId('resource-identity-section').tagName).toBe('TBODY');
    expect(
      screen.getByTestId('resource-change-history-section').querySelector('.mt-3.grid.gap-2'),
    ).toBeNull();
    const identitySection = screen.getByTestId('resource-identity-section');
    expect(screen.queryByText('Host')).toBeNull();
    expect(screen.queryByText('Service')).toBeNull();
    expect(screen.queryByText('Supporting context')).toBeNull();
    expect(screen.queryByText('Mail details are only available for PMG resources.')).toBeNull();
    expect(
      screen.queryByText('Namespaces are only available for Kubernetes cluster resources.'),
    ).toBeNull();
    expect(
      screen.queryByText('Deployments are only available for Kubernetes cluster resources.'),
    ).toBeNull();
    expect(
      screen.queryByText(
        'Swarm details are only available for Docker runtimes reporting Swarm metadata.',
      ),
    ).toBeNull();
    expect(screen.queryByText('Container Updates')).toBeNull();
    expect(screen.queryByText('Check Updates')).toBeNull();
    expect(screen.queryByText('Show update controls')).toBeNull();
    expect(screen.queryByText('Access')).toBeNull();
    expect(screen.queryByText('Analysis')).toBeNull();
    expect(
      screen.queryByText('Supporting metadata only. The web interface path above stays primary.'),
    ).toBeNull();
    expect(screen.queryByRole('button', { name: 'Show access' })).toBeNull();
    // One Details disclosure holds the inventory; no per-card "Show details".
    expect(screen.getAllByText('Details')).toHaveLength(1);
    expect(screen.queryByRole('button', { name: 'Show details' })).toBeNull();
    expect(screen.queryByText('Platform ID')).toBeNull();
    expect(within(identitySection).getByText('Tags')).toBeInTheDocument();
    expect(within(identitySection).getByText('Tags')).toBeInTheDocument();
    expect(
      within(changeHistorySection).queryByText('Filterable event history for this resource.'),
    ).toBeNull();
    expect(within(changeHistorySection).queryByText('Recent activity')).toBeNull();
    expect(screen.queryByText('Events')).toBeNull();
    expect(screen.getAllByText('Timeline 3')).toHaveLength(1);
    expect(screen.getAllByText('Restart 2')).toHaveLength(1);
    expect(screen.getAllByText('Anomaly 1')).toHaveLength(1);
    expect(screen.getAllByText('Platform event 1')).toHaveLength(1);
    expect(screen.getAllByText('Pulse diff 2')).toHaveLength(1);
    expect(screen.getAllByText('Docker adapter 2')).toHaveLength(1);
    expect(screen.getAllByText('Proxmox adapter 1')).toHaveLength(1);
    expect(changeHistorySection.querySelectorAll('.mt-1.grid').length).toBe(0);
    expect(screen.queryByText('Quick links')).toBeNull();
    const relationshipMap = within(screen.getByTestId('resource-relationship-map-section'));
    expect(screen.getByText('Relationship map')).toBeInTheDocument();
    expect(relationshipMap.getByText('Canonical relationships')).toBeInTheDocument();
    // Legacy /infrastructure?resource=... cross-jumps were retired; the
    // relationship map renders resource labels as plain text now.
    expect(relationshipMap.queryAllByRole('link')).toHaveLength(0);
    expect(relationshipMap.getByText('PVE Node 1')).toBeInTheDocument();
    expect(relationshipMap.getByText('Runs On')).toBeInTheDocument();
    expect(screen.getByText('Depends on')).toBeInTheDocument();
    expect(screen.getByText('Used by')).toBeInTheDocument();
    expect(screen.getByText('Correlations')).toBeInTheDocument();
    expect(screen.getByText('Storage 1 alias')).toBeInTheDocument();
    expect(screen.getByText('VM Child')).toBeInTheDocument();
    // Platform context sits inside the Overview's Details, opened by render().
    await screen.findByText('Platform details');
    expect(screen.getByText('Context')).toBeInTheDocument();
    expect(screen.queryByText('Capabilities 1')).toBeNull();
    expect(screen.queryByText('Relationships 1')).toBeNull();
    expect(screen.queryByText('Analysis')).toBeNull();

    fireEvent.click(screen.getByRole('button', { name: 'Show context' }));
    const contextSection = screen.getByTestId('resource-investigation-context');
    await within(contextSection).findByText('Analysis');
    expect(contextSection.querySelector('table')).toBeTruthy();
    expect(contextSection.querySelector('tbody')).toBeTruthy();
    expect(contextSection.querySelectorAll('tbody[class*="shadow-xs"]')).toHaveLength(1);
    expect(screen.getByText('Health')).toBeInTheDocument();
    expect(screen.getByText('A · 92/100')).toBeInTheDocument();
    expect(screen.getByText('Trend')).toBeInTheDocument();
    expect(screen.getByText('stable')).toBeInTheDocument();
    expect(screen.getByText('Notes')).toBeInTheDocument();
    expect(screen.getByText('3')).toBeInTheDocument();
    expect(screen.queryByTestId('resource-correlation-context')).toBeNull();
    expect(screen.queryByRole('button', { name: 'Show correlations' })).toBeNull();

    fireEvent.click(screen.getByRole('tab', { name: 'Manage' }));
    expect(screen.getByText('Access')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Show access' })).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Show access' }));
    const accessSection = within(screen.getByTestId('resource-access-section'));
    expect(accessSection.getAllByText('Web interface')).toHaveLength(2);
    expect(accessSection.queryByText('Analysis')).toBeNull();
    expect(accessSection.queryByRole('button', { name: 'Open analysis' })).toBeNull();
  });

  it('keeps default internal cloud-summary posture out of the investigation context drawer block', async () => {
    aiIntelligenceMock.getResourceIntelligence.mockResolvedValueOnce({
      resource_id: 'agent-default-policy',
      health: {
        score: 100,
        grade: 'A',
        trend: 'stable',
        factors: [],
        prediction: '',
      },
      dependencies: [],
      dependents: [],
      correlations: [],
      recent_changes: [],
      note_count: 0,
    });

    const resource = baseResource({
      id: 'agent-default-policy',
      name: 'default-policy-host',
      displayName: 'Default Policy Host',
      policy: {
        sensitivity: 'internal',
        routing: {
          scope: 'cloud-summary',
        },
      },
      aiSafeSummary: 'agent resource; status online; sources agent',
    });

    render(() => <ResourceDetailDrawer resource={resource} />);

    await screen.findByTestId('resource-technical-details');
    expect(screen.queryByText('Context')).toBeNull();
    expect(screen.queryByText('Governance')).toBeNull();
    expect(screen.queryByText('Safe Summary')).toBeNull();
    expect(screen.queryByText('Routing Cloud Summary')).toBeNull();
  });

  it('keeps details label-first without a summary sentence', () => {
    facetBundleMock.getFacetBundle.mockResolvedValueOnce({
      capabilities: [],
      relationships: [],
      recentChanges: [],
    });

    const resource = baseResource({
      id: 'agent-with-support',
      name: 'agent-with-support',
      displayName: 'Agent With Support',
      platformId: 'agent-with-support',
      sourceType: 'agent',
      identity: {
        hostname: 'agent-with-support.local',
      },
      tags: ['support-tag'],
      platformData: {
        sources: ['agent'],
        agent: {
          agentId: 'agent-support-1',
          hostname: 'agent-with-support.local',
        },
      },
    });

    render(() => <ResourceDetailDrawer resource={resource} />);

    expect(
      within(screen.getByTestId('resource-identity-section')).getByText('Aliases'),
    ).toBeInTheDocument();
    expect(screen.queryByTestId('resource-current-state-section')).toBeNull();
  });

  it('renders timeline history without surfacing unsupported capability or relationship facets', async () => {
    facetBundleMock.getFacetBundle.mockResolvedValueOnce({
      capabilities: [
        {
          name: 'restart',
          type: 'common',
          description: 'Restart the resource safely.',
          minimumApprovalLevel: 'admin',
          platform: 'proxmox',
          params: [
            {
              name: 'force',
              type: 'boolean',
              required: false,
              isSensitive: false,
              description: 'Force the restart when needed.',
            },
          ],
        },
      ],
      relationships: [
        {
          sourceId: 'node:pve-1',
          targetId: 'vm:42',
          type: 'runs_on',
          confidence: 1,
          active: true,
          discoverer: 'proxmox_adapter',
          observedAt: '2026-03-18T12:00:00Z',
          lastSeenAt: '2026-03-18T12:05:00Z',
          metadata: {
            cluster: 'pve-prod',
            hypervisor: 'pve-1',
          },
        },
      ],
      recentChanges: [
        {
          id: 'change-1',
          observedAt: '2026-03-18T12:06:00Z',
          occurredAt: '2026-03-18T12:04:00Z',
          resourceId: 'vm:42',
          kind: 'restart',
          from: 'running',
          to: 'restarting',
          sourceType: 'platform_event',
          sourceAdapter: 'proxmox_adapter',
          confidence: 'high',
          actor: 'agent:oncall-helper',
          relatedResources: ['node:pve-1'],
          reason: 'Routine restart requested',
          metadata: {
            ticket: 'INC-1234',
            policy: 'routine-maintenance',
          },
        },
      ],
      counts: {
        recentChanges: 3,
        recentChangeKinds: {
          restart: 2,
          metric_anomaly: 1,
        },
        recentChangeSourceAdapters: {
          docker_adapter: 1,
          proxmox_adapter: 2,
        },
      },
    });

    const resource = baseResource({
      id: 'vm:42',
      type: 'vm',
      name: 'vm-42',
      displayName: 'VM 42',
      platformId: 'vm-42',
      platformType: 'proxmox-pve',
      platformData: { sources: ['proxmox'] },
    });

    render(() => (
      <ResourceDetailDrawer
        resource={resource}
        resolveResourceLabel={(resourceId) =>
          resourceId === 'node:pve-1' ? 'PVE Node 1' : resourceId
        }
      />
    ));

    await screen.findByText('Change history');
    const historyPanel = screen.getByTestId('resource-change-history-section');
    const panel = within(historyPanel);
    expect(await panel.findByText('Changes loaded')).toBeInTheDocument();
    expect(panel.getByText('Routine restart requested')).toBeInTheDocument();
    expect(panel.queryByText('Recent activity')).toBeNull();
    expect(panel.queryByText('Filterable event history for this resource.')).toBeNull();
    expect(panel.queryByText('Event log')).toBeNull();
    // Cross-jump to /infrastructure?resource=... retired; related resources
    // render as plain text now.
    expect(panel.queryAllByRole('link')).toHaveLength(0);
    expect(panel.getByText('PVE Node 1')).toBeInTheDocument();
    expect(panel.getByText('Routine restart requested')).toBeInTheDocument();
    expect(panel.getByText('Confidence')).toBeInTheDocument();
    expect(panel.getByText('Adapter')).toBeInTheDocument();
    expect(panel.getByText('Confidence').parentElement).toHaveClass(
      'justify-between',
      'lg:grid',
      'lg:grid-cols-[7rem_minmax(0,1fr)]',
    );
    expect(panel.getByText('High')).toHaveClass('text-right', 'lg:text-left');
    expect(panel.getByText('Metadata')).toBeInTheDocument();
    expect(panel.getByText(/"ticket": "INC-1234"/)).toBeInTheDocument();
    expect(panel.queryByText('Capabilities')).toBeNull();
    expect(panel.queryByText('Relationships')).toBeNull();
    expect(panel.queryByText('Runs on')).toBeNull();
  });

  it('labels an alert that moved to its Pulse agent as a move, not a recovery', async () => {
    const summary =
      'Alert moved to pve1 (Host Agent). This is not a recovery: check the agent for the current reading.';
    facetBundleMock.getFacetBundle.mockResolvedValueOnce({
      recentChanges: [
        {
          id: 'change-moved',
          observedAt: '2026-10-06T15:00:00Z',
          occurredAt: '2026-10-06T15:00:00Z',
          resourceId: 'node:pve1',
          kind: 'alert_resolved',
          sourceType: 'heuristic',
          confidence: 'high',
          reason: summary,
          metadata: {
            alert_identifier: 'pve1-memory',
            alert_type: 'memory',
            alert_resolution: 'moved_to_agent',
          },
        },
        {
          id: 'change-recovered',
          observedAt: '2026-10-06T14:00:00Z',
          resourceId: 'node:pve1',
          kind: 'alert_resolved',
          sourceType: 'heuristic',
          confidence: 'high',
          reason: 'Alert resolved: Node CPU at 91%',
          metadata: { alert_identifier: 'pve1-cpu', alert_type: 'cpu' },
        },
      ],
      counts: { recentChanges: 2, recentChangeKinds: { alert_resolved: 2 } },
    });

    render(() => (
      <ResourceDetailDrawer
        resource={baseResource({
          id: 'node:pve1',
          type: 'agent',
          name: 'pve1',
          displayName: 'pve1',
          platformType: 'proxmox-pve',
          platformData: { sources: ['proxmox', 'agent'] },
        })}
      />
    ));

    await screen.findByText('Change history');
    const panel = within(screen.getByTestId('resource-change-history-section'));
    const movedReason = await panel.findByText(summary);
    const movedEntry = movedReason.parentElement as HTMLElement;
    expect(within(movedEntry).getByText('Alert moved')).toBeInTheDocument();
    expect(within(movedEntry).queryByText('Alert resolved')).toBeNull();

    // An ordinary recovery keeps its kind label.
    const recoveredEntry = panel.getByText('Alert resolved: Node CPU at 91%')
      .parentElement as HTMLElement;
    expect(within(recoveredEntry).getByText('Alert resolved')).toBeInTheDocument();
  });

  it('surfaces resource-scoped action history from the canonical action audit API', async () => {
    actionAuditMock.listActionAudits.mockResolvedValueOnce({
      available: true,
      count: 2,
      resourceId: 'vm:action-42',
      audits: [
        {
          id: 'action-1',
          createdAt: '2026-04-29T12:00:00Z',
          updatedAt: '2026-04-29T12:05:00Z',
          state: 'completed',
          request: {
            requestId: 'req-1',
            resourceId: 'vm:action-42',
            capabilityName: 'restart_service',
            reason: 'Restart nginx after patching',
            requestedBy: 'agent:oncall-helper',
          },
          plan: {
            actionId: 'action-1',
            requestId: 'req-1',
            allowed: true,
            requiresApproval: true,
            approvalPolicy: 'admin',
            rollbackAvailable: true,
            preflight: {
              target: 'agent:node-1',
              currentState: 'nginx active',
              intendedChange: 'Restart nginx',
              dryRunAvailable: false,
              dryRunSummary: 'No provider-supported dry run is available for this action.',
              safetyChecks: ['Approval scoped to this resource.'],
              verificationSteps: ['Read back service state after execution.'],
              generatedAt: '2026-04-29T12:01:00Z',
            },
          },
          result: {
            success: true,
            output: 'nginx restarted',
          },
          verification: {
            ran: true,
            command: "systemctl is-active 'nginx'",
            output: 'active',
            success: true,
            ranAt: '2026-04-29T12:05:20Z',
          },
          verificationOutcome: {
            status: 'verified',
            evidenceSummary: 'Readback reported nginx active.',
          },
        },
        {
          id: 'action-refused',
          createdAt: '2026-04-29T12:10:00Z',
          updatedAt: '2026-04-29T12:10:30Z',
          state: 'failed',
          request: {
            requestId: 'req-refused',
            resourceId: 'vm:action-42',
            capabilityName: 'lock_remediation',
            reason: 'Patrol proposed remediation while remediation was locked',
            requestedBy: 'pulse_patrol',
          },
          plan: {
            actionId: 'action-refused',
            requestId: 'req-refused',
            allowed: true,
            requiresApproval: true,
            approvalPolicy: 'mfa',
            rollbackAvailable: false,
          },
          result: {
            success: false,
            errorMessage: 'resource_remediation_locked: operator lock is active',
          },
          verificationOutcome: {
            status: 'unverified',
            evidenceSummary: 'No dispatch occurred, so no verification probe ran.',
          },
        },
      ],
    });

    facetBundleMock.getFacetBundle.mockResolvedValueOnce({
      capabilities: [],
      relationships: [],
      recentChanges: [],
      counts: { recentChanges: 0 },
    });

    render(() => (
      <ResourceDetailDrawer
        resource={baseResource({
          id: 'vm:action-42',
          type: 'vm',
          name: 'action-vm',
          displayName: 'Action VM',
          platformType: 'proxmox-pve',
        })}
      />
    ));

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

    const actionHistoryNode = await screen.findByTestId('resource-action-history-section');
    const actionHistory = within(actionHistoryNode);

    expect(actionAuditMock.listActionAudits).toHaveBeenCalledWith({
      resourceId: 'vm:action-42',
      limit: 5,
    });
    expect(actionHistory.getByText('Action history')).toBeInTheDocument();
    expect(actionHistory.getByText('Actions 2')).toBeInTheDocument();
    expect(actionHistory.getByText('Actions loaded')).toBeInTheDocument();
    expect(actionHistory.getByText('Restart Service')).toBeInTheDocument();
    expect(actionHistory.getByText('Completed')).toBeInTheDocument();
    expect(actionHistory.getByText('agent:oncall-helper')).toBeInTheDocument();
    expect(actionHistory.getByText('Restart nginx after patching')).toBeInTheDocument();
    expect(actionHistory.getByText('Admin approval')).toBeInTheDocument();
    expect(actionHistory.getByText('Not available')).toBeInTheDocument();
    expect(actionHistory.getByText('Restart nginx')).toBeInTheDocument();
    expect(actionHistory.getByText('Approval scoped to this resource.')).toBeInTheDocument();
    expect(actionHistory.getByText('nginx restarted')).toBeInTheDocument();
    expect(actionHistory.getByText('Readback reported nginx active.')).toBeInTheDocument();
    expect(actionHistory.getAllByText('Legacy check passed (source unclassified)')).toHaveLength(2);
    expect(actionHistory.queryByText('Verified')).toBeNull();
    expect(actionHistory.getByText("systemctl is-active 'nginx'")).toBeInTheDocument();
    expect(actionHistory.getByText('active')).toBeInTheDocument();
    expect(actionHistory.getByText('Refused')).toBeInTheDocument();
    expect(actionHistory.getByText('Execution refused')).toBeInTheDocument();
    expect(actionHistory.getByText('Refused before dispatch')).toBeInTheDocument();
    expect(actionHistory.getByText('Resource remediation locked')).toBeInTheDocument();
    expect(
      actionHistory.getByText(
        'Pulse refused the action before dispatch because this resource is locked against automatic remediation.',
      ),
    ).toBeInTheDocument();
    expect(actionHistory.getByText('Recorded detail:')).toBeInTheDocument();
    expect(actionHistory.getByText('operator lock is active')).toBeInTheDocument();
    expect(actionHistory.getByText('Verification not confirmed')).toBeInTheDocument();
    expect(
      actionHistory.getByText(
        'Pulse did not receive verification evidence that confirmed the intended state.',
      ),
    ).toBeInTheDocument();
    expect(
      actionHistory.getByText('No dispatch occurred, so no verification probe ran.'),
    ).toBeInTheDocument();
    expect(actionHistoryNode.textContent).not.toContain('resource_remediation_locked:');
  });

  it('keeps service details summary-first until the service-local reveal is opened', () => {
    facetBundleMock.getFacetBundle.mockResolvedValueOnce({
      capabilities: [],
      relationships: [],
      recentChanges: [],
    });

    const resource = baseResource({
      id: 'pbs-1',
      type: 'pbs',
      name: 'pbs-main',
      displayName: 'PBS Main',
      platformId: 'pbs-main',
      platformType: 'proxmox-pbs',
      platformData: {
        sources: ['pbs'],
        pbs: {
          hostname: 'pbs-main.local',
          connectionHealth: 'online',
          datastoreCount: 2,
          backupJobCount: 3,
          jobHealthEvidenceCount: 2,
          jobHealthEvidence: [
            {
              id: 'backup:task-history:fast:vm/100',
              family: 'backup',
              store: 'fast',
              confidence: 'direct-task-match',
              evidenceSource: 'pbs-task-history',
              evidenceScope: 'task-history',
              'last-run-state': 'OK',
              'last-run-upid': 'UPID:backup:1',
              'last-run-endtime': 1776717000,
              freshness: {
                observedAt: '2026-04-20T21:30:00Z',
                state: 'observed',
              },
              posture: 'healthy',
            },
            {
              id: 'prune:partial',
              family: 'prune',
              store: 'archive',
              confidence: 'partial-permission',
              evidenceSource: 'pbs-partial-read',
              evidenceScope: 'partial-read',
              freshness: {
                observedAt: '2026-04-20T21:30:00Z',
                state: 'partial',
              },
              posture: 'unknown',
              postureReason: 'PBS token cannot read prune job configuration.',
              error: 'permission denied',
            },
          ],
        },
      },
    });

    render(() => <ResourceDetailDrawer resource={resource} />);

    expect(screen.getByText('Service')).toBeInTheDocument();
    expect(
      Array.from(screen.getByTestId('resource-support-sections').children).map((node) =>
        node.getAttribute('data-testid'),
      ),
    ).toEqual(['resource-service-details-section']);
    fireEvent.click(screen.getByRole('button', { name: 'Show service' }));
    const serviceDetails = within(screen.getByTestId('resource-service-details-section'));
    expect(
      screen.getByTestId('resource-service-details-section').querySelector('.mt-3.space-y-3'),
    ).toBeTruthy();
    expect(
      screen.getByTestId('resource-service-details-section').querySelector('.mt-3.grid'),
    ).toBeNull();
    expect(serviceDetails.getByText('PBS')).toBeInTheDocument();
    expect(serviceDetails.queryByText('PBS Service')).toBeNull();
    expect(serviceDetails.queryByText('Connection')).toBeNull();
    expect(screen.queryByText('Backup summary')).toBeNull();
    expect(screen.queryByText('Job breakdown')).toBeNull();
    expect(screen.queryByText('Types')).toBeNull();
    expect(screen.queryByText('Job health evidence')).toBeNull();
    expect(screen.queryByText('Show job detail')).toBeNull();
    fireEvent.click(screen.getByRole('button', { name: 'Show jobs' }));
    expect(screen.getByText('Types')).toBeInTheDocument();
    const evidence = within(screen.getByTestId('pbs-job-health-evidence'));
    expect(evidence.getByText('2 evidence records')).toBeInTheDocument();
    expect(evidence.getByText('Observed backup task history')).toBeInTheDocument();
    expect(evidence.getByText('Partial PBS read')).toBeInTheDocument();
    expect(evidence.getByText('Partial read')).toBeInTheDocument();
    expect(evidence.getByText('Permission gap')).toBeInTheDocument();
    expect(evidence.queryByText(/scheduled backup/i)).toBeNull();
  });

  it('keeps PMG node count out of the primary mail-flow metric grid', () => {
    facetBundleMock.getFacetBundle.mockResolvedValueOnce({
      capabilities: [],
      relationships: [],
      recentChanges: [],
    });

    const resource = baseResource({
      id: 'pmg-1',
      type: 'pmg',
      name: 'pmg-main',
      displayName: 'PMG Main',
      platformId: 'pmg-main',
      platformType: 'proxmox-pmg',
      platformData: {
        sources: ['pmg'],
        pmg: {
          hostname: 'pmg-main.local',
          connectionHealth: 'online',
          nodeCount: 1,
          lastUpdated: '2026-03-19T23:00:00Z',
          queueTotal: 519,
          queueDeferred: 12,
          queueHold: 4,
          mailCountTotal: 1200,
          spamIn: 32,
          virusIn: 2,
        },
      },
    });

    render(() => <ResourceDetailDrawer resource={resource} />);

    fireEvent.click(screen.getByRole('button', { name: 'Show service' }));
    fireEvent.click(screen.getByRole('button', { name: 'Show mail flow' }));
    expect(screen.getByText('Queue')).toBeInTheDocument();
    expect(screen.getByText('Backlog')).toBeInTheDocument();
    const supportContext = within(screen.getByTestId('pmg-support-context'));
    expect(supportContext.getByText('Nodes')).toBeInTheDocument();
    expect(supportContext.getByText('Updated')).toBeInTheDocument();
    expect(screen.getByText('Queue detail').closest('summary')?.textContent).toBe('Queue detail');
    expect(screen.getByText('Mail detail').closest('summary')?.textContent).toBe('Mail detail');
  });

  it('filters timeline entries by kind and source type', async () => {
    const unfilteredFacetBundle = {
      capabilities: [
        {
          name: 'restart',
          type: 'common',
          description: 'Restart the resource safely.',
          minimumApprovalLevel: 'admin',
        },
      ],
      relationships: [
        {
          sourceId: 'node:pve-1',
          targetId: 'vm:42',
          type: 'runs_on',
          confidence: 1,
          active: true,
          discoverer: 'proxmox_adapter',
          observedAt: '2026-03-18T12:00:00Z',
          lastSeenAt: '2026-03-18T12:05:00Z',
          metadata: {
            cluster: 'pve-prod',
            source: 'live',
          },
        },
      ],
      recentChanges: [
        {
          id: 'change-1',
          observedAt: '2026-03-18T12:06:00Z',
          occurredAt: '2026-03-18T12:04:00Z',
          resourceId: 'vm:42',
          kind: 'restart',
          sourceType: 'platform_event',
          sourceAdapter: 'proxmox_adapter',
          confidence: 'high',
          actor: 'agent:oncall-helper',
          relatedResources: ['node:pve-1'],
          reason: 'Routine restart requested',
          metadata: {
            ticket: 'INC-1234',
          },
        },
        {
          id: 'change-2',
          observedAt: '2026-03-18T12:02:00Z',
          resourceId: 'vm:42',
          kind: 'metric_anomaly',
          sourceType: 'pulse_diff',
          sourceAdapter: 'proxmox_adapter',
          confidence: 'medium',
          reason: 'CPU spike detected',
        },
      ],
      counts: {
        recentChanges: 2,
        recentChangeKinds: {
          restart: 1,
          metric_anomaly: 1,
        },
        recentChangeSourceAdapters: {
          docker_adapter: 1,
          proxmox_adapter: 1,
        },
      },
    };
    const filteredFacetBundle = {
      capabilities: [
        {
          name: 'restart',
          type: 'common',
          description: 'Restart the resource safely.',
          minimumApprovalLevel: 'admin',
        },
      ],
      relationships: unfilteredFacetBundle.relationships,
      recentChanges: [
        {
          id: 'change-1',
          observedAt: '2026-03-18T12:06:00Z',
          occurredAt: '2026-03-18T12:04:00Z',
          resourceId: 'vm:42',
          kind: 'restart',
          sourceType: 'platform_event',
          sourceAdapter: 'proxmox_adapter',
          confidence: 'high',
          actor: 'agent:oncall-helper',
          relatedResources: ['node:pve-1'],
          reason: 'Routine restart requested',
          metadata: {
            ticket: 'INC-1234',
          },
        },
      ],
      counts: {
        recentChanges: 1,
      },
    };
    facetBundleMock.getFacetBundle
      .mockResolvedValueOnce(unfilteredFacetBundle)
      .mockResolvedValueOnce(filteredFacetBundle)
      .mockResolvedValueOnce(filteredFacetBundle);

    const resource = baseResource({
      id: 'vm:42',
      type: 'vm',
      name: 'vm-42',
      displayName: 'VM 42',
      platformId: 'vm-42',
      platformType: 'proxmox-pve',
      platformData: { sources: ['proxmox'] },
    });

    render(() => <ResourceDetailDrawer resource={resource} />);

    await screen.findByText('Change history');
    const historyPanel = screen.getByTestId('resource-change-history-section');
    const panel = within(historyPanel);
    expect(await panel.findByText('Changes loaded')).toBeInTheDocument();
    expect(panel.getByText('CPU spike detected')).toBeInTheDocument();
    expect(panel.queryByLabelText('Change kind')).toBeNull();
    expect(panel.getByRole('button', { name: 'Filter history' })).toBeInTheDocument();

    fireEvent.click(panel.getByRole('button', { name: 'Filter history' }));

    fireEvent.change(panel.getByLabelText('Change kind'), {
      target: { value: 'restart' },
    });
    fireEvent.change(panel.getByLabelText('Source type'), {
      target: { value: 'platform_event' },
    });

    expect(await panel.findByText('Filtered changes loaded')).toBeInTheDocument();
    expect(await panel.findByText('Timeline 1')).toBeInTheDocument();
    expect(panel.queryByText('Timeline 2')).toBeNull();
    expect(await panel.findByText('Routine restart requested')).toBeInTheDocument();
    expect(panel.queryByText('CPU spike detected')).toBeNull();

    fireEvent.click(panel.getByRole('button', { name: 'Clear filters' }));

    expect(await panel.findByText('Changes loaded')).toBeInTheDocument();
    expect(await panel.findByText('Timeline 2')).toBeInTheDocument();
    expect(panel.queryByText('Filtered changes loaded')).toBeNull();
    expect(panel.getByText('CPU spike detected')).toBeInTheDocument();
    expect(panel.queryByLabelText('Change kind')).toBeNull();
    expect(panel.getByRole('button', { name: 'Filter history' })).toBeInTheDocument();
  });

  it('filters timeline entries by source adapter', async () => {
    facetBundleMock.getFacetBundle
      .mockResolvedValueOnce({
        capabilities: [
          {
            name: 'restart',
            type: 'common',
            description: 'Restart the resource safely.',
            minimumApprovalLevel: 'admin',
          },
        ],
        relationships: [
          {
            sourceId: 'node:pve-1',
            targetId: 'vm:42',
            type: 'runs_on',
            confidence: 1,
            active: true,
            discoverer: 'proxmox_adapter',
            observedAt: '2026-03-18T12:00:00Z',
            lastSeenAt: '2026-03-18T12:05:00Z',
            metadata: {
              cluster: 'pve-prod',
              source: 'live',
            },
          },
        ],
        recentChanges: [
          {
            id: 'change-1',
            observedAt: '2026-03-18T12:06:00Z',
            occurredAt: '2026-03-18T12:04:00Z',
            resourceId: 'vm:42',
            kind: 'restart',
            sourceType: 'platform_event',
            sourceAdapter: 'proxmox_adapter',
            confidence: 'high',
            actor: 'agent:oncall-helper',
            relatedResources: ['node:pve-1'],
            reason: 'Routine restart requested',
            metadata: {
              ticket: 'INC-1234',
            },
          },
          {
            id: 'change-2',
            observedAt: '2026-03-18T12:02:00Z',
            resourceId: 'vm:42',
            kind: 'metric_anomaly',
            sourceType: 'pulse_diff',
            sourceAdapter: 'docker_adapter',
            confidence: 'medium',
            reason: 'CPU spike detected',
          },
        ],
        counts: {
          recentChanges: 2,
          recentChangeKinds: {
            restart: 1,
            metric_anomaly: 1,
          },
          recentChangeSourceAdapters: {
            docker_adapter: 1,
            proxmox_adapter: 1,
          },
        },
      })
      .mockResolvedValueOnce({
        capabilities: [
          {
            name: 'restart',
            type: 'common',
            description: 'Restart the resource safely.',
            minimumApprovalLevel: 'admin',
          },
        ],
        relationships: [
          {
            sourceId: 'node:pve-1',
            targetId: 'vm:42',
            type: 'runs_on',
            confidence: 1,
            active: true,
            discoverer: 'proxmox_adapter',
            observedAt: '2026-03-18T12:00:00Z',
            lastSeenAt: '2026-03-18T12:05:00Z',
            metadata: {
              cluster: 'pve-prod',
              source: 'live',
            },
          },
        ],
        recentChanges: [
          {
            id: 'change-2',
            observedAt: '2026-03-18T12:02:00Z',
            resourceId: 'vm:42',
            kind: 'metric_anomaly',
            sourceType: 'pulse_diff',
            sourceAdapter: 'docker_adapter',
            confidence: 'medium',
            reason: 'CPU spike detected',
          },
        ],
        counts: {
          recentChanges: 1,
          recentChangeKinds: {
            metric_anomaly: 1,
          },
          recentChangeSourceAdapters: {
            docker_adapter: 1,
          },
        },
      });

    const resource = baseResource({
      id: 'vm:42',
      type: 'vm',
      name: 'vm-42',
      displayName: 'VM 42',
      platformId: 'vm-42',
      platformType: 'proxmox-pve',
      platformData: { sources: ['proxmox'] },
    });

    render(() => <ResourceDetailDrawer resource={resource} />);

    await screen.findByText('Change history');
    const historyPanel = screen.getByTestId('resource-change-history-section');
    const panel = within(historyPanel);
    expect(await panel.findByText('Changes loaded')).toBeInTheDocument();
    expect(panel.getByText('CPU spike detected')).toBeInTheDocument();
    expect(panel.queryByLabelText('Source adapter')).toBeNull();

    fireEvent.click(panel.getByRole('button', { name: 'Filter history' }));

    fireEvent.change(panel.getByLabelText('Source adapter'), {
      target: { value: 'docker_adapter' },
    });

    expect(await panel.findByText('Filtered changes loaded')).toBeInTheDocument();
    expect(await panel.findByText('Timeline 1')).toBeInTheDocument();
    expect(panel.queryByText('Timeline 2')).toBeNull();
    expect(await panel.findByText('CPU spike detected')).toBeInTheDocument();
    expect(panel.queryByText('Routine restart requested')).toBeNull();
  });
  it('does not re-display embedded changes after a denied facet read', async () => {
    facetBundleMock.getFacetBundle.mockRejectedValueOnce(
      Object.assign(new Error('private response detail'), { status: 403 }),
    );
    render(() => (
      <ResourceDetailDrawer
        resource={baseResource({
          recentChanges: [
            {
              id: 'embedded',
              resourceId: 'resource-1',
              observedAt: '2026-10-03T03:00:00Z',
              kind: 'restart',
              sourceType: 'platform_event',
              confidence: 'high',
              actor: 'Embedded snapshot actor',
            },
          ],
          facetCounts: { recentChanges: 7 },
        })}
      />
    ));
    const history = screen.getByTestId('resource-change-history-section');
    await waitFor(() =>
      expect(within(history).getByRole('alert')).toHaveTextContent(
        'Access denied. Check your permissions and license plan.',
      ),
    );
    expect(history).not.toHaveTextContent('Embedded snapshot actor');
    expect(history).not.toHaveTextContent('No events yet.');
    expect(history).not.toHaveTextContent('Changes loaded');
    expect(within(history).getByRole('button', { name: /^Retry$/ })).toBeInTheDocument();
  });

  it('keeps a failed first action read and retry visible in Manage', async () => {
    actionAuditMock.listActionAudits.mockRejectedValueOnce(
      Object.assign(new Error('Actions temporarily unavailable'), { status: 503 }),
    );
    render(() => <ResourceDetailDrawer resource={baseResource({})} />);
    fireEvent.click(screen.getByRole('tab', { name: 'Manage' }));
    await waitFor(() =>
      expect(screen.getByTestId('resource-action-history-section')).toHaveTextContent(
        'Actions temporarily unavailable',
      ),
    );
    const actions = screen.getByTestId('resource-action-history-section');
    expect(actions).toHaveTextContent('Actions unavailable');
    expect(actions).not.toHaveTextContent('No actions yet.');
    actionAuditMock.listActionAudits.mockResolvedValueOnce({
      audits: [],
      count: 0,
      available: true,
    });
    fireEvent.click(within(actions).getByRole('button', { name: /^Retry$/ }));
    await waitFor(() => expect(actions).toHaveTextContent('No actions yet.'));
    expect(actions).not.toHaveTextContent('Actions temporarily unavailable');
  });
});

describe('ResourceDetailDrawer Overview alert sources', () => {
  it('charts only the resource own alerts and explains latched ones with the shared copy', () => {
    // Needs attention lists every alert for the resource and what nests under
    // it; a chart trigger must be the resource's own (a host's container
    // memory alert is not the host's memory trigger).
    expect(resourceDetailDrawerOverviewSource).toContain('getOwnAlertsForUnifiedResource(');
    expect(resourceDetailDrawerOverviewSource).toContain('...getAlertAttentionCopy(alert, now)');
    expect(resourceDetailDrawerOverviewSource).not.toContain('message: alert.message,');
  });
});

describe('ResourceDetailDrawer header status dot', () => {
  it("reads a container's run state and health check, as its row does", () => {
    const { unmount } = render(() => (
      <ResourceDetailDrawer
        resource={baseResource({
          id: 'app-container:edge-web',
          type: 'app-container',
          name: 'edge-web',
          status: 'online',
          docker: { containerId: 'abc', containerState: 'running', health: 'unhealthy' },
        })}
      />
    ));
    // Running but failing its check is red with the row's label, not green.
    expect(screen.getByRole('img', { name: 'Unhealthy' })).toHaveClass('bg-red-500');
    unmount();

    render(() => <ResourceDetailDrawer resource={baseResource({ status: 'online' })} />);
    // Other resources keep the shared run-status dot.
    expect(screen.queryByRole('img', { name: 'Unhealthy' })).toBeNull();
  });
});