Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(logs): add alert creation wizard (#81274)

Matt Pua1de40b544b38
diff --git a/.agents/skills/adding-product-alerting/references/frontend-alerting.md b/.agents/skills/adding-product-alerting/references/frontend-alerting.md
index f749c64dafb0..74a20bcd8a52 100644
--- a/.agents/skills/adding-product-alerting/references/frontend-alerting.md
+++ b/.agents/skills/adding-product-alerting/references/frontend-alerting.md
@@ -12,6 +12,20 @@ Use the shared product alert editor components in `products/alerts/frontend/comp
A product can use both paths when it has a simple HogFunction creation flow and a richer product-owned alert configuration surface.
+## Compose a creation wizard
+
+Use `products/alerts/frontend/components/AlertWizard` for a product-owned alert creation modal that has ordered, meaningful setup stages. Logs and insight alerts use this pattern.
+
+- Keep the wizard container and navigation shared. Define product-specific steps in the product adapter.
+- Reuse `AlertEditorFormDetails` for name and enabled state.
+- Reuse `AlertWizardReview` for a final aligned summary. Pass normalized label/value items from the product.
+- Keep triggers, filters, simulations, destinations, and product-specific validation in product-owned step content and keyed kea logic.
+- Do not create an empty alert when the modal opens. Persist only when the user completes the final review step.
+- Validate a step before moving forward. Show its errors only after the user attempts to continue.
+- Keep a simulation within its relevant configuration step. Run it explicitly and clear stale results when its inputs change.
+
+Do not force every alert into a wizard. Use a direct editor when creation needs no ordered setup or review.
+
## Compose the shared editor
Build the product form around these components:
diff --git a/products/alerts/frontend/components/AlertWizard.tsx b/products/alerts/frontend/components/AlertWizard.tsx
index a7bf2ecbc7de..1db495f650b3 100644
--- a/products/alerts/frontend/components/AlertWizard.tsx
+++ b/products/alerts/frontend/components/AlertWizard.tsx
@@ -16,7 +16,8 @@ export interface AlertWizardStep {
canAdvance?: boolean
/** Reason shown as a tooltip when the step can't advance. */
cannotAdvanceReason?: string
- content: React.ReactNode
+ content?: React.ReactNode
+ renderContent?: (showValidationErrors: boolean) => React.ReactNode
}
export interface AlertWizardProps {
@@ -163,7 +164,7 @@ export function AlertWizard({
<h3 className="text-base font-semibold m-0">{step?.title}</h3>
{step?.description ? <p className="text-xs text-secondary m-0">{step.description}</p> : null}
</div>
- {step?.content}
+ {step?.renderContent ? step.renderContent(blockedAdvanceAttempted) : step?.content}
</section>
<footer className="flex flex-wrap items-center justify-between gap-2 border-t p-4">
<div className="flex-1">{leadingActions ? leadingActions : null}</div>
diff --git a/products/alerts/frontend/components/AlertWizardReview.tsx b/products/alerts/frontend/components/AlertWizardReview.tsx
new file mode 100644
index 000000000000..e9d12341c454
--- /dev/null
+++ b/products/alerts/frontend/components/AlertWizardReview.tsx
@@ -0,0 +1,29 @@
+import type { ReactNode } from 'react'
+
+export interface AlertWizardReviewItem {
+ label: string
+ value: ReactNode
+}
+
+interface AlertWizardReviewProps {
+ items: AlertWizardReviewItem[]
+ notice?: ReactNode
+ footer?: ReactNode
+}
+
+export function AlertWizardReview({ items, notice, footer }: AlertWizardReviewProps): JSX.Element {
+ return (
+ <div className="space-y-3">
+ {notice}
+ <div className="space-y-1.5 rounded border border-border bg-bg-light p-3 text-sm">
+ {items.map(({ label, value }) => (
+ <div key={label} className="grid grid-cols-[13rem_minmax(0,1fr)] gap-2">
+ <span className="text-muted">{label}</span>
+ <span className="font-medium">{value}</span>
+ </div>
+ ))}
+ </div>
+ {footer}
+ </div>
+ )
+}
diff --git a/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsx b/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsx
index 5ca6be7bc442..1f38a672d6a9 100644
--- a/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsx
+++ b/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsx
@@ -1,6 +1,7 @@
import type { ReactNode } from 'react'
import { AlertWizardStep } from 'products/alerts/frontend/components/AlertWizard'
+import { AlertWizardReview } from 'products/alerts/frontend/components/AlertWizardReview'
interface WizardStepInput {
nameNode: ReactNode
@@ -66,26 +67,19 @@ export function buildWizardSteps(input: WizardStepInput): AlertWizardStep[] {
canAdvance: !alertFormHasErrors,
cannotAdvanceReason: alertFormHasErrors ? 'Fix the errors in previous steps before creating.' : undefined,
content: (
- <div className="space-y-3">
- <div className="rounded border border-border bg-bg-light p-3 space-y-1.5 text-sm">
- <div className="flex gap-2">
- <span className="text-muted w-20 shrink-0">Fires when</span>
- <span className="font-medium">{reviewFires}</span>
- </div>
- <div className="flex gap-2">
- <span className="text-muted w-20 shrink-0">Runs</span>
- <span className="font-medium">{reviewCadence}</span>
- </div>
- <div className="flex gap-2">
- <span className="text-muted w-20 shrink-0">Notifies</span>
- <span className="font-medium">{reviewNotifies}</span>
- </div>
- </div>
- <p className="text-xs text-muted">
- You can adjust any of this later without stepping through the wizard. Editing an existing alert
- opens straight to its sections.
- </p>
- </div>
+ <AlertWizardReview
+ items={[
+ { label: 'Fires when', value: reviewFires },
+ { label: 'Runs', value: reviewCadence },
+ { label: 'Notifies', value: reviewNotifies },
+ ]}
+ footer={
+ <p className="text-xs text-muted">
+ You can adjust any of this later without stepping through the wizard. Editing an existing
+ alert opens straight to its sections.
+ </p>
+ }
+ />
),
},
]
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
new file mode 100644
index 000000000000..3fef2c44b884
--- /dev/null
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
@@ -0,0 +1,178 @@
+import { BindLogic, useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonBanner, LemonModal } from '@posthog/lemon-ui'
+
+import { AlertEditorFormDetails } from 'products/alerts/frontend/components/AlertEditor'
+import { AlertWizard, AlertWizardStep } from 'products/alerts/frontend/components/AlertWizard'
+import { AlertWizardReview } from 'products/alerts/frontend/components/AlertWizardReview'
+
+import { LogsAlertFilters, LogsAlertTrigger } from './LogsAlertForm'
+import { logsAlertFormLogic, LogsAlertFormType } from './logsAlertFormLogic'
+import { logsAlertNotificationLogic } from './logsAlertNotificationLogic'
+import { LogsAlertNotifications } from './LogsAlertNotifications'
+import { LogsAlertSimulation } from './LogsAlertSimulation'
+import { hasAnyFilter, PendingLogsAlertNotification } from './logsAlertUtils'
+
+interface LogsAlertCreateModalProps {
+ isOpen: boolean
+ onClose: () => void
+}
+
+export function LogsAlertCreateModal({ isOpen, onClose }: LogsAlertCreateModalProps): JSX.Element {
+ return (
+ <LemonModal isOpen={isOpen} onClose={onClose} title="" simple width={900}>
+ {isOpen ? <LogsAlertCreateModalContent onClose={onClose} /> : null}
+ </LemonModal>
+ )
+}
+
+function LogsAlertCreateModalContent({ onClose }: { onClose: () => void }): JSX.Element {
+ const formLogicProps = { alert: null, onCreateSuccess: onClose }
+ const { isAlertFormSubmitting, alertFormChanged, alertForm } = useValues(logsAlertFormLogic(formLogicProps))
+ const { touchAlertFormField } = useActions(logsAlertFormLogic(formLogicProps))
+ const { pendingNotifications } = useValues(logsAlertNotificationLogic({}))
+ const hasLogFilter = hasAnyFilter(alertForm.severityLevels, alertForm.serviceNames, alertForm.filterGroup)
+ const nameError = alertForm.name.trim() ? undefined : 'Enter an alert name.'
+ const filterError = hasLogFilter
+ ? undefined
+ : 'Select at least one severity or service, or add an attribute filter.'
+ const configurationCannotAdvanceReason = nameError ?? filterError
+ const steps = buildLogsAlertWizardSteps({
+ alertForm,
+ pendingNotifications,
+ configurationCannotAdvanceReason,
+ nameError,
+ filterError,
+ })
+
+ return (
+ <BindLogic logic={logsAlertFormLogic} props={formLogicProps}>
+ <BindLogic logic={logsAlertNotificationLogic} props={{}}>
+ <Form
+ logic={logsAlertFormLogic}
+ props={formLogicProps}
+ formKey="alertForm"
+ enableFormOnSubmit
+ className="LemonModal__layout"
+ >
+ <AlertWizard
+ title="New alert"
+ steps={steps}
+ isSubmitting={isAlertFormSubmitting}
+ hasChanges={alertFormChanged}
+ onBack={onClose}
+ onSubmitAttempted={() => touchAlertFormField('name')}
+ />
+ </Form>
+ </BindLogic>
+ </BindLogic>
+ )
+}
+
+function buildLogsAlertWizardSteps({
+ alertForm,
+ pendingNotifications,
+ configurationCannotAdvanceReason,
+ nameError,
+ filterError,
+}: {
+ alertForm: LogsAlertFormType
+ pendingNotifications: PendingLogsAlertNotification[]
+ configurationCannotAdvanceReason: string | undefined
+ nameError: string | undefined
+ filterError: string | undefined
+}): AlertWizardStep[] {
+ return [
+ {
+ key: 'configure',
+ title: 'Configure',
+ description: 'Select matching logs and set when this alert fires.',
+ canAdvance: !configurationCannotAdvanceReason,
+ cannotAdvanceReason: configurationCannotAdvanceReason,
+ renderContent: (showValidationErrors) => (
+ <div className="max-w-2xl space-y-5">
+ <AlertEditorFormDetails nameError={showValidationErrors ? nameError : undefined} />
+ <LogsAlertFilters filterError={showValidationErrors ? filterError : undefined} />
+ </div>
+ ),
+ },
+ {
+ key: 'trigger',
+ title: 'Set trigger',
+ description: 'Set the log count that fires the alert and reduce notification noise if needed.',
+ content: (
+ <div className="max-w-2xl space-y-6">
+ <LogsAlertTrigger />
+ <LogsAlertSimulation embedded />
+ </div>
+ ),
+ },
+ {
+ key: 'notify',
+ title: 'Notify',
+ description: 'Choose where to send alert events.',
+ content: (
+ <div className="max-w-2xl">
+ <LogsAlertNotifications />
+ </div>
+ ),
+ },
+ {
+ key: 'review',
+ title: 'Review',
+ description: 'Confirm the alert before you create it.',
+ content: <LogsAlertReview alertForm={alertForm} pendingNotifications={pendingNotifications} />,
+ },
+ ]
+}
+
+function LogsAlertReview({
+ alertForm,
+ pendingNotifications,
+}: {
+ alertForm: LogsAlertFormType
+ pendingNotifications: PendingLogsAlertNotification[]
+}): JSX.Element {
+ const severity = alertForm.severityLevels.length ? alertForm.severityLevels.join(', ') : 'all severities'
+ const services = alertForm.serviceNames.length ? alertForm.serviceNames.join(', ') : 'all services'
+ const attributeCount = alertForm.filterGroup.values.length
+ const notificationSummary = pendingNotifications.length
+ ? `${pendingNotifications.length} notification destination${pendingNotifications.length === 1 ? '' : 's'}`
+ : 'No notification destinations'
+
+ return (
+ <div className="max-w-2xl">
+ <AlertWizardReview
+ notice={
+ pendingNotifications.length === 0 ? (
+ <LemonBanner type="warning">
+ This alert will run without notifications. Go back to Notify to add a destination.
+ </LemonBanner>
+ ) : undefined
+ }
+ items={[
+ { label: 'Name', value: alertForm.name },
+ { label: 'Severity', value: severity },
+ { label: 'Service', value: services },
+ {
+ label: 'Attributes',
+ value: attributeCount
+ ? `${attributeCount} attribute filter${attributeCount === 1 ? '' : 's'}`
+ : 'None',
+ },
+ {
+ label: 'Fires when',
+ value: `log count is ${alertForm.thresholdOperator} ${alertForm.thresholdCount} in ${alertForm.windowMinutes} minutes`,
+ },
+ {
+ label: 'Noise reduction',
+ value: `${alertForm.datapointsToAlarm} of ${alertForm.evaluationPeriods} checks must match`,
+ },
+ { label: 'Notification cooldown', value: `${alertForm.cooldownMinutes} minutes` },
+ { label: 'Notifies', value: notificationSummary },
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
index 888558b34456..a78ebf9b8318 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
@@ -1,6 +1,6 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { LemonButton, LemonModal, LemonTable, LemonTableColumns, LemonTag, LemonTagType } from '@posthog/lemon-ui'
+import { LemonButton, LemonTable, LemonTableColumns, LemonTag, LemonTagType } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
@@ -20,25 +20,6 @@ import {
import { LogsAlertEventHistoryLogicProps, logsAlertEventHistoryLogic } from './logsAlertEventHistoryLogic'
-interface LogsAlertEventHistoryModalProps {
- alert: LogsAlertConfigurationApi | null
- onClose: () => void
-}
-
-export function LogsAlertEventHistoryModal({ alert, onClose }: LogsAlertEventHistoryModalProps): JSX.Element {
- return (
- <LemonModal
- isOpen={alert !== null}
- onClose={onClose}
- width={960}
- title={alert ? `Alert history · ${alert.name}` : 'Alert history'}
- description="Evaluations, transitions, errors, and user actions."
- >
- {alert ? <LogsAlertEventHistoryContent alert={alert} /> : null}
- </LemonModal>
- )
-}
-
export function LogsAlertEventHistoryContent({ alert }: { alert: LogsAlertConfigurationApi }): JSX.Element {
const logicProps: LogsAlertEventHistoryLogicProps = { alertId: alert.id }
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
index 6969c76240f7..6d364e976fef 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
@@ -102,76 +102,93 @@ function CheckDotsTooltip({ datapoints, periods }: { datapoints: number; periods
}
export function LogsAlertForm(): JSX.Element {
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <AlertEditorSection
+ title="Definition"
+ description="Checks run every 5 minutes. Each check queries logs matching these filters."
+ >
+ <div className="space-y-5">
+ <LogsAlertFilters />
+ <LogsAlertTrigger />
+ </div>
+ </AlertEditorSection>
+ </div>
+ )
+}
+
+export function LogsAlertFilters({ filterError }: { filterError?: string }): JSX.Element {
const { alertForm } = useValues(logsAlertFormLogic)
const { setAlertFormValue } = useActions(logsAlertFormLogic)
-
const handleFilterGroupChange = useCallback(
(group: UniversalFiltersGroup) => setAlertFormValue('filterGroup', group),
[setAlertFormValue]
)
+
+ return (
+ <div className="space-y-3">
+ <h4 className="m-0">Filters</h4>
+ {filterError ? <LemonField.Error error={filterError} /> : null}
+ <div className="grid max-w-3xl gap-3 md:grid-cols-2">
+ <LemonField name="severityLevels" label="Severity">
+ <SeverityLevelsFilter
+ value={alertForm.severityLevels}
+ onChange={(levels) => setAlertFormValue('severityLevels', levels)}
+ />
+ </LemonField>
+ <LemonField.Pure label="Service">
+ <ServiceFilter
+ value={alertForm.serviceNames}
+ onChange={(names) => setAlertFormValue('serviceNames', names)}
+ />
+ </LemonField.Pure>
+ </div>
+ <LemonField name="filterGroup" label="Attributes">
+ <AlertFilterGroup filterGroup={alertForm.filterGroup} onChange={handleFilterGroupChange} />
+ </LemonField>
+ </div>
+ )
+}
+
+export function LogsAlertTrigger(): JSX.Element {
+ const { alertForm } = useValues(logsAlertFormLogic)
+ const { setAlertFormValue } = useActions(logsAlertFormLogic)
const enabledAdvancedOptionsCount =
Number(alertForm.evaluationPeriods > 1 || alertForm.datapointsToAlarm > 1) +
Number(alertForm.cooldownMinutes > 0)
return (
- <div className="space-y-6 max-w-2xl">
- <AlertEditorSection
- title="Definition"
- description="Checks run every 5 minutes. Each check queries logs matching these filters."
- >
- <div className="space-y-6">
- <div className="space-y-5">
- <h4 className="m-0">Filters</h4>
- <LemonField name="severityLevels" label="Severity">
- <SeverityLevelsFilter
- value={alertForm.severityLevels}
- onChange={(levels) => setAlertFormValue('severityLevels', levels)}
- />
- </LemonField>
- <LemonField.Pure label="Service">
- <ServiceFilter
- value={alertForm.serviceNames}
- onChange={(names) => setAlertFormValue('serviceNames', names)}
- />
- </LemonField.Pure>
- <LemonField name="filterGroup" label="Attributes">
- <AlertFilterGroup filterGroup={alertForm.filterGroup} onChange={handleFilterGroupChange} />
- </LemonField>
- </div>
-
- <div className="space-y-2">
- <h4 className="m-0">Trigger condition</h4>
- <AlertDefinitionRow label="Alert if count goes">
- <LemonSegmentedButton
- value={alertForm.thresholdOperator}
- onChange={(value) => setAlertFormValue('thresholdOperator', value)}
- options={[
- { value: LogsAlertThresholdOperatorEnumApi.Above, label: 'above' },
- { value: LogsAlertThresholdOperatorEnumApi.Below, label: 'below' },
- ]}
- size="small"
- />
- <LemonInput
- type="number"
- min={0}
- value={alertForm.thresholdCount}
- onChange={(value) => setAlertFormValue('thresholdCount', value ?? 0)}
- className="w-24"
- size="small"
- data-attr="logs-alert-threshold-count"
- />
- <span className="text-sm">in the last</span>
- <LemonSelect
- value={alertForm.windowMinutes}
- onChange={(value) => setAlertFormValue('windowMinutes', value ?? 10)}
- options={WINDOW_OPTIONS}
- size="small"
- />
- </AlertDefinitionRow>
- </div>
- </div>
- </AlertEditorSection>
-
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <h4 className="m-0">Trigger condition</h4>
+ <AlertDefinitionRow label="Alert if count goes">
+ <LemonSegmentedButton
+ value={alertForm.thresholdOperator}
+ onChange={(value) => setAlertFormValue('thresholdOperator', value)}
+ options={[
+ { value: LogsAlertThresholdOperatorEnumApi.Above, label: 'above' },
+ { value: LogsAlertThresholdOperatorEnumApi.Below, label: 'below' },
+ ]}
+ size="small"
+ />
+ <LemonInput
+ type="number"
+ min={0}
+ value={alertForm.thresholdCount}
+ onChange={(value) => setAlertFormValue('thresholdCount', value ?? 0)}
+ className="w-24"
+ size="small"
+ data-attr="logs-alert-threshold-count"
+ />
+ <span className="text-sm">in the last</span>
+ <LemonSelect
+ value={alertForm.windowMinutes}
+ onChange={(value) => setAlertFormValue('windowMinutes', value ?? 10)}
+ options={WINDOW_OPTIONS}
+ size="small"
+ />
+ </AlertDefinitionRow>
+ </div>
<AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount}>
<LemonField.Pure
label={
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx
index d97ee6ff173e..5bd5716e1821 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx
@@ -10,24 +10,16 @@ import {
LemonTableColumn,
LemonTableColumns,
LemonTag,
- SpinnerOverlay,
} from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { MemberSelect } from 'lib/components/MemberSelect'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
import { TZLabel } from 'lib/components/TZLabel'
+import type { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
- DropdownMenuTrigger,
-} from 'lib/ui/quill'
import { urls } from 'scenes/urls'
import { ProductKey } from '~/queries/schema/schema-general'
@@ -79,17 +71,15 @@ export function LogsAlertDestinationTags({
}
export function LogsAlertList(): JSX.Element {
- const { alerts, alertsLoading, resettingAlertIds, creatingAlert, createdByFilter } = useValues(logsAlertingLogic)
+ const { alerts, alertsLoading, resettingAlertIds, createdByFilter } = useValues(logsAlertingLogic)
const {
- setEditingAlert,
setCreatedByFilter,
deleteAlert,
toggleAlertEnabled,
resetAlert,
- setViewingHistoryAlert,
snoozeAlert,
unsnoozeAlert,
- createAlertAndOpen,
+ openCreateAlertModal,
} = useActions(logsAlertingLogic)
const columns: LemonTableColumns<LogsAlertConfigurationApi> = [
@@ -216,81 +206,59 @@ export function LogsAlertList(): JSX.Element {
title: '',
render: (_, alert) => {
const isResetting = resettingAlertIds.has(alert.id)
+ const menuItems: LemonMenuItems = [
+ { label: 'Edit', to: urls.logsAlertDetail(alert.id) },
+ { label: 'View history', to: urls.logsAlertDetail(alert.id, 'history') },
+ alert.state === LogsAlertConfigurationStateEnumApi.Snoozed
+ ? { label: 'Unsnooze', onClick: () => unsnoozeAlert(alert.id) }
+ : {
+ label: 'Snooze',
+ items: SNOOZE_DURATIONS.map((duration) => ({
+ label: duration.label,
+ onClick: () => snoozeAlert(alert.id, duration.minutes),
+ })),
+ },
+ alert.state === LogsAlertConfigurationStateEnumApi.Broken && {
+ label: isResetting ? 'Resetting…' : 'Reset alert',
+ disabledReason: isResetting ? 'Reset in progress' : undefined,
+ onClick: () => resetAlert(alert.id),
+ },
+ {
+ label: 'Delete',
+ status: 'danger',
+ 'data-attr': 'logs-alert-row-delete',
+ onClick: () => {
+ LemonDialog.open({
+ title: `Delete "${alert.name}"?`,
+ description: 'This alert will be permanently deleted. This action cannot be undone.',
+ primaryButton: {
+ children: 'Delete',
+ type: 'primary',
+ status: 'danger',
+ onClick: () => deleteAlert(alert.id),
+ 'data-attr': 'logs-alert-delete-confirm',
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ },
+ ]
return (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <LemonButton
- type="tertiary"
- size="small"
- icon={<IconEllipsis />}
- aria-label={`More options for ${alert.name}`}
- />
- }
+ <LemonMenu items={menuItems} placement="bottom-end">
+ <LemonButton
+ type="tertiary"
+ size="small"
+ icon={<IconEllipsis />}
+ aria-label={`More options for ${alert.name}`}
/>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => setEditingAlert(alert)}>Edit</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setViewingHistoryAlert(alert)}>
- View history
- </DropdownMenuItem>
- {alert.state === LogsAlertConfigurationStateEnumApi.Snoozed ? (
- <DropdownMenuItem onClick={() => unsnoozeAlert(alert.id)}>Unsnooze</DropdownMenuItem>
- ) : (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>Snooze</DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- {SNOOZE_DURATIONS.map((duration) => (
- <DropdownMenuItem
- key={duration.minutes}
- onClick={() => snoozeAlert(alert.id, duration.minutes)}
- >
- {duration.label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- )}
- {alert.state === LogsAlertConfigurationStateEnumApi.Broken ? (
- <DropdownMenuItem disabled={isResetting} onClick={() => resetAlert(alert.id)}>
- {isResetting ? 'Resetting…' : 'Reset alert'}
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem
- variant="destructive"
- data-attr="logs-alert-row-delete"
- onClick={() => {
- LemonDialog.open({
- title: `Delete "${alert.name}"?`,
- description:
- 'This alert will be permanently deleted. This action cannot be undone.',
- primaryButton: {
- children: 'Delete',
- type: 'primary',
- status: 'danger',
- onClick: () => deleteAlert(alert.id),
- 'data-attr': 'logs-alert-delete-confirm',
- },
- secondaryButton: {
- children: 'Cancel',
- },
- })
- }}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ </LemonMenu>
)
},
},
]
- if (alertsLoading && alerts.length === 0) {
- return <SpinnerOverlay />
- }
-
- if (alerts.length === 0 && !createdByFilter) {
+ if (alerts.length === 0 && !createdByFilter && !alertsLoading) {
return (
<ProductIntroduction
productName="Logs alerts"
@@ -303,8 +271,7 @@ export function LogsAlertList(): JSX.Element {
<LemonButton
type="primary"
icon={<IconPlus />}
- onClick={() => createAlertAndOpen()}
- loading={creatingAlert}
+ onClick={openCreateAlertModal}
data-attr="logs-alerts-new"
>
Create alert
@@ -322,13 +289,7 @@ export function LogsAlertList(): JSX.Element {
<span>Created by:</span>
<MemberSelect value={createdByFilter} onChange={(user) => setCreatedByFilter(user?.uuid ?? null)} />
</div>
- <LemonButton
- type="primary"
- size="small"
- onClick={() => createAlertAndOpen()}
- loading={creatingAlert}
- data-attr="logs-alerts-new"
- >
+ <LemonButton type="primary" size="small" onClick={openCreateAlertModal} data-attr="logs-alerts-new">
New alert
</LemonButton>
</div>
@@ -337,6 +298,7 @@ export function LogsAlertList(): JSX.Element {
dataSource={alerts}
rowKey="id"
loading={alertsLoading}
+ loadingSkeletonRows={5}
emptyState={createdByFilter ? 'No alerts match this filter.' : 'No alerts configured yet.'}
size="small"
pagination={{ pageSize: 30 }}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
index a9323a8969f9..db86cf87f736 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
-import { LemonButton, LemonSelect, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+import { LemonButton, LemonCard, LemonSelect, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
import { DefaultTooltip, type Series, TimeSeriesBarChart, type TimeSeriesBarChartConfig } from '@posthog/quill-charts'
import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
@@ -180,14 +180,15 @@ function SimulationSummary({
)
}
-function SimulationIncidents({ incidents, threshold }: { incidents: Incident[]; threshold: number }): JSX.Element {
+function SimulationIncidents({
+ incidents,
+ threshold,
+}: {
+ incidents: Incident[]
+ threshold: number
+}): JSX.Element | null {
if (incidents.length === 0) {
- return (
- <div className="text-center py-4 text-secondary text-sm border rounded">
- No alerts — the alert would not have fired during this period.
- {threshold > 0 && ' Consider lowering the threshold.'}
- </div>
- )
+ return null
}
return (
@@ -260,12 +261,18 @@ function SimulationResults({ result }: { result: LogsAlertSimulateResponseApi })
)
}
-export function LogsAlertSimulation(): JSX.Element {
+export function LogsAlertSimulation({ embedded = false }: { embedded?: boolean }): JSX.Element {
const { simulationResult, simulationResultLoading, simulationDateFrom } = useValues(logsAlertFormLogic)
const { simulateAlert, setSimulationDateFrom } = useActions(logsAlertFormLogic)
- return (
- <div className="space-y-4 p-4">
+ const simulation = (
+ <div className="space-y-4">
+ {embedded ? (
+ <div>
+ <h4 className="m-0">Preview</h4>
+ <p className="m-0 text-xs text-secondary">Check how this alert would behave on historical data.</p>
+ </div>
+ ) : null}
<div className="flex gap-2 items-center">
<LemonSelect
size="small"
@@ -288,11 +295,21 @@ export function LogsAlertSimulation(): JSX.Element {
{simulationResult && <SimulationResults result={simulationResult} />}
{!simulationResult && !simulationResultLoading && (
- <div className="text-center py-8 text-secondary text-sm">
+ <div className="py-4 text-secondary text-sm">
Select a time range and click "Run simulation" to preview how this alert would behave on historical
data.
</div>
)}
</div>
)
+
+ if (embedded) {
+ return (
+ <LemonCard className="p-4" hoverEffect={false}>
+ {simulation}
+ </LemonCard>
+ )
+ }
+
+ return <div className="p-4">{simulation}</div>
}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
index 743157f79434..8de77912fb12 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
@@ -1,38 +1,22 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { Form } from 'kea-forms'
-import { IconTestTube } from '@posthog/icons'
-import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
+import { LemonBanner, Link } from '@posthog/lemon-ui'
-import { LemonModal } from 'lib/lemon-ui/LemonModal'
-
-import { AlertEditor, AlertEditorFormDetails } from 'products/alerts/frontend/components/AlertEditor'
-import {
- LogsAlertConfigurationApi,
- LogsAlertConfigurationStateEnumApi,
-} from 'products/logs/frontend/generated/api.schemas'
-
-import { LogsAlertEventHistoryModal } from './LogsAlertEventHistory'
-import { LogsAlertForm } from './LogsAlertForm'
-import { logsAlertFormLogic } from './logsAlertFormLogic'
+import { LogsAlertCreateModal } from './LogsAlertCreateModal'
import { logsAlertingLogic } from './logsAlertingLogic'
import { LogsAlertList } from './LogsAlertList'
-import { logsAlertNotificationLogic } from './logsAlertNotificationLogic'
-import { LogsAlertSimulation } from './LogsAlertSimulation'
export function LogsAlertingSection(): JSX.Element {
return (
<BindLogic logic={logsAlertingLogic} props={{}}>
- <LogsAlertingSectionInner />
+ <LogsAlertingSectionContent />
</BindLogic>
)
}
-function LogsAlertingSectionInner(): JSX.Element {
- const { isCreating, editingAlert, viewingHistoryAlert } = useValues(logsAlertingLogic)
- const { setIsCreating, setEditingAlert, setViewingHistoryAlert } = useActions(logsAlertingLogic)
-
- const isModalOpen = isCreating || editingAlert !== null
+function LogsAlertingSectionContent(): JSX.Element {
+ const { isCreateAlertModalOpen } = useValues(logsAlertingLogic)
+ const { closeCreateAlertModal } = useActions(logsAlertingLogic)
return (
<>
@@ -49,105 +33,7 @@ function LogsAlertingSectionInner(): JSX.Element {
or share feedback with what you'd like to see.
</LemonBanner>
<LogsAlertList />
- <LemonModal
- isOpen={isModalOpen}
- onClose={() => {
- setIsCreating(false)
- setEditingAlert(null)
- }}
- title=""
- simple
- width={720}
- >
- {isModalOpen ? <LogsAlertModalContent editingAlert={editingAlert} /> : null}
- </LemonModal>
- <LogsAlertEventHistoryModal alert={viewingHistoryAlert} onClose={() => setViewingHistoryAlert(null)} />
+ <LogsAlertCreateModal isOpen={isCreateAlertModalOpen} onClose={closeCreateAlertModal} />
</>
)
}
-
-function LogsAlertModalContent({ editingAlert }: { editingAlert: LogsAlertConfigurationApi | null }): JSX.Element {
- const notifLogicProps = { alertId: editingAlert?.id }
- const formLogicProps = { alert: editingAlert }
- const { isAlertFormSubmitting, alertFormChanged, isSimulationPanelOpen } = useValues(
- logsAlertFormLogic(formLogicProps)
- )
- const { openSimulationPanel, closeSimulationPanel } = useActions(logsAlertFormLogic(formLogicProps))
- const { resetAlert } = useActions(logsAlertingLogic)
- const { resettingAlertIds } = useValues(logsAlertingLogic)
- const { pendingNotifications } = useValues(logsAlertNotificationLogic(notifLogicProps))
- const hasPendingNotifications = pendingNotifications.length > 0
- const isBroken = editingAlert?.state === LogsAlertConfigurationStateEnumApi.Broken
- const isResetting = editingAlert ? resettingAlertIds.has(editingAlert.id) : false
-
- return (
- <BindLogic logic={logsAlertFormLogic} props={formLogicProps}>
- <BindLogic logic={logsAlertNotificationLogic} props={notifLogicProps}>
- <Form
- logic={logsAlertFormLogic}
- props={formLogicProps}
- formKey="alertForm"
- enableFormOnSubmit
- className="LemonModal__layout"
- >
- <AlertEditor
- title={editingAlert ? 'Edit alert' : 'New alert'}
- className="min-h-0 flex-1 overflow-hidden"
- contentClassName="min-h-0 flex-1 overflow-y-auto"
- description="Alerts are checked every 5 minutes."
- isEditing={editingAlert !== null}
- isSubmitting={isAlertFormSubmitting}
- hasChanges={alertFormChanged}
- hasPendingChanges={hasPendingNotifications}
- leadingActions={
- <LemonButton
- type="secondary"
- icon={<IconTestTube />}
- onClick={openSimulationPanel}
- tooltip="Run this alert against historical data to see when it would have fired"
- >
- Simulate
- </LemonButton>
- }
- >
- {isBroken && editingAlert ? (
- <LemonBanner
- type="error"
- className="mb-3"
- action={{
- children: isResetting ? 'Resetting…' : 'Reset alert',
- onClick: () => resetAlert(editingAlert.id),
- loading: isResetting,
- disabledReason: isResetting ? 'Reset in progress' : undefined,
- }}
- >
- <div className="font-semibold">
- This alert was auto-disabled after repeated check failures.
- </div>
- {editingAlert.last_error_message ? (
- <div className="text-xs text-muted-alt mt-1">
- Last error: {editingAlert.last_error_message}
- </div>
- ) : null}
- </LemonBanner>
- ) : null}
- <div className="space-y-6 max-w-2xl">
- <AlertEditorFormDetails />
- <LogsAlertForm />
- </div>
- </AlertEditor>
- </Form>
-
- <LemonModal
- isOpen={isSimulationPanelOpen}
- onClose={closeSimulationPanel}
- title="Alert simulation"
- description="Run the alert against historical data to preview when it would have fired. Includes threshold evaluation, N-of-M noise reduction, and cooldown."
- width={960}
- >
- <LogsAlertSimulation />
- </LemonModal>
- </BindLogic>
- </BindLogic>
- )
-}
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
index f182b272dd2a..7b8d3a8d0376 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
@@ -14,7 +14,6 @@ import {
} from 'products/logs/frontend/generated/api.schemas'
import { LogsAlertFormType, logsAlertFormLogic } from '../logsAlertFormLogic'
-import { logsAlertingLogic } from '../logsAlertingLogic'
jest.mock('products/logs/frontend/generated/api', () => ({
logsAlertsCreate: jest.fn(),
@@ -87,8 +86,6 @@ const VALID_FORM_VALUES: LogsAlertFormType = {
}
describe('logsAlertFormLogic', () => {
- let alertingLogic: ReturnType<typeof logsAlertingLogic.build>
-
beforeEach(() => {
initKeaTests()
jest.clearAllMocks()
@@ -98,12 +95,6 @@ describe('logsAlertFormLogic', () => {
results: [],
count: 0,
})
- alertingLogic = logsAlertingLogic.build()
- alertingLogic.mount()
- })
-
- afterEach(() => {
- alertingLogic?.unmount()
})
describe('errors validation', () => {
@@ -239,10 +230,12 @@ describe('logsAlertFormLogic', () => {
describe('create path (props.alert is null)', () => {
let logic: ReturnType<typeof logsAlertFormLogic.build>
+ let onCreateSuccess: jest.Mock
beforeEach(() => {
mockLogsAlertsCreate.mockResolvedValue(MOCK_CREATED_ALERT)
- logic = logsAlertFormLogic({ alert: null })
+ onCreateSuccess = jest.fn()
+ logic = logsAlertFormLogic({ alert: null, onCreateSuccess })
logic.mount()
})
@@ -288,6 +281,7 @@ describe('logsAlertFormLogic', () => {
}).toFinishAllListeners()
expect(lemonToast.success).toHaveBeenCalledWith('Alert created')
+ expect(onCreateSuccess).toHaveBeenCalledTimes(1)
})
it('trims whitespace from name in create payload', async () => {
@@ -366,16 +360,6 @@ describe('logsAlertFormLogic', () => {
expect((calledWith.filters as Record<string, unknown>).filterGroup).toBeUndefined()
})
- it('dispatches setEditingAlert(null) and setIsCreating(false) after create', async () => {
- await expectLogic(logic, () => {
- logic.actions.setAlertFormValues(VALID_FORM_VALUES)
- logic.actions.submitAlertForm()
- }).toFinishAllListeners()
-
- expect(alertingLogic.values.editingAlert).toBeNull()
- expect(alertingLogic.values.isCreating).toBe(false)
- })
-
it('shows error toast when create API throws with detail', async () => {
mockLogsAlertsCreate.mockRejectedValue({ detail: 'Quota exceeded' })
@@ -490,16 +474,6 @@ describe('logsAlertFormLogic', () => {
expect(lemonToast.error).toHaveBeenCalledWith('Permission denied')
})
-
- it('dispatches setEditingAlert(null) and setIsCreating(false) after update', async () => {
- await expectLogic(logic, () => {
- logic.actions.setAlertFormValues(VALID_FORM_VALUES)
- logic.actions.submitAlertForm()
- }).toFinishAllListeners()
-
- expect(alertingLogic.values.editingAlert).toBeNull()
- expect(alertingLogic.values.isCreating).toBe(false)
- })
})
describe('isEditing selector', () => {
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
index 6c2eab2b2a6a..b763bb0951c9 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
@@ -8,7 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
-import { logsAlertsList, logsAlertsResetCreate } from 'products/logs/frontend/generated/api'
+import { logsAlertsCreate, logsAlertsList, logsAlertsResetCreate } from 'products/logs/frontend/generated/api'
import { logsAlertingLogic } from '../logsAlertingLogic'
@@ -31,6 +31,7 @@ jest.mock('@posthog/lemon-ui', () => ({
const mockReset = logsAlertsResetCreate as jest.MockedFunction<typeof logsAlertsResetCreate>
const mockList = logsAlertsList as jest.MockedFunction<typeof logsAlertsList>
+const mockCreate = logsAlertsCreate as jest.MockedFunction<typeof logsAlertsCreate>
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve!: (value: T) => void
@@ -142,25 +143,6 @@ describe('logsAlertingLogic', () => {
logic.unmount()
})
- it('updates editingAlert optimistically when the reset target matches the open modal', async () => {
- const editing = { id: 'alert-1', name: 'broken', state: 'broken' } as any
- const updated = { id: 'alert-1', name: 'broken', state: 'ok' } as any
- mockReset.mockResolvedValue(updated)
-
- const logic = logsAlertingLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- logic.actions.setEditingAlert(editing)
-
- await expectLogic(logic, () => {
- logic.actions.resetAlert('alert-1')
- })
- .toFinishAllListeners()
- .toMatchValues({ editingAlert: updated })
-
- logic.unmount()
- })
-
it('surfaces an error toast and does not reload on failure', async () => {
mockReset.mockRejectedValue(new Error('boom'))
@@ -180,41 +162,18 @@ describe('logsAlertingLogic', () => {
})
})
- describe('createAlertAndOpen', () => {
- it('posts an empty draft and routes to detail', async () => {
- const mockCreate = require('products/logs/frontend/generated/api').logsAlertsCreate as jest.Mock
- mockCreate.mockResolvedValueOnce({ id: 'new-alert-id', name: 'Untitled alert' })
- const { router } = require('kea-router')
- const pushSpy = jest.spyOn(router.actions, 'push')
-
+ describe('create alert modal', () => {
+ it('opens without creating an empty draft', async () => {
const logic = logsAlertingLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.createAlertAndOpen()
- }).toFinishAllListeners()
-
- expect(mockCreate).toHaveBeenCalledWith(expect.any(String), { enabled: false })
- expect(pushSpy).toHaveBeenCalledWith('/logs/alerts/new-alert-id')
-
- pushSpy.mockRestore()
- logic.unmount()
- })
-
- it('shows an error toast on create failure', async () => {
- const mockCreate = require('products/logs/frontend/generated/api').logsAlertsCreate as jest.Mock
- mockCreate.mockRejectedValueOnce({ detail: 'Maximum number of alerts reached' })
+ logic.actions.openCreateAlertModal()
+ }).toMatchValues({ isCreateAlertModalOpen: true })
- const logic = logsAlertingLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- await expectLogic(logic, () => {
- logic.actions.createAlertAndOpen()
- }).toFinishAllListeners()
+ expect(mockCreate).not.toHaveBeenCalled()
- expect(lemonToast.error).toHaveBeenCalledWith('Maximum number of alerts reached')
logic.unmount()
})
})
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
index 0969b7249c1b..d14e5fc566cb 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
@@ -2,10 +2,13 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
+import { ApiError } from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import { LogMessage } from '~/queries/schema/schema-general'
import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
@@ -47,6 +50,7 @@ export interface LogsAlertFormType {
export interface LogsAlertFormLogicProps {
alert: LogsAlertConfigurationApi | null
+ onCreateSuccess?: () => void
}
function extractFilterGroup(alert: LogsAlertConfigurationApi | null): UniversalFiltersGroup {
@@ -61,6 +65,10 @@ function extractFilterGroup(alert: LogsAlertConfigurationApi | null): UniversalF
return EMPTY_FILTER_GROUP
}
+function saveErrorMessage(error: ApiError): string {
+ return error.detail ?? error.message ?? 'Failed to save alert'
+}
+
export function buildFormDefaults(alert: LogsAlertConfigurationApi | null): LogsAlertFormType {
return {
name: alert?.name ?? '',
@@ -106,12 +114,6 @@ export interface logsAlertFormLogicActions {
alertId: string
} // logsAlertNotificationLogic
loadAlerts: (_?: any) => any // logsAlertingLogic
- setEditingAlert: (alert: LogsAlertConfigurationApi | null) => {
- alert: LogsAlertConfigurationApi | null
- } // logsAlertingLogic
- setIsCreating: (isCreating: boolean) => {
- isCreating: boolean
- } // logsAlertingLogic
clearSimulation: () => {
value: true
}
@@ -229,7 +231,7 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
],
actions: [
logsAlertingLogic,
- ['loadAlerts', 'setEditingAlert', 'setIsCreating'],
+ ['loadAlerts'],
logsAlertNotificationLogic({ alertId: alert?.id }),
['createPendingHogFunctions'],
],
@@ -333,8 +335,8 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
cooldown_minutes: form.cooldownMinutes,
}
+ let savedAlertId: string
try {
- let savedAlertId: string
if (props.alert) {
const patch: PatchedLogsAlertConfigurationApi = { ...payload }
await logsAlertsPartialUpdate(projectId, props.alert.id, patch)
@@ -345,24 +347,33 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
savedAlertId = created.id
lemonToast.success('Alert created')
}
+ } catch (error: unknown) {
+ lemonToast.error(saveErrorMessage(error as ApiError))
+ throw error
+ }
+ let notificationsConfigured = true
+ try {
if (values.pendingNotifications.length > 0) {
const notifLogic = logsAlertNotificationLogic({ alertId: props.alert?.id })
await notifLogic.asyncActions.createPendingHogFunctions(savedAlertId)
+ notificationsConfigured = notifLogic.values.pendingNotifications.length === 0
}
+ } catch {
+ notificationsConfigured = false
+ if (props.alert) {
+ lemonToast.error('Alert updated, but notifications could not be configured.')
+ } else {
+ lemonToast.error('Alert created, but notifications could not be configured.')
+ }
+ }
- actions.setEditingAlert(null)
- actions.setIsCreating(false)
- actions.loadAlerts()
- } catch (e: any) {
- const message =
- typeof e?.detail === 'string'
- ? e.detail
- : typeof e?.message === 'string'
- ? e.message
- : 'Failed to save alert'
- lemonToast.error(message)
- throw e
+ actions.loadAlerts()
+ if (!props.alert) {
+ props.onCreateSuccess?.()
+ if (!notificationsConfigured) {
+ router.actions.push(urls.logsAlertDetail(savedAlertId, 'notifications'))
+ }
}
return form
},
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
index f4e6cf7f3402..d63033d14225 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts
@@ -445,6 +445,9 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([
const failedNotifications = pending.filter((_, i) => results[i].status === 'rejected')
+ actions.loadExistingHogFunctions(alertId)
+ actions.destinationsChanged()
+
if (failedNotifications.length > 0) {
lemonToast.error(
`Alert saved, but ${failedNotifications.length} notification(s) failed to create. Reopen the alert to add them again.`
@@ -456,9 +459,6 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([
}
actions.clearPendingNotifications()
}
-
- actions.loadExistingHogFunctions(alertId)
- actions.destinationsChanged()
},
})),
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts
index fc23f1f7fe0d..3e38032eafab 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts
@@ -10,7 +10,6 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import {
- logsAlertsCreate,
logsAlertsDestroy,
logsAlertsList,
logsAlertsPartialUpdate,
@@ -28,16 +27,13 @@ export interface logsAlertingLogicValues {
alerts: LogsAlertConfigurationApi[]
alertsLoading: boolean
createdByFilter: string | null
- creatingAlert: boolean
- editingAlert: LogsAlertConfigurationApi | null
- isCreating: boolean
+ isCreateAlertModalOpen: boolean
resettingAlertIds: Set<string>
- viewingHistoryAlert: LogsAlertConfigurationApi | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertingLogicActions {
- createAlertAndOpen: () => {
+ closeCreateAlertModal: () => {
value: true
}
deleteAlert: (id: string) => {
@@ -58,21 +54,15 @@ export interface logsAlertingLogicActions {
alerts: LogsAlertConfigurationApi[]
payload?: any
}
+ openCreateAlertModal: () => {
+ value: true
+ }
resetAlert: (id: string) => {
id: string
}
setCreatedByFilter: (createdByFilter: string | null) => {
createdByFilter: string | null
}
- setCreatingAlert: (creating: boolean) => {
- creating: boolean
- }
- setEditingAlert: (alert: LogsAlertConfigurationApi | null) => {
- alert: LogsAlertConfigurationApi | null
- }
- setIsCreating: (isCreating: boolean) => {
- isCreating: boolean
- }
setResettingAlertId: (
id: string,
resetting: boolean
@@ -80,9 +70,6 @@ export interface logsAlertingLogicActions {
id: string
resetting: boolean
}
- setViewingHistoryAlert: (alert: LogsAlertConfigurationApi | null) => {
- alert: LogsAlertConfigurationApi | null
- }
snoozeAlert: (
alertId: string,
durationMinutes: number
@@ -108,18 +95,15 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
}),
actions({
- setEditingAlert: (alert: LogsAlertConfigurationApi | null) => ({ alert }),
setCreatedByFilter: (createdByFilter: string | null) => ({ createdByFilter }),
- setIsCreating: (isCreating: boolean) => ({ isCreating }),
deleteAlert: (id: string) => ({ id }),
toggleAlertEnabled: (alert: LogsAlertConfigurationApi) => ({ alert }),
resetAlert: (id: string) => ({ id }),
setResettingAlertId: (id: string, resetting: boolean) => ({ id, resetting }),
- setViewingHistoryAlert: (alert: LogsAlertConfigurationApi | null) => ({ alert }),
snoozeAlert: (alertId: string, durationMinutes: number) => ({ alertId, durationMinutes }),
unsnoozeAlert: (alertId: string) => ({ alertId }),
- createAlertAndOpen: true,
- setCreatingAlert: (creating: boolean) => ({ creating }),
+ openCreateAlertModal: true,
+ closeCreateAlertModal: true,
}),
reducers({
@@ -129,20 +113,6 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
setCreatedByFilter: (_, { createdByFilter }) => createdByFilter,
},
],
- editingAlert: [
- null as LogsAlertConfigurationApi | null,
- {
- setEditingAlert: (_, { alert }) => alert,
- setIsCreating: () => null,
- },
- ],
- isCreating: [
- false,
- {
- setIsCreating: (_, { isCreating }) => isCreating,
- setEditingAlert: () => false,
- },
- ],
resettingAlertIds: [
new Set<string>(),
{
@@ -150,16 +120,11 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
resetting ? new Set([...state, id]) : new Set([...state].filter((x) => x !== id)),
},
],
- viewingHistoryAlert: [
- null as LogsAlertConfigurationApi | null,
- {
- setViewingHistoryAlert: (_, { alert }) => alert,
- },
- ],
- creatingAlert: [
+ isCreateAlertModalOpen: [
false,
{
- setCreatingAlert: (_, { creating }) => creating,
+ openCreateAlertModal: () => true,
+ closeCreateAlertModal: () => false,
},
],
}),
@@ -222,13 +187,8 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
const projectId = String(values.currentTeamId)
actions.setResettingAlertId(id, true)
try {
- const updated = await logsAlertsResetCreate(projectId, id)
+ await logsAlertsResetCreate(projectId, id)
lemonToast.success('Alert reset — next check will run shortly.')
- // Refresh the modal's snapshot so the "broken" banner disappears without
- // waiting for the list reload to round-trip.
- if (values.editingAlert?.id === id) {
- actions.setEditingAlert(updated)
- }
actions.loadAlerts()
} catch {
lemonToast.error('Failed to reset alert')
@@ -257,19 +217,6 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
lemonToast.error('Failed to unsnooze alert')
}
},
- createAlertAndOpen: async () => {
- const projectId = String(values.currentTeamId)
- actions.setCreatingAlert(true)
- try {
- const created = await logsAlertsCreate(projectId, { enabled: false })
- router.actions.push(urls.logsAlertDetail(created.id))
- actions.loadAlerts()
- } catch (e: any) {
- lemonToast.error(e?.detail ?? e?.message ?? 'Failed to create alert')
- } finally {
- actions.setCreatingAlert(false)
- }
- },
})),
subscriptions(({ actions }) => ({
@@ -280,13 +227,11 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
},
})),
- afterMount(({ actions, values, cache }) => {
+ afterMount(({ actions, cache }) => {
actions.loadAlerts()
cache.disposables.add(() => {
const intervalId = window.setInterval(() => {
- if (!values.isCreating && values.editingAlert === null && values.viewingHistoryAlert === null) {
- actions.loadAlerts()
- }
+ actions.loadAlerts()
}, ALERT_POLL_INTERVAL_MS)
return () => clearInterval(intervalId)
}, 'pollAlerts')