diff --git a/frontend-modern/browser-verification/2c8ce3dfb63f9248.json b/frontend-modern/browser-verification/2c8ce3dfb63f9248.json new file mode 100644 index 0000000000..107ddce6e1 --- /dev/null +++ b/frontend-modern/browser-verification/2c8ce3dfb63f9248.json @@ -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 · 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 · 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" + ] +} diff --git a/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx b/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx index 874a056ce6..6c4c02f121 100644 --- a/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx +++ b/frontend-modern/src/features/standalone/AgentsMachinesTable.tsx @@ -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) => ( +
{props.title}
+); + +const TooltipOverflowNote: Component<{ count: number; noun: string }> = (props) => ( + 0}> +
+ +{props.count} more {props.noun} +
+
+); + +const TooltipMoreBadge: Component<{ count: number }> = (props) => ( + 0}> + + +{props.count} + + +); + const AgentMachineMetricTooltip: Component<{ triggerDataAttribute: string; tooltipDataAttribute: string; @@ -274,9 +301,7 @@ const AgentMachineTemperatureCell: Component<{ {(section) => (
-
- {section.heading} -
+
{(row) => ( @@ -354,11 +379,7 @@ const AgentMachineNetworkInterfacesList: Component<{ )} - maxAddressesPerInterface()}> - - +{iface.addresses.length - maxAddressesPerInterface()} - - +
)} - 0}> -
- +{hiddenInterfaceCount()} more interfaces -
-
+ ); }; @@ -425,9 +442,7 @@ const AgentMachineNetworkCell: Component<{ } >
-
- Network Interfaces -
+
@@ -477,7 +492,7 @@ const AgentMachineIpCell: Component<{ } >
-
IP Addresses
+ 0} fallback={
{getWorkloadsGuestNetworkEmptyState()}
} @@ -493,19 +508,13 @@ const AgentMachineIpCell: Component<{ )} - 0}> - - +{hiddenIpCount()} - - +
0}>
-
- Network Interfaces -
+
-
Disk I/O
+
Read @@ -599,11 +608,7 @@ const AgentMachineDiskIOCell: Component<{
)} - 0}> -
- +{hiddenDetailCount()} more devices -
-
+
@@ -662,9 +667,9 @@ const AgentMachineRaidCell: Component<{ } >
-
- {lastKnownTitle() ? 'RAID Arrays (last known)' : 'RAID Arrays'} -
+
{(array, index) => { @@ -783,22 +788,14 @@ const AgentMachineRaidCell: Component<{ )} - 12}> - - +{devices().length - 12} - - +
); }} - 0}> -
- +{hiddenArrayCount()} more arrays -
-
+
@@ -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 = { + 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<{ } >
+ + {(message) => ( + + {message()} + + )} + 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<{ )} + + {(notice) => ( + + + + )} +
@@ -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 } /> @@ -2080,6 +2100,20 @@ export const AgentsMachinesTable: Component<{ detailRowId={detailRowId()} colSpan={detailColspan()} initialShowHostDetails={false} + context={ + + {(notice) => ( + + {notice().detail} + + )} + + } onClose={() => { drawer.close(machine); }} diff --git a/frontend-modern/src/features/standalone/HostIdentityConflictNotice.tsx b/frontend-modern/src/features/standalone/HostIdentityConflictNotice.tsx index 0f1863e5c4..b04af880e4 100644 --- a/frontend-modern/src/features/standalone/HostIdentityConflictNotice.tsx +++ b/frontend-modern/src/features/standalone/HostIdentityConflictNotice.tsx @@ -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'; diff --git a/frontend-modern/src/features/standalone/StandalonePageSurface.tsx b/frontend-modern/src/features/standalone/StandalonePageSurface.tsx index fe734e16b0..e32ad7c80b 100644 --- a/frontend-modern/src/features/standalone/StandalonePageSurface.tsx +++ b/frontend-modern/src/features/standalone/StandalonePageSurface.tsx @@ -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 = () => ; const vmIcon = () => ; -const availabilityIcon = () => ; 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(() => - 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 = () => ( +
+ + + + View checks + +
+ ); + return (
1}> @@ -340,69 +319,22 @@ export function StandalonePageSurface() { /> } > - -
- 0}> - - - Manage checks - - } - /> - - -
-
- - - } - > - } - 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." - /> - + } + 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." + /> @@ -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={ -
- - - - View checks - -
- } + 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={ -
- - - - View checks - -
- } + actions={renderEmptyMachineActions()} />
} diff --git a/frontend-modern/src/features/standalone/StandaloneVirtualMachinesTable.tsx b/frontend-modern/src/features/standalone/StandaloneVirtualMachinesTable.tsx index 82c3b4a70f..21c9bf7caa 100644 --- a/frontend-modern/src/features/standalone/StandaloneVirtualMachinesTable.tsx +++ b/frontend-modern/src/features/standalone/StandaloneVirtualMachinesTable.tsx @@ -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 { - 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(); 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<{ } >
+ + {(message) => ( + + {message()} + + )} + {(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<{
- {[stateLabel(), note()?.short].filter(Boolean).join(' · ')} + {[stateLabel(), note()?.compactShort ?? note()?.short] + .filter(Boolean) + .join(' · ')}
@@ -563,6 +626,20 @@ export const StandaloneVirtualMachinesTable: Component<{ detailRowId={detailRowId()} colSpan={7} resolveResourceLabel={resolveResourceLabel} + context={ + + {(notice) => ( + + {notice().detail} + + )} + + } onClose={() => drawer.close(vm)} /> diff --git a/frontend-modern/src/features/standalone/__tests__/standaloneStaleness.test.tsx b/frontend-modern/src/features/standalone/__tests__/standaloneStaleness.test.tsx new file mode 100644 index 0000000000..4823705d6c --- /dev/null +++ b/frontend-modern/src/features/standalone/__tests__/standaloneStaleness.test.tsx @@ -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 }) => ( +
+ ), +})); + +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 }), +})); + +const NOW = Date.parse('2026-11-28T05:00:00Z'); + +const makeMachine = (overrides: Partial = {}): 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 => + ({ + 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([ + 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(() => ( + } + 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([ + 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(() => ( + } + 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(); + }); +}); diff --git a/frontend-modern/src/features/standalone/agentMachineTableModel.ts b/frontend-modern/src/features/standalone/agentMachineTableModel.ts index 661e02c86c..b298209082 100644 --- a/frontend-modern/src/features/standalone/agentMachineTableModel.ts +++ b/frontend-modern/src/features/standalone/agentMachineTableModel.ts @@ -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 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'); }); +}; diff --git a/frontend-modern/src/features/standalone/standaloneStaleness.ts b/frontend-modern/src/features/standalone/standaloneStaleness.ts new file mode 100644 index 0000000000..0a7943e0ea --- /dev/null +++ b/frontend-modern/src/features/standalone/standaloneStaleness.ts @@ -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(); + 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; +}; diff --git a/frontend-modern/src/features/standalone/standaloneVmTableModel.ts b/frontend-modern/src/features/standalone/standaloneVmTableModel.ts index 5dd222500c..6b5c912752 100644 --- a/frontend-modern/src/features/standalone/standaloneVmTableModel.ts +++ b/frontend-modern/src/features/standalone/standaloneVmTableModel.ts @@ -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; @@ -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, machinesByName?: ReadonlyMap, 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)