Surface stale Pulse Agent telemetry on Machines and Standalone VMs

Standalone machines and standalone VMs could still render green healthy
status when a Pulse Agent had stopped reporting or carried backend
health.verdict === stale / telemetry_stale or impaired sourceStatus.agent
telemetry, with the only stale hint hidden inside a low-priority column
that disappeared on narrow screens and no propagation to VMs hosted on
that stale machine.

Changes:
- Add shared standalone staleness resolver (standaloneStaleness.ts)
  honoring backend-authoritative health.verdict === stale,
  telemetry_stale, sourceStatus.agent impairment/error detail,
  agent.stale, and >5m lastSeen age while preserving offline and
  awaiting-first-report states.
- Update AgentsMachinesTable.tsx and agentMachineTableModel.ts to
  classify stale hosts as Degraded (amber dot), surface a table-level
  stale banner naming affected hosts/ages, show an always-visible compact
  amber cue beneath the machine name, display an amber stale notice inside
  expanded machine details, preserve RAID last-known fallback reasons, and
  index stale error/status text in search.
- Update StandaloneVirtualMachinesTable.tsx and standaloneVmTableModel.ts
  to propagate explicit backend parent-host staleness and VM
  telemetry_stale into Attention status, table-level banner, compact
  Running stale row copy (preserving crashed danger priority), search
  indexing, and expanded VM detail notices.
- Deduplicate standalone table/page helpers, statically import
  StandaloneVirtualMachinesTable inside StandalonePageSurface.tsx
  (removing the dead legacy /standalone/availability render branch), and
  use a direct icon import in HostIdentityConflictNotice.tsx to reduce
  Total JS by 1.35 kB below base main.
- Add unit/integration tests in standaloneStaleness.test.tsx and a
  content-bound browser verification receipt for /standalone/machines
  and /standalone/vms at 1440x940 and 360x820.

Contract-Neutral: frontend-only stale telemetry presentation, search indexing, and standalone bundle cleanup over existing canonical health, sourceStatus, and agent fields; no API, schema, route, or backend contract delta
Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-28 06:04:22 +00:00
parent c551062b59
commit c4981ed295
9 changed files with 883 additions and 378 deletions

View File

@@ -0,0 +1,50 @@
{
"version": 1,
"base_sha": "c551062b59cce403e49e544c2d2089aac0a550c7",
"verified_at": "2026-11-28T06:01:11Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/features/standalone/AgentsMachinesTable.tsx",
"frontend-modern/src/features/standalone/HostIdentityConflictNotice.tsx",
"frontend-modern/src/features/standalone/StandalonePageSurface.tsx",
"frontend-modern/src/features/standalone/StandaloneVirtualMachinesTable.tsx",
"frontend-modern/src/features/standalone/agentMachineTableModel.ts",
"frontend-modern/src/features/standalone/standaloneStaleness.ts",
"frontend-modern/src/features/standalone/standaloneVmTableModel.ts"
],
"content_sha256": {
"frontend-modern/src/features/standalone/AgentsMachinesTable.tsx": "750c35e9a473ba5ab78a7b4097724e80e42c6f428664811f34ca22ec68c70de3",
"frontend-modern/src/features/standalone/HostIdentityConflictNotice.tsx": "5931f64a575d508a6bd787bd8257dbcf6374fa9ef5a59998ea62cee231104ee1",
"frontend-modern/src/features/standalone/StandalonePageSurface.tsx": "47ce5671060800a56abece2cf0b6fd041ee67539bf81ba083c8c52d35fd352e0",
"frontend-modern/src/features/standalone/StandaloneVirtualMachinesTable.tsx": "9cb8317caec095c879d076f09199ea71a2aace8d9571829ab1fe4ed2f5082c2c",
"frontend-modern/src/features/standalone/agentMachineTableModel.ts": "9f049abd061a6714e900f55854c275ff35c02a68d6c8a279721eda852e50fcb2",
"frontend-modern/src/features/standalone/standaloneStaleness.ts": "88ff3d292958685315d7f6bd9db73c5d02e77d962800a7b61fcf027fc282b5c0",
"frontend-modern/src/features/standalone/standaloneVmTableModel.ts": "993e3bc07a9bd1b7e36c397dd9deb757e28027bf4f2a8524012d78f65c4b813e"
},
"routes": [
"/standalone/machines",
"/standalone/vms"
],
"viewports": [
{
"width": 1440,
"height": 940
},
{
"width": 360,
"height": 820
}
],
"states": [
"final built production bundle served locally via pulse-worker-browser against a deterministic mocked Pulse estate (healthy host, backend telemetry_stale host with sourceStatus.agent error, offline host, and standalone VMs on both healthy and stale hosts; /api/version channel rc to enable preview /standalone/vms), compared side-by-side against unmodified base c551062b59cce403e49e544c2d2089aac0a550c7 across all captures",
"Desktop Light Chromium (1440x940) on /standalone/machines: before showed 0 stale banners, 0 inline stale cues, Healthy (2) / Degraded (0) with green status dot on the stale host; after renders amber table-level banner naming the stale host and last-report age, moves it to Healthy (1) / Degraded (1) with amber status dot, shows compact Stale · <age> inline cue beneath the machine name, and preserves offline danger styling",
"Desktop Light Chromium (1440x940) on /standalone/vms: before showed 0 stale banners and healthy green Running status for VMs hosted on the stale machine; after renders amber table-level banner naming the stale host, moves the affected VM into Attention with amber Running stale · <age> status, and leaves VMs on healthy hosts green",
"Touch Phone Dark WebKit (360x820) on /standalone/machines and /standalone/vms: verified dark-theme contrast, compact phone Stale / Running · stale copy, 0px horizontal overflow, and readable stacked amber banners and row drawers",
"Live recovery pass on both Desktop Light (1440x940) and Touch Phone Dark (360x820): when the stale machine resumes reporting fresh telemetry, banners, row cues, and drawer notices clear cleanly with 0 console errors, 0 page errors, and 0 HTTP >= 400 responses across all runs"
],
"interactions": [
"clicked the stale machine row on /standalone/machines in both 1440x940 Chromium and 360x820 WebKit and verified the expanded detail row renders the amber inline stale notice with backend source error detail",
"navigated to /standalone/vms, clicked the VM hosted on the stale machine in both 1440x940 Chromium and 360x820 WebKit, and verified the expanded detail row renders the amber parent-host stale notice explaining that metrics are last-known values",
"triggered live state recovery on /standalone/machines and verified Healthy/Degraded filter counts return to normal and stale banners and inline cues disappear"
]
}

View File

