Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

feat(alerts): add destination severity routing

rcourtman8df9db7ab115
diff --git a/docs/release-control/v6/internal/MOBILE_COMPATIBILITY_MANIFEST.json b/docs/release-control/v6/internal/MOBILE_COMPATIBILITY_MANIFEST.json
index 96f5cdb730..d7417cc107 100644
--- a/docs/release-control/v6/internal/MOBILE_COMPATIBILITY_MANIFEST.json
+++ b/docs/release-control/v6/internal/MOBILE_COMPATIBILITY_MANIFEST.json
@@ -46,6 +46,7 @@
"types": [
{ "value": "patrol_finding", "go_symbol": "PushTypePatrolFinding" },
{ "value": "patrol_critical", "go_symbol": "PushTypePatrolCritical" },
+ { "value": "alert_fired", "go_symbol": "PushTypeAlertFired" },
{ "value": "external_probe_offline", "go_symbol": "PushTypeExternalProbeOffline" },
{ "value": "approval_request", "go_symbol": "PushTypeApprovalRequest" },
{ "value": "fix_completed", "go_symbol": "PushTypeFixCompleted" }
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 80c56fa1bd..df94344337 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -6693,3 +6693,16 @@ prior live inventory. `TestHandleEnroll_Success`,
`TestMintBootstrapTokenForTarget_RollsBackWhenPersistenceFails` in
`internal/api/deploy_handlers_test.go` pin the durable replacement and rollback
paths.
+
+### Alert push routing does not create an agent lifecycle channel
+
+The shared API router may classify an external-probe outage for specialized
+mobile copy and may publish an ordinary dispatched incident through Relay, but
+that path carries only the canonical alert identity, severity, and private
+operator-facing copy. It cannot enroll, assign, link, update, command, revoke,
+remove, or re-enroll an agent. External-probe assignment remains an
+alerts-owned classification input rather than a second agent identity, and a
+mobile notification action resolves to the existing alert detail route rather
+than an agent lifecycle operation. The ordinary-alert and probe-specific
+payload proofs in `internal/api/alerting/external_probe_notifications_test.go`
+pin this boundary.
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 8d843dd39a..fd7621860f 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -442,10 +442,11 @@ transition references recovery evidence separate from its trigger evidence.
`frontend-modern/src/utils/alertDestinationsPresentation.ts`. The
destinations surface presents mobile push (Pulse Mobile paired through
Relay) alongside email, Apprise, and webhooks so phone delivery is
- discoverable where alert routing is configured. It stays a pointer
- surface: it routes setup to the canonical `/settings/system-relay` Remote
- Access panel rather than duplicating relay pairing state or relay API
- calls, and when the `relay` feature is absent it gates through the shared
+ discoverable where alert routing is configured. It may read and update the
+ Relay destination's alert minimum severity, but routes pairing and
+ connectivity setup to the canonical `/settings/system-relay` Remote Access
+ panel rather than duplicating Relay runtime state. When the `relay` feature
+ is absent it gates through the shared
`FeatureGateSection` and upgrade-navigation contract, rendering no upgrade
call-to-action when prompt suppression applies.
11. Add or change system-scoped alerts through
@@ -926,6 +927,10 @@ labels become `key:value` tags (or `key` for empty values), host-agent tags
remain literal, and unified resources forward their canonical `Tags`. The
alerts surface owns this producer metadata and routing UX; destination
matching, persistence, and receipt-aware delivery remain notifications-owned.
+The same editor exposes a minimum-severity policy for email, Apprise, each
+webhook, and Relay mobile push. The alerts surface owns the coherent routing UX;
+notifications owns provider filtering and recovery receipts, while Relay owns
+privacy-safe mobile projection and persisted mobile routing policy.
The alert manager callback layer now also has to stay fan-out-safe. Monitor
delivery, the unified alert bridge, and Patrol-adjacent AI listeners must
compose through additive fired/resolved subscriptions instead of overwriting a
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e4e54a2e9c..752145ca7b 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -132,13 +132,18 @@ and must not suppress the endpoint from type filters, totals, REST reloads, or
websocket snapshots. Plural machine projections use `availabilityChecks`; the
singular `availability` field remains only a compatibility projection.
-The API-owned Relay adapter may translate a canonical external-probe outage
-into the governed Pulse Mobile push contract only after alert identity is
-established. The push carries the stable alert ID and the generated
-`external_probe_offline` type with the existing `view_alert` action; it carries
-no infrastructure name, target, address, error text, or arbitrary alert
-metadata. A host-offline alert is eligible only when that host currently owns
-an enabled external-probe assignment.
+The API-owned Relay adapter projects every canonical alert that reaches the
+fired-dispatch callback into the governed Pulse Mobile push contract, subject
+to the Relay destination's persisted all-alert or critical-only floor. An
+ordinary alert carries the stable alert ID, generated `alert_fired` type,
+canonical severity, and existing `view_alert` action. A canonical
+external-probe outage retains the generated `external_probe_offline` type; a
+host-offline alert is eligible for that specialized type only when the host
+currently owns an enabled external-probe assignment. Both projections carry no
+infrastructure name, target, address, error text, or arbitrary alert metadata.
+`GET` and `PUT /api/settings/relay` expose `alert_minimum_severity` without
+exposing Relay secrets, and mixed persisted state normalizes to all-alert
+delivery unless critical-only was selected explicitly.
`POST /api/agent-install-command` accepts an optional `insecure` boolean for
Proxmox installer generation. When true, the returned command uses insecure
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 0109527141..be26d32986 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -6670,3 +6670,16 @@ panel-local Show/Hide control. Status badges use shared theme tokens, error and
unavailable states remain textually distinct, and the four-part status grid
collapses without horizontal overflow at phone widths. This pattern is the
required primitive composition for future secret-bearing destination panels.
+
+### Alert destinations share one severity-policy primitive
+
+Email, webhook, Apprise, and entitled mobile-push panels compose the
+feature-owned `DestinationSeveritySelect` rather than implementing separate
+labels, option vocabularies, or responsive layouts. The control builds on the
+shared `FormSelect` primitive, exposes one associated label, and uses the same
+`All alerts` / `Critical alerts only` presentation at desktop and phone widths.
+Destination-specific help may explain transport semantics—mobile copy states
+its privacy and current-state boundary—but it must not redefine the policy.
+Alert feature state owns persistence and entitlement gating; the primitive
+owns presentation only. `alertDestinationsPresentation.test.ts` pins the
+shared vocabulary and the distinct mobile guidance.
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 87be164583..c0759d13b0 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -403,21 +403,27 @@ received that exact firing occurrence. Successful recovery delivery deletes
the receipt; persistent receipts survive restart and are retention-bounded.
Receipt read failure suppresses recovery rather than inventing prior delivery.
-### Resource-tag destination routing
+### Destination alert routing
Email and every enabled alert webhook may define a normalized resource-tag
filter and an `all` or `any` match mode. Empty filters preserve global
delivery. Matching is exact after trimming and case folding, and grouped
firing alerts are filtered independently for each destination; Apprise remains
-global. Tags may arrive through the canonical `tags`, `resourceTags`,
+global by resource tag. Tags may arrive through the canonical `tags`, `resourceTags`,
`hostTags`, or `serviceTags` alert metadata keys.
-Resolved delivery deliberately bypasses current tag matching and is filtered
-by occurrence-bound delivery receipts instead. This guarantees that a
+Email, every enabled alert webhook, and Apprise may also define a normalized
+minimum severity of `all`, `warning`, or `critical`. Omitted or unknown values
+preserve backwards-compatible all-alert delivery. Grouped firing alerts are
+filtered independently per destination, after both tag and severity policy are
+applied, so one incident batch may produce different destination payloads.
+
+Resolved delivery deliberately bypasses current tag and severity matching and
+is filtered by occurrence-bound delivery receipts instead. This guarantees that a
destination which received a firing occurrence can receive its recovery even
-if resource tags change. Configuration copies must isolate filter slices,
-mixed-version updates must preserve omitted routing fields, and explicit empty
-filters must remain the supported clear operation.
+if resource tags or destination policy change. Configuration copies must
+isolate filter slices, mixed-version updates must preserve omitted routing
+fields, and explicit empty filters must remain the supported clear operation.
Cooldown state is published only after firing receipts are recorded. Persistent
workers atomically claim a still-pending row after taking per-alert delivery
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 6c6ad9c5a2..f40d8886d7 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2848,3 +2848,15 @@ poll context and cluster failover boundary, adds no goroutine or frontend
request, and a failed read retains the previous bounded slice.
`internal/monitoring/node_memory_sources_test.go` pins both failure continuity
and the within-window no-call path.
+
+### Mobile alert severity routing stays off persistence hot paths
+
+The router loads the persisted Relay alert-severity floor when it constructs or
+refreshes the Relay client and caches the normalized value under the same
+`relayMu` boundary. Dispatching an incident performs one in-memory eligibility
+comparison before the existing asynchronous push call; it does not read system
+settings, open storage, enumerate paired devices, add a poll, or create a new
+goroutine per destination. Updating Relay settings atomically replaces the
+cached client and floor, so the next incident observes the new policy without
+turning alert fan-out into configuration I/O. The hosted Relay runtime tests
+pin persistence and cache replacement together.
diff --git a/docs/release-control/v6/internal/subsystems/relay-runtime.md b/docs/release-control/v6/internal/subsystems/relay-runtime.md
index 1243010a76..67a170153d 100644
--- a/docs/release-control/v6/internal/subsystems/relay-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/relay-runtime.md
@@ -26,11 +26,15 @@ warning, approval, and fix-result notifications. The relay protocol preserves
each boolean so server-side delivery can enforce the paired device's choices;
legacy clients omit the entire preferences object and remain wire-compatible.
-The generated mobile push vocabulary includes
-`external_probe_offline` for a Pulse instance that is still connected while
-one of its assigned external probes stops reporting. Desktop Relay sends only
-generic copy, the canonical alert ID, and the existing `view_alert` action;
-resource names, addresses, targets, and probe errors remain inside Pulse.
+The generated mobile push vocabulary includes `alert_fired` for ordinary
+canonical alerts and `external_probe_offline` for a Pulse instance that is
+still connected while one of its assigned external probes stops reporting.
+Desktop Relay sends only generic severity-aware copy, the canonical alert ID,
+and the existing `view_alert` action; resource names, addresses, targets,
+messages, metadata, and probe errors remain inside Pulse. The persisted Relay
+destination policy defaults to all alerts and may be set to critical-only;
+runtime dispatch reads the cached live policy rather than loading persisted
+configuration for each alert.
Relay's independent whole-instance disconnect notification remains the sole
dark-site signal and must not be conflated with this per-agent alert.
@@ -68,7 +72,7 @@ dark-site signal and must not be conflated with this per-agent alert.
1. Add or change desktop relay reconnect, registration, drain, proxy-stream, or encrypted channel behavior through `internal/relay/`
2. Add or change relay control payload schemas, including mobile-visible push notification metadata, through `internal/relay/protocol.go`
-3. Add or change persisted relay enablement, server URL, or reconnect-safe default loading through `internal/config/persistence_relay.go`
+3. Add or change persisted relay enablement, server URL, alert severity routing, or reconnect-safe default loading through `internal/config/persistence_relay.go`
`LoadRelayConfig` must apply environment-variable overrides
(`PULSE_RELAY_ENABLED`, `PULSE_RELAY_SERVER`) on top of the file-loaded
or default-fallback `relay.Config` via `relay.ApplyEnvOverrides`. The
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index cb7fa0bc82..59df4ad00f 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -2368,3 +2368,18 @@ primary-token projection, returns an error, and discloses no runtime secret;
failed bootstrap minting likewise returns no credential material. The success,
replay, and forced-write-failure paths are exercised in
`internal/api/deploy_handlers_test.go`.
+
+### Mobile alert notifications are private by construction
+
+Ordinary warning and critical alert pushes contain a generic severity-aware
+title and private prompt to open Pulse Mobile; lock-screen payloads do not
+include hostnames, resource names, addresses, metric values, thresholds,
+provider identifiers, probe targets, or notification credentials. The action
+carries only the canonical alert ID required to open the authenticated alert
+surface, where current state is re-read rather than trusted from stale push
+copy. External-probe outages retain their existing private specialized
+message. Relay configuration responses expose the normalized alert-severity
+floor but never the Relay private key, and omitted or invalid floors fail open
+to `all` rather than silently suppressing warnings. Payload-shape and config
+normalization proofs live in `internal/relay/push_test.go` and
+`internal/api/relay_hosted_runtime_test.go`.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 6fbe25857e..49ba6acb02 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -5655,3 +5655,17 @@ no backup, restore, retention, snapshot, or recovery authority; they prevent a
successful enrollment response from describing credential state that a restart
would undo. Their success and forced-write-failure proofs live in
`internal/api/deploy_handlers_test.go`.
+
+### Destination severity policy preserves notification recovery identity
+
+Email, webhook, Apprise, and Relay minimum-severity floors persist through
+their existing configuration records; they create no backup, snapshot,
+restore, retention, or storage-action authority. Filtering occurs before a
+firing delivery is enqueued. A resolution is instead governed by the durable
+per-occurrence destination receipt, so a destination that received the firing
+event receives its recovery even if tags or severity policy changed in the
+meantime, while a destination that was filtered out does not receive an
+orphaned recovery. The canonical occurrence and receipt remain notification
+queue identities; the alert ID carried by a mobile push is navigation state,
+not a new persistence or recovery key. Restart and retry semantics therefore
+remain owned by the existing notification queue and config persistence paths.
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index f3c94011bb..9bff03a719 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,33 +1,60 @@
{
"version": 1,
- "base_sha": "ce555ee09d7cef30a2d784c18c629272aef9ab22",
- "verified_at": "2026-08-27T17:11:50Z",
+ "base_sha": "3d4c43162a2e05e86b486fc7ff24a677bf73036d",
+ "verified_at": "2026-08-27T17:51:27Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/api/resourceOperatorState.ts",
- "frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx",
- "frontend-modern/src/features/alerts/ResourceMonitoringPolicyAction.tsx"
+ "frontend-modern/src/api/notifications.ts",
+ "frontend-modern/src/api/relay.ts",
+ "frontend-modern/src/components/Alerts/DestinationSeveritySelect.tsx",
+ "frontend-modern/src/components/Alerts/EmailProviderSelect.tsx",
+ "frontend-modern/src/components/Alerts/WebhookConfigForm.tsx",
+ "frontend-modern/src/components/Alerts/WebhookConfigList.tsx",
+ "frontend-modern/src/components/Alerts/useWebhookConfigState.ts",
+ "frontend-modern/src/features/alerts/AlertAppriseDestinationsSection.tsx",
+ "frontend-modern/src/features/alerts/AlertPushDestinationsSection.tsx",
+ "frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx",
+ "frontend-modern/src/features/alerts/alertDestinationsModel.ts",
+ "frontend-modern/src/features/alerts/helpers.ts",
+ "frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx",
+ "frontend-modern/src/features/alerts/types.ts",
+ "frontend-modern/src/features/alerts/useAlertDestinationsState.ts",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationState.ts",
+ "frontend-modern/src/utils/alertDestinationsPresentation.ts"
],
"content_sha256": {
- "frontend-modern/src/api/resourceOperatorState.ts": "edbbb0253d63fba3f8c893edb4c911948883c88ba1ee61ecdac453853d370de4",
- "frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx": "9b45eb2a826c6db7fb7a47ec3dcc341c1ed47109228d83ed085788e647c69012",
- "frontend-modern/src/features/alerts/ResourceMonitoringPolicyAction.tsx": "fc2e4d010d80419e9532c49cddd9df954672c2d4a3b5de9d3336fd483562a4ad"
+ "frontend-modern/src/api/notifications.ts": "faf71397a60ad8cbabf70f9dfc891ad969efb34a455f9787c7d219400e822743",
+ "frontend-modern/src/api/relay.ts": "13b9b2cf5d7455b0e1a685db85ce50aff73a10071c8029348535acb3560f394f",
+ "frontend-modern/src/components/Alerts/DestinationSeveritySelect.tsx": "c7eb4c2b93c3090deccf7a7add952d37f762b802ed69e6c0d1021976af03b4d5",
+ "frontend-modern/src/components/Alerts/EmailProviderSelect.tsx": "6df0e0966111f68cf353cc7385b3eaac152480613ad51e587d1c574bd218cbc1",
+ "frontend-modern/src/components/Alerts/WebhookConfigForm.tsx": "c2e07aae1a8fb6080cf07ff12ee373f67809dbf966f21c2713135570cd142f2a",
+ "frontend-modern/src/components/Alerts/WebhookConfigList.tsx": "ee5df9481e03cf77388f45e7b6c2f4d97b2c4de4a50c2717a2e9dd215c12381c",
+ "frontend-modern/src/components/Alerts/useWebhookConfigState.ts": "29f9d17c646b059454d3a7f71578c63317a341970b6302911e9d964595d94a28",
+ "frontend-modern/src/features/alerts/AlertAppriseDestinationsSection.tsx": "26f04c0eb96ac7632b01ab7a6fd2fd676309ce28ea37a90df3f1350b405e3e62",
+ "frontend-modern/src/features/alerts/AlertPushDestinationsSection.tsx": "079e71faeef74b1d56ded4a345a28447629fd1742942f355ce4d9c9a4941f52c",
+ "frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx": "7f4f91966cd0638a6867e983875ab5170984d3e245ecc6ea7a28018f1fc7ecda",
+ "frontend-modern/src/features/alerts/alertDestinationsModel.ts": "cb289cc948d1f4f86e8e4a93618c32d545e8d7a7bbfdf45ab1c9f14325609f38",
+ "frontend-modern/src/features/alerts/helpers.ts": "6421ea5377ee3dc11226dd917e6dddc98f285ab1c324cc5e583fd49c3e56cc73",
+ "frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx": "991f1076a75ff64e62fd02dd0f8cbfcd4e46bb865eb115ce6efbdf477201be27",
+ "frontend-modern/src/features/alerts/types.ts": "d25caaaf62e354247fac70c9278b27b6db82380f8914949ddf5fb7cd296e501d",
+ "frontend-modern/src/features/alerts/useAlertDestinationsState.ts": "36a89bd5cbde02cf9e263734911468b15591927c170cb5287cb0f1354f325e20",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationState.ts": "48870de79c4e803bbcff3456d3da1d8af06f4eb3d6d7cbb68c714aca64d1f443",
+ "frontend-modern/src/utils/alertDestinationsPresentation.ts": "4e3fd6d4799bb86df65a2fde5b73e62b9cc65bcebc66d3d3d142d678fa0bac7a"
},
- "routes": ["/alerts/overview", "/proxmox/overview"],
+ "routes": ["/alerts/notifications"],
"viewports": [
{ "width": 1280, "height": 800 },
{ "width": 390, "height": 844 }
],
"states": [
- "active Alerts overview with the per-alert Monitoring policy action",
- "newly discovered resource with no explicit operator-state record",
- "resource Manage drawer with the maintenance scheduler open in recurring mode",
- "recurring schedule with weekday, Europe/London timezone, and descendant scope selected"
+ "notifications-paused install with email, Apprise, webhook, watchdog, mobile push, and delivery-evidence sections",
+ "unlicensed Relay install with the mobile push upgrade gate",
+ "email and Apprise destinations using backwards-compatible all-alert routing"
],
"interactions": [
- "opened an alert Monitoring action and confirmed the canonical policy choices render without changing saved state",
- "opened a resource with no saved operator state and confirmed the lookup completes without a failed response or console error",
- "opened Manage, switched the maintenance scheduler from One time to Recurring, and exercised weekday, timezone, and descendant-scope controls without saving",
- "verified the full scheduler at 1280x800 and 390x844 with no horizontal overflow, interaction console errors, or failed interaction responses"
+ "opened Alerts Notifications from the alert navigation and confirmed two accessible minimum-severity selectors render",
+ "verified All alerts and Critical alerts only options plus occurrence-aware recovery guidance for email and Apprise",
+ "verified the unlicensed mobile push gate remains coherent and no Relay control is presented without entitlement",
+ "verified the route at 1280x800 and 390x844 with no browser console errors"
]
}
diff --git a/frontend-modern/src/api/__tests__/notifications.test.ts b/frontend-modern/src/api/__tests__/notifications.test.ts
index ddcce6ea04..fae76d7d8a 100644
--- a/frontend-modern/src/api/__tests__/notifications.test.ts
+++ b/frontend-modern/src/api/__tests__/notifications.test.ts
@@ -27,6 +27,7 @@ describe('NotificationsAPI', () => {
tls: false,
startTLS: false,
rateLimit: 0,
+ minimumSeverity: 'all',
} as any);
const config = await NotificationsAPI.getEmailConfig();
@@ -44,6 +45,7 @@ describe('NotificationsAPI', () => {
tls: false,
startTLS: false,
rateLimit: 0,
+ minimumSeverity: 'all',
});
});
@@ -76,6 +78,7 @@ describe('NotificationsAPI', () => {
tls: false,
startTLS: false,
rateLimit: undefined,
+ minimumSeverity: 'all',
});
});
diff --git a/frontend-modern/src/api/notifications.ts b/frontend-modern/src/api/notifications.ts
index fa62d42c5f..f1f431db92 100644
--- a/frontend-modern/src/api/notifications.ts
+++ b/frontend-modern/src/api/notifications.ts
@@ -42,6 +42,8 @@ export interface WebhookTemplate {
};
}
+export type NotificationMinimumSeverity = 'all' | 'critical';
+
export interface EmailConfig {
enabled: boolean;
provider: string;
@@ -56,6 +58,7 @@ export interface EmailConfig {
rateLimit?: number;
tagFilter?: string[];
tagFilterMode?: 'all' | 'any';
+ minimumSeverity?: NotificationMinimumSeverity;
}
export interface Webhook {
@@ -71,6 +74,7 @@ export interface Webhook {
mention?: string; // Platform-specific mention (e.g., @everyone, @channel, <@USER_ID>)
tagFilter?: string[];
tagFilterMode?: 'all' | 'any';
+ minimumSeverity?: NotificationMinimumSeverity;
}
export interface AppriseConfig {
@@ -84,6 +88,7 @@ export interface AppriseConfig {
apiKey?: string;
apiKeyHeader?: string;
skipTlsVerify?: boolean;
+ minimumSeverity?: NotificationMinimumSeverity;
// Responses never include the stored apiKey; this reports whether one is saved.
hasApiKey?: boolean;
}
@@ -413,6 +418,7 @@ export class NotificationsAPI {
if (typeof backendConfig.tagFilterMode === 'string') {
config.tagFilterMode = backendConfig.tagFilterMode === 'any' ? 'any' : 'all';
}
+ config.minimumSeverity = backendConfig.minimumSeverity === 'critical' ? 'critical' : 'all';
return config;
}
@@ -441,6 +447,9 @@ export class NotificationsAPI {
if (config.tagFilterMode !== undefined) {
backendConfig.tagFilterMode = config.tagFilterMode === 'any' ? 'any' : 'all';
}
+ if (config.minimumSeverity !== undefined) {
+ backendConfig.minimumSeverity = config.minimumSeverity === 'critical' ? 'critical' : 'all';
+ }
return apiFetchJSON(`${this.baseUrl}/email`, {
method: 'PUT',
diff --git a/frontend-modern/src/api/relay.ts b/frontend-modern/src/api/relay.ts
index 7121d1f237..cd427652ed 100644
--- a/frontend-modern/src/api/relay.ts
+++ b/frontend-modern/src/api/relay.ts
@@ -4,6 +4,7 @@ export interface RelayConfig {
enabled: boolean;
server_url: string;
identity_fingerprint?: string;
+ alert_minimum_severity?: 'all' | 'critical';
}
export interface RelayStatus {
@@ -21,7 +22,7 @@ export class RelayAPI {
}
static async updateConfig(
- update: Partial<Pick<RelayConfig, 'enabled' | 'server_url'>>,
+ update: Partial<Pick<RelayConfig, 'enabled' | 'server_url' | 'alert_minimum_severity'>>,
): Promise<void> {
await apiFetchJSON(this.baseUrl, {
method: 'PUT',
diff --git a/frontend-modern/src/components/Alerts/DestinationSeveritySelect.tsx b/frontend-modern/src/components/Alerts/DestinationSeveritySelect.tsx
new file mode 100644
index 0000000000..6e2786908d
--- /dev/null
+++ b/frontend-modern/src/components/Alerts/DestinationSeveritySelect.tsx
@@ -0,0 +1,36 @@
+import type { NotificationMinimumSeverity } from '@/api/notifications';
+import { controlClass, formControl } from '@/components/shared/Form';
+import { FormSelect } from '@/components/shared/FormSelect';
+import {
+ ALERT_DESTINATION_ALL_SEVERITIES_LABEL,
+ ALERT_DESTINATION_CRITICAL_ONLY_LABEL,
+ ALERT_DESTINATION_MINIMUM_SEVERITY_HELP,
+ ALERT_DESTINATION_MINIMUM_SEVERITY_LABEL,
+} from '@/utils/alertDestinationsPresentation';
+
+interface DestinationSeveritySelectProps {
+ id: string;
+ value: NotificationMinimumSeverity;
+ onChange: (value: NotificationMinimumSeverity) => void;
+ compact?: boolean;
+ help?: string;
+}
+
+export function DestinationSeveritySelect(props: DestinationSeveritySelectProps) {
+ return (
+ <FormSelect
+ id={props.id}
+ label={ALERT_DESTINATION_MINIMUM_SEVERITY_LABEL}
+ labelClass={props.compact ? undefined : 'text-xs uppercase tracking-[0.08em]'}
+ value={props.value}
+ onChange={(event) =>
+ props.onChange(event.currentTarget.value === 'critical' ? 'critical' : 'all')
+ }
+ selectBaseClass={props.compact ? controlClass('px-2 py-1.5') : formControl}
+ help={props.help ?? ALERT_DESTINATION_MINIMUM_SEVERITY_HELP}
+ >
+ <option value="all">{ALERT_DESTINATION_ALL_SEVERITIES_LABEL}</option>
+ <option value="critical">{ALERT_DESTINATION_CRITICAL_ONLY_LABEL}</option>
+ </FormSelect>
+ );
+}
diff --git a/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx b/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx
index 93d0c01ae8..f8f2f59de1 100644
--- a/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx
+++ b/frontend-modern/src/components/Alerts/EmailProviderSelect.test.tsx
@@ -234,7 +234,7 @@ describe('EmailProviderSelect', () => {
expect(screen.getByText('Gmail (smtp.gmail.com:587)')).toBeInTheDocument();
});
- const select = screen.getByRole('combobox') as HTMLSelectElement;
+ const select = screen.getByRole('combobox', { name: 'Email provider' }) as HTMLSelectElement;
fireEvent.change(select, { target: { value: 'Gmail' } });
expect(onChangeMock).toHaveBeenCalledWith(
@@ -261,7 +261,7 @@ describe('EmailProviderSelect', () => {
expect(screen.getByText('SendGrid (smtp.sendgrid.net:587)')).toBeInTheDocument();
});
- const select = screen.getByRole('combobox') as HTMLSelectElement;
+ const select = screen.getByRole('combobox', { name: 'Email provider' }) as HTMLSelectElement;
fireEvent.change(select, { target: { value: 'SendGrid' } });
expect(onChangeMock).toHaveBeenCalledWith(
@@ -285,7 +285,7 @@ describe('EmailProviderSelect', () => {
expect(screen.getByText('Gmail (smtp.gmail.com:587)')).toBeInTheDocument();
});
- const select = screen.getByRole('combobox') as HTMLSelectElement;
+ const select = screen.getByRole('combobox', { name: 'Email provider' }) as HTMLSelectElement;
fireEvent.change(select, { target: { value: 'Gmail' } });
expect(onChangeMock).toHaveBeenCalledWith(
@@ -309,7 +309,7 @@ describe('EmailProviderSelect', () => {
expect(screen.getByText('Gmail (smtp.gmail.com:587)')).toBeInTheDocument();
});
- const select = screen.getByRole('combobox') as HTMLSelectElement;
+ const select = screen.getByRole('combobox', { name: 'Email provider' }) as HTMLSelectElement;
fireEvent.change(select, { target: { value: '' } });
expect(onChangeMock).toHaveBeenCalledWith(
diff --git a/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx b/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx
index fb6d9d8f1b..df004a6881 100644
--- a/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx
+++ b/frontend-modern/src/components/Alerts/EmailProviderSelect.tsx
@@ -39,6 +39,7 @@ import {
import { FormSelect } from '@/components/shared/FormSelect';
import { FormTextarea } from '@/components/shared/FormTextarea';
import { TagInput } from '@/components/shared/TagInput';
+import { DestinationSeveritySelect } from './DestinationSeveritySelect';
interface EmailProviderSelectProps extends EmailProviderSelectStateProps {
config: UIEmailConfig;
@@ -61,6 +62,7 @@ export function EmailProviderSelect(props: EmailProviderSelectProps) {
maxRetries: `${fieldIdPrefix}-max-retries`,
retryDelay: `${fieldIdPrefix}-retry-delay`,
tagMode: `${fieldIdPrefix}-tag-mode`,
+ minimumSeverity: `${fieldIdPrefix}-minimum-severity`,
};
const instructionBoxClass =
'mt-2 rounded border border-blue-200 bg-blue-50 px-3 py-2 text-xs leading-relaxed text-blue-900 dark:border-blue-700 dark:bg-blue-900 dark:text-blue-200';
@@ -238,6 +240,15 @@ export function EmailProviderSelect(props: EmailProviderSelectProps) {
placeholder={getAlertEmailRecipientsPlaceholder(props.config.from)}
/>
+ <div class="space-y-2 border-t border-border pt-3">
+ <DestinationSeveritySelect
+ id={fieldIds.minimumSeverity}
+ value={props.config.minimumSeverity ?? 'all'}
+ compact
+ onChange={(minimumSeverity) => props.onChange({ ...props.config, minimumSeverity })}
+ />
+ </div>
+
<div class="space-y-2 border-t border-border pt-3">
<div>
<div class={labelClass()}>Resource tag routing</div>
diff --git a/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx b/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx
index e35e18eac4..ddd23c2f57 100644
--- a/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx
+++ b/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx
@@ -831,7 +831,7 @@ describe('WebhookConfig', () => {
expect(screen.getByText(/Discord →/)).toBeInTheDocument();
// Verify template method is applied — the select should now show POST (Discord template method)
- const methodSelect = screen.getByRole('combobox') as HTMLSelectElement;
+ const methodSelect = screen.getByRole('combobox', { name: 'HTTP method' }) as HTMLSelectElement;
expect(methodSelect.value).toBe('POST');
// Verify template name was applied to form since name was empty
@@ -1042,7 +1042,7 @@ describe('WebhookConfig', () => {
fireEvent.click(screen.getByText('+ Add Webhook'));
- const methodSelect = screen.getByRole('combobox') as HTMLSelectElement;
+ const methodSelect = screen.getByRole('combobox', { name: 'HTTP method' }) as HTMLSelectElement;
expect(methodSelect.value).toBe('POST');
fireEvent.change(methodSelect, { target: { value: 'PUT' } });
diff --git a/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx b/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx
index a8e1c5fc4e..7e6e86ae05 100644
--- a/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx
+++ b/frontend-modern/src/components/Alerts/WebhookConfigForm.tsx
@@ -48,6 +48,7 @@ import { FormTextarea } from '@/components/shared/FormTextarea';
import { TagInput } from '@/components/shared/TagInput';
import type { CustomFieldInput, HeaderInput, WebhookConfigFormData } from './useWebhookConfigState';
+import { DestinationSeveritySelect } from './DestinationSeveritySelect';
type SetterLike<T> = (value: T | ((prev: T) => T)) => T;
@@ -168,6 +169,17 @@ export function WebhookConfigForm(props: WebhookConfigFormProps) {
</p>
</div>
+ <div class="space-y-2 border-t border-border pt-3">
+ <DestinationSeveritySelect
+ id="alert-webhook-minimum-severity"
+ value={props.formData().minimumSeverity ?? 'all'}
+ compact
+ onChange={(minimumSeverity) =>
+ props.setFormData((prev) => ({ ...prev, minimumSeverity }))
+ }
+ />
+ </div>
+
<div class="space-y-2 border-t border-border pt-3">
<div>
<div class={labelClass()}>Resource tag routing</div>
diff --git a/frontend-modern/src/components/Alerts/WebhookConfigList.tsx b/frontend-modern/src/components/Alerts/WebhookConfigList.tsx
index 0c8b91dc79..547275e72d 100644
--- a/frontend-modern/src/components/Alerts/WebhookConfigList.tsx
+++ b/frontend-modern/src/components/Alerts/WebhookConfigList.tsx
@@ -11,6 +11,7 @@ import {
getAlertWebhookToggleAllLabel,
getAlertWebhookToggleLabel,
} from '@/utils/alertWebhookPresentation';
+import { getAlertDestinationSeverityLabel } from '@/utils/alertDestinationsPresentation';
interface WebhookConfigListProps {
webhooks: Webhook[];
@@ -75,6 +76,11 @@ export function WebhookConfigList(props: WebhookConfigListProps) {
<span class="rounded bg-surface-alt px-2 py-0.5 text-base-content">
{webhook.method}
</span>
+ <span class="rounded bg-surface-alt px-2 py-0.5 text-base-content">
+ {getAlertDestinationSeverityLabel(
+ webhook.minimumSeverity === 'critical' ? 'critical' : 'all',
+ )}
+ </span>
<For each={webhook.tagFilter ?? []}>
{(tag) => (
<span class="rounded bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-900 dark:text-sky-300">
diff --git a/frontend-modern/src/components/Alerts/useWebhookConfigState.ts b/frontend-modern/src/components/Alerts/useWebhookConfigState.ts
index d0f22132e0..080e44d0ec 100644
--- a/frontend-modern/src/components/Alerts/useWebhookConfigState.ts
+++ b/frontend-modern/src/components/Alerts/useWebhookConfigState.ts
@@ -41,6 +41,7 @@ const createDefaultFormData = (): WebhookConfigFormData => ({
mention: '',
tagFilter: [],
tagFilterMode: 'all',
+ minimumSeverity: 'all',
});
const buildMapFromInputs = (
@@ -184,6 +185,7 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigS
mention: webhook.mention || '',
tagFilter: webhook.tagFilter ?? [],
tagFilterMode: webhook.tagFilterMode === 'any' ? 'any' : 'all',
+ minimumSeverity: webhook.minimumSeverity === 'critical' ? 'critical' : 'all',
});
const headers = webhook.headers || {};
@@ -269,6 +271,7 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigS
mention: data.mention,
tagFilter: data.tagFilter ?? [],
tagFilterMode: data.tagFilterMode === 'any' ? 'any' : 'all',
+ minimumSeverity: data.minimumSeverity === 'critical' ? 'critical' : 'all',
});
resetForm();
};
diff --git a/frontend-modern/src/features/alerts/AlertAppriseDestinationsSection.tsx b/frontend-modern/src/features/alerts/AlertAppriseDestinationsSection.tsx
index a653618e1e..e79e47b870 100644
--- a/frontend-modern/src/features/alerts/AlertAppriseDestinationsSection.tsx
+++ b/frontend-modern/src/features/alerts/AlertAppriseDestinationsSection.tsx
@@ -6,6 +6,7 @@ import { Toggle } from '@/components/shared/Toggle';
import { formControl, formField, formHelpText, labelClass } from '@/components/shared/Form';
import { FormSelect } from '@/components/shared/FormSelect';
import { FormTextarea } from '@/components/shared/FormTextarea';
+import { DestinationSeveritySelect } from '@/components/Alerts/DestinationSeveritySelect';
import type { UIAppriseConfig } from './types';
import {
ALERT_DESTINATIONS_APPRISE_API_KEY_HEADER_HELP,
@@ -62,6 +63,7 @@ export function AlertAppriseDestinationsSection(props: AlertAppriseDestinationsS
apiKeyHeader: `${fieldIdPrefix}-api-key-header`,
skipTlsVerify: `${fieldIdPrefix}-skip-tls-verify`,
timeout: `${fieldIdPrefix}-timeout`,
+ minimumSeverity: `${fieldIdPrefix}-minimum-severity`,
};
return (
@@ -128,6 +130,15 @@ export function AlertAppriseDestinationsSection(props: AlertAppriseDestinationsS
help={getAlertDestinationsAppriseTargetsHelp(props.config.mode)}
/>
+ <DestinationSeveritySelect
+ id={fieldIds.minimumSeverity}
+ value={props.config.minimumSeverity ?? 'all'}
+ onChange={(minimumSeverity) => {
+ props.updateApprise({ minimumSeverity });
+ props.setHasUnsavedChanges(true);
+ }}
+ />
+
<Show when={props.config.mode === 'cli'}>
<div class={formField}>
<label for={fieldIds.cliPath} class={labelClass('text-xs uppercase tracking-[0.08em]')}>
diff --git a/frontend-modern/src/features/alerts/AlertPushDestinationsSection.test.tsx b/frontend-modern/src/features/alerts/AlertPushDestinationsSection.test.tsx
index 248e274b68..4f279c12b3 100644
--- a/frontend-modern/src/features/alerts/AlertPushDestinationsSection.test.tsx
+++ b/frontend-modern/src/features/alerts/AlertPushDestinationsSection.test.tsx
@@ -1,10 +1,11 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { Route, Router } from '@solidjs/router';
import type { JSX } from 'solid-js';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { AlertPushDestinationsSection } from './AlertPushDestinationsSection';
import {
ALERT_DESTINATIONS_PUSH_GATE_MESSAGE,
+ ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP,
ALERT_DESTINATIONS_PUSH_READY_MESSAGE,
ALERT_DESTINATIONS_PUSH_SETUP_LINK_LABEL,
} from '@/utils/alertDestinationsPresentation';
@@ -29,11 +30,14 @@ describe('AlertPushDestinationsSection', () => {
});
it('points licensed installs at Remote Access settings', () => {
+ const onMinimumSeverityChange = vi.fn();
renderWithRouter(() => (
<AlertPushDestinationsSection
relayLicensed={true}
showUpgradePrompts={true}
upgradeDestination={upgradeDestination}
+ minimumSeverity="critical"
+ onMinimumSeverityChange={onMinimumSeverityChange}
/>
));
@@ -42,6 +46,12 @@ describe('AlertPushDestinationsSection', () => {
name: `${ALERT_DESTINATIONS_PUSH_SETUP_LINK_LABEL} →`,
});
expect(link).toHaveAttribute('href', '/settings/system-relay');
+
+ const severity = screen.getByRole('combobox', { name: 'Minimum alert severity' });
+ expect(severity).toHaveValue('critical');
+ fireEvent.change(severity, { target: { value: 'all' } });
+ expect(onMinimumSeverityChange).toHaveBeenCalledWith('all');
+ expect(screen.getByText(ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP)).toBeInTheDocument();
});
it('shows the Relay upgrade gate to unlicensed installs', () => {
diff --git a/frontend-modern/src/features/alerts/AlertPushDestinationsSection.tsx b/frontend-modern/src/features/alerts/AlertPushDestinationsSection.tsx
index 567054ca5b..a696863628 100644
--- a/frontend-modern/src/features/alerts/AlertPushDestinationsSection.tsx
+++ b/frontend-modern/src/features/alerts/AlertPushDestinationsSection.tsx
@@ -6,16 +6,20 @@ import type { UpgradeDestination } from '@/utils/upgradeNavigation';
import {
ALERT_DESTINATIONS_PUSH_GATE_MESSAGE,
ALERT_DESTINATIONS_PUSH_GATE_TITLE,
+ ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP,
ALERT_DESTINATIONS_PUSH_PANEL_DESCRIPTION,
ALERT_DESTINATIONS_PUSH_PANEL_TITLE,
ALERT_DESTINATIONS_PUSH_READY_MESSAGE,
ALERT_DESTINATIONS_PUSH_SETUP_LINK_LABEL,
} from '@/utils/alertDestinationsPresentation';
+import { DestinationSeveritySelect } from '@/components/Alerts/DestinationSeveritySelect';
interface AlertPushDestinationsSectionProps {
relayLicensed: boolean;
showUpgradePrompts: boolean;
upgradeDestination: UpgradeDestination;
+ minimumSeverity?: 'all' | 'critical';
+ onMinimumSeverityChange?: (value: 'all' | 'critical') => void;
}
export function AlertPushDestinationsSection(props: AlertPushDestinationsSectionProps) {
@@ -38,8 +42,14 @@ export function AlertPushDestinationsSection(props: AlertPushDestinationsSection
/>
}
>
- <div class="flex flex-col gap-2">
+ <div class="flex flex-col gap-4">
<p class="text-sm text-muted">{ALERT_DESTINATIONS_PUSH_READY_MESSAGE}</p>
+ <DestinationSeveritySelect
+ id="alert-push-minimum-severity"
+ value={props.minimumSeverity ?? 'all'}
+ onChange={(value) => props.onMinimumSeverityChange?.(value)}
+ help={ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP}
+ />
<a
href="/settings/system-relay"
class="text-sm font-medium text-blue-600 dark:text-blue-400 hover:underline"
diff --git a/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx b/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
index 618c687ce5..d8531b1da4 100644
--- a/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
+++ b/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
@@ -214,6 +214,8 @@ export function AlertsConfigurationSurface(props: AlertsConfigurationSurfaceProp
setHasUnsavedChanges={state.guardedSetHasUnsavedChanges}
deadManPingUrl={state.deadManPingUrl}
setDeadManPingUrl={state.setDeadManPingUrl}
+ pushMinimumSeverity={state.pushMinimumSeverity}
+ setPushMinimumSeverity={state.setPushMinimumSeverity}
emailConfig={state.emailConfig}
setEmailConfig={state.setEmailConfig}
appriseConfig={state.appriseConfig}
diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712.test.ts
index 372a05c47a..e510c6d050 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712.test.ts
@@ -117,6 +117,7 @@ describe('buildEmailConfigPayload — branch coverage (batch 2)', () => {
tls: false,
startTLS: false,
+ minimumSeverity: 'all',
});
});
diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712c.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712c.test.ts
index c29e9f8f6a..0ca707d6bb 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712c.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712c.test.ts
@@ -144,7 +144,7 @@ describe('buildEmailConfigPayload — branch coverage (batch 3 / 0712c)', () =>
// the value-level toStrictEqual checks in the sibling suite.
// -----------------------------------------------------------------------
describe('payload contract — exact key set', () => {
- it('emits exactly the 11 EmailConfig keys in declaration order and omits replyTo/maxRetries/retryDelay/rateLimit', () => {
+ it('emits exactly the EmailConfig keys in declaration order and omits replyTo/maxRetries/retryDelay/rateLimit', () => {
const result = buildEmailConfigPayload(
makeUIEmailConfig({
replyTo: '[email protected]',
@@ -164,6 +164,7 @@ describe('buildEmailConfigPayload — branch coverage (batch 3 / 0712c)', () =>
'to',
'tls',
'startTLS',
+ 'minimumSeverity',
]);
expect(result).not.toHaveProperty('replyTo');
expect(result).not.toHaveProperty('maxRetries');
diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0713.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0713.test.ts
index 5a9854eec8..4e254dfdd2 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0713.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0713.test.ts
@@ -324,6 +324,7 @@ describe('normalizeAppriseConfig — branch coverage (0713)', () => {
apiKeyHeader: 'X-API-KEY',
skipTlsVerify: false,
hasApiKey: false,
+ minimumSeverity: 'all',
};
it('returns the exact default shape for null input', () => {
@@ -543,7 +544,7 @@ describe('buildAppriseConfigPayload — branch coverage (0713)', () => {
// catches UI-only fields (targetsText) leaking into the API payload.
// -----------------------------------------------------------------------
describe('payload contract — exact key set', () => {
- it('emits exactly the 10 AppriseConfig keys and omits targetsText', () => {
+ it('emits exactly the AppriseConfig keys and omits targetsText', () => {
const result = buildAppriseConfigPayload(
makeUIAppriseConfig({
enabled: true,
@@ -569,6 +570,7 @@ describe('buildAppriseConfigPayload — branch coverage (0713)', () => {
'apiKey',
'apiKeyHeader',
'skipTlsVerify',
+ 'minimumSeverity',
]);
expect(result).not.toHaveProperty('targetsText');
});
@@ -599,6 +601,7 @@ describe('buildAppriseConfigPayload — branch coverage (0713)', () => {
apiKey: fakeKey,
apiKeyHeader: 'X-API-KEY',
skipTlsVerify: true,
+ minimumSeverity: 'all',
});
});
});
@@ -647,6 +650,7 @@ describe('buildEmailConfigPayload — branch coverage additions (0713)', () => {
tls: true,
startTLS: true,
+ minimumSeverity: 'all',
});
});
});
diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts
index 45baf5d9b6..96a3beebb0 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.test.ts
@@ -15,6 +15,7 @@ describe('alertDestinationsModel', () => {
targets: ['https://notify.example.test'],
serverUrl: 'https://apprise.example.test',
timeoutSeconds: 30,
+ minimumSeverity: 'critical',
}),
).toEqual(
expect.objectContaining({
@@ -23,6 +24,7 @@ describe('alertDestinationsModel', () => {
targetsText: 'https://notify.example.test',
serverUrl: 'https://apprise.example.test',
timeoutSeconds: 30,
+ minimumSeverity: 'critical',
}),
);
});
@@ -69,11 +71,13 @@ describe('alertDestinationsModel', () => {
rateLimit: 0,
tagFilter: [],
tagFilterMode: 'any',
+ minimumSeverity: 'critical',
}),
).toEqual(
expect.objectContaining({
tagFilter: [],
tagFilterMode: 'any',
+ minimumSeverity: 'critical',
}),
);
});
@@ -95,11 +99,13 @@ describe('alertDestinationsModel', () => {
maxRetries: 3,
retryDelay: 60,
rateLimit: 0,
+ minimumSeverity: 'critical',
}),
).toEqual(
expect.objectContaining({
server: 'smtp.internal',
+ minimumSeverity: 'critical',
}),
);
@@ -116,12 +122,14 @@ describe('alertDestinationsModel', () => {
apiKeyHeader: 'X-API-KEY',
skipTlsVerify: false,
hasApiKey: false,
+ minimumSeverity: 'critical',
}),
).toEqual(
expect.objectContaining({
mode: 'http',
targets: ['https://notify.internal'],
serverUrl: 'https://apprise.internal',
+ minimumSeverity: 'critical',
}),
);
});
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
index 0b478d74a3..4a0efab2fe 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
@@ -4,6 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { NotificationsAPI } from '@/api/notifications';
import { AlertsAPI } from '@/api/alerts';
+import { RelayAPI } from '@/api/relay';
+import { hasFeature } from '@/stores/license';
import { useAlertDestinationsState } from '../useAlertDestinationsState';
@@ -23,6 +25,17 @@ vi.mock('@/api/alerts', () => ({
},
}));
+vi.mock('@/api/relay', () => ({
+ RelayAPI: {
+ getConfig: vi.fn(),
+ updateConfig: vi.fn(),
+ },
+}));
+
+vi.mock('@/stores/license', () => ({
+ hasFeature: vi.fn(),
+}));
+
vi.mock('@/utils/logger', () => ({
logger: {
error: vi.fn(),
@@ -37,6 +50,10 @@ describe('useAlertDestinationsState', () => {
vi.mocked(NotificationsAPI.updateAppriseConfig).mockReset();
vi.mocked(AlertsAPI.getDeadManConfig).mockReset();
vi.mocked(AlertsAPI.updateDeadManConfig).mockReset();
+ vi.mocked(RelayAPI.getConfig).mockReset();
+ vi.mocked(RelayAPI.updateConfig).mockReset();
+ vi.mocked(hasFeature).mockReset();
+ vi.mocked(hasFeature).mockReturnValue(true);
});
it('owns alert destinations reload and save behavior separately from alert policy config', async () => {
@@ -53,6 +70,7 @@ describe('useAlertDestinationsState', () => {
tls: true,
startTLS: true,
+ minimumSeverity: 'critical',
} as any);
vi.mocked(NotificationsAPI.getAppriseConfig).mockResolvedValue({
enabled: true,
@@ -60,6 +78,7 @@ describe('useAlertDestinationsState', () => {
targets: ['mailto://[email protected]'],
cliPath: '/usr/local/bin/apprise',
timeoutSeconds: 20,
+ minimumSeverity: 'critical',
} as any);
vi.mocked(NotificationsAPI.updateEmailConfig).mockResolvedValue(undefined as any);
vi.mocked(NotificationsAPI.updateAppriseConfig).mockResolvedValue({
@@ -81,6 +100,12 @@ describe('useAlertDestinationsState', () => {
success: true,
configured: true,
});
+ vi.mocked(RelayAPI.getConfig).mockResolvedValue({
+ enabled: true,
+ server_url: 'wss://relay.example.test',
+ alert_minimum_severity: 'critical',
+ });
+ vi.mocked(RelayAPI.updateConfig).mockResolvedValue(undefined);
const { result } = renderHook(() => useAlertDestinationsState({ activeTab }));
@@ -88,9 +113,13 @@ describe('useAlertDestinationsState', () => {
expect(NotificationsAPI.getEmailConfig).toHaveBeenCalledTimes(1);
expect(NotificationsAPI.getAppriseConfig).toHaveBeenCalledTimes(1);
expect(AlertsAPI.getDeadManConfig).toHaveBeenCalledTimes(1);
+ expect(RelayAPI.getConfig).toHaveBeenCalledTimes(1);
expect(result.emailConfig().server).toBe('smtp.example.com');
+ expect(result.emailConfig().minimumSeverity).toBe('critical');
expect(result.appriseConfig().targetsText).toContain('mailto://[email protected]');
+ expect(result.appriseConfig().minimumSeverity).toBe('critical');
expect(result.deadManPingUrl()).toBe('***REDACTED***');
+ expect(result.pushMinimumSeverity()).toBe('critical');
setActiveTab('destinations');
await Promise.resolve();
@@ -98,6 +127,7 @@ describe('useAlertDestinationsState', () => {
expect(NotificationsAPI.getEmailConfig).toHaveBeenCalledTimes(2);
expect(NotificationsAPI.getAppriseConfig).toHaveBeenCalledTimes(2);
expect(AlertsAPI.getDeadManConfig).toHaveBeenCalledTimes(2);
+ expect(RelayAPI.getConfig).toHaveBeenCalledTimes(2);
setActiveTab('overview');
await Promise.resolve();
@@ -113,6 +143,7 @@ describe('useAlertDestinationsState', () => {
targetsText: 'https://notify.internal',
});
result.setDeadManPingUrl('https://watchdog.example.test/ping/replacement-token');
+ result.setPushMinimumSeverity('all');
await result.saveDestinations();
@@ -129,6 +160,7 @@ describe('useAlertDestinationsState', () => {
expect(AlertsAPI.updateDeadManConfig).toHaveBeenCalledWith(
'https://watchdog.example.test/ping/replacement-token',
);
+ expect(RelayAPI.updateConfig).toHaveBeenCalledWith({ alert_minimum_severity: 'all' });
expect(result.appriseConfig().mode).toBe('http');
expect(result.appriseConfig().serverUrl).toBe('https://apprise.example.test');
@@ -137,5 +169,6 @@ describe('useAlertDestinationsState', () => {
expect(result.emailConfig().enabled).toBe(false);
expect(result.appriseConfig().enabled).toBe(false);
expect(result.deadManPingUrl()).toBe('');
+ expect(result.pushMinimumSeverity()).toBe('all');
});
});
diff --git a/frontend-modern/src/features/alerts/alertDestinationsModel.ts b/frontend-modern/src/features/alerts/alertDestinationsModel.ts
index 028ec70d80..0f7fc75d94 100644
--- a/frontend-modern/src/features/alerts/alertDestinationsModel.ts
+++ b/frontend-modern/src/features/alerts/alertDestinationsModel.ts
@@ -21,6 +21,7 @@ export function normalizeAppriseConfig(
apiKeyHeader: config?.apiKeyHeader || 'X-API-KEY',
skipTlsVerify: Boolean(config?.skipTlsVerify),
hasApiKey: Boolean(config?.hasApiKey || config?.apiKey),
+ minimumSeverity: config?.minimumSeverity === 'critical' ? 'critical' : 'all',
};
}
@@ -43,6 +44,7 @@ export function buildEmailConfigPayload(config: UIEmailConfig): EmailConfig {
if (config.tagFilterMode !== undefined) {
payload.tagFilterMode = config.tagFilterMode === 'any' ? 'any' : 'all';
}
+ payload.minimumSeverity = config.minimumSeverity === 'critical' ? 'critical' : 'all';
return payload;
}
@@ -58,6 +60,7 @@ export function buildAppriseConfigPayload(config: UIAppriseConfig): AppriseConfi
apiKey: config.apiKey,
apiKeyHeader: config.apiKeyHeader,
skipTlsVerify: config.skipTlsVerify,
+ minimumSeverity: config.minimumSeverity === 'critical' ? 'critical' : 'all',
} as AppriseConfig;
}
diff --git a/frontend-modern/src/features/alerts/helpers.ts b/frontend-modern/src/features/alerts/helpers.ts
index add10fc845..42178c8b03 100644
--- a/frontend-modern/src/features/alerts/helpers.ts
+++ b/frontend-modern/src/features/alerts/helpers.ts
@@ -86,6 +86,7 @@ export const createDefaultAppriseConfig = (): UIAppriseConfig => ({
apiKeyHeader: 'X-API-KEY',
skipTlsVerify: false,
hasApiKey: false,
+ minimumSeverity: 'all',
});
export const createDefaultEmailConfig = (): UIEmailConfig => ({
@@ -105,6 +106,7 @@ export const createDefaultEmailConfig = (): UIEmailConfig => ({
rateLimit: 60,
tagFilter: [],
tagFilterMode: 'all',
+ minimumSeverity: 'all',
});
export const readStringValue = (value: unknown, fallback = ''): string =>
@@ -139,6 +141,7 @@ export const normalizeEmailConfigFromAPI = (
rateLimit: readNumberValue(value?.rateLimit, defaults.rateLimit),
tagFilter: readStringArrayValue(value?.tagFilter),
tagFilterMode: value?.tagFilterMode === 'any' ? 'any' : 'all',
+ minimumSeverity: value?.minimumSeverity === 'critical' ? 'critical' : 'all',
};
};
diff --git a/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx b/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
index d9a9949221..66c0ba7c86 100644
--- a/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
+++ b/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
@@ -26,6 +26,8 @@ export interface DestinationsTabProps extends AlertDestinationsTabStateProps {
setEmailConfig: (config: ReturnType<AlertDestinationsTabStateProps['emailConfig']>) => void;
deadManPingUrl: () => string;
setDeadManPingUrl: (value: string) => void;
+ pushMinimumSeverity: () => 'all' | 'critical';
+ setPushMinimumSeverity: (value: 'all' | 'critical') => void;
}
export function DestinationsTab(props: DestinationsTabProps) {
@@ -133,6 +135,11 @@ export function DestinationsTab(props: DestinationsTabProps) {
relayLicensed={hasFeature('relay')}
showUpgradePrompts={!presentationPolicyHidesUpgradePrompts()}
upgradeDestination={getUpgradeActionDestination('relay')}
+ minimumSeverity={props.pushMinimumSeverity()}
+ onMinimumSeverityChange={(minimumSeverity) => {
+ props.setPushMinimumSeverity(minimumSeverity);
+ props.setHasUnsavedChanges(true);
+ }}
/>
<AlertDeliveryLogCard
diff --git a/frontend-modern/src/features/alerts/types.ts b/frontend-modern/src/features/alerts/types.ts
index ee5f5339b4..7068ca9f9f 100644
--- a/frontend-modern/src/features/alerts/types.ts
+++ b/frontend-modern/src/features/alerts/types.ts
@@ -155,6 +155,7 @@ export interface UIEmailConfig {
rateLimit: number;
tagFilter?: string[];
tagFilterMode?: 'all' | 'any';
+ minimumSeverity?: 'all' | 'critical';
}
export interface UIAppriseConfig {
@@ -169,6 +170,7 @@ export interface UIAppriseConfig {
apiKeyHeader: string;
skipTlsVerify: boolean;
hasApiKey: boolean;
+ minimumSeverity?: 'all' | 'critical';
}
export interface QuietHoursConfig {
diff --git a/frontend-modern/src/features/alerts/useAlertDestinationsState.ts b/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
index 2ca9da213f..1c29e0260e 100644
--- a/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
+++ b/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
@@ -3,6 +3,8 @@ import type { Accessor } from 'solid-js';
import { AlertsAPI } from '@/api/alerts';
import { NotificationsAPI } from '@/api/notifications';
+import { RelayAPI } from '@/api/relay';
+import { hasFeature } from '@/stores/license';
import { getAlertDestinationsConfigLoadError } from '@/utils/alertDestinationsPresentation';
import { logger } from '@/utils/logger';
@@ -27,6 +29,7 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
createDefaultAppriseConfig(),
);
const [deadManPingUrl, setDeadManPingUrl] = createSignal('');
+ const [pushMinimumSeverity, setPushMinimumSeverity] = createSignal<'all' | 'critical'>('all');
let reloadVersion = 0;
let lastActiveTab: AlertTab | null = null;
@@ -36,6 +39,7 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
setEmailConfig(createDefaultEmailConfig());
setAppriseConfig(createDefaultAppriseConfig());
setDeadManPingUrl('');
+ setPushMinimumSeverity('all');
};
const loadDestinations = async (options: { indicateLoading?: boolean } = {}) => {
@@ -50,13 +54,14 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
NotificationsAPI.getEmailConfig(),
NotificationsAPI.getAppriseConfig(),
AlertsAPI.getDeadManConfig(),
+ hasFeature('relay') ? RelayAPI.getConfig() : Promise.resolve(null),
]);
if (thisVersion !== reloadVersion) {
return;
}
- const [emailResult, appriseResult, deadManResult] = results;
+ const [emailResult, appriseResult, deadManResult, relayResult] = results;
if (emailResult.status === 'fulfilled') {
setEmailConfig(normalizeEmailConfigFromAPI(emailResult.value));
@@ -70,6 +75,12 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
setDeadManPingUrl(deadManResult.value.pingUrl || '');
}
+ if (relayResult.status === 'fulfilled' && relayResult.value) {
+ setPushMinimumSeverity(
+ relayResult.value.alert_minimum_severity === 'critical' ? 'critical' : 'all',
+ );
+ }
+
const failures = results.filter(
(result): result is PromiseRejectedResult => result.status === 'rejected',
);
@@ -97,6 +108,10 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
await AlertsAPI.updateDeadManConfig(deadManPingUrl());
+ if (hasFeature('relay')) {
+ await RelayAPI.updateConfig({ alert_minimum_severity: pushMinimumSeverity() });
+ }
+
setAppriseConfig(normalizeAppriseConfig(updatedApprise));
};
@@ -121,6 +136,8 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
setAppriseConfig,
deadManPingUrl,
setDeadManPingUrl,
+ pushMinimumSeverity,
+ setPushMinimumSeverity,
resetDestinations,
loadDestinations,
saveDestinations,
diff --git a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
index b51f9c0a22..04915fe32e 100644
--- a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
+++ b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
@@ -139,6 +139,8 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
setAppriseConfig: destinationsState.setAppriseConfig,
deadManPingUrl: destinationsState.deadManPingUrl,
setDeadManPingUrl: destinationsState.setDeadManPingUrl,
+ pushMinimumSeverity: destinationsState.pushMinimumSeverity,
+ setPushMinimumSeverity: destinationsState.setPushMinimumSeverity,
...configurationSnapshotState,
allGuests: overridesState.allGuests,
agentResources: overridesState.agentResources,
diff --git a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
index 2ca1b06060..62d53ed297 100644
--- a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
+++ b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
@@ -1087,6 +1087,7 @@ describe('normalizeEmailConfigFromAPI', () => {
rateLimit: 0,
tagFilter: [],
tagFilterMode: 'all',
+ minimumSeverity: 'all',
});
});
@@ -1124,6 +1125,7 @@ describe('normalizeEmailConfigFromAPI', () => {
rateLimit: 60,
tagFilter: [],
tagFilterMode: 'all',
+ minimumSeverity: 'all',
});
});
});
diff --git a/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts b/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
index 5719b0a9ac..821454cd02 100644
--- a/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
import {
+ ALERT_DESTINATION_ALL_SEVERITIES_LABEL,
+ ALERT_DESTINATION_CRITICAL_ONLY_LABEL,
+ ALERT_DESTINATION_MINIMUM_SEVERITY_HELP,
+ ALERT_DESTINATION_MINIMUM_SEVERITY_LABEL,
getAlertDestinationsDeliveryPausedActionLabel,
getAlertDestinationsDeliveryPausedDescription,
getAlertDestinationsDeliveryPausedTitle,
@@ -9,6 +13,7 @@ import {
ALERT_DESTINATIONS_PUSH_PANEL_DESCRIPTION,
ALERT_DESTINATIONS_PUSH_PANEL_TITLE,
ALERT_DESTINATIONS_PUSH_READY_MESSAGE,
+ ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP,
ALERT_DESTINATIONS_PUSH_SETUP_LINK_LABEL,
ALERT_DESTINATIONS_APPRISE_API_KEY_HEADER_HELP,
ALERT_DESTINATIONS_APPRISE_ENABLE_FOR_TEST_ERROR,
@@ -49,6 +54,7 @@ import {
getAlertDestinationsDeliveryRetryLabel,
getAlertDestinationsEmailTestFailure,
getAlertDestinationsEmailTestSuccess,
+ getAlertDestinationSeverityLabel,
getAlertDestinationsLoadErrorBanner,
getAlertDestinationsRetryLabel,
getAlertDestinationsStatusLabel,
@@ -122,6 +128,17 @@ describe('alertDestinationsPresentation', () => {
expect(getAlertDestinationsAppriseTestFailure()).toBe('Unable to send the test notification.');
});
+ it('uses one explicit severity policy vocabulary across destinations', () => {
+ expect(ALERT_DESTINATION_MINIMUM_SEVERITY_LABEL).toBe('Minimum alert severity');
+ expect(ALERT_DESTINATION_ALL_SEVERITIES_LABEL).toBe('All alerts');
+ expect(ALERT_DESTINATION_CRITICAL_ONLY_LABEL).toBe('Critical alerts only');
+ expect(getAlertDestinationSeverityLabel('all')).toBe('All alerts');
+ expect(getAlertDestinationSeverityLabel('critical')).toBe('Critical alerts only');
+ expect(ALERT_DESTINATION_MINIMUM_SEVERITY_HELP).toContain(
+ 'Recoveries follow the destination that received the original alert',
+ );
+ });
+
it('returns canonical mobile push destination copy', () => {
expect(ALERT_DESTINATIONS_PUSH_PANEL_TITLE).toBe('Mobile push notifications');
expect(ALERT_DESTINATIONS_PUSH_PANEL_DESCRIPTION).toBe(
@@ -129,6 +146,10 @@ describe('alertDestinationsPresentation', () => {
);
expect(ALERT_DESTINATIONS_PUSH_READY_MESSAGE).toContain('Pulse Mobile devices paired');
expect(ALERT_DESTINATIONS_PUSH_READY_MESSAGE).toContain('Remote Access settings');
+ expect(ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP).toContain('Push copy stays private');
+ expect(ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP).toContain(
+ 'Open Pulse Mobile for current alert state',
+ );
expect(ALERT_DESTINATIONS_PUSH_SETUP_LINK_LABEL).toBe('Open Remote Access settings');
expect(ALERT_DESTINATIONS_PUSH_GATE_TITLE).toBe('Get alerts on your phone');
expect(ALERT_DESTINATIONS_PUSH_GATE_MESSAGE).toContain('Pulse Mobile app');
diff --git a/frontend-modern/src/utils/alertDestinationsPresentation.ts b/frontend-modern/src/utils/alertDestinationsPresentation.ts
index b1427b0bcb..411f785b2b 100644
--- a/frontend-modern/src/utils/alertDestinationsPresentation.ts
+++ b/frontend-modern/src/utils/alertDestinationsPresentation.ts
@@ -7,6 +7,11 @@ export const ALERT_DESTINATIONS_RETRY_LABEL = 'Retry';
export const ALERT_DESTINATIONS_RETRYING_LABEL = 'Retrying…';
export const ALERT_DESTINATIONS_ENABLED_LABEL = 'Enabled';
export const ALERT_DESTINATIONS_DISABLED_LABEL = 'Disabled';
+export const ALERT_DESTINATION_MINIMUM_SEVERITY_LABEL = 'Minimum alert severity';
+export const ALERT_DESTINATION_MINIMUM_SEVERITY_HELP =
+ 'Choose whether this destination receives every alert or only critical incidents. Recoveries follow the destination that received the original alert.';
+export const ALERT_DESTINATION_ALL_SEVERITIES_LABEL = 'All alerts';
+export const ALERT_DESTINATION_CRITICAL_ONLY_LABEL = 'Critical alerts only';
export const ALERT_DESTINATIONS_EMAIL_PANEL_TITLE = 'Email notifications';
export const ALERT_DESTINATIONS_EMAIL_PANEL_DESCRIPTION =
'Configure SMTP delivery for alert emails.';
@@ -71,6 +76,8 @@ export const ALERT_DESTINATIONS_PUSH_PANEL_DESCRIPTION =
'Deliver alerts to your phone through the Pulse Mobile app.';
export const ALERT_DESTINATIONS_PUSH_READY_MESSAGE =
'Alerts are pushed to Pulse Mobile devices paired with this instance. Manage pairing and connectivity in Remote Access settings.';
+export const ALERT_DESTINATIONS_PUSH_MINIMUM_SEVERITY_HELP =
+ 'Choose whether phones receive warning and critical pushes or critical pushes only. Push copy stays private. Open Pulse Mobile for current alert state.';
export const ALERT_DESTINATIONS_PUSH_SETUP_LINK_LABEL = 'Open Remote Access settings';
export const ALERT_DESTINATIONS_PUSH_GATE_TITLE = 'Get alerts on your phone';
export const ALERT_DESTINATIONS_PUSH_GATE_MESSAGE =
@@ -104,6 +111,12 @@ export function getAlertDestinationsStatusLabel(enabled: boolean) {
return enabled ? ALERT_DESTINATIONS_ENABLED_LABEL : ALERT_DESTINATIONS_DISABLED_LABEL;
}
+export function getAlertDestinationSeverityLabel(minimumSeverity: 'all' | 'critical') {
+ return minimumSeverity === 'critical'
+ ? ALERT_DESTINATION_CRITICAL_ONLY_LABEL
+ : ALERT_DESTINATION_ALL_SEVERITIES_LABEL;
+}
+
export function getAlertDestinationsAppriseTestLabel(isTesting: boolean) {
return isTesting
? ALERT_DESTINATIONS_APPRISE_TESTING_LABEL
diff --git a/internal/api/alerting/external_probe_notifications.go b/internal/api/alerting/external_probe_notifications.go
index ecf3c1ecbf..2c96f53981 100644
--- a/internal/api/alerting/external_probe_notifications.go
+++ b/internal/api/alerting/external_probe_notifications.go
@@ -32,3 +32,20 @@ func ExternalProbePushNotification(
}
return relay.NewExternalProbeUnavailableNotification(alert.ID), true
}
+
+// CanonicalAlertPushNotification projects every dispatched alert into a
+// privacy-safe mobile notification. External-probe outages retain their
+// purpose-built attention signal; every other alert uses the canonical alert
+// identity and severity without exposing infrastructure details.
+func CanonicalAlertPushNotification(
+ alert *alerts.Alert,
+ hasProbeAssignments func(string) bool,
+) relay.PushNotificationPayload {
+ if notification, specialized := ExternalProbePushNotification(alert, hasProbeAssignments); specialized {
+ return notification
+ }
+ if alert == nil {
+ return relay.PushNotificationPayload{}
+ }
+ return relay.NewAlertFiredNotification(alert.ID, string(alert.Level))
+}
diff --git a/internal/api/alerting/external_probe_notifications_test.go b/internal/api/alerting/external_probe_notifications_test.go
index 8791649386..99970d2319 100644
--- a/internal/api/alerting/external_probe_notifications_test.go
+++ b/internal/api/alerting/external_probe_notifications_test.go
@@ -1,6 +1,7 @@
package alerting
import (
+ "strings"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
@@ -64,3 +65,47 @@ func TestExternalProbePushNotificationSelectsAssignedHostOffline(t *testing.T) {
t.Fatalf("ordinary host-offline alert produced external probe push %#v", got)
}
}
+
+func TestCanonicalAlertPushNotificationCoversOrdinaryAlerts(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ level alerts.AlertLevel
+ priority string
+ }{
+ {name: "warning", level: alerts.AlertLevelWarning, priority: relay.PushPriorityNormal},
+ {name: "critical", level: alerts.AlertLevelCritical, priority: relay.PushPriorityHigh},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ notification := CanonicalAlertPushNotification(&alerts.Alert{
+ ID: " alert-ordinary ",
+ Level: tc.level,
+ ResourceName: "private-cluster-node-1",
+ Message: "10.0.0.7 exceeded its threshold",
+ }, nil)
+ if notification.Type != relay.PushTypeAlertFired || notification.Priority != tc.priority {
+ t.Fatalf("notification = %#v, want ordinary alert push with priority %q", notification, tc.priority)
+ }
+ if notification.ActionType != relay.PushActionViewAlert || notification.ActionID != "alert-ordinary" {
+ t.Fatalf("notification does not route to canonical alert: %#v", notification)
+ }
+ if strings.Contains(notification.Title+notification.Body, "private-cluster") ||
+ strings.Contains(notification.Title+notification.Body, "10.0.0.7") {
+ t.Fatalf("notification leaked infrastructure detail: %#v", notification)
+ }
+ })
+ }
+}
+
+func TestCanonicalAlertPushNotificationRetainsProbeSpecificSignal(t *testing.T) {
+ notification := CanonicalAlertPushNotification(&alerts.Alert{
+ ID: "probe-alert",
+ Level: alerts.AlertLevelWarning,
+ Metadata: map[string]interface{}{
+ "incidentCode": alerts.ExternalProbeUnavailableIncidentCode,
+ "incidentSource": alerts.ExternalProbeIncidentSource,
+ },
+ }, nil)
+ if notification.Type != relay.PushTypeExternalProbeOffline {
+ t.Fatalf("notification = %#v, want specialized probe-loss signal", notification)
+ }
+}
diff --git a/internal/api/alerting/notifications.go b/internal/api/alerting/notifications.go
index 2ea15693b0..6f4188eb4b 100644
--- a/internal/api/alerting/notifications.go
+++ b/internal/api/alerting/notifications.go
@@ -195,9 +195,10 @@ func (h *NotificationHandlers) UpdateEmailConfig(w http.ResponseWriter, r *http.
// Parse strict subset to check for presence of fields
var presenceCheck struct {
- RateLimit *int `json:"rateLimit"`
- TagFilter *[]string `json:"tagFilter"`
- TagMode *string `json:"tagFilterMode"`
+ RateLimit *int `json:"rateLimit"`
+ TagFilter *[]string `json:"tagFilter"`
+ TagMode *string `json:"tagFilterMode"`
+ MinimumSeverity *string `json:"minimumSeverity"`
}
if err := json.Unmarshal(body, &presenceCheck); err != nil {
// Non-fatal, just means we can't do presence check
@@ -227,6 +228,9 @@ func (h *NotificationHandlers) UpdateEmailConfig(w http.ResponseWriter, r *http.
if presenceCheck.TagMode == nil {
config.TagMode = existingConfig.TagMode
}
+ if presenceCheck.MinimumSeverity == nil {
+ config.MinimumSeverity = existingConfig.MinimumSeverity
+ }
log.Info().
Bool("enabled", config.Enabled).
@@ -289,13 +293,20 @@ func (h *NotificationHandlers) UpdateAppriseConfig(w http.ResponseWriter, r *htt
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ var presenceCheck struct {
+ MinimumSeverity *string `json:"minimumSeverity"`
+ }
+ _ = json.Unmarshal(body, &presenceCheck)
+ existingConfig := h.getMonitor(r.Context()).GetNotificationManager().GetAppriseConfig()
// An empty API key means "keep the saved key": responses never include the
// stored value, so the settings form cannot round-trip it.
if config.APIKey == "" {
- existingConfig := h.getMonitor(r.Context()).GetNotificationManager().GetAppriseConfig()
config.APIKey = existingConfig.APIKey
}
+ if presenceCheck.MinimumSeverity == nil {
+ config.MinimumSeverity = existingConfig.MinimumSeverity
+ }
log.Info().
Bool("enabled", config.Enabled).
@@ -372,6 +383,7 @@ func (h *NotificationHandlers) GetWebhooks(w http.ResponseWriter, r *http.Reques
whMap["tagFilter"] = append([]string(nil), webhook.TagFilter...)
whMap["tagFilterMode"] = webhook.TagMode
}
+ whMap["minimumSeverity"] = webhook.MinimumSeverity
// Signal that a signing secret is configured without revealing it
if webhook.SigningSecret != "" {
@@ -433,6 +445,7 @@ func (h *NotificationHandlers) CreateWebhook(w http.ResponseWriter, r *http.Requ
responseData["customFields"] = webhook.CustomFields
responseData["tagFilter"] = webhook.TagFilter
responseData["tagFilterMode"] = webhook.TagMode
+ responseData["minimumSeverity"] = webhook.MinimumSeverity
if err := utils.WriteJSONResponse(w, responseData); err != nil {
log.Error().Err(err).Msg("Failed to write webhook creation response")
@@ -467,8 +480,9 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
return
}
var routingPresence struct {
- TagFilter *[]string `json:"tagFilter"`
- TagMode *string `json:"tagFilterMode"`
+ TagFilter *[]string `json:"tagFilter"`
+ TagMode *string `json:"tagFilterMode"`
+ MinimumSeverity *string `json:"minimumSeverity"`
}
_ = json.Unmarshal(bodyBytes, &routingPresence)
webhook = notifications.NormalizeWebhookConfig(webhook)
@@ -484,6 +498,9 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
if routingPresence.TagMode == nil {
webhook.TagMode = existing.TagMode
}
+ if routingPresence.MinimumSeverity == nil {
+ webhook.MinimumSeverity = existing.MinimumSeverity
+ }
// Preserve headers if incoming contains redacted values
if len(webhook.Headers) > 0 && len(existing.Headers) > 0 {
hasRedacted := false
@@ -546,6 +563,7 @@ func (h *NotificationHandlers) UpdateWebhook(w http.ResponseWriter, r *http.Requ
responseData["customFields"] = webhook.CustomFields
responseData["tagFilter"] = webhook.TagFilter
responseData["tagFilterMode"] = webhook.TagMode
+ responseData["minimumSeverity"] = webhook.MinimumSeverity
if err := utils.WriteJSONResponse(w, responseData); err != nil {
log.Error().Err(err).Str("webhookID", webhookID).Msg("Failed to write webhook update response")
diff --git a/internal/api/alerting/notifications_test.go b/internal/api/alerting/notifications_test.go
index 4fd5cd7349..84de96a0df 100644
--- a/internal/api/alerting/notifications_test.go
+++ b/internal/api/alerting/notifications_test.go
@@ -351,21 +351,22 @@ func TestNotificationHandlers(t *testing.T) {
t.Run("UpdateEmailConfig_PreservesOmittedTagRouting", func(t *testing.T) {
existing := notifications.EmailConfig{
- TagFilter: []string{"customer:alpha", "critical"},
- TagMode: "any",
+ TagFilter: []string{"customer:alpha", "critical"},
+ TagMode: "any",
+ MinimumSeverity: "critical",
}
mockManager.On("GetEmailConfig").Return(existing).Once()
mockManager.On("SetEmailConfig", mock.MatchedBy(func(cfg notifications.EmailConfig) bool {
return assert.ObjectsAreEqual(
[]string{"customer:alpha", "critical"},
cfg.TagFilter,
- ) && cfg.TagMode == "any"
+ ) && cfg.TagMode == "any" && cfg.MinimumSeverity == "critical"
})).Return().Once()
mockPersistence.On("SaveEmailConfig", mock.MatchedBy(func(cfg notifications.EmailConfig) bool {
return assert.ObjectsAreEqual(
[]string{"customer:alpha", "critical"},
cfg.TagFilter,
- ) && cfg.TagMode == "any"
+ ) && cfg.TagMode == "any" && cfg.MinimumSeverity == "critical"
})).Return(nil).Once()
req := httptest.NewRequest(
@@ -426,13 +427,14 @@ func TestNotificationHandlers(t *testing.T) {
t.Run("GetWebhooks", func(t *testing.T) {
webhooks := []notifications.WebhookConfig{
{
- ID: "wh1",
- Name: "Test Webhook",
- URL: "https://example.com",
- Headers: map[string]string{"Authorization": "Bearer token"},
- Mention: "@everyone",
- TagFilter: []string{"customer:alpha", "critical"},
- TagMode: "any",
+ ID: "wh1",
+ Name: "Test Webhook",
+ URL: "https://example.com",
+ Headers: map[string]string{"Authorization": "Bearer token"},
+ Mention: "@everyone",
+ TagFilter: []string{"customer:alpha", "critical"},
+ TagMode: "any",
+ MinimumSeverity: "critical",
},
}
mockManager.On("GetWebhooks").Return(webhooks).Once()
@@ -449,6 +451,7 @@ func TestNotificationHandlers(t *testing.T) {
assert.Equal(t, "@everyone", resp[0]["mention"])
assert.Equal(t, []interface{}{"customer:alpha", "critical"}, resp[0]["tagFilter"])
assert.Equal(t, "any", resp[0]["tagFilterMode"])
+ assert.Equal(t, "critical", resp[0]["minimumSeverity"])
headers := resp[0]["headers"].(map[string]interface{})
assert.Equal(t, "***REDACTED***", headers["Authorization"])
})
@@ -540,13 +543,13 @@ func TestNotificationHandlers(t *testing.T) {
})
t.Run("UpdateAppriseConfig_PreservesSavedAPIKeyWhenBlank", func(t *testing.T) {
- existing := notifications.AppriseConfig{Enabled: true, APIKey: "saved-key"}
+ existing := notifications.AppriseConfig{Enabled: true, APIKey: "saved-key", MinimumSeverity: "critical"}
mockManager.On("GetAppriseConfig").Return(existing).Twice() // preserve lookup + response echo
mockManager.On("SetAppriseConfig", mock.MatchedBy(func(cfg notifications.AppriseConfig) bool {
- return cfg.APIKey == "saved-key"
+ return cfg.APIKey == "saved-key" && cfg.MinimumSeverity == "critical"
})).Return().Once()
mockPersistence.On("SaveAppriseConfig", mock.MatchedBy(func(cfg notifications.AppriseConfig) bool {
- return cfg.APIKey == "saved-key"
+ return cfg.APIKey == "saved-key" && cfg.MinimumSeverity == "critical"
})).Return(nil).Once()
req := httptest.NewRequest(
@@ -568,7 +571,7 @@ func TestNotificationHandlers(t *testing.T) {
mockPersistence.On("SaveAppriseConfig", mock.MatchedBy(func(cfg notifications.AppriseConfig) bool {
return cfg.APIKey == "new-key"
})).Return(nil).Once()
- mockManager.On("GetAppriseConfig").Return(notifications.AppriseConfig{Enabled: true, APIKey: "new-key"}).Once()
+ mockManager.On("GetAppriseConfig").Return(notifications.AppriseConfig{Enabled: true, APIKey: "new-key"}).Twice()
req := httptest.NewRequest(
"PUT",
@@ -600,10 +603,11 @@ func TestNotificationHandlers(t *testing.T) {
t.Run("UpdateWebhook_PreservesOmittedTagRouting", func(t *testing.T) {
existing := notifications.WebhookConfig{
- ID: "wh1",
- URL: "https://example.com/hook",
- TagFilter: []string{"customer:alpha", "critical"},
- TagMode: "any",
+ ID: "wh1",
+ URL: "https://example.com/hook",
+ TagFilter: []string{"customer:alpha", "critical"},
+ TagMode: "any",
+ MinimumSeverity: "critical",
}
mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{existing}).Once()
mockManager.On("ValidateWebhookURL", existing.URL).Return(nil).Once()
@@ -614,7 +618,7 @@ func TestNotificationHandlers(t *testing.T) {
return assert.ObjectsAreEqual(
[]string{"customer:alpha", "critical"},
cfg.TagFilter,
- ) && cfg.TagMode == "any"
+ ) && cfg.TagMode == "any" && cfg.MinimumSeverity == "critical"
}),
).Return(nil).Once()
mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{existing}).Once()
@@ -633,6 +637,7 @@ func TestNotificationHandlers(t *testing.T) {
assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &response))
assert.Equal(t, []interface{}{"customer:alpha", "critical"}, response["tagFilter"])
assert.Equal(t, "any", response["tagFilterMode"])
+ assert.Equal(t, "critical", response["minimumSeverity"])
})
t.Run("DeleteWebhook", func(t *testing.T) {
diff --git a/internal/api/alerting_compat.go b/internal/api/alerting_compat.go
index cfb4533610..3872a9c6e8 100644
--- a/internal/api/alerting_compat.go
+++ b/internal/api/alerting_compat.go
@@ -33,3 +33,10 @@ func externalProbePushNotification(
) (relay.PushNotificationPayload, bool) {
return alertingapi.ExternalProbePushNotification(alert, hasProbeAssignments)
}
+
+func canonicalAlertPushNotification(
+ alert *alerts.Alert,
+ hasProbeAssignments func(string) bool,
+) relay.PushNotificationPayload {
+ return alertingapi.CanonicalAlertPushNotification(alert, hasProbeAssignments)
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index e56ab0fe08..e375650414 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -9876,7 +9876,8 @@ func TestContract_HostedRelayConfigResponseJSONSnapshot(t *testing.T) {
"enabled":true,
"server_url":"%s",
"identity_public_key":"%s",
- "identity_fingerprint":"%s"
+ "identity_fingerprint":"%s",
+ "alert_minimum_severity":"all"
}`, relay.DefaultServerURL, cfg.IdentityPublicKey, cfg.IdentityFingerprint)
assertJSONSnapshot(t, rec.Body.Bytes(), want)
diff --git a/internal/api/relay_hosted_runtime_test.go b/internal/api/relay_hosted_runtime_test.go
index 17c6bae84b..67ef8061bf 100644
--- a/internal/api/relay_hosted_runtime_test.go
+++ b/internal/api/relay_hosted_runtime_test.go
@@ -4,8 +4,10 @@ import (
"context"
"crypto/ed25519"
"encoding/base64"
+ "net/http"
"net/http/httptest"
"net/url"
+ "strings"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -167,6 +169,35 @@ func TestLoadRelayConfigForRuntime_DoesNotOverrideExplicitDisabledRelayConfig(t
}
}
+func TestUpdateRelayConfigPersistsAndCachesAlertSeverityPolicy(t *testing.T) {
+ persistence := config.NewConfigPersistence(t.TempDir())
+ if err := persistence.SaveRelayConfig(*relay.DefaultConfig()); err != nil {
+ t.Fatalf("SaveRelayConfig() error = %v", err)
+ }
+ router := &Router{persistence: persistence}
+ req := httptest.NewRequest(http.MethodPut, "/api/settings/relay", strings.NewReader(`{"alert_minimum_severity":"critical"}`))
+ rec := httptest.NewRecorder()
+
+ router.handleUpdateRelayConfig(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ persisted, err := persistence.LoadRelayConfig()
+ if err != nil {
+ t.Fatalf("LoadRelayConfig() error = %v", err)
+ }
+ if persisted.AlertMinimumSeverity != relay.AlertMinimumSeverityCritical {
+ t.Fatalf("persisted alert severity = %q, want critical", persisted.AlertMinimumSeverity)
+ }
+ router.relayMu.RLock()
+ cached := router.relayAlertMinimumSeverity
+ router.relayMu.RUnlock()
+ if cached != relay.AlertMinimumSeverityCritical {
+ t.Fatalf("cached alert severity = %q, want critical", cached)
+ }
+}
+
func TestHostedRelayRuntimeBuildsMobileOnboardingAppRelayURL(t *testing.T) {
router, _, instanceHost := newHostedRelayRuntimeTestRouter(t)
diff --git a/internal/api/relay_mobile_capability_generated.go b/internal/api/relay_mobile_capability_generated.go
index 1955157759..4918bc1606 100644
--- a/internal/api/relay_mobile_capability_generated.go
+++ b/internal/api/relay_mobile_capability_generated.go
@@ -1,5 +1,5 @@
// Code generated by scripts/release_control/generate_mobile_compatibility.py. DO NOT EDIT.
-// Source SHA256: a01ae5ea3367976f07ee8110dffb99d6c878fff8377c38b3614c5c4f6536ca1c
+// Source SHA256: 388616526d453c26fb94fbec507042665580fdcbd637c8790a3905b05a1e1193
package api
diff --git a/internal/api/router.go b/internal/api/router.go
index 800ec6ae6f..833f8afb0c 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -148,30 +148,31 @@ type Router struct {
serverVersion string
projectRoot string
// Cached system settings to avoid loading from disk on every request
- settingsMu sync.RWMutex
- cachedAllowEmbedding bool
- cachedAllowedOrigins string
- publicURLMu sync.Mutex
- publicURLDetected bool
- bootstrapTokenHash string
- bootstrapTokenPath string
- checksumMu sync.RWMutex
- checksumCache map[string]checksumCacheEntry
- installScriptClient *http.Client
- relayMu sync.RWMutex
- relayClient relayRuntimeClient
- relayCancel context.CancelFunc
- lifecycleCtx context.Context
- lifecycleCancel context.CancelFunc
- lifecycleWG sync.WaitGroup
- backgroundWorkersOnce sync.Once
- hostedMode bool
- stripeWebhookHandlers *StripeWebhookHandlers
- patrolLifecycleMu sync.Mutex
- startedPatrolOrgs map[string]bool
- actionRecoveryMu sync.Mutex
- aiAutoFixEndpoints extensions.AIAutoFixEndpoints
- aiAlertAnalysisEndpoints extensions.AIAlertAnalysisEndpoints
+ settingsMu sync.RWMutex
+ cachedAllowEmbedding bool
+ cachedAllowedOrigins string
+ publicURLMu sync.Mutex
+ publicURLDetected bool
+ bootstrapTokenHash string
+ bootstrapTokenPath string
+ checksumMu sync.RWMutex
+ checksumCache map[string]checksumCacheEntry
+ installScriptClient *http.Client
+ relayMu sync.RWMutex
+ relayClient relayRuntimeClient
+ relayCancel context.CancelFunc
+ relayAlertMinimumSeverity string
+ lifecycleCtx context.Context
+ lifecycleCancel context.CancelFunc
+ lifecycleWG sync.WaitGroup
+ backgroundWorkersOnce sync.Once
+ hostedMode bool
+ stripeWebhookHandlers *StripeWebhookHandlers
+ patrolLifecycleMu sync.Mutex
+ startedPatrolOrgs map[string]bool
+ actionRecoveryMu sync.Mutex
+ aiAutoFixEndpoints extensions.AIAutoFixEndpoints
+ aiAlertAnalysisEndpoints extensions.AIAlertAnalysisEndpoints
// Per-router perf state: keeps caches and singleflight groups isolated
// between tests and prevents cross-tenant cache pollution.
@@ -970,25 +971,30 @@ func (r *Router) setupRoutes() {
// If the whole instance is offline, Relay's independent disconnect
// timer supplies the complementary dark-site notification.
r.monitor.SetAlertPushCallback(func(alert *alerts.Alert) {
- notification, ok := externalProbePushNotification(
- alert,
- r.monitor.HasExternalProbeAssignments,
- )
- if !ok {
+ if alert == nil {
return
}
r.relayMu.RLock()
client := r.relayClient
+ minimumSeverity := r.relayAlertMinimumSeverity
r.relayMu.RUnlock()
if client == nil {
return
}
+ if !relay.AlertMeetsMinimumSeverity(string(alert.Level), minimumSeverity) {
+ log.Debug().Str("alertID", alert.ID).Str("level", string(alert.Level)).Msg("Alert excluded from mobile push by destination severity policy")
+ return
+ }
+ notification := canonicalAlertPushNotification(
+ alert,
+ r.monitor.HasExternalProbeAssignments,
+ )
if err := client.SendPushNotification(notification); err != nil {
log.Warn().
Err(err).
Str("alertID", notification.ActionID).
Str("type", notification.Type).
- Msg("External probe push notification send failed")
+ Msg("Alert push notification send failed")
}
})
}
@@ -3787,6 +3793,9 @@ func (r *Router) StartRelay(ctx context.Context) {
log.Error().Err(err).Msg("Failed to load relay config")
return
}
+ r.relayMu.Lock()
+ r.relayAlertMinimumSeverity = relay.NormalizeAlertMinimumSeverity(cfg.AlertMinimumSeverity)
+ r.relayMu.Unlock()
if !cfg.Enabled {
log.Debug().Msg("Relay not enabled, skipping")
return
@@ -3871,15 +3880,17 @@ func (r *Router) handleGetRelayConfig(w http.ResponseWriter, req *http.Request)
// Omit the instance secret and private key from the response
resp := struct {
- Enabled bool `json:"enabled"`
- ServerURL string `json:"server_url"`
- IdentityPublicKey string `json:"identity_public_key,omitempty"`
- IdentityFingerprint string `json:"identity_fingerprint,omitempty"`
+ Enabled bool `json:"enabled"`
+ ServerURL string `json:"server_url"`
+ IdentityPublicKey string `json:"identity_public_key,omitempty"`
+ IdentityFingerprint string `json:"identity_fingerprint,omitempty"`
+ AlertMinimumSeverity string `json:"alert_minimum_severity"`
}{
- Enabled: cfg.Enabled,
- ServerURL: cfg.ServerURL,
- IdentityPublicKey: cfg.IdentityPublicKey,
- IdentityFingerprint: cfg.IdentityFingerprint,
+ Enabled: cfg.Enabled,
+ ServerURL: cfg.ServerURL,
+ IdentityPublicKey: cfg.IdentityPublicKey,
+ IdentityFingerprint: cfg.IdentityFingerprint,
+ AlertMinimumSeverity: relay.NormalizeAlertMinimumSeverity(cfg.AlertMinimumSeverity),
}
w.Header().Set("Content-Type", "application/json")
@@ -3888,9 +3899,10 @@ func (r *Router) handleGetRelayConfig(w http.ResponseWriter, req *http.Request)
func (r *Router) handleUpdateRelayConfig(w http.ResponseWriter, req *http.Request) {
var update struct {
- Enabled *bool `json:"enabled"`
- ServerURL *string `json:"server_url"`
- InstanceSecret *string `json:"instance_secret"`
+ Enabled *bool `json:"enabled"`
+ ServerURL *string `json:"server_url"`
+ InstanceSecret *string `json:"instance_secret"`
+ AlertMinimumSeverity *string `json:"alert_minimum_severity"`
}
if err := json.NewDecoder(req.Body).Decode(&update); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
@@ -3914,6 +3926,9 @@ func (r *Router) handleUpdateRelayConfig(w http.ResponseWriter, req *http.Reques
if update.InstanceSecret != nil {
cfg.InstanceSecret = *update.InstanceSecret
}
+ if update.AlertMinimumSeverity != nil {
+ cfg.AlertMinimumSeverity = relay.NormalizeAlertMinimumSeverity(*update.AlertMinimumSeverity)
+ }
// Generate a full identity keypair on first enable, or repair a partial
// identity so the running client can sign mobile key exchanges.
@@ -3935,6 +3950,9 @@ func (r *Router) handleUpdateRelayConfig(w http.ResponseWriter, req *http.Reques
http.Error(w, "failed to save relay config", http.StatusInternalServerError)
return
}
+ r.relayMu.Lock()
+ r.relayAlertMinimumSeverity = relay.NormalizeAlertMinimumSeverity(cfg.AlertMinimumSeverity)
+ r.relayMu.Unlock()
// Restart relay client if any connection-relevant field changed.
// Also restart when identity keypair was just generated so the running
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index d5a95031da..d8a4b703ec 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -343,6 +343,7 @@ func copyWebhookConfig(webhook WebhookConfig) WebhookConfig {
func NormalizeWebhookConfig(webhook WebhookConfig) WebhookConfig {
normalized := webhook
normalized.TagFilter = normalizeNotificationTagFilter(normalized.TagFilter)
+ normalized.MinimumSeverity = normalizeNotificationMinimumSeverity(normalized.MinimumSeverity)
if len(normalized.TagFilter) == 0 {
normalized.TagMode = ""
} else {
@@ -477,6 +478,7 @@ func notificationQueueBucketsForJob(job notificationDeliveryJob, now time.Time)
// NormalizeAppriseConfig cleans and normalizes Apprise configuration values.
func NormalizeAppriseConfig(cfg AppriseConfig) AppriseConfig {
normalized := cfg
+ normalized.MinimumSeverity = normalizeNotificationMinimumSeverity(normalized.MinimumSeverity)
mode := strings.ToLower(strings.TrimSpace(string(normalized.Mode)))
switch mode {
@@ -563,35 +565,37 @@ type Alert interface {
// EmailConfig holds email notification settings
type EmailConfig struct {
- Enabled bool `json:"enabled"`
- Provider string `json:"provider"` // Email provider name (Gmail, SendGrid, etc.)
- SMTPHost string `json:"server"` // Changed from smtpHost to server for frontend consistency
- SMTPPort int `json:"port"` // Changed from smtpPort to port for frontend consistency
- Username string `json:"username"`
- Password string `json:"password"`
- From string `json:"from"`
- To []string `json:"to"`
- TLS bool `json:"tls"`
- StartTLS bool `json:"startTLS"` // STARTTLS support
- RateLimit int `json:"rateLimit"` // Max emails per minute (0 = default 60)
- TagFilter []string `json:"tagFilter,omitempty"`
- TagMode string `json:"tagFilterMode,omitempty"` // "all" (default) or "any"
+ Enabled bool `json:"enabled"`
+ Provider string `json:"provider"` // Email provider name (Gmail, SendGrid, etc.)
+ SMTPHost string `json:"server"` // Changed from smtpHost to server for frontend consistency
+ SMTPPort int `json:"port"` // Changed from smtpPort to port for frontend consistency
+ Username string `json:"username"`
+ Password string `json:"password"`
+ From string `json:"from"`
+ To []string `json:"to"`
+ TLS bool `json:"tls"`
+ StartTLS bool `json:"startTLS"` // STARTTLS support
+ RateLimit int `json:"rateLimit"` // Max emails per minute (0 = default 60)
+ TagFilter []string `json:"tagFilter,omitempty"`
+ TagMode string `json:"tagFilterMode,omitempty"` // "all" (default) or "any"
+ MinimumSeverity string `json:"minimumSeverity,omitempty"` // "all" (default), "warning", or "critical"
}
// WebhookConfig holds webhook settings
type WebhookConfig struct {
- ID string `json:"id"`
- Name string `json:"name"`
- URL string `json:"url"`
- Method string `json:"method"`
- Headers map[string]string `json:"headers"`
- Enabled bool `json:"enabled"`
- Service string `json:"service"` // discord, slack, teams, etc.
- Template string `json:"template"` // Custom payload template
- CustomFields map[string]string `json:"customFields,omitempty"`
- Mention string `json:"mention,omitempty"` // Platform-specific mention (e.g., @everyone, @channel, <@USER_ID>)
- TagFilter []string `json:"tagFilter,omitempty"`
- TagMode string `json:"tagFilterMode,omitempty"` // "all" (default) or "any"
+ ID string `json:"id"`
+ Name string `json:"name"`
+ URL string `json:"url"`
+ Method string `json:"method"`
+ Headers map[string]string `json:"headers"`
+ Enabled bool `json:"enabled"`
+ Service string `json:"service"` // discord, slack, teams, etc.
+ Template string `json:"template"` // Custom payload template
+ CustomFields map[string]string `json:"customFields,omitempty"`
+ Mention string `json:"mention,omitempty"` // Platform-specific mention (e.g., @everyone, @channel, <@USER_ID>)
+ TagFilter []string `json:"tagFilter,omitempty"`
+ TagMode string `json:"tagFilterMode,omitempty"` // "all" (default) or "any"
+ MinimumSeverity string `json:"minimumSeverity,omitempty"` // "all" (default), "warning", or "critical"
// SigningSecret enables HMAC-SHA256 signing of outbound deliveries.
// When set, requests carry X-Pulse-Timestamp and X-Pulse-Signature
// (v1=hex(hmac_sha256(secret, timestamp + "." + body))) so receivers
@@ -614,16 +618,17 @@ const (
// AppriseConfig holds Apprise notification settings.
type AppriseConfig struct {
- Enabled bool `json:"enabled"`
- Mode AppriseMode `json:"mode,omitempty"`
- Targets []string `json:"targets"`
- CLIPath string `json:"cliPath,omitempty"`
- TimeoutSeconds int `json:"timeoutSeconds,omitempty"`
- ServerURL string `json:"serverUrl,omitempty"`
- ConfigKey string `json:"configKey,omitempty"`
- APIKey string `json:"apiKey,omitempty"`
- APIKeyHeader string `json:"apiKeyHeader,omitempty"`
- SkipTLSVerify bool `json:"skipTlsVerify,omitempty"`
+ Enabled bool `json:"enabled"`
+ Mode AppriseMode `json:"mode,omitempty"`
+ Targets []string `json:"targets"`
+ CLIPath string `json:"cliPath,omitempty"`
+ TimeoutSeconds int `json:"timeoutSeconds,omitempty"`
+ ServerURL string `json:"serverUrl,omitempty"`
+ ConfigKey string `json:"configKey,omitempty"`
+ APIKey string `json:"apiKey,omitempty"`
+ APIKeyHeader string `json:"apiKeyHeader,omitempty"`
+ SkipTLSVerify bool `json:"skipTlsVerify,omitempty"`
+ MinimumSeverity string `json:"minimumSeverity,omitempty"` // "all" (default), "warning", or "critical"
}
func normalizeEmailConfig(cfg EmailConfig) EmailConfig {
@@ -633,6 +638,7 @@ func normalizeEmailConfig(cfg EmailConfig) EmailConfig {
normalized.Username = strings.TrimSpace(normalized.Username)
normalized.From = strings.TrimSpace(normalized.From)
normalized.TagFilter = normalizeNotificationTagFilter(normalized.TagFilter)
+ normalized.MinimumSeverity = normalizeNotificationMinimumSeverity(normalized.MinimumSeverity)
if len(normalized.TagFilter) == 0 {
normalized.TagMode = ""
} else {
@@ -1557,7 +1563,7 @@ func buildNotificationDeliveryJobsForTarget(
jobs := make([]notificationDeliveryJob, 0, 2+len(webhooks))
if emailConfig.Enabled && (target == notificationDeliveryTargetAll || target == notificationDeliveryTargetEmail) {
- routedAlerts := routeNotificationAlerts(alertsToSend, emailConfig.TagFilter, emailConfig.TagMode, event)
+ routedAlerts := routeNotificationAlerts(alertsToSend, emailConfig.TagFilter, emailConfig.TagMode, emailConfig.MinimumSeverity, event)
if len(routedAlerts) > 0 {
emailCopy := emailConfig
jobs = append(jobs, notificationDeliveryJob{
@@ -1574,7 +1580,7 @@ func buildNotificationDeliveryJobsForTarget(
if !webhook.Enabled {
continue
}
- routedAlerts := routeNotificationAlerts(alertsToSend, webhook.TagFilter, webhook.TagMode, event)
+ routedAlerts := routeNotificationAlerts(alertsToSend, webhook.TagFilter, webhook.TagMode, webhook.MinimumSeverity, event)
if len(routedAlerts) > 0 {
webhookCopy := webhook
jobs = append(jobs, notificationDeliveryJob{
@@ -1588,14 +1594,17 @@ func buildNotificationDeliveryJobsForTarget(
}
}
if appriseConfig.Enabled && (target == notificationDeliveryTargetAll || target == notificationDeliveryTargetApprise) {
- appriseCopy := appriseConfig
- jobs = append(jobs, notificationDeliveryJob{
- Type: "apprise",
- Event: event,
- Alerts: alertsToSend,
- ResolvedAt: resolvedAt,
- AppriseConfig: &appriseCopy,
- })
+ routedAlerts := routeNotificationAlerts(alertsToSend, nil, "", appriseConfig.MinimumSeverity, event)
+ if len(routedAlerts) > 0 {
+ appriseCopy := appriseConfig
+ jobs = append(jobs, notificationDeliveryJob{
+ Type: "apprise",
+ Event: event,
+ Alerts: routedAlerts,
+ ResolvedAt: resolvedAt,
+ AppriseConfig: &appriseCopy,
+ })
+ }
}
return jobs
}
diff --git a/internal/notifications/tag_routing.go b/internal/notifications/tag_routing.go
index bd256b1e3b..c99a2c13ca 100644
--- a/internal/notifications/tag_routing.go
+++ b/internal/notifications/tag_routing.go
@@ -11,6 +11,23 @@ const (
notificationTagModeAny = "any"
)
+const (
+ notificationMinimumSeverityAll = "all"
+ notificationMinimumSeverityWarning = "warning"
+ notificationMinimumSeverityCritical = "critical"
+)
+
+func normalizeNotificationMinimumSeverity(raw string) string {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case notificationMinimumSeverityWarning:
+ return notificationMinimumSeverityWarning
+ case notificationMinimumSeverityCritical:
+ return notificationMinimumSeverityCritical
+ default:
+ return notificationMinimumSeverityAll
+ }
+}
+
func normalizeNotificationTagMode(raw string) string {
if strings.EqualFold(strings.TrimSpace(raw), notificationTagModeAny) {
return notificationTagModeAny
@@ -108,22 +125,43 @@ func notificationAlertMatchesTags(alert *alerts.Alert, filter []string, mode str
return true
}
+func notificationAlertMeetsMinimumSeverity(alert *alerts.Alert, minimumSeverity string) bool {
+ switch normalizeNotificationMinimumSeverity(minimumSeverity) {
+ case notificationMinimumSeverityAll:
+ return true
+ case notificationMinimumSeverityWarning:
+ return alert != nil && (alert.Level == alerts.AlertLevelWarning || alert.Level == alerts.AlertLevelCritical)
+ case notificationMinimumSeverityCritical:
+ return alert != nil && alert.Level == alerts.AlertLevelCritical
+ default:
+ return false
+ }
+}
+
func routeNotificationAlerts(
alertList []*alerts.Alert,
filter []string,
mode string,
+ minimumSeverity string,
event notificationEvent,
) []*alerts.Alert {
// Resolutions are routed by delivery receipts later in the pipeline.
- // Reapplying a mutable tag filter here could suppress the clear after tags
- // changed between firing and recovery.
- if event == eventResolved || len(normalizeNotificationTagFilter(filter)) == 0 {
+ // Reapplying mutable tag or severity policy here could suppress the clear
+ // after destination routing changed between firing and recovery.
+ if event == eventResolved {
+ return alertList
+ }
+
+ normalizedFilter := normalizeNotificationTagFilter(filter)
+ normalizedMinimumSeverity := normalizeNotificationMinimumSeverity(minimumSeverity)
+ if len(normalizedFilter) == 0 && normalizedMinimumSeverity == notificationMinimumSeverityAll {
return alertList
}
routed := make([]*alerts.Alert, 0, len(alertList))
for _, alert := range alertList {
- if notificationAlertMatchesTags(alert, filter, mode) {
+ if notificationAlertMatchesTags(alert, normalizedFilter, mode) &&
+ notificationAlertMeetsMinimumSeverity(alert, normalizedMinimumSeverity) {
routed = append(routed, alert)
}
}
diff --git a/internal/notifications/tag_routing_test.go b/internal/notifications/tag_routing_test.go
index c1420f4c2d..3f294233ea 100644
--- a/internal/notifications/tag_routing_test.go
+++ b/internal/notifications/tag_routing_test.go
@@ -86,6 +86,7 @@ func TestResolvedTagRoutingDefersToDeliveryReceipts(t *testing.T) {
[]*alerts.Alert{alert},
[]string{"customer:alpha"},
notificationTagModeAll,
+ notificationMinimumSeverityAll,
eventResolved,
)
if len(routed) != 1 {
@@ -93,6 +94,62 @@ func TestResolvedTagRoutingDefersToDeliveryReceipts(t *testing.T) {
}
}
+func TestBuildNotificationDeliveryJobsRoutesGroupedAlertsByDestinationSeverity(t *testing.T) {
+ warning := &alerts.Alert{ID: "warning", Level: alerts.AlertLevelWarning, StartTime: time.Unix(1_700_000_000, 0)}
+ critical := &alerts.Alert{ID: "critical", Level: alerts.AlertLevelCritical, StartTime: time.Unix(1_700_000_001, 0)}
+
+ jobs := buildNotificationDeliveryJobs(
+ EmailConfig{Enabled: true, MinimumSeverity: notificationMinimumSeverityCritical},
+ []WebhookConfig{
+ {ID: "all", Enabled: true, MinimumSeverity: notificationMinimumSeverityAll},
+ {ID: "critical", Enabled: true, MinimumSeverity: notificationMinimumSeverityCritical},
+ },
+ AppriseConfig{Enabled: true, Mode: AppriseModeHTTP, ServerURL: "https://apprise.example.test", MinimumSeverity: notificationMinimumSeverityCritical},
+ []*alerts.Alert{warning, critical},
+ eventAlert,
+ time.Time{},
+ )
+
+ if len(jobs) != 4 {
+ t.Fatalf("jobs = %d, want email, two webhooks, and Apprise", len(jobs))
+ }
+ want := [][]string{{"critical"}, {"warning", "critical"}, {"critical"}, {"critical"}}
+ for index, expected := range want {
+ if got := alertIDs(jobs[index].Alerts); !reflect.DeepEqual(got, expected) {
+ t.Fatalf("job %d alerts = %v, want %v", index, got, expected)
+ }
+ }
+}
+
+func TestResolvedSeverityRoutingDefersToOccurrenceReceipts(t *testing.T) {
+ warning := &alerts.Alert{ID: "warning", Level: alerts.AlertLevelWarning}
+ routed := routeNotificationAlerts(
+ []*alerts.Alert{warning},
+ nil,
+ "",
+ notificationMinimumSeverityCritical,
+ eventResolved,
+ )
+ if len(routed) != 1 {
+ t.Fatal("resolution must reach the receipt filter after minimum severity changes")
+ }
+}
+
+func TestNotificationMinimumSeverityNormalizationAndMatching(t *testing.T) {
+ if got := normalizeNotificationMinimumSeverity(" CRITICAL "); got != notificationMinimumSeverityCritical {
+ t.Fatalf("normalized severity = %q, want critical", got)
+ }
+ if got := normalizeNotificationMinimumSeverity("unexpected"); got != notificationMinimumSeverityAll {
+ t.Fatalf("unknown severity = %q, want all", got)
+ }
+ if notificationAlertMeetsMinimumSeverity(&alerts.Alert{Level: alerts.AlertLevelWarning}, notificationMinimumSeverityCritical) {
+ t.Fatal("warning alert unexpectedly met critical-only floor")
+ }
+ if !notificationAlertMeetsMinimumSeverity(&alerts.Alert{Level: alerts.AlertLevelCritical}, notificationMinimumSeverityCritical) {
+ t.Fatal("critical alert did not meet critical-only floor")
+ }
+}
+
func TestNotificationTagConfigNormalizationAndCopies(t *testing.T) {
email := normalizeEmailConfig(EmailConfig{
TagFilter: []string{" Customer:Alpha ", "customer:alpha", "", "Critical"},
@@ -104,6 +161,9 @@ func TestNotificationTagConfigNormalizationAndCopies(t *testing.T) {
if email.TagMode != notificationTagModeAll {
t.Fatalf("normalized email mode = %q, want all", email.TagMode)
}
+ if email.MinimumSeverity != notificationMinimumSeverityAll {
+ t.Fatalf("normalized email minimum severity = %q, want all", email.MinimumSeverity)
+ }
webhook := NormalizeWebhookConfig(WebhookConfig{
TagFilter: []string{" prod ", "PROD", "customer:beta"},
@@ -115,6 +175,9 @@ func TestNotificationTagConfigNormalizationAndCopies(t *testing.T) {
if webhook.TagMode != notificationTagModeAny {
t.Fatalf("normalized webhook mode = %q, want any", webhook.TagMode)
}
+ if webhook.MinimumSeverity != notificationMinimumSeverityAll {
+ t.Fatalf("normalized webhook minimum severity = %q, want all", webhook.MinimumSeverity)
+ }
if got := NormalizeWebhookConfig(WebhookConfig{TagMode: notificationTagModeAny}); got.TagMode != "" {
t.Fatalf("unfiltered webhook mode = %q, want empty for legacy compatibility", got.TagMode)
}
diff --git a/internal/relay/config.go b/internal/relay/config.go
index e785e894c7..966870ebc8 100644
--- a/internal/relay/config.go
+++ b/internal/relay/config.go
@@ -1,10 +1,18 @@
package relay
+import "strings"
+
+const (
+ AlertMinimumSeverityAll = "all"
+ AlertMinimumSeverityCritical = "critical"
+)
+
// Config holds relay client configuration.
type Config struct {
- Enabled bool `json:"enabled"`
- ServerURL string `json:"server_url"`
- InstanceSecret string `json:"instance_secret"`
+ Enabled bool `json:"enabled"`
+ ServerURL string `json:"server_url"`
+ InstanceSecret string `json:"instance_secret"`
+ AlertMinimumSeverity string `json:"alert_minimum_severity,omitempty"`
// Instance identity keypair for MITM prevention.
IdentityPrivateKey string `json:"identity_private_key,omitempty"`
@@ -18,7 +26,27 @@ const DefaultServerURL = "wss://relay.pulserelay.pro/ws/instance"
// DefaultConfig returns a Config with sensible defaults.
func DefaultConfig() *Config {
return &Config{
- Enabled: false,
- ServerURL: DefaultServerURL,
+ Enabled: false,
+ ServerURL: DefaultServerURL,
+ AlertMinimumSeverity: AlertMinimumSeverityAll,
+ }
+}
+
+// NormalizeAlertMinimumSeverity preserves global alert push delivery unless
+// the operator explicitly chooses critical-only mobile attention.
+func NormalizeAlertMinimumSeverity(raw string) string {
+ if strings.EqualFold(strings.TrimSpace(raw), AlertMinimumSeverityCritical) {
+ return AlertMinimumSeverityCritical
+ }
+ return AlertMinimumSeverityAll
+}
+
+// AlertMeetsMinimumSeverity reports whether one alert level is eligible for
+// the configured mobile push floor. Unknown levels fail closed only when the
+// operator selected critical-only delivery.
+func AlertMeetsMinimumSeverity(level, minimumSeverity string) bool {
+ if NormalizeAlertMinimumSeverity(minimumSeverity) == AlertMinimumSeverityAll {
+ return true
}
+ return strings.EqualFold(strings.TrimSpace(level), AlertMinimumSeverityCritical)
}
diff --git a/internal/relay/mobile_compatibility_generated.go b/internal/relay/mobile_compatibility_generated.go
index 8d09c1489e..25c2f0edf1 100644
--- a/internal/relay/mobile_compatibility_generated.go
+++ b/internal/relay/mobile_compatibility_generated.go
@@ -1,5 +1,5 @@
// Code generated by scripts/release_control/generate_mobile_compatibility.py. DO NOT EDIT.
-// Source SHA256: a01ae5ea3367976f07ee8110dffb99d6c878fff8377c38b3614c5c4f6536ca1c
+// Source SHA256: 388616526d453c26fb94fbec507042665580fdcbd637c8790a3905b05a1e1193
package relay
@@ -7,6 +7,7 @@ package relay
const (
PushTypePatrolFinding = "patrol_finding"
PushTypePatrolCritical = "patrol_critical"
+ PushTypeAlertFired = "alert_fired"
PushTypeExternalProbeOffline = "external_probe_offline"
PushTypeApprovalRequest = "approval_request"
PushTypeFixCompleted = "fix_completed"
diff --git a/internal/relay/push.go b/internal/relay/push.go
index 4356f9e5f8..90388e58c8 100644
--- a/internal/relay/push.go
+++ b/internal/relay/push.go
@@ -102,6 +102,35 @@ func NewExternalProbeUnavailableNotification(alertID string) PushNotificationPay
}
}
+// NewAlertFiredNotification creates a privacy-safe mobile projection of a
+// canonical alert. Infrastructure identity and message text remain inside
+// Pulse; the alert ID is enough for an authenticated mobile client to open the
+// owning incident surface and fetch current detail.
+func NewAlertFiredNotification(alertID, severity string) PushNotificationPayload {
+ severity = strings.ToLower(strings.TrimSpace(severity))
+ if severity != AlertMinimumSeverityCritical {
+ severity = "warning"
+ }
+ priority := PushPriorityNormal
+ title := "Pulse warning"
+ body := "Pulse detected a warning alert. Open Pulse for details."
+ if severity == AlertMinimumSeverityCritical {
+ priority = PushPriorityHigh
+ title = "Critical Pulse alert"
+ body = "Pulse detected a critical alert. Open Pulse for details."
+ }
+ return PushNotificationPayload{
+ Type: PushTypeAlertFired,
+ Priority: priority,
+ Title: title,
+ Body: body,
+ ActionType: PushActionViewAlert,
+ ActionID: strings.TrimSpace(alertID),
+ Category: "alert",
+ Severity: severity,
+ }
+}
+
// NewApprovalRequestNotification creates a push notification for a fix needing approval.
func NewApprovalRequestNotification(approvalID, findingTitle, riskLevel string) PushNotificationPayload {
body := "A proposed fix requires your approval"
diff --git a/internal/relay/push_test.go b/internal/relay/push_test.go
index 7141251dd2..617bfdd248 100644
--- a/internal/relay/push_test.go
+++ b/internal/relay/push_test.go
@@ -120,6 +120,49 @@ func TestNewExternalProbeUnavailableNotification(t *testing.T) {
}
}
+func TestNewAlertFiredNotification(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ severity string
+ priority string
+ title string
+ }{
+ {name: "warning", severity: "warning", priority: PushPriorityNormal, title: "Pulse warning"},
+ {name: "critical", severity: "critical", priority: PushPriorityHigh, title: "Critical Pulse alert"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ n := NewAlertFiredNotification(" alert-123 ", tc.severity)
+ if n.Type != PushTypeAlertFired || n.Priority != tc.priority || n.Title != tc.title {
+ t.Fatalf("notification posture = %#v", n)
+ }
+ if n.ActionType != PushActionViewAlert || n.ActionID != "alert-123" {
+ t.Fatalf("notification must open the canonical alert: %#v", n)
+ }
+ if n.Category != "alert" || n.Severity != tc.severity {
+ t.Fatalf("notification routing metadata = %#v", n)
+ }
+ if strings.Contains(n.Title+n.Body, "alert-123") {
+ t.Fatalf("notification exposed alert identity in lock-screen copy: %#v", n)
+ }
+ })
+ }
+}
+
+func TestAlertMinimumSeverityRouting(t *testing.T) {
+ if !AlertMeetsMinimumSeverity("warning", AlertMinimumSeverityAll) {
+ t.Fatal("all-alert policy excluded a warning")
+ }
+ if AlertMeetsMinimumSeverity("warning", AlertMinimumSeverityCritical) {
+ t.Fatal("critical-only policy included a warning")
+ }
+ if !AlertMeetsMinimumSeverity(" CRITICAL ", AlertMinimumSeverityCritical) {
+ t.Fatal("critical-only policy excluded a normalized critical alert")
+ }
+ if NormalizeAlertMinimumSeverity("unexpected") != AlertMinimumSeverityAll {
+ t.Fatal("invalid persisted policy did not fail open to backwards-compatible all-alert delivery")
+ }
+}
+
func TestNewApprovalRequestNotification(t *testing.T) {
t.Run("with risk level", func(t *testing.T) {
n := NewApprovalRequestNotification("approval-789", "Fix disk space", "high")