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): align log alert editing with insight alerts (#82165)

Matt Pua74e1e6da3108
diff --git a/frontend/src/lib/components/DateFilter/DateFilter.tsx b/frontend/src/lib/components/DateFilter/DateFilter.tsx
index 39503af1ad93..e3e90cd32033 100644
--- a/frontend/src/lib/components/DateFilter/DateFilter.tsx
+++ b/frontend/src/lib/components/DateFilter/DateFilter.tsx
@@ -57,6 +57,7 @@ export interface DateFilterProps {
resolvedDateRange?: ResolvedDateRangeResponse
showJumpToTimestamp?: boolean
showCustomRelativeRange?: boolean
+ footerComponent?: (onClose: () => void) => React.ReactNode
/**
* When true, surfaces every option — presets, rolling picker, "Custom date…" (single exact),
* "Custom fixed date range…", and "Custom relative range…" — in one flat list. Callers opt
@@ -129,6 +130,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
showCustomRelativeRange = false,
allowSingleAndRange = false,
onOpenChange,
+ footerComponent,
},
ref
) {
@@ -202,7 +204,12 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
const showFixedRangeTimeToggle = allowTimePrecision || allowFixedRangeWithTime
const showExclusions =
(showIncompletePeriodExclusion || showDaysOfWeekExclusions) && !!exclusions && !!onExclusionsChange
- const showFooter = showCustomRangeOptions || showExplicitDateToggle || showExclusions || showJumpToTimestamp
+ const showFooter =
+ showCustomRangeOptions ||
+ showExplicitDateToggle ||
+ showExclusions ||
+ showJumpToTimestamp ||
+ Boolean(footerComponent)
const popoverOverlay =
view === DateFilterView.FixedRange ? (
@@ -405,6 +412,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
)}
</>
)}
+ {footerComponent?.(close)}
{showCustomRangeOptions && (showExplicitDateToggle || showExclusions) && <LemonDivider />}
{showExplicitDateToggle && (
<div
diff --git a/products/alerts/frontend/AlertsScene.tsx b/products/alerts/frontend/AlertsScene.tsx
index b7d56fe1d0ab..9d58ba8c7ae8 100644
--- a/products/alerts/frontend/AlertsScene.tsx
+++ b/products/alerts/frontend/AlertsScene.tsx
@@ -4,7 +4,6 @@ import { router } from 'kea-router'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
import { Alerts } from './views/Alerts'
@@ -15,11 +14,6 @@ export function AlertsScene(): JSX.Element {
return (
<SceneContent>
- <SceneTitleSection
- name="Alerts"
- description="Monitor insight metrics and get notified when conditions are met."
- resourceType={{ type: 'inbox' }}
- />
<Alerts alertId={alertId} />
</SceneContent>
)
diff --git a/products/alerts/frontend/components/AlertSummaryBanner.tsx b/products/alerts/frontend/components/AlertSummaryBanner.tsx
index f9a343ae5f04..7a8135555709 100644
--- a/products/alerts/frontend/components/AlertSummaryBanner.tsx
+++ b/products/alerts/frontend/components/AlertSummaryBanner.tsx
@@ -9,11 +9,13 @@ export function AlertSummaryBanner({
header,
footer,
activeSection,
+ showCadence = true,
}: {
summary: AlertSummaryParts
header?: ReactNode
footer?: ReactNode
activeSection?: AlertSummarySection
+ showCadence?: boolean
}): JSX.Element {
const fires = summary.fires || 'a threshold'
const cadence = summary.cadence || 'unscheduled'
@@ -29,13 +31,24 @@ export function AlertSummaryBanner({
label="Fires when"
value={fires}
/>
- <SummarySection
- active={activeSection === 'schedule'}
- dataAttr="alert-summary-schedule"
- label="runs"
- value={cadence}
- separated
- />
+ {showCadence ? (
+ <SummarySection
+ active={activeSection === 'schedule'}
+ dataAttr="alert-summary-schedule"
+ label="runs"
+ value={cadence}
+ separated
+ />
+ ) : null}
+ {summary.filters ? (
+ <SummarySection
+ active={activeSection === 'monitor'}
+ dataAttr="alert-summary-filters"
+ label="matching"
+ value={summary.filters}
+ separated
+ />
+ ) : null}
<SummarySection
active={activeSection === 'notify'}
dataAttr="alert-summary-notify"
diff --git a/products/alerts/frontend/components/SnoozeButton.tsx b/products/alerts/frontend/components/SnoozeButton.tsx
index 6fbe4dbce2fc..1ec70a70f689 100644
--- a/products/alerts/frontend/components/SnoozeButton.tsx
+++ b/products/alerts/frontend/components/SnoozeButton.tsx
@@ -1,5 +1,5 @@
import { IconCalendar } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
+import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { dayjs } from 'lib/dayjs'
@@ -9,11 +9,12 @@ const DATETIME_FORMAT = 'MMM D - HH:mm'
interface SnoozeButtonProps {
onChange: (snoonzeUntil: string) => void
+ onClear?: () => void
value?: string
disabledReason?: string
}
-export function SnoozeButton({ onChange, value, disabledReason }: SnoozeButtonProps): JSX.Element {
+export function SnoozeButton({ onChange, onClear, value, disabledReason }: SnoozeButtonProps): JSX.Element {
if (disabledReason) {
return (
<LemonButton type="secondary" size="medium" icon={<IconCalendar />} disabledReason={disabledReason}>
@@ -22,35 +23,71 @@ export function SnoozeButton({ onChange, value, disabledReason }: SnoozeButtonPr
)
}
+ const footerComponent =
+ onClear && value
+ ? (onClose: () => void): JSX.Element => (
+ <>
+ <LemonDivider />
+ <LemonButton
+ onClick={() => {
+ onClear()
+ onClose()
+ }}
+ size="medium"
+ status="danger"
+ fullWidth
+ >
+ Clear snooze
+ </LemonButton>
+ </>
+ )
+ : undefined
+
return (
- <DateFilter
- dateFrom={value ?? null}
- onChange={(snoozeUntil) => {
- if (snoozeUntil) {
- onChange(snoozeUntil)
- }
- }}
- placeholder="Snooze until"
- max={31}
- isFixedDateMode
- showRollingRangePicker={false}
- allowedRollingDateOptions={['days', 'weeks', 'months', 'years']}
- showCustom
- dateOptions={[
- {
- key: 'Tomorrow',
- values: ['+1d'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDate(date.add(1, 'd'), DATETIME_FORMAT),
- defaultInterval: 'day',
- },
- {
- key: 'One week from now',
- values: ['+1w'],
- getFormattedDate: (date: dayjs.Dayjs): string => formatDate(date.add(1, 'w'), DATETIME_FORMAT),
- defaultInterval: 'day',
- },
- ]}
- size="medium"
- />
+ <div className="flex items-center gap-2">
+ {value ? <span className="text-sm text-muted-alt">Snoozed until</span> : null}
+ <DateFilter
+ dateFrom={value ?? null}
+ onChange={(snoozeUntil) => {
+ if (snoozeUntil) {
+ onChange(snoozeUntil)
+ }
+ }}
+ placeholder="Snooze until"
+ max={31}
+ isFixedDateMode
+ showRollingRangePicker={false}
+ allowedRollingDateOptions={['days', 'weeks', 'months', 'years']}
+ showCustom
+ footerComponent={footerComponent}
+ dateOptions={[
+ {
+ key: '30 minutes',
+ values: ['+30m'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDate(date.add(30, 'm'), DATETIME_FORMAT),
+ defaultInterval: 'minute',
+ },
+ {
+ key: '1 hour',
+ values: ['+1h'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDate(date.add(1, 'h'), DATETIME_FORMAT),
+ defaultInterval: 'hour',
+ },
+ {
+ key: '4 hours',
+ values: ['+4h'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDate(date.add(4, 'h'), DATETIME_FORMAT),
+ defaultInterval: 'hour',
+ },
+ {
+ key: '24 hours',
+ values: ['+24h'],
+ getFormattedDate: (date: dayjs.Dayjs): string => formatDate(date.add(24, 'h'), DATETIME_FORMAT),
+ defaultInterval: 'day',
+ },
+ ]}
+ size="medium"
+ />
+ </div>
)
}
diff --git a/products/alerts/frontend/components/alertSummary.ts b/products/alerts/frontend/components/alertSummary.ts
index 3ef8707bbb0c..cfd87f164b80 100644
--- a/products/alerts/frontend/components/alertSummary.ts
+++ b/products/alerts/frontend/components/alertSummary.ts
@@ -11,6 +11,8 @@ export interface AlertSummaryParts {
cadence: string
/** Who it notifies — e.g. "2 people" or "2 people + Slack". Empty when none configured. */
notifies: string
+ /** What the alert matches before it evaluates the trigger. Empty when all data matches. */
+ filters?: string
}
const ALERT_KIND_LABELS: Partial<Record<AlertConfig['type'], string>> = {
diff --git a/products/alerts/frontend/logic/alertFormLogic.ts b/products/alerts/frontend/logic/alertFormLogic.ts
index 5f81a79f0a5f..ba9bd9b3ace7 100644
--- a/products/alerts/frontend/logic/alertFormLogic.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.ts
@@ -30,6 +30,7 @@ import {
getDefaultSimulationRange,
isSubDailyAlertInterval,
} from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { resolveSnoozeUntil } from 'products/alerts/frontend/utils'
import {
AlertConfig,
@@ -863,7 +864,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
throw new Error("Cannot snooze alert that doesn't exist")
}
const updatedAlert: AlertType = await api.alerts.update(values.alertForm.id, {
- snoozed_until: snoozeUntil,
+ snoozed_until: resolveSnoozeUntil(snoozeUntil),
})
hydrateAlertLogicFromSaveResponse(updatedAlert)
const parent = getParentLogic()
diff --git a/products/alerts/frontend/utils.ts b/products/alerts/frontend/utils.ts
index 76e841d5baef..8319b3b41dc1 100644
--- a/products/alerts/frontend/utils.ts
+++ b/products/alerts/frontend/utils.ts
@@ -1,3 +1,5 @@
+import { dayjs } from 'lib/dayjs'
+
import { AlertState } from '~/queries/schema/schema-general'
import type { AlertCheck, AlertCheckDelivery } from './types'
@@ -7,6 +9,32 @@ export enum AlertsTab {
LOGS = 'logs',
}
+export function resolveSnoozeUntil(value: string): string {
+ const relativeValue = value.match(/^\+(\d+)([mhdwMy])$/)
+ if (!relativeValue) {
+ return dayjs(value).toISOString()
+ }
+
+ const amount = Number(relativeValue[1])
+ const unit = relativeValue[2]
+ if (unit === 'm') {
+ return dayjs().add(amount, 'minute').toISOString()
+ }
+ if (unit === 'h') {
+ return dayjs().add(amount, 'hour').toISOString()
+ }
+ if (unit === 'd') {
+ return dayjs().add(amount, 'day').toISOString()
+ }
+ if (unit === 'w') {
+ return dayjs().add(amount, 'week').toISOString()
+ }
+ if (unit === 'M') {
+ return dayjs().add(amount, 'month').toISOString()
+ }
+ return dayjs().add(amount, 'year').toISOString()
+}
+
interface AlertsAccessState {
alertId: string | null
requestedTab: string | undefined
diff --git a/products/alerts/frontend/views/Alerts.tsx b/products/alerts/frontend/views/Alerts.tsx
index 9717766b620d..1d9266e909c9 100644
--- a/products/alerts/frontend/views/Alerts.tsx
+++ b/products/alerts/frontend/views/Alerts.tsx
@@ -1,8 +1,8 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { Suspense } from 'react'
+import { Suspense, useEffect } from 'react'
-import { LemonTabs, SpinnerOverlay } from '@posthog/lemon-ui'
+import { LemonSkeleton, LemonTabs } from '@posthog/lemon-ui'
import { AccessDenied } from 'lib/components/AccessDenied'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
@@ -10,31 +10,47 @@ import { getAppContext } from 'lib/utils/getAppContext'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { urls } from 'scenes/urls'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { AlertType } from '../types'
import { AlertsTab, getActiveAlertsTab, getAlertsTabs } from '../utils'
-const InsightAlerts = lazyWithRetry(() =>
- import('./InsightAlerts').then((module) => ({
- default: module.InsightAlerts,
- }))
-)
-
-const LogsAlertingSection = lazyWithRetry(() =>
+const loadInsightAlerts = (): Promise<{ default: typeof import('./InsightAlerts').InsightAlerts }> =>
+ import('./InsightAlerts').then((module) => ({ default: module.InsightAlerts }))
+const loadLogsAlertingSection = (): Promise<{
+ default: typeof import('products/logs/frontend/components/LogsAlerting/LogsAlertingSection').LogsAlertingSection
+}> =>
import('products/logs/frontend/components/LogsAlerting/LogsAlertingSection').then((module) => ({
default: module.LogsAlertingSection,
}))
-)
+
+const InsightAlerts = lazyWithRetry(loadInsightAlerts)
+const LogsAlertingSection = lazyWithRetry(loadLogsAlertingSection)
interface AlertsProps {
alertId: AlertType['id'] | null
}
+const ALERTS_DESCRIPTION: Record<AlertsTab, string> = {
+ [AlertsTab.INSIGHTS]: 'Monitor insight metrics and get notified when conditions are met.',
+ [AlertsTab.LOGS]: 'Monitor matching logs and get notified when they cross a threshold.',
+}
+
function hasEffectiveResourceAccess(resourceType: AccessControlResourceType): boolean {
return getAppContext()?.effective_resource_access_control?.[resourceType] !== AccessControlLevel.None
}
+function AlertsPanelSkeleton(): JSX.Element {
+ return (
+ <div className="space-y-4 p-4">
+ <LemonSkeleton className="h-10 w-full" />
+ <LemonSkeleton className="h-32 w-full" />
+ <LemonSkeleton className="h-32 w-full" />
+ </div>
+ )
+}
+
export function Alerts({ alertId }: AlertsProps): JSX.Element {
const { push } = useActions(router)
const { searchParams } = useValues(router)
@@ -42,6 +58,11 @@ export function Alerts({ alertId }: AlertsProps): JSX.Element {
const canViewInsightAlerts = hasEffectiveResourceAccess(AccessControlResourceType.Insight)
const canViewLogAlerts = showLogAlerts && hasEffectiveResourceAccess(AccessControlResourceType.Logs)
+ useEffect(() => {
+ void loadInsightAlerts()
+ void loadLogsAlertingSection()
+ }, [])
+
const activeTab = getActiveAlertsTab({
alertId,
requestedTab: typeof searchParams.alert_type === 'string' ? searchParams.alert_type : undefined,
@@ -64,8 +85,13 @@ export function Alerts({ alertId }: AlertsProps): JSX.Element {
return (
<>
+ <SceneTitleSection
+ name="Alerts"
+ description={ALERTS_DESCRIPTION[activeTab]}
+ resourceType={{ type: 'inbox' }}
+ />
<LemonTabs<AlertsTab> activeKey={activeTab} onChange={switchTab} tabs={tabs} sceneInset />
- <Suspense fallback={<SpinnerOverlay />}>
+ <Suspense fallback={<AlertsPanelSkeleton />}>
{activeTab === AlertsTab.LOGS ? <LogsAlertingSection /> : <InsightAlerts alertId={alertId} />}
</Suspense>
</>
diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsx
index b73dddc32821..acabab8e6b38 100644
--- a/products/alerts/frontend/views/EditAlertModal.tsx
+++ b/products/alerts/frontend/views/EditAlertModal.tsx
@@ -46,7 +46,7 @@ import type { AlertType } from '../types'
import { AlertHistorySection } from './AlertHistorySection'
import { AlertEnabledAction, AlertLeadingActions } from './EditAlertModal/AlertLeadingActions'
import { buildWizardSteps } from './EditAlertModal/buildWizardSteps'
-import { EditAlertTabs } from './EditAlertModal/EditAlertTabs'
+import { defaultAlertTabs, EditAlertTabs } from './EditAlertModal/EditAlertTabs'
interface AlertModalCommonProps {
isOpen: boolean | undefined
@@ -457,41 +457,55 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {
trailingActions={<AlertEnabledAction alertForm={alertForm} />}
>
<div className="space-y-3">
- <EditAlertTabs
- summary={summary}
- summaryHeader={
- alert ? (
- <div className="flex items-center justify-between gap-3">
- <span className="font-medium">Current status</span>
- <AlertStateIndicator alert={alert} />
+ {(() => {
+ const tabs = defaultAlertTabs({
+ monitorContent: (
+ <div className="space-y-3 pt-3">
+ <AlertEditorFormDetails
+ nameError={nameError}
+ activity={
+ alert?.created_by ? (
+ <UserActivityIndicator
+ at={alert.created_at}
+ by={alert.created_by}
+ prefix="Created"
+ />
+ ) : undefined
+ }
+ />
+ {previewNode}
+ {definitionNode}
</div>
- ) : undefined
- }
- nameNode={
- <AlertEditorFormDetails
- nameError={nameError}
- activity={
- alert?.created_by ? (
- <UserActivityIndicator
- at={alert.created_at}
- by={alert.created_by}
- prefix="Created"
- />
+ ),
+ scheduleContent: (
+ <div className="space-y-3 pt-3">
+ {scheduleNode}
+ {advancedNode}
+ </div>
+ ),
+ notifyContent: <div className="pt-3">{notifyNode}</div>,
+ historyContent:
+ alertId && alert ? (
+ <div className="pt-3">
+ <AlertHistorySection alertId={alert.id} showCurrentStatus={false} />
+ </div>
+ ) : undefined,
+ })
+ return (
+ <EditAlertTabs
+ summary={summary}
+ summaryHeader={
+ alert ? (
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium">Current status</span>
+ <AlertStateIndicator alert={alert} />
+ </div>
) : undefined
}
+ tabs={tabs}
/>
- }
- previewNode={previewNode}
- definitionNode={definitionNode}
- scheduleNode={scheduleNode}
- advancedNode={advancedNode}
- notifyNode={notifyNode}
- historyNode={
- alertId && alert ? (
- <AlertHistorySection alertId={alert.id} showCurrentStatus={false} />
- ) : null
- }
- />
+ )
+ })()}
</div>
</AlertEditor>
)}
diff --git a/products/alerts/frontend/views/EditAlertModal/EditAlertTabs.tsx b/products/alerts/frontend/views/EditAlertModal/EditAlertTabs.tsx
index 547a71aea6b6..a72d2dd273ed 100644
--- a/products/alerts/frontend/views/EditAlertModal/EditAlertTabs.tsx
+++ b/products/alerts/frontend/views/EditAlertModal/EditAlertTabs.tsx
@@ -1,100 +1,58 @@
import { useState } from 'react'
-import { IconBell, IconClock, IconGraph, IconPulse } from '@posthog/icons'
import { LemonTabs } from '@posthog/lemon-ui'
import type { LemonTab } from '@posthog/lemon-ui'
import { AlertSummaryBanner, AlertSummarySection } from 'products/alerts/frontend/components/AlertSummaryBanner'
+export type EditAlertTab = LemonTab<string> & { summarySection?: AlertSummarySection }
+
+export function defaultAlertTabs({
+ monitorContent,
+ scheduleContent,
+ notifyContent,
+ historyContent,
+}: {
+ monitorContent: JSX.Element
+ scheduleContent: JSX.Element
+ notifyContent: JSX.Element
+ historyContent?: JSX.Element
+}): EditAlertTab[] {
+ return [
+ { key: 'monitor', summarySection: 'monitor', label: 'Monitor', content: monitorContent },
+ { key: 'schedule', summarySection: 'schedule', label: 'Schedule', content: scheduleContent },
+ { key: 'notify', summarySection: 'notify', label: 'Notify', content: notifyContent },
+ ...(historyContent ? [{ key: 'history', label: 'History', content: historyContent }] : []),
+ ]
+}
+
interface EditAlertTabsProps {
summary: { fires: string; cadence: string; notifies: string }
summaryHeader?: React.ReactNode
- nameNode: React.ReactNode
- previewNode: React.ReactNode
- definitionNode: React.ReactNode
- scheduleNode: React.ReactNode
- advancedNode: React.ReactNode
- notifyNode: React.ReactNode
- historyNode: React.ReactNode | null
+ statusNode?: React.ReactNode
+ tabs: EditAlertTab[]
+ showCadence?: boolean
}
export function EditAlertTabs({
summary,
summaryHeader,
- nameNode,
- previewNode,
- definitionNode,
- scheduleNode,
- advancedNode,
- notifyNode,
- historyNode,
+ statusNode,
+ tabs,
+ showCadence,
}: EditAlertTabsProps): JSX.Element {
const [activeKey, setActiveKey] = useState<string>('monitor')
-
- const tabs: (LemonTab<string> | null)[] = [
- {
- key: 'monitor',
- label: (
- <span className="flex items-center gap-1.5">
- <IconPulse className="size-4" />
- Monitor
- </span>
- ),
- content: (
- <div className="space-y-3 pt-3">
- {nameNode}
- {previewNode}
- {definitionNode}
- </div>
- ),
- },
- {
- key: 'schedule',
- label: (
- <span className="flex items-center gap-1.5">
- <IconClock className="size-4" />
- Schedule
- </span>
- ),
- content: (
- <div className="space-y-3 pt-3">
- {scheduleNode}
- {advancedNode}
- </div>
- ),
- },
- {
- key: 'notify',
- label: (
- <span className="flex items-center gap-1.5">
- <IconBell className="size-4" />
- Notify
- </span>
- ),
- content: <div className="pt-3">{notifyNode}</div>,
- },
- historyNode
- ? {
- key: 'history',
- label: (
- <span className="flex items-center gap-1.5">
- <IconGraph className="size-4" />
- History
- </span>
- ),
- content: <div className="pt-3">{historyNode}</div>,
- }
- : null,
- ]
-
- let activeSummarySection: AlertSummarySection | undefined
- if (['monitor', 'schedule', 'notify'].includes(activeKey)) {
- activeSummarySection = activeKey as AlertSummarySection
- }
+ const activeSummarySection = tabs.find((tab) => tab.key === activeKey)?.summarySection
return (
<div className="space-y-3">
- <AlertSummaryBanner summary={summary} header={summaryHeader} activeSection={activeSummarySection} />
+ <AlertSummaryBanner
+ summary={summary}
+ header={summaryHeader}
+ activeSection={activeSummarySection}
+ showCadence={showCadence}
+ />
+ {statusNode}
<LemonTabs tabs={tabs} activeKey={activeKey} onChange={setActiveKey} className="flex-1 min-h-0" />
</div>
)
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
index 7cc5e717acee..f7f32e59b91f 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
@@ -28,7 +28,7 @@ export function LogsAlertCreateModal({ isOpen, onClose }: LogsAlertCreateModalPr
}
function LogsAlertCreateModalContent({ onClose }: { onClose: () => void }): JSX.Element {
- const formLogicProps = { alert: null, onCreateSuccess: onClose }
+ const formLogicProps = { alert: null, onSubmitSuccess: onClose }
const { isAlertFormSubmitting, alertFormChanged, alertForm } = useValues(logsAlertFormLogic(formLogicProps))
const { touchAlertFormField } = useActions(logsAlertFormLogic(formLogicProps))
const { pendingNotifications } = useValues(logsAlertNotificationLogic({}))
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEditModal.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEditModal.tsx
new file mode 100644
index 000000000000..0170f5828a78
--- /dev/null
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEditModal.tsx
@@ -0,0 +1,241 @@
+import { BindLogic, useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { IconBell, IconGraph, IconList, IconPulse, IconTarget } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonModal, LemonSwitch } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { AlertEditor, AlertEditorFormDetails } from 'products/alerts/frontend/components/AlertEditor'
+import { AlertSummaryParts } from 'products/alerts/frontend/components/alertSummary'
+import { SnoozeButton } from 'products/alerts/frontend/components/SnoozeButton'
+import { EditAlertTab, EditAlertTabs } from 'products/alerts/frontend/views/EditAlertModal/EditAlertTabs'
+import { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'
+
+import { LogsAlertEventHistoryContent } from './LogsAlertEventHistory'
+import { LogsAlertFilters, LogsAlertTrigger } from './LogsAlertForm'
+import { logsAlertFormLogic } from './logsAlertFormLogic'
+import { logsAlertingLogic } from './logsAlertingLogic'
+import { logsAlertNotificationLogic } from './logsAlertNotificationLogic'
+import { LogsAlertNotifications } from './LogsAlertNotifications'
+import { LogsAlertSimulation } from './LogsAlertSimulation'
+import { LogsAlertStateIndicator } from './LogsAlertStateIndicator'
+import { LogsAlertStateTimeline } from './LogsAlertStateTimeline'
+
+interface LogsAlertEditModalProps {
+ alert: LogsAlertConfigurationApi | null
+ onClose: () => void
+}
+
+export function LogsAlertEditModal({ alert, onClose }: LogsAlertEditModalProps): JSX.Element {
+ return (
+ <LemonModal isOpen={alert !== null} onClose={onClose} title="" simple width={900}>
+ {alert ? <LogsAlertEditModalContent alert={alert} onClose={onClose} /> : null}
+ </LemonModal>
+ )
+}
+
+function LogsAlertEditModalContent({
+ alert,
+ onClose,
+}: {
+ alert: LogsAlertConfigurationApi
+ onClose: () => void
+}): JSX.Element {
+ const formLogicProps = { alert, onSubmitSuccess: onClose }
+ const notificationLogicProps = { alertId: alert.id }
+ const { isAlertFormSubmitting, alertFormChanged, alertFormErrors, alertForm } = useValues(
+ logsAlertFormLogic(formLogicProps)
+ )
+ const { touchAlertFormField } = useActions(logsAlertFormLogic(formLogicProps))
+ const { destinationGroups } = useValues(logsAlertNotificationLogic(notificationLogicProps))
+ const { snoozingAlertIds } = useValues(logsAlertingLogic)
+ const { deleteAlert, snoozeAlertUntil, toggleAlertEnabled, unsnoozeAlert } = useActions(logsAlertingLogic)
+ const nameError = alertFormErrors.name as string | undefined
+ const filterParts: string[] = []
+ if (alertForm.severityLevels.length > 0) {
+ filterParts.push(`${alertForm.severityLevels.join(', ')} logs`)
+ }
+ if (alertForm.serviceNames.length > 0) {
+ filterParts.push(`from ${alertForm.serviceNames.join(', ')}`)
+ }
+ if (alertForm.filterGroup.values.length > 0) {
+ const attributeCount = alertForm.filterGroup.values.length
+ filterParts.push(`${attributeCount} ${attributeCount === 1 ? 'attribute filter' : 'attribute filters'}`)
+ }
+ const summary: AlertSummaryParts = {
+ fires: `count ${alertForm.thresholdOperator} ${alertForm.thresholdCount} in the last ${alertForm.windowMinutes} minutes`,
+ cadence: '',
+ notifies: destinationGroups.length
+ ? `${destinationGroups.length} ${destinationGroups.length === 1 ? 'destination' : 'destinations'}`
+ : '',
+ filters: filterParts.join(' '),
+ }
+ const tabs: EditAlertTab[] = [
+ {
+ key: 'monitor',
+ summarySection: 'monitor',
+ label: (
+ <>
+ <IconPulse className="size-4" />
+ Monitor
+ </>
+ ),
+ content: (
+ <div className="space-y-3 pt-3">
+ <AlertEditorFormDetails nameError={nameError} />
+ <div className="max-w-2xl space-y-6">
+ <LogsAlertFilters />
+ </div>
+ </div>
+ ),
+ },
+ {
+ key: 'trigger',
+ summarySection: 'monitor',
+ label: (
+ <>
+ <IconTarget className="size-4" />
+ Trigger
+ </>
+ ),
+ content: (
+ <div className="max-w-2xl space-y-6 pt-3">
+ <LogsAlertTrigger />
+ <LogsAlertSimulation embedded />
+ </div>
+ ),
+ },
+ {
+ key: 'notify',
+ summarySection: 'notify',
+ label: (
+ <>
+ <IconBell className="size-4" />
+ Notify
+ </>
+ ),
+ content: (
+ <div className="pt-3">
+ <LogsAlertNotifications alertId={alert.id} />
+ </div>
+ ),
+ },
+ {
+ key: 'history',
+ label: (
+ <>
+ <IconGraph className="size-4" />
+ History
+ </>
+ ),
+ content: (
+ <div className="pt-3">
+ <LogsAlertEventHistoryContent alert={alert} />
+ </div>
+ ),
+ },
+ {
+ key: 'observed-logs',
+ label: (
+ <>
+ <IconList className="size-4" />
+ Observed logs
+ </>
+ ),
+ link: urls.logsAlertDetail(alert.id, 'logs'),
+ },
+ ]
+
+ const leadingActions = (
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ 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, onClose)
+ },
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }}
+ >
+ Delete alert
+ </LemonButton>
+ {(alert.enabled ?? true) ? (
+ <SnoozeButton
+ onChange={(snoozeUntil) => snoozeAlertUntil(alert.id, snoozeUntil)}
+ onClear={alert.snooze_until ? () => unsnoozeAlert(alert.id) : undefined}
+ value={alert.snooze_until ?? undefined}
+ disabledReason={snoozingAlertIds.has(alert.id) ? 'Updating snooze' : undefined}
+ />
+ ) : null}
+ </div>
+ )
+
+ return (
+ <BindLogic logic={logsAlertFormLogic} props={formLogicProps}>
+ <BindLogic logic={logsAlertNotificationLogic} props={notificationLogicProps}>
+ <Form
+ logic={logsAlertFormLogic}
+ props={formLogicProps}
+ formKey="alertForm"
+ enableFormOnSubmit
+ className="LemonModal__layout"
+ >
+ <AlertEditor
+ title="Edit alert"
+ className="min-h-0 flex-1 overflow-hidden"
+ contentClassName="min-h-0 flex-1 overflow-y-auto"
+ onBack={onClose}
+ isEditing
+ isSubmitting={isAlertFormSubmitting}
+ hasChanges={alertFormChanged}
+ onSubmitAttempted={() => touchAlertFormField('name')}
+ leadingActions={leadingActions}
+ trailingActions={
+ <LemonSwitch
+ checked={alert.enabled ?? true}
+ label="Enabled"
+ onChange={() => toggleAlertEnabled(alert)}
+ />
+ }
+ >
+ <EditAlertTabs
+ summary={summary}
+ summaryHeader={
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium">Current status</span>
+ <LogsAlertStateIndicator
+ state={alert.state}
+ enabled={alert.enabled ?? true}
+ firstEnabledAt={alert.first_enabled_at}
+ lastErrorMessage={alert.last_error_message}
+ snoozeUntil={alert.snooze_until}
+ />
+ </div>
+ }
+ statusNode={
+ <LogsAlertStateTimeline
+ timeline={alert.state_timeline}
+ className="h-8 w-full"
+ showAxis
+ />
+ }
+ tabs={tabs}
+ showCadence={false}
+ />
+ </AlertEditor>
+ </Form>
+ </BindLogic>
+ </BindLogic>
+ )
+}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
index a78ebf9b8318..0e61cc16cf3a 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
@@ -92,18 +92,20 @@ function LogsAlertEventTimeline({ alert }: { alert: LogsAlertConfigurationApi })
evaluationNoun="evaluation"
/>
) : null}
- <LemonTable
- columns={columns}
- dataSource={eventsPage.results}
- rowKey="id"
- loading={eventsPageLoading}
- emptyState="No events yet. Evaluations, transitions, and user actions will appear here."
- size="small"
- expandable={{
- rowExpandable: () => true,
- expandedRowRender: (event) => <LogsAlertEventDetails event={event} />,
- }}
- />
+ <div className="max-h-96 overflow-y-auto">
+ <LemonTable
+ columns={columns}
+ dataSource={eventsPage.results}
+ rowKey="id"
+ loading={eventsPageLoading}
+ emptyState="No events yet. Evaluations, transitions, and user actions will appear here."
+ size="small"
+ expandable={{
+ rowExpandable: () => true,
+ expandedRowRender: (event) => <LogsAlertEventDetails event={event} />,
+ }}
+ />
+ </div>
{hasMore ? (
<div className="flex justify-center">
<LemonButton type="secondary" size="small" onClick={loadMore} loading={eventsPageLoading}>
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx
index 5bd5716e1821..49d8e3638c16 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx
@@ -71,7 +71,7 @@ export function LogsAlertDestinationTags({
}
export function LogsAlertList(): JSX.Element {
- const { alerts, alertsLoading, resettingAlertIds, createdByFilter } = useValues(logsAlertingLogic)
+ const { alerts, alertsLoading, resettingAlertIds, snoozingAlertIds, createdByFilter } = useValues(logsAlertingLogic)
const {
setCreatedByFilter,
deleteAlert,
@@ -80,6 +80,7 @@ export function LogsAlertList(): JSX.Element {
snoozeAlert,
unsnoozeAlert,
openCreateAlertModal,
+ openEditAlertModal,
} = useActions(logsAlertingLogic)
const columns: LemonTableColumns<LogsAlertConfigurationApi> = [
@@ -87,7 +88,7 @@ export function LogsAlertList(): JSX.Element {
title: 'Name',
dataIndex: 'name',
render: (_, alert) => (
- <LemonButton type="tertiary" size="small" to={urls.logsAlertDetail(alert.id)}>
+ <LemonButton type="tertiary" size="small" onClick={() => openEditAlertModal(alert)}>
{alert.name}
</LemonButton>
),
@@ -98,7 +99,7 @@ export function LogsAlertList(): JSX.Element {
render: (_, alert) => (
<LogsAlertStateIndicator
state={alert.state}
- enabled={alert.enabled ?? true}
+ enabled={alert.enabled === true}
firstEnabledAt={alert.first_enabled_at}
lastErrorMessage={alert.last_error_message}
snoozeUntil={alert.snooze_until}
@@ -191,7 +192,7 @@ export function LogsAlertList(): JSX.Element {
dataIndex: 'enabled',
render: (_, alert) => (
<LemonSwitch
- checked={alert.enabled ?? true}
+ checked={alert.enabled === true}
onChange={() => toggleAlertEnabled(alert)}
disabledReason={
alert.state === LogsAlertConfigurationStateEnumApi.Broken
@@ -206,18 +207,28 @@ export function LogsAlertList(): JSX.Element {
title: '',
render: (_, alert) => {
const isResetting = resettingAlertIds.has(alert.id)
+ const isSnoozing = snoozingAlertIds.has(alert.id)
+ let snoozeMenuItem: LemonMenuItems[number] | false = false
+ if (alert.enabled === true && alert.state === LogsAlertConfigurationStateEnumApi.Snoozed) {
+ snoozeMenuItem = {
+ label: isSnoozing ? 'Unsnoozing…' : 'Unsnooze',
+ disabledReason: isSnoozing ? 'Updating snooze' : undefined,
+ onClick: () => unsnoozeAlert(alert.id),
+ }
+ } else if (alert.enabled === true) {
+ snoozeMenuItem = {
+ label: isSnoozing ? 'Snoozing…' : 'Snooze',
+ disabledReason: isSnoozing ? 'Updating snooze' : undefined,
+ items: SNOOZE_DURATIONS.map((duration) => ({
+ label: duration.label,
+ onClick: () => snoozeAlert(alert.id, duration.minutes),
+ })),
+ }
+ }
const menuItems: LemonMenuItems = [
- { label: 'Edit', to: urls.logsAlertDetail(alert.id) },
+ { label: 'Edit', onClick: () => openEditAlertModal(alert) },
{ 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),
- })),
- },
+ snoozeMenuItem,
alert.state === LogsAlertConfigurationStateEnumApi.Broken && {
label: isResetting ? 'Resetting…' : 'Reset alert',
disabledReason: isResetting ? 'Reset in progress' : undefined,
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
index 8de77912fb12..a6a8930c8365 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertingSection.tsx
@@ -3,6 +3,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import { LemonBanner, Link } from '@posthog/lemon-ui'
import { LogsAlertCreateModal } from './LogsAlertCreateModal'
+import { LogsAlertEditModal } from './LogsAlertEditModal'
import { logsAlertingLogic } from './logsAlertingLogic'
import { LogsAlertList } from './LogsAlertList'
@@ -15,8 +16,8 @@ export function LogsAlertingSection(): JSX.Element {
}
function LogsAlertingSectionContent(): JSX.Element {
- const { isCreateAlertModalOpen } = useValues(logsAlertingLogic)
- const { closeCreateAlertModal } = useActions(logsAlertingLogic)
+ const { isCreateAlertModalOpen, editingAlert } = useValues(logsAlertingLogic)
+ const { closeCreateAlertModal, closeEditAlertModal } = useActions(logsAlertingLogic)
return (
<>
@@ -34,6 +35,7 @@ function LogsAlertingSectionContent(): JSX.Element {
</LemonBanner>
<LogsAlertList />
<LogsAlertCreateModal isOpen={isCreateAlertModalOpen} onClose={closeCreateAlertModal} />
+ <LogsAlertEditModal alert={editingAlert} onClose={closeEditAlertModal} />
</>
)
}
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
index 7a3f8e7ee732..a2a8c27ac76a 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
@@ -1,20 +1,10 @@
import { FilterLogicalOperator, HogFunctionType, PropertyFilterType, PropertyOperator } from '~/types'
-import {
- LogsAlertConfigurationApi,
- LogsAlertThresholdOperatorEnumApi,
-} from 'products/logs/frontend/generated/api.schemas'
+import { LogsAlertThresholdOperatorEnumApi } from 'products/logs/frontend/generated/api.schemas'
import { LogsAlertFormType } from '../logsAlertFormLogic'
import { buildLogsAlertFilterConfig, groupLogsAlertDestinations, runPreEnableChecks } from '../logsAlertUtils'
-const baseAlert = (overrides: Partial<LogsAlertConfigurationApi> = {}): LogsAlertConfigurationApi =>
- ({
- id: 'a',
- destination_types: ['slack'],
- ...overrides,
- }) as LogsAlertConfigurationApi
-
const baseForm = (overrides: Partial<LogsAlertFormType> = {}): LogsAlertFormType => ({
name: 'A',
severityLevels: ['error'],
@@ -183,13 +173,12 @@ describe('logsAlertUtils', () => {
})
describe('runPreEnableChecks', () => {
- it('returns ok when filters and destinations are present', () => {
- expect(runPreEnableChecks(baseAlert(), baseForm())).toEqual({ ok: true })
+ it('returns ok when filters are present', () => {
+ expect(runPreEnableChecks(baseForm())).toEqual({ ok: true })
})
it('blocks when no filters', () => {
const result = runPreEnableChecks(
- baseAlert(),
baseForm({
severityLevels: [],
serviceNames: [],
@@ -199,21 +188,8 @@ describe('logsAlertUtils', () => {
expect(result).toEqual({ blocked: true, reason: 'Add at least one filter to enable' })
})
- it('warns when no destinations', () => {
- const result = runPreEnableChecks(baseAlert({ destination_types: [] }), baseForm())
- expect(result).toMatchObject({ warning: { title: 'No notifications configured' } })
- })
-
- it('blocks before warning when both apply', () => {
- const result = runPreEnableChecks(
- baseAlert({ destination_types: [] }),
- baseForm({
- severityLevels: [],
- serviceNames: [],
- filterGroup: { type: FilterLogicalOperator.And, values: [] },
- })
- )
- expect(result).toEqual({ blocked: true, reason: 'Add at least one filter to enable' })
+ it('allows an alert without notification destinations', () => {
+ expect(runPreEnableChecks(baseForm())).toEqual({ ok: true })
})
})
})
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
index b763bb0951c9..7b4b65f00b33 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
@@ -8,7 +8,17 @@ import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
-import { logsAlertsCreate, logsAlertsList, logsAlertsResetCreate } from 'products/logs/frontend/generated/api'
+import { resolveSnoozeUntil } from 'products/alerts/frontend/utils'
+import {
+ logsAlertsCreate,
+ logsAlertsList,
+ logsAlertsPartialUpdate,
+ logsAlertsResetCreate,
+} from 'products/logs/frontend/generated/api'
+import {
+ LogsAlertConfigurationApi,
+ LogsAlertConfigurationStateEnumApi,
+} from 'products/logs/frontend/generated/api.schemas'
import { logsAlertingLogic } from '../logsAlertingLogic'
@@ -32,6 +42,43 @@ 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>
+const mockPartialUpdate = logsAlertsPartialUpdate as jest.MockedFunction<typeof logsAlertsPartialUpdate>
+
+const MOCK_ALERT: LogsAlertConfigurationApi = {
+ id: 'alert-1',
+ name: 'Errors',
+ enabled: true,
+ filters: { severityLevels: ['error'] },
+ threshold_count: 100,
+ threshold_operator: 'above',
+ window_minutes: 5,
+ evaluation_periods: 1,
+ datapoints_to_alarm: 1,
+ cooldown_minutes: 0,
+ snooze_until: null,
+ check_interval_minutes: 5,
+ state: LogsAlertConfigurationStateEnumApi.NotFiring,
+ next_check_at: null,
+ last_notified_at: null,
+ last_checked_at: null,
+ consecutive_failures: 0,
+ last_error_message: null,
+ state_timeline: [],
+ destination_types: [],
+ first_enabled_at: null,
+ created_at: '2026-08-12T12:00:00.000Z',
+ created_by: {
+ id: 1,
+ uuid: 'user-1',
+ email: '[email protected]',
+ hedgehog_config: null,
+ },
+ updated_at: null,
+}
+
+function createMockAlert(overrides: Partial<LogsAlertConfigurationApi> = {}): LogsAlertConfigurationApi {
+ return { ...MOCK_ALERT, ...overrides }
+}
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve!: (value: T) => void
@@ -45,7 +92,7 @@ describe('logsAlertingLogic', () => {
beforeEach(() => {
initKeaTests()
jest.clearAllMocks()
- mockList.mockResolvedValue({ results: [] } as any)
+ mockList.mockResolvedValue({ count: 0, results: [] })
})
describe('createdByFilter', () => {
@@ -95,13 +142,13 @@ describe('logsAlertingLogic', () => {
await expectLogic(logic).toFinishAllListeners()
const previousProjectResponse = deferred<Awaited<ReturnType<typeof logsAlertsList>>>()
- const currentProjectAlerts = [{ id: 'current-project-alert' }] as any
+ const currentProjectAlerts = [createMockAlert({ id: 'current-project-alert' })]
const nextTeamId = MOCK_DEFAULT_TEAM.id + 1
mockList.mockImplementation((projectId) => {
if (projectId === String(MOCK_DEFAULT_TEAM.id)) {
return previousProjectResponse.promise
}
- return Promise.resolve({ results: currentProjectAlerts } as any)
+ return Promise.resolve({ count: currentProjectAlerts.length, results: currentProjectAlerts })
})
await expectLogic(logic, () => {
logic.actions.setCreatedByFilter('019abcde-1234-7000-8000-000000000001')
@@ -112,7 +159,10 @@ describe('logsAlertingLogic', () => {
}).toDispatchActions(['loadAlerts', 'loadAlertsSuccess'])
expect(logic.values.alerts).toEqual(currentProjectAlerts)
- previousProjectResponse.resolve({ results: [{ id: 'previous-project-alert' }] } as any)
+ previousProjectResponse.resolve({
+ count: 1,
+ results: [createMockAlert({ id: 'previous-project-alert' })],
+ })
await Promise.resolve()
await Promise.resolve()
@@ -124,7 +174,7 @@ describe('logsAlertingLogic', () => {
describe('resetAlert', () => {
it('calls the reset endpoint, reloads the list, and surfaces a success toast', async () => {
- mockReset.mockResolvedValue(undefined as any)
+ mockReset.mockResolvedValue(MOCK_ALERT)
const logic = logsAlertingLogic()
logic.mount()
@@ -137,7 +187,6 @@ describe('logsAlertingLogic', () => {
expect(mockReset).toHaveBeenCalledWith(expect.any(String), 'alert-1')
expect(lemonToast.success).toHaveBeenCalledWith(expect.stringContaining('Alert reset'))
- // loadAlerts runs on mount + after the successful reset.
expect(mockList).toHaveBeenCalledTimes(1)
logic.unmount()
@@ -177,4 +226,118 @@ describe('logsAlertingLogic', () => {
logic.unmount()
})
})
+
+ describe('edit alert modal', () => {
+ it('opens for the selected alert and clears it on close', async () => {
+ const logic = logsAlertingLogic()
+ const alert = createMockAlert()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.openEditAlertModal(alert)
+ }).toMatchValues({ editingAlert: alert })
+
+ await expectLogic(logic, () => {
+ logic.actions.closeEditAlertModal()
+ }).toMatchValues({ editingAlert: null })
+
+ logic.unmount()
+ })
+
+ it('updates the open editor after disabling an alert', async () => {
+ const logic = logsAlertingLogic()
+ const alert = createMockAlert()
+ const updatedAlert = { ...alert, enabled: false }
+ mockPartialUpdate.mockResolvedValue(updatedAlert)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openEditAlertModal(alert)
+ await expectLogic(logic, () => {
+ logic.actions.toggleAlertEnabled(alert)
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ editingAlert: updatedAlert })
+
+ expect(mockPartialUpdate).toHaveBeenCalledWith(expect.any(String), alert.id, {
+ enabled: false,
+ snooze_until: null,
+ })
+
+ logic.unmount()
+ })
+
+ it('updates the open editor after snoozing an alert', async () => {
+ const logic = logsAlertingLogic()
+ const alert = createMockAlert()
+ const updatedAlert = { ...alert, snooze_until: '2026-08-13T12:00:00.000Z' }
+ mockPartialUpdate.mockResolvedValue(updatedAlert)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openEditAlertModal(alert)
+ await expectLogic(logic, () => {
+ logic.actions.snoozeAlertUntil(alert.id, '+1d')
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ editingAlert: updatedAlert })
+
+ logic.unmount()
+ })
+
+ it('does not open the editor after snoozing from the alert list', async () => {
+ const logic = logsAlertingLogic()
+ const alert = createMockAlert()
+ mockPartialUpdate.mockResolvedValue({ ...alert, snooze_until: '2026-08-13T12:00:00.000Z' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.snoozeAlertUntil(alert.id, '+1d')
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ editingAlert: null })
+
+ logic.unmount()
+ })
+
+ it('updates the open editor after unsnoozing an alert', async () => {
+ const logic = logsAlertingLogic()
+ const alert = createMockAlert({ snooze_until: '2026-08-13T12:00:00.000Z' })
+ const updatedAlert = { ...alert, snooze_until: null }
+ mockPartialUpdate.mockResolvedValue(updatedAlert)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openEditAlertModal(alert)
+ await expectLogic(logic, () => {
+ logic.actions.unsnoozeAlert(alert.id)
+ })
+ .toFinishAllListeners()
+ .toMatchValues({ editingAlert: updatedAlert })
+
+ logic.unmount()
+ })
+ })
+
+ describe('resolveSnoozeUntil', () => {
+ it.each([
+ ['+30m', '2026-08-12T12:30:00.000Z'],
+ ['+1d', '2026-08-13T12:00:00.000Z'],
+ ['+1w', '2026-08-19T12:00:00.000Z'],
+ ['+1M', '2026-09-12T12:00:00.000Z'],
+ ['+1y', '2027-08-12T12:00:00.000Z'],
+ ])('converts %s into an ISO datetime', (value: string, expected: string) => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-08-12T12:00:00.000Z'))
+
+ expect(resolveSnoozeUntil(value)).toBe(expected)
+
+ jest.useRealTimers()
+ })
+
+ it('preserves a custom datetime', () => {
+ expect(resolveSnoozeUntil('2026-08-13T14:30:00.000Z')).toBe('2026-08-13T14:30:00.000Z')
+ })
+ })
})
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
index 8006bccc5d2d..ad34126f7a9d 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
@@ -56,6 +56,7 @@ export interface LogsAlertFormType {
export interface LogsAlertFormLogicProps {
alert: LogsAlertConfigurationApi | null
onCreateSuccess?: () => void
+ onSubmitSuccess?: () => void
}
function extractFilterGroup(alert: LogsAlertConfigurationApi | null): UniversalFiltersGroup {
@@ -386,6 +387,7 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
}
actions.loadAlerts()
+ props.onSubmitSuccess?.()
if (!props.alert) {
props.onCreateSuccess?.()
if (!notificationsConfigured) {
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts
index 5de26a3b272c..ea9feaba4c02 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts
@@ -1,4 +1,4 @@
-import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
+import { lemonToast } from '@posthog/lemon-ui'
import {
LOGS_ALERT_AUTO_DISABLED_EVENT_ID,
@@ -63,31 +63,12 @@ export type PreEnableFilters = {
filterGroup: UniversalFiltersGroup
}
-export type PreEnableCheckResult =
- | { ok: true }
- | { blocked: true; reason: string }
- | {
- warning: {
- title: string
- description: string
- confirmLabel: string
- }
- }
+export type PreEnableCheckResult = { ok: true } | { blocked: true; reason: string }
-export function runPreEnableChecks(alert: LogsAlertConfigurationApi, filters: PreEnableFilters): PreEnableCheckResult {
+export function runPreEnableChecks(filters: PreEnableFilters): PreEnableCheckResult {
if (!hasAnyFilter(filters.severityLevels, filters.serviceNames, filters.filterGroup)) {
return { blocked: true, reason: 'Add at least one filter to enable' }
}
- if ((alert.destination_types ?? []).length === 0) {
- return {
- warning: {
- title: 'No notifications configured',
- description:
- "This alert has no notification destinations. It will fire silently — you won't receive any alerts when conditions are met.",
- confirmLabel: 'Enable anyway',
- },
- }
- }
return { ok: true }
}
@@ -101,32 +82,12 @@ export function alertFiltersForPreEnableCheck(alert: LogsAlertConfigurationApi):
}
}
-export function dispatchPreEnableCheck(
- result: PreEnableCheckResult,
- callbacks: { onConfirm: () => void; onConfigureNotifications: () => void }
-): void {
+export function dispatchPreEnableCheck(result: PreEnableCheckResult, onConfirm: () => void): void {
if ('blocked' in result) {
lemonToast.error(result.reason)
return
}
- if ('warning' in result) {
- LemonDialog.open({
- title: result.warning.title,
- description: result.warning.description,
- primaryButton: {
- children: 'Configure notifications',
- onClick: callbacks.onConfigureNotifications,
- 'data-attr': 'logs-alert-warning-configure-notifications',
- },
- secondaryButton: {
- children: result.warning.confirmLabel,
- onClick: callbacks.onConfirm,
- 'data-attr': 'logs-alert-warning-enable-anyway',
- },
- })
- return
- }
- callbacks.onConfirm()
+ onConfirm()
}
export const SNOOZE_DURATIONS = [
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts
index 3e38032eafab..9bf5ba6314b4 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts
@@ -1,21 +1,23 @@
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
-import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
+import { resolveSnoozeUntil } from 'products/alerts/frontend/utils'
import {
logsAlertsDestroy,
logsAlertsList,
logsAlertsPartialUpdate,
logsAlertsResetCreate,
} from 'products/logs/frontend/generated/api'
-import { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'
+import {
+ LogsAlertConfigurationApi,
+ PatchedLogsAlertConfigurationApi,
+} from 'products/logs/frontend/generated/api.schemas'
import { alertFiltersForPreEnableCheck, dispatchPreEnableCheck, runPreEnableChecks } from './logsAlertUtils'
@@ -27,8 +29,10 @@ export interface logsAlertingLogicValues {
alerts: LogsAlertConfigurationApi[]
alertsLoading: boolean
createdByFilter: string | null
+ editingAlert: LogsAlertConfigurationApi | null
isCreateAlertModalOpen: boolean
resettingAlertIds: Set<string>
+ snoozingAlertIds: Set<string>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -36,8 +40,15 @@ export interface logsAlertingLogicActions {
closeCreateAlertModal: () => {
value: true
}
- deleteAlert: (id: string) => {
+ closeEditAlertModal: () => {
+ value: true
+ }
+ deleteAlert: (
+ id: string,
+ onSuccess?: () => void
+ ) => {
id: string
+ onSuccess: (() => void) | undefined
}
loadAlerts: (_?: any) => any
loadAlertsFailure: (
@@ -57,6 +68,9 @@ export interface logsAlertingLogicActions {
openCreateAlertModal: () => {
value: true
}
+ openEditAlertModal: (alert: LogsAlertConfigurationApi) => {
+ alert: LogsAlertConfigurationApi
+ }
resetAlert: (id: string) => {
id: string
}
@@ -70,6 +84,13 @@ export interface logsAlertingLogicActions {
id: string
resetting: boolean
}
+ setSnoozingAlertId: (
+ id: string,
+ snoozing: boolean
+ ) => {
+ id: string
+ snoozing: boolean
+ }
snoozeAlert: (
alertId: string,
durationMinutes: number
@@ -77,12 +98,22 @@ export interface logsAlertingLogicActions {
alertId: string
durationMinutes: number
}
+ snoozeAlertUntil: (
+ alertId: string,
+ snoozeUntil: string
+ ) => {
+ alertId: string
+ snoozeUntil: string
+ }
toggleAlertEnabled: (alert: LogsAlertConfigurationApi) => {
alert: LogsAlertConfigurationApi
}
unsnoozeAlert: (alertId: string) => {
alertId: string
}
+ updateEditingAlert: (alert: LogsAlertConfigurationApi) => {
+ alert: LogsAlertConfigurationApi
+ }
}
export type logsAlertingLogicType = MakeLogicType<logsAlertingLogicValues, logsAlertingLogicActions>
@@ -96,14 +127,19 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
actions({
setCreatedByFilter: (createdByFilter: string | null) => ({ createdByFilter }),
- deleteAlert: (id: string) => ({ id }),
+ deleteAlert: (id: string, onSuccess?: () => void) => ({ id, onSuccess }),
toggleAlertEnabled: (alert: LogsAlertConfigurationApi) => ({ alert }),
resetAlert: (id: string) => ({ id }),
setResettingAlertId: (id: string, resetting: boolean) => ({ id, resetting }),
+ setSnoozingAlertId: (id: string, snoozing: boolean) => ({ id, snoozing }),
snoozeAlert: (alertId: string, durationMinutes: number) => ({ alertId, durationMinutes }),
+ snoozeAlertUntil: (alertId: string, snoozeUntil: string) => ({ alertId, snoozeUntil }),
unsnoozeAlert: (alertId: string) => ({ alertId }),
openCreateAlertModal: true,
closeCreateAlertModal: true,
+ openEditAlertModal: (alert: LogsAlertConfigurationApi) => ({ alert }),
+ closeEditAlertModal: true,
+ updateEditingAlert: (alert: LogsAlertConfigurationApi) => ({ alert }),
}),
reducers({
@@ -120,6 +156,13 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
resetting ? new Set([...state, id]) : new Set([...state].filter((x) => x !== id)),
},
],
+ snoozingAlertIds: [
+ new Set<string>(),
+ {
+ setSnoozingAlertId: (state, { id, snoozing }) =>
+ snoozing ? new Set([...state, id]) : new Set([...state].filter((x) => x !== id)),
+ },
+ ],
isCreateAlertModalOpen: [
false,
{
@@ -127,6 +170,14 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
closeCreateAlertModal: () => false,
},
],
+ editingAlert: [
+ null as LogsAlertConfigurationApi | null,
+ {
+ openEditAlertModal: (_, { alert }) => alert,
+ closeEditAlertModal: () => null,
+ updateEditingAlert: (editingAlert, { alert }) => (editingAlert?.id === alert.id ? alert : editingAlert),
+ },
+ ],
}),
loaders(({ values }) => ({
@@ -148,12 +199,13 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
listeners(({ actions, values }) => ({
setCreatedByFilter: () => actions.loadAlerts(),
- deleteAlert: async ({ id }) => {
+ deleteAlert: async ({ id, onSuccess }) => {
const projectId = String(values.currentTeamId)
try {
await logsAlertsDestroy(projectId, id)
lemonToast.success('Alert deleted')
actions.loadAlerts()
+ onSuccess?.()
} catch {
lemonToast.error('Failed to delete alert')
}
@@ -163,10 +215,13 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
const projectId = String(values.currentTeamId)
const performToggle = async (): Promise<void> => {
+ const update: PatchedLogsAlertConfigurationApi = { enabled: !(alert.enabled ?? true) }
+ if (!update.enabled) {
+ update.snooze_until = null
+ }
try {
- await logsAlertsPartialUpdate(projectId, alert.id, {
- enabled: !(alert.enabled ?? true),
- })
+ const updatedAlert = await logsAlertsPartialUpdate(projectId, alert.id, update)
+ actions.updateEditingAlert(updatedAlert)
actions.loadAlerts()
} catch {
lemonToast.error('Failed to update alert')
@@ -178,10 +233,7 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
return
}
- dispatchPreEnableCheck(runPreEnableChecks(alert, alertFiltersForPreEnableCheck(alert)), {
- onConfirm: () => void performToggle(),
- onConfigureNotifications: () => router.actions.push(urls.logsAlertDetail(alert.id, 'notifications')),
- })
+ dispatchPreEnableCheck(runPreEnableChecks(alertFiltersForPreEnableCheck(alert)), () => void performToggle())
},
resetAlert: async ({ id }) => {
const projectId = String(values.currentTeamId)
@@ -199,22 +251,45 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([
snoozeAlert: async ({ alertId, durationMinutes }) => {
const projectId = String(values.currentTeamId)
const snoozeUntil = dayjs().add(durationMinutes, 'minute').toISOString()
+ actions.setSnoozingAlertId(alertId, true)
try {
- await logsAlertsPartialUpdate(projectId, alertId, { snooze_until: snoozeUntil })
+ const updatedAlert = await logsAlertsPartialUpdate(projectId, alertId, { snooze_until: snoozeUntil })
+ actions.updateEditingAlert(updatedAlert)
lemonToast.success('Alert snoozed')
actions.loadAlerts()
} catch {
lemonToast.error('Failed to snooze alert')
+ } finally {
+ actions.setSnoozingAlertId(alertId, false)
+ }
+ },
+ snoozeAlertUntil: async ({ alertId, snoozeUntil }) => {
+ const projectId = String(values.currentTeamId)
+ actions.setSnoozingAlertId(alertId, true)
+ try {
+ const updatedAlert = await logsAlertsPartialUpdate(projectId, alertId, {
+ snooze_until: resolveSnoozeUntil(snoozeUntil),
+ })
+ actions.updateEditingAlert(updatedAlert)
+ actions.loadAlerts()
+ } catch {
+ lemonToast.error('Failed to snooze alert')
+ } finally {
+ actions.setSnoozingAlertId(alertId, false)
}
},
unsnoozeAlert: async ({ alertId }) => {
const projectId = String(values.currentTeamId)
+ actions.setSnoozingAlertId(alertId, true)
try {
- await logsAlertsPartialUpdate(projectId, alertId, { snooze_until: null })
+ const updatedAlert = await logsAlertsPartialUpdate(projectId, alertId, { snooze_until: null })
+ actions.updateEditingAlert(updatedAlert)
lemonToast.success('Alert unsnoozed')
actions.loadAlerts()
} catch {
lemonToast.error('Failed to unsnooze alert')
+ } finally {
+ actions.setSnoozingAlertId(alertId, false)
}
},
})),
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx b/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
index e35f86d3a226..0cb46c3cd951 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
@@ -181,23 +181,24 @@ function AlertHeader(): JSX.Element {
{isEnabled ? 'Disable' : 'Enable'}
</LemonButton>
)}
- {isSnoozed ? (
- <LemonButton size="small" type="secondary" onClick={unsnoozeAlert}>
- Unsnooze
- </LemonButton>
- ) : (
- <LemonMenu
- placement="bottom-end"
- items={SNOOZE_DURATIONS.map((d) => ({
- label: d.label,
- onClick: () => snoozeAlert(d.minutes),
- }))}
- >
- <LemonButton size="small" type="secondary" sideIcon={<IconChevronDown />}>
- Snooze
+ {isEnabled &&
+ (isSnoozed ? (
+ <LemonButton size="small" type="secondary" onClick={unsnoozeAlert}>
+ Unsnooze
</LemonButton>
- </LemonMenu>
- )}
+ ) : (
+ <LemonMenu
+ placement="bottom-end"
+ items={SNOOZE_DURATIONS.map((d) => ({
+ label: d.label,
+ onClick: () => snoozeAlert(d.minutes),
+ }))}
+ >
+ <LemonButton size="small" type="secondary" sideIcon={<IconChevronDown />}>
+ Snooze
+ </LemonButton>
+ </LemonMenu>
+ ))}
<LemonButton
size="small"
type="primary"
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
index 011de569b52a..811429341cac 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
@@ -48,7 +48,6 @@ const MOCK_ALERT: LogsAlertConfigurationApi = {
last_checked_at: null,
consecutive_failures: 0,
last_error_message: null,
- // Non-empty so runPreEnableChecks short-circuits past the "no destinations" warning.
destination_types: ['slack'],
state_timeline: [],
first_enabled_at: null,
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
index bead6b2bfa67..7d6683e90493 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
@@ -33,7 +33,10 @@ import {
logsAlertsResetCreate,
logsAlertsRetrieve,
} from 'products/logs/frontend/generated/api'
-import { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'
+import {
+ LogsAlertConfigurationApi,
+ PatchedLogsAlertConfigurationApi,
+} from 'products/logs/frontend/generated/api.schemas'
import type { LogsAlertFormType } from '../../components/LogsAlerting/logsAlertFormLogic'
@@ -414,10 +417,7 @@ export const logsAlertDetailSceneLogic = kea<logsAlertDetailSceneLogicType>([
actions.applyEnabledChange(false)
return
}
- dispatchPreEnableCheck(runPreEnableChecks(values.alert, values.alertForm), {
- onConfirm: () => actions.applyEnabledChange(true),
- onConfigureNotifications: () => actions.setActiveTab('notifications'),
- })
+ dispatchPreEnableCheck(runPreEnableChecks(values.alertForm), () => actions.applyEnabledChange(true))
},
enableAlert: () => {
if (!values.alert) {
@@ -431,14 +431,15 @@ export const logsAlertDetailSceneLogic = kea<logsAlertDetailSceneLogicType>([
actions.applyEnabledChange(true)
}
}
- dispatchPreEnableCheck(runPreEnableChecks(values.alert, values.alertForm), {
- onConfirm: proceed,
- onConfigureNotifications: () => actions.setActiveTab('notifications'),
- })
+ dispatchPreEnableCheck(runPreEnableChecks(values.alertForm), proceed)
},
applyEnabledChange: async ({ enabled }) => {
+ const update: PatchedLogsAlertConfigurationApi = { enabled }
+ if (!enabled) {
+ update.snooze_until = null
+ }
try {
- const updated = await logsAlertsPartialUpdate(String(values.currentTeamId), props.id, { enabled })
+ const updated = await logsAlertsPartialUpdate(String(values.currentTeamId), props.id, update)
actions.patchAlertLocally(updated)
actions.resetAlertForm(buildFormDefaults(updated))
} catch (e: any) {