Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Keep drawer CPU and memory when history fails

rcourtman06fa51d47072
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 16cda823f9..b2774d360f 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -20,6 +20,20 @@
## Purpose
+### Drawer History keeps live readings when no chart can be drawn (2 November 2026)
+
+When the first history read fails, or the selected range is beyond the plan,
+`GuestDrawerHistory` shows a "Latest readings" strip in place of the charts. It
+reads the same `currentMetrics` and `deferredMetrics` as the chart readouts,
+through one `getLiveReading` helper, so retained or freshness-unknown memory
+keeps the qualifier and explanation from `getMemoryObservationPresentation`.
+The strip draws no plot, timestamp or inspection. A final 401/403 still
+withdraws the whole panel, readings included, and a successful read restores
+the charts. PBS servers depend on this: their host CPU and memory are read in
+the drawer, not the Backups table. `GuestDrawerHistory.refresh.test.tsx` and
+`ResourceDetailDrawer.history.test.tsx` (a PBS drawer with a rejected history
+read) cover it.
+
### Compact toggles mark selection by colour, and icon labels stay on one line (2 November 2026)
The compact `FilterButtonGroup` variant (View preferences, type and status
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 3ea1994e45..41ccee1175 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -15,6 +15,14 @@
## Purpose
+### Drawer live-readings strip adds no history work (2 November 2026)
+
+`GuestDrawerHistory` renders its "Latest readings" strip only in place of
+charts it cannot draw (a failed first read or a plan-locked range). It reads
+the `currentMetrics` and `deferredMetrics` the drawer already derives, issues
+no request, adds no poll or timer, and holds one item per configured series.
+The history query, its 30-second poll and its retry are unchanged.
+
### Missing backup completion remains a presentation-only uncertainty
Workloads keeps its existing scalar and legacy absence classification, but
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index c885d912ad..b21a175783 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -23,6 +23,19 @@ and sort the complete canonical change table while startup and ingestion wait.
## Purpose
+### Resource memory and disk percentages validate their byte pair (2 November 2026)
+
+`getMemoryPercent` and `getDiskPercent` in `frontend-modern/src/types/resource.ts`
+use the used/total byte pair only when it is valid: finite non-negative used,
+positive total, used no more than total. A valid pair wins, including a
+measured zero; `used: 0` used to read as absent, so a stale 99% selection
+showed instead. Otherwise a finite 0-100 `current` stands in, and anything else
+returns `undefined` rather than NaN or a made-up 0, so the drawer shows no
+reading. Drawer callers already pass the value through `finiteMetric`; the
+unused `topByMemory` sort ranks no reading as 0. `resource.test.ts` and
+`ResourceDetailDrawer.history.test.tsx` cover measured zero, invalid pairs and
+percentage-only readings.
+
### Compact Proxmox node Disk cells show the fullest disk (2 November 2026)
A compact Proxmox node row (phone width or compact metrics) has no room for
diff --git a/frontend-modern/browser-verification/f8232aabc7fe3035.json b/frontend-modern/browser-verification/f8232aabc7fe3035.json
new file mode 100644
index 0000000000..5ac2a4cde3
--- /dev/null
+++ b/frontend-modern/browser-verification/f8232aabc7fe3035.json
@@ -0,0 +1,40 @@
+{
+ "version": 1,
+ "base_sha": "8918a53c3d2de7626e31bb2a847b20417c2e81b7",
+ "verified_at": "2026-11-02T12:05:00Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx",
+ "frontend-modern/src/hooks/useResources.ts",
+ "frontend-modern/src/types/resource.ts"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx": "b8ccd7bfb726e78ca6dc53788ee4a151105b85a7123452764c92442626024c00",
+ "frontend-modern/src/hooks/useResources.ts": "ef86bdae0804808adca09b0a539c1645b10ec35638812865f895379e6f65b670",
+ "frontend-modern/src/types/resource.ts": "bbff35284b99d04fd48b14f982ba2279853d3b1e2098b98732766195dd73a0bb"
+ },
+ "routes": [
+ "/proxmox/backups"
+ ],
+ "viewports": [
+ {
+ "width": 1280,
+ "height": 900
+ },
+ {
+ "width": 390,
+ "height": 844
+ }
+ ],
+ "states": [
+ "Production vite build of this exact source served by vite preview on pulse-dev, proxied to the :7699 mock-estate perf rig; headless Chromium from the rig's measurement tools. Every /api/metrics-store/history request answered HTTP 500.",
+ "PBS server drawer (backup-vault) Overview after the failed first history read: danger notice 'Failed to load history data', Retry history, no chart plots, and a 'Latest readings' strip with CPU 10.2% current and Memory 33.3% current, consistent with the drawer fact line 5.33 GB of 16.0 GB RAM.",
+ "Same state at 390x844: strip readable below the notice and range picker, no horizontal page overflow; the earlier capture that left the strip under the fixed bottom navigation was re-shot with the strip scrolled to centre.",
+ "Retry history issued a second request, which also failed; the strip stayed. Recovery to charts, locked-range, retained/freshness-unknown memory and 401/403 withdrawal are covered by the component and drawer tests, not by this browser pass."
+ ],
+ "interactions": [
+ "Signed in with the rig's documented dev login, opened /proxmox/backups, expanded the first Backup servers row (disclosure button at 1280, row tap at 390) to open the PBS server drawer.",
+ "Waited for the failure notice, counted plots and live-reading items with their qualifiers, checked document scroll width against the viewport, captured the history region and the viewport at both widths and inspected the images.",
+ "Clicked Retry history once per width and confirmed the second history request and the strip's persistence."
+ ]
+}
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
index 4980b8dfe4..e6fd47e641 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
@@ -368,6 +368,71 @@ describe('ResourceDetailDrawer change history section', () => {
}
});
+ it('keeps a PBS server CPU and qualified memory visible when its first history read fails', async () => {
+ resetCreateNonSuspendingQueryCacheForTest();
+ // The Backups page sends people here for PBS host figures, so a failed
+ // history read must not take the server's own readings with it.
+ const source = baseResource({
+ id: 'pbs-history-down',
+ type: 'pbs',
+ name: 'pbs-main',
+ displayName: 'PBS Main',
+ platformId: 'pbs-main',
+ platformType: 'proxmox-pbs',
+ platformData: { sources: ['pbs'], pbs: { hostname: 'pbs-main.local' } },
+ metricsTarget: { resourceType: 'agent', resourceId: 'pbs-main' },
+ cpu: { current: 7 },
+ memory: { current: 99, total: 8_000, used: 2_000 },
+ });
+ const read = vi
+ .spyOn(ChartsAPI, 'getMetricsHistory')
+ .mockRejectedValue(new Error('history store unavailable'));
+ const [resource, setResource] = createSignal(source);
+ const view = render(() => <ResourceDetailDrawer resource={resource()} />);
+ try {
+ const history = view.container.querySelector('[data-testid="resource-metrics-history"]')!;
+ await waitFor(() => expect(history).toHaveTextContent('Failed to load history data'));
+ expect(history.querySelector('[data-testid="guest-history-plot"]')).toBeNull();
+ const readings = history.querySelector('[data-testid="guest-history-live-readings"]')!;
+ expect(readings.querySelector('[data-live-reading="cpu"]')).toHaveTextContent(
+ 'CPU7.0%current',
+ );
+ // The byte pair is the measurement; the stale 99% selection is ignored.
+ expect(readings.querySelector('[data-live-reading="memory"]')).toHaveTextContent(
+ 'Memory25.0%current',
+ );
+
+ setResource({ ...source, memory: { current: 99, total: 8_000, used: 0 } });
+ expect(readings.querySelector('[data-live-reading="memory"]')).toHaveTextContent(
+ 'Memory0.0%current',
+ );
+
+ setResource({
+ ...source,
+ memory: {
+ current: 40,
+ observation: {
+ state: 'last-known',
+ source: 'status-mem',
+ observedAt: '2026-10-04T12:00:00Z',
+ },
+ },
+ });
+ expect(readings.querySelector('[data-live-reading="memory"]')).toHaveTextContent(
+ 'Memory40.0%last known',
+ );
+ expect(readings.querySelector('[data-history-deferred="memory"]')).toHaveTextContent(
+ '2026-10-04 12:00:00 UTC',
+ );
+ expect(readings.querySelector('[data-live-reading="cpu"]')).toHaveTextContent('7.0%current');
+ expect(read).toHaveBeenCalled();
+ } finally {
+ view.unmount();
+ read.mockRestore();
+ resetCreateNonSuspendingQueryCacheForTest();
+ }
+ });
+
it.each(['vm', 'system-container'] as const)(
'keeps the mounted %s Overview charts on the selected filesystem producer',
async (type) => {
diff --git a/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx b/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx
index 633eb01b6d..2d59cf66ed 100644
--- a/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx
+++ b/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx
@@ -257,6 +257,114 @@ const HistoryPointMarker: Component<HistoryPointMarkerProps> = (props) => {
);
};
+type LiveReadingQualifier = 'current' | 'last known' | 'freshness unknown';
+
+interface LiveReading {
+ value: number | undefined;
+ deferred: GuestDrawerHistoryDeferredMetric | undefined;
+ qualifier: LiveReadingQualifier | null;
+}
+
+// The resource's own reading for one series: current, or a deferred
+// last-known or freshness-unknown value with its explanation. The chart
+// readouts and the strip shown when no chart can be drawn both use it, so a
+// retained reading is qualified the same way in either place.
+const getLiveReading = (
+ metric: string,
+ currentMetrics: Record<string, number | null | undefined> | undefined,
+ deferredMetrics: Record<string, GuestDrawerHistoryDeferredMetric | undefined> | undefined,
+): LiveReading => {
+ const deferred = deferredMetrics?.[metric];
+ const raw = deferred ? deferred.lastKnownValue : currentMetrics?.[metric];
+ const value = typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined;
+ return {
+ value,
+ deferred,
+ qualifier:
+ value === undefined
+ ? null
+ : !deferred
+ ? 'current'
+ : deferred.valueLabel === 'freshness unknown'
+ ? 'freshness unknown'
+ : 'last known',
+ };
+};
+
+interface GuestDrawerLiveReadingsProps {
+ currentMetrics?: Record<string, number | null | undefined>;
+ deferredMetrics?: Record<string, GuestDrawerHistoryDeferredMetric | undefined>;
+ groups: GuestDrawerHistoryGroupConfig[];
+}
+
+// Shown in place of the charts when none can be drawn (the first read failed
+// or the range is beyond the plan), so CPU and memory stay visible: they
+// belong to the resource, not to its stored history.
+const GuestDrawerLiveReadings: Component<GuestDrawerLiveReadingsProps> = (props) => {
+ const descriptionId = `live-readings-${createUniqueId()}`;
+ const items = createMemo(() => {
+ const seen = new Set<string>();
+ return props.groups.flatMap((group) =>
+ group.series.flatMap((series) => {
+ if (seen.has(series.metric)) return [];
+ seen.add(series.metric);
+ const reading = getLiveReading(series.metric, props.currentMetrics, props.deferredMetrics);
+ return reading.value !== undefined || reading.deferred ? [{ ...series, ...reading }] : [];
+ }),
+ );
+ });
+ return (
+ <Show when={items().length > 0}>
+ <section
+ class="rounded-xs border border-border bg-surface p-2.5"
+ data-testid="guest-history-live-readings"
+ >
+ <h4 class="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">
+ Latest readings
+ </h4>
+ <div class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted">
+ <For each={items()}>
+ {(item, index) => (
+ <span
+ class="inline-flex items-center gap-1"
+ data-live-reading={item.metric}
+ data-live-reading-qualifier={item.qualifier ?? undefined}
+ aria-describedby={item.deferred ? `${descriptionId}-${index()}` : undefined}
+ >
+ <svg aria-hidden="true" class="h-2.5 w-2.5 shrink-0" viewBox="0 0 10 10">
+ <circle cx="5" cy="5" r="4" fill={item.color} />
+ </svg>
+ <span class="font-medium text-base-content">{item.label}</span>
+ <span class="tabular-nums text-base-content">
+ {item.value !== undefined
+ ? formatHistoryChartTooltipValue(item.value, item.unit)
+ : '-'}
+ </span>
+ <Show when={item.qualifier}>{(qualifier) => <span>{qualifier()}</span>}</Show>
+ </span>
+ )}
+ </For>
+ </div>
+ <For each={items()}>
+ {(item, index) => (
+ <Show when={item.deferred}>
+ {(deferred) => (
+ <p
+ id={`${descriptionId}-${index()}`}
+ class="mt-2 text-xs leading-relaxed text-muted"
+ data-history-deferred={item.metric}
+ >
+ {item.label} reading: {deferred().message}
+ </p>
+ )}
+ </Show>
+ )}
+ </For>
+ </section>
+ </Show>
+ );
+};
+
const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps> = (props) => {
const [hoverTimestamp, setHoverTimestamp] = createSignal<number | null>(null);
const [selectedTimestamp, setSelectedTimestamp] = createSignal<number | null>(null);
@@ -516,12 +624,8 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
series().map((item, index) => {
const timestamp = readoutTimestamp();
const point = item.points.find((point) => point.timestamp === timestamp);
- const deferred = props.deferredMetrics?.[item.metric];
- const fallbackValue = deferred
- ? deferred.lastKnownValue
- : props.currentMetrics?.[item.metric];
- const isFallback =
- timestamp === null && typeof fallbackValue === 'number' && Number.isFinite(fallbackValue);
+ const reading = getLiveReading(item.metric, props.currentMetrics, props.deferredMetrics);
+ const isFallback = timestamp === null && reading.value !== undefined;
const alert = props.alerts?.[item.metric];
return {
...item,
@@ -531,11 +635,11 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
? `alert at ${formatHistoryChartTooltipValue(alert.value, item.unit)}`
: null,
reserve: valueReserves().get(item.metric) ?? ['', ''],
- deferred,
+ deferred: reading.deferred,
descriptionId: `${inspectionId}-deferred-${index}`,
- isCurrent: isFallback && !deferred,
- isLastKnown: isFallback && Boolean(deferred) && !deferred?.valueLabel,
- isUnknown: isFallback && deferred?.valueLabel === 'freshness unknown',
+ isCurrent: isFallback && reading.qualifier === 'current',
+ isLastKnown: isFallback && reading.qualifier === 'last known',
+ isUnknown: isFallback && reading.qualifier === 'freshness unknown',
valueLabel: point
? getGuestDrawerHistoryValueLabel([point], item.unit)
: // A stored time where this series has no reading says so in place,
@@ -543,8 +647,8 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
// the chart) as the inspected time changes.
timestamp !== null
? 'no reading'
- : typeof fallbackValue === 'number' && Number.isFinite(fallbackValue)
- ? formatHistoryChartTooltipValue(fallbackValue, item.unit)
+ : reading.value !== undefined
+ ? formatHistoryChartTooltipValue(reading.value, item.unit)
: '-',
};
}),
@@ -1029,6 +1133,20 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
),
);
+ const liveCurrentMetrics = () =>
+ props.liveReadingsAvailable !== false ? props.currentMetrics : undefined;
+ // A final 401/403 withdraws the whole History panel, readings included; an
+ // outage or a locked range leaves the resource's own readings standing.
+ const liveReadings = () => (
+ <Show when={!getAPIReadAccessErrorMessage(historyQuery.error())}>
+ <GuestDrawerLiveReadings
+ groups={groups()}
+ currentMetrics={liveCurrentMetrics()}
+ deferredMetrics={props.deferredMetrics}
+ />
+ </Show>
+ );
+
return (
<Show
when={props.target}
@@ -1098,13 +1216,16 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
<Show
when={!locked()}
fallback={
- <div class="rounded-xs border border-border bg-surface p-5 text-sm text-muted">
- {formatHistoryRangeOptionLabel(props.range)} history requires a higher license plan.
- This instance's plan retains {maxHistoryDays()} days.
- </div>
+ <>
+ <div class="rounded-xs border border-border bg-surface p-5 text-sm text-muted">
+ {formatHistoryRangeOptionLabel(props.range)} history requires a higher license plan.
+ This instance's plan retains {maxHistoryDays()} days.
+ </div>
+ {liveReadings()}
+ </>
}
>
- <Show when={!historyQuery.error() || hasHistoryPoints()}>
+ <Show when={!historyQuery.error() || hasHistoryPoints()} fallback={liveReadings()}>
{/* A reply that is not stored history says so once, above its charts. */}
<Show when={hasHistoryPoints() && getHistorySourceNotice(historyQuery.value().source)}>
{(notice) => (
@@ -1125,9 +1246,7 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
group={group}
loading={historyQuery.loading() && !historyQuery.resolvedOnce()}
metrics={metrics()}
- currentMetrics={
- props.liveReadingsAvailable !== false ? props.currentMetrics : undefined
- }
+ currentMetrics={liveCurrentMetrics()}
deferredMetrics={props.deferredMetrics}
range={props.range}
source={historyQuery.value().source}
diff --git a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsx b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsx
index bab700415c..106c446826 100644
--- a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsx
@@ -306,6 +306,58 @@ describe('GuestDrawerHistory refresh recovery', () => {
},
);
+ it('keeps qualified live readings without charts when the first read fails or the range is locked', async () => {
+ const pending = deferred<AllMetricsHistoryResponse>();
+ const fetch = vi
+ .spyOn(ChartsAPI, 'getMetricsHistory')
+ .mockRejectedValueOnce(new Error('store offline'))
+ .mockReturnValueOnce(pending.promise);
+ const [range, setRange] = createSignal<HistoryTimeRange>('24h');
+ const { container } = render(() => (
+ <GuestDrawerHistory
+ target={target}
+ range={range()}
+ currentMetrics={{ cpu: 12, memory: 0 }}
+ deferredMetrics={{
+ disk: { lastKnownValue: 61, message: 'Filesystem read paused.' },
+ netin: { lastKnownValue: 2048, valueLabel: 'freshness unknown', message: 'No time.' },
+ }}
+ />
+ ));
+ await screen.findByText('Failed to load history data');
+ expect(paths(container)).toHaveLength(0);
+ const readings = screen.getByTestId('guest-history-live-readings');
+ expect(readings).toHaveTextContent('Latest readings');
+ expect(readings.querySelector('[data-live-reading="cpu"]')).toHaveTextContent(
+ 'CPU12.0%current',
+ );
+ // A measured zero is a reading, not an absence.
+ expect(readings.querySelector('[data-live-reading="memory"]')).toHaveTextContent(
+ 'Memory0.0%current',
+ );
+ expect(readings.querySelector('[data-live-reading="disk"]')).toHaveTextContent(
+ 'Disk61.0%last known',
+ );
+ expect(readings.querySelector('[data-live-reading="netin"]')).toHaveAttribute(
+ 'data-live-reading-qualifier',
+ 'freshness unknown',
+ );
+ expect(readings.querySelector('[data-history-deferred="disk"]')).toHaveTextContent(
+ 'Disk reading: Filesystem read paused.',
+ );
+ expect(readings.querySelector('[data-live-reading="diskread"]')).toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry history' }));
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
+ pending.resolve(response());
+ await waitFor(() => expect(paths(container)).toHaveLength(1));
+ expect(screen.queryByTestId('guest-history-live-readings')).not.toBeInTheDocument();
+
+ setRange('14d');
+ await screen.findByText(/14 days history requires a higher license plan/);
+ expect(screen.getByTestId('guest-history-live-readings')).toHaveTextContent('CPU12.0%current');
+ });
+
it('offers no refresh when the target is absent or the range is locked', async () => {
const fetch = vi.spyOn(ChartsAPI, 'getMetricsHistory');
const [currentTarget, setTarget] = createSignal<GuestDrawerHistoryTarget | null>(null);
diff --git a/frontend-modern/src/components/Workloads/__tests__/HistoryResponse.contract.test.tsx b/frontend-modern/src/components/Workloads/__tests__/HistoryResponse.contract.test.tsx
index 05a6e1c673..cc220c1edb 100644
--- a/frontend-modern/src/components/Workloads/__tests__/HistoryResponse.contract.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/HistoryResponse.contract.test.tsx
@@ -70,13 +70,19 @@ describe('production History consumers reject unbound response evidence', () =>
);
expect(plots(view.container)).toHaveLength(0);
expect(view.container).not.toHaveTextContent('97.0%');
- expect(view.container).not.toHaveTextContent('99.0%');
+ // The resource's own reading stays, labelled current, and never stands
+ // in for a history series.
+ expect(screen.getByTestId('guest-history-live-readings')).toHaveTextContent(
+ 'CPU99.0%current',
+ );
+ expect(view.container.querySelector('[data-history-current]')).toBeNull();
expect(view.container).not.toHaveTextContent('No stored history');
expect(view.container).not.toHaveTextContent('private');
transport.mockResolvedValueOnce(body(0));
fireEvent.click(screen.getByRole('button', { name: 'Retry history' }));
await settle();
expect(plots(view.container)).toHaveLength(1);
+ expect(screen.queryByTestId('guest-history-live-readings')).not.toBeInTheDocument();
expect(view.container).toHaveTextContent('0.0%');
transport.mockResolvedValueOnce({ ...body(), metrics: {} });
await vi.advanceTimersByTimeAsync(GUEST_DRAWER_HISTORY_POLL_MS);
diff --git a/frontend-modern/src/hooks/useResources.ts b/frontend-modern/src/hooks/useResources.ts
index 385c74ac70..edd6a4fc1c 100644
--- a/frontend-modern/src/hooks/useResources.ts
+++ b/frontend-modern/src/hooks/useResources.ts
@@ -242,7 +242,7 @@ export function useResources(storeOverride?: ResourceStoreLike): UseResourcesRet
const topByMemory = (limit: number = 10): Resource[] => {
return [...resources()]
.filter((r) => r.memory)
- .sort((a, b) => getMemoryPercent(b) - getMemoryPercent(a))
+ .sort((a, b) => (getMemoryPercent(b) ?? 0) - (getMemoryPercent(a) ?? 0))
.slice(0, limit);
};
diff --git a/frontend-modern/src/types/__tests__/resource.test.ts b/frontend-modern/src/types/__tests__/resource.test.ts
index d18a60b121..17ad7cd798 100644
--- a/frontend-modern/src/types/__tests__/resource.test.ts
+++ b/frontend-modern/src/types/__tests__/resource.test.ts
@@ -743,18 +743,43 @@ describe('Resource Helper Functions', () => {
expect(getMemoryPercent(resource)).toBe(45.5);
});
- it('returns 0 when memory is undefined', () => {
+ it('returns undefined when memory is undefined', () => {
const resource = createResource({});
- expect(getMemoryPercent(resource)).toBe(0);
+ expect(getMemoryPercent(resource)).toBeUndefined();
});
it('handles zero total gracefully', () => {
const resource = createResource({
memory: { current: 50, total: 0, used: 0 },
});
- // When total is 0 (falsy), it should fall back to current
+ // A zero total is not a valid pair, so the percentage stands in.
expect(getMemoryPercent(resource)).toBe(50);
});
+
+ it('reads a measured zero from a valid pair instead of the percentage', () => {
+ const resource = createResource({
+ memory: { current: 99, total: 1000, used: 0 },
+ });
+ expect(getMemoryPercent(resource)).toBe(0);
+ });
+
+ it.each([
+ ['used above total', { used: 2000, total: 1000 }],
+ ['negative used', { used: -1, total: 1000 }],
+ ['negative total', { used: 10, total: -1000 }],
+ ['non-finite used', { used: Number.NaN, total: 1000 }],
+ ['non-finite total', { used: 10, total: Number.POSITIVE_INFINITY }],
+ ])('keeps a valid percentage when the pair is invalid (%s)', (_label, pair) => {
+ const resource = createResource({ memory: { current: 42, ...pair } });
+ expect(getMemoryPercent(resource)).toBe(42);
+ });
+
+ it('returns undefined when neither the pair nor the percentage is valid', () => {
+ for (const current of [Number.NaN, -5, 101, Number.POSITIVE_INFINITY]) {
+ const resource = createResource({ memory: { current, total: 1000, used: 2000 } });
+ expect(getMemoryPercent(resource)).toBeUndefined();
+ }
+ });
});
describe('getDiskPercent', () => {
@@ -772,9 +797,21 @@ describe('Resource Helper Functions', () => {
expect(getDiskPercent(resource)).toBe(80.2);
});
- it('returns 0 when disk is undefined', () => {
+ it('returns undefined when disk is undefined', () => {
const resource = createResource({});
- expect(getDiskPercent(resource)).toBe(0);
+ expect(getDiskPercent(resource)).toBeUndefined();
+ });
+
+ it('reads a measured zero and ignores an invalid pair, as memory does', () => {
+ expect(getDiskPercent(createResource({ disk: { current: 70, total: 500, used: 0 } }))).toBe(
+ 0,
+ );
+ expect(getDiskPercent(createResource({ disk: { current: 70, total: 500, used: 900 } }))).toBe(
+ 70,
+ );
+ expect(
+ getDiskPercent(createResource({ disk: { current: 170, total: 500, used: 900 } })),
+ ).toBeUndefined();
});
});
});
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index 2852cd742a..42d2e87569 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -1744,24 +1744,31 @@ export function getCpuPercent(r: Resource): number {
return r.cpu?.current ?? 0;
}
+const isFiniteNumber = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isFinite(value);
+
+// A valid byte pair is the measurement, including a measured zero: `used: 0`
+// is not absence. Only when the pair is missing or invalid does the selected
+// percentage stand in, and only within 0-100. Anything else is no reading.
+const getResourceMetricPercent = (metric: ResourceMetric | undefined): number | undefined => {
+ if (!metric) return undefined;
+ const { used, total, current } = metric;
+ if (isFiniteNumber(used) && isFiniteNumber(total) && used >= 0 && total > 0 && used <= total) {
+ return (used / total) * 100;
+ }
+ return isFiniteNumber(current) && current >= 0 && current <= 100 ? current : undefined;
+};
+
/**
- * Helper to get memory percentage
+ * Helper to get memory percentage; undefined when the resource has no valid reading.
*/
-export function getMemoryPercent(r: Resource): number {
- if (!r.memory) return 0;
- if (r.memory.total && r.memory.used) {
- return (r.memory.used / r.memory.total) * 100;
- }
- return r.memory.current;
+export function getMemoryPercent(r: Resource): number | undefined {
+ return getResourceMetricPercent(r.memory);
}
/**
- * Helper to get disk percentage
+ * Helper to get disk percentage; undefined when the resource has no valid reading.
*/
-export function getDiskPercent(r: Resource): number {
- if (!r.disk) return 0;
- if (r.disk.total && r.disk.used) {
- return (r.disk.used / r.disk.total) * 100;
- }
- return r.disk.current;
+export function getDiskPercent(r: Resource): number | undefined {
+ return getResourceMetricPercent(r.disk);
}