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.

21.0 KB
Raw Blame
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ResourceActionsAPI } from '@/api/resourceActions';
import type { Resource } from '@/types/resource';
import { ResourceDetailDrawer } from '../ResourceDetailDrawer';
import { markSystemSettingsLoadedWithDefaults } from '@/stores/systemSettings';

vi.mock('@/contexts/appRuntime', async (importOriginal) => ({
  ...(await importOriginal<typeof import('@/contexts/appRuntime')>()),
  useWebSocket: () => ({ activeAlerts: {} }),
}));

vi.mock('@/components/Workloads/GuestDrawerHistory', () => ({
  GuestDrawerHistory: (props: {
    target: { resourceType: string; resourceId: string } | null;
    range: string;
    currentMetrics?: Record<string, number | undefined>;
  }) => (
    <div
      data-testid="container-history"
      data-resource-type={props.target?.resourceType}
      data-resource-id={props.target?.resourceId}
      data-range={props.range}
      data-cpu={props.currentMetrics?.cpu}
    />
  ),
  GuestDrawerHistoryRangeSelect: (props: {
    range: string;
    onRangeChange: (range: string) => void;
  }) => (
    <select
      aria-label="History range"
      value={props.range}
      onChange={(event) => props.onRangeChange(event.currentTarget.value)}
    >
      <option value="24h">24 hours</option>
      <option value="7d">7 days</option>
    </select>
  ),
}));

vi.mock('@/api/resourceActions', () => ({
  ResourceActionsAPI: {
    planAction: vi.fn().mockResolvedValue({
      actionId: 'detail-action-1',
      requestId: 'detail-request-1',
      allowed: true,
      requiresApproval: true,
      approvalPolicy: 'admin',
      rollbackAvailable: false,
    }),
    decideAction: vi.fn().mockResolvedValue({
      actionId: 'detail-action-1',
      outcome: 'approved',
      decidedAt: '2026-06-12T20:00:01Z',
    }),
    executeAction: vi.fn().mockResolvedValue({
      actionId: 'detail-action-1',
      state: 'completed',
      result: { success: true },
    }),
    getAction: vi.fn().mockResolvedValue({
      audit: {
        id: 'detail-action-1',
        createdAt: '2026-06-12T20:00:00Z',
        updatedAt: '2026-06-12T20:00:00Z',
        state: 'pending_approval',
        decisionRevision: 0,
        request: {
          requestId: 'detail-request-1',
          resourceId: 'app-container-web',
          capabilityName: 'restart',
          reason: 'restart Docker container edge-web from the resource details.',
          requestedBy: 'ui:resource-detail',
        },
        plan: {
          actionId: 'detail-action-1',
          requestId: 'detail-request-1',
          allowed: true,
          requiresApproval: true,
          approvalPolicy: 'admin',
          rollbackAvailable: false,
          expiresAt: '2026-06-12T20:05:00Z',
          policyDecision: {
            version: 0,
            status: 'legacy_unknown',
            scope: { orgId: '', resourceId: '', capabilityName: '' },
            authorities: [],
            approvalRequirement: {
              version: 0,
              floor: 'admin',
              quorum: 1,
              disallowRequester: false,
            },
            planningAllowed: false,
            requiresApproval: true,
          },
        },
        verificationOutcome: { status: 'unknown' },
      },
      events: [],
    }),
  },
}));

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

// The server advertises update on a container with an available update.
const UPDATE_CAPABILITY = {
  name: 'update',
  type: 'common',
  platform: 'docker',
  minimumApprovalLevel: 'admin',
} as NonNullable<Resource['capabilities']>[number];

const resource = (overrides: Partial<Resource>): Resource =>
  ({
    id: overrides.id ?? 'app-container-1',
    name: overrides.name ?? overrides.id ?? 'app-container-1',
    displayName: overrides.displayName ?? overrides.name ?? overrides.id ?? 'app-container-1',
    type: overrides.type ?? 'app-container',
    platformId: 'docker',
    platformType: 'docker',
    sourceType: 'agent',
    status: 'online',
    lastSeen: 1_700_000_000_000,
    ...overrides,
  }) as Resource;

