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.

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

import { ResourceActionsAPI } from '@/api/resourceActions';
import { WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH } from '@/components/Workloads/guestRowModel';
import type { Resource } from '@/types/resource';
import { DockerContainersTable } from '../DockerContainersTable';
import { DockerConfigsTable } from '../DockerConfigsTable';
import { DockerImagesTable } from '../DockerImagesTable';
import { DockerNetworksTable } from '../DockerNetworksTable';
import { DockerSecretsTable } from '../DockerSecretsTable';
import { DockerServicesTable } from '../DockerServicesTable';
import { DockerStorageUsageTable } from '../DockerStorageUsageTable';
import { DockerSwarmNodesTable } from '../DockerSwarmNodesTable';
import { DockerTasksTable } from '../DockerTasksTable';
import { DockerVolumesTable } from '../DockerVolumesTable';

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

// Pass-through spy on the real threshold lookup, so a test can see which
// override ids a table asked for.
const getMetricThresholdsSpy = vi.hoisted(() => vi.fn());
vi.mock('@/stores/alertsActivation', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@/stores/alertsActivation')>();
  return {
    ...actual,
    useAlertsActivation: () => {
      const store = actual.useAlertsActivation();
      return {
        ...store,
        getMetricThresholds: (...args: Parameters<typeof store.getMetricThresholds>) => {
          getMetricThresholdsSpy(...args);
          return store.getMetricThresholds(...args);
        },
      };
    },
  };
});

vi.mock('@/api/resourceActions', () => ({
  ResourceActionsAPI: {
    planAction: vi.fn().mockResolvedValue({
      actionId: 'action-1',
      requestId: 'request-1',
      allowed: true,
      requiresApproval: true,
      approvalPolicy: 'admin',
      rollbackAvailable: false,
      plannedAt: '2026-06-12T20:00:00Z',
      expiresAt: '2026-06-12T20:05:00Z',
      resourceVersion: 'resource-version',
      policyVersion: 'policy-version',
      planHash: 'plan-hash',
    }),
    decideAction: vi.fn().mockResolvedValue({
      actionId: 'action-1',
      state: 'approved',
      approval: {
        actor: 'operator',
        method: 'api',
        timestamp: '2026-06-12T20:00:01Z',
        outcome: 'approved',
      },
      audit: {},
    }),
    executeAction: vi.fn().mockResolvedValue({
      actionId: 'action-1',
      state: 'completed',
      result: { success: true },
      audit: {},
    }),
    getAction: vi.fn().mockResolvedValue({
      audit: {
        id: 'action-1',
        createdAt: '2026-06-12T20:00:00Z',
        updatedAt: '2026-06-12T20:00:00Z',
        state: 'pending_approval',
        decisionRevision: 0,
        request: {
          requestId: 'request-1',
          resourceId: 'container-1',
          capabilityName: 'restart',
          reason: 'restart Docker container edge-web',
          requestedBy: 'ui:docker-page',
        },
        plan: {
          actionId: 'action-1',
          requestId: '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(),
  },
}));

vi.mock('@/stores/containerUpdates', () => ({
  clearContainerUpdateState: vi.fn(),
  getContainerUpdateState: vi.fn(() => undefined),
  markContainerQueued: vi.fn(),
  markContainerUpdateError: vi.fn(),
  markContainerUpdateSuccess: vi.fn(),
  updateStates: vi.fn(() => ({})),
}));

vi.mock('@/stores/systemSettings', () => ({
  areSystemSettingsLoaded: () => true,
  shouldHideDockerUpdateActions: () => false,
}));

// jsdom has no ResizeObserver; stub the shared metric cells like the
// DockerHostsTable tests do.
vi.mock('@/components/shared/responsive', () => ({
  ResponsiveMetricCell: (props: {
    type: string;
    isRunning?: boolean;
    resourceId?: string;
    thresholds?: { warning: number; critical: number } | null;
  }) => (
    <div
      data-testid={`responsive-${props.type}-metric`}
      data-resource-id={props.resourceId ?? ''}
      data-running={String(props.isRunning)}
      data-thresholds={
        props.thresholds ? `${props.thresholds.warning}/${props.thresholds.critical}` : ''
      }
    />
  ),
}));

vi.mock('@/components/Workloads/StackedMemoryBar', () => ({
  StackedMemoryBar: (props: { used: number; total: number; percentOnly?: number }) => (
    <div
      data-testid="stacked-memory-bar"
      data-used={String(props.used)}
      data-total={String(props.total)}
      data-percent-only={String(props.percentOnly ?? '')}
    />
  ),
}));

const makeResource = ({
  id,
  type,
  ...overrides
}: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource => ({
  id,
  name: id,
  displayName: id,
  platformId: 'docker-1',
  platformType: 'docker',
  sourceType: 'agent',
  sources: ['docker'],
  status: 'online',
  type,
  lastSeen: 1_700_000_000_000,
  ...overrides,
});

// DockerContainersTable URL-backs its host scope filter (useSearchParams), so
// it must render inside a Router context.
const renderInRouter = (component: () => JSX.Element) =>
  render(() => (
    <Router>
      <Route path="/" component={component} />
    </Router>
  ));

const setViewportWidth = (width: number) => {
  Object.defineProperty(window, 'innerWidth', {
    configurable: true,
    writable: true,
    value: width,
  });
};

afterEach(() => {
  window.history.pushState({}, '', '/');
  setViewportWidth(1024);
  window.localStorage.clear();
  cleanup();
  vi.clearAllMocks();
});

describe('Docker native tables', () => {
  it('offers bulk web-link editing keyed by the container drawer identity', async () => {
    // The trigger and panel are lazy-loaded; transform them up front so they resolve promptly.
    await import('@/components/Workloads/WorkloadWebLinksAction');
    await import('@/components/Workloads/WorkloadWebLinksDialog');
    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            customUrl: 'https://edge-web.example',
            docker: {
              hostSourceId: 'docker-host-edge',
              containerId: 'native-container-1',
              hostname: 'edge-01',
              image: 'nginx:latest',
              containerState: 'running',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    fireEvent.click(await screen.findByRole('button', { name: 'Edit links' }));
    const dialog = within(await screen.findByRole('dialog', { name: 'Web links' }));
    const input = dialog.getByLabelText(/edge-web/);

    expect(dialog.getByText(/for each container/)).toBeInTheDocument();
    expect(input).toHaveValue('https://edge-web.example');
    expect(input).toHaveAttribute(
      'data-metadata-id',
      'app-container:docker-host-edge:name:edge-web',
    );
    expect(dialog.getByText('edge-01 · nginx:latest')).toBeInTheDocument();
  }, 30_000);

  it('renders Docker container API fields', () => {
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            cpu: { current: 42 },
            memory: { current: 50, used: 512 * 1024 * 1024, total: 1024 * 1024 * 1024 },
            docker: {
              agentId: 'agent-1',
              hostname: 'edge-01',
              runtime: 'docker',
              runtimeVersion: '27.5.1',
              image: 'nginx:latest',
              containerState: 'running',
              health: 'healthy',
              restartCount: 2,
              ports: [{ ip: '0.0.0.0', publicPort: 8080, privatePort: 80, protocol: 'tcp' }],
              networks: [{ name: 'frontend', ipv4: '172.18.0.2' }],
              mounts: [
                {
                  type: 'volume',
                  source: 'nginx-html',
                  destination: '/usr/share/nginx/html',
                  mode: 'rw',
                  rw: true,
                },
              ],
              updateStatus: {
                updateAvailable: true,
                currentDigest: 'sha256:current',
                latestDigest: 'sha256:latest',
                lastChecked: '2026-05-24T13:00:00Z',
              },
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: {
              agentId: 'agent-2',
              hostname: 'edge-02',
              runtime: 'podman',
              runtimeVersion: '5.2.1',
              image: 'redis:7.4',
              containerState: 'running',
              health: 'healthy',
              restartCount: 7,
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Container')).toBeInTheDocument();
    // Grouped by host, the engine and host move to the group header.
    expect(screen.queryByText('Engine')).not.toBeInTheDocument();
    expect(screen.getByText('CPU')).toBeInTheDocument();
    expect(screen.getByText('Memory')).toBeInTheDocument();
    expect(screen.getByText('Restarts')).toBeInTheDocument();
    expect(screen.getByText('Updates')).toBeInTheDocument();
    expect(screen.getByText('Actions')).toBeInTheDocument();
    expect(screen.queryByText('Health')).not.toBeInTheDocument();
    expect(screen.queryByText('State')).not.toBeInTheDocument();
    expect(screen.getByText('edge-web')).toBeInTheDocument();
    // Multi-host fleets group by host by default, so the host name renders
    // once, in the group header row, instead of again on every container.
    expect(screen.getAllByText('edge-01')).toHaveLength(1);
    expect(screen.getByText('docker 27.5.1')).toBeInTheDocument();
    expect(screen.getByText('podman 5.2.1')).toBeInTheDocument();
    expect(screen.getByText('nginx:latest')).toBeInTheDocument();
    expect(screen.getByText('2')).toBeInTheDocument();
    // The cell drops the all-interfaces address; the title keeps the full form.
    expect(screen.getByText('8080->80/tcp')).toHaveAttribute('title', '0.0.0.0:8080->80/tcp');
    expect(screen.getByText('frontend 172.18.0.2')).toBeInTheDocument();
    expect(screen.getByText('volume:/usr/share/nginx/html (rw)')).toBeInTheDocument();
    expect(screen.getByText('Available')).toBeInTheDocument();

    // A crash-looper (restarts above the v5 attention threshold) is flagged in
    // amber, the colour its row dot shows: running, but worth a look.
    expect(screen.getByText('7')).toHaveClass('text-amber-700');
    expect(screen.getByText('2')).not.toHaveClass('text-amber-700');
    expect(screen.getByTitle('7 restarts')).toBeInTheDocument();

    // Both rows get a CPU cell; only the row with memory data gets a bar.
    expect(screen.getAllByTestId('responsive-cpu-metric').length).toBe(2);
    expect(screen.getByTestId('container-table-cpu-scale')).toHaveTextContent(
      'CPU is a percentage of total host capacity: 100% means all host CPUs.',
    );
    expect(screen.getByTestId('container-table-cpu-scale')).toHaveTextContent(
      'Docker and Podman stats may use a per-core scale.',
    );
    expect(screen.getByTestId('stacked-memory-bar')).toHaveAttribute(
      'data-used',
      String(512 * 1024 * 1024),
    );
  });

  it('hides the Engine column when every container reports the same runtime', () => {
    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              runtime: 'docker',
              runtimeVersion: '27.5.1',
              image: 'nginx:latest',
              containerState: 'running',
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: {
              hostname: 'edge-02',
              runtime: 'docker',
              runtimeVersion: '27.5.1',
              image: 'redis:7.4',
              containerState: 'running',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.queryByText('Engine')).not.toBeInTheDocument();
    // Each host group header still names its engine once.
    expect(screen.getAllByText('docker 27.5.1')).toHaveLength(2);
  });

  it('applies the URL host scope to container rows', () => {
    window.history.pushState({}, '', '/?host=edge-02');

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              runtime: 'docker',
              image: 'nginx:latest',
              containerState: 'running',
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: {
              hostname: 'edge-02',
              runtime: 'docker',
              image: 'redis:7.4',
              containerState: 'running',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('edge-cache')).toBeInTheDocument();
    // Scoped to edge-02: the group header names the host once.
    expect(screen.getAllByText('edge-02')).toHaveLength(1);
    expect(screen.queryByText('edge-web')).not.toBeInTheDocument();
    expect(screen.queryByText('edge-01')).not.toBeInTheDocument();
  });

  it('groups containers under host headers with counts and host web links', () => {
    const { container } = renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', image: 'nginx:latest', containerState: 'running' },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: { hostname: 'edge-02', image: 'redis:7.4', containerState: 'running' },
          }),
          makeResource({
            id: 'container-3',
            type: 'app-container',
            name: 'edge-proxy',
            status: 'running',
            docker: { hostname: 'edge-01', image: 'traefik:v3', containerState: 'running' },
          }),
        ]}
        hosts={[
          makeResource({
            id: 'host-1',
            type: 'docker-host',
            name: 'edge-01',
            status: 'online',
            customUrl: 'https://edge-01.example:9443',
            docker: { hostname: 'edge-01' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    const headers = [...container.querySelectorAll('[data-docker-host-group]')];
    expect(headers.map((row) => row.getAttribute('data-docker-host-group'))).toEqual([
      'edge-01',
      'edge-02',
    ]);
    expect(within(headers[0] as HTMLElement).getByText('2 containers')).toBeInTheDocument();
    expect(within(headers[1] as HTMLElement).getByText('1 container')).toBeInTheDocument();
    // Host resource provides the group header's web interface link.
    const hostLink = within(headers[0] as HTMLElement).getByRole('link', {
      name: 'Open web interface for edge-01',
    });
    expect(hostLink).toHaveAttribute('href', 'https://edge-01.example:9443');
  });

  it('renders a flat list when only one host is present', () => {
    const { container } = renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', image: 'nginx:latest', containerState: 'running' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(container.querySelector('[data-docker-host-group]')).toBeNull();
  });

  it('offers no layout choice in the View menu for a single-host inventory', () => {
    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', image: 'nginx:latest', containerState: 'running' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
      />
    ));

    // The View menu always carries the shared inventory-totals toggle, but a
    // single-host inventory must not offer host grouping.
    fireEvent.click(screen.getByRole('button', { name: 'View' }));

    const dialog = screen.getByRole('region', { name: 'View preferences' });
    expect(within(dialog).getByText('Inventory totals')).toBeInTheDocument();
    expect(within(dialog).queryByText('Layout')).not.toBeInTheDocument();
    expect(within(dialog).queryByRole('group', { name: 'Group by' })).not.toBeInTheDocument();
  });

  it('honors a persisted flat preference for multi-host fleets', () => {
    window.localStorage.setItem('dockerContainersGroupingMode', 'flat');

    const { container } = renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', image: 'nginx:latest', containerState: 'running' },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: { hostname: 'edge-02', image: 'redis:7.4', containerState: 'running' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(container.querySelector('[data-docker-host-group]')).toBeNull();
  });

  it('keeps Docker grouping inside the shared View preferences disclosure', () => {
    const { container } = renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', image: 'nginx:latest', containerState: 'running' },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: { hostname: 'edge-02', image: 'redis:7.4', containerState: 'running' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
      />
    ));

    expect(screen.getByRole('button', { name: 'View' })).toBeInTheDocument();
    expect(screen.queryByRole('group', { name: 'Group by' })).not.toBeInTheDocument();

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

    const dialog = screen.getByRole('region', { name: 'View preferences' });
    expect(within(dialog).getByText('Layout')).toBeInTheDocument();
    expect(within(dialog).getByRole('group', { name: 'Group by' })).toBeInTheDocument();
    fireEvent.click(within(dialog).getByRole('button', { name: 'List' }));
    expect(container.querySelector('[data-docker-host-group]')).toBeNull();
    expect(window.localStorage.getItem('dockerContainersGroupingMode')).toBe('flat');
  });

  it('renders a distinct container launch control without linking the name', () => {
    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            customUrl: 'http://edge-01.example:8080',
            docker: { hostname: 'edge-01', image: 'nginx:latest', containerState: 'running' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    const launchLink = screen.getByRole('link', { name: 'Open web interface for edge-web' });
    expect(launchLink).toHaveAttribute('href', 'http://edge-01.example:8080');
    expect(screen.getByText('edge-web').closest('a')).toBeNull();
  });

  it('applies the URL search filter, including -term exclusions, to container rows', () => {
    window.history.pushState({}, '', '/?q=-redis');

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              runtime: 'docker',
              image: 'nginx:latest',
              containerState: 'running',
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: {
              hostname: 'edge-02',
              runtime: 'docker',
              image: 'redis:7.4',
              containerState: 'running',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('edge-web')).toBeInTheDocument();
    expect(screen.queryByText('edge-cache')).not.toBeInTheDocument();
  });

  it('preserves grouped search drawer history state when a live snapshot replaces resources', async () => {
    window.history.pushState({}, '', '/?q=nginx');
    const makeContainers = (restartCount: number) => [
      makeResource({
        id: 'container-1',
        type: 'app-container',
        name: 'nginx',
        status: 'running',
        metricsTarget: { resourceType: 'app-container', resourceId: 'container-1' },
        docker: {
          hostname: 'edge-01',
          image: 'nginx:latest',
          containerState: 'running',
          restartCount,
        },
      }),
      makeResource({
        id: 'container-2',
        type: 'app-container',
        name: 'redis',
        status: 'running',
        metricsTarget: { resourceType: 'app-container', resourceId: 'container-2' },
        docker: {
          hostname: 'edge-02',
          image: 'redis:7.4',
          containerState: 'running',
        },
      }),
    ];
    const [resources, setResources] = createSignal(makeContainers(0));

    renderInRouter(() => (
      <DockerContainersTable
        resources={resources()}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
      />
    ));

    fireEvent.click(screen.getByRole('button', { name: 'Expand details for nginx' }));
    const historyRange = await screen.findByRole('combobox', { name: 'History range' });
    fireEvent.change(historyRange, { target: { value: '1h' } });
    fireEvent.click(screen.getByRole('tab', { name: 'Manage' }));

    expect(screen.getByRole('tab', { name: 'Manage' })).toHaveAttribute('aria-selected', 'true');
    expect(historyRange).toHaveValue('1h');

    setResources(makeContainers(1));

    await waitFor(() =>
      expect(screen.getByRole('tab', { name: 'Manage' })).toHaveAttribute('aria-selected', 'true'),
    );
    fireEvent.click(screen.getByRole('tab', { name: 'Overview' }));
    expect(screen.getByRole('combobox', { name: 'History range' })).toHaveValue('1h');
    expect(screen.getByRole('button', { name: 'Collapse details for nginx' })).toBeInTheDocument();
  });

  it('applies the URL status filter to container rows', () => {
    window.history.pushState({}, '', '/?status=offline');

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              runtime: 'docker',
              image: 'nginx:latest',
              containerState: 'running',
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'offline',
            docker: {
              hostname: 'edge-02',
              runtime: 'docker',
              image: 'redis:7.4',
              containerState: 'exited',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('edge-cache')).toBeInTheDocument();
    expect(screen.queryByText('edge-web')).not.toBeInTheDocument();
  });

  it('clears search, status, and host in one navigation when resetting filters', async () => {
    window.history.pushState({}, '', '/?q=-redis&status=offline&host=edge-01');

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              runtime: 'docker',
              image: 'nginx:latest',
              containerState: 'running',
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'offline',
            docker: {
              hostname: 'edge-02',
              runtime: 'docker',
              image: 'redis:7.4',
              containerState: 'exited',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
      />
    ));

    fireEvent.click(screen.getByLabelText('Clear filters'));

    // Reset must be a single setSearchParams write: consecutive writes each
    // merge against the pre-navigation URL (the router commits inside an
    // async transition), so a per-param reset resurrects the params cleared
    // by the earlier writes.
    await waitFor(() => expect(window.location.search).toBe(''));
    expect(screen.getByText('edge-web')).toBeInTheDocument();
    expect(screen.getByText('edge-cache')).toBeInTheDocument();
  });

  it('hides the Restarts column when the current containers have no restart signal', () => {
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              image: 'nginx:latest',
              containerState: 'running',
              restartCount: 0,
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'running',
            docker: {
              hostname: 'edge-02',
              image: 'redis:7.4',
              containerState: 'running',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.queryByText('Restarts')).not.toBeInTheDocument();
  });

  it('shows the State column when any current container is not running', () => {
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              image: 'nginx:latest',
              containerState: 'running',
            },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'offline',
            docker: {
              hostname: 'edge-02',
              image: 'redis:7.4',
              containerState: 'exited',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('State')).toBeInTheDocument();
    expect(screen.getByText('Exited')).toBeInTheDocument();
  });

  it('shows the State column for a running container whose health check fails', () => {
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', containerState: 'running', health: 'healthy' },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-api',
            status: 'running',
            docker: { hostname: 'edge-01', containerState: 'running', health: 'unhealthy' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('State')).toBeInTheDocument();
    const unhealthy = screen.getByText('Unhealthy');
    expect(unhealthy).toHaveAttribute('data-docker-container-state', 'danger');
    expect(unhealthy).toHaveAttribute('title', 'Running, but its health check is failing');
    expect(screen.getByText('Healthy')).toHaveAttribute('data-docker-container-state', 'ok');
  });

  it.each([320, WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH])(
    'updates the same container row dot across health and lifecycle refreshes at %ipx',
    (width) => {
      setViewportWidth(width);
      const [resources, setResources] = createStore<Resource[]>([
        makeResource({
          id: 'container-health',
          type: 'app-container',
          name: 'edge-api',
          status: 'running',
          docker: { hostname: 'edge-01', containerState: 'running', health: 'healthy' },
        }),
      ]);
      const { container } = renderInRouter(() => (
        <DockerContainersTable
          resources={resources}
          emptyIcon={<span />}
          emptyTitle="No containers"
          emptyDescription="No containers"
          showToolbar={false}
        />
      ));
      const row = container.querySelector('[data-docker-container-row="container-health"]')!;
      const initialResource = resources[0];
      expect(within(row as HTMLElement).getByTitle('Healthy')).toHaveClass('bg-emerald-500');

      for (const [health, label, colour] of [
        ['starting', 'Starting', 'bg-amber-500'],
        ['unhealthy', 'Unhealthy', 'bg-red-500'],
        ['healthy', 'Healthy', 'bg-emerald-500'],
      ]) {
        setResources(0, 'docker', 'health', health);
        expect(resources[0]).toBe(initialResource);
        expect(container.querySelector('[data-docker-container-row="container-health"]')).toBe(row);
        expect(within(row as HTMLElement).getByTitle(label)).toHaveClass(colour);
        if (health === 'healthy' && width === WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH) {
          // Wide tables drop the State column when every row is healthy;
          // the still-mounted dot, asserted above, carries that verdict.
          expect(within(row as HTMLElement).queryByText('Healthy')).not.toBeInTheDocument();
          expect(screen.queryByRole('columnheader', { name: /State/ })).not.toBeInTheDocument();
        } else {
          expect(within(row as HTMLElement).getByText(label)).toHaveAttribute(
            'data-docker-container-state',
            health === 'unhealthy' ? 'danger' : health === 'starting' ? 'warning' : 'ok',
          );
        }
      }

      setResources(0, 'docker', 'containerState', 'exited');
      setResources(0, 'docker', 'exitCode', 137);
      expect(within(row as HTMLElement).getByTitle('Exited (137)')).toHaveClass('bg-red-500');
      setResources(0, 'docker', 'containerState', 'restarting');
      expect(within(row as HTMLElement).getByTitle('Restarting')).toHaveClass('bg-amber-500');
      setResources(0, 'docker', 'containerState', 'exited');
      setResources(0, 'docker', 'exitCode', 0);
      expect(within(row as HTMLElement).getByTitle('Exited')).toHaveClass('bg-slate-400');
    },
  );

  it('puts state words that need attention beside the name where a phone row has no State column', () => {
    // A narrow table cannot give "Unhealthy" its own column beside the 40%
    // name, both metric pills and the Update control without cutting it.
    setViewportWidth(320);

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', containerState: 'running' },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-api',
            status: 'running',
            docker: { hostname: 'edge-01', containerState: 'running', health: 'unhealthy' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.queryByRole('columnheader', { name: /State/ })).not.toBeInTheDocument();
    const unhealthy = screen.getByText('Unhealthy');
    expect(unhealthy).toHaveAttribute('data-docker-container-state', 'danger');
    expect(unhealthy.closest('td')).toBe(screen.getByText('edge-api').closest('td'));
    // The words join the name on its line, so the row stays one line tall.
    expect(unhealthy).toHaveClass('min-w-0', 'truncate', 'shrink-0');
    expect(unhealthy.parentElement).toHaveClass('items-center');
    expect(unhealthy.parentElement).not.toHaveClass('flex-col');
    // A running container reads in its green dot; screen readers keep the words.
    const running = screen.getByText('Running');
    expect(running.closest('td')).toBe(screen.getByText('edge-web').closest('td'));
    expect(running).toHaveClass('sr-only');
  });

  it('keeps a saved State sort only where the State column shows', () => {
    window.localStorage.setItem('dockerContainersSortKey', 'state');
    window.localStorage.setItem('dockerContainersSortDirection', 'asc');
    const resources = [
      makeResource({
        id: 'container-1',
        type: 'app-container',
        name: 'edge-web',
        status: 'running',
        docker: { hostname: 'edge-01', containerState: 'running' },
      }),
      makeResource({
        id: 'container-2',
        type: 'app-container',
        name: 'edge-api',
        status: 'running',
        docker: { hostname: 'edge-01', containerState: 'running', health: 'unhealthy' },
      }),
    ];
    const rowOrder = () =>
      [...document.querySelectorAll('[data-docker-container-row]')].map((row) =>
        row.getAttribute('data-docker-container-row'),
      );
    const renderTable = () =>
      renderInRouter(() => (
        <DockerContainersTable
          resources={resources}
          emptyIcon={<span />}
          emptyTitle="No containers"
          emptyDescription="No containers"
          showToolbar={false}
        />
      ));

    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);
    renderTable();
    // "Running" sorts before "Unhealthy" while the header shows the sort.
    expect(rowOrder()).toEqual(['container-1', 'container-2']);
    cleanup();

    // A phone row has no State header to show the sort, so the rows keep the
    // attention-first order and the failing container leads.
    setViewportWidth(320);
    renderTable();
    expect(rowOrder()).toEqual(['container-2', 'container-1']);
    expect(window.localStorage.getItem('dockerContainersSortKey')).toBe('state');
  });

  it("shows each running container's uptime and none for a stopped one", () => {
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', containerState: 'running', uptimeSeconds: 90_000 },
          }),
          makeResource({
            id: 'container-2',
            type: 'app-container',
            name: 'edge-cache',
            status: 'offline',
            docker: {
              hostname: 'edge-01',
              containerState: 'exited',
              exitCode: 1,
              uptimeSeconds: 184_082,
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Uptime')).toBeInTheDocument();
    const runningRow = document.querySelector('[data-docker-container-row="container-1"]');
    const stoppedRow = document.querySelector('[data-docker-container-row="container-2"]');
    expect(runningRow?.textContent).toContain('1d');
    expect(stoppedRow?.textContent).not.toContain('2d');
    expect(screen.getByText('Exited (1)')).toHaveAttribute('data-docker-container-state', 'danger');
  });

  it('flags a crash-looping container in State where the Restarts column is hidden', () => {
    const rows = [
      makeResource({
        id: 'container-1',
        type: 'app-container',
        name: 'edge-web',
        status: 'running',
        docker: { hostname: 'edge-01', containerState: 'running', restartCount: 7 },
      }),
      makeResource({
        id: 'container-2',
        type: 'app-container',
        name: 'edge-api',
        status: 'running',
        docker: { hostname: 'edge-01', containerState: 'running', restartCount: 1 },
      }),
    ];
    // 600px is the mobile layout, which has no Restarts column.
    setViewportWidth(600);
    const { unmount } = renderInRouter(() => (
      <DockerContainersTable
        resources={rows}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));
    expect(screen.queryByText('Restarts')).not.toBeInTheDocument();
    expect(screen.getByText('7 restarts')).toHaveAttribute(
      'data-docker-container-state',
      'warning',
    );
    // State sorts by the words the row shows: "7 restarts" ranks apart from
    // "Running" both ways (with equal labels both orders would be the same).
    const rowOrder = () =>
      [...document.querySelectorAll('[data-docker-container-row]')].map((row) =>
        row.getAttribute('data-docker-container-row'),
      );
    const clickState = () => {
      const header = screen
        .getAllByRole('columnheader')
        .find((th) => th.textContent?.trim().startsWith('State'));
      fireEvent.click(header!.querySelector('button') ?? header!);
    };
    clickState();
    expect(rowOrder()).toEqual(['container-1', 'container-2']);
    clickState();
    expect(rowOrder()).toEqual(['container-2', 'container-1']);
    unmount();

    // A wide table shows the count in its own column instead.
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);
    renderInRouter(() => (
      <DockerContainersTable
        resources={rows}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));
    expect(screen.getByText('Restarts')).toBeInTheDocument();
    expect(screen.queryByText('7 restarts')).not.toBeInTheDocument();
    // The row dot carries the same verdict at every width.
    expect(screen.getByTitle('7 restarts')).toBeInTheDocument();
  });

  it('leaves out the Uptime column when no container reports one', () => {
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: { hostname: 'edge-01', containerState: 'running' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    expect(screen.queryByText('Uptime')).not.toBeInTheDocument();
  });

  it('renders actionable Docker container updates with native agent and container IDs', async () => {
    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              hostSourceId: 'agent-edge',
              containerId: 'native-container-1',
              hostname: 'edge-01',
              image: 'nginx:latest',
              containerState: 'running',
              updateStatus: {
                updateAvailable: true,
                currentDigest: 'sha256:current',
                latestDigest: 'sha256:latest',
                lastChecked: '2026-05-24T13:00:00Z',
              },
            },
            capabilities: [
              { name: 'update', type: 'common', platform: 'docker', minimumApprovalLevel: 'admin' },
            ],
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    // One click plans the governed action; the review dialog is the
    // confirmation surface, so no second in-row confirm click exists.
    const updateButton = screen.getByRole('button', { name: /click to review and update/i });
    // The phone reflow boundary must include the governed action, not just read-only badges.
    expect(updateButton.closest('td')).toHaveClass('docker-container-update-cell');
    expect(updateButton).toHaveTextContent('Update');
    // The table keeps the compact pill; only the drawer asks for a phone target.
    expect(updateButton).not.toHaveClass('max-sm:min-h-11');
    fireEvent.click(updateButton);

    await waitFor(() =>
      expect(ResourceActionsAPI.planAction).toHaveBeenCalledWith(
        expect.objectContaining({
          resourceId: 'container-1',
          capabilityName: 'update',
          requestedBy: 'ui:container-update',
        }),
      ),
    );
    expect(await screen.findByRole('dialog')).toBeInTheDocument();
    expect(ResourceActionsAPI.decideAction).not.toHaveBeenCalled();
    expect(ResourceActionsAPI.executeAction).not.toHaveBeenCalled();
  });

  it('opens canonical review on the first Docker lifecycle click without auto-approving or executing', async () => {
    const onLifecycleActionSettled = vi.fn();

    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              agentId: 'agent-edge',
              hostSourceId: 'docker-host-edge',
              containerId: 'native-container-1',
              hostname: 'edge-01',
              image: 'nginx:latest',
              runtime: 'docker',
              containerState: 'running',
            },
            capabilities: [
              {
                name: 'restart',
                type: 'common',
                platform: 'docker',
                minimumApprovalLevel: 'admin',
              },
              {
                name: 'stop',
                type: 'common',
                platform: 'docker',
                minimumApprovalLevel: 'admin',
              },
            ],
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
        onLifecycleActionSettled={onLifecycleActionSettled}
      />
    ));

    // The 28px menu button overhangs the row rather than setting a 37px row.
    expect(screen.getByRole('button', { name: 'Container actions for edge-web' })).toHaveClass(
      '-my-0.5',
      'h-7',
    );
    fireEvent.click(
      screen.getByRole('button', {
        name: 'Container actions for edge-web',
      }),
    );
    const lifecycleMenu = screen.getByRole('menu', {
      name: 'Container actions for edge-web',
    });
    const restartButton = screen.getByRole('menuitem', {
      name: 'Review restart for edge-web',
    });
    await waitFor(() =>
      expect(
        within(lifecycleMenu).getByRole('menuitem', { name: 'Review stop for edge-web' }),
      ).toHaveFocus(),
    );
    fireEvent.keyDown(restartButton, { key: 'Escape' });
    await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());
    const lifecycleTrigger = screen.getByRole('button', {
      name: 'Container actions for edge-web',
    });
    expect(lifecycleTrigger).toHaveFocus();
    fireEvent.keyDown(lifecycleTrigger, { key: 'ArrowUp' });
    await waitFor(() => expect(screen.getAllByRole('menuitem').at(-1)).toHaveFocus());
    fireEvent.click(
      screen.getByRole('menuitem', {
        name: 'Review restart for edge-web',
      }),
    );

    await waitFor(() =>
      expect(ResourceActionsAPI.planAction).toHaveBeenCalledWith(
        expect.objectContaining({
          resourceId: 'container-1',
          capabilityName: 'restart',
          requestedBy: 'ui:docker-page',
        }),
      ),
    );
    expect(await screen.findByRole('dialog', { name: 'Restart' })).toBeInTheDocument();
    expect(screen.getByText('Policy evidence unavailable')).toBeInTheDocument();
    expect(ResourceActionsAPI.decideAction).not.toHaveBeenCalled();
    expect(ResourceActionsAPI.executeAction).not.toHaveBeenCalled();
    expect(onLifecycleActionSettled).not.toHaveBeenCalled();
  });

  it('shows disabled Docker lifecycle buttons with explicit unavailable reasons', () => {
    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            status: 'running',
            docker: {
              agentId: 'agent-edge',
              containerId: 'native-container-1',
              hostname: 'edge-01',
              image: 'nginx:latest',
              runtime: 'docker',
              containerState: 'running',
            },
            sourceStatus: { docker: { status: 'stale' } },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    fireEvent.click(
      screen.getByRole('button', {
        name: 'Container actions for edge-web',
      }),
    );
    expect(
      screen.getByRole('menuitem', {
        name: 'Restart unavailable: Docker inventory is stale. Refresh inventory before running lifecycle actions.',
      }),
    ).toBeDisabled();
  });

  it('renders container rows with status mapped from containerState + health + exitCode, attention rows first', () => {
    renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'happy',
            type: 'app-container',
            docker: { containerState: 'running', health: 'healthy' },
          }),
          makeResource({
            id: 'dead',
            type: 'app-container',
            docker: { containerState: 'dead' },
          }),
          makeResource({
            id: 'restart',
            type: 'app-container',
            docker: { containerState: 'restarting' },
          }),
          makeResource({
            id: 'exited',
            type: 'app-container',
            docker: { containerState: 'exited', exitCode: 137 },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    const rows = Array.from(document.querySelectorAll('[data-docker-container-row]')).map((row) =>
      row.getAttribute('data-docker-container-row'),
    );
    // Two danger rows tied -> name-sorted; then warning; then success.
    expect(rows).toEqual(['dead', 'exited', 'restart', 'happy']);
    expect(screen.getByText('State')).toBeInTheDocument();
    expect(screen.getByTitle('Dead')).toHaveClass('bg-red-500');
    expect(screen.getByTitle('Exited (137)')).toHaveClass('bg-red-500');
    expect(screen.getByTitle('Restarting')).toHaveClass('bg-amber-500');
    expect(screen.getByTitle('Healthy')).toHaveClass('bg-emerald-500');
  });

  it('keeps the repository and tag of a container image visible', () => {
    setViewportWidth(WORKLOAD_TABLE_WIDE_LAYOUT_WIDTH);

    const { container } = renderInRouter(() => (
      <DockerContainersTable
        resources={[
          makeResource({
            id: 'container-ghcr',
            type: 'app-container',
            name: 'backup-coordinator',
            status: 'running',
            docker: {
              hostname: 'edge-01',
              image: 'ghcr.io/pulse-demo/backup-coordinator:2026.04',
              containerState: 'running',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No containers"
        emptyDescription="No containers"
        showToolbar={false}
      />
    ));

    // The container image cell shares the head/tail reference rendering with the
    // images and services tables: the shared registry head truncates, the
    // repository:tag tail stays visible, and the full reference is on the title.
    const reference = container.querySelector<HTMLElement>('[data-docker-image-reference]');
    expect(reference).not.toBeNull();
    expect(reference).toHaveAttribute('title', 'ghcr.io/pulse-demo/backup-coordinator:2026.04');
    expect(reference).toHaveTextContent('ghcr.io/pulse-demo/backup-coordinator:2026.04');
    expect(reference?.querySelector('[data-docker-image-reference-tail]')).toHaveTextContent(
      'backup-coordinator:2026.04',
    );
  });

  it('keeps the repository and tag of a registry-prefixed image name visible', () => {
    const { container } = render(() => (
      <DockerImagesTable
        resources={[
          makeResource({
            id: 'image-ghcr',
            type: 'docker-image',
            name: 'ghcr.io/pulse-demo/backup-coordinator:2026.04',
          }),
          makeResource({ id: 'image-hub', type: 'docker-image', name: 'postgres:16.4' }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No images"
        emptyDescription="No images"
        showToolbar={false}
      />
    ));

    // Images that share a registry and namespace differ only at the end, so a
    // narrow name cell truncates the shared head and keeps the tail visible.
    const references = [
      ...container.querySelectorAll<HTMLElement>('[data-docker-image-reference]'),
    ];
    const prefixed = references.find(
      (element) => element.title === 'ghcr.io/pulse-demo/backup-coordinator:2026.04',
    );
    expect(prefixed).toHaveTextContent('ghcr.io/pulse-demo/backup-coordinator:2026.04');
    expect(prefixed?.querySelector('[data-docker-image-reference-tail]')).toHaveTextContent(
      'backup-coordinator:2026.04',
    );
    const bare = references.find((element) => element.title === 'postgres:16.4');
    expect(bare).toHaveTextContent('postgres:16.4');
    expect(bare?.querySelector('[data-docker-image-reference-tail]')?.textContent).toBe('');

    // Head and tail are flex items, so a browser copy would put a line break
    // between them; a selection inside one reference copies as the reference.
    const copy = (selected: Node) => {
      const range = document.createRange();
      range.selectNodeContents(selected);
      window.getSelection()?.removeAllRanges();
      window.getSelection()?.addRange(range);
      const setData = vi.fn();
      const event = new Event('copy', { bubbles: true, cancelable: true });
      Object.defineProperty(event, 'clipboardData', { value: { setData } });
      prefixed!.dispatchEvent(event);
      return { setData, prevented: event.defaultPrevented };
    };
    const inside = copy(prefixed!);
    expect(inside.setData).toHaveBeenCalledWith(
      'text/plain',
      'ghcr.io/pulse-demo/backup-coordinator:2026.04',
    );
    expect(inside.prevented).toBe(true);
    const wider = copy(container);
    expect(wider.setData).not.toHaveBeenCalled();
    expect(wider.prevented).toBe(false);
  });

  it('renders Docker image API fields', () => {
    render(() => (
      <DockerImagesTable
        resources={[
          makeResource({
            id: 'image-1',
            type: 'docker-image',
            name: 'nginx:latest',
            docker: {
              hostname: 'edge-01',
              repoTags: ['nginx:latest', 'nginx:stable'],
              repoDigests: ['nginx@sha256:manifest'],
              sizeBytes: 805306368,
              imageContainers: 2,
            },
          }),
        ]}
        relatedContainers={[
          makeResource({
            id: 'container-1',
            type: 'app-container',
            name: 'edge-web',
            docker: {
              image: 'nginx:latest',
              updateStatus: {
                updateAvailable: true,
                currentDigest: 'sha256:current',
                latestDigest: 'sha256:latest',
              },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No images"
        emptyDescription="No images"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Used by')).toBeInTheDocument();
    expect(screen.getByText('Update check')).toBeInTheDocument();
    expect(screen.getByText('nginx:latest')).toBeInTheDocument();
    expect(screen.getByText('edge-web')).toBeInTheDocument();
    expect(screen.getByText('Update available')).toBeInTheDocument();
    expect(screen.queryByText('nginx@sha256:manifest')).not.toBeInTheDocument();
    expect(screen.getByText('edge-01')).toBeInTheDocument();
  });

  it('opens a failed image check from a named native button without toggling its row twice', () => {
    const error = 'authentication required (synthetic registry)';
    const { container } = render(() => (
      <DockerImagesTable
        resources={[
          makeResource({
            id: 'image-failed',
            type: 'docker-image',
            name: 'registry.example.invalid/team/web:latest',
            docker: {
              hostname: 'edge-01',
              image: 'registry.example.invalid/team/web:latest',
              updateStatus: { updateAvailable: false, error },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No images"
        emptyDescription="No images"
        showToolbar={false}
      />
    ));

    const button = screen.getByRole('button', {
      name: 'Check failed for registry.example.invalid/team/web:latest. Details',
    });
    expect(button).toHaveAttribute('type', 'button');
    expect(button.tabIndex).toBe(0);
    expect(button).toHaveAttribute('aria-expanded', 'false');
    expect(screen.queryByText(error)).not.toBeInTheDocument();
    button.focus();
    fireEvent.click(button);
    expect(button).toHaveFocus();
    expect(button).toHaveAttribute('aria-expanded', 'true');
    const detail = document.getElementById(button.getAttribute('aria-controls')!);
    expect(detail).toBeInTheDocument();
    expect(within(detail!).getByText(error)).toBeInTheDocument();
    expect(detail).toHaveTextContent('Host edge-01');
    expect(container.querySelectorAll('[data-inline-platform-resource-detail-for]')).toHaveLength(
      1,
    );
    fireEvent.click(button);
    expect(button).toHaveAttribute('aria-expanded', 'false');
    expect(screen.queryByText(error)).not.toBeInTheDocument();
    expect(button).toHaveFocus();
    expect(ResourceActionsAPI.planAction).not.toHaveBeenCalled();
    expect(ResourceActionsAPI.executeAction).not.toHaveBeenCalled();
  });

  it('keeps two failed image explanations attached to their own expanded row', () => {
    render(() => (
      <DockerImagesTable
        resources={['one', 'two'].map((name) =>
          makeResource({
            id: `image-${name}`,
            type: 'docker-image',
            name: `service-${name}:latest`,
            docker: {
              hostname: `edge-${name}`,
              updateStatus: { updateAvailable: false, error: `registry failure ${name}` },
            },
          }),
        )}
        emptyIcon={<span />}
        emptyTitle="No images"
        emptyDescription="No images"
        showToolbar={false}
      />
    ));

    const one = screen.getByRole('button', { name: /Check failed for service-one/ });
    const two = screen.getByRole('button', { name: /Check failed for service-two/ });
    fireEvent.click(one);
    expect(screen.getByText('registry failure one')).toBeInTheDocument();
    expect(screen.queryByText('registry failure two')).not.toBeInTheDocument();
    fireEvent.click(two);
    expect(one).toHaveAttribute('aria-expanded', 'false');
    expect(two).toHaveAttribute('aria-expanded', 'true');
    expect(screen.queryByText('registry failure one')).not.toBeInTheDocument();
    expect(screen.getByText('registry failure two')).toBeInTheDocument();
  });

  it('renders Docker volume API fields', () => {
    render(() => (
      <DockerVolumesTable
        resources={[
          makeResource({
            id: 'volume-1',
            type: 'docker-volume',
            name: 'app-data',
            docker: {
              driver: 'local',
              scope: 'global',
              sizeBytes: 2048,
              refCount: 3,
              createdAt: '2026-05-24T13:00:00Z',
              mountpoint: '/var/lib/docker/volumes/app-data/_data',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No volumes"
        emptyDescription="No volumes"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Created')).toBeInTheDocument();
    expect(screen.getByText('Refs')).toBeInTheDocument();
    expect(screen.getByText('app-data')).toBeInTheDocument();
    expect(screen.getByText('local')).toBeInTheDocument();
    expect(screen.getByText('3')).toBeInTheDocument();
    // Created renders as a relative time with the absolute timestamp in the
    // tooltip, not as a raw ISO string.
    expect(screen.queryByText('2026-05-24T13:00:00Z')).not.toBeInTheDocument();
    expect(screen.getByText(/ago$/)).toBeInTheDocument();
    expect(screen.getByText('/var/lib/docker/volumes/app-data/_data')).toBeInTheDocument();
  });

  it('keeps Docker volume tables filterable when rendered standalone', () => {
    render(() => (
      <DockerVolumesTable
        resources={[
          makeResource({
            id: 'volume-app',
            type: 'docker-volume',
            name: 'app-data',
            status: 'online',
            docker: { driver: 'local' },
          }),
          makeResource({
            id: 'volume-cache',
            type: 'docker-volume',
            name: 'cache-data',
            status: 'offline',
            docker: { driver: 'local' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No volumes"
        emptyDescription="No volumes"
      />
    ));

    expect(document.querySelectorAll('[data-docker-volume-row]')).toHaveLength(2);

    fireEvent.click(screen.getByRole('button', { name: /^Offline, \d+$/ }));

    expect(screen.getByText('1 of 2 volumes')).toBeInTheDocument();
    expect(document.querySelector('[data-docker-volume-row="volume-cache"]')).not.toBeNull();
    expect(document.querySelector('[data-docker-volume-row="volume-app"]')).toBeNull();

    const search = screen.getByPlaceholderText('Search volumes');
    fireEvent.input(search, { target: { value: 'app' } });

    expect(screen.getByText('0 of 2 volumes')).toBeInTheDocument();
    expect(screen.getByText('No volumes match current filters')).toBeInTheDocument();

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

    expect(search).toHaveValue('');
    expect(screen.getByText('2 volumes')).toBeInTheDocument();
    expect(document.querySelectorAll('[data-docker-volume-row]')).toHaveLength(2);
  });

  it('renders Docker network API fields', () => {
    const network = makeResource({
      id: 'network-1',
      type: 'docker-network',
      name: 'frontend',
      docker: {
        hostname: 'edge-01',
        hostSourceId: 'docker-host-1',
        networkId: 'net-1',
        driver: 'overlay',
        scope: 'swarm',
        enableIpv4: true,
        attachable: true,
        ingress: true,
        subnets: [{ subnet: '10.88.0.0/24', gateway: '10.88.0.1' }],
      },
    });

    renderInRouter(() => (
      <DockerNetworksTable
        resources={[network]}
        emptyIcon={<span />}
        emptyTitle="No networks"
        emptyDescription="No networks"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Attached workloads')).toBeInTheDocument();
    expect(screen.getByText('State')).toBeInTheDocument();
    expect(screen.getByText('frontend')).toBeInTheDocument();
    expect(screen.getByText('No containers')).toBeInTheDocument();
    expect(screen.getByText('Unused')).toBeInTheDocument();
    expect(screen.getByText('overlay')).toBeInTheDocument();
    expect(screen.getByText('10.88.0.0/24 via 10.88.0.1')).toBeInTheDocument();

    const row = document.querySelector('[data-docker-network-row="network-1"]');
    expect(row).not.toHaveAttribute('aria-expanded');
    expect(row?.querySelector('[data-row-action="true"]')).toHaveAttribute(
      'aria-expanded',
      'false',
    );

    fireEvent.click(row!);

    expect(row).not.toHaveAttribute('aria-expanded');
    expect(row?.querySelector('[data-row-action="true"]')).toHaveAttribute('aria-expanded', 'true');
    expect(screen.getByText('Addressing')).toBeInTheDocument();
    expect(screen.getByText('Flags')).toBeInTheDocument();
    expect(screen.getByText('IPv4')).toBeInTheDocument();
    expect(screen.getByText('attachable, ingress')).toBeInTheDocument();
    expect(screen.getByText('net-1')).toBeInTheDocument();
  });

  it('nests Docker containers attached to a network and searches attachment fields', () => {
    const network = makeResource({
      id: 'network-1',
      type: 'docker-network',
      name: 'frontend',
      docker: {
        hostname: 'edge-01',
        hostSourceId: 'docker-host-1',
        networkId: 'net-1',
        driver: 'bridge',
        scope: 'local',
        enableIpv4: true,
        subnets: [{ subnet: '10.88.0.0/24', gateway: '10.88.0.1' }],
      },
    });
    const container = makeResource({
      id: 'container-1',
      type: 'app-container',
      name: 'edge-web',
      displayName: 'edge-web',
      status: 'running',
      relationships: [
        {
          sourceId: 'container-1',
          targetId: 'network-1',
          type: 'attached_to',
          confidence: 1,
          active: true,
          discoverer: 'docker_adapter',
          observedAt: '2026-06-03T09:00:00Z',
          lastSeenAt: '2026-06-03T09:00:00Z',
        },
      ],
      docker: {
        hostname: 'edge-01',
        hostSourceId: 'docker-host-1',
        image: 'nginx:latest',
        containerState: 'running',
        health: 'healthy',
        networks: [{ name: 'frontend', ipv4: '10.88.0.12' }],
        ports: [{ ip: '0.0.0.0', publicPort: 8080, privatePort: 80, protocol: 'tcp' }],
      },
    });

    renderInRouter(() => (
      <DockerNetworksTable
        resources={[network]}
        relatedResources={[network, container]}
        emptyIcon={<span />}
        emptyTitle="No networks"
        emptyDescription="No networks"
      />
    ));

    expect(screen.getByText('1 attached container · edge-web 10.88.0.12')).toBeInTheDocument();
    expect(screen.getByText('1 running')).toBeInTheDocument();

    const search = screen.getByPlaceholderText('Search networks');
    fireEvent.input(search, { target: { value: '8080' } });

    expect(document.querySelector('[data-docker-network-row="network-1"]')).not.toBeNull();

    const row = document.querySelector('[data-docker-network-row="network-1"]');
    fireEvent.click(row!);

    const detail = within(document.querySelector('[data-docker-network-detail-row="network-1"]')!);
    expect(detail.getByText('Attached containers')).toBeInTheDocument();
    expect(detail.getByText('edge-web')).toBeInTheDocument();
    expect(detail.getByText('Healthy')).toBeInTheDocument();
    expect(detail.getByText('10.88.0.12')).toBeInTheDocument();
    expect(detail.getByText('0.0.0.0:8080->80/tcp')).toBeInTheDocument();
    expect(detail.getByText('nginx:latest')).toBeInTheDocument();
  });

  it('keeps dense Docker network attachment lists searchable and grouped', () => {
    const network = makeResource({
      id: 'network-dense',
      type: 'docker-network',
      name: 'frontend',
      docker: {
        hostname: 'edge-01',
        hostSourceId: 'docker-host-1',
        networkId: 'net-dense',
        driver: 'bridge',
        scope: 'local',
        enableIpv4: true,
      },
    });
    const makeAttachedContainer = (
      index: number,
      overrides: Partial<Resource['docker']> = {},
    ): Resource => {
      const name =
        index === 0
          ? 'api-unhealthy'
          : index === 1
            ? 'api-restarting'
            : index === 2
              ? 'worker-stopped'
              : `worker-${String(index).padStart(2, '0')}`;
      return makeResource({
        id: `container-${index}`,
        type: 'app-container',
        name,
        displayName: name,
        status: 'running',
        relationships: [
          {
            sourceId: `container-${index}`,
            targetId: 'network-dense',
            type: 'attached_to',
            confidence: 1,
            active: true,
            discoverer: 'docker_adapter',
            observedAt: '2026-06-03T09:00:00Z',
            lastSeenAt: '2026-06-03T09:00:00Z',
          },
        ],
        docker: {
          hostname: 'edge-01',
          hostSourceId: 'docker-host-1',
          image: `repo/${name}:latest`,
          containerState: 'running',
          networks: [{ name: 'frontend', ipv4: `10.88.0.${index + 10}` }],
          ports: [{ ip: '0.0.0.0', publicPort: 8000 + index, privatePort: 80, protocol: 'tcp' }],
          ...overrides,
        },
      });
    };
    const containers = [
      makeAttachedContainer(0, { health: 'unhealthy' }),
      makeAttachedContainer(1, { containerState: 'restarting' }),
      makeAttachedContainer(2, { containerState: 'exited', exitCode: 0 }),
      ...Array.from({ length: 27 }, (_, offset) => makeAttachedContainer(offset + 3)),
    ];

    renderInRouter(() => (
      <DockerNetworksTable
        resources={[network]}
        relatedResources={[network, ...containers]}
        emptyIcon={<span />}
        emptyTitle="No networks"
        emptyDescription="No networks"
      />
    ));

    expect(
      screen.getByText(
        '30 attached containers · api-unhealthy 10.88.0.10, api-restarting 10.88.0.11, worker-stopped 10.88.0.12 +27',
      ),
    ).toBeInTheDocument();

    // The network's state counts every container the Attention filter holds,
    // the restarting warning as well as the unhealthy one.
    expect(screen.getAllByText('2 need attention').length).toBeGreaterThan(0);
    // One dot per row: the name's dot carries that verdict, not the network's
    // always-online status, and the State words have no second dot.
    const networkCells = document
      .querySelector('[data-docker-network-row="network-dense"]')!
      .querySelectorAll('td');
    expect(networkCells[0].querySelector('[title="2 need attention"]')).not.toBeNull();
    expect(networkCells[0].querySelector('[title="Online"]')).toBeNull();
    expect(networkCells[2].querySelectorAll('[title]')).toHaveLength(1);
    // The health filter reads the same verdict: degraded, not healthy, and not
    // offline, since the network itself is up.
    const networkFilters = within(screen.getByRole('group', { name: 'Status' }));
    expect(networkFilters.getByRole('button', { name: /^Degraded, 1$/ })).toBeInTheDocument();
    expect(networkFilters.queryByRole('button', { name: /^Healthy, 1$/ })).toBeNull();

    fireEvent.click(document.querySelector('[data-docker-network-row="network-dense"]')!);

    const detail = within(
      document.querySelector('[data-docker-network-detail-row="network-dense"]')!,
    );
    // Resolve filters in their accessible group, not the growing attachment
    // list. Keep the same real buttons, role/name/visibility checks and clicks.
    const attachmentFilters = within(detail.getByRole('group', { name: 'Status' }));
    expect(detail.getByPlaceholderText('Search attached containers')).toBeInTheDocument();
    expect(detail.getByText('Show all 30 containers')).toBeInTheDocument();
    expect(detail.getByText('api-unhealthy')).toBeInTheDocument();
    expect(detail.getByText('api-restarting')).toBeInTheDocument();
    expect(detail.queryByText('worker-29')).toBeNull();

    fireEvent.click(detail.getByRole('button', { name: 'Show all 30 containers' }));
    expect(detail.getByText('worker-29')).toBeInTheDocument();
    expect(detail.getByText('Show first 24')).toBeInTheDocument();

    fireEvent.click(attachmentFilters.getByRole('button', { name: /^Attention, \d+$/ }));
    expect(detail.getAllByText('2 of 30 containers').length).toBeGreaterThan(0);
    expect(detail.getByText('api-unhealthy')).toBeInTheDocument();
    expect(detail.getByText('api-restarting')).toBeInTheDocument();
    expect(detail.queryByText('worker-29')).toBeNull();

    // Running is Docker's run state: the unhealthy container still runs, so it
    // matches Running too, listed under its Attention section.
    fireEvent.click(attachmentFilters.getByRole('button', { name: /^Running, 28$/ }));
    expect(detail.getAllByText('28 of 30 containers').length).toBeGreaterThan(0);
    expect(detail.getByText('api-unhealthy')).toBeInTheDocument();
    expect(detail.getByText('Needs operator review')).toBeInTheDocument();
    // A card's state words read in its dot's colour; a plain running one does not.
    expect(detail.getByText('Unhealthy')).toHaveClass('text-red-600');
    expect(document.querySelector('[data-docker-attachment-state="success"]')).toHaveClass(
      'text-base-content',
    );
    expect(detail.queryByText('api-restarting')).toBeNull();
    expect(detail.queryByText('worker-stopped')).toBeNull();

    fireEvent.click(attachmentFilters.getByRole('button', { name: /^Other, 2$/ }));
    expect(detail.getByText('api-restarting')).toBeInTheDocument();
    expect(detail.getByText('worker-stopped')).toBeInTheDocument();
    expect(detail.queryByText('api-unhealthy')).toBeNull();

    fireEvent.click(attachmentFilters.getByRole('button', { name: /^All, \d+$/ }));
    fireEvent.input(detail.getByPlaceholderText('Search attached containers'), {
      target: { value: 'worker-29' },
    });

    expect(detail.getAllByText('1 of 30 containers').length).toBeGreaterThan(0);
    expect(detail.getByText('worker-29')).toBeInTheDocument();
    expect(detail.getByText('0.0.0.0:8029->80/tcp')).toBeInTheDocument();
  });

  it('renders Docker Swarm node API fields', () => {
    render(() => (
      <DockerSwarmNodesTable
        resources={[
          makeResource({
            id: 'node-1',
            type: 'docker-swarm-node',
            name: 'worker-1',
            docker: {
              nodeRole: 'manager',
              availability: 'active',
              managerReachability: 'reachable',
              leader: true,
              engineVersion: '26.1.4',
              nanoCpus: 4_000_000_000,
              memoryBytes: 17179869184,
              address: '10.0.0.11',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No nodes"
        emptyDescription="No nodes"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Avail')).toHaveClass('platform-table-label-compact');
    expect(screen.getByText('Availability')).toHaveClass('platform-table-label-full');
    expect(screen.getByText('Mem')).toHaveClass('platform-table-label-compact');
    expect(screen.getByText('Memory')).toHaveClass('platform-table-label-full');
    expect(screen.getByText('Reachability')).toBeInTheDocument();
    expect(screen.getByText('worker-1')).toBeInTheDocument();
    expect(screen.getByText('manager')).toBeInTheDocument();
    expect(screen.getByText('leader')).toBeInTheDocument();
    expect(screen.getByText('26.1.4')).toBeInTheDocument();
    expect(screen.getByText('4')).toBeInTheDocument();
    expect(screen.getByText('10.0.0.11')).toBeInTheDocument();
  });

  it("reads an unreachable manager's Reachability in its dot's colour", () => {
    render(() => (
      <DockerSwarmNodesTable
        resources={[
          makeResource({
            id: 'node-2',
            type: 'docker-swarm-node',
            name: 'manager-2',
            docker: {
              nodeRole: 'manager',
              availability: 'active',
              managerReachability: 'unreachable',
            },
          }),
          makeResource({
            id: 'node-3',
            type: 'docker-swarm-node',
            name: 'worker-3',
            docker: { nodeRole: 'worker', availability: 'drain' },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No nodes"
        emptyDescription="No nodes"
        showToolbar={false}
      />
    ));

    expect(screen.getByTitle('Manager unreachable')).toBeInTheDocument();
    expect(screen.getByText('unreachable')).toHaveClass('text-red-600');
    expect(screen.getByTitle('Drained')).toBeInTheDocument();
    expect(screen.getByText('drain')).toHaveClass('text-amber-700');
    expect(screen.getByText('active')).toHaveClass('text-base-content');
  });

  it('renders Docker Swarm service API fields including update status', () => {
    render(() => (
      <DockerServicesTable
        resources={[
          makeResource({
            id: 'service-1',
            type: 'docker-service',
            name: 'checkout-api',
            docker: {
              hostname: 'manager-1',
              image: 'registry.example.com/checkout-api:2026.05',
              mode: 'replicated',
              desiredTasks: 4,
              runningTasks: 2,
              labels: { 'com.docker.stack.namespace': 'shop' },
              endpointPorts: [
                { protocol: 'tcp', targetPort: 8080, publishedPort: 18080, publishMode: 'ingress' },
              ],
              serviceUpdate: {
                state: 'rollback_started',
                message: 'Service replicas below desired',
              },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No services"
        emptyDescription="No services"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Update')).toBeInTheDocument();
    expect(screen.getByText('Run')).toHaveClass('platform-table-label-compact');
    expect(screen.getByText('Running')).toHaveClass('platform-table-label-full');
    expect(screen.getByText('Stack')).toBeInTheDocument();
    expect(screen.getByText('shop')).toBeInTheDocument();
    expect(screen.getByText('checkout-api')).toBeInTheDocument();
    // The image keeps its repository and tag visible when the cell truncates;
    // the full reference stays on the title.
    const serviceImage = screen.getByTitle('registry.example.com/checkout-api:2026.05');
    expect(serviceImage).toHaveTextContent('registry.example.com/checkout-api:2026.05');
    expect(serviceImage.querySelector('[data-docker-image-reference-tail]')).toHaveTextContent(
      'checkout-api:2026.05',
    );
    expect(screen.getByText('replicated')).toBeInTheDocument();
    expect(screen.getAllByText('4').length).toBeGreaterThan(0);
    expect(screen.getByText('2')).toBeInTheDocument();
    // A phone hides Desired, so its Running count reads out of what.
    expect(screen.getByText('/4')).toHaveClass('platform-table-phone-only-inline');
    // The snake_case rollout token reads as words; the raw token stays in the title.
    expect(screen.getByText('Rollback started')).toBeInTheDocument();
    // One line at every width; the full words stay in the title.
    expect(screen.getByText('Rollback started')).toHaveClass('truncate');
    expect(screen.getByText('Rollback started')).not.toHaveClass('whitespace-normal');
    expect(
      screen.getByText('Rollback started').closest('[title]')?.getAttribute('title'),
    ).toContain('rollback_started');
    // The dot names the rollout for what it is, and the cells behind its
    // verdict read amber: the Update words and the short Running count.
    expect(screen.getByTitle('Rolling back')).toBeInTheDocument();
    expect(screen.getByText('Rollback started')).toHaveClass('text-amber-700');
    expect(document.querySelector('[data-docker-service-running="warning"]')).toHaveClass(
      'text-amber-700',
    );
    expect(screen.getByText('18080:8080/tcp')).toBeInTheDocument();
    expect(screen.getByText('manager-1')).toBeInTheDocument();
    expect(document.querySelector('[data-docker-service-row="service-1"]')).not.toBeNull();
  });

  it('renders Docker engine storage usage fields from the disk usage API shape', () => {
    render(() => (
      <DockerStorageUsageTable
        hosts={[
          makeResource({
            id: 'host-1',
            type: 'agent',
            name: 'edge-01',
            docker: {
              imagesUsage: {
                totalCount: 6,
                activeCount: 4,
                totalSizeBytes: 2 * 1024 * 1024 * 1024,
                reclaimableBytes: 512 * 1024 * 1024,
              },
              containersUsage: {
                totalCount: 8,
                activeCount: 5,
                totalSizeBytes: 3 * 1024 * 1024 * 1024,
                reclaimableBytes: 256 * 1024 * 1024,
              },
              volumesUsage: {
                totalCount: 3,
                activeCount: 2,
                totalSizeBytes: 12 * 1024 * 1024 * 1024,
                reclaimableBytes: 1024 * 1024 * 1024,
              },
              buildCacheUsage: {
                totalCount: 4,
                activeCount: 1,
                totalSizeBytes: 5 * 1024 * 1024 * 1024,
                reclaimableBytes: 4 * 1024 * 1024 * 1024,
              },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No storage"
        emptyDescription="No storage"
      />
    ));

    expect(screen.getByText('Images')).toBeInTheDocument();
    expect(screen.getByText('Containers')).toBeInTheDocument();
    expect(screen.getByText('Volumes')).toBeInTheDocument();
    expect(screen.getByText('Build Cache')).toBeInTheDocument();
    expect(screen.getByPlaceholderText('Search storage usage')).toBeInTheDocument();
    expect(screen.getByText('edge-01')).toBeInTheDocument();
    expect(screen.getByText('2.00 GB · 4/6')).toBeInTheDocument();
    expect(screen.getByText('5.00 GB · 1/4')).toBeInTheDocument();
    expect(document.querySelector('[data-docker-storage-row="host-1"]')).not.toBeNull();
  });

  it('keeps Docker engine storage usage tables filterable when rendered standalone', () => {
    const storageUsage = {
      totalCount: 1,
      activeCount: 1,
      totalSizeBytes: 1024,
      reclaimableBytes: 0,
    };

    render(() => (
      <DockerStorageUsageTable
        hosts={[
          makeResource({
            id: 'host-edge',
            type: 'agent',
            name: 'edge-01',
            status: 'online',
            docker: { imagesUsage: storageUsage },
          }),
          makeResource({
            id: 'host-archive',
            type: 'agent',
            name: 'archive-01',
            status: 'offline',
            docker: { imagesUsage: storageUsage },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No storage"
        emptyDescription="No storage"
      />
    ));

    expect(document.querySelectorAll('[data-docker-storage-row]')).toHaveLength(2);

    const search = screen.getByPlaceholderText('Search storage usage');
    fireEvent.input(search, { target: { value: 'archive' } });

    expect(search).toHaveValue('archive');
    expect(screen.getByText('1 of 2 hosts')).toBeInTheDocument();
    expect(document.querySelector('[data-docker-storage-row="host-archive"]')).not.toBeNull();
    expect(document.querySelector('[data-docker-storage-row="host-edge"]')).toBeNull();

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

    expect(search).toHaveValue('');
    expect(screen.getByText('2 hosts')).toBeInTheDocument();
    expect(document.querySelectorAll('[data-docker-storage-row]')).toHaveLength(2);
  });

  it('renders Docker Swarm task API fields', () => {
    render(() => (
      <DockerTasksTable
        resources={[
          makeResource({
            id: 'task-1',
            type: 'docker-task',
            name: 'web.2',
            docker: {
              serviceName: 'web',
              slot: 2,
              desiredState: 'running',
              currentState: 'running',
              nodeName: 'worker-1',
              startedAt: '2026-05-24T13:05:00Z',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No tasks"
        emptyDescription="No tasks"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Slot')).toBeInTheDocument();
    expect(screen.getByText('Desired')).toBeInTheDocument();
    expect(screen.getByText('Current')).toBeInTheDocument();
    expect(screen.getByText('web.2')).toBeInTheDocument();
    expect(screen.getByText('web')).toBeInTheDocument();
    // Current reads the row dot's words, and Desired reads as words beside it;
    // Docker's own token stays on hover.
    expect(document.querySelector('[data-docker-task-state="success"]')).toHaveTextContent(
      'Running',
    );
    expect(screen.getAllByText('Running')).toHaveLength(2);
    expect(screen.getAllByTitle('running')).toHaveLength(2);
    // The raw RFC3339 stamp moves to the title; the cell shows an age.
    const started = screen.getByTitle('2026-05-24T13:05:00Z');
    expect(started).toBeInTheDocument();
    expect(started.textContent).toMatch(/ago$/);
  });

  it("reads a failed Swarm task's state in its dot's colour, error on hover", () => {
    render(() => (
      <DockerTasksTable
        resources={[
          makeResource({
            id: 'task-2',
            type: 'docker-task',
            name: 'web.3',
            docker: {
              serviceName: 'web',
              desiredState: 'shutdown',
              currentState: 'failed',
              error: 'task: non-zero exit (1)',
              nodeName: 'worker-1',
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No tasks"
        emptyDescription="No tasks"
        showToolbar={false}
      />
    ));

    const state = screen.getByText('Failed');
    expect(state).toHaveClass('text-red-600');
    expect(state).toHaveAttribute('title', 'task: non-zero exit (1)');
    // A phone cannot hover: the drawer leads with why it failed, under the
    // task's name and the row's own dot.
    fireEvent.click(document.querySelector('[data-docker-task-row="task-2"]')!);
    const detail = within(document.querySelector('[data-testid="docker-task-detail"]')!);
    expect(detail.getByRole('heading', { name: 'web.3' })).toBeInTheDocument();
    expect(detail.getByLabelText('Failed')).toBeInTheDocument();
    expect(detail.getByText('task: non-zero exit (1)')).toBeInTheDocument();
    expect(detail.getByText('Shutdown')).toBeInTheDocument();
  });

  it('renders Docker Swarm secret API metadata without secret data', () => {
    render(() => (
      <DockerSecretsTable
        resources={[
          makeResource({
            id: 'secret-1',
            type: 'docker-secret',
            name: 'api-token',
            docker: {
              hostname: 'manager-1',
              driver: 'vault',
              templatingDriver: 'golang',
              objectCreatedAt: '2026-05-24T13:10:00Z',
              labels: { stack: 'ops' },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No secrets"
        emptyDescription="No secrets"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Secret')).toBeInTheDocument();
    expect(screen.getByText('Template')).toBeInTheDocument();
    expect(screen.getByText('api-token')).toBeInTheDocument();
    expect(screen.getByText('vault')).toBeInTheDocument();
    expect(screen.getByText('golang')).toBeInTheDocument();
    expect(screen.getByText('stack=ops')).toBeInTheDocument();
    expect(screen.getByText('manager-1')).toBeInTheDocument();
  });

  it('renders Docker Swarm config API metadata', () => {
    renderInRouter(() => (
      <DockerConfigsTable
        resources={[
          makeResource({
            id: 'config-1',
            type: 'docker-config',
            name: 'nginx-conf',
            docker: {
              hostname: 'manager-1',
              templatingDriver: 'golang',
              objectCreatedAt: '2026-05-24T13:15:00Z',
              labels: { stack: 'edge' },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No configs"
        emptyDescription="No configs"
        showToolbar={false}
      />
    ));

    expect(screen.getByText('Config')).toBeInTheDocument();
    expect(screen.getByText('Template')).toBeInTheDocument();
    expect(screen.getByText('nginx-conf')).toBeInTheDocument();
    expect(screen.getByText('golang')).toBeInTheDocument();
    expect(screen.getByText('stack=edge')).toBeInTheDocument();
    expect(screen.getByText('manager-1')).toBeInTheDocument();

    const configRow = document.querySelector<HTMLElement>('[data-docker-config-row="config-1"]');
    expect(configRow).not.toBeNull();
    const configDisclosure = configRow!.querySelector<HTMLElement>('[data-row-action="true"]');
    expect(configDisclosure).not.toBeNull();
    fireEvent.click(configDisclosure!);
    expect(configRow).not.toHaveAttribute('aria-expanded');
    expect(configDisclosure).toHaveAttribute('aria-expanded', 'true');
    expect(
      document.querySelector('[data-inline-docker-config-detail-for="config-1"]'),
    ).not.toBeNull();
  });
  it('opens a Swarm service as a record drawer with every label, human dates, and its host', () => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-05-24T15:00:00Z'));
    renderInRouter(() => (
      <DockerServicesTable
        resources={[
          makeResource({
            id: 'service-1',
            type: 'docker-service',
            name: 'checkout-api',
            docker: {
              hostname: 'manager-1',
              serviceId: 'svc-abc123',
              image: 'registry.example.com/checkout-api:2026.05',
              mode: 'replicated',
              desiredTasks: 4,
              runningTasks: 2,
              labels: {
                'com.docker.stack.namespace': 'shop',
                'com.example.owner': 'payments',
                'com.example.tier': 'api',
                'com.example.zone': 'eu-west',
              },
              serviceUpdate: {
                state: 'rollback_started',
                message: 'Service replicas below desired',
                completedAt: '2026-05-24T13:00:00Z',
              },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No services"
        emptyDescription="No services"
        showToolbar={false}
      />
    ));

    const disclosure = screen.getByRole('button', { name: 'Expand details for checkout-api' });
    fireEvent.click(disclosure);

    const panel = document.querySelector<HTMLElement>('[data-testid="docker-service-detail"]')!;
    const detail = within(panel);
    // Headed by the service and the row's own dot, with its verdict in words.
    expect(detail.getByRole('heading', { name: 'checkout-api' })).toBeInTheDocument();
    expect(detail.getByLabelText('Rolling back')).toBeInTheDocument();
    expect(
      detail.getByText(
        '2 of 4 replicas running · update rollback started · Service replicas below desired',
      ),
    ).toBeInTheDocument();
    // Every label, not the first three the table cell keeps.
    expect(detail.getByText('Labels (4)')).toBeInTheDocument();
    expect(detail.getByText('com.example.zone')).toBeInTheDocument();
    expect(detail.getByText('eu-west')).toBeInTheDocument();
    // A completion stamp reads as a date and an age, the raw stamp on hover.
    expect(detail.getAllByTitle('2026-05-24T13:00:00Z')[0]).toHaveTextContent(/2026.*\(2h ago\)$/);
    // The reporting host is one tap away.
    expect(detail.getByRole('link', { name: 'Open manager-1' })).toHaveAttribute(
      'href',
      '/docker/overview?q=manager-1',
    );
    // The header closes the drawer and hands focus back to the row's disclosure.
    expect(disclosure).toHaveAttribute('aria-controls', 'docker-service-detail-service-1');
    expect(document.getElementById('docker-service-detail-service-1')).toContainElement(panel);
    fireEvent.click(detail.getByRole('button', { name: 'Collapse checkout-api details' }));
    expect(document.querySelector('[data-testid="docker-service-detail"]')).toBeNull();
    vi.useRealTimers();
  });

  it('shows a Swarm secret record without any secret value', () => {
    renderInRouter(() => (
      <DockerSecretsTable
        resources={[
          makeResource({
            id: 'secret-1',
            type: 'docker-secret',
            name: 'api-token',
            docker: {
              hostname: 'manager-1',
              secretId: 'sec-1',
              driver: 'vault',
              objectCreatedAt: '2026-05-24T13:10:00Z',
              labels: { stack: 'ops' },
            },
          }),
        ]}
        emptyIcon={<span />}
        emptyTitle="No secrets"
        emptyDescription="No secrets"
        showToolbar={false}
      />
    ));

    fireEvent.click(document.querySelector('[data-docker-secret-row="secret-1"]')!);
    const detail = within(
      document.querySelector<HTMLElement>('[data-testid="docker-secret-detail"]')!,
    );
    expect(detail.getByRole('heading', { name: 'api-token' })).toBeInTheDocument();
    expect(
      detail.getByText("Pulse sees this secret's metadata only, never its value."),
    ).toBeInTheDocument();
    expect(detail.getByText('sec-1')).toBeInTheDocument();
    expect(detail.getByText('Labels (1)')).toBeInTheDocument();
  });

  it('links each container on a network to the Docker overview', () => {
    const network = makeResource({
      id: 'network-1',
      type: 'docker-network',
      name: 'frontend',
      docker: { hostname: 'edge-01', networkId: 'net-1', driver: 'bridge', scope: 'local' },
    });
    const container = makeResource({
      id: 'container-1',
      type: 'app-container',
      name: 'edge-web',
      displayName: 'edge-web',
      status: 'running',
      relationships: [
        {
          sourceId: 'container-1',
          targetId: 'network-1',
          type: 'attached_to',
          confidence: 1,
          active: true,
          discoverer: 'docker_adapter',
          observedAt: '2026-06-03T09:00:00Z',
          lastSeenAt: '2026-06-03T09:00:00Z',
        },
      ],
      docker: {
        hostname: 'edge-01',
        image: 'nginx:latest',
        containerState: 'running',
        networks: [{ name: 'frontend', ipv4: '10.88.0.12' }],
      },
    });

    renderInRouter(() => (
      <DockerNetworksTable
        resources={[network]}
        relatedResources={[network, container]}
        emptyIcon={<span />}
        emptyTitle="No networks"
        emptyDescription="No networks"
        showToolbar={false}
      />
    ));

    fireEvent.click(document.querySelector('[data-docker-network-row="network-1"]')!);
    const detail = within(
      document.querySelector<HTMLElement>('[data-testid="docker-network-detail"]')!,
    );
    expect(detail.getByRole('heading', { name: 'frontend' })).toBeInTheDocument();
    expect(detail.getByText('bridge · local · 1 attached container')).toBeInTheDocument();
    expect(detail.getByRole('link', { name: 'edge-web' })).toHaveAttribute(
      'href',
      '/docker/overview?q=edge-web',
    );
    expect(detail.getByText('Network ID')).toBeInTheDocument();
  });

  it('looks container alert thresholds up by name-first override ids, so a recreated container keeps its overrides (#1601)', () => {
    const host = makeResource({
      id: 'host-1',
      type: 'docker-host',
      name: 'edge-01',
      status: 'online',
      docker: { hostname: 'edge-01' },
    });

    for (const containerId of ['container-before', 'container-after-recreate']) {
      getMetricThresholdsSpy.mockClear();
      renderInRouter(() => (
        <DockerContainersTable
          resources={[
            makeResource({
              id: containerId,
              type: 'app-container',
              name: 'edge-web',
              status: 'running',
              docker: { hostname: 'edge-01', image: 'nginx:latest', containerState: 'running' },
            }),
          ]}
          hosts={[host]}
          emptyIcon={<span />}
          emptyTitle="No containers"
          emptyDescription="No containers"
          showToolbar={false}
        />
      ));

      const cpuLookups = getMetricThresholdsSpy.mock.calls.filter(
        ([scope, metric]) => scope === 'docker' && metric === 'cpu',
      );
      expect(cpuLookups.length).toBeGreaterThan(0);
      for (const [, , resourceIds] of cpuLookups) {
        // The durable key is host id + container name, whatever the runtime id
        // is now; the old id forms trail as lookup fallbacks.
        expect((resourceIds as string[])[0]).toBe('docker:host-1/edge-web');
        expect(resourceIds).toContain(`docker:host-1/${containerId}`);
      }
      cleanup();
    }
  });
});