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.

13.0 KB
Raw Blame
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { PatrolRunRecord } from '@/api/patrol';
import { RunHistoryEntry } from '../RunHistoryEntry';

const { findingsPanelState } = vi.hoisted(() => ({
  findingsPanelState: {
    latestProps: null as Record<string, unknown> | null,
  },
}));

vi.mock('@/components/AI/FindingsPanel', () => ({
  FindingsPanel: (props: Record<string, unknown>) => {
    findingsPanelState.latestProps = {
      filterFindingIds: Array.isArray(props.filterFindingIds)
        ? [...(props.filterFindingIds as string[])]
        : props.filterFindingIds,
      filterOverride: props.filterOverride,
      scopeResourceIds: Array.isArray(props.scopeResourceIds)
        ? [...(props.scopeResourceIds as string[])]
        : props.scopeResourceIds,
      scopeResourceTypes: Array.isArray(props.scopeResourceTypes)
        ? [...(props.scopeResourceTypes as string[])]
        : props.scopeResourceTypes,
      findingsSource: props.findingsSource,
      showControls: props.showControls,
      showScopeWarnings: props.showScopeWarnings,
      runSnapshot: props.runSnapshot,
    };
    return <div data-testid="findings-panel" />;
  },
}));

vi.mock('../RunToolCallTrace', () => ({
  RunToolCallTrace: () => <div data-testid="tool-call-trace" />,
}));

vi.mock('@/components/AI/aiChatUtils', () => ({
  renderMarkdown: (content: string) => content,
}));

