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.

Improve Machines agent monitoring parity

rcourtmanbebaaa647f7c
diff --git a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx
index ddd29b865b..136030177c 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx
@@ -7,6 +7,10 @@ import { PMGInstanceDrawer } from '@/components/PMG/PMGInstanceDrawer';
import { K8sDeploymentsDrawer } from '@/components/Kubernetes/K8sDeploymentsDrawer';
import { K8sNamespacesDrawer } from '@/components/Kubernetes/K8sNamespacesDrawer';
import { SwarmServicesDrawer } from '@/components/Docker/SwarmServicesDrawer';
+import {
+ GuestDrawerHistory,
+ GuestDrawerHistoryRangeSelect,
+} from '@/components/Workloads/GuestDrawerHistory';
import { ResourceDetailDrawerDebugTab } from './ResourceDetailDrawerDebugTab';
import { ResourceDetailDrawerOverviewTab } from './ResourceDetailDrawerOverviewTab';
import { useResourceDetailDrawerState } from './useResourceDetailDrawerState';
@@ -143,6 +147,35 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {
/>
</div>
+ {/* Agent Machine Metrics History Tab */}
+ <div
+ class={drawer.activeTab() === 'history' ? '' : 'hidden'}
+ style={{ 'overflow-anchor': 'none' }}
+ >
+ <Show when={drawer.activeTab() === 'history'}>
+ <Show
+ when={drawer.metricsHistoryTarget()}
+ fallback={<TabAvailabilityNotice message="Metrics history is unavailable." />}
+ >
+ {(target) => (
+ <div class="space-y-3" data-testid="resource-metrics-history-tab">
+ <div class="flex items-center justify-end">
+ <GuestDrawerHistoryRangeSelect
+ range={drawer.metricsHistoryRange()}
+ onRangeChange={drawer.setMetricsHistoryRange}
+ />
+ </div>
+ <GuestDrawerHistory
+ target={target()}
+ range={drawer.metricsHistoryRange()}
+ fallbackMetrics={drawer.metricsHistoryFallbackMetrics()}
+ />
+ </div>
+ )}
+ </Show>
+ </Show>
+ </div>
+
{/* PMG Mail Tab */}
<div
class={drawer.activeTab() === 'mail' ? '' : 'hidden'}
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.machine-history.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.machine-history.test.tsx
new file mode 100644
index 0000000000..560810e51f
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.machine-history.test.tsx
@@ -0,0 +1,92 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { Resource } from '@/types/resource';
+import { ResourceDetailDrawer } from '../ResourceDetailDrawer';
+
+vi.mock('@/components/Workloads/GuestDrawerHistory', () => ({
+ GuestDrawerHistory: (props: {
+ target: { resourceType: string; resourceId: string } | null;
+ range: string;
+ fallbackMetrics?: Record<string, number | undefined>;
+ }) => (
+ <div
+ data-testid="machine-history"
+ data-resource-type={props.target?.resourceType}
+ data-resource-id={props.target?.resourceId}
+ data-range={props.range}
+ data-cpu={props.fallbackMetrics?.cpu}
+ data-netin={props.fallbackMetrics?.netin}
+ />
+ ),
+ GuestDrawerHistoryRangeSelect: (props: {
+ range: string;
+ onRangeChange: (range: string) => void;
+ }) => (
+ <select
+ aria-label="History range"
+ value={props.range}
+ onChange={(event) => props.onRangeChange(event.currentTarget.value)}
+ >
+ <option value="24h">24 hours</option>
+ <option value="7d">7 days</option>
+ </select>
+ ),
+}));
+
+const resource = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: overrides.id ?? 'agent-1',
+ name: overrides.name ?? overrides.id ?? 'agent-1',
+ displayName: overrides.displayName ?? overrides.name ?? overrides.id ?? 'agent-1',
+ type: overrides.type ?? 'agent',
+ platformId: 'agent',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...overrides,
+ }) as Resource;
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('ResourceDetailDrawer machine metrics history', () => {
+ it('adds a metrics history tab for Pulse Agent machines', async () => {
+ render(() => (
+ <ResourceDetailDrawer
+ resource={resource({
+ id: 'agent-mac-mini',
+ metricsTarget: { resourceType: 'agent', resourceId: 'agent-mac-mini' },
+ cpu: { current: 42 },
+ network: { rxBytes: 1024, txBytes: 2048 },
+ })}
+ />
+ ));
+
+ await fireEvent.click(screen.getByRole('button', { name: 'History' }));
+
+ const history = screen.getByTestId('machine-history');
+ expect(history).toHaveAttribute('data-resource-type', 'agent');
+ expect(history).toHaveAttribute('data-resource-id', 'agent-mac-mini');
+ expect(history).toHaveAttribute('data-range', '24h');
+ expect(history).toHaveAttribute('data-cpu', '42');
+ expect(history).toHaveAttribute('data-netin', '1024');
+ });
+
+ it('does not add machine history to non-agent availability resources', () => {
+ render(() => (
+ <ResourceDetailDrawer
+ resource={resource({
+ id: 'ping-mac-mini',
+ type: 'network-endpoint',
+ platformType: 'availability',
+ sourceType: 'api',
+ })}
+ />
+ ));
+
+ expect(screen.queryByRole('button', { name: 'History' })).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend-modern/src/components/Infrastructure/resourceDetailDrawerMetricsHistoryModel.ts b/frontend-modern/src/components/Infrastructure/resourceDetailDrawerMetricsHistoryModel.ts
new file mode 100644
index 0000000000..d5f196decf
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/resourceDetailDrawerMetricsHistoryModel.ts
@@ -0,0 +1,49 @@
+import type { ResourceType as MetricsHistoryResourceType } from '@/api/charts';
+import type { GuestDrawerHistoryTarget } from '@/components/Workloads/guestDrawerModel';
+import type { Resource } from '@/types/resource';
+import { getDiskPercent, getMemoryPercent } from '@/types/resource';
+import { asTrimmedString } from '@/utils/stringUtils';
+
+const finiteMetric = (value: number | undefined): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+export const getResourceMetricsHistoryTarget = (
+ resource: Resource,
+): GuestDrawerHistoryTarget | null => {
+ const metricsType = asTrimmedString(resource.metricsTarget?.resourceType);
+ const metricsId = asTrimmedString(resource.metricsTarget?.resourceId);
+ if (metricsType && metricsId) {
+ return {
+ resourceType: metricsType as MetricsHistoryResourceType,
+ resourceId: metricsId,
+ };
+ }
+
+ if (resource.type === 'agent') {
+ const resourceId = asTrimmedString(resource.id);
+ return resourceId ? { resourceType: 'agent', resourceId } : null;
+ }
+
+ return null;
+};
+
+export const resourceSupportsMetricsHistory = (resource: Resource): boolean =>
+ resource.type === 'agent' && getResourceMetricsHistoryTarget(resource) !== null;
+
+export const getResourceMetricsHistoryFallbackMetrics = (
+ resource: Resource,
+): Record<string, number | undefined> => {
+ if (resource.type !== 'agent') {
+ return {};
+ }
+
+ return {
+ cpu: finiteMetric(resource.cpu?.current),
+ memory: resource.memory ? finiteMetric(getMemoryPercent(resource)) : undefined,
+ disk: resource.disk ? finiteMetric(getDiskPercent(resource)) : undefined,
+ netin: finiteMetric(resource.network?.rxBytes),
+ netout: finiteMetric(resource.network?.txBytes),
+ diskread: finiteMetric(resource.diskIO?.readRate),
+ diskwrite: finiteMetric(resource.diskIO?.writeRate),
+ };
+};
diff --git a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts
index 7abde54b4d..9e6399f155 100644
--- a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts
+++ b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts
@@ -58,6 +58,11 @@ import {
buildSourceSummary,
hasRuntimeOperationalContext as buildHasRuntimeOperationalContext,
} from './resourceDetailDrawerOperationalModel';
+import {
+ getResourceMetricsHistoryFallbackMetrics,
+ getResourceMetricsHistoryTarget,
+ resourceSupportsMetricsHistory,
+} from './resourceDetailDrawerMetricsHistoryModel';
import {
buildDiscoveryContextSummary,
buildIdentityMatchInfo,
@@ -75,7 +80,7 @@ import {
} from './resourceDetailDrawerTrueNASModel';
import { getResourceHealthIssuePresentation } from './resourceHealthPresentation';
-type DrawerTab = 'overview' | 'mail' | 'namespaces' | 'deployments' | 'swarm' | 'debug';
+type DrawerTab = 'overview' | 'history' | 'mail' | 'namespaces' | 'deployments' | 'swarm' | 'debug';
interface ResourceDrawerDiscoverySourceKey {
type: DiscoveryResourceType;
@@ -326,6 +331,11 @@ export const useResourceDetailDrawerDerivedState = (
const trueNASDetailSections = createMemo(() => buildTrueNASDetailSections(resource));
const hasTrueNASDetails = createMemo(() => trueNASDetailSections().length > 0);
const trueNASDetailsSummary = createMemo(() => buildTrueNASDetailsSummary(resource));
+ const metricsHistoryTarget = createMemo(() => getResourceMetricsHistoryTarget(resource));
+ const metricsHistoryFallbackMetrics = createMemo(() =>
+ getResourceMetricsHistoryFallbackMetrics(resource),
+ );
+ const hasMetricsHistory = createMemo(() => resourceSupportsMetricsHistory(resource));
const relatedLinks = createMemo(() => buildRelatedLinks(resource, displayName()));
const accessSummary = createMemo(() =>
@@ -356,6 +366,7 @@ export const useResourceDetailDrawerDerivedState = (
const tabs = createMemo(() => {
const base = [
{ id: 'overview' as DrawerTab, label: 'Overview' },
+ ...(hasMetricsHistory() ? [{ id: 'history' as DrawerTab, label: 'History' }] : []),
...(resource.type === 'pmg' ? [{ id: 'mail' as DrawerTab, label: 'Mail' }] : []),
...(resource.type === 'k8s-cluster'
? [{ id: 'namespaces' as DrawerTab, label: 'Namespaces' }]
@@ -448,6 +459,9 @@ export const useResourceDetailDrawerDerivedState = (
hostDetailSummary,
hasServiceDetails,
serviceDetailsSummary,
+ metricsHistoryTarget,
+ metricsHistoryFallbackMetrics,
+ hasMetricsHistory,
hasVMwareDetails,
vmwareDetailsSummary,
vmwareDetailSections,
diff --git a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts
index 777415977b..3593de74b6 100644
--- a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts
+++ b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts
@@ -1,12 +1,14 @@
import { createEffect, createSignal } from 'solid-js';
import type { Resource } from '@/types/resource';
+import type { HistoryTimeRange } from '@/api/charts';
+import { GUEST_DRAWER_HISTORY_DEFAULT_RANGE } from '@/components/Workloads/guestDrawerModel';
import { createLocalStorageBooleanSignal, STORAGE_KEYS } from '@/utils/localStorage';
import { useResourceDetailDrawerDockerActionsState } from './useResourceDetailDrawerDockerActionsState';
import { useResourceDetailDrawerHistoryState } from './useResourceDetailDrawerHistoryState';
import { useResourceDetailDrawerDerivedState } from './useResourceDetailDrawerDerivedState';
import type { ResourceDetailDrawerPresentation } from './resourceDetailDrawerPresentation';
-type DrawerTab = 'overview' | 'mail' | 'namespaces' | 'deployments' | 'swarm' | 'debug';
+type DrawerTab = 'overview' | 'history' | 'mail' | 'namespaces' | 'deployments' | 'swarm' | 'debug';
export interface UseResourceDetailDrawerStateOptions {
resource: Resource;
@@ -18,6 +20,9 @@ export interface UseResourceDetailDrawerStateOptions {
export const useResourceDetailDrawerState = (options: UseResourceDetailDrawerStateOptions) => {
const { resource, resolveResourceLabel: resolveResourceLabelInput } = options;
const [activeTab, setActiveTab] = createSignal<DrawerTab>('overview');
+ const [metricsHistoryRange, setMetricsHistoryRange] = createSignal<HistoryTimeRange>(
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ );
const [debugEnabled] = createLocalStorageBooleanSignal(STORAGE_KEYS.DEBUG_MODE, false);
const [copied, setCopied] = createSignal(false);
const [showReportModal, setShowReportModal] = createSignal(false);
@@ -91,6 +96,8 @@ export const useResourceDetailDrawerState = (options: UseResourceDetailDrawerSta
return {
activeTab,
setActiveTab,
+ metricsHistoryRange,
+ setMetricsHistoryRange,
debugEnabled,
copied,
showReportModal,
diff --git a/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx b/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx
index b0dc1cbad0..ea05e637ab 100644
--- a/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx
+++ b/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx
@@ -1,6 +1,7 @@
-import { For, Show, type Component, type JSX } from 'solid-js';
+import { For, Show, createMemo, createSignal, type Component, type JSX } from 'solid-js';
import { StackedDiskBar } from '@/components/Workloads/StackedDiskBar';
import { StackedMemoryBar } from '@/components/Workloads/StackedMemoryBar';
+import { ColumnPicker } from '@/components/shared/ColumnPicker';
import { ResponsiveMetricCell } from '@/components/shared/responsive';
import { StatusDot } from '@/components/shared/StatusDot';
import {
@@ -31,12 +32,31 @@ import {
getPlatformTableHeadClassForKind,
type PlatformResourceStatusFilter,
} from '@/features/platformPage/sharedPlatformPage';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import type { Disk } from '@/types/api';
import type { Resource, ResourceAvailabilityMeta } from '@/types/resource';
-import { normalizeDiskArray } from '@/utils/format';
+import { formatSpeed, normalizeDiskArray } from '@/utils/format';
import { buildMetricKeyForUnifiedResource } from '@/utils/metricsKeys';
import { getSimpleStatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
+import { formatTemperature as formatTemperatureValue } from '@/utils/temperature';
+import {
+ AGENT_MACHINE_COLUMNS,
+ getAgentMachineCpuPercent,
+ getAgentMachineDiskIOTotal,
+ getAgentMachineIpValues,
+ getAgentMachineNetworkTotal,
+ getAgentMachinePrimaryIp,
+ getAgentMachineRaidSummary,
+ getAgentMachineTemperatureCelsius,
+ getAgentMachineTemperatureTitle,
+ getNextAgentMachineSortState,
+ sortAgentMachines,
+ timestampMillisFrom,
+ type AgentMachineColumn,
+ type AgentMachineColumnId,
+ type AgentMachineSortKey,
+} from './agentMachineTableModel';
const formatUptime = (seconds: number | undefined): string => {
if (!seconds || seconds <= 0) return '—';
@@ -48,24 +68,15 @@ const formatUptime = (seconds: number | undefined): string => {
return `${mins}m`;
};
-const formatTemperature = (celsius: number | undefined): JSX.Element => {
+const formatTemperature = (celsius: number | undefined, title?: string): JSX.Element => {
if (typeof celsius !== 'number' || !Number.isFinite(celsius) || celsius <= 0) {
return <span class="text-muted">—</span>;
}
- return <span class="tabular-nums">{Math.round(celsius)}°C</span>;
-};
-
-const timestampMillisFrom = (value: number | string | Date | undefined): number | undefined => {
- if (value instanceof Date) {
- const millis = value.getTime();
- return Number.isFinite(millis) ? millis : undefined;
- }
- if (typeof value === 'string') {
- const millis = Date.parse(value);
- return Number.isFinite(millis) ? millis : undefined;
- }
- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;
- return value < 10_000_000_000 ? value * 1000 : value;
+ return (
+ <span class="tabular-nums" title={title}>
+ {formatTemperatureValue(celsius)}
+ </span>
+ );
};
const formatLastSeen = (value: number | string | Date | undefined): string => {
@@ -114,9 +125,6 @@ const availabilityAddressFor = (machine: Resource): string => {
return asTrimmedString(machine.identity?.hostname) ?? '';
};
-const percentFromMetric = (metric: Resource['cpu'] | undefined): number | undefined =>
- finiteMetric(metric?.current);
-
const memoryTotalFor = (machine: Resource): number =>
finiteMetric(machine.memory?.total) ?? finiteMetric(machine.agent?.memory?.total) ?? 0;
@@ -160,6 +168,118 @@ const systemLabelFor = (machine: Resource): string => {
);
};
+const agentVersionFor = (machine: Resource): string =>
+ isAgentlessMachine(machine) ? 'Agentless' : asTrimmedString(machine.agent?.agentVersion) || '—';
+
+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 ${formatSpeed(machine.diskIO.readRate)}\nWrite ${formatSpeed(machine.diskIO.writeRate)}`;
+};
+
+const machineColumnWidthClass = (columnId: AgentMachineColumnId): string => {
+ switch (columnId) {
+ case 'machine':
+ return 'w-[34%] md:w-[16%]';
+ case 'system':
+ return 'hidden md:table-cell md:w-[12%]';
+ case 'agent':
+ return 'hidden md:table-cell md:w-[6%]';
+ case 'cpu':
+ case 'memory':
+ case 'disk':
+ return 'w-[22%] 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 'hidden lg:table-cell lg:w-[6%]';
+ case 'ip':
+ return '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%]';
+ }
+};
+
+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={props.column.label}>
+ {(sortKey) => (
+ <button
+ type="button"
+ class="inline-flex max-w-full items-center gap-1 truncate hover:text-base-content focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/60"
+ 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;
@@ -171,8 +291,31 @@ export const AgentsMachinesTable: Component<{
initialStatus: 'all' as PlatformResourceStatusFilter,
filter: filterPlatformResources,
});
+ const [sortKey, setSortKey] = createSignal<AgentMachineSortKey>('name');
+ const [sortDirection, setSortDirection] = createSignal<'asc' | 'desc'>('asc');
+ const columnVisibility = useColumnVisibility(
+ 'pulse:standalone:machines:columns:v3',
+ AGENT_MACHINE_COLUMNS,
+ );
const drawer = createPlatformResourceDetailState({ idPrefix: 'agents-machine-drawer' });
- const detailColspan = 9;
+ const visibleColumns = createMemo(
+ () => columnVisibility.visibleColumns() as AgentMachineColumn[],
+ );
+ const detailColspan = createMemo(() => visibleColumns().length);
+ const sortedMachines = createMemo(() =>
+ sortAgentMachines(
+ tableState.filtered(),
+ sortKey(),
+ sortDirection(),
+ systemLabelFor,
+ agentVersionFor,
+ ),
+ );
+ const handleSort = (key: AgentMachineSortKey) => {
+ const next = getNextAgentMachineSortState(sortKey(), sortDirection(), key);
+ setSortKey(next.key);
+ setSortDirection(next.direction);
+ };
return (
<Show
@@ -186,17 +329,27 @@ export const AgentsMachinesTable: Component<{
}
>
<div class="space-y-3">
- <PlatformTableToolbar
- search={tableState.search}
- onSearchChange={tableState.setSearch}
- searchPlaceholder="Search machines"
- status={tableState.status()}
- onStatusChange={tableState.setStatus}
- statusOptions={PLATFORM_HEALTH_FILTER_OPTIONS}
- visible={tableState.visible()}
- total={tableState.total()}
- rowNoun="machines"
- />
+ <div class="flex flex-wrap items-center gap-2">
+ <div class="min-w-[280px] flex-1">
+ <PlatformTableToolbar
+ search={tableState.search}
+ onSearchChange={tableState.setSearch}
+ searchPlaceholder="Search machines"
+ status={tableState.status()}
+ onStatusChange={tableState.setStatus}
+ statusOptions={PLATFORM_HEALTH_FILTER_OPTIONS}
+ visible={tableState.visible()}
+ total={tableState.total()}
+ rowNoun="machines"
+ />
+ </div>
+ <ColumnPicker
+ columns={columnVisibility.availableToggles()}
+ isHidden={columnVisibility.isHiddenByUser}
+ onToggle={columnVisibility.toggle}
+ onReset={columnVisibility.resetToDefaults}
+ />
+ </div>
<Show
when={tableState.filtered().length > 0}
@@ -210,59 +363,23 @@ export const AgentsMachinesTable: Component<{
>
<TableCard class={PLATFORM_TABLE_CARD_CLASS}>
<TableCardHeader title="Machines" />
- <Table class="min-w-full table-fixed text-xs md:min-w-[1120px]">
+ <Table class="min-w-full table-fixed text-xs md:min-w-[1160px]">
<TableHeader>
<TableRow class={PLATFORM_TABLE_HEADER_ROW_CLASS}>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('name')} w-[40%] md:w-[19%]`}
- >
- Machine
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} hidden md:table-cell md:w-[14%]`}
- >
- System
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} hidden md:table-cell md:w-[8%]`}
- >
- Agent
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('metric-bar')} w-[20%] md:w-[12%]`}
- >
- CPU
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('metric-bar')} w-[20%] md:w-[12%]`}
- >
- <span class="md:hidden">Mem</span>
- <span class="hidden md:inline">Memory</span>
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('metric-bar')} w-[20%] md:w-[12%]`}
- >
- Disk
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} hidden md:table-cell md:w-[7%]`}
- >
- Uptime
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} hidden md:table-cell md:w-[7%]`}
- >
- Temp
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} hidden lg:table-cell lg:w-[9%]`}
- >
- Last seen
- </TableHead>
+ <For each={visibleColumns()}>
+ {(column) => (
+ <AgentMachineSortableHead
+ column={column}
+ activeSort={sortKey()}
+ direction={sortDirection()}
+ onSort={handleSort}
+ />
+ )}
+ </For>
</TableRow>
</TableHeader>
<TableBody class={PLATFORM_TABLE_BODY_CLASS}>
- <For each={tableState.filtered()}>
+ <For each={sortedMachines()}>
{(machine) => {
const name = () => asTrimmedString(machine.name) || machine.id;
const hostname = () =>
@@ -271,14 +388,11 @@ export const AgentsMachinesTable: Component<{
: asTrimmedString(machine.agent?.hostname) ||
asTrimmedString(machine.identity?.hostname);
const systemLabel = () => systemLabelFor(machine);
- const agentVersion = () =>
- isAgentlessMachine(machine)
- ? 'Agentless'
- : asTrimmedString(machine.agent?.agentVersion) || '—';
+ const agentVersion = () => agentVersionFor(machine);
const indicator = () => getSimpleStatusIndicator(machine.status);
const canRenderMetrics = () => indicator().variant !== 'danger';
const metricsKey = () => buildMetricKeyForUnifiedResource(machine);
- const cpuPercent = () => percentFromMetric(machine.cpu);
+ const cpuPercent = () => getAgentMachineCpuPercent(machine);
const memoryUsed = () => memoryUsedFor(machine);
const memoryTotal = () => memoryTotalFor(machine);
const memoryPercentOnly = () => memoryPercentOnlyFor(machine);
@@ -288,6 +402,13 @@ export const AgentsMachinesTable: Component<{
const disks = () => normalizeDiskArray(machine.agent?.disks);
const hasDiskMetric = () =>
aggregateDisk() !== undefined || (disks()?.length ?? 0) > 0;
+ const networkTotal = () => getAgentMachineNetworkTotal(machine);
+ const diskIOTotal = () => getAgentMachineDiskIOTotal(machine);
+ const primaryIp = () => getAgentMachinePrimaryIp(machine);
+ const ipValues = () => getAgentMachineIpValues(machine);
+ const raidSummary = () => getAgentMachineRaidSummary(machine);
+ const temperature = () => getAgentMachineTemperatureCelsius(machine);
+ const temperatureTitle = () => getAgentMachineTemperatureTitle(machine);
const isExpanded = () => drawer.isExpanded(machine);
const detailRowId = () => drawer.detailRowId(machine);
@@ -303,7 +424,7 @@ export const AgentsMachinesTable: Component<{
tabIndex={0}
>
<TableCell
- class={`${getPlatformTableCellClassForKind('name')} w-[40%] md:w-auto`}
+ class={`${getPlatformTableCellClassForKind('name')} ${machineColumnWidthClass('machine')}`}
>
<div class="flex min-w-0 items-center gap-2">
<StatusDot
@@ -323,20 +444,26 @@ export const AgentsMachinesTable: Component<{
{hostname() || systemLabel()}
</span>
</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" title={agentVersion()}>
+ {agentVersion()}
+ </span>
+ </TableCell>
+ </Show>
<TableCell
- class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content md:table-cell`}
- >
- <span class="truncate" title={systemLabel()}>
- {systemLabel()}
- </span>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('text')} hidden font-mono text-[11px] text-base-content md:table-cell`}
- >
- {agentVersion()}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('metric-bar')} w-[20%] md:w-auto`}
+ class={`${getPlatformTableCellClassForKind('metric-bar')} ${machineColumnWidthClass('cpu')}`}
>
<ResponsiveMetricCell
class="w-full"
@@ -348,7 +475,7 @@ export const AgentsMachinesTable: Component<{
/>
</TableCell>
<TableCell
- class={`${getPlatformTableCellClassForKind('metric-bar')} w-[20%] md:w-auto`}
+ class={`${getPlatformTableCellClassForKind('metric-bar')} ${machineColumnWidthClass('memory')}`}
>
<Show
when={canRenderMetrics() && hasMemoryMetric()}
@@ -362,7 +489,7 @@ export const AgentsMachinesTable: Component<{
</Show>
</TableCell>
<TableCell
- class={`${getPlatformTableCellClassForKind('metric-bar')} w-[20%] md:w-auto`}
+ class={`${getPlatformTableCellClassForKind('metric-bar')} ${machineColumnWidthClass('disk')}`}
>
<Show
when={canRenderMetrics() && hasDiskMetric()}
@@ -375,31 +502,129 @@ export const AgentsMachinesTable: Component<{
/>
</Show>
</TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} hidden text-base-content md:table-cell`}
- >
- {formatUptime(machine.uptime ?? machine.agent?.uptimeSeconds)}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} hidden text-base-content md:table-cell`}
- >
- {formatTemperature(machine.temperature)}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} hidden text-base-content lg:table-cell`}
- >
- {formatLastSeen(
- isAgentlessMachine(machine)
- ? availabilityFor(machine)?.lastChecked
- : machine.lastSeen,
- )}
- </TableCell>
+ <Show when={columnVisibility.isColumnVisible('network')}>
+ <TableCell
+ class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('network')} text-base-content`}
+ >
+ <Show
+ when={canRenderMetrics() && networkTotal() !== undefined}
+ fallback={metricFallback()}
+ >
+ <div
+ class="grid w-full grid-cols-[0.75rem_minmax(0,1fr)_0.75rem_minmax(0,1fr)] items-center gap-x-1 text-[11px] tabular-nums"
+ title={networkTitleFor(machine)}
+ >
+ <span class="inline-flex w-3 justify-center text-emerald-500">
+ ↓
+ </span>
+ <span class="min-w-0 truncate">
+ {formatSpeed(machine.network?.rxBytes ?? 0)}
+ </span>
+ <span class="inline-flex w-3 justify-center text-orange-400">
+ ↑
+ </span>
+ <span class="min-w-0 truncate">
+ {formatSpeed(machine.network?.txBytes ?? 0)}
+ </span>
+ </div>
+ </Show>
+ </TableCell>
+ </Show>
+ <Show when={columnVisibility.isColumnVisible('diskio')}>
+ <TableCell
+ class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('diskio')} text-base-content`}
+ >
+ <Show
+ when={canRenderMetrics() && diskIOTotal() !== undefined}
+ fallback={metricFallback()}
+ >
+ <div
+ class="grid w-full grid-cols-[0.75rem_minmax(0,1fr)_0.75rem_minmax(0,1fr)] items-center gap-x-1 text-[11px] tabular-nums"
+ title={diskIOTitleFor(machine)}
+ >
+ <span class="inline-flex w-3 justify-center font-mono text-blue-500">
+ R
+ </span>
+ <span class="min-w-0 truncate">
+ {formatSpeed(machine.diskIO?.readRate ?? 0)}
+ </span>
+ <span class="inline-flex w-3 justify-center font-mono text-amber-500">
+ W
+ </span>
+ <span class="min-w-0 truncate">
+ {formatSpeed(machine.diskIO?.writeRate ?? 0)}
+ </span>
+ </div>
+ </Show>
+ </TableCell>
+ </Show>
+ <Show when={columnVisibility.isColumnVisible('uptime')}>
+ <TableCell
+ class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('uptime')} text-base-content`}
+ >
+ {formatUptime(machine.uptime ?? machine.agent?.uptimeSeconds)}
+ </TableCell>
+ </Show>
+ <Show when={columnVisibility.isColumnVisible('temp')}>
+ <TableCell
+ class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('temp')} text-base-content`}
+ >
+ {formatTemperature(temperature(), temperatureTitle())}
+ </TableCell>
+ </Show>
+ <Show when={columnVisibility.isColumnVisible('lastSeen')}>
+ <TableCell
+ class={`${getPlatformTableCellClassForKind('numeric-value')} ${machineColumnWidthClass('lastSeen')} text-base-content`}
+ >
+ {formatLastSeen(
+ isAgentlessMachine(machine)
+ ? availabilityFor(machine)?.lastChecked
+ : machine.lastSeen,
+ )}
+ </TableCell>
+ </Show>
+ <Show when={columnVisibility.isColumnVisible('ip')}>
+ <TableCell
+ class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('ip')} text-base-content`}
+ >
+ <span class="truncate" title={ipValues().join('\n')}>
+ {primaryIp() || '—'}
+ </span>
+ </TableCell>
+ </Show>
+ <Show when={columnVisibility.isColumnVisible('raid')}>
+ <TableCell
+ class={`${getPlatformTableCellClassForKind('text')} ${machineColumnWidthClass('raid')} text-base-content`}
+ >
+ <span class="truncate" title={raidSummary()}>
+ {raidSummary() || '—'}
+ </span>
+ </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>
</TableRow>
<PlatformResourceDetailTableRow
resource={machine}
open={isExpanded()}
detailRowId={detailRowId()}
- colSpan={detailColspan}
+ colSpan={detailColspan()}
onClose={() => drawer.close(machine)}
/>
</>
diff --git a/frontend-modern/src/features/standalone/__tests__/AgentsMachinesTable.test.tsx b/frontend-modern/src/features/standalone/__tests__/AgentsMachinesTable.test.tsx
new file mode 100644
index 0000000000..9fc4bd26e0
--- /dev/null
+++ b/frontend-modern/src/features/standalone/__tests__/AgentsMachinesTable.test.tsx
@@ -0,0 +1,157 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Resource } from '@/types/resource';
+import { AgentsMachinesTable } from '../AgentsMachinesTable';
+
+vi.mock('@/components/Infrastructure/ResourceDetailDrawer', () => ({
+ ResourceDetailDrawer: () => <div data-testid="resource-detail-drawer" />,
+}));
+
+const resource = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: overrides.id ?? 'machine-1',
+ name: overrides.name ?? overrides.id ?? 'machine-1',
+ displayName: overrides.displayName ?? overrides.name ?? overrides.id ?? 'machine-1',
+ type: 'agent',
+ platformId: 'agent',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...overrides,
+ }) as Resource;
+
+const emptyIcon = <span data-testid="empty-icon" />;
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ },
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ window.localStorage.clear();
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+describe('AgentsMachinesTable', () => {
+ it('surfaces machine-native monitoring columns for agent machines', async () => {
+ render(() => (
+ <AgentsMachinesTable
+ resources={[
+ resource({
+ id: 'tower',
+ name: 'Tower',
+ cpu: { current: 12 },
+ memory: { current: 32, total: 100, used: 32, free: 68 },
+ disk: { current: 45, total: 100, used: 45, free: 55 },
+ network: { rxBytes: 1024, txBytes: 2048 },
+ diskIO: { readRate: 4096, writeRate: 8192 },
+ temperature: 52,
+ uptime: 86_400,
+ identity: { ips: ['192.168.0.10'] },
+ agent: {
+ agentVersion: '6.0.0',
+ osName: 'Unraid',
+ osVersion: '7.2.2',
+ architecture: 'x86_64',
+ kernelVersion: '6.12.24',
+ raid: [
+ {
+ device: '/dev/md0',
+ level: 'raid1',
+ state: 'clean',
+ totalDevices: 2,
+ activeDevices: 2,
+ workingDevices: 2,
+ failedDevices: 0,
+ spareDevices: 0,
+ devices: [],
+ rebuildPercent: 0,
+ },
+ ],
+ },
+ }),
+ ]}
+ emptyIcon={emptyIcon}
+ emptyTitle="No machines"
+ emptyDescription="Install Pulse Agent."
+ />
+ ));
+
+ expect(screen.getByRole('button', { name: 'Sort by Net I/O' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Sort by Disk I/O' })).toBeInTheDocument();
+ expect(screen.getByText('1.00 KB/s')).toBeInTheDocument();
+ expect(screen.getByText('8.00 KB/s')).toBeInTheDocument();
+
+ expect(screen.queryByText('192.168.0.10')).not.toBeInTheDocument();
+ await fireEvent.click(screen.getByTitle('Choose which columns to display'));
+ await fireEvent.click(screen.getByLabelText('IP'));
+ await fireEvent.click(screen.getByLabelText('RAID'));
+
+ expect(screen.getByText('192.168.0.10')).toBeInTheDocument();
+ expect(screen.getByText('1 clean')).toBeInTheDocument();
+ });
+
+ it('sorts machines by operational metrics from the column headers', async () => {
+ const { container } = render(() => (
+ <AgentsMachinesTable
+ resources={[
+ resource({ id: 'alpha', name: 'Alpha', cpu: { current: 3 } }),
+ resource({ id: 'zulu', name: 'Zulu', cpu: { current: 80 } }),
+ ]}
+ emptyIcon={emptyIcon}
+ emptyTitle="No machines"
+ emptyDescription="Install Pulse Agent."
+ />
+ ));
+
+ expect(
+ Array.from(container.querySelectorAll('[data-agents-machine-row]')).map((row) =>
+ row.getAttribute('data-agents-machine-row'),
+ ),
+ ).toEqual(['alpha', 'zulu']);
+
+ await fireEvent.click(screen.getByRole('button', { name: 'Sort by CPU' }));
+
+ expect(
+ Array.from(container.querySelectorAll('[data-agents-machine-row]')).map((row) =>
+ row.getAttribute('data-agents-machine-row'),
+ ),
+ ).toEqual(['zulu', 'alpha']);
+ });
+
+ it('keeps deep identity columns available through the column picker', async () => {
+ render(() => (
+ <AgentsMachinesTable
+ resources={[
+ resource({
+ id: 'mac-mini',
+ name: 'Mac Mini',
+ agent: {
+ architecture: 'arm64',
+ kernelVersion: 'Darwin 25.5.0',
+ },
+ }),
+ ]}
+ emptyIcon={emptyIcon}
+ emptyTitle="No machines"
+ emptyDescription="Install Pulse Agent."
+ />
+ ));
+
+ expect(screen.queryByText('arm64')).not.toBeInTheDocument();
+
+ await fireEvent.click(screen.getByTitle('Choose which columns to display'));
+ await fireEvent.click(screen.getByLabelText('Arch'));
+
+ expect(screen.getByText('arm64')).toBeInTheDocument();
+ });
+});
diff --git a/frontend-modern/src/features/standalone/agentMachineTableModel.ts b/frontend-modern/src/features/standalone/agentMachineTableModel.ts
new file mode 100644
index 0000000000..413d904504
--- /dev/null
+++ b/frontend-modern/src/features/standalone/agentMachineTableModel.ts
@@ -0,0 +1,379 @@
+import type { ColumnDef } from '@/hooks/useColumnVisibility';
+import type { Resource } from '@/types/resource';
+import { asTrimmedString } from '@/utils/stringUtils';
+
+export type AgentMachineColumnId =
+ | 'machine'
+ | 'system'
+ | 'agent'
+ | 'cpu'
+ | 'memory'
+ | 'disk'
+ | 'network'
+ | 'diskio'
+ | 'uptime'
+ | 'temp'
+ | 'lastSeen'
+ | 'ip'
+ | 'raid'
+ | 'arch'
+ | 'kernel';
+
+export type AgentMachineSortKey =
+ | 'name'
+ | 'system'
+ | 'agent'
+ | 'cpu'
+ | 'memory'
+ | 'disk'
+ | 'network'
+ | 'diskio'
+ | 'uptime'
+ | 'temp'
+ | 'lastSeen'
+ | 'ip'
+ | 'raid'
+ | 'arch'
+ | 'kernel';
+
+export type AgentMachineSortDirection = 'asc' | 'desc';
+
+export type AgentMachineColumn = ColumnDef & {
+ id: AgentMachineColumnId;
+ sortKey?: AgentMachineSortKey;
+};
+
+export const AGENT_MACHINE_COLUMNS: AgentMachineColumn[] = [
+ { id: 'machine', label: 'Machine', kind: 'name', sortKey: 'name' },
+ { id: 'system', label: 'System', kind: 'text', sortKey: 'system', toggleable: true },
+ { id: 'agent', label: 'Agent', kind: 'text', sortKey: 'agent', toggleable: true },
+ { id: 'cpu', label: 'CPU', kind: 'metric-bar', sortKey: 'cpu' },
+ { id: 'memory', label: 'Memory', kind: 'metric-bar', sortKey: 'memory' },
+ { id: 'disk', label: 'Disk', kind: 'metric-bar', sortKey: 'disk' },
+ { id: 'network', label: 'Net I/O', kind: 'numeric-value', sortKey: 'network', toggleable: true },
+ { id: 'diskio', label: 'Disk I/O', kind: 'numeric-value', sortKey: 'diskio', toggleable: true },
+ { id: 'uptime', label: 'Uptime', kind: 'numeric-value', sortKey: 'uptime', toggleable: true },
+ { id: 'temp', label: 'Temp', kind: 'numeric-value', sortKey: 'temp', toggleable: true },
+ {
+ id: 'lastSeen',
+ label: 'Last seen',
+ kind: 'numeric-value',
+ sortKey: 'lastSeen',
+ toggleable: true,
+ },
+ {
+ id: 'ip',
+ label: 'IP',
+ kind: 'text',
+ sortKey: 'ip',
+ toggleable: true,
+ defaultHidden: true,
+ },
+ {
+ id: 'raid',
+ label: 'RAID',
+ kind: 'text',
+ sortKey: 'raid',
+ toggleable: true,
+ defaultHidden: true,
+ },
+ {
+ id: 'arch',
+ label: 'Arch',
+ kind: 'text',
+ sortKey: 'arch',
+ toggleable: true,
+ defaultHidden: true,
+ },
+ {
+ id: 'kernel',
+ label: 'Kernel',
+ kind: 'text',
+ sortKey: 'kernel',
+ toggleable: true,
+ defaultHidden: true,
+ },
+];
+
+const AGENT_MACHINE_SORT_DESC_DEFAULTS = new Set<AgentMachineSortKey>([
+ 'cpu',
+ 'memory',
+ 'disk',
+ 'network',
+ 'diskio',
+ 'uptime',
+ 'temp',
+ 'lastSeen',
+]);
+
+const finiteMetric = (value: number | undefined): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+const getMetricPercent = (metric: Resource['cpu'] | undefined): number | undefined =>
+ finiteMetric(metric?.current);
+
+export const getAgentMachineCpuPercent = (machine: Resource): number | undefined =>
+ getMetricPercent(machine.cpu);
+
+export const getAgentMachineMemoryPercent = (machine: Resource): number | undefined => {
+ const total = finiteMetric(machine.memory?.total);
+ const used = finiteMetric(machine.memory?.used);
+ if (total && total > 0 && typeof used === 'number') {
+ return (used / total) * 100;
+ }
+ return finiteMetric(machine.memory?.current) ?? finiteMetric(machine.agent?.memory?.usage);
+};
+
+export const getAgentMachineDiskPercent = (machine: Resource): number | undefined => {
+ const total = finiteMetric(machine.disk?.total);
+ const used = finiteMetric(machine.disk?.used);
+ if (total && total > 0 && typeof used === 'number') {
+ return (used / total) * 100;
+ }
+ return finiteMetric(machine.disk?.current);
+};
+
+export const getAgentMachineNetworkTotal = (machine: Resource): number | undefined => {
+ const rx = finiteMetric(machine.network?.rxBytes);
+ const tx = finiteMetric(machine.network?.txBytes);
+ if (rx === undefined && tx === undefined) return undefined;
+ return (rx ?? 0) + (tx ?? 0);
+};
+
+export const getAgentMachineDiskIOTotal = (machine: Resource): number | undefined => {
+ const read = finiteMetric(machine.diskIO?.readRate);
+ const write = finiteMetric(machine.diskIO?.writeRate);
+ if (read === undefined && write === undefined) return undefined;
+ return (read ?? 0) + (write ?? 0);
+};
+
+export const getAgentMachineTemperatureCelsius = (machine: Resource): number | undefined => {
+ const direct = finiteMetric(machine.temperature);
+ if (direct !== undefined && direct > 0) return direct;
+
+ const values = Object.values(machine.agent?.sensors?.temperatureCelsius ?? {}).filter(
+ (value): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0,
+ );
+ return values.length > 0 ? Math.max(...values) : undefined;
+};
+
+export const getAgentMachineTemperatureTitle = (machine: Resource): string => {
+ const readings = Object.entries(machine.agent?.sensors?.temperatureCelsius ?? {})
+ .filter(([, value]) => typeof value === 'number' && Number.isFinite(value) && value > 0)
+ .sort((left, right) => right[1] - left[1])
+ .slice(0, 6)
+ .map(([label, value]) => `${label}: ${Math.round(value)}°C`);
+ return readings.join('\n');
+};
+
+export const timestampMillisFrom = (
+ value: number | string | Date | undefined,
+): number | undefined => {
+ if (value instanceof Date) {
+ const millis = value.getTime();
+ return Number.isFinite(millis) ? millis : undefined;
+ }
+ if (typeof value === 'string') {
+ const millis = Date.parse(value);
+ return Number.isFinite(millis) ? millis : undefined;
+ }
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;
+ return value < 10_000_000_000 ? value * 1000 : value;
+};
+
+export const getAgentMachineIpValues = (machine: Resource): string[] => {
+ const candidates = [
+ ...(machine.identity?.ips ?? []),
+ ...(machine.agent?.networkInterfaces ?? []).flatMap((iface) => iface.addresses ?? []),
+ ];
+ const seen = new Set<string>();
+ const result: string[] = [];
+
+ for (const candidate of candidates) {
+ const value = asTrimmedString(candidate);
+ if (!value || seen.has(value)) continue;
+ seen.add(value);
+ result.push(value);
+ }
+ return result;
+};
+
+export const getAgentMachinePrimaryIp = (machine: Resource): string =>
+ getAgentMachineIpValues(machine)[0] ?? '';
+
+export const getAgentMachineRaidSummary = (machine: Resource): string => {
+ const arrays = machine.agent?.raid ?? [];
+ if (arrays.length === 0) return '';
+
+ const failed = arrays.filter((array) => (array.failedDevices ?? 0) > 0).length;
+ if (failed > 0) {
+ return `${failed}/${arrays.length} degraded`;
+ }
+
+ const rebuilding = arrays.filter((array) => (array.rebuildPercent ?? 0) > 0).length;
+ if (rebuilding > 0) {
+ return `${rebuilding}/${arrays.length} rebuilding`;
+ }
+
+ const states = new Set(
+ arrays
+ .map((array) => asTrimmedString(array.state)?.toLowerCase())
+ .filter((state): state is string => Boolean(state)),
+ );
+ if (states.size === 1) {
+ return `${arrays.length} ${[...states][0]}`;
+ }
+ return `${arrays.length} arrays`;
+};
+
+export const getNextAgentMachineSortState = (
+ currentKey: AgentMachineSortKey,
+ currentDirection: AgentMachineSortDirection,
+ nextKey: AgentMachineSortKey,
+): { key: AgentMachineSortKey; direction: AgentMachineSortDirection } => {
+ if (currentKey === nextKey) {
+ return { key: nextKey, direction: currentDirection === 'asc' ? 'desc' : 'asc' };
+ }
+
+ return {
+ key: nextKey,
+ direction: AGENT_MACHINE_SORT_DESC_DEFAULTS.has(nextKey) ? 'desc' : 'asc',
+ };
+};
+
+const compareNullableNumber = (
+ left: number | undefined,
+ right: number | undefined,
+ direction: AgentMachineSortDirection,
+): number => {
+ const leftMissing = left === undefined;
+ const rightMissing = right === undefined;
+ if (leftMissing && rightMissing) return 0;
+ if (leftMissing) return 1;
+ if (rightMissing) return -1;
+ return direction === 'asc' ? left - right : right - left;
+};
+
+const compareText = (
+ left: string | undefined,
+ right: string | undefined,
+ direction: AgentMachineSortDirection,
+): number => {
+ const leftValue = (left ?? '').trim().toLowerCase();
+ const rightValue = (right ?? '').trim().toLowerCase();
+ if (!leftValue && !rightValue) return 0;
+ if (!leftValue) return 1;
+ if (!rightValue) return -1;
+ const result = leftValue.localeCompare(rightValue, undefined, { numeric: true });
+ return direction === 'asc' ? result : -result;
+};
+
+export const sortAgentMachines = (
+ machines: readonly Resource[],
+ sortKey: AgentMachineSortKey,
+ direction: AgentMachineSortDirection,
+ getSystemLabel: (machine: Resource) => string,
+ getAgentLabel: (machine: Resource) => string,
+): Resource[] =>
+ [...machines].sort((left, right) => {
+ let result = 0;
+ switch (sortKey) {
+ case 'cpu':
+ result = compareNullableNumber(
+ getAgentMachineCpuPercent(left),
+ getAgentMachineCpuPercent(right),
+ direction,
+ );
+ break;
+ case 'memory':
+ result = compareNullableNumber(
+ getAgentMachineMemoryPercent(left),
+ getAgentMachineMemoryPercent(right),
+ direction,
+ );
+ break;
+ case 'disk':
+ result = compareNullableNumber(
+ getAgentMachineDiskPercent(left),
+ getAgentMachineDiskPercent(right),
+ direction,
+ );
+ break;
+ case 'network':
+ result = compareNullableNumber(
+ getAgentMachineNetworkTotal(left),
+ getAgentMachineNetworkTotal(right),
+ direction,
+ );
+ break;
+ case 'diskio':
+ result = compareNullableNumber(
+ getAgentMachineDiskIOTotal(left),
+ getAgentMachineDiskIOTotal(right),
+ direction,
+ );
+ break;
+ case 'uptime':
+ result = compareNullableNumber(
+ left.uptime ?? left.agent?.uptimeSeconds,
+ right.uptime ?? right.agent?.uptimeSeconds,
+ direction,
+ );
+ break;
+ case 'temp':
+ result = compareNullableNumber(
+ getAgentMachineTemperatureCelsius(left),
+ getAgentMachineTemperatureCelsius(right),
+ direction,
+ );
+ break;
+ case 'lastSeen':
+ result = compareNullableNumber(
+ timestampMillisFrom(left.lastSeen),
+ timestampMillisFrom(right.lastSeen),
+ direction,
+ );
+ break;
+ case 'system':
+ result = compareText(getSystemLabel(left), getSystemLabel(right), direction);
+ break;
+ case 'agent':
+ result = compareText(getAgentLabel(left), getAgentLabel(right), direction);
+ break;
+ case 'ip':
+ result = compareText(
+ getAgentMachinePrimaryIp(left),
+ getAgentMachinePrimaryIp(right),
+ direction,
+ );
+ break;
+ case 'raid':
+ result = compareText(
+ getAgentMachineRaidSummary(left),
+ getAgentMachineRaidSummary(right),
+ direction,
+ );
+ break;
+ case 'arch':
+ result = compareText(left.agent?.architecture, right.agent?.architecture, direction);
+ break;
+ case 'kernel':
+ result = compareText(left.agent?.kernelVersion, right.agent?.kernelVersion, direction);
+ break;
+ case 'name':
+ default:
+ result = compareText(
+ left.displayName || left.name || left.id,
+ right.displayName || right.name || right.id,
+ direction,
+ );
+ break;
+ }
+
+ if (result !== 0) return result;
+ return compareText(
+ left.displayName || left.name || left.id,
+ right.displayName || right.name || right.id,
+ 'asc',
+ );
+ });