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.

Extract alert override projection owner

rcourtman4375b1d22107
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 2895c0491b..21b5cecb3f 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -235,12 +235,15 @@ living inline in `frontend-modern/src/pages/Alerts.tsx`. The page shell owns
navigation, activation chrome, and cross-surface routing; the configuration
surface is now a shell that composes the destinations, schedule, and thresholds
tabs. The canonical alert-policy runtime owner is now
-`frontend-modern/src/features/alerts/useAlertsConfigurationState.ts`, while
-notification destination reload and persistence now route through
-`frontend-modern/src/features/alerts/useAlertDestinationsState.ts`. Future
-config cleanup should extend the alert-policy hook or the destinations hook
-based on which subsystem actually owns the behavior instead of letting the
-broader configuration hook absorb both concerns again.
+`frontend-modern/src/features/alerts/useAlertsConfigurationState.ts` for
+config transport, defaults, and save/load orchestration,
+`frontend-modern/src/features/alerts/useAlertOverridesState.ts` for raw
+override normalization plus resource-backed override projection, and
+`frontend-modern/src/features/alerts/useAlertDestinationsState.ts` for
+notification destination reload and persistence. Future config cleanup should
+extend the config transport hook, the override-projection hook, or the
+destinations hook based on which subsystem actually owns the behavior instead
+of letting the broader configuration hook absorb all three concerns again.
Alert filter metadata and grouped header consumers must also preserve the
canonical `agent` and `node` header boundary when reusing shared filter
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 99fac03da7..25a12542d2 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -434,10 +434,12 @@ configuration orchestration. `frontend-modern/src/pages/Alerts.tsx` is the page
shell, while `frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx`
is the feature shell. The canonical runtime owner is now
`frontend-modern/src/features/alerts/useAlertsConfigurationState.ts` for alert
-policy state, while `frontend-modern/src/features/alerts/useAlertDestinationsState.ts`
-owns notification destination reload and persistence. Future cleanup should
-extend the alert-policy hook or the destinations hook based on the true owner,
-not move config control flow back into the top-level page shell.
+config transport, `frontend-modern/src/features/alerts/useAlertOverridesState.ts`
+for override projection and thresholds-facing resource selectors, and
+`frontend-modern/src/features/alerts/useAlertDestinationsState.ts` for
+notification destination reload and persistence. Future cleanup should extend
+the transport hook, override hook, or destinations hook based on the true
+owner, not move config control flow back into the top-level page shell.
The same rule now also covers cross-tab incident timelines: the shared runtime
owner is `frontend-modern/src/features/alerts/useAlertIncidentTimelineState.ts`,
while `frontend-modern/src/features/alerts/OverviewTab.tsx` and
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertOverridesState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertOverridesState.test.tsx
new file mode 100644
index 0000000000..07f46702c3
--- /dev/null
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertOverridesState.test.tsx
@@ -0,0 +1,115 @@
+import { renderHook, waitFor } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+
+import type { Resource } from '@/types/resource';
+
+import { useAlertOverridesState } from '../useAlertOverridesState';
+
+const makeResource = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: 'resource-1',
+ name: 'resource-1',
+ type: 'vm',
+ ...overrides,
+ }) as Resource;
+
+describe('useAlertOverridesState', () => {
+ it('owns raw override normalization and projected alert override read models outside config transport', async () => {
+ const [hasUnsavedChanges] = createSignal(false);
+ const [overviewOverrides, setOverviewOverrides] = createSignal([]);
+ const resources = [
+ makeResource({
+ id: 'agent-resource-1',
+ name: 'Agent 01',
+ type: 'agent',
+ platformData: {
+ agent: {
+ agentId: 'agent-1',
+ platform: 'Linux',
+ },
+ },
+ }),
+ ];
+
+ const { result } = renderHook(() =>
+ useAlertOverridesState({
+ allResources: () => resources,
+ byType: (resourceType) => resources.filter((resource) => resource.type === resourceType),
+ children: () => [],
+ hasUnsavedChanges,
+ setOverviewOverrides,
+ }),
+ );
+
+ result.replaceRawOverridesConfig({
+ 'agent:agent-1/disk:NVMe 0n1': {
+ disk: { trigger: 90, clear: 85 },
+ } as any,
+ });
+
+ await waitFor(() => expect(result.overrides()).toHaveLength(1));
+
+ expect(Object.keys(result.rawOverridesConfig())).toEqual(['agent:agent-1/disk:nvme-0n1']);
+ expect(result.overrides()[0]).toMatchObject({
+ id: 'agent:agent-1/disk:nvme-0n1',
+ type: 'agentDisk',
+ node: 'Agent 01',
+ thresholds: {
+ disk: 90,
+ },
+ });
+ expect(overviewOverrides()).toEqual(result.overrides());
+ });
+
+ it('projects guest overrides without agent resources and clears stale overrides when config is emptied', async () => {
+ const [hasUnsavedChanges] = createSignal(false);
+ const [overviewOverrides, setOverviewOverrides] = createSignal([]);
+ const resources = [
+ makeResource({
+ id: 'vm-100',
+ name: 'db-01',
+ type: 'vm',
+ platformId: 'qemu/100',
+ platformData: {
+ vmid: 100,
+ node: 'pve-1',
+ instance: 'qemu/100',
+ },
+ }),
+ ];
+
+ const { result } = renderHook(() =>
+ useAlertOverridesState({
+ allResources: () => resources,
+ byType: (resourceType) => resources.filter((resource) => resource.type === resourceType),
+ children: () => [],
+ hasUnsavedChanges,
+ setOverviewOverrides,
+ }),
+ );
+
+ result.replaceRawOverridesConfig({
+ 'vm-100': {
+ cpu: { trigger: 95, clear: 90 },
+ disabled: true,
+ } as any,
+ });
+
+ await waitFor(() => expect(result.overrides()).toHaveLength(1));
+ expect(result.overrides()[0]).toMatchObject({
+ id: 'vm-100',
+ type: 'guest',
+ resourceType: 'VM',
+ disabled: true,
+ thresholds: {
+ cpu: 95,
+ },
+ });
+
+ result.replaceRawOverridesConfig({});
+
+ await waitFor(() => expect(result.overrides()).toEqual([]));
+ expect(overviewOverrides()).toEqual([]);
+ });
+});
diff --git a/frontend-modern/src/features/alerts/useAlertOverridesState.ts b/frontend-modern/src/features/alerts/useAlertOverridesState.ts
new file mode 100644
index 0000000000..8dd30d34ed
--- /dev/null
+++ b/frontend-modern/src/features/alerts/useAlertOverridesState.ts
@@ -0,0 +1,459 @@
+import { createEffect, createMemo, createSignal, type Accessor } from 'solid-js';
+
+import type { PBSInstance, PMGInstance } from '@/types/api';
+import type { RawOverrideConfig } from '@/types/alerts';
+import type { Resource, ResourceType } from '@/types/resource';
+import { getActionableAgentIdFromResource, hasAgentFacet } from '@/utils/agentResources';
+import { isAppContainerDiscoveryResourceType } from '@/utils/discoveryTarget';
+import { pbsInstanceFromResource, pmgInstanceFromResource } from '@/utils/resourceStateAdapters';
+
+import {
+ extractTriggerValues,
+ getAlertResourceDisplayLabel,
+ guessNumericId,
+ platformData,
+} from './helpers';
+import type { Override } from './types';
+
+export interface AlertOverridesStateProps {
+ allResources: Accessor<Resource[]>;
+ byType: (resourceType: ResourceType) => Resource[];
+ children: (resourceId: string) => Resource[];
+ hasUnsavedChanges: Accessor<boolean>;
+ setOverviewOverrides: (value: Override[]) => void;
+}
+
+const asRecord = (value: unknown): Record<string, unknown> | undefined =>
+ value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;
+
+const asString = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+
+const uniqueIds = (...values: unknown[]): string[] => {
+ const ids: string[] = [];
+ const seen = new Set<string>();
+
+ values.forEach((value) => {
+ const normalized = asString(value);
+ if (!normalized || seen.has(normalized)) return;
+ seen.add(normalized);
+ ids.push(normalized);
+ });
+
+ return ids;
+};
+
+const normalizeRawOverridesConfig = (
+ rawOverrides: Record<string, RawOverrideConfig>,
+): Record<string, RawOverrideConfig> => {
+ const cleanedOverrides: Record<string, RawOverrideConfig> = {};
+
+ for (const [key, value] of Object.entries(rawOverrides)) {
+ const diskMatch = key.match(/^(agent:.+\/disk:)(.+)$/);
+ if (diskMatch) {
+ const normalized =
+ diskMatch[2]
+ .toLowerCase()
+ .replace(/[^a-z0-9]/g, '-')
+ .replace(/-{2,}/g, '-')
+ .replace(/^-|-$/g, '') || 'unknown';
+ cleanedOverrides[diskMatch[1] + normalized] = value;
+ continue;
+ }
+
+ cleanedOverrides[key] = value;
+ }
+
+ return cleanedOverrides;
+};
+
+export function useAlertOverridesState(props: AlertOverridesStateProps) {
+ const [overrides, setOverrides] = createSignal<Override[]>([]);
+ const [rawOverridesConfig, setRawOverridesConfig] = createSignal<
+ Record<string, RawOverrideConfig>
+ >({});
+
+ const pd = platformData;
+
+ const hostOverrideIdCandidates = (resource: Resource): string[] => {
+ const data = pd(resource);
+ const agent = asRecord(data?.agent);
+ return uniqueIds(
+ getActionableAgentIdFromResource(resource),
+ resource.discoveryTarget?.agentId,
+ resource.agent?.agentId,
+ agent?.agentId,
+ data?.agentId,
+ resource.id,
+ );
+ };
+
+ const dockerHostOverrideIdCandidates = (resource: Resource): string[] => {
+ const data = pd(resource);
+ const docker = asRecord(data?.docker);
+ const discoveryTarget = resource.discoveryTarget;
+ return uniqueIds(
+ isAppContainerDiscoveryResourceType(discoveryTarget?.resourceType)
+ ? discoveryTarget?.resourceId
+ : undefined,
+ docker?.hostSourceId,
+ data?.hostSourceId,
+ discoveryTarget?.agentId,
+ resource.id,
+ );
+ };
+
+ const dockerContainerOverrideIdCandidates = (host: Resource, shortId: string): string[] =>
+ uniqueIds(
+ ...dockerHostOverrideIdCandidates(host).map((hostId) => `docker:${hostId}/${shortId}`),
+ );
+
+ const allGuests = createMemo(
+ () => [
+ ...props.byType('vm'),
+ ...props.byType('system-container'),
+ ...props.byType('oci-container'),
+ ],
+ [],
+ {
+ equals: (prev, next) => {
+ if (prev.length !== next.length) return false;
+ return prev.every(
+ (current, index) => current.id === next[index].id && current.name === next[index].name,
+ );
+ },
+ },
+ );
+
+ const agentResources = createMemo(() =>
+ props.allResources().filter(
+ (resource) =>
+ (resource.type === 'agent' ||
+ resource.type === 'pbs' ||
+ resource.type === 'pmg' ||
+ resource.type === 'truenas') &&
+ hasAgentFacet(resource),
+ ),
+ );
+
+ const pbsInstances = createMemo<PBSInstance[]>(() =>
+ props
+ .allResources()
+ .filter((resource) => resource.type === 'pbs')
+ .map(pbsInstanceFromResource)
+ .filter((resource): resource is PBSInstance => Boolean(resource)),
+ );
+
+ const pbsInstanceById = createMemo(
+ () => new Map(pbsInstances().map((instance) => [instance.id, instance])),
+ );
+
+ const pmgInstances = createMemo<PMGInstance[]>(() =>
+ props
+ .allResources()
+ .filter((resource) => resource.type === 'pmg')
+ .map(pmgInstanceFromResource)
+ .filter((resource): resource is PMGInstance => Boolean(resource)),
+ );
+
+ createEffect(() => {
+ if (props.hasUnsavedChanges()) {
+ return;
+ }
+
+ const rawConfig = rawOverridesConfig();
+ if (Object.keys(rawConfig).length === 0) {
+ if (overrides().length > 0) {
+ setOverrides([]);
+ }
+ return;
+ }
+
+ const nodeResources = props.byType('agent');
+ const vmResources = props.byType('vm');
+ const containerResources = [
+ ...props.byType('system-container'),
+ ...props.byType('oci-container'),
+ ];
+ const storageResources = props
+ .allResources()
+ .filter((resource) => resource.type === 'storage' || resource.type === 'datastore');
+ const agentResourceList = agentResources();
+ const dockerHostResources = props.byType('docker-host');
+ const overridesList: Override[] = [];
+ const dockerHostMap = new Map<string, Resource>();
+ const dockerContainerMap = new Map<
+ string,
+ { host: Resource; container: Resource; containerShortId: string }
+ >();
+ const agentMap = new Map<string, Resource>();
+
+ const storageCoords = (resource: Resource): { node: string; instance: string } => {
+ const data = pd(resource);
+ if (resource.type === 'datastore') {
+ const instance =
+ (data?.pbsInstanceId as string | undefined) ||
+ resource.parentId ||
+ resource.platformId ||
+ 'pbs';
+ const node = (data?.pbsInstanceName as string | undefined) || instance;
+ return { node, instance };
+ }
+
+ return {
+ node: (data?.node as string | undefined) || '',
+ instance: (data?.instance as string | undefined) || resource.platformId || '',
+ };
+ };
+
+ dockerHostResources.forEach((host) => {
+ dockerHostOverrideIdCandidates(host).forEach((id) => {
+ dockerHostMap.set(id, host);
+ });
+
+ const containers = props
+ .children(host.id)
+ .filter((resource) => resource.type === 'app-container');
+
+ containers.forEach((container) => {
+ const shortId = container.id.includes('/') ? container.id.split('/').pop()! : container.id;
+ dockerContainerOverrideIdCandidates(host, shortId).forEach((resourceId) => {
+ dockerContainerMap.set(resourceId, { host, container, containerShortId: shortId });
+ });
+ });
+ });
+
+ agentResourceList.forEach((agentResource) => {
+ hostOverrideIdCandidates(agentResource).forEach((id) => {
+ agentMap.set(id, agentResource);
+ });
+ });
+
+ Object.entries(rawConfig).forEach(([key, thresholds]) => {
+ const dockerHost = dockerHostMap.get(key);
+ if (dockerHost) {
+ overridesList.push({
+ id: key,
+ name: getAlertResourceDisplayLabel(dockerHost),
+ type: 'dockerHost',
+ resourceType: 'Container Runtime',
+ disableConnectivity: thresholds.disableConnectivity || false,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ const dockerContainer = dockerContainerMap.get(key);
+ if (dockerContainer) {
+ const { host, container, containerShortId } = dockerContainer;
+ const containerName = getAlertResourceDisplayLabel(container, containerShortId);
+ overridesList.push({
+ id: key,
+ name: containerName,
+ type: 'dockerContainer',
+ resourceType: 'Container',
+ node: getAlertResourceDisplayLabel(host),
+ instance: getAlertResourceDisplayLabel(host),
+ disabled: thresholds.disabled || false,
+ disableConnectivity: thresholds.disableConnectivity || false,
+ poweredOffSeverity:
+ thresholds.poweredOffSeverity === 'critical'
+ ? 'critical'
+ : thresholds.poweredOffSeverity === 'warning'
+ ? 'warning'
+ : undefined,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ if (key.startsWith('docker:')) {
+ const [, rest] = key.split(':', 2);
+ const [hostId, containerId] = (rest || '').split('/', 2);
+ if (containerId) {
+ overridesList.push({
+ id: key,
+ name: containerId,
+ type: 'dockerContainer',
+ resourceType: 'Container',
+ node: hostId,
+ disabled: thresholds.disabled || false,
+ disableConnectivity: thresholds.disableConnectivity || false,
+ poweredOffSeverity:
+ thresholds.poweredOffSeverity === 'critical'
+ ? 'critical'
+ : thresholds.poweredOffSeverity === 'warning'
+ ? 'warning'
+ : undefined,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ overridesList.push({
+ id: key,
+ name: hostId || key,
+ type: 'dockerHost',
+ resourceType: 'Container Runtime',
+ disableConnectivity: thresholds.disableConnectivity || false,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ const diskMatch = key.match(/^agent:(.+)\/disk:(.+)$/);
+ if (diskMatch) {
+ const [, agentId, diskLabel] = diskMatch;
+ const agent = agentMap.get(agentId);
+ overridesList.push({
+ id: key,
+ name: diskLabel.replace(/-/g, '/'),
+ type: 'agentDisk',
+ resourceType: 'Agent Disk',
+ node: agent ? getAlertResourceDisplayLabel(agent) : agentId,
+ disabled: thresholds.disabled || false,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ const agentResource = agentMap.get(key);
+ if (agentResource) {
+ const displayName = getAlertResourceDisplayLabel(agentResource);
+ const data = pd(agentResource);
+ const agent = asRecord(data?.agent);
+ overridesList.push({
+ id: key,
+ name: displayName,
+ type: 'agent',
+ resourceType: 'Agent',
+ node: displayName,
+ instance:
+ asString(agent?.platform) ||
+ asString(agent?.osName) ||
+ asString(data?.platform) ||
+ asString(data?.osName) ||
+ '',
+ disabled: thresholds.disabled || false,
+ disableConnectivity: thresholds.disableConnectivity || false,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ if (key.startsWith('pbs-')) {
+ const pbs = pbsInstanceById().get(key);
+ if (pbs) {
+ overridesList.push({
+ id: key,
+ name: pbs.name,
+ type: 'pbs',
+ resourceType: 'PBS',
+ disableConnectivity: thresholds.disableConnectivity || false,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ }
+ return;
+ }
+
+ const node = nodeResources.find((resource) => resource.id === key);
+ if (node) {
+ overridesList.push({
+ id: key,
+ name: getAlertResourceDisplayLabel(node),
+ type: 'agent',
+ resourceType: 'Agent',
+ disableConnectivity: thresholds.disableConnectivity || false,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ const storage = storageResources.find((resource) => resource.id === key);
+ if (storage) {
+ const coords = storageCoords(storage);
+ overridesList.push({
+ id: key,
+ name: getAlertResourceDisplayLabel(storage),
+ type: 'storage',
+ resourceType: 'Storage',
+ node: coords.node,
+ instance: coords.instance,
+ disabled: thresholds.disabled || false,
+ thresholds: extractTriggerValues(thresholds),
+ });
+ return;
+ }
+
+ const guest =
+ vmResources.find((resource) => resource.id === key) ||
+ containerResources.find((resource) => resource.id === key);
+ if (!guest) {
+ return;
+ }
+
+ const data = pd(guest);
+ overridesList.push({
+ id: key,
+ name: getAlertResourceDisplayLabel(guest),
+ type: 'guest',
+ resourceType: guest.type === 'vm' ? 'VM' : 'Container',
+ vmid: (data?.vmid as number | undefined) ?? guessNumericId(guest.id),
+ node: (data?.node as string | undefined) ?? '',
+ instance: (data?.instance as string | undefined) ?? guest.platformId,
+ disabled: thresholds.disabled || false,
+ disableConnectivity: thresholds.disableConnectivity || false,
+ poweredOffSeverity:
+ thresholds.poweredOffSeverity === 'critical'
+ ? 'critical'
+ : thresholds.poweredOffSeverity === 'warning'
+ ? 'warning'
+ : undefined,
+ thresholds: extractTriggerValues(thresholds),
+ backup: thresholds.backup,
+ snapshot: thresholds.snapshot,
+ });
+ });
+
+ const currentOverrides = overrides();
+ const hasChanged =
+ overridesList.length !== currentOverrides.length ||
+ overridesList.some((newOverride) => {
+ const existing = currentOverrides.find((override) => override.id === newOverride.id);
+ if (!existing) return true;
+ return (
+ JSON.stringify(newOverride.thresholds) !== JSON.stringify(existing.thresholds) ||
+ Boolean(newOverride.disableConnectivity) !== Boolean(existing.disableConnectivity) ||
+ Boolean(newOverride.disabled) !== Boolean(existing.disabled) ||
+ (newOverride.poweredOffSeverity ?? null) !== (existing.poweredOffSeverity ?? null) ||
+ JSON.stringify(newOverride.backup ?? null) !== JSON.stringify(existing.backup ?? null) ||
+ JSON.stringify(newOverride.snapshot ?? null) !==
+ JSON.stringify(existing.snapshot ?? null)
+ );
+ });
+
+ if (hasChanged) {
+ setOverrides(overridesList);
+ }
+ });
+
+ createEffect(() => {
+ props.setOverviewOverrides(overrides());
+ });
+
+ const replaceRawOverridesConfig = (value: Record<string, RawOverrideConfig>) => {
+ setRawOverridesConfig(normalizeRawOverridesConfig(value));
+ };
+
+ return {
+ overrides,
+ setOverrides,
+ rawOverridesConfig,
+ setRawOverridesConfig,
+ replaceRawOverridesConfig,
+ allGuests,
+ agentResources,
+ pbsInstances,
+ pmgInstances,
+ };
+}
diff --git a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
index 1e609cf081..786731a35c 100644
--- a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
+++ b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
@@ -1,26 +1,18 @@
-import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';
+import { createSignal, onCleanup, onMount } from 'solid-js';
import type { Accessor } from 'solid-js';
import { AlertsAPI } from '@/api/alerts';
import { eventBus } from '@/stores/events';
import { notificationStore } from '@/stores/notifications';
-import type { Alert, PBSInstance, PMGInstance } from '@/types/api';
-import type {
- ActivationState,
- BackupAlertConfig,
- RawOverrideConfig,
- SnapshotAlertConfig,
-} from '@/types/alerts';
+import type { Alert } from '@/types/api';
+import type { ActivationState, BackupAlertConfig, SnapshotAlertConfig } from '@/types/alerts';
import type { Resource, ResourceType } from '@/types/resource';
import {
getAlertConfigDiscardedSuccess,
getAlertConfigReloadFailure,
getAlertConfigSaveSuccess,
} from '@/utils/alertConfigPresentation';
-import { getActionableAgentIdFromResource, hasAgentFacet } from '@/utils/agentResources';
-import { isAppContainerDiscoveryResourceType } from '@/utils/discoveryTarget';
import { logger } from '@/utils/logger';
-import { pbsInstanceFromResource, pmgInstanceFromResource } from '@/utils/resourceStateAdapters';
import {
clampMaxAlertsPerHour,
@@ -30,15 +22,12 @@ import {
createDefaultQuietHours,
createDefaultResolveNotifications,
DEFAULT_DELAY_SECONDS,
- extractTriggerValues,
fallbackMaxAlertsPerHour,
- getAlertResourceDisplayLabel,
getTriggerValue,
- guessNumericId,
normalizeMetricDelayMap,
- platformData,
} from './helpers';
import { useAlertDestinationsState } from './useAlertDestinationsState';
+import { useAlertOverridesState } from './useAlertOverridesState';
import type {
AlertTab,
CooldownConfig,
@@ -129,10 +118,6 @@ export const FACTORY_BACKUP_DEFAULTS: BackupAlertConfig = {
export function useAlertsConfigurationState(props: AlertsConfigurationSurfaceProps) {
const [isReloadingConfig, setIsReloadingConfig] = createSignal(false);
- const [overrides, setOverrides] = createSignal<Override[]>([]);
- const [rawOverridesConfig, setRawOverridesConfig] = createSignal<
- Record<string, RawOverrideConfig>
- >({});
const [scheduleQuietHours, setScheduleQuietHours] =
createSignal<QuietHoursConfig>(createDefaultQuietHours());
const [scheduleCooldown, setScheduleCooldown] =
@@ -222,98 +207,13 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
const [disableAllPMGOffline, setDisableAllPMGOffline] = createSignal(false);
const [disableAllDockerHostsOffline, setDisableAllDockerHostsOffline] = createSignal(false);
const destinationsState = useAlertDestinationsState({ activeTab: props.activeTab });
-
- const pd = platformData;
- const asRecord = (value: unknown): Record<string, unknown> | undefined =>
- value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;
- const asString = (value: unknown): string | undefined =>
- typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
- const uniqueIds = (...values: unknown[]): string[] => {
- const ids: string[] = [];
- const seen = new Set<string>();
- values.forEach((value) => {
- const normalized = asString(value);
- if (!normalized || seen.has(normalized)) return;
- seen.add(normalized);
- ids.push(normalized);
- });
- return ids;
- };
- const hostOverrideIdCandidates = (resource: Resource): string[] => {
- const data = pd(resource);
- const agent = asRecord(data?.agent);
- return uniqueIds(
- getActionableAgentIdFromResource(resource),
- resource.discoveryTarget?.agentId,
- resource.agent?.agentId,
- agent?.agentId,
- data?.agentId,
- resource.id,
- );
- };
- const dockerHostOverrideIdCandidates = (resource: Resource): string[] => {
- const data = pd(resource);
- const docker = asRecord(data?.docker);
- const discoveryTarget = resource.discoveryTarget;
- return uniqueIds(
- isAppContainerDiscoveryResourceType(discoveryTarget?.resourceType)
- ? discoveryTarget?.resourceId
- : undefined,
- docker?.hostSourceId,
- data?.hostSourceId,
- discoveryTarget?.agentId,
- resource.id,
- );
- };
- const dockerContainerOverrideIdCandidates = (host: Resource, shortId: string): string[] =>
- uniqueIds(
- ...dockerHostOverrideIdCandidates(host).map((hostId) => `docker:${hostId}/${shortId}`),
- );
-
- const allGuests = createMemo(
- () => [
- ...props.byType('vm'),
- ...props.byType('system-container'),
- ...props.byType('oci-container'),
- ],
- [],
- {
- equals: (prev, next) => {
- if (prev.length !== next.length) return false;
- return prev.every(
- (current, index) => current.id === next[index].id && current.name === next[index].name,
- );
- },
- },
- );
-
- const agentResources = createMemo(() =>
- props.allResources().filter(
- (resource) =>
- (resource.type === 'agent' ||
- resource.type === 'pbs' ||
- resource.type === 'pmg' ||
- resource.type === 'truenas') &&
- hasAgentFacet(resource),
- ),
- );
- const pbsInstances = createMemo<PBSInstance[]>(() =>
- props
- .allResources()
- .filter((resource) => resource.type === 'pbs')
- .map(pbsInstanceFromResource)
- .filter((resource): resource is PBSInstance => Boolean(resource)),
- );
- const pbsInstanceById = createMemo(
- () => new Map(pbsInstances().map((instance) => [instance.id, instance])),
- );
- const pmgInstances = createMemo<PMGInstance[]>(() =>
- props
- .allResources()
- .filter((resource) => resource.type === 'pmg')
- .map(pmgInstanceFromResource)
- .filter((resource): resource is PMGInstance => Boolean(resource)),
- );
+ const overridesState = useAlertOverridesState({
+ allResources: props.allResources,
+ byType: props.byType,
+ children: props.children,
+ hasUnsavedChanges: props.hasUnsavedChanges,
+ setOverviewOverrides: props.setOverviewOverrides,
+ });
const resetGuestDefaults = () => {
setGuestDefaults({ ...FACTORY_GUEST_DEFAULTS });
@@ -354,280 +254,6 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
props.setHasUnsavedChanges(true);
};
- createEffect(() => {
- if (props.hasUnsavedChanges()) {
- return;
- }
-
- const rawConfig = rawOverridesConfig();
- if (Object.keys(rawConfig).length === 0 || props.byType('agent').length === 0) {
- return;
- }
-
- const nodeResources = props.byType('agent');
- const vmResources = props.byType('vm');
- const containerResources = [
- ...props.byType('system-container'),
- ...props.byType('oci-container'),
- ];
- const storageResources = props
- .allResources()
- .filter((resource) => resource.type === 'storage' || resource.type === 'datastore');
- const agentResourceList = agentResources();
- const dockerHostResources = props.byType('docker-host');
- const overridesList: Override[] = [];
- const dockerHostMap = new Map<string, Resource>();
- const dockerContainerMap = new Map<
- string,
- { host: Resource; container: Resource; containerShortId: string }
- >();
- const agentMap = new Map<string, Resource>();
-
- const storageCoords = (resource: Resource): { node: string; instance: string } => {
- const data = pd(resource);
- if (resource.type === 'datastore') {
- const instance =
- (data?.pbsInstanceId as string | undefined) ||
- resource.parentId ||
- resource.platformId ||
- 'pbs';
- const node = (data?.pbsInstanceName as string | undefined) || instance;
- return { node, instance };
- }
- return {
- node: (data?.node as string | undefined) || '',
- instance: (data?.instance as string | undefined) || resource.platformId || '',
- };
- };
-
- dockerHostResources.forEach((host) => {
- dockerHostOverrideIdCandidates(host).forEach((id) => {
- dockerHostMap.set(id, host);
- });
- const containers = props.children(host.id).filter((resource) => resource.type === 'app-container');
- containers.forEach((container) => {
- const shortId = container.id.includes('/') ? container.id.split('/').pop()! : container.id;
- dockerContainerOverrideIdCandidates(host, shortId).forEach((resourceId) => {
- dockerContainerMap.set(resourceId, { host, container, containerShortId: shortId });
- });
- });
- });
- agentResourceList.forEach((agentResource) => {
- hostOverrideIdCandidates(agentResource).forEach((id) => {
- agentMap.set(id, agentResource);
- });
- });
-
- Object.entries(rawConfig).forEach(([key, thresholds]) => {
- const dockerHost = dockerHostMap.get(key);
- if (dockerHost) {
- overridesList.push({
- id: key,
- name: getAlertResourceDisplayLabel(dockerHost),
- type: 'dockerHost',
- resourceType: 'Container Runtime',
- disableConnectivity: thresholds.disableConnectivity || false,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- const dockerContainer = dockerContainerMap.get(key);
- if (dockerContainer) {
- const { host, container, containerShortId } = dockerContainer;
- const containerName = getAlertResourceDisplayLabel(container, containerShortId);
- overridesList.push({
- id: key,
- name: containerName,
- type: 'dockerContainer',
- resourceType: 'Container',
- node: getAlertResourceDisplayLabel(host),
- instance: getAlertResourceDisplayLabel(host),
- disabled: thresholds.disabled || false,
- disableConnectivity: thresholds.disableConnectivity || false,
- poweredOffSeverity:
- thresholds.poweredOffSeverity === 'critical'
- ? 'critical'
- : thresholds.poweredOffSeverity === 'warning'
- ? 'warning'
- : undefined,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- if (key.startsWith('docker:')) {
- const [, rest] = key.split(':', 2);
- const [hostId, containerId] = (rest || '').split('/', 2);
- if (containerId) {
- overridesList.push({
- id: key,
- name: containerId,
- type: 'dockerContainer',
- resourceType: 'Container',
- node: hostId,
- disabled: thresholds.disabled || false,
- disableConnectivity: thresholds.disableConnectivity || false,
- poweredOffSeverity:
- thresholds.poweredOffSeverity === 'critical'
- ? 'critical'
- : thresholds.poweredOffSeverity === 'warning'
- ? 'warning'
- : undefined,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- overridesList.push({
- id: key,
- name: hostId || key,
- type: 'dockerHost',
- resourceType: 'Container Runtime',
- disableConnectivity: thresholds.disableConnectivity || false,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- const diskMatch = key.match(/^agent:(.+)\/disk:(.+)$/);
- if (diskMatch) {
- const [, agentId, diskLabel] = diskMatch;
- const agent = agentMap.get(agentId);
- overridesList.push({
- id: key,
- name: diskLabel.replace(/-/g, '/'),
- type: 'agentDisk',
- resourceType: 'Agent Disk',
- node: agent ? getAlertResourceDisplayLabel(agent) : agentId,
- disabled: thresholds.disabled || false,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- const agentResource = agentMap.get(key);
- if (agentResource) {
- const displayName = getAlertResourceDisplayLabel(agentResource);
- const data = pd(agentResource);
- const agent = asRecord(data?.agent);
- overridesList.push({
- id: key,
- name: displayName,
- type: 'agent',
- resourceType: 'Agent',
- node: displayName,
- instance:
- asString(agent?.platform) ||
- asString(agent?.osName) ||
- asString(data?.platform) ||
- asString(data?.osName) ||
- '',
- disabled: thresholds.disabled || false,
- disableConnectivity: thresholds.disableConnectivity || false,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- if (key.startsWith('pbs-')) {
- const pbs = pbsInstanceById().get(key);
- if (pbs) {
- overridesList.push({
- id: key,
- name: pbs.name,
- type: 'pbs',
- resourceType: 'PBS',
- disableConnectivity: thresholds.disableConnectivity || false,
- thresholds: extractTriggerValues(thresholds),
- });
- }
- return;
- }
-
- const node = nodeResources.find((resource) => resource.id === key);
- if (node) {
- overridesList.push({
- id: key,
- name: getAlertResourceDisplayLabel(node),
- type: 'agent',
- resourceType: 'Agent',
- disableConnectivity: thresholds.disableConnectivity || false,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- const storage = storageResources.find((resource) => resource.id === key);
- if (storage) {
- const coords = storageCoords(storage);
- overridesList.push({
- id: key,
- name: getAlertResourceDisplayLabel(storage),
- type: 'storage',
- resourceType: 'Storage',
- node: coords.node,
- instance: coords.instance,
- disabled: thresholds.disabled || false,
- thresholds: extractTriggerValues(thresholds),
- });
- return;
- }
-
- const guest =
- vmResources.find((resource) => resource.id === key) ||
- containerResources.find((resource) => resource.id === key);
- if (guest) {
- const data = pd(guest);
- overridesList.push({
- id: key,
- name: getAlertResourceDisplayLabel(guest),
- type: 'guest',
- resourceType: guest.type === 'vm' ? 'VM' : 'Container',
- vmid: (data?.vmid as number | undefined) ?? guessNumericId(guest.id),
- node: (data?.node as string | undefined) ?? '',
- instance: (data?.instance as string | undefined) ?? guest.platformId,
- disabled: thresholds.disabled || false,
- disableConnectivity: thresholds.disableConnectivity || false,
- poweredOffSeverity:
- thresholds.poweredOffSeverity === 'critical'
- ? 'critical'
- : thresholds.poweredOffSeverity === 'warning'
- ? 'warning'
- : undefined,
- thresholds: extractTriggerValues(thresholds),
- backup: thresholds.backup,
- snapshot: thresholds.snapshot,
- });
- }
- });
-
- const currentOverrides = overrides();
- const hasChanged =
- overridesList.length !== currentOverrides.length ||
- overridesList.some((newOverride) => {
- const existing = currentOverrides.find((override) => override.id === newOverride.id);
- if (!existing) return true;
- return (
- JSON.stringify(newOverride.thresholds) !== JSON.stringify(existing.thresholds) ||
- Boolean(newOverride.disableConnectivity) !== Boolean(existing.disableConnectivity) ||
- Boolean(newOverride.disabled) !== Boolean(existing.disabled) ||
- (newOverride.poweredOffSeverity ?? null) !== (existing.poweredOffSeverity ?? null) ||
- JSON.stringify(newOverride.backup ?? null) !== JSON.stringify(existing.backup ?? null) ||
- JSON.stringify(newOverride.snapshot ?? null) !==
- JSON.stringify(existing.snapshot ?? null)
- );
- });
-
- if (hasChanged) {
- setOverrides(overridesList);
- }
- });
-
- createEffect(() => {
- props.setOverviewOverrides(overrides());
- });
-
const loadAlertConfiguration = async (options: { notify?: boolean } = {}) => {
setIsReloadingConfig(true);
props.setHasUnsavedChanges(false);
@@ -864,23 +490,7 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
setDisableAllPMGOffline(config.disableAllPMGOffline ?? false);
setDisableAllDockerHostsOffline(config.disableAllDockerHostsOffline ?? false);
- const rawOverrides = config.overrides || {};
- const cleanedOverrides: typeof rawOverrides = {};
- for (const [key, value] of Object.entries(rawOverrides)) {
- const diskMatch = key.match(/^(agent:.+\/disk:)(.+)$/);
- if (diskMatch) {
- const normalized =
- diskMatch[2]
- .toLowerCase()
- .replace(/[^a-z0-9]/g, '-')
- .replace(/-{2,}/g, '-')
- .replace(/^-|-$/g, '') || 'unknown';
- cleanedOverrides[diskMatch[1] + normalized] = value;
- } else {
- cleanedOverrides[key] = value;
- }
- }
- setRawOverridesConfig(cleanedOverrides);
+ overridesState.replaceRawOverridesConfig(config.overrides || {});
if (config.schedule) {
if (config.schedule.quietHours) {
@@ -1111,7 +721,7 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
.filter((value) => value.length > 0),
},
pmgDefaults: pmgThresholds(),
- overrides: rawOverridesConfig(),
+ overrides: overridesState.rawOverridesConfig(),
schedule: {
quietHours: scheduleQuietHours(),
cooldown: normalizedCooldownMinutes,
@@ -1167,10 +777,10 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
isReloadingConfig,
isLoadingDestinations: destinationsState.isLoadingDestinations,
destConfigLoadError: destinationsState.destConfigLoadError,
- overrides,
- setOverrides,
- rawOverridesConfig,
- setRawOverridesConfig,
+ overrides: overridesState.overrides,
+ setOverrides: overridesState.setOverrides,
+ rawOverridesConfig: overridesState.rawOverridesConfig,
+ setRawOverridesConfig: overridesState.setRawOverridesConfig,
emailConfig: destinationsState.emailConfig,
setEmailConfig: destinationsState.setEmailConfig,
appriseConfig: destinationsState.appriseConfig,
@@ -1253,10 +863,10 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
setDisableAllPMGOffline,
disableAllDockerHostsOffline,
setDisableAllDockerHostsOffline,
- allGuests,
- agentResources,
- pbsInstances,
- pmgInstances,
+ allGuests: overridesState.allGuests,
+ agentResources: overridesState.agentResources,
+ pbsInstances: overridesState.pbsInstances,
+ pmgInstances: overridesState.pmgInstances,
resetGuestDefaults,
resetNodeDefaults,
resetPBSDefaults,
diff --git a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
index 2ddf1fe6a0..cb047d6519 100644
--- a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
+++ b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import alertsPageSource from '@/pages/Alerts.tsx?raw';
import alertsConfigurationSurfaceSource from '@/features/alerts/AlertsConfigurationSurface.tsx?raw';
import alertsConfigurationStateSource from '@/features/alerts/useAlertsConfigurationState.ts?raw';
+import alertOverridesStateSource from '@/features/alerts/useAlertOverridesState.ts?raw';
import alertDestinationsStateSource from '@/features/alerts/useAlertDestinationsState.ts?raw';
import alertAcknowledgementStateSource from '@/features/alerts/useAlertAcknowledgementState.ts?raw';
import alertHistoryStateSource from '@/features/alerts/useAlertHistoryState.ts?raw';
@@ -193,9 +194,19 @@ describe('tab path helpers', () => {
expect(alertsConfigurationStateSource).toContain('export function useAlertsConfigurationState');
expect(alertsConfigurationStateSource).toContain('AlertsAPI.getConfig');
expect(alertsConfigurationStateSource).toContain('useAlertDestinationsState');
+ expect(alertsConfigurationStateSource).toContain('useAlertOverridesState');
expect(alertsConfigurationStateSource).not.toContain('NotificationsAPI.getEmailConfig');
expect(alertsConfigurationStateSource).not.toContain('NotificationsAPI.updateEmailConfig');
expect(alertsConfigurationStateSource).toContain("eventBus.on('org_switched'");
+ expect(alertsConfigurationStateSource).not.toContain(
+ 'const [rawOverridesConfig, setRawOverridesConfig] = createSignal',
+ );
+ expect(alertsConfigurationStateSource).not.toContain('const hostOverrideIdCandidates =');
+ expect(alertsConfigurationStateSource).not.toContain('const allGuests = createMemo');
+ expect(alertOverridesStateSource).toContain('export function useAlertOverridesState');
+ expect(alertOverridesStateSource).toContain('getActionableAgentIdFromResource');
+ expect(alertOverridesStateSource).toContain('pbsInstanceFromResource');
+ expect(alertOverridesStateSource).toContain('props.setOverviewOverrides(overrides())');
expect(alertDestinationsStateSource).toContain('export function useAlertDestinationsState');
expect(alertDestinationsStateSource).toContain('NotificationsAPI.getEmailConfig');
expect(alertDestinationsStateSource).toContain('NotificationsAPI.updateEmailConfig');
diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
index b983817d92..38a7fac82c 100644
--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
@@ -326,6 +326,7 @@ import alertWebhookPresentationSource from '@/utils/alertWebhookPresentation.ts?
import alertOverviewTabSource from '@/features/alerts/OverviewTab.tsx?raw';
import alertsConfigurationSurfaceSource from '@/features/alerts/AlertsConfigurationSurface.tsx?raw';
import alertsConfigurationStateSource from '@/features/alerts/useAlertsConfigurationState.ts?raw';
+import alertOverridesStateSource from '@/features/alerts/useAlertOverridesState.ts?raw';
import alertDestinationsStateSource from '@/features/alerts/useAlertDestinationsState.ts?raw';
import alertAcknowledgementStateSource from '@/features/alerts/useAlertAcknowledgementState.ts?raw';
import alertHistoryStateSource from '@/features/alerts/useAlertHistoryState.ts?raw';
@@ -2771,9 +2772,19 @@ describe('frontend resource type boundaries', () => {
expect(alertsConfigurationSurfaceSource).not.toContain('AlertsAPI.getConfig');
expect(alertsConfigurationStateSource).toContain('AlertsAPI.getConfig');
expect(alertsConfigurationStateSource).toContain('useAlertDestinationsState');
+ expect(alertsConfigurationStateSource).toContain('useAlertOverridesState');
expect(alertsConfigurationStateSource).not.toContain('NotificationsAPI.getEmailConfig');
expect(alertsConfigurationStateSource).not.toContain('NotificationsAPI.updateEmailConfig');
expect(alertsConfigurationStateSource).toContain("eventBus.on('org_switched'");
+ expect(alertsConfigurationStateSource).not.toContain(
+ 'const [rawOverridesConfig, setRawOverridesConfig] = createSignal',
+ );
+ expect(alertsConfigurationStateSource).not.toContain('const hostOverrideIdCandidates =');
+ expect(alertsConfigurationStateSource).not.toContain('const allGuests = createMemo');
+ expect(alertOverridesStateSource).toContain('export function useAlertOverridesState');
+ expect(alertOverridesStateSource).toContain('getActionableAgentIdFromResource');
+ expect(alertOverridesStateSource).toContain('pbsInstanceFromResource');
+ expect(alertOverridesStateSource).toContain('props.setOverviewOverrides(overrides())');
expect(alertDestinationsStateSource).toContain('getAlertDestinationsConfigLoadError');
expect(alertDestinationsStateSource).toContain('NotificationsAPI.getEmailConfig');
expect(alertDestinationsStateSource).toContain('NotificationsAPI.updateEmailConfig');