diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md index a28f2de9d6..1bd248e31a 100644 --- a/docs/release-control/v6/internal/subsystems/alerts.md +++ b/docs/release-control/v6/internal/subsystems/alerts.md @@ -1727,7 +1727,36 @@ the other host child alerts, still resolves under the child ID. Tests in `TestHostNativeSensorPendingRunRestartsAfterPolicyOff`, `TestHostNativeSensorUsesSensorDelayPolicy`) and `TestResourceAlertSpecValidateAllowsAgentSensorMigrationBridgeType` pin this. -No Thresholds UI writes these overrides yet. + +Alerts → Thresholds → Machines writes these overrides in its Machine Sensors +section (`ThresholdsTableAgentSensorsSection`). It lists every usable +temperature sensor a machine reports, plus every sensor with saved settings, +so a configured sensor that reads invalid, has left the report, sits on a +machine that is not reporting, or belongs to a machine no longer present stays +editable and removable with its reason beside the name; a non-reporting +machine shows no current reading. Rows are grouped by the machine's resource +ID, not its name. The frontend builds the ID with `agentSensorResourceId` +(`frontend-modern/src/features/alerts/agentSensorIdentity.ts`), the same +UTF-8 hex encoding as `HostNativeSensorResourceID`, and the overrides +projection reads it back as type `agentSensor`. The section has no Global +Defaults row and no Alerts toggle: a row's presentation default is +`temperature: 0`, marked `presentationDefaults`, so an unconfigured sensor +reads Off as the engine treats it, and the limit cell is the only switch. +Because that default is display-only, saving any Off value on a sensor row +stores no threshold and removes an override left with nothing else, and any stored sensor override, +a saved 0 included, shows as Custom with a revert action. Other rows keep an +explicit Off over an Off inherited default, so it survives a later change to +that default. The overrides projection carries each stored override's note +for every resource type, so a reloaded editor keeps it. A row's delay action opens the alert intent editor on +`metric.temperature` (shared `getAlertResourcePreferredIntentSignal`), and +the editor keeps a target that is not a listed resource, such as a machine +sensor or disk, as its own option under the row's label instead of falling +back to the first listed resource; preview is unavailable for such targets. +A handoff is applied once per request: a later change to the resource list +does not replay it over the operator's own selection. +`useThresholdsHostData.agentSensors.test.ts`, +`useThresholdsOverrideMutations.test.tsx`, `AlertIntentPolicyPanel.test.tsx` +and `ResourceTable.test.tsx` pin the frontend side. ### Agent custom sensors use canonical health-assessment alerts diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md index 2cc02cdc3d..15ba67a030 100644 --- a/docs/release-control/v6/internal/subsystems/api-contracts.md +++ b/docs/release-control/v6/internal/subsystems/api-contracts.md @@ -6405,9 +6405,13 @@ in `native`: `id` (`/`), `chip`, optional `adapter`, `channel`, `label`, `kind` (`temperature`/`fan`), `unit` (`celsius`/`rpm`), optional `value` and `status` (`ok`/`invalid`). The models-backed frontend host summary always emits `native` as a possibly empty array, beside `custom` and -`gpu`; the unified-resource and agent payloads omit it when empty. No -frontend code reads it yet, so `frontend-modern/src/types/api.ts` gains its -optional `native` type with the first consumer. +`gpu`; the unified-resource and agent payloads omit it when empty. +`frontend-modern/src/types/api.ts` mirrors it as optional +`HostSensorSummary.native: HostNativeSensor[]`, with `kind` and `unit` as the +literal unions above. Its first reader is the Alerts → Thresholds Machine +Sensors section, which lists only `temperature` entries, never shows an +`invalid` entry's value as a reading, and keeps a configured sensor whose +entry is missing as a retained row rather than a removal. `id` is the host-scoped sensor source key; `label` is display text and is not unique. Clients must not chart, alert on or headline an `invalid` entry, and must not read an absent or empty `native` array, or an entry missing from a diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md index 576ea2896d..fe5416e1e0 100644 --- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md +++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md @@ -10392,6 +10392,23 @@ muted dash for metrics an override cannot store (Docker container restart and memory-limit rules, every PMG threshold). No shared primitive, table component or layout changes. +### Threshold rows hand a labelled target to the delay editor (1 November 2026) + +A threshold row's delay action passes its resource ID, the alert signal from +the shared `getAlertResourcePreferredIntentSignal` (first supported CPU, +memory, disk or temperature column, else offline; desktop and mobile rows use +the same helper) and a label from `getAlertResourceIntentTargetLabel` (the +row's name and, when known, its machine or node). `AlertIntentPolicyPanel` +lists a target that is not one of its resources, such as a machine disk or +sensor child ID, as its own option under that label instead of resetting the +selection to the first listed resource, and disables preview for it. It +applies each handoff once, reading the resource list untracked, so an +inventory change cannot replay it over the operator's later selection. The +Machine Sensors section reuses the shared table with no Global Defaults row +and no Alerts column; its rows stay one line, with the reading and chip in the +subtitle and any `readingMessage` on the name's line. No shared primitive or +layout changes. + ### Stopped VM filesystem presentation (12 October 2026) `getWorkloadGuestDiskRead` treats an explicitly stopped VM as having no current diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md index 4166077c47..6acce499e0 100644 --- a/docs/release-control/v6/internal/subsystems/monitoring.md +++ b/docs/release-control/v6/internal/subsystems/monitoring.md @@ -253,9 +253,10 @@ only still skips power collection, as before. The legacy maps keep their keys, filters and consumers. Cluster peer collection omits the inventory, which belongs to each host's own report. -This is the identity foundation for #3565. Nothing reads the inventory yet: it -adds no alert, threshold, History series, sensor preference, CPU-source choice -or UI. An absent field (older agent, failed collection), an empty inventory +This is the identity foundation for #3565. The alert engine reads it only for +temperature inputs with their own threshold, and Alerts → Thresholds lists it +in a Machine Sensors section to set that threshold (see the alerts contract); +it adds no History series, sensor preference, CPU-source choice or other UI. An absent field (older agent, failed collection), an empty inventory and a truncated one are not distinguished, and the 256 bound drops the last chips in name order, so no consumer may read a missing entry as a removed sensor until the report carries completeness state. When one chip's @@ -272,6 +273,19 @@ complete `Sensors` result, peer omission and ingest through the frontend and read-state projections. The fixtures are inferred lm-sensors JSON, not exports from an installed host. +Mock Linux agent hosts carry a native inventory from `mockHostNativeSensors` +in `internal/mock/generator.go`: CPU core and two NVMe sensors whose labels +repeat across chips on every host, plus, on about one host in four (a stable +hash of the host ID), an Intel Mac's applesmc sensors with the battery +(`TB0T`), an implausible -127 °C reading that stays listed as `invalid`, and +a fan input. Values follow the host's existing temperature sample with fixed +offsets and refresh with the host's CPU sensors in the ordinary host update +(`updateHosts`, when random metrics are on), so mock mode exercises +the Thresholds sensor section and native sensor alerts with the same ID, +sort, status and kind rules as ingest. +`TestMockHostNativeSensorsMatchIngestedInventoryShape` and +`TestUpdateHostsRefreshesNativeSensorInventory` pin the shape and refresh. + ### Background backup scans belong to their configured connection PVE tasks, storage backups and guest snapshots share one in-flight owner per 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 4df69320e7..d3b537a07b 100644 --- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md +++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md @@ -452,6 +452,14 @@ reading takes one `SampleMetric` and rebuilds its core list (copied, never mutated in place), and each agent host rewrites its CPU keys from the sample it already took. No new timer, pass or fixture-wide scan is added. +Mock Linux agent hosts rebuild their native sensor inventory (at most ten +entries) in that same per-host update in `updateHosts`, from one more +`SampleMetric` and a stable hash, only when the host already has one. That is constant work per +host per tick; it adds no timer, pass or fixture-wide scan, and the Thresholds +sensor rows are derived in the existing host-data memo, which parses +configured sensor IDs once into a per-host map, so composition is linear in +reported plus configured sensors. + ### Unavailable filesystem values share the existing disk model The filesystem list and guest Overview use the same nullable measured-byte ratio diff --git a/frontend-modern/browser-verification/1eb7f5ad6cfc79d0.json b/frontend-modern/browser-verification/1eb7f5ad6cfc79d0.json new file mode 100644 index 0000000000..4dcda3ed28 --- /dev/null +++ b/frontend-modern/browser-verification/1eb7f5ad6cfc79d0.json @@ -0,0 +1,86 @@ +{ + "version": 1, + "base_sha": "faffec9441a10140bff1e9b8cc82a545155e4994", + "verified_at": "2026-11-01T11:12:00Z", + "result": "passed", + "changed_paths": [ + "frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx", + "frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx", + "frontend-modern/src/components/Alerts/ResourceTable.tsx", + "frontend-modern/src/components/Alerts/Thresholds/hooks/useCollapsedSections.ts", + "frontend-modern/src/components/Alerts/ThresholdsTableAgentSensorsSection.tsx", + "frontend-modern/src/components/Alerts/ThresholdsTableAgentsTab.tsx", + "frontend-modern/src/components/Alerts/alertResourceTableModel.ts", + "frontend-modern/src/features/alerts/AlertIntentPolicyPanel.tsx", + "frontend-modern/src/features/alerts/agentSensorIdentity.ts", + "frontend-modern/src/features/alerts/alertOverridesModel.ts", + "frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsAvailabilityMutations.ts", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsHostData.ts", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsOverrideMutations.ts", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsTableState.ts", + "frontend-modern/src/features/alerts/thresholds/tableTypes.ts", + "frontend-modern/src/features/alerts/thresholds/types.ts", + "frontend-modern/src/features/alerts/types.ts", + "frontend-modern/src/types/api.ts", + "frontend-modern/src/utils/alertThresholdsPresentation.ts" + ], + "content_sha256": { + "frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx": "26d9121cf18a62da503fbf45fed24190072565ee00e0f9421a88db3e43faa2ab", + "frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx": "82db0d7076c0452cdbafccee3bb3897d4bd49968199415d8b8feec8cfca06e99", + "frontend-modern/src/components/Alerts/ResourceTable.tsx": "c55572fe61c417cc5be639559c7d10eb0bf53e3941905d47dc992cb54f5d84df", + "frontend-modern/src/components/Alerts/Thresholds/hooks/useCollapsedSections.ts": "fe702e7fd6a25512b42be2b6dac833cda884de006d80dc3305fd9b9c395d05ea", + "frontend-modern/src/components/Alerts/ThresholdsTableAgentSensorsSection.tsx": "14b6c8449f8c9bbe5667c694111a7d96b3a13afe5563449823ee6fde439c3945", + "frontend-modern/src/components/Alerts/ThresholdsTableAgentsTab.tsx": "9086f095a9fc8f086bc2603acdf0e7ef8988769ba8456e81a26a4ec64948b54d", + "frontend-modern/src/components/Alerts/alertResourceTableModel.ts": "c4cb57d1a935c48a7ff9569dca0db73f5ca8dbb198fda9686173b189a436b876", + "frontend-modern/src/features/alerts/AlertIntentPolicyPanel.tsx": "442a8a7b0146aef22c77eb25de722299b7d842967a761641232bccc3a2fcd4b8", + "frontend-modern/src/features/alerts/agentSensorIdentity.ts": "be2138170040c3437a082ac9d6540ffd8470b9f0de12b290670f7116ce51787c", + "frontend-modern/src/features/alerts/alertOverridesModel.ts": "bc1d4f7db9e11eba3499876a7a454d54a7bd6b9d3efe70f9f6c7844d2f5191ac", + "frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx": "7dff533a9061298e696730e73a9f01861fc059d07a163ce61dd839dff62f0994", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsAvailabilityMutations.ts": "8eaf13cb4acf3042836f9f23595c63d4888f9572e445eef47b6269bb8e0f958d", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsHostData.ts": "1d70f2fa4b54c463ff04015cb912617f99075ed705b4cb618b517370be800516", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsOverrideMutations.ts": "677e6268fafbc87e8953cb26e7d2d38dbee848f1aa3cea4045d5f56582388367", + "frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsTableState.ts": "f3b70db9ba7d82e782a8937d860d7d4c999436e99badad462dcee43873c7769b", + "frontend-modern/src/features/alerts/thresholds/tableTypes.ts": "3234b55df9b465d3dbb64501e00a2d95897d026e018bf77ca4d7b08bb50a9708", + "frontend-modern/src/features/alerts/thresholds/types.ts": "94ad016ffb13bbc502558d8a53b47786975511250c22388f6f762cc068fa6852", + "frontend-modern/src/features/alerts/types.ts": "33d85b25ad07a723894314d4e17808c69b106544d15d1a6372274d267c86ba25", + "frontend-modern/src/types/api.ts": "44ac592b94964945639fa62ade84314ca71f9914dcc8765d95242a19be1aa67c", + "frontend-modern/src/utils/alertThresholdsPresentation.ts": "5317a78f48b29eae211d3f4ed515f633666c017afe0481e593fcd4ef4ec49fe7" + }, + "routes": [ + "/alerts/thresholds/systems", + "/alerts/thresholds/proxmox", + "/alerts/overview" + ], + "viewports": [ + { + "width": 1366, + "height": 900 + }, + { + "width": 375, + "height": 812 + } + ], + "states": [ + "Machines tab collapsed: Machine Sensors group after Machine Disks with count 23 and the line \"Off until a sensor has its own limit\"", + "Machine Sensors expanded on a private mock stack: rows grouped per machine, each one line with label, current reading and chip; every unconfigured sensor reads Off; no Global Defaults row and no Alerts column", + "Intel Mac mock host (Meridian-731) lists TB0T, TC0P and Th1H; the invalid TB1T and the fan input are not listed", + "Two NVMe drives labelled Composite on different chips read as two rows told apart by chip in the subtitle", + "TB0T with a saved 15\u00b0C limit: Custom badge and revert action; limit and its note survive a page reload and reappear in the reopened editor", + "Backend raised Meridian-731 (TB0T) temperature warning at 18.6\u00b0C against the 15\u00b0C limit; Alerts Overview shows it with alert and clear levels", + "TB0T switched Off with the note cleared: row reads Off with no Custom badge, the saved config has no sensor override and the backend resolved the alert", + "Delay editor opened from the TB0T row (desktop and phone) selects \"TB0T \u00b7 Meridian-731\" and Temperature threshold with preview disabled; a saved grace shows Remove override", + "Phone width: sensor cards show name, reading and chip, the limit and edit, delay and revert actions" + ], + "interactions": [ + "Collapse all, then expand Machine Sensors", + "Edit TB0T: switch the limit On, type 15, commit by clicking away, Save Changes; captured request stores agent:host-linux-4/sensor: with trigger 15 and clear 10", + "Edit TB0T again: add the note \"Battery: alert early\", save; captured request carries the note; reload and reopen the editor to find it", + "Edit TB0T: clear the note, switch the limit Off, save; captured request has no sensor override", + "Open the TB0T delay action, enter a 600 second grace and Save override; backend intent policy holds metric.temperature graceSeconds 600 for the sensor ID", + "Open the TB0T delay action from the phone card", + "Open Alerts Overview and find the TB0T alert card", + "Switch between 1366x900 and 375x812 viewports" + ] +} diff --git a/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx b/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx index 72a6bac84c..bc6cd77673 100644 --- a/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx +++ b/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx @@ -29,6 +29,8 @@ import { getAlertResourceMetricDisplayValue, getAlertResourceRelaxedTriggerSummary, isAlertResourceMetricOverridden, + getAlertResourceIntentTargetLabel, + getAlertResourcePreferredIntentSignal, normalizeAlertResourceMetricKey, } from './alertResourceTableModel'; import type { Resource } from '@/features/alerts/thresholds/tableTypes'; @@ -392,18 +394,13 @@ export function AlertResourceTableMobile(props: AlertResourceTableMobileProps) { { - const preferredMetric = ['cpu', 'memory', 'disk'].find( - (metric) => - props.table.columns.some( - (column) => normalizeAlertResourceMetricKey(column) === metric, - ) && alertResourceSupportsMetric(resource.type, metric), - ); + onClick={() => props.table.onConfigureResourceIntent?.( resource.id, - preferredMetric ? `metric.${preferredMetric}` : 'state.offline', - ); - }} + getAlertResourcePreferredIntentSignal(props.table.columns, resource.type), + getAlertResourceIntentTargetLabel(resource), + ) + } label={`Configure alert delay for ${getAlertResourceLabel(resource)}`} title="Configure individual alert delay" tone="neutral" diff --git a/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx b/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx index 6056c6a950..f8f10400ff 100644 --- a/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx +++ b/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx @@ -26,8 +26,10 @@ import { getAlertResourceColumnKind, getAlertResourceLabel, getAlertResourceInitialEditMetric, + getAlertResourceIntentTargetLabel, getAlertResourceMetricBounds, getAlertResourceMetricDisplayValue, + getAlertResourcePreferredIntentSignal, getAlertResourceRelaxedTriggerSummary, isAlertResourceMetricOff, isAlertResourceMetricOverridden, @@ -68,7 +70,11 @@ interface AlertResourceTableRowProps { onSetOfflineState?: (resourceId: string, state: OfflineState) => void; onToggleBackup?: (resourceId: string, forceState?: boolean) => void; onToggleSnapshot?: (resourceId: string, forceState?: boolean) => void; - onConfigureResourceIntent?: (resourceId: string, signal: AlertIntentSignal) => void; + onConfigureResourceIntent?: ( + resourceId: string, + signal: AlertIntentSignal, + label?: string, + ) => void; globalDisableFlag?: () => boolean; globalDisableOfflineFlag?: () => boolean; editingNote: () => string; @@ -102,17 +108,8 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) { props.editingThresholds(), isEditing(), ); - const preferredIntentSignal = (): AlertIntentSignal => { - for (const metric of ['cpu', 'memory', 'disk'] as const) { - if ( - props.columns.some((column) => normalizeAlertResourceMetricKey(column) === metric) && - alertResourceSupportsMetric(props.resource.type, metric) - ) { - return `metric.${metric}`; - } - } - return 'state.offline'; - }; + const preferredIntentSignal = (): AlertIntentSignal => + getAlertResourcePreferredIntentSignal(props.columns, props.resource.type); const getThresholds = (): AlertResourceThresholdMap => thresholds(); @@ -649,6 +646,7 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) { props.onConfigureResourceIntent?.( props.resource.id, preferredIntentSignal(), + getAlertResourceIntentTargetLabel(props.resource), ) } label={`Configure alert delay for ${resourceLabel()}`} diff --git a/frontend-modern/src/components/Alerts/ResourceTable.test.tsx b/frontend-modern/src/components/Alerts/ResourceTable.test.tsx index ba45b50501..b0b2ab2638 100644 --- a/frontend-modern/src/components/Alerts/ResourceTable.test.tsx +++ b/frontend-modern/src/components/Alerts/ResourceTable.test.tsx @@ -2369,7 +2369,7 @@ describe('ResourceTable', () => { fireEvent.click(screen.getByLabelText('Configure alert delay for Database VM')); - expect(onConfigureResourceIntent).toHaveBeenCalledWith('vm-1', 'metric.cpu'); + expect(onConfigureResourceIntent).toHaveBeenCalledWith('vm-1', 'metric.cpu', 'Database VM'); }); it('falls back to the offline signal when the row has no supported metric', () => { @@ -2383,7 +2383,38 @@ describe('ResourceTable', () => { fireEvent.click(screen.getByLabelText('Configure alert delay for Docker Host')); - expect(onConfigureResourceIntent).toHaveBeenCalledWith('docker-host-1', 'state.offline'); + expect(onConfigureResourceIntent).toHaveBeenCalledWith( + 'docker-host-1', + 'state.offline', + 'Docker Host', + ); + }); + + it('opens a machine sensor on its temperature signal, named with its machine', () => { + const onConfigureResourceIntent = vi.fn(); + const props = makeProps({ + resources: [ + makeResource({ + id: 'agent:host-1/sensor:6162', + name: 'TB0T', + type: 'agentSensor', + node: 'macbook-pve', + thresholds: {}, + defaults: { temperature: 0 }, + }), + ], + columns: ['Temp °C'], + onConfigureResourceIntent, + }); + render(() => ); + + fireEvent.click(screen.getByLabelText('Configure alert delay for TB0T')); + + expect(onConfigureResourceIntent).toHaveBeenCalledWith( + 'agent:host-1/sensor:6162', + 'metric.temperature', + 'TB0T · macbook-pve', + ); }); it('shows delay toggle button when showDelayColumn and onMetricDelayChange are provided', () => { diff --git a/frontend-modern/src/components/Alerts/ResourceTable.tsx b/frontend-modern/src/components/Alerts/ResourceTable.tsx index 8c28c22336..4e70819580 100644 --- a/frontend-modern/src/components/Alerts/ResourceTable.tsx +++ b/frontend-modern/src/components/Alerts/ResourceTable.tsx @@ -19,7 +19,11 @@ export type { GroupHeaderMeta, Resource } from '@/features/alerts/thresholds/tab export interface ResourceTableProps { title: string; - onConfigureResourceIntent?: (resourceId: string, signal: AlertIntentSignal) => void; + onConfigureResourceIntent?: ( + resourceId: string, + signal: AlertIntentSignal, + label?: string, + ) => void; resources?: Resource[]; groupedResources?: Record; columns: string[]; diff --git a/frontend-modern/src/components/Alerts/Thresholds/hooks/useCollapsedSections.ts b/frontend-modern/src/components/Alerts/Thresholds/hooks/useCollapsedSections.ts index 9ddb7bc4a5..4cb15349ea 100644 --- a/frontend-modern/src/components/Alerts/Thresholds/hooks/useCollapsedSections.ts +++ b/frontend-modern/src/components/Alerts/Thresholds/hooks/useCollapsedSections.ts @@ -30,6 +30,7 @@ const DEFAULT_COLLAPSED: CollapsedSectionsState = { pmg: true, agents: true, agentDisks: true, + agentSensors: true, dockerHosts: true, dockerContainers: true, kubernetesClusters: true, diff --git a/frontend-modern/src/components/Alerts/ThresholdsTableAgentSensorsSection.tsx b/frontend-modern/src/components/Alerts/ThresholdsTableAgentSensorsSection.tsx new file mode 100644 index 0000000000..1c5a196cbe --- /dev/null +++ b/frontend-modern/src/components/Alerts/ThresholdsTableAgentSensorsSection.tsx @@ -0,0 +1,64 @@ +import { Show } from 'solid-js'; +import Thermometer from 'lucide-solid/icons/thermometer'; + +import { ResourceTable } from './ResourceTable'; +import { CollapsibleSection } from './Thresholds/sections/CollapsibleSection'; +import { formatMetricValue } from '@/features/alerts/thresholds/helpers'; +import type { ThresholdsTableSectionProps } from '@/features/alerts/thresholds/thresholdsTableSectionProps'; + +const AGENT_SENSOR_THRESHOLD_COLUMNS = ['Temp °C']; +const AGENT_SENSOR_COLUMN_TOOLTIPS = { + 'Temp °C': 'Sensor temperature that raises an alert. Off until you set a limit.', +}; + +// Native lm-sensors temperatures, one row per sensor under its machine. A +// sensor alerts only on its own limit: there is no global default, so the +// section has no defaults row and every unconfigured sensor reads Off. The +// limit cell is the only switch, so there is no separate Alerts toggle. +export function ThresholdsTableAgentSensorsSection(props: ThresholdsTableSectionProps) { + const { state, tableProps } = props; + + return ( + + state.toggleSection('agentSensors')} + icon={} + isGloballyDisabled={tableProps.disableAllAgents()} + emptyMessage={state.AGENT_SENSORS_EMPTY_STATE} + > +
+ state.handleBulkEdit(ids, AGENT_SENSOR_THRESHOLD_COLUMNS)} + formatMetricValue={formatMetricValue} + hasActiveAlert={state.hasActiveAlert} + setHasUnsavedChanges={tableProps.setHasUnsavedChanges} + /> +
+
+
+ ); +} diff --git a/frontend-modern/src/components/Alerts/ThresholdsTableAgentsTab.tsx b/frontend-modern/src/components/Alerts/ThresholdsTableAgentsTab.tsx index b860b18953..20fa2f8c86 100644 --- a/frontend-modern/src/components/Alerts/ThresholdsTableAgentsTab.tsx +++ b/frontend-modern/src/components/Alerts/ThresholdsTableAgentsTab.tsx @@ -1,4 +1,5 @@ import { ThresholdsTableAgentDisksSection } from './ThresholdsTableAgentDisksSection'; +import { ThresholdsTableAgentSensorsSection } from './ThresholdsTableAgentSensorsSection'; import { ThresholdsTableAgentsResourcesSection } from './ThresholdsTableAgentsResourcesSection'; import { ThresholdsTableSMARTDefaultsCard } from './ThresholdsTableSMARTDefaultsCard'; import type { ThresholdsTableSectionProps } from '@/features/alerts/thresholds/thresholdsTableSectionProps'; @@ -9,6 +10,7 @@ export function ThresholdsTableAgentsTab(props: ThresholdsTableSectionProps) { {/* The groups and their default limits lead; disk health rules follow. */} + ); diff --git a/frontend-modern/src/components/Alerts/alertResourceTableModel.ts b/frontend-modern/src/components/Alerts/alertResourceTableModel.ts index c07bffa712..caa7cf4ad2 100644 --- a/frontend-modern/src/components/Alerts/alertResourceTableModel.ts +++ b/frontend-modern/src/components/Alerts/alertResourceTableModel.ts @@ -1,3 +1,4 @@ +import type { AlertIntentSignal } from '@/api/alertIntentPolicies'; import type { Resource as UnifiedResource, ResourcePolicy } from '@/types/resource'; import type { PlatformTableColumnKind } from '@/features/platformPage/columnAlignment'; import { getPreferredInfrastructureDisplayName } from '@/utils/resourceIdentity'; @@ -330,6 +331,35 @@ export function getAlertResourceInitialEditMetric(columns: string[], resourceTyp ); } +// The alert signal a row's delay action configures: its first threshold +// metric the resource supports, else its offline state. +export function getAlertResourcePreferredIntentSignal( + columns: readonly string[], + resourceType: string | undefined, +): AlertIntentSignal { + for (const metric of ['cpu', 'memory', 'disk', 'temperature'] as const) { + if ( + columns.some((column) => normalizeAlertResourceMetricKey(column) === metric) && + alertResourceSupportsMetric(resourceType, metric) + ) { + return `metric.${metric}`; + } + } + return 'state.offline'; +} + +// How the delay panel names a row it may not list itself, such as a machine +// disk or sensor: the row's label and, when known, its machine or node. +export function getAlertResourceIntentTargetLabel(resource: { + name: string; + displayName?: string; + node?: string; +}): string { + const label = resource.displayName?.trim() || resource.name; + const node = resource.node?.trim(); + return node && node !== label ? `${label} · ${node}` : label; +} + export function alertResourceSupportsMetric( resourceType: string | undefined, metric: string, @@ -347,6 +377,9 @@ export function alertResourceSupportsMetric( if (resourceType === 'storage') { return metric === 'usage'; } + if (resourceType === 'agentSensor') { + return metric === 'temperature'; + } if (resourceType === 'kubernetesNamespace') { return false; } diff --git a/frontend-modern/src/features/alerts/AlertIntentPolicyPanel.tsx b/frontend-modern/src/features/alerts/AlertIntentPolicyPanel.tsx index ef6e916db5..3dffe0156d 100644 --- a/frontend-modern/src/features/alerts/AlertIntentPolicyPanel.tsx +++ b/frontend-modern/src/features/alerts/AlertIntentPolicyPanel.tsx @@ -1,4 +1,4 @@ -import { For, Show, createEffect, createMemo, createSignal, onMount } from 'solid-js'; +import { For, Show, createEffect, createMemo, createSignal, onMount, untrack } from 'solid-js'; import { AlertIntentPoliciesAPI, @@ -27,6 +27,7 @@ const SIGNALS: ReadonlyArray<{ value: AlertIntentSignal; label: string }> = [ { value: 'metric.cpu', label: 'CPU threshold' }, { value: 'metric.memory', label: 'Memory threshold' }, { value: 'metric.disk', label: 'Disk threshold' }, + { value: 'metric.temperature', label: 'Temperature threshold' }, ]; const MAX_GRACE_SECONDS = 30 * 24 * 60 * 60; @@ -63,9 +64,16 @@ const ruleFor = ( export interface AlertIntentPolicySelectionTarget { resourceId: string; signal: AlertIntentSignal; + /** Names a target the resource list does not hold, such as a machine sensor. */ + label?: string; requestId: number; } +interface AlertIntentResourceOption { + id: string; + label: string; +} + export function AlertIntentPolicyPanel(props: { resources: readonly Resource[]; selectionTarget?: AlertIntentPolicySelectionTarget | null; @@ -93,6 +101,20 @@ export function AlertIntentPolicyPanel(props: { ), ), ); + // A row can target a child alert resource (a machine disk or sensor) that + // is not itself a listed resource. It joins the options under the row's own + // label rather than the selection falling back to an unrelated resource. + const [targetOption, setTargetOption] = createSignal(null); + const resourceOptions = createMemo(() => { + const listed = sortedResources().map((resource) => ({ + id: resource.id, + label: `${getPreferredInfrastructureDisplayName(resource)} · ${resource.type}`, + })); + const target = targetOption(); + return target && !listed.some((option) => option.id === target.id) + ? [target, ...listed] + : listed; + }); const [resourceId, setResourceId] = createSignal(''); const [signal, setSignal] = createSignal('state.offline'); const [overrideGrace, setOverrideGrace] = createSignal(''); @@ -130,8 +152,8 @@ export function AlertIntentPolicyPanel(props: { setBackupAware(offline.backupOffline?.enabled ?? false); setBackupPostGrace(String(offline.backupOffline?.postGraceSeconds ?? 60)); setBackupMaxDeferral(String(offline.backupOffline?.maxDeferralSeconds ?? 3600)); - if (!resourceId() && sortedResources().length > 0) { - setResourceId(sortedResources()[0].id); + if (!resourceId() && resourceOptions().length > 0) { + setResourceId(resourceOptions()[0].id); } } catch (cause) { setError(cause instanceof Error ? cause.message : 'Failed to load alert intent policies.'); @@ -143,14 +165,14 @@ export function AlertIntentPolicyPanel(props: { onMount(() => void load()); createEffect(() => { - const resources = sortedResources(); + const options = resourceOptions(); const selected = resourceId(); - if (resources.length === 0) { + if (options.length === 0) { if (selected) setResourceId(''); return; } - if (!resources.some((resource) => resource.id === selected)) { - setResourceId(resources[0].id); + if (!options.some((option) => option.id === selected)) { + setResourceId(options[0].id); } }); @@ -158,6 +180,14 @@ export function AlertIntentPolicyPanel(props: { const target = props.selectionTarget; if (!target) return; const requestId = target.requestId; + // Untracked: a later inventory change must not replay this handoff over + // a selection the operator has changed since. + const listed = untrack(() => + sortedResources().some((resource) => resource.id === target.resourceId), + ); + setTargetOption( + listed ? null : { id: target.resourceId, label: target.label?.trim() || target.resourceId }, + ); setResourceId(target.resourceId); setSignal(target.signal); setExpanded(true); @@ -509,12 +539,8 @@ export function AlertIntentPolicyPanel(props: { onChange={(event) => setResourceId(event.currentTarget.value)} fieldClass="lg:col-span-2" > - - {(resource) => ( - - )} + + {(option) => } void runPreview()} > Preview current policy diff --git a/frontend-modern/src/features/alerts/__tests__/AlertIntentPolicyPanel.test.tsx b/frontend-modern/src/features/alerts/__tests__/AlertIntentPolicyPanel.test.tsx index 00f2b7b735..52fbb80bc0 100644 --- a/frontend-modern/src/features/alerts/__tests__/AlertIntentPolicyPanel.test.tsx +++ b/frontend-modern/src/features/alerts/__tests__/AlertIntentPolicyPanel.test.tsx @@ -96,6 +96,61 @@ describe('AlertIntentPolicyPanel', () => { expect(screen.getByLabelText('Signal')).toHaveValue('metric.memory'); }); + it('keeps a row-selected machine sensor that the resource list does not hold', async () => { + const sensorId = 'agent:host-1/sensor:6170706c65736d632d6973612d303330302f74656d7031'; + render(() => ( + + )); + + expect(await screen.findByRole('button', { name: 'Hide policies' })).toBeInTheDocument(); + const select = screen.getByLabelText('Resource'); + expect(select).toHaveValue(sensorId); + expect(screen.getByRole('option', { name: 'TB0T · macbook-pve' })).toBeInTheDocument(); + expect(screen.getByLabelText('Signal')).toHaveValue('metric.temperature'); + expect(screen.getByRole('button', { name: 'Preview current policy' })).toBeDisabled(); + + fireEvent.input(await screen.findByLabelText(/^Grace override \(seconds\)/), { + target: { value: '600' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Save override' })); + + await waitFor(() => expect(AlertIntentPoliciesAPI.update).toHaveBeenCalledTimes(1)); + const saved = vi.mocked(AlertIntentPoliciesAPI.update).mock.calls[0][0]; + expect(saved.resources?.[sensorId]?.['metric.temperature']).toEqual({ graceSeconds: 600 }); + }); + + it('does not replay a row handoff when the resource list changes', async () => { + const sensorId = 'agent:host-1/sensor:6162'; + const [resources, setResources] = createSignal([resource]); + render(() => ( + + )); + + const select = await screen.findByLabelText('Resource'); + fireEvent.change(select, { target: { value: resource.id } }); + fireEvent.change(screen.getByLabelText('Signal'), { target: { value: 'metric.cpu' } }); + setResources([resource, { ...resource, id: 'vm-other', name: 'other', displayName: 'other' }]); + + await waitFor(() => expect(screen.getByLabelText('Resource')).toHaveValue(resource.id)); + expect(screen.getByLabelText('Signal')).toHaveValue('metric.cpu'); + }); + it('saves field-level resource overrides without disabling inherited policy', async () => { render(() => ); diff --git a/frontend-modern/src/features/alerts/agentSensorIdentity.ts b/frontend-modern/src/features/alerts/agentSensorIdentity.ts new file mode 100644 index 0000000000..c786071078 --- /dev/null +++ b/frontend-modern/src/features/alerts/agentSensorIdentity.ts @@ -0,0 +1,33 @@ +const AGENT_SENSOR_RESOURCE_ID_PATTERN = /^agent:(.+)\/sensor:((?:[0-9a-f]{2})+)$/; + +// The alert resource ID of one native sensor, as the backend builds it +// (internal/alerts/host_native_sensor.go HostNativeSensorResourceID): +// "agent:/sensor:". +// The hex form keeps sensor IDs that differ only by case or punctuation apart. +export const agentSensorResourceId = (hostId: string, sensorId: string): string => { + const hex = Array.from(new TextEncoder().encode(sensorId), (byte) => + byte.toString(16).padStart(2, '0'), + ).join(''); + return `agent:${hostId.trim() || 'unknown'}/sensor:${hex}`; +}; + +// The host ID and sensor ID an agentSensorResourceId encodes, or null when +// the ID is not a native sensor resource. +export const parseAgentSensorResourceId = ( + resourceId: string, +): { hostId: string; sensorId: string } | null => { + const match = resourceId.match(AGENT_SENSOR_RESOURCE_ID_PATTERN); + if (!match) return null; + const bytes = new Uint8Array(match[2].length / 2); + for (let index = 0; index < bytes.length; index += 1) { + bytes[index] = parseInt(match[2].slice(index * 2, index * 2 + 2), 16); + } + try { + return { + hostId: match[1], + sensorId: new TextDecoder('utf-8', { fatal: true }).decode(bytes), + }; + } catch { + return null; + } +}; diff --git a/frontend-modern/src/features/alerts/alertOverridesModel.ts b/frontend-modern/src/features/alerts/alertOverridesModel.ts index f39cb23a6d..d1f68cb201 100644 --- a/frontend-modern/src/features/alerts/alertOverridesModel.ts +++ b/frontend-modern/src/features/alerts/alertOverridesModel.ts @@ -4,6 +4,7 @@ import type { Resource } from '@/types/resource'; import { getActionableAgentIdFromResource, isTrueNASSystemResource } from '@/utils/agentResources'; import { isAppContainerDiscoveryResourceType } from '@/utils/discoveryTarget'; +import { parseAgentSensorResourceId } from './agentSensorIdentity'; import { extractTriggerValues, getAlertResourceDisplayLabel, @@ -313,7 +314,15 @@ export const buildProjectedOverrides = ({ { resource: Resource; type: Override['type']; resourceType: string } >(); - const upsertProjectedOverride = (override: Override) => { + // Every projection is keyed by its raw override key, so the stored note is + // carried here once for all resource types. Without it a reloaded editor + // opens with a blank note and the next save drops the stored one. + const upsertProjectedOverride = (projected: Override) => { + const storedNote = rawConfig[projected.id]?.note; + const override = + projected.note === undefined && typeof storedNote === 'string' && storedNote.trim() + ? { ...projected, note: storedNote } + : projected; const existingIndex = overrideIndexByID.get(override.id); if (existingIndex !== undefined) { overridesList[existingIndex] = override; @@ -588,6 +597,21 @@ export const buildProjectedOverrides = ({ return; } + const sensorKey = parseAgentSensorResourceId(key); + if (sensorKey) { + const agent = agentMap.get(sensorKey.hostId); + upsertProjectedOverride({ + id: key, + name: sensorKey.sensorId, + type: 'agentSensor', + resourceType: 'Machine Sensor', + node: agent ? getAlertResourceDisplayLabel(agent) : sensorKey.hostId, + disabled: thresholds.disabled || false, + thresholds: extractTriggerValues(thresholds), + }); + return; + } + const diskMatch = key.match(/^agent:(.+)\/disk:(.+)$/); if (diskMatch) { const [, agentId, diskLabel] = diskMatch; diff --git a/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx b/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx index 78421cddf3..bc17e22a4e 100644 --- a/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx +++ b/frontend-modern/src/features/alerts/tabs/ThresholdsTab.tsx @@ -15,11 +15,16 @@ export function ThresholdsTab(props: ThresholdsTabProps) { createSignal(null); let intentSelectionRequest = 0; - const configureResourceIntent = (resourceId: string, signal: AlertIntentSignal) => { + const configureResourceIntent = ( + resourceId: string, + signal: AlertIntentSignal, + label?: string, + ) => { intentSelectionRequest += 1; setIntentSelectionTarget({ resourceId, signal, + label, requestId: intentSelectionRequest, }); }; diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsHostData.agentSensors.test.ts b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsHostData.agentSensors.test.ts new file mode 100644 index 0000000000..282b416d7f --- /dev/null +++ b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsHostData.agentSensors.test.ts @@ -0,0 +1,264 @@ +import { createRoot, createSignal } from 'solid-js'; +import { describe, expect, it } from 'vitest'; + +import { buildProjectedOverrides } from '@/features/alerts/alertOverridesModel'; +import { + agentSensorResourceId, + parseAgentSensorResourceId, +} from '@/features/alerts/agentSensorIdentity'; +import type { HostNativeSensor } from '@/types/api'; +import type { Resource } from '@/types/resource'; + +import type { Override, ThresholdsTableProps } from '../../types'; +import { useThresholdsHostData } from '../useThresholdsHostData'; + +const sensor = ( + chip: string, + channel: string, + label: string, + value: number | undefined, + status: HostNativeSensor['status'] = 'ok', + kind: HostNativeSensor['kind'] = 'temperature', +): HostNativeSensor => ({ + id: `${chip}/${channel}`, + chip, + channel, + label, + kind, + unit: kind === 'fan' ? 'rpm' : 'celsius', + value, + status, +}); + +const machine = ( + id: string, + hostId: string, + name: string, + native: HostNativeSensor[], + status: Resource['status'] = 'online', +): Resource => + ({ + id, + name, + displayName: name, + type: 'agent', + status, + agent: { agentId: hostId, sensors: { native } }, + }) as unknown as Resource; + +const sensorOverride = (hostId: string, sensorId: string, trigger: number): Override => ({ + id: agentSensorResourceId(hostId, sensorId), + name: sensorId, + type: 'agentSensor', + thresholds: { temperature: trigger }, +}); + +const sensorRows = (agents: Resource[], overrides: Override[] = [], search = '') => + createRoot((dispose) => { + const [term] = createSignal(search); + const data = useThresholdsHostData({ + props: { + agents, + overrides: () => overrides, + agentDefaults: {}, + nodeDefaults: {}, + } as unknown as ThresholdsTableProps, + editingId: () => null, + searchTerm: term, + }); + const rows = data.agentSensorsWithOverrides(); + const groups = data.agentSensorsGroupedByAgent(); + dispose(); + return { rows, groups }; + }); + +describe('agentSensorResourceId', () => { + it('builds the backend alert resource ID from the UTF-8 hex of the sensor ID', () => { + expect(agentSensorResourceId('host-1', 'applesmc-isa-0300/temp1')).toBe( + 'agent:host-1/sensor:6170706c65736d632d6973612d303330302f74656d7031', + ); + // Case-only differences stay distinct, as the backend keeps them. + expect(agentSensorResourceId('host-1', 'chip/TEMP1')).not.toBe( + agentSensorResourceId('host-1', 'chip/temp1'), + ); + }); + + it('round-trips through parseAgentSensorResourceId and rejects other IDs', () => { + const id = agentSensorResourceId('host:1', 'nvme-pci-0100/temp1'); + expect(parseAgentSensorResourceId(id)).toEqual({ + hostId: 'host:1', + sensorId: 'nvme-pci-0100/temp1', + }); + expect(parseAgentSensorResourceId('agent:host-1/disk:root')).toBeNull(); + expect(parseAgentSensorResourceId('agent:host-1/sensor:abc')).toBeNull(); + expect(parseAgentSensorResourceId('agent:host-1/sensor:ff')).toBeNull(); + }); +}); + +describe('useThresholdsHostData machine sensors', () => { + it('lists usable temperature sensors under their machine, Off by default', () => { + const mac = machine('agent-res-1', 'host-1', 'macbook-pve', [ + sensor('applesmc-isa-0300', 'temp1', 'TB0T', 31.5), + sensor('applesmc-isa-0300', 'temp2', 'TB1T', -127, 'invalid'), + sensor('applesmc-isa-0300', 'fan1', 'Left side', 1800, 'ok', 'fan'), + ]); + + const { rows, groups } = sensorRows([mac]); + + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + id: agentSensorResourceId('host-1', 'applesmc-isa-0300/temp1'), + name: 'TB0T', + rawName: 'applesmc-isa-0300/temp1', + type: 'agentSensor', + node: 'macbook-pve', + instance: 'applesmc-isa-0300', + subtitle: '31.5°C · applesmc-isa-0300', + defaults: { temperature: 0 }, + thresholds: {}, + hasOverride: false, + }); + expect(rows[0].readingMessage).toBeUndefined(); + expect(Object.keys(groups)).toEqual(['agent-res-1']); + }); + + it('keeps configured sensors that read invalid or went missing', () => { + const mac = machine('agent-res-1', 'host-1', 'macbook-pve', [ + sensor('applesmc-isa-0300', 'temp2', 'TB1T', -127, 'invalid'), + ]); + + const { rows } = sensorRows( + [mac], + [ + sensorOverride('host-1', 'applesmc-isa-0300/temp2', 45), + sensorOverride('host-1', 'applesmc-isa-0300/temp9', 50), + ], + ); + + const byName = new Map(rows.map((row) => [row.name, row])); + expect(byName.get('TB1T')).toMatchObject({ + hasOverride: true, + thresholds: { temperature: 45 }, + subtitle: 'applesmc-isa-0300', + readingMessage: 'No valid reading from this sensor.', + }); + expect(byName.get('applesmc-isa-0300/temp9')).toMatchObject({ + hasOverride: true, + thresholds: { temperature: 50 }, + readingMessage: 'Not reported by this machine. Saved alert settings are retained.', + }); + }); + + it('keeps a saved zero limit removable and carries the override note', () => { + const mac = machine('agent-res-1', 'host-1', 'macbook-pve', [ + sensor('applesmc-isa-0300', 'temp1', 'TB0T', 31.5), + ]); + const saved: Override = { + ...sensorOverride('host-1', 'applesmc-isa-0300/temp1', 0), + note: 'battery swelling watch', + }; + + const { rows } = sensorRows([mac], [saved]); + + expect(rows[0]).toMatchObject({ + hasOverride: true, + presentationDefaults: true, + note: 'battery swelling watch', + thresholds: { temperature: 0 }, + }); + }); + + it('shows no current reading for a machine that is not reporting', () => { + const offline = machine( + 'agent-res-1', + 'host-1', + 'macbook-pve', + [sensor('applesmc-isa-0300', 'temp1', 'TB0T', 31.5)], + 'offline', + ); + + const { rows } = sensorRows( + [offline], + [sensorOverride('host-1', 'applesmc-isa-0300/temp1', 45)], + ); + + expect(rows).toHaveLength(1); + expect(rows[0].subtitle).toBe('applesmc-isa-0300'); + expect(rows[0].readingMessage).toBe( + 'Machine is not reporting, so there is no current reading.', + ); + }); + + it('tells repeated labels apart and keeps same-named machines apart', () => { + const first = machine('agent-res-1', 'host-1', 'pve', [ + sensor('nvme-pci-0100', 'temp1', 'Composite', 40), + sensor('nvme-pci-0200', 'temp1', 'Composite', 42), + sensor('acpitz-acpi-0', 'temp1', 'temp', 30), + sensor('acpitz-acpi-0', 'temp2', 'temp', 31), + ]); + const second = machine('agent-res-2', 'host-2', 'pve', [ + sensor('coretemp-isa-0000', 'temp1', 'Package id 0', 50), + ]); + + const { rows, groups } = sensorRows([first, second]); + + // Across chips the subtitle's chip tells the rows apart; within one chip + // the channel joins the name. + expect(groups['agent-res-1'].map((row) => [row.name, row.subtitle])).toEqual([ + ['Composite', '40.0°C · nvme-pci-0100'], + ['Composite', '42.0°C · nvme-pci-0200'], + ['temp (temp1)', '30.0°C · acpitz-acpi-0'], + ['temp (temp2)', '31.0°C · acpitz-acpi-0'], + ]); + expect(groups['agent-res-2'].map((row) => row.name)).toEqual(['Package id 0']); + expect(new Set(rows.map((row) => row.id)).size).toBe(5); + }); + + it('keeps an override whose machine is gone, and searches by sensor ID', () => { + const { rows, groups } = sensorRows([], [sensorOverride('ghost', 'chip/temp1', 60)]); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + name: 'chip/temp1', + node: 'ghost', + readingMessage: 'Machine not found. Saved alert settings are retained.', + }); + expect(Object.keys(groups)).toEqual(['ghost']); + + const mac = machine('agent-res-1', 'host-1', 'macbook-pve', [ + sensor('applesmc-isa-0300', 'temp1', 'TB0T', 31.5), + sensor('coretemp-isa-0000', 'temp1', 'Package id 0', 50), + ]); + expect(sensorRows([mac], [], 'applesmc').rows.map((row) => row.name)).toEqual(['TB0T']); + }); +}); + +describe('buildProjectedOverrides machine sensors', () => { + it('projects a sensor override with its sensor ID and machine name', () => { + const mac = machine('agent-res-1', 'host-1', 'macbook-pve', []); + const id = agentSensorResourceId('host-1', 'applesmc-isa-0300/temp1'); + + const projected = buildProjectedOverrides({ + rawConfig: { [id]: { temperature: { trigger: 45, clear: 40 }, note: 'battery' } }, + nodeResources: [], + vmResources: [], + containerResources: [], + storageResources: [], + agentResourceList: [mac], + containerRuntimeResources: [], + getChildren: () => [], + pbsInstanceById: new Map(), + allResources: [mac], + } as unknown as Parameters[0]); + + expect(projected).toEqual([ + expect.objectContaining({ + id, + note: 'battery', + name: 'applesmc-isa-0300/temp1', + type: 'agentSensor', + node: 'macbook-pve', + thresholds: { temperature: 45 }, + }), + ]); + }); +}); diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsOverrideMutations.test.tsx b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsOverrideMutations.test.tsx index 36711fff29..0c7e9a5777 100644 --- a/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsOverrideMutations.test.tsx +++ b/frontend-modern/src/features/alerts/thresholds/hooks/__tests__/useThresholdsOverrideMutations.test.tsx @@ -112,6 +112,116 @@ describe('useThresholdsOverrideMutations', () => { expect(cancelEdit).toHaveBeenCalledTimes(1); }); + it('saves a machine sensor limit and drops the override when it is switched Off', () => { + const overrideSignal = createSignal([]); + const { props, rawOverridesConfig } = buildTableProps(overrideSignal); + const [editingThresholds, setEditingThresholds] = createSignal< + Record + >({ temperature: 45 }); + const [editingNote] = createSignal(''); + const [bulkEditIds] = createSignal([]); + const cancelEdit = vi.fn(); + const sensorId = 'agent:host-1/sensor:6170706c65736d632d6973612d303330302f74656d7031'; + const [sensorRow, setSensorRow] = createSignal({ + id: sensorId, + name: 'TB0T', + type: 'agentSensor', + resourceType: 'Machine Sensor', + node: 'macbook-pve', + instance: 'applesmc-isa-0300', + defaults: { temperature: 0 }, + presentationDefaults: true, + thresholds: {}, + }); + + const { result } = renderHook(() => + useThresholdsOverrideMutations({ + props, + resources: { + nodesWithOverrides: () => [], + agentsWithOverrides: () => [], + agentDisksWithOverrides: () => [], + agentSensorsWithOverrides: () => [sensorRow()], + dockerHostsWithOverrides: () => [], + guestsFlat: () => [], + dockerContainersFlat: () => [], + pbsServersWithOverrides: () => [], + pmgServersWithOverrides: () => [], + storageWithOverrides: () => [], + }, + editingThresholds, + editingNote, + bulkEditIds, + cancelEdit, + }), + ); + + result.saveEdit(sensorId); + + expect(overrideSignal[0]()).toEqual([ + expect.objectContaining({ + id: sensorId, + type: 'agentSensor', + thresholds: { temperature: 45 }, + }), + ]); + expect(rawOverridesConfig()).toEqual({ + [sensorId]: { temperature: { trigger: 45, clear: 40 } }, + }); + + setSensorRow((row) => ({ ...row, hasOverride: true, thresholds: { temperature: 45 } })); + setEditingThresholds({ temperature: -1 }); + result.saveEdit(sensorId); + + expect(overrideSignal[0]()).toEqual([]); + expect(rawOverridesConfig()).toEqual({}); + }); + + it('keeps an explicit Off over an Off inherited default on ordinary rows', () => { + const overrideSignal = createSignal([]); + const { props, rawOverridesConfig } = buildTableProps(overrideSignal); + const [editingThresholds] = createSignal>({ cpu: -1 }); + const [editingNote] = createSignal(''); + const [bulkEditIds] = createSignal([]); + const machine: TableResource = { + id: 'host-1', + name: 'pve', + type: 'agent', + resourceType: 'System', + defaults: { cpu: 0 }, + thresholds: {}, + }; + + const { result } = renderHook(() => + useThresholdsOverrideMutations({ + props, + resources: { + nodesWithOverrides: () => [], + agentsWithOverrides: () => [machine], + agentDisksWithOverrides: () => [], + dockerHostsWithOverrides: () => [], + guestsFlat: () => [], + dockerContainersFlat: () => [], + pbsServersWithOverrides: () => [], + pmgServersWithOverrides: () => [], + storageWithOverrides: () => [], + }, + editingThresholds, + editingNote, + bulkEditIds, + cancelEdit: vi.fn(), + }), + ); + + result.saveEdit('host-1'); + + // The default may be switched back on later; the machine's Off must stay. + expect(overrideSignal[0]()).toEqual([ + expect.objectContaining({ id: 'host-1', thresholds: { cpu: -1 } }), + ]); + expect(Object.keys(rawOverridesConfig())).toEqual(['host-1']); + }); + it('bulk-saves guest filesystem thresholds under the stable override identity', () => { const overrideSignal = createSignal([]); const { props, rawOverridesConfig } = buildTableProps(overrideSignal); diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsAvailabilityMutations.ts b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsAvailabilityMutations.ts index 0c7df6c540..a092194695 100644 --- a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsAvailabilityMutations.ts +++ b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsAvailabilityMutations.ts @@ -23,6 +23,7 @@ interface ThresholdsAvailabilityMutationResources { nodesWithOverrides: () => TableResource[]; agentsWithOverrides: () => TableResource[]; agentDisksWithOverrides: () => TableResource[]; + agentSensorsWithOverrides?: () => TableResource[]; guestDisksWithOverrides?: () => TableResource[]; dockerHostsWithOverrides: () => TableResource[]; guestsFlat: () => TableResource[]; @@ -76,6 +77,7 @@ export function useThresholdsAvailabilityMutations({ ...resources.pbsServersWithOverrides(), ...resources.agentsWithOverrides(), ...resources.agentDisksWithOverrides(), + ...optionalResources(resources.agentSensorsWithOverrides), ...optionalResources(resources.guestDisksWithOverrides), ...optionalResources(resources.kubernetesClustersWithOverrides), ...optionalResources(resources.kubernetesNodesWithOverrides), @@ -100,6 +102,7 @@ export function useThresholdsAvailabilityMutations({ resource.type !== 'dockerContainer' && resource.type !== 'agent' && resource.type !== 'agentDisk' && + resource.type !== 'agentSensor' && resource.type !== 'guestDisk' && resource.type !== 'kubernetesCluster' && resource.type !== 'kubernetesNode' && diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsHostData.ts b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsHostData.ts index 22810065a2..24f6d5696a 100644 --- a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsHostData.ts +++ b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsHostData.ts @@ -1,6 +1,11 @@ import { createMemo } from 'solid-js'; +import { + parseAgentSensorResourceId, + agentSensorResourceId, +} from '@/features/alerts/agentSensorIdentity'; import { getAlertResourceDisplayLabel } from '@/features/alerts/helpers'; +import { formatTemperature } from '@/utils/temperature'; import type { GroupHeaderMeta, Resource as TableResource } from '../tableTypes'; import { ThresholdsDataInputs } from '../thresholdsResourceModel'; @@ -277,6 +282,153 @@ export function useThresholdsHostData(inputs: ThresholdsDataInputs) { return grouped; }); + // One row per usable temperature sensor a machine reports, plus every sensor + // that has saved alert settings, so a configured sensor stays editable and + // removable while it reads invalid, has gone missing or its machine is + // offline. Sensors have no global default: the presentation default of 0 + // makes an unconfigured row read Off, which is what the alert engine does. + const agentSensorsWithOverrides = createMemo((prev = []) => { + if (editingId()) { + return prev; + } + + const search = searchTerm().toLowerCase(); + const overridesMap = createOverridesMap(props.overrides()); + // Configured sensor IDs parsed once, by host, so each machine reads only + // its own entries. + const configuredSensorIdsByHost = new Map(); + (props.overrides() ?? []).forEach((override) => { + if (override.type !== 'agentSensor') return; + const parsed = parseAgentSensorResourceId(override.id); + if (!parsed) return; + const ids = configuredSensorIdsByHost.get(parsed.hostId) ?? []; + ids.push(parsed.sensorId); + configuredSensorIdsByHost.set(parsed.hostId, ids); + }); + const seen = new Set(); + const sensors: TableResource[] = []; + + (props.agents ?? []).forEach((agentResource) => { + const hostId = readString(agentResource.agent?.agentId) || hostActionId(agentResource); + const agentDisplayName = getAlertResourceDisplayLabel(agentResource); + const hostReporting = + agentResource.status !== 'offline' && agentResource.agent?.stale !== true; + const reported = (agentResource.agent?.sensors?.native ?? []).filter( + (sensor) => sensor.kind === 'temperature', + ); + const reportedById = new Map(reported.map((sensor) => [sensor.id, sensor])); + const labelCounts = new Map(); + reported.forEach((sensor) => { + const labelKey = `${sensor.chip}\u0000${sensor.label}`; + labelCounts.set(labelKey, (labelCounts.get(labelKey) ?? 0) + 1); + }); + + const sensorIds = new Set( + reported.filter((sensor) => sensor.status === 'ok').map((sensor) => sensor.id), + ); + configuredSensorIdsByHost.get(hostId)?.forEach((sensorId) => sensorIds.add(sensorId)); + + sensorIds.forEach((sensorId) => { + const resourceId = agentSensorResourceId(hostId, sensorId); + const override = overridesMap.get(resourceId); + const sensor = reportedById.get(sensorId); + const label = sensor?.label.trim() || sensorId; + const name = + sensor && (labelCounts.get(`${sensor.chip}\u0000${sensor.label}`) ?? 0) > 1 + ? `${label} (${sensor.channel})` + : label; + const chip = sensor?.chip || sensorId.split('/')[0] || ''; + let readingMessage: string | undefined; + let reading: string | undefined; + if (!sensor) { + readingMessage = 'Not reported by this machine. Saved alert settings are retained.'; + } else if (!hostReporting) { + readingMessage = 'Machine is not reporting, so there is no current reading.'; + } else if (sensor.status !== 'ok' || typeof sensor.value !== 'number') { + readingMessage = 'No valid reading from this sensor.'; + } else { + reading = formatTemperature(sensor.value, { decimals: 1 }); + } + + seen.add(resourceId); + sensors.push({ + id: resourceId, + name, + displayName: name, + rawName: sensorId, + type: 'agentSensor' as const, + resourceType: 'Machine Sensor', + groupKey: agentResource.id, + node: agentDisplayName, + instance: chip, + status: agentResource.status, + // The default is presentation-only, so any stored entry is an + // override: a saved 0 stays visible and removable. + hasOverride: Boolean(override), + note: override?.note, + disabled: override?.disabled || false, + thresholds: override?.thresholds || {}, + defaults: { temperature: 0 }, + presentationDefaults: true, + subtitle: reading ? `${reading} · ${chip}` : chip, + readingMessage, + } satisfies TableResource); + }); + }); + + (props.overrides() ?? []) + .filter((override) => override.type === 'agentSensor' && !seen.has(override.id)) + .forEach((override) => { + const parsed = parseAgentSensorResourceId(override.id); + const name = parsed?.sensorId || override.name || override.id; + sensors.push({ + id: override.id, + name, + displayName: name, + rawName: name, + type: 'agentSensor' as const, + resourceType: 'Machine Sensor', + groupKey: parsed?.hostId || override.node || 'Unknown Machine', + node: override.node || parsed?.hostId || 'Unknown Machine', + instance: '', + status: 'unknown', + hasOverride: true, + disabled: override.disabled || false, + thresholds: override.thresholds || {}, + defaults: { temperature: 0 }, + presentationDefaults: true, + note: override.note, + readingMessage: 'Machine not found. Saved alert settings are retained.', + } satisfies TableResource); + }); + + return search + ? sensors.filter( + (sensor) => + sensor.name.toLowerCase().includes(search) || + sensor.rawName?.toLowerCase().includes(search) || + sensor.node?.toLowerCase().includes(search), + ) + : sensors; + }, []); + + // Grouped by the machine's resource ID, not its display name, so two + // machines with the same name keep separate sensor lists. + const agentSensorsGroupedByAgent = createMemo>(() => { + const grouped: Record = {}; + agentSensorsWithOverrides().forEach((sensor) => { + const key = + typeof sensor.groupKey === 'string' && sensor.groupKey + ? sensor.groupKey + : 'Unknown Machine'; + (grouped[key] ??= []).push(sensor); + }); + Object.values(grouped).forEach((resources) => { + resources.sort((a, b) => a.name.localeCompare(b.name)); + }); + return grouped; + }); + const agentGroupHeaderMeta = createMemo>(() => { const meta: Record = {}; (props.agents ?? []).forEach((agent) => { @@ -293,6 +445,8 @@ export function useThresholdsHostData(inputs: ThresholdsDataInputs) { agentsWithOverrides, agentDisksWithOverrides, agentDisksGroupedByAgent, + agentSensorsWithOverrides, + agentSensorsGroupedByAgent, agentGroupHeaderMeta, }; } diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsOverrideMutations.ts b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsOverrideMutations.ts index 2391949cc7..5701e3bc1b 100644 --- a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsOverrideMutations.ts +++ b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsOverrideMutations.ts @@ -1,5 +1,6 @@ import type { Accessor } from 'solid-js'; +import { alertResourceThresholdsEquivalent } from '@/components/Alerts/alertResourceTableModel'; import type { RawOverrideConfig } from '@/types/alerts'; import type { Override, @@ -23,6 +24,7 @@ interface ThresholdsOverrideMutationResources { nodesWithOverrides: Accessor; agentsWithOverrides: Accessor; agentDisksWithOverrides: Accessor; + agentSensorsWithOverrides?: Accessor; guestDisksWithOverrides?: Accessor; dockerHostsWithOverrides: Accessor; guestsFlat: Accessor; @@ -69,6 +71,7 @@ export function useThresholdsOverrideMutations({ ...resources.nodesWithOverrides(), ...resources.agentsWithOverrides(), ...resources.agentDisksWithOverrides(), + ...optionalResources(resources.agentSensorsWithOverrides), ...optionalResources(resources.guestDisksWithOverrides), ...resources.dockerHostsWithOverrides(), ...resources.pbsServersWithOverrides(), @@ -95,6 +98,19 @@ export function useThresholdsOverrideMutations({ const findThresholdResource = (resourceId: string) => allThresholdResources().find((entry) => entry.id === resourceId); + // An edited value that equals the row's default stores nothing. Where the + // defaults are presentation-only (machine sensors, which have no default), + // any Off value equals the Off default; elsewhere an explicit Off stays an + // override, so it survives a later change to the inherited default. + const matchesDefault = ( + resource: TableResource, + value: number | undefined, + defaultValue: number | undefined, + ) => + resource.presentationDefaults + ? alertResourceThresholdsEquivalent(value, defaultValue) + : value === defaultValue; + const removeOverride = (resourceId: string) => { const resource = findThresholdResource(resourceId); props.setOverrides(stripOverrideCandidates(props.overrides(), resource)); @@ -121,7 +137,7 @@ export function useThresholdsOverrideMutations({ if (key === 'backup' || key === 'snapshot') return; const editedValue = editedThresholdMap[key]; const defaultValue = defaultThresholds[key]; - if (editedValue !== undefined && editedValue !== defaultValue) { + if (editedValue !== undefined && !matchesDefault(resource, editedValue, defaultValue)) { overrideThresholds[key] = editedValue; } }); @@ -246,7 +262,7 @@ export function useThresholdsOverrideMutations({ if (key === 'backup' || key === 'snapshot') return; if (thresholds[key] !== undefined) { const value = thresholds[key]; - if (value === defaultThresholds[key]) { + if (matchesDefault(resource, value, defaultThresholds[key])) { delete newThresholds[key]; } else { newThresholds[key] = value as number; diff --git a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsTableState.ts b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsTableState.ts index a24a8747a7..aa00583bd3 100644 --- a/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsTableState.ts +++ b/frontend-modern/src/features/alerts/thresholds/hooks/useThresholdsTableState.ts @@ -9,6 +9,8 @@ import { logger } from '@/utils/logger'; import { AGENT_DISKS_EMPTY_STATE, AGENT_DISKS_FILTER_EMPTY_STATE, + AGENT_SENSORS_EMPTY_STATE, + AGENT_SENSORS_FILTER_EMPTY_STATE, AGENT_THRESHOLDS_FILTER_EMPTY_STATE, getAlertThresholdsHelpBanner, getAlertThresholdsGuestFilterPresentation, @@ -56,6 +58,7 @@ const HELP_BANNER_KEY = 'pulse-thresholds-help-dismissed'; interface ThresholdsSummaryItem { key: | 'agentDisks' + | 'agentSensors' | 'agents' | 'backups' | 'dockerContainers' @@ -276,6 +279,8 @@ export function useThresholdsTableState(props: ThresholdsTableProps) { agentsWithOverrides: rawAgentsWithOverrides, agentDisksWithOverrides: rawAgentDisksWithOverrides, agentDisksGroupedByAgent: rawAgentDisksGroupedByAgent, + agentSensorsWithOverrides: rawAgentSensorsWithOverrides = () => [], + agentSensorsGroupedByAgent: rawAgentSensorsGroupedByAgent = () => ({}), agentGroupHeaderMeta, dockerHostsWithOverrides: rawDockerHostsWithOverrides, dockerContainersGroupedByHost: rawDockerContainersGroupedByHost, @@ -342,6 +347,12 @@ export function useThresholdsTableState(props: ThresholdsTableProps) { const agentDisksGroupedByAgent = createMemo(() => filterGroupedResources(rawAgentDisksGroupedByAgent()), ); + const agentSensorsWithOverrides = createMemo(() => + filterResources(rawAgentSensorsWithOverrides()), + ); + const agentSensorsGroupedByAgent = createMemo(() => + filterGroupedResources(rawAgentSensorsGroupedByAgent()), + ); const dockerHostsWithOverrides = createMemo(() => filterResources(rawDockerHostsWithOverrides())); const dockerContainersGroupedByHost = createMemo(() => filterGroupedResources(rawDockerContainersGroupedByHost()), @@ -546,6 +557,13 @@ export function useThresholdsTableState(props: ThresholdsTableProps) { tab: 'systems', total: agentDisksWithOverrides().length, }, + { + key: 'agentSensors', + label: 'Machine Sensors', + overrides: countOverrides(rawAgentSensorsWithOverrides()), + tab: 'systems', + total: agentSensorsWithOverrides().length, + }, { key: 'storage', label: 'Storage', @@ -741,6 +759,7 @@ export function useThresholdsTableState(props: ThresholdsTableProps) { nodesWithOverrides, agentsWithOverrides, agentDisksWithOverrides, + agentSensorsWithOverrides, guestDisksWithOverrides, dockerHostsWithOverrides, guestsFlat, @@ -775,6 +794,7 @@ export function useThresholdsTableState(props: ThresholdsTableProps) { nodesWithOverrides, agentsWithOverrides, agentDisksWithOverrides, + agentSensorsWithOverrides, guestDisksWithOverrides, dockerHostsWithOverrides, guestsFlat, @@ -881,6 +901,8 @@ export function useThresholdsTableState(props: ThresholdsTableProps) { agentDisksGroupedByAgent, agentGroupHeaderMeta, agentDisksWithOverrides, + agentSensorsGroupedByAgent, + agentSensorsWithOverrides, agentsWithOverrides, alertsEnabled, backupDefaultsRecord, @@ -997,6 +1019,8 @@ export function useThresholdsTableState(props: ThresholdsTableProps) { setSearchTerm, AGENT_DISKS_EMPTY_STATE, AGENT_DISKS_FILTER_EMPTY_STATE, + AGENT_SENSORS_EMPTY_STATE, + AGENT_SENSORS_FILTER_EMPTY_STATE, AGENT_THRESHOLDS_FILTER_EMPTY_STATE, getAlertThresholdsHelpBanner, getAlertThresholdsHelpDismissLabel, diff --git a/frontend-modern/src/features/alerts/thresholds/tableTypes.ts b/frontend-modern/src/features/alerts/thresholds/tableTypes.ts index b17535c7f5..a290d98671 100644 --- a/frontend-modern/src/features/alerts/thresholds/tableTypes.ts +++ b/frontend-modern/src/features/alerts/thresholds/tableTypes.ts @@ -24,6 +24,8 @@ export interface Resource { readingMessage?: string; thresholds?: AlertResourceThresholdMap; defaults?: AlertResourceThresholdMap; + /** Defaults are display-only (no inherited policy), so an Off value is no override. */ + presentationDefaults?: boolean; disabled?: boolean; disableConnectivity?: boolean; poweredOffSeverity?: 'warning' | 'critical'; diff --git a/frontend-modern/src/features/alerts/thresholds/types.ts b/frontend-modern/src/features/alerts/thresholds/types.ts index 338c601d5c..35c62a5bbc 100644 --- a/frontend-modern/src/features/alerts/thresholds/types.ts +++ b/frontend-modern/src/features/alerts/thresholds/types.ts @@ -13,6 +13,7 @@ export type OverrideType = | 'guestDisk' | 'agent' | 'agentDisk' + | 'agentSensor' | 'storage' | 'pbs' | 'pmg' @@ -75,7 +76,11 @@ export interface SimpleThresholds { } export interface ThresholdsTableProps { - onConfigureResourceIntent?: (resourceId: string, signal: AlertIntentSignal) => void; + onConfigureResourceIntent?: ( + resourceId: string, + signal: AlertIntentSignal, + label?: string, + ) => void; overrides: () => Override[]; setOverrides: (overrides: Override[]) => void; rawOverridesConfig: () => Record; diff --git a/frontend-modern/src/features/alerts/types.ts b/frontend-modern/src/features/alerts/types.ts index c003f54ff1..92292cb34d 100644 --- a/frontend-modern/src/features/alerts/types.ts +++ b/frontend-modern/src/features/alerts/types.ts @@ -92,6 +92,7 @@ export type OverrideType = | 'guestDisk' | 'agent' | 'agentDisk' + | 'agentSensor' | 'storage' | 'pbs' | 'pmg' @@ -122,6 +123,7 @@ export interface Override { disabled?: boolean; // Completely disable alerts for this guest/storage disableConnectivity?: boolean; // For nodes/agents - disable offline/connectivity alerts poweredOffSeverity?: 'warning' | 'critical'; + note?: string; // Operator's note on the override backup?: BackupAlertConfig; snapshot?: SnapshotAlertConfig; thresholds: { diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.ts index 2c07e4991d..c07940ef8a 100644 --- a/frontend-modern/src/types/api.ts +++ b/frontend-modern/src/types/api.ts @@ -584,11 +584,31 @@ export interface HostSensorSummary { powerWatts?: Record; additional?: Record; custom?: HostCustomSensorMetric[]; + native?: HostNativeSensor[]; gpu?: HostGPUSensor[]; thermalState?: HostThermalState; smart?: HostDiskSMART[]; // S.M.A.R.T. disk data } +/** + * One lm-sensors temperature or fan input from the host agent's inventory. + * `id` is the host-scoped "/" source key (e.g. + * "applesmc-isa-0300/temp1"), not a physical-device identity; `label` is the + * chip's original feature name and is not unique. `invalid` marks an + * implausible reading, and `value` is absent when the chip gave no number. + */ +export interface HostNativeSensor { + id: string; + chip: string; + adapter?: string; + channel: string; + label: string; + kind: 'temperature' | 'fan'; + unit: 'celsius' | 'rpm'; + value?: number; + status: 'ok' | 'invalid'; +} + export interface HostCustomSensorMetric { id: string; name: string; diff --git a/frontend-modern/src/utils/__tests__/alertThresholdsPresentation.test.ts b/frontend-modern/src/utils/__tests__/alertThresholdsPresentation.test.ts index 9d18a65d23..61ef25f604 100644 --- a/frontend-modern/src/utils/__tests__/alertThresholdsPresentation.test.ts +++ b/frontend-modern/src/utils/__tests__/alertThresholdsPresentation.test.ts @@ -212,6 +212,7 @@ describe('alertThresholdsPresentation', () => { pmg: 'Mail Gateway Thresholds', agents: 'Machines', agentDisks: 'Machine Disks', + agentSensors: 'Machine Sensors', dockerHosts: 'Container Runtimes', dockerContainers: 'Containers', }); diff --git a/frontend-modern/src/utils/alertThresholdsPresentation.ts b/frontend-modern/src/utils/alertThresholdsPresentation.ts index fff86863be..5de7f50388 100644 --- a/frontend-modern/src/utils/alertThresholdsPresentation.ts +++ b/frontend-modern/src/utils/alertThresholdsPresentation.ts @@ -22,6 +22,9 @@ export const AGENT_THRESHOLDS_FILTER_EMPTY_STATE = 'No machines match the curren export const AGENT_DISKS_EMPTY_STATE = 'No machine disks found. Machines with mounted filesystems will appear here.'; export const AGENT_DISKS_FILTER_EMPTY_STATE = 'No machine disks match the current filters.'; +export const AGENT_SENSORS_EMPTY_STATE = + 'No machine sensors found. Linux machines with lm-sensors temperature inputs will appear here.'; +export const AGENT_SENSORS_FILTER_EMPTY_STATE = 'No machine sensors match the current filters.'; export const CONTAINER_RUNTIMES_FILTER_EMPTY_STATE = 'No container runtimes match the current filters.'; export const CONTAINERS_FILTER_EMPTY_STATE = 'No containers match the current filters.'; @@ -91,6 +94,7 @@ export const ALERT_THRESHOLDS_SECTION_TITLE_STORAGE = 'Storage Devices'; export const ALERT_THRESHOLDS_SECTION_TITLE_PMG = 'Mail Gateway Thresholds'; export const ALERT_THRESHOLDS_SECTION_TITLE_AGENTS = 'Machines'; export const ALERT_THRESHOLDS_SECTION_TITLE_AGENT_DISKS = 'Machine Disks'; +export const ALERT_THRESHOLDS_SECTION_TITLE_AGENT_SENSORS = 'Machine Sensors'; export const ALERT_THRESHOLDS_SECTION_TITLE_DOCKER_HOSTS = 'Container Runtimes'; export const ALERT_THRESHOLDS_SECTION_TITLE_DOCKER_CONTAINERS = 'Containers'; @@ -202,6 +206,7 @@ export function getAlertThresholdsSectionTitles() { pmg: ALERT_THRESHOLDS_SECTION_TITLE_PMG, agents: ALERT_THRESHOLDS_SECTION_TITLE_AGENTS, agentDisks: ALERT_THRESHOLDS_SECTION_TITLE_AGENT_DISKS, + agentSensors: ALERT_THRESHOLDS_SECTION_TITLE_AGENT_SENSORS, dockerHosts: ALERT_THRESHOLDS_SECTION_TITLE_DOCKER_HOSTS, dockerContainers: ALERT_THRESHOLDS_SECTION_TITLE_DOCKER_CONTAINERS, } as const; diff --git a/internal/mock/generator.go b/internal/mock/generator.go index 2b86ec4e56..6eed541169 100644 --- a/internal/mock/generator.go +++ b/internal/mock/generator.go @@ -3777,6 +3777,9 @@ func generateHosts(config MockConfig) []models.Host { } } } + if profile.Platform == "linux" { + sensors.Native = mockHostNativeSensors(hostID, now) + } status := "online" if rand.Float64() < 0.04 { @@ -4190,6 +4193,90 @@ func syncMockKubernetesNodeHosts(data *models.StateSnapshot) { } } +// mockNativeSensorSpec is one lm-sensors input of a mock machine. offset +// shifts the shared temperature series so sensors on one host differ, and +// invalid marks the implausible reading some chips report (-127 °C). +type mockNativeSensorSpec struct { + chip string + adapter string + channel string + label string + offset float64 + invalid bool +} + +var ( + mockNativeIntelSensors = []mockNativeSensorSpec{ + {chip: "coretemp-isa-0000", adapter: "ISA adapter", channel: "temp1", label: "Package id 0"}, + {chip: "coretemp-isa-0000", adapter: "ISA adapter", channel: "temp2", label: "Core 0", offset: -2}, + {chip: "coretemp-isa-0000", adapter: "ISA adapter", channel: "temp3", label: "Core 1", offset: -3}, + } + mockNativeNVMeSensors = []mockNativeSensorSpec{ + {chip: "nvme-pci-0100", adapter: "PCI adapter", channel: "temp1", label: "Composite", offset: -8}, + {chip: "nvme-pci-0200", adapter: "PCI adapter", channel: "temp1", label: "Composite", offset: -6}, + } + // An Intel Mac running Linux exposes its SMC sensors through applesmc, + // including the battery (TB0T) and a probe that reads -127 °C. + mockNativeAppleSMCSensors = []mockNativeSensorSpec{ + {chip: "applesmc-isa-0300", adapter: "ISA adapter", channel: "temp1", label: "TB0T", offset: -20}, + {chip: "applesmc-isa-0300", adapter: "ISA adapter", channel: "temp2", label: "TB1T", invalid: true}, + {chip: "applesmc-isa-0300", adapter: "ISA adapter", channel: "temp3", label: "TC0P", offset: -4}, + {chip: "applesmc-isa-0300", adapter: "ISA adapter", channel: "temp4", label: "Th1H", offset: -9}, + } +) + +// mockHostNativeSensors returns a Linux mock machine's native sensor +// inventory. Every machine has CPU core sensors and two NVMe drives whose +// labels repeat across chips; about one machine in four is an Intel Mac whose +// SMC sensors, an invalid one among them, are listed too. A fan input shows +// the inventory is not temperature-only. +func mockHostNativeSensors(hostID string, now time.Time) []models.HostNativeSensor { + specs := append([]mockNativeSensorSpec{}, mockNativeIntelSensors...) + specs = append(specs, mockNativeNVMeSensors...) + appleSMC := mockStableHash64(hostID, "native-sensors-applesmc")%4 == 0 + if appleSMC { + specs = append(specs, mockNativeAppleSMCSensors...) + } + base := SampleMetric("agent", hostID, "temperature", now) + sensors := make([]models.HostNativeSensor, 0, len(specs)+1) + for _, spec := range specs { + value := base + spec.offset + status := "ok" + if spec.invalid { + value = -127 + status = "invalid" + } + value = math.Round(value*10) / 10 + sensors = append(sensors, models.HostNativeSensor{ + ID: spec.chip + "/" + spec.channel, + Chip: spec.chip, + Adapter: spec.adapter, + Channel: spec.channel, + Label: spec.label, + Kind: "temperature", + Unit: "celsius", + Value: &value, + Status: status, + }) + } + if appleSMC { + rpm := float64(1800 + mockStableHash64(hostID, "native-sensors-fan")%400) + sensors = append(sensors, models.HostNativeSensor{ + ID: "applesmc-isa-0300/fan1", + Chip: "applesmc-isa-0300", + Adapter: "ISA adapter", + Channel: "fan1", + Label: "Left side", + Kind: "fan", + Unit: "rpm", + Value: &rpm, + Status: "ok", + }) + } + sort.Slice(sensors, func(i, j int) bool { return sensors[i].ID < sensors[j].ID }) + return sensors +} + func ensureMockFixtureHostIORates(data *models.StateSnapshot) { if data == nil { return @@ -7211,6 +7298,9 @@ func updateHosts(data *models.StateSnapshot, config MockConfig, now time.Time) { } refreshMockHostCPUSensors(host, now) + if len(host.Sensors.Native) > 0 { + host.Sensors.Native = mockHostNativeSensors(host.ID, now) + } if len(host.LoadAverage) == 3 { for j := range host.LoadAverage { diff --git a/internal/mock/generator_test.go b/internal/mock/generator_test.go index 9395450507..e6ce6fe28e 100644 --- a/internal/mock/generator_test.go +++ b/internal/mock/generator_test.go @@ -1690,3 +1690,97 @@ func TestGenerateDockerContainerUpdateStatusLocalImageShape(t *testing.T) { t.Fatal("generator never produced the local image state") } } + +// The mock native inventory must look like an ingested agent report: ids are +// "/", sorted and unique, status matches the reading, and only +// some machines are Intel Macs with applesmc sensors (an invalid one among +// them) so the Thresholds sensor section has realistic rows to show. +func TestMockHostNativeSensorsMatchIngestedInventoryShape(t *testing.T) { + now := time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC) + appleSMCHosts := 0 + for i := 1; i <= 40; i++ { + hostID := fmt.Sprintf("host-linux-%d", i) + sensors := mockHostNativeSensors(hostID, now) + if len(sensors) == 0 { + t.Fatalf("%s: empty native inventory", hostID) + } + seen := make(map[string]bool, len(sensors)) + hasAppleSMC := false + for idx, sensor := range sensors { + if sensor.ID != sensor.Chip+"/"+sensor.Channel { + t.Fatalf("%s: id %q is not chip/channel", hostID, sensor.ID) + } + if seen[sensor.ID] { + t.Fatalf("%s: duplicate id %q", hostID, sensor.ID) + } + seen[sensor.ID] = true + if idx > 0 && sensors[idx-1].ID >= sensor.ID { + t.Fatalf("%s: inventory not sorted at %q", hostID, sensor.ID) + } + if sensor.Value == nil { + t.Fatalf("%s: %s has no value", hostID, sensor.ID) + } + switch sensor.Kind { + case "temperature": + valid := *sensor.Value >= -55 && *sensor.Value <= 150 + if valid != (sensor.Status == "ok") { + t.Fatalf("%s: %s reads %v with status %q", hostID, sensor.ID, *sensor.Value, sensor.Status) + } + if sensor.Unit != "celsius" { + t.Fatalf("%s: %s unit %q", hostID, sensor.ID, sensor.Unit) + } + case "fan": + if sensor.Unit != "rpm" || sensor.Status != "ok" { + t.Fatalf("%s: fan %s unit %q status %q", hostID, sensor.ID, sensor.Unit, sensor.Status) + } + default: + t.Fatalf("%s: %s kind %q", hostID, sensor.ID, sensor.Kind) + } + if strings.HasPrefix(sensor.Chip, "applesmc-") { + hasAppleSMC = true + } + } + if hasAppleSMC { + appleSMCHosts++ + if !seen["applesmc-isa-0300/temp1"] || !seen["applesmc-isa-0300/temp2"] { + t.Fatalf("%s: applesmc inventory missing TB0T or the invalid TB1T", hostID) + } + } + if again := mockHostNativeSensors(hostID, now); len(again) != len(sensors) { + t.Fatalf("%s: inventory size changed between calls: %d then %d", hostID, len(sensors), len(again)) + } + } + if appleSMCHosts == 0 || appleSMCHosts == 40 { + t.Fatalf("applesmc hosts = %d of 40, want some but not all", appleSMCHosts) + } +} + +// The ordinary host update refreshes a native inventory with its CPU sensors, +// and leaves hosts without one alone. +func TestUpdateHostsRefreshesNativeSensorInventory(t *testing.T) { + start := time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC) + later := start.Add(37 * time.Minute) + data := &models.StateSnapshot{Hosts: []models.Host{ + {ID: "host-linux-1", Status: "online", Sensors: models.HostSensorSummary{ + TemperatureCelsius: map[string]float64{"cpu_package": 40}, + Native: mockHostNativeSensors("host-linux-1", start), + }}, + {ID: "host-windows-1", Status: "online"}, + }} + + updateHosts(data, MockConfig{RandomMetrics: true}, later) + + want := mockHostNativeSensors("host-linux-1", later) + got := data.Hosts[0].Sensors.Native + if len(got) != len(want) { + t.Fatalf("native inventory has %d entries, want %d", len(got), len(want)) + } + for i := range want { + if got[i].ID != want[i].ID || *got[i].Value != *want[i].Value || got[i].Status != want[i].Status { + t.Fatalf("entry %d = %s %v %s, want %s %v %s", i, got[i].ID, *got[i].Value, got[i].Status, want[i].ID, *want[i].Value, want[i].Status) + } + } + if data.Hosts[1].Sensors.Native != nil { + t.Fatalf("host without an inventory gained one: %+v", data.Hosts[1].Sensors.Native) + } +}