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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Lead alert cards and Patrol with the live reading of held alerts
rcourtman991948f28b4f
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 1f82e68833..f2b5fa5736 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -4653,6 +4653,21 @@ Assistant receives a selected attention item only after the operator opens it.The handoff is explanation-only and cannot infer a capability, approve anaction, or replace evidence and lifecycle truth.+A held threshold alert's attention summary leads with the live reading (issue+#2068). An alert's `Message` keeps the last breach while the alert waits below+its trigger for the clear level, so for a `MetricStatus` in the `latched` or+`recovering` phase that is under ten minutes old, the projection builds+`plainLanguageSummary` from the status instead: the reading now, then for a+latched alert the alert level it is back under and the clear level with its+hold, and for a recovering alert the clear level, delay and progress so far+(rounded down). The words and rounding follow the frontend's+`features/alerts/metricAlertPresentation.ts`, and a guest's disk is named+from `metadata.label`. Temperatures stay in °C like the alert messages,+because the server does not know a viewer's unit preference. A breaching+alert keeps `Message`, which tracks the breach, and a stale or missing status+falls back to it. The Patrol inbox, the investigation handoff and API clients+read that summary, so none of them re-derives the phase.+### Patrol model-readiness evidenceKeep the Patrol model-readiness advisor provider-neutral and evidence-based.diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 043df12ec8..9854905d3a 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -32,6 +32,23 @@ day is not auto-resolved as unmonitored. Frontend surfaces format the statusthrough `features/alerts/metricAlertPresentation.ts` and never re-derive thephase or recovery timing.+### Alert card and open incident lead with the live reading — issue #2068++The Alerts overview card leads an open threshold alert with the presentation's+summary and clear rule, keeps the last breach as the summary's hover text, and+labels the alert and clear levels in the status's unit (temperatures follow+the viewer's °C/°F preference, as every frontend reading does). Without a live+status it keeps the message and labels an alert level only for metric types+whose unit is known; other thresholds (queue ages, counts) are stated in their+own message, so the card never guesses a percent. The resource incident panel+describes only the open occurrence whose `alertIdentifier` and `openedAt`+match an active alert's id and `startTime` (the incident store's occurrence+key), from that alert's live status, rechecked on the shared relative-time+clock so it turns stale when evaluations stop; closed occurrences keep their+recorded message. Every disk alert on a guest carries the guest's name, so the+presentation names the disk from `metadata.label`, as the per-disk message+does.+### Retained guest observations are not alert evidenceGuest memory marked `last-known`, `unavailable` or an unknown observation statediff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 4286b59290..f1e42c6366 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -30,6 +30,18 @@ and `title`, and `getTemperatureTextClass` treats an open alert's severity asa floor: a reading that has dipped under an open alert's trigger keeps thealert's tone, while the reading still wins when it is worse.+### Alert card and incident panel format held alerts through one helper — issue #2068++`AlertOverviewAlertCard` and `AlertResourceIncidentsPanel` describe an open+threshold alert through `features/alerts/metricAlertPresentation.ts`+(summary, clear rule, `alertLevel` and `clearLevel`) instead of their own unit+guesses or the breach message. `useAlertHistoryState` exposes its active-alert+accessor so the incident panel matches its open occurrence to the live alert+without a second store read, and the panel reads `useRelativeTimeNow` so a+reading that stops updating turns stale on screen. From the `sm` breakpoint the+card's text column keeps a 16rem floor and breaks long words, so the action+buttons wrap instead of squeezing the reading to its longest word beside them.+### Canonical drawer History preserves guest read provenanceThe shared resource drawer passes selected memory observation state/source/timediff --git a/frontend-modern/browser-verification/811c71b54c36777b.json b/frontend-modern/browser-verification/811c71b54c36777b.jsonnew file mode 100644index 0000000000..cfb96ffcd7--- /dev/null+++ b/frontend-modern/browser-verification/811c71b54c36777b.json@@ -0,0 +1,61 @@+{+ "version": 1,+ "base_sha": "3ca8b9647ab992101adf9153b71b5ef1757ac82f",+ "verified_at": "2026-10-06T19:34:00Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx",+ "frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx",+ "frontend-modern/src/features/alerts/metricAlertPresentation.ts",+ "frontend-modern/src/features/alerts/useAlertHistoryState.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx": "bae52439900c395e8c7d33f87296e6c3d4f449e15fcf1dc69a0137111025d0ab",+ "frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx": "6c8347cb65f80520711f9f4b66b2c46e09c51121bf67e9ec382bce67ca3468a6",+ "frontend-modern/src/features/alerts/metricAlertPresentation.ts": "1b7314213d79cdfbad9f84b854ae8652802ad6c2d51955586c175475a024dbee",+ "frontend-modern/src/features/alerts/useAlertHistoryState.ts": "5b9f10978f2d2d7101f92343e826bef9ae5e2677b36ccf431ff0e6dfa9d676a8"+ },+ "routes": [+ "/alerts/overview",+ "/alerts/history",+ "/patrol"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 900+ },+ {+ "width": 1024,+ "height": 607+ },+ {+ "width": 768,+ "height": 1024+ },+ {+ "width": 375,+ "height": 812+ }+ ],+ "states": [+ "Private mock stack (sidecar build, uncommitted generator overlay pinning pve2 CPU temperature; alert level 80\u00b0C, clear level 75\u00b0C, 5 minute recovery delay)",+ "Alerts overview card, breaching at 95\u00b0C: \"Temperature 95\u00b0C, above the 80\u00b0C alert level\", clear rule detail, \"Alert level 80\u00b0C\" and \"Clear level 75\u00b0C\"",+ "Alerts overview card, held at 78\u00b0C: \"Temperature 78\u00b0C now, back under the 80\u00b0C alert level\" with hover \"Last reading at or above 80\u00b0C: 95\u00b0C\"; message \"Node temperature at 95.0\u00b0C\" no longer shown",+ "Alerts overview card, recovering at 72\u00b0C: \"Temperature 72\u00b0C now, recovering\" and \"Clears after 5 minutes at 75\u00b0C or lower, 2 minutes so far.\" at 1280px and 375px (no horizontal scroll)",+ "Fahrenheit preference: held card reads \"Temperature 172\u00b0F now, back under the 176\u00b0F alert level\", \"Alert level 176\u00b0F\", \"Clear level 167\u00b0F\", hover \"Last reading at or above 176\u00b0F: 203\u00b0F\"",+ "Mail Gateway queue-age card keeps its message and no longer shows a guessed \"30%\" level; breaching memory card shows \"Memory 85%, above the 85% alert level\" with its levels",+ "Card layout at 1024px: text column 256px with actions wrapped to two rows (was 110-160px beside one row); a 66-character resource name truncates with no overflow; 1280px unchanged (one row of actions); 768px text 256px, no overflow; 375px stacked, no horizontal scroll",+ "Card removed after the alert resolved",+ "History resource incidents panel: the open occurrence whose id and start match the live alert shows the live summary with the breach on hover; a cached open occurrence with an earlier start and closed occurrences keep their recorded messages (incident list extended in-page because mock mode never records open occurrences)",+ "Patrol inbox row for pve2 shows the held summary from plainLanguageSummary; API shows recovering summary, breaching pve3 keeps its message, resolved pve2 keeps \"Resolved: Node temperature at 72.0\u00b0C\""+ ],+ "interactions": [+ "Walked pve2 temperature 95 -> 78 -> 72 via the control file and reloaded the overview between phases; repeated 95 -> 78 after the final rebuild",+ "Read card text and hover titles in each phase",+ "Switched the temperature unit to Fahrenheit (localStorage temperatureUnit) and reloaded",+ "Measured card column widths and overflow at 1280, 1024, 768 and 375 px, with a long resource name substituted in the DOM",+ "Opened the pve2 Resource incidents panel from the History table row and pressed Refresh",+ "Opened Patrol inbox and read the pve2 row"+ ]+}diff --git a/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx b/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsxindex 9c82fe010e..870d095c84 100644--- a/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx+++ b/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx@@ -28,12 +28,14 @@ import {import { alertTypeDisplayLabel } from './helpers';import { describeAlertDeliveryStatus } from './deliveryDiagnosisPresentation';import { getCanonicalAlertId } from './identity';+import { getMetricAlertPresentation } from './metricAlertPresentation';import type { AlertIncidentTimelineState } from './useAlertIncidentTimelineState';import type { AlertOverviewState } from './useAlertOverviewState';import { ResourceMonitoringPolicyAction } from './ResourceMonitoringPolicyAction';import { AlertSnoozeAction } from './AlertSnoozeAction';import { isAlertSnoozed } from './useAlertSnoozeState';import { isPulseSystemAlert } from '@/utils/alertScope';+import { formatTemperature } from '@/utils/temperature';import {normalizeSourcePlatformQueryValue,resolvePlatformTypeFromSources,@@ -82,6 +84,23 @@ const PLATFORM_PAGE_PATHS: Record<PrimaryPlatformNavId, string> = {standalone: buildStandalonePath(),};+// Units of the threshold metrics, matching the evaluator's metric status unit.+const THRESHOLD_UNIT_BY_ALERT_TYPE: Record<string, string> = {+ cpu: '%',+ memory: '%',+ disk: '%',+ 'disk-usage': '%',+ usage: '%',+ temperature: '°C',+ disk_temperature: '°C',+ diskTemperature: '°C',+ diskRead: ' MB/s',+ diskWrite: ' MB/s',+ networkIn: ' MB/s',+ networkOut: ' MB/s',+ 'disk-wearout': '%',+};+const platformPagePath = (platform: string | undefined): string | undefined => {if (!platform) return undefined;const navId = PRIMARY_PLATFORM_NAV_IDS.find((id) =>@@ -116,8 +135,35 @@ export function AlertOverviewAlertCard(props: AlertOverviewAlertCardProps) {return describeAlertDeliveryStatus(diagnosis, props.alert.acknowledged);};const [moreOpen, setMoreOpen] = createSignal(false);+ // A threshold alert can stay open below its trigger, so the card leads with+ // the reading Pulse is evaluating now; the message keeps the last breach.+ const metricPresentation = () =>+ isPulseSystemAlert(props.alert)+ ? null+ : getMetricAlertPresentation(props.alert, props.state.tick());+ const alertLevels = (): { alert: string; clear?: string } | null => {+ const presentation = metricPresentation();+ if (presentation) {+ return {+ alert: presentation.alertLevel,+ clear:+ presentation.clearLevel !== presentation.alertLevel ? presentation.clearLevel : undefined,+ };+ }+ if (isPulseSystemAlert(props.alert) || !(props.alert.threshold > 0)) return null;+ // Without a live status only the metric types carry a known unit; other+ // thresholds (queue ages, counts) are stated in their own message.+ const unit = THRESHOLD_UNIT_BY_ALERT_TYPE[props.alert.type];+ if (!unit) return null;+ return {+ alert:+ unit === '°C'+ ? formatTemperature(props.alert.threshold)+ : `${props.alert.threshold}${unit}`,+ };+ };const hasMetaLine = () =>- (!isPulseSystemAlert(props.alert) && props.alert.threshold > 0) ||+ Boolean(alertLevels()) ||Boolean(deliveryStatusLine()) ||(isAlertSnoozed(props.alert) && Boolean(props.alert.operationalRecord?.suppression?.expiresAt));const timelineOpen = () => props.timelineState.expandedIncidents().has(alertKey());@@ -203,7 +249,9 @@ export function AlertOverviewAlertCard(props: AlertOverviewAlertCardProps) {return (<div id={`alert-${alertKey()}`} class={alertCardPresentation().cardClassName}><div class="flex flex-col gap-2 sm:flex-row sm:items-start">- <div class="flex items-start flex-1">+ {/* Without a floor the text column shrinks to its longest word and the+ actions keep one row, squeezing the reading to ~110px beside them. */}+ <div class="flex items-start flex-1 sm:min-w-64"><div class={alertCardPresentation().iconClassName}>{props.alert.acknowledged ? (<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">@@ -225,7 +273,7 @@ export function AlertOverviewAlertCard(props: AlertOverviewAlertCardProps) {</svg>)}</div>- <div class="flex-1 min-w-0">+ <div class="flex-1 min-w-0 wrap-anywhere"><div class="flex flex-wrap items-center gap-x-2 gap-y-0.5"><Showwhen={hasResource()}@@ -273,16 +321,37 @@ export function AlertOverviewAlertCard(props: AlertOverviewAlertCardProps) {{formatAlertOverviewStartedAgo(props.alert.startTime, props.state.tick())}</span></div>- <p class="text-sm text-base-content mt-0.5 wrap-break-word">{props.alert.message}</p>+ <Show+ when={metricPresentation()}+ fallback={+ <p class="text-sm text-base-content mt-0.5 wrap-break-word">+ {props.alert.message}+ </p>+ }+ >+ {(presentation) => (+ <>+ <p+ class="text-sm text-base-content mt-0.5 wrap-break-word"+ title={presentation().lastBreach}+ >+ {presentation().summary}+ </p>+ <p class="text-xs text-muted wrap-break-word">{presentation().detail}</p>+ </>+ )}+ </Show><Show when={hasMetaLine()}><div class="flex flex-wrap items-center gap-x-3 gap-y-0.5 mt-0.5">- <Show when={!isPulseSystemAlert(props.alert) && props.alert.threshold > 0}>- <span class="text-xs text-muted">- limit: {props.alert.threshold}- {props.alert.type === 'temperature' || props.alert.type === 'diskTemperature'- ? '°C'- : '%'}- </span>+ <Show when={alertLevels()}>+ {(levels) => (+ <>+ <span class="text-xs text-muted">Alert level {levels().alert}</span>+ <Show when={levels().clear}>+ <span class="text-xs text-muted">Clear level {levels().clear}</span>+ </Show>+ </>+ )}</Show><Show when={deliveryStatusLine()}><spandiff --git a/frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx b/frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsxindex 13c198d3b6..c35e9d77a1 100644--- a/frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx+++ b/frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx@@ -4,7 +4,9 @@ import { IncidentEventFilters } from '@/components/Alerts/IncidentEventFilters';import { IncidentAssistantHandoffButton } from '@/components/Alerts/IncidentAssistantHandoffButton';import { IncidentTimelineEventCard } from '@/components/Alerts/IncidentTimelineEventCard';import { Card } from '@/components/shared/Card';+import type { Alert, Incident } from '@/types/api';import type { Resource } from '@/types/resource';+import { useRelativeTimeNow } from '@/utils/relativeTimeClock';import { getPreferredInfrastructureDisplayName } from '@/utils/resourceIdentity';import {formatIncidentEvidenceTime,@@ -29,8 +31,10 @@ import {getAlertResourceIncidentToggleButtonClass,getAlertResourceIncidentToggleLabel,getAlertResourceIncidentTruncatedEventsLabel,+ normalizeAlertIncidentStatus,} from '@/utils/alertIncidentPresentation';+import { getMetricAlertPresentation } from './metricAlertPresentation';import { filterIncidentEvents, summarizeIncidentEvents } from './types';import type { AlertHistoryState } from './useAlertHistoryState';@@ -44,6 +48,9 @@ interface AlertResourceIncidentsPanelProps {}export function AlertResourceIncidentsPanel(props: AlertResourceIncidentsPanelProps) {+ // The live reading turns stale when evaluations stop, so it rechecks on the+ // shared clock rather than only when the alert changes.+ const now = useRelativeTimeNow();return (<Show when={props.state.resourceIncidentPanel()}>{(selection) => {@@ -53,6 +60,20 @@ export function AlertResourceIncidentsPanel(props: AlertResourceIncidentsPanelPrconst hasError = () => props.state.resourceIncidentError()[resourceId];const lookupResource = () => props.getResource ?? props.state.getResource;const resource = () => lookupResource()?.(resourceId);+ // An open occurrence's message is the breach that opened it. A+ // threshold alert can stay open below its trigger, so describe the+ // open occurrence from its live alert; closed ones keep their copy.+ // An occurrence is its alert id plus its start, as the incident store+ // keys it, so a cached row never takes a later recurrence's reading.+ const liveAlertFor = (incident: Incident): Alert | undefined => {+ if (normalizeAlertIncidentStatus(incident.status) !== 'open') return undefined;+ const openedAt = Date.parse(incident.openedAt);+ if (!Number.isFinite(openedAt)) return undefined;+ return Object.values(props.state.activeAlerts?.() ?? {}).find(+ (alert) =>+ alert?.id === incident.alertIdentifier && Date.parse(alert.startTime) === openedAt,+ );+ };const resourceDisplayName = () => {const current = resource();if (current) {@@ -155,6 +176,10 @@ export function AlertResourceIncidentsPanel(props: AlertResourceIncidentsPanelPrfilteredEvents().length > 0? filteredEvents()[filteredEvents().length - 1]: undefined;+ const livePresentation = () => {+ const alert = liveAlertFor(incident);+ return alert ? getMetricAlertPresentation(alert, now()) : null;+ };const filteredLabel = () =>filteredEvents().length !== events.length? `${filteredEvents().length}/${events.length}`@@ -192,8 +217,24 @@ export function AlertResourceIncidentsPanel(props: AlertResourceIncidentsPanelPr{INCIDENT_HISTORY_PARTIAL}</p></Show>- <Show when={incident.message}>- <p class={getAlertIncidentTimelineOutputClass()}>{incident.message}</p>+ <Show+ when={livePresentation()}+ fallback={+ <Show when={incident.message}>+ <p class={getAlertIncidentTimelineOutputClass()}>+ {incident.message}+ </p>+ </Show>+ }+ >+ {(live) => (+ <p+ class={getAlertIncidentTimelineOutputClass()}+ title={live().lastBreach}+ >+ {live().summary}. {live().detail}+ </p>+ )}</Show><Show when={incident.acknowledged && incident.ackUser}><p class={getAlertIncidentTimelineOutputClass()}>diff --git a/frontend-modern/src/features/alerts/__tests__/AlertOverviewAlertCard.system-scope.test.tsx b/frontend-modern/src/features/alerts/__tests__/AlertOverviewAlertCard.system-scope.test.tsxindex 31b9436d66..a3dddd8e8f 100644--- a/frontend-modern/src/features/alerts/__tests__/AlertOverviewAlertCard.system-scope.test.tsx+++ b/frontend-modern/src/features/alerts/__tests__/AlertOverviewAlertCard.system-scope.test.tsx@@ -3,6 +3,7 @@ import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';import type { AlertOverviewState } from '../useAlertOverviewState';import type { AlertIncidentTimelineState } from '../useAlertIncidentTimelineState';import { makeSystemAlert, SYSTEM_ALERT_TYPES } from '../__fixtures__/systemAlerts';+import { temperatureStore } from '@/utils/temperature';vi.mock('@solidjs/router', () => ({A: (props: any) => (@@ -67,7 +68,7 @@ describe('Pulse system-alert overview scope', () => {<AlertOverviewAlertCard alert={alert} state={state} timelineState={timelineState} />));expect(screen.getByText('Pulse').closest('a')).toBeNull();- expect(screen.queryByText(/limit:/)).toBeNull();+ expect(screen.queryByText(/Alert level/)).toBeNull();fireEvent.click(screen.getByRole('button', { name: 'More' }));expect(screen.queryByText('Resource monitoring policy')).toBeNull();});@@ -87,13 +88,135 @@ describe('Pulse system-alert overview scope', () => {'href','/proxmox/overview',);- expect(screen.getByText('limit: 80%')).toBeInTheDocument();+ expect(screen.getByText('Alert level 80%')).toBeInTheDocument();// Monitoring policy is a secondary action behind the More disclosure.expect(screen.queryByText('Resource monitoring policy')).toBeNull();fireEvent.click(screen.getByRole('button', { name: 'More' }));expect(screen.getByText('Resource monitoring policy')).toBeInTheDocument();});+ it('leads a threshold alert held under its trigger with the reading now', () => {+ // minipc on 2026-10-06: the card said "Node temperature at 80.0°C" while+ // the node read 72°C, because the message keeps the last breach.+ const now = Date.now();+ const alert = makeSystemAlert('temperature', {+ id: 'homelab-minipc::metric-threshold:temperature',+ resourceId: 'homelab-minipc',+ resourceName: 'minipc',+ node: 'minipc',+ message: 'Node temperature at 80.0°C',+ value: 80,+ threshold: 80,+ lastSeen: new Date(now - 5 * 60_000).toISOString(),+ metadata: { resourceType: 'node' },+ metricStatus: {+ phase: 'recovering',+ value: 72,+ unit: '°C',+ observedAt: new Date(now).toISOString(),+ trigger: 80,+ recovery: 75,+ recoveryDelaySeconds: 300,+ recoveryElapsedSeconds: 120,+ },+ });+ render(() => (+ <AlertOverviewAlertCard alert={alert} state={state} timelineState={timelineState} />+ ));+ expect(screen.getByText('Temperature 72°C now, recovering')).toHaveAttribute(+ 'title',+ expect.stringMatching(/^Last reading at or above 80°C: 80°C, /),+ );+ expect(+ screen.getByText('Clears after 5 minutes at 75°C or lower, 2 minutes so far.'),+ ).toBeInTheDocument();+ expect(screen.queryByText('Node temperature at 80.0°C')).toBeNull();+ expect(screen.getByText('Alert level 80°C')).toBeInTheDocument();+ expect(screen.getByText('Clear level 75°C')).toBeInTheDocument();+ });++ it('labels a rate alert level in its own unit, not a guessed percent', () => {+ const alert = makeSystemAlert('diskWrite', {+ id: 'vm-101::metric-threshold:diskWrite',+ resourceId: 'vm-101',+ resourceName: 'db-01',+ message: 'VM diskWrite at 240.0 MB/s',+ value: 240,+ threshold: 200,+ metadata: { resourceType: 'vm' },+ metricStatus: {+ phase: 'breaching',+ value: 240,+ unit: 'MB/s',+ observedAt: new Date().toISOString(),+ trigger: 200,+ recovery: 200,+ },+ });+ render(() => (+ <AlertOverviewAlertCard alert={alert} state={state} timelineState={timelineState} />+ ));+ expect(screen.getByText('Disk Write 240 MB/s, above the 200 MB/s alert level')).toBeVisible();+ expect(screen.getByText('Alert level 200 MB/s')).toBeInTheDocument();+ // Clearing at the trigger itself needs no second level.+ expect(screen.queryByText(/Clear level/)).toBeNull();+ });++ it('does not guess a percent for a threshold stated in its own message', () => {+ const alert = makeSystemAlert('queue-age', {+ id: 'pmg-eu::queue-age',+ resourceId: 'pmg-eu',+ resourceName: 'mail-gateway-eu',+ message: 'PMG mail-gateway-eu has messages queued for 57 minutes (threshold: 30 minutes)',+ value: 57,+ threshold: 30,+ metadata: { resourceType: 'pmg' },+ });+ render(() => (+ <AlertOverviewAlertCard alert={alert} state={state} timelineState={timelineState} />+ ));+ expect(screen.getByText(alert.message)).toBeInTheDocument();+ expect(screen.queryByText(/Alert level/)).toBeNull();+ });++ it('keeps the level label for a percent threshold that has no live status', () => {+ const alert = makeSystemAlert('disk-wearout', {+ id: 'disk-wearout-nvme0',+ resourceId: 'host-1/disk:nvme0n1',+ resourceName: 'nvme0n1',+ message: 'SSD nvme0n1 has less than 10% life remaining',+ value: 7,+ threshold: 10,+ metadata: { resourceType: 'physical_disk' },+ });+ render(() => (+ <AlertOverviewAlertCard alert={alert} state={state} timelineState={timelineState} />+ ));+ expect(screen.getByText('Alert level 10%')).toBeInTheDocument();+ });++ it('shows a temperature level without a live status in the viewer unit', () => {+ // Right after a restart an alert has no live status until it is evaluated.+ temperatureStore.setUnit('fahrenheit');+ try {+ const alert = makeSystemAlert('temperature', {+ id: 'homelab-minipc::metric-threshold:temperature',+ resourceId: 'homelab-minipc',+ resourceName: 'minipc',+ message: 'Node temperature at 80.0°C',+ value: 80,+ threshold: 80,+ metadata: { resourceType: 'node' },+ });+ render(() => (+ <AlertOverviewAlertCard alert={alert} state={state} timelineState={timelineState} />+ ));+ expect(screen.getByText('Alert level 176°F')).toBeInTheDocument();+ } finally {+ temperatureStore.setUnit('celsius');+ }+ });+it('links a vCenter alarm on a network to vSphere by its incident provider', () => {// The summary is the alarm's own name, so the message no longer says VMware.const alert = makeSystemAlert('resource-incident', {diff --git a/frontend-modern/src/features/alerts/__tests__/AlertResourceIncidentsPanel.test.tsx b/frontend-modern/src/features/alerts/__tests__/AlertResourceIncidentsPanel.test.tsxindex 653d748759..2adfb51e4a 100644--- a/frontend-modern/src/features/alerts/__tests__/AlertResourceIncidentsPanel.test.tsx+++ b/frontend-modern/src/features/alerts/__tests__/AlertResourceIncidentsPanel.test.tsx@@ -189,6 +189,101 @@ describe('AlertResourceIncidentsPanel', () => {).toBeNull();});+ it('describes only the open occurrence from its live alert', () => {+ // The recorded message is the breach that opened the occurrence; a+ // threshold alert held below its trigger reads lower now.+ const alertId = 'homelab-minipc::metric-threshold:temperature';+ const occurrence = (overrides: Partial<Incident>): Incident => ({+ id: 'occurrence',+ alertIdentifier: alertId,+ alertType: 'temperature',+ level: 'warning',+ resourceId: 'homelab-minipc',+ resourceName: 'minipc',+ status: 'open',+ acknowledged: false,+ openedAt: '2026-10-06T07:57:44Z',+ message: 'Node temperature at 80.0°C',+ events: [],+ ...overrides,+ });+ const now = Date.now();+ render(() => (+ <AlertResourceIncidentsPanel+ state={+ {+ resourceIncidentPanel: () => ({ resourceId: 'homelab-minipc', resourceName: 'minipc' }),+ resourceIncidents: () => ({+ 'homelab-minipc': [+ occurrence({ id: 'open' }),+ // A cached row still marked open from an earlier start is a+ // different occurrence and must not take this alert's reading.+ occurrence({+ id: 'cached-earlier',+ openedAt: '2026-10-04T09:00:00Z',+ message: 'Node temperature at 81.0°C',+ }),+ occurrence({+ id: 'closed',+ status: 'resolved',+ openedAt: '2026-10-05T07:00:00Z',+ closedAt: '2026-10-05T08:00:00Z',+ message: 'Node temperature at 83.0°C',+ }),+ ],+ }),+ activeAlerts: () => ({+ [alertId]: {+ id: alertId,+ type: 'temperature',+ level: 'warning',+ resourceId: 'homelab-minipc',+ resourceName: 'minipc',+ node: 'minipc',+ instance: 'homelab',+ message: 'Node temperature at 80.0°C',+ value: 80,+ threshold: 80,+ startTime: '2026-10-06T07:57:44Z',+ lastSeen: new Date(now - 5 * 60_000).toISOString(),+ acknowledged: false,+ metricStatus: {+ phase: 'latched',+ value: 76,+ unit: '°C',+ observedAt: new Date(now).toISOString(),+ trigger: 80,+ recovery: 75,+ recoveryDelaySeconds: 300,+ },+ },+ }),+ resourceIncidentError: () => ({}),+ resourceIncidentLoading: () => ({ 'homelab-minipc': false }),+ expandedResourceIncidentIds: () => new Set<string>(),+ resourceIncidentEventFilters: () => new Set<string>(['opened']),+ setResourceIncidentEventFilters: vi.fn(),+ refreshResourceIncidentPanel: vi.fn(),+ setResourceIncidentPanel: vi.fn(),+ toggleResourceIncidentDetails: vi.fn(),+ } as any+ }+ />+ ));++ const live = screen.getByText(+ 'Temperature 76°C now, back under the 80°C alert level. Stays open until it reaches 75°C or lower and stays there for 5 minutes.',+ );+ expect(live).toHaveAttribute(+ 'title',+ expect.stringMatching(/^Last reading at or above 80°C: 80°C, /),+ );+ expect(screen.queryByText('Node temperature at 80.0°C')).toBeNull();+ expect(screen.getByText('Node temperature at 83.0°C')).toBeInTheDocument();+ expect(screen.getByText('Node temperature at 81.0°C')).toBeInTheDocument();+ expect(screen.getAllByText(/now, back under the 80°C alert level/)).toHaveLength(1);+ });+it('opens Assistant from a resource incident without carrying raw command details', () => {const openSpy = vi.spyOn(aiChatStore, 'open');aiChatStore.setEnabled(true);diff --git a/frontend-modern/src/features/alerts/__tests__/helpers.test.ts b/frontend-modern/src/features/alerts/__tests__/helpers.test.tsindex 676038b14f..d04919c3bd 100644--- a/frontend-modern/src/features/alerts/__tests__/helpers.test.ts+++ b/frontend-modern/src/features/alerts/__tests__/helpers.test.ts@@ -288,6 +288,8 @@ describe('getMetricAlertPresentation', () => {summary: 'Temperature 76°C now, back under the 80°C alert level',detail: 'Stays open until it reaches 75°C or lower and stays there for 5 minutes.',phaseLabel: 'Alert still open',+ alertLevel: '80°C',+ clearLevel: '75°C',});expect(presentation?.lastBreach).toMatch(/^Last reading at or above 80°C: 80°C, /);});@@ -309,6 +311,13 @@ describe('getMetricAlertPresentation', () => {NOW,)?.detail,).toBe('Clears after 5 minutes at 75°C or lower, 2 minutes so far.');+ // Progress rounds down: 4m50s into a 5 minute delay is not "5 minutes so far".+ expect(+ getMetricAlertPresentation(+ minipcAlert({ phase: 'recovering', value: 72, recoveryElapsedSeconds: 290 }),+ NOW,+ )?.detail,+ ).toBe('Clears after 5 minutes at 75°C or lower, 4 minutes so far.');});it('names the alert level while the reading is still over it', () => {@@ -360,6 +369,31 @@ describe('getMetricAlertPresentation', () => {});});+ it('names the disk of a per-disk guest alert, as its message does', () => {+ // Every disk alert on a guest carries the guest's name; only the message+ // and metadata say which disk.+ const alert: Alert = {+ ...minipcAlert(),+ type: 'disk',+ resourceName: 'web-01',+ message: 'VM disk (/var) at 92.0%',+ metadata: { label: '/var', mountpoint: '/var' },+ metricStatus: {+ phase: 'latched',+ value: 87,+ unit: '%',+ observedAt: new Date(NOW).toISOString(),+ trigger: 90,+ recovery: 85,+ },+ };+ expect(getMetricAlertPresentation(alert, NOW)).toMatchObject({+ summary: 'Disk (/var) 87% now, back under the 90% alert level',+ alertLevel: '90%',+ clearLevel: '85%',+ });+ });+it('returns null without a live status so callers keep the alert message', () => {expect(getMetricAlertPresentation(minipcAlert(), NOW)).toBeNull();expect(getAlertAttentionCopy(minipcAlert(), NOW)).toEqual({diff --git a/frontend-modern/src/features/alerts/metricAlertPresentation.ts b/frontend-modern/src/features/alerts/metricAlertPresentation.tsindex 8d72d7c312..d0c3937aea 100644--- a/frontend-modern/src/features/alerts/metricAlertPresentation.ts+++ b/frontend-modern/src/features/alerts/metricAlertPresentation.ts@@ -22,6 +22,10 @@ export interface MetricAlertPresentation {phaseLabel: string;/** The last reading that met the trigger, once the live one differs. */lastBreach?: string;+ /** The level that opens the alert, in the metric's unit. */+ alertLevel: string;+ /** The level the reading must reach before the alert can clear. */+ clearLevel: string;}const formatMetricValue = (value: number, unit: string | undefined): string => {@@ -43,6 +47,14 @@ const formatSeconds = (seconds: number): string => {return `${hours} ${hours === 1 ? 'hour' : 'hours'}`;};+// Progress rounds down, so a run four minutes and fifty seconds into a five+// minute delay does not read as finished while the alert is still open.+const formatElapsed = (seconds: number): string => {+ if (seconds < 60) return formatSeconds(seconds);+ if (seconds < 3600) return formatSeconds(Math.floor(seconds / 60) * 60);+ return formatSeconds(Math.floor(seconds / 360) * 360);+};+const describeReading = (label: string, status: MetricAlertStatus): string => {const value = formatMetricValue(status.value, status.unit);const window = status.evaluationWindowSeconds ?? 0;@@ -62,6 +74,14 @@ const describeClearRule = (status: MetricAlertStatus, lead: string): string => {: `${lead} ${recovery} or lower.`;};+// A guest raises one disk alert per disk, all named after the guest, so the+// reading names the disk the way the alert message does ("VM disk (/var)").+const readingLabel = (alert: Pick<Alert, 'type' | 'metadata'>): string => {+ const label = alertTypeDisplayLabel(alert.type);+ const disk = alert.type === 'disk' ? alert.metadata?.label : undefined;+ return typeof disk === 'string' && disk.trim() ? `${label} (${disk.trim()})` : label;+};+const isUsableStatus = (status: MetricAlertStatus | undefined): status is MetricAlertStatus =>!!status &&Number.isFinite(status.value) &&@@ -76,15 +96,15 @@ const isUsableStatus = (status: MetricAlertStatus | undefined): status is Metric* no live status (non-threshold alerts, or the moments after a restart).*/export function getMetricAlertPresentation(- alert: Pick<Alert, 'type' | 'value' | 'lastSeen' | 'metricStatus'>,+ alert: Pick<Alert, 'type' | 'value' | 'lastSeen' | 'metricStatus' | 'metadata'>,now: number = Date.now(),): MetricAlertPresentation | null {const status = alert.metricStatus;if (!isUsableStatus(status)) return null;- const label = alertTypeDisplayLabel(alert.type);- const reading = describeReading(label, status);+ const reading = describeReading(readingLabel(alert), status);const trigger = formatMetricValue(status.trigger, status.unit);+ const recovery = formatMetricValue(status.recovery, status.unit);const observedAt = Date.parse(status.observedAt);const stale = !Number.isFinite(observedAt) || now - observedAt > METRIC_ALERT_STATUS_STALE_MS;@@ -105,12 +125,11 @@ export function getMetricAlertPresentation(case 'recovering': {const delay = status.recoveryDelaySeconds ?? 0;const elapsed = status.recoveryElapsedSeconds ?? 0;- const recovery = formatMetricValue(status.recovery, status.unit);summary = `${reading} now, recovering`;detail =delay > 0? `Clears after ${formatSeconds(delay)} at ${recovery} or lower${- elapsed > 0 ? `, ${formatSeconds(Math.min(elapsed, delay))} so far` : ''+ elapsed > 0 ? `, ${formatElapsed(Math.min(elapsed, delay))} so far` : ''}.`: `Clears at ${recovery} or lower.`;phaseLabel = 'Recovering';@@ -131,7 +150,16 @@ export function getMetricAlertPresentation(lastBreach = `Last reading at or above ${trigger}: ${formatMetricValue(alert.value, status.unit)}${when}`;}- return { phase: status.phase, stale, summary, detail, phaseLabel, lastBreach };+ return {+ phase: status.phase,+ stale,+ summary,+ detail,+ phaseLabel,+ lastBreach,+ alertLevel: trigger,+ clearLevel: recovery,+ };}export interface AlertAttentionCopy {@@ -142,7 +170,7 @@ export interface AlertAttentionCopy {/** Copy for an alert row in a drawer's "Needs attention" list. */export function getAlertAttentionCopy(- alert: Pick<Alert, 'type' | 'message' | 'value' | 'lastSeen' | 'metricStatus'>,+ alert: Pick<Alert, 'type' | 'message' | 'value' | 'lastSeen' | 'metricStatus' | 'metadata'>,now: number = Date.now(),): AlertAttentionCopy {const presentation = getMetricAlertPresentation(alert, now);diff --git a/frontend-modern/src/features/alerts/useAlertHistoryState.ts b/frontend-modern/src/features/alerts/useAlertHistoryState.tsindex 5ef14948ec..88d5d64381 100644--- a/frontend-modern/src/features/alerts/useAlertHistoryState.ts+++ b/frontend-modern/src/features/alerts/useAlertHistoryState.ts@@ -361,6 +361,9 @@ export function useAlertHistoryState(props: UseAlertHistoryStateProps) {// Exposed so the inline resource panel can resolve a display name without// threading the lookup down through the table and mobile list.getResource: props.getResource,+ // Exposed so the resource panel can describe its open occurrence from the+ // live alert instead of the message recorded when it opened.+ activeAlerts: props.activeAlerts,formatAlertRowTime,formatAlertRowTimestamp,openResourceIncidentPanel: resourceIncidentsState.openResourceIncidentPanel,diff --git a/internal/ai/attention.go b/internal/ai/attention.goindex 68c115f692..b43400b45c 100644--- a/internal/ai/attention.go+++ b/internal/ai/attention.go@@ -3,11 +3,14 @@ package aiimport ("errors""fmt"+ "math""sort"+ "strconv""strings""time""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"recoverymodel "github.com/rcourtman/pulse-go-rewrite/internal/recovery/model")@@ -223,7 +226,7 @@ func projectAttentionAlert(freshness, completeness := summarizeAttentionEvidence(record.State, evidence, now)resourceName := firstAttentionText(alert.ResourceName, alert.Instance, record.SubjectResourceID)title := attentionTitle(alert, resourceName)- summary := firstAttentionText(alert.Message, record.ImpactSummary, title)+ summary := firstAttentionText(heldMetricAlertSummary(alert, now), alert.Message, record.ImpactSummary, title)related := make([]AttentionResource, 0, len(record.RelatedResourceIDs))for _, resourceID := range canonicalAttentionIDs(record.RelatedResourceIDs) {@@ -635,6 +638,190 @@ func attentionResourceType(alert alerts.Alert) string {return ""}+// attentionMetricStatusStaleAfter matches the frontend's+// METRIC_ALERT_STATUS_STALE_MS: an older evaluation is no longer "now".+const attentionMetricStatusStaleAfter = 10 * time.Minute++// heldMetricAlertSummary describes a threshold alert that is still open below+// its trigger from the evaluator's live status, in the words the frontend's+// metric alert presentation uses. The alert's Message keeps the last reading+// that met the trigger, so on its own it reports a value the resource may no+// longer have. A breaching alert keeps its Message, which tracks the current+// breach, and a missing or stale status returns "" so the caller falls back+// to it.+func heldMetricAlertSummary(alert alerts.Alert, now time.Time) string {+ status := alert.MetricStatus+ if status == nil {+ return ""+ }+ if status.Phase != models.MetricAlertPhaseLatched && status.Phase != models.MetricAlertPhaseRecovering {+ return ""+ }+ if !attentionFinite(status.Value) || !attentionFinite(status.Trigger) || !attentionFinite(status.Recovery) {+ return ""+ }+ if status.ObservedAt.IsZero() || now.Sub(status.ObservedAt) > attentionMetricStatusStaleAfter {+ return ""+ }++ reading := attentionMetricReading(alert, status)+ recovery := formatAttentionMetricValue(status.Recovery, status.Unit)+ delay := status.RecoveryDelaySeconds+ if status.Phase == models.MetricAlertPhaseRecovering {+ if delay <= 0 {+ return fmt.Sprintf("%s now, recovering. Clears at %s or lower.", reading, recovery)+ }+ progress := ""+ if elapsed := status.RecoveryElapsedSeconds; elapsed > 0 {+ progress = ", " + formatAttentionElapsed(min(elapsed, delay)) + " so far"+ }+ return fmt.Sprintf("%s now, recovering. Clears after %s at %s or lower%s.",+ reading, formatAttentionSeconds(delay), recovery, progress)+ }+ hold := ""+ if delay > 0 {+ hold = " and stays there for " + formatAttentionSeconds(delay)+ }+ return fmt.Sprintf("%s now, back under the %s alert level. Stays open until it reaches %s or lower%s.",+ reading, formatAttentionMetricValue(status.Trigger, status.Unit), recovery, hold)+}++func attentionMetricReading(alert alerts.Alert, status *models.MetricAlertStatus) string {+ label := attentionMetricLabel(alert)+ value := formatAttentionMetricValue(status.Value, status.Unit)+ if status.EvaluationWindowSeconds <= 0 {+ return label + " " + value+ }+ latest := ""+ if status.RawValue != nil && attentionFinite(*status.RawValue) {+ latest = ", latest " + formatAttentionMetricValue(*status.RawValue, status.Unit)+ }+ return fmt.Sprintf("%s averaged %s over %s%s",+ label, value, formatAttentionSeconds(status.EvaluationWindowSeconds), latest)+}++// attentionMetricLabel names the metric the way the alert type label does. A+// guest raises one disk alert per disk, all named after the guest, so a disk+// reading also names its disk, as the alert message does.+func attentionMetricLabel(alert alerts.Alert) string {+ var label string+ switch alert.Type {+ case "cpu":+ label = "CPU"+ case "memory":+ label = "Memory"+ case "disk", "disk-usage":+ label = "Disk"+ case "usage":+ label = "Usage"+ case "diskRead":+ label = "Disk Read"+ case "diskWrite":+ label = "Disk Write"+ case "networkIn":+ label = "Network In"+ case "networkOut":+ label = "Network Out"+ case "temperature", "disk_temperature", "diskTemperature":+ label = "Temperature"+ default:+ label = firstAttentionText(alert.Type, "Reading")+ }+ if alert.Type == "disk" {+ if disk, ok := alert.Metadata["label"].(string); ok && strings.TrimSpace(disk) != "" {+ label += " (" + strings.TrimSpace(disk) + ")"+ }+ }+ return label+}++func formatAttentionMetricValue(value float64, unit string) string {+ switch unit {+ case "°C":+ return formatAttentionDecimal(attentionRoundHalfUp(value), 0) + "°C"+ case "%":+ if math.Abs(value) >= 10 {+ return formatAttentionDecimal(attentionRoundHalfUp(value), 0) + "%"+ }+ return formatAttentionDecimal(value, 1) + "%"+ case "":+ return formatAttentionDecimal(value, 1)+ default:+ return formatAttentionDecimal(value, 1) + " " + unit+ }+}++// formatAttentionDecimal rounds like the frontend's Number(value.toFixed(n)):+// from the float's exact value, so 2.55 (stored just under it) reads 2.5, and+// an exact tie such as 4.25 rounds away from zero where FormatFloat would+// round it to even. No trailing ".0".+func formatAttentionDecimal(value float64, places int) string {+ scale := math.Pow10(places)+ scaled := value * scale+ var rounded float64+ if math.FMA(value, scale, -scaled) == 0 && math.Abs(scaled-math.Trunc(scaled)) == 0.5 {+ rounded = math.Round(scaled) / scale+ } else {+ parsed, err := strconv.ParseFloat(strconv.FormatFloat(value, 'f', places, 64), 64)+ if err != nil {+ parsed = value+ }+ rounded = parsed+ }+ if rounded == 0 {+ rounded = 0 // a template literal prints -0 as "0"+ }+ return strconv.FormatFloat(rounded, 'f', -1, 64)+}++// attentionRoundHalfUp rounds like JavaScript's Math.round: ties go toward+// positive infinity, so -10.5 rounds to -10 where math.Round gives -11.+func attentionRoundHalfUp(value float64) float64 {+ floor := math.Floor(value)+ if value-floor >= 0.5 {+ return floor + 1+ }+ return floor+}++func formatAttentionSeconds(seconds int) string {+ plural := func(n float64, unit string) string {+ if n == 1 {+ return "1 " + unit+ }+ return strconv.FormatFloat(n, 'f', -1, 64) + " " + unit + "s"+ }+ switch {+ case seconds < 60:+ return plural(float64(seconds), "second")+ case seconds < 3600:+ return plural(math.Round(float64(seconds)/60), "minute")+ default:+ hours, err := strconv.ParseFloat(formatAttentionDecimal(float64(seconds)/3600, 1), 64)+ if err != nil {+ hours = float64(seconds) / 3600+ }+ return plural(hours, "hour")+ }+}++// formatAttentionElapsed rounds progress down, so a run four minutes and+// fifty seconds into a five minute delay does not read as finished.+func formatAttentionElapsed(seconds int) string {+ switch {+ case seconds < 60:+ return formatAttentionSeconds(seconds)+ case seconds < 3600:+ return formatAttentionSeconds(seconds / 60 * 60)+ default:+ return formatAttentionSeconds(seconds / 360 * 360)+ }+}++func attentionFinite(value float64) bool {+ return !math.IsNaN(value) && !math.IsInf(value, 0)+}+func firstAttentionText(values ...string) string {for _, value := range values {if normalized := strings.TrimSpace(value); normalized != "" {diff --git a/internal/ai/attention_test.go b/internal/ai/attention_test.goindex ccd1230896..6e89d5fc08 100644--- a/internal/ai/attention_test.go+++ b/internal/ai/attention_test.go@@ -5,6 +5,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"recoverymodel "github.com/rcourtman/pulse-go-rewrite/internal/recovery/model")@@ -242,6 +243,145 @@ func TestProjectAttentionItemsProducesCurrentCalmEvaluation(t *testing.T) {}}+func TestProjectAttentionItemsLeadsHeldMetricAlertsWithTheLiveReading(t *testing.T) {+ // minipc on 2026-10-06: the alert opened at 80°C and stayed open while the+ // node read 71-76°C, and Patrol kept saying "Node temperature at 80.0°C".+ now := time.Date(2026, 10, 6, 10, 52, 0, 0, time.UTC)+ raw := 61.0+ tests := []struct {+ name string+ alertType string+ message string+ metadata map[string]interface{}+ status *models.MetricAlertStatus+ want string+ }{+ {+ name: "held under the trigger",+ alertType: "temperature",+ message: "Node temperature at 80.0°C",+ status: &models.MetricAlertStatus{+ Phase: models.MetricAlertPhaseLatched, Value: 76, Unit: "°C",+ ObservedAt: now.Add(-10 * time.Second), Trigger: 80, Recovery: 75, RecoveryDelaySeconds: 300,+ },+ want: "Temperature 76°C now, back under the 80°C alert level. Stays open until it reaches 75°C or lower and stays there for 5 minutes.",+ },+ {+ name: "recovering at the clear level",+ alertType: "temperature",+ message: "Node temperature at 80.0°C",+ status: &models.MetricAlertStatus{+ Phase: models.MetricAlertPhaseRecovering, Value: 72, Unit: "°C",+ ObservedAt: now.Add(-10 * time.Second), Trigger: 80, Recovery: 75,+ RecoveryDelaySeconds: 300, RecoveryElapsedSeconds: 120,+ },+ want: "Temperature 72°C now, recovering. Clears after 5 minutes at 75°C or lower, 2 minutes so far.",+ },+ {+ name: "recovery progress rounds down",+ alertType: "temperature",+ message: "Node temperature at 80.0°C",+ status: &models.MetricAlertStatus{+ Phase: models.MetricAlertPhaseRecovering, Value: 72, Unit: "°C",+ ObservedAt: now, Trigger: 80, Recovery: 75,+ RecoveryDelaySeconds: 300, RecoveryElapsedSeconds: 290,+ },+ want: "Temperature 72°C now, recovering. Clears after 5 minutes at 75°C or lower, 4 minutes so far.",+ },+ {+ name: "one of a guest's disks",+ alertType: "disk",+ message: "VM disk (/var) at 92.0%",+ metadata: map[string]interface{}{"label": "/var"},+ status: &models.MetricAlertStatus{+ Phase: models.MetricAlertPhaseRecovering, Value: 84.6, Unit: "%",+ ObservedAt: now, Trigger: 90, Recovery: 85,+ },+ want: "Disk (/var) 85% now, recovering. Clears at 85% or lower.",+ },+ {+ name: "rolling-average rule",+ alertType: "cpu",+ message: "VM cpu at 93.0%",+ status: &models.MetricAlertStatus{+ Phase: models.MetricAlertPhaseLatched, Value: 84.2, RawValue: &raw, EvaluationWindowSeconds: 600,+ Unit: "%", ObservedAt: now, Trigger: 90, Recovery: 80,+ },+ want: "CPU averaged 84% over 10 minutes, latest 61% now, back under the 90% alert level. Stays open until it reaches 80% or lower.",+ },+ {+ name: "breaching keeps the message that tracks the breach",+ alertType: "temperature",+ message: "Node temperature at 88.0°C",+ status: &models.MetricAlertStatus{+ Phase: models.MetricAlertPhaseBreaching, Value: 88, Unit: "°C",+ ObservedAt: now, Trigger: 80, Recovery: 75,+ },+ want: "Node temperature at 88.0°C",+ },+ {+ name: "an old evaluation is not described as now",+ alertType: "temperature",+ message: "Node temperature at 80.0°C",+ status: &models.MetricAlertStatus{+ Phase: models.MetricAlertPhaseLatched, Value: 76, Unit: "°C",+ ObservedAt: now.Add(-attentionMetricStatusStaleAfter - time.Minute), Trigger: 80, Recovery: 75,+ },+ want: "Node temperature at 80.0°C",+ },+ {+ name: "no live status",+ alertType: "temperature",+ message: "Node temperature at 80.0°C",+ want: "Node temperature at 80.0°C",+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ alert := attentionTestAlert("held", operationaltrust.OperationalOpen, operationaltrust.SeverityWarning, now.Add(-3*time.Hour), now)+ alert.Type = tt.alertType+ alert.Message = tt.message+ alert.Value = 80+ alert.Metadata = tt.metadata+ alert.MetricStatus = tt.status+ projected := ProjectAttentionItems([]alerts.Alert{alert}, nil, nil, now)+ if len(projected.Details) != 1 {+ t.Fatalf("details = %d, want 1", len(projected.Details))+ }+ if got := projected.Details[0].Item.PlainLanguageSummary; got != tt.want {+ t.Fatalf("summary = %q, want %q", got, tt.want)+ }+ })+ }+}++func TestAttentionMetricFormattingRoundsLikeTheFrontend(t *testing.T) {+ // The frontend rounds with Number(value.toFixed(1)), which works from the+ // float's exact value: 2.55 is stored just under 2.55 and reads 2.5.+ cases := []struct{ got, want string }{+ {formatAttentionMetricValue(2.55, "MB/s"), "2.5 MB/s"},+ {formatAttentionMetricValue(4.25, "%"), "4.3%"},+ {formatAttentionMetricValue(0.75, "MB/s"), "0.8 MB/s"},+ {formatAttentionMetricValue(1.05, "MB/s"), "1.1 MB/s"},+ {formatAttentionMetricValue(12.5, "MB/s"), "12.5 MB/s"},+ {formatAttentionMetricValue(3.0, "MB/s"), "3 MB/s"},+ {formatAttentionMetricValue(84.5, "%"), "85%"},+ {formatAttentionMetricValue(71.6, "°C"), "72°C"},+ {formatAttentionMetricValue(-10.5, "%"), "-10%"},+ {formatAttentionMetricValue(-0.01, "MB/s"), "0 MB/s"},+ {formatAttentionMetricValue(0.49999999999999994, "°C"), "0°C"},+ {formatAttentionSeconds(4140), "1.1 hours"},+ {formatAttentionSeconds(3600), "1 hour"},+ {formatAttentionSeconds(90), "2 minutes"},+ {formatAttentionElapsed(290), "4 minutes"},+ }+ for _, tc := range cases {+ if tc.got != tc.want {+ t.Errorf("formatted %q, want %q", tc.got, tc.want)+ }+ }+}+func TestAttentionTitleProducesHumanReadableLabels(t *testing.T) {tests := []struct {name string