Skip to content

Commit 43f6856

Browse files
authored
[HDX-5089] Allow editing and deleting alerts from the alert details page (#2931)
## Summary Allows users to **edit an alert's configuration and delete the alert directly from the alert details page** (`/alerts/[alertId]`, behind `NEXT_PUBLIC_ENABLE_ALERT_DETAILS`), instead of having to navigate back to the saved search modal or dashboard tile editor. **App:** - New `EditAlertModal` opened from an "Edit alert" header action. Edits threshold type/value(s), evaluation interval, schedule (offset / start anchor / consecutive windows), notification webhook, and note for both saved-search and tile alerts. Saved-search alerts additionally expose the group-by SQL expression (tile alerts derive grouping from the chart config), with autocomplete backed by the saved search's source. - New "Delete" header action using the existing `ConfirmDeleteMenu` confirmation pattern; on success it redirects back to `/alerts`. - Saves validate via the same zod schema as the existing saved-search alert modal, invalidate the alert/alerts/saved-search/dashboards queries so the details view reflects changes immediately, and keep the modal open on error (with a notification) so edits aren't lost. **API / common-utils:** - `GET /alerts` and `GET /alerts/:id` now include `channel.webhookId` plus the alert's `name`/`message` template. Without these, the edit form couldn't prefill the webhook selector, and a save would silently clear `name`/`message` (the PUT nulls omitted fields). Webhook ids are already visible to team members via `GET /webhooks`, so this is not new exposure. - `AlertsPageItemSchema.channel` gains an optional `webhookId`. Edits and deletes go through the existing team-scoped `PUT/DELETE /alerts/:id` endpoints, so existing permission enforcement applies unchanged. ### Screenshots or video | Before | After | | :----- | :---- | | | Alert details header gains "Edit alert" (opens config modal) and "Delete" (confirm menu) actions | ### How to test on Vercel preview N/A — non-testable in preview: alerts require cloud mode (LOCAL_MODE has no alert API), and the alert details page is gated behind `NEXT_PUBLIC_ENABLE_ALERT_DETAILS`. ### References - Linear Issue: [HDX-5089](https://linear.app/clickhouse/issue/HDX-5089/allow-users-to-edit-alert-configs-from-the-alert-details-page) - Related PRs: N/A ### Testing - `make ci-lint` — passes (0 errors) - `make ci-unit` — passes across all packages, including new `EditAlertModal` unit tests (saved-search payload with preserved name/message/webhookId, tile payload with dashboardId+tileId, edited threshold round-trip) - `make dev-int FILE=alerts.int` — all 288 alert-router integration tests pass, including a new test asserting `channel.webhookId`/`name`/`message` are returned by GET list and GET single ### Screenshots <img width="1414" height="461" alt="image" src="https://github.com/user-attachments/assets/d66785fd-5187-43e0-8be6-bdfd0e3c643f" /> <img width="1461" height="838" alt="image" src="https://github.com/user-attachments/assets/191f112a-0a50-4a23-b13b-33e8b3178f91" />
1 parent e60a7d3 commit 43f6856

10 files changed

Lines changed: 1086 additions & 6 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@hyperdx/common-utils': patch
3+
'@hyperdx/app': patch
4+
'@hyperdx/api': patch
5+
---
6+
7+
Allow editing and deleting alerts directly from the alert details page. An
8+
"Edit alert" action opens a modal for changing the alert's threshold,
9+
evaluation interval, schedule, group-by (saved-search alerts), notification
10+
webhook, and note, and a Delete action (with confirmation) removes the alert
11+
and returns to the alerts list. Alert API responses now include the
12+
notification channel's webhook id and the alert's name/message template so
13+
edits round-trip these fields.

‎packages/api/src/routers/api/__tests__/alerts.int.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,42 @@ describe('alerts router', () => {
130130
expect(allAlerts.body.data[0].threshold).toBe(10);
131131
});
132132

133+
it('returns channel.webhookId, name, and message in GET list and GET single', async () => {
134+
const dashboard = await agent
135+
.post('/dashboards')
136+
.send(MOCK_DASHBOARD)
137+
.expect(200);
138+
const alert = await agent
139+
.post('/alerts')
140+
.send({
141+
...makeAlertInput({
142+
dashboardId: dashboard.body.id,
143+
tileId: dashboard.body.tiles[0].id,
144+
webhookId: webhook._id.toString(),
145+
}),
146+
name: 'My alert',
147+
message: 'My message template',
148+
})
149+
.expect(200);
150+
151+
// Edit surfaces (e.g. the alert detail page) prefill from these
152+
// responses, so the notification channel and message template fields must
153+
// be present — a PUT that omits name/message clears them.
154+
const expected = {
155+
channel: { type: 'webhook', webhookId: webhook._id.toString() },
156+
name: 'My alert',
157+
message: 'My message template',
158+
};
159+
160+
const list = await agent.get('/alerts').expect(200);
161+
expect(list.body.data[0]).toMatchObject(expected);
162+
163+
const single = await agent
164+
.get(`/alerts/${alert.body.data._id}`)
165+
.expect(200);
166+
expect(single.body.data).toMatchObject(expected);
167+
});
168+
133169
it('returns 404 when updating an alert that does not exist', async () => {
134170
const dashboard = await agent
135171
.post('/dashboards')

‎packages/api/src/routers/api/alerts.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,10 @@ const formatAlertResponse = (
5050
createdBy: alert.createdBy
5151
? pick(alert.createdBy, ['email', 'name'])
5252
: undefined,
53-
channel: pick(alert.channel, ['type']),
53+
// webhookId is included so edit surfaces (e.g. the alert detail page) can
54+
// prefill the notification channel; webhook ids are already visible to
55+
// team members via GET /webhooks.
56+
channel: pick(alert.channel, ['type', 'webhookId']),
5457
...(alert.dashboard && {
5558
dashboardId: alert.dashboard._id,
5659
dashboard: {
@@ -83,6 +86,8 @@ const formatAlertResponse = (
8386
'thresholdType',
8487
'state',
8588
'source',
89+
'name',
90+
'message',
8691
'note',
8792
'createdAt',
8893
'updatedAt',

‎packages/app/src/AlertDetailPage.tsx‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,18 @@ import {
1313
Stack,
1414
Text,
1515
} from '@mantine/core';
16-
import { IconExternalLink } from '@tabler/icons-react';
16+
import { notifications } from '@mantine/notifications';
17+
import { IconExternalLink, IconPencil } from '@tabler/icons-react';
18+
import { useQueryClient } from '@tanstack/react-query';
1719

1820
import { AckAlert } from '@/components/alerts/AckAlert';
1921
import { AlertDetailChart } from '@/components/alerts/AlertDetailChart';
22+
import { AlertDetailProperties } from '@/components/alerts/AlertDetailProperties';
2023
import { AlertEvaluationsTable } from '@/components/alerts/AlertEvaluationsTable';
2124
import { AlertHistoryCardList } from '@/components/alerts/AlertHistoryCards';
22-
import { AlertPropertiesSummary } from '@/components/alerts/AlertPropertiesSummary';
2325
import { AlertStateBadge } from '@/components/alerts/AlertStateBadge';
26+
import { EditAlertModal } from '@/components/alerts/EditAlertModal';
27+
import ConfirmDeleteMenu from '@/components/ConfirmDeleteMenu';
2428
import EmptyState from '@/components/EmptyState';
2529
import { PageHeader } from '@/components/PageHeader';
2630
import { TimePicker } from '@/components/TimePicker';
@@ -71,14 +75,43 @@ const TIMELINE_ITEMS = 60;
7175
function AlertProperties({ alert }: { alert: AlertsPageItem }) {
7276
return (
7377
<Stack gap={2}>
74-
<AlertPropertiesSummary alert={alert} showSchedule />
78+
<AlertDetailProperties alert={alert} />
7579
{alert.note && <AlertNote note={alert.note} />}
7680
</Stack>
7781
);
7882
}
7983

8084
function AlertDetailBody({ alert }: { alert: AlertsPageItem }) {
8185
const alertUrl = getAlertSourceUrl(alert);
86+
const brandName = useBrandDisplayName();
87+
const router = useRouter();
88+
const queryClient = useQueryClient();
89+
const deleteAlert = api.useDeleteAlert();
90+
const [isEditModalOpen, setIsEditModalOpen] = React.useState(false);
91+
92+
const onDeleteAlert = React.useCallback(async () => {
93+
try {
94+
await deleteAlert.mutateAsync(alert._id);
95+
notifications.show({
96+
color: 'green',
97+
message: 'Alert deleted!',
98+
autoClose: 5000,
99+
});
100+
// The alerts list and the source-bound edit surfaces (saved search
101+
// modal / dashboard tile editor) all render this alert.
102+
queryClient.invalidateQueries({ queryKey: api.getAlertsQueryKey() });
103+
queryClient.invalidateQueries({ queryKey: ['saved-search'] });
104+
queryClient.invalidateQueries({ queryKey: ['dashboards'] });
105+
router.push('/alerts');
106+
} catch (error) {
107+
console.error('Failed to delete alert:', error);
108+
notifications.show({
109+
color: 'red',
110+
message: `Something went wrong. Please contact ${brandName} team.`,
111+
autoClose: 5000,
112+
});
113+
}
114+
}, [alert._id, brandName, deleteAlert, queryClient, router]);
82115

83116
// Interval-dependent, but fixed for the page lifetime: the body only
84117
// mounts once the alert has loaded, and useNewTimeQuery reads the initial
@@ -144,6 +177,16 @@ function AlertDetailBody({ alert }: { alert: AlertsPageItem }) {
144177
actions={
145178
<Group gap="sm" wrap="nowrap">
146179
<AckAlert alert={alert} />
180+
<Button
181+
data-testid="edit-alert-button"
182+
variant="secondary"
183+
size="compact-sm"
184+
leftSection={<IconPencil size={14} />}
185+
onClick={() => setIsEditModalOpen(true)}
186+
>
187+
Edit alert
188+
</Button>
189+
<ConfirmDeleteMenu onDelete={onDeleteAlert} />
147190
{alertUrl && (
148191
<Button
149192
component={Link}
@@ -165,6 +208,12 @@ function AlertDetailBody({ alert }: { alert: AlertsPageItem }) {
165208
</Group>
166209
}
167210
/>
211+
<EditAlertModal
212+
alert={alert}
213+
opened={isEditModalOpen}
214+
onClose={() => setIsEditModalOpen(false)}
215+
dateRange={searchedTimeRange}
216+
/>
168217
<div style={{ overflow: 'auto', flexGrow: 1 }}>
169218
<Container size="xl" py="md">
170219
<Stack gap="lg">
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import * as React from 'react';
2+
import { WebhookService } from '@hyperdx/common-utils/dist/types';
3+
import { Badge, Group, Text } from '@mantine/core';
4+
5+
import api from '@/api';
6+
import { AlertPropertiesSummary } from '@/components/alerts/AlertPropertiesSummary';
7+
import type { AlertsPageItem } from '@/types';
8+
import { FormatTime } from '@/useFormatTime';
9+
import { isAlertSilenceExpired } from '@/utils/alerts';
10+
11+
function PropertyRow({
12+
label,
13+
children,
14+
testId,
15+
}: {
16+
label: string;
17+
children: React.ReactNode;
18+
testId?: string;
19+
}) {
20+
return (
21+
<Group gap="xs" align="baseline" wrap="nowrap" data-testid={testId}>
22+
<Text size="xs" c="dimmed" style={{ flexShrink: 0 }}>
23+
{label}
24+
</Text>
25+
<Text size="xs" component="div" style={{ minWidth: 0 }}>
26+
{children}
27+
</Text>
28+
</Group>
29+
);
30+
}
31+
32+
/**
33+
* Full alert metadata block for the alert detail page: the shared one-line
34+
* summary (threshold, schedule, channel, creator) plus every other persisted
35+
* property — name, message template, group-by, schedule anchor/offset,
36+
* acknowledgement, tags, and created/updated timestamps. Rows render only
37+
* when the field is set.
38+
*/
39+
export function AlertDetailProperties({ alert }: { alert: AlertsPageItem }) {
40+
// Resolve the notification webhook's display name (the alert only stores
41+
// its id). Falls back to the generic "Webhook" label while loading or if
42+
// the webhook has been deleted.
43+
const { data: webhooks } = api.useWebhooks([
44+
WebhookService.Slack,
45+
WebhookService.Generic,
46+
WebhookService.IncidentIO,
47+
]);
48+
const webhookName = React.useMemo(() => {
49+
if (!alert.channel.webhookId) {
50+
return undefined;
51+
}
52+
return webhooks?.data?.find(
53+
(w: { _id: string; name: string }) => w._id === alert.channel.webhookId,
54+
)?.name;
55+
}, [webhooks, alert.channel.webhookId]);
56+
57+
const tags = alert.dashboard?.tags ?? alert.savedSearch?.tags ?? [];
58+
const hasScheduleAnchor = alert.scheduleStartAt != null;
59+
const hasScheduleOffset =
60+
alert.scheduleOffsetMinutes != null && alert.scheduleOffsetMinutes > 0;
61+
62+
return (
63+
<div data-testid="alert-detail-properties">
64+
<AlertPropertiesSummary
65+
alert={alert}
66+
showSchedule
67+
webhookName={webhookName}
68+
/>
69+
<div className="d-flex flex-column gap-1 mt-2">
70+
{alert.name && (
71+
<PropertyRow label="Name" testId="alert-property-name">
72+
{alert.name}
73+
</PropertyRow>
74+
)}
75+
{alert.message && (
76+
<PropertyRow label="Message template" testId="alert-property-message">
77+
{alert.message}
78+
</PropertyRow>
79+
)}
80+
{alert.groupBy && (
81+
<PropertyRow label="Grouped by" testId="alert-property-group-by">
82+
<Text size="xs" ff="monospace" component="span">
83+
{alert.groupBy}
84+
</Text>
85+
</PropertyRow>
86+
)}
87+
{(hasScheduleAnchor || hasScheduleOffset) && (
88+
<PropertyRow label="Schedule" testId="alert-property-schedule">
89+
{hasScheduleAnchor ? (
90+
<>
91+
Windows anchored at{' '}
92+
<FormatTime value={alert.scheduleStartAt!} format="withYear" />
93+
</>
94+
) : (
95+
<>
96+
Offset {alert.scheduleOffsetMinutes}m into each evaluation
97+
window
98+
</>
99+
)}
100+
</PropertyRow>
101+
)}
102+
{alert.silenced && (
103+
<PropertyRow label="Acknowledged" testId="alert-property-silenced">
104+
{alert.silenced.by ? <>by {alert.silenced.by} · </> : null}
105+
{isAlertSilenceExpired(alert.silenced) ? (
106+
<>
107+
expired <FormatTime value={alert.silenced.until} />
108+
</>
109+
) : (
110+
<>
111+
silenced until <FormatTime value={alert.silenced.until} />
112+
</>
113+
)}
114+
</PropertyRow>
115+
)}
116+
{tags.length > 0 && (
117+
<PropertyRow label="Tags" testId="alert-property-tags">
118+
<Group gap={4}>
119+
{tags.map(tag => (
120+
<Badge key={tag} variant="light" color="gray" size="xs">
121+
{tag}
122+
</Badge>
123+
))}
124+
</Group>
125+
</PropertyRow>
126+
)}
127+
<PropertyRow label="Created" testId="alert-property-created">
128+
<Text size="xs" c="dimmed" component="span">
129+
<FormatTime value={alert.createdAt} format="withYear" />
130+
{alert.updatedAt && alert.updatedAt !== alert.createdAt && (
131+
<>
132+
{' '}
133+
· Updated{' '}
134+
<FormatTime value={alert.updatedAt} format="withYear" />
135+
</>
136+
)}
137+
</Text>
138+
</PropertyRow>
139+
</div>
140+
</div>
141+
);
142+
}

‎packages/app/src/components/alerts/AlertPropertiesSummary.tsx‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ type AlertPropertiesSummaryProps = {
1414
* keep the shorter line.
1515
*/
1616
showSchedule?: boolean;
17+
/**
18+
* Display name of the notification webhook (the alert only stores its id).
19+
* The detail page resolves and passes it; the alerts-page rows keep the
20+
* generic "Webhook" label.
21+
*/
22+
webhookName?: string;
1723
};
1824

1925
/**
@@ -24,6 +30,7 @@ type AlertPropertiesSummaryProps = {
2430
export function AlertPropertiesSummary({
2531
alert,
2632
showSchedule = false,
33+
webhookName,
2734
}: AlertPropertiesSummaryProps) {
2835
const thresholdLabel =
2936
TILE_ALERT_THRESHOLD_TYPE_OPTIONS[alert.thresholdType] ??
@@ -58,7 +65,8 @@ export function AlertPropertiesSummary({
5865
)}
5966
<span>&middot;</span>
6067
<Group gap={5}>
61-
Notify via {getWebhookChannelIcon(alert.channel.type)} Webhook
68+
Notify via {getWebhookChannelIcon(alert.channel.type)}
69+
<span>{webhookName ?? 'Webhook'}</span>
6270
</Group>
6371
{alert.createdBy && (
6472
<>

0 commit comments

Comments
 (0)