afterEach(() => {
  cleanup();
  vi.clearAllMocks();
});

describe('ResourceDetailDrawer for Docker containers', () => {
  it('renders governed lifecycle controls in Docker container details', async () => {
    const onResourceActionSettled = vi.fn();

    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        onResourceActionSettled={onResourceActionSettled}
        resource={resource({
          id: 'app-container-web',
          name: 'edge-web',
          docker: {
            agentId: 'agent-edge',
            containerId: 'abc123def456',
            containerState: 'running',
            runtime: 'docker',
            image: 'ghcr.io/example/edge-web:2026.05',
          },
          capabilities: [
            {
              name: 'restart',
              type: 'common',
              platform: 'docker',
              minimumApprovalLevel: 'admin',
            },
          ],
          sourceStatus: { docker: { status: 'online' } },
        })}
      />
    ));

    const restartButton = screen.getByRole('button', {
      name: 'Review restart for edge-web',
    });
    expect(restartButton.closest('[data-docker-container-actions-surface]')).toHaveAttribute(
      'data-docker-container-actions-surface',
      'resource-detail',
    );

    fireEvent.click(restartButton);

    await waitFor(() =>
      expect(ResourceActionsAPI.planAction).toHaveBeenCalledWith(
        expect.objectContaining({
          resourceId: 'app-container-web',
          capabilityName: 'restart',
          reason: expect.stringContaining('from the resource details'),
          requestedBy: 'ui:resource-detail',
        }),
      ),
    );
    expect(await screen.findByRole('dialog', { name: 'Restart' })).toBeInTheDocument();
    expect(ResourceActionsAPI.decideAction).not.toHaveBeenCalled();
    expect(ResourceActionsAPI.executeAction).not.toHaveBeenCalled();
    expect(onResourceActionSettled).not.toHaveBeenCalled();
  });

  it('charts metrics history on Overview for app-containers with a metrics target', async () => {
    render(() => (
      <ResourceDetailDrawer
        resource={resource({
          id: 'app-container-web',
          name: 'edge-web',
          metricsTarget: { resourceType: 'app-container', resourceId: 'abc123def456' },
          cpu: { current: 75 },
        })}
      />
    ));

    expect(screen.queryByRole('tab', { name: 'History' })).not.toBeInTheDocument();
    const history = screen.getByTestId('container-history');
    expect(history).toHaveAttribute('data-resource-type', 'app-container');
    expect(history).toHaveAttribute('data-resource-id', 'abc123def456');
    expect(history).toHaveAttribute('data-cpu', '75');
  });

  it('omits history charts when no metrics target resolves', () => {
    render(() => (
      <ResourceDetailDrawer
        resource={resource({
          id: 'docker-image-1',
          type: 'docker-image',
          name: 'nginx:latest',
        })}
      />
    ));

    expect(screen.queryByTestId('container-history')).not.toBeInTheDocument();
  });

  it('renders container runtime facts in the table-row summary', () => {
    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        resource={resource({
          id: 'app-container-web',
          name: 'edge-web',
          docker: {
            containerId: 'abc123def456',
            containerState: 'running',
            image: 'ghcr.io/example/edge-web:2026.05',
            updateStatus: {
              updateAvailable: true,
              currentDigest: 'sha256:current-digest',
              latestDigest: 'sha256:target-digest',
              lastChecked: '2026-05-24T13:00:00Z',
            },
            restartCount: 7,
            createdAt: '2026-04-13T01:14:01Z',
            startedAt: '2026-04-13T01:15:01Z',
            finishedAt: '2026-04-13T02:15:01Z',
            blockIo: { readBytes: 1_048_576, writeBytes: 2_097_152 },
            podman: {
              podName: 'edge-pod',
              podId: 'pod-123',
              infra: true,
              composeProject: 'orion',
              composeService: 'web',
              autoUpdatePolicy: 'registry',
              userNamespace: 'keep-id',
            },
            labels: {
              'com.docker.compose.project': 'legacy-project',
              'com.docker.compose.service': 'legacy-service',
              'traefik.enable': 'true',
            },
          },
        })}
      />
    ));

    // The facts line names the image and Compose service in front.
    const facts = screen.getByTestId('resource-drawer-facts');
    expect(facts).toHaveTextContent('ghcr.io/example/edge-web:2026.05');
    expect(facts).toHaveTextContent(/Compose orion/);
    const section = screen.getByTestId('resource-docker-container-section');
    expect(within(section).getByText('Image')).toBeInTheDocument();
    expect(within(section).getByText('ghcr.io/example/edge-web:2026.05')).toBeInTheDocument();
    // An available update is something to act on, so it is lifted in front.
    const updateRow = screen.getByTestId('resource-drawer-exceptions');
    expect(within(updateRow).getByText('Image update')).toBeInTheDocument();
    expect(within(updateRow).getByText('Available').closest('td')).toHaveClass('text-cyan-700');
    expect(within(section).queryByText('Image update')).not.toBeInTheDocument();
    expect(within(section).getByText('Current digest')).toBeInTheDocument();
    expect(within(section).getByText('sha256:current-digest')).toBeInTheDocument();
    expect(within(section).getByText('Target digest')).toBeInTheDocument();
    expect(within(section).getByText('sha256:target-digest')).toBeInTheDocument();
    expect(within(section).queryByText('Release information')).not.toBeInTheDocument();
    // A worrying restart count moves in front of the charts, not repeated below.
    const lifted = screen.getByTestId('resource-drawer-exceptions');
    expect(within(lifted).getByText('Restarts')).toBeInTheDocument();
    // Amber, as its row dot reads: running, but worth a look.
    expect(within(lifted).getByText('7').closest('td')).toHaveClass('text-amber-700');
    expect(within(section).queryByText('Restarts')).not.toBeInTheDocument();
    expect(within(section).getByText('Created')).toBeInTheDocument();
    expect(within(section).getByText('Started')).toBeInTheDocument();
    expect(within(section).getByText('Finished')).toBeInTheDocument();
    expect(within(section).getAllByText(/ago$/).length).toBeGreaterThanOrEqual(3);
    expect(within(section).getByText('Podman pod')).toBeInTheDocument();
    expect(within(section).getByText('edge-pod')).toBeInTheDocument();
    expect(within(section).getByText('Podman pod ID')).toBeInTheDocument();
    expect(within(section).getByText('pod-123')).toBeInTheDocument();
    expect(within(section).getByText('Podman infra')).toBeInTheDocument();
    expect(within(section).getByText('Yes')).toBeInTheDocument();
    expect(within(section).getByText('Compose project')).toBeInTheDocument();
    expect(within(section).getByText('orion')).toBeInTheDocument();
    expect(within(section).queryByText('legacy-project')).not.toBeInTheDocument();
    expect(within(section).getByText('Compose service')).toBeInTheDocument();
    expect(within(section).getByText('Auto-update')).toBeInTheDocument();
    expect(within(section).getByText('registry')).toBeInTheDocument();
    expect(within(section).getByText('User namespace')).toBeInTheDocument();
    expect(within(section).getByText('keep-id')).toBeInTheDocument();
    expect(within(section).getByText('Block I/O read')).toBeInTheDocument();
    expect(within(section).getByText('1.00 MB')).toBeInTheDocument();
    expect(within(section).getByText('Block I/O write')).toBeInTheDocument();
    expect(within(section).getByText('2.00 MB')).toBeInTheDocument();
    expect(within(section).getByText('Labels')).toBeInTheDocument();
    expect(within(section).getByText(/traefik\.enable/)).toBeInTheDocument();
  });

  it('offers the update and the new image beside an available update in Worth checking', () => {
    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        resource={resource({
          id: 'app-container-proxy',
          name: 'edge-proxy',
          docker: {
            hostSourceId: 'agent-edge',
            containerId: 'proxy123',
            containerState: 'running',
            image: 'nginx:1.27',
            updateStatus: {
              updateAvailable: true,
              currentDigest: 'sha256:current',
              latestDigest: 'sha256:latest',
              lastChecked: '2026-10-14T10:00:00Z',
            },
          },
          capabilities: [UPDATE_CAPABILITY],
        })}
      />
    ));
    const lifted = screen.getByTestId('resource-drawer-exceptions');
    expect(within(lifted).getByText('Image update')).toBeInTheDocument();
    expect(within(lifted).getByText('Available')).toBeInTheDocument();
    // The same update control the containers table offers, so a phone, whose
    // row hides the Updates column, can still act.
    // (System settings never load here, so it shows its loading state.)
    expect(within(lifted).getByRole('button')).toHaveTextContent('Update');
    expect(within(lifted).getByRole('link', { name: 'View image tags' })).toHaveAttribute(
      'href',
      expect.stringContaining('nginx'),
    );
  });

  it('keeps an open update review through resource refreshes and clock ticks', async () => {
    markSystemSettingsLoadedWithDefaults();
    vi.useFakeTimers();
    try {
      const proxy = (cpu: number) =>
        resource({
          id: 'app-container-proxy',
          name: 'edge-proxy',
          cpu: { current: cpu },
          docker: {
            hostSourceId: 'agent-edge',
            containerId: 'proxy123',
            containerState: 'running',
            image: 'nginx:1.27',
            createdAt: '2026-10-01T10:00:00Z',
            updateStatus: { updateAvailable: true, lastChecked: '2026-10-14T10:00:00Z' },
          },
          capabilities: [UPDATE_CAPABILITY],
        });
      const [current, setCurrent] = createSignal(proxy(10));
      render(() => <ResourceDetailDrawer presentation="table-row" resource={current()} />);
      fireEvent.click(within(screen.getByTestId('resource-drawer-exceptions')).getByRole('button'));
      await vi.advanceTimersByTimeAsync(0);
      const dialog = await screen.findByRole('dialog');
      setCurrent(proxy(20));
      await vi.advanceTimersByTimeAsync(61_000);
      expect(screen.getByRole('dialog')).toBe(dialog);
      expect(dialog.isConnected).toBe(true);
    } finally {
      vi.useRealTimers();
    }
  });

  it('says why Pulse cannot apply an update that is refused, at a tappable size', () => {
    markSystemSettingsLoadedWithDefaults();
    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        resource={resource({
          id: 'app-container-proxy',
          name: 'edge-proxy',
          actionReadiness: [
            { name: 'update', available: false, reason: 'Command agent disconnected' },
          ],
          docker: {
            hostSourceId: 'agent-edge',
            containerId: 'proxy123',
            containerState: 'running',
            image: 'nginx:1.27',
            updateStatus: { updateAvailable: true, lastChecked: '2026-10-14T10:00:00Z' },
          },
        })}
      />
    ));
    const lifted = screen.getByTestId('resource-drawer-exceptions');
    const locked = within(lifted).getByLabelText(
      /Pulse cannot apply it: Command agent disconnected/,
    );
    expect(locked).toHaveTextContent('Update');
    expect(locked).toHaveClass('max-sm:min-h-11');
    expect(within(lifted).queryByRole('button')).toBeNull();
  });

  it('keeps the same update control through resource refreshes and clock ticks', async () => {
    vi.useFakeTimers();
    try {
      const proxy = (cpu: number) =>
        resource({
          id: 'app-container-proxy',
          name: 'edge-proxy',
          cpu: { current: cpu },
          docker: {
            hostSourceId: 'agent-edge',
            containerId: 'proxy123',
            containerState: 'running',
            image: 'nginx:1.27',
            createdAt: '2026-10-01T10:00:00Z',
            updateStatus: { updateAvailable: true, lastChecked: '2026-10-14T10:00:00Z' },
          },
          capabilities: [UPDATE_CAPABILITY],
        });
      const [current, setCurrent] = createSignal(proxy(10));
      render(() => <ResourceDetailDrawer presentation="table-row" resource={current()} />);
      const button = () =>
        within(screen.getByTestId('resource-drawer-exceptions')).getByRole('button');
      const first = button();
      // A fresh snapshot of the same container, then the shared clock moving
      // its ages: the rows rebuild, the control (and any open review) stays.
      setCurrent(proxy(20));
      await vi.advanceTimersByTimeAsync(61_000);
      expect(button()).toBe(first);
      expect(first.isConnected).toBe(true);
    } finally {
      vi.useRealTimers();
    }
  });

  it('names a failing health check apart from the running state', () => {
    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        resource={resource({
          id: 'app-container-api',
          name: 'edge-api',
          uptime: 3600,
          docker: {
            containerId: 'def456abc123',
            containerState: 'running',
            health: 'unhealthy',
            uptimeSeconds: 3600,
          },
        })}
      />
    ));

    // The header dot agrees with the row: running but unhealthy is red, not green.
    const dot = screen.getByRole('img', { name: 'Unhealthy' });
    expect(dot).toHaveClass('bg-red-500');
    const runtime = screen.getByTestId('resource-runtime-context-section');
    expect(within(runtime).getByText('Running')).toBeInTheDocument();
    // The failing check is lifted into Worth checking, in front of the charts.
    const lifted = screen.getByTestId('resource-drawer-exceptions');
    expect(within(lifted).getByText('Health check')).toBeInTheDocument();
    const health = within(lifted).getByText('Failing');
    expect(health.closest('td')).toHaveClass('text-rose-700');
    expect(within(runtime).queryByText('Failing')).not.toBeInTheDocument();
    expect(health.closest('td')).toHaveAttribute('title', 'Its health check is failing');
    expect(within(runtime).getByText('Uptime')).toBeInTheDocument();
  });

  it('shows a stopped container its exit code without stale health or uptime', () => {
    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        resource={resource({
          id: 'app-container-worker',
          name: 'edge-worker',
          uptime: 184_082,
          docker: {
            containerId: 'abc999def000',
            containerState: 'exited',
            exitCode: 1,
            health: 'unhealthy',
            uptimeSeconds: 184_082,
          },
        })}
      />
    ));

    // A failed exit is red in the header, and its stale health check says nothing.
    expect(screen.getByRole('img', { name: 'Exited (1)' })).toHaveClass('bg-red-500');
    const runtime = screen.getByTestId('resource-runtime-context-section');
    const lifted = screen.getByTestId('resource-drawer-exceptions');
    expect(within(lifted).getByText('Exited (1)').closest('td')).toHaveClass('text-rose-700');
    expect(within(runtime).queryByText('Health check')).not.toBeInTheDocument();
    expect(within(runtime).queryByText('Uptime')).not.toBeInTheDocument();
  });

  it('links update targets to a reliable public registry tags page', () => {
    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        resource={resource({
          id: 'app-container-web',
          name: 'edge-web',
          docker: {
            containerId: 'abc123def456',
            containerState: 'running',
            image: 'docker.io/library/nginx:latest',
            updateStatus: {
              updateAvailable: true,
              currentDigest: 'sha256:current',
              latestDigest: 'sha256:target',
              lastChecked: '2026-05-24T13:00:00Z',
            },
          },
        })}
      />
    ));

    const section = screen.getByTestId('resource-docker-container-section');
    expect(within(section).getByText('Release information')).toBeInTheDocument();
    expect(within(section).getByRole('link', { name: 'View image tags' })).toHaveAttribute(
      'href',
      'https://hub.docker.com/_/nginx/tags',
    );
  });

  it('does not render the container section for non-container resources', () => {
    render(() => (
      <ResourceDetailDrawer
        presentation="table-row"
        resource={resource({
          id: 'docker-volume-1',
          type: 'docker-volume',
          name: 'app-data',
          docker: { volumeName: 'app-data', driver: 'local', createdAt: '2026-04-13T01:14:01Z' },
        })}
      />
    ));

    expect(screen.queryByTestId('resource-docker-container-section')).not.toBeInTheDocument();
  });
});