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
feat(agent): add REST custom metrics
[email protected]9e8b3ee6ff73
diff --git a/cmd/pulse-agent/main.go b/cmd/pulse-agent/main.goindex 52cefca0a8..8cf1ff2193 100644--- a/cmd/pulse-agent/main.go+++ b/cmd/pulse-agent/main.go@@ -1037,7 +1037,7 @@ func loadConfig(args []string, getenv func(string) string) (Config, error) {caCertFlag := fs.String("cacert", envCACertPath, "Path to custom CA bundle for agent HTTPS transport")serverFingerprintFlag := fs.String("server-fingerprint", envServerFingerprint, "Expected Pulse server TLS certificate fingerprint (SHA256)")observersFileFlag := fs.String("observers-file", envObserversFile, "Absolute path to a private JSON file defining report-only Pulse observer destinations")- customSensorsFileFlag := fs.String("custom-sensors-file", envCustomSensorsFile, "Absolute path to a private YAML file defining local numeric sensor commands")+ customSensorsFileFlag := fs.String("custom-sensors-file", envCustomSensorsFile, "Absolute path to a private YAML file defining command or REST custom metrics")deploySSHUserFlag := fs.String("deploy-ssh-user", envDeploySSHUser, "SSH user for peer deploy fan-out (default: root; non-root requires passwordless sudo)")logLevelFlag := fs.String("log-level", defaultLogLevel(envLogLevel), "Log level")logFileFlag := fs.String("log-file", envLogFile, "Write rotating JSON logs to this file")diff --git a/cmd/pulse-agent/main_test.go b/cmd/pulse-agent/main_test.goindex 1abf9c25d7..dd9d14423d 100644--- a/cmd/pulse-agent/main_test.go+++ b/cmd/pulse-agent/main_test.go@@ -978,7 +978,7 @@ func TestLoadConfig(t *testing.T) {t.Errorf("expected deploy SSH user from env, got %s", cfg.DeploySSHUser)}if cfg.CustomSensorsFile != "/etc/pulse/custom-sensors.yaml" {- t.Errorf("expected custom sensors file from env, got %s", cfg.CustomSensorsFile)+ t.Errorf("expected command/REST custom metrics file from env, got %s", cfg.CustomSensorsFile)}})@@ -1006,7 +1006,7 @@ func TestLoadConfig(t *testing.T) {t.Errorf("expected deploy SSH user from flag, got %s", cfg.DeploySSHUser)}if cfg.CustomSensorsFile != "/tmp/custom-sensors.yaml" {- t.Errorf("expected custom sensors file from flag, got %s", cfg.CustomSensorsFile)+ t.Errorf("expected command/REST custom metrics file from flag, got %s", cfg.CustomSensorsFile)}})diff --git a/docs/UNIFIED_AGENT.md b/docs/UNIFIED_AGENT.mdindex 7be6392462..8710426971 100644--- a/docs/UNIFIED_AGENT.md+++ b/docs/UNIFIED_AGENT.md@@ -136,11 +136,12 @@ containers or hardened service units without `CAP_NET_RAW`, ICMP checks fail;prefer TCP or HTTP checks there, or grant the capability. See "ICMP probeprivileges" in docs/CONFIGURATION.md.-## Custom numeric sensors+## Custom metrics-The host module can report numeric metrics produced by local executables. This-is intended for site-specific signals such as queue depth, UPS load, pending-updates, or an application counter that Pulse cannot collect natively.+The host module can report numeric, boolean, and timestamp metrics produced by+local executables or HTTP(S) REST endpoints. This is intended for site-specific+signals such as queue depth, UPS load, service status, DNS update age, or a+backup timestamp that Pulse cannot collect natively.Create a private YAML file:@@ -156,14 +157,54 @@ sensors:warningAbove: 20criticalAbove: 50alertOnError: true++ - id: main_dns_update+ name: Main DNS update+ group: Main server+ subgroup: Domain+ kind: timestamp+ url: https://metrics.example.net/dns/main+ interval: 1m+ timeout: 2s+ staleAfter: 10m+ warningAbove: 3600+ criticalAbove: 7200++ - id: checkout_online+ name: Checkout service+ group: Main server+ subgroup: Service statuses+ kind: boolean+ url: http://monitoring.internal/checkout+ criticalBelow: 0.5```Then start or restart the agent with`--custom-sensors-file /etc/pulse/custom-sensors.yaml`, or set-`PULSE_CUSTOM_SENSORS_FILE` to that absolute path. Each command must be an-absolute executable path, receives no arguments, and must write exactly one-finite number to standard output. Put any query logic in the executable or-script itself.+`PULSE_CUSTOM_SENSORS_FILE` to that absolute path. Each metric configures+exactly one source:++- `command`: an absolute executable path. It receives no arguments and writes+ one scalar to standard output.+- `url`: an absolute HTTP(S) URL polled with `GET`. Redirects are not followed,+ non-2xx responses fail, and the response is limited to 4 KiB.++REST endpoints can return a plain scalar or a JSON object:++```json+{"value": 42.5, "observedAt": "2026-07-30T20:00:00Z"}+```++`value` may be a number, string, or boolean. `observedAt` is optional RFC3339+source time. When `staleAfter` is configured, older source data becomes a stale+error and follows `alertOnError`.++`kind` defaults to `number`. Boolean metrics accept true/false, 1/0, yes/no,+on/off, up/down, and online/offline; Pulse stores true as 1 and false as 0, so+`criticalBelow: 0.5` alerts when a service is offline. Timestamp metrics accept+RFC3339 or Unix seconds, display time since the event, and apply thresholds to+the age in seconds. Optional `group` and `subgroup` values organize labels in+the **Custom Metrics** card.The agent evaluates optional `warningAbove`, `criticalAbove`, `warningBelow`,and `criticalBelow` thresholds locally. Pulse displays the typed value and unit@@ -172,12 +213,15 @@ failure alerts by default; set `alertOnError: false` to make failuresreport-only. If a probe fails after a successful reading, the last good value isshown as stale with its original observation time.-This feature is deliberately local-only. The Pulse server and remote agent-configuration cannot supply commands or arguments. The file is limited to 32-sensors; intervals must be between 10 seconds and 24 hours; timeouts must be-between 100 milliseconds and 10 seconds and shorter than the interval. At most-four probes run concurrently, output is bounded, and each executable is-revalidated before use.+Configuration is deliberately local-only. The Pulse server and remote agent+configuration cannot supply commands, URLs, or arguments. The file is limited+to 32 metrics; intervals must be between 10 seconds and 24 hours; timeouts must+be between 100 milliseconds and 10 seconds and shorter than the interval.+`staleAfter` must be between 10 seconds and 30 days. At most four probes run+concurrently, output is bounded, HTTP credentials in URLs are rejected, and+each executable is revalidated before use. Standard TLS certificate validation+applies to HTTPS endpoints; use network policy to constrain destinations where+required.On POSIX systems, the YAML file must be a regular, non-symlink file owned bythe agent service user with no group/other permissions (normally mode `0600`).@@ -198,7 +242,7 @@ sudo chmod 0700 /usr/local/libexec/pulse-queue-depth| `--url` | `PULSE_URL` | Pulse server URL | `http://localhost:7655` || `--token` | `PULSE_TOKEN` | API token | *(required)* || `--observers-file` | `PULSE_OBSERVERS_FILE` | Private JSON file defining report-only destinations | *(none)* |-| `--custom-sensors-file` | `PULSE_CUSTOM_SENSORS_FILE` | Private YAML file defining local numeric sensor executables and thresholds | *(none)* |+| `--custom-sensors-file` | `PULSE_CUSTOM_SENSORS_FILE` | Private YAML file defining command/REST custom metrics and thresholds | *(none)* || `--token-file` | - | Read API token from file | *(unset)* || `--interval` | `PULSE_INTERVAL` | Reporting interval | `30s` || `--enable-host` | `PULSE_ENABLE_HOST` | Enable host metrics | `true` |diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex cab0e88435..8ba28b7311 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -2299,19 +2299,26 @@ Agent` secondary handoff against the live setup wizard instead of relying## Current State-### Local custom numeric sensors are a bounded reporting module+### Local command and REST custom metrics are a bounded reporting moduleThe host agent now accepts an optional private version-1 YAML file through`--custom-sensors-file` / `PULSE_CUSTOM_SENSORS_FILE`. Each of at most 32-definitions names one absolute local executable, collection interval, timeout,-unit, and optional upper/lower warning and critical thresholds. The executable-receives no arguments and must emit exactly one finite number. Collection is+definitions names exactly one absolute local executable or HTTP(S) REST URL,+plus collection interval, timeout, optional group/subgroup, numeric, boolean,+or timestamp kind, source-freshness limit, and upper/lower warning and critical+thresholds. Executables receive no arguments; REST collection uses bounded GET+requests without redirects and accepts one scalar or a bounded JSON+`value`/`observedAt` object. Boolean values normalize to 1/0 and timestamp+values to event age in seconds before threshold evaluation. Collection remainsbounded to four concurrent executions inside the existing ten-second hostcollection context; last-good values survive failures as stale evidence with-their original observation time. The resulting typed `sensors.custom` array is-reporting data only and grants no command, enrollment, lifecycle, remote-shell,-or AI authority. Agent initialization fails closed on invalid configuration,-and Windows service startup carries the same optional file path.+their original observation and event times. The resulting typed+`sensors.custom` array is reporting data only and grants no command, enrollment,+lifecycle, remote-shell, or AI authority. Agent initialization fails closed on+invalid configuration, and Windows service startup carries the same optional+file path. `TestLoadConfig`, `TestCustomSensorKindsAndHTTPFreshness`, and+`TestCustomSensorMetricJSONRoundTrip` pin CLI plumbing, runtime semantics, and+the additive report wire shape.### Rootful Docker outranks rootless socket discovery and runtime labels are truthfuldiff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 89d2d7f37b..bab915d4e0 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -336,13 +336,15 @@ inspectability, or convert missing/stale evidence into health.### Agent custom sensors use canonical health-assessment alerts-Typed `HostSensorSummary.Custom` readings with `warning` or `critical` status-now map to one canonical `custom-sensor` alert per host and sensor ID.+Typed `HostSensorSummary.Custom` numeric, boolean, or timestamp readings with+`warning` or `critical` status map to one canonical `custom-sensor` alert per+host and sensor ID. Alert evidence preserves the optional group, subgroup,+kind, and event time alongside the evaluated numeric value.Collection errors map to warning only when the local definition reports`alertOnError`; healthy reports, removed definitions, disabled host thresholds,host removal, and telemetry expiry clear the same identity. Alert evaluationconsumes the agent-authored typed status and never executes or receives the-local sensor command. `TestHostCustomSensorAlertLifecycle` and+local command or REST URL. `TestHostCustomSensorAlertLifecycle` and`TestHostCustomSensorErrorCanBeReportOnly` in`internal/alerts/host_unraid_lifecycle_test.go` pin creation, recovery,opt-out, and cleanup.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 927c84c2aa..6fc4e4dc14 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -3771,15 +3771,18 @@ auto-register mutation boundary.## Current State-### Host sensor payloads carry typed custom numeric readings+### Host sensor payloads carry typed command and REST custom readingsAgent, host-model, frontend, and unified-resource sensor payloads now include a-`custom` array whose entries preserve `id`, `name`, optional `unit` and numeric-`value`, agent-authored `status`, `observedAt`, bounded `error`,-`alertOnError`, and `stale`. This is an additive wire field: older agents and-clients may omit it, and normalization exposes an empty collection rather than-reinterpreting the legacy temperature-oriented `additional` map. Accepted-report ingest and the JSON projection are pinned by+`custom` array whose entries preserve `id`, `name`, optional `group` and+`subgroup`, `kind` (`number`, `boolean`, or `timestamp`), optional `unit`,+normalized numeric `value`, agent-authored `status`, `observedAt`, optional+`eventAt`, bounded `error`, `alertOnError`, and `stale`. Boolean values use 1/0+and timestamp values use age in seconds on the wire. This is an additive wire+shape: older agents and clients may omit the new fields, and normalization+exposes an empty collection rather than reinterpreting the legacy+temperature-oriented `additional` map. Accepted report ingest and the JSON+projection are pinned by `TestCustomSensorMetricJSONRoundTrip`,`TestApplyHostReportPreservesTypedSensorSummary` and`TestHostCustomSensorMetaJSONContract`.diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 87cf95eed0..9e0d2ce84e 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -1296,6 +1296,17 @@ path. Monitoring must preserve `sensors.powerWatts` readings from agent reportsthrough models, read-state projection, and frontend conversion withoutpromoting wattage into temperature history, resource lifecycle, storage health,or alert metrics unless a separate governed contract adds that metric.+Host-agent custom metrics may originate from a locally configured executable or+an HTTP(S) REST endpoint, but remain agent-authored typed host metadata.+Monitoring must preserve group, subgroup, numeric/boolean/timestamp kind,+numeric threshold value, observation time, optional event time, status, bounded+error, stale state, and error-alert preference through ingest and frontend+projection. Boolean values use 1/0 and timestamp values use age in seconds so+the existing threshold and canonical alert lifecycle remains authoritative.+REST collection ownership stays in the agent: server configuration cannot+inject destinations, redirects are not followed, response bodies are bounded,+and an endpoint-supplied RFC3339 `observedAt` must trip the configured+`staleAfter` policy when old.That same monitoring owner also owns canonical unified-resource publication on`/api/state` and the websocket `state.resources` hydrate path. Monitoring mustpublish those resources from the same canonical unified snapshot thatdiff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 70f4e0b32b..064104863a 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -886,8 +886,9 @@ without contention or cross-delivery.The Infrastructure detail drawer formats `sensors.custom` from the alreadyselected resource payload. It performs no fetch, subscription, global resourcescan, or history query, and the native agent limits the source collection to 32-definitions with four concurrent executions. Formatting is a bounded-sort-and-map over that collection and remains outside table-row and virtualized+definitions with four concurrent command or REST executions. Group/subgroup+ordering and numeric, boolean, or timestamp rendering remain one bounded+sort-and-map over that collection and stay outside table-row and virtualizedviewport hot paths.`UnifiedResourceTable.performance.contract.test.tsx` pins the resource-localprojection and no-fetch boundary.diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex aa1b656dad..72cbd1e64e 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -597,19 +597,23 @@ tokens, and path-normalization variants.## Current State-### Custom sensor execution authority is local-only and fail-closed+### Custom metric source authority is local-only and fail-closed-`pulse-agent` may load site-defined numeric probes only from the absolute path+`pulse-agent` may load site-defined probes only from the absolute pathnamed by `--custom-sensors-file` or `PULSE_CUSTOM_SENSORS_FILE`. Serverprofiles, remote configuration, AI tooling, and command transport cannot author-the executable or arguments. The strict versioned YAML schema accepts absolute-executables with no shell or arguments; POSIX ownership, permissions, and-symlink checks protect the config, executable, and immediate parent directory,-and the executable is revalidated before each run. Count, concurrency, timeout,-stdout, and error sizes are bounded. Probe stderr is discarded so credentials-or query detail cannot enter reports or alerts; tests in+the executable, REST URL, or arguments. The strict versioned YAML schema accepts+exactly one absolute executable or HTTP(S) URL per metric. Executables use no+shell or arguments; POSIX ownership, permissions, and symlink checks protect the+config, executable, and immediate parent directory, and the executable is+revalidated before each run. REST URLs reject embedded credentials and+fragments, retain standard TLS validation, do not follow redirects, and expose+neither the configured URL nor transport errors that could contain query+credentials in reports. Count, concurrency, timeout, output, response, label,+and error sizes are bounded. Probe stderr is discarded so credentials or query+detail cannot enter reports or alerts; tests in`internal/hostagent/custom_sensors_test.go` pin unsafe-config rejection and the-stderr boundary.+stderr, REST-shape, freshness, and response-size boundaries.### System settings mutation surface no longer accepts dead schedule inputsdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 6edb3d2c91..52239a061a 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -2035,11 +2035,13 @@ capability over storage or recovery data.### Unified host read state preserves custom sensor evidenceThe shared host/unified-resource read-state boundary now carries typed custom-numeric readings as cloned evidence. Storage and recovery consumers may display-or preserve that host snapshot, but must not reinterpret custom units as-temperatures, execute probe paths, or treat a stale last-good value as a fresh-observation. No custom executable path or arguments enter the server model,-durable recovery data, or frontend payload. Adapter and clone isolation are+numeric, boolean, and timestamp readings as cloned evidence, including optional+group, subgroup, kind, and event time. Storage and recovery consumers may+display or preserve that host snapshot, but must not reinterpret custom units+as temperatures, execute source paths, or treat a stale last-good value as a+fresh observation. No custom executable path, REST URL, or arguments enter the+server model, durable recovery data, or frontend payload. Value and event-time+pointer isolation arepinned by `TestResourceFromHostPreservesCustomSensorMeta` and`TestCloneResourceIsolatesCustomSensorValues`.diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 98714b7f44..54ea9dbe25 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1684,11 +1684,13 @@ AI-only summary payloads, or page-local heuristics.`resourceFromHost` projects `models.HostSensorSummary.Custom` into`Agent.Sensors.Custom` with a private slice and numeric value pointers.-Read-state cloning preserves identity, name, unit, status, observation time,-bounded error, error-alert preference, and stale state without aliasing mutable-host-model memory. The detail drawer reads this typed collection under-**Custom Metrics**; it does not fold custom values into thermal metadata or-change canonical resource identity. `TestResourceFromHostPreservesCustomSensorMeta`,+Read-state cloning preserves identity, name, group, subgroup,+numeric/boolean/timestamp kind, unit, status, observation time, optional event+time, bounded error, error-alert preference, and stale state without aliasing+mutable host-model memory. The detail drawer reads this typed collection under+**Custom Metrics**, orders grouped labels, and renders boolean and event-age+values without folding them into thermal metadata or changing canonical+resource identity. `TestResourceFromHostPreservesCustomSensorMeta`,`TestCloneResourceIsolatesCustomSensorValues`, and`TestHostCustomSensorMetaJSONContract` pin adapter, clone, and JSON behavior.diff --git a/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsxindex c24e3adbea..55a73733dc 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx+++ b/frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx@@ -641,9 +641,39 @@ describe('UnifiedResourceTable performance contract', () => {status: 'warning',observedAt: '2026-07-30T19:00:00Z',},+ {+ id: 'backup_age',+ name: 'Last backup',+ group: 'Main server',+ subgroup: 'Backup',+ kind: 'timestamp',+ value: 7200,+ status: 'warning',+ observedAt: '2026-07-30T20:00:00Z',+ },+ {+ id: 'service_online',+ name: 'Checkout',+ group: 'Main server',+ subgroup: 'Services',+ kind: 'boolean',+ value: 1,+ status: 'ok',+ observedAt: '2026-07-30T20:00:00Z',+ },],}),).toEqual([+ {+ label: 'Main server / Backup / Last backup',+ value: '2h ago',+ valueTitle: '2h ago · Warning',+ },+ {+ label: 'Main server / Services / Checkout',+ value: 'Online',+ valueTitle: 'Online · OK',+ },{label: 'Queue depth',value: '12.5 items',diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.test.tsindex c4b36933aa..e46e554bff 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.test.ts+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.test.ts@@ -263,6 +263,47 @@ describe('resourceDetailMappers', () => {},]);});++ it('groups boolean and timestamp metrics and formats their typed values', () => {+ expect(+ buildCustomSensorRows({+ custom: [+ {+ id: 'backup_age',+ name: 'Last file backup',+ group: 'Main server',+ subgroup: 'Backup',+ kind: 'timestamp',+ value: 7_200,+ status: 'warning',+ observedAt: '2026-07-30T20:00:00Z',+ eventAt: '2026-07-30T18:00:00Z',+ },+ {+ id: 'dns_online',+ name: 'DNS online',+ group: 'Main server',+ subgroup: 'Services',+ kind: 'boolean',+ value: 0,+ status: 'critical',+ observedAt: '2026-07-30T20:00:00Z',+ },+ ],+ }),+ ).toEqual([+ {+ label: 'Main server / Backup / Last file backup',+ value: '2h ago',+ valueTitle: '2h ago · Warning',+ },+ {+ label: 'Main server / Services / DNS online',+ value: 'Offline',+ valueTitle: 'Offline · Critical',+ },+ ]);+ });});describe('toNodeFromProxmox', () => {diff --git a/frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts b/frontend-modern/src/components/Infrastructure/resourceDetailMappers.tsindex ab082ae5f5..adf635b2f6 100644--- a/frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts+++ b/frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts@@ -525,23 +525,50 @@ const formatCustomSensorValue = (value: number, unit?: string): string => {return `${formatted} ${normalizedUnit}`;};+const formatCustomSensorAge = (seconds: number): string => {+ const normalized = Math.max(0, Math.floor(seconds));+ if (normalized < 60) return `${normalized}s ago`;+ if (normalized < 3600) return `${Math.floor(normalized / 60)}m ago`;+ if (normalized < 86400) return `${Math.floor(normalized / 3600)}h ago`;+ return `${Math.floor(normalized / 86400)}d ago`;+};+export const buildCustomSensorRows = (sensors?: HostSensorSummary) =>(sensors?.custom ?? []).filter((metric) => metric.id?.trim() && metric.name?.trim())- .sort((a, b) => a.name.localeCompare(b.name))+ .sort((a, b) =>+ [a.group, a.subgroup, a.name]+ .map((part) => part?.trim() ?? '')+ .join('\u0000')+ .localeCompare(+ [b.group, b.subgroup, b.name]+ .map((part) => part?.trim() ?? '')+ .join('\u0000'),+ ),+ ).map((metric) => {const status = (metric.status || 'unknown').trim().toLowerCase();const hasValue = typeof metric.value === 'number' && Number.isFinite(metric.value);- const measured = hasValue- ? formatCustomSensorValue(metric.value as number, metric.unit)- : 'Unavailable';+ const kind = (metric.kind || 'number').trim().toLowerCase();+ let measured = 'Unavailable';+ if (hasValue && kind === 'boolean') {+ measured = (metric.value as number) >= 0.5 ? 'Online' : 'Offline';+ } else if (hasValue && kind === 'timestamp') {+ measured = formatCustomSensorAge(metric.value as number);+ } else if (hasValue) {+ measured = formatCustomSensorValue(metric.value as number, metric.unit);+ }const value = metric.stale ? `${measured} (stale)` : measured;const details = [status === 'ok' ? 'OK' : titleCaseDelimitedLabel(status),metric.error?.trim(),].filter(Boolean);+ const label = [metric.group, metric.subgroup, metric.name]+ .map((part) => part?.trim())+ .filter(Boolean)+ .join(' / ');return {- label: metric.name.trim(),+ label,value,valueTitle: details.length > 0 ? `${value} · ${details.join(' · ')}` : value,};diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.tsindex f25c5035cd..fd84ba1544 100644--- a/frontend-modern/src/types/api.ts+++ b/frontend-modern/src/types/api.ts@@ -552,10 +552,14 @@ export interface HostSensorSummary {export interface HostCustomSensorMetric {id: string;name: string;+ group?: string;+ subgroup?: string;+ kind?: 'number' | 'boolean' | 'timestamp' | string;unit?: string;value?: number;status: 'ok' | 'warning' | 'critical' | 'error' | string;observedAt: string;+ eventAt?: string;error?: string;alertOnError?: boolean;stale?: boolean;diff --git a/internal/alerts/host.go b/internal/alerts/host.goindex accd281168..63f1612b0f 100644--- a/internal/alerts/host.go+++ b/internal/alerts/host.go@@ -954,6 +954,9 @@ func (m *Manager) syncHostCustomSensorAlerts(host models.Host, nodeName, instancmetadata["metric"] = "customSensor"metadata["customSensorId"] = metric.IDmetadata["customSensorName"] = metric.Name+ metadata["customSensorGroup"] = metric.Group+ metadata["customSensorSubgroup"] = metric.Subgroup+ metadata["customSensorKind"] = metric.Kindmetadata["customSensorUnit"] = metric.Unitmetadata["customSensorStatus"] = metric.Statusmetadata["customSensorStale"] = metric.Stale@@ -963,6 +966,9 @@ func (m *Manager) syncHostCustomSensorAlerts(host models.Host, nodeName, instancif metric.Error != "" {metadata["customSensorError"] = metric.Error}+ if metric.EventAt != nil {+ metadata["customSensorEventAt"] = metric.EventAt.UTC().Format(time.RFC3339)+ }resourceName := fmt.Sprintf("%s - %s", hostDisplayName(host), metric.Name)_, _ = m.syncCanonicalHealthAssessmentAlert(canonicalHealthAssessmentAlertParams{diff --git a/internal/alerts/host_unraid_lifecycle_test.go b/internal/alerts/host_unraid_lifecycle_test.goindex 0e7bfc6051..14b244e6d6 100644--- a/internal/alerts/host_unraid_lifecycle_test.go+++ b/internal/alerts/host_unraid_lifecycle_test.go@@ -12,6 +12,7 @@ func TestHostCustomSensorAlertLifecycle(t *testing.T) {manager := newTestManager(t)manager.ClearActiveAlerts()value := 23.0+ eventAt := time.Now().UTC().Add(-2 * time.Hour)host := models.Host{ID: "custom-sensor-host",Hostname: "edge-1",@@ -20,19 +21,35 @@ func TestHostCustomSensorAlertLifecycle(t *testing.T) {Custom: []models.HostCustomSensorMetric{{ID: "queue_depth",Name: "Queue depth",+ Group: "Main server",+ Subgroup: "Backup",+ Kind: "timestamp",Unit: "items",Value: &value,Status: "critical",ObservedAt: time.Now().UTC(),+ EventAt: &eventAt,AlertOnError: true,}},},}manager.CheckHost(host)- if !hasAlertType(manager.GetActiveAlerts(), "custom-sensor") {+ active := manager.GetActiveAlerts()+ if !hasAlertType(active, "custom-sensor") {t.Fatal("expected custom sensor alert")}+ for _, alert := range active {+ if alert.Type != "custom-sensor" {+ continue+ }+ if alert.Metadata["customSensorGroup"] != "Main server" ||+ alert.Metadata["customSensorSubgroup"] != "Backup" ||+ alert.Metadata["customSensorKind"] != "timestamp" ||+ alert.Metadata["customSensorEventAt"] != eventAt.Format(time.RFC3339) {+ t.Fatalf("custom sensor alert metadata = %#v", alert.Metadata)+ }+ }host.Sensors.Custom[0].Status = "ok"manager.CheckHost(host)diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex ee8f7c80b3..11624d9ffc 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -409,7 +409,7 @@ func New(cfg Config) (*Agent, error) {logger.Info().Int("sensorCount", len(customSensorDefinitions)).Str("configPath", cfg.CustomSensorsFile).- Msg("Custom sensor execution enabled from local configuration")+ Msg("Custom metric collection enabled from local configuration")}// Create command client for AI command execution (only if enabled)diff --git a/internal/hostagent/custom_sensors.go b/internal/hostagent/custom_sensors.goindex 8ffa31c394..89be01902f 100644--- a/internal/hostagent/custom_sensors.go+++ b/internal/hostagent/custom_sensors.go@@ -3,10 +3,13 @@ package hostagentimport ("bytes""context"+ "encoding/json""errors""fmt""io""math"+ "net/http"+ "net/url""os""os/exec""path/filepath"@@ -27,6 +30,7 @@ const (maxCustomSensorConfigBytes = 64 * 1024maxCustomSensorOutputBytes = 4 * 1024maxCustomSensorErrorBytes = 256+ maxCustomSensorLabelBytes = 64maxCustomSensors = 32maxConcurrentCustomSensors = 4defaultCustomSensorInterval = 5 * time.Minute@@ -35,6 +39,7 @@ const (maxCustomSensorInterval = 24 * time.HourminCustomSensorTimeout = 100 * time.MillisecondmaxCustomSensorTimeout = 10 * time.Second+ maxCustomSensorFutureSkew = 5 * time.Minute)var (@@ -50,10 +55,15 @@ type customSensorFile struct {type customSensorFileEntry struct {ID string `yaml:"id"`Name string `yaml:"name"`- Command string `yaml:"command"`+ Group string `yaml:"group,omitempty"`+ Subgroup string `yaml:"subgroup,omitempty"`+ Kind string `yaml:"kind,omitempty"`+ Command string `yaml:"command,omitempty"`+ URL string `yaml:"url,omitempty"`Unit string `yaml:"unit,omitempty"`Interval string `yaml:"interval,omitempty"`Timeout string `yaml:"timeout,omitempty"`+ StaleAfter string `yaml:"staleAfter,omitempty"`WarningAbove *float64 `yaml:"warningAbove,omitempty"`CriticalAbove *float64 `yaml:"criticalAbove,omitempty"`WarningBelow *float64 `yaml:"warningBelow,omitempty"`@@ -64,10 +74,15 @@ type customSensorFileEntry struct {type customSensorDefinition struct {ID stringName string+ Group string+ Subgroup string+ Kind stringCommand string+ URL stringUnit stringInterval time.DurationTimeout time.Duration+ StaleAfter time.DurationWarningAbove *float64CriticalAbove *float64WarningBelow *float64@@ -76,6 +91,12 @@ type customSensorDefinition struct {}type customSensorExecution func(context.Context, string) (string, error)+type customSensorHTTPFetch func(context.Context, string) (customSensorSourceReading, error)++type customSensorSourceReading struct {+ output string+ observedAt time.Time+}type customSensorRuntimeState struct {reading agentshost.CustomSensorMetric@@ -88,6 +109,7 @@ type customSensorRuntime struct {definitions []customSensorDefinitionstates map[string]customSensorRuntimeStateexecute customSensorExecution+ fetchHTTP customSensorHTTPFetchnow func() time.Time}@@ -164,13 +186,45 @@ func resolveCustomSensorDefinition(entry customSensorFileEntry) (customSensorDefreturn customSensorDefinition{}, errors.New("unit contains unsupported characters or exceeds 24 characters")}- command := filepath.Clean(strings.TrimSpace(entry.Command))- if !filepath.IsAbs(command) {- return customSensorDefinition{}, errors.New("command must be an absolute path")+ group, err := validateCustomSensorLabel(entry.Group, "group")+ if err != nil {+ return customSensorDefinition{}, err}- if err := validateCustomSensorCommandFile(command); err != nil {+ subgroup, err := validateCustomSensorLabel(entry.Subgroup, "subgroup")+ if err != nil {return customSensorDefinition{}, err}+ kind := strings.ToLower(strings.TrimSpace(entry.Kind))+ if kind == "" {+ kind = agentshost.CustomSensorKindNumber+ }+ switch kind {+ case agentshost.CustomSensorKindNumber, agentshost.CustomSensorKindBoolean, agentshost.CustomSensorKindTimestamp:+ default:+ return customSensorDefinition{}, errors.New("kind must be number, boolean, or timestamp")+ }++ command := strings.TrimSpace(entry.Command)+ sourceURL := strings.TrimSpace(entry.URL)+ if (command == "") == (sourceURL == "") {+ return customSensorDefinition{}, errors.New("exactly one of command or url must be configured")+ }+ if command != "" {+ command = filepath.Clean(command)+ if !filepath.IsAbs(command) {+ return customSensorDefinition{}, errors.New("command must be an absolute path")+ }+ if err := validateCustomSensorCommandFile(command); err != nil {+ return customSensorDefinition{}, err+ }+ }+ if sourceURL != "" {+ normalizedURL, err := validateCustomSensorURL(sourceURL)+ if err != nil {+ return customSensorDefinition{}, err+ }+ sourceURL = normalizedURL+ }interval, err := parseCustomSensorDuration(entry.Interval, defaultCustomSensorInterval, minCustomSensorInterval, maxCustomSensorInterval, "interval")if err != nil {@@ -183,6 +237,13 @@ func resolveCustomSensorDefinition(entry customSensorFileEntry) (customSensorDefif timeout >= interval {return customSensorDefinition{}, errors.New("timeout must be shorter than interval")}+ staleAfter, err := parseOptionalCustomSensorDuration(entry.StaleAfter, minCustomSensorInterval, 30*24*time.Hour, "staleAfter")+ if err != nil {+ return customSensorDefinition{}, err+ }+ if staleAfter > 0 && sourceURL == "" {+ return customSensorDefinition{}, errors.New("staleAfter requires an HTTP url source with observedAt data")+ }for label, value := range map[string]*float64{"warningAbove": entry.WarningAbove,"criticalAbove": entry.CriticalAbove,@@ -218,10 +279,15 @@ func resolveCustomSensorDefinition(entry customSensorFileEntry) (customSensorDefreturn customSensorDefinition{ID: id,Name: name,+ Group: group,+ Subgroup: subgroup,+ Kind: kind,Command: command,+ URL: sourceURL,Unit: unit,Interval: interval,Timeout: timeout,+ StaleAfter: staleAfter,WarningAbove: cloneFloat64(entry.WarningAbove),CriticalAbove: cloneFloat64(entry.CriticalAbove),WarningBelow: cloneFloat64(entry.WarningBelow),@@ -230,6 +296,30 @@ func resolveCustomSensorDefinition(entry customSensorFileEntry) (customSensorDef}, nil}+func validateCustomSensorLabel(raw, label string) (string, error) {+ value := strings.TrimSpace(raw)+ if len(value) > maxCustomSensorLabelBytes || strings.IndexFunc(value, func(character rune) bool {+ return character == '\n' || character == '\r' || !unicode.IsPrint(character)+ }) >= 0 {+ return "", fmt.Errorf("%s must be at most %d printable characters on one line", label, maxCustomSensorLabelBytes)+ }+ return value, nil+}++func validateCustomSensorURL(raw string) (string, error) {+ parsed, err := url.ParseRequestURI(raw)+ if err != nil {+ return "", errors.New("url must be a valid absolute HTTP(S) URL")+ }+ if parsed.Scheme != "http" && parsed.Scheme != "https" {+ return "", errors.New("url scheme must be http or https")+ }+ if parsed.Hostname() == "" || parsed.User != nil || parsed.Fragment != "" {+ return "", errors.New("url must include a host and must not include credentials or a fragment")+ }+ return parsed.String(), nil+}+func parseCustomSensorDuration(raw string, fallback, minimum, maximum time.Duration, label string) (time.Duration, error) {raw = strings.TrimSpace(raw)if raw == "" {@@ -245,6 +335,13 @@ func parseCustomSensorDuration(raw string, fallback, minimum, maximum time.Duratreturn parsed, nil}+func parseOptionalCustomSensorDuration(raw string, minimum, maximum time.Duration, label string) (time.Duration, error) {+ if strings.TrimSpace(raw) == "" {+ return 0, nil+ }+ return parseCustomSensorDuration(raw, 0, minimum, maximum, label)+}+func validateCustomSensorConfigFile(path string) error {info, err := os.Lstat(path)if err != nil {@@ -315,6 +412,7 @@ func newCustomSensorRuntime(definitions []customSensorDefinition, execute customdefinitions: append([]customSensorDefinition(nil), definitions...),states: make(map[string]customSensorRuntimeState, len(definitions)),execute: execute,+ fetchHTTP: fetchCustomSensorHTTP,now: time.Now,}}@@ -394,26 +492,54 @@ func (runtimeState *customSensorRuntime) collect(ctx context.Context) []agentsho}func (runtimeState *customSensorRuntime) executeOne(parent context.Context, definition customSensorDefinition, previous *agentshost.CustomSensorMetric, observedAt time.Time) agentshost.CustomSensorMetric {- if err := validateCustomSensorCommandFile(definition.Command); err != nil {- return customSensorErrorReading(definition, previous, observedAt, errors.New("custom sensor command failed security validation"))- }ctx, cancel := context.WithTimeout(parent, definition.Timeout)defer cancel()- output, err := runtimeState.execute(ctx, definition.Command)+ sourceReading := customSensorSourceReading{observedAt: observedAt}+ var err error+ if definition.Command != "" {+ if err := validateCustomSensorCommandFile(definition.Command); err != nil {+ return customSensorErrorReading(definition, previous, observedAt, errors.New("custom sensor command failed security validation"))+ }+ sourceReading.output, err = runtimeState.execute(ctx, definition.Command)+ } else {+ sourceReading, err = runtimeState.fetchHTTP(ctx, definition.URL)+ if sourceReading.observedAt.IsZero() {+ sourceReading.observedAt = observedAt+ }+ }if err != nil {return customSensorErrorReading(definition, previous, observedAt, err)}- value, err := parseCustomSensorValue(output)+ if sourceReading.observedAt.After(observedAt.Add(maxCustomSensorFutureSkew)) {+ return customSensorErrorReading(definition, previous, observedAt, errors.New("custom sensor source observation time is in the future"))+ }+ value, eventAt, err := parseCustomSensorValueForKind(sourceReading.output, definition.Kind, observedAt)if err != nil {return customSensorErrorReading(definition, previous, observedAt, err)}+ if definition.StaleAfter > 0 && observedAt.Sub(sourceReading.observedAt) > definition.StaleAfter {+ reading := customSensorMetric(definition, &value, agentshost.CustomSensorStatusError, sourceReading.observedAt)+ reading.EventAt = eventAt+ reading.Stale = true+ reading.Error = fmt.Sprintf("source data is stale; last observed at %s", sourceReading.observedAt.UTC().Format(time.RFC3339))+ return reading+ }status := customSensorStatus(definition, value)+ reading := customSensorMetric(definition, &value, status, sourceReading.observedAt)+ reading.EventAt = eventAt+ return reading+}++func customSensorMetric(definition customSensorDefinition, value *float64, status string, observedAt time.Time) agentshost.CustomSensorMetric {return agentshost.CustomSensorMetric{ID: definition.ID,Name: definition.Name,+ Group: definition.Group,+ Subgroup: definition.Subgroup,+ Kind: definition.Kind,Unit: definition.Unit,- Value: &value,+ Value: value,Status: status,ObservedAt: observedAt,AlertOnError: definition.AlertOnError,@@ -421,19 +547,13 @@ func (runtimeState *customSensorRuntime) executeOne(parent context.Context, defi}func customSensorErrorReading(definition customSensorDefinition, previous *agentshost.CustomSensorMetric, observedAt time.Time, err error) agentshost.CustomSensorMetric {- reading := agentshost.CustomSensorMetric{- ID: definition.ID,- Name: definition.Name,- Unit: definition.Unit,- Status: agentshost.CustomSensorStatusError,- ObservedAt: observedAt,- AlertOnError: definition.AlertOnError,- Error: boundedCustomSensorError(err),- }+ reading := customSensorMetric(definition, nil, agentshost.CustomSensorStatusError, observedAt)+ reading.Error = boundedCustomSensorError(err)if previous != nil && previous.Value != nil {value := *previous.Valuereading.Value = &valuereading.ObservedAt = previous.ObservedAt+ reading.EventAt = cloneTime(previous.EventAt)reading.Stale = true}return reading@@ -451,6 +571,48 @@ func parseCustomSensorValue(output string) (float64, error) {return value, nil}+func parseCustomSensorValueForKind(output, kind string, now time.Time) (float64, *time.Time, error) {+ switch kind {+ case agentshost.CustomSensorKindBoolean:+ switch strings.ToLower(strings.TrimSpace(output)) {+ case "1", "true", "yes", "on", "up", "online", "healthy":+ return 1, nil, nil+ case "0", "false", "no", "off", "down", "offline", "unhealthy":+ return 0, nil, nil+ default:+ return 0, nil, errors.New("boolean custom sensor output must be true/false, 1/0, yes/no, on/off, up/down, or online/offline")+ }+ case agentshost.CustomSensorKindTimestamp:+ eventAt, err := parseCustomSensorTimestamp(output)+ if err != nil {+ return 0, nil, err+ }+ if eventAt.After(now.Add(maxCustomSensorFutureSkew)) {+ return 0, nil, errors.New("timestamp custom sensor event time is in the future")+ }+ age := now.Sub(eventAt).Seconds()+ if age < 0 {+ age = 0+ }+ return age, &eventAt, nil+ default:+ value, err := parseCustomSensorValue(output)+ return value, nil, err+ }+}++func parseCustomSensorTimestamp(output string) (time.Time, error) {+ raw := strings.TrimSpace(output)+ if parsed, err := time.Parse(time.RFC3339, raw); err == nil {+ return parsed.UTC(), nil+ }+ seconds, err := strconv.ParseInt(raw, 10, 64)+ if err != nil {+ return time.Time{}, errors.New("timestamp custom sensor output must be RFC3339 or Unix seconds")+ }+ return time.Unix(seconds, 0).UTC(), nil+}+func customSensorStatus(definition customSensorDefinition, value float64) string {if definition.CriticalAbove != nil && value >= *definition.CriticalAbove {return agentshost.CustomSensorStatusCritical@@ -467,6 +629,75 @@ func customSensorStatus(definition customSensorDefinition, value float64) stringreturn agentshost.CustomSensorStatusOK}+type customSensorHTTPResponse struct {+ Value any `json:"value"`+ ObservedAt string `json:"observedAt,omitempty"`+}++func fetchCustomSensorHTTP(ctx context.Context, sourceURL string) (customSensorSourceReading, error) {+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, sourceURL, nil)+ if err != nil {+ return customSensorSourceReading{}, errors.New("create custom sensor HTTP request")+ }+ request.Header.Set("Accept", "application/json, text/plain")+ client := &http.Client{+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {+ return http.ErrUseLastResponse+ },+ }+ response, err := client.Do(request)+ if err != nil {+ if contextError := ctx.Err(); contextError != nil {+ return customSensorSourceReading{}, fmt.Errorf("custom sensor HTTP request: %w", contextError)+ }+ return customSensorSourceReading{}, errors.New("custom sensor HTTP request failed")+ }+ defer response.Body.Close()+ if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {+ return customSensorSourceReading{}, fmt.Errorf("custom sensor HTTP endpoint returned status %d", response.StatusCode)+ }+ body, err := io.ReadAll(io.LimitReader(response.Body, maxCustomSensorOutputBytes+1))+ if err != nil {+ return customSensorSourceReading{}, errors.New("read custom sensor HTTP response")+ }+ if len(body) > maxCustomSensorOutputBytes {+ return customSensorSourceReading{}, fmt.Errorf("custom sensor HTTP response exceeds %d bytes", maxCustomSensorOutputBytes)+ }+ raw := strings.TrimSpace(string(body))+ reading := customSensorSourceReading{output: raw, observedAt: time.Now().UTC()}+ if !strings.HasPrefix(raw, "{") {+ return reading, nil+ }+ var payload customSensorHTTPResponse+ decoder := json.NewDecoder(strings.NewReader(raw))+ decoder.UseNumber()+ if err := decoder.Decode(&payload); err != nil {+ return customSensorSourceReading{}, errors.New("custom sensor HTTP response must be a scalar or JSON object with value")+ }+ var trailing any+ if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {+ return customSensorSourceReading{}, errors.New("custom sensor HTTP response must contain exactly one JSON value")+ }+ switch value := payload.Value.(type) {+ case json.Number:+ reading.output = value.String()+ case string:+ reading.output = value+ case bool:+ reading.output = strconv.FormatBool(value)+ default:+ return customSensorSourceReading{}, errors.New("custom sensor HTTP JSON value must be a number, string, or boolean")+ }+ if strings.TrimSpace(payload.ObservedAt) != "" {+ parsed, err := time.Parse(time.RFC3339, payload.ObservedAt)+ if err != nil {+ return customSensorSourceReading{}, errors.New("custom sensor HTTP observedAt must be RFC3339")+ }+ reading.observedAt = parsed.UTC()+ }+ return reading, nil+}+func executeCustomSensorCommand(ctx context.Context, path string) (string, error) {var stdout boundedSensorBufferstdout.limit = maxCustomSensorOutputBytes@@ -533,5 +764,14 @@ func cloneFloat64(value *float64) *float64 {func cloneCustomSensorMetric(metric agentshost.CustomSensorMetric) agentshost.CustomSensorMetric {metric.Value = cloneFloat64(metric.Value)+ metric.EventAt = cloneTime(metric.EventAt)return metric}++func cloneTime(value *time.Time) *time.Time {+ if value == nil {+ return nil+ }+ cloned := *value+ return &cloned+}diff --git a/internal/hostagent/custom_sensors_test.go b/internal/hostagent/custom_sensors_test.goindex f88baa3ff8..7c1912d615 100644--- a/internal/hostagent/custom_sensors_test.go+++ b/internal/hostagent/custom_sensors_test.go@@ -3,6 +3,8 @@ package hostagentimport ("context""errors"+ "net/http"+ "net/http/httptest""os""path/filepath""runtime"@@ -67,6 +69,41 @@ sensors:}}+func TestLoadCustomSensorDefinitionsSupportsGroupedHTTPKinds(t *testing.T) {+ configPath, _ := writeCustomSensorFixture(t, `version: 1+sensors:+ - id: dns_update+ name: Main DNS update+ group: Main server+ subgroup: Domain+ kind: timestamp+ url: https://metrics.example.test/dns+ interval: 1m+ timeout: 2s+ staleAfter: 10m+ warningAbove: 3600+ criticalAbove: 7200+`)++ definitions, err := loadCustomSensorDefinitions(configPath)+ if err != nil {+ t.Fatalf("loadCustomSensorDefinitions: %v", err)+ }+ if len(definitions) != 1 {+ t.Fatalf("definition count = %d, want 1", len(definitions))+ }+ definition := definitions[0]+ if definition.Command != "" || definition.URL != "https://metrics.example.test/dns" {+ t.Fatalf("unexpected HTTP source: %+v", definition)+ }+ if definition.Group != "Main server" || definition.Subgroup != "Domain" || definition.Kind != agentshost.CustomSensorKindTimestamp {+ t.Fatalf("unexpected grouped kind: %+v", definition)+ }+ if definition.StaleAfter != 10*time.Minute {+ t.Fatalf("staleAfter = %s, want 10m", definition.StaleAfter)+ }+}+func TestLoadCustomSensorDefinitionsRejectsUnsafeAndAmbiguousConfiguration(t *testing.T) {t.Run("unknown field", func(t *testing.T) {configPath, _ := writeCustomSensorFixture(t, `version: 1@@ -93,6 +130,31 @@ sensors:}})+ t.Run("ambiguous source", func(t *testing.T) {+ configPath, _ := writeCustomSensorFixture(t, `version: 1+sensors:+ - id: metric+ name: Metric+ command: __COMMAND__+ url: https://metrics.example.test/value+`)+ if _, err := loadCustomSensorDefinitions(configPath); err == nil || !strings.Contains(err.Error(), "exactly one") {+ t.Fatalf("expected ambiguous source rejection, got %v", err)+ }+ })++ t.Run("unsafe url", func(t *testing.T) {+ configPath, _ := writeCustomSensorFixture(t, `version: 1+sensors:+ - id: metric+ name: Metric+ url: file:///etc/passwd+`)+ if _, err := loadCustomSensorDefinitions(configPath); err == nil || !strings.Contains(err.Error(), "scheme") {+ t.Fatalf("expected URL scheme rejection, got %v", err)+ }+ })+t.Run("control character in name", func(t *testing.T) {_, err := resolveCustomSensorDefinition(customSensorFileEntry{ID: "metric",@@ -274,6 +336,80 @@ func TestParseCustomSensorValueAndStatus(t *testing.T) {}}+func TestCustomSensorKindsAndHTTPFreshness(t *testing.T) {+ now := time.Date(2026, 7, 30, 20, 0, 0, 0, time.UTC)+ booleanValue, eventAt, err := parseCustomSensorValueForKind("offline", agentshost.CustomSensorKindBoolean, now)+ if err != nil || booleanValue != 0 || eventAt != nil {+ t.Fatalf("boolean parse = %v, %v, %v", booleanValue, eventAt, err)+ }+ age, eventAt, err := parseCustomSensorValueForKind("2026-07-30T18:30:00Z", agentshost.CustomSensorKindTimestamp, now)+ if err != nil || age != 90*time.Minute.Seconds() || eventAt == nil || !eventAt.Equal(now.Add(-90*time.Minute)) {+ t.Fatalf("timestamp parse = %v, %v, %v", age, eventAt, err)+ }++ criticalBelow := 0.5+ definition := customSensorDefinition{+ ID: "service",+ Name: "Service online",+ Group: "Main server",+ Subgroup: "Services",+ Kind: agentshost.CustomSensorKindBoolean,+ URL: "https://metrics.example.test/service",+ Interval: time.Minute,+ Timeout: time.Second,+ StaleAfter: 5 * time.Minute,+ CriticalBelow: &criticalBelow,+ AlertOnError: true,+ }+ customRuntime := newCustomSensorRuntime([]customSensorDefinition{definition}, nil)+ customRuntime.now = func() time.Time { return now }+ customRuntime.fetchHTTP = func(context.Context, string) (customSensorSourceReading, error) {+ return customSensorSourceReading{output: "true", observedAt: now.Add(-10 * time.Minute)}, nil+ }+ readings := customRuntime.collect(context.Background())+ if len(readings) != 1 || readings[0].Status != agentshost.CustomSensorStatusError || !readings[0].Stale {+ t.Fatalf("expected stale HTTP reading: %+v", readings)+ }+ if readings[0].Group != "Main server" || readings[0].Subgroup != "Services" || readings[0].Value == nil || *readings[0].Value != 1 {+ t.Fatalf("HTTP reading metadata/value not preserved: %+v", readings[0])+ }+}++func TestFetchCustomSensorHTTPAcceptsBoundedScalarAndJSON(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ if request.URL.Path == "/json" {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"value":false,"observedAt":"2026-07-30T19:00:00Z"}`))+ return+ }+ if request.URL.Path == "/redirect" {+ http.Redirect(w, request, "https://example.test/secret", http.StatusFound)+ return+ }+ if request.URL.Path == "/large" {+ _, _ = w.Write([]byte(strings.Repeat("1", maxCustomSensorOutputBytes+1)))+ return+ }+ _, _ = w.Write([]byte("42.5\n"))+ }))+ defer server.Close()++ scalar, err := fetchCustomSensorHTTP(context.Background(), server.URL+"/scalar")+ if err != nil || scalar.output != "42.5" {+ t.Fatalf("scalar HTTP reading = %+v, %v", scalar, err)+ }+ jsonReading, err := fetchCustomSensorHTTP(context.Background(), server.URL+"/json")+ if err != nil || jsonReading.output != "false" || !jsonReading.observedAt.Equal(time.Date(2026, 7, 30, 19, 0, 0, 0, time.UTC)) {+ t.Fatalf("JSON HTTP reading = %+v, %v", jsonReading, err)+ }+ if _, err := fetchCustomSensorHTTP(context.Background(), server.URL+"/redirect"); err == nil || !strings.Contains(err.Error(), "status 302") {+ t.Fatalf("expected redirect rejection, got %v", err)+ }+ if _, err := fetchCustomSensorHTTP(context.Background(), server.URL+"/large"); err == nil || !strings.Contains(err.Error(), "exceeds") {+ t.Fatalf("expected oversized response rejection, got %v", err)+ }+}+func TestExecuteCustomSensorCommandDoesNotExposeStderr(t *testing.T) {if runtime.GOOS == "windows" {t.Skip("shell fixture is POSIX-only")diff --git a/internal/models/converters.go b/internal/models/converters.goindex a1213572a6..77081a7e1d 100644--- a/internal/models/converters.go+++ b/internal/models/converters.go@@ -908,10 +908,14 @@ func hostSensorSummaryToFrontend(src HostSensorSummary) *HostSensorSummaryFrontedest.Custom[i] = HostCustomSensorMetricFrontend{ID: metric.ID,Name: metric.Name,+ Group: metric.Group,+ Subgroup: metric.Subgroup,+ Kind: metric.Kind,Unit: metric.Unit,Value: cloneFloat64Ptr(metric.Value),Status: metric.Status,ObservedAt: metric.ObservedAt,+ EventAt: cloneTimePtr(metric.EventAt),Error: metric.Error,AlertOnError: metric.AlertOnError,Stale: metric.Stale,diff --git a/internal/models/deepcopy.go b/internal/models/deepcopy.goindex 6519f96227..6d3f53d0ee 100644--- a/internal/models/deepcopy.go+++ b/internal/models/deepcopy.go@@ -271,6 +271,7 @@ func cloneHostCustomSensors(src []HostCustomSensorMetric) []HostCustomSensorMetrfor i, metric := range src {dest[i] = metricdest[i].Value = cloneFloat64Ptr(metric.Value)+ dest[i].EventAt = cloneTimePtr(metric.EventAt)}return dest}diff --git a/internal/models/models.go b/internal/models/models.goindex 78e36e0179..d4ea7cfef2 100644--- a/internal/models/models.go+++ b/internal/models/models.go@@ -499,15 +499,19 @@ type HostSensorSummary struct {}type HostCustomSensorMetric struct {- ID string `json:"id"`- Name string `json:"name"`- Unit string `json:"unit,omitempty"`- Value *float64 `json:"value,omitempty"`- Status string `json:"status"`- ObservedAt time.Time `json:"observedAt"`- Error string `json:"error,omitempty"`- AlertOnError bool `json:"alertOnError,omitempty"`- Stale bool `json:"stale,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ Group string `json:"group,omitempty"`+ Subgroup string `json:"subgroup,omitempty"`+ Kind string `json:"kind,omitempty"`+ Unit string `json:"unit,omitempty"`+ Value *float64 `json:"value,omitempty"`+ Status string `json:"status"`+ ObservedAt time.Time `json:"observedAt"`+ EventAt *time.Time `json:"eventAt,omitempty"`+ Error string `json:"error,omitempty"`+ AlertOnError bool `json:"alertOnError,omitempty"`+ Stale bool `json:"stale,omitempty"`}type HostGPUSensor struct {diff --git a/internal/models/models_frontend.go b/internal/models/models_frontend.goindex 827c7a08f2..e01aafcfbf 100644--- a/internal/models/models_frontend.go+++ b/internal/models/models_frontend.go@@ -772,15 +772,19 @@ type HostSensorSummaryFrontend struct {}type HostCustomSensorMetricFrontend struct {- ID string `json:"id"`- Name string `json:"name"`- Unit string `json:"unit,omitempty"`- Value *float64 `json:"value,omitempty"`- Status string `json:"status"`- ObservedAt time.Time `json:"observedAt"`- Error string `json:"error,omitempty"`- AlertOnError bool `json:"alertOnError,omitempty"`- Stale bool `json:"stale,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ Group string `json:"group,omitempty"`+ Subgroup string `json:"subgroup,omitempty"`+ Kind string `json:"kind,omitempty"`+ Unit string `json:"unit,omitempty"`+ Value *float64 `json:"value,omitempty"`+ Status string `json:"status"`+ ObservedAt time.Time `json:"observedAt"`+ EventAt *time.Time `json:"eventAt,omitempty"`+ Error string `json:"error,omitempty"`+ AlertOnError bool `json:"alertOnError,omitempty"`+ Stale bool `json:"stale,omitempty"`}type HostGPUSensorFrontend struct {diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 7538c6f8dc..1c756ed229 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -3539,10 +3539,14 @@ func hostSensorsFromReadStateView(sensors *unifiedresources.HostSensorMeta) modeout.Custom[i] = models.HostCustomSensorMetric{ID: metric.ID,Name: metric.Name,+ Group: metric.Group,+ Subgroup: metric.Subgroup,+ Kind: metric.Kind,Unit: metric.Unit,Value: cloneFloat64Ptr(metric.Value),Status: metric.Status,ObservedAt: metric.ObservedAt,+ EventAt: cloneReportTimePtr(metric.EventAt),Error: metric.Error,AlertOnError: metric.AlertOnError,Stale: metric.Stale,diff --git a/internal/monitoring/monitor_helpers.go b/internal/monitoring/monitor_helpers.goindex b2da513dde..52ce71116b 100644--- a/internal/monitoring/monitor_helpers.go+++ b/internal/monitoring/monitor_helpers.go@@ -732,10 +732,14 @@ func convertAgentCustomSensorsToModels(metrics []agentshost.CustomSensorMetric)result[i] = models.HostCustomSensorMetric{ID: strings.TrimSpace(metric.ID),Name: strings.TrimSpace(metric.Name),+ Group: strings.TrimSpace(metric.Group),+ Subgroup: strings.TrimSpace(metric.Subgroup),+ Kind: strings.TrimSpace(metric.Kind),Unit: strings.TrimSpace(metric.Unit),Value: cloneFloat64Ptr(metric.Value),Status: strings.TrimSpace(metric.Status),ObservedAt: metric.ObservedAt,+ EventAt: cloneReportTimePtr(metric.EventAt),Error: strings.TrimSpace(metric.Error),AlertOnError: metric.AlertOnError,Stale: metric.Stale,diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.goindex baf366dd60..dc48c8455f 100644--- a/internal/monitoring/monitor_host_agents_test.go+++ b/internal/monitoring/monitor_host_agents_test.go@@ -536,14 +536,19 @@ func TestFindLinkedProxmoxEntityWithHints_UsesExactEndpointHostnameBeforeNameFalfunc TestHostSensorsFromReadStateViewPreservesTypedSensorData(t *testing.T) {customValue := 12.5observedAt := time.Date(2026, 7, 30, 19, 0, 0, 0, time.UTC)+ eventAt := observedAt.Add(-2 * time.Hour)sensors := &unifiedresources.HostSensorMeta{Custom: []unifiedresources.HostCustomSensorMetric{{ID: "queue_depth",Name: "Queue depth",+ Group: "Main server",+ Subgroup: "Backup",+ Kind: "timestamp",Unit: "items",Value: &customValue,Status: "warning",ObservedAt: observedAt,+ EventAt: &eventAt,AlertOnError: true,}},SMART: []unifiedresources.HostSMARTMeta{@@ -572,13 +577,20 @@ func TestHostSensorsFromReadStateViewPreservesTypedSensorData(t *testing.T) {if len(got.Custom) != 1 || got.Custom[0].Value == nil || *got.Custom[0].Value != customValue {t.Fatalf("custom sensors = %+v, want one typed reading", got.Custom)}- if got.Custom[0].ObservedAt != observedAt || got.Custom[0].Status != "warning" || !got.Custom[0].AlertOnError {+ if got.Custom[0].ObservedAt != observedAt || got.Custom[0].EventAt == nil ||+ !got.Custom[0].EventAt.Equal(eventAt) || got.Custom[0].Group != "Main server" ||+ got.Custom[0].Subgroup != "Backup" || got.Custom[0].Kind != "timestamp" ||+ got.Custom[0].Status != "warning" || !got.Custom[0].AlertOnError {t.Fatalf("custom sensor metadata was not preserved: %+v", got.Custom[0])}customValue = 99if *got.Custom[0].Value != 12.5 {t.Fatalf("custom sensor value was not cloned: %v", *got.Custom[0].Value)}+ eventAt = eventAt.Add(time.Hour)+ if got.Custom[0].EventAt.Equal(eventAt) {+ t.Fatal("custom sensor event time was not cloned")+ }}func TestApplyDockerReportNormalizesContainerCPUCapacityAcceptedIngestProof(t *testing.T) {diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.goindex 7d8990962b..572e0588ee 100644--- a/internal/unifiedresources/adapters.go+++ b/internal/unifiedresources/adapters.go@@ -280,10 +280,14 @@ func resourceFromHost(host models.Host) (Resource, ResourceIdentity) {sensorMeta.Custom[i] = HostCustomSensorMetric{ID: metric.ID,Name: metric.Name,+ Group: metric.Group,+ Subgroup: metric.Subgroup,+ Kind: metric.Kind,Unit: metric.Unit,Value: cloneFloat64Ptr(metric.Value),Status: metric.Status,ObservedAt: metric.ObservedAt,+ EventAt: cloneTimePtr(metric.EventAt),Error: metric.Error,AlertOnError: metric.AlertOnError,Stale: metric.Stale,diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.goindex c0961ddf20..563863ca6b 100644--- a/internal/unifiedresources/adapters_test.go+++ b/internal/unifiedresources/adapters_test.go@@ -44,6 +44,7 @@ func TestResourceFromProxmoxNodeIncludesTemperature(t *testing.T) {func TestResourceFromHostPreservesCustomSensorMeta(t *testing.T) {value := 12.5observedAt := time.Date(2026, 7, 30, 19, 0, 0, 0, time.UTC)+ eventAt := observedAt.Add(-2 * time.Hour)host := models.Host{ID: "agent-custom",Hostname: "edge-1",@@ -51,10 +52,14 @@ func TestResourceFromHostPreservesCustomSensorMeta(t *testing.T) {Custom: []models.HostCustomSensorMetric{{ID: "queue_depth",Name: "Queue depth",+ Group: "Main server",+ Subgroup: "Backup",+ Kind: "timestamp",Unit: "items",Value: &value,Status: "warning",ObservedAt: observedAt,+ EventAt: &eventAt,AlertOnError: true,}},},@@ -65,13 +70,19 @@ func TestResourceFromHostPreservesCustomSensorMeta(t *testing.T) {t.Fatalf("custom sensor projection = %+v", resource.Agent)}custom := resource.Agent.Sensors.Custom[0]- if custom.ID != "queue_depth" || custom.Value == nil || *custom.Value != 12.5 || custom.ObservedAt != observedAt {+ if custom.ID != "queue_depth" || custom.Group != "Main server" || custom.Subgroup != "Backup" ||+ custom.Kind != "timestamp" || custom.Value == nil || *custom.Value != 12.5 ||+ custom.ObservedAt != observedAt || custom.EventAt == nil || !custom.EventAt.Equal(eventAt) {t.Fatalf("custom sensor projection = %+v", custom)}value = 99if *custom.Value != 12.5 {t.Fatal("custom sensor projection aliases the model value")}+ eventAt = eventAt.Add(time.Hour)+ if custom.EventAt.Equal(eventAt) {+ t.Fatal("custom sensor projection aliases the model event time")+ }}func TestResourceFromProxmoxNodeUsesDisplayNameWithoutChangingRawNodeIdentity(t *testing.T) {diff --git a/internal/unifiedresources/canonical_ids_types_test.go b/internal/unifiedresources/canonical_ids_types_test.goindex 833af71548..5537d33b30 100644--- a/internal/unifiedresources/canonical_ids_types_test.go+++ b/internal/unifiedresources/canonical_ids_types_test.go@@ -69,14 +69,19 @@ func TestHostSMARTMetaCarriesSizeBytesJSONContract(t *testing.T) {func TestHostCustomSensorMetaJSONContract(t *testing.T) {value := 12.5observedAt := "2026-07-30T19:00:00Z"+ eventAt := "2026-07-30T18:00:00Z"payload := HostSensorMeta{Custom: []HostCustomSensorMetric{{ID: "queue_depth",Name: "Queue depth",+ Group: "Main server",+ Subgroup: "Backup",+ Kind: "timestamp",Unit: "items",Value: &value,Status: "warning",ObservedAt: time.Date(2026, 7, 30, 19, 0, 0, 0, time.UTC),+ EventAt: timePointer(time.Date(2026, 7, 30, 18, 0, 0, 0, time.UTC)),}},}@@ -87,9 +92,13 @@ func TestHostCustomSensorMetaJSONContract(t *testing.T) {for _, expected := range []string{`"custom":[`,`"id":"queue_depth"`,+ `"group":"Main server"`,+ `"subgroup":"Backup"`,+ `"kind":"timestamp"`,`"value":12.5`,`"status":"warning"`,`"observedAt":"` + observedAt + `"`,+ `"eventAt":"` + eventAt + `"`,} {if !strings.Contains(string(data), expected) {t.Fatalf("custom sensor JSON missing %s: %s", expected, data)diff --git a/internal/unifiedresources/clone.go b/internal/unifiedresources/clone.goindex 4620ef622f..57660bf907 100644--- a/internal/unifiedresources/clone.go+++ b/internal/unifiedresources/clone.go@@ -837,6 +837,7 @@ func cloneHostCustomSensors(in []HostCustomSensorMetric) []HostCustomSensorMetrifor i, metric := range in {out[i] = metricout[i].Value = cloneFloat64Ptr(metric.Value)+ out[i].EventAt = cloneTimePtr(metric.EventAt)}return out}diff --git a/internal/unifiedresources/clone_test.go b/internal/unifiedresources/clone_test.goindex e7b5b517f1..96f6fb131e 100644--- a/internal/unifiedresources/clone_test.go+++ b/internal/unifiedresources/clone_test.go@@ -104,15 +104,17 @@ func TestCloneResource_MutateOriginalMetrics(t *testing.T) {func TestCloneResourceIsolatesCustomSensorValues(t *testing.T) {value := 12.5+ eventAt := time.Date(2026, 7, 30, 18, 0, 0, 0, time.UTC)original := &Resource{ID: "agent-custom",Agent: &AgentData{Sensors: &HostSensorMeta{Custom: []HostCustomSensorMetric{{- ID: "queue_depth",- Name: "Queue depth",- Value: &value,- Status: "warning",+ ID: "queue_depth",+ Name: "Queue depth",+ Value: &value,+ EventAt: &eventAt,+ Status: "warning",}},},},@@ -127,6 +129,10 @@ func TestCloneResourceIsolatesCustomSensorValues(t *testing.T) {if original.Agent.Sensors.Custom[0].Name != "Queue depth" {t.Fatal("custom sensor slice was shared by clone")}+ *cloned.Agent.Sensors.Custom[0].EventAt = eventAt.Add(time.Hour)+ if !original.Agent.Sensors.Custom[0].EventAt.Equal(eventAt) {+ t.Fatal("custom sensor event time pointer was shared by clone")+ }}func TestCloneResource_MutateIncidents(t *testing.T) {diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.goindex bb285adff0..0e4694ec69 100644--- a/internal/unifiedresources/types.go+++ b/internal/unifiedresources/types.go@@ -619,15 +619,19 @@ type HostSensorMeta struct {}type HostCustomSensorMetric struct {- ID string `json:"id"`- Name string `json:"name"`- Unit string `json:"unit,omitempty"`- Value *float64 `json:"value,omitempty"`- Status string `json:"status"`- ObservedAt time.Time `json:"observedAt"`- Error string `json:"error,omitempty"`- AlertOnError bool `json:"alertOnError,omitempty"`- Stale bool `json:"stale,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ Group string `json:"group,omitempty"`+ Subgroup string `json:"subgroup,omitempty"`+ Kind string `json:"kind,omitempty"`+ Unit string `json:"unit,omitempty"`+ Value *float64 `json:"value,omitempty"`+ Status string `json:"status"`+ ObservedAt time.Time `json:"observedAt"`+ EventAt *time.Time `json:"eventAt,omitempty"`+ Error string `json:"error,omitempty"`+ AlertOnError bool `json:"alertOnError,omitempty"`+ Stale bool `json:"stale,omitempty"`}type HostGPUSensor struct {diff --git a/pkg/agents/host/report.go b/pkg/agents/host/report.goindex b3e29c11de..7434292b8a 100644--- a/pkg/agents/host/report.go+++ b/pkg/agents/host/report.go@@ -269,21 +269,28 @@ const (CustomSensorStatusWarning = "warning"CustomSensorStatusCritical = "critical"CustomSensorStatusError = "error"+ CustomSensorKindNumber = "number"+ CustomSensorKindBoolean = "boolean"+ CustomSensorKindTimestamp = "timestamp")-// CustomSensorMetric is a bounded numeric reading produced by an explicitly-// configured local executable. The agent, not the server, owns execution and-// threshold evaluation.+// CustomSensorMetric is a bounded reading produced by an explicitly configured+// local executable or HTTP endpoint. The agent owns collection and threshold+// evaluation.type CustomSensorMetric struct {- ID string `json:"id"`- Name string `json:"name"`- Unit string `json:"unit,omitempty"`- Value *float64 `json:"value,omitempty"`- Status string `json:"status"`- ObservedAt time.Time `json:"observedAt"`- Error string `json:"error,omitempty"`- AlertOnError bool `json:"alertOnError,omitempty"`- Stale bool `json:"stale,omitempty"`+ ID string `json:"id"`+ Name string `json:"name"`+ Group string `json:"group,omitempty"`+ Subgroup string `json:"subgroup,omitempty"`+ Kind string `json:"kind,omitempty"`+ Unit string `json:"unit,omitempty"`+ Value *float64 `json:"value,omitempty"`+ Status string `json:"status"`+ ObservedAt time.Time `json:"observedAt"`+ EventAt *time.Time `json:"eventAt,omitempty"`+ Error string `json:"error,omitempty"`+ AlertOnError bool `json:"alertOnError,omitempty"`+ Stale bool `json:"stale,omitempty"`}// GPUSensor captures direct GPU telemetry reported by a local host agent.diff --git a/pkg/agents/host/report_test.go b/pkg/agents/host/report_test.goindex 9e81562802..3f02e501ec 100644--- a/pkg/agents/host/report_test.go+++ b/pkg/agents/host/report_test.go@@ -92,6 +92,38 @@ func TestReport_JSONMarshal(t *testing.T) {}}+func TestCustomSensorMetricJSONRoundTrip(t *testing.T) {+ value := 7200.0+ eventAt := time.Date(2026, 7, 30, 18, 0, 0, 0, time.UTC)+ original := CustomSensorMetric{+ ID: "backup_age",+ Name: "Last file backup",+ Group: "Main server",+ Subgroup: "Backup",+ Kind: CustomSensorKindTimestamp,+ Unit: "seconds",+ Value: &value,+ Status: CustomSensorStatusWarning,+ ObservedAt: time.Date(2026, 7, 30, 20, 0, 0, 0, time.UTC),+ EventAt: &eventAt,+ AlertOnError: true,+ }++ data, err := json.Marshal(original)+ if err != nil {+ t.Fatalf("marshal custom sensor metric: %v", err)+ }+ var decoded CustomSensorMetric+ if err := json.Unmarshal(data, &decoded); err != nil {+ t.Fatalf("unmarshal custom sensor metric: %v", err)+ }+ if decoded.Group != original.Group || decoded.Subgroup != original.Subgroup ||+ decoded.Kind != CustomSensorKindTimestamp || decoded.Value == nil ||+ *decoded.Value != value || decoded.EventAt == nil || !decoded.EventAt.Equal(eventAt) {+ t.Fatalf("custom sensor metric did not round trip: %+v", decoded)+ }+}+func TestAgentInfo_Fields(t *testing.T) {agent := AgentInfo{ID: "agent-123",