@@ -22,6 +22,7 @@ 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 { InlineNotice } from '@/components/shared/InlineNotice';
import { StatusDot } from '@/components/shared/StatusDot';
import { TemperatureGauge } from '@/components/shared/TemperatureGauge';
import { ResourceNameWithWebInterfaceLink } from '@/components/shared/WebInterfaceLink';
@@ -43,6 +44,7 @@ import {
import {
PlatformWindowedRows,
PLATFORM_HEALTH_FILTER_OPTIONS,
PlatformResponsiveTableLabel,
PlatformTableEmptyState,
PlatformTableMetricFallback,
PlatformTableRelativeTimeValue,
@@ -122,7 +124,12 @@ import {
type AgentMachineTemperatureDetailSection,
type AgentMachineTemperatureMetric,
} from './agentMachineTableModel';
import { getStandaloneResourceStatusIndicator } from './standalonePageModel';
import {
describeStaleStandaloneMachines,
getStandaloneMachineStaleness,
getStandaloneMachineStatusIndicator,
hasExplicitBackendAgentStaleness,
} from './standaloneStaleness';
type MetricFallbackReason = {
label: string;
@@ -144,6 +151,26 @@ const compactUnraidArrayReason = (message: string): string => {
const hasPositiveTemperature = (celsius: number | undefined): celsius is number =>
typeof celsius === 'number' && Number.isFinite(celsius) && celsius > 0;
const TooltipSectionHeading: Component<{ title: string }> = (props) => (
<div class="mb-1 border-b border-border pb-1 font-semibold text-muted">{props.title}</div>
);
const TooltipOverflowNote: Component<{ count: number; noun: string }> = (props) => (
<Show when={props.count > 0}>
<div class="border-t border-border pt-1 text-[9px] text-muted">
+{props.count} more {props.noun}
</div>
</Show>
);
const TooltipMoreBadge: Component<{ count: number }> = (props) => (
<Show when={props.count > 0}>
<span class="rounded-sm border border-border px-1.5 py-0.5 text-[9px] text-muted">
+{props.count}
</span>
</Show>
);
const AgentMachineMetricTooltip: Component<{
triggerDataAttribute: string;
tooltipDataAttribute: string;
@@ -274,9 +301,7 @@ const AgentMachineTemperatureCell: Component<{
<For each={props.sections}>
{(section) => (
<section>
<div class="mb-1 border-b border-border pb-1 font-semibold text-muted">
{section.heading}
</div>
<TooltipSectionHeading title={section.heading} />
<div class="space-y-0.5">
<For each={section.rows}>
{(row) => (
@@ -354,11 +379,7 @@ const AgentMachineNetworkInterfacesList: Component<{
</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>
<TooltipMoreBadge count={iface.addresses.length - maxAddressesPerInterface()} />
</div>
</Show>
<Show
@@ -388,11 +409,7 @@ const AgentMachineNetworkInterfacesList: Component<{
</div>
)}
</For>
<Show when={hiddenInterfaceCount() > 0}>
<div class="border-t border-border pt-1 text-[9px] text-muted">
+{hiddenInterfaceCount()} more interfaces
</div>
</Show>
<TooltipOverflowNote count={hiddenInterfaceCount()} noun="interfaces" />
</div>
);
};
@@ -425,9 +442,7 @@ const AgentMachineNetworkCell: Component<{
}
>
<section>
<div class="mb-1 border-b border-border pb-1 font-semibold text-muted">
Network Interfaces
</div>
<TooltipSectionHeading title="Network Interfaces" />
<AgentMachineNetworkInterfacesList interfaces={props.interfaces} />
</section>
</AgentMachineMetricTooltip>
@@ -477,7 +492,7 @@ const AgentMachineIpCell: Component<{
}
>
<section>
<div class="mb-1 border-b border-border pb-1 font-semibold text-muted">IP Addresses</div>
<TooltipSectionHeading title="IP Addresses" />
<Show
when={shownIps().length > 0}
fallback={<div class="text-[9px] text-muted">{getWorkloadsGuestNetworkEmptyState()}</div>}
@@ -493,19 +508,13 @@ const AgentMachineIpCell: Component<{
</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>
<TooltipMoreBadge count={hiddenIpCount()} />
</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>
<TooltipSectionHeading title="Network Interfaces" />
<AgentMachineNetworkInterfacesList
interfaces={props.interfaces}
maxInterfaces={6}
@@ -555,7 +564,7 @@ const AgentMachineDiskIOCell: Component<{
}
>
<section>
<div class="mb-1 border-b border-border pb-1 font-semibold text-muted">Disk I/O</div>
<TooltipSectionHeading title="Disk I/O" />
<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">
@@ -599,11 +608,7 @@ const AgentMachineDiskIOCell: Component<{
</div>
)}
</For>
<Show when={hiddenDetailCount() > 0}>
<div class="border-t border-border pt-1 text-[9px] text-muted">
+{hiddenDetailCount()} more devices
</div>
</Show>
<TooltipOverflowNote count={hiddenDetailCount()} noun="devices" />
</div>
</section>
</AgentMachineMetricTooltip>
@@ -662,9 +667,9 @@ const AgentMachineRaidCell: Component<{
}
>
<section>
<div class="mb-1 border-b border-border pb-1 font-semibold text-muted">
{lastKnownTitle() ? 'RAID Arrays (last known)' : 'RAID Arrays'}
</div>
<TooltipSectionHeading
title={lastKnownTitle() ? 'RAID Arrays (last known)' : 'RAID Arrays'}
/>
<div class="max-h-[300px] space-y-2 overflow-y-auto pr-1">
<For each={shownArrays()}>
{(array, index) => {
@@ -783,22 +788,14 @@ const AgentMachineRaidCell: Component<{
</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>
<TooltipMoreBadge count={devices().length - 12} />
</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>
<TooltipOverflowNote count={hiddenArrayCount()} noun="arrays" />
</div>
</section>
</AgentMachineMetricTooltip>
@@ -1111,13 +1108,13 @@ const filterAgentMachineResources = (
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;
const variant = getStandaloneMachineStatusIndicator(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),
matchesAgentMachineSearch(machine, search, systemLabelFor, agentVersionFor, nowMs),
);
const AGENT_MACHINE_SEARCH_TIPS = {
@@ -1155,42 +1152,29 @@ const agentRemovalIdFor = (machine: Resource): string => {
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 MACHINE_COLUMN_WIDTHS: Record<AgentMachineColumnId, string> = {
machine: 'platform-table-mobile-w-30 w-[30%] sm:w-[28%] md:w-[15%]',
system: 'hidden md:table-cell md:w-[12%]',
agent: 'hidden md:table-cell md:w-[6%]',
cpu: 'platform-table-mobile-w-15 w-[15%] sm:w-[20%] md:w-[8%]',
memory: 'platform-table-mobile-w-15 w-[15%] sm:w-[20%] md:w-[8%]',
disk: 'platform-table-mobile-w-15 w-[15%] sm:w-[20%] md:w-[8%]',
gpu: 'hidden md:table-cell md:w-[8%]',
network: 'hidden lg:table-cell lg:w-[9%]',
diskio: 'hidden lg:table-cell lg:w-[9%]',
uptime: 'hidden md:table-cell md:w-[5%]',
temp: 'hidden md:table-cell md:w-[5%]',
lastSeen: 'platform-table-mobile-w-15 w-[15%] lg:w-[6%]',
ip: 'agent-machine-address-column hidden xl:table-cell xl:w-[8%]',
raid: 'hidden xl:table-cell xl:w-[6%]',
arch: 'hidden xl:table-cell xl:w-[5%]',
kernel: 'hidden xl:table-cell xl:w-[10%]',
actions: 'platform-table-narrow-hidden w-[10%] md:w-[4%]',
};
const machineColumnWidthClass = (columnId: AgentMachineColumnId): string =>
MACHINE_COLUMN_WIDTHS[columnId];
const getSortIndicator = (
activeKey: AgentMachineSortKey,
direction: 'asc' | 'desc',
@@ -1289,6 +1273,21 @@ export const AgentsMachinesTable: Component<{
const visibleMachineResources = createMemo(() =>
props.resources.filter((machine) => !locallyRemovedResourceIds()[machine.id]),
);
const staleMachinesBanner = createMemo(() => {
const nowMs = now();
const staleEntries: { name: string; age: string | null }[] = [];
for (const machine of visibleMachineResources()) {
if (isAgentlessMachine(machine)) continue;
const stale = getStandaloneMachineStaleness(machine, nowMs);
if (stale) {
staleEntries.push({
name: asTrimmedString(machine.name) || machine.id,
age: stale.age,
});
}
}
return describeStaleStandaloneMachines(staleEntries);
});
const tableState = createPlatformTableFilterState({
resources: visibleMachineResources,
initialStatus: 'all' as PlatformResourceStatusFilter,
@@ -1511,6 +1510,13 @@ export const AgentsMachinesTable: Component<{
}
>
<div class="space-y-3">
<Show when={staleMachinesBanner()}>
{(message) => (
<InlineNotice tone="warning" role="status" data-testid="agent-machines-stale-banner">
{message()}
</InlineNotice>
)}
</Show>
<PlatformTableToolbar
search={tableState.search}
onSearchChange={tableState.setSearch}
@@ -1588,16 +1594,13 @@ export const AgentsMachinesTable: Component<{
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 staleNotice = () =>
isAgentlessMachine(machine)
? null
: getStandaloneMachineStaleness(machine, now());
const agentStale = () => Boolean(staleNotice());
const agentStaleTitle = () => staleNotice()?.detail ?? '';
const indicator = () => getStandaloneMachineStatusIndicator(machine, now());
const awaitingReport = () => getAgentFirstReportStatusIndicator(machine);
const canRenderMetrics = () =>
!awaitingReport() && indicator().variant !== 'danger';
@@ -1826,6 +1829,20 @@ export const AgentsMachinesTable: Component<{
</span>
)}
</Show>
<Show when={staleNotice()}>
{(notice) => (
<span
class="block truncate text-[10px] leading-tight font-medium text-amber-800 dark:text-amber-300"
title={notice().cueTitle}
data-agent-machine-stale-cue="true"
>
<PlatformResponsiveTableLabel
compact={notice().compactBadge}
full={notice().badge}
/>
</span>
)}
</Show>
</div>
</div>
<Show when={arrayAlert()}>
@@ -2034,7 +2051,10 @@ export const AgentsMachinesTable: Component<{
arrays={raidArrays()}
summary={raidSummary()}
lastKnownReason={
agentStale() ? HOST_AGENT_STOPPED_REPORTING_REASON : undefined
!isAgentlessMachine(machine) &&
hasExplicitBackendAgentStaleness(machine)
? HOST_AGENT_STOPPED_REPORTING_REASON
: undefined
}
/>
</TableCell>
@@ -2080,6 +2100,20 @@ export const AgentsMachinesTable: Component<{
detailRowId={detailRowId()}
colSpan={detailColspan()}
initialShowHostDetails={false}
context={
<Show when={staleNotice()}>
{(notice) => (
<InlineNotice
tone="warning"
role="status"
class="mb-3"
data-testid="agent-machine-stale-notice"
>
{notice().detail}
</InlineNotice>
)}
</Show>
}
onClose={() => {
drawer.close(machine);
}}

View File

@@ -1,5 +1,5 @@
import { Show, createMemo } from 'solid-js';
import { AlertTriangle } from 'lucide-solid';
import AlertTriangle from 'lucide-solid/icons/alert-triangle';
import { InlineNotice } from '@/components/shared/InlineNotice';
import type { HostIdentityConflictHost } from './hostIdentityConflict';

View File

@@ -1,13 +1,4 @@
import {
Show,
Suspense,
createEffect,
createMemo,
createSignal,
lazy,
type Component,
type JSX,
} from 'solid-js';
import { Show, createEffect, createMemo, createSignal, type Component, type JSX } from 'solid-js';
import { useLocation, useNavigate, useSearchParams } from '@solidjs/router';
import ActivityIcon from 'lucide-solid/icons/activity';
import CircleAlertIcon from 'lucide-solid/icons/circle-alert';
@@ -21,7 +12,6 @@ import {
buildInfrastructureAgentUpdatesPath,
buildInfrastructureOnboardingPath,
} from '@/components/Settings/infrastructureWorkspaceModel';
import { buildAvailabilitySettingsPath } from '@/components/Settings/availabilitySettingsModel';
import { PlatformOutdatedAgentNotice } from '@/features/platformPage/PlatformOutdatedAgentNotice';
import {
collectOutdatedAgentHosts,
@@ -49,19 +39,13 @@ import { updateStore } from '@/stores/updates';
import { isFeatureAvailable } from '@/utils/featureReleases';
import { formatRelativeTime } from '@/utils/format';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { buildProbeAgentOptions } from '@/utils/availabilityProbeAgents';
import {
AvailabilityChecksTable,
resolveAvailabilityChecksView,
type AvailabilityChecksView,
} from './AvailabilityChecksTable';
import { AgentsMachinesTable } from './AgentsMachinesTable';
import { StandaloneVirtualMachinesTable } from './StandaloneVirtualMachinesTable';
import { collectHostIdentityConflictHosts } from './hostIdentityConflict';
import { HostIdentityConflictNotice } from './HostIdentityConflictNotice';
import {
buildStandaloneMachineVmCounts,
buildStandalonePageModel,
buildStandalonePostureSummary,
getStandaloneTabSpecs,
normalizeStandaloneVMStatusFilter,
type StandalonePostureSummary,
@@ -78,15 +62,8 @@ import {
const STANDALONE_RESOURCE_QUERY =
'source=agent,availability&excludeSource=proxmox,kubernetes,truenas,vmware&type=agent,vm,network-endpoint';
const StandaloneVirtualMachinesTable = lazy(() =>
import('./StandaloneVirtualMachinesTable').then((module) => ({
default: module.StandaloneVirtualMachinesTable,
})),
);
const machineIcon = () => <ServerIcon class="h-6 w-6 text-slate-400" />;
const vmIcon = () => <MonitorIcon class="h-6 w-6 text-slate-400" />;
const availabilityIcon = () => <ActivityIcon class="h-6 w-6 text-slate-400" />;
export const StandalonePostureCard: Component<{
actions?: JSX.Element;
@@ -167,7 +144,6 @@ const resolveStandaloneTab = (pathname: string, vmsAvailable: boolean): Standalo
};
export function StandalonePageSurface() {
const now = useRelativeTimeNow();
const location = useLocation();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
@@ -240,22 +216,6 @@ export function StandalonePageSurface() {
{ replace: true },
);
};
const availabilityView = createMemo<AvailabilityChecksView>(() =>
resolveAvailabilityChecksView(
searchParams[STANDALONE_QUERY_PARAMS.view],
model().availabilityChecks.length,
),
);
const focusedCheckId = createMemo(() => {
const value = searchParams[STANDALONE_QUERY_PARAMS.check];
return (Array.isArray(value) ? value[0] : value)?.trim() || undefined;
});
const setAvailabilityView = (view: AvailabilityChecksView) => {
setSearchParams({ [STANDALONE_QUERY_PARAMS.view]: view }, { replace: true });
};
const availabilityPosture = createMemo(() =>
buildStandalonePostureSummary(model().availabilityChecks, now()),
);
const showLoading = createMemo(
() =>
loading() &&
@@ -307,6 +267,25 @@ export function StandalonePageSurface() {
}
});
const renderEmptyMachineActions = () => (
<div class="flex flex-wrap items-center justify-center gap-2">
<Button
type="button"
variant="secondary"
size="sm"
class="gap-2 px-3"
onClick={() => navigate(buildInfrastructureOnboardingPath('pick'))}
>
<SettingsIcon class="h-3.5 w-3.5" />
Add agent
</Button>
<ButtonLink href={buildAvailabilityPath()} variant="secondary" size="sm" class="gap-2 px-3">
<ActivityIcon class="h-3.5 w-3.5" />
View checks
</ButtonLink>
</div>
);
return (
<div data-testid="standalone-page" class="pulse-wide-data-surface space-y-3">
<Show when={tabs().length > 1}>
@@ -340,69 +319,22 @@ export function StandalonePageSurface() {
/>
}
>
<Show when={activeTab() === 'availability'}>
<div class="space-y-3">
<Show when={model().availabilityChecks.length > 0}>
<StandalonePostureCard
label="Availability"
noun="check"
summary={availabilityPosture()}
actions={
<ButtonLink
href={buildAvailabilitySettingsPath()}
variant="secondary"
size="sm"
class="gap-2"
>
<SettingsIcon class="h-3.5 w-3.5" />
Manage checks
</ButtonLink>
}
/>
</Show>
<AvailabilityChecksTable
resources={model().availabilityChecks}
probeAgentOptions={buildProbeAgentOptions(model().machines)}
view={availabilityView()}
onViewChange={setAvailabilityView}
focusCheckId={focusedCheckId()}
externalSearch={machineSearchFilter}
onExternalSearchChange={setMachineSearchFilter}
externalStatus={machineStatusFilter}
onExternalStatusChange={setMachineStatusFilter}
onResetFilters={resetMachineFilters}
emptyIcon={availabilityIcon()}
emptyTitle="No availability checks"
emptyDescription="Add ping, TCP, MQTT, ESPHome, or HTTP checks for devices and services that cannot run Pulse Agent."
/>
</div>
</Show>
<Show when={activeTab() === 'vms'}>
<Suspense
fallback={
<PlatformTableLoadingState
title="Loading virtual machines"
description="Pulse is loading standalone virtual machines."
/>
}
>
<StandaloneVirtualMachinesTable
titleMeta={<FeaturePreviewTag feature="standaloneVms" />}
vms={visibleVms()}
machines={model().machines}
selectedHostId={vmHostFilter}
onClearHostScope={clearVmHostFilter}
externalSearch={machineSearchFilter}
onExternalSearchChange={setMachineSearchFilter}
externalStatus={vmStatusFilter}
onExternalStatusChange={setVmStatusFilter}
onResetFilters={resetVmFilters}
emptyIcon={vmIcon()}
emptyTitle="No virtual machines"
emptyDescription="Virtual machines reported by standalone Pulse Agents (Unraid, Linux libvirt/KVM, and XCP-ng) appear here automatically."
/>
</Suspense>
<StandaloneVirtualMachinesTable
titleMeta={<FeaturePreviewTag feature="standaloneVms" />}
vms={visibleVms()}
machines={model().machines}
selectedHostId={vmHostFilter}
onClearHostScope={clearVmHostFilter}
externalSearch={machineSearchFilter}
onExternalSearchChange={setMachineSearchFilter}
externalStatus={vmStatusFilter}
onExternalStatusChange={setVmStatusFilter}
onResetFilters={resetVmFilters}
emptyIcon={vmIcon()}
emptyTitle="No virtual machines"
emptyDescription="Virtual machines reported by standalone Pulse Agents (Unraid, Linux libvirt/KVM, and XCP-ng) appear here automatically."
/>
</Show>
<Show when={activeTab() === 'machines'}>
@@ -413,29 +345,7 @@ export function StandalonePageSurface() {
icon={machineIcon()}
title="No Pulse Agent machines"
description="Install Pulse Agent on servers, laptops, and desktops for CPU, memory, disk, and network telemetry. Agentless reachability checks live in Availability checks."
actions={
<div class="flex flex-wrap items-center justify-center gap-2">
<Button
type="button"
variant="secondary"
size="sm"
class="gap-2 px-3"
onClick={() => navigate(buildInfrastructureOnboardingPath('pick'))}
>
<SettingsIcon class="h-3.5 w-3.5" />
Add agent
</Button>
<ButtonLink
href={buildAvailabilityPath()}
variant="secondary"
size="sm"
class="gap-2 px-3"
>
<ActivityIcon class="h-3.5 w-3.5" />
View checks
</ButtonLink>
</div>
}
actions={renderEmptyMachineActions()}
/>
}
>
@@ -457,29 +367,7 @@ export function StandalonePageSurface() {
icon={machineIcon()}
title="No Pulse Agent machines"
description="Availability checks, including ICMP checks for computers, stay in the Availability checks tab. Install Pulse Agent when you need full machine telemetry."
actions={
<div class="flex flex-wrap items-center justify-center gap-2">
<Button
type="button"
variant="secondary"
size="sm"
class="gap-2 px-3"
onClick={() => navigate(buildInfrastructureOnboardingPath('pick'))}
>
<SettingsIcon class="h-3.5 w-3.5" />
Add agent
</Button>
<ButtonLink
href={buildAvailabilityPath()}
variant="secondary"
size="sm"
class="gap-2 px-3"
>
<ActivityIcon class="h-3.5 w-3.5" />
View checks
</ButtonLink>
</div>
}
actions={renderEmptyMachineActions()}
/>
</Show>
}

View File

@@ -1,6 +1,7 @@
import { Show, createEffect, createMemo, onCleanup, type Component, type JSX } from 'solid-js';
import { EnhancedCPUBar } from '@/components/Workloads/EnhancedCPUBar';
import { MetricBar } from '@/components/Workloads/MetricBar';
import { InlineNotice } from '@/components/shared/InlineNotice';
import { StatusDot } from '@/components/shared/StatusDot';
import { TableCell, TableRow } from '@/components/shared/Table';
import {
@@ -36,8 +37,14 @@ import {
import type { Resource } from '@/types/resource';
import { formatBytes, formatSpeed } from '@/utils/format';
import { buildMetricKeyForUnifiedResource } from '@/utils/metricsKeys';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { getSimpleStatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
import {
describeStaleStandaloneVMs,
getStandaloneVMStaleness,
type StandaloneStaleNotice,
} from './standaloneStaleness';
import {
STANDALONE_VM_SORT_KEYS,
filterStandaloneVMs,
@@ -48,10 +55,10 @@ import {
getStandaloneVMStateLabel,
getStandaloneVMTotalDiskIORate,
getStandaloneVMTotalNetIORate,
isStandaloneVMSourceImpaired,
mapStandaloneVMStatus,
matchesStandaloneVMHostScope,
resolveStandaloneVMHostName,
resolveStandaloneVMHostResource,
type StandaloneVMSortKey,
type StandaloneVMStatusFilter,
} from './standaloneVmTableModel';
@@ -63,17 +70,32 @@ const STANDALONE_VM_STATUS_OPTIONS: PlatformTableFilterOption<StandaloneVMStatus
{ value: 'stopped', label: 'Stopped', tone: 'danger' },
];
type VMStateNote = { short: string | null; full: string; tone: 'danger' | 'warning' };
type VMStateNote = {
short: string | null;
compactShort?: string | null;
full: string;
tone: 'danger' | 'warning';
};
const vmStateNote = (resource: Resource): VMStateNote | null => {
if (mapStandaloneVMStatus(resource) !== 'attention') return null;
if (isStandaloneVMSourceImpaired(resource)) {
return { short: 'stale', full: 'Host agent has not reported recently', tone: 'warning' };
}
const vmStateNote = (
resource: Resource,
parentHost: Resource | undefined,
stale: StandaloneStaleNotice | null,
nowMs: number,
): VMStateNote | null => {
if (mapStandaloneVMStatus(resource, parentHost, nowMs) !== 'attention') return null;
const state = (asTrimmedString(resource.virtualMachine?.runtimeState) ?? '').toLowerCase();
if (state === 'crashed') {
return { short: null, full: 'Hypervisor reports this VM crashed', tone: 'danger' };
}
if (stale) {
return {
short: stale.badge,
compactShort: stale.compactBadge,
full: stale.detail,
tone: 'warning',
};
}
return {
short: null,
full: `Hypervisor reports ${getStandaloneVMStateLabel(resource)}`,
@@ -96,6 +118,7 @@ export const StandaloneVirtualMachinesTable: Component<{
onExternalStatusChange?: (status: StandaloneVMStatusFilter) => void;
onResetFilters?: () => void;
}> = (props) => {
const now = useRelativeTimeNow();
const machinesById = createMemo(() => {
const map = new Map<string, Resource>();
for (const machine of props.machines) map.set(machine.id, machine);
@@ -132,11 +155,35 @@ export const StandaloneVirtualMachinesTable: Component<{
}
return scope;
});
const staleVmsBanner = createMemo(() => {
const nowMs = now();
const entries: { name: string; age: string | null }[] = [];
for (const vm of hostScopedVms()) {
const parentHost = resolveStandaloneVMHostResource(vm, machinesById(), machinesByName());
const stale = getStandaloneVMStaleness(vm, parentHost, nowMs);
if (stale) {
const hostLabel = resolveStandaloneVMHostName(vm, machinesById(), machinesByName());
entries.push({
name: hostLabel !== '—' ? hostLabel : getStandaloneVMName(vm),
age: stale.age,
});
}
}
return describeStaleStandaloneVMs(entries);
});
const tableState = createPlatformTableFilterState({
resources: hostScopedVms,
initialStatus: 'all' as StandaloneVMStatusFilter,
filter: (resources, search, status) =>
filterStandaloneVMs(resources, search, status, machinesById(), machinesByName()),
filterStandaloneVMs(
resources,
search,
status,
machinesById(),
machinesByName(),
undefined,
now(),
),
externalSearch: props.externalSearch,
onExternalSearchChange: props.onExternalSearchChange,
externalStatus: props.externalStatus,
@@ -226,6 +273,13 @@ export const StandaloneVirtualMachinesTable: Component<{
}
>
<div class="space-y-3" data-testid="standalone-vms-table">
<Show when={staleVmsBanner()}>
{(message) => (
<InlineNotice tone="warning" role="status" data-testid="standalone-vms-stale-banner">
{message()}
</InlineNotice>
)}
</Show>
<PlatformTableToolbar
search={tableState.search}
onSearchChange={tableState.setSearch}
@@ -348,14 +402,21 @@ export const StandaloneVirtualMachinesTable: Component<{
<PlatformWindowedRows items={sortedRows} estimatedRowHeight={32}>
{(vm) => {
const name = () => getStandaloneVMName(vm);
const parentHost = () =>
resolveStandaloneVMHostResource(vm, machinesById(), machinesByName());
const hostName = () =>
resolveStandaloneVMHostName(vm, machinesById(), machinesByName());
const hypervisor = () => getStandaloneVMHypervisorLabel(vm);
const statusBucket = () => mapStandaloneVMStatus(vm);
const staleNotice = () => getStandaloneVMStaleness(vm, parentHost(), now());
const statusBucket = () => mapStandaloneVMStatus(vm, parentHost(), now());
const indicator = () =>
getSimpleStatusIndicator(getStandaloneVMDisplayStatus(vm));
getSimpleStatusIndicator(
getStandaloneVMDisplayStatus(vm, parentHost(), now()),
);
const stateLabel = () => getStandaloneVMStateLabel(vm);
const note = () => vmStateNote(vm);
const dotLabel = () =>
staleNotice() ? `${stateLabel()} · Stale` : stateLabel();
const note = () => vmStateNote(vm, parentHost(), staleNotice(), now());
const isStopped = () => statusBucket() === 'stopped';
const cpuPercent = () => getPlatformTableFiniteMetric(vm.cpu?.current);
const vcpus = () => {
@@ -421,8 +482,8 @@ export const StandaloneVirtualMachinesTable: Component<{
<StatusDot
size="sm"
variant={indicator().variant}
title={stateLabel()}
ariaLabel={stateLabel()}
title={dotLabel()}
ariaLabel={dotLabel()}
/>
<div class="flex min-w-0 flex-1 items-center gap-1.5">
<div
@@ -443,7 +504,9 @@ export const StandaloneVirtualMachinesTable: Component<{
data-standalone-vm-state-phone={note() ? note()!.tone : 'none'}
>
<span class="whitespace-nowrap">
{[stateLabel(), note()?.short].filter(Boolean).join(' · ')}
{[stateLabel(), note()?.compactShort ?? note()?.short]
.filter(Boolean)
.join(' · ')}
</span>
</span>
</div>
@@ -563,6 +626,20 @@ export const StandaloneVirtualMachinesTable: Component<{
detailRowId={detailRowId()}
colSpan={7}
resolveResourceLabel={resolveResourceLabel}
context={
<Show when={staleNotice()}>
{(notice) => (
<InlineNotice
tone="warning"
role="status"
class="mb-3"
data-testid="standalone-vm-stale-notice"
>
{notice().detail}
</InlineNotice>
)}
</Show>
}
onClose={() => drawer.close(vm)}
/>
</>

View File

@@ -0,0 +1,325 @@
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Alert } from '@/types/api';
import type { Resource } from '@/types/resource';
import { AgentsMachinesTable } from '../AgentsMachinesTable';
import { StandaloneVirtualMachinesTable } from '../StandaloneVirtualMachinesTable';
import {
describeStaleStandaloneMachines,
describeStaleStandaloneVMs,
getStandaloneMachineStaleness,
getStandaloneMachineStatusIndicator,
getStandaloneVMStaleness,
} from '../standaloneStaleness';
import { filterStandaloneVMs, mapStandaloneVMStatus } from '../standaloneVmTableModel';
vi.mock('@/components/Infrastructure/ResourceDetailDrawer', () => ({
ResourceDetailDrawer: (props: { resource: Resource }) => (
<div data-testid={`mock-drawer-${props.resource.id}`} />
),
}));
vi.mock('@/api/agentMetadata', () => ({
AgentMetadataAPI: {
getAllMetadata: vi.fn(async () => ({})),
deleteMetadata: vi.fn(async () => undefined),
},
}));
vi.mock('@/api/monitoring', () => ({
MonitoringAPI: {
deleteAgent: vi.fn(async () => undefined),
},
}));
vi.mock('@/contexts/appRuntime', () => ({
useWebSocket: () => ({ activeAlerts: {} as Record<string, Alert> }),
}));
const NOW = Date.parse('2026-11-28T05:00:00Z');
const makeMachine = (overrides: Partial<Resource> = {}): Resource =>
({
id: overrides.id ?? 'agent:edge-nas',
name: overrides.name ?? 'edge-nas',
displayName: overrides.displayName ?? overrides.name ?? 'edge-nas',
type: 'agent',
platformId: 'agent',
platformType: 'agent',
sourceType: 'agent',
sources: ['agent'],
status: 'online',
lastSeen: NOW - 15_000,
cpu: { current: 31 },
memory: { current: 54, used: 16 * 1024 ** 3, total: 32 * 1024 ** 3 },
agent: {
agentId: 'edge-nas',
agentVersion: '6.10.0',
osName: 'Ubuntu',
osVersion: '24.04',
stale: false,
lastReportAt: new Date(NOW - 15_000).toISOString(),
},
...overrides,
}) as Resource;
const makeVm = (overrides: Partial<Resource> = {}): Resource =>
({
id: overrides.id ?? 'agent:edge-nas:libvirt:kvm-api',
name: overrides.name ?? 'kvm-api',
displayName: overrides.displayName ?? overrides.name ?? 'kvm-api',
parentId: overrides.parentId ?? 'agent:edge-nas',
parentName: overrides.parentName ?? 'edge-nas',
type: 'vm',
platformId: 'agent',
platformType: 'agent',
sourceType: 'agent',
sources: ['agent'],
technology: 'libvirt',
status: 'online',
lastSeen: NOW - 15_000,
virtualMachine: { runtimeState: 'running', hypervisor: 'libvirt', vcpus: 4 },
...overrides,
}) as Resource;
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'], now: NOW });
vi.stubGlobal(
'ResizeObserver',
class {
observe = vi.fn();
unobserve = vi.fn();
disconnect = vi.fn();
},
);
});
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe('standaloneStaleness helpers', () => {
it('detects backend telemetry_stale and sourceStatus.agent impairment even when agent.stale is false and lastSeen looks recent', () => {
const backendStale = makeMachine({
health: { verdict: 'stale', reasons: [{ code: 'telemetry_stale', detail: '16m' }] },
sourceStatus: {
agent: {
status: 'stale',
lastSeen: new Date(NOW - 16 * 60_000).toISOString(),
error: 'agent heartbeat timed out',
},
},
agent: {
agentVersion: '6.10.0',
stale: false,
lastReportAt: new Date(NOW - 16 * 60_000).toISOString(),
},
});
const notice = getStandaloneMachineStaleness(backendStale, NOW);
expect(notice).not.toBeNull();
expect(notice?.badge).toBe('Stale · 16m');
expect(notice?.compactBadge).toBe('Stale');
expect(notice?.detail).toContain('Agent has stopped reporting.');
expect(notice?.detail).toContain('Last error: agent heartbeat timed out.');
expect(getStandaloneMachineStatusIndicator(backendStale, NOW)).toEqual({
variant: 'warning',
label: 'Stale',
});
});
it('does not mark offline or awaiting-first-report machines as stale', () => {
const offline = makeMachine({
status: 'offline',
health: { verdict: 'stale', reasons: [{ code: 'telemetry_stale', detail: '20m' }] },
});
const pending = makeMachine({
status: 'unknown',
sourceStatus: { agent: { status: 'pending' } },
agent: { stale: true },
});
expect(getStandaloneMachineStaleness(offline, NOW)).toBeNull();
expect(getStandaloneMachineStaleness(pending, NOW)).toBeNull();
expect(getStandaloneMachineStatusIndicator(offline, NOW).variant).toBe('danger');
});
it('propagates parent host staleness and VM telemetry_stale to standalone VMs', () => {
const staleHost = makeMachine({
id: 'agent:lab-unraid',
name: 'lab-unraid',
lastSeen: NOW - 14 * 60_000,
agent: { stale: true, lastReportAt: new Date(NOW - 14 * 60_000).toISOString() },
});
const vmOnStaleHost = makeVm({
id: 'agent:lab-unraid:libvirt:kvm-billing',
name: 'kvm-billing',
parentId: 'agent:lab-unraid',
parentName: 'lab-unraid',
sourceStatus: { agent: { status: 'online' } },
});
const notice = getStandaloneVMStaleness(vmOnStaleHost, staleHost, NOW);
expect(notice?.badge).toBe('stale · 14m');
expect(mapStandaloneVMStatus(vmOnStaleHost, staleHost, NOW)).toBe('attention');
const machinesById = new Map([[staleHost.id, staleHost]]);
expect(
filterStandaloneVMs(
[vmOnStaleHost],
'stale',
'attention',
machinesById,
undefined,
undefined,
NOW,
).map((vm) => vm.id),
).toEqual([vmOnStaleHost.id]);
});
it('formats deduplicated stale source banners for machines and VMs', () => {
expect(
describeStaleStandaloneMachines([
{ name: 'edge-nas', age: '16m' },
{ name: 'lab-unraid', age: '14m' },
]),
).toContain('edge-nas (16m) and lab-unraid (14m)');
expect(
describeStaleStandaloneVMs([
{ name: 'lab-unraid', age: '14m' },
{ name: 'lab-unraid', age: '14m' },
]),
).toContain('lab-unraid (14m)');
});
});
describe('AgentsMachinesTable stale telemetry presentation', () => {
it('surfaces backend-stale hosts in Degraded with banner, inline cue, searchable error, drawer notice, and clears on recovery', async () => {
const [machines, setMachines] = createStore<Resource[]>([
makeMachine({
id: 'agent:edge-nas',
name: 'edge-nas',
health: { verdict: 'stale', reasons: [{ code: 'telemetry_stale', detail: '16m' }] },
sourceStatus: {
agent: {
status: 'stale',
lastSeen: new Date(NOW - 16 * 60_000).toISOString(),
error: 'agent heartbeat timed out',
},
},
agent: {
agentVersion: '6.10.0',
stale: false,
lastReportAt: new Date(NOW - 16 * 60_000).toISOString(),
},
}),
makeMachine({ id: 'agent:prod-worker', name: 'prod-worker' }),
]);
render(() => (
<AgentsMachinesTable
resources={machines}
emptyIcon={<span />}
emptyTitle="No machines"
emptyDescription="Empty"
/>
));
expect(screen.getByTestId('agent-machines-stale-banner')).toHaveTextContent(
/Telemetry is stale for edge-nas \(16m\)/,
);
expect(screen.getByRole('button', { name: 'Healthy, 1' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Degraded, 1' })).toBeInTheDocument();
expect(document.querySelectorAll('[data-agent-machine-stale-cue]')).toHaveLength(1);
// Search matches stale error text
const search = screen.getByPlaceholderText('Search machines');
await fireEvent.input(search, { target: { value: 'heartbeat timed out' } });
expect(document.querySelectorAll('[data-agents-machine-row]')).toHaveLength(1);
await fireEvent.input(search, { target: { value: '' } });
// Expanding stale machine shows inline drawer notice
await fireEvent.click(document.querySelector('[data-agents-machine-row="agent:edge-nas"]')!);
expect(screen.getByTestId('agent-machine-stale-notice')).toHaveTextContent(
/Last error: agent heartbeat timed out\./,
);
// Live recovery clears banner, row cue, and drawer notice
setMachines(0, {
health: { verdict: 'ok', reasons: [] },
sourceStatus: { agent: { status: 'online', lastSeen: new Date(NOW).toISOString() } },
lastSeen: NOW,
agent: { agentVersion: '6.10.0', stale: false, lastReportAt: new Date(NOW).toISOString() },
});
expect(screen.queryByTestId('agent-machines-stale-banner')).not.toBeInTheDocument();
expect(screen.queryByTestId('agent-machine-stale-notice')).not.toBeInTheDocument();
expect(document.querySelectorAll('[data-agent-machine-stale-cue]')).toHaveLength(0);
expect(screen.getByRole('button', { name: 'Healthy, 2' })).toBeInTheDocument();
});
});
describe('StandaloneVirtualMachinesTable stale telemetry presentation', () => {
it('flags VMs on stale hosts with banner, Attention bucket, stale dot title, drawer notice, and clears on recovery', async () => {
const [machines, setMachines] = createStore<Resource[]>([
makeMachine({
id: 'agent:lab-unraid',
name: 'lab-unraid',
lastSeen: NOW - 14 * 60_000,
agent: { stale: true, lastReportAt: new Date(NOW - 14 * 60_000).toISOString() },
}),
makeMachine({ id: 'agent:prod-worker', name: 'prod-worker' }),
]);
const vms = [
makeVm({
id: 'agent:lab-unraid:libvirt:kvm-billing',
name: 'kvm-billing',
parentId: 'agent:lab-unraid',
parentName: 'lab-unraid',
}),
makeVm({
id: 'agent:prod-worker:libvirt:kvm-fresh-db',
name: 'kvm-fresh-db',
parentId: 'agent:prod-worker',
parentName: 'prod-worker',
}),
];
render(() => (
<StandaloneVirtualMachinesTable
vms={vms}
machines={machines}
emptyIcon={<span />}
emptyTitle="No VMs"
emptyDescription="Empty"
/>
));
expect(screen.getByTestId('standalone-vms-stale-banner')).toHaveTextContent(
/Host agent telemetry is stale for lab-unraid \(14m\)/,
);
expect(screen.getByRole('button', { name: 'Running, 1' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Attention, 1' })).toBeInTheDocument();
expect(screen.getByRole('img', { name: 'Running · Stale' })).toBeInTheDocument();
// Expanding stale VM shows inline drawer notice
await fireEvent.click(
document.querySelector('[data-standalone-vm-row="agent:lab-unraid:libvirt:kvm-billing"]')!,
);
expect(screen.getByTestId('standalone-vm-stale-notice')).toHaveTextContent(
/Host agent has not reported recently \(14m ago\)/,
);
// Parent host recovery clears banner and moves VM back to Running
setMachines(0, {
lastSeen: NOW,
agent: { stale: false, lastReportAt: new Date(NOW).toISOString() },
});
expect(screen.queryByTestId('standalone-vms-stale-banner')).not.toBeInTheDocument();
expect(screen.queryByTestId('standalone-vm-stale-notice')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Running, 2' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Attention, 0' })).toBeInTheDocument();
});
});

View File

@@ -5,6 +5,7 @@ import { getPlatformTableFiniteMetric } from '@/features/platformPage/sharedPlat
import { isPhysicalDiskTemperatureCurrent } from '@/features/storageBackups/diskTemperaturePresentation';
import { formatBytes, normalizeDiskArray } from '@/utils/format';
import { asTrimmedString } from '@/utils/stringUtils';
import { getStandaloneMachineStaleness } from './standaloneStaleness';
export type AgentMachineColumnId =
| 'machine'
@@ -802,11 +803,21 @@ export const matchesAgentMachineSearch = (
search: string,
getSystemLabel: (machine: Resource) => string,
getAgentLabel: (machine: Resource) => string,
nowMs?: number,
): boolean => {
const needle = search.trim().toLowerCase();
if (!needle) return true;
const staleNotice = getStandaloneMachineStaleness(machine, nowMs ?? 0);
const values: string[] = [];
if (staleNotice) {
appendSearchValues(values, [
staleNotice.badge,
staleNotice.compactBadge,
staleNotice.detail,
staleNotice.error,
]);
}
appendSearchValues(values, [
machine.name,
machine.displayName,
@@ -911,119 +922,51 @@ const compareText = (
return direction === 'asc' ? result : -result;
};
const NUMERIC_SORT_GETTERS: Partial<
Record<AgentMachineSortKey, (machine: Resource) => number | undefined>
> = {
cpu: getAgentMachineCpuPercent,
gpu: getAgentMachineGPUUtilizationPercent,
memory: getAgentMachineMemoryPercent,
disk: getAgentMachineDiskPercent,
network: getAgentMachineNetworkTotal,
diskio: getAgentMachineDiskIOTotal,
uptime: (machine) => machine.uptime ?? machine.agent?.uptimeSeconds,
temp: getAgentMachineTemperatureCelsius,
lastSeen: (machine) => timestampMillisFrom(machine.lastSeen),
};
const machineNameKey = (machine: Resource): string =>
machine.displayName || machine.name || machine.id;
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 'gpu':
result = compareNullableNumber(
getAgentMachineGPUUtilizationPercent(left),
getAgentMachineGPUUtilizationPercent(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;
}
): Resource[] => {
const numericGetter = NUMERIC_SORT_GETTERS[sortKey];
const textGetter: ((machine: Resource) => string | undefined) | undefined = numericGetter
? undefined
: sortKey === 'system'
? getSystemLabel
: sortKey === 'agent'
? getAgentLabel
: sortKey === 'ip'
? getAgentMachinePrimaryIp
: sortKey === 'raid'
? getAgentMachineRaidSummary
: sortKey === 'arch'
? (machine) => machine.agent?.architecture
: sortKey === 'kernel'
? (machine) => machine.agent?.kernelVersion
: machineNameKey;
if (result !== 0) return result;
return compareText(
left.displayName || left.name || left.id,
right.displayName || right.name || right.id,
'asc',
);
return [...machines].sort((left, right) => {
const result = numericGetter
? compareNullableNumber(numericGetter(left), numericGetter(right), direction)
: compareText(textGetter!(left), textGetter!(right), direction);
return result !== 0 ? result : compareText(machineNameKey(left), machineNameKey(right), 'asc');
});
};

View File

@@ -0,0 +1,175 @@
import type { Resource } from '@/types/resource';
import { getResourceStaleness } from '@/features/platformPage/resourceStaleness';
import { getAgentFirstReportStatusIndicator } from '@/utils/agentResources';
import { formatRelativeTime } from '@/utils/format';
import { getResourceSourceStatus, hasImpairedResourceSource } from '@/utils/resourceSourceHealth';
import { getSimpleStatusIndicator, type StatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
import { getStandaloneResourceStatusIndicator } from './standalonePageModel';
const AGENT_REPORT_STALE_AFTER_MS = 5 * 60 * 1000;
const HEALTHY_AGENT_STATUSES = new Set(['online', 'running', 'healthy', 'connected', 'ok']);
export interface StandaloneStaleNotice {
badge: string;
compactBadge: string;
age: string | null;
detail: string;
cueTitle: string;
error?: string;
}
const relativeAge = (value: unknown, nowMs: number): string => {
const input =
typeof value === 'number'
? Number.isFinite(value) && value > 0
? value
: undefined
: asTrimmedString(value);
return input === undefined
? ''
: formatRelativeTime(input, { compact: true, emptyText: '', now: nowMs });
};
const isAgentSourceImpaired = (resource: Resource, ignorePendingAndOffline = true): boolean => {
if (hasImpairedResourceSource(resource, 'agent')) return true;
const status = (asTrimmedString(resource.sourceStatus?.agent?.status) ?? '').toLowerCase();
if (!status || HEALTHY_AGENT_STATUSES.has(status)) return false;
return !ignorePendingAndOffline || (status !== 'pending' && status !== 'offline');
};
export const hasExplicitBackendAgentStaleness = (machine: Resource | undefined | null): boolean =>
Boolean(
machine &&
machine.type === 'agent' &&
!getAgentFirstReportStatusIndicator(machine) &&
(machine.agent?.stale === true ||
getResourceStaleness(machine) ||
isAgentSourceImpaired(machine)),
);
export const getStandaloneMachineStaleness = (
machine: Resource | undefined | null,
nowMs = Date.now(),
options?: { includeClockStale?: boolean },
): StandaloneStaleNotice | null => {
if (!machine || machine.type !== 'agent' || getAgentFirstReportStatusIndicator(machine)) {
return null;
}
if (getSimpleStatusIndicator(machine.status).variant === 'danger') return null;
const healthStale = getResourceStaleness(machine);
const lastSeenStale =
options?.includeClockStale !== false &&
Number.isFinite(machine.lastSeen) &&
machine.lastSeen > 0 &&
nowMs - machine.lastSeen > AGENT_REPORT_STALE_AFTER_MS;
if (
!healthStale &&
!isAgentSourceImpaired(machine) &&
machine.agent?.stale !== true &&
!lastSeenStale
) {
return null;
}
const agentSource = getResourceSourceStatus(machine, 'agent') ?? machine.sourceStatus?.agent;
const rel =
relativeAge(machine.agent?.lastReportAt, nowMs) ||
relativeAge(agentSource?.lastSeen, nowMs) ||
relativeAge(machine.lastSeen, nowMs);
const age =
healthStale?.age ??
(rel && rel !== 'just now' && rel !== '—' ? rel.replace(/\s+ago$/i, '').trim() || null : null);
const error = asTrimmedString(agentSource?.error);
const lastReportText = rel ? ` Last report ${rel}.` : age ? ` Last report ${age} ago.` : '';
const errorText = error ? ` Last error: ${error}.` : '';
const cueBase = age
? `No report for ${age} — showing last known readings.`
: 'Showing last known readings — no fresh update received recently.';
return {
badge: age ? `Stale · ${age}` : 'Stale data',
compactBadge: 'Stale',
age,
detail: `Agent has stopped reporting.${lastReportText} Showing last known readings.${errorText}`,
cueTitle: `${cueBase}${errorText}`,
...(error ? { error } : {}),
};
};
export const getStandaloneMachineStatusIndicator = (
machine: Resource,
nowMs = Date.now(),
): StatusIndicator => {
const base = getStandaloneResourceStatusIndicator(machine, nowMs);
if (base.variant === 'danger' || getAgentFirstReportStatusIndicator(machine)) return base;
return getStandaloneMachineStaleness(machine, nowMs)
? { variant: 'warning', label: 'Stale' }
: base;
};
export const getStandaloneVMStaleness = (
vm: Resource,
parentHost?: Resource,
nowMs = Date.now(),
): StandaloneStaleNotice | null => {
const healthStale = getResourceStaleness(vm);
const parentStale = parentHost
? getStandaloneMachineStaleness(parentHost, nowMs, { includeClockStale: false })
: null;
if (!healthStale && !isAgentSourceImpaired(vm, false) && !parentStale) return null;
const agentSource = getResourceSourceStatus(vm, 'agent') ?? vm.sourceStatus?.agent;
const age = healthStale?.age ?? parentStale?.age ?? null;
const error = asTrimmedString(agentSource?.error) || parentStale?.error;
const detail =
!age && !error
? 'Host agent has not reported recently'
: `Host agent has not reported recently${age ? ` (${age} ago)` : ''}. Showing last known VM state and metrics.${error ? ` Last error: ${error}.` : ''}`;
return {
badge: age ? `stale · ${age}` : 'stale',
compactBadge: 'stale',
age,
detail,
cueTitle: detail,
...(error ? { error } : {}),
};
};
const formatStaleSourceList = (
entries: readonly { name: string; age: string | null }[],
): string => {
const seen = new Set<string>();
const labels: string[] = [];
for (const entry of entries) {
const key = entry.name.trim().toLowerCase();
if (!key || seen.has(key)) continue;
seen.add(key);
labels.push(entry.age ? `${entry.name} (${entry.age})` : entry.name);
}
if (labels.length <= 1) return labels[0] ?? '';
if (labels.length === 2) return `${labels[0]} and ${labels[1]}`;
if (labels.length === 3) return `${labels[0]}, ${labels[1]}, and ${labels[2]}`;
return `${labels[0]}, ${labels[1]}, ${labels[2]}, +${labels.length - 3} more`;
};
export const describeStaleStandaloneMachines = (
entries: readonly { name: string; age: string | null }[],
): string | null => {
const list = formatStaleSourceList(entries);
return list
? `Telemetry is stale for ${list}. CPU, memory, disk, and sensor readings shown are last known values until their agents report again.`
: null;
};
export const describeStaleStandaloneVMs = (
entries: readonly { name: string; age: string | null }[],
): string | null => {
const list = formatStaleSourceList(entries);
return list
? `Host agent telemetry is stale for ${list}. VM states and metrics shown for affected guests are last known values.`
: null;
};

View File

@@ -3,12 +3,12 @@ import {
formatPlatformTableTitleCaseValue,
type PlatformTableSortValue,
} from '@/features/platformPage/sharedPlatformPage';
import { hasImpairedResourceSource } from '@/utils/resourceSourceHealth';
import { asTrimmedString } from '@/utils/stringUtils';
import {
normalizeStandaloneVMStatusFilter,
type StandaloneVMStatusFilter,
} from './standalonePageModel';
import { getStandaloneVMStaleness } from './standaloneStaleness';
export { normalizeStandaloneVMStatusFilter, type StandaloneVMStatusFilter };
export type StandaloneVMStatusBucket = Exclude<StandaloneVMStatusFilter, 'all'>;
@@ -32,21 +32,23 @@ export const getStandaloneVMRuntimeState = (resource: Resource): string =>
''
).toLowerCase();
const HEALTHY_SOURCE_STATUSES = new Set(['online', 'running', 'healthy', 'connected', 'ok']);
export const isStandaloneVMSourceImpaired = (
resource: Resource,
parentHost?: Resource,
nowMs?: number,
): boolean => Boolean(getStandaloneVMStaleness(resource, parentHost, nowMs));
export const isStandaloneVMSourceImpaired = (resource: Resource): boolean => {
if (hasImpairedResourceSource(resource, 'agent')) return true;
const directStatus = (asTrimmedString(resource.sourceStatus?.agent?.status) ?? '').toLowerCase();
return directStatus !== '' && !HEALTHY_SOURCE_STATUSES.has(directStatus);
};
export const mapStandaloneVMStatus = (resource: Resource): StandaloneVMStatusBucket => {
export const mapStandaloneVMStatus = (
resource: Resource,
parentHost?: Resource,
nowMs?: number,
): StandaloneVMStatusBucket => {
const state = getStandaloneVMRuntimeState(resource);
if (state === 'shutoff' || state === 'stopped' || state === 'halted' || state === 'offline') {
return 'stopped';
}
if (
isStandaloneVMSourceImpaired(resource) ||
isStandaloneVMSourceImpaired(resource, parentHost, nowMs) ||
state === 'paused' ||
state === 'suspended' ||
state === 'shutting-down' ||
@@ -64,8 +66,12 @@ export const mapStandaloneVMStatus = (resource: Resource): StandaloneVMStatusBuc
return 'attention';
};
export const getStandaloneVMDisplayStatus = (resource: Resource): string => {
const bucket = mapStandaloneVMStatus(resource);
export const getStandaloneVMDisplayStatus = (
resource: Resource,
parentHost?: Resource,
nowMs?: number,
): string => {
const bucket = mapStandaloneVMStatus(resource, parentHost, nowMs);
if (bucket === 'running') return 'online';
if (bucket === 'stopped') return 'stopped';
const state = getStandaloneVMRuntimeState(resource);
@@ -185,16 +191,19 @@ export const filterStandaloneVMs = (
machinesById: ReadonlyMap<string, Resource>,
machinesByName?: ReadonlyMap<string, Resource>,
selectedHostId?: string,
nowMs?: number,
): Resource[] => {
const needle = search.trim().toLowerCase();
return vms.filter((vm) => {
if (!matchesStandaloneVMHostScope(vm, selectedHostId, machinesById, machinesByName)) {
return false;
}
if (status !== 'all' && mapStandaloneVMStatus(vm) !== status) {
const parentHost = resolveStandaloneVMHostResource(vm, machinesById, machinesByName);
if (status !== 'all' && mapStandaloneVMStatus(vm, parentHost, nowMs) !== status) {
return false;
}
if (!needle) return true;
const staleNotice = getStandaloneVMStaleness(vm, parentHost, nowMs ?? 0);
const haystack = [
getStandaloneVMName(vm),
vm.name,
@@ -202,6 +211,10 @@ export const filterStandaloneVMs = (
getStandaloneVMStateLabel(vm),
getStandaloneVMRuntimeState(vm),
getStandaloneVMHypervisorLabel(vm),
staleNotice?.badge,
staleNotice?.compactBadge,
staleNotice?.detail,
staleNotice?.error,
vm.id,
]
.filter(Boolean)