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.

Keep alert settings with their admitted reader

pulse-triage[bot]947fa4ee64bb
diff --git a/frontend-modern/browser-verification/38c72912bf97aa22.json b/frontend-modern/browser-verification/38c72912bf97aa22.json
new file mode 100644
index 0000000000..ce4eba8018
--- /dev/null
+++ b/frontend-modern/browser-verification/38c72912bf97aa22.json
@@ -0,0 +1,62 @@
+{
+ "version": 1,
+ "base_sha": "11b2d46fb642be7bf5af0096f9805e2e1b2433f5",
+ "verified_at": "2026-11-02T16:19:37Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/App.tsx",
+ "frontend-modern/src/api/alerts.ts",
+ "frontend-modern/src/api/notifications.ts",
+ "frontend-modern/src/api/relay.ts",
+ "frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx",
+ "frontend-modern/src/features/alerts/useAlertDestinationsState.ts",
+ "frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts",
+ "frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationState.ts",
+ "frontend-modern/src/features/alerts/useNotificationDeliveryHealth.ts",
+ "frontend-modern/src/features/alerts/useNotificationDeliveryLog.ts",
+ "frontend-modern/src/pages/Alerts.tsx",
+ "frontend-modern/src/utils/alertDestinationsPresentation.ts",
+ "frontend-modern/src/utils/apiClient.ts"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/App.tsx": "52d46866148cb18fccd0219d33dbab64eab6ff9efa33c2085ce97ee750fbd7d7",
+ "frontend-modern/src/api/alerts.ts": "f165968e3882983d8a917d1cf3825b8e4023b4a4b0ca45cee871df7629505b7e",
+ "frontend-modern/src/api/notifications.ts": "5944986c86327a416f8ed3bcf82611aab89c087e369b7f3aed32630e93e5db4b",
+ "frontend-modern/src/api/relay.ts": "c5b3dd124946b4f4182134e7ddbe0a746e9e2ba49d1cef2e7b3c32ef62e969c9",
+ "frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx": "1a700330eb8dbdca071d177087fbf2006572a531810d34a5b5699697dab06f76",
+ "frontend-modern/src/features/alerts/useAlertDestinationsState.ts": "9dffa47880dc6f324d409e20fba1650b8b93cef34e041a736fef432c536f4e98",
+ "frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts": "796cf460d749ba40ef9bd8266face49862b199f35efed32ae29da47e304f74c0",
+ "frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts": "216691ecbfc2a79b9bd2534d036cf80f708bd1792ec03c27f51a7f3062033831",
+ "frontend-modern/src/features/alerts/useAlertsConfigurationState.ts": "fcd049daa344e0ab2d02467b1c73e555c56e632011c2a2f0ee1a38c16ef29970",
+ "frontend-modern/src/features/alerts/useNotificationDeliveryHealth.ts": "97252c73820c86fa507de0439e71d1e7e58a83f327fc5a2a03d71e55a43c0124",
+ "frontend-modern/src/features/alerts/useNotificationDeliveryLog.ts": "b3cce16b4668b4c1bc9af726ab0cf02d6fdf59b6978d96737363d69fd81f5bbc",
+ "frontend-modern/src/pages/Alerts.tsx": "de54a1ce22dad099c2f72adc5e96306c60229e369e0ac58236770d27b18f4460",
+ "frontend-modern/src/utils/alertDestinationsPresentation.ts": "331cb64aca721517bf571756fc9d762ffd53341cf322badd86a803e81cca0035",
+ "frontend-modern/src/utils/apiClient.ts": "69c5fecf7e7114b8bfdee071a127ee607e4856439f694c69e551ae7a8738c1a5"
+ },
+ "routes": [
+ "/alerts/destinations",
+ "/alerts/schedule"
+ ],
+ "viewports": [
+ {
+ "width": 1280,
+ "height": 900
+ },
+ {
+ "width": 390,
+ "height": 844
+ }
+ ],
+ "states": [
+ "Actual App route passes authenticated security-status facts to the keyed Alerts configuration reader. Existing configuration owner, API adapters, destination editor and workspace-event producer consume only synthetic local endpoints.",
+ "Complete saved snapshot, partial denied read, explicit Retry, pending obsolete read, replacement workspace recovery, acknowledged save and pending old-policy write. Chromium desktop/light and WebKit narrow/dark; Playwright 1.56.1 matches the integration lock. Principal/token/capability equality and retirement are covered separately by registered page tests, not claimed as installed IdP proof."
+ ],
+ "interactions": [
+ "39 checks at 1280x900 and 390x844. Denied reads withdraw all destination details and Test controls; no fallback retry or configuration/test side effect from reading. Explicit recovery requires a complete fresh snapshot.",
+ "Obsolete reads are cancelled; current saved reads use no-store and expected workspace. Released old reads do not overwrite the new workspace. A single Save dispatches exactly policy/email/Apprise/watchdog once; old policy completion starts no destination writes or new success notice after replacement. Issued writes are not undone.",
+ "All eight viewport captures opened with native view_image. Desktop and narrow pixels show readable denial/retry with no old fields, then only tenant-b and tenant-c SMTP/webhook values. Crops do not show every editor control or prove provider/installed recovery.",
+ "Both browser contexts/engines, Vite and HTTP fixture close. No uncaught page errors. Earlier fixture error, two pending-read recovery failures and an overbroad old-toast assertion remain in retained evidence; the assertion now dismisses the earlier accepted save through its real Dismiss control before judging new feedback."
+ ]
+}
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index 51806436dc..3eaf431b0a 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -315,6 +315,8 @@ function App() {
/>
);
+ const AlertsRoute = () => <AlertsPage securityStatus={runtime.securityStatus()} />;
+
// Root layout component for Router
const RootLayout = (props: { children?: JSX.Element }) => {
const [shortcutsOpen, setShortcutsOpen] = createSignal(false);
@@ -607,7 +609,7 @@ function App() {
<Route path={STANDALONE_PATH} component={StandalonePage} />
<Route path={`${STANDALONE_PATH}/*`} component={StandalonePage} />
- <Route path="/alerts/*" component={AlertsPage} />
+ <Route path="/alerts/*" component={AlertsRoute} />
<Route path="/actions/*" component={ActionsPage} />
<Route path={`${ROOT_PATROL_PATH}/*`} component={AIIntelligencePage} />
<Route path="/settings/*" component={SettingsRoute} />
diff --git a/frontend-modern/src/__tests__/App.architecture.test.ts b/frontend-modern/src/__tests__/App.architecture.test.ts
index 58807f0101..ccc9b980af 100644
--- a/frontend-modern/src/__tests__/App.architecture.test.ts
+++ b/frontend-modern/src/__tests__/App.architecture.test.ts
@@ -54,6 +54,14 @@ const makeResource = (overrides: Partial<Resource>): Resource =>
}) as Resource;
describe('App platform navigation admission', () => {
+ it('hands current authenticated reader facts to the existing Alerts route', () => {
+ expect(appSource).toContain(
+ 'const AlertsRoute = () => <AlertsPage securityStatus={runtime.securityStatus()} />;',
+ );
+ expect(appSource).toContain('<Route path="/alerts/*" component={AlertsRoute} />');
+ expect(appSource).not.toContain('<Route path="/alerts/*" component={AlertsPage} />');
+ });
+
const authenticatedResources = [
makeResource({ id: 'machine-1', platformType: 'agent' }),
makeResource({ id: 'docker-1', type: 'docker-host', platformType: 'docker' }),
diff --git a/frontend-modern/src/api/__tests__/alerts.test.ts b/frontend-modern/src/api/__tests__/alerts.test.ts
index c4e804930f..37830d6864 100644
--- a/frontend-modern/src/api/__tests__/alerts.test.ts
+++ b/frontend-modern/src/api/__tests__/alerts.test.ts
@@ -56,7 +56,7 @@ describe('AlertsAPI', () => {
const result = await AlertsAPI.getConfig();
- expect(apiFetchJSON).toHaveBeenCalledWith('/api/alerts/config');
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/alerts/config', undefined);
expect(result).toEqual(mockConfig);
});
diff --git a/frontend-modern/src/api/__tests__/alertsDeadMan.test.ts b/frontend-modern/src/api/__tests__/alertsDeadMan.test.ts
index 5bd77f9718..679dea8569 100644
--- a/frontend-modern/src/api/__tests__/alertsDeadMan.test.ts
+++ b/frontend-modern/src/api/__tests__/alertsDeadMan.test.ts
@@ -23,7 +23,7 @@ describe('AlertsAPI external watchdog', () => {
pingUrl: '***REDACTED***',
configured: true,
});
- expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/alerts/deadman/config');
+ expect(mockedApiFetchJSON).toHaveBeenLastCalledWith('/api/alerts/deadman/config', undefined);
mockedApiFetchJSON.mockResolvedValueOnce({
configured: true,
diff --git a/frontend-modern/src/api/__tests__/notifications.branchcov0718.test.ts b/frontend-modern/src/api/__tests__/notifications.branchcov0718.test.ts
index 7efa7b2d49..f34a7ea6fe 100644
--- a/frontend-modern/src/api/__tests__/notifications.branchcov0718.test.ts
+++ b/frontend-modern/src/api/__tests__/notifications.branchcov0718.test.ts
@@ -41,7 +41,7 @@ describe('NotificationsAPI — branch coverage (0718)', () => {
const result = await NotificationsAPI.getAppriseConfig();
expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/apprise');
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/apprise', undefined);
expect(result).toEqual(payload);
});
});
diff --git a/frontend-modern/src/api/__tests__/notifications.test.ts b/frontend-modern/src/api/__tests__/notifications.test.ts
index 02bc33f61c..6adff21b67 100644
--- a/frontend-modern/src/api/__tests__/notifications.test.ts
+++ b/frontend-modern/src/api/__tests__/notifications.test.ts
@@ -14,6 +14,49 @@ describe('NotificationsAPI', () => {
apiFetchJSONMock.mockReset();
});
+ it('retains the admitted workspace and retry policy through every destination configuration adapter', async () => {
+ const context = { expectedOrgID: 'tenant-a', retry: false } as const;
+ const email = {
+ enabled: true,
+ server: 'smtp.example.test',
+ provider: 'custom',
+ port: 587,
+ username: 'ops',
+ password: '',
+ tls: true,
+ startTLS: true,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(email);
+ await NotificationsAPI.getEmailConfig(context);
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/notifications/email', context);
+ apiFetchJSONMock.mockResolvedValueOnce({ enabled: false });
+ await NotificationsAPI.getAppriseConfig(context);
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/notifications/apprise', context);
+ apiFetchJSONMock.mockResolvedValueOnce([]);
+ await NotificationsAPI.getWebhooks(context);
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith('/api/notifications/webhooks', context);
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true });
+ await NotificationsAPI.updateEmailConfig(email, context);
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith(
+ '/api/notifications/email',
+ expect.objectContaining({ ...context, method: 'PUT' }),
+ );
+ apiFetchJSONMock.mockResolvedValueOnce({ enabled: false });
+ await NotificationsAPI.updateAppriseConfig({ enabled: false }, context);
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith(
+ '/api/notifications/apprise',
+ expect.objectContaining({ ...context, method: 'PUT' }),
+ );
+ apiFetchJSONMock.mockResolvedValueOnce({ success: true });
+ await NotificationsAPI.testNotification({ type: 'email' }, context);
+ expect(apiFetchJSONMock).toHaveBeenLastCalledWith(
+ '/api/notifications/test',
+ expect.objectContaining({ ...context, method: 'POST' }),
+ );
+ });
+
it('preserves valid zero values when mapping email config', async () => {
apiFetchJSONMock.mockResolvedValueOnce({
enabled: false,
@@ -32,7 +75,7 @@ describe('NotificationsAPI', () => {
const config = await NotificationsAPI.getEmailConfig();
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/email');
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/email', undefined);
expect(config).toEqual({
enabled: false,
provider: 'smtp',
@@ -134,7 +177,7 @@ describe('NotificationsAPI', () => {
const result = await NotificationsAPI.getWebhooks();
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/webhooks');
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/webhooks', undefined);
expect(result).toEqual([]);
});
@@ -173,7 +216,7 @@ describe('NotificationsAPI', () => {
const health = await NotificationsAPI.getHealth();
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/health');
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/health', undefined);
expect(health).toEqual({
overallHealthy: false,
queue: {
@@ -343,7 +386,10 @@ describe('NotificationsAPI', () => {
const log = await NotificationsAPI.getDeliveryLog(25);
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/delivery-log?limit=25');
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/notifications/delivery-log?limit=25',
+ undefined,
+ );
expect(log.windowDays).toBe(30);
expect(log.completedRetentionDays).toBe(7);
expect(log.deadLetterRetentionDays).toBe(30);
@@ -365,7 +411,7 @@ describe('NotificationsAPI', () => {
const log = await NotificationsAPI.getDeliveryLog();
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/delivery-log');
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/delivery-log', undefined);
expect(log.entries).toEqual([]);
// A missing or nonsensical window falls back to the seven-day default.
expect(log.windowDays).toBe(7);
diff --git a/frontend-modern/src/api/__tests__/relay.test.ts b/frontend-modern/src/api/__tests__/relay.test.ts
index 426a1ba42f..e092fccda5 100644
--- a/frontend-modern/src/api/__tests__/relay.test.ts
+++ b/frontend-modern/src/api/__tests__/relay.test.ts
@@ -18,7 +18,7 @@ describe('RelayAPI', () => {
const result = await RelayAPI.getConfig();
- expect(apiFetchJSON).toHaveBeenCalledWith('/api/settings/relay');
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/settings/relay', undefined);
expect(result).toEqual(mockConfig);
});
});
diff --git a/frontend-modern/src/api/alerts.ts b/frontend-modern/src/api/alerts.ts
index 4548324ac5..d38de2b6e1 100644
--- a/frontend-modern/src/api/alerts.ts
+++ b/frontend-modern/src/api/alerts.ts
@@ -1,6 +1,6 @@
import type { Alert, AlertDeliveryDiagnosis, AlertEvent, Incident } from '@/types/api';
import type { AlertConfig, DeadManStatus } from '@/types/alerts';
-import { apiFetchJSON } from '@/utils/apiClient';
+import { apiFetchJSON, type APIContextOptions } from '@/utils/apiClient';
import { arrayOrEmpty } from './responseUtils';
export class AlertsAPI {
@@ -37,19 +37,22 @@ export class AlertsAPI {
return arrayOrEmpty<AlertDeliveryDiagnosis>(diagnoses);
}
- static async getEvents(params?: {
- alertIdentifier?: string;
- types?: string[];
- since?: string;
- limit?: number;
- }): Promise<AlertEvent[]> {
+ static async getEvents(
+ params?: {
+ alertIdentifier?: string;
+ types?: string[];
+ since?: string;
+ limit?: number;
+ },
+ options?: APIContextOptions,
+ ): Promise<AlertEvent[]> {
const query = new URLSearchParams();
if (params?.alertIdentifier) query.set('alertIdentifier', params.alertIdentifier);
if (params?.types?.length) query.set('type', params.types.join(','));
if (params?.since) query.set('since', params.since);
if (params?.limit) query.set('limit', String(params.limit));
const suffix = query.size > 0 ? `?${query.toString()}` : '';
- const events = (await apiFetchJSON(`${this.baseUrl}/events${suffix}`)) as AlertEvent[];
+ const events = (await apiFetchJSON(`${this.baseUrl}/events${suffix}`, options)) as AlertEvent[];
return arrayOrEmpty<AlertEvent>(events);
}
@@ -127,12 +130,16 @@ export class AlertsAPI {
}
// Alert configuration methods
- static async getConfig(): Promise<AlertConfig> {
- return apiFetchJSON(`${this.baseUrl}/config`) as Promise<AlertConfig>;
+ static async getConfig(options?: APIContextOptions): Promise<AlertConfig> {
+ return apiFetchJSON(`${this.baseUrl}/config`, options) as Promise<AlertConfig>;
}
- static async updateConfig(config: AlertConfig): Promise<{ success: boolean }> {
+ static async updateConfig(
+ config: AlertConfig,
+ options?: APIContextOptions,
+ ): Promise<{ success: boolean }> {
return apiFetchJSON(`${this.baseUrl}/config`, {
+ ...options,
method: 'PUT',
body: JSON.stringify(config),
});
@@ -142,18 +149,24 @@ export class AlertsAPI {
return apiFetchJSON(`${this.baseUrl}/deadman/status`) as Promise<DeadManStatus>;
}
- static async getDeadManConfig(): Promise<{ pingUrl: string; configured: boolean }> {
- return apiFetchJSON(`${this.baseUrl}/deadman/config`) as Promise<{
+ static async getDeadManConfig(
+ options?: APIContextOptions,
+ ): Promise<{ pingUrl: string; configured: boolean }> {
+ return apiFetchJSON(`${this.baseUrl}/deadman/config`, options) as Promise<{
pingUrl: string;
configured: boolean;
}>;
}
- static async updateDeadManConfig(pingUrl: string): Promise<{
+ static async updateDeadManConfig(
+ pingUrl: string,
+ options?: APIContextOptions,
+ ): Promise<{
success: boolean;
configured: boolean;
}> {
return apiFetchJSON(`${this.baseUrl}/deadman/config`, {
+ ...options,
method: 'PUT',
body: JSON.stringify({ pingUrl }),
}) as Promise<{ success: boolean; configured: boolean }>;
diff --git a/frontend-modern/src/api/notifications.ts b/frontend-modern/src/api/notifications.ts
index 87a63eabfd..edf37d338b 100644
--- a/frontend-modern/src/api/notifications.ts
+++ b/frontend-modern/src/api/notifications.ts
@@ -1,4 +1,4 @@
-import { apiFetchJSON } from '@/utils/apiClient';
+import { apiFetchJSON, type APIContextOptions } from '@/utils/apiClient';
import {
arrayOrEmpty,
finiteNumberOrUndefined,
@@ -258,12 +258,12 @@ function normalizeFailureClassCounts(value: unknown): NotificationFailureClassCo
export class NotificationsAPI {
private static baseUrl = '/api/notifications';
- static async getAppriseConfig(): Promise<AppriseConfig> {
- return apiFetchJSON(`${this.baseUrl}/apprise`);
+ static async getAppriseConfig(options?: APIContextOptions): Promise<AppriseConfig> {
+ return apiFetchJSON(`${this.baseUrl}/apprise`, options);
}
- static async getHealth(): Promise<NotificationHealth> {
- const payload = await apiFetchJSON<Record<string, unknown>>(`${this.baseUrl}/health`);
+ static async getHealth(options?: APIContextOptions): Promise<NotificationHealth> {
+ const payload = await apiFetchJSON<Record<string, unknown>>(`${this.baseUrl}/health`, options);
const queue = apiRecord(payload.queue);
const pending = nonNegativeCount(queue.pending);
const sending = nonNegativeCount(queue.sending);
@@ -351,10 +351,14 @@ export class NotificationsAPI {
};
}
- static async getDeliveryLog(limit?: number): Promise<NotificationDeliveryLog> {
+ static async getDeliveryLog(
+ limit?: number,
+ options?: APIContextOptions,
+ ): Promise<NotificationDeliveryLog> {
const query = limit && limit > 0 ? `?limit=${limit}` : '';
const payload = await apiFetchJSON<Record<string, unknown>>(
`${this.baseUrl}/delivery-log${query}`,
+ options,
);
const rawEntries = arrayOrEmpty<unknown>(payload.entries);
const entries: NotificationDeliveryLogEntry[] = [];
@@ -383,10 +387,12 @@ export class NotificationsAPI {
};
}
- static async retryTerminalFailures(): Promise<NotificationTerminalFailureActionResult> {
+ static async retryTerminalFailures(
+ options?: APIContextOptions,
+ ): Promise<NotificationTerminalFailureActionResult> {
const payload = await apiFetchJSON<Record<string, unknown>>(
`${this.baseUrl}/terminal-failures/retry`,
- { method: 'POST' },
+ { ...options, method: 'POST' },
);
return {
success: strictBoolean(payload.success),
@@ -394,10 +400,12 @@ export class NotificationsAPI {
};
}
- static async dismissTerminalFailures(): Promise<NotificationTerminalFailureActionResult> {
+ static async dismissTerminalFailures(
+ options?: APIContextOptions,
+ ): Promise<NotificationTerminalFailureActionResult> {
const payload = await apiFetchJSON<Record<string, unknown>>(
`${this.baseUrl}/terminal-failures/dismiss`,
- { method: 'POST' },
+ { ...options, method: 'POST' },
);
return {
success: strictBoolean(payload.success),
@@ -405,16 +413,23 @@ export class NotificationsAPI {
};
}
- static async updateAppriseConfig(config: AppriseConfig): Promise<AppriseConfig> {
+ static async updateAppriseConfig(
+ config: AppriseConfig,
+ options?: APIContextOptions,
+ ): Promise<AppriseConfig> {
return apiFetchJSON(`${this.baseUrl}/apprise`, {
+ ...options,
method: 'PUT',
body: JSON.stringify(config),
});
}
// Email configuration
- static async getEmailConfig(): Promise<EmailConfig> {
- const backendConfig = await apiFetchJSON<Record<string, unknown>>(`${this.baseUrl}/email`);
+ static async getEmailConfig(options?: APIContextOptions): Promise<EmailConfig> {
+ const backendConfig = await apiFetchJSON<Record<string, unknown>>(
+ `${this.baseUrl}/email`,
+ options,
+ );
const port = finiteNumberOrUndefined(backendConfig.port);
// Backend already returns fields with correct names (server, port)
@@ -444,7 +459,10 @@ export class NotificationsAPI {
return config;
}
- static async updateEmailConfig(config: EmailConfig): Promise<{ success: boolean }> {
+ static async updateEmailConfig(
+ config: EmailConfig,
+ options?: APIContextOptions,
+ ): Promise<{ success: boolean }> {
// Backend expects fields with these names (server, port)
const backendConfig: Record<string, unknown> = {
enabled: config.enabled,
@@ -477,33 +495,47 @@ export class NotificationsAPI {
}
return apiFetchJSON(`${this.baseUrl}/email`, {
+ ...options,
method: 'PUT',
body: JSON.stringify(backendConfig),
});
}
// Webhook management
- static async getWebhooks(): Promise<Webhook[]> {
- const data = await apiFetchJSON<Webhook[] | null>(`${this.baseUrl}/webhooks`);
+ static async getWebhooks(options?: APIContextOptions): Promise<Webhook[]> {
+ const data = await apiFetchJSON<Webhook[] | null>(`${this.baseUrl}/webhooks`, options);
return arrayOrEmpty<Webhook>(data);
}
- static async createWebhook(webhook: Omit<Webhook, 'id'>): Promise<Webhook> {
+ static async createWebhook(
+ webhook: Omit<Webhook, 'id'>,
+ options?: APIContextOptions,
+ ): Promise<Webhook> {
return apiFetchJSON(`${this.baseUrl}/webhooks`, {
+ ...options,
method: 'POST',
body: JSON.stringify(webhook),
});
}
- static async updateWebhook(id: string, webhook: Partial<Webhook>): Promise<Webhook> {
+ static async updateWebhook(
+ id: string,
+ webhook: Partial<Webhook>,
+ options?: APIContextOptions,
+ ): Promise<Webhook> {
return apiFetchJSON(`${this.baseUrl}/webhooks/${encodeURIComponent(id)}`, {
+ ...options,
method: 'PUT',
body: JSON.stringify(webhook),
});
}
- static async deleteWebhook(id: string): Promise<{ success: boolean }> {
+ static async deleteWebhook(
+ id: string,
+ options?: APIContextOptions,
+ ): Promise<{ success: boolean }> {
return apiFetchJSON(`${this.baseUrl}/webhooks/${encodeURIComponent(id)}`, {
+ ...options,
method: 'DELETE',
});
}
@@ -518,7 +550,10 @@ export class NotificationsAPI {
}
// Testing
- static async testNotification(request: NotificationTestRequest): Promise<NotificationTestResult> {
+ static async testNotification(
+ request: NotificationTestRequest,
+ options?: APIContextOptions,
+ ): Promise<NotificationTestResult> {
const body: {
method: string;
config?: Record<string, unknown> | AppriseConfig;
@@ -538,6 +573,7 @@ export class NotificationsAPI {
}
return apiFetchJSON(`${this.baseUrl}/test`, {
+ ...options,
method: 'POST',
body: JSON.stringify(body),
});
@@ -545,8 +581,10 @@ export class NotificationsAPI {
static async testWebhook(
webhook: Omit<Webhook, 'id'>,
+ options?: APIContextOptions,
): Promise<{ success?: boolean; message?: string; deliveryPaused?: boolean }> {
return apiFetchJSON(`${this.baseUrl}/webhooks/test`, {
+ ...options,
method: 'POST',
body: JSON.stringify(webhook),
});
diff --git a/frontend-modern/src/api/relay.ts b/frontend-modern/src/api/relay.ts
index cd427652ed..0014b79762 100644
--- a/frontend-modern/src/api/relay.ts
+++ b/frontend-modern/src/api/relay.ts
@@ -1,4 +1,4 @@
-import { apiFetchJSON } from '@/utils/apiClient';
+import { apiFetchJSON, type APIContextOptions } from '@/utils/apiClient';
export interface RelayConfig {
enabled: boolean;
@@ -17,14 +17,16 @@ export interface RelayStatus {
export class RelayAPI {
private static baseUrl = '/api/settings/relay';
- static async getConfig(): Promise<RelayConfig> {
- return apiFetchJSON(this.baseUrl) as Promise<RelayConfig>;
+ static async getConfig(options?: APIContextOptions): Promise<RelayConfig> {
+ return apiFetchJSON(this.baseUrl, options) as Promise<RelayConfig>;
}
static async updateConfig(
update: Partial<Pick<RelayConfig, 'enabled' | 'server_url' | 'alert_minimum_severity'>>,
+ options?: APIContextOptions,
): Promise<void> {
await apiFetchJSON(this.baseUrl, {
+ ...options,
method: 'PUT',
body: JSON.stringify(update),
});
diff --git a/frontend-modern/src/features/alerts/__tests__/DestinationsTab.recoveryediting.test.tsx b/frontend-modern/src/features/alerts/__tests__/DestinationsTab.recoveryediting.test.tsx
index 7c13a54495..adb41fbeb8 100644
--- a/frontend-modern/src/features/alerts/__tests__/DestinationsTab.recoveryediting.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/DestinationsTab.recoveryediting.test.tsx
@@ -104,6 +104,47 @@ function degradedHealth(): NotificationHealth {
}
describe('DestinationsTab recovery while editing SMTP', () => {
+ it('withdraws saved destination details and all editors during a failed read, then recovers explicitly', async () => {
+ const [emailConfig, setEmailConfig] = createSignal(buildEmailConfig());
+ const [appriseConfig, setAppriseConfig] = createSignal(buildAppriseConfig());
+ const [error, setError] = createSignal<string | null>(null);
+ const [loading, setLoading] = createSignal(false);
+ const retry = vi.fn();
+ render(() => (
+ <DestinationsTab
+ emailConfig={emailConfig}
+ setEmailConfig={setEmailConfig}
+ appriseConfig={appriseConfig}
+ setAppriseConfig={setAppriseConfig}
+ setHasUnsavedChanges={vi.fn()}
+ configLoadError={error}
+ isRetrying={() => false}
+ isLoadingDestinations={loading}
+ onRetryLoad={retry}
+ webhooks={() => []}
+ deadManPingUrl={() => ''}
+ setDeadManPingUrl={vi.fn()}
+ pushMinimumSeverity={() => 'all'}
+ setPushMinimumSeverity={vi.fn()}
+ />
+ ));
+ await screen.findByRole('textbox', { name: 'SMTP server' });
+ setLoading(true);
+ expect(screen.queryByRole('textbox', { name: 'SMTP server' })).not.toBeInTheDocument();
+ setError('Unable to load notification settings.');
+ setLoading(false);
+ expect(screen.queryByRole('textbox', { name: 'SMTP server' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Test/ })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Retry', exact: true }));
+ expect(retry).toHaveBeenCalledOnce();
+ expect(screen.getByText(/Destination details and controls stay hidden/)).toBeInTheDocument();
+ setEmailConfig({ ...emailConfig(), server: 'smtp.current.example.test' });
+ setError(null);
+ expect(await screen.findByRole('textbox', { name: 'SMTP server' })).toHaveValue(
+ 'smtp.current.example.test',
+ );
+ });
+
beforeEach(() => {
vi.resetAllMocks();
setActiveLocale(DEFAULT_LOCALE);
diff --git a/frontend-modern/src/features/alerts/__tests__/alertSettingsSave.acknowledgement.test.tsx b/frontend-modern/src/features/alerts/__tests__/alertSettingsSave.acknowledgement.test.tsx
index 53a52638f1..c722907bbf 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertSettingsSave.acknowledgement.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/alertSettingsSave.acknowledgement.test.tsx
@@ -125,12 +125,15 @@ describe('alert settings save acknowledgement', () => {
expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledWith(
expect.objectContaining({ server: 'smtp.first.example.test' }),
+ { expectedOrgID: 'default', retry: false },
);
expect(NotificationsAPI.updateAppriseConfig).toHaveBeenCalledWith(
expect.objectContaining({ serverUrl: 'https://apprise.first.example.test' }),
+ { expectedOrgID: 'default', retry: false },
);
expect(AlertsAPI.updateDeadManConfig).toHaveBeenCalledWith(
'https://watchdog.example.test/first',
+ { expectedOrgID: 'default', retry: false },
);
expect(result.emailConfig().server).toBe('smtp.newer.example.test');
expect(result.appriseConfig().serverUrl).toBe('https://apprise.newer.example.test');
@@ -160,6 +163,7 @@ describe('alert settings save acknowledgement', () => {
await result.saveAlertConfiguration();
expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledWith(
expect.objectContaining({ server: 'smtp.loaded.example.test' }),
+ { expectedOrgID: 'default', retry: false },
);
expect(result.dirty()).toBe(false);
});
@@ -226,6 +230,7 @@ describe('alert settings save acknowledgement', () => {
await result.saveAlertConfiguration();
expect(NotificationsAPI.updateEmailConfig).toHaveBeenLastCalledWith(
expect.objectContaining({ server: 'smtp.newer.example.test' }),
+ { expectedOrgID: 'default', retry: false },
);
expect(result.dirty()).toBe(false);
});
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
index e8372c6dd7..ec980b3f94 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsState.test.tsx
@@ -6,6 +6,7 @@ import { NotificationsAPI } from '@/api/notifications';
import { AlertsAPI } from '@/api/alerts';
import { RelayAPI } from '@/api/relay';
import { hasFeature } from '@/stores/license';
+import { setOrgID } from '@/utils/apiClient';
import { useAlertDestinationsState } from '../useAlertDestinationsState';
@@ -45,6 +46,7 @@ vi.mock('@/utils/logger', () => ({
describe('useAlertDestinationsState', () => {
beforeEach(() => {
+ setOrgID('default');
vi.mocked(NotificationsAPI.getEmailConfig).mockReset();
vi.mocked(NotificationsAPI.getAppriseConfig).mockReset();
vi.mocked(NotificationsAPI.getWebhooks).mockReset();
@@ -56,6 +58,10 @@ describe('useAlertDestinationsState', () => {
vi.mocked(RelayAPI.updateConfig).mockReset();
vi.mocked(hasFeature).mockReset();
vi.mocked(hasFeature).mockReturnValue(true);
+ vi.mocked(NotificationsAPI.getEmailConfig).mockResolvedValue({ enabled: false } as never);
+ vi.mocked(NotificationsAPI.getAppriseConfig).mockResolvedValue({ enabled: false } as never);
+ vi.mocked(NotificationsAPI.getWebhooks).mockResolvedValue([]);
+ vi.mocked(AlertsAPI.getDeadManConfig).mockResolvedValue({ pingUrl: '', configured: false });
});
it('owns alert destinations reload and save behavior separately from alert policy config', async () => {
@@ -168,6 +174,7 @@ describe('useAlertDestinationsState', () => {
expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledWith(
expect.objectContaining({ server: 'smtp.internal', rateLimit: 17 }),
+ { expectedOrgID: 'default', retry: false },
);
expect(NotificationsAPI.updateAppriseConfig).toHaveBeenCalledWith(
expect.objectContaining({
@@ -175,11 +182,16 @@ describe('useAlertDestinationsState', () => {
serverUrl: 'https://apprise.internal',
targets: ['https://notify.internal'],
}),
+ { expectedOrgID: 'default', retry: false },
);
expect(AlertsAPI.updateDeadManConfig).toHaveBeenCalledWith(
'https://watchdog.example.test/ping/replacement-token',
+ { expectedOrgID: 'default', retry: false },
+ );
+ expect(RelayAPI.updateConfig).toHaveBeenCalledWith(
+ { alert_minimum_severity: 'all' },
+ { expectedOrgID: 'default', retry: false },
);
- expect(RelayAPI.updateConfig).toHaveBeenCalledWith({ alert_minimum_severity: 'all' });
expect(result.appriseConfig().mode).toBe('http');
expect(result.appriseConfig().serverUrl).toBe('https://apprise.example.test');
@@ -231,6 +243,7 @@ describe('useAlertDestinationsState', () => {
}));
vi.mocked(AlertsAPI.updateDeadManConfig).mockResolvedValue({ success: true, configured: true });
const { result } = renderHook(() => useAlertDestinationsState({ activeTab: () => 'overview' }));
+ await result.loadDestinations();
result.setAppriseConfig({
...result.appriseConfig(),
serverUrl: 'https://first.example.test',
@@ -252,9 +265,11 @@ describe('useAlertDestinationsState', () => {
serverUrl: 'https://first.example.test',
apiKey: 'synthetic-first',
}),
+ { expectedOrgID: 'default', retry: false },
);
expect(AlertsAPI.updateDeadManConfig).toHaveBeenCalledWith(
'https://watchdog.example.test/first',
+ { expectedOrgID: 'default', retry: false },
);
expect(result.appriseConfig().serverUrl).toBe('https://newer.example.test');
expect(result.appriseConfig().apiKey).toBe('synthetic-newer');
@@ -279,7 +294,11 @@ describe('useAlertDestinationsState', () => {
const { result } = renderHook(() => useAlertDestinationsState({ activeTab: () => 'overview' }));
const oldRead = result.loadDestinations({ indicateLoading: true });
expect(result.isLoadingDestinations()).toBe(true);
+ const obsoleteSignal = vi.mocked(NotificationsAPI.getEmailConfig).mock.calls.at(-1)![0]!
+ .signal!;
+ expect(obsoleteSignal.aborted).toBe(false);
result.resetDestinations();
+ expect(obsoleteSignal.aborted).toBe(true);
expect(result.isLoadingDestinations()).toBe(false);
await result.loadDestinations();
acknowledgeOldRead({ enabled: true, server: 'smtp.old.example.test' } as never);
@@ -289,6 +308,97 @@ describe('useAlertDestinationsState', () => {
expect(result.emailConfig().server).toBe('smtp.current.example.test');
});
+ it.each(['email', 'apprise', 'watchdog', 'webhooks', 'push'] as const)(
+ 'withdraws the whole saved snapshot when the %s read fails, without writing defaults',
+ async (failed) => {
+ vi.mocked(NotificationsAPI.getEmailConfig).mockResolvedValue({
+ enabled: true,
+ server: 'smtp.private.example.test',
+ } as never);
+ vi.mocked(NotificationsAPI.getAppriseConfig).mockResolvedValue({
+ enabled: true,
+ serverUrl: 'https://apprise.private.example.test',
+ apiKey: 'synthetic-private',
+ } as never);
+ vi.mocked(AlertsAPI.getDeadManConfig).mockResolvedValue({
+ pingUrl: 'https://watchdog.private.example.test',
+ configured: true,
+ });
+ vi.mocked(NotificationsAPI.getWebhooks).mockResolvedValue([
+ { id: 'private-id', name: 'Private destination', url: 'https://private.example.test' },
+ ] as never);
+ vi.mocked(RelayAPI.getConfig).mockResolvedValue({
+ enabled: true,
+ server_url: 'wss://push.example.test',
+ alert_minimum_severity: 'critical',
+ });
+ const { result } = renderHook(() =>
+ useAlertDestinationsState({ activeTab: () => 'destinations' }),
+ );
+ await result.loadDestinations();
+ expect(result.emailConfig().server).toBe('smtp.private.example.test');
+ result.setAppriseConfig({ ...result.appriseConfig(), apiKey: 'synthetic-draft' });
+ const endpoints = {
+ email: NotificationsAPI.getEmailConfig,
+ apprise: NotificationsAPI.getAppriseConfig,
+ watchdog: AlertsAPI.getDeadManConfig,
+ webhooks: NotificationsAPI.getWebhooks,
+ push: RelayAPI.getConfig,
+ };
+ vi.mocked(endpoints[failed]).mockRejectedValueOnce(new Error('private-provider-response'));
+ const reload = result.loadDestinations();
+ expect(result.isLoadingDestinations()).toBe(true);
+ expect(result.emailConfig().server).toBe('');
+ expect(result.appriseConfig().apiKey).toBe('');
+ expect(result.webhooks()).toEqual([]);
+ expect(result.deadManPingUrl()).toBe('');
+ await reload;
+ expect(result.destConfigLoadError()).toContain('Unable to load notification settings');
+ expect(result.emailConfig().server).toBe('');
+ expect(result.appriseConfig().serverUrl).toBe('');
+ expect(result.webhooks()).toEqual([]);
+ expect(result.deadManPingUrl()).toBe('');
+ await result.saveDestinations();
+ expect(NotificationsAPI.updateEmailConfig).not.toHaveBeenCalled();
+ expect(NotificationsAPI.updateAppriseConfig).not.toHaveBeenCalled();
+ expect(AlertsAPI.updateDeadManConfig).not.toHaveBeenCalled();
+ await result.loadDestinations();
+ expect(result.destConfigLoadError()).toBeNull();
+ expect(result.emailConfig().server).toBe('smtp.private.example.test');
+ expect(NotificationsAPI.getEmailConfig).toHaveBeenLastCalledWith({
+ expectedOrgID: 'default',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ cache: 'no-store',
+ });
+ },
+ );
+
+ it('does not publish a late read or send downstream saves after a silent workspace change', async () => {
+ vi.mocked(hasFeature).mockReturnValue(false);
+ const { result } = renderHook(() => useAlertDestinationsState({ activeTab: () => 'overview' }));
+ await result.loadDestinations();
+ let accept!: (value: { success: boolean }) => void;
+ vi.mocked(NotificationsAPI.updateEmailConfig).mockReturnValueOnce(
+ new Promise((resolve) => {
+ accept = resolve;
+ }),
+ );
+ const save = result.saveDestinations();
+ setOrgID('tenant-b');
+ accept({ success: true });
+ await save;
+ expect(NotificationsAPI.updateEmailConfig).toHaveBeenCalledWith(expect.anything(), {
+ expectedOrgID: 'default',
+ retry: false,
+ });
+ expect(NotificationsAPI.updateAppriseConfig).not.toHaveBeenCalled();
+ expect(AlertsAPI.updateDeadManConfig).not.toHaveBeenCalled();
+ await result.loadDestinations();
+ expect(NotificationsAPI.getEmailConfig).toHaveBeenCalledTimes(1);
+ setOrgID('default');
+ });
+
it('does not refresh destinations before the policy owner admits a loaded context', async () => {
vi.mocked(hasFeature).mockReturnValue(false);
vi.mocked(NotificationsAPI.getEmailConfig).mockResolvedValue({
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx
index 00518bb4e5..a775693201 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx
@@ -78,6 +78,50 @@ const buildAppriseConfig = (): UIAppriseConfig => ({
});
describe('useAlertDestinationsTabState', () => {
+ it.each(['email', 'apprise'] as const)(
+ 'does not announce a late %s Test after the editor is withdrawn',
+ async (kind) => {
+ vi.mocked(NotificationsAPI.getHealth).mockResolvedValue({
+ queue: { status: 'healthy' },
+ } as never);
+ vi.mocked(NotificationsAPI.getDeliveryLog).mockResolvedValue({ entries: [] } as never);
+ vi.mocked(AlertsAPI.getEvents).mockResolvedValue([]);
+ const [appriseConfig, setAppriseConfig] = createSignal(buildAppriseConfig());
+ let accept!: (value: { success: boolean }) => void;
+ vi.mocked(NotificationsAPI.testNotification).mockReturnValueOnce(
+ new Promise((resolve) => {
+ accept = resolve;
+ }),
+ );
+ const { result, cleanup } = renderHook(() =>
+ useAlertDestinationsTabState({
+ appriseConfig,
+ setAppriseConfig,
+ emailConfig: () => buildEmailConfig(),
+ configLoadError: () => null,
+ isRetrying: () => false,
+ isLoadingDestinations: () => false,
+ onRetryLoad: vi.fn(),
+ webhooks: () => [],
+ }),
+ );
+ const pending = kind === 'email' ? result.testEmailConfig() : result.testApprise();
+ expect(NotificationsAPI.testNotification).toHaveBeenCalledOnce();
+ cleanup();
+ vi.mocked(notificationStore.success).mockClear();
+ vi.mocked(notificationStore.warning).mockClear();
+ vi.mocked(showErrorWithDetail).mockClear();
+ accept({ success: true });
+ await pending;
+ expect(notificationStore.success).not.toHaveBeenCalled();
+ expect(notificationStore.warning).not.toHaveBeenCalled();
+ expect(showErrorWithDetail).not.toHaveBeenCalled();
+ await result.testEmailConfig();
+ await result.testApprise();
+ expect(NotificationsAPI.testNotification).toHaveBeenCalledOnce();
+ },
+ );
+
describe.each(['retryTerminalFailures', 'dismissTerminalFailures'] as const)(
'%s view replacement',
(action) => {
@@ -380,6 +424,7 @@ describe('useAlertDestinationsTabState', () => {
types: ['notification_suppressed', 'notification_deferred'],
limit: 100,
}),
+ { expectedOrgID: 'default', retry: false },
);
expect(result.deliveryHealth()?.queue.status).toBe('healthy');
expect(result.deliveryLog()?.entries).toHaveLength(1);
@@ -394,6 +439,7 @@ describe('useAlertDestinationsTabState', () => {
await result.testEmailConfig();
expect(NotificationsAPI.testNotification).toHaveBeenCalledWith(
expect.objectContaining({ type: 'email' }),
+ { expectedOrgID: 'default', retry: false },
);
await result.testApprise();
@@ -405,6 +451,7 @@ describe('useAlertDestinationsTabState', () => {
targets: ['mailto://[email protected]'],
}),
}),
+ { expectedOrgID: 'default', retry: false },
);
expect(result.webhooks()).toEqual([
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsx
index 61cc1e83f1..6b931d79f3 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertWebhookDestinationsState.test.tsx
@@ -112,10 +112,13 @@ describe('useAlertWebhookDestinationsState', () => {
);
await result.testWebhook('hook-2');
- expect(NotificationsAPI.testNotification).toHaveBeenCalledWith({
- type: 'webhook',
- webhookId: 'hook-2',
- });
+ expect(NotificationsAPI.testNotification).toHaveBeenCalledWith(
+ {
+ type: 'webhook',
+ webhookId: 'hook-2',
+ },
+ { expectedOrgID: 'default', retry: false },
+ );
await result.deleteWebhook('hook-1');
expect(result.webhooks().map((hook) => hook.id)).toEqual(['hook-2']);
diff --git a/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx b/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
index 2c1a804600..b4f7092406 100644
--- a/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
+++ b/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
@@ -28,6 +28,28 @@ export interface DestinationsTabProps extends AlertDestinationsTabStateProps {
}
export function DestinationsTab(props: DestinationsTabProps) {
+ return (
+ <Show
+ when={!props.isLoadingDestinations() && !props.isRetrying()}
+ fallback={<AlertDestinationsLoadingState />}
+ >
+ <Show
+ when={!props.configLoadError()}
+ fallback={
+ <AlertDestinationsLoadErrorCard
+ error={props.configLoadError() || ''}
+ isRetrying={props.isRetrying()}
+ onRetry={props.onRetryLoad}
+ />
+ }
+ >
+ <LoadedDestinationsTab {...props} />
+ </Show>
+ </Show>
+ );
+}
+
+function LoadedDestinationsTab(props: DestinationsTabProps) {
const state = useAlertDestinationsTabState(props);
// Destinations configured here are inert while delivery is gated off, so the
// pause has to be visible on this surface rather than only on the overview.
@@ -91,47 +113,51 @@ export function DestinationsTab(props: DestinationsTabProps) {
Teams, Slack) come first because they are what most installs use, and
delivery activity follows the destinations.
*/}
- <AlertWebhookDestinationsSection
- webhooks={state.webhooks()}
- addWebhook={state.addWebhook}
- updateWebhook={state.updateWebhook}
- deleteWebhook={state.deleteWebhook}
- testWebhook={state.testWebhook}
- testingWebhook={state.testingWebhook()}
- />
+ <Show when={!state.hasLoadError()}>
+ <AlertWebhookDestinationsSection
+ webhooks={state.webhooks()}
+ addWebhook={state.addWebhook}
+ updateWebhook={state.updateWebhook}
+ deleteWebhook={state.deleteWebhook}
+ testWebhook={state.testWebhook}
+ testingWebhook={state.testingWebhook()}
+ />
- <AlertEmailDestinationsSection
- config={props.emailConfig()}
- setConfig={props.setEmailConfig}
- setHasUnsavedChanges={props.setHasUnsavedChanges}
- onTest={state.testEmailConfig}
- testing={state.testingEmail()}
- />
+ <AlertEmailDestinationsSection
+ config={props.emailConfig()}
+ setConfig={props.setEmailConfig}
+ setHasUnsavedChanges={props.setHasUnsavedChanges}
+ onTest={state.testEmailConfig}
+ testing={state.testingEmail()}
+ />
- <AlertAppriseDestinationsSection
- config={state.appriseState()}
- updateApprise={state.updateApprise}
- setHasUnsavedChanges={props.setHasUnsavedChanges}
- onTest={state.testApprise}
- testing={state.testingApprise()}
- />
+ <AlertAppriseDestinationsSection
+ config={state.appriseState()}
+ updateApprise={state.updateApprise}
+ setHasUnsavedChanges={props.setHasUnsavedChanges}
+ onTest={state.testApprise}
+ testing={state.testingApprise()}
+ />
+ </Show>
<Show when={!state.deliveryNeedsAttention()}>{deliveryLog()}</Show>
- <AlertDeadManDestinationSection
- pingUrl={props.deadManPingUrl}
- setPingUrl={props.setDeadManPingUrl}
- setHasUnsavedChanges={props.setHasUnsavedChanges}
- />
+ <Show when={!state.hasLoadError()}>
+ <AlertDeadManDestinationSection
+ pingUrl={props.deadManPingUrl}
+ setPingUrl={props.setDeadManPingUrl}
+ setHasUnsavedChanges={props.setHasUnsavedChanges}
+ />
- <AlertPushDestinationsSection
- relayLicensed={hasFeature('relay')}
- minimumSeverity={props.pushMinimumSeverity()}
- onMinimumSeverityChange={(minimumSeverity) => {
- props.setPushMinimumSeverity(minimumSeverity);
- props.setHasUnsavedChanges(true);
- }}
- />
+ <AlertPushDestinationsSection
+ relayLicensed={hasFeature('relay')}
+ minimumSeverity={props.pushMinimumSeverity()}
+ onMinimumSeverityChange={(minimumSeverity) => {
+ props.setPushMinimumSeverity(minimumSeverity);
+ props.setHasUnsavedChanges(true);
+ }}
+ />
+ </Show>
</Show>
</div>
);
diff --git a/frontend-modern/src/features/alerts/useAlertDestinationsState.ts b/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
index 479c612b3b..fc49cbc496 100644
--- a/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
+++ b/frontend-modern/src/features/alerts/useAlertDestinationsState.ts
@@ -8,6 +8,7 @@ import { RelayAPI } from '@/api/relay';
import { hasFeature } from '@/stores/license';
import { getAlertDestinationsConfigLoadError } from '@/utils/alertDestinationsPresentation';
import { logger } from '@/utils/logger';
+import { getOrgID } from '@/utils/apiClient';
import {
buildAppriseConfigPayload,
@@ -21,9 +22,11 @@ import type { AlertTab, UIAppriseConfig, UIEmailConfig } from './types';
interface AlertDestinationsStateOptions {
activeTab: Accessor<AlertTab>;
canReload?: Accessor<boolean>;
+ isCurrentReader?: Accessor<boolean>;
}
export function useAlertDestinationsState(options: AlertDestinationsStateOptions) {
+ let hasLoadedDestinations = false;
const [isLoadingDestinations, setIsLoadingDestinations] = createSignal(false);
const [destConfigLoadError, setDestConfigLoadError] = createSignal<string | null>(null);
const [emailConfig, setEmailConfig] = createSignal<UIEmailConfig>(createDefaultEmailConfig());
@@ -36,12 +39,23 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
let reloadVersion = 0;
let lastActiveTab: AlertTab | null = null;
+ let disposed = false;
+ let readController: AbortController | undefined;
+ const org = getOrgID() || 'default';
+ const requestOptions = { expectedOrgID: org, retry: false } as const;
+ const isCurrentReader = () =>
+ !disposed && options.isCurrentReader?.() !== false && (getOrgID() || 'default') === org;
onCleanup(() => {
+ disposed = true;
++reloadVersion;
+ readController?.abort();
});
const resetDestinations = () => {
+ readController?.abort();
+ readController = undefined;
+ hasLoadedDestinations = false;
++reloadVersion;
setIsLoadingDestinations(false);
setDestConfigLoadError(null);
@@ -52,23 +66,42 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
setWebhooks([]);
};
- const loadDestinations = async (options: { indicateLoading?: boolean } = {}) => {
- const indicateLoading = options.indicateLoading ?? false;
+ const loadDestinations = async (_options: { indicateLoading?: boolean } = {}) => {
+ if (!isCurrentReader()) return;
+ // A refresh withdraws the previous snapshot, including unsaved private
+ // values. A partial read is not permission to edit or test empty defaults.
+ resetDestinations();
const thisVersion = ++reloadVersion;
-
- if (indicateLoading) {
- setIsLoadingDestinations(true);
- }
+ const controller = new AbortController();
+ readController = controller;
+ const readOptions = {
+ ...requestOptions,
+ cache: 'no-store' as const,
+ signal: controller.signal,
+ };
+ setIsLoadingDestinations(true);
const results = await Promise.allSettled([
- NotificationsAPI.getEmailConfig(),
- NotificationsAPI.getAppriseConfig(),
- AlertsAPI.getDeadManConfig(),
- hasFeature('relay') ? RelayAPI.getConfig() : Promise.resolve(null),
- NotificationsAPI.getWebhooks(),
+ NotificationsAPI.getEmailConfig(readOptions),
+ NotificationsAPI.getAppriseConfig(readOptions),
+ AlertsAPI.getDeadManConfig(readOptions),
+ hasFeature('relay') ? RelayAPI.getConfig(readOptions) : Promise.resolve(null),
+ NotificationsAPI.getWebhooks(readOptions),
]);
- if (thisVersion !== reloadVersion) {
+ if (thisVersion !== reloadVersion || !isCurrentReader()) {
+ return;
+ }
+ readController = undefined;
+
+ const failures = results.filter(
+ (result): result is PromiseRejectedResult => result.status === 'rejected',
+ );
+ if (failures.length > 0) {
+ // Do not put provider-controlled details (URLs or credentials) in feedback.
+ logger.error('Failed to load complete notification configuration');
+ setDestConfigLoadError(getAlertDestinationsConfigLoadError());
+ setIsLoadingDestinations(false);
return;
}
@@ -101,22 +134,9 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
);
}
- const failures = results.filter(
- (result): result is PromiseRejectedResult => result.status === 'rejected',
- );
-
- if (failures.length > 0) {
- failures.forEach((result) => {
- logger.error('Failed to load notification configuration:', result.reason);
- });
- setDestConfigLoadError(getAlertDestinationsConfigLoadError());
- } else {
- setDestConfigLoadError(null);
- }
-
- if (indicateLoading) {
- setIsLoadingDestinations(false);
- }
+ setDestConfigLoadError(null);
+ hasLoadedDestinations = true;
+ setIsLoadingDestinations(false);
};
// Capture every endpoint's payload before any write yields. The alert-policy
@@ -132,24 +152,35 @@ export function useAlertDestinationsState(options: AlertDestinationsStateOptions
});
const saveDestinations = async (snapshot = captureDestinations(), ownsSave = () => true) => {
- if (!ownsSave()) return;
- await NotificationsAPI.updateEmailConfig(snapshot.email);
- if (!ownsSave()) return;
-
- const updatedApprise = await NotificationsAPI.updateAppriseConfig(snapshot.apprise);
- if (!ownsSave()) return;
+ const ownsWrite = () =>
+ isCurrentReader() &&
+ hasLoadedDestinations &&
+ ownsSave() &&
+ snapshot.reloadVersion === reloadVersion;
+ if (!ownsWrite()) return;
+ await NotificationsAPI.updateEmailConfig(snapshot.email, requestOptions);
+ if (!ownsWrite()) return;
+
+ const updatedApprise = await NotificationsAPI.updateAppriseConfig(
+ snapshot.apprise,
+ requestOptions,
+ );
+ if (!ownsWrite()) return;
- await AlertsAPI.updateDeadManConfig(snapshot.pingUrl);
- if (!ownsSave()) return;
+ await AlertsAPI.updateDeadManConfig(snapshot.pingUrl, requestOptions);
+ if (!ownsWrite()) return;
if (snapshot.relayEnabled && hasFeature('relay')) {
- await RelayAPI.updateConfig({ alert_minimum_severity: snapshot.pushMinimumSeverity });
+ await RelayAPI.updateConfig(
+ { alert_minimum_severity: snapshot.pushMinimumSeverity },
+ requestOptions,
+ );
}
// 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() &&
+ ownsWrite() &&
reloadVersion === snapshot.reloadVersion &&
appriseConfig() === snapshot.appriseDraft
) {
diff --git a/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts b/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts
index 86c90f37f1..78894b291b 100644
--- a/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts
+++ b/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts
@@ -1,10 +1,11 @@
-import { createMemo, createSignal, onMount, type Accessor } from 'solid-js';
+import { createMemo, createSignal, onCleanup, onMount, type Accessor } from 'solid-js';
import { NotificationsAPI, type AppriseConfig, type Webhook } from '@/api/notifications';
import type { Setter } from 'solid-js';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
import { showErrorWithDetail } from '@/utils/toast';
+import { getOrgID } from '@/utils/apiClient';
import {
getAlertDestinationsAppriseTestFailure,
getAlertDestinationsAppriseTestSuccess,
@@ -33,6 +34,13 @@ export interface AlertDestinationsTabStateProps {
}
export function useAlertDestinationsTabState(props: AlertDestinationsTabStateProps) {
+ const org = getOrgID() || 'default';
+ const requestOptions = { expectedOrgID: org, retry: false } as const;
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ });
+ const isCurrentReader = () => !disposed && (getOrgID() || 'default') === org;
const [testingEmail, setTestingEmail] = createSignal(false);
const [testingApprise, setTestingApprise] = createSignal(false);
const {
@@ -47,7 +55,11 @@ export function useAlertDestinationsTabState(props: AlertDestinationsTabStatePro
retryingTerminalFailures,
dismissTerminalFailures,
dismissingTerminalFailures,
- } = useNotificationDeliveryHealth({ onAfterQueueAction: () => loadDeliveryLog() });
+ } = useNotificationDeliveryHealth({
+ requestOptions,
+ isCurrentReader,
+ onAfterQueueAction: () => loadDeliveryLog(),
+ });
const {
deliveryLog,
deliveryLogUnavailable,
@@ -56,7 +68,7 @@ export function useAlertDestinationsTabState(props: AlertDestinationsTabStatePro
heldEventsUnavailable,
refreshingHeldEvents,
loadDeliveryLog,
- } = useNotificationDeliveryLog();
+ } = useNotificationDeliveryLog({ requestOptions, isCurrentReader });
const webhookState = useAlertWebhookDestinationsState({
webhooks: props.webhooks,
setWebhooks: props.setWebhooks,
@@ -92,29 +104,36 @@ export function useAlertDestinationsTabState(props: AlertDestinationsTabStatePro
};
const testEmailConfig = async () => {
+ if (!isCurrentReader() || hasLoadError() || isLoading() || testingEmail()) return;
setTestingEmail(true);
try {
- const result = await NotificationsAPI.testNotification({
- type: 'email',
- config: { ...props.emailConfig() } as Record<string, unknown>,
- });
+ const result = await NotificationsAPI.testNotification(
+ {
+ type: 'email',
+ config: { ...props.emailConfig() } as Record<string, unknown>,
+ },
+ requestOptions,
+ );
+ if (!isCurrentReader()) return;
if (result.deliveryPaused) {
notificationStore.warning(getAlertDestinationsTestPausedWarning());
} else {
notificationStore.success(getAlertDestinationsEmailTestSuccess());
}
} catch (error) {
+ if (!isCurrentReader()) return;
logger.error(getAlertDestinationsEmailTestFailure(), error);
const message =
error instanceof Error ? error.message : getAlertDestinationsEmailTestFailure();
const detail = (error as Error & { detail?: string })?.detail;
showErrorWithDetail(message, detail);
} finally {
- setTestingEmail(false);
+ if (isCurrentReader()) setTestingEmail(false);
}
};
const testApprise = async () => {
+ if (!isCurrentReader() || hasLoadError() || isLoading() || testingApprise()) return;
setTestingApprise(true);
try {
const config = buildAppriseRequestConfig();
@@ -131,27 +150,33 @@ export function useAlertDestinationsTabState(props: AlertDestinationsTabStatePro
throw new Error(getAlertDestinationsAppriseValidationError('missingServerUrl'));
}
- const result = await NotificationsAPI.testNotification({
- type: 'apprise',
- config,
- });
+ const result = await NotificationsAPI.testNotification(
+ {
+ type: 'apprise',
+ config,
+ },
+ requestOptions,
+ );
+ if (!isCurrentReader()) return;
if (result.deliveryPaused) {
notificationStore.warning(getAlertDestinationsTestPausedWarning());
} else {
notificationStore.success(getAlertDestinationsAppriseTestSuccess());
}
} catch (error) {
+ if (!isCurrentReader()) return;
logger.error(getAlertDestinationsAppriseTestFailure(), error);
const message =
error instanceof Error ? error.message : getAlertDestinationsAppriseTestFailure();
const detail = (error as Error & { detail?: string })?.detail;
showErrorWithDetail(message, detail);
} finally {
- setTestingApprise(false);
+ if (isCurrentReader()) setTestingApprise(false);
}
};
const handleRetry = () => {
+ if (!isCurrentReader()) return;
props.onRetryLoad();
if (props.webhooks === undefined) {
void webhookState.loadWebhooks();
diff --git a/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts b/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts
index 5ca9d83f34..f04e06a9ba 100644
--- a/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts
+++ b/frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts
@@ -4,6 +4,7 @@ import { NotificationsAPI, type Webhook } from '@/api/notifications';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
import { showErrorWithDetail } from '@/utils/toast';
+import { getOrgID } from '@/utils/apiClient';
import {
getAlertDestinationsTestPausedWarning,
getAlertDestinationsWebhookLoadError,
@@ -35,22 +36,29 @@ export function useAlertWebhookDestinationsState(
const [webhookLoadError, setWebhookLoadError] = createSignal<string | null>(null);
const [isLoadingWebhooks, setIsLoadingWebhooks] = createSignal(options.autoLoad !== false);
const [testingWebhook, setTestingWebhook] = createSignal<string | null>(null);
+ const org = getOrgID() || 'default';
+ const requestOptions = { expectedOrgID: org, retry: false } as const;
let disposed = false;
+ const isCurrentReader = () => !disposed && (getOrgID() || 'default') === org;
onCleanup(() => {
disposed = true;
});
const loadWebhooks = async () => {
+ if (!isCurrentReader()) return;
setWebhookLoadError(null);
+ setWebhooks([]);
setIsLoadingWebhooks(true);
try {
- const hooks = await NotificationsAPI.getWebhooks();
+ const hooks = await NotificationsAPI.getWebhooks(requestOptions);
+ if (!isCurrentReader()) return;
setWebhooks(hooks.map(normalizeWebhook));
- } catch (error) {
- logger.error('Failed to load webhooks:', error);
+ } catch {
+ if (!isCurrentReader()) return;
+ logger.error('Failed to load webhooks');
setWebhookLoadError(getAlertDestinationsWebhookLoadError());
} finally {
- setIsLoadingWebhooks(false);
+ if (isCurrentReader()) setIsLoadingWebhooks(false);
}
};
@@ -61,35 +69,38 @@ export function useAlertWebhookDestinationsState(
});
const testWebhook = async (webhookId: string, webhookData?: Omit<Webhook, 'id'>) => {
+ if (!isCurrentReader() || webhookLoadError() || isLoadingWebhooks() || testingWebhook()) return;
setTestingWebhook(webhookId);
try {
const result = webhookData
- ? await NotificationsAPI.testWebhook(webhookData)
- : await NotificationsAPI.testNotification({ type: 'webhook', webhookId });
+ ? await NotificationsAPI.testWebhook(webhookData, requestOptions)
+ : await NotificationsAPI.testNotification({ type: 'webhook', webhookId }, requestOptions);
+ if (!isCurrentReader()) return;
if (result.deliveryPaused) {
notificationStore.warning(getAlertDestinationsTestPausedWarning());
} else {
notificationStore.success(getAlertWebhookTestSuccess());
}
} catch (error) {
+ if (!isCurrentReader()) return;
const message = error instanceof Error ? error.message : getAlertWebhookTestFailure();
const detail = (error as Error & { detail?: string })?.detail;
showErrorWithDetail(message, detail);
} finally {
- setTestingWebhook(null);
+ if (isCurrentReader()) setTestingWebhook(null);
}
};
const addWebhook = async (webhook: Omit<Webhook, 'id'>) => {
- if (disposed) return false;
+ if (!isCurrentReader()) return false;
try {
- const created = await NotificationsAPI.createWebhook(webhook);
- if (disposed) return false;
+ const created = await NotificationsAPI.createWebhook(webhook, requestOptions);
+ if (!isCurrentReader()) return false;
setWebhooks((current) => [...current, normalizeWebhook(created)]);
notificationStore.success(getAlertWebhookMutationSuccess('add'));
return true;
} catch (error) {
- if (disposed) return false;
+ if (!isCurrentReader()) return false;
logger.error('Failed to add webhook:', error);
notificationStore.error(
error instanceof Error ? error.message : getAlertWebhookMutationFailure('add'),
@@ -99,17 +110,17 @@ export function useAlertWebhookDestinationsState(
};
const updateWebhook = async (webhook: Webhook) => {
- if (disposed) return false;
+ if (!isCurrentReader()) return false;
try {
- const updated = await NotificationsAPI.updateWebhook(webhook.id, webhook);
- if (disposed) return false;
+ const updated = await NotificationsAPI.updateWebhook(webhook.id, webhook, requestOptions);
+ if (!isCurrentReader()) 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;
+ if (!isCurrentReader()) return false;
logger.error('Failed to update webhook:', error);
notificationStore.error(
error instanceof Error ? error.message : getAlertWebhookMutationFailure('update'),
@@ -119,10 +130,10 @@ export function useAlertWebhookDestinationsState(
};
const deleteWebhook = async (id: string) => {
- if (disposed) return false;
+ if (!isCurrentReader()) return false;
try {
- const result = await NotificationsAPI.deleteWebhook(id);
- if (disposed) return false;
+ const result = await NotificationsAPI.deleteWebhook(id, requestOptions);
+ if (!isCurrentReader()) return false;
if (result.success !== true) {
throw new Error(getAlertWebhookMutationFailure('delete'));
}
@@ -130,7 +141,7 @@ export function useAlertWebhookDestinationsState(
notificationStore.success(getAlertWebhookMutationSuccess('delete'));
return true;
} catch (error) {
- if (disposed) return false;
+ if (!isCurrentReader()) return false;
logger.error('Failed to delete webhook:', error);
notificationStore.error(
error instanceof Error ? error.message : getAlertWebhookMutationFailure('delete'),
diff --git a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
index 62f2eb2553..c118bf3dde 100644
--- a/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
+++ b/frontend-modern/src/features/alerts/useAlertsConfigurationState.ts
@@ -15,6 +15,7 @@ import {
getAlertConfigSaveSuccess,
} from '@/utils/alertConfigPresentation';
import { logger } from '@/utils/logger';
+import { getOrgID } from '@/utils/apiClient';
import {
ALERT_DOCKER_GAP_VALIDATION_ERROR,
@@ -28,6 +29,7 @@ import { useAlertOverridesState } from './useAlertOverridesState';
import type { AlertTab, Override } from './types';
export interface AlertsConfigurationSurfaceProps {
+ isCurrentReader?: Accessor<boolean>;
activeTab: Accessor<AlertTab>;
allResources: Accessor<Resource[]>;
byType: (resourceType: ResourceType) => Resource[];
@@ -46,6 +48,12 @@ export interface AlertsConfigurationSurfaceProps {
}
export function useAlertsConfigurationState(props: AlertsConfigurationSurfaceProps) {
+ const org = getOrgID() || 'default';
+ const requestOptions = { expectedOrgID: org, retry: false } as const;
+ let disposed = false;
+ let readController: AbortController | undefined;
+ const isCurrentReader = () =>
+ !disposed && props.isCurrentReader?.() !== false && (getOrgID() || 'default') === org;
const alertsActivation = useAlertsActivation();
const [isReloadingConfig, setIsReloadingConfig] = createSignal(false);
const [isConfigLoaded, setIsConfigLoaded] = createSignal(false);
@@ -55,6 +63,7 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
let configurationVersion = 0;
const [suppressDirtyFlag, setSuppressDirtyFlag] = createSignal(false);
const guardedSetHasUnsavedChanges = (value: boolean) => {
+ if (!isCurrentReader()) return;
if (value && suppressDirtyFlag()) return;
if (value) ++draftRevision;
props.setHasUnsavedChanges(value);
@@ -64,6 +73,7 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
});
const destinationsState = useAlertDestinationsState({
activeTab: props.activeTab,
+ isCurrentReader,
canReload: () =>
isConfigLoaded() && !props.hasUnsavedChanges() && !isSavingConfig() && !isReloadingConfig(),
});
@@ -76,7 +86,12 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
});
const loadAlertConfiguration = async (options: { notify?: boolean } = {}) => {
+ if (!isCurrentReader()) return;
+ readController?.abort();
+ const controller = new AbortController();
+ readController = controller;
const thisVersion = ++configurationVersion;
+ const ownsRead = () => isCurrentReader() && 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);
@@ -91,8 +106,12 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
);
try {
- const config = await AlertsAPI.getConfig();
- if (thisVersion !== configurationVersion) return;
+ const config = await AlertsAPI.getConfig({
+ ...requestOptions,
+ cache: 'no-store',
+ signal: controller.signal,
+ });
+ if (!ownsRead()) return;
configurationSnapshotState.applyConfigurationSnapshot(
readAlertsConfigurationSnapshot(config),
);
@@ -100,24 +119,25 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
overridesState.replaceRawOverridesConfig(config.overrides || {});
await destinationsState.loadDestinations();
- if (thisVersion !== configurationVersion) return;
+ if (!ownsRead()) return;
setIsConfigLoaded(true);
if (options.notify) {
notificationStore.success(getAlertConfigDiscardedSuccess());
}
} catch (error) {
- if (thisVersion !== configurationVersion) return;
+ if (!ownsRead()) return;
setConfigLoadError(getAlertConfigLoadError());
logger.error('Failed to load alert configuration:', error);
if (options.notify) {
notificationStore.error(getAlertConfigReloadFailure());
}
} finally {
- if (thisVersion === configurationVersion) {
+ if (ownsRead()) {
+ readController = undefined;
setIsReloadingConfig(false);
queueMicrotask(() => {
- if (thisVersion === configurationVersion) setSuppressDirtyFlag(false);
+ if (ownsRead()) setSuppressDirtyFlag(false);
});
}
}
@@ -125,6 +145,7 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
const saveAlertConfiguration = async () => {
if (
+ !isCurrentReader() ||
!isConfigLoaded() ||
isSavingConfig() ||
isReloadingConfig() ||
@@ -146,11 +167,11 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
const destinationsSnapshot = destinationsState.captureDestinations();
const savedRevision = draftRevision;
const savedVersion = configurationVersion;
- const ownsSave = () => savedVersion === configurationVersion;
+ const ownsSave = () => isCurrentReader() && savedVersion === configurationVersion;
setIsSavingConfig(true);
let configSaved = false;
try {
- await AlertsAPI.updateConfig(result.alertConfig!);
+ await AlertsAPI.updateConfig(result.alertConfig!, requestOptions);
configSaved = true;
if (!ownsSave()) return;
await destinationsState.saveDestinations(destinationsSnapshot, ownsSave);
@@ -172,10 +193,16 @@ export function useAlertsConfigurationState(props: AlertsConfigurationSurfacePro
onMount(() => {
void loadAlertConfiguration();
- const unsubscribeOrgSwitched = eventBus.on('org_switched', () => {
- void loadAlertConfiguration();
- });
+ // The page's keyed reader owns workspace replacement. Standalone callers
+ // without that owner retain the existing explicit reload event.
+ const unsubscribeOrgSwitched = props.isCurrentReader
+ ? () => undefined
+ : eventBus.on('org_switched', () => {
+ void loadAlertConfiguration();
+ });
onCleanup(() => {
+ disposed = true;
+ readController?.abort();
++configurationVersion;
unsubscribeOrgSwitched();
});
diff --git a/frontend-modern/src/features/alerts/useNotificationDeliveryHealth.ts b/frontend-modern/src/features/alerts/useNotificationDeliveryHealth.ts
index 846816253d..4d0fe5688c 100644
--- a/frontend-modern/src/features/alerts/useNotificationDeliveryHealth.ts
+++ b/frontend-modern/src/features/alerts/useNotificationDeliveryHealth.ts
@@ -3,6 +3,7 @@ import { batch, createMemo, createSignal, onCleanup } from 'solid-js';
import { NotificationsAPI, type NotificationHealth } from '@/api/notifications';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
+import type { APIContextOptions } from '@/utils/apiClient';
import {
getAlertDestinationsDeliveryDismissConfirmation,
getAlertDestinationsDeliveryRetryConfirmation,
@@ -15,6 +16,8 @@ import {
// The retained-queue actions live here for the same reason: the warning must
// be clearable wherever it is shown, not only on the destinations tab.
export function useNotificationDeliveryHealth(options?: {
+ requestOptions?: APIContextOptions;
+ isCurrentReader?: () => boolean;
onAfterQueueAction?: () => Promise<unknown> | unknown;
}) {
const [deliveryHealth, setDeliveryHealth] = createSignal<NotificationHealth | null>(null);
@@ -31,13 +34,15 @@ export function useNotificationDeliveryHealth(options?: {
// Mount, configuration retry and queue actions can overlap. Only the latest
// requested snapshot owns health and loading state, regardless of completion order.
let latestHealthRequest = 0;
- const ownsHealthRequest = (request: number) => !disposed && request === latestHealthRequest;
+ const isCurrentReader = () => !disposed && options?.isCurrentReader?.() !== false;
+ const ownsHealthRequest = (request: number) =>
+ isCurrentReader() && request === latestHealthRequest;
const loadDeliveryHealth = async () => {
- if (disposed) return;
+ if (!isCurrentReader()) return;
const request = ++latestHealthRequest;
setRefreshingDeliveryHealth(true);
try {
- const health = await NotificationsAPI.getHealth();
+ const health = await NotificationsAPI.getHealth(options?.requestOptions);
if (!ownsHealthRequest(request)) return;
// Snapshot and availability change together. Set one at a time and
// deliveryNeedsAttention reads a half-updated pair (no health, not yet
@@ -75,18 +80,18 @@ export function useNotificationDeliveryHealth(options?: {
const [queueActionFeedback, setQueueActionFeedback] = createSignal<string | null>(null);
let latestAction = 0;
const clearQueueActionFeedback = () => {
- if (disposed) return;
+ if (!isCurrentReader()) return;
++latestAction;
setQueueActionFeedback(null);
};
const refreshAfterAction = async (action: number) => {
- if (disposed) return;
+ if (!isCurrentReader()) return;
await Promise.all([
loadDeliveryHealth(),
Promise.resolve()
- .then(() => (disposed ? undefined : options?.onAfterQueueAction?.()))
+ .then(() => (!isCurrentReader() ? undefined : options?.onAfterQueueAction?.()))
.catch((error) => {
- if (disposed) return;
+ if (!isCurrentReader()) return;
logger.error(
'Failed to refresh notification activity after accepted queue action',
error,
@@ -104,7 +109,7 @@ export function useNotificationDeliveryHealth(options?: {
const [dismissingTerminalFailures, setDismissingTerminalFailures] = createSignal(false);
const retryTerminalFailures = async () => {
- if (disposed) return;
+ if (!isCurrentReader()) return;
const count = deliveryHealth()?.queue.attentionRequired ?? 0;
if (count <= 0 || !confirm(getAlertDestinationsDeliveryRetryConfirmation(count))) {
return;
@@ -113,25 +118,25 @@ export function useNotificationDeliveryHealth(options?: {
setQueueActionFeedback(null);
setRetryingTerminalFailures(true);
try {
- const result = await NotificationsAPI.retryTerminalFailures();
- if (disposed) return;
+ const result = await NotificationsAPI.retryTerminalFailures(options?.requestOptions);
+ if (!isCurrentReader()) return;
notificationStore.success(
`${result.affected} retained ${result.affected === 1 ? 'delivery' : 'deliveries'} queued for retry.`,
);
await refreshAfterAction(action);
} catch (error) {
- if (disposed) return;
+ if (!isCurrentReader()) return;
logger.error('Failed to retry retained notification deliveries', error);
if (action === latestAction)
setQueueActionFeedback('Unable to retry retained notification deliveries.');
notificationStore.error('Unable to retry retained notification deliveries.');
} finally {
- if (!disposed) setRetryingTerminalFailures(false);
+ if (isCurrentReader()) setRetryingTerminalFailures(false);
}
};
const dismissTerminalFailures = async () => {
- if (disposed) return;
+ if (!isCurrentReader()) return;
const count = deliveryHealth()?.queue.attentionRequired ?? 0;
if (count <= 0 || !confirm(getAlertDestinationsDeliveryDismissConfirmation(count))) {
return;
@@ -140,20 +145,20 @@ export function useNotificationDeliveryHealth(options?: {
setQueueActionFeedback(null);
setDismissingTerminalFailures(true);
try {
- const result = await NotificationsAPI.dismissTerminalFailures();
- if (disposed) return;
+ const result = await NotificationsAPI.dismissTerminalFailures(options?.requestOptions);
+ if (!isCurrentReader()) return;
notificationStore.success(
`${result.affected} retained ${result.affected === 1 ? 'failure' : 'failures'} dismissed.`,
);
await refreshAfterAction(action);
} catch (error) {
- if (disposed) return;
+ if (!isCurrentReader()) return;
logger.error('Failed to dismiss retained notification failures', error);
if (action === latestAction)
setQueueActionFeedback('Unable to dismiss retained notification failures.');
notificationStore.error('Unable to dismiss retained notification failures.');
} finally {
- if (!disposed) setDismissingTerminalFailures(false);
+ if (isCurrentReader()) setDismissingTerminalFailures(false);
}
};
diff --git a/frontend-modern/src/features/alerts/useNotificationDeliveryLog.ts b/frontend-modern/src/features/alerts/useNotificationDeliveryLog.ts
index e36c6036df..9e0463356c 100644
--- a/frontend-modern/src/features/alerts/useNotificationDeliveryLog.ts
+++ b/frontend-modern/src/features/alerts/useNotificationDeliveryLog.ts
@@ -4,6 +4,7 @@ import { AlertsAPI } from '@/api/alerts';
import { NotificationsAPI, type NotificationDeliveryLog } from '@/api/notifications';
import type { AlertEvent } from '@/types/api';
import { logger } from '@/utils/logger';
+import type { APIContextOptions } from '@/utils/apiClient';
const HELD_EVENT_TYPES = ['notification_suppressed', 'notification_deferred'];
const HELD_EVENT_WINDOW_DAYS = 7;
@@ -20,7 +21,10 @@ const DELIVERY_LOG_LIMIT = 200;
// deliberately not attempted, with the mechanism that held them. They come
// from the alert event log and degrade independently — a failed events read
// withdraws the held rows and reports that gap without hiding readable attempts.
-export function useNotificationDeliveryLog() {
+export function useNotificationDeliveryLog(options?: {
+ requestOptions?: APIContextOptions;
+ isCurrentReader?: () => boolean;
+}) {
const [deliveryLog, setDeliveryLog] = createSignal<NotificationDeliveryLog | null>(null);
const [deliveryLogUnavailable, setDeliveryLogUnavailable] = createSignal(false);
const [refreshingDeliveryLog, setRefreshingDeliveryLog] = createSignal(false);
@@ -35,7 +39,8 @@ export function useNotificationDeliveryLog() {
onCleanup(() => {
disposed = true;
});
- const ownsRequest = (request: number) => !disposed && request === latestRequest;
+ const isCurrentReader = () => !disposed && options?.isCurrentReader?.() !== false;
+ const ownsRequest = (request: number) => isCurrentReader() && request === latestRequest;
const loadHeldEvents = async (request: number) => {
setRefreshingHeldEvents(true);
@@ -43,11 +48,14 @@ export function useNotificationDeliveryLog() {
const since = new Date(
Date.now() - HELD_EVENT_WINDOW_DAYS * 24 * 60 * 60 * 1000,
).toISOString();
- const events = await AlertsAPI.getEvents({
- types: HELD_EVENT_TYPES,
- since,
- limit: HELD_EVENT_LIMIT,
- });
+ const events = await AlertsAPI.getEvents(
+ {
+ types: HELD_EVENT_TYPES,
+ since,
+ limit: HELD_EVENT_LIMIT,
+ },
+ options?.requestOptions,
+ );
if (!ownsRequest(request)) return;
setHeldEvents(events);
setHeldEventsUnavailable(false);
@@ -62,7 +70,7 @@ export function useNotificationDeliveryLog() {
};
const loadDeliveryLog = async () => {
- if (disposed) return;
+ if (!isCurrentReader()) return;
const request = ++latestRequest;
setRefreshingDeliveryLog(true);
// Held events refresh independently: they must never delay or fail the
@@ -72,7 +80,9 @@ export function useNotificationDeliveryLog() {
// Request the server's bounded maximum. A degraded queue can retain more
// than the default page of 50 failures, and the evidence view should not
// hide them behind unrelated successful attempts when space is available.
- const log = await NotificationsAPI.getDeliveryLog(DELIVERY_LOG_LIMIT);
+ const log = await (options?.requestOptions
+ ? NotificationsAPI.getDeliveryLog(DELIVERY_LOG_LIMIT, options.requestOptions)
+ : NotificationsAPI.getDeliveryLog(DELIVERY_LOG_LIMIT));
if (!ownsRequest(request)) return;
setDeliveryLog(log);
setDeliveryLogUnavailable(false);
diff --git a/frontend-modern/src/pages/Alerts.tsx b/frontend-modern/src/pages/Alerts.tsx
index 1becee87d5..033bfdd5b2 100644
--- a/frontend-modern/src/pages/Alerts.tsx
+++ b/frontend-modern/src/pages/Alerts.tsx
@@ -43,12 +43,15 @@ import History from 'lucide-solid/icons/history';
import Gauge from 'lucide-solid/icons/gauge';
import Send from 'lucide-solid/icons/send';
import { presentationPolicyIsReadOnly } from '@/stores/sessionPresentationPolicy';
+import type { SecurityStatus } from '@/types/config';
+import { getOrgID } from '@/utils/apiClient';
+import { eventBus } from '@/stores/events';
import { AlertsConfigurationSurface } from '@/features/alerts/AlertsConfigurationSurface';
import { OverviewTab } from '@/features/alerts/OverviewTab';
import { HistoryTab } from '@/features/alerts/tabs/HistoryTab';
import { pathForTab, tabFromPath, type AlertTab, type Override } from '@/features/alerts/types';
-export function Alerts() {
+export function Alerts(props: { securityStatus?: SecurityStatus | null }) {
const {
activeAlerts,
activeAlertsHydrationStatus,
@@ -63,6 +66,29 @@ export function Alerts() {
const alertsActivation = useAlertsActivation();
const [isSwitchingActivation, setIsSwitchingActivation] = createSignal(false);
const readOnlySession = createMemo(() => presentationPolicyIsReadOnly());
+ const [workspaceRevision, setWorkspaceRevision] = createSignal(0);
+ const unsubscribeWorkspace = eventBus.on('org_switched', () => {
+ setWorkspaceRevision((revision) => revision + 1);
+ });
+ onCleanup(unsubscribeWorkspace);
+ // A copied status with the same facts must preserve drafts and focus. A new
+ // reader must never inherit destination credentials or an in-flight editor.
+ const configurationReader = createMemo(() => {
+ const status = props.securityStatus;
+ if (!status || status.requiresAuth !== false || readOnlySession()) return undefined;
+ return JSON.stringify([
+ workspaceRevision(),
+ getOrgID() || 'default',
+ status.currentUsername ??
+ status.proxyAuthUsername ??
+ status.ssoSessionUsername ??
+ status.authUsername,
+ status.apiTokenHint,
+ status.tokenScopes?.slice().sort(),
+ status.proxyAuthIsAdmin,
+ Object.entries(status.settingsCapabilities ?? {}).sort(([a], [b]) => a.localeCompare(b)),
+ ]);
+ });
const isNotificationDeliveryActive = alertsActivation.notificationDeliveryEnabled;
const alertActivationPresentation = createMemo(() =>
getAlertActivationPresentation({
@@ -159,6 +185,11 @@ export function Alerts() {
};
const [hasUnsavedChanges, setHasUnsavedChanges] = createSignal(false);
+ createEffect(() => {
+ configurationReader();
+ setHasUnsavedChanges(false);
+ setOverviewOverrides([]);
+ });
const [showAcknowledged, setShowAcknowledged] = createSignal(true);
// Quick tip visibility state
const [showQuickTip, setShowQuickTip] = createSignal(
@@ -437,19 +468,35 @@ export function Alerts() {
</Show>
<Show when={!readOnlySession()}>
- <AlertsConfigurationSurface
- activeTab={activeTab}
- allResources={allResources}
- byType={byType}
- children={children}
- activeAlerts={activeAlerts}
- removeAlerts={removeAlerts}
- setOverviewOverrides={setOverviewOverrides}
- hasUnsavedChanges={hasUnsavedChanges}
- setHasUnsavedChanges={setHasUnsavedChanges}
- alertsActivationState={alertsActivation.activationState}
- alertsActivationConfig={alertsActivation.config}
- />
+ <Show
+ when={configurationReader()}
+ keyed
+ fallback={
+ <Show when={isAlertsConfigurationTab(activeTab())}>
+ <p role="status" class="text-sm text-muted">
+ Alert settings access is unavailable. Reload Pulse to check access before
+ editing.
+ </p>
+ </Show>
+ }
+ >
+ {(acceptedReader) => (
+ <AlertsConfigurationSurface
+ isCurrentReader={() => configurationReader() === acceptedReader}
+ activeTab={activeTab}
+ allResources={allResources}
+ byType={byType}
+ children={children}
+ activeAlerts={activeAlerts}
+ removeAlerts={removeAlerts}
+ setOverviewOverrides={setOverviewOverrides}
+ hasUnsavedChanges={hasUnsavedChanges}
+ setHasUnsavedChanges={setHasUnsavedChanges}
+ alertsActivationState={alertsActivation.activationState}
+ alertsActivationConfig={alertsActivation.config}
+ />
+ )}
+ </Show>
</Show>
<Show when={activeTab() === 'history'}>
diff --git a/frontend-modern/src/pages/__tests__/Alerts.readOnly.test.tsx b/frontend-modern/src/pages/__tests__/Alerts.readOnly.test.tsx
index 5068020dfe..ff9c59f936 100644
--- a/frontend-modern/src/pages/__tests__/Alerts.readOnly.test.tsx
+++ b/frontend-modern/src/pages/__tests__/Alerts.readOnly.test.tsx
@@ -3,6 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Alerts } from '@/pages/Alerts';
import { createAlertAcknowledgementRequests } from '@/stores/alertAcknowledgementRequests';
+import { createSignal, onCleanup } from 'solid-js';
+import type { SecurityStatus } from '@/types/config';
+import { eventBus } from '@/stores/events';
+import { setOrgID } from '@/utils/apiClient';
import alertsPageSource from '@/pages/Alerts.tsx?raw';
import alertHistoryFiltersCardSource from '@/features/alerts/AlertHistoryFiltersCard.tsx?raw';
@@ -108,9 +112,17 @@ vi.mock('@/features/alerts/AlertsConfigurationSurface', () => ({
AlertsConfigurationSurface: configurationSurfaceSpy,
}));
+const admittedStatus = {
+ requiresAuth: false,
+ currentUsername: 'alice',
+ apiTokenHint: 'hint-a',
+ tokenScopes: ['settings:read', 'settings:write'],
+} as SecurityStatus;
+
describe('Alerts read-only presentation', () => {
beforeEach(() => {
cleanup();
+ setOrgID('default');
navigateSpy.mockReset();
presentationPolicyIsReadOnlyMock.mockReset();
presentationPolicyIsReadOnlyMock.mockReturnValue(false);
@@ -127,8 +139,49 @@ describe('Alerts read-only presentation', () => {
afterEach(() => cleanup());
+ it('withholds configuration until the current security status is known', () => {
+ locationState.pathname = '/alerts/destinations';
+ render(() => <Alerts securityStatus={null} />);
+ expect(screen.queryByTestId('alerts-config-surface')).not.toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent('Alert settings access is unavailable');
+ expect(configurationSurfaceSpy).not.toHaveBeenCalled();
+ });
+
+ it('keeps equivalent reader facts mounted, but retires user, token, scope and workspace lifetimes', async () => {
+ const retired = vi.fn();
+ configurationSurfaceSpy.mockImplementation(() => {
+ onCleanup(retired);
+ return <div data-testid="alerts-config-surface">Config</div>;
+ });
+ const [status, setStatus] = createSignal<SecurityStatus | null>(admittedStatus);
+ render(() => <Alerts securityStatus={status()} />);
+ await screen.findByTestId('alerts-config-surface');
+ expect(configurationSurfaceSpy).toHaveBeenCalledTimes(1);
+ setStatus({ ...admittedStatus, tokenScopes: admittedStatus.tokenScopes!.slice().reverse() });
+ await Promise.resolve();
+ expect(retired).not.toHaveBeenCalled();
+ expect(configurationSurfaceSpy).toHaveBeenCalledTimes(1);
+ for (const delta of [
+ { currentUsername: 'bob' },
+ { apiTokenHint: 'hint-b' },
+ { tokenScopes: ['settings:read'] },
+ ]) {
+ const previous = retired.mock.calls.length;
+ setStatus({ ...status()!, ...delta });
+ await waitFor(() => expect(retired).toHaveBeenCalledTimes(previous + 1));
+ }
+ const previous = retired.mock.calls.length;
+ setOrgID('tenant-b');
+ eventBus.emit('org_switched', 'tenant-b');
+ await waitFor(() => expect(retired).toHaveBeenCalledTimes(previous + 1));
+ setStatus(null);
+ await waitFor(() =>
+ expect(screen.queryByTestId('alerts-config-surface')).not.toBeInTheDocument(),
+ );
+ });
+
it('hands the store acknowledgement requests to the overview', async () => {
- render(() => <Alerts />);
+ render(() => <Alerts securityStatus={admittedStatus} />);
expect(await screen.findByTestId('overview-tab')).toBeInTheDocument();
expect(overviewTabSpy.mock.calls.at(-1)?.[0].acknowledgementRequests).toBe(
@@ -153,7 +206,7 @@ describe('Alerts read-only presentation', () => {
it('keeps the active mobile destination visible when the tab rail narrows', async () => {
locationState.pathname = '/alerts/schedule';
- render(() => <Alerts />);
+ render(() => <Alerts securityStatus={admittedStatus} />);
const navigation = document.querySelector<HTMLElement>('nav.touch-scroll');
expect(navigation).not.toBeNull();
@@ -182,7 +235,7 @@ describe('Alerts read-only presentation', () => {
presentationPolicyIsReadOnlyMock.mockReturnValue(true);
activationStateMock.mockReturnValue('pending_review');
- render(() => <Alerts />);
+ render(() => <Alerts securityStatus={admittedStatus} />);
await waitFor(() => {
expect(screen.getByTestId('overview-tab')).toBeInTheDocument();
@@ -204,7 +257,7 @@ describe('Alerts read-only presentation', () => {
activationStateMock.mockReturnValue('pending_review');
locationState.pathname = '/alerts/thresholds';
- render(() => <Alerts />);
+ render(() => <Alerts securityStatus={admittedStatus} />);
await waitFor(() => {
expect(navigateSpy).toHaveBeenCalledWith('/alerts/overview', { replace: true });
@@ -217,7 +270,7 @@ describe('Alerts read-only presentation', () => {
activationStateMock.mockReturnValue('active');
locationState.pathname = '/alerts/thresholds';
- render(() => <Alerts />);
+ render(() => <Alerts securityStatus={admittedStatus} />);
await waitFor(() => {
expect(screen.getByTestId('alerts-config-surface')).toBeInTheDocument();
@@ -231,7 +284,7 @@ describe('Alerts read-only presentation', () => {
presentationPolicyIsReadOnlyMock.mockReturnValue(false);
activationStateMock.mockReturnValue('pending_review');
- render(() => <Alerts />);
+ render(() => <Alerts securityStatus={admittedStatus} />);
expect(await screen.findByTestId('overview-tab')).toBeInTheDocument();
expect(screen.getByTestId('alerts-config-surface')).toBeInTheDocument();
@@ -248,7 +301,7 @@ describe('Alerts read-only presentation', () => {
presentationPolicyIsReadOnlyMock.mockReturnValue(false);
activationStateMock.mockReturnValue('active');
- render(() => <Alerts />);
+ render(() => <Alerts securityStatus={admittedStatus} />);
expect(await screen.findByTestId('overview-tab')).toBeInTheDocument();
expect(screen.getByRole('checkbox', { name: 'Send notifications' })).toBeChecked();
diff --git a/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts b/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
index 948e47da8f..0fc95c9808 100644
--- a/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
@@ -80,10 +80,10 @@ describe('alertDestinationsPresentation', () => {
it('returns canonical destinations retry and warning copy', () => {
expect(ALERT_DESTINATIONS_LOAD_ERROR_RISK_NOTICE).toBe(
- 'Saving now may overwrite your existing settings with defaults.',
+ 'Destination details and controls stay hidden until saved settings can be read. Retry to check access.',
);
expect(getAlertDestinationsLoadErrorBanner('Unable to load webhook settings.')).toBe(
- 'Unable to load webhook settings. Saving now may overwrite your existing settings with defaults.',
+ 'Unable to load webhook settings. Destination details and controls stay hidden until saved settings can be read. Retry to check access.',
);
expect(ALERT_DESTINATIONS_RETRY_LABEL).toBe('Retry');
expect(ALERT_DESTINATIONS_RETRYING_LABEL).toBe('Retrying…');
diff --git a/frontend-modern/src/utils/alertDestinationsPresentation.ts b/frontend-modern/src/utils/alertDestinationsPresentation.ts
index 5e1bdda41d..23818388a5 100644
--- a/frontend-modern/src/utils/alertDestinationsPresentation.ts
+++ b/frontend-modern/src/utils/alertDestinationsPresentation.ts
@@ -3,7 +3,7 @@ export const ALERT_DESTINATIONS_CONFIG_LOAD_ERROR =
'Unable to load notification settings. Your existing configuration could not be retrieved.';
export const ALERT_DESTINATIONS_WEBHOOK_LOAD_ERROR = 'Unable to load webhook settings.';
export const ALERT_DESTINATIONS_LOAD_ERROR_RISK_NOTICE =
- 'Saving now may overwrite your existing settings with defaults.';
+ 'Destination details and controls stay hidden until saved settings can be read. Retry to check access.';
export const ALERT_DESTINATIONS_RETRY_LABEL = 'Retry';
export const ALERT_DESTINATIONS_RETRYING_LABEL = 'Retrying…';
export const ALERT_DESTINATIONS_ENABLED_LABEL = 'Enabled';
diff --git a/frontend-modern/src/utils/apiClient.ts b/frontend-modern/src/utils/apiClient.ts
index ec62f98f1d..e9d41e0df7 100644
--- a/frontend-modern/src/utils/apiClient.ts
+++ b/frontend-modern/src/utils/apiClient.ts
@@ -82,6 +82,9 @@ interface FetchOptions extends Omit<RequestInit, 'headers'> {
expectedOrgID?: string;
}
+// A surface can retain its admitted workspace without exposing auth/header overrides.
+export type APIContextOptions = Pick<FetchOptions, 'expectedOrgID' | 'retry' | 'signal' | 'cache'>;
+
type APIErrorDetails = Record<string, string>;
type APIErrorShape = Error & {