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(replay-vision): add the alerts tab behind a feature flag (#88407)

Tue Haulundb17670bf89fa
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index fb44b5e13c11..2f24e7984f10 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -471,6 +471,7 @@ export const FEATURE_FLAGS = {
REPLAY_PLAYLIST_SURFACING_SCORE: 'replay-playlist-surfacing-score', // owner: #team-replay
REPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replay
REPLAY_UI_REDESIGN_2026: 'replay-ui-redesign-2026', // owner: #team-replay, New UI layout for replay
+ REPLAY_VISION_ALERTS: 'replay-vision-alerts', // owner: #team-replay, scanner alerts on the shared alerts platform replacing legacy vision-action alerts
REPLAY_VISION_ANALYSIS_NUDGE: 'replay-vision-analysis-nudge', // owner: #team-replay, in-player nudge offering an AI-drafted scanner after analyzing several recordings
REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT: 'replay-vision-model-tier-naming-experiment', // owner: #team-replay multivariate=control,test,lite-standard-pro
REPLAY_VISION_SCOUT_DIGESTS: 'replay-vision-scout-digests', // owner: #team-replay, scanner digests backed by Signals scouts instead of vision actions
diff --git a/products/alerts/frontend/components/AlertEditor.tsx b/products/alerts/frontend/components/AlertEditor.tsx
index c8f9c806e238..aef62d5a5e60 100644
--- a/products/alerts/frontend/components/AlertEditor.tsx
+++ b/products/alerts/frontend/components/AlertEditor.tsx
@@ -160,7 +160,11 @@ export function AlertEditorFormDetails({
<div className="space-y-2">
<div className="flex gap-4 items-center">
<LemonField className="flex-auto" name="name">
- <LemonInput placeholder="Alert name" data-attr={nameDataAttr} />
+ <LemonInput
+ placeholder="Alert name"
+ data-attr={nameDataAttr}
+ status={nameError ? 'danger' : undefined}
+ />
</LemonField>
{enabled ? (
<LemonField name="enabled">
diff --git a/products/replay_vision/backend/api/vision_alerts.py b/products/replay_vision/backend/api/vision_alerts.py
index 15195b16a466..850b28205d9b 100644
--- a/products/replay_vision/backend/api/vision_alerts.py
+++ b/products/replay_vision/backend/api/vision_alerts.py
@@ -7,7 +7,7 @@ from django.db.models import F, Q, QuerySet
from django.shortcuts import get_object_or_404
from django.utils import timezone
-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied, ValidationError
@@ -483,6 +483,7 @@ class VisionAlertDestinationResponseSerializer(serializers.Serializer):
)
+@extend_schema_view(list=extend_schema(parameters=[VisionAlertListQuerySerializer]))
class VisionAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "vision_alert"
scope_object_read_actions = ["list", "retrieve", "events"]
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index fd60a4d91970..a3363cc30888 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -2627,6 +2627,10 @@ export type VisionAlertsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Only return alerts on this scanner.
+ */
+ scanner_id?: string
}
export type VisionAlertsEventsListParams = {
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
index 1522a6e8d5be..c65d613d015e 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
@@ -22,6 +22,7 @@ import { ObservationSearchTab } from '../search/ObservationSearchTab'
import { getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { formatCreditsRange } from '../utils/credits'
import { quotaBannerState } from '../utils/quotaProjection'
+import { ScannerAlertsTab } from './components/ScannerAlertsTab'
import { ScannerBackfillsTab } from './components/ScannerBackfillsTab'
import { ScannerCalibrationTab } from './components/ScannerCalibrationTab'
import { ScannerConfigReadonly } from './components/ScannerConfigReadonly'
@@ -48,7 +49,16 @@ export function ReplayScannerSceneComponent(): JSX.Element {
const { setActiveTab } = useActions(replayScannerSceneLogic)
const { featureFlags } = useValues(featureFlagLogic)
const scoutDigests = !!featureFlags[FEATURE_FLAGS.REPLAY_VISION_SCOUT_DIGESTS]
- const visibleTabs = Object.values(ReplayScannerTab).filter((tab) => scoutDigests || tab !== ReplayScannerTab.Scouts)
+ const newAlerts = !!featureFlags[FEATURE_FLAGS.REPLAY_VISION_ALERTS]
+ // With both flags on the Actions tab has nothing left to show: digests live on Scouts and
+ // alerts live on the new Alerts tab.
+ const hideActionsTab = newAlerts && scoutDigests
+ const visibleTabs = Object.values(ReplayScannerTab).filter(
+ (tab) =>
+ (scoutDigests || tab !== ReplayScannerTab.Scouts) &&
+ (newAlerts || tab !== ReplayScannerTab.Alerts) &&
+ (!hideActionsTab || tab !== ReplayScannerTab.Actions)
+ )
const scannerLogic = replayScannerLogic({ id: scannerId })
useAttachedLogic(scannerLogic, replayScannerSceneLogic)
@@ -176,17 +186,31 @@ export function ReplayScannerSceneComponent(): JSX.Element {
},
]
: []),
- {
- key: ReplayScannerTab.Actions,
- // Digests moved to their own Scouts tab, leaving this one to alerts alone.
- label: scoutDigests ? 'Alerts' : 'Digests and alerts',
- content: (
- <VisionActionsTab
- scannerId={scannerId}
- scannerUserAccessLevel={scanner.user_access_level}
- />
- ),
- },
+ ...(newAlerts
+ ? [
+ {
+ key: ReplayScannerTab.Alerts,
+ label: 'Alerts',
+ content: <ScannerAlertsTab scannerId={scannerId} />,
+ },
+ ]
+ : []),
+ ...(hideActionsTab
+ ? []
+ : [
+ {
+ key: ReplayScannerTab.Actions,
+ // Digests moved to the Scouts tab and new alerts to the Alerts tab;
+ // the label names whatever this tab still carries.
+ label: newAlerts ? 'Digests' : scoutDigests ? 'Alerts' : 'Digests and alerts',
+ content: (
+ <VisionActionsTab
+ scannerId={scannerId}
+ scannerUserAccessLevel={scanner.user_access_level}
+ />
+ ),
+ },
+ ]),
]}
/>
</SceneContent>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerAlertCreateModal.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertCreateModal.tsx
new file mode 100644
index 000000000000..ed2437a242b0
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertCreateModal.tsx
@@ -0,0 +1,173 @@
+import { BindLogic, useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonBanner, LemonModal } from '@posthog/lemon-ui'
+
+import { WizardReview } from 'lib/components/WizardReview'
+
+import { AlertEditorFormDetails } from 'products/alerts/frontend/components/AlertEditor'
+import { AlertWizard, AlertWizardStep } from 'products/alerts/frontend/components/AlertWizard'
+
+import { ScannerAlertFormType, scannerAlertFormLogic } from '../scannerAlertFormLogic'
+import { scannerAlertNotificationLogic } from '../scannerAlertNotificationLogic'
+import { PendingVisionAlertNotification } from '../scannerAlertUtils'
+import { ScannerAlertKindPicker, ScannerAlertSelectionFields, ScannerAlertTrigger } from './ScannerAlertForm'
+import { ScannerAlertNotifications } from './ScannerAlertNotifications'
+
+interface ScannerAlertCreateModalProps {
+ scannerId: string
+ scannerType?: string
+ isOpen: boolean
+ onClose: () => void
+}
+
+export function ScannerAlertCreateModal({
+ scannerId,
+ scannerType,
+ isOpen,
+ onClose,
+}: ScannerAlertCreateModalProps): JSX.Element {
+ return (
+ <LemonModal isOpen={isOpen} onClose={onClose} title="" simple width={900}>
+ {isOpen ? (
+ <ScannerAlertCreateModalContent scannerId={scannerId} scannerType={scannerType} onClose={onClose} />
+ ) : null}
+ </LemonModal>
+ )
+}
+
+function ScannerAlertCreateModalContent({
+ scannerId,
+ scannerType,
+ onClose,
+}: {
+ scannerId: string
+ scannerType?: string
+ onClose: () => void
+}): JSX.Element {
+ const formLogicProps = { scannerId, alert: null, onSubmitSuccess: onClose }
+ const { isAlertFormSubmitting, alertFormChanged, alertForm } = useValues(scannerAlertFormLogic(formLogicProps))
+ const { touchAlertFormField } = useActions(scannerAlertFormLogic(formLogicProps))
+ const { pendingNotifications } = useValues(scannerAlertNotificationLogic({}))
+
+ const nameError = alertForm.name.trim() ? undefined : 'Enter an alert name.'
+ const thresholdError =
+ alertForm.kind === 'metric' && alertForm.threshold === null ? 'Enter a threshold.' : undefined
+
+ const steps: AlertWizardStep[] = [
+ {
+ key: 'configure',
+ title: 'Configure',
+ description: 'Name the alert and pick its type.',
+ canAdvance: !nameError,
+ cannotAdvanceReason: nameError,
+ renderContent: (showValidationErrors) => (
+ <div className="max-w-2xl space-y-5">
+ <AlertEditorFormDetails nameError={showValidationErrors ? nameError : undefined} />
+ <ScannerAlertKindPicker />
+ </div>
+ ),
+ },
+ {
+ key: 'trigger',
+ title: 'Set trigger',
+ description: 'Choose which observations count and when the alert fires.',
+ canAdvance: !thresholdError,
+ cannotAdvanceReason: thresholdError,
+ renderContent: (showValidationErrors) => (
+ <div className="max-w-2xl space-y-6">
+ <ScannerAlertSelectionFields scannerType={scannerType} />
+ <ScannerAlertTrigger thresholdError={showValidationErrors ? thresholdError : undefined} />
+ </div>
+ ),
+ },
+ {
+ key: 'notify',
+ title: 'Notify',
+ description: 'Choose where to send alert notifications.',
+ content: (
+ <div className="max-w-2xl">
+ <ScannerAlertNotifications />
+ </div>
+ ),
+ },
+ {
+ key: 'review',
+ title: 'Review',
+ description: 'Confirm the alert before you create it.',
+ content: <ScannerAlertReview alertForm={alertForm} pendingNotifications={pendingNotifications} />,
+ },
+ ]
+
+ return (
+ <BindLogic logic={scannerAlertFormLogic} props={formLogicProps}>
+ <BindLogic logic={scannerAlertNotificationLogic} props={{}}>
+ <Form
+ logic={scannerAlertFormLogic}
+ 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 ScannerAlertReview({
+ alertForm,
+ pendingNotifications,
+}: {
+ alertForm: ScannerAlertFormType
+ pendingNotifications: PendingVisionAlertNotification[]
+}): JSX.Element {
+ const firesWhen =
+ alertForm.kind === 'match'
+ ? 'every matching observation, bundled into one notification per minute'
+ : `${alertForm.metric === 'avg_score' ? 'average score' : 'matching observation count'} is ${
+ alertForm.direction === 'below' ? 'at or below' : 'at or above'
+ } ${alertForm.threshold} in the last ${alertForm.windowDays === 1 ? '24 hours' : `${alertForm.windowDays} days`}`
+ const watches =
+ [
+ alertForm.verdict.length ? `verdict ${alertForm.verdict.join(', ')}` : null,
+ alertForm.tags.length ? `tags ${alertForm.tags.join(', ')}` : null,
+ alertForm.minScore !== null ? `score ≥ ${alertForm.minScore}` : null,
+ alertForm.maxScore !== null ? `score ≤ ${alertForm.maxScore}` : null,
+ ]
+ .filter(Boolean)
+ .join(', ') || 'all observations'
+ const notificationSummary = pendingNotifications.length
+ ? `${pendingNotifications.length} notification destination${pendingNotifications.length === 1 ? '' : 's'}`
+ : 'No notification destinations'
+
+ return (
+ <WizardReview
+ 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: 'Type',
+ value: alertForm.kind === 'match' ? 'Every matching observation' : 'Metric threshold',
+ },
+ { label: 'Watches', value: watches },
+ { label: 'Fires when', value: firesWhen },
+ { label: 'Notifies', value: notificationSummary },
+ ]}
+ />
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerAlertEditModal.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertEditModal.tsx
new file mode 100644
index 000000000000..a8dbff8f70b9
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertEditModal.tsx
@@ -0,0 +1,227 @@
+import { BindLogic, useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { IconBell, IconGraph, IconPulse, IconTarget } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonModal, LemonSwitch } from '@posthog/lemon-ui'
+
+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 type { VisionAlertConfigurationApi } from '../../generated/api.schemas'
+import { scannerAlertFormLogic } from '../scannerAlertFormLogic'
+import { scannerAlertNotificationLogic } from '../scannerAlertNotificationLogic'
+import { scannerAlertsLogic } from '../scannerAlertsLogic'
+import { conditionSummary, selectionSummary } from '../scannerAlertUtils'
+import { ScannerAlertEventHistory } from './ScannerAlertEventHistory'
+import { ScannerAlertSelectionFields, ScannerAlertTrigger } from './ScannerAlertForm'
+import { ScannerAlertNotifications } from './ScannerAlertNotifications'
+import { ScannerAlertStateTag } from './ScannerAlertStateTag'
+
+interface ScannerAlertEditModalProps {
+ scannerId: string
+ scannerType?: string
+ alert: VisionAlertConfigurationApi | null
+ onClose: () => void
+}
+
+export function ScannerAlertEditModal({
+ scannerId,
+ scannerType,
+ alert,
+ onClose,
+}: ScannerAlertEditModalProps): JSX.Element {
+ return (
+ <LemonModal isOpen={alert !== null} onClose={onClose} title="" simple width={900}>
+ {alert ? (
+ <ScannerAlertEditModalContent
+ scannerId={scannerId}
+ scannerType={scannerType}
+ alert={alert}
+ onClose={onClose}
+ />
+ ) : null}
+ </LemonModal>
+ )
+}
+
+function ScannerAlertEditModalContent({
+ scannerId,
+ scannerType,
+ alert,
+ onClose,
+}: {
+ scannerId: string
+ scannerType?: string
+ alert: VisionAlertConfigurationApi
+ onClose: () => void
+}): JSX.Element {
+ const formLogicProps = { scannerId, alert, onSubmitSuccess: onClose }
+ const notificationLogicProps = { alertId: alert.id }
+ const { isAlertFormSubmitting, alertFormChanged, alertFormErrors } = useValues(
+ scannerAlertFormLogic(formLogicProps)
+ )
+ const { touchAlertFormField } = useActions(scannerAlertFormLogic(formLogicProps))
+ const { destinationGroups } = useValues(scannerAlertNotificationLogic(notificationLogicProps))
+ const { busyAlertIds } = useValues(scannerAlertsLogic({ scannerId }))
+ const { deleteAlert, snoozeAlertUntil, toggleAlertEnabled, unsnoozeAlert } = useActions(
+ scannerAlertsLogic({ scannerId })
+ )
+ const nameError = alertFormErrors.name as string | undefined
+
+ const summary: AlertSummaryParts = {
+ fires: conditionSummary(alert),
+ cadence: '',
+ notifies: destinationGroups.length
+ ? `${destinationGroups.length} ${destinationGroups.length === 1 ? 'destination' : 'destinations'}`
+ : '',
+ filters: selectionSummary(alert),
+ }
+
+ 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">
+ <ScannerAlertSelectionFields scannerType={scannerType} />
+ </div>
+ </div>
+ ),
+ },
+ {
+ key: 'trigger',
+ summarySection: 'monitor',
+ label: (
+ <>
+ <IconTarget className="size-4" />
+ Trigger
+ </>
+ ),
+ content: (
+ <div className="max-w-2xl space-y-6 pt-3">
+ <ScannerAlertTrigger />
+ </div>
+ ),
+ },
+ {
+ key: 'notify',
+ summarySection: 'notify',
+ label: (
+ <>
+ <IconBell className="size-4" />
+ Notify
+ </>
+ ),
+ content: (
+ <div className="pt-3">
+ <ScannerAlertNotifications />
+ </div>
+ ),
+ },
+ {
+ key: 'history',
+ label: (
+ <>
+ <IconGraph className="size-4" />
+ History
+ </>
+ ),
+ content: (
+ <div className="pt-3">
+ <ScannerAlertEventHistory alert={alert} />
+ </div>
+ ),
+ },
+ ]
+
+ const leadingActions = (
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ data-attr="vision-alert-delete"
+ onClick={() => {
+ LemonDialog.open({
+ title: `Delete "${alert.name}"?`,
+ description:
+ 'This alert and its notification destinations will be permanently deleted. This 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={busyAlertIds.has(alert.id) ? 'Updating snooze' : undefined}
+ />
+ ) : null}
+ </div>
+ )
+
+ return (
+ <BindLogic logic={scannerAlertFormLogic} props={formLogicProps}>
+ <BindLogic logic={scannerAlertNotificationLogic} props={notificationLogicProps}>
+ <Form
+ logic={scannerAlertFormLogic}
+ 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>
+ <ScannerAlertStateTag alert={alert} />
+ </div>
+ }
+ tabs={tabs}
+ showCadence={false}
+ />
+ </AlertEditor>
+ </Form>
+ </BindLogic>
+ </BindLogic>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerAlertEventHistory.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertEventHistory.tsx
new file mode 100644
index 000000000000..39250bce4ba1
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertEventHistory.tsx
@@ -0,0 +1,121 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { LemonButton, LemonTable, LemonTableColumns, LemonTag, LemonTagType } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+
+import {
+ AlertEvaluationHistoryChart,
+ AlertEvaluationHistoryPoint,
+ AlertEvaluationThreshold,
+} from 'products/alerts/frontend/components/AlertEvaluationHistoryChart'
+
+import type { VisionAlertConfigurationApi, VisionAlertEventApi } from '../../generated/api.schemas'
+import { ScannerAlertEventsLogicProps, scannerAlertEventsLogic } from '../scannerAlertEventsLogic'
+
+export function ScannerAlertEventHistory({ alert }: { alert: VisionAlertConfigurationApi }): JSX.Element {
+ const logicProps: ScannerAlertEventsLogicProps = { alertId: alert.id }
+ return (
+ <BindLogic logic={scannerAlertEventsLogic} props={logicProps}>
+ <ScannerAlertEventTimeline alert={alert} />
+ </BindLogic>
+ )
+}
+
+function describeEvent(event: VisionAlertEventApi): { label: string; type: LemonTagType; detail?: string } {
+ if (event.kind !== 'check') {
+ const labels: Record<string, string> = {
+ reset: 'Reset',
+ enable: 'Enabled',
+ disable: 'Disabled',
+ snooze: 'Snoozed',
+ unsnooze: 'Unsnoozed',
+ threshold_change: 'Condition changed',
+ }
+ return { label: labels[event.kind] ?? event.kind, type: 'default' }
+ }
+ if (event.error_message) {
+ return { label: 'Check failed', type: 'danger', detail: event.error_message }
+ }
+ if (event.state_after === 'firing' && event.state_before !== 'firing') {
+ return { label: 'Fired', type: 'danger' }
+ }
+ if (event.state_before === 'firing' && event.state_after === 'not_firing') {
+ return { label: 'Resolved', type: 'success' }
+ }
+ return { label: 'Checked', type: 'default' }
+}
+
+function getHistoryThresholds(alert: VisionAlertConfigurationApi): AlertEvaluationThreshold[] {
+ const thresholdValue = alert.threshold ?? 0
+ if (alert.direction === 'below') {
+ return [{ direction: 'lower', value: thresholdValue, label: `At or below (${thresholdValue})` }]
+ }
+ return [{ direction: 'upper', value: thresholdValue, label: `At or above (${thresholdValue})` }]
+}
+
+function getHistoryPoints(events: VisionAlertEventApi[]): AlertEvaluationHistoryPoint[] {
+ return events
+ .filter((event) => event.kind === 'check' && event.metric_value !== null && event.metric_value !== undefined)
+ .sort((left, right) => left.created_at.localeCompare(right.created_at))
+ .map((event) => ({
+ label: dayjs(event.created_at).format('MMM D, HH:mm'),
+ value: event.metric_value ?? 0,
+ firedAtTime: event.state_after === 'firing',
+ }))
+}
+
+function ScannerAlertEventTimeline({ alert }: { alert: VisionAlertConfigurationApi }): JSX.Element {
+ const { eventsPage, eventsPageLoading } = useValues(scannerAlertEventsLogic)
+ const { loadMore } = useActions(scannerAlertEventsLogic)
+ const historyPoints = getHistoryPoints(eventsPage.results)
+
+ const columns: LemonTableColumns<VisionAlertEventApi> = [
+ {
+ title: 'Event',
+ render: (_, event) => {
+ const { label, type } = describeEvent(event)
+ return <LemonTag type={type}>{label}</LemonTag>
+ },
+ },
+ {
+ title: 'When',
+ render: (_, event) => <TZLabel time={event.created_at} formatDate="MMM D" formatTime="HH:mm:ss" />,
+ },
+ {
+ title: 'Detail',
+ render: (_, event) => {
+ const { detail } = describeEvent(event)
+ return detail ? <span className="text-muted text-xs">{detail}</span> : null
+ },
+ },
+ ]
+
+ return (
+ <div className="space-y-4">
+ {alert.kind === 'metric' ? (
+ <AlertEvaluationHistoryChart
+ points={historyPoints}
+ valueLabel={alert.metric === 'avg_score' ? 'Average score' : 'Matching observations'}
+ thresholds={getHistoryThresholds(alert)}
+ historyLimit={100}
+ evaluationNoun="check"
+ />
+ ) : null}
+ <LemonTable
+ columns={columns}
+ dataSource={eventsPage.results}
+ loading={eventsPageLoading}
+ rowKey="id"
+ emptyState="No history yet. Events appear after the first check runs."
+ data-attr="vision-alert-event-history"
+ />
+ {eventsPage.next ? (
+ <LemonButton type="secondary" size="small" onClick={loadMore} loading={eventsPageLoading}>
+ Load more
+ </LemonButton>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerAlertForm.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertForm.tsx
new file mode 100644
index 000000000000..e2dd1b90c929
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertForm.tsx
@@ -0,0 +1,258 @@
+import { useValues } from 'kea'
+
+import { LemonInput, LemonInputSelect, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { AlertAdvancedOptions } from 'products/alerts/frontend/components/AlertAdvancedOptions'
+import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'
+import { AlertEditorSection } from 'products/alerts/frontend/components/AlertEditor'
+import { QuietHoursFields } from 'products/alerts/frontend/components/QuietHoursFields'
+
+import { scannerAlertFormLogic } from '../scannerAlertFormLogic'
+
+const WINDOW_OPTIONS = [
+ { value: 1, label: '24 hours' },
+ { value: 3, label: '3 days' },
+ { value: 7, label: '7 days' },
+ { value: 14, label: '14 days' },
+ { value: 30, label: '30 days' },
+]
+
+const MONITOR_VERDICT_OPTIONS = [
+ { key: 'yes', label: 'Yes' },
+ { key: 'no', label: 'No' },
+ { key: 'inconclusive', label: 'Inconclusive' },
+]
+
+// Cadence is server-managed (hourly checks); shown to explain when quiet hours apply.
+const CHECK_CADENCE_MINUTES = 60
+
+export function ScannerAlertKindPicker(): JSX.Element {
+ return (
+ <LemonField name="kind" label="Alert type">
+ {({ value, onChange }) => (
+ <LemonSegmentedButton
+ value={value}
+ onChange={onChange}
+ options={[
+ {
+ value: 'match',
+ label: 'Every matching observation',
+ tooltip: 'Notifies within about a minute of each observation that matches.',
+ 'data-attr': 'vision-alert-kind-match',
+ },
+ {
+ value: 'metric',
+ label: 'Metric threshold',
+ tooltip: 'Notifies when a metric over a rolling window crosses a threshold.',
+ 'data-attr': 'vision-alert-kind-metric',
+ },
+ ]}
+ fullWidth
+ />
+ )}
+ </LemonField>
+ )
+}
+
+export function ScannerAlertSelectionFields({ scannerType }: { scannerType?: string }): JSX.Element {
+ return (
+ <AlertEditorSection
+ title="Which observations count"
+ description="Leave everything empty to match every observation of this scanner."
+ >
+ <div className="space-y-3">
+ {scannerType === 'monitor' ? (
+ <LemonField name="verdict" label="Verdict">
+ {({ value, onChange }) => (
+ <LemonInputSelect
+ mode="multiple"
+ value={value}
+ onChange={onChange}
+ options={MONITOR_VERDICT_OPTIONS}
+ placeholder="Any verdict"
+ data-attr="vision-alert-verdict"
+ />
+ )}
+ </LemonField>
+ ) : null}
+ {scannerType === 'classifier' ? (
+ <LemonField name="tags" label="Tags" info="Matches observations carrying any of these tags.">
+ {({ value, onChange }) => (
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
+ value={value}
+ onChange={onChange}
+ options={[]}
+ placeholder="Any tag"
+ data-attr="vision-alert-tags"
+ />
+ )}
+ </LemonField>
+ ) : null}
+ {scannerType === 'scorer' ? (
+ <div className="flex gap-4">
+ <LemonField name="minScore" label="Minimum score">
+ {({ value, onChange }) => (
+ <LemonInput
+ type="number"
+ value={value ?? undefined}
+ onChange={(v) => onChange(v ?? null)}
+ placeholder="No minimum"
+ data-attr="vision-alert-min-score"
+ />
+ )}
+ </LemonField>
+ <LemonField name="maxScore" label="Maximum score">
+ {({ value, onChange }) => (
+ <LemonInput
+ type="number"
+ value={value ?? undefined}
+ onChange={(v) => onChange(v ?? null)}
+ placeholder="No maximum"
+ data-attr="vision-alert-max-score"
+ />
+ )}
+ </LemonField>
+ </div>
+ ) : null}
+ </div>
+ </AlertEditorSection>
+ )
+}
+
+export function ScannerAlertTrigger({ thresholdError }: { thresholdError?: string } = {}): JSX.Element {
+ const { alertForm } = useValues(scannerAlertFormLogic)
+ const { currentTeam } = useValues(teamLogic)
+
+ if (alertForm.kind !== 'metric') {
+ return (
+ <AlertEditorSection title="When it fires">
+ <div className="space-y-4">
+ <p className="text-muted mb-0">
+ You get one bundled notification per minute covering every new matching observation, so a burst
+ of matches sends one message instead of many.
+ </p>
+ <AlertAdvancedOptions>
+ <LemonField name="scheduleRestriction">
+ {({ value, onChange }) => (
+ <QuietHoursFields
+ scheduleRestriction={value}
+ cadenceMinutes={CHECK_CADENCE_MINUTES}
+ teamTimezone={currentTeam?.timezone ?? 'UTC'}
+ onChange={onChange}
+ />
+ )}
+ </LemonField>
+ </AlertAdvancedOptions>
+ </div>
+ </AlertEditorSection>
+ )
+ }
+
+ return (
+ <AlertEditorSection title="When it fires">
+ <div className="space-y-4">
+ <AlertDefinitionRow label="Measure">
+ <LemonField name="metric">
+ {({ value, onChange }) => (
+ <LemonSelect
+ value={value}
+ onChange={onChange}
+ options={[
+ { value: 'count', label: 'number of matching observations' },
+ { value: 'avg_score', label: 'average score' },
+ ]}
+ data-attr="vision-alert-metric"
+ />
+ )}
+ </LemonField>
+ </AlertDefinitionRow>
+ <AlertDefinitionRow label="Alert if it is">
+ <LemonField name="direction">
+ {({ value, onChange }) => (
+ <LemonSelect
+ value={value}
+ onChange={onChange}
+ options={[
+ { value: 'above', label: 'at or above' },
+ { value: 'below', label: 'at or below' },
+ ]}
+ data-attr="vision-alert-direction"
+ />
+ )}
+ </LemonField>
+ <LemonField name="threshold">
+ {({ value, onChange }) => (
+ <LemonInput
+ type="number"
+ value={value ?? undefined}
+ onChange={(v) => onChange(v ?? null)}
+ className="w-24"
+ status={thresholdError ? 'danger' : undefined}
+ data-attr="vision-alert-threshold"
+ />
+ )}
+ </LemonField>
+ <span>in the last</span>
+ <LemonField name="windowDays">
+ {({ value, onChange }) => (
+ <LemonSelect
+ value={value}
+ onChange={onChange}
+ options={WINDOW_OPTIONS}
+ data-attr="vision-alert-window"
+ />
+ )}
+ </LemonField>
+ </AlertDefinitionRow>
+ {thresholdError ? <LemonField.Error error={thresholdError} /> : null}
+
+ <AlertAdvancedOptions>
+ <LemonField.Pure
+ label="Noise reduction"
+ info="How many of the recent checks must breach before the alert fires (N of M)."
+ >
+ <div className="flex items-center gap-2">
+ <LemonField name="datapointsToAlarm">
+ {({ value, onChange }) => (
+ <LemonInput type="number" min={1} max={10} value={value} onChange={onChange} />
+ )}
+ </LemonField>
+ <span>of</span>
+ <LemonField name="evaluationPeriods">
+ {({ value, onChange }) => (
+ <LemonInput type="number" min={1} max={10} value={value} onChange={onChange} />
+ )}
+ </LemonField>
+ <span>checks must breach</span>
+ </div>
+ </LemonField.Pure>
+ <LemonField.Pure
+ label="Notification cooldown"
+ info="Minimum minutes between repeated notifications. 0 means no cooldown."
+ >
+ <LemonField name="cooldownMinutes">
+ {({ value, onChange }) => (
+ <LemonInput type="number" min={0} value={value} onChange={onChange} className="w-24" />
+ )}
+ </LemonField>
+ </LemonField.Pure>
+ <LemonField name="scheduleRestriction">
+ {({ value, onChange }) => (
+ <QuietHoursFields
+ scheduleRestriction={value}
+ cadenceMinutes={CHECK_CADENCE_MINUTES}
+ teamTimezone={currentTeam?.timezone ?? 'UTC'}
+ onChange={onChange}
+ />
+ )}
+ </LemonField>
+ </AlertAdvancedOptions>
+ </div>
+ </AlertEditorSection>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerAlertNotifications.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertNotifications.tsx
new file mode 100644
index 000000000000..ae88b74a15c6
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertNotifications.tsx
@@ -0,0 +1,101 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { slackIntegrationLogic } from 'lib/integrations/slackIntegrationLogic'
+
+import {
+ AlertNotificationDestinationEditor,
+ AlertNotificationDestinationView,
+ PendingAlertNotificationDestinationView,
+} from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'
+
+import { VISION_ALERT_NOTIFICATION_TYPE_OPTIONS, scannerAlertNotificationLogic } from '../scannerAlertNotificationLogic'
+import { PendingVisionAlertNotification, VISION_ALERT_NOTIFICATION_TYPE_SLACK } from '../scannerAlertUtils'
+
+function pendingDestinationView(notification: PendingVisionAlertNotification): {
+ title: string
+ detail?: string
+} {
+ if (notification.type === VISION_ALERT_NOTIFICATION_TYPE_SLACK) {
+ return { title: 'Slack', detail: `#${notification.slackChannelName ?? 'channel'}` }
+ }
+ return { title: 'Webhook', detail: notification.webhookUrl }
+}
+
+export function ScannerAlertNotifications(): JSX.Element {
+ const {
+ existingHogFunctionsLoading,
+ destinationGroups,
+ pendingNotifications,
+ integrationsLoading,
+ integrationsFailed,
+ slackIntegrations,
+ firstSlackIntegration,
+ selectedType,
+ slackChannelValue,
+ webhookUrl,
+ urlInput,
+ addDisabledReason,
+ } = useValues(scannerAlertNotificationLogic)
+ const {
+ addSelectedNotification,
+ removePendingNotification,
+ deleteExistingDestination,
+ setSelectedType,
+ setSlackChannelValue,
+ setWebhookUrl,
+ loadIntegrations,
+ } = useActions(scannerAlertNotificationLogic)
+
+ const slackLogic = slackIntegrationLogic({ id: firstSlackIntegration?.id ?? 0 })
+ const { loadAllSlackChannels } = useActions(slackLogic)
+ useEffect(() => {
+ if (firstSlackIntegration?.id) {
+ loadAllSlackChannels()
+ }
+ }, [firstSlackIntegration?.id, loadAllSlackChannels])
+
+ const existingDestinations: AlertNotificationDestinationView[] = destinationGroups.map((group) => ({
+ key: group.key,
+ title: group.label,
+ tags: group.enabled ? undefined : [{ label: 'Disabled' }],
+ onDelete: () => deleteExistingDestination(group),
+ deleting: false,
+ }))
+ const pendingDestinations: PendingAlertNotificationDestinationView[] = pendingNotifications.map(
+ (notification, index) => ({
+ key: `${notification.type}-${index}`,
+ ...pendingDestinationView(notification),
+ onRemove: () => removePendingNotification(index),
+ })
+ )
+
+ return (
+ <AlertNotificationDestinationEditor
+ description="Each destination receives every notification this alert sends."
+ destinations={{
+ showExisting: true,
+ existingLoading: existingHogFunctionsLoading,
+ existing: existingDestinations,
+ pending: pendingDestinations,
+ }}
+ notificationType={{
+ options: VISION_ALERT_NOTIFICATION_TYPE_OPTIONS,
+ value: selectedType,
+ onChange: setSelectedType,
+ }}
+ slack={{
+ notificationType: VISION_ALERT_NOTIFICATION_TYPE_SLACK,
+ integrationsLoading,
+ integrationsFailed,
+ onRetryIntegrations: loadIntegrations,
+ integrations: slackIntegrations,
+ integration: firstSlackIntegration,
+ channelValue: slackChannelValue,
+ onChannelValueChange: setSlackChannelValue,
+ }}
+ url={urlInput ? { input: urlInput, value: webhookUrl, onChange: setWebhookUrl } : undefined}
+ add={{ onClick: addSelectedNotification, disabledReason: addDisabledReason }}
+ />
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerAlertStateTag.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertStateTag.tsx
new file mode 100644
index 000000000000..f750ae05bb6d
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertStateTag.tsx
@@ -0,0 +1,24 @@
+import { LemonTag } from '@posthog/lemon-ui'
+
+import type { VisionAlertConfigurationApi } from '../../generated/api.schemas'
+
+export function ScannerAlertStateTag({ alert }: { alert: VisionAlertConfigurationApi }): JSX.Element {
+ if (!(alert.enabled ?? true)) {
+ return <LemonTag type="muted">Disabled</LemonTag>
+ }
+ if (alert.kind === 'match') {
+ return <LemonTag type="success">Active</LemonTag>
+ }
+ switch (alert.state) {
+ case 'firing':
+ return <LemonTag type="danger">Firing</LemonTag>
+ case 'snoozed':
+ return <LemonTag type="warning">Snoozed</LemonTag>
+ case 'errored':
+ return <LemonTag type="warning">Errored</LemonTag>
+ case 'broken':
+ return <LemonTag type="danger">Broken</LemonTag>
+ default:
+ return <LemonTag type="success">Not firing</LemonTag>
+ }
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerAlertsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertsTab.tsx
new file mode 100644
index 000000000000..991ee21a3301
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerAlertsTab.tsx
@@ -0,0 +1,173 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { IconPlus, IconRefresh } from '@posthog/icons'
+import { LemonButton, LemonSwitch, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+
+import type { VisionAlertConfigurationApi } from '../../generated/api.schemas'
+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
+import { replayScannerLogic } from '../replayScannerLogic'
+import { scannerAlertsLogic } from '../scannerAlertsLogic'
+import { conditionSummary, selectionSummary } from '../scannerAlertUtils'
+import { ScannerAlertCreateModal } from './ScannerAlertCreateModal'
+import { ScannerAlertEditModal } from './ScannerAlertEditModal'
+import { ScannerAlertStateTag } from './ScannerAlertStateTag'
+
+export function ScannerAlertsTab({ scannerId }: { scannerId: string }): JSX.Element {
+ return (
+ <BindLogic logic={scannerAlertsLogic} props={{ scannerId }}>
+ <ScannerAlertsTabContent scannerId={scannerId} />
+ </BindLogic>
+ )
+}
+
+function ScannerAlertsTabContent({ scannerId }: { scannerId: string }): JSX.Element {
+ const { alerts, alertsLoading, busyAlertIds, isCreateAlertModalOpen, editingAlert } = useValues(scannerAlertsLogic)
+ const {
+ toggleAlertEnabled,
+ resetAlert,
+ openCreateAlertModal,
+ closeCreateAlertModal,
+ openEditAlertModal,
+ closeEditAlertModal,
+ } = useActions(scannerAlertsLogic)
+ const { scanner } = useValues(replayScannerLogic({ id: scannerId }))
+ const scannerType = scanner?.scanner_type
+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)
+
+ const columns: LemonTableColumns<VisionAlertConfigurationApi> = [
+ {
+ title: 'Name',
+ key: 'name',
+ render: (_, alert) => (
+ <span className="flex items-center gap-2">
+ <Link
+ className="font-semibold"
+ onClick={() => openEditAlertModal(alert)}
+ data-attr="vision-alert-open-edit"
+ >
+ {alert.name}
+ </Link>
+ <LemonTag type="default">{alert.kind === 'match' ? 'Every match' : 'Metric threshold'}</LemonTag>
+ </span>
+ ),
+ },
+ {
+ title: 'Condition',
+ key: 'condition',
+ render: (_, alert) => (
+ <div className="text-sm">
+ <div>{conditionSummary(alert)}</div>
+ <div className="text-muted text-xs">{selectionSummary(alert)}</div>
+ </div>
+ ),
+ },
+ {
+ title: 'Status',
+ key: 'status',
+ render: (_, alert) => (
+ <div className="flex items-center gap-2">
+ <ScannerAlertStateTag alert={alert} />
+ {alert.state === 'broken' ? (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconRefresh />}
+ tooltip="Reset the alert and run a check shortly"
+ onClick={() => resetAlert(alert.id)}
+ loading={busyAlertIds.has(alert.id)}
+ disabledReason={editDisabledReason}
+ data-attr="vision-alert-reset"
+ >
+ Reset
+ </LemonButton>
+ ) : null}
+ </div>
+ ),
+ },
+ {
+ title: 'Last checked',
+ key: 'last_checked',
+ render: (_, alert) =>
+ alert.kind === 'match' ? (
+ <span className="text-muted text-sm">Continuous</span>
+ ) : alert.last_checked_at ? (
+ <TZLabel time={alert.last_checked_at} formatDate="MMM D" formatTime="HH:mm" />
+ ) : (
+ <span className="text-muted">Not yet</span>
+ ),
+ },
+ {
+ title: 'Created by',
+ key: 'created_by',
+ render: (_, alert) =>
+ alert.created_by ? (
+ <ProfilePicture
+ user={{
+ email: alert.created_by.email,
+ first_name: alert.created_by.first_name,
+ last_name: alert.created_by.last_name,
+ }}
+ size="md"
+ showName
+ />
+ ) : (
+ <span className="text-muted">—</span>
+ ),
+ },
+ {
+ title: 'Enabled',
+ key: 'enabled',
+ width: 0,
+ render: (_, alert) => (
+ <LemonSwitch
+ checked={alert.enabled ?? true}
+ onChange={() => toggleAlertEnabled(alert)}
+ disabled={busyAlertIds.has(alert.id)}
+ disabledReason={editDisabledReason}
+ size="small"
+ data-attr="vision-alert-toggle-enabled"
+ />
+ ),
+ },
+ ]
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonTable
+ columns={columns}
+ dataSource={alerts}
+ loading={alertsLoading}
+ rowKey="id"
+ data-attr="vision-alerts-table"
+ emptyState="No alerts on this scanner yet. Create one to get notified about matching observations or metric thresholds."
+ />
+ <div className="flex justify-center">
+ <LemonButton
+ type="primary"
+ icon={<IconPlus />}
+ onClick={openCreateAlertModal}
+ disabledReason={editDisabledReason}
+ data-attr="vision-alert-new"
+ >
+ New alert
+ </LemonButton>
+ </div>
+ <ScannerAlertCreateModal
+ scannerId={scannerId}
+ scannerType={scannerType}
+ isOpen={isCreateAlertModalOpen}
+ onClose={closeCreateAlertModal}
+ />
+ <ScannerAlertEditModal
+ scannerId={scannerId}
+ scannerType={scannerType}
+ alert={editingAlert}
+ onClose={closeEditAlertModal}
+ />
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
index 82bf672e16ae..40d5f41ed35c 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
@@ -116,24 +116,30 @@ function VisionActionsTable({
// When on, digests live on the scanner's own Scouts tab; vision actions then only carry alerts
// (plus any legacy digests awaiting migration).
const scoutDigests = !!featureFlags[FEATURE_FLAGS.REPLAY_VISION_SCOUT_DIGESTS]
+ // New alerts live on the Alerts tab; this tab then only lists legacy digests, and legacy
+ // alert rows and the legacy "New alert" button disappear (existing configs keep running
+ // backend-side until the migration).
+ const newAlerts = !!featureFlags[FEATURE_FLAGS.REPLAY_VISION_ALERTS]
// The scanner's built-in featured digest is listed here alongside user-created digests and alerts
// (marked with a "Featured digest" chip), so this page is the one place to see and manage every
// automation on the scanner. It also has its own hero surface on the Observations tab.
- const rows = visionActions
+ const rows = newAlerts ? visionActions.filter((action) => action.mode !== 'alert') : visionActions
if (!visionActionsLoading && rows.length === 0) {
const emptyState = (
<ProductIntroduction
- productName={scoutDigests ? 'Alerts' : 'Digests and alerts'}
- thingName={scoutDigests ? 'alert' : 'digest or alert'}
+ productName={newAlerts ? 'Digests' : scoutDigests ? 'Alerts' : 'Digests and alerts'}
+ thingName={newAlerts ? 'digest' : scoutDigests ? 'alert' : 'digest or alert'}
isEmpty
customHog={HedgehogXRay}
docsURL={visionDocsUrl('actions')}
description={
- scoutDigests
- ? 'Set alerts that notify you when new matches appear or a threshold is reached. Alerts can deliver to Slack.'
- : "Get scheduled digests of this scanner's observations, synthesized by AI on the cadence you choose. Or set alerts that notify you when new matches appear or a threshold is reached. Both can deliver to Slack."
+ newAlerts
+ ? "Get scheduled digests of this scanner's observations, synthesized by AI on the cadence you choose."
+ : scoutDigests
+ ? 'Set alerts that notify you when new matches appear or a threshold is reached. Alerts can deliver to Slack.'
+ : "Get scheduled digests of this scanner's observations, synthesized by AI on the cadence you choose. Or set alerts that notify you when new matches appear or a threshold is reached. Both can deliver to Slack."
}
actionElementOverride={
<div className="flex gap-2">
@@ -149,16 +155,18 @@ function VisionActionsTable({
</LemonButton>
</EditorGate>
)}
- <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}>
- <LemonButton
- type="secondary"
- icon={<IconPlus />}
- to={urls.replayVisionActionNew(scannerId, 'alert')}
- data-attr="vision-action-new-alert-empty"
- >
- New alert
- </LemonButton>
- </EditorGate>
+ {!newAlerts && (
+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}>
+ <LemonButton
+ type="secondary"
+ icon={<IconPlus />}
+ to={urls.replayVisionActionNew(scannerId, 'alert')}
+ data-attr="vision-action-new-alert-empty"
+ >
+ New alert
+ </LemonButton>
+ </EditorGate>
+ )}
</div>
}
/>
@@ -291,16 +299,18 @@ function VisionActionsTable({
</LemonButton>
</EditorGate>
)}
- <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}>
- <LemonButton
- type="secondary"
- icon={<IconPlus />}
- to={urls.replayVisionActionNew(scannerId, 'alert')}
- data-attr="vision-action-new-alert"
- >
- New alert
- </LemonButton>
- </EditorGate>
+ {!newAlerts && (
+ <EditorGate userAccessLevel={scannerUserAccessLevel ?? undefined}>
+ <LemonButton
+ type="secondary"
+ icon={<IconPlus />}
+ to={urls.replayVisionActionNew(scannerId, 'alert')}
+ data-attr="vision-action-new-alert"
+ >
+ New alert
+ </LemonButton>
+ </EditorGate>
+ )}
</div>
<LemonTable
columns={columns}
@@ -309,9 +319,11 @@ function VisionActionsTable({
rowKey="id"
data-attr="vision-actions-table"
emptyState={
- scoutDigests
- ? 'No alerts set up for this scanner yet.'
- : 'No digests or alerts set up for this scanner yet.'
+ newAlerts
+ ? 'No digests set up for this scanner yet.'
+ : scoutDigests
+ ? 'No alerts set up for this scanner yet.'
+ : 'No digests or alerts set up for this scanner yet.'
}
/>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts
index f8369e63d40a..e07b4a4b61a0 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts
@@ -18,6 +18,7 @@ export enum ReplayScannerTab {
Configuration = 'configuration',
Actions = 'actions',
Scouts = 'scouts',
+ Alerts = 'alerts',
}
const SCANNER_TABS: ReplayScannerTab[] = Object.values(ReplayScannerTab)
@@ -132,6 +133,18 @@ export const replayScannerSceneLogic = kea<replayScannerSceneLogicType>([
if (tab === ReplayScannerTab.Scouts && !values.featureFlags[FEATURE_FLAGS.REPLAY_VISION_SCOUT_DIGESTS]) {
tab = DEFAULT_TAB
}
+ if (tab === ReplayScannerTab.Alerts && !values.featureFlags[FEATURE_FLAGS.REPLAY_VISION_ALERTS]) {
+ tab = DEFAULT_TAB
+ }
+ // With both flags on the Actions tab is hidden entirely, so a stale
+ // `?tab=actions` URL would select a tab with no content.
+ if (
+ tab === ReplayScannerTab.Actions &&
+ values.featureFlags[FEATURE_FLAGS.REPLAY_VISION_ALERTS] &&
+ values.featureFlags[FEATURE_FLAGS.REPLAY_VISION_SCOUT_DIGESTS]
+ ) {
+ tab = DEFAULT_TAB
+ }
if (tab !== values.activeTab) {
actions.setActiveTab(tab)
}
diff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertEventsLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertEventsLogic.ts
new file mode 100644
index 000000000000..40583f878b1c
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertEventsLogic.ts
@@ -0,0 +1,138 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, path, props } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { visionAlertsEventsList } from '../generated/api'
+import type { VisionAlertEventApi } from '../generated/api.schemas'
+
+export interface ScannerAlertEventsLogicProps {
+ alertId: string
+}
+
+export interface AlertEventsPage {
+ results: VisionAlertEventApi[]
+ next: string | null
+ count: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertEventsLogicValues {
+ currentTeamId: number | null // teamLogic
+ eventsPage: AlertEventsPage
+ eventsPageLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertEventsLogicActions {
+ loadEvents: () => any
+ loadEventsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadEventsSuccess: (
+ eventsPage: {
+ count: number
+ next: string | null
+ results: VisionAlertEventApi[]
+ },
+ payload?: any
+ ) => {
+ eventsPage: {
+ count: number
+ next: string | null
+ results: VisionAlertEventApi[]
+ }
+ payload?: any
+ }
+ loadMore: () => {
+ value: true
+ }
+ loadMoreFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMoreSuccess: (
+ eventsPage: AlertEventsPage,
+ payload?: {
+ value: true
+ }
+ ) => {
+ eventsPage: AlertEventsPage
+ payload?: {
+ value: true
+ }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertEventsLogicMeta {
+ key: string
+}
+
+export type scannerAlertEventsLogicType = MakeLogicType<
+ scannerAlertEventsLogicValues,
+ scannerAlertEventsLogicActions,
+ ScannerAlertEventsLogicProps,
+ scannerAlertEventsLogicMeta
+>
+
+export const scannerAlertEventsLogic = kea<scannerAlertEventsLogicType>([
+ path((key) => ['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerAlertEventsLogic', key]),
+ props({} as ScannerAlertEventsLogicProps),
+ key((props) => props.alertId),
+
+ connect({
+ values: [teamLogic, ['currentTeamId']],
+ }),
+
+ actions({
+ loadMore: true,
+ }),
+
+ loaders(({ props, values }) => ({
+ eventsPage: [
+ { results: [], next: null, count: 0 } as AlertEventsPage,
+ {
+ loadEvents: async () => {
+ const response = await visionAlertsEventsList(String(values.currentTeamId), props.alertId)
+ return {
+ results: response.results ?? [],
+ next: response.next ?? null,
+ count: response.count ?? 0,
+ }
+ },
+ loadMore: async () => {
+ const nextUrl = values.eventsPage.next
+ if (!nextUrl) {
+ return values.eventsPage
+ }
+ const res = await fetch(nextUrl, { credentials: 'include' })
+ if (!res.ok) {
+ throw new Error(`Failed to load more events: ${res.status} ${res.statusText}`)
+ }
+ const data = (await res.json()) as {
+ results?: VisionAlertEventApi[]
+ next?: string | null
+ count?: number
+ }
+ return {
+ results: [...values.eventsPage.results, ...(data.results ?? [])],
+ next: data.next ?? null,
+ count: data.count ?? values.eventsPage.count,
+ }
+ },
+ },
+ ],
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadEvents()
+ }),
+])
diff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertFormLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertFormLogic.test.ts
new file mode 100644
index 000000000000..2ad9abe4352d
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertFormLogic.test.ts
@@ -0,0 +1,29 @@
+import type { VisionAlertConfigurationApi } from '../generated/api.schemas'
+import { buildFormDefaults, buildSelection } from './scannerAlertFormLogic'
+
+describe('scannerAlertFormLogic selection mapping', () => {
+ it('round-trips an alert selection through form defaults and back', () => {
+ const alert = {
+ id: 'a1',
+ name: 'Failed checkouts',
+ kind: 'match',
+ selection: { verdict: ['yes'], tags: ['checkout'], min_score: 2 },
+ metric: 'count',
+ direction: 'above',
+ threshold: null,
+ window_days: 1,
+ evaluation_periods: 1,
+ datapoints_to_alarm: 1,
+ cooldown_minutes: 0,
+ schedule_restriction: null,
+ } as unknown as VisionAlertConfigurationApi
+
+ const form = buildFormDefaults(alert)
+ expect(buildSelection(form)).toEqual({ verdict: ['yes'], tags: ['checkout'], min_score: 2 })
+ })
+
+ it('empty selection stays empty', () => {
+ const alert = { selection: {} } as unknown as VisionAlertConfigurationApi
+ expect(buildSelection(buildFormDefaults(alert))).toEqual({})
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertFormLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertFormLogic.ts
new file mode 100644
index 000000000000..dc9eb70cefc0
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertFormLogic.ts
@@ -0,0 +1,266 @@
+import { MakeLogicType, afterMount, connect, kea, key, path, props, selectors } from 'kea'
+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
+import { forms } from 'kea-forms'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { ApiError } from 'lib/api'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { findQuietHoursIssues } from 'products/alerts/frontend/logic/scheduleRestrictionValidation'
+import type { ScheduleRestriction } from 'products/alerts/frontend/types'
+
+import { visionAlertsCreate, visionAlertsPartialUpdate } from '../generated/api'
+import type { VisionAlertConfigurationApi } from '../generated/api.schemas'
+import { scannerAlertNotificationLogic } from './scannerAlertNotificationLogic'
+import { scannerAlertsLogic } from './scannerAlertsLogic'
+import type { PendingVisionAlertNotification } from './scannerAlertUtils'
+
+export type VisionAlertKind = 'metric' | 'match'
+
+export interface ScannerAlertFormType {
+ name: string
+ kind: VisionAlertKind
+ verdict: string[]
+ tags: string[]
+ minScore: number | null
+ maxScore: number | null
+ metric: 'count' | 'avg_score'
+ direction: 'above' | 'below'
+ threshold: number | null
+ windowDays: number
+ evaluationPeriods: number
+ datapointsToAlarm: number
+ cooldownMinutes: number
+ scheduleRestriction: ScheduleRestriction | null
+}
+
+export interface ScannerAlertFormLogicProps {
+ scannerId: string
+ alert: VisionAlertConfigurationApi | null
+ onSubmitSuccess?: () => void
+}
+
+export function buildFormDefaults(alert: VisionAlertConfigurationApi | null): ScannerAlertFormType {
+ const selection = (alert?.selection ?? {}) as Record<string, unknown>
+ return {
+ name: alert?.name ?? '',
+ kind: (alert?.kind as VisionAlertKind) ?? 'match',
+ verdict: (selection.verdict as string[] | undefined) ?? [],
+ tags: (selection.tags as string[] | undefined) ?? [],
+ minScore: (selection.min_score as number | undefined) ?? null,
+ maxScore: (selection.max_score as number | undefined) ?? null,
+ metric: alert?.metric ?? 'count',
+ direction: alert?.direction ?? 'above',
+ threshold: alert?.threshold ?? null,
+ windowDays: alert?.window_days ?? 1,
+ evaluationPeriods: alert?.evaluation_periods ?? 1,
+ datapointsToAlarm: alert?.datapoints_to_alarm ?? 1,
+ cooldownMinutes: alert?.cooldown_minutes ?? 0,
+ scheduleRestriction: (alert?.schedule_restriction as ScheduleRestriction | null) ?? null,
+ }
+}
+
+export function buildSelection(form: ScannerAlertFormType): Record<string, unknown> {
+ const selection: Record<string, unknown> = {}
+ if (form.verdict.length) {
+ selection.verdict = form.verdict
+ }
+ if (form.tags.length) {
+ selection.tags = form.tags
+ }
+ if (form.minScore !== null) {
+ selection.min_score = form.minScore
+ }
+ if (form.maxScore !== null) {
+ selection.max_score = form.maxScore
+ }
+ return selection
+}
+
+function saveErrorMessage(error: ApiError): string {
+ return error.detail ?? error.message ?? 'Could not save the alert. Try again.'
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertFormLogicValues {
+ pendingNotifications: PendingVisionAlertNotification[] // scannerAlertNotificationLogic
+ currentTeamId: number | null // teamLogic
+ alertForm: ScannerAlertFormType
+ alertFormAllErrors: Record<string, any>
+ alertFormChanged: boolean
+ alertFormErrors: DeepPartialMap<ScannerAlertFormType, ValidationErrorType>
+ alertFormHasErrors: boolean
+ alertFormManualErrors: Record<string, any>
+ alertFormTouched: boolean
+ alertFormTouches: Record<string, boolean>
+ alertFormValidationErrors: DeepPartialMap<ScannerAlertFormType, ValidationErrorType>
+ isAlertFormSubmitting: boolean
+ isAlertFormValid: boolean
+ isEditing: boolean
+ showAlertFormErrors: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertFormLogicActions {
+ createPendingHogFunctions: (alertId: string) => {
+ alertId: string
+ } // scannerAlertNotificationLogic
+ loadAlerts: (_?: any) => any // scannerAlertsLogic
+ updateEditingAlert: (alert: VisionAlertConfigurationApi) => {
+ alert: VisionAlertConfigurationApi
+ } // scannerAlertsLogic
+ resetAlertForm: (values?: ScannerAlertFormType) => {
+ values?: ScannerAlertFormType
+ }
+ setAlertFormManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setAlertFormValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setAlertFormValues: (values: DeepPartial<ScannerAlertFormType>) => {
+ values: DeepPartial<ScannerAlertFormType>
+ }
+ submitAlertForm: () => {
+ value: boolean
+ }
+ submitAlertFormFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitAlertFormRequest: (alertForm: ScannerAlertFormType) => {
+ alertForm: ScannerAlertFormType
+ }
+ submitAlertFormSuccess: (alertForm: ScannerAlertFormType) => {
+ alertForm: ScannerAlertFormType
+ }
+ touchAlertFormField: (key: string) => {
+ key: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertFormLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ isEditing: (arg: any) => boolean
+ }
+}
+
+export type scannerAlertFormLogicType = MakeLogicType<
+ scannerAlertFormLogicValues,
+ scannerAlertFormLogicActions,
+ ScannerAlertFormLogicProps,
+ scannerAlertFormLogicMeta
+>
+
+export const scannerAlertFormLogic = kea<scannerAlertFormLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerAlertFormLogic']),
+ props({} as ScannerAlertFormLogicProps),
+ key(({ alert, scannerId }) => alert?.id ?? `new-${scannerId}`),
+
+ connect(({ alert, scannerId }: ScannerAlertFormLogicProps) => ({
+ values: [
+ teamLogic,
+ ['currentTeamId'],
+ scannerAlertNotificationLogic({ alertId: alert?.id }),
+ ['pendingNotifications'],
+ ],
+ actions: [
+ scannerAlertsLogic({ scannerId }),
+ ['loadAlerts', 'updateEditingAlert'],
+ scannerAlertNotificationLogic({ alertId: alert?.id }),
+ ['createPendingHogFunctions'],
+ ],
+ })),
+
+ selectors({
+ isEditing: [() => [(_, props) => props.alert], (alert: VisionAlertConfigurationApi | null) => alert !== null],
+ }),
+
+ afterMount(({ actions, props }) => {
+ // Pass values explicitly to reset — kea caches logic instances by key, so defaults
+ // from a previous mount may be stale.
+ actions.resetAlertForm(buildFormDefaults(props.alert))
+ }),
+
+ forms(({ props, actions, values }) => ({
+ alertForm: {
+ defaults: buildFormDefaults(props.alert),
+ errors: ({ name, kind, threshold }) => ({
+ name: !name?.trim() ? 'Enter an alert name.' : undefined,
+ threshold: kind === 'metric' && threshold === null ? 'Enter a threshold.' : undefined,
+ }),
+ submit: async (form) => {
+ if (form.scheduleRestriction?.blocked_windows) {
+ const quietHoursIssue = findQuietHoursIssues(form.scheduleRestriction.blocked_windows)
+ if (quietHoursIssue) {
+ throw new Error(quietHoursIssue.message)
+ }
+ }
+
+ const projectId = String(values.currentTeamId)
+ const isMetric = form.kind === 'metric'
+ const payload = {
+ scanner_id: props.scannerId,
+ name: form.name.trim(),
+ kind: form.kind,
+ selection: buildSelection(form),
+ // The drain holds match bundles through quiet hours too.
+ schedule_restriction: form.scheduleRestriction,
+ ...(isMetric
+ ? {
+ metric: form.metric,
+ direction: form.direction,
+ threshold: form.threshold,
+ window_days: form.windowDays,
+ evaluation_periods: form.evaluationPeriods,
+ datapoints_to_alarm: form.datapointsToAlarm,
+ cooldown_minutes: form.cooldownMinutes,
+ }
+ : {}),
+ }
+
+ let savedAlertId: string
+ try {
+ if (props.alert) {
+ // kind and scanner are immutable server-side; leave them out of the patch.
+ const { kind: _kind, scanner_id: _scanner, ...patch } = payload
+ const updated = await visionAlertsPartialUpdate(projectId, props.alert.id, patch)
+ actions.updateEditingAlert(updated)
+ savedAlertId = props.alert.id
+ lemonToast.success('Alert updated')
+ } else {
+ const created = await visionAlertsCreate(projectId, payload as any)
+ savedAlertId = created.id
+ lemonToast.success('Alert created')
+ }
+ } catch (error: unknown) {
+ lemonToast.error(saveErrorMessage(error as ApiError))
+ throw error
+ }
+
+ try {
+ if (values.pendingNotifications.length > 0) {
+ const notifLogic = scannerAlertNotificationLogic({ alertId: props.alert?.id })
+ await notifLogic.asyncActions.createPendingHogFunctions(savedAlertId)
+ }
+ } catch {
+ lemonToast.error('Alert saved, but notifications could not be configured.')
+ }
+
+ actions.loadAlerts()
+ props.onSubmitSuccess?.()
+ return form
+ },
+ },
+ })),
+])
diff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts
new file mode 100644
index 000000000000..aaf8a2093659
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts
@@ -0,0 +1,461 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { HogFunctionType, IntegrationType } from '~/types'
+
+import type { AlertNotificationUrlInput } from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'
+
+import { visionAlertsDestinationsCreate, visionAlertsDestinationsDeleteCreate } from '../generated/api'
+import {
+ PendingVisionAlertNotification,
+ VISION_ALERT_NOTIFICATION_TYPE_SLACK,
+ VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK,
+ VisionAlertDestinationGroup,
+ VisionAlertNotificationType,
+ buildVisionAlertFilterConfig,
+ groupVisionAlertDestinations,
+} from './scannerAlertUtils'
+
+export const VISION_ALERT_NOTIFICATION_TYPE_OPTIONS = [
+ { label: 'Slack', value: VISION_ALERT_NOTIFICATION_TYPE_SLACK },
+ { label: 'Webhook', value: VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK },
+]
+
+export interface ScannerAlertNotificationLogicProps {
+ alertId?: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertNotificationLogicValues {
+ integrationsLoading: boolean // integrationsLogic
+ slackIntegrations: IntegrationType[] | undefined // integrationsLogic
+ currentTeamId: number | null // teamLogic
+ addDisabledReason: string | undefined
+ destinationGroups: VisionAlertDestinationGroup[]
+ existingHogFunctions: HogFunctionType[]
+ existingHogFunctionsLoading: boolean
+ firstSlackIntegration: IntegrationType | undefined
+ integrationsFailed: boolean
+ pendingNotifications: PendingVisionAlertNotification[]
+ selectedType: VisionAlertNotificationType
+ slackChannelValue: string | null
+ urlInput: AlertNotificationUrlInput | undefined
+ webhookUrl: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertNotificationLogicActions {
+ loadIntegrations: () => any // integrationsLogic
+ loadIntegrationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // integrationsLogic
+ loadIntegrationsSuccess: (
+ integrations: {
+ config: any
+ created_at: string
+ created_by?: null | import('~/types').UserBasicType | undefined
+ display_name: string
+ errors?: string | undefined
+ icon_url: any
+ id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
+ kind:
+ | 'apns'
+ | 'aws-s3'
+ | 'azure-blob'
+ | 'bing-ads'
+ | 'clickup'
+ | 'customerio-app'
+ | 'customerio-track'
+ | 'customerio-webhook'
+ | 'databricks'
+ | 'email'
+ | 'firebase'
+ | 'github'
+ | 'gitlab'
+ | 'google-ads'
+ | 'google-analytics'
+ | 'google-calendar'
+ | 'google-cloud-service-account'
+ | 'google-cloud-storage'
+ | 'google-pubsub'
+ | 'google-search-console'
+ | 'google-sheets'
+ | 'hubspot'
+ | 'instagram'
+ | 'intercom'
+ | 'jira'
+ | 'linear'
+ | 'linkedin-ads'
+ | 'meta-ads'
+ | 'pardot'
+ | 'pinterest-ads'
+ | 'postgresql'
+ | 'reddit-ads'
+ | 's3-compatible'
+ | 'salesforce'
+ | 'slack'
+ | 'snapchat'
+ | 'snowflake'
+ | 'stripe'
+ | 'tiktok-ads'
+ | 'twilio'
+ | 'vercel'
+ | 'youtube-analytics'
+ }[],
+ payload?: any
+ ) => {
+ integrations: {
+ config: any
+ created_at: string
+ created_by?: null | import('~/types').UserBasicType | undefined
+ display_name: string
+ errors?: string | undefined
+ icon_url: any
+ id: number
+ installation_shared?: boolean | null | undefined
+ installation_status?:
+ | null
+ | import('products/integrations/frontend/generated/api.schemas').InstallationStatusEnumApi
+ | undefined
+ kind:
+ | 'apns'
+ | 'aws-s3'
+ | 'azure-blob'
+ | 'bing-ads'
+ | 'clickup'
+ | 'customerio-app'
+ | 'customerio-track'
+ | 'customerio-webhook'
+ | 'databricks'
+ | 'email'
+ | 'firebase'
+ | 'github'
+ | 'gitlab'
+ | 'google-ads'
+ | 'google-analytics'
+ | 'google-calendar'
+ | 'google-cloud-service-account'
+ | 'google-cloud-storage'
+ | 'google-pubsub'
+ | 'google-search-console'
+ | 'google-sheets'
+ | 'hubspot'
+ | 'instagram'
+ | 'intercom'
+ | 'jira'
+ | 'linear'
+ | 'linkedin-ads'
+ | 'meta-ads'
+ | 'pardot'
+ | 'pinterest-ads'
+ | 'postgresql'
+ | 'reddit-ads'
+ | 's3-compatible'
+ | 'salesforce'
+ | 'slack'
+ | 'snapchat'
+ | 'snowflake'
+ | 'stripe'
+ | 'tiktok-ads'
+ | 'twilio'
+ | 'vercel'
+ | 'youtube-analytics'
+ }[]
+ payload?: any
+ } // integrationsLogic
+ addPendingNotification: (notification: PendingVisionAlertNotification) => {
+ notification: PendingVisionAlertNotification
+ }
+ addSelectedNotification: () => {
+ value: true
+ }
+ clearPendingNotifications: () => {
+ value: true
+ }
+ createPendingHogFunctions: (alertId: string) => {
+ alertId: string
+ }
+ deleteExistingDestination: (group: VisionAlertDestinationGroup) => {
+ group: VisionAlertDestinationGroup
+ }
+ loadExistingHogFunctions: (alertId?: string) => string
+ loadExistingHogFunctionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadExistingHogFunctionsSuccess: (
+ existingHogFunctions: HogFunctionType[],
+ payload?: string
+ ) => {
+ existingHogFunctions: HogFunctionType[]
+ payload?: string
+ }
+ removePendingNotification: (index: number) => {
+ index: number
+ }
+ setPendingNotifications: (notifications: PendingVisionAlertNotification[]) => {
+ notifications: PendingVisionAlertNotification[]
+ }
+ setSelectedType: (selectedType: VisionAlertNotificationType) => {
+ selectedType: VisionAlertNotificationType
+ }
+ setSlackChannelValue: (slackChannelValue: string | null) => {
+ slackChannelValue: string | null
+ }
+ setWebhookUrl: (webhookUrl: string) => {
+ webhookUrl: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertNotificationLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ firstSlackIntegration: (slackIntegrations: IntegrationType[] | undefined) => IntegrationType | undefined
+ urlInput: (selectedType: VisionAlertNotificationType) => AlertNotificationUrlInput | undefined
+ addDisabledReason: (
+ selectedType: VisionAlertNotificationType,
+ firstSlackIntegration: IntegrationType | undefined,
+ slackChannelValue: string | null,
+ webhookUrl: string
+ ) => string | undefined
+ destinationGroups: (existingHogFunctions: HogFunctionType[]) => VisionAlertDestinationGroup[]
+ }
+}
+
+export type scannerAlertNotificationLogicType = MakeLogicType<
+ scannerAlertNotificationLogicValues,
+ scannerAlertNotificationLogicActions,
+ ScannerAlertNotificationLogicProps,
+ scannerAlertNotificationLogicMeta
+>
+
+export const scannerAlertNotificationLogic = kea<scannerAlertNotificationLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerAlertNotificationLogic']),
+ props({} as ScannerAlertNotificationLogicProps),
+ key(({ alertId }) => alertId ?? 'new'),
+
+ connect({
+ values: [teamLogic, ['currentTeamId'], integrationsLogic, ['integrationsLoading', 'slackIntegrations']],
+ actions: [integrationsLogic, ['loadIntegrations', 'loadIntegrationsFailure', 'loadIntegrationsSuccess']],
+ }),
+
+ actions({
+ addPendingNotification: (notification: PendingVisionAlertNotification) => ({ notification }),
+ addSelectedNotification: true,
+ removePendingNotification: (index: number) => ({ index }),
+ clearPendingNotifications: true,
+ setPendingNotifications: (notifications: PendingVisionAlertNotification[]) => ({ notifications }),
+ deleteExistingDestination: (group: VisionAlertDestinationGroup) => ({ group }),
+ createPendingHogFunctions: (alertId: string) => ({ alertId }),
+ setSelectedType: (selectedType: VisionAlertNotificationType) => ({ selectedType }),
+ setSlackChannelValue: (slackChannelValue: string | null) => ({ slackChannelValue }),
+ setWebhookUrl: (webhookUrl: string) => ({ webhookUrl }),
+ }),
+
+ reducers({
+ pendingNotifications: [
+ [] as PendingVisionAlertNotification[],
+ {
+ addPendingNotification: (state, { notification }) => [...state, notification],
+ removePendingNotification: (state, { index }) => state.filter((_, i) => i !== index),
+ clearPendingNotifications: () => [],
+ setPendingNotifications: (_, { notifications }) => notifications,
+ },
+ ],
+ integrationsFailed: [
+ false,
+ {
+ loadIntegrations: () => false,
+ loadIntegrationsFailure: () => true,
+ loadIntegrationsSuccess: () => false,
+ },
+ ],
+ slackChannelValue: [
+ null as string | null,
+ {
+ setSlackChannelValue: (_, { slackChannelValue }) => slackChannelValue,
+ },
+ ],
+ webhookUrl: [
+ '' as string,
+ {
+ setWebhookUrl: (_, { webhookUrl }) => webhookUrl,
+ },
+ ],
+ selectedType: [
+ VISION_ALERT_NOTIFICATION_TYPE_SLACK as VisionAlertNotificationType,
+ {
+ setSelectedType: (_, { selectedType }) => selectedType,
+ },
+ ],
+ }),
+
+ loaders(({ props }) => ({
+ existingHogFunctions: [
+ [] as HogFunctionType[],
+ {
+ loadExistingHogFunctions: async (alertId?: string) => {
+ const id = alertId ?? props.alertId
+ if (!id) {
+ return []
+ }
+ const response = await api.hogFunctions.list({
+ types: ['internal_destination'],
+ filter_groups: [buildVisionAlertFilterConfig(id)],
+ full: true,
+ })
+ return response.results
+ },
+ },
+ ],
+ })),
+
+ selectors({
+ firstSlackIntegration: [
+ (s) => [s.slackIntegrations],
+ (slackIntegrations: IntegrationType[] | undefined): IntegrationType | undefined => slackIntegrations?.[0],
+ ],
+ urlInput: [
+ (s) => [s.selectedType],
+ (selectedType: VisionAlertNotificationType): AlertNotificationUrlInput | undefined =>
+ selectedType === VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK
+ ? { placeholder: 'https://example.com/webhook' }
+ : undefined,
+ ],
+ addDisabledReason: [
+ (s) => [s.selectedType, s.firstSlackIntegration, s.slackChannelValue, s.webhookUrl],
+ (
+ selectedType: VisionAlertNotificationType,
+ firstSlackIntegration: IntegrationType | undefined,
+ slackChannelValue: string | null,
+ webhookUrl: string
+ ): string | undefined => {
+ if (selectedType !== VISION_ALERT_NOTIFICATION_TYPE_SLACK) {
+ return webhookUrl ? undefined : 'Enter a webhook URL'
+ }
+ if (!firstSlackIntegration) {
+ return 'Connect Slack first'
+ }
+ return slackChannelValue ? undefined : 'Select a Slack channel'
+ },
+ ],
+ destinationGroups: [
+ (s) => [s.existingHogFunctions],
+ (hogFunctions: HogFunctionType[]): VisionAlertDestinationGroup[] =>
+ groupVisionAlertDestinations(hogFunctions),
+ ],
+ }),
+
+ listeners(({ actions, values, props }) => ({
+ addSelectedNotification: () => {
+ if (values.selectedType === VISION_ALERT_NOTIFICATION_TYPE_SLACK) {
+ if (!values.slackChannelValue || !values.firstSlackIntegration) {
+ return
+ }
+ const [channelId, channelLabel] = values.slackChannelValue.split('|')
+ actions.addPendingNotification({
+ type: VISION_ALERT_NOTIFICATION_TYPE_SLACK,
+ slackWorkspaceId: values.firstSlackIntegration.id,
+ slackChannelId: channelId,
+ slackChannelName: channelLabel?.replace('#', '') ?? channelId,
+ })
+ actions.setSlackChannelValue(null)
+ return
+ }
+ if (!values.webhookUrl) {
+ return
+ }
+ actions.addPendingNotification({
+ type: VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK,
+ webhookUrl: values.webhookUrl,
+ })
+ actions.setWebhookUrl('')
+ },
+ addPendingNotification: () => {
+ if (props.alertId) {
+ actions.createPendingHogFunctions(props.alertId)
+ }
+ },
+ loadIntegrationsSuccess: () => {
+ if (!values.firstSlackIntegration) {
+ actions.setSelectedType(VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK)
+ }
+ },
+ deleteExistingDestination: async ({ group }) => {
+ if (!props.alertId) {
+ return
+ }
+ try {
+ await visionAlertsDestinationsDeleteCreate(String(values.currentTeamId), props.alertId, {
+ hog_function_ids: group.hogFunctions.map((hf) => hf.id),
+ })
+ lemonToast.success(`Removed ${group.label}`)
+ } catch {
+ lemonToast.error(`Could not remove ${group.label}. Try again.`)
+ }
+ actions.loadExistingHogFunctions()
+ },
+ createPendingHogFunctions: async ({ alertId }) => {
+ const pending = values.pendingNotifications
+ if (pending.length === 0) {
+ return
+ }
+
+ const projectId = String(values.currentTeamId)
+ const results = await Promise.allSettled(
+ pending.map((notification) => {
+ const payload =
+ notification.type === VISION_ALERT_NOTIFICATION_TYPE_SLACK
+ ? {
+ type: VISION_ALERT_NOTIFICATION_TYPE_SLACK,
+ slack_workspace_id: notification.slackWorkspaceId,
+ slack_channel_id: notification.slackChannelId,
+ slack_channel_name: notification.slackChannelName,
+ }
+ : {
+ type: notification.type,
+ webhook_url: notification.webhookUrl,
+ }
+ return visionAlertsDestinationsCreate(projectId, alertId, payload)
+ })
+ )
+
+ const failedNotifications = pending.filter((_, i) => results[i].status === 'rejected')
+ actions.loadExistingHogFunctions(alertId)
+
+ if (failedNotifications.length > 0) {
+ lemonToast.error(
+ `Alert saved, but ${failedNotifications.length} notification destination(s) could not be created. Reopen the alert to add them again.`
+ )
+ actions.setPendingNotifications(failedNotifications)
+ } else {
+ lemonToast.success(`${pending.length} notification destination(s) created.`)
+ actions.clearPendingNotifications()
+ }
+ },
+ })),
+
+ afterMount(({ actions, props }) => {
+ if (props.alertId) {
+ actions.loadExistingHogFunctions()
+ }
+ }),
+])
diff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertUtils.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertUtils.ts
new file mode 100644
index 000000000000..d2c1ca197530
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertUtils.ts
@@ -0,0 +1,114 @@
+import { CyclotronJobFiltersType, HogFunctionType, PropertyFilterType, PropertyOperator } from '~/types'
+
+import type { VisionAlertConfigurationApi } from '../generated/api.schemas'
+
+// pinned: internal event ids — HogFunction destination filters match on them
+export const VISION_ALERT_FIRING_EVENT_ID = '$replay_vision_alert_firing'
+export const VISION_ALERT_RESOLVED_EVENT_ID = '$replay_vision_alert_resolved'
+export const VISION_ALERT_AUTO_DISABLED_EVENT_ID = '$replay_vision_alert_auto_disabled'
+export const VISION_ALERT_ERRORED_EVENT_ID = '$replay_vision_alert_errored'
+export const VISION_ALERT_MATCH_EVENT_ID = '$replay_vision_alert_match'
+
+export const VISION_ALERT_NOTIFICATION_TYPE_SLACK = 'slack' as const
+export const VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK = 'webhook' as const
+
+export type VisionAlertNotificationType =
+ | typeof VISION_ALERT_NOTIFICATION_TYPE_SLACK
+ | typeof VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK
+
+export type PendingVisionAlertNotification =
+ | {
+ type: typeof VISION_ALERT_NOTIFICATION_TYPE_SLACK
+ slackWorkspaceId: number
+ slackChannelId: string
+ slackChannelName?: string
+ }
+ | {
+ type: typeof VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK
+ webhookUrl: string
+ }
+
+export type VisionAlertDestinationGroup = {
+ key: string
+ type: VisionAlertNotificationType
+ label: string
+ hogFunctions: HogFunctionType[]
+ enabled: boolean
+}
+
+// Matches every HogFunction belonging to this alert regardless of event kind: the create
+// endpoint fans out into one HogFunction per event kind, and the alert_id property alone
+// identifies the whole group.
+export function buildVisionAlertFilterConfig(alertId: string): CyclotronJobFiltersType {
+ return {
+ properties: [
+ {
+ key: 'alert_id',
+ value: alertId,
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ }
+}
+
+export function groupVisionAlertDestinations(hogFunctions: HogFunctionType[]): VisionAlertDestinationGroup[] {
+ const groups = new Map<string, VisionAlertDestinationGroup>()
+ for (const hf of hogFunctions) {
+ const templateId = hf.template_id ?? hf.template?.id
+ const slackChannelValue = hf.inputs?.channel?.value as string | undefined
+ const webhookUrl = hf.inputs?.url?.value as string | undefined
+
+ let key: string
+ let type: VisionAlertNotificationType
+ let label: string
+ if (templateId === 'template-slack') {
+ type = VISION_ALERT_NOTIFICATION_TYPE_SLACK
+ key = `slack:${slackChannelValue ?? hf.id}`
+ label = 'Slack'
+ } else {
+ type = VISION_ALERT_NOTIFICATION_TYPE_WEBHOOK
+ key = `webhook:${webhookUrl ?? hf.id}`
+ label = webhookUrl ?? hf.name
+ }
+
+ const existing = groups.get(key)
+ if (existing) {
+ existing.hogFunctions.push(hf)
+ existing.enabled = existing.enabled || !!hf.enabled
+ } else {
+ groups.set(key, { key, type, label, hogFunctions: [hf], enabled: !!hf.enabled })
+ }
+ }
+ return Array.from(groups.values())
+}
+
+export function conditionSummary(alert: VisionAlertConfigurationApi): string {
+ if (alert.kind === 'match') {
+ return 'every matching observation'
+ }
+ const metricLabel = alert.metric === 'avg_score' ? 'average score' : 'matching observations'
+ const directionLabel = alert.direction === 'below' ? 'at or below' : 'at or above'
+ const windowLabel = alert.window_days === 1 ? '24 hours' : `${alert.window_days} days`
+ return `${metricLabel} ${directionLabel} ${alert.threshold} in the last ${windowLabel}`
+}
+
+export function selectionSummary(alert: VisionAlertConfigurationApi): string {
+ const selection = (alert.selection ?? {}) as Record<string, unknown>
+ const parts: string[] = []
+ const verdict = selection.verdict as string[] | undefined
+ const tags = selection.tags as string[] | undefined
+ if (verdict?.length) {
+ parts.push(`verdict ${verdict.join(', ')}`)
+ }
+ if (tags?.length) {
+ parts.push(`tags ${tags.join(', ')}`)
+ }
+ if (selection.min_score !== undefined && selection.min_score !== null) {
+ parts.push(`score ≥ ${selection.min_score}`)
+ }
+ if (selection.max_score !== undefined && selection.max_score !== null) {
+ parts.push(`score ≤ ${selection.max_score}`)
+ }
+ return parts.length ? parts.join(', ') : 'all observations'
+}
diff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertsLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertsLogic.ts
new file mode 100644
index 000000000000..afa09a888538
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertsLogic.ts
@@ -0,0 +1,240 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ visionAlertsDestroy,
+ visionAlertsList,
+ visionAlertsPartialUpdate,
+ visionAlertsResetCreate,
+} from '../generated/api'
+import type { PatchedVisionAlertConfigurationApi, VisionAlertConfigurationApi } from '../generated/api.schemas'
+
+export interface ScannerAlertsLogicProps {
+ scannerId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertsLogicValues {
+ currentTeamId: number | null // teamLogic
+ alerts: VisionAlertConfigurationApi[]
+ alertsLoading: boolean
+ busyAlertIds: Set<string>
+ editingAlert: VisionAlertConfigurationApi | null
+ isCreateAlertModalOpen: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertsLogicActions {
+ closeCreateAlertModal: () => {
+ value: true
+ }
+ closeEditAlertModal: () => {
+ value: true
+ }
+ deleteAlert: (
+ id: string,
+ onSuccess?: () => void
+ ) => {
+ id: string
+ onSuccess: (() => void) | undefined
+ }
+ loadAlerts: (_?: any) => any
+ loadAlertsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAlertsSuccess: (
+ alerts: VisionAlertConfigurationApi[],
+ payload?: any
+ ) => {
+ alerts: VisionAlertConfigurationApi[]
+ payload?: any
+ }
+ openCreateAlertModal: () => {
+ value: true
+ }
+ openEditAlertModal: (alert: VisionAlertConfigurationApi) => {
+ alert: VisionAlertConfigurationApi
+ }
+ resetAlert: (id: string) => {
+ id: string
+ }
+ setAlertBusy: (
+ id: string,
+ busy: boolean
+ ) => {
+ busy: boolean
+ id: string
+ }
+ snoozeAlertUntil: (
+ alertId: string,
+ snoozeUntil: string
+ ) => {
+ alertId: string
+ snoozeUntil: string
+ }
+ toggleAlertEnabled: (alert: VisionAlertConfigurationApi) => {
+ alert: VisionAlertConfigurationApi
+ }
+ unsnoozeAlert: (alertId: string) => {
+ alertId: string
+ }
+ updateEditingAlert: (alert: VisionAlertConfigurationApi) => {
+ alert: VisionAlertConfigurationApi
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerAlertsLogicMeta {
+ key: string
+}
+
+export type scannerAlertsLogicType = MakeLogicType<
+ scannerAlertsLogicValues,
+ scannerAlertsLogicActions,
+ ScannerAlertsLogicProps,
+ scannerAlertsLogicMeta
+>
+
+export const scannerAlertsLogic = kea<scannerAlertsLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerAlertsLogic']),
+ props({} as ScannerAlertsLogicProps),
+ key((props) => props.scannerId),
+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
+
+ actions({
+ deleteAlert: (id: string, onSuccess?: () => void) => ({ id, onSuccess }),
+ toggleAlertEnabled: (alert: VisionAlertConfigurationApi) => ({ alert }),
+ resetAlert: (id: string) => ({ id }),
+ setAlertBusy: (id: string, busy: boolean) => ({ id, busy }),
+ snoozeAlertUntil: (alertId: string, snoozeUntil: string) => ({ alertId, snoozeUntil }),
+ unsnoozeAlert: (alertId: string) => ({ alertId }),
+ openCreateAlertModal: true,
+ closeCreateAlertModal: true,
+ openEditAlertModal: (alert: VisionAlertConfigurationApi) => ({ alert }),
+ closeEditAlertModal: true,
+ updateEditingAlert: (alert: VisionAlertConfigurationApi) => ({ alert }),
+ }),
+
+ reducers({
+ busyAlertIds: [
+ new Set<string>(),
+ {
+ setAlertBusy: (state, { id, busy }) =>
+ busy ? new Set([...state, id]) : new Set([...state].filter((x) => x !== id)),
+ },
+ ],
+ isCreateAlertModalOpen: [
+ false,
+ {
+ openCreateAlertModal: () => true,
+ closeCreateAlertModal: () => false,
+ },
+ ],
+ editingAlert: [
+ null as VisionAlertConfigurationApi | null,
+ {
+ openEditAlertModal: (_, { alert }) => alert,
+ closeEditAlertModal: () => null,
+ updateEditingAlert: (editingAlert, { alert }) => (editingAlert?.id === alert.id ? alert : editingAlert),
+ },
+ ],
+ }),
+
+ loaders(({ props, values }) => ({
+ alerts: [
+ [] as VisionAlertConfigurationApi[],
+ {
+ loadAlerts: async (_?: any, breakpoint?: any) => {
+ const response = await visionAlertsList(String(values.currentTeamId), {
+ scanner_id: props.scannerId,
+ })
+ breakpoint?.()
+ return response.results
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions, values }) => ({
+ deleteAlert: async ({ id, onSuccess }) => {
+ try {
+ await visionAlertsDestroy(String(values.currentTeamId), id)
+ lemonToast.success('Alert deleted')
+ actions.loadAlerts()
+ onSuccess?.()
+ } catch {
+ lemonToast.error('Could not delete the alert. Try again.')
+ }
+ },
+ toggleAlertEnabled: async ({ alert }) => {
+ const update: PatchedVisionAlertConfigurationApi = { enabled: !(alert.enabled ?? true) }
+ if (!update.enabled) {
+ update.snooze_until = null
+ }
+ actions.setAlertBusy(alert.id, true)
+ try {
+ const updated = await visionAlertsPartialUpdate(String(values.currentTeamId), alert.id, update)
+ actions.updateEditingAlert(updated)
+ actions.loadAlerts()
+ } catch {
+ lemonToast.error('Could not update the alert. Try again.')
+ } finally {
+ actions.setAlertBusy(alert.id, false)
+ }
+ },
+ resetAlert: async ({ id }) => {
+ actions.setAlertBusy(id, true)
+ try {
+ await visionAlertsResetCreate(String(values.currentTeamId), id)
+ lemonToast.success('Alert reset. The next check runs shortly.')
+ actions.loadAlerts()
+ } catch {
+ lemonToast.error('Could not reset the alert. Try again.')
+ } finally {
+ actions.setAlertBusy(id, false)
+ }
+ },
+ snoozeAlertUntil: async ({ alertId, snoozeUntil }) => {
+ actions.setAlertBusy(alertId, true)
+ try {
+ const updated = await visionAlertsPartialUpdate(String(values.currentTeamId), alertId, {
+ snooze_until: snoozeUntil,
+ })
+ actions.updateEditingAlert(updated)
+ lemonToast.success('Alert snoozed')
+ actions.loadAlerts()
+ } catch {
+ lemonToast.error('Could not snooze the alert. Try again.')
+ } finally {
+ actions.setAlertBusy(alertId, false)
+ }
+ },
+ unsnoozeAlert: async ({ alertId }) => {
+ actions.setAlertBusy(alertId, true)
+ try {
+ const updated = await visionAlertsPartialUpdate(String(values.currentTeamId), alertId, {
+ snooze_until: null,
+ })
+ actions.updateEditingAlert(updated)
+ lemonToast.success('Alert unsnoozed')
+ actions.loadAlerts()
+ } catch {
+ lemonToast.error('Could not unsnooze the alert. Try again.')
+ } finally {
+ actions.setAlertBusy(alertId, false)
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadAlerts()
+ }),
+])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2cc60c1f8517..a187198c1426 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -97108,6 +97108,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Only return alerts on this scanner.
+ */
+ scanner_id?: string;
};
export type VisionAlertsEventsListParams = {