describe('RunHistoryEntry', () => {
  const patrolStream = {
    phase: () => '',
    currentTool: () => '',
    tokens: () => 0,
    resynced: () => false,
    resyncReason: () => '',
    bufferStartSeq: () => 0,
    bufferEndSeq: () => 0,
    outputTruncated: () => false,
    reconnectCount: () => 0,
    isStreaming: () => false,
    errorMessage: () => '',
  };

  const run: PatrolRunRecord = {
    id: 'run-1',
    started_at: '2026-03-12T10:00:00Z',
    completed_at: '2026-03-12T10:01:00Z',
    duration_ms: 60000,
    type: 'scoped',
    trigger_reason: 'alert_fired',
    scope_resource_ids: ['seed-resource'],
    effective_scope_resource_ids: [],
    scope_resource_types: ['vm'],
    resources_checked: 0,
    nodes_checked: 0,
    guests_checked: 0,
    docker_checked: 0,
    storage_checked: 0,
    hosts_checked: 0,
    truenas_checked: 0,
    pbs_checked: 0,
    pmg_checked: 0,
    kubernetes_checked: 0,
    new_findings: 0,
    existing_findings: 0,
    rejected_findings: 0,
    resolved_findings: 0,
    auto_fix_count: 0,
    findings_summary: 'All clear',
    finding_ids: [],
    error_count: 0,
    status: 'healthy',
    triage_flags: 0,
    tool_call_count: 0,
  };

  beforeEach(() => {
    findingsPanelState.latestProps = null;
  });

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

  it('renders an explicit empty snapshot with canonical scope props', () => {
    render(() => (
      <RunHistoryEntry
        run={run}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByTestId('findings-panel')).toBeInTheDocument();
    expect(findingsPanelState.latestProps).toMatchObject({
      filterFindingIds: [],
      filterOverride: 'all',
      scopeResourceIds: [],
      scopeResourceTypes: ['vm'],
      findingsSource: 'patrol',
      showControls: false,
      showScopeWarnings: true,
      runSnapshot: run,
    });
  });

  it('renders the inline findings panel in snapshot-unavailable mode for legacy runs without finding ids', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-missing-finding-ids',
          finding_ids: undefined,
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('Completed check')).toBeInTheDocument();
    expect(screen.getByText('completed')).toBeInTheDocument();
    expect(screen.getByTestId('findings-panel')).toBeInTheDocument();
    expect(findingsPanelState.latestProps).toMatchObject({
      filterFindingIds: undefined,
      filterOverride: 'all',
      scopeResourceIds: [],
      scopeResourceTypes: ['vm'],
      findingsSource: 'patrol',
      showControls: false,
      showScopeWarnings: true,
      runSnapshot: {
        ...run,
        id: 'run-missing-finding-ids',
        finding_ids: undefined,
      },
    });
    expect(
      screen.getAllByText(
        (_, element) =>
          element?.tagName === 'P' &&
          (element.textContent?.includes('This older run has no issue list.') ?? false),
      ).length,
    ).toBeGreaterThan(0);
    expect(screen.getByText('Finding record unavailable')).toBeInTheDocument();
    expect(screen.queryByText('All clear — no new issues.')).not.toBeInTheDocument();
    expect(screen.queryByText(/^All clear$/)).not.toBeInTheDocument();
    expect(screen.queryByText('healthy')).not.toBeInTheDocument();
  });

  it('uses a shared coverage summary when a scoped run checked fewer resources than its scope', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-partial-scope',
          duration_ms: 453,
          effective_scope_resource_ids: ['expanded-a', 'expanded-b'],
          resources_checked: 1,
          guests_checked: 1,
          error_count: 1,
          status: 'error',
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('Patrol needs attention')).toBeInTheDocument();
    expect(
      screen.getAllByText(
        'Checked 1 of 2 scoped resources in 453ms. Runtime issue: 1 Patrol runtime error recorded.',
      ).length,
    ).toBeGreaterThan(0);
    expect(screen.getByText('Resources checked (1 of 2 scoped)')).toBeInTheDocument();
    expect(screen.queryByText('• 1 resources')).not.toBeInTheDocument();
    expect(screen.queryByText('Scoped to 2 resources')).not.toBeInTheDocument();
    expect(
      screen.getAllByText(
        (_, element) =>
          element?.tagName === 'P' &&
          (element.textContent?.includes('Checked 1 of 2 scoped resources') ?? false) &&
          (element.textContent?.includes('453ms') ?? false) &&
          (element.textContent?.includes('Runtime issue: 1 Patrol runtime error recorded.') ??
            false),
      ).length,
    ).toBeGreaterThan(0);
  });

  it('surfaces structured Patrol runtime error details on expanded runs', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-runtime-error',
          error_count: 1,
          status: 'error',
          error_summary: 'Selected model does not support Patrol tools',
          error_detail:
            "agentic patrol failed: API error (404): No endpoints found that support the provided 'tool_choice' value.",
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('Selected model does not support Patrol tools')).toBeInTheDocument();
    expect(screen.getAllByText(/Provider rejected Patrol tool calls/).length).toBeGreaterThan(0);
    expect(screen.queryByText(/tool_choice/)).toBeNull();
    expect(screen.queryByText(/No endpoints found/)).toBeNull();
    expect(screen.getByText('error')).toBeInTheDocument();
    expect(screen.getByRole('link', { name: 'Check Patrol model' })).toHaveAttribute(
      'href',
      '/settings/pulse-intelligence/patrol',
    );
  });

  it('does not show provider settings for healthy runs', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-healthy',
          error_count: 0,
          status: 'healthy',
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.queryByRole('link', { name: 'Check Patrol model' })).toBeNull();
  });

  it('keeps zero-coverage scoped runs on the shared coverage narrative', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-zero-coverage-scope',
          duration_ms: 453,
          effective_scope_resource_ids: ['expanded-a', 'expanded-b'],
          resources_checked: 0,
          error_count: 1,
          status: 'error',
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('Patrol needs attention')).toBeInTheDocument();
    expect(
      screen.getAllByText(
        'Checked 0 of 2 scoped resources in 453ms. Runtime issue: 1 Patrol runtime error recorded.',
      ).length,
    ).toBeGreaterThan(0);
    expect(screen.queryByText('Scoped to 2 resources')).not.toBeInTheDocument();
    expect(
      screen.getAllByText(
        (_, element) =>
          element?.tagName === 'P' &&
          (element.textContent?.includes('Checked 0 of 2 scoped resources') ?? false) &&
          (element.textContent?.includes('453ms') ?? false) &&
          (element.textContent?.includes('Runtime issue: 1 Patrol runtime error recorded.') ??
            false),
      ).length,
    ).toBeGreaterThan(0);
    expect(screen.queryByText(/^Patrol completed in 453ms/)).not.toBeInTheDocument();
  });

  it('does not claim all clear when the run still had existing issues', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-existing-issues',
          existing_findings: 2,
          status: 'critical',
          findings_summary: 'Existing issues remain',
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('2 issues still open')).toBeInTheDocument();
    expect(screen.getAllByText('Patrol ran in 1m. No new issues.').length).toBeGreaterThan(0);
    expect(screen.queryByText('All clear — no new issues.')).not.toBeInTheDocument();
    expect(screen.queryByText(/^All clear$/)).not.toBeInTheDocument();
  });

  it('uses singular issue wording when a single issue remains open', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-existing-issue-singular',
          existing_findings: 1,
          status: 'issues_found',
          findings_summary: 'One existing issue remains',
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('1 issue still open')).toBeInTheDocument();
    expect(screen.getAllByText('Patrol ran in 1m. No new issues.').length).toBeGreaterThan(0);
    // Guard against the regression: the prior wording was "1 existing issue remain."
    expect(
      screen.queryByText(
        (_, element) =>
          element?.tagName === 'P' &&
          (element.textContent?.includes('existing issue remain.') ?? false) &&
          !(element.textContent?.includes('remains.') ?? false),
      ),
    ).not.toBeInTheDocument();
  });

  it('surfaces deterministic triage runs that skipped the llm', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-triage-only',
          triage_flags: 3,
          triage_skipped_llm: true,
          findings_summary: 'Quiet infrastructure',
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('3 triage flags')).toBeInTheDocument();
    expect(screen.getByText('LLM skipped')).toBeInTheDocument();
  });

  it('keeps technical run trace behind an explicit details disclosure', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-technical-details',
          duration_ms: 60_000,
          tool_call_count: 2,
          triage_flags: 1,
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('Technical details')).toBeInTheDocument();
    expect(screen.queryByTestId('tool-call-trace')).not.toBeInTheDocument();

    const technicalDetails = screen.getByText('Technical details').closest('details');
    expect(technicalDetails).not.toBeNull();
    technicalDetails!.open = true;
    fireEvent(technicalDetails!, new Event('toggle'));

    expect(screen.getByTestId('tool-call-trace')).toBeInTheDocument();
  });

  it('renders TrueNAS run coverage separately from agent hosts', () => {
    render(() => (
      <RunHistoryEntry
        run={{
          ...run,
          id: 'run-truenas',
          resources_checked: 2,
          docker_checked: 1,
          truenas_checked: 1,
        }}
        isLive={false}
        patrolStream={patrolStream}
        selected={true}
        onSelect={vi.fn()}
      />
    ));

    expect(screen.getByText('1 container')).toBeInTheDocument();
    expect(screen.getByText('1 TrueNAS system')).toBeInTheDocument();
    expect(screen.queryByText('1 agent')).not.toBeInTheDocument();
  });
});