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.

Lead the guest and node drawers with alerts and 24h trends

rcourtman3d334dbff336
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index ea1c598258..a3f641d6e4 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -5440,7 +5440,29 @@ compact `DetailSectionTable` rows as Overview; those facts must not switch to a
provider-local card mosaic or require another tap. Only genuinely large or
interactive provider-support content belongs behind
`TechnicalDetailsDisclosure`, which owns its collapsed, lazily mounted
-boundary. `DetailSectionTable` keeps the single bordered table at narrow widths
+boundary.
+The Proxmox guest and node drawers (`GuestDrawerOverview.tsx`,
+`NodeDrawerOverview.tsx`) are the exception, by maintainer decision on
+2026-10-13 (demand ledger "Drawer Overview leads with attention and trends",
+a named bet): a grid of equal-weight inventory cards buried the drawer's job.
+Their Overview leads with active alerts (or one "No active alerts" line), then
+24h trend cards for the metrics the row shows, which add the time dimension
+the row lacks rather than restating it. Any warning- or danger-toned detail row
+is lifted into a "Worth checking" section in front, whichever section owns it,
+so demotion never hides a reason a reading cannot be trusted. Guest
+filesystems, physical disks, RAID, node GPU and NVMe sensor readings (which
+carry no heat tone of their own), and any availability check that is not both
+healthy and fresh stay visible; "availability checks passing" is said only of
+fresh healthy evidence. Trend cards withhold the live value of an offline or
+stale node, and a guest's withdrawn memory reading shows no bytes either.
+A node card is coloured only by the node's own alerts, which
+`ProxmoxNodesTable.tsx` passes as `ownAlerts` by identity match; the drawer's
+`alerts` list also carries its guests' alerts through the node-name match. A
+one-line facts strip carries OS, address, a healthy last completed backup and
+tags. The complete inventory sits in a closed "Details"
+`TechnicalDetailsDisclosure` with `keepMounted`, so its rows stay in the
+document for find-in-page and tests while hidden. Other drawers keep the rule
+above until that bet is graded. `DetailSectionTable` keeps the single bordered table at narrow widths
where density matters, then presents those same canonical rows as bounded
section cards on desktop. Desktop cards share the available row width, stretch
to the same row height, and use stable three- or four-column tracks. An
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 929f9c726e..bc6ea8e360 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2897,12 +2897,14 @@ and supplement known utilization with the threshold-colored progress metadata
derived by `diskListModel.ts`. `GuestDrawerOverview.tsx` passes that metadata
to the shared detail-row primitive; it does not parse display strings, create
local bar geometry, or render a bar for the negative unknown-usage sentinel.
-Within that compact technical layout, `GuestDrawerOverview.tsx` declares the
-`Filesystems` section before the `Tags` section, so the shared
-`DetailSectionTable` span algorithm gives the longer mount-point list the wider
-panel and keeps the short tag list in the narrower slot. Future section-order
-changes in that overview must preserve the filesystem-first ordering rather
-than letting the shorter tag list take the wide column.
+`GuestDrawerOverview.tsx` renders the `Filesystems` section on its own, in
+front of the collapsed Details, so the mount-point list never shares a card
+row with shorter sections; tags render as chips in the Overview facts strip
+rather than as a `Tags` detail section. The Overview's 24h trend cards
+(`DrawerTrendCards.tsx`, lazy-loaded out of the WorkloadsSurface chunk) and
+the History tab read one query from `guestDrawerHistoryQuery.ts` with one cache
+key, and each mounts only while its tab is visible: the node drawer's History
+no longer stays mounted and polling while hidden.
Panel width alone does not make mount paths readable. Filesystem disk rows must
opt into the shared `layout: 'stacked'` presentation so their full mount path
wraps above usage and progress at desktop and phone widths. Shared-prefix paths
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 22ac317998..a7fc02fec2 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -136,6 +136,18 @@ the shared live-status copy to `TemperatureGauge`. Other node alerts never
recolour the cell. The Mail Gateway drawer formats its attention rows through
`getAlertAttentionCopy`.
+### Proxmox node drawer trend cards follow the node's own alerts
+
+`ProxmoxNodesTable` passes `NodeDrawer` two lists. `alerts` keeps the
+node-name match, so Needs attention also lists the node's guests. `ownAlerts`
+is the same `hostOverrideIdCandidates` identity match without the name, and
+only it colours the drawer's CPU, memory, temperature and disk trend cards and
+draws their triggers. Node alerts are keyed on the cluster-qualified id (for
+example `homelab-delly2`), which the drawer's own node record does not carry,
+so the drawer must not rebuild this match itself. `NodeDrawer.test.tsx` covers
+a guest alert that leaves the card plain and a table-supplied node alert that
+colours it.
+
### Canonical Discovery honours VM guest-read deferrals
The canonical resource drawer uses the same fixed PVE VM lock, backup and
diff --git a/frontend-modern/browser-verification/49277e3dae2c1371.json b/frontend-modern/browser-verification/49277e3dae2c1371.json
new file mode 100644
index 0000000000..0e4d62ff72
--- /dev/null
+++ b/frontend-modern/browser-verification/49277e3dae2c1371.json
@@ -0,0 +1,63 @@
+{
+ "version": 1,
+ "base_sha": "e9083fdf8020200e39e71f7cd2e1448af5450ec8",
+ "verified_at": "2026-10-13T09:33:00Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/components/Workloads/DrawerTrendCards.tsx",
+ "frontend-modern/src/components/Workloads/GuestDrawer.tsx",
+ "frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx",
+ "frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx",
+ "frontend-modern/src/components/Workloads/NodeDrawer.tsx",
+ "frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx",
+ "frontend-modern/src/components/Workloads/drawerOverviewModel.ts",
+ "frontend-modern/src/components/Workloads/guestDrawerHistoryQuery.ts",
+ "frontend-modern/src/components/shared/TechnicalDetailsDisclosure.tsx",
+ "frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/components/Workloads/DrawerTrendCards.tsx": "414c2989dd404301d7e0b0fd06fd15472f40217ba6bf1d26083d6f91e74f9d28",
+ "frontend-modern/src/components/Workloads/GuestDrawer.tsx": "2892e4cf2f6e1811559a0093ea9bab0cf84600c878a3a2d16d7666d480003717",
+ "frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx": "6c2ff6fcc5111ba706386ac6431a466e67b36b25f96503d3447ffa56c077d0eb",
+ "frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx": "983b9c2c1da71c05f7d537f716747b8870487c2a3ec3a8be1b0fb5208f3b8f08",
+ "frontend-modern/src/components/Workloads/NodeDrawer.tsx": "a7c7c3e5f862c506e090451d2b971594b7f456d58b2998e3fe3065221ec25aba",
+ "frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx": "591766e5d15e1c9dd592901069b01423d16d28420778fd2190edddb1ad2cc272",
+ "frontend-modern/src/components/Workloads/drawerOverviewModel.ts": "c15dab901c0230698cecbadf5d589cb5562da275c931dcdc7699a35eb21b8cfb",
+ "frontend-modern/src/components/Workloads/guestDrawerHistoryQuery.ts": "e028e1dd36a24bd7ad2b605f3a32157869d32f60f44f11ee4504619cdad2d0d7",
+ "frontend-modern/src/components/shared/TechnicalDetailsDisclosure.tsx": "dab4ef9a255fbe1ccacf6a15a2b762ab1146c53f666a8afc24cda856a98d58cc",
+ "frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx": "45255f415466fae949a3b67c55da37650c5903ca6ae42a79786a85c136d429ee"
+ },
+ "routes": [
+ "/proxmox"
+ ],
+ "viewports": [
+ {
+ "width": 1280,
+ "height": 800
+ },
+ {
+ "width": 1024,
+ "height": 900
+ },
+ {
+ "width": 390,
+ "height": 844
+ }
+ ],
+ "states": [
+ "sidecar Vite dev server serving these final bytes, proxied to the shared dev backend with the real homelab estate (delly, delly2, minipc; 36 guests); websocket not proxied, so data arrived over REST",
+ "VM msp-eval-lab with an active 85% memory warning: Needs attention first, CPU and Memory trend cards (no Disk card: no disk reading, the Filesystems section carries the guest-agent reason once), Memory card amber with the alert trigger drawn, Last completed backup in the facts strip, Details closed",
+ "LXC frigate with no alerts and a fresh passing HTTP check: 'No active alerts \u00b7 availability checks passing', CPU/Memory/Disk trend cards, Filesystems section with / and /media/frigate, facts strip with OS, IP, backup and tag chips (IP tag not repeated); Details opened shows Summary, System, Memory, Network and the availability card",
+ "PVE node delly: guest's memory alert listed under Needs attention but the node's Memory card stays plain (own alerts only), CPU temperature range 42-92\u00b0C from bucket extremes, Worth checking lists the denied update check, Sensors shows NVMe readings outside Details, facts strip, Details closed with the full inventory inside",
+ "390px phone: cards stack full width (356px), no element extends past the viewport, page scrollWidth equals the viewport, Details summary is 44px tall",
+ "after the final node fixes (table-supplied own alerts, last-known memory, measured disk), reloaded at 1280px: delly2 with its own critical memory alert shows a red Memory card with the trigger drawn and the alert under Needs attention; delly with only a guest's warning keeps a plain Memory card; all three nodes show CPU/Memory/(temperature)/Root disk cards with live values and 24h ranges"
+ ],
+ "interactions": [
+ "expanded and collapsed msp-eval-lab, frigate and the delly node rows",
+ "opened Details on frigate and delly by clicking the summary; content was already mounted and became visible",
+ "on delly switched to History: zero History charts before the click, three after (History mounts on demand while Overview trend cards own the 24h read)",
+ "reloaded at 1024, 1280 and 390px widths and re-checked overflow",
+ "negative controls on a pulse-dev copy: reverted the own-alert filter, threshold scaling, bucket extremes, offline withholding, hidden-tab polling and fresh-availability rule in turn; each made exactly its targeted test fail, then restored",
+ "queried /api/alerts/active to confirm delly2's memory alert is keyed on homelab-delly2, then expanded delly, delly2 and minipc in turn"
+ ]
+}
diff --git a/frontend-modern/src/components/Workloads/DrawerTrendCards.tsx b/frontend-modern/src/components/Workloads/DrawerTrendCards.tsx
new file mode 100644
index 0000000000..6686055301
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/DrawerTrendCards.tsx
@@ -0,0 +1,283 @@
+import { For, Show, createMemo, type Component } from 'solid-js';
+
+import type { AggregatedMetricPoint } from '@/api/charts';
+import { formatHistoryChartTooltipValue } from '@/components/shared/historyChartModel';
+
+import {
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ getGuestDrawerHistoryScale,
+ normalizeGuestDrawerHistoryPoints,
+ type GuestDrawerHistoryDeferredMetric,
+ type GuestDrawerHistoryTarget,
+} from './guestDrawerModel';
+import {
+ createGuestDrawerHistoryQuery,
+ createGuestDrawerHistorySource,
+} from './guestDrawerHistoryQuery';
+
+export interface DrawerTrendCardConfig {
+ /** Metrics-store key, shared with the History tab's series. */
+ metric: string;
+ label: string;
+ unit: '%' | 'C';
+ color: string;
+ /** Live reading; a current value is never drawn as a trend point. */
+ current?: number;
+ /** Set when the live reading is not current, e.g. during a backup. */
+ deferred?: GuestDrawerHistoryDeferredMetric;
+ /** Short secondary fact, e.g. "3.42 of 4.00 GB". */
+ detail?: string;
+ /** Severity of an active alert on this metric. */
+ alertSeverity?: 'warning' | 'critical';
+ /** The active alert's trigger, drawn as a dashed line. */
+ alertThreshold?: number;
+}
+
+interface DrawerTrendCardsProps {
+ target: GuestDrawerHistoryTarget | null;
+ /** False while another drawer tab is showing, so hidden cards do not poll. */
+ enabled: boolean;
+ cards: DrawerTrendCardConfig[];
+}
+
+const PLOT_WIDTH = 240;
+const PLOT_HEIGHT = 48;
+
+const formatValue = (value: number, unit: string): string =>
+ formatHistoryChartTooltipValue(value, unit);
+
+const buildPath = (
+ points: readonly AggregatedMetricPoint[],
+ scale: { minValue: number; maxValue: number },
+ startTime: number,
+ endTime: number,
+): string => {
+ if (points.length < 2) return '';
+ const timeSpan = Math.max(1, endTime - startTime);
+ const valueSpan = Math.max(1, scale.maxValue - scale.minValue);
+ return points
+ .map((point, index) => {
+ const x = ((point.timestamp - startTime) / timeSpan) * PLOT_WIDTH;
+ const bounded = Math.min(Math.max(point.value, scale.minValue), scale.maxValue);
+ const y = (1 - (bounded - scale.minValue) / valueSpan) * PLOT_HEIGHT;
+ return `${index === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
+ })
+ .join(' ');
+};
+
+const thresholdY = (value: number, scale: { minValue: number; maxValue: number }): number => {
+ const valueSpan = Math.max(1, scale.maxValue - scale.minValue);
+ const bounded = Math.min(Math.max(value, scale.minValue), scale.maxValue);
+ return (1 - (bounded - scale.minValue) / valueSpan) * PLOT_HEIGHT;
+};
+
+const cardBorderClass = (severity: DrawerTrendCardConfig['alertSeverity']): string => {
+ if (severity === 'critical') return 'border-red-400 dark:border-red-700';
+ if (severity === 'warning') return 'border-amber-400 dark:border-amber-600';
+ return 'border-border';
+};
+
+const valueToneClass = (severity: DrawerTrendCardConfig['alertSeverity']): string => {
+ if (severity === 'critical') return 'text-red-700 dark:text-red-300';
+ if (severity === 'warning') return 'text-amber-700 dark:text-amber-300';
+ return 'text-base-content';
+};
+
+// The drawer Overview's 24h trend for the metrics its table row shows. It reads
+// the same query as the History tab, so a trend here and the History tab's 24h
+// chart are one observation set.
+const DrawerTrendCards: Component<DrawerTrendCardsProps> = (props) => {
+ const source = createGuestDrawerHistorySource(
+ () => props.target,
+ () => GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ () => props.enabled,
+ );
+ const query = createGuestDrawerHistoryQuery(source);
+ const metrics = createMemo(() => query.value().metrics ?? {});
+ const historyWindow = createMemo(() => {
+ const value = query.value();
+ return value.end > value.start ? { start: value.start, end: value.end } : null;
+ });
+
+ return (
+ <Show when={props.target && props.cards.length > 0}>
+ <ul
+ data-testid="drawer-trend-cards"
+ aria-label="Last 24 hours"
+ class={`grid gap-2 sm:grid-cols-2 ${props.cards.length > 3 ? 'xl:grid-cols-4' : 'xl:grid-cols-3'}`}
+ >
+ <For each={props.cards}>
+ {(card) => {
+ const points = createMemo(() =>
+ normalizeGuestDrawerHistoryPoints(metrics()[card.metric], card.unit),
+ );
+ // An alert trigger outside the observed range widens the scale,
+ // so the dashed line sits at its real value, not clamped to an edge.
+ const scale = createMemo(() =>
+ getGuestDrawerHistoryScale(
+ [
+ { points: points() },
+ ...(typeof card.alertThreshold === 'number' && points().length > 0
+ ? [
+ {
+ points: [
+ {
+ timestamp: points()[0].timestamp,
+ value: card.alertThreshold,
+ min: card.alertThreshold,
+ max: card.alertThreshold,
+ },
+ ],
+ },
+ ]
+ : []),
+ ],
+ card.unit,
+ ),
+ );
+ const bounds = createMemo(() => {
+ const list = points();
+ const w = historyWindow();
+ const first = list[0]?.timestamp;
+ const last = list[list.length - 1]?.timestamp;
+ if (first === undefined || last === undefined) return null;
+ return {
+ start: Math.min(w?.start ?? first, first),
+ end: Math.max(w?.end ?? last, last),
+ };
+ });
+ const path = createMemo(() => {
+ const b = bounds();
+ return b ? buildPath(points(), scale(), b.start, b.end) : '';
+ });
+ const range = createMemo(() => {
+ const list = points();
+ if (list.length === 0) return null;
+ let low = Infinity;
+ let high = -Infinity;
+ // Buckets carry their own extremes; a spike inside an averaged
+ // bucket must still widen the stated range.
+ for (const point of list) {
+ low = Math.min(low, point.min ?? point.value);
+ high = Math.max(high, point.max ?? point.value);
+ }
+ return { low, high };
+ });
+ const displayValue = createMemo(() => {
+ if (typeof card.current === 'number') return formatValue(card.current, card.unit);
+ if (card.deferred && typeof card.deferred.lastKnownValue === 'number') {
+ return formatValue(card.deferred.lastKnownValue, card.unit);
+ }
+ return '—';
+ });
+ const valueQualifier = () => {
+ if (typeof card.current === 'number') return '';
+ if (card.deferred?.valueLabel) return card.deferred.valueLabel;
+ if (card.deferred && typeof card.deferred.lastKnownValue === 'number') {
+ return 'last known';
+ }
+ return card.deferred ? 'not current' : '';
+ };
+ const rangeLabel = () => {
+ const r = range();
+ if (!r) return null;
+ if (points().length === 1) return '24h: one reading so far';
+ const low = formatValue(r.low, card.unit);
+ const high = formatValue(r.high, card.unit);
+ return low === high ? `24h: steady at ${low}` : `24h: ${low}–${high}`;
+ };
+ const ariaLabel = () => {
+ const r = range();
+ const trend = r
+ ? `, ${formatValue(r.low, card.unit)} to ${formatValue(r.high, card.unit)} over 24 hours`
+ : '';
+ const qualifier = valueQualifier() ? `${valueQualifier()} ` : '';
+ return `${card.label} ${qualifier}${displayValue()}${trend}`;
+ };
+ return (
+ <li
+ data-testid={`drawer-trend-card-${card.metric}`}
+ class={`flex min-w-0 flex-col gap-1.5 rounded-md border bg-surface px-3 py-2.5 ${cardBorderClass(card.alertSeverity)}`}
+ >
+ <div class="flex items-baseline justify-between gap-2">
+ <span class="text-xs text-muted">{card.label}</span>
+ <span class="flex items-baseline gap-1.5">
+ <Show when={valueQualifier()}>
+ <span class="text-[10px] text-muted">{valueQualifier()}</span>
+ </Show>
+ <span
+ class={`text-lg font-semibold tabular-nums leading-none ${valueToneClass(card.alertSeverity)}`}
+ >
+ {displayValue()}
+ </span>
+ </span>
+ </div>
+ <Show
+ when={path()}
+ fallback={
+ <div class="flex h-12 items-center text-[11px] text-muted">
+ {query.loading() && !query.resolvedOnce()
+ ? 'Loading trend…'
+ : query.error()
+ ? 'Trend unavailable'
+ : 'Collecting history'}
+ </div>
+ }
+ >
+ <svg
+ class="block h-12 w-full"
+ viewBox={`0 0 ${PLOT_WIDTH} ${PLOT_HEIGHT}`}
+ preserveAspectRatio="none"
+ role="img"
+ aria-label={ariaLabel()}
+ >
+ <Show when={typeof card.alertThreshold === 'number'}>
+ <line
+ data-testid="drawer-trend-threshold"
+ x1="0"
+ x2={PLOT_WIDTH}
+ y1={thresholdY(card.alertThreshold!, scale())}
+ y2={thresholdY(card.alertThreshold!, scale())}
+ stroke="currentColor"
+ class={
+ card.alertSeverity === 'critical' ? 'text-red-500' : 'text-amber-500'
+ }
+ stroke-width="1"
+ stroke-dasharray="4 4"
+ vector-effect="non-scaling-stroke"
+ />
+ </Show>
+ <path
+ d={path()}
+ fill="none"
+ stroke={card.color}
+ stroke-width="1.5"
+ stroke-linejoin="round"
+ vector-effect="non-scaling-stroke"
+ />
+ </svg>
+ </Show>
+ <Show when={path() && query.error()}>
+ <p class="text-[11px] leading-snug text-amber-700 dark:text-amber-300">
+ Refresh failed. Showing the last loaded trend.
+ </p>
+ </Show>
+ <div class="flex flex-wrap justify-between gap-x-2 text-[11px] text-muted">
+ <span>{rangeLabel() ?? ''}</span>
+ <Show when={card.detail}>
+ <span class="tabular-nums">{card.detail}</span>
+ </Show>
+ </div>
+ <Show when={card.deferred?.message}>
+ <p class="text-[11px] leading-snug text-muted">{card.deferred!.message}</p>
+ </Show>
+ </li>
+ );
+ }}
+ </For>
+ </ul>
+ </Show>
+ );
+};
+
+export default DrawerTrendCards;
diff --git a/frontend-modern/src/components/Workloads/GuestDrawer.test.tsx b/frontend-modern/src/components/Workloads/GuestDrawer.test.tsx
index d4a25f7406..ab4891ad26 100644
--- a/frontend-modern/src/components/Workloads/GuestDrawer.test.tsx
+++ b/frontend-modern/src/components/Workloads/GuestDrawer.test.tsx
@@ -133,7 +133,9 @@ function makeGuestWithDiscoveryTarget(overrides: Partial<WorkloadGuest> = {}): W
});
}
-const technicalDetails = () => within(screen.getByTestId('guest-technical-details'));
+// Filesystems and lifted warning rows render outside Details; the render
+// helper opens Details, so read the whole Overview.
+const technicalDetails = () => within(screen.getByTestId('guest-drawer-overview'));
const makeHistoryPoints = (base: number) => [
{ timestamp: 1, value: base, min: base, max: base },
@@ -1125,36 +1127,45 @@ describe('GuestDrawer', () => {
// ── Tags card ──
describe('Tags card', () => {
+ const tagChips = () =>
+ Array.from(
+ screen.getByTestId('guest-drawer-facts').querySelectorAll('span.rounded-full'),
+ ).map((chip) => chip.textContent);
+
it('renders tags from an array', () => {
render(() => (
<GuestDrawer guest={makeGuest({ tags: ['production', 'web'] })} onClose={vi.fn()} />
));
- expect(screen.getByText('Tags')).toBeInTheDocument();
- expect(technicalDetails().getByText('production, web')).toBeInTheDocument();
+ expect(tagChips()).toEqual(['production', 'web']);
});
it('renders tags from a comma-separated string', () => {
render(() => (
<GuestDrawer guest={makeGuest({ tags: 'db,critical' as any })} onClose={vi.fn()} />
));
- expect(technicalDetails().getByText('db, critical')).toBeInTheDocument();
+ expect(tagChips()).toEqual(['db', 'critical']);
});
it('trims whitespace from tags', () => {
render(() => (
<GuestDrawer guest={makeGuest({ tags: ' spaced , padded ' as any })} onClose={vi.fn()} />
));
- expect(technicalDetails().getByText('spaced, padded')).toBeInTheDocument();
+ expect(tagChips()).toEqual(['spaced', 'padded']);
});
- it('hides Tags card when tags is null', () => {
+ it('renders no tag chips when tags is null', () => {
render(() => <GuestDrawer guest={makeGuest({ tags: null })} onClose={vi.fn()} />);
expect(screen.queryByText('Tags')).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId('guest-drawer-facts')?.querySelectorAll('span.rounded-full') ?? [],
+ ).toHaveLength(0);
});
- it('hides Tags card when tags is empty array', () => {
+ it('renders no tag chips when tags is empty array', () => {
render(() => <GuestDrawer guest={makeGuest({ tags: [] })} onClose={vi.fn()} />);
- expect(screen.queryByText('Tags')).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId('guest-drawer-facts')?.querySelectorAll('span.rounded-full') ?? [],
+ ).toHaveLength(0);
});
});
diff --git a/frontend-modern/src/components/Workloads/GuestDrawer.tsx b/frontend-modern/src/components/Workloads/GuestDrawer.tsx
index 0b3211b84a..7fb18728eb 100644
--- a/frontend-modern/src/components/Workloads/GuestDrawer.tsx
+++ b/frontend-modern/src/components/Workloads/GuestDrawer.tsx
@@ -142,6 +142,10 @@ const GuestDrawerContent: Component<GuestDrawerProps> = (props) => {
parentMemoryTotal={props.parentMemoryTotal}
memoryDisplayBasis={props.memoryDisplayBasis}
alerts={props.alerts}
+ historyTarget={hasHistorySupport() ? historyTarget() : null}
+ trendsEnabled={activeTab() === 'overview'}
+ currentMetrics={historyCurrentMetrics()}
+ deferredMetrics={historyDeferredMetrics()}
/>
</div>
diff --git a/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx b/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx
index f0b05cdafb..c64c303e63 100644
--- a/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx
+++ b/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx
@@ -10,14 +10,7 @@ import {
type Component,
} from 'solid-js';
-import {
- ChartsAPI,
- type AggregatedMetricPoint,
- type AllMetricsHistoryResponse,
- type HistoryTimeRange,
- type ResourceType,
- type SingleMetricHistoryResponse,
-} from '@/api/charts';
+import { type AggregatedMetricPoint, type HistoryTimeRange } from '@/api/charts';
import { FormSelect } from '@/components/shared/FormSelect';
import { filterSelectClass } from '@/components/shared/FilterToolbar';
import { Button } from '@/components/shared/Button';
@@ -28,12 +21,10 @@ import {
formatHistoryChartTooltipValue,
formatHistoryChartTimeLabel,
} from '@/components/shared/historyChartModel';
-import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
import { isRangeLocked, loadRuntimeCapabilities, maxHistoryDays } from '@/stores/license';
import { getAPIReadAccessErrorMessage } from '@/utils/apiAccessError';
import {
- GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
GUEST_DRAWER_HISTORY_GROUPS,
buildGuestDrawerHistoryPath,
getGuestDrawerHistoryRangeBounds,
@@ -46,6 +37,10 @@ import {
type GuestDrawerHistoryTarget,
type GuestDrawerHistoryTimeBounds,
} from './guestDrawerModel';
+import {
+ createGuestDrawerHistoryQuery,
+ createGuestDrawerHistorySource,
+} from './guestDrawerHistoryQuery';
interface GuestDrawerHistoryProps {
currentMetrics?: Record<string, number | null | undefined>;
@@ -60,12 +55,6 @@ interface GuestDrawerHistoryRangeSelectProps {
range: HistoryTimeRange;
}
-interface GuestDrawerHistoryQueryKey {
- resourceType: ResourceType;
- resourceId: string;
- range: HistoryTimeRange;
-}
-
interface GuestDrawerHistoryGroupChartProps {
currentMetrics?: Record<string, number | null | undefined>;
deferredMetrics?: Record<string, GuestDrawerHistoryDeferredMetric | undefined>;
@@ -78,8 +67,6 @@ interface GuestDrawerHistoryGroupChartProps {
touchInspection: boolean;
}
-const GUEST_DRAWER_HISTORY_MAX_POINTS = 240;
-const GUEST_DRAWER_HISTORY_POLL_MS = 30_000;
const GUEST_DRAWER_HISTORY_CHART_WIDTH = 360;
const GUEST_DRAWER_HISTORY_CHART_HEIGHT = 92;
const GUEST_DRAWER_HISTORY_PLOT_LEFT = 34;
@@ -87,16 +74,6 @@ const GUEST_DRAWER_HISTORY_PLOT_RIGHT = 8;
const GUEST_DRAWER_HISTORY_PLOT_TOP = 8;
const GUEST_DRAWER_HISTORY_PLOT_BOTTOM = 18;
-const EMPTY_HISTORY_RESPONSE: AllMetricsHistoryResponse = {
- resourceType: '',
- resourceId: '',
- range: GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
- start: 0,
- end: 0,
- metrics: {},
- source: 'store',
-};
-
const formatRangeLabel = (range: HistoryTimeRange): string => {
switch (range) {
case '1h':
@@ -139,21 +116,6 @@ export const GuestDrawerHistoryRangeSelect: Component<GuestDrawerHistoryRangeSel
</FormSelect>
);
-const normalizeHistoryResponse = (
- result: SingleMetricHistoryResponse | AllMetricsHistoryResponse,
-): AllMetricsHistoryResponse => {
- if ('metrics' in result) return result;
- return {
- resourceType: result.resourceType,
- resourceId: result.resourceId,
- range: result.range,
- start: result.start,
- end: result.end,
- metrics: { [result.metric]: result.points ?? [] },
- source: result.source,
- };
-};
-
const getAxisLabel = (unit: string, pct: number): string => {
if (unit === '%') {
if (pct === 0) return '100%';
@@ -702,53 +664,12 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
});
const locked = createMemo(() => isRangeLocked(props.range));
- // Snapshot replacement often creates a new target object with unchanged
- // coordinates. Only a real target/range/access change owns a new read.
- const historySource = createMemo<GuestDrawerHistoryQueryKey | null>(
- () => {
- const target = props.target;
- if (!target || locked()) return null;
- return {
- resourceType: target.resourceType,
- resourceId: target.resourceId,
- range: props.range,
- };
- },
- null,
- {
- equals: (previous, next) =>
- previous === next ||
- Boolean(
- previous &&
- next &&
- previous.resourceType === next.resourceType &&
- previous.resourceId === next.resourceId &&
- previous.range === next.range,
- ),
- },
+ const historySource = createGuestDrawerHistorySource(
+ () => props.target,
+ () => props.range,
+ () => !locked(),
);
- const historyQuery = createNonSuspendingQuery<
- AllMetricsHistoryResponse,
- GuestDrawerHistoryQueryKey
- >({
- source: historySource,
- fetcher: async (key, signal) =>
- normalizeHistoryResponse(
- await ChartsAPI.getMetricsHistory({
- resourceType: key.resourceType,
- resourceId: key.resourceId,
- range: key.range,
- maxPoints: GUEST_DRAWER_HISTORY_MAX_POINTS,
- signal,
- }),
- ),
- initialValue: EMPTY_HISTORY_RESPONSE,
- cacheKey: (key) => `guest-drawer-history:${key.resourceType}:${key.resourceId}:${key.range}`,
- // Former-host or former-range observations are not evidence for this
- // target. Matching cached reads and same-source polling remain retained.
- retainPreviousValueOnSourceChange: false,
- pollMs: GUEST_DRAWER_HISTORY_POLL_MS,
- });
+ const historyQuery = createGuestDrawerHistoryQuery(historySource);
const metrics = createMemo(() => historyQuery.value().metrics ?? {});
const groups = createMemo(() => props.groups ?? GUEST_DRAWER_HISTORY_GROUPS);
diff --git a/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx b/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx
index fcb8d8675f..af688764de 100644
--- a/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx
+++ b/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx
@@ -1,12 +1,16 @@
+import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
-import { Show, Suspense, lazy } from 'solid-js';
+import { For, Show, Suspense, createMemo, lazy } from 'solid-js';
import {
compactDetailRows,
compactDetailSections,
makeDetailRow,
} from '@/components/shared/DetailSectionTable';
-import { TechnicalDetailsSection } from '@/components/shared/TechnicalDetailsDisclosure';
+import {
+ TechnicalDetailsDisclosure,
+ TechnicalDetailsSection,
+} from '@/components/shared/TechnicalDetailsDisclosure';
import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
import type { Alert } from '@/types/api';
import { AvailabilityProbeStatusCards } from '@/components/Infrastructure/AvailabilityProbeStatusCard';
@@ -21,13 +25,23 @@ import {
import { buildWorkloadsDiskPresentation } from './diskListModel';
import {
+ GUEST_DRAWER_HISTORY_GROUPS,
getGuestDrawerAlertAttention,
getGuestDrawerMemoryRows,
getGuestDrawerMemoryReading,
getGuestDrawerGuestReadPresentation,
isGuestDrawerVM,
type GuestDrawerBackupPresentation,
+ type GuestDrawerHistoryDeferredMetric,
+ type GuestDrawerHistoryTarget,
} from './guestDrawerModel';
+import {
+ collectDrawerExceptionRows,
+ getDrawerMetricAlert,
+ isDrawerAvailabilityHealthy,
+ withoutDrawerExceptionRows,
+} from './drawerOverviewModel';
+import type { DrawerTrendCardConfig } from './DrawerTrendCards';
import type { NestedWorkloadContext } from './nestedWorkloadContext';
import { WORKLOAD_ACTION_AGENT_LABEL } from './workloadAgentReadiness';
import { getWorkloadAlertResourceIdCandidates } from './workloadTopology';
@@ -44,6 +58,15 @@ const GuestPhysicalDisks = lazy(() =>
})),
);
+// The 24h trend cards read metrics history only once a drawer is open; keep
+// their chart code out of the WorkloadsSurface table chunk the same way.
+const DrawerTrendCards = lazy(() => import('./DrawerTrendCards'));
+
+const historySeriesColor = (metric: string): string =>
+ GUEST_DRAWER_HISTORY_GROUPS.flatMap((group) => group.series).find(
+ (series) => series.metric === metric,
+ )?.color ?? 'currentColor';
+
interface GuestDrawerOverviewProps {
guest: GuestDrawerProps['guest'];
guestOsSummary: string;
@@ -66,6 +89,11 @@ interface GuestDrawerOverviewProps {
parentMemoryTotal?: GuestDrawerProps['parentMemoryTotal'];
memoryDisplayBasis?: GuestDrawerProps['memoryDisplayBasis'];
alerts?: Alert[];
+ historyTarget?: GuestDrawerHistoryTarget | null;
+ /** True while Overview is the visible tab; hidden trends do not poll. */
+ trendsEnabled?: boolean;
+ currentMetrics?: Record<string, number | undefined>;
+ deferredMetrics?: Record<string, GuestDrawerHistoryDeferredMetric | undefined>;
}
export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
@@ -114,9 +142,9 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
const overviewSections = () =>
compactDetailSections([
{
- label: 'Operator context',
+ label: 'Summary',
rows: compactDetailRows([
- makeDetailRow('System', props.hasOsInfo ? props.guestOsSummary : null),
+ // OS and primary IP lead the facts strip; they are not repeated here.
makeDetailRow('Pulse coverage', coverageLabel(), {
title: props.hasWorkloadActionAgent
? props.workloadActionAgentTitle
@@ -135,7 +163,6 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
layout: 'stacked',
wrap: true,
}),
- makeDetailRow('Primary IP', props.ipAddresses[0]),
// Starting or ending an operation is not evidence of a completed
// backup. Keep its activity separate from the last completed age.
makeDetailRow('Last completed backup', protectionPresentation().label, {
@@ -289,14 +316,6 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
]),
}
: null,
- props.normalizedTags.length > 0
- ? {
- label: 'Tags',
- rows: compactDetailRows([
- makeDetailRow('Values', props.normalizedTags.join(', '), { wrap: true }),
- ]),
- }
- : null,
props.hasNetworkInterfaces
? {
label: 'Network',
@@ -338,8 +357,89 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
]);
};
+ const sectionsByLabel = () => {
+ const technical = technicalSections();
+ const filesystems = technical.filter((section) => section.label === 'Filesystems');
+ const rest = technical.filter((section) => section.label !== 'Filesystems');
+ return {
+ filesystems,
+ details: withoutDrawerExceptionRows([...overviewSections(), ...rest]),
+ };
+ };
+ const exceptionRows = createMemo(() =>
+ collectDrawerExceptionRows([...overviewSections(), ...technicalSections()]),
+ );
+
+ const availabilityChecks = () => [
+ ...(props.guest.availability ? [props.guest.availability] : []),
+ ...(props.guest.availabilityChecks ?? []),
+ ];
+ const hasAvailability = () => availabilityChecks().length > 0;
+ const availabilityHealthy = () =>
+ hasAvailability() &&
+ availabilityChecks().every((check) => isDrawerAvailabilityHealthy(check, now()));
+
+ const memoryDetail = () => {
+ const memory = props.guest.memory;
+ // Bytes follow the same decision as the percentage: a withdrawn reading
+ // shows neither, a last-known one shows both.
+ const hasReading =
+ typeof props.currentMetrics?.memory === 'number' ||
+ typeof props.deferredMetrics?.memory?.lastKnownValue === 'number';
+ if (!memory || !hasReading || memory.usageUnavailable || !((memory.total ?? 0) > 0)) {
+ return undefined;
+ }
+ return `${formatBytes(memory.used ?? 0)} of ${formatBytes(memory.total ?? 0)}`;
+ };
+ const diskDetail = () => {
+ const disk = props.guest.disk;
+ if (!disk || !((disk.total ?? 0) > 0) || typeof props.currentMetrics?.disk !== 'number') {
+ return undefined;
+ }
+ return `${formatBytes(disk.used ?? 0)} of ${formatBytes(disk.total ?? 0)}`;
+ };
+ const trendCards = (): DrawerTrendCardConfig[] => {
+ const card = (metric: string, label: string, detail?: string): DrawerTrendCardConfig => {
+ const alert = getDrawerMetricAlert(props.alerts, metric);
+ return {
+ metric,
+ label,
+ unit: '%',
+ color: historySeriesColor(metric),
+ current: props.currentMetrics?.[metric],
+ deferred: props.deferredMetrics?.[metric],
+ detail,
+ alertSeverity: alert?.severity,
+ alertThreshold: alert?.threshold,
+ };
+ };
+ // With no disk reading at all, the Filesystems section below already says
+ // why; an empty Disk card would only repeat it.
+ const diskReading =
+ typeof props.currentMetrics?.disk === 'number' ||
+ typeof props.deferredMetrics?.disk?.lastKnownValue === 'number';
+ return [
+ card('cpu', 'CPU', props.guest.cpus ? `${props.guest.cpus} vCPU` : undefined),
+ card('memory', 'Memory', memoryDetail()),
+ ...(diskReading ? [card('disk', 'Disk', diskDetail())] : []),
+ ];
+ };
+
+ const facts = () =>
+ [
+ props.hasOsInfo ? props.guestOsSummary : '',
+ props.ipAddresses[0] ?? '',
+ // A late or missing backup is listed under Worth checking instead.
+ protectionPresentation().tone === 'success'
+ ? `Last completed backup ${protectionPresentation().label}`
+ : '',
+ ].filter((fact) => fact.trim().length > 0);
+
+ // A tag that repeats a fact already on the strip (often the IP) adds nothing.
+ const tagChips = () => props.normalizedTags.filter((tag) => !facts().includes(tag));
+
return (
- <div class="space-y-3">
+ <div class="space-y-3" data-testid="guest-drawer-overview">
<DrawerAttentionSection
items={(props.alerts ?? []).map((alert) => ({
id: alert.id,
@@ -356,10 +456,47 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
acknowledged: alert.acknowledged,
}))}
/>
- <TechnicalDetailsSection
- dataTestId="guest-technical-details"
- sections={[...overviewSections(), ...technicalSections()]}
- />
+ <Show when={(props.alerts ?? []).length === 0}>
+ <p data-testid="drawer-no-attention" class="text-xs text-muted">
+ <span class="font-medium text-base-content">{ALERTS_EMPTY_STATE}</span>
+ <Show when={availabilityHealthy()}>
+ <span> · availability checks passing</span>
+ </Show>
+ </p>
+ </Show>
+
+ <Show when={props.historyTarget}>
+ <Suspense fallback={<div class="h-28" aria-hidden="true" />}>
+ <DrawerTrendCards
+ target={props.historyTarget ?? null}
+ enabled={props.trendsEnabled ?? true}
+ cards={trendCards()}
+ />
+ </Suspense>
+ </Show>
+ {/* Visible text, not a tooltip: the caveat and what to do about it
+ must reach touch and keyboard users too. */}
+ <Show when={memoryReading()?.cacheNote}>
+ {(note) => (
+ <p data-testid="drawer-memory-reading-note" class="text-xs leading-snug text-muted">
+ {note()}
+ </p>
+ )}
+ </Show>
+
+ <Show when={exceptionRows().length > 0}>
+ <TechnicalDetailsSection
+ dataTestId="guest-drawer-exceptions"
+ sections={[{ label: 'Worth checking', rows: exceptionRows() }]}
+ />
+ </Show>
+
+ <Show when={sectionsByLabel().filesystems.length > 0}>
+ <TechnicalDetailsSection
+ dataTestId="guest-drawer-filesystems"
+ sections={sectionsByLabel().filesystems}
+ />
+ </Show>
<Show
when={
props.guest.agentKind === 'pulse' ||
@@ -386,18 +523,54 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
/>
</Show>
- <div class="space-y-3">
- <Show when={props.guest.availability || props.guest.availabilityChecks?.length}>
- <div class="mt-3 max-w-sm">
- <div class="space-y-3">
- <AvailabilityProbeStatusCards
- availability={props.guest.availability}
- checks={props.guest.availabilityChecks}
- />
- </div>
+ {/* A failing or unknown check is something to act on, so it stays in
+ front. A passing one is summarised above and kept under Details. */}
+ <Show when={hasAvailability() && !availabilityHealthy()}>
+ <div class="max-w-sm space-y-3">
+ <AvailabilityProbeStatusCards
+ availability={props.guest.availability}
+ checks={props.guest.availabilityChecks}
+ />
+ </div>
+ </Show>
+
+ <Show when={facts().length > 0 || tagChips().length > 0}>
+ <div
+ data-testid="guest-drawer-facts"
+ class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted"
+ >
+ <For each={facts()}>{(fact) => <span class="wrap-break-word">{fact}</span>}</For>
+ <For each={tagChips()}>
+ {(tag) => (
+ <span class="max-w-full rounded-full border border-border px-2 py-0.5 text-[11px] break-all">
+ {tag}
+ </span>
+ )}
+ </For>
+ </div>
+ </Show>
+
+ <TechnicalDetailsDisclosure
+ dataTestId="guest-technical-details"
+ title="Details"
+ keepMounted
+ subtitle="system, coverage, memory, network and availability checks"
+ class="border-t border-border pt-2"
+ contentClass="mt-2 space-y-3"
+ >
+ <TechnicalDetailsSection
+ dataTestId="guest-technical-details-sections"
+ sections={sectionsByLabel().details}
+ />
+ <Show when={availabilityHealthy()}>
+ <div class="max-w-sm space-y-3">
+ <AvailabilityProbeStatusCards
+ availability={props.guest.availability}
+ checks={props.guest.availabilityChecks}
+ />
</div>
</Show>
- </div>
+ </TechnicalDetailsDisclosure>
</div>
);
}
diff --git a/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx b/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
index 85ff621105..aa10444ca8 100644
--- a/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
+++ b/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
@@ -26,8 +26,12 @@ vi.mock('@/stores/license', () => ({
import { NodeDrawer } from './NodeDrawer';
+// Details is closed by default; a warning row is lifted out of it into
+// Worth checking, so read the whole Overview with Details open.
const openTechnicalDetails = () => {
- return within(screen.getByTestId('node-technical-details'));
+ const details = screen.getByTestId('node-technical-details') as HTMLDetailsElement;
+ details.open = true;
+ return within(screen.getByTestId('node-drawer-overview'));
};
const makeHistoryPoints = (base: number) => [
@@ -211,11 +215,12 @@ describe('NodeDrawer', () => {
/>
));
- const technical = openTechnicalDetails();
- expect(technical.getByText('GPU')).toBeInTheDocument();
- expect(technical.getByText('GPU 0')).toBeInTheDocument();
+ // GPU readings stay visible in Sensors rather than inside closed Details.
+ const sensors = within(screen.getByTestId('node-drawer-sensors'));
+ expect(sensors.getByText('Sensors')).toBeInTheDocument();
+ expect(sensors.getByText('GPU 0')).toBeInTheDocument();
expect(
- technical.getByText('NVIDIA RTX A6000 · 63°C · 42% · 8.00 GB / 48.0 GB'),
+ sensors.getByText('NVIDIA RTX A6000 · 63°C · 42% · 8.00 GB / 48.0 GB'),
).toBeInTheDocument();
});
@@ -389,3 +394,104 @@ describe('NodeDrawer', () => {
]);
});
});
+
+describe('NodeDrawer Overview trends', () => {
+ const guestAlert = makeAlert({
+ id: 'guest-memory',
+ resourceId: 'qemu-281',
+ resourceName: 'msp-eval-lab',
+ message: 'VM memory at 85.4%',
+ threshold: 85,
+ });
+
+ it("marks a trend card only for the node's own alert, not a guest's on the same node", async () => {
+ render(() => <NodeDrawer node={makeNode()} alerts={[guestAlert]} />);
+ const memory = await screen.findByTestId('drawer-trend-card-memory');
+ // The guest's alert is still listed under Needs attention.
+ expect(screen.getByText('VM memory at 85.4%')).toBeInTheDocument();
+ expect(memory).not.toHaveClass('border-amber-400');
+ expect(screen.queryByTestId('drawer-trend-threshold')).toBeNull();
+ });
+
+ it("draws the node's own memory alert on its memory card", async () => {
+ render(() => <NodeDrawer node={makeNode()} alerts={[makeAlert(), guestAlert]} />);
+ const memory = await screen.findByTestId('drawer-trend-card-memory');
+ expect(memory).toHaveClass('border-amber-400');
+ expect(await within(memory).findByTestId('drawer-trend-threshold')).toBeInTheDocument();
+ });
+
+ it("does not present an offline node's last readings as live", async () => {
+ render(() => <NodeDrawer node={makeNode({ status: 'offline' })} />);
+ const cpu = await screen.findByTestId('drawer-trend-card-cpu');
+ expect(within(cpu).getByText('not current')).toBeInTheDocument();
+ expect(cpu).toHaveTextContent('Node is offline. Showing its history only.');
+ // No used-of-total bytes beside a withheld reading.
+ expect(screen.getByTestId('drawer-trend-card-memory').textContent).not.toMatch(/ of /);
+ });
+
+ it('keeps NVMe and GPU sensor readings visible rather than inside closed Details', () => {
+ render(() => (
+ <NodeDrawer
+ node={makeNode({
+ temperature: {
+ ...makeNode().temperature!,
+ nvme: [{ device: 'nvme0', temp: 71 }],
+ },
+ })}
+ />
+ ));
+ const sensors = screen.getByTestId('node-drawer-sensors');
+ expect(sensors.closest('details')).toBeNull();
+ expect(within(sensors).getByText(/nvme0 71/)).toBeInTheDocument();
+ });
+
+ it("uses the table's own-alert list when its id differs from the node record", async () => {
+ // Proxmox node alerts are keyed on the cluster-qualified id (homelab-pve-node-1),
+ // not the drawer node's id, so the table supplies the node's own alerts.
+ const nodeAlert = makeAlert({
+ resourceId: 'homelab-pve-node-1',
+ level: 'critical',
+ threshold: 95,
+ });
+ render(() => <NodeDrawer node={makeNode()} alerts={[nodeAlert]} ownAlerts={[nodeAlert]} />);
+ const memory = await screen.findByTestId('drawer-trend-card-memory');
+ expect(memory).toHaveClass('border-red-400');
+ expect(await within(memory).findByTestId('drawer-trend-threshold')).toBeInTheDocument();
+ });
+
+ it('labels retained node memory as last known instead of live', async () => {
+ render(() => (
+ <NodeDrawer
+ node={makeNode({
+ memory: {
+ total: 8000,
+ used: 3200,
+ free: 4800,
+ usage: 40,
+ observation: { state: 'last-known', source: 'node-meminfo' },
+ },
+ })}
+ />
+ ));
+ const memory = await screen.findByTestId('drawer-trend-card-memory');
+ expect(within(memory).getByText('last known')).toBeInTheDocument();
+ expect(within(memory).getByText('40.0%')).toBeInTheDocument();
+ });
+
+ it('does not show a filled-in zero for a node with no disk measurement', async () => {
+ render(() => (
+ <NodeDrawer node={makeNode({ disk: { total: 0, used: 0, free: 0, usage: 0 } })} />
+ ));
+ const disk = await screen.findByTestId('drawer-trend-card-disk');
+ expect(within(disk).queryByText('0.0%')).toBeNull();
+ expect(within(disk).getByText('—')).toBeInTheDocument();
+ });
+
+ it('reads the 24h trend once while Overview shows and mounts History only on demand', async () => {
+ render(() => <NodeDrawer node={makeNode()} />);
+ await screen.findByTestId('drawer-trend-card-cpu');
+ await waitFor(() => expect(chartsApiMocks.getMetricsHistory).toHaveBeenCalledTimes(1));
+ expect(chartsApiMocks.getMetricsHistory.mock.calls[0][0]).toMatchObject({ range: '24h' });
+ expect(screen.queryByTestId('guest-history-group-chart')).toBeNull();
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/NodeDrawer.tsx b/frontend-modern/src/components/Workloads/NodeDrawer.tsx
index 471da3ed6c..8419c79414 100644
--- a/frontend-modern/src/components/Workloads/NodeDrawer.tsx
+++ b/frontend-modern/src/components/Workloads/NodeDrawer.tsx
@@ -26,6 +26,11 @@ interface NodeDrawerProps {
disks?: Disk[];
temperatureThresholds?: MetricDisplayThresholds | null;
alerts?: Alert[];
+ /**
+ * The node's own alerts, matched by its identities rather than by node
+ * name. `alerts` also lists its guests'; only these describe its metrics.
+ */
+ ownAlerts?: Alert[];
onClose?: () => void;
}
@@ -43,6 +48,13 @@ export const NodeDrawer: Component<NodeDrawerProps> = (props) => {
const historyTarget = createMemo(() => getNodeDrawerHistoryTarget(props.node));
const historyGroups = createMemo(() => getNodeDrawerHistoryGroups(props.node));
const currentMetrics = createMemo(() => getNodeDrawerCurrentMetrics(props.node));
+ // The drawer lists alerts for the node's guests too; only the node's own
+ // alerts describe the metrics on its trend cards.
+ const ownAlerts = createMemo(() => {
+ if (props.ownAlerts) return props.ownAlerts;
+ const ids = new Set(nodeOverrideIdCandidates(props.node));
+ return (props.alerts ?? []).filter((alert) => ids.has(alert.resourceId));
+ });
const headerIndicator = createMemo(() => getSimpleStatusIndicator(props.node.status));
const temperatureThresholds = createMemo(() =>
props.temperatureThresholds !== undefined
@@ -107,17 +119,24 @@ export const NodeDrawer: Component<NodeDrawerProps> = (props) => {
disks={props.disks}
temperatureThresholds={temperatureThresholds()}
alerts={props.alerts}
+ historyTarget={historyTarget()}
+ trendsEnabled={activeTab() === 'overview'}
+ metricAlerts={ownAlerts()}
/>
</div>
- <div class={`[overflow-anchor:none] ${activeTab() === 'history' ? '' : 'hidden'}`}>
- <GuestDrawerHistory
- currentMetrics={currentMetrics()}
- groups={historyGroups()}
- range={historyRange()}
- target={historyTarget()}
- />
- </div>
+ {/* Mounted on demand, like the guest drawer's History: a hidden History
+ would poll the same resource the Overview trends already read. */}
+ <Show when={activeTab() === 'history'}>
+ <div class="[overflow-anchor:none]">
+ <GuestDrawerHistory
+ currentMetrics={currentMetrics()}
+ groups={historyGroups()}
+ range={historyRange()}
+ target={historyTarget()}
+ />
+ </div>
+ </Show>
<div class={`[overflow-anchor:none] ${activeTab() === 'manage' ? '' : 'hidden'}`}>
<Show when={activeTab() === 'manage'}>
diff --git a/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx b/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx
index 2d4e200477..57467f8f0c 100644
--- a/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx
+++ b/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx
@@ -1,5 +1,12 @@
+import { For, Show, Suspense, createMemo, lazy } from 'solid-js';
+
+import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
-import { TechnicalDetailsSection } from '@/components/shared/TechnicalDetailsDisclosure';
+import {
+ TechnicalDetailsDisclosure,
+ TechnicalDetailsSection,
+} from '@/components/shared/TechnicalDetailsDisclosure';
+import { HOST_METRICS_HISTORY_GROUPS } from '@/components/shared/hostMetricsHistoryModel';
import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
import {
compactDetailRows,
@@ -13,16 +20,45 @@ import { alertTypeDisplayLabel } from '@/features/alerts/helpers';
import { getAlertAttentionCopy } from '@/features/alerts/metricAlertPresentation';
import { formatBytes, formatRelativeTime, normalizeDiskArray } from '@/utils/format';
import type { MetricDisplayThresholds } from '@/utils/metricThresholds';
+import { getMemoryObservationPresentation } from '@/utils/memoryObservation';
import { getProxmoxUpdateEvidencePresentation } from '@/utils/proxmoxUpdateEvidence';
import { formatTemperature, getCpuTemperature, getTemperatureTextClass } from '@/utils/temperature';
import { buildDrawerDiskListItems } from './DrawerDiskListCard';
+import type { DrawerTrendCardConfig } from './DrawerTrendCards';
+import {
+ collectDrawerExceptionRows,
+ getDrawerMetricAlert,
+ withoutDrawerExceptionRows,
+} from './drawerOverviewModel';
+import type {
+ GuestDrawerHistoryDeferredMetric,
+ GuestDrawerHistoryTarget,
+} from './guestDrawerModel';
+
+// Loaded once a node drawer opens, so the Proxmox table chunk does not carry it.
+const DrawerTrendCards = lazy(() => import('./DrawerTrendCards'));
+
+const hostSeriesColor = (metric: string): string =>
+ HOST_METRICS_HISTORY_GROUPS.flatMap((group) => group.series).find(
+ (series) => series.metric === metric,
+ )?.color ?? 'currentColor';
+
+const finitePercent = (value: number | null | undefined): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) && value >= 0
+ ? Math.min(100, value)
+ : undefined;
interface NodeDrawerOverviewProps {
node: Node;
disks?: Disk[];
temperatureThresholds?: MetricDisplayThresholds | null;
alerts?: Alert[];
+ historyTarget?: GuestDrawerHistoryTarget | null;
+ /** True while Overview is the visible tab; hidden trends do not poll. */
+ trendsEnabled?: boolean;
+ /** The node's own alerts, without its guests', for the trend cards. */
+ metricAlerts?: Alert[];
}
interface NodeOverviewRow {
@@ -298,6 +334,15 @@ export function NodeDrawerOverview(props: NodeDrawerOverviewProps) {
return buildDrawerDiskListItems(disks);
};
+ const thermalRows = () =>
+ getThermalRows(
+ props.node.temperature,
+ props.temperatureThresholds,
+ (props.node.sensors?.gpu?.length ?? 0) > 0,
+ );
+ const isSensorRow = (row: NodeOverviewRow): boolean =>
+ row.label === 'NVMe' || row.label === 'GPU';
+
const technicalSections = () =>
compactDetailSections([
{ label: 'Platform', rows: toDetailRows(platformRows()) },
@@ -325,16 +370,22 @@ export function NodeDrawerOverview(props: NodeDrawerOverviewProps) {
: toDetailRows(storageRows()),
},
{ label: 'Telemetry', rows: toDetailRows(telemetryRows()) },
- { label: 'GPU', rows: toDetailRows(getGPUTelemetryRows(props.node)) },
{
label: 'Thermals',
- rows: toDetailRows(
- getThermalRows(
- props.node.temperature,
- props.temperatureThresholds,
- (props.node.sensors?.gpu?.length ?? 0) > 0,
- ),
- ),
+ rows: toDetailRows(thermalRows().filter((row) => !isSensorRow(row))),
+ },
+ ]);
+
+ // GPU and NVMe readings carry no heat judgement of their own, so nothing
+ // would lift a hot one out of Details; they stay visible instead.
+ const sensorSections = () =>
+ compactDetailSections([
+ {
+ label: 'Sensors',
+ rows: toDetailRows([
+ ...thermalRows().filter(isSensorRow),
+ ...getGPUTelemetryRows(props.node),
+ ]),
},
]);
@@ -347,7 +398,7 @@ export function NodeDrawerOverview(props: NodeDrawerOverviewProps) {
: '';
return compactDetailSections([
{
- label: 'Operator context',
+ label: 'Summary',
rows: compactDetailRows([
makeDetailRow('Platform', versionLabel() ? `PVE ${versionLabel()}` : null),
makeDetailRow(
@@ -371,8 +422,124 @@ export function NodeDrawerOverview(props: NodeDrawerOverviewProps) {
]);
};
+ const exceptionRows = createMemo(() =>
+ collectDrawerExceptionRows([...overviewSections(), ...technicalSections()]),
+ );
+
+ // The table withholds readings from an offline or stale node; the trend
+ // cards do the same instead of presenting the last numbers as live.
+ const liveReadingsWithheld = (): string | null => {
+ const health = (props.node.connectionHealth || '').trim().toLowerCase();
+ if (props.node.status === 'offline') return 'Node is offline. Showing its history only.';
+ if (
+ props.node.status === 'unknown' ||
+ health === 'error' ||
+ health === 'degraded' ||
+ health === 'stale'
+ ) {
+ return 'Proxmox readings for this node are stale. Showing its history only.';
+ }
+ return null;
+ };
+
+ const trendCards = (): DrawerTrendCardConfig[] => {
+ const card = (
+ metric: string,
+ label: string,
+ unit: DrawerTrendCardConfig['unit'],
+ current: number | undefined,
+ detail?: string,
+ deferred?: GuestDrawerHistoryDeferredMetric,
+ ): DrawerTrendCardConfig => {
+ const alert = getDrawerMetricAlert(props.metricAlerts, metric);
+ const withheld = liveReadingsWithheld();
+ return {
+ metric,
+ label,
+ unit,
+ color: hostSeriesColor(metric),
+ current: withheld ? undefined : current,
+ deferred: withheld ? { message: withheld } : deferred,
+ detail: withheld ? undefined : detail,
+ alertSeverity: alert?.severity,
+ alertThreshold: alert?.threshold,
+ };
+ };
+ const memory = props.node.memory;
+ const disk = props.node.disk;
+ // The adapter fills missing usage with zero; a known total is the
+ // evidence that a percentage was measured at all.
+ const memoryValue =
+ memory?.usageUnavailable || !((memory?.total ?? 0) > 0)
+ ? undefined
+ : finitePercent(memory?.usage);
+ // A retained or undated reading is shown as last known, the same rule the
+ // guest cards follow, rather than as a live value.
+ const memoryReading = getMemoryObservationPresentation(memoryValue, memory?.observation);
+ const memoryDeferred: GuestDrawerHistoryDeferredMetric | undefined =
+ memoryReading && memoryReading.state !== 'current'
+ ? {
+ lastKnownValue: memoryReading.state === 'unavailable' ? undefined : memoryValue,
+ ...(memoryReading.state === 'unknown'
+ ? { valueLabel: 'freshness unknown' as const }
+ : {}),
+ message: memoryReading.message,
+ }
+ : undefined;
+ const memoryCurrent = memoryDeferred ? undefined : memoryValue;
+ const diskMeasured = (disk?.total ?? 0) > 0;
+ const temperature = getCpuTemperature(props.node.temperature);
+ return [
+ card(
+ 'cpu',
+ 'CPU',
+ '%',
+ finitePercent(props.node.cpu),
+ loadAverageLabel() !== '-' ? `load ${props.node.loadAverage?.[0]?.toFixed(2)}` : undefined,
+ ),
+ card(
+ 'memory',
+ 'Memory',
+ '%',
+ memoryCurrent,
+ (memoryCurrent ?? memoryDeferred?.lastKnownValue) !== undefined
+ ? `${formatBytes(memory.used ?? 0)} of ${formatBytes(memory.total)}`
+ : undefined,
+ memoryDeferred,
+ ),
+ ...(typeof temperature === 'number'
+ ? [card('temperature', 'CPU temperature', 'C', temperature)]
+ : []),
+ card(
+ 'disk',
+ 'Root disk',
+ '%',
+ diskMeasured ? finitePercent(disk?.usage) : undefined,
+ diskMeasured
+ ? `${formatBytes(disk?.used ?? 0)} of ${formatBytes(disk?.total ?? 0)}`
+ : undefined,
+ ),
+ ];
+ };
+
+ const facts = () => {
+ const model = cleanText(props.node.cpuInfo?.model);
+ const cores = props.node.cpuInfo?.cores;
+ const firstAddress = (props.node.networkInterfaces || [])
+ .flatMap((networkInterface) => networkInterface.addresses || [])
+ .map((address) => cleanText(address))
+ .find(Boolean);
+ return [
+ versionLabel() ? `Proxmox VE ${versionLabel()}` : '',
+ [model, hasPositiveNumber(cores) ? `${cores} logical CPUs` : ''].filter(Boolean).join(' · '),
+ (props.node.memory?.total ?? 0) > 0 ? `${formatBytes(props.node.memory.total)} RAM` : '',
+ firstAddress ?? '',
+ clusterLabel() && clusterLabel() !== 'Standalone' ? `Cluster ${clusterLabel()}` : '',
+ ].filter((fact) => fact.trim().length > 0);
+ };
+
return (
- <div class="space-y-3">
+ <div class="space-y-3" data-testid="node-drawer-overview">
<DrawerAttentionSection
items={(props.alerts ?? []).map((alert) => ({
id: alert.id,
@@ -387,9 +554,50 @@ export function NodeDrawerOverview(props: NodeDrawerOverviewProps) {
acknowledged: alert.acknowledged,
}))}
/>
- <TechnicalDetailsSection
+ <Show when={(props.alerts ?? []).length === 0}>
+ <p data-testid="drawer-no-attention" class="text-xs font-medium text-base-content">
+ {ALERTS_EMPTY_STATE}
+ </p>
+ </Show>
+
+ <Show when={props.historyTarget}>
+ <Suspense fallback={<div class="h-28" aria-hidden="true" />}>
+ <DrawerTrendCards
+ target={props.historyTarget ?? null}
+ enabled={props.trendsEnabled ?? true}
+ cards={trendCards()}
+ />
+ </Suspense>
+ </Show>
+
+ <Show when={exceptionRows().length > 0}>
+ <TechnicalDetailsSection
+ dataTestId="node-drawer-exceptions"
+ sections={[{ label: 'Worth checking', rows: exceptionRows() }]}
+ />
+ </Show>
+
+ <Show when={sensorSections().length > 0}>
+ <TechnicalDetailsSection dataTestId="node-drawer-sensors" sections={sensorSections()} />
+ </Show>
+
+ <Show when={facts().length > 0}>
+ <div
+ data-testid="node-drawer-facts"
+ class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted"
+ >
+ <For each={facts()}>{(fact) => <span class="wrap-break-word">{fact}</span>}</For>
+ </div>
+ </Show>
+
+ <TechnicalDetailsDisclosure
dataTestId="node-technical-details"
- sections={[...overviewSections(), ...technicalSections()]}
+ title="Details"
+ keepMounted
+ subtitle="platform, hardware, memory, network, storage and sensors"
+ class="border-t border-border pt-2"
+ contentClass="mt-2"
+ sections={withoutDrawerExceptionRows([...overviewSections(), ...technicalSections()])}
/>
</div>
);
diff --git a/frontend-modern/src/components/Workloads/__tests__/DrawerTrendCards.test.tsx b/frontend-modern/src/components/Workloads/__tests__/DrawerTrendCards.test.tsx
new file mode 100644
index 0000000000..bffeb88f5d
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/DrawerTrendCards.test.tsx
@@ -0,0 +1,228 @@
+import { cleanup, render, screen, waitFor, within } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ChartsAPI, type AllMetricsHistoryResponse } from '@/api/charts';
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
+import DrawerTrendCards, { type DrawerTrendCardConfig } from '../DrawerTrendCards';
+
+afterEach(() => {
+ cleanup();
+ resetCreateNonSuspendingQueryCacheForTest();
+ vi.restoreAllMocks();
+});
+
+const start = Date.UTC(2026, 9, 12, 12);
+const target = { resourceType: 'vm' as const, resourceId: 'fixture:pve:281' };
+const point = (hour: number, value: number) => ({
+ timestamp: start + hour * 3_600_000,
+ value,
+ min: value,
+ max: value,
+});
+const response = (metrics: AllMetricsHistoryResponse['metrics']): AllMetricsHistoryResponse => ({
+ ...target,
+ range: '24h',
+ start,
+ end: start + 24 * 3_600_000,
+ source: 'store',
+ metrics,
+});
+const memoryCard = (overrides: Partial<DrawerTrendCardConfig> = {}): DrawerTrendCardConfig => ({
+ metric: 'memory',
+ label: 'Memory',
+ unit: '%',
+ color: '#f59e0b',
+ current: 85.4,
+ detail: '3.42 GB of 4.00 GB',
+ ...overrides,
+});
+const card = (metric = 'memory') => screen.getByTestId(`drawer-trend-card-${metric}`);
+
+describe('DrawerTrendCards', () => {
+ it('reads the 24h history once and shows the live value, the 24h range and the detail', async () => {
+ const fetch = vi
+ .spyOn(ChartsAPI, 'getMetricsHistory')
+ .mockResolvedValue(response({ memory: [point(0, 84), point(12, 84.6), point(23, 85.6)] }));
+ render(() => <DrawerTrendCards target={target} enabled cards={[memoryCard()]} />);
+
+ await waitFor(() => expect(card()).toHaveTextContent('24h: 84.0%–85.6%'));
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch.mock.calls[0][0]).toMatchObject({ ...target, range: '24h' });
+ expect(within(card()).getByText('85.4%')).toBeInTheDocument();
+ expect(card()).toHaveTextContent('3.42 GB of 4.00 GB');
+ expect(within(card()).getByRole('img')).toHaveAccessibleName(
+ 'Memory 85.4%, 84.0% to 85.6% over 24 hours',
+ );
+ // A current reading is not drawn as a trend point; three stored points.
+ expect(card().querySelector('path')?.getAttribute('d')?.match(/[ML]/g)).toHaveLength(3);
+ });
+
+ it("draws an active alert's own trigger and marks the card with its severity", async () => {
+ vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
+ response({ memory: [point(0, 84), point(23, 85.6)] }),
+ );
+ render(() => (
+ <DrawerTrendCards
+ target={target}
+ enabled
+ cards={[memoryCard({ alertSeverity: 'warning', alertThreshold: 85 })]}
+ />
+ ));
+
+ const threshold = await screen.findByTestId('drawer-trend-threshold');
+ // 0-100% scale on a 48px plot: 85% sits at 7.2px.
+ expect(Number(threshold.getAttribute('y1'))).toBeCloseTo(7.2, 1);
+ expect(card()).toHaveClass('border-amber-400');
+ });
+
+ it('labels a deferred reading as last known and says why, instead of calling it current', async () => {
+ vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
+ response({ memory: [point(0, 60), point(23, 62)] }),
+ );
+ render(() => (
+ <DrawerTrendCards
+ target={target}
+ enabled
+ cards={[
+ memoryCard({
+ current: undefined,
+ deferred: { lastKnownValue: 62, message: 'Guest reads are paused during a backup.' },
+ }),
+ ]}
+ />
+ ));
+
+ expect(within(card()).getByText('last known')).toBeInTheDocument();
+ expect(within(card()).getByText('62.0%')).toBeInTheDocument();
+ expect(card()).toHaveTextContent('Guest reads are paused during a backup.');
+ // The chart's accessible name carries the same qualifier as the visible value.
+ expect(await within(card()).findByRole('img')).toHaveAccessibleName(
+ 'Memory last known 62.0%, 60.0% to 62.0% over 24 hours',
+ );
+ });
+
+ it('says it is still collecting when no history has been stored', async () => {
+ vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(response({}));
+ render(() => <DrawerTrendCards target={target} enabled cards={[memoryCard()]} />);
+ await waitFor(() => expect(card()).toHaveTextContent('Collecting history'));
+ });
+
+ it('does not read history while its tab is hidden', async () => {
+ const fetch = vi
+ .spyOn(ChartsAPI, 'getMetricsHistory')
+ .mockResolvedValue(response({ memory: [point(0, 84), point(23, 85)] }));
+ const [enabled, setEnabled] = createSignal(false);
+ render(() => <DrawerTrendCards target={target} enabled={enabled()} cards={[memoryCard()]} />);
+
+ await Promise.resolve();
+ expect(fetch).not.toHaveBeenCalled();
+ setEnabled(true);
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
+ });
+
+ it('states a spike inside an averaged bucket, and does not call one reading steady', async () => {
+ vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
+ response({
+ memory: [
+ { timestamp: start, value: 50, min: 48, max: 99 },
+ { timestamp: start + 3_600_000, value: 51, min: 50, max: 52 },
+ ],
+ cpu: [point(0, 4)],
+ }),
+ );
+ render(() => (
+ <DrawerTrendCards
+ target={target}
+ enabled
+ cards={[memoryCard(), memoryCard({ metric: 'cpu', label: 'CPU', current: 4 })]}
+ />
+ ));
+ await waitFor(() => expect(card()).toHaveTextContent('24h: 48.0%–99.0%'));
+ expect(card('cpu')).toHaveTextContent('24h: one reading so far');
+ });
+
+ it("widens a temperature scale to the alert's trigger instead of clamping the line", async () => {
+ vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
+ response({ temperature: [point(0, 45), point(12, 55), point(23, 50)] }),
+ );
+ render(() => (
+ <DrawerTrendCards
+ target={target}
+ enabled
+ cards={[
+ {
+ metric: 'temperature',
+ label: 'CPU temperature',
+ unit: 'C',
+ color: '#ef4444',
+ current: 50,
+ alertSeverity: 'warning',
+ alertThreshold: 85,
+ },
+ ]}
+ />
+ ));
+ const threshold = await screen.findByTestId('drawer-trend-threshold');
+ const thresholdY = Number(threshold.getAttribute('y1'));
+ // Clamped to a 45-55°C scale the line would sit on the top edge (0).
+ expect(thresholdY).toBeGreaterThan(0);
+ const pathYs = (card('temperature').querySelector('path')?.getAttribute('d') ?? '')
+ .split(/[ML]/)
+ .filter(Boolean)
+ .map((pair) => Number(pair.split(',')[1]));
+ expect(Math.min(...pathYs)).toBeGreaterThan(thresholdY);
+ });
+
+ it('keeps an earlier trend after a failed refresh, and says so', async () => {
+ const fetch = vi
+ .spyOn(ChartsAPI, 'getMetricsHistory')
+ .mockResolvedValueOnce(response({ memory: [point(0, 84), point(23, 85)] }))
+ .mockRejectedValue(new Error('boom'));
+ const [enabled, setEnabled] = createSignal(true);
+ render(() => <DrawerTrendCards target={target} enabled={enabled()} cards={[memoryCard()]} />);
+ await waitFor(() => expect(card()).toHaveTextContent('24h: 84.0%–85.0%'));
+ setEnabled(false);
+ setEnabled(true);
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
+ await waitFor(() =>
+ expect(card()).toHaveTextContent('Refresh failed. Showing the last loaded trend.'),
+ );
+ expect(card()).toHaveTextContent('24h: 84.0%–85.0%');
+ });
+
+ it('stops polling while hidden and reads again when shown', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ const fetch = vi
+ .spyOn(ChartsAPI, 'getMetricsHistory')
+ .mockResolvedValue(response({ memory: [point(0, 84), point(23, 85)] }));
+ const [enabled, setEnabled] = createSignal(true);
+ render(() => <DrawerTrendCards target={target} enabled={enabled()} cards={[memoryCard()]} />);
+ const settle = async () => {
+ for (let i = 0; i < 5; i += 1) await Promise.resolve();
+ };
+ await settle();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(30_000);
+ await settle();
+ expect(fetch).toHaveBeenCalledTimes(2);
+ setEnabled(false);
+ vi.advanceTimersByTime(120_000);
+ await settle();
+ expect(fetch).toHaveBeenCalledTimes(2);
+ setEnabled(true);
+ await settle();
+ expect(fetch).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('says the trend is unavailable when the read fails, keeping the live value', async () => {
+ vi.spyOn(ChartsAPI, 'getMetricsHistory').mockRejectedValue(new Error('boom'));
+ render(() => <DrawerTrendCards target={target} enabled cards={[memoryCard()]} />);
+
+ await waitFor(() => expect(card()).toHaveTextContent('Trend unavailable'));
+ expect(within(card()).getByText('85.4%')).toBeInTheDocument();
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/GuestDrawer.backup-clock.test.tsx b/frontend-modern/src/components/Workloads/__tests__/GuestDrawer.backup-clock.test.tsx
index 0bf1b7c448..10694b86a6 100644
--- a/frontend-modern/src/components/Workloads/__tests__/GuestDrawer.backup-clock.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/GuestDrawer.backup-clock.test.tsx
@@ -1,5 +1,6 @@
import { cleanup, fireEvent, render, screen, within } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { WorkloadGuest } from '@/types/workloads';
import { RELATIVE_TIME_TICK_MS } from '@/utils/relativeTimeClock';
@@ -55,19 +56,45 @@ const guest = (type: 'qemu' | 'lxc', lastBackup: number): WorkloadGuest => ({
lock: '',
lastSeen: new Date(start).toISOString(),
});
-const details = () => within(screen.getByTestId('guest-technical-details'));
+// Details is closed by default and a late backup is lifted into Worth
+// checking, so read the whole Overview with Details open.
+const details = () => {
+ const disclosure = screen.getByTestId('guest-technical-details') as HTMLDetailsElement;
+ if (!disclosure.open) {
+ disclosure.open = true;
+ // jsdom queues the native toggle event as a zero-delay task.
+ vi.advanceTimersByTime(0);
+ }
+ return within(screen.getByTestId('guest-drawer-overview'));
+};
const backupRow = () => details().getByText('Last completed backup').closest('tr')!;
const completion = () => backupRow().querySelector('time');
+// Overview's 24h trend cards read history by design. Backup age is judged by
+// the local clock, so no other history read (a History tab range) happens.
+const expectOnlyTrendReads = () =>
+ expect(calls.history.mock.calls.every(([params]) => params?.range === '24h')).toBe(true);
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(start);
policy.freshHours = 24;
policy.staleHours = 72;
- calls.history.mockClear();
+ calls.history.mockReset();
+ calls.history.mockResolvedValue({
+ resourceType: 'vm',
+ resourceId: 'lab:pve-a:101',
+ range: '24h',
+ start: 0,
+ end: 0,
+ metrics: {},
+ source: 'store',
+ });
});
afterEach(() => {
cleanup();
+ // The Overview's 24h trend read leaves the shared query cache's expiry
+ // timer behind; it is module state, not a timer this drawer owns.
+ resetCreateNonSuspendingQueryCacheForTest();
expect(vi.getTimerCount()).toBe(0);
vi.useRealTimers();
});
@@ -101,7 +128,7 @@ describe('mounted completed-backup evidence', () => {
expect(within(backupRow()).getByText('1d ago').closest('td')).toHaveClass('text-amber-700');
expect(completion()).toHaveAttribute('datetime', new Date(timestamp).toISOString());
expect(screen.getByTestId('guest-technical-details')).toBe(drawer);
- expect(calls.history).not.toHaveBeenCalled();
+ expectOnlyTrendReads();
},
);
@@ -114,7 +141,7 @@ describe('mounted completed-backup evidence', () => {
expect(details().getByText('59 mins ago').closest('td')).toHaveClass('text-emerald-700');
vi.advanceTimersByTime(RELATIVE_TIME_TICK_MS);
expect(details().getByText('1 hour ago').closest('td')).toHaveClass('text-amber-700');
- expect(calls.history).not.toHaveBeenCalled();
+ expectOnlyTrendReads();
},
);
@@ -148,7 +175,7 @@ describe('mounted completed-backup evidence', () => {
expect(completion()).toHaveAttribute('datetime', '2026-10-12T12:00:30.000Z');
vi.advanceTimersByTime(60_000);
expect(details().getByText('1 min ago')).toBeVisible();
- expect(calls.history).not.toHaveBeenCalled();
+ expectOnlyTrendReads();
});
it('rejudges future and backwards-clock times without manufacturing completion', () => {
@@ -174,7 +201,7 @@ describe('mounted completed-backup evidence', () => {
).toHaveClass('text-amber-700');
expect(completion()).toBeNull();
expect(details().queryByText('No completed backup found')).not.toBeInTheDocument();
- expect(calls.history).not.toHaveBeenCalled();
+ expectOnlyTrendReads();
});
it.each([0, NaN, Infinity])(
@@ -185,7 +212,7 @@ describe('mounted completed-backup evidence', () => {
vi.advanceTimersByTime(60_000);
expect(backupRow()).toHaveTextContent(initial!);
expect(completion()).toBeNull();
- expect(calls.history).not.toHaveBeenCalled();
+ expectOnlyTrendReads();
},
);
});
diff --git a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.source-isolation.test.tsx b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.source-isolation.test.tsx
index e5c16ba3d6..a3c1c7a3a6 100644
--- a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.source-isolation.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.source-isolation.test.tsx
@@ -6,6 +6,7 @@ import {
createNonSuspendingQuery,
resetCreateNonSuspendingQueryCacheForTest,
} from '@/hooks/createNonSuspendingQuery';
+import DrawerTrendCards from '../DrawerTrendCards';
import { GuestDrawerHistory } from '../GuestDrawerHistory';
import type { GuestDrawerHistoryTarget } from '../guestDrawerModel';
@@ -234,4 +235,35 @@ describe('GuestDrawerHistory source isolation', () => {
view.unmount();
expect(active!.aborted).toBe(true);
});
+
+ it.each([
+ ['opens on', '24h', 1],
+ ['does not borrow', '6h', 0],
+ ] as const)(
+ "%s the Overview trend's read for the same target when the range is %s",
+ async (_label, range, expectedPaths) => {
+ const fetch = vi
+ .spyOn(ChartsAPI, 'getMetricsHistory')
+ .mockResolvedValueOnce(response('host-shared'))
+ .mockImplementation(() => new Promise(() => {}));
+ const target = { resourceType: 'agent' as const, resourceId: 'host-shared' };
+ const overview = render(() => (
+ <DrawerTrendCards
+ target={target}
+ enabled
+ cards={[{ metric: 'cpu', label: 'CPU', unit: '%', color: '#8b5cf6', current: 88 }]}
+ />
+ ));
+ await waitFor(() =>
+ expect(screen.getByTestId('drawer-trend-card-cpu')).toHaveTextContent('24h: 87.0%–88.0%'),
+ );
+ overview.unmount();
+
+ // The History tab's own read never settles here: anything it draws came
+ // from the Overview's read through the shared query cache key.
+ const { container } = render(() => <GuestDrawerHistory target={target} range={range} />);
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
+ expect(paths(container)).toHaveLength(expectedPaths);
+ },
+ );
});
diff --git a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.agent-state.test.tsx b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.agent-state.test.tsx
index 21011baffc..c0e662b268 100644
--- a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.agent-state.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.agent-state.test.tsx
@@ -1,7 +1,18 @@
-import { cleanup, render, screen, within } from '@solidjs/testing-library';
+import { cleanup, render as solidRender, screen, within } from '@solidjs/testing-library';
import { createSignal, type ComponentProps } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { GuestDrawerOverview } from '../GuestDrawerOverview';
+
+// Coverage and read rows live in the Overview's Details, closed by default.
+// Opening it is a tap, not a hover, so these explanations stay reachable.
+const render = (...args: Parameters<typeof solidRender>): ReturnType<typeof solidRender> => {
+ const result = solidRender(...args);
+ const details = result.container.querySelector<HTMLDetailsElement>(
+ '[data-testid="guest-technical-details"]',
+ );
+ if (details) details.open = true;
+ return result;
+};
import type { WorkloadGuest } from '@/types/workloads';
import type { VM } from '@/types/api';
import {
@@ -58,7 +69,13 @@ function overviewProps(value: WorkloadGuest): ComponentProps<typeof GuestDrawerO
};
}
-const readRow = () => screen.getByText('Guest-agent reads').closest('tr')!;
+const readRow = () => {
+ const row = screen.getByText('Guest-agent reads').closest('tr')!;
+ // Details is closed by default; opening it is a tap, not a hover.
+ const details = row.closest('details');
+ if (details) details.open = true;
+ return row;
+};
afterEach(cleanup);
diff --git a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.filesystems.test.tsx b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.filesystems.test.tsx
index c0deca4921..01f92d7ac8 100644
--- a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.filesystems.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerOverview.filesystems.test.tsx
@@ -144,8 +144,5 @@ describe('GuestDrawerOverview filesystem labels', () => {
).toBeNull();
expect(screen.getByText(/— · \?\/10.0 GB · MP1/)).toBeInTheDocument();
expect(screen.getByText('CPUs').closest('tr')).toHaveClass('lg:grid-cols-[7rem_minmax(0,1fr)]');
- expect(screen.getByText('Values').closest('tr')).toHaveClass(
- 'lg:grid-cols-[7rem_minmax(0,1fr)]',
- );
});
});
diff --git a/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx b/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx
index c505e6d157..621635fa86 100644
--- a/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx
@@ -1706,19 +1706,22 @@ describe('Workloads performance contract', () => {
expect(guestDrawerOverviewSource).not.toMatch(
/^import (?!type )[^;]*from '\.\/GuestPhysicalDisks';/m,
);
- // The shared DetailSectionTable gives the earlier of the last two sections
- // the wider span, so the longer filesystem list must be declared before the
- // short tag list for mount points to get the readable panel width.
+ // Filesystems render as their own section in front of the collapsed
+ // Details, so mount points never share a card row with short sections.
+ // Tags render as facts-strip chips, not as a detail section.
const filesystemsSectionIndex = guestDrawerOverviewSource.indexOf("label: 'Filesystems'");
- const tagsSectionIndex = guestDrawerOverviewSource.indexOf("label: 'Tags'");
expect(filesystemsSectionIndex).toBeGreaterThan(-1);
- expect(tagsSectionIndex).toBeGreaterThan(-1);
- expect(filesystemsSectionIndex).toBeLessThan(tagsSectionIndex);
- // Ordering cannot prevent the compact label column from clipping paths.
+ expect(guestDrawerOverviewSource).not.toContain("label: 'Tags'");
+ expect(guestDrawerOverviewSource).toContain('dataTestId="guest-drawer-filesystems"');
+ // The 24h trend cards load with an open drawer, outside the table chunk.
+ expect(guestDrawerOverviewSource).toContain("import('./DrawerTrendCards')");
+ expect(guestDrawerOverviewSource).not.toMatch(
+ /^import (?!type )[^;]*from '\.\/DrawerTrendCards';/m,
+ );
// Filesystem rows delegate full-path presentation to the shared renderer.
const filesystemSectionSource = guestDrawerOverviewSource.slice(
filesystemsSectionIndex,
- tagsSectionIndex,
+ guestDrawerOverviewSource.indexOf('label:', filesystemsSectionIndex + 1),
);
expect(filesystemSectionSource).toContain("layout: 'stacked'");
expect(filesystemSectionSource).toContain('wrap: true');
diff --git a/frontend-modern/src/components/Workloads/__tests__/drawerOverviewModel.test.ts b/frontend-modern/src/components/Workloads/__tests__/drawerOverviewModel.test.ts
new file mode 100644
index 0000000000..2e24d45884
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/drawerOverviewModel.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+import type { DetailSection } from '@/components/shared/detailSectionModel';
+import type { Alert } from '@/types/api';
+import {
+ collectDrawerExceptionRows,
+ getDrawerMetricAlert,
+ isDrawerAvailabilityHealthy,
+ withoutDrawerExceptionRows,
+} from '../drawerOverviewModel';
+
+const alert = (overrides: Partial<Alert>): Alert =>
+ ({ id: 'a', type: 'memory', level: 'warning', threshold: 85, ...overrides }) as Alert;
+
+describe('getDrawerMetricAlert', () => {
+ it('matches the metric and prefers a critical alert over a warning', () => {
+ expect(
+ getDrawerMetricAlert(
+ [
+ alert({ id: 'w', level: 'warning', threshold: 85 }),
+ alert({ id: 'c', level: 'critical', threshold: 95 }),
+ alert({ id: 'w2', level: 'warning', threshold: 80 }),
+ ],
+ 'memory',
+ ),
+ ).toEqual({ severity: 'critical', threshold: 95 });
+ });
+
+ it('ignores other metrics and info-level alerts', () => {
+ expect(
+ getDrawerMetricAlert([alert({ type: 'cpu' }), alert({ level: 'info' })], 'memory'),
+ ).toBeUndefined();
+ });
+
+ it('drops a non-finite threshold rather than drawing a line at NaN', () => {
+ expect(getDrawerMetricAlert([alert({ threshold: Number.NaN })], 'memory')).toEqual({
+ severity: 'warning',
+ threshold: undefined,
+ });
+ });
+});
+
+describe('drawer exception rows', () => {
+ const sections: DetailSection[] = [
+ {
+ label: 'Summary',
+ rows: [
+ { label: 'System', value: 'Debian' },
+ { label: 'Updates', value: 'Unavailable', tone: 'warning' },
+ ],
+ },
+ {
+ label: 'Thermals',
+ rows: [{ label: 'CPU record', value: '91°C', tone: 'danger' }],
+ },
+ { label: 'Telemetry', rows: [{ label: 'Status', value: 'Stopped', tone: 'warning' }] },
+ ];
+
+ it('lifts warning and danger rows from every section, once each', () => {
+ expect(collectDrawerExceptionRows([...sections, sections[0]]).map((row) => row.label)).toEqual([
+ 'Updates',
+ 'CPU record',
+ 'Status',
+ ]);
+ });
+
+ it('moves lifted rows out of Details and drops sections they emptied', () => {
+ const remaining = withoutDrawerExceptionRows(sections);
+ expect(remaining.map((section) => section.label)).toEqual(['Summary']);
+ expect(remaining[0].rows.map((row) => row.label)).toEqual(['System']);
+ });
+});
+
+describe('isDrawerAvailabilityHealthy', () => {
+ const now = Date.parse('2026-10-13T10:00:00Z');
+ const fresh = { pollIntervalSeconds: 30, lastChecked: '2026-10-13T09:59:30Z' };
+
+ it('judges a fresh check by the aggregate state when present, else by availability', () => {
+ expect(
+ isDrawerAvailabilityHealthy({ ...fresh, aggregateState: 'healthy', available: false }, now),
+ ).toBe(true);
+ expect(
+ isDrawerAvailabilityHealthy({ ...fresh, aggregateState: 'degraded', available: true }, now),
+ ).toBe(false);
+ expect(isDrawerAvailabilityHealthy({ ...fresh, available: true }, now)).toBe(true);
+ expect(isDrawerAvailabilityHealthy({ ...fresh }, now)).toBe(false);
+ });
+
+ it('does not call an expired or undated success passing', () => {
+ // Two missed polls: the success is stale evidence.
+ expect(
+ isDrawerAvailabilityHealthy(
+ { available: true, pollIntervalSeconds: 30, lastChecked: '2026-10-13T09:58:00Z' },
+ now,
+ ),
+ ).toBe(false);
+ expect(
+ isDrawerAvailabilityHealthy(
+ { available: true, evidence: { validUntil: '2026-10-13T09:59:00Z' } } as never,
+ now,
+ ),
+ ).toBe(false);
+ // No interval and no validity window: freshness is unknown, not passing.
+ expect(isDrawerAvailabilityHealthy({ available: true }, now)).toBe(false);
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/filesystemUsage.evidence.test.tsx b/frontend-modern/src/components/Workloads/__tests__/filesystemUsage.evidence.test.tsx
index 4ffbe725b5..a531f26e16 100644
--- a/frontend-modern/src/components/Workloads/__tests__/filesystemUsage.evidence.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/filesystemUsage.evidence.test.tsx
@@ -141,7 +141,7 @@ describe('both filesystem panels preserve unavailable versus measured zero', ()
'does not show an empty healthy disk for %s',
(_name, values) => {
renderPanels(disk(values));
- for (const id of ['disk-list-panel', 'guest-technical-details']) {
+ for (const id of ['disk-list-panel', 'guest-drawer-filesystems']) {
const panel = screen.getByTestId(id);
expect(panel.textContent).toContain('—');
expect(panel.textContent).not.toMatch(/0%|NaN|Infinity/);
@@ -152,7 +152,7 @@ describe('both filesystem panels preserve unavailable versus measured zero', ()
it('withdraws a prior measurement and restores zero only after explicit same-filesystem evidence', () => {
const update = renderPanels(disk());
- const details = screen.getByTestId('guest-technical-details');
+ const details = screen.getByTestId('guest-drawer-filesystems');
expect(within(details).getByRole('progressbar')).toHaveAttribute('aria-valuenow', '50');
update(disk({ used: undefined }));
expect(within(details).queryByRole('progressbar')).not.toBeInTheDocument();
diff --git a/frontend-modern/src/components/Workloads/drawerOverviewModel.ts b/frontend-modern/src/components/Workloads/drawerOverviewModel.ts
new file mode 100644
index 0000000000..b636387df4
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/drawerOverviewModel.ts
@@ -0,0 +1,85 @@
+import {
+ compactDetailSections,
+ type DetailRow,
+ type DetailSection,
+} from '@/components/shared/detailSectionModel';
+import type { Alert } from '@/types/api';
+import type { ResourceAvailabilityMeta } from '@/types/resource';
+import { getAvailabilityProbePresentation } from '@/utils/availabilityProbePresentation';
+
+export interface DrawerMetricAlert {
+ severity: 'warning' | 'critical';
+ threshold?: number;
+}
+
+// An active alert on a trend card's metric colours that card and draws the
+// alert's own trigger. The most severe active alert wins.
+export const getDrawerMetricAlert = (
+ alerts: readonly Alert[] | undefined,
+ metric: string,
+): DrawerMetricAlert | undefined => {
+ let result: DrawerMetricAlert | undefined;
+ for (const alert of alerts ?? []) {
+ if (alert.type.trim().toLowerCase() !== metric || alert.level === 'info') continue;
+ const severity = alert.level === 'critical' ? 'critical' : 'warning';
+ if (result?.severity === 'critical' && severity === 'warning') continue;
+ result = {
+ severity,
+ threshold:
+ typeof alert.threshold === 'number' && Number.isFinite(alert.threshold)
+ ? alert.threshold
+ : undefined,
+ };
+ }
+ return result;
+};
+
+const isExceptionRow = (row: DetailRow): boolean => row.tone === 'warning' || row.tone === 'danger';
+
+// The drawer demotes inventory to a collapsed Details section, but a fact that
+// says something is wrong or untrustworthy must stay in front whichever section
+// owns it. Detail rows already carry that judgement as a warning/danger tone.
+export const collectDrawerExceptionRows = (sections: readonly DetailSection[]): DetailRow[] => {
+ const seen = new Set<string>();
+ const rows: DetailRow[] = [];
+ for (const section of sections) {
+ for (const row of section.rows) {
+ if (!isExceptionRow(row)) continue;
+ const key = `${row.label}\u0000${row.value}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ rows.push(row);
+ }
+ }
+ return rows;
+};
+
+// Lifted rows move rather than repeat: each fact appears once in the drawer.
+export const withoutDrawerExceptionRows = (sections: readonly DetailSection[]): DetailSection[] =>
+ compactDetailSections(
+ sections.map((section) => ({
+ ...section,
+ rows: section.rows.filter((row) => !isExceptionRow(row)),
+ })),
+ );
+
+// "Passing" needs a healthy result that is still fresh. A success whose
+// evidence has expired, or whose freshness is unknown, is not summarised away:
+// its card stays in front, where it says Stale.
+export const isDrawerAvailabilityHealthy = (
+ check: ResourceAvailabilityMeta,
+ now: number,
+): boolean => {
+ const up = check.aggregateState ? check.aggregateState === 'healthy' : check.available === true;
+ if (!up) return false;
+ const presentation = getAvailabilityProbePresentation(
+ {
+ type: 'network-endpoint',
+ platformType: 'availability',
+ status: 'online',
+ availability: check,
+ },
+ new Date(now),
+ );
+ return presentation?.freshnessLabel === 'fresh';
+};
diff --git a/frontend-modern/src/components/Workloads/guestDrawerHistoryQuery.ts b/frontend-modern/src/components/Workloads/guestDrawerHistoryQuery.ts
new file mode 100644
index 0000000000..05a8068735
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/guestDrawerHistoryQuery.ts
@@ -0,0 +1,106 @@
+import { createMemo, type Accessor } from 'solid-js';
+
+import {
+ ChartsAPI,
+ type AllMetricsHistoryResponse,
+ type HistoryTimeRange,
+ type ResourceType,
+ type SingleMetricHistoryResponse,
+} from '@/api/charts';
+import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
+
+import {
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ type GuestDrawerHistoryTarget,
+} from './guestDrawerModel';
+
+export const GUEST_DRAWER_HISTORY_MAX_POINTS = 240;
+export const GUEST_DRAWER_HISTORY_POLL_MS = 30_000;
+
+export interface GuestDrawerHistoryQueryKey {
+ resourceType: ResourceType;
+ resourceId: string;
+ range: HistoryTimeRange;
+}
+
+const EMPTY_HISTORY_RESPONSE: AllMetricsHistoryResponse = {
+ resourceType: '',
+ resourceId: '',
+ range: GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ start: 0,
+ end: 0,
+ metrics: {},
+ source: 'store',
+};
+
+const normalizeHistoryResponse = (
+ result: SingleMetricHistoryResponse | AllMetricsHistoryResponse,
+): AllMetricsHistoryResponse => {
+ if ('metrics' in result) return result;
+ return {
+ resourceType: result.resourceType,
+ resourceId: result.resourceId,
+ range: result.range,
+ start: result.start,
+ end: result.end,
+ metrics: { [result.metric]: result.points ?? [] },
+ source: result.source,
+ };
+};
+
+// Snapshot replacement often creates a new target object with unchanged
+// coordinates. Only a real target/range/access change owns a new read.
+export const createGuestDrawerHistorySource = (
+ target: Accessor<GuestDrawerHistoryTarget | null>,
+ range: Accessor<HistoryTimeRange>,
+ enabled: Accessor<boolean>,
+): Accessor<GuestDrawerHistoryQueryKey | null> =>
+ createMemo<GuestDrawerHistoryQueryKey | null>(
+ () => {
+ const current = target();
+ if (!current || !enabled()) return null;
+ return {
+ resourceType: current.resourceType,
+ resourceId: current.resourceId,
+ range: range(),
+ };
+ },
+ null,
+ {
+ equals: (previous, next) =>
+ previous === next ||
+ Boolean(
+ previous &&
+ next &&
+ previous.resourceType === next.resourceType &&
+ previous.resourceId === next.resourceId &&
+ previous.range === next.range,
+ ),
+ },
+ );
+
+// The drawer's Overview trends and its History tab read one resource's
+// metrics-store history through this query. The shared cache key lets the
+// History tab open on the Overview's 24h read instead of starting another.
+export const createGuestDrawerHistoryQuery = (
+ source: Accessor<GuestDrawerHistoryQueryKey | null>,
+) =>
+ createNonSuspendingQuery<AllMetricsHistoryResponse, GuestDrawerHistoryQueryKey>({
+ source,
+ fetcher: async (key, signal) =>
+ normalizeHistoryResponse(
+ await ChartsAPI.getMetricsHistory({
+ resourceType: key.resourceType,
+ resourceId: key.resourceId,
+ range: key.range,
+ maxPoints: GUEST_DRAWER_HISTORY_MAX_POINTS,
+ signal,
+ }),
+ ),
+ initialValue: EMPTY_HISTORY_RESPONSE,
+ cacheKey: (key) => `guest-drawer-history:${key.resourceType}:${key.resourceId}:${key.range}`,
+ // Former-host or former-range observations are not evidence for this
+ // target. Matching cached reads and same-source polling remain retained.
+ retainPreviousValueOnSourceChange: false,
+ pollMs: GUEST_DRAWER_HISTORY_POLL_MS,
+ });
diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
index 8c6211f907..da004b459c 100644
--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
@@ -8761,7 +8761,10 @@ describe('shared primitive guardrails', () => {
'src/components/shared/TechnicalDetailsDisclosure.tsx',
);
expect(disclosureSource).toContain('onToggle');
- expect(disclosureSource).toContain('<Show when={expanded()}>');
+ // Lazily mounted by default; keepMounted is an explicit opt-in for a
+ // disclosure that holds a surface's complete record (drawer Details).
+ expect(disclosureSource).toContain('<Show when={props.keepMounted || expanded()}>');
+ expect(disclosureSource).toContain('keepMounted?: boolean;');
expect(disclosureSource).toContain('sections?: DetailSection[]');
expect(disclosureSource).toContain('<DetailSectionTable');
expect(disclosureSource).toContain('export const TechnicalDetailsSection');
diff --git a/frontend-modern/src/components/shared/TechnicalDetailsDisclosure.tsx b/frontend-modern/src/components/shared/TechnicalDetailsDisclosure.tsx
index b6866064e0..411cb1585a 100644
--- a/frontend-modern/src/components/shared/TechnicalDetailsDisclosure.tsx
+++ b/frontend-modern/src/components/shared/TechnicalDetailsDisclosure.tsx
@@ -9,6 +9,12 @@ interface TechnicalDetailsDisclosureProps {
dataTestId: string;
class?: string;
contentClass?: string;
+ /**
+ * Keep the content in the document while the disclosure is closed. A closed
+ * native <details> still hides it, and browser find-in-page can open it.
+ * Use where the collapsed content is the surface's complete record.
+ */
+ keepMounted?: boolean;
}
interface TechnicalDetailsSectionProps {
@@ -51,11 +57,17 @@ export const TechnicalDetailsDisclosure: Component<TechnicalDetailsDisclosurePro
class={props.class ?? 'rounded-sm border border-border bg-surface px-2 py-1.5'}
onToggle={(event) => setExpanded(event.currentTarget.open)}
>
- <summary class="cursor-pointer list-none text-[11px] font-medium text-base-content">
+ <summary class="flex min-h-11 cursor-pointer list-none flex-wrap items-center text-[11px] font-medium text-base-content sm:min-h-0">
+ <span
+ aria-hidden="true"
+ class={`mr-1 inline-block text-muted transition-transform ${expanded() ? 'rotate-90' : ''}`}
+ >
+ ›
+ </span>
{props.title ?? 'Technical details'}
<span class="ml-2 font-normal text-muted">{props.subtitle}</span>
</summary>
- <Show when={expanded()}>
+ <Show when={props.keepMounted || expanded()}>
<div class={props.contentClass ?? 'mt-2 border-t border-border pt-2'}>
<TechnicalDetailsContent sections={props.sections} children={props.children} />
</div>
diff --git a/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx b/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
index 6d606cc387..12baa33eff 100644
--- a/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
+++ b/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
@@ -823,6 +823,13 @@ export const ProxmoxNodesTable: Component<{
alertsEnabled(),
node.name,
)}
+ // Without the node-name match: the node's own alerts,
+ // not its guests', drive its trend cards.
+ ownAlerts={getAlertsForResource(
+ alertResourceIds(),
+ activeAlerts,
+ alertsEnabled(),
+ )}
disks={normalizeDiskArray(node.agent?.disks)}
temperatureThresholds={temperatureThresholds()}
/>