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.

45.0 KB
Raw Blame
import { describe, expect, it } from 'vitest';
import type { Alert } from '@/types/api';
import type { Resource } from '@/types/resource';
import {
  getKubernetesNodeAttentionRank,
  getKubernetesNodesNeedingAttention,
  splitKubernetesNameTail,
  isSingleKubernetesCluster,
  kubernetesScopeDisplayLabel,
} from '../kubernetesPageModel';
import {
  KUBERNETES_TAB_SPECS,
  buildKubernetesClusterChildCounts,
  buildKubernetesOverviewPosture,
  buildKubernetesIncidentRows,
  buildKubernetesPageModel,
  compareKubernetesControllers,
  filterKubernetesIncidents,
  filterKubernetesResources,
  compareKubernetesDeployments,
  compareKubernetesEvents,
  compareKubernetesNodes,
  compareKubernetesPods,
  getKubernetesPageTabSpecs,
  kubernetesClusterLabel,
  kubernetesScopeLabel,
  mapKubernetesControllerStatus,
  mapKubernetesCronJobStatus,
  mapKubernetesDaemonSetStatus,
  mapKubernetesDeploymentStatus,
  mapKubernetesEventSeverity,
  mapKubernetesIncidentSeverity,
  mapKubernetesJobStatus,
  mapKubernetesNodeStatus,
  mapKubernetesPodStatus,
  mapKubernetesReplicaSetStatus,
  mapKubernetesStatefulSetStatus,
  resolveKubernetesPageTabId,
} from '../kubernetesPageModel';

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

describe('kubernetesPageModel', () => {
  it('shows the namespace alone when one cluster is in view', () => {
    const inCluster = (id: string, clusterName: string, namespace?: string) =>
      ({
        id,
        type: 'pod',
        name: id,
        kubernetes: { clusterName, ...(namespace ? { namespace } : {}) },
      }) as unknown as Resource;
    const services = inCluster('a', 'Production EU', 'services');
    const clusterRole = inCluster('b', 'Production EU');
    const otherCluster = inCluster('c', 'Staging', 'services');

    expect(isSingleKubernetesCluster([services, clusterRole])).toBe(true);
    expect(isSingleKubernetesCluster([services, otherCluster])).toBe(false);
    expect(isSingleKubernetesCluster([])).toBe(true);
    // Two clusters can share a display name, and a row with no cluster at all
    // counts as its own, so neither case loses the cluster from the cell.
    const sameNameOtherId = {
      id: 'd',
      type: 'pod',
      name: 'd',
      kubernetes: { clusterId: 'eu-2', clusterName: 'Production EU', namespace: 'services' },
    } as unknown as Resource;
    const euOne = {
      id: 'e',
      type: 'pod',
      name: 'e',
      kubernetes: { clusterId: 'eu-1', clusterName: 'Production EU', namespace: 'apps' },
    } as unknown as Resource;
    const noCluster = {
      id: 'f',
      type: 'pod',
      name: 'f',
      kubernetes: { namespace: 'apps' },
    } as unknown as Resource;
    expect(isSingleKubernetesCluster([euOne, sameNameOtherId])).toBe(false);
    expect(isSingleKubernetesCluster([euOne, noCluster])).toBe(false);
    expect(isSingleKubernetesCluster([noCluster])).toBe(true);

    expect(kubernetesScopeDisplayLabel(services, true)).toBe('services');
    expect(kubernetesScopeDisplayLabel(clusterRole, true)).toBe('Cluster');
    // Several clusters keep the cluster in the cell so rows stay unambiguous.
    expect(kubernetesScopeDisplayLabel(services, false)).toBe('Production EU/services');
    expect(kubernetesScopeDisplayLabel(clusterRole, false)).toBe('Production EU');
  });

  it('splits off the generated tail that tells sibling names apart', () => {
    expect(splitKubernetesNameTail('checkout-api-6d8f9c7b5-x7k2p')).toEqual({
      head: 'checkout-api-6d8f9c7b5',
      tail: '-x7k2p',
    });
    expect(splitKubernetesNameTail('prod-euw1-k8s-03')).toEqual({
      head: 'prod-euw1-k8s',
      tail: '-03',
    });
    expect(splitKubernetesNameTail('nightly-backfill-28918234')).toEqual({
      head: 'nightly-backfill',
      tail: '-28918234',
    });
    // No dash, a trailing dash, or a tail too long to be a generated suffix
    // (a cloud node's domain) leaves the name whole for plain truncation.
    expect(splitKubernetesNameTail('postgres')).toEqual({ head: 'postgres', tail: '' });
    expect(splitKubernetesNameTail('web-')).toEqual({ head: 'web-', tail: '' });
    expect(splitKubernetesNameTail('ip-10-0-1-23.eu-west-1.compute.internal')).toEqual({
      head: 'ip-10-0-1-23.eu-west-1.compute.internal',
      tail: '',
    });
    expect(splitKubernetesNameTail('-')).toEqual({ head: '-', tail: '' });
  });

  it('declares operator workflow tabs for Kubernetes inventory', () => {
    expect(KUBERNETES_TAB_SPECS.map((tab) => tab.id)).toEqual([
      'overview',
      'nodes',
      'workloads',
      'services',
      'storage',
      'configuration',
      'events',
    ]);
  });

  it('keeps legacy Kubernetes object routes mapped to workflow tabs', () => {
    expect(resolveKubernetesPageTabId(undefined)).toBe('overview');
    expect(resolveKubernetesPageTabId('nodes')).toBe('nodes');
    expect(resolveKubernetesPageTabId('pods')).toBe('workloads');
    expect(resolveKubernetesPageTabId('deployments')).toBe('workloads');
    expect(resolveKubernetesPageTabId('controllers')).toBe('workloads');
    expect(resolveKubernetesPageTabId('autoscaling')).toBe('workloads');
    expect(resolveKubernetesPageTabId('networking')).toBe('services');
    expect(resolveKubernetesPageTabId('config')).toBe('configuration');
    expect(resolveKubernetesPageTabId('policy')).toBe('configuration');
    expect(resolveKubernetesPageTabId('unknown')).toBe('overview');
  });

  it('shows Kubernetes workflow tabs only when the workflow has inventory', () => {
    const clusterOnlyModel = buildKubernetesPageModel([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
    ]);
    const workloadModel = buildKubernetesPageModel([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({ id: 'node-1', type: 'k8s-node' }),
      makeResource({ id: 'pod-1', type: 'pod' }),
      makeResource({ id: 'svc-1', type: 'k8s-service' }),
      makeResource({ id: 'pvc-1', type: 'k8s-persistent-volume-claim' }),
      makeResource({ id: 'cm-1', type: 'k8s-configmap' }),
      makeResource({ id: 'event-1', type: 'k8s-event' }),
    ]);

    expect(getKubernetesPageTabSpecs(clusterOnlyModel).map((tab) => tab.id)).toEqual(['overview']);
    expect(getKubernetesPageTabSpecs(workloadModel).map((tab) => tab.id)).toEqual([
      'overview',
      'nodes',
      'workloads',
      'services',
      'storage',
      'configuration',
      'events',
    ]);
  });

  it('keeps workflow tabs visible from source-scoped type facets on partial routes', () => {
    const activeRouteModel = buildKubernetesPageModel([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
    ]);

    expect(
      getKubernetesPageTabSpecs(activeRouteModel, {
        'k8s-node': 2,
        pod: 12,
        'k8s-service': 3,
        'k8s-storage-class': 1,
        'k8s-configmap': 4,
        'k8s-event': 6,
      }).map((tab) => tab.id),
    ).toEqual(['overview', 'nodes', 'workloads', 'services', 'storage', 'configuration', 'events']);
  });

  it('summarizes actionable Kubernetes overview posture from native resource states', () => {
    const model = buildKubernetesPageModel([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({ id: 'node-ready', type: 'k8s-node', kubernetes: { ready: true } }),
      makeResource({ id: 'node-down', type: 'k8s-node', kubernetes: { ready: false } }),
      makeResource({
        id: 'pod-pending',
        type: 'pod',
        kubernetes: { podPhase: 'Pending' },
      }),
      makeResource({
        id: 'deployment-short',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 3, readyReplicas: 2 },
        incidents: [{ code: 'k8s_under_replicated', severity: 'warning', summary: '2 / 3 ready' }],
      }),
    ]);

    expect(buildKubernetesOverviewPosture(model)).toEqual({
      nodeAttention: 1,
      podAttention: 1,
      deploymentAttention: 1,
      criticalResources: 1,
      criticalIncidents: 0,
      warningIncidents: 1,
      attentionResources: 3,
      attentionSignals: 1,
    });
  });

  it('buckets clusters, nodes, workloads, services, storage, config, policy, autoscaling, and events', () => {
    const model = buildKubernetesPageModel([
      makeResource({ id: 'cluster-1', type: 'k8s-cluster' }),
      makeResource({ id: 'node-1', type: 'k8s-node' }),
      makeResource({ id: 'pod-1', type: 'pod' }),
      makeResource({ id: 'dep-1', type: 'k8s-deployment' }),
      makeResource({ id: 'rs-1', type: 'k8s-replicaset' }),
      makeResource({ id: 'svc-1', type: 'k8s-service' }),
      makeResource({ id: 'sts-1', type: 'k8s-statefulset' }),
      makeResource({ id: 'ds-1', type: 'k8s-daemonset' }),
      makeResource({ id: 'job-1', type: 'k8s-job' }),
      makeResource({ id: 'cron-1', type: 'k8s-cronjob' }),
      makeResource({ id: 'ing-1', type: 'k8s-ingress' }),
      makeResource({ id: 'eps-1', type: 'k8s-endpoint-slice' }),
      makeResource({ id: 'netpol-1', type: 'k8s-network-policy' }),
      makeResource({ id: 'pv-1', type: 'k8s-persistent-volume' }),
      makeResource({ id: 'pvc-1', type: 'k8s-persistent-volume-claim' }),
      makeResource({ id: 'sc-1', type: 'k8s-storage-class' }),
      makeResource({ id: 'ns-1', type: 'k8s-namespace' }),
      makeResource({ id: 'cm-1', type: 'k8s-configmap' }),
      makeResource({ id: 'secret-1', type: 'k8s-secret' }),
      makeResource({ id: 'sa-1', type: 'k8s-serviceaccount' }),
      makeResource({ id: 'role-1', type: 'k8s-role' }),
      makeResource({ id: 'crole-1', type: 'k8s-cluster-role' }),
      makeResource({ id: 'rb-1', type: 'k8s-role-binding' }),
      makeResource({ id: 'crb-1', type: 'k8s-cluster-role-binding' }),
      makeResource({ id: 'quota-1', type: 'k8s-resource-quota' }),
      makeResource({ id: 'limits-1', type: 'k8s-limit-range' }),
      makeResource({ id: 'pdb-1', type: 'k8s-pod-disruption-budget' }),
      makeResource({ id: 'hpa-1', type: 'k8s-horizontal-pod-autoscaler' }),
      makeResource({ id: 'event-1', type: 'k8s-event' }),
      makeResource({ id: 'proxmox-vm', type: 'vm', platformType: 'proxmox-pve' }),
    ]);

    expect(model.clusters.map((r) => r.id)).toEqual(['cluster-1']);
    expect(model.nodes.map((r) => r.id)).toEqual(['node-1']);
    expect(model.pods.map((r) => r.id)).toEqual(['pod-1']);
    expect(model.deployments.map((r) => r.id)).toEqual(['dep-1']);
    expect(model.replicaSets.map((r) => r.id)).toEqual(['rs-1']);
    expect(model.services.map((r) => r.id)).toEqual(['svc-1']);
    expect(model.statefulSets.map((r) => r.id)).toEqual(['sts-1']);
    expect(model.daemonSets.map((r) => r.id)).toEqual(['ds-1']);
    expect(model.jobs.map((r) => r.id)).toEqual(['job-1']);
    expect(model.cronJobs.map((r) => r.id)).toEqual(['cron-1']);
    expect(model.ingresses.map((r) => r.id)).toEqual(['ing-1']);
    expect(model.endpointSlices.map((r) => r.id)).toEqual(['eps-1']);
    expect(model.networkPolicies.map((r) => r.id)).toEqual(['netpol-1']);
    expect(model.persistentVolumes.map((r) => r.id)).toEqual(['pv-1']);
    expect(model.persistentVolumeClaims.map((r) => r.id)).toEqual(['pvc-1']);
    expect(model.storageClasses.map((r) => r.id)).toEqual(['sc-1']);
    expect(model.namespaces.map((r) => r.id)).toEqual(['ns-1']);
    expect(model.configMaps.map((r) => r.id)).toEqual(['cm-1']);
    expect(model.secrets.map((r) => r.id)).toEqual(['secret-1']);
    expect(model.serviceAccounts.map((r) => r.id)).toEqual(['sa-1']);
    expect(model.roles.map((r) => r.id)).toEqual(['role-1']);
    expect(model.clusterRoles.map((r) => r.id)).toEqual(['crole-1']);
    expect(model.roleBindings.map((r) => r.id)).toEqual(['rb-1']);
    expect(model.clusterRoleBindings.map((r) => r.id)).toEqual(['crb-1']);
    expect(model.resourceQuotas.map((r) => r.id)).toEqual(['quota-1']);
    expect(model.limitRanges.map((r) => r.id)).toEqual(['limits-1']);
    expect(model.podDisruptionBudgets.map((r) => r.id)).toEqual(['pdb-1']);
    expect(model.horizontalPodAutoscalers.map((r) => r.id)).toEqual(['hpa-1']);
    expect(model.events.map((r) => r.id)).toEqual(['event-1']);
    expect(model.workloads.map((r) => r.id).sort()).toEqual(
      ['cron-1', 'dep-1', 'ds-1', 'job-1', 'pod-1', 'rs-1', 'sts-1'].sort(),
    );
    expect(model.storage.map((r) => r.id).sort()).toEqual(['pv-1', 'pvc-1', 'sc-1']);
    expect(model.serviceNetworking.map((r) => r.id).sort()).toEqual(['eps-1', 'ing-1']);
    expect(model.config.map((r) => r.id).sort()).toEqual(
      ['cm-1', 'crb-1', 'crole-1', 'ns-1', 'rb-1', 'role-1', 'sa-1', 'secret-1'].sort(),
    );
    expect(model.policy.map((r) => r.id).sort()).toEqual(
      ['limits-1', 'netpol-1', 'pdb-1', 'quota-1'].sort(),
    );
    expect(model.autoscaling.map((r) => r.id)).toEqual(['hpa-1']);
    expect(model.resources).toHaveLength(29);
  });

  it('treats agent rows that report a kubernetes source as Kubernetes nodes', () => {
    const model = buildKubernetesPageModel([
      makeResource({
        id: 'merged-node-1',
        type: 'agent',
        platformType: 'kubernetes',
        sources: ['agent', 'kubernetes'],
      }),
      makeResource({
        id: 'plain-host',
        type: 'agent',
        platformType: 'agent',
        sources: ['agent'],
      }),
    ]);

    expect(model.nodes.map((r) => r.id)).toEqual(['merged-node-1']);
  });

  it('maps Kubernetes Event severity from the event type instead of generic resource status', () => {
    expect(mapKubernetesEventSeverity('Warning')).toEqual({
      variant: 'warning',
      label: 'Warning',
    });
    expect(mapKubernetesEventSeverity('Normal')).toEqual({
      variant: 'muted',
      label: 'Normal',
    });
    expect(mapKubernetesEventSeverity(undefined)).toEqual({
      variant: 'muted',
      label: 'Unknown',
    });
  });

  it('orders Kubernetes Events by observed time from newest to oldest', () => {
    const older = makeResource({
      id: 'older',
      type: 'k8s-event',
      kubernetes: {
        eventTime: '2026-05-24T11:00:00Z',
      },
    });
    const newerFromFirstSeen = makeResource({
      id: 'newer-first-seen',
      type: 'k8s-event',
      kubernetes: {
        firstSeen: '2026-05-24T13:00:00Z',
      },
    });
    const newestFromCreatedAt = makeResource({
      id: 'newest-created',
      type: 'k8s-event',
      kubernetes: {
        createdAt: '2026-05-24T14:00:00Z',
      },
    });

    expect([older, newestFromCreatedAt, newerFromFirstSeen].sort(compareKubernetesEvents)).toEqual([
      newestFromCreatedAt,
      newerFromFirstSeen,
      older,
    ]);
    expect(
      buildKubernetesPageModel([older, newestFromCreatedAt, newerFromFirstSeen]).events.map(
        (event) => event.id,
      ),
    ).toEqual(['newest-created', 'newer-first-seen', 'older']);
  });

  describe('mapKubernetesPodStatus', () => {
    it('escalates CrashLoopBackOff to danger regardless of phase', () => {
      const indicator = mapKubernetesPodStatus(
        makeResource({
          id: 'crash',
          type: 'pod',
          kubernetes: {
            podPhase: 'Running',
            podContainers: [
              { name: 'app', ready: false, state: 'waiting', reason: 'CrashLoopBackOff' },
            ],
          },
        }),
      );
      expect(indicator.variant).toBe('danger');
      expect(indicator.label).toBe('CrashLoopBackOff');
    });

    it('flags ImagePullBackOff and OOMKilled as danger', () => {
      expect(
        mapKubernetesPodStatus(
          makeResource({
            id: 'pull',
            type: 'pod',
            kubernetes: {
              podPhase: 'Pending',
              podContainers: [{ ready: false, state: 'waiting', reason: 'ImagePullBackOff' }],
            },
          }),
        ).variant,
      ).toBe('danger');
      expect(
        mapKubernetesPodStatus(
          makeResource({
            id: 'oom',
            type: 'pod',
            kubernetes: {
              podPhase: 'Running',
              podContainers: [{ ready: false, state: 'terminated', reason: 'OOMKilled' }],
            },
          }),
        ).variant,
      ).toBe('danger');
    });

    it('warns on Running pods whose containers are not all ready', () => {
      expect(
        mapKubernetesPodStatus(
          makeResource({
            id: 'not-ready',
            type: 'pod',
            kubernetes: {
              podPhase: 'Running',
              podContainers: [
                { ready: true, state: 'running' },
                { ready: false, state: 'running' },
              ],
            },
          }),
        ),
      ).toEqual({ variant: 'warning', label: 'Not ready' });
    });

    it('returns success when phase is Running and all containers ready', () => {
      expect(
        mapKubernetesPodStatus(
          makeResource({
            id: 'happy',
            type: 'pod',
            kubernetes: {
              podPhase: 'Running',
              podContainers: [{ ready: true, state: 'running' }],
            },
          }),
        ),
      ).toEqual({ variant: 'success', label: 'Running' });
    });

    it('treats Pending and Failed phases distinctly', () => {
      expect(
        mapKubernetesPodStatus(
          makeResource({
            id: 'pending',
            type: 'pod',
            kubernetes: { podPhase: 'Pending', podContainers: [] },
          }),
        ),
      ).toEqual({ variant: 'warning', label: 'Pending' });
      expect(
        mapKubernetesPodStatus(
          makeResource({
            id: 'failed',
            type: 'pod',
            kubernetes: { podPhase: 'Failed', podContainers: [] },
          }),
        ),
      ).toEqual({ variant: 'danger', label: 'Failed' });
    });
  });

  describe('mapKubernetesNodeStatus', () => {
    it('returns danger when ready is false even if status reports online', () => {
      expect(
        mapKubernetesNodeStatus(
          makeResource({
            id: 'not-ready',
            type: 'k8s-node',
            status: 'online',
            kubernetes: { ready: false },
          }),
        ),
      ).toEqual({ variant: 'danger', label: 'NotReady' });
    });

    it('returns success when ready is true', () => {
      expect(
        mapKubernetesNodeStatus(
          makeResource({
            id: 'ready',
            type: 'k8s-node',
            status: 'online',
            kubernetes: { ready: true },
          }),
        ),
      ).toEqual({ variant: 'success', label: 'Ready' });
    });

    it('returns warning for a cordoned node even though it reports ready', () => {
      expect(
        mapKubernetesNodeStatus(
          makeResource({
            id: 'cordoned',
            type: 'k8s-node',
            status: 'warning',
            kubernetes: { ready: true, unschedulable: true },
          }),
        ),
      ).toEqual({ variant: 'warning', label: 'Unschedulable' });
    });

    it('keeps NotReady as the dominant state when a cordoned node is also down', () => {
      expect(
        mapKubernetesNodeStatus(
          makeResource({
            id: 'cordoned-down',
            type: 'k8s-node',
            status: 'offline',
            kubernetes: { ready: false, unschedulable: true },
          }),
        ),
      ).toEqual({ variant: 'danger', label: 'NotReady' });
    });

    it('falls back to resource.status when ready is undefined', () => {
      expect(
        mapKubernetesNodeStatus(
          makeResource({ id: 'fallback-ok', type: 'k8s-node', status: 'online' }),
        ),
      ).toEqual({ variant: 'success', label: 'Ready' });
      expect(
        mapKubernetesNodeStatus(
          makeResource({ id: 'fallback-off', type: 'k8s-node', status: 'offline' }),
        ),
      ).toEqual({ variant: 'danger', label: 'NotReady' });
    });
  });

  describe('controller status mappers', () => {
    it('classifies Deployments by ready vs desired replicas', () => {
      const fullyReady = makeResource({
        id: 'dep-ok',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 3, readyReplicas: 3 },
      });
      const partiallyReady = makeResource({
        id: 'dep-partial',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 3, readyReplicas: 1 },
      });
      const zeroReady = makeResource({
        id: 'dep-zero',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 3, readyReplicas: 0 },
      });
      const scaledToZero = makeResource({
        id: 'dep-scaled-zero',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 0, readyReplicas: 0 },
      });

      expect(mapKubernetesDeploymentStatus(fullyReady).variant).toBe('success');
      expect(mapKubernetesDeploymentStatus(partiallyReady).variant).toBe('warning');
      expect(mapKubernetesDeploymentStatus(zeroReady).variant).toBe('danger');
      expect(mapKubernetesDeploymentStatus(scaledToZero).variant).toBe('muted');
    });

    it('shares the replica indicator across ReplicaSet and StatefulSet', () => {
      const partial = {
        kubernetes: { desiredReplicas: 5, readyReplicas: 2 },
      } as const;
      expect(
        mapKubernetesReplicaSetStatus(
          makeResource({ id: 'rs', type: 'k8s-replicaset', ...partial }),
        ).variant,
      ).toBe('warning');
      expect(
        mapKubernetesStatefulSetStatus(
          makeResource({ id: 'sts', type: 'k8s-statefulset', ...partial }),
        ).variant,
      ).toBe('warning');
    });

    it('flags misscheduled DaemonSet pods even when scheduling is otherwise complete', () => {
      const indicator = mapKubernetesDaemonSetStatus(
        makeResource({
          id: 'ds',
          type: 'k8s-daemonset',
          kubernetes: {
            desiredNumberScheduled: 3,
            numberReady: 3,
            numberMisscheduled: 1,
          },
        }),
      );
      expect(indicator).toEqual({ variant: 'warning', label: '1 misscheduled' });
    });

    it('classifies Jobs by failed/active/succeeded counts', () => {
      expect(
        mapKubernetesJobStatus(
          makeResource({ id: 'j-fail', type: 'k8s-job', kubernetes: { failed: 2 } }),
        ).variant,
      ).toBe('danger');
      expect(
        mapKubernetesJobStatus(
          makeResource({ id: 'j-active', type: 'k8s-job', kubernetes: { active: 1 } }),
        ).variant,
      ).toBe('warning');
      expect(
        mapKubernetesJobStatus(
          makeResource({ id: 'j-done', type: 'k8s-job', kubernetes: { succeeded: 1 } }),
        ).variant,
      ).toBe('success');
    });

    it('treats suspended CronJobs as muted', () => {
      expect(
        mapKubernetesCronJobStatus(
          makeResource({ id: 'cj', type: 'k8s-cronjob', kubernetes: { suspend: true } }),
        ),
      ).toEqual({ variant: 'muted', label: 'Suspended' });
      expect(
        mapKubernetesCronJobStatus(
          makeResource({ id: 'cj-on', type: 'k8s-cronjob', kubernetes: { suspend: false } }),
        ),
      ).toEqual({ variant: 'success', label: 'Scheduled' });
    });

    it('routes controllers to the correct mapper by resource type', () => {
      expect(
        mapKubernetesControllerStatus(
          makeResource({
            id: 'rs-routed',
            type: 'k8s-replicaset',
            kubernetes: { desiredReplicas: 2, readyReplicas: 0 },
          }),
        ).variant,
      ).toBe('danger');
      expect(
        mapKubernetesControllerStatus(
          makeResource({ id: 'cj-routed', type: 'k8s-cronjob', kubernetes: { suspend: true } }),
        ).variant,
      ).toBe('muted');
    });
  });

  describe('rank comparators float attention rows above healthy rows', () => {
    it('orders pods danger → warning → success', () => {
      const happy = makeResource({
        id: 'happy',
        type: 'pod',
        kubernetes: {
          podPhase: 'Running',
          podContainers: [{ ready: true, state: 'running' }],
        },
      });
      const pending = makeResource({
        id: 'pending',
        type: 'pod',
        kubernetes: { podPhase: 'Pending', podContainers: [] },
      });
      const crashing = makeResource({
        id: 'crashing',
        type: 'pod',
        kubernetes: {
          podPhase: 'Running',
          podContainers: [{ ready: false, state: 'waiting', reason: 'CrashLoopBackOff' }],
        },
      });

      expect([happy, pending, crashing].sort(compareKubernetesPods).map((r) => r.id)).toEqual([
        'crashing',
        'pending',
        'happy',
      ]);
    });

    it('floats NotReady nodes above Ready nodes', () => {
      const ready = makeResource({
        id: 'node-ready',
        type: 'k8s-node',
        kubernetes: { ready: true },
      });
      const notReady = makeResource({
        id: 'node-not-ready',
        type: 'k8s-node',
        kubernetes: { ready: false },
      });
      expect([ready, notReady].sort(compareKubernetesNodes).map((r) => r.id)).toEqual([
        'node-not-ready',
        'node-ready',
      ]);
    });

    it('orders Deployments by replica health', () => {
      const happy = makeResource({
        id: 'dep-happy',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 2, readyReplicas: 2 },
      });
      const partial = makeResource({
        id: 'dep-partial',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 2, readyReplicas: 1 },
      });
      const broken = makeResource({
        id: 'dep-broken',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 2, readyReplicas: 0 },
      });
      expect([happy, partial, broken].sort(compareKubernetesDeployments).map((r) => r.id)).toEqual([
        'dep-broken',
        'dep-partial',
        'dep-happy',
      ]);
    });

    it('mixes controller kinds in a single attention-first order', () => {
      const cronOk = makeResource({
        id: 'cron-ok',
        type: 'k8s-cronjob',
        kubernetes: { suspend: false },
      });
      const jobFailed = makeResource({
        id: 'job-fail',
        type: 'k8s-job',
        kubernetes: { failed: 1 },
      });
      const dsMisscheduled = makeResource({
        id: 'ds-mis',
        type: 'k8s-daemonset',
        kubernetes: { desiredNumberScheduled: 2, numberReady: 2, numberMisscheduled: 1 },
      });
      const rsHappy = makeResource({
        id: 'rs-ok',
        type: 'k8s-replicaset',
        kubernetes: { desiredReplicas: 1, readyReplicas: 1 },
      });
      // `muted` (suspended CronJob, scaled-to-zero Deployment, etc.) sits between
      // `warning` and `success` so deliberate-non-running rows float above
      // fully-healthy rows — matches the rank ordering vSphere already uses for
      // its VM status table.
      expect(
        [cronOk, jobFailed, dsMisscheduled, rsHappy]
          .sort(compareKubernetesControllers)
          .map((r) => r.id),
      ).toEqual(['job-fail', 'ds-mis', 'cron-ok', 'rs-ok']);
    });

    it('emits pre-sorted buckets from buildKubernetesPageModel', () => {
      const crashing = makeResource({
        id: 'pod-crash',
        type: 'pod',
        kubernetes: {
          podPhase: 'Running',
          podContainers: [{ ready: false, state: 'waiting', reason: 'CrashLoopBackOff' }],
        },
      });
      const happy = makeResource({
        id: 'pod-happy',
        type: 'pod',
        kubernetes: {
          podPhase: 'Running',
          podContainers: [{ ready: true, state: 'running' }],
        },
      });
      const partial = makeResource({
        id: 'dep-partial',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 3, readyReplicas: 1 },
      });
      const broken = makeResource({
        id: 'dep-broken',
        type: 'k8s-deployment',
        kubernetes: { desiredReplicas: 3, readyReplicas: 0 },
      });

      const model = buildKubernetesPageModel([happy, crashing, partial, broken]);
      expect(model.pods.map((r) => r.id)).toEqual(['pod-crash', 'pod-happy']);
      expect(model.deployments.map((r) => r.id)).toEqual(['dep-broken', 'dep-partial']);
      expect(model.workloads.slice(0, 2).map((r) => r.id)).toEqual(['dep-broken', 'dep-partial']);
    });
  });

  describe('buildKubernetesClusterChildCounts', () => {
    const cluster = (id: string, k: { clusterId?: string; clusterName?: string }): Resource =>
      makeResource({ id, type: 'k8s-cluster', kubernetes: k });

    it('walks resources once and rolls per-cluster nodes / pods / deployments', () => {
      const prod = cluster('cluster-prod', { clusterId: 'prod', clusterName: 'Production' });
      const stg = cluster('cluster-stg', { clusterId: 'stg', clusterName: 'Staging' });
      const resources = [
        prod,
        stg,
        makeResource({ id: 'n1', type: 'k8s-node', kubernetes: { clusterId: 'prod' } }),
        makeResource({ id: 'n2', type: 'k8s-node', kubernetes: { clusterId: 'prod' } }),
        makeResource({ id: 'n3', type: 'k8s-node', kubernetes: { clusterId: 'stg' } }),
        makeResource({ id: 'p1', type: 'pod', kubernetes: { clusterId: 'prod' } }),
        makeResource({ id: 'p2', type: 'pod', kubernetes: { clusterId: 'prod' } }),
        makeResource({ id: 'p3', type: 'pod', kubernetes: { clusterId: 'prod' } }),
        makeResource({ id: 'p4', type: 'pod', kubernetes: { clusterName: 'Staging' } }),
        makeResource({
          id: 'd1',
          type: 'k8s-deployment',
          kubernetes: { clusterId: 'prod' },
        }),
      ];

      const counts = buildKubernetesClusterChildCounts(resources, [prod, stg]);
      expect(counts.get('cluster-prod')).toEqual({
        nodes: { total: 2, attention: 0 },
        pods: { total: 3, attention: 0 },
        deployments: { total: 1, attention: 0 },
      });
      expect(counts.get('cluster-stg')).toEqual({
        nodes: { total: 1, attention: 0 },
        pods: { total: 1, attention: 0 },
        deployments: { total: 0, attention: 0 },
      });
    });

    it('tallies attention per bucket from the status mappers', () => {
      const prod = cluster('cluster-prod', { clusterId: 'prod' });
      const counts = buildKubernetesClusterChildCounts(
        [
          prod,
          makeResource({
            id: 'n-ready',
            type: 'k8s-node',
            kubernetes: { clusterId: 'prod', ready: true },
          }),
          makeResource({
            id: 'n-cordoned',
            type: 'k8s-node',
            kubernetes: { clusterId: 'prod', ready: true, unschedulable: true },
          }),
          makeResource({
            id: 'p-running',
            type: 'pod',
            kubernetes: {
              clusterId: 'prod',
              podPhase: 'Running',
              podContainers: [{ ready: true, state: 'running' }],
            },
          }),
          makeResource({
            id: 'p-crash',
            type: 'pod',
            kubernetes: {
              clusterId: 'prod',
              podPhase: 'Running',
              podContainers: [{ ready: false, state: 'waiting', reason: 'CrashLoopBackOff' }],
            },
          }),
          makeResource({
            id: 'd-scaled-to-zero',
            type: 'k8s-deployment',
            kubernetes: { clusterId: 'prod', desiredReplicas: 0 },
          }),
          makeResource({
            id: 'd-partial',
            type: 'k8s-deployment',
            kubernetes: { clusterId: 'prod', desiredReplicas: 3, readyReplicas: 1 },
          }),
        ],
        [prod],
      );
      expect(counts.get('cluster-prod')).toEqual({
        nodes: { total: 2, attention: 1 },
        pods: { total: 2, attention: 1 },
        // Scaled-to-zero is muted, not degraded; only the partial rollout
        // counts as attention.
        deployments: { total: 2, attention: 1 },
      });
    });

    it('counts agent rows that report a kubernetes source as cluster nodes', () => {
      const prod = cluster('cluster-prod', { clusterId: 'prod' });
      const counts = buildKubernetesClusterChildCounts(
        [
          prod,
          makeResource({
            id: 'merged-node',
            type: 'agent',
            sources: ['agent', 'kubernetes'],
            kubernetes: { clusterId: 'prod' },
          }),
          makeResource({
            id: 'plain-agent',
            type: 'agent',
            sources: ['agent'],
            kubernetes: { clusterId: 'prod' },
          }),
        ],
        [prod],
      );
      expect(counts.get('cluster-prod')).toEqual({
        nodes: { total: 1, attention: 0 },
        pods: { total: 0, attention: 0 },
        deployments: { total: 0, attention: 0 },
      });
    });

    it('ignores resources whose kubernetes.clusterId / clusterName matches no cluster row', () => {
      const prod = cluster('cluster-prod', { clusterId: 'prod' });
      const counts = buildKubernetesClusterChildCounts(
        [
          prod,
          makeResource({ id: 'orphan-pod', type: 'pod', kubernetes: { clusterId: 'gone' } }),
          makeResource({ id: 'no-cluster', type: 'pod', kubernetes: {} }),
        ],
        [prod],
      );
      expect(counts.get('cluster-prod')).toEqual({
        nodes: { total: 0, attention: 0 },
        pods: { total: 0, attention: 0 },
        deployments: { total: 0, attention: 0 },
      });
    });

    it('returns an empty map when there are no clusters', () => {
      expect(
        buildKubernetesClusterChildCounts(
          [makeResource({ id: 'p', type: 'pod', kubernetes: { clusterId: 'x' } })],
          [],
        ).size,
      ).toBe(0);
    });
  });

  describe('filterKubernetesResources', () => {
    const rows: Resource[] = [
      makeResource({
        id: 'pod-checkout',
        type: 'pod',
        status: 'online',
        kubernetes: {
          clusterName: 'prod-cluster',
          namespace: 'payments',
          podName: 'checkout-api-abc',
          ownerKind: 'Deployment',
          ownerName: 'checkout-api',
          image: 'ghcr.io/pulse-demo/checkout-api:2026.04',
        },
      }),
      makeResource({
        id: 'svc-checkout',
        type: 'k8s-service',
        status: 'online',
        kubernetes: { serviceType: 'ClusterIP', clusterIp: '10.0.5.4', namespace: 'payments' },
      }),
      makeResource({
        id: 'node-worker',
        type: 'k8s-node',
        status: 'degraded',
        kubernetes: { kubeletVersion: 'v1.30.4', roles: ['worker'] },
      }),
      makeResource({
        id: 'event-warn',
        type: 'k8s-event',
        status: 'online',
        kubernetes: { eventType: 'Warning', reason: 'BackOff', involvedName: 'checkout-api-abc' },
      }),
    ];

    it('matches kubernetes.* fields the shared filter no longer carries', () => {
      expect(
        filterKubernetesResources(rows, 'payments', 'all')
          .map((r) => r.id)
          .sort(),
      ).toEqual(['pod-checkout', 'svc-checkout'].sort());
      expect(filterKubernetesResources(rows, 'prod-cluster', 'all').map((r) => r.id)).toEqual([
        'pod-checkout',
      ]);
      expect(filterKubernetesResources(rows, 'v1.30.4', 'all').map((r) => r.id)).toEqual([
        'node-worker',
      ]);
      expect(filterKubernetesResources(rows, 'BackOff', 'all').map((r) => r.id)).toEqual([
        'event-warn',
      ]);
    });

    it('matches node-role labels via kubernetes.roles', () => {
      expect(filterKubernetesResources(rows, 'worker', 'all').map((r) => r.id)).toEqual([
        'node-worker',
      ]);
    });

    it('combines status and search', () => {
      expect(filterKubernetesResources(rows, 'v1.30', 'degraded').map((r) => r.id)).toEqual([
        'node-worker',
      ]);
      expect(filterKubernetesResources(rows, 'v1.30', 'online')).toEqual([]);
    });

    it('buckets the backend `warning` status into the degraded filter', () => {
      // The Kubernetes adapter emits `warning` (never `degraded`) for
      // unhealthy-but-alive rows; the Degraded chip must match them.
      const warningRows: Resource[] = [
        makeResource({
          id: 'pod-crashloop',
          type: 'pod',
          status: 'warning',
          kubernetes: { namespace: 'payments', podName: 'checkout-api-abc' },
        }),
        makeResource({ id: 'pod-healthy', type: 'pod', status: 'online' }),
      ];
      expect(filterKubernetesResources(warningRows, '', 'degraded').map((r) => r.id)).toEqual([
        'pod-crashloop',
      ]);
      expect(filterKubernetesResources(warningRows, '', 'online').map((r) => r.id)).toEqual([
        'pod-healthy',
      ]);
      expect(filterKubernetesResources(warningRows, '', 'offline')).toEqual([]);
    });
  });

  describe('kubernetesScopeLabel', () => {
    it('prefers the human cluster name over the internal cluster id', () => {
      expect(
        kubernetesScopeLabel(
          makeResource({
            id: 'pod-1',
            type: 'pod',
            kubernetes: {
              clusterId: 'k8s-production-1',
              clusterName: 'Production EU',
              namespace: 'services',
            },
          }),
        ),
      ).toBe('Production EU/services');
      expect(
        kubernetesClusterLabel(
          makeResource({
            id: 'pod-2',
            type: 'pod',
            kubernetes: { clusterId: 'k8s-production-1' },
          }),
        ),
      ).toBe('k8s-production-1');
    });

    it('falls back through namespace-only and empty scopes', () => {
      expect(
        kubernetesScopeLabel(
          makeResource({ id: 'ns-only', type: 'pod', kubernetes: { namespace: 'apps' } }),
        ),
      ).toBe('apps');
      expect(kubernetesScopeLabel(makeResource({ id: 'bare', type: 'pod' }))).toBe('Cluster');
    });
  });

  describe('mapKubernetesIncidentSeverity', () => {
    it('buckets severity strings into critical / warning / info', () => {
      expect(mapKubernetesIncidentSeverity('critical')).toBe('critical');
      expect(mapKubernetesIncidentSeverity('FATAL')).toBe('critical');
      expect(mapKubernetesIncidentSeverity('warning')).toBe('warning');
      expect(mapKubernetesIncidentSeverity('degraded')).toBe('warning');
      expect(mapKubernetesIncidentSeverity('info')).toBe('info');
      expect(mapKubernetesIncidentSeverity(undefined)).toBe('info');
    });
  });

  describe('buildKubernetesIncidentRows', () => {
    it('emits one row per ResourceIncident and sorts by severity then name', () => {
      const rows = buildKubernetesIncidentRows([
        makeResource({
          id: 'pod-payments',
          type: 'pod',
          kubernetes: { clusterName: 'prod', namespace: 'payments' },
          incidents: [
            { code: 'k8s_pod_crashloop', severity: 'critical', summary: 'CrashLoopBackOff' },
          ],
        }),
        makeResource({
          id: 'dep-checkout',
          type: 'k8s-deployment',
          kubernetes: { clusterName: 'prod', namespace: 'apps' },
          incidents: [
            {
              code: 'k8s_deployment_under_replicated',
              severity: 'warning',
              summary: '1 / 3 ready',
            },
          ],
        }),
      ]);

      expect(rows.map((r) => ({ id: r.resourceId, severity: r.severityBucket }))).toEqual([
        { id: 'pod-payments', severity: 'critical' },
        { id: 'dep-checkout', severity: 'warning' },
      ]);
      expect(rows[0].source).toBe('kubernetes');
      expect(rows[0].category).toBe('kubernetes-health');
    });

    it('falls back to a rollup row when only incidentSummary is present', () => {
      const rows = buildKubernetesIncidentRows([
        makeResource({
          id: 'node-worker',
          type: 'k8s-node',
          incidentSeverity: 'warning',
          incidentSummary: 'Disk pressure',
        }),
      ]);
      expect(rows).toHaveLength(1);
      expect(rows[0].id).toBe('node-worker:incident:rollup');
      expect(rows[0].summary).toBe('Disk pressure');
    });

    it('surfaces incidents on the page model output', () => {
      const model = buildKubernetesPageModel([
        makeResource({
          id: 'pod-crash',
          type: 'pod',
          incidents: [{ code: 'k8s_pod_crashloop', severity: 'critical', summary: 'crash' }],
        }),
        makeResource({ id: 'pod-ok', type: 'pod' }),
      ]);
      expect(model.incidents.map((r) => r.resourceId)).toEqual(['pod-crash']);
    });
  });

  describe('filterKubernetesIncidents', () => {
    const incidents = buildKubernetesIncidentRows([
      makeResource({
        id: 'pod-payments',
        type: 'pod',
        kubernetes: { clusterName: 'prod', namespace: 'payments' },
        incidents: [
          { code: 'k8s_pod_crashloop', severity: 'critical', summary: 'CrashLoopBackOff' },
        ],
      }),
      makeResource({
        id: 'dep-checkout',
        type: 'k8s-deployment',
        kubernetes: { clusterName: 'prod', namespace: 'apps' },
        incidents: [
          {
            code: 'k8s_deployment_under_replicated',
            severity: 'warning',
            summary: '1 / 3 ready',
          },
        ],
      }),
    ]);

    it('filters by severity bucket', () => {
      expect(filterKubernetesIncidents(incidents, '', 'critical').map((r) => r.resourceId)).toEqual(
        ['pod-payments'],
      );
      expect(filterKubernetesIncidents(incidents, '', 'warning').map((r) => r.resourceId)).toEqual([
        'dep-checkout',
      ]);
    });

    it('matches resource name, code, cluster, and namespace', () => {
      expect(
        filterKubernetesIncidents(incidents, 'crashloop', 'all').map((r) => r.resourceId),
      ).toEqual(['pod-payments']);
      expect(
        filterKubernetesIncidents(incidents, 'payments', 'all').map((r) => r.resourceId),
      ).toEqual(['pod-payments']);
      expect(filterKubernetesIncidents(incidents, 'prod', 'all').length).toBe(2);
    });
  });
});

describe('getKubernetesNodesNeedingAttention', () => {
  const node = (id: string, kubernetes: Record<string, unknown>, status = 'online') =>
    ({ id, name: id, type: 'k8s-node', status, kubernetes }) as never;

  it('names NotReady nodes first, then cordoned ones, and leaves Ready nodes out', () => {
    const nodes = [
      node('b-ready', { ready: true }),
      node('c-cordoned', { ready: true, unschedulable: true }),
      node('a-down', { ready: false }),
    ];

    const result = getKubernetesNodesNeedingAttention({ nodes } as never);

    expect(result.map((entry: { id: string }) => entry.id)).toEqual(['a-down', 'c-cordoned']);
  });

  // A node running a Pulse agent is an agent row whose alerts are keyed
  // "agent:<agentId>" and labelled with its hostname.
  const agentNode = (id: string, agentId: string, kubernetes: Record<string, unknown>) =>
    ({
      id,
      name: id,
      type: 'agent',
      status: 'online',
      agent: { agentId },
      kubernetes,
    }) as never;
  const alert = (id: string, resourceId: string, overrides: Partial<Alert> = {}): Alert => ({
    id,
    type: 'memory',
    level: 'critical',
    resourceId,
    resourceName: id,
    node: id,
    instance: '',
    message: id,
    value: 100,
    threshold: 90,
    startTime: '2026-10-06T10:00:00Z',
    acknowledged: false,
    ...overrides,
  });

  it('names Ready nodes with an unacknowledged open alert, critical ones with NotReady', () => {
    const nodes = [
      agentNode('a-ready', 'host-a', { ready: true }),
      agentNode('b-memory', 'host-b', { ready: true }),
      agentNode('c-cordoned', 'host-c', { ready: true, unschedulable: true }),
      agentNode('d-down', 'host-d', { ready: false }),
      agentNode('e-disk', 'host-e', { ready: true }),
      agentNode('f-acked', 'host-f', { ready: true }),
    ];
    const activeAlerts = {
      memory: alert('memory', 'agent:host-b'),
      // A component alert the drawer lists counts for its node too.
      disk: alert('disk', 'agent:host-e/disk:root', { type: 'disk', level: 'warning' }),
      acked: alert('acked', 'agent:host-f', { acknowledged: true }),
    };

    const result = getKubernetesNodesNeedingAttention({ nodes } as never, activeAlerts, true);

    // Within a rank, node state orders: NotReady ahead of a Ready node.
    expect(result.map((entry: { id: string }) => entry.id)).toEqual([
      'd-down',
      'b-memory',
      'c-cordoned',
      'e-disk',
    ]);
    // With alert detection off the list falls back to node state alone.
    expect(
      getKubernetesNodesNeedingAttention({ nodes } as never, activeAlerts, false).map(
        (entry: { id: string }) => entry.id,
      ),
    ).toEqual(['d-down', 'c-cordoned']);
  });

  it('counts alerts keyed on a node without an agent by its own id', () => {
    // Unified Kubernetes metric and incident alerts carry the resource id and
    // the cluster as their node.
    const nodes = [node('k8s-node-a', { ready: true }), node('k8s-node-b', { ready: true })];
    const activeAlerts = {
      cpu: alert('cpu', 'k8s-node-b', { type: 'cpu', level: 'warning', node: 'prod-west' }),
    };

    expect(
      getKubernetesNodesNeedingAttention({ nodes } as never, activeAlerts, true).map(
        (entry: { id: string }) => entry.id,
      ),
    ).toEqual(['k8s-node-b']);
  });

  it('ranks a node by the stronger of its state and its open alerts', () => {
    const ready = agentNode('ready', 'host-ready', { ready: true });
    const cordoned = agentNode('cordoned', 'host-cordoned', { ready: true, unschedulable: true });
    const warning = { w: alert('w', 'agent:host-ready', { level: 'warning' }) };
    const critical = { c: alert('c', 'agent:host-cordoned') };

    expect(getKubernetesNodeAttentionRank(ready, {}, true)).toBe(2);
    expect(getKubernetesNodeAttentionRank(ready, warning, true)).toBe(1);
    expect(getKubernetesNodeAttentionRank(cordoned, {}, true)).toBe(1);
    expect(getKubernetesNodeAttentionRank(cordoned, critical, true)).toBe(0);
  });
});