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.

82.6 KB
Raw Blame
import Loader2Icon from 'lucide-solid/icons/loader-2';
import MoreHorizontalIcon from 'lucide-solid/icons/more-horizontal';
import Trash2Icon from 'lucide-solid/icons/trash-2';
import {
  For,
  Show,
  createEffect,
  createMemo,
  createSignal,
  onCleanup,
  type Component,
  type JSX,
} from 'solid-js';
import { Portal } from 'solid-js/web';
import { AgentMetadataAPI, type AgentMetadata } from '@/api/agentMetadata';
import { MonitoringAPI } from '@/api/monitoring';
import { HOST_AGENT_STOPPED_REPORTING_REASON } from '@/components/Infrastructure/resourceDetailMappers';
import { EnhancedCPUBar } from '@/components/Workloads/EnhancedCPUBar';
import { MetricBar } from '@/components/Workloads/MetricBar';
import { StackedDiskBar } from '@/components/Workloads/StackedDiskBar';
import { StackedMemoryBar } from '@/components/Workloads/StackedMemoryBar';
import { ActionIconButton } from '@/components/shared/Button';
import { ColumnPicker } from '@/components/shared/ColumnPicker';
import { StatusDot } from '@/components/shared/StatusDot';
import { TemperatureGauge } from '@/components/shared/TemperatureGauge';
import { ResourceNameWithWebInterfaceLink } from '@/components/shared/WebInterfaceLink';
import { TableCell, TableHead, TableRow } from '@/components/shared/Table';
import { TooltipPortal } from '@/components/shared/TooltipPortal';
import { useWebSocket } from '@/contexts/appRuntime';
import { hostOverrideIdCandidates } from '@/features/alerts/alertOverridesModel';
import {
  compareAgentVersions,
  formatAgentVersionDisplay,
  hostAgentVersion,
} from '@/features/platformPage/agentVersion';
import {
  PlatformResourceDetailToggleButton,
  PlatformResourceDetailTableRow,
  createPlatformResourceDetailState,
  getPlatformResourceDetailRowClass,
} from '@/features/platformPage/PlatformResourceDetailTableRow';
import {
  PlatformWindowedRows,
  PLATFORM_HEALTH_FILTER_OPTIONS,
  PlatformTableEmptyState,
  PlatformTableMetricFallback,
  PlatformTableRelativeTimeValue,
  PlatformTableResetFiltersButton,
  PlatformTableShell,
  PlatformTableToolbar,
  createPlatformTableFilterState,
  filterPlatformResources,
  formatPlatformTableRelativeTimeValue,
  formatPlatformTableUptimeValue,
  getPlatformTableFiniteMetric,
  getPlatformTableCellClassForKind,
  getPlatformTableHeadClassForKind,
  type PlatformResourceStatusFilter,
  withPlatformStatusCounts,
} from '@/features/platformPage/sharedPlatformPage';
import { PHYSICAL_DISK_TEMPERATURE_LAST_KNOWN_CLASS } from '@/features/storageBackups/diskTemperaturePresentation';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import type { Disk } from '@/types/api';
import type { Resource, ResourceAvailabilityMeta } from '@/types/resource';
import type { MetricDisplayThresholds } from '@/utils/metricThresholds';
import {
  getActionableAgentIdFromResource,
  getAgentFirstReportStatusIndicator,
} from '@/utils/agentResources';
import { getUnifiedResourceAlertStyles } from '@/utils/alerts';
import { formatBytes, formatSpeed, formatObservedSpeed, normalizeDiskArray } from '@/utils/format';
import { STORAGE_KEYS } from '@/utils/localStorage';
import { useAlertsActivation } from '@/stores/alertsActivation';
import { notificationStore } from '@/stores/notifications';
import { buildMetricKeyForUnifiedResource } from '@/utils/metricsKeys';
import {
  RAID_LAST_KNOWN_DEVICE_BADGE_CLASS,
  getRaidDeviceBadgeClass,
  getRaidLastKnownDeviceLabel,
  getRaidStateTextClass,
  getRaidStateVariant,
} from '@/utils/raidPresentation';
import { asTrimmedString } from '@/utils/stringUtils';
import { getPreferredResourceIP } from '@/utils/resourceIdentity';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { formatTemperature } from '@/utils/temperature';
import {
  RESOURCE_METADATA_CHANGED_EVENT,
  type ResourceMetadataChangedDetail,
} from '@/utils/resourceMetadataEvents';
import { getWorkloadsGuestNetworkEmptyState } from '@/utils/workloadGuestPresentation';
import {
  AGENT_MACHINE_COLUMNS,
  getAgentMachineCpuPercent,
  getAgentMachineGPUTitle,
  getAgentMachineGPUUtilizationPercent,
  getAgentMachineDiskIODetails,
  getAgentMachineIpValues,
  matchesAgentMachineSearch,
  getAgentMachineNetworkInterfaceDetails,
  getAgentMachineNetworkTotal,
  getAgentMachinePrimaryIp,
  getAgentMachineRaidArrayDetails,
  getAgentMachineRaidSummary,
  getAgentMachineTemperatureCelsius,
  getAgentMachineTemperatureDetailSections,
  getAgentMachineHottestSmartDiskType,
  getAgentMachineTemperatureMetric,
  getAgentMachineTemperatureTitle,
  getAgentMachineThermalPressurePresentation,
  getNextAgentMachineSortState,
  isAgentMachineTemperatureLastKnown,
  sortAgentMachines,
  type AgentMachineColumn,
  type AgentMachineColumnId,
  type AgentMachineDiskIODetail,
  type AgentMachineNetworkInterfaceDetail,
  type AgentMachineRaidArrayDetail,
  type AgentMachineSortKey,
  type AgentMachineTemperatureDetailSection,
  type AgentMachineTemperatureMetric,
} from './agentMachineTableModel';
import { getStandaloneResourceStatusIndicator } from './standalonePageModel';

type MetricFallbackReason = {
  label: string;
  title: string;
};

const hasPositiveTemperature = (celsius: number | undefined): celsius is number =>
  typeof celsius === 'number' && Number.isFinite(celsius) && celsius > 0;

const AgentMachineMetricTooltip: Component<{
  triggerDataAttribute: string;
  tooltipDataAttribute: string;
  triggerClass: string;
  tooltipClass: string;
  enabled: boolean;
  ariaLabel?: string;
  title?: string;
  maxWidth: number;
  trigger: JSX.Element;
  children: JSX.Element;
}> = (props) => {
  const [visible, setVisible] = createSignal(false);
  const [position, setPosition] = createSignal({ x: 0, y: 0 });
  const triggerDataAttributes = () => ({ [props.triggerDataAttribute]: 'true' });
  const tooltipDataAttributes = () => ({ [props.tooltipDataAttribute]: 'true' });
  const enabled = () => props.enabled;
  const label = () => props.ariaLabel || props.title || undefined;
  const open = (event: MouseEvent | FocusEvent) => {
    if (!enabled()) return;
    const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
    setPosition({ x: rect.left + rect.width / 2, y: rect.top });
    setVisible(true);
  };
  const close = () => setVisible(false);

  return (
    <>
      <span
        {...triggerDataAttributes()}
        class={props.triggerClass}
        aria-label={label()}
        title={!enabled() ? props.title || undefined : undefined}
        tabIndex={enabled() ? 0 : undefined}
        onMouseEnter={open}
        onMouseOver={open}
        onMouseLeave={close}
        onFocus={open}
        onBlur={close}
        onClick={(event) => {
          event.stopPropagation();
          open(event);
        }}
      >
        {props.trigger}
      </span>
      <TooltipPortal
        when={visible() && enabled()}
        x={position().x}
        y={position().y}
        maxWidth={props.maxWidth}
      >
        <div {...tooltipDataAttributes()} class={props.tooltipClass}>
          {props.children}
        </div>
      </TooltipPortal>
    </>
  );
};

const AgentMachineTemperatureCell: Component<{
  celsius: number | undefined;
  /** The value is a retained reading, not a current one. */
  lastKnown?: boolean;
  metric: AgentMachineTemperatureMetric;
  sections: AgentMachineTemperatureDetailSection[];
  thresholds?: MetricDisplayThresholds | null;
  title: string;
  thermalPressure?: {
    label: string;
    title: string;
    className: string;
  };
}> = (props) => {
  const hasDetails = () => props.sections.length > 0;
  const positiveTemperature = () =>
    hasPositiveTemperature(props.celsius) ? props.celsius : undefined;
  const fallbackTitle = () => props.thermalPressure?.title ?? props.title;

  return (
    <AgentMachineMetricTooltip
      triggerDataAttribute="data-agent-machine-temperature-trigger"
      tooltipDataAttribute="data-agent-machine-temperature-tooltip"
      triggerClass="inline-flex min-w-9 justify-end text-xs tabular-nums"
      tooltipClass="min-w-[190px] max-w-[300px] space-y-2"
      enabled={hasDetails()}
      ariaLabel={fallbackTitle() || undefined}
      title={fallbackTitle()}
      maxWidth={320}
      trigger={
        <Show
          when={positiveTemperature()}
          fallback={
            <Show when={props.thermalPressure} fallback={<span class="text-muted">—</span>}>
              {(thermal) => (
                <span class={`text-[11px] font-medium ${thermal().className}`}>
                  {thermal().label}
                </span>
              )}
            </Show>
          }
        >
          {(value) => (
            <Show
              when={!props.lastKnown}
              fallback={
                // A retained reading takes no threshold colour; its detail
                // rows say it is last known.
                <span
                  class={`text-xs whitespace-nowrap ${PHYSICAL_DISK_TEMPERATURE_LAST_KNOWN_CLASS}`}
                  data-temperature-reading="last-known"
                >
                  {formatTemperature(value())}
                  <span class="sr-only">, last known</span>
                </span>
              }
            >
              <TemperatureGauge
                value={value()}
                metric={props.metric}
                thresholds={props.thresholds}
              />
            </Show>
          )}
        </Show>
      }
    >
      <For each={props.sections}>
        {(section) => (
          <section>
            <div class="mb-1 border-b border-border pb-1 font-semibold text-muted">
              {section.heading}
            </div>
            <div class="space-y-0.5">
              <For each={section.rows}>
                {(row) => (
                  <div class="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3">
                    <span class="min-w-0 truncate text-muted" title={row.label}>
                      {row.label}
                    </span>
                    <span
                      classList={{
                        'text-base-content': !row.muted,
                        'text-muted': row.muted,
                      }}
                      class="font-mono tabular-nums"
                    >
                      {row.value}
                    </span>
                  </div>
                )}
              </For>
            </div>
          </section>
        )}
      </For>
    </AgentMachineMetricTooltip>
  );
};

const AgentMachineNetworkInterfacesList: Component<{
  interfaces: AgentMachineNetworkInterfaceDetail[];
  maxInterfaces?: number;
  maxAddressesPerInterface?: number;
}> = (props) => {
  const maxInterfaces = () => props.maxInterfaces ?? 8;
  const maxAddressesPerInterface = () => props.maxAddressesPerInterface ?? 4;
  const shownInterfaces = () => props.interfaces.slice(0, maxInterfaces());
  const hiddenInterfaceCount = () =>
    Math.max(0, props.interfaces.length - shownInterfaces().length);

  return (
    <div class="max-h-[280px] space-y-1.5 overflow-y-auto pr-1">
      <For each={shownInterfaces()}>
        {(iface, index) => (
          <div class="min-w-0" classList={{ 'border-t border-border pt-1.5': index() > 0 }}>
            <div class="flex min-w-0 items-center gap-2">
              <span class="min-w-0 truncate font-semibold text-base-content" title={iface.name}>
                {iface.name}
              </span>
              <Show when={iface.mac}>
                {(mac) => (
                  <span
                    class="max-w-[150px] shrink-0 truncate font-mono text-[9px] text-muted"
                    title={mac()}
                  >
                    {mac()}
                  </span>
                )}
              </Show>
            </div>
            <Show
              when={iface.addresses.length > 0}
              fallback={
                <div class="mt-0.5 text-[9px] text-muted">
                  {getWorkloadsGuestNetworkEmptyState()}
                </div>
              }
            >
              <div class="mt-1 flex flex-wrap gap-1">
                <For each={iface.addresses.slice(0, maxAddressesPerInterface())}>
                  {(address) => (
                    <span
                      class="max-w-full truncate rounded-sm border border-border bg-surface-alt px-1.5 py-0.5 font-mono text-[9px] text-base-content"
                      title={address}
                    >
                      {address}
                    </span>
                  )}
                </For>
                <Show when={iface.addresses.length > maxAddressesPerInterface()}>
                  <span class="rounded-sm border border-border px-1.5 py-0.5 text-[9px] text-muted">
                    +{iface.addresses.length - maxAddressesPerInterface()}
                  </span>
                </Show>
              </div>
            </Show>
            <Show
              when={
                iface.rxBytes !== undefined ||
                iface.txBytes !== undefined ||
                iface.speedMbps !== undefined
              }
            >
              <div class="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[9px] text-muted">
                {/* Interface counters are cumulative totals, not rates — format as bytes. */}
                <Show when={iface.rxBytes !== undefined || iface.txBytes !== undefined}>
                  <span>
                    <span class="font-mono text-emerald-500">RX</span>{' '}
                    {formatBytes(iface.rxBytes ?? 0)}
                  </span>
                  <span>
                    <span class="font-mono text-orange-400">TX</span>{' '}
                    {formatBytes(iface.txBytes ?? 0)}
                  </span>
                </Show>
                <Show when={iface.speedMbps !== undefined}>
                  <span>{iface.speedMbps} Mbps</span>
                </Show>
              </div>
            </Show>
          </div>
        )}
      </For>
      <Show when={hiddenInterfaceCount() > 0}>
        <div class="border-t border-border pt-1 text-[9px] text-muted">
          +{hiddenInterfaceCount()} more interfaces
        </div>
      </Show>
    </div>
  );
};

const AgentMachineNetworkCell: Component<{
  network: Resource['network'] | undefined;
  interfaces: AgentMachineNetworkInterfaceDetail[];
  title: string;
}> = (props) => {
  const hasDetails = () => props.interfaces.length > 0;
  const ariaLabel = () => props.title.replace(/\n/g, ', ') || 'Network throughput';

  return (
    <AgentMachineMetricTooltip
      triggerDataAttribute="data-agent-machine-network-trigger"
      tooltipDataAttribute="data-agent-machine-network-tooltip"
      triggerClass="flex w-full min-w-0 items-center gap-1 text-[11px] tabular-nums"
      tooltipClass="min-w-[230px] max-w-[360px] space-y-2"
      enabled={hasDetails()}
      ariaLabel={ariaLabel()}
      title={props.title}
      maxWidth={380}
      trigger={
        <>
          <span class="inline-flex shrink-0 text-emerald-500">↓</span>
          <span class="min-w-0 truncate">{formatSpeed(props.network?.rxBytes ?? 0)}</span>
          <span class="inline-flex shrink-0 text-orange-400">↑</span>
          <span class="min-w-0 truncate">{formatSpeed(props.network?.txBytes ?? 0)}</span>
        </>
      }
    >
      <section>
        <div class="mb-1 border-b border-border pb-1 font-semibold text-muted">
          Network Interfaces
        </div>
        <AgentMachineNetworkInterfacesList interfaces={props.interfaces} />
      </section>
    </AgentMachineMetricTooltip>
  );
};

const AgentMachineIpCell: Component<{
  primaryIp: string;
  ipValues: string[];
  interfaces: AgentMachineNetworkInterfaceDetail[];
}> = (props) => {
  const hasDetails = () => props.ipValues.length > 0 || props.interfaces.length > 0;
  const shownIps = () => props.ipValues.slice(0, 12);
  const hiddenIpCount = () => Math.max(0, props.ipValues.length - shownIps().length);
  const additionalIpCount = () => Math.max(0, props.ipValues.length - (props.primaryIp ? 1 : 0));
  const title = () => props.ipValues.join('\n') || props.primaryIp || '—';
  const ariaLabel = () =>
    hasDetails() ? `IP details: ${props.ipValues.join(', ') || props.primaryIp}` : 'IP unavailable';

  return (
    <AgentMachineMetricTooltip
      triggerDataAttribute="data-agent-machine-ip-trigger"
      tooltipDataAttribute="data-agent-machine-ip-tooltip"
      triggerClass="inline-flex max-w-full min-w-0 justify-start"
      tooltipClass="min-w-[230px] max-w-[380px] space-y-2"
      enabled={hasDetails()}
      ariaLabel={ariaLabel()}
      title={title()}
      maxWidth={400}
      trigger={
        <span class="inline-flex max-w-full min-w-0 items-center gap-1.5">
          <span
            class="min-w-0 truncate font-mono text-[11px]"
            classList={{
              'text-base-content': Boolean(props.primaryIp),
              'text-muted': !props.primaryIp,
            }}
          >
            {props.primaryIp || '—'}
          </span>
          <Show when={additionalIpCount() > 0}>
            <span class="shrink-0 rounded-sm border border-border px-1 py-0.5 text-[9px] text-muted">
              +{additionalIpCount()}
            </span>
          </Show>
        </span>
      }
    >
      <section>
        <div class="mb-1 border-b border-border pb-1 font-semibold text-muted">IP Addresses</div>
        <Show
          when={shownIps().length > 0}
          fallback={<div class="text-[9px] text-muted">{getWorkloadsGuestNetworkEmptyState()}</div>}
        >
          <div class="flex max-h-[120px] flex-wrap gap-1 overflow-y-auto pr-1">
            <For each={shownIps()}>
              {(address) => (
                <span
                  class="max-w-full truncate rounded-sm border border-border bg-surface-alt px-1.5 py-0.5 font-mono text-[9px] text-base-content"
                  title={address}
                >
                  {address}
                </span>
              )}
            </For>
            <Show when={hiddenIpCount() > 0}>
              <span class="rounded-sm border border-border px-1.5 py-0.5 text-[9px] text-muted">
                +{hiddenIpCount()}
              </span>
            </Show>
          </div>
        </Show>
      </section>
      <Show when={props.interfaces.length > 0}>
        <section>
          <div class="mb-1 border-b border-border pb-1 font-semibold text-muted">
            Network Interfaces
          </div>
          <AgentMachineNetworkInterfacesList
            interfaces={props.interfaces}
            maxInterfaces={6}
            maxAddressesPerInterface={4}
          />
        </section>
      </Show>
    </AgentMachineMetricTooltip>
  );
};

const AgentMachineDiskIOCell: Component<{
  diskIO: Resource['diskIO'] | undefined;
  details: AgentMachineDiskIODetail[];
  title: string;
}> = (props) => {
  const hasDetails = () => props.details.length > 0;
  const shownDetails = () => props.details.slice(0, 8);
  const hiddenDetailCount = () => Math.max(0, props.details.length - shownDetails().length);
  const ariaLabel = () => props.title.replace(/\n/g, ', ') || 'Disk I/O throughput';
  const hasCounterValue = (disk: AgentMachineDiskIODetail) =>
    disk.readBytes !== undefined ||
    disk.writeBytes !== undefined ||
    disk.readOps !== undefined ||
    disk.writeOps !== undefined ||
    disk.readTimeMs !== undefined ||
    disk.writeTimeMs !== undefined ||
    disk.ioTimeMs !== undefined;

  return (
    <AgentMachineMetricTooltip
      triggerDataAttribute="data-agent-machine-diskio-trigger"
      tooltipDataAttribute="data-agent-machine-diskio-tooltip"
      triggerClass="flex w-full min-w-0 items-center gap-1 text-[11px] tabular-nums"
      tooltipClass="min-w-[230px] max-w-[360px] space-y-2"
      enabled={hasDetails()}
      ariaLabel={ariaLabel()}
      title={props.title}
      maxWidth={380}
      trigger={
        <>
          <span class="inline-flex shrink-0 font-mono text-blue-500">R</span>
          <span class="min-w-0 truncate">{formatObservedSpeed(props.diskIO?.readRate)}</span>
          <span class="inline-flex shrink-0 font-mono text-amber-500">W</span>
          <span class="min-w-0 truncate">{formatObservedSpeed(props.diskIO?.writeRate)}</span>
        </>
      }
    >
      <section>
        <div class="mb-1 border-b border-border pb-1 font-semibold text-muted">Disk I/O</div>
        <div class="mb-1 grid grid-cols-[auto_minmax(0,1fr)] gap-x-2 gap-y-0.5 text-[9px]">
          <span class="font-mono text-blue-500">Read</span>
          <span class="min-w-0 truncate text-base-content">
            {formatObservedSpeed(props.diskIO?.readRate)}
          </span>
          <span class="font-mono text-amber-500">Write</span>
          <span class="min-w-0 truncate text-base-content">
            {formatObservedSpeed(props.diskIO?.writeRate)}
          </span>
        </div>
        <div class="max-h-[280px] space-y-1.5 overflow-y-auto pr-1">
          <For each={shownDetails()}>
            {(disk, index) => (
              <div class="min-w-0" classList={{ 'border-t border-border pt-1.5': index() > 0 }}>
                <div class="truncate font-semibold text-base-content" title={disk.device}>
                  {disk.device}
                </div>
                <Show
                  when={hasCounterValue(disk)}
                  fallback={<div class="mt-0.5 text-[9px] text-muted">No device counters</div>}
                >
                  <div class="mt-1 grid grid-cols-[auto_minmax(0,1fr)_auto_minmax(0,1fr)] gap-x-2 gap-y-0.5 text-[9px] text-muted">
                    <Show when={disk.readBytes !== undefined || disk.writeBytes !== undefined}>
                      <span class="font-mono text-blue-500">R</span>
                      <span class="min-w-0 truncate">{formatBytes(disk.readBytes ?? 0)}</span>
                      <span class="font-mono text-amber-500">W</span>
                      <span class="min-w-0 truncate">{formatBytes(disk.writeBytes ?? 0)}</span>
                    </Show>
                    <Show when={disk.readOps !== undefined || disk.writeOps !== undefined}>
                      <span class="font-mono text-blue-500">RO</span>
                      <span class="min-w-0 truncate">{Math.round(disk.readOps ?? 0)}</span>
                      <span class="font-mono text-amber-500">WO</span>
                      <span class="min-w-0 truncate">{Math.round(disk.writeOps ?? 0)}</span>
                    </Show>
                    <Show when={disk.ioTimeMs !== undefined}>
                      <span class="font-mono">IO</span>
                      <span class="min-w-0 truncate">{Math.round(disk.ioTimeMs ?? 0)} ms</span>
                    </Show>
                  </div>
                </Show>
              </div>
            )}
          </For>
          <Show when={hiddenDetailCount() > 0}>
            <div class="border-t border-border pt-1 text-[9px] text-muted">
              +{hiddenDetailCount()} more devices
            </div>
          </Show>
        </div>
      </section>
    </AgentMachineMetricTooltip>
  );
};

const AgentMachineRaidCell: Component<{
  arrays: AgentMachineRaidArrayDetail[];
  summary: string;
  /** Why the array states are retained rather than current. */
  lastKnownReason?: string;
}> = (props) => {
  const hasDetails = () => props.arrays.length > 0;
  // A silent agent's arrays are its last report: keep the states as evidence
  // without live status colour or rebuild progress.
  const lastKnownTitle = () => {
    const reason = props.lastKnownReason?.trim();
    return reason ? `Last known reading, not current: ${reason}` : undefined;
  };
  const shownArrays = () => props.arrays.slice(0, 6);
  const hiddenArrayCount = () => Math.max(0, props.arrays.length - shownArrays().length);
  const triggerLabel = () => props.summary || '—';
  const stateLabel = (state: string) => asTrimmedString(state) ?? 'unknown';
  const arrayLabel = (array: AgentMachineRaidArrayDetail) =>
    asTrimmedString(array.name) ?? asTrimmedString(array.device) ?? 'RAID array';
  const rebuildWidth = (percent: number) => `${Math.min(100, Math.max(0, percent))}%`;

  return (
    <AgentMachineMetricTooltip
      triggerDataAttribute="data-agent-machine-raid-trigger"
      tooltipDataAttribute="data-agent-machine-raid-tooltip"
      triggerClass="inline-flex max-w-full justify-start"
      tooltipClass="min-w-[250px] max-w-[380px] space-y-2"
      enabled={hasDetails()}
      ariaLabel={
        hasDetails()
          ? `RAID details: ${triggerLabel()}${lastKnownTitle() ? ', last known' : ''}`
          : 'RAID unavailable'
      }
      title={lastKnownTitle() ? `${triggerLabel()}. ${lastKnownTitle()}` : triggerLabel()}
      maxWidth={400}
      trigger={
        <span
          class="max-w-full truncate text-[11px] font-medium"
          classList={{
            'text-base-content': hasDetails() && !lastKnownTitle(),
            'text-muted': !hasDetails() || Boolean(lastKnownTitle()),
          }}
          data-raid-reading={lastKnownTitle() ? 'last-known' : 'current'}
        >
          {triggerLabel()}
          <Show when={hasDetails() && lastKnownTitle()}>
            <span class="sr-only">, last known</span>
          </Show>
        </span>
      }
    >
      <section>
        <div class="mb-1 border-b border-border pb-1 font-semibold text-muted">
          {lastKnownTitle() ? 'RAID Arrays (last known)' : 'RAID Arrays'}
        </div>
        <div class="max-h-[300px] space-y-2 overflow-y-auto pr-1">
          <For each={shownArrays()}>
            {(array, index) => {
              const rebuildPercent = () => array.rebuildPercent ?? 0;
              const devices = () => array.devices ?? [];
              const rebuilding = () => Number.isFinite(rebuildPercent()) && rebuildPercent() > 0;

              return (
                <div class="min-w-0" classList={{ 'border-t border-border pt-2': index() > 0 }}>
                  <div class="flex min-w-0 items-start justify-between gap-2">
                    <div class="min-w-0">
                      <div
                        class="truncate font-semibold text-base-content"
                        title={arrayLabel(array)}
                      >
                        {arrayLabel(array)}
                      </div>
                      <div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[9px] text-muted">
                        <span class="font-mono uppercase">{array.level}</span>
                        <Show when={array.device && array.device !== arrayLabel(array)}>
                          <span class="font-mono">{array.device}</span>
                        </Show>
                      </div>
                    </div>
                    <div
                      class="flex shrink-0 items-center gap-1.5"
                      title={lastKnownTitle() ?? stateLabel(array.state)}
                    >
                      <StatusDot
                        variant={lastKnownTitle() ? 'muted' : getRaidStateVariant(array.state)}
                        size="xs"
                        ariaHidden
                      />
                      <span
                        class={`text-[10px] font-medium ${
                          lastKnownTitle() ? 'text-muted' : getRaidStateTextClass(array.state)
                        }`}
                      >
                        {stateLabel(array.state)}
                      </span>
                    </div>
                  </div>

                  <div class="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[9px] text-muted">
                    <span>
                      Active <span class="font-mono text-base-content">{array.activeDevices}</span>/
                      <span class="font-mono text-base-content">{array.totalDevices}</span>
                    </span>
                    <span>
                      Working{' '}
                      <span class="font-mono text-base-content">{array.workingDevices}</span>
                    </span>
                    <Show when={array.spareDevices > 0}>
                      <span>
                        Spare <span class="font-mono text-base-content">{array.spareDevices}</span>
                      </span>
                    </Show>
                    <Show when={array.failedDevices > 0}>
                      <span>
                        Failed{' '}
                        <span
                          class="font-mono"
                          classList={{
                            'text-red-600 dark:text-red-400': !lastKnownTitle(),
                            'text-base-content': Boolean(lastKnownTitle()),
                          }}
                        >
                          {array.failedDevices}
                        </span>
                      </span>
                    </Show>
                  </div>

                  <Show when={rebuilding()}>
                    <Show
                      when={!lastKnownTitle()}
                      fallback={
                        <div class="mt-1.5 text-[9px] text-muted">
                          Rebuild was at {Math.round(rebuildPercent())}%
                        </div>
                      }
                    >
                      <div class="mt-1.5">
                        <div class="mb-0.5 flex items-center justify-between gap-3 text-[9px]">
                          <span class="text-amber-600 dark:text-amber-400">Rebuilding</span>
                          <span class="font-mono text-base-content">
                            {Math.round(rebuildPercent())}%
                          </span>
                        </div>
                        <div class="h-1 overflow-hidden rounded-full bg-surface-alt">
                          <div
                            class="h-full rounded-full bg-amber-500"
                            style={{ width: rebuildWidth(rebuildPercent()) }}
                          />
                        </div>
                        <Show when={array.rebuildSpeed}>
                          {(speed) => <div class="mt-0.5 text-[9px] text-muted">{speed()}</div>}
                        </Show>
                      </div>
                    </Show>
                  </Show>

                  <Show when={devices().length > 0}>
                    <div class="mt-1.5 flex flex-wrap gap-1">
                      <For each={devices().slice(0, 12)}>
                        {(device) => (
                          <span
                            class={`inline-flex max-w-full items-center truncate rounded-sm border px-1.5 py-0.5 text-[9px] font-medium ${
                              lastKnownTitle()
                                ? RAID_LAST_KNOWN_DEVICE_BADGE_CLASS
                                : getRaidDeviceBadgeClass(device)
                            }`}
                            title={`slot ${device.slot} - ${device.state}`}
                          >
                            {lastKnownTitle() ? getRaidLastKnownDeviceLabel(device) : device.device}
                          </span>
                        )}
                      </For>
                      <Show when={devices().length > 12}>
                        <span class="rounded-sm border border-border px-1.5 py-0.5 text-[9px] text-muted">
                          +{devices().length - 12}
                        </span>
                      </Show>
                    </div>
                  </Show>
                </div>
              );
            }}
          </For>
          <Show when={hiddenArrayCount() > 0}>
            <div class="border-t border-border pt-1 text-[9px] text-muted">
              +{hiddenArrayCount()} more arrays
            </div>
          </Show>
        </div>
      </section>
    </AgentMachineMetricTooltip>
  );
};

const AgentMachineActionsCell: Component<{
  name: string;
  agentId: string;
  menuOpen: boolean;
  confirmingRemoval: boolean;
  removing: boolean;
  onToggleMenu: () => void;
  onRemove: () => void;
}> = (props) => {
  const removeLabel = () => `Remove ${props.name} from Pulse`;
  const confirmLabel = () => `Confirm remove ${props.name} from Pulse`;
  const [menuPosition, setMenuPosition] = createSignal({ left: 0, top: 0 });
  let triggerRef: HTMLButtonElement | undefined;
  const updateMenuPosition = () => {
    if (!triggerRef || typeof window === 'undefined') return;
    const rect = triggerRef.getBoundingClientRect();
    const menuWidth = 240;
    setMenuPosition({
      left: Math.max(8, Math.min(window.innerWidth - menuWidth - 8, rect.right - menuWidth)),
      top: rect.bottom + 4,
    });
  };

  createEffect(() => {
    if (!props.menuOpen || typeof window === 'undefined') return;
    updateMenuPosition();
    window.addEventListener('resize', updateMenuPosition);
    window.addEventListener('scroll', updateMenuPosition, true);
    onCleanup(() => {
      window.removeEventListener('resize', updateMenuPosition);
      window.removeEventListener('scroll', updateMenuPosition, true);
    });
  });

  return (
    <div
      data-agent-machine-actions-root
      class="relative flex justify-center"
      onClick={(event) => event.stopPropagation()}
      onKeyDown={(event) => {
        event.stopPropagation();
        if (event.key === 'Escape' && props.menuOpen) props.onToggleMenu();
      }}
    >
      <ActionIconButton
        ref={triggerRef}
        label={`Machine actions for ${props.name}`}
        tone="muted"
        size="sm"
        class="-my-2 min-h-11 min-w-11 sm:-my-0.5 sm:min-h-0 sm:min-w-0"
        aria-haspopup="menu"
        aria-expanded={props.menuOpen ? 'true' : 'false'}
        onClick={(event) => {
          event.stopPropagation();
          updateMenuPosition();
          props.onToggleMenu();
        }}
      >
        <MoreHorizontalIcon class="h-3.5 w-3.5" />
      </ActionIconButton>

      <Show when={props.menuOpen}>
        <Portal mount={document.body}>
          <div
            data-agent-machine-actions-root
            data-agent-machine-actions-menu
            role="menu"
            class="fixed z-9999 w-60 rounded-md border border-border bg-surface p-1 text-left shadow-lg"
            style={{
              left: `${menuPosition().left}px`,
              top: `${menuPosition().top}px`,
            }}
            onMouseDown={(event) => event.stopPropagation()}
            onClick={(event) => event.stopPropagation()}
            onKeyDown={(event) => {
              event.stopPropagation();
              if (event.key === 'Escape' && props.menuOpen) props.onToggleMenu();
            }}
          >
            <button
              type="button"
              role="menuitem"
              class="flex min-h-11 w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium text-red-600 transition-colors hover:bg-red-50 focus:outline-hidden focus-visible:ring-2 focus-visible:ring-red-500/60 disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-0 dark:text-red-400 dark:hover:bg-red-950/25"
              aria-label={props.confirmingRemoval ? confirmLabel() : removeLabel()}
              disabled={props.removing || !props.agentId}
              onClick={(event) => {
                event.stopPropagation();
                props.onRemove();
              }}
            >
              <Show
                when={props.removing}
                fallback={<Trash2Icon class="h-3.5 w-3.5 shrink-0" aria-hidden="true" />}
              >
                <Loader2Icon class="h-3.5 w-3.5 shrink-0 animate-spin" aria-hidden="true" />
              </Show>
              <span class="min-w-0 truncate">
                {props.removing
                  ? 'Removing...'
                  : props.confirmingRemoval
                    ? 'Click again to confirm'
                    : 'Remove from Pulse'}
              </span>
            </button>

            <Show when={props.confirmingRemoval}>
              <p class="px-2 pb-1.5 pt-1 text-[10px] leading-snug text-muted">
                Pulse will forget this machine. The agent stays installed until you run the
                uninstall command.
              </p>
            </Show>
          </div>
        </Portal>
      </Show>
    </div>
  );
};

const availabilityFor = (machine: Resource): ResourceAvailabilityMeta | undefined =>
  machine.availability ??
  (machine.platformData?.availability as ResourceAvailabilityMeta | undefined);

const isAgentlessMachine = (machine: Resource): boolean =>
  machine.type !== 'agent' &&
  machine.sourceType !== 'agent' &&
  machine.platformType !== 'agent' &&
  String(availabilityFor(machine)?.targetKind ?? '')
    .trim()
    .toLowerCase() === 'machine';

const availabilityAddressFor = (machine: Resource): string => {
  const availability = availabilityFor(machine);
  const address = asTrimmedString(availability?.address);
  if (address) return address;
  const identityWithIPAddresses = machine.identity as
    (Resource['identity'] & { ipAddresses?: string[] }) | undefined;
  const firstIP = asTrimmedString(
    identityWithIPAddresses?.ipAddresses?.[0] ?? machine.identity?.ips?.[0],
  );
  if (firstIP) return firstIP;
  return asTrimmedString(machine.identity?.hostname) ?? '';
};

const memoryTotalFor = (machine: Resource): number =>
  getPlatformTableFiniteMetric(machine.memory?.total) ??
  getPlatformTableFiniteMetric(machine.agent?.memory?.total) ??
  0;

const memoryUsedFor = (machine: Resource): number =>
  getPlatformTableFiniteMetric(machine.memory?.used) ??
  getPlatformTableFiniteMetric(machine.agent?.memory?.used) ??
  0;

const memoryPercentOnlyFor = (machine: Resource): number | undefined => {
  if (memoryTotalFor(machine) > 0) return undefined;
  return (
    getPlatformTableFiniteMetric(machine.memory?.current) ??
    getPlatformTableFiniteMetric(machine.agent?.memory?.usage)
  );
};

const memoryUnavailableFor = (machine: Resource): boolean =>
  !machine.memory && machine.agent?.memory?.usageUnavailable === true;

const memoryBalloonFor = (machine: Resource): number | undefined =>
  getPlatformTableFiniteMetric(machine.agent?.memory?.balloon);

const memoryCacheFor = (machine: Resource): number | undefined =>
  getPlatformTableFiniteMetric(machine.agent?.memory?.cache);

const memorySwapUsedFor = (machine: Resource): number | undefined =>
  getPlatformTableFiniteMetric(machine.agent?.memory?.swapUsed);

const memorySwapTotalFor = (machine: Resource): number | undefined =>
  getPlatformTableFiniteMetric(machine.agent?.memory?.swapTotal);

const cpuCoresFor = (machine: Resource): number | undefined => {
  const cores = getPlatformTableFiniteMetric(machine.agent?.cpuCount);
  return cores && cores > 0 ? cores : undefined;
};

const cpuLoadAverageFor = (machine: Resource): number | undefined =>
  getPlatformTableFiniteMetric(machine.agent?.loadAverage?.[0]);

const aggregateDiskFor = (machine: Resource): Disk | undefined => {
  if (!machine.disk) return undefined;
  const total = getPlatformTableFiniteMetric(machine.disk.total) ?? 0;
  const used = getPlatformTableFiniteMetric(machine.disk.used) ?? 0;
  const free =
    getPlatformTableFiniteMetric(machine.disk.free) ?? (total > 0 ? Math.max(0, total - used) : 0);
  const usage =
    total > 0 && used > 0
      ? (used / total) * 100
      : (getPlatformTableFiniteMetric(machine.disk.current) ?? 0);
  if (total <= 0 && usage <= 0) return undefined;
  return { total, used, free, usage };
};

const titleCase = (value: string): string =>
  value
    .split(/[\s_-]+/)
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
    .join(' ');

const SYSTEM_NAME_OVERRIDES = new Map<string, string>([
  ['darwin', 'macOS'],
  ['freebsd', 'FreeBSD'],
  ['linux', 'Linux'],
  ['mac os', 'macOS'],
  ['macos', 'macOS'],
  ['microsoft windows', 'Windows'],
  ['unraid', 'Unraid'],
  ['win32', 'Windows'],
  ['windows', 'Windows'],
]);

const systemNameForDisplay = (value: string, titleCaseFallback = false): string => {
  const trimmed = value.trim();
  if (!trimmed) return '';

  const normalized = trimmed.toLowerCase().replace(/[_-]+/g, ' ').replace(/\s+/g, ' ');
  return (
    SYSTEM_NAME_OVERRIDES.get(normalized) ?? (titleCaseFallback ? titleCase(trimmed) : trimmed)
  );
};

const normalizedIdentityToken = (value: string | undefined): string =>
  (value ?? '').trim().toLowerCase();

const appendUniqueMachineSubtitlePart = (parts: string[], value: string | undefined) => {
  const normalized = normalizedIdentityToken(value);
  if (!normalized || parts.some((part) => normalizedIdentityToken(part) === normalized)) return;
  parts.push(value?.trim() ?? '');
};

const machineRowSubtitleFor = (
  name: string,
  hostname: string | undefined,
  primaryIp: string,
  lastSeen: string,
  includePrimaryIp: boolean,
  includeLastSeen: boolean,
): string => {
  const parts: string[] = [];

  if (normalizedIdentityToken(hostname) !== normalizedIdentityToken(name)) {
    appendUniqueMachineSubtitlePart(parts, hostname);
  }
  if (includePrimaryIp) {
    appendUniqueMachineSubtitlePart(parts, primaryIp);
  }
  if (includeLastSeen && lastSeen && lastSeen !== '—') {
    appendUniqueMachineSubtitlePart(parts, `seen ${lastSeen}`);
  }

  return parts.slice(0, 2).join(' | ');
};

const systemLabelFor = (machine: Resource): string => {
  if (isAgentlessMachine(machine)) {
    const protocol = (asTrimmedString(availabilityFor(machine)?.protocol) ?? '').toUpperCase();
    return protocol ? `${protocol} availability` : 'Agentless availability';
  }
  const osName = asTrimmedString(machine.agent?.osName);
  const osVersion = asTrimmedString(machine.agent?.osVersion);
  if (osName && osVersion) return `${systemNameForDisplay(osName)} ${osVersion}`;
  if (osName) return systemNameForDisplay(osName);
  return systemNameForDisplay(
    asTrimmedString(machine.agent?.platform) || asTrimmedString(machine.technology) || 'Agent',
    true,
  );
};

const agentVersionFor = (machine: Resource): string =>
  isAgentlessMachine(machine) ? 'Agentless' : asTrimmedString(machine.agent?.agentVersion) || '—';

const outdatedAgentTelemetryFallbackFor = (
  machine: Resource,
  targetAgentVersion: string | null | undefined,
): MetricFallbackReason | undefined => {
  if (isAgentlessMachine(machine)) return undefined;

  const agentVersion = hostAgentVersion(machine);
  const comparison = compareAgentVersions(agentVersion, targetAgentVersion);
  if (comparison === null || comparison >= 0) return undefined;

  const current = formatAgentVersionDisplay(agentVersion) || agentVersion || 'this version';
  const target = formatAgentVersionDisplay(targetAgentVersion) || targetAgentVersion;
  return {
    label: 'old agent',
    title: target
      ? `Update this agent from ${current} to ${target} for full machine telemetry.`
      : `Update this agent from ${current} for full machine telemetry.`,
  };
};

const filterAgentMachineResources = (
  resources: Resource[],
  search: string,
  status: PlatformResourceStatusFilter,
  nowMs: number,
): Resource[] =>
  filterPlatformResources(resources, '', status, (machine) => {
    // Health is the row's current presentation, not its last reported status.
    // Never write this derived classification back into the canonical resource.
    const variant = getStandaloneResourceStatusIndicator(machine, nowMs).variant;
    if (variant === 'success') return 'online';
    if (variant === 'warning') return 'degraded';
    if (variant === 'danger') return 'offline';
    return 'unknown';
  }).filter((machine) =>
    matchesAgentMachineSearch(machine, search, systemLabelFor, agentVersionFor),
  );

const AGENT_MACHINE_SEARCH_TIPS = {
  popoverId: 'machines-search-help',
  intro: 'Filter Pulse Agent machines by identity, platform, or reported inventory.',
  tips: [
    { code: 'mac-mini', description: 'Match hostnames and display names' },
    { code: '192.168.0.98', description: 'Find reported IP addresses' },
    { code: 'macos', description: 'Find operating system names or versions' },
    { code: 'arm64', description: 'Match CPU architecture' },
    { code: 'darwin', description: 'Find kernel or platform details' },
  ],
  footerHighlight: 'Tip',
  footerText: 'Hidden columns such as IP, RAID, Arch, and Kernel are still searchable.',
};

const networkTitleFor = (machine: Resource): string => {
  if (!machine.network) return '';
  return `In ${formatSpeed(machine.network.rxBytes)}\nOut ${formatSpeed(machine.network.txBytes)}`;
};

const diskIOTitleFor = (machine: Resource): string => {
  if (!machine.diskIO) return '';
  return `Read ${formatObservedSpeed(machine.diskIO.readRate)}\nWrite ${formatObservedSpeed(machine.diskIO.writeRate)}`;
};

const agentIdentityIdFor = (machine: Resource): string =>
  asTrimmedString(getActionableAgentIdFromResource(machine)) || asTrimmedString(machine.id) || '';

const agentMetadataIdFor = (machine: Resource): string =>
  isAgentlessMachine(machine) ? '' : agentIdentityIdFor(machine);

const agentRemovalIdFor = (machine: Resource): string => {
  if (isAgentlessMachine(machine)) return '';
  return agentIdentityIdFor(machine);
};

const machineColumnWidthClass = (columnId: AgentMachineColumnId): string => {
  switch (columnId) {
    case 'machine':
      return 'platform-table-mobile-w-30 w-[30%] sm:w-[28%] md:w-[15%]';
    case 'system':
      return 'hidden md:table-cell md:w-[12%]';
    case 'agent':
      return 'hidden md:table-cell md:w-[6%]';
    case 'cpu':
    case 'memory':
      return 'platform-table-mobile-w-15 w-[15%] sm:w-[20%] md:w-[8%]';
    case 'disk':
      return 'platform-table-mobile-w-15 w-[15%] sm:w-[20%] md:w-[8%]';
    case 'gpu':
      return 'hidden md:table-cell md:w-[8%]';
    case 'network':
    case 'diskio':
      return 'hidden lg:table-cell lg:w-[9%]';
    case 'uptime':
    case 'temp':
      return 'hidden md:table-cell md:w-[5%]';
    case 'lastSeen':
      return 'platform-table-mobile-w-15 w-[15%] lg:w-[6%]';
    case 'ip':
      return 'agent-machine-address-column hidden xl:table-cell xl:w-[8%]';
    case 'raid':
      return 'hidden xl:table-cell xl:w-[6%]';
    case 'arch':
      return 'hidden xl:table-cell xl:w-[5%]';
    case 'kernel':
      return 'hidden xl:table-cell xl:w-[10%]';
    case 'actions':
      return 'platform-table-narrow-hidden w-[10%] md:w-[4%]';
  }
};

const getSortIndicator = (
  activeKey: AgentMachineSortKey,
  direction: 'asc' | 'desc',
  key: AgentMachineSortKey | undefined,
): '▲' | '▼' | '' => {
  if (!key || activeKey !== key) return '';
  return direction === 'asc' ? '▲' : '▼';
};

const getCompactColumnLabel = (column: AgentMachineColumn): string => {
  switch (column.id) {
    case 'uptime':
      return 'Up';
    case 'lastSeen':
      return 'Seen';
    default:
      return column.label;
  }
};

const AgentMachineSortableHead: Component<{
  column: AgentMachineColumn;
  activeSort: AgentMachineSortKey;
  direction: 'asc' | 'desc';
  onSort: (key: AgentMachineSortKey) => void;
}> = (props) => {
  const sortIndicator = () =>
    getSortIndicator(props.activeSort, props.direction, props.column.sortKey);
  const kind = (): NonNullable<AgentMachineColumn['kind']> => props.column.kind ?? 'text';

  return (
    <TableHead
      class={`${getPlatformTableHeadClassForKind(kind())} ${machineColumnWidthClass(props.column.id)}`}
      aria-sort={
        props.column.sortKey && props.activeSort === props.column.sortKey
          ? props.direction === 'asc'
            ? 'ascending'
            : 'descending'
          : undefined
      }
    >
      <Show
        when={props.column.sortKey}
        fallback={
          <span class={props.column.id === 'actions' ? 'sr-only' : 'truncate'}>
            {props.column.label}
          </span>
        }
      >
        {(sortKey) => (
          <button
            type="button"
            class="-my-3 inline-flex min-h-11 max-w-full items-center gap-1 truncate py-3 hover:text-base-content focus:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-500/60 sm:my-0 sm:min-h-0 sm:py-0"
            onClick={() => props.onSort(sortKey())}
            aria-label={`Sort by ${props.column.label}`}
          >
            <span class="truncate">
              <Show
                when={props.column.id === 'memory'}
                fallback={getCompactColumnLabel(props.column)}
              >
                <span class="md:hidden">Mem</span>
                <span class="hidden md:inline">Memory</span>
              </Show>
            </span>
            <span class="w-2 shrink-0 text-[9px]" aria-hidden="true">
              {sortIndicator()}
            </span>
          </button>
        )}
      </Show>
    </TableHead>
  );
};

export const AgentsMachinesTable: Component<{
  resources: Resource[];
  emptyIcon: JSX.Element;
  emptyTitle: string;
  emptyDescription: string;
  targetAgentVersion?: string | null;
  externalSearch?: () => string;
  onExternalSearchChange?: (value: string) => void;
  externalStatus?: () => PlatformResourceStatusFilter;
  onExternalStatusChange?: (value: PlatformResourceStatusFilter) => void;
  onResetFilters?: () => void;
}> = (props) => {
  // A machine that stops reporting keeps the same last-seen time, which is
  // exactly when its age must keep moving, so row ages read the shared clock.
  const now = useRelativeTimeNow();
  const [locallyRemovedResourceIds, setLocallyRemovedResourceIds] = createSignal<
    Record<string, boolean>
  >({});
  const visibleMachineResources = createMemo(() =>
    props.resources.filter((machine) => !locallyRemovedResourceIds()[machine.id]),
  );
  const tableState = createPlatformTableFilterState({
    resources: visibleMachineResources,
    initialStatus: 'all' as PlatformResourceStatusFilter,
    filter: (resources, search, status) =>
      filterAgentMachineResources(resources, search, status, now()),
    externalSearch: props.externalSearch,
    onExternalSearchChange: props.onExternalSearchChange,
    externalStatus: props.externalStatus,
    onExternalStatusChange: props.onExternalStatusChange,
  });
  const resetFilters = () => {
    if (props.onResetFilters) {
      props.onResetFilters();
      return;
    }
    tableState.resetFilters();
  };
  const { activeAlerts } = useWebSocket();
  const alertsActivation = useAlertsActivation();
  const [sortKey, setSortKey] = createSignal<AgentMachineSortKey>('name');
  const [sortDirection, setSortDirection] = createSignal<'asc' | 'desc'>('asc');
  const relevantMachineColumns = createMemo(() => {
    const relevant = new Set(AGENT_MACHINE_COLUMNS.map((column) => column.id));
    const hasGPUUtilization = visibleMachineResources().some(
      (machine) => getAgentMachineGPUUtilizationPercent(machine) !== undefined,
    );
    if (!hasGPUUtilization) relevant.delete('gpu');
    return relevant;
  });
  const columnVisibility = useColumnVisibility(
    'pulse:standalone:machines:columns:v4',
    AGENT_MACHINE_COLUMNS,
    [],
    relevantMachineColumns,
    {},
    ['network', 'diskio', 'uptime', 'temp'],
  );
  const drawer = createPlatformResourceDetailState({ idPrefix: 'agents-machine-drawer' });
  const [agentMetadataById, setAgentMetadataById] = createSignal<Record<string, AgentMetadata>>({});
  const [actionsMenuResourceId, setActionsMenuResourceId] = createSignal<string | null>(null);
  const [confirmingRemovalResourceId, setConfirmingRemovalResourceId] = createSignal<string | null>(
    null,
  );
  const [removingResourceIds, setRemovingResourceIds] = createSignal<Record<string, boolean>>({});
  const visibleColumns = createMemo(
    () => columnVisibility.visibleColumns() as AgentMachineColumn[],
  );
  const detailColspan = createMemo(() => visibleColumns().length);
  const agentMetadataTargetIds = createMemo(() => {
    const ids = new Set<string>();
    for (const machine of visibleMachineResources()) {
      const metadataId = agentMetadataIdFor(machine);
      if (metadataId) ids.add(metadataId);
    }
    return [...ids].sort();
  });
  const sortedMachines = createMemo(() =>
    sortAgentMachines(
      tableState.filtered(),
      sortKey(),
      sortDirection(),
      systemLabelFor,
      agentVersionFor,
    ),
  );
  const savedAgentCustomUrlFor = (metadataId: string): string =>
    asTrimmedString(agentMetadataById()[metadataId]?.customUrl) ?? '';
  const handleSort = (key: AgentMachineSortKey) => {
    const next = getNextAgentMachineSortState(sortKey(), sortDirection(), key);
    setSortKey(next.key);
    setSortDirection(next.direction);
  };
  const closeActionsMenu = () => {
    setActionsMenuResourceId(null);
    setConfirmingRemovalResourceId(null);
  };
  const toggleActionsMenu = (resourceId: string) => {
    setActionsMenuResourceId((current) => (current === resourceId ? null : resourceId));
    setConfirmingRemovalResourceId(null);
  };
  const isRemovingMachine = (resourceId: string): boolean =>
    Boolean(removingResourceIds()[resourceId]);
  const setMachineRemoving = (resourceId: string, removing: boolean) => {
    setRemovingResourceIds((current) => {
      if (removing) {
        return { ...current, [resourceId]: true };
      }
      const next = { ...current };
      delete next[resourceId];
      return next;
    });
  };
  const removeAgentMetadata = async (metadataId: string) => {
    if (!metadataId) return;
    try {
      await AgentMetadataAPI.deleteMetadata(metadataId);
    } catch (_error) {
      // The agent removal has already succeeded; stale metadata can be cleaned up later.
    }

    setAgentMetadataById((current) => {
      if (!current[metadataId]) return current;
      const next = { ...current };
      delete next[metadataId];
      return next;
    });
  };
  const handleRemoveMachine = async (machine: Resource, agentId: string, name: string) => {
    const resourceId = machine.id;
    if (!agentId) {
      notificationStore.error('Agent identifier unavailable.');
      closeActionsMenu();
      return;
    }

    if (confirmingRemovalResourceId() !== resourceId) {
      setActionsMenuResourceId(resourceId);
      setConfirmingRemovalResourceId(resourceId);
      return;
    }

    setMachineRemoving(resourceId, true);
    try {
      await MonitoringAPI.deleteAgent(agentId);
      await removeAgentMetadata(agentMetadataIdFor(machine));
      setLocallyRemovedResourceIds((current) => ({ ...current, [resourceId]: true }));
      drawer.close(machine);
      notificationStore.success(`${name} removed from Pulse`);
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to remove machine';
      notificationStore.error(message);
    } finally {
      setMachineRemoving(resourceId, false);
      closeActionsMenu();
    }
  };

  createEffect(() => {
    const targetIds = agentMetadataTargetIds();
    if (targetIds.length === 0) {
      setAgentMetadataById({});
      return;
    }

    let cancelled = false;
    void AgentMetadataAPI.getAllMetadata()
      .then((metadata) => {
        if (!cancelled) setAgentMetadataById(metadata ?? {});
      })
      .catch(() => {
        if (!cancelled) setAgentMetadataById({});
      });

    onCleanup(() => {
      cancelled = true;
    });
  });

  createEffect(() => {
    if (typeof window === 'undefined') return;

    const handleMetadataChanged = (event: Event) => {
      const detail = (event as CustomEvent<ResourceMetadataChangedDetail>).detail;
      if (!detail || detail.metadataKind !== 'agent') return;

      const metadataId = asTrimmedString(detail.metadataId);
      if (!metadataId) return;

      const customUrl = asTrimmedString(detail.customUrl) ?? '';
      setAgentMetadataById((current) => {
        const previous = current[metadataId] ?? { id: metadataId };
        if (previous.customUrl === customUrl) return current;
        return {
          ...current,
          [metadataId]: {
            ...previous,
            customUrl,
          },
        };
      });
    };

    window.addEventListener(RESOURCE_METADATA_CHANGED_EVENT, handleMetadataChanged);
    onCleanup(() => {
      window.removeEventListener(RESOURCE_METADATA_CHANGED_EVENT, handleMetadataChanged);
    });
  });

  createEffect(() => {
    if (typeof document === 'undefined' || !actionsMenuResourceId()) return;

    const handleMouseDown = (event: MouseEvent) => {
      const target = event.target;
      if (target instanceof Element && target.closest('[data-agent-machine-actions-root]')) {
        return;
      }
      closeActionsMenu();
    };
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') closeActionsMenu();
    };

    document.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('keydown', handleKeyDown);
    onCleanup(() => {
      document.removeEventListener('mousedown', handleMouseDown);
      document.removeEventListener('keydown', handleKeyDown);
    });
  });

  return (
    <Show
      when={visibleMachineResources().length > 0}
      fallback={
        <PlatformTableEmptyState
          icon={props.emptyIcon}
          title={props.emptyTitle}
          description={props.emptyDescription}
        />
      }
    >
      <div class="space-y-3">
        <PlatformTableToolbar
          search={tableState.search}
          onSearchChange={tableState.setSearch}
          searchPlaceholder="Search machines"
          searchSuggestions={tableState.searchSuggestions}
          searchHistory={{
            storageKey: STORAGE_KEYS.MACHINES_SEARCH_HISTORY,
            emptyMessage: 'Machine searches you run will appear here.',
          }}
          searchTips={AGENT_MACHINE_SEARCH_TIPS}
          status={tableState.status()}
          onStatusChange={tableState.setStatus}
          statusOptions={withPlatformStatusCounts(
            PLATFORM_HEALTH_FILTER_OPTIONS,
            tableState.countForStatus,
          )}
          visible={tableState.visible()}
          total={tableState.total()}
          rowNoun="machines"
          hasActiveFilters={tableState.hasActiveFilters()}
          onResetFilters={resetFilters}
          viewOptions={
            <div>
              <div class="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted">
                Table
              </div>
              <ColumnPicker
                inline
                columns={columnVisibility.availableToggles()}
                isHidden={columnVisibility.isHiddenByUser}
                onToggle={columnVisibility.toggle}
                onReset={columnVisibility.resetToDefaults}
              />
            </div>
          }
        />

        <Show
          when={tableState.filtered().length > 0}
          fallback={
            <PlatformTableEmptyState
              icon={props.emptyIcon}
              title="No machines match current filters"
              description="Adjust the search or status filter to see more Pulse Agent machines."
              actions={<PlatformTableResetFiltersButton onReset={resetFilters} />}
            />
          }
        >
          <PlatformTableShell
            title="Machines"
            tableClass="min-w-full table-fixed text-xs md:min-w-[840px]"
            header={
              <>
                <For each={visibleColumns()}>
                  {(column) => (
                    <AgentMachineSortableHead
                      column={column}
                      activeSort={sortKey()}
                      direction={sortDirection()}
                      onSort={handleSort}
                    />
                  )}
                </For>
              </>
            }
            body={
              <>
                <PlatformWindowedRows items={sortedMachines} estimatedRowHeight={32}>
                  {(machine) => {
                    const name = () => asTrimmedString(machine.name) || machine.id;
                    const hostname = () =>
                      isAgentlessMachine(machine)
                        ? availabilityAddressFor(machine)
                        : asTrimmedString(machine.agent?.hostname) ||
                          asTrimmedString(machine.identity?.hostname);
                    const systemLabel = () => systemLabelFor(machine);
                    const agentVersion = () => agentVersionFor(machine);
                    const agentStale = () =>
                      !isAgentlessMachine(machine) && Boolean(machine.agent?.stale);
                    const agentStaleTitle = () => {
                      const last = asTrimmedString(machine.agent?.lastReportAt);
                      const when = last
                        ? ` Last report ${formatPlatformTableRelativeTimeValue(last, { now: now() })}.`
                        : '';
                      return `Agent has stopped reporting.${when} Re-run the install command from the Pulse UI to refresh its token.`;
                    };
                    const indicator = () => getStandaloneResourceStatusIndicator(machine, now());
                    const awaitingReport = () => getAgentFirstReportStatusIndicator(machine);
                    const canRenderMetrics = () =>
                      !awaitingReport() && indicator().variant !== 'danger';
                    const telemetryFallback = () =>
                      canRenderMetrics()
                        ? outdatedAgentTelemetryFallbackFor(machine, props.targetAgentVersion)
                        : undefined;
                    const telemetryFallbackMarker = () => {
                      const reason = telemetryFallback();
                      return (
                        <PlatformTableMetricFallback label={reason?.label} title={reason?.title} />
                      );
                    };
                    const metricsKey = () => buildMetricKeyForUnifiedResource(machine);
                    const alertResourceIds = () => hostOverrideIdCandidates(machine);
                    const cpuThresholds = () =>
                      alertsActivation.getMetricThresholds('agent', 'cpu', alertResourceIds());
                    const memoryThresholds = () =>
                      alertsActivation.getMetricThresholds('agent', 'memory', alertResourceIds());
                    const diskThresholds = () =>
                      alertsActivation.getMetricThresholds('agent', 'disk', alertResourceIds());
                    const cpuPercent = () => getAgentMachineCpuPercent(machine);
                    const gpuUtilization = () => getAgentMachineGPUUtilizationPercent(machine);
                    const gpuTitle = () => getAgentMachineGPUTitle(machine);
                    const cpuCores = () => cpuCoresFor(machine);
                    const cpuLoadAverage = () => cpuLoadAverageFor(machine);
                    const memoryUsed = () => memoryUsedFor(machine);
                    const memoryTotal = () => memoryTotalFor(machine);
                    const memoryCache = () => memoryCacheFor(machine);
                    const memoryBalloon = () => memoryBalloonFor(machine);
                    const memorySwapUsed = () => memorySwapUsedFor(machine);
                    const memorySwapTotal = () => memorySwapTotalFor(machine);
                    const memoryPercentOnly = () => memoryPercentOnlyFor(machine);
                    const hasMemoryMetric = () =>
                      memoryTotal() > 0 || memoryPercentOnly() !== undefined;
                    const aggregateDisk = () => aggregateDiskFor(machine);
                    const disks = () => normalizeDiskArray(machine.agent?.disks);
                    const hasDiskMetric = () =>
                      aggregateDisk() !== undefined || (disks()?.length ?? 0) > 0;
                    const networkTotal = () => getAgentMachineNetworkTotal(machine);
                    const networkInterfaces = () => getAgentMachineNetworkInterfaceDetails(machine);
                    const diskIODetails = () => getAgentMachineDiskIODetails(machine);
                    const primaryIp = () =>
                      getPreferredResourceIP(machine) ?? getAgentMachinePrimaryIp(machine);
                    const lastSeenValue = () =>
                      isAgentlessMachine(machine)
                        ? availabilityFor(machine)?.lastChecked
                        : machine.lastSeen;
                    const lastSeenLabel = () =>
                      formatPlatformTableRelativeTimeValue(lastSeenValue(), { now: now() });
                    const machineSubtitle = () =>
                      machineRowSubtitleFor(
                        name(),
                        hostname(),
                        primaryIp(),
                        lastSeenLabel(),
                        // The dedicated IP column is container-responsive. Keep the
                        // primary address in the identity subtitle as well so a user
                        // enabling that column never makes the address disappear in a
                        // narrower table pane.
                        true,
                        !columnVisibility.isColumnVisible('lastSeen'),
                      );
                    const ipValues = () => {
                      const preferred = getPreferredResourceIP(machine);
                      const values = getAgentMachineIpValues(machine);
                      return preferred
                        ? [preferred, ...values.filter((value) => value !== preferred)]
                        : values;
                    };
                    const raidArrays = () => getAgentMachineRaidArrayDetails(machine);
                    const raidSummary = () => getAgentMachineRaidSummary(machine);
                    const temperature = () => getAgentMachineTemperatureCelsius(machine);
                    const temperatureLastKnown = () => isAgentMachineTemperatureLastKnown(machine);
                    const temperatureMetric = () => getAgentMachineTemperatureMetric(machine);
                    const temperatureThresholds = () =>
                      temperatureMetric() === 'diskTemperature'
                        ? alertsActivation.getDiskTemperatureThresholds(
                            getAgentMachineHottestSmartDiskType(machine),
                            alertResourceIds(),
                          )
                        : alertsActivation.getMetricThresholds(
                            'node',
                            temperatureMetric(),
                            alertResourceIds(),
                          );
                    const temperatureSections = () =>
                      getAgentMachineTemperatureDetailSections(machine);
                    const temperatureTitle = () => getAgentMachineTemperatureTitle(machine);
                    const thermalPressure = () =>
                      getAgentMachineThermalPressurePresentation(machine);
                    const isExpanded = () => drawer.isExpanded(machine);
                    const detailRowId = () => drawer.detailRowId(machine);
                    // Tint the row for the open alerts its drawer lists, so a
                    // machine over a threshold stands out without opening it.
                    const machineAlertStyles = createMemo(() =>
                      getUnifiedResourceAlertStyles(
                        machine,
                        activeAlerts,
                        alertsActivation.detectionEnabled(),
                      ),
                    );
                    const machineAlertBg = () => {
                      const s = machineAlertStyles();
                      if (!s.hasUnacknowledgedAlert) return '';
                      return s.severity === 'critical'
                        ? 'bg-red-50 dark:bg-red-950/25'
                        : 'bg-yellow-50 dark:bg-yellow-950/25';
                    };
                    const agentMetadataId = () => agentMetadataIdFor(machine);
                    const agentRemovalId = () => agentRemovalIdFor(machine);
                    const savedWebInterfaceUrl = () => savedAgentCustomUrlFor(agentMetadataId());
                    const toggleDetails = () => {
                      drawer.toggle(machine);
                    };

                    return (
                      <>
                        <TableRow
                          class={`${getPlatformResourceDetailRowClass(isExpanded())} text-[11px] sm:text-xs ${
                            isExpanded() ? '' : machineAlertBg()
                          }`}
                          data-agents-machine-row={machine.id}
                          onClick={toggleDetails}
                        >
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('name')} ${machineColumnWidthClass('machine')}`}
                            title={[name(), machineSubtitle() || systemLabel()]
                              .filter(Boolean)
                              .join(' · ')}
                          >
                            <div class="flex min-w-0 items-center gap-2">
                              <PlatformResourceDetailToggleButton
                                expanded={isExpanded()}
                                resourceLabel={name()}
                                controlsId={detailRowId()}
                                onToggle={toggleDetails}
                              />
                              <StatusDot
                                size="sm"
                                variant={indicator().variant}
                                title={indicator().label}
                                ariaLabel={indicator().label}
                              />
                              <div class="min-w-0">
                                <ResourceNameWithWebInterfaceLink
                                  name={name()}
                                  url={savedWebInterfaceUrl()}
                                  class="min-w-0"
                                  nameClass="truncate font-semibold text-base-content"
                                />
                                <Show when={awaitingReport()}>
                                  {(waiting) => (
                                    <span class="block whitespace-normal text-[10px] leading-snug text-muted">
                                      {waiting().label}
                                    </span>
                                  )}
                                </Show>
                              </div>
                            </div>
                          </TableCell>
                          <Show when={columnVisibility.isColumnVisible('system')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('system')} text-base-content`}
                            >
                              <span class="truncate" title={systemLabel()}>
                                {systemLabel()}
                              </span>
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('agent')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('agent')} font-mono text-[11px] text-base-content`}
                            >
                              <span
                                class="truncate"
                                classList={{
                                  'text-amber-600 dark:text-amber-400': agentStale(),
                                }}
                                title={agentStale() ? agentStaleTitle() : agentVersion()}
                              >
                                {agentVersion()}
                                <Show when={agentStale()}>
                                  <span class="ml-1">(stale)</span>
                                </Show>
                              </span>
                            </TableCell>
                          </Show>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('metric-bar')} ${machineColumnWidthClass('cpu')}`}
                          >
                            <Show
                              when={canRenderMetrics() && cpuPercent() !== undefined}
                              fallback={telemetryFallbackMarker()}
                            >
                              <EnhancedCPUBar
                                usage={cpuPercent() ?? 0}
                                loadAverage={cpuLoadAverage()}
                                cores={cpuCores()}
                                thresholds={cpuThresholds()}
                                resourceId={metricsKey()}
                              />
                            </Show>
                          </TableCell>
                          <Show when={columnVisibility.isColumnVisible('gpu')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('metric-bar')} ${machineColumnWidthClass('gpu')}`}
                              title={gpuTitle()}
                            >
                              <Show
                                when={canRenderMetrics() && gpuUtilization() !== undefined}
                                fallback={telemetryFallbackMarker()}
                              >
                                <MetricBar
                                  value={gpuUtilization() ?? 0}
                                  label={`${Math.round(gpuUtilization() ?? 0)}%`}
                                  type="generic"
                                  resourceId={metricsKey()}
                                />
                              </Show>
                            </TableCell>
                          </Show>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('metric-bar')} ${machineColumnWidthClass('memory')}`}
                          >
                            <Show
                              when={canRenderMetrics() && hasMemoryMetric()}
                              fallback={telemetryFallbackMarker()}
                            >
                              <StackedMemoryBar
                                used={memoryUsed()}
                                total={memoryTotal()}
                                unavailable={memoryUnavailableFor(machine)}
                                percentOnly={memoryPercentOnly()}
                                cache={memoryCache()}
                                balloon={memoryBalloon()}
                                swapUsed={memorySwapUsed()}
                                swapTotal={memorySwapTotal()}
                                thresholds={memoryThresholds()}
                                resourceId={metricsKey()}
                              />
                            </Show>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('metric-bar')} ${machineColumnWidthClass('disk')}`}
                          >
                            <Show
                              when={canRenderMetrics() && hasDiskMetric()}
                              fallback={telemetryFallbackMarker()}
                            >
                              <StackedDiskBar
                                mode={(disks()?.length ?? 0) > 1 ? 'vertical-bars' : undefined}
                                disks={disks()}
                                aggregateDisk={aggregateDisk()}
                                thresholds={diskThresholds()}
                              />
                            </Show>
                          </TableCell>
                          <Show when={columnVisibility.isColumnVisible('network')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('network')} text-base-content`}
                            >
                              <Show
                                when={canRenderMetrics() && networkTotal() !== undefined}
                                fallback={telemetryFallbackMarker()}
                              >
                                <AgentMachineNetworkCell
                                  network={machine.network}
                                  interfaces={networkInterfaces()}
                                  title={networkTitleFor(machine)}
                                />
                              </Show>
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('diskio')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('diskio')} text-base-content`}
                            >
                              <Show
                                when={
                                  canRenderMetrics() &&
                                  (machine.diskIO?.readRate !== undefined ||
                                    machine.diskIO?.writeRate !== undefined)
                                }
                                fallback={telemetryFallbackMarker()}
                              >
                                <AgentMachineDiskIOCell
                                  diskIO={machine.diskIO}
                                  details={diskIODetails()}
                                  title={diskIOTitleFor(machine)}
                                />
                              </Show>
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('uptime')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('uptime')} text-base-content`}
                            >
                              {formatPlatformTableUptimeValue(
                                canRenderMetrics()
                                  ? (machine.uptime ?? machine.agent?.uptimeSeconds)
                                  : undefined,
                              )}
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('temp')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('temp')} text-base-content`}
                            >
                              <Show
                                when={canRenderMetrics()}
                                fallback={<span class="text-muted">—</span>}
                              >
                                <AgentMachineTemperatureCell
                                  celsius={temperature()}
                                  lastKnown={temperatureLastKnown()}
                                  metric={temperatureMetric()}
                                  sections={temperatureSections()}
                                  thresholds={temperatureThresholds()}
                                  title={temperatureTitle()}
                                  thermalPressure={thermalPressure()}
                                />
                              </Show>
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('lastSeen')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('lastSeen')} text-base-content`}
                            >
                              <PlatformTableRelativeTimeValue value={lastSeenValue()} />
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('ip')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('ip')} text-base-content`}
                            >
                              <AgentMachineIpCell
                                primaryIp={primaryIp()}
                                ipValues={ipValues()}
                                interfaces={networkInterfaces()}
                              />
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('raid')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('raid')} text-base-content`}
                            >
                              <AgentMachineRaidCell
                                arrays={raidArrays()}
                                summary={raidSummary()}
                                lastKnownReason={
                                  agentStale() ? HOST_AGENT_STOPPED_REPORTING_REASON : undefined
                                }
                              />
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('arch')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('arch')} text-base-content`}
                            >
                              <span class="truncate" title={machine.agent?.architecture}>
                                {machine.agent?.architecture || '—'}
                              </span>
                            </TableCell>
                          </Show>
                          <Show when={columnVisibility.isColumnVisible('kernel')}>
                            <TableCell
                              class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('kernel')} text-base-content`}
                            >
                              <span class="truncate" title={machine.agent?.kernelVersion}>
                                {machine.agent?.kernelVersion || '—'}
                              </span>
                            </TableCell>
                          </Show>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('badge')} ${machineColumnWidthClass('actions')} text-base-content`}
                          >
                            <AgentMachineActionsCell
                              name={name()}
                              agentId={agentRemovalId()}
                              menuOpen={actionsMenuResourceId() === machine.id}
                              confirmingRemoval={confirmingRemovalResourceId() === machine.id}
                              removing={isRemovingMachine(machine.id)}
                              onToggleMenu={() => toggleActionsMenu(machine.id)}
                              onRemove={() =>
                                void handleRemoveMachine(machine, agentRemovalId(), name())
                              }
                            />
                          </TableCell>
                        </TableRow>
                        <PlatformResourceDetailTableRow
                          resource={machine}
                          statusIndicator={indicator()}
                          open={isExpanded()}
                          detailRowId={detailRowId()}
                          colSpan={detailColspan()}
                          initialShowHostDetails={false}
                          onClose={() => {
                            drawer.close(machine);
                          }}
                        />
                      </>
                    );
                  }}
                </PlatformWindowedRows>
              </>
            }
          />
        </Show>
      </div>
    </Show>
  );
};

export default AgentsMachinesTable;