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.

Retain newer alert settings drafts until their save is acknowledged

pulse-triage[bot]8c9c137ef755
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index c242472ccb..c156fa09af 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -15,6 +15,34 @@
## Purpose
+### Existing settings saves retain the pending and newer drafts
+
+One save per loaded editor owns a click-time snapshot of the alert policy and
+all separately persisted destinations. Save and Discard are unavailable while
+it is pending; fields stay editable. Completion clears the dirty flag only
+when no newer edits occurred. If newer edits exist, the acknowledgement says
+that the submitted settings were accepted and the newer changes remain
+unsaved. Failed writes stop later calls, retain drafts and restore Save for a
+deliberate retry. The existing multi-endpoint save is not atomic: earlier
+acknowledged writes are not rolled back or described as undone.
+
+Entering the notifications tab does not reload an unsaved draft or an active
+save. Explicit Discard still reloads saved settings when no save is pending.
+Reload, organisation switch and unmount invalidate stale completions and stop
+unsent writes; they cannot cancel or undo an already-issued request. The newer
+context alone owns load results and pending flags. Apprise response masking
+replaces only the untouched submitted draft, not newer input.
+
+`alertSettingsSave.acknowledgement.test.tsx` exercises the real policy and
+destination owners with deferred/rejected API replies, coherent snapshots,
+newer edits, duplicate admission, tab navigation, retry, normal masking and
+organisation invalidation. `useAlertDestinationsState.test.tsx` bounds the
+same downstream snapshot; `alertConfigPresentation.test.ts` distinguishes
+pending, accepted and newer-unsaved messages. Browser proof mounts the real
+configuration surface at desktop and narrow widths with synthetic local
+endpoints. These are source controls, not ordinary notification delivery.
+
+
### PMG collection opt-outs are not recovery evidence
Missing node queues (including an entirely disabled collector) cannot resolve
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 666b1c1bba..8a5421a9d1 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -20,6 +20,19 @@
## Purpose
+### Existing alerts Save controls expose acknowledgement state
+
+The settings Save button renders Saving… with aria-busy while its logical
+save is pending, and both Save and Discard are disabled until completion or
+failure. Newer edits remain possible and visibly unsaved; acknowledgement is
+not a claim that those edits were saved. Shared alert-configuration copy keeps
+the existing normal-save vocabulary and supplies a separate newer-unsaved
+message. Keyboard activation, tab re-entry and 320px/390px layouts are covered
+by the parent-bound browser fixture. `alertConfigPresentation.test.ts` and
+`alertSettingsSave.acknowledgement.test.tsx` exercise the copy and state owner.
+No new primitive, route or permission is introduced.
+
+
### Existing Assistant control selectors describe planning
Settings and Chat have only Read-only and Ask first options. Legacy
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 420443ce5b..fb19cf45d9 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -15,6 +15,26 @@
## Purpose
+### Destination saves use one submitted snapshot without replacing newer input
+
+The existing email, Apprise, watchdog and entitled push writes preserve their
+payload fields, endpoint order and server-side policy. The editor captures
+them before the preceding alert-policy request yields, rather than reading
+later edits between writes. Apprise response normalisation and masking apply
+only to its untouched submitted draft in the same loaded context. Newer input
+and unsaved status survive old acknowledgements; context invalidation stops
+remaining unsent calls, without cancelling or undoing an issued request.
+Failed multi-endpoint saves can have earlier persisted writes and are not
+represented as atomic rollback or provider delivery.
+
+`useAlertDestinationsState.test.tsx` and
+`alertSettingsSave.acknowledgement.test.tsx` use deferred and rejected replies
+to prove the snapshot, draft, retry and context boundaries. The genuine browser
+fixture runs the existing surface, state owners and API adapters against local
+synthetic endpoints, not SMTP/Apprise providers. Credentials, TLS verification,
+entitlement, activation, ordinary delivery, queue and retry policy are unchanged.
+
+
### Notification redirects keep the configured receiver's origin
Webhook and HTTP Apprise firing, recovery, Test and admitted queued delivery
diff --git a/frontend-modern/browser-verification/82b551c27ed5468d.json b/frontend-modern/browser-verification/82b551c27ed5468d.json
new file mode 100644
index 0000000000..cb1b0e23a1
--- /dev/null
+++ b/frontend-modern/browser-verification/82b551c27ed5468d.json
@@ -0,0 +1,73 @@
+{
+ "version": 1,
+ "base_sha": "f7a33482bb1b6694b4e0a8c6d563543da7fae345",
+ "verified_at": "2026-10-10T08:38:47.061Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx",
+ "frontend-modern/src/features/alerts/useAlertDestinationsState.ts",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationState.ts",
+ "frontend-modern/src/utils/alertConfigPresentation.ts"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx": "e787b907b88ccee5dd2b04711601776649be4b8f16a81a61aa92cb16376c764a",
+ "frontend-modern/src/features/alerts/useAlertDestinationsState.ts": "bd1fdc838f6fbbb3e8258fdd2c8e89c616658a3f50914dff5e01de0649b31fe6",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationState.ts": "969c1b1adb24e5a9761b0ad7f017e8fe0eb28ff492856d9e661053bb9e9f33a1",
+ "frontend-modern/src/utils/alertConfigPresentation.ts": "c2483fbed1d26a0abfc4f0b0661efbc6fa5af1f236dfa9f64ea34980f3514e32"
+ },
+ "routes": [
+ "/qualification/save (local fixture for the existing /alerts/notifications and /alerts/schedule settings; not a product route)"
+ ],
+ "viewports": [
+ {
+ "name": "desktop-light",
+ "width": 1365,
+ "height": 900
+ },
+ {
+ "name": "desktop-dark",
+ "width": 1365,
+ "height": 900
+ },
+ {
+ "name": "phone-light",
+ "width": 390,
+ "height": 844
+ },
+ {
+ "name": "narrow-dark",
+ "width": 320,
+ "height": 844
+ }
+ ],
+ "states": [
+ "Production AlertsConfigurationSurface, real state owners, payload builders, API adapters and CSS against synthetic local endpoints; Playwright 1.56.1 matches the integration lock. Chromium 141.0.7390.37 and WebKit 26.0, light/dark desktop and narrow viewports.",
+ "One click-time policy/destination snapshot while the policy PUT and Apprise reply are deferred. Saving\u2026 and aria-busy remain visible; Save and Discard are disabled. Fields remain editable.",
+ "Newer SMTP/Apprise drafts and dirty status survive older acknowledgements and settings-tab navigation without a replacement GET. Failure retains the draft and restores Save for a deliberate retry.",
+ "Twelve pending/newer-draft/rejected captures inspected across all four variants. Save controls and unsaved notice fit at 320px/390px with no horizontal overflow; inherited panel descriptions still truncate at narrow widths.",
+ "The fixture does not mount the global toast layer or prove native SMTP/Apprise delivery, tenant operations, physical-phone, release or installed acceptance. The state tests cover newer-unsaved acknowledgement copy and context invalidation."
+ ],
+ "interactions": [
+ "32 assertion groups: keyboard Save; prevent duplicate click and Discard; edit during both pending requests; switch settings tabs; verify exact click-time wire fields; preserve newer inputs and dirty status.",
+ "Reject Apprise after email acknowledgement: no later watchdog write, draft retained, Save restored. Deliberate retry clears dirty status only after all writes; explicit idle Discard reloads accepted settings. Earlier accepted writes are not atomic rollback.",
+ "No Test, retained-queue Retry/Dismiss, Relay/provider/native call, unexpected API request or page error. Browser and preview server closed. Parent observations and first fixture failure remain separate."
+ ],
+ "evidence_sha256": {
+ "script": "c49265b3fb37284370876111342b902648ed326c9492bf37d50420a157b3213f",
+ "results": "ea67d8fd4a2b8d49f98987a1f54aaa1fb8a1558d71dfd27e84e746a6e985d2cb",
+ "captures": {
+ "desktop-light-pending.png": "8e60e665251b0f82963d58ce45803af5100caf8b8ccf859529835c5c9e42079c",
+ "desktop-light-newer-draft.png": "8df40368acc5ac00a944504d8606ac13f0a144ee96f2764d9e72cc64cc56873e",
+ "desktop-light-rejected.png": "75efcf88bc5d6278d28bdd13c081b3d30596216c5eb123ad8bbde880b20f08b9",
+ "desktop-dark-pending.png": "fa15f9f887268912db4f3d05576d3c31b18e4890bc412ebe64aff6a3b840e858",
+ "desktop-dark-newer-draft.png": "4878665803f9c42caafe860a76e043519a9cbaa9844205f3b47bf0bd20800cf5",
+ "desktop-dark-rejected.png": "b69f423848a6389a04ae08964409c94e08fbc7bde988b4b414424fea05956275",
+ "phone-light-pending.png": "d4a54a9151e6072f4334ecc85314cbca4d2c6e3b9c4595323f1f5fae5a872b7a",
+ "phone-light-newer-draft.png": "1f58966f3a8710c963a0abbca177f36974f0f4c4bb8d3f586cd04df128ee5adc",
+ "phone-light-rejected.png": "8f2caa325c91ed71f3cba5564700825e61aa1d10a3eba60f84ce824315cca4bc",
+ "narrow-dark-pending.png": "9b13d2baba6d5a27ee850aca20f83b0890db4b78b0e9cab123e28ce4f052f06b",
+ "narrow-dark-newer-draft.png": "c6124ae4b6249f69a08c6ebef44ff3f51a9946f7619e3495a788ad8f44fac430",
+ "narrow-dark-rejected.png": "6437e9352a8dee0bdb205108e94b5ff94402a4e29c941575aa2e82f6dbc5fac7"
+ }
+ }
+}
diff --git a/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx b/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
index a662485d11..7fef76dd2b 100644
--- a/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
+++ b/frontend-modern/src/features/alerts/AlertsConfigurationSurface.tsx
@@ -70,7 +70,13 @@ export function AlertsConfigurationSurface(props: AlertsConfigurationSurfaceProp
<div class="flex w-full gap-2 sm:w-auto">
<button
class="flex-1 px-4 py-2 text-sm text-white transition-colors sm:flex-initial bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed"
- disabled={state.isReloadingConfig() || !!state.destConfigLoadError()}
+ disabled={
+ state.isReloadingConfig() ||
+ state.isLoadingDestinations() ||
+ state.isSavingConfig() ||
+ !!state.destConfigLoadError()
+ }
+ aria-busy={state.isSavingConfig()}
onClick={async () => {
try {
await state.saveAlertConfiguration();
@@ -82,11 +88,11 @@ export function AlertsConfigurationSurface(props: AlertsConfigurationSurfaceProp
}
}}
>
- {getAlertConfigSaveChangesLabel()}
+ {getAlertConfigSaveChangesLabel(state.isSavingConfig())}
</button>
<button
class="flex-1 px-4 py-2 text-sm transition-colors border border-border rounded-md text-base-content hover:bg-surface-hover sm:flex-initial disabled:opacity-60 disabled:cursor-not-allowed"
- disabled={state.isReloadingConfig()}
+ disabled={state.isReloadingConfig() || state.isSavingConfig()}
onClick={async () => {
await state.loadAlertConfiguration({ notify: true });
}}
diff --git a/frontend-modern/src/features/alerts/__tests__/alertSettingsSave.acknowledgement.test.tsx b/frontend-modern/src/features/alerts/__tests__/alertSettingsSave.acknowledgement.test.tsx
new file mode 100644
index 0000000000..1d5cf08786
--- /dev/null
+++ b/frontend-modern/src/features/alerts/__tests__/alertSettingsSave.acknowledgement.test.tsx
@@ -0,0 +1,302 @@
+import { cleanup, renderHook, waitFor } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AlertsAPI } from '@/api/alerts';
+import { NotificationsAPI } from '@/api/notifications';
+import { eventBus } from '@/stores/events';
+import { notificationStore } from '@/stores/notifications';
+import { useAlertsConfigurationState } from '../useAlertsConfigurationState';
+import type { AlertTab } from '../types';
+
+vi.mock('@/api/alerts', () => ({
+ AlertsAPI: {
+ getConfig: vi.fn(),
+ updateConfig: vi.fn(),
+ getDeadManConfig: vi.fn(),
+ updateDeadManConfig: vi.fn(),
+ },
+}));
+vi.mock('@/api/notifications', () => ({
+ NotificationsAPI: {
+ getEmailConfig: vi.fn(),
+ updateEmailConfig: vi.fn(),
+ getAppriseConfig: vi.fn(),
+ updateAppriseConfig: vi.fn(),
+ getWebhooks: vi.fn(),
+ },
+}));
+vi.mock('@/stores/license', () => ({ hasFeature: () => false }));
+vi.mock('@/stores/notifications', () => ({
+ notificationStore: { success: vi.fn(), error: vi.fn() },
+}));
+vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn() } }));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+async function editor() {
+ const hook = renderHook(() => {
+ const [activeTab, setActiveTab] = createSignal<AlertTab>('destinations');
+ const [dirty, setDirty] = createSignal(false);
+ const state = useAlertsConfigurationState({
+ activeTab,
+ allResources: () => [],
+ byType: () => [],
+ children: () => [],
+ activeAlerts: {},
+ removeAlerts: vi.fn(),
+ setOverviewOverrides: vi.fn(),
+ hasUnsavedChanges: dirty,
+ setHasUnsavedChanges: setDirty,
+ alertsActivationState: () => 'active',
+ alertsActivationConfig: () => ({ enabled: true }),
+ });
+ return { ...state, dirty, setActiveTab };
+ });
+ await waitFor(() => {
+ expect(AlertsAPI.getConfig).toHaveBeenCalledTimes(1);
+ expect(hook.result.isReloadingConfig()).toBe(false);
+ });
+ vi.mocked(notificationStore.success).mockClear();
+ return hook;
+}
+
+function editEmail(state: Awaited<ReturnType<typeof editor>>['result'], server: string) {
+ state.setEmailConfig({ ...state.emailConfig(), server });
+ state.guardedSetHasUnsavedChanges(true);
+}
+
+describe('alert settings save acknowledgement', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(AlertsAPI.getConfig).mockResolvedValue({ overrides: {} } as never);
+ vi.mocked(AlertsAPI.updateConfig).mockResolvedValue({ success: true });
+ vi.mocked(AlertsAPI.getDeadManConfig).mockResolvedValue({ pingUrl: '', configured: false });
+ vi.mocked(AlertsAPI.updateDeadManConfig).mockResolvedValue({ success: true, configured: true });
+ vi.mocked(NotificationsAPI.getEmailConfig).mockResolvedValue({
+ enabled: true,
+ server: 'smtp.saved.example.test',
+ } as never);
+ vi.mocked(NotificationsAPI.updateEmailConfig).mockResolvedValue({ success: true });
+ vi.mocked(NotificationsAPI.getAppriseConfig).mockResolvedValue({
+ enabled: true,
+ mode: 'http',
+ serverUrl: 'https://apprise.saved.example.test',
+ apiKey: '',
+ hasApiKey: true,
+ } as never);
+ vi.mocked(NotificationsAPI.updateAppriseConfig).mockImplementation(async (config) => ({
+ ...config,
+ apiKey: '',
+ hasApiKey: true,
+ }));
+ vi.mocked(NotificationsAPI.getWebhooks).mockResolvedValue([]);
+ });
+
+ it('saves one coherent click-time snapshot, not later destination edits', async () => {
+ const { result } = await editor();
+ const pending = deferred<{ success: boolean }>();
+ vi.mocked(AlertsAPI.updateConfig).mockReturnValueOnce(pending.promise);
+ editEmail(result, 'smtp.first.example.test');
+ result.setAppriseConfig({
+ ...result.appriseConfig(),
+ serverUrl: 'https://apprise.first.example.test',
+ });
+ result.setDeadManPingUrl('https://watchdog.example.test/first');
+ const save = result.saveAlertConfiguration();
+
+ editEmail(result, 'smtp.newer.example.test');
+ result.setAppriseConfig({
+ ...result.appriseConfig(),
+ serverUrl: 'https://apprise.newer.example.test',
+ });
+ result.setDeadManPingUrl('https://watchdog.example.test/newer');
+ pending.resolve({ success: true });
+ await save;
+
+ expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledWith(
+ expect.objectContaining({ server: 'smtp.first.example.test' }),
+ );
+ expect(NotificationsAPI.updateAppriseConfig).toHaveBeenCalledWith(
+ expect.objectContaining({ serverUrl: 'https://apprise.first.example.test' }),
+ );
+ expect(AlertsAPI.updateDeadManConfig).toHaveBeenCalledWith(
+ 'https://watchdog.example.test/first',
+ );
+ expect(result.emailConfig().server).toBe('smtp.newer.example.test');
+ expect(result.appriseConfig().serverUrl).toBe('https://apprise.newer.example.test');
+ expect(result.deadManPingUrl()).toBe('https://watchdog.example.test/newer');
+ expect(result.dirty()).toBe(true);
+ });
+
+ it('keeps edits made during a destination write dirty after acknowledgement', async () => {
+ const { result } = await editor();
+ const pending = deferred<{ success: boolean }>();
+ vi.mocked(NotificationsAPI.updateEmailConfig).mockReturnValueOnce(pending.promise);
+ editEmail(result, 'smtp.first.example.test');
+ const save = result.saveAlertConfiguration();
+ await waitFor(() => expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledTimes(1));
+ editEmail(result, 'smtp.newer.example.test');
+ pending.resolve({ success: true });
+ await save;
+
+ expect(result.dirty()).toBe(true);
+ expect(result.emailConfig().server).toBe('smtp.newer.example.test');
+ expect(notificationStore.success).toHaveBeenLastCalledWith(
+ expect.stringContaining('still unsaved'),
+ );
+ await result.saveAlertConfiguration();
+ expect(NotificationsAPI.updateEmailConfig).toHaveBeenLastCalledWith(
+ expect.objectContaining({ server: 'smtp.newer.example.test' }),
+ );
+ expect(result.dirty()).toBe(false);
+ });
+
+ it('does not replace a newer Apprise draft with the older saved response', async () => {
+ const { result } = await editor();
+ const pending = deferred<Awaited<ReturnType<typeof NotificationsAPI.updateAppriseConfig>>>();
+ vi.mocked(NotificationsAPI.updateAppriseConfig).mockReturnValueOnce(pending.promise);
+ result.setAppriseConfig({ ...result.appriseConfig(), configKey: 'first' });
+ result.guardedSetHasUnsavedChanges(true);
+ const save = result.saveAlertConfiguration();
+ await waitFor(() => expect(NotificationsAPI.updateAppriseConfig).toHaveBeenCalledTimes(1));
+ result.setAppriseConfig({
+ ...result.appriseConfig(),
+ configKey: 'newer',
+ apiKey: 'synthetic-new-draft',
+ });
+ result.guardedSetHasUnsavedChanges(true);
+ pending.resolve({
+ enabled: true,
+ mode: 'http',
+ configKey: 'first',
+ apiKey: '',
+ hasApiKey: true,
+ } as never);
+ await save;
+
+ expect(result.appriseConfig().configKey).toBe('newer');
+ expect(result.appriseConfig().apiKey).toBe('synthetic-new-draft');
+ expect(result.dirty()).toBe(true);
+ });
+
+ it('admits only one save until the preceding writes complete', async () => {
+ const { result } = await editor();
+ const pending = deferred<{ success: boolean }>();
+ vi.mocked(AlertsAPI.updateConfig).mockReturnValue(pending.promise);
+ editEmail(result, 'smtp.first.example.test');
+ const first = result.saveAlertConfiguration();
+ const duplicate = result.saveAlertConfiguration();
+ pending.resolve({ success: true });
+ await Promise.all([first, duplicate]);
+
+ expect(AlertsAPI.updateConfig).toHaveBeenCalledTimes(1);
+ expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledTimes(1);
+ expect(NotificationsAPI.updateAppriseConfig).toHaveBeenCalledTimes(1);
+ expect(AlertsAPI.updateDeadManConfig).toHaveBeenCalledTimes(1);
+ });
+
+ it('retains unsaved destination drafts when switching settings tabs', async () => {
+ const { result } = await editor();
+ editEmail(result, 'smtp.draft.example.test');
+ result.setActiveTab('schedule');
+ result.setActiveTab('destinations');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(NotificationsAPI.getEmailConfig).toHaveBeenCalledTimes(1);
+ expect(result.emailConfig().server).toBe('smtp.draft.example.test');
+ expect(result.dirty()).toBe(true);
+ });
+
+ it('retains drafts on a failed write and admits a deliberate retry', async () => {
+ const { result } = await editor();
+ editEmail(result, 'smtp.retry.example.test');
+ vi.mocked(NotificationsAPI.updateAppriseConfig).mockRejectedValueOnce(
+ new Error('Synthetic save failure'),
+ );
+ await expect(result.saveAlertConfiguration()).rejects.toThrow('Synthetic save failure');
+ expect(result.dirty()).toBe(true);
+ expect(result.emailConfig().server).toBe('smtp.retry.example.test');
+ expect(notificationStore.success).not.toHaveBeenCalled();
+ expect(AlertsAPI.updateDeadManConfig).not.toHaveBeenCalled();
+
+ await result.saveAlertConfiguration();
+ expect(result.dirty()).toBe(false);
+ expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it('only reports a completed save when every requested write succeeded', async () => {
+ const { result } = await editor();
+ editEmail(result, 'smtp.accepted.example.test');
+ result.setAppriseConfig({ ...result.appriseConfig(), apiKey: 'synthetic-replacement' });
+ result.guardedSetHasUnsavedChanges(true);
+ await result.saveAlertConfiguration();
+
+ expect(result.dirty()).toBe(false);
+ expect(result.appriseConfig().apiKey).toBe('');
+ expect(result.appriseConfig().hasApiKey).toBe(true);
+ expect(notificationStore.success).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops unsent destination writes after the organisation changes', async () => {
+ const { result } = await editor();
+ const pending = deferred<{ success: boolean }>();
+ vi.mocked(AlertsAPI.updateConfig).mockReturnValueOnce(pending.promise);
+ editEmail(result, 'smtp.previous-org.example.test');
+ const save = result.saveAlertConfiguration();
+ eventBus.emit('org_switched', 'synthetic-other-org');
+ await waitFor(() => expect(AlertsAPI.getConfig).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.isReloadingConfig()).toBe(false));
+ pending.resolve({ success: true });
+ await save;
+
+ expect(NotificationsAPI.updateEmailConfig).not.toHaveBeenCalled();
+ expect(NotificationsAPI.updateAppriseConfig).not.toHaveBeenCalled();
+ expect(AlertsAPI.updateDeadManConfig).not.toHaveBeenCalled();
+ expect(notificationStore.success).not.toHaveBeenCalled();
+ expect(result.emailConfig().server).toBe('smtp.saved.example.test');
+ });
+
+ it('stops later writes when the organisation changes during the email request', async () => {
+ const { result } = await editor();
+ const pending = deferred<{ success: boolean }>();
+ vi.mocked(NotificationsAPI.updateEmailConfig).mockReturnValueOnce(pending.promise);
+ editEmail(result, 'smtp.previous-org.example.test');
+ const save = result.saveAlertConfiguration();
+ await waitFor(() => expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledTimes(1));
+ eventBus.emit('org_switched', 'synthetic-other-org');
+ await waitFor(() => expect(AlertsAPI.getConfig).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.isReloadingConfig()).toBe(false));
+ pending.resolve({ success: true });
+ await save;
+
+ expect(NotificationsAPI.updateAppriseConfig).not.toHaveBeenCalled();
+ expect(AlertsAPI.updateDeadManConfig).not.toHaveBeenCalled();
+ expect(notificationStore.success).not.toHaveBeenCalled();
+ expect(result.emailConfig().server).toBe('smtp.saved.example.test');
+ });
+
+ it('does not advance an unfinished save after the editor unmounts', async () => {
+ const { result } = await editor();
+ const pending = deferred<{ success: boolean }>();
+ vi.mocked(AlertsAPI.updateConfig).mockReturnValueOnce(pending.promise);
+ editEmail(result, 'smtp.unmounted.example.test');
+ const save = result.saveAlertConfiguration();
+ cleanup();
+ pending.resolve({ success: true });
+ await save;
+
+ expect(NotificationsAPI.updateEmailConfig).not.toHaveBeenCalled();
+ expect(notificationStore.success).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
index ad753891a4..c8fbbae78e 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
@@ -215,4 +215,49 @@ describe('useAlertDestinationsState', () => {
expect(RelayAPI.getConfig).not.toHaveBeenCalled();
expect(RelayAPI.updateConfig).not.toHaveBeenCalled();
});
+
+ it('captures downstream writes before awaiting email and retains a newer Apprise draft', async () => {
+ vi.mocked(hasFeature).mockReturnValue(false);
+ let acknowledgeEmail!: (value: { success: boolean }) => void;
+ vi.mocked(NotificationsAPI.updateEmailConfig).mockReturnValue(
+ new Promise((resolve) => {
+ acknowledgeEmail = resolve;
+ }),
+ );
+ vi.mocked(NotificationsAPI.updateAppriseConfig).mockImplementation(async (config) => ({
+ ...config,
+ apiKey: '',
+ hasApiKey: true,
+ }));
+ vi.mocked(AlertsAPI.updateDeadManConfig).mockResolvedValue({ success: true, configured: true });
+ const { result } = renderHook(() => useAlertDestinationsState({ activeTab: () => 'overview' }));
+ result.setAppriseConfig({
+ ...result.appriseConfig(),
+ serverUrl: 'https://first.example.test',
+ apiKey: 'synthetic-first',
+ });
+ result.setDeadManPingUrl('https://watchdog.example.test/first');
+ const save = result.saveDestinations();
+ result.setAppriseConfig({
+ ...result.appriseConfig(),
+ serverUrl: 'https://newer.example.test',
+ apiKey: 'synthetic-newer',
+ });
+ result.setDeadManPingUrl('https://watchdog.example.test/newer');
+ acknowledgeEmail({ success: true });
+ await save;
+
+ expect(NotificationsAPI.updateAppriseConfig).toHaveBeenCalledWith(
+ expect.objectContaining({
+ serverUrl: 'https://first.example.test',
+ apiKey: 'synthetic-first',
+ }),
+ );
+ expect(AlertsAPI.updateDeadManConfig).toHaveBeenCalledWith(
+ 'https://watchdog.example.test/first',
+ );
+ expect(result.appriseConfig().serverUrl).toBe('https://newer.example.test');
+ expect(result.appriseConfig().apiKey).toBe('synthetic-newer');
+ expect(RelayAPI.updateConfig).not.toHaveBeenCalled();
+ });
});
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx
index fdf6059f45..bddb2f1cb2 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertsConfigurationState.test.tsx
@@ -32,6 +32,7 @@ vi.mock('../useAlertDestinationsState', () => ({
appriseConfig: () => null,
setAppriseConfig: vi.fn(),
resetDestinations: vi.fn(),
+ captureDestinations: () => ({}),
loadDestinations: (...args: unknown[]) => mockLoadDestinations(...args),
saveDestinations: (...args: unknown[]) => mockSaveDestinations(...args),
}),
@@ -86,7 +87,10 @@ describe('useAlertsConfigurationState', () => {
}),
);
- await waitFor(() => expect(mockGetConfig).toHaveBeenCalledTimes(1));
+ await waitFor(() => {
+ expect(mockGetConfig).toHaveBeenCalledTimes(1);
+ expect(result.isReloadingConfig()).toBe(false);
+ });
expect(result.containerRuntimeResources).toBe(containerRuntimeResources);
expect(result.containerRuntimeResources()).toEqual([
expect.objectContaining({
@@ -124,7 +128,10 @@ describe('useAlertsConfigurationState', () => {
}),
);
- await waitFor(() => expect(mockGetConfig).toHaveBeenCalledTimes(1));
+ await waitFor(() => {
+ expect(mockGetConfig).toHaveBeenCalledTimes(1);
+ expect(result.isReloadingConfig()).toBe(false);
+ });
await result.saveAlertConfiguration();
expect(mockUpdateConfig).toHaveBeenCalledTimes(1);
diff --git a/frontend-modern/src/features/alerts/useAlertDestinationsState.ts b/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
index 442de4ef82..6a56c34302 100644
--- a/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
+++ b/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
@@ -1,4 +1,4 @@
-import { createEffect, createSignal } from 'solid-js';
+import { createEffect, createSignal, onCleanup, untrack } from 'solid-js';
import type { Accessor } from 'solid-js';
import { AlertsAPI } from '@/api/alerts';
@@ -20,6 +20,7 @@ import type { AlertTab, UIAppriseConfig, UIEmailConfig } from './types';
interface AlertDestinationsStateOptions {
activeTab: Accessor<AlertTab>;
+ canReload?: Accessor<boolean>;
}
export function useAlertDestinationsState(options: AlertDestinationsStateOptions) {
@@ -36,7 +37,12 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
let reloadVersion = 0;
let lastActiveTab: AlertTab | null = null;
+ onCleanup(() => {
+ ++reloadVersion;
+ });
+
const resetDestinations = () => {
+ ++reloadVersion;
setDestConfigLoadError(null);
setEmailConfig(createDefaultEmailConfig());
setAppriseConfig(createDefaultAppriseConfig());
@@ -112,20 +118,42 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
}
};
- const saveDestinations = async () => {
- await NotificationsAPI.updateEmailConfig(buildEmailConfigPayload(emailConfig()));
+ // Capture every endpoint's payload before any write yields. The alert-policy
+ // owner uses the same snapshot even while its preceding PUT is pending.
+ const captureDestinations = () => ({
+ email: structuredClone(buildEmailConfigPayload(emailConfig())),
+ apprise: structuredClone(buildAppriseConfigPayload(appriseConfig())),
+ appriseDraft: appriseConfig(),
+ pingUrl: deadManPingUrl(),
+ pushMinimumSeverity: pushMinimumSeverity(),
+ relayEnabled: hasFeature('relay'),
+ reloadVersion,
+ });
+
+ const saveDestinations = async (snapshot = captureDestinations(), ownsSave = () => true) => {
+ if (!ownsSave()) return;
+ await NotificationsAPI.updateEmailConfig(snapshot.email);
+ if (!ownsSave()) return;
- const updatedApprise = await NotificationsAPI.updateAppriseConfig(
- buildAppriseConfigPayload(appriseConfig()),
- );
+ const updatedApprise = await NotificationsAPI.updateAppriseConfig(snapshot.apprise);
+ if (!ownsSave()) return;
- await AlertsAPI.updateDeadManConfig(deadManPingUrl());
+ await AlertsAPI.updateDeadManConfig(snapshot.pingUrl);
+ if (!ownsSave()) return;
- if (hasFeature('relay')) {
- await RelayAPI.updateConfig({ alert_minimum_severity: pushMinimumSeverity() });
+ if (snapshot.relayEnabled && hasFeature('relay')) {
+ await RelayAPI.updateConfig({ alert_minimum_severity: snapshot.pushMinimumSeverity });
}
- setAppriseConfig(normalizeAppriseConfig(updatedApprise));
+ // An acknowledgement is not a reload: it may replace the submitted draft
+ // with masked fields, but must not overwrite edits or another context.
+ if (
+ ownsSave() &&
+ reloadVersion === snapshot.reloadVersion &&
+ appriseConfig() === snapshot.appriseDraft
+ ) {
+ setAppriseConfig(normalizeAppriseConfig(updatedApprise));
+ }
};
createEffect(() => {
@@ -133,10 +161,13 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
const previous = lastActiveTab;
lastActiveTab = current;
- if (current !== 'destinations' || previous === null) {
+ if (current !== 'destinations' || previous === null || previous === current) {
return;
}
+ // Entering a tab must not replace drafts or race a pending save. Only tab
+ // changes trigger this refresh, not later changes to the admission flags.
+ if (!untrack(options.canReload ?? (() => true))) return;
void loadDestinations({ indicateLoading: true });
});
@@ -155,6 +186,7 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
setWebhooks,
resetDestinations,
loadDestinations,
+ captureDestinations,
saveDestinations,
};
}
diff --git a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
index f3bf78be64..69c9e7afa3 100644
--- a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
+++ b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
@@ -45,15 +45,22 @@ export interface AlertsConfigurationSurfaceProps {
export function useAlertsConfigurationState(props: AlertsConfigurationSurfaceProps) {
const [isReloadingConfig, setIsReloadingConfig] = createSignal(false);
+ const [isSavingConfig, setIsSavingConfig] = createSignal(false);
+ let draftRevision = 0;
+ let configurationVersion = 0;
const [suppressDirtyFlag, setSuppressDirtyFlag] = createSignal(false);
const guardedSetHasUnsavedChanges = (value: boolean) => {
if (value && suppressDirtyFlag()) return;
+ if (value) ++draftRevision;
props.setHasUnsavedChanges(value);
};
const configurationSnapshotState = useAlertsConfigurationSnapshotState({
setHasUnsavedChanges: guardedSetHasUnsavedChanges,
});
- const destinationsState = useAlertDestinationsState({ activeTab: props.activeTab });
+ const destinationsState = useAlertDestinationsState({
+ activeTab: props.activeTab,
+ canReload: () => !props.hasUnsavedChanges() && !isSavingConfig() && !isReloadingConfig(),
+ });
const overridesState = useAlertOverridesState({
allResources: props.allResources,
byType: props.byType,
@@ -63,6 +70,10 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
});
const loadAlertConfiguration = async (options: { notify?: boolean } = {}) => {
+ const thisVersion = ++configurationVersion;
+ // A context change invalidates unsent writes from the old editor. It cannot
+ // cancel or undo a request that has already reached the server.
+ setIsSavingConfig(false);
setIsReloadingConfig(true);
setSuppressDirtyFlag(true);
props.setHasUnsavedChanges(false);
@@ -73,6 +84,7 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
try {
const config = await AlertsAPI.getConfig();
+ if (thisVersion !== configurationVersion) return;
configurationSnapshotState.applyConfigurationSnapshot(
readAlertsConfigurationSnapshot(config),
);
@@ -80,22 +92,35 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
overridesState.replaceRawOverridesConfig(config.overrides || {});
await destinationsState.loadDestinations();
+ if (thisVersion !== configurationVersion) return;
if (options.notify) {
notificationStore.success(getAlertConfigDiscardedSuccess());
}
} catch (error) {
+ if (thisVersion !== configurationVersion) return;
logger.error('Failed to load alert configuration:', error);
if (options.notify) {
notificationStore.error(getAlertConfigReloadFailure());
}
} finally {
- setIsReloadingConfig(false);
- queueMicrotask(() => setSuppressDirtyFlag(false));
+ if (thisVersion === configurationVersion) {
+ setIsReloadingConfig(false);
+ queueMicrotask(() => {
+ if (thisVersion === configurationVersion) setSuppressDirtyFlag(false);
+ });
+ }
}
};
const saveAlertConfiguration = async () => {
+ if (
+ isSavingConfig() ||
+ isReloadingConfig() ||
+ destinationsState.isLoadingDestinations() ||
+ destinationsState.destConfigLoadError()
+ )
+ return;
const result = buildAlertsConfigurationPayload({
snapshot: configurationSnapshotState.captureConfigurationSnapshot(),
rawOverridesConfig: overridesState.rawOverridesConfig(),
@@ -107,11 +132,25 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
return;
}
- await AlertsAPI.updateConfig(result.alertConfig!);
+ const destinationsSnapshot = destinationsState.captureDestinations();
+ const savedRevision = draftRevision;
+ const savedVersion = configurationVersion;
+ const ownsSave = () => savedVersion === configurationVersion;
+ setIsSavingConfig(true);
+ try {
+ await AlertsAPI.updateConfig(result.alertConfig!);
+ if (!ownsSave()) return;
+ await destinationsState.saveDestinations(destinationsSnapshot, ownsSave);
+ if (!ownsSave()) return;
- await destinationsState.saveDestinations();
- props.setHasUnsavedChanges(false);
- notificationStore.success(getAlertConfigSaveSuccess());
+ const hasNewerChanges = savedRevision !== draftRevision;
+ if (!hasNewerChanges) props.setHasUnsavedChanges(false);
+ notificationStore.success(getAlertConfigSaveSuccess(hasNewerChanges));
+ } catch (error) {
+ if (ownsSave()) throw error;
+ } finally {
+ if (ownsSave()) setIsSavingConfig(false);
+ }
};
onMount(() => {
@@ -120,12 +159,14 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
void loadAlertConfiguration();
});
onCleanup(() => {
+ ++configurationVersion;
unsubscribeOrgSwitched();
});
});
return {
isReloadingConfig,
+ isSavingConfig,
guardedSetHasUnsavedChanges,
isLoadingDestinations: destinationsState.isLoadingDestinations,
destConfigLoadError: destinationsState.destConfigLoadError,
diff --git a/frontend-modern/src/utils/__tests__/alertConfigPresentation.test.ts b/frontend-modern/src/utils/__tests__/alertConfigPresentation.test.ts
index 3f4f1cd1da..e0281777f5 100644
--- a/frontend-modern/src/utils/__tests__/alertConfigPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/alertConfigPresentation.test.ts
@@ -83,6 +83,15 @@ import {
} from '@/utils/alertConfigPresentation';
describe('alertConfigPresentation', () => {
+ it('distinguishes a pending save from accepted settings with newer unsaved edits', () => {
+ expect(getAlertConfigSaveChangesLabel(true)).toBe('Saving…');
+ expect(getAlertConfigSaveChangesLabel(false)).toBe('Save Changes');
+ expect(getAlertConfigSaveSuccess(true)).toBe(
+ 'Settings from this save were accepted. Your newer changes are still unsaved.',
+ );
+ expect(getAlertConfigSaveSuccess(false)).toBe(ALERT_CONFIG_SAVE_SUCCESS);
+ });
+
it('returns canonical alert config shell vocabulary', () => {
expect(ALERT_CONFIG_UNSAVED_CHANGES).toBe('You have unsaved changes');
expect(ALERT_CONFIG_SAVE_CHANGES).toBe('Save Changes');
diff --git a/frontend-modern/src/utils/alertConfigPresentation.ts b/frontend-modern/src/utils/alertConfigPresentation.ts
index 6807638c6b..3ca38aa08d 100644
--- a/frontend-modern/src/utils/alertConfigPresentation.ts
+++ b/frontend-modern/src/utils/alertConfigPresentation.ts
@@ -2,6 +2,9 @@ import { getAllFilterOptionLabel } from '@/components/shared/filterOptionPresent
export const ALERT_CONFIG_UNSAVED_CHANGES = 'You have unsaved changes';
export const ALERT_CONFIG_SAVE_CHANGES = 'Save Changes';
+export const ALERT_CONFIG_SAVING = 'Saving…';
+export const ALERT_CONFIG_NEWER_CHANGES_UNSAVED =
+ 'Settings from this save were accepted. Your newer changes are still unsaved.';
export const ALERT_CONFIG_RESET_DEFAULTS = 'Reset to defaults';
export const ALERT_CONFIG_RESET_DEFAULTS_TITLE =
'Restore quiet hours, cooldown, grouping, delivery, and escalation settings to their defaults';
@@ -107,8 +110,8 @@ export function getAlertConfigUnsavedChangesLabel() {
return ALERT_CONFIG_UNSAVED_CHANGES;
}
-export function getAlertConfigSaveChangesLabel() {
- return ALERT_CONFIG_SAVE_CHANGES;
+export function getAlertConfigSaveChangesLabel(isSaving = false) {
+ return isSaving ? ALERT_CONFIG_SAVING : ALERT_CONFIG_SAVE_CHANGES;
}
export function getAlertConfigResetDefaultsLabel() {
@@ -195,8 +198,8 @@ export function getAlertConfigReloadFailure() {
return ALERT_CONFIG_RELOAD_FAILURE;
}
-export function getAlertConfigSaveSuccess() {
- return ALERT_CONFIG_SAVE_SUCCESS;
+export function getAlertConfigSaveSuccess(hasNewerChanges = false) {
+ return hasNewerChanges ? ALERT_CONFIG_NEWER_CHANGES_UNSAVED : ALERT_CONFIG_SAVE_SUCCESS;
}
export function getAlertConfigSaveFailure() {