Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Serialise webhook list changes behind acknowledged saves
pulse-triage[bot]d359c8433c91
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 9c4ce39f80..848557fdba 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -15,6 +15,35 @@## Purpose+### Webhook list changes share the editor's acknowledged writer++Enable/Disable, deletion, bulk changes and form saves cannot overlap in one+webhook editor. An open add/edit draft also locks list actions so a saved+row change cannot invalidate that draft's enabled state or identity. Pending+list actions expose a live status and keep the saved inventory until the+server acknowledges each change. Deletion requires `success: true` before+removing a row; a resolved but unaccepted response retains it.++Bulk Enable/Disable captures only rows whose state needs changing and sends+them sequentially. A rejected or unconfirmed write stops the remaining batch,+retains earlier acknowledged changes and gives fixed partial-change guidance.+No automatic retry or rollback occurs. Unmount withdraws remaining unsent+calls, without cancelling or undoing a request already issued. Existing masks,+routing, payloads, endpoint policy and notification delivery remain unchanged.+The retired destination-tab mutation owner cannot dispatch another call, publish+a late toast or replace shared inventory belonging to a newly loaded context.++`WebhookConfig.mutations.test.tsx` connects the real editor and destination+owner to deferred/rejected synthetic API replies for serial batches, shared+pending admission, no-op rows, partial failure, open drafts, deletion acceptance,+explicit retry and unmount. `WebhookConfig.test.tsx` retains service, payload,+form and list coverage with acknowledged bulk sequencing.+`useAlertWebhookDestinationsState.test.tsx` checks late create/update/delete+replies against replacement inventory and refuses calls from the retired owner.+Browser proof uses+the real existing section, hooks and API adapters at desktop/narrow widths,+with synthetic local endpoints; it does not establish provider delivery.+### Existing settings saves retain the pending and newer draftsOne save per loaded editor owns a click-time snapshot of the alert policy anddiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex c1c23d131d..cad7159000 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -20,6 +20,23 @@## Purpose+### Existing webhook list controls expose pending acknowledgement++The webhook section shares pending admission across form saves, list toggles,+bulk changes and deletion. Pending list writes announce a `role="status"`+message and disable competing list controls and Add. An open draft also locks+the saved-row controls; its own fields, Test and Save remain available until+that draft is submitted. A fixed `role="alert"` message explains that earlier+batch changes may already be saved when a later change is unconfirmed, rather+than presenting an atomic rollback or automatically retrying it.++The existing section, state owners and API adapters are exercised in desktop+and 390px browser fixtures with deferred/rejected synthetic replies, masked+drafts, deliberate retry and unmount. List controls retain their narrow 44px+touch targets and the section does not overflow horizontally. These checks+establish source interaction and layout, not ordinary notification delivery.+No new primitive, route, permission, destination or transport policy is added.+### Existing alerts Save controls expose acknowledgement stateThe settings Save button renders Saving… with aria-busy while its logicaldiff --git a/frontend-modern/browser-verification/00bce0704a2ebda1.json b/frontend-modern/browser-verification/00bce0704a2ebda1.jsonnew file mode 100644index 0000000000..c178144010--- /dev/null+++ b/frontend-modern/browser-verification/00bce0704a2ebda1.json@@ -0,0 +1,49 @@+{+ "version": 1,+ "result": "passed",+ "base_sha": "912f37ac6284f13a5be8a09375bd56ab6f8df3c4",+ "changed_paths": [+ "frontend-modern/src/components/Alerts/WebhookConfig.tsx",+ "frontend-modern/src/components/Alerts/useWebhookConfigState.ts",+ "frontend-modern/src/features/alerts/AlertWebhookDestinationsSection.tsx",+ "frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/components/Alerts/useWebhookConfigState.ts": "c08c16075b39d6bf4ce66c802fe59cb92540954b9ad97aaa125c71a14484aa51",+ "frontend-modern/src/components/Alerts/WebhookConfig.tsx": "d1b7dccfc0db12863b215d041abd01dc7d449b7fa06d798025ac863290cf8d17",+ "frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts": "50cdcec4d337c9959724777b0b066db83e80af6e027f6a00a69361a3de128677",+ "frontend-modern/src/features/alerts/AlertWebhookDestinationsSection.tsx": "edc82aa1379a942dde66bc7cb38920b4d70e5f12dbaa271e277d0deed1ccbc46"+ },+ "routes": [+ "/settings/alerts"+ ],+ "states": [+ "Existing webhook section in a source-isolated offline fixture, using the real component, state owners and API adapters",+ "Deferred bulk and individual writes, unchanged rows, 503 partial failure with earlier acknowledged changes retained",+ "Unaccepted deletion, deliberate retry, open masked draft and retired editor"+ ],+ "interactions": [+ "Bulk Disable with blocked competing Enable, row deletion and new editor entry; one acknowledged write at a time",+ "Explicit retry changes only remaining changed rows; no editor retry or rollback on failure",+ "Single toggle and deletion share pending admission; success:false preserves the row, success:true removes it",+ "Edit/Cancel retain the existing mask and draft fields, while list controls remain disabled",+ "Leave the editor while a batch is pending: no remaining unsent write is issued"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 960+ },+ {+ "width": 390,+ "height": 844+ }+ ],+ "verified_at": "2026-10-10T12:16:16.965Z",+ "browser": {+ "client": "1.56.1",+ "engine": "Chromium",+ "version": "141.0.7390.37"+ },+ "scope": "Targeted existing section fixture and synthetic local API endpoints, not full authenticated application, provider delivery or installed recovery."+}diff --git a/frontend-modern/src/components/Alerts/WebhookConfig.mutations.test.tsx b/frontend-modern/src/components/Alerts/WebhookConfig.mutations.test.tsxnew file mode 100644index 0000000000..b95ad446fb--- /dev/null+++ b/frontend-modern/src/components/Alerts/WebhookConfig.mutations.test.tsx@@ -0,0 +1,256 @@+import { createSignal } from 'solid-js';+import {+ cleanup,+ fireEvent,+ render,+ renderHook,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { NotificationsAPI, type Webhook } from '@/api/notifications';+import { useAlertWebhookDestinationsState } from '@/features/alerts/useAlertWebhookDestinationsState';+import { WebhookConfig } from './WebhookConfig';++vi.mock('@/api/notifications', () => ({+ NotificationsAPI: {+ getWebhookTemplates: vi.fn(),+ createWebhook: vi.fn(),+ updateWebhook: vi.fn(),+ deleteWebhook: vi.fn(),+ testNotification: vi.fn(),+ },+}));+vi.mock('@/stores/notifications', () => ({+ notificationStore: { success: vi.fn(), error: vi.fn() },+}));+vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn() } }));++const webhook: Webhook = {+ id: 'hook-1',+ name: 'First destination',+ url: 'https://example.test/receiver',+ method: 'POST',+ enabled: true,+ service: 'generic',+ headers: { Authorization: '********' },+ customFields: { team: 'ops' },+ template: '{"message":"{{message}}"}',+ mention: 'operators',+ tagFilter: ['department-a'],+ tagFilterMode: 'any',+ minimumSeverity: 'warning',+};+const secondWebhook = { ...webhook, id: 'hook-2', name: 'Second destination' };+const thirdWebhook = { ...webhook, id: 'hook-3', name: 'Third destination' };++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: Error) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}++function mount(initial: Webhook[] = [webhook]) {+ const { result: owner } = renderHook(() => {+ const [webhooks, setWebhooks] = createSignal(initial);+ return useAlertWebhookDestinationsState({ webhooks, setWebhooks, autoLoad: false });+ });+ const rendered = render(() => (+ <WebhookConfig+ webhooks={owner.webhooks()}+ onAdd={owner.addWebhook}+ onUpdate={owner.updateWebhook}+ onDelete={owner.deleteWebhook}+ onTest={owner.testWebhook}+ />+ ));+ return { owner, unmount: rendered.unmount };+}++function expectListLocked() {+ const list = screen.getByRole('button', { name: 'Disable All' }).closest('.space-y-3')!;+ for (const name of [+ 'Disable All',+ 'Enable All',+ 'Edit',+ 'Delete',+ 'Enabled',+ 'Disabled',+ 'Test',+ ]) {+ for (const button of within(list as HTMLElement).queryAllByRole('button', {+ name,+ })) {+ expect(button).toBeDisabled();+ }+ }+}++describe('acknowledged webhook list mutations', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.mocked(NotificationsAPI.getWebhookTemplates).mockResolvedValue([]);+ });+ afterEach(cleanup);++ it('serialises a bulk change, skips unchanged rows and locks all conflicting controls', async () => {+ const first = deferred<Webhook>();+ const second = deferred<Webhook>();+ vi.mocked(NotificationsAPI.updateWebhook)+ .mockReturnValueOnce(first.promise)+ .mockReturnValueOnce(second.promise);+ const unchanged = { ...thirdWebhook, enabled: false };+ const { owner } = mount([webhook, secondWebhook, unchanged]);+ const disableAll = screen.getByRole('button', { name: 'Disable All' });+ fireEvent.click(disableAll);+ fireEvent.click(disableAll);++ expect(NotificationsAPI.updateWebhook).toHaveBeenCalledTimes(1);+ expect(NotificationsAPI.updateWebhook).toHaveBeenNthCalledWith(1, 'hook-1', {+ ...webhook,+ enabled: false,+ });+ expectListLocked();+ expect(screen.getByRole('button', { name: '+ Add Webhook' })).toBeDisabled();+ expect(screen.getByRole('status')).toHaveTextContent('Saving webhook changes');+ expect(owner.webhooks()).toEqual([webhook, secondWebhook, unchanged]);++ first.resolve({ ...webhook, enabled: false });+ await waitFor(() => expect(NotificationsAPI.updateWebhook).toHaveBeenCalledTimes(2));+ expect(NotificationsAPI.updateWebhook).toHaveBeenNthCalledWith(2, 'hook-2', {+ ...secondWebhook,+ enabled: false,+ });+ expect(owner.webhooks()).toEqual([{ ...webhook, enabled: false }, secondWebhook, unchanged]);+ expectListLocked();++ second.resolve({ ...secondWebhook, enabled: false });+ await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument());+ expect(owner.webhooks().every((entry) => !entry.enabled)).toBe(true);+ expect(NotificationsAPI.updateWebhook).toHaveBeenCalledTimes(2);+ expect(screen.getByRole('button', { name: 'Enable All' })).toBeEnabled();+ });++ it('keeps the saved row unchanged and admits no competing action during a pending toggle', async () => {+ const pending = deferred<Webhook>();+ vi.mocked(NotificationsAPI.updateWebhook).mockReturnValueOnce(pending.promise);+ const { owner } = mount();+ const toggle = screen.getByRole('button', { name: 'Enabled' });+ fireEvent.click(toggle);+ fireEvent.click(toggle);+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));+ fireEvent.click(screen.getByRole('button', { name: '+ Add Webhook' }));+ expect(NotificationsAPI.updateWebhook).toHaveBeenCalledTimes(1);+ expect(NotificationsAPI.deleteWebhook).not.toHaveBeenCalled();+ expect(screen.queryByLabelText('Name')).not.toBeInTheDocument();+ expect(owner.webhooks()).toEqual([webhook]);+ expectListLocked();++ pending.resolve({ ...webhook, enabled: false });+ await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument());+ expect(owner.webhooks()).toEqual([{ ...webhook, enabled: false }]);+ expect(screen.getByRole('button', { name: 'Disabled' })).toBeEnabled();+ });++ it('waits for deletion acknowledgement without removing the row or allowing another write', async () => {+ const pending = deferred<{ success: boolean }>();+ vi.mocked(NotificationsAPI.deleteWebhook).mockReturnValueOnce(pending.promise);+ const { owner } = mount();+ const remove = screen.getByRole('button', { name: 'Delete' });+ fireEvent.click(remove);+ fireEvent.click(remove);+ expect(NotificationsAPI.deleteWebhook).toHaveBeenCalledTimes(1);+ expect(owner.webhooks()).toEqual([webhook]);+ expectListLocked();+ expect(screen.getByRole('button', { name: '+ Add Webhook' })).toBeDisabled();++ pending.resolve({ success: true });+ await waitFor(() => expect(screen.queryByText(webhook.name)).not.toBeInTheDocument());+ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: '+ Add Webhook' })).toBeEnabled();+ });++ it('stops a partially acknowledged bulk change at the first failed write without rollback or retry', async () => {+ vi.mocked(NotificationsAPI.updateWebhook)+ .mockResolvedValueOnce({ ...webhook, enabled: false })+ .mockRejectedValueOnce(new Error('Synthetic receiver detail'));+ const { owner } = mount([webhook, secondWebhook, thirdWebhook]);+ fireEvent.click(screen.getByRole('button', { name: 'Disable All' }));+ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());+ expect(screen.getByRole('alert')).toHaveTextContent(+ 'Some destinations may already have changed',+ );+ expect(screen.getByRole('alert')).not.toHaveTextContent('Synthetic receiver detail');+ expect(owner.webhooks()).toEqual([{ ...webhook, enabled: false }, secondWebhook, thirdWebhook]);+ expect(NotificationsAPI.updateWebhook).toHaveBeenCalledTimes(2);+ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Disable All' })).toBeEnabled();+ });++ it('preserves an open edit draft by refusing list changes until it is saved or cancelled', async () => {+ const { owner } = mount();+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));+ fireEvent.input(screen.getByLabelText('Name'), { target: { value: 'Unsaved destination' } });+ expectListLocked();+ fireEvent.click(screen.getByRole('button', { name: 'Enabled' }));+ fireEvent.click(screen.getByRole('button', { name: 'Disable All' }));+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));+ expect(NotificationsAPI.updateWebhook).not.toHaveBeenCalled();+ expect(NotificationsAPI.deleteWebhook).not.toHaveBeenCalled();+ expect(owner.webhooks()).toEqual([webhook]);+ expect(screen.getByLabelText('Name')).toHaveValue('Unsaved destination');+ expect(screen.getByLabelText('Custom header 1 value')).toHaveValue('********');+ expect(screen.getByRole('button', { name: 'Update Webhook' })).toBeEnabled();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(screen.getByRole('button', { name: 'Enabled' })).toBeEnabled();+ });++ it('withdraws unsent bulk writes when the editor is unmounted', async () => {+ const pending = deferred<Webhook>();+ vi.mocked(NotificationsAPI.updateWebhook).mockReturnValueOnce(pending.promise);+ const { unmount } = mount([webhook, secondWebhook]);+ fireEvent.click(screen.getByRole('button', { name: 'Disable All' }));+ expect(NotificationsAPI.updateWebhook).toHaveBeenCalledTimes(1);+ unmount();+ pending.resolve({ ...webhook, enabled: false });+ // Drain the promise chain, including the batch continuation, without a timer retry.+ for (let index = 0; index < 10; index++) await Promise.resolve();+ expect(NotificationsAPI.updateWebhook).toHaveBeenCalledTimes(1);+ });++ it('retains a failed deletion and requires a deliberate retry before changing inventory', async () => {+ vi.mocked(NotificationsAPI.deleteWebhook).mockRejectedValueOnce(+ new Error('Delete unavailable'),+ );+ const { owner } = mount();+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));+ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());+ expect(owner.webhooks()).toEqual([webhook]);+ expect(NotificationsAPI.deleteWebhook).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('alert')).toHaveTextContent('Check the configured destinations');++ const retry = deferred<{ success: boolean }>();+ vi.mocked(NotificationsAPI.deleteWebhook).mockReturnValueOnce(retry.promise);+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expectListLocked();+ retry.resolve({ success: true });+ await waitFor(() => expect(owner.webhooks()).toEqual([]));+ expect(NotificationsAPI.deleteWebhook).toHaveBeenCalledTimes(2);+ });++ it('does not treat an unaccepted deletion response as an acknowledged removal', async () => {+ vi.mocked(NotificationsAPI.deleteWebhook).mockResolvedValueOnce({ success: false });+ const { owner } = mount();+ expect(await owner.deleteWebhook(webhook.id)).toBe(false);+ expect(owner.webhooks()).toEqual([webhook]);+ expect(NotificationsAPI.deleteWebhook).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend-modern/src/components/Alerts/WebhookConfig.persistence.test.tsx b/frontend-modern/src/components/Alerts/WebhookConfig.persistence.test.tsxindex 0e162351d9..f2e7bfb7bb 100644--- a/frontend-modern/src/components/Alerts/WebhookConfig.persistence.test.tsx+++ b/frontend-modern/src/components/Alerts/WebhookConfig.persistence.test.tsx@@ -196,7 +196,7 @@ describe('webhook persistence acknowledgement', () => {throw new Error(privateDetail);}}onUpdate={async () => false}- onDelete={() => {}}+ onDelete={() => true}onTest={() => {}}/>));diff --git a/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx b/frontend-modern/src/components/Alerts/WebhookConfig.test.tsxindex 18c8d4a3a5..b2cc22efb7 100644--- a/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx+++ b/frontend-modern/src/components/Alerts/WebhookConfig.test.tsx@@ -112,7 +112,7 @@ describe('WebhookConfig', () => {beforeEach(() => {onAddMock = vi.fn().mockResolvedValue(true);onUpdateMock = vi.fn().mockResolvedValue(true);- onDeleteMock = vi.fn();+ onDeleteMock = vi.fn().mockResolvedValue(true);onTestMock = vi.fn();getWebhookTemplatesMock.mockReset();getWebhookTemplatesMock.mockResolvedValue(mockTemplates);@@ -345,7 +345,7 @@ describe('WebhookConfig', () => {);});- it('"Enable All" calls onUpdate for each webhook with enabled=true', () => {+ it('"Enable All" awaits onUpdate for each webhook with enabled=true', async () => {const webhooks = [makeWebhook({ id: 'wh-1', enabled: false }),makeWebhook({ id: 'wh-2', enabled: false }),@@ -363,7 +363,7 @@ describe('WebhookConfig', () => {fireEvent.click(screen.getByText('Enable All'));- expect(onUpdateMock).toHaveBeenCalledTimes(2);+ await waitFor(() => expect(onUpdateMock).toHaveBeenCalledTimes(2));expect(onUpdateMock).toHaveBeenCalledWith(expect.objectContaining({ id: 'wh-1', enabled: true }),);@@ -372,7 +372,7 @@ describe('WebhookConfig', () => {);});- it('"Disable All" calls onUpdate for each webhook with enabled=false', () => {+ it('"Disable All" awaits onUpdate for each webhook with enabled=false', async () => {const webhooks = [makeWebhook({ id: 'wh-1', enabled: true }),makeWebhook({ id: 'wh-2', enabled: true }),@@ -390,7 +390,7 @@ describe('WebhookConfig', () => {fireEvent.click(screen.getByText('Disable All'));- expect(onUpdateMock).toHaveBeenCalledTimes(2);+ await waitFor(() => expect(onUpdateMock).toHaveBeenCalledTimes(2));expect(onUpdateMock).toHaveBeenCalledWith(expect.objectContaining({ id: 'wh-1', enabled: false }),);@@ -1324,7 +1324,7 @@ describe('WebhookConfig', () => {fireEvent.click(screen.getByText('Delete'));- // The handler checks `webhook.id && props.onDelete(webhook.id)` — empty string is falsy+ // Empty identities cannot dispatch a delete.expect(onDeleteMock).not.toHaveBeenCalled();});diff --git a/frontend-modern/src/components/Alerts/WebhookConfig.tsx b/frontend-modern/src/components/Alerts/WebhookConfig.tsxindex b7a3cde737..f0f60fd71b 100644--- a/frontend-modern/src/components/Alerts/WebhookConfig.tsx+++ b/frontend-modern/src/components/Alerts/WebhookConfig.tsx@@ -11,7 +11,7 @@ export interface WebhookConfigProps {webhooks: Webhook[];onAdd: (webhook: Omit<Webhook, 'id'>) => boolean | Promise<boolean>;onUpdate: (webhook: Webhook) => boolean | Promise<boolean>;- onDelete: (id: string) => void;+ onDelete: (id: string) => boolean | Promise<boolean>;onTest: (id: string, webhookData?: Omit<Webhook, 'id'>) => void;testing?: string | null;}@@ -26,17 +26,28 @@ export function WebhookConfig(props: WebhookConfigProps) {webhooks={props.webhooks}templates={state.templates}testing={props.testing}- saving={state.saving()}+ saving={state.saving() || state.adding()}allEnabled={state.allEnabled}someEnabled={state.someEnabled}toggleAllWebhooks={state.toggleAllWebhooks}- onToggleWebhook={(webhook) => props.onUpdate({ ...webhook, enabled: !webhook.enabled })}+ onToggleWebhook={state.toggleWebhook}onTestWebhook={(webhook) => webhook.id && props.onTest(webhook.id)}onEditWebhook={state.editWebhook}- onDeleteWebhook={(webhook) => webhook.id && props.onDelete(webhook.id)}+ onDeleteWebhook={state.deleteWebhook}/></Show>+ <Show when={state.saving() && !state.adding()}>+ <p role="status" class="text-xs text-muted">+ Saving webhook changes…+ </p>+ </Show>+ <Show when={state.mutationError()}>+ <p role="alert" class="text-xs text-red-600 dark:text-red-400">+ {state.mutationError()}+ </p>+ </Show>+<Show when={state.adding()}><WebhookConfigFormeditingId={state.editingId}diff --git a/frontend-modern/src/components/Alerts/useWebhookConfigState.ts b/frontend-modern/src/components/Alerts/useWebhookConfigState.tsindex 7a4b5b12e2..0ee3101f17 100644--- a/frontend-modern/src/components/Alerts/useWebhookConfigState.ts+++ b/frontend-modern/src/components/Alerts/useWebhookConfigState.ts@@ -1,4 +1,4 @@-import { createEffect, createSignal } from 'solid-js';+import { createEffect, createSignal, onCleanup } from 'solid-js';import type { Accessor } from 'solid-js';import { NotificationsAPI, type Webhook, type WebhookTemplate } from '@/api/notifications';@@ -74,6 +74,7 @@ export interface WebhookConfigState {adding: Accessor<boolean>;saving: Accessor<boolean>;saveError: Accessor<string | null>;+ mutationError: Accessor<string | null>;editingId: Accessor<string | null>;formData: Accessor<WebhookConfigFormData>;templates: Accessor<WebhookTemplate[]>;@@ -91,7 +92,9 @@ export interface WebhookConfigState {selectService: (service: string) => void;saveWebhook: () => Promise<void>;testWebhookForm: () => void;- toggleAllWebhooks: (enabled: boolean) => void;+ toggleAllWebhooks: (enabled: boolean) => Promise<void>;+ toggleWebhook: (webhook: Webhook) => Promise<void>;+ deleteWebhook: (webhook: Webhook) => Promise<void>;updateHeaderInput: (index: number, patch: Partial<HeaderInput>) => void;removeHeaderInput: (index: number) => void;addHeaderInput: () => void;@@ -104,12 +107,17 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigSconst [adding, setAdding] = createSignal(false);const [saving, setSaving] = createSignal(false);const [saveError, setSaveError] = createSignal<string | null>(null);+ const [mutationError, setMutationError] = createSignal<string | null>(null);const [editingId, setEditingId] = createSignal<string | null>(null);const [formData, setFormData] = createSignal<WebhookConfigFormData>(createDefaultFormData());const [templates, setTemplates] = createSignal<WebhookTemplate[]>([]);const [showServiceDropdown, setShowServiceDropdown] = createSignal(false);const [headerInputs, setHeaderInputs] = createSignal<HeaderInput[]>([]);const [customFieldInputs, _setCustomFieldInputs] = createSignal<CustomFieldInput[]>([]);+ let disposed = false;+ onCleanup(() => {+ disposed = true;+ });const setCustomFieldInputs = (inputs: CustomFieldInput[]) => {_setCustomFieldInputs(inputs);@@ -152,17 +160,51 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigSconst currentTemplate = () =>templates().find((template) => template.service === formData().service);- const toggleAllWebhooks = (enabled: boolean) => {- props.webhooks.forEach((webhook) => {- props.onUpdate({ ...webhook, enabled });+ // The form and list share one writer. Do not let a late toggle acknowledgement+ // replace a later operator choice, or let list changes invalidate an open draft.+ const mutateList = async (mutate: () => boolean | Promise<boolean>) => {+ if (disposed || saving() || adding()) return;+ setSaving(true);+ setMutationError(null);+ const failureMessage =+ 'Could not confirm all webhook changes. Some destinations may already have changed. Check the configured destinations before trying again.';+ try {+ if ((await mutate()) !== true && !disposed) setMutationError(failureMessage);+ } catch {+ // Callback/provider text may contain private destination details.+ if (!disposed) setMutationError(failureMessage);+ } finally {+ if (!disposed) setSaving(false);+ }+ };++ const toggleAllWebhooks = (enabled: boolean) =>+ mutateList(async () => {+ // Capture only changed rows before yielding. Each acknowledgement updates+ // inventory; a failure leaves earlier accepted changes intact, not rolled back.+ const submitted = props.webhooks+ .filter((webhook) => webhook.enabled !== enabled)+ .map((webhook) => structuredClone({ ...webhook, enabled }));+ for (const webhook of submitted) {+ if (disposed) return false;+ if ((await props.onUpdate(webhook)) !== true) return false;+ }+ return true;});++ const toggleWebhook = (webhook: Webhook) =>+ mutateList(() => props.onUpdate(structuredClone({ ...webhook, enabled: !webhook.enabled })));++ const deleteWebhook = async (webhook: Webhook) => {+ if (!webhook.id) return;+ await mutateList(() => props.onDelete(webhook.id));};const allEnabled = () => props.webhooks.every((webhook) => webhook.enabled);const someEnabled = () => props.webhooks.some((webhook) => webhook.enabled);const openAddForm = () => {- if (saving()) return;+ if (disposed || saving()) return;setSaveError(null);setAdding(true);setEditingId(null);@@ -175,12 +217,12 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigS};const cancelForm = () => {- if (saving()) return;+ if (disposed || saving()) return;resetForm();};const editWebhook = (webhook: Webhook) => {- if (saving()) return;+ if (disposed || saving()) return;setSaveError(null);if (webhook.id) {setEditingId(webhook.id);@@ -253,7 +295,7 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigS};const saveWebhook = async () => {- if (saving()) return;+ if (disposed || saving()) return;const data = formData();if (!data.name || !data.url) return;@@ -296,13 +338,15 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigS? data.minimumSeverity: 'all',});- if (accepted === true) resetForm();- else setSaveError(failureMessage);+ if (!disposed) {+ if (accepted === true) resetForm();+ else setSaveError(failureMessage);+ }} catch {// Callback/provider text can contain submitted destination details.- setSaveError(failureMessage);+ if (!disposed) setSaveError(failureMessage);} finally {- setSaving(false);+ if (!disposed) setSaving(false);}};@@ -360,6 +404,7 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigSadding,saving,saveError,+ mutationError,editingId,formData,templates,@@ -378,6 +423,8 @@ export function useWebhookConfigState(props: WebhookConfigProps): WebhookConfigSsaveWebhook,testWebhookForm,toggleAllWebhooks,+ toggleWebhook,+ deleteWebhook,updateHeaderInput,removeHeaderInput,addHeaderInput,diff --git a/frontend-modern/src/features/alerts/AlertWebhookDestinationsSection.tsx b/frontend-modern/src/features/alerts/AlertWebhookDestinationsSection.tsxindex e37b413d37..afd7f76b70 100644--- a/frontend-modern/src/features/alerts/AlertWebhookDestinationsSection.tsx+++ b/frontend-modern/src/features/alerts/AlertWebhookDestinationsSection.tsx@@ -10,7 +10,7 @@ interface AlertWebhookDestinationsSectionProps {webhooks: Webhook[];addWebhook: WebhookConfigProps['onAdd'];updateWebhook: WebhookConfigProps['onUpdate'];- deleteWebhook: (id: string) => void;+ deleteWebhook: WebhookConfigProps['onDelete'];testWebhook: (webhookId: string, webhookData?: Omit<Webhook, 'id'>) => void;testingWebhook: string | null;}diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsxindex 0cde2a53b0..61cc1e83f1 100644--- a/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsx+++ b/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsx@@ -1,7 +1,8 @@import { renderHook, waitFor } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { NotificationsAPI } from '@/api/notifications';+import { NotificationsAPI, type Webhook } from '@/api/notifications';import { notificationStore } from '@/stores/notifications';import { showErrorWithDetail } from '@/utils/toast';@@ -124,4 +125,54 @@ describe('useAlertWebhookDestinationsState', () => {expect(notificationStore.success).toHaveBeenCalled();expect(showErrorWithDetail).not.toHaveBeenCalled();});++ it.each(['create', 'update', 'delete'] as const)(+ 'withdraws the retired %s owner before a late reply can change replacement inventory',+ async (operation) => {+ const saved: Webhook = {+ id: 'old-hook',+ name: 'Previous context',+ url: 'https://example.test/old',+ method: 'POST',+ headers: {},+ enabled: true,+ };+ const replacement = { ...saved, name: 'Replacement context' };+ let resolve!: (value: Webhook | { success: boolean }) => void;+ const pending = new Promise<Webhook | { success: boolean }>((yes) => {+ resolve = yes;+ });+ vi.mocked(NotificationsAPI.createWebhook).mockReturnValue(pending as Promise<Webhook>);+ vi.mocked(NotificationsAPI.updateWebhook).mockReturnValue(pending as Promise<Webhook>);+ vi.mocked(NotificationsAPI.deleteWebhook).mockReturnValue(+ pending as Promise<{ success: boolean }>,+ );+ // The shared inventory outlives its child destination-tab owner, as it+ // does when saved-policy loading replaces that child on an org change.+ const [webhooks, setWebhooks] = createSignal([saved]);+ const { result, cleanup: dispose } = renderHook(() =>+ useAlertWebhookDestinationsState({ webhooks, setWebhooks, autoLoad: false }),+ );+ const invoke = () =>+ operation === 'create'+ ? result.addWebhook(saved)+ : operation === 'update'+ ? result.updateWebhook(saved)+ : result.deleteWebhook(saved.id);+ const write = invoke();+ dispose();+ setWebhooks([replacement]);+ resolve(operation === 'delete' ? { success: true } : saved);+ expect(await write).toBe(false);+ expect(webhooks()).toEqual([replacement]);+ expect(notificationStore.success).not.toHaveBeenCalled();+ expect(notificationStore.error).not.toHaveBeenCalled();+ expect(await invoke()).toBe(false);+ expect(+ vi.mocked(NotificationsAPI.createWebhook).mock.calls.length ++ vi.mocked(NotificationsAPI.updateWebhook).mock.calls.length ++ vi.mocked(NotificationsAPI.deleteWebhook).mock.calls.length,+ ).toBe(1);+ },+ );});diff --git a/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts b/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.tsindex bf0689e218..5ca9d83f34 100644--- a/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts+++ b/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts@@ -1,4 +1,4 @@-import { createSignal, onMount, type Accessor, type Setter } from 'solid-js';+import { createSignal, onCleanup, onMount, type Accessor, type Setter } from 'solid-js';import { NotificationsAPI, type Webhook } from '@/api/notifications';import { notificationStore } from '@/stores/notifications';@@ -35,6 +35,10 @@ export function useAlertWebhookDestinationsState(const [webhookLoadError, setWebhookLoadError] = createSignal<string | null>(null);const [isLoadingWebhooks, setIsLoadingWebhooks] = createSignal(options.autoLoad !== false);const [testingWebhook, setTestingWebhook] = createSignal<string | null>(null);+ let disposed = false;+ onCleanup(() => {+ disposed = true;+ });const loadWebhooks = async () => {setWebhookLoadError(null);@@ -77,12 +81,15 @@ export function useAlertWebhookDestinationsState(};const addWebhook = async (webhook: Omit<Webhook, 'id'>) => {+ if (disposed) return false;try {const created = await NotificationsAPI.createWebhook(webhook);+ if (disposed) return false;setWebhooks((current) => [...current, normalizeWebhook(created)]);notificationStore.success(getAlertWebhookMutationSuccess('add'));return true;} catch (error) {+ if (disposed) return false;logger.error('Failed to add webhook:', error);notificationStore.error(error instanceof Error ? error.message : getAlertWebhookMutationFailure('add'),@@ -92,14 +99,17 @@ export function useAlertWebhookDestinationsState(};const updateWebhook = async (webhook: Webhook) => {+ if (disposed) return false;try {const updated = await NotificationsAPI.updateWebhook(webhook.id, webhook);+ if (disposed) return false;setWebhooks((current) =>current.map((entry) => (entry.id === webhook.id ? normalizeWebhook(updated) : entry)),);notificationStore.success(getAlertWebhookMutationSuccess('update'));return true;} catch (error) {+ if (disposed) return false;logger.error('Failed to update webhook:', error);notificationStore.error(error instanceof Error ? error.message : getAlertWebhookMutationFailure('update'),@@ -109,15 +119,23 @@ export function useAlertWebhookDestinationsState(};const deleteWebhook = async (id: string) => {+ if (disposed) return false;try {- await NotificationsAPI.deleteWebhook(id);+ const result = await NotificationsAPI.deleteWebhook(id);+ if (disposed) return false;+ if (result.success !== true) {+ throw new Error(getAlertWebhookMutationFailure('delete'));+ }setWebhooks((current) => current.filter((entry) => entry.id !== id));notificationStore.success(getAlertWebhookMutationSuccess('delete'));+ return true;} catch (error) {+ if (disposed) return false;logger.error('Failed to delete webhook:', error);notificationStore.error(error instanceof Error ? error.message : getAlertWebhookMutationFailure('delete'),);+ return false;}};