: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): clarify adding notification destinations (#73234)
Matt Pua87f9a5ddd98d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6d696aa6f534..7271b024d88b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4719,13 +4719,13 @@ snapshots:products-alerts-shared-components--evaluation-history--light:hash: v1.k794b7964.4d156162bbf222b25d0bcea9f4be1c23c8c787a360b4b0bef507de7f361e8025.25EdkHo5WY5JPgsCWiwy4a_UjKJ594t0qnizfl_KW8Aproducts-alerts-shared-components--notifications--dark:- hash: v1.k794b7964.3f137bbf7a90843202ca75d89d5dec7f102945cf55f2c4532ccac3b4e8073c9b.phN1IPBCANIC0EsrGxopacxr96qniH5DnAm-ZnKVUz0+ hash: v1.k794b7964.81ff4b2654d65e3866f9dd9e04dfcedb6d1dbbb45fcdf73acfd60153ba263480.Zq6Us8BfcBnrdUHjpISWQFYe5836RgaIlc6eoFwpshEproducts-alerts-shared-components--notifications--light:- hash: v1.k794b7964.240b6085693c57e601cf978fe479a2cb6124c80c7cd743f44ff61744e94c90bb.v4D0nGdwscIlnUoeTqwHQsyEggk4eOm3GBGvgvFkXII+ hash: v1.k794b7964.7beb7eceac054cc9237abe9162264cccedd8a6432a7412384b89ebad24e67ac9.8fhutb-WaRjPZK54RrbK7XIxD7HXw8ZesPZXQP_V2eAproducts-alerts-shared-components--notifications-multiple-slack-workspaces--dark:- hash: v1.k794b7964.44080ef3cc8fb24fb5ad535ee387b4911358d8804045747939750530be5c6235.7UCJ4oJX1LEan-IVOu2iA5Hzz14HQQoZENCw_SMOxss+ hash: v1.k794b7964.3c027b2e0731f9738cdfe21d14b6a893375c0fe0a0f11b587580adafc09340f9.GfzW8vynGlDg1ZO7Mp1sS9oDhRiKra5Vxhtopyi31Goproducts-alerts-shared-components--notifications-multiple-slack-workspaces--light:- hash: v1.k794b7964.7af987b36145b9e49adca1cbc6d1a4616ae94866476f72bc510ab96d286e4133.3H70LHwnl5IAqi3fUW4lQZZ7UT9o23krCbiAdBvWpvY+ hash: v1.k794b7964.63ec31eddf76c6f6544838a9b765e091bbe84325070fff837ed94d2cc1e85ba8.rPHnjzF-XA_HZd7mJ9KKN8iLGsZVXVdne4uww2vsx4wproducts-alerts-shared-components--quiet-hours--dark:hash: v1.k794b7964.3a4e054512c5b607cf75f1cc3e6dd2212333d05e4fb89274b580b47f01e5aeaf.nPp2_jJIgcpjkQgHQA63v-eqzVox-oIfDi3SQKPdRisproducts-alerts-shared-components--quiet-hours--light:diff --git a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsxindex 336ea9a93843..895072b75e81 100644--- a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx+++ b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx@@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'import {LemonBanner,+ LemonBannerProps,LemonButton,LemonInputSelect,LemonInputSelectOption,@@ -21,10 +22,13 @@ import { IntegrationType, SlackChannelType } from '~/types'import { slackChannelId } from './slackChannel'import { slackIntegrationLogic } from './slackIntegrationLogic'-export function SlackNotConfiguredBanner(): JSX.Element {+export function SlackNotConfiguredBanner({+ type = 'info',+ className,+}: Partial<Pick<LemonBannerProps, 'type' | 'className'>>): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)return (- <LemonBanner type="info">+ <LemonBanner type={type} className={className}><div className="flex flex-col gap-2"><div className="flex justify-between gap-2 items-center"><span>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b1ca3ad5097a..0956e2ea8289 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2783,6 +2783,9 @@ importers:'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ '@testing-library/react':+ specifier: '*'+ version: 14.3.1(@types/[email protected])([email protected]([email protected]))([email protected])kea-test-utils:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsxindex 3283fb0365d5..c7b507f251f5 100644--- a/products/alerts/frontend/components/AlertComponents.stories.tsx+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx@@ -165,8 +165,8 @@ function NotificationsStory(): JSX.Element {const [pendingDestinations, setPendingDestinations] = useState<PendingAlertNotificationDestinationView[]>([{key: 'pending-webhook',- label: 'Webhook: https://example.com/pending',- status: '(pending, save alert to apply)',+ title: 'Webhook',+ detail: 'https://example.com/pending',onRemove: () => setPendingDestinations([]),},])@@ -179,8 +179,8 @@ function NotificationsStory(): JSX.Element {...destinations,{key: `pending-${destinations.length}`,- label: `Webhook: ${urlValue}`,- status: '(pending, save alert to apply)',+ title: 'Webhook',+ detail: urlValue,onRemove: () => setPendingDestinations([]),},])@@ -211,6 +211,10 @@ function NotificationsStory(): JSX.Element {}}slack={{notificationType: 'slack',+ integrationsLoading: false,+ integrationsFailed: false,+ onRetryIntegrations: () => {},+ integrations: [],channelValue: slackChannelValue,onChannelValueChange: setSlackChannelValue,}}diff --git a/products/alerts/frontend/components/AlertIntervalRow.tsx b/products/alerts/frontend/components/AlertIntervalRow.tsxindex eeda212530de..66a1bc1a1d1b 100644--- a/products/alerts/frontend/components/AlertIntervalRow.tsx+++ b/products/alerts/frontend/components/AlertIntervalRow.tsx@@ -6,6 +6,7 @@ import { TZLabel } from 'lib/components/TZLabel'import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonField } from 'lib/lemon-ui/LemonField'+import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'import { AlertCalculationInterval } from '~/queries/schema/schema-general'@@ -17,6 +18,7 @@ import {cadenceFinerThanInsightInterval,selectAlertCalculationInterval,} from 'products/alerts/frontend/logic/alertIntervalHelpers'+import { approximateNextAlertRun } from 'products/alerts/frontend/logic/alertSchedulingStale'import {AlertType,isHogQLAlertConfig,@@ -61,6 +63,7 @@ export function AlertIntervalRow({}: AlertIntervalRowProps): JSX.Element {const { hasAvailableFeature } = useValues(userLogic)const { guardAvailableFeature } = useValues(upgradeModalLogic)+ const { currentTeam } = useValues(teamLogic)const hasHighFrequencyAlertsEntitlement = hasAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS)const hasRealTimeAlertsEntitlement = hasAvailableFeature(AvailableFeature.REAL_TIME_ALERTS)const realTimeAlertsEnabled = useFeatureFlag('ALERTS_REAL_TIME_INTERVAL')@@ -89,12 +92,21 @@ export function AlertIntervalRow({)}- let nextEvaluation: JSX.Element | null = null- if (!creatingNewAlert && alert) {+ let nextEvaluation: JSX.Element | null+ if (alertForm.calculation_interval === AlertCalculationInterval.REAL_TIME) {+ nextEvaluation = null+ } else if (creatingNewAlert || nextPlannedEvaluationStale) {+ const approximateTime = approximateNextAlertRun(alertForm.calculation_interval, currentTeam?.timezone ?? 'UTC')+ nextEvaluation = (+ <AlertNextEvaluationStatus>+ <span>+ Approximately <TZLabel time={approximateTime} />+ </span>+ </AlertNextEvaluationStatus>+ )+ } else if (alert) {let status: JSX.Element- if (nextPlannedEvaluationStale) {- status = <span>We'll recalculate this after you save.</span>- } else if (alert.next_check_at) {+ if (alert.next_check_at) {status = <TZLabel time={alert.next_check_at} />} else {status = <span>We're calculating this. This can take a few minutes.</span>@@ -104,6 +116,8 @@ export function AlertIntervalRow({{status}</AlertNextEvaluationStatus>)+ } else {+ nextEvaluation = null}const scheduleLabel =diff --git a/products/alerts/frontend/components/AlertNotificationDestinationEditor.test.tsx b/products/alerts/frontend/components/AlertNotificationDestinationEditor.test.tsxnew file mode 100644index 000000000000..d8367a3a7cb4--- /dev/null+++ b/products/alerts/frontend/components/AlertNotificationDestinationEditor.test.tsx@@ -0,0 +1,126 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { KeyboardEvent, ReactNode } from 'react'++import { AlertNotificationDestinationEditor } from './AlertNotificationDestinationEditor'++jest.mock('@posthog/lemon-ui', () => ({+ LemonButton: ({ children }: { children: ReactNode }) => <button>{children}</button>,+ LemonBanner: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ LemonInput: ({+ onPressEnter,+ placeholder,+ }: {+ onPressEnter?: (event: KeyboardEvent<HTMLInputElement>) => void+ placeholder?: string+ }) => (+ <input+ placeholder={placeholder}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ onPressEnter?.(event)+ }+ }}+ />+ ),+ LemonSelect: () => <select />,+ LemonSkeleton: () => <div>Loading integrations</div>,+ LemonTag: ({ children }: { children: ReactNode }) => <span>{children}</span>,+}))++jest.mock('lib/integrations/SlackIntegrationHelpers', () => ({+ SlackChannelPicker: () => <div>Slack channel picker</div>,+ SlackNotConfiguredBanner: () => <div>Slack is not yet configured for this project.</div>,+}))++describe('AlertNotificationDestinationEditor', () => {+ it('waits for integrations to load before showing Slack as not configured', () => {+ const props = {+ destinations: {+ showExisting: false,+ existingLoading: false,+ existing: [],+ pending: [],+ },+ notificationType: {+ options: [{ label: 'Slack', value: 'slack' }],+ value: 'slack',+ onChange: jest.fn(),+ },+ slack: {+ notificationType: 'slack',+ integrationsLoading: false,+ integrationsFailed: false,+ onRetryIntegrations: jest.fn(),+ channelValue: null,+ onChannelValueChange: jest.fn(),+ },+ add: { onClick: jest.fn() },+ }++ const { rerender } = render(<AlertNotificationDestinationEditor {...props} />)++ expect(screen.queryByText(/Slack is not yet configured/)).toBeNull()++ rerender(<AlertNotificationDestinationEditor {...props} slack={{ ...props.slack, integrations: [] }} />)++ expect(screen.getByText(/Slack is not yet configured/)).toBeTruthy()++ rerender(+ <AlertNotificationDestinationEditor+ {...props}+ slack={{ ...props.slack, integrations: [], integrationsFailed: true }}+ />+ )++ expect(screen.getByText("Couldn't load Slack workspaces.")).toBeTruthy()+ expect(screen.queryByText(/Slack is not yet configured/)).toBeNull()++ rerender(+ <AlertNotificationDestinationEditor+ {...props}+ slack={{ ...props.slack, integrationsLoading: true, integrationsFailed: true }}+ />+ )++ expect(screen.getByText('Loading integrations')).toBeTruthy()+ expect(screen.queryByText("Couldn't load Slack workspaces.")).toBeNull()+ })++ it('adds a valid URL on Enter without bubbling to the wizard', () => {+ const onAdd = jest.fn()+ const onWizardKeyDown = jest.fn()+ render(+ <div onKeyDown={onWizardKeyDown}>+ <AlertNotificationDestinationEditor+ destinations={{ showExisting: false, existingLoading: false, existing: [], pending: [] }}+ notificationType={{ options: [], value: 'webhook', onChange: jest.fn() }}+ slack={{+ notificationType: 'slack',+ integrationsLoading: false,+ integrationsFailed: false,+ onRetryIntegrations: jest.fn(),+ integrations: [],+ channelValue: null,+ onChannelValueChange: jest.fn(),+ }}+ url={{+ input: { placeholder: 'https://example.com/webhook' },+ value: 'https://example.com/destination',+ onChange: jest.fn(),+ }}+ add={{ onClick: onAdd }}+ />+ </div>+ )++ const input = screen.getByPlaceholderText('https://example.com/webhook')+ fireEvent.keyDown(input, { key: 'Enter', isComposing: true })+ expect(onAdd).not.toHaveBeenCalled()+ expect(onWizardKeyDown).not.toHaveBeenCalled()++ fireEvent.keyDown(input, { key: 'Enter' })++ expect(onAdd).toHaveBeenCalledTimes(1)+ expect(onWizardKeyDown).not.toHaveBeenCalled()+ })+})diff --git a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsxindex d51c542b6a45..ecb7e4715c89 100644--- a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx+++ b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx@@ -3,6 +3,7 @@ import { ReactNode } from 'react'import { IconExternal, IconTrash } from '@posthog/icons'import {LemonButton,+ LemonBanner,LemonInput,LemonSelect,LemonSelectOptions,@@ -42,8 +43,8 @@ export interface AlertNotificationDestinationView {export interface PendingAlertNotificationDestinationView {key: string- label: string- status: string+ title: ReactNode+ detail?: ReactNodeonRemove: () => void}@@ -67,6 +68,9 @@ interface AlertNotificationDestinationEditorProps<NotificationType extends strin}slack: {notificationType: NotificationType+ integrationsLoading: boolean+ integrationsFailed: boolean+ onRetryIntegrations: () => voidintegrations?: IntegrationType[]integration?: IntegrationTypeonIntegrationChange?: (integrationId: number | null) => void@@ -185,10 +189,17 @@ function PendingDestinations({<div className="space-y-2">{destinations.map((destination) => (<div key={destination.key} className="flex items-center justify-between border rounded p-2 gap-2">- <span className="text-sm min-w-0 truncate flex flex-col">- {destination.label}- <span className="text-muted-alt">{destination.status}</span>- </span>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-sm font-medium truncate">{destination.title}</span>+ <LemonTag type="warning" size="small">+ Pending+ </LemonTag>+ </div>+ {destination.detail ? (+ <span className="text-xs text-muted-alt truncate block">{destination.detail}</span>+ ) : null}+ </div><LemonButtonicon={<IconTrash />}size="xsmall"@@ -210,9 +221,36 @@ export function AlertNotificationDestinationEditor<NotificationType extends striurl,add,}: AlertNotificationDestinationEditorProps<NotificationType>): JSX.Element {+ const addDestinationButton = (+ <LemonButton+ type="primary"+ size="small"+ onClick={add.onClick}+ disabledReason={add.disabledReason}+ className="shrink-0"+ >+ Add+ </LemonButton>+ )+ const addDestinationButtonIsInline = notificationType.value === slack.notificationType || Boolean(url)+let slackDestinationInput: JSX.Element | null = nullif (notificationType.value === slack.notificationType) {- if (slack.integration) {+ if (slack.integrationsLoading || slack.integrations === undefined) {+ slackDestinationInput = <LemonSkeleton className="h-10" />+ } else if (slack.integrationsFailed) {+ slackDestinationInput = (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: slack.onRetryIntegrations,+ }}+ >+ Couldn't load Slack workspaces.+ </LemonBanner>+ )+ } else if (slack.integration) {slackDestinationInput = (<div className="space-y-3">{(slack.integrations?.length ?? 0) > 1 ? (@@ -232,21 +270,30 @@ export function AlertNotificationDestinationEditor<NotificationType extends stri) : null}<fieldset className="space-y-1"><legend className="text-sm font-medium">Channel</legend>- <SlackChannelPicker- value={slack.channelValue ?? undefined}- onChange={slack.onChannelValueChange}- integration={slack.integration}- />+ <div className="flex flex-col sm:flex-row items-start gap-2">+ <div className="flex-1 min-w-0 w-full">+ <SlackChannelPicker+ value={slack.channelValue ?? undefined}+ onChange={slack.onChannelValueChange}+ integration={slack.integration}+ />+ </div>+ {addDestinationButton}+ </div></fieldset></div>)} else {- slackDestinationInput = <SlackNotConfiguredBanner />+ slackDestinationInput = <SlackNotConfiguredBanner type="warning" className="max-w-4xl" />}}+ const hasDestinations =+ (destinations.showExisting && (destinations.existingLoading || destinations.existing.length > 0)) ||+ destinations.pending.length > 0+return (- <div className="space-y-4">+ <div className="flex flex-col gap-4" data-prevent-wizard-submit>{description ? <p className="text-xs text-muted-alt m-0">{description}</p> : null}{destinations.showExisting ? (@@ -255,7 +302,9 @@ export function AlertNotificationDestinationEditor<NotificationType extends stri<PendingDestinations destinations={destinations.pending} />- <div className="space-y-3 border rounded p-3">+ {hasDestinations ? <hr className="border-border m-0" /> : null}++ <div className="space-y-3 max-w-xl"><LemonSelectfullWidthoptions={notificationType.options}@@ -267,19 +316,31 @@ export function AlertNotificationDestinationEditor<NotificationType extends stri{url ? (<div className="space-y-1">- <LemonInput- placeholder={url.input.placeholder}- value={url.value}- onChange={url.onChange}- fullWidth- />+ <div className="flex flex-col sm:flex-row items-start gap-2">+ <LemonInput+ placeholder={url.input.placeholder}+ value={url.value}+ onChange={url.onChange}+ onPressEnter={(event) => {+ if (event.nativeEvent.isComposing) {+ event.stopPropagation()+ return+ }+ event.preventDefault()+ event.stopPropagation()+ if (!add.disabledReason) {+ add.onClick()+ }+ }}+ fullWidth+ />+ {addDestinationButton}+ </div>{url.input.helpText ? <p className="text-xs text-muted-alt m-0">{url.input.helpText}</p> : null}</div>) : null}- <LemonButton type="secondary" size="small" onClick={add.onClick} disabledReason={add.disabledReason}>- Add notification- </LemonButton>+ {!addDestinationButtonIsInline ? addDestinationButton : null}</div></div>)diff --git a/products/alerts/frontend/components/AlertWizard.tsx b/products/alerts/frontend/components/AlertWizard.tsxindex b9bba8574ee2..a7bf2ecbc7de 100644--- a/products/alerts/frontend/components/AlertWizard.tsx+++ b/products/alerts/frontend/components/AlertWizard.tsx@@ -91,6 +91,9 @@ export function AlertWizard({event.target instanceof HTMLInputElement) {event.preventDefault()+ if (event.target.closest('[data-prevent-wizard-submit]')) {+ return+ }goNext()}}}@@ -120,6 +123,7 @@ export function AlertWizard({}}className={cn('flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-accent',+ canAccess && 'cursor-pointer',!canAccess && 'opacity-40 cursor-not-allowed',isCurrent? 'bg-accent text-white font-semibold'@@ -174,7 +178,7 @@ export function AlertWizard({Close</LemonButton>) : (- <LemonButton type="secondary" icon={<IconChevronLeft />} onClick={goPrev}>+ <LemonButton type="secondary" icon={<IconChevronLeft className="size-4" />} onClick={goPrev}>Back</LemonButton>)}diff --git a/products/alerts/frontend/logic/alertFormLogic.test.ts b/products/alerts/frontend/logic/alertFormLogic.test.tsindex 508a3cfbfe19..9461559bf077 100644--- a/products/alerts/frontend/logic/alertFormLogic.test.ts+++ b/products/alerts/frontend/logic/alertFormLogic.test.ts@@ -349,6 +349,10 @@ describe('alertFormLogic', () => {})expect(thresholdAlertHasBounds(logic.values.alertForm)).toBe(false)+ expect(logic.values.alertFormValidationErrors.threshold).toBe(+ 'Enter at least one threshold (less than or more than)'+ )+ expect(logic.values.thresholdBoundsFormError).toBeUndefined()logic.actions.setAlertFormSubmitAttempted()diff --git a/products/alerts/frontend/logic/alertNotificationLogic.test.ts b/products/alerts/frontend/logic/alertNotificationLogic.test.tsindex 801c06b97bb9..36207d4a2f34 100644--- a/products/alerts/frontend/logic/alertNotificationLogic.test.ts+++ b/products/alerts/frontend/logic/alertNotificationLogic.test.ts@@ -1,6 +1,7 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { initKeaTests } from '~/test/init'import { HogFunctionType, IntegrationType } from '~/types'@@ -63,6 +64,36 @@ describe('alertNotificationLogic', () => {await expectLogic(logic).toMatchValues({ slackChannelValue: null })})+ it('selects a Slack workspace that loaded before the alert logic mounted', async () => {+ const workspace = makeSlackIntegration(1)+ const integrationsListSpy = jest.spyOn(api.integrations, 'list').mockReturnValue(new Promise(() => {}))+ const unmountIntegrations = integrationsLogic.mount()+ integrationsLogic.actions.loadIntegrationsSuccess([workspace])+ await expectLogic(integrationsLogic).toMatchValues({ slackIntegrations: [workspace] })++ logic = alertNotificationLogic({ alertId: 'alert-123' })+ logic.mount()++ await expectLogic(logic).toMatchValues({ selectedSlackIntegration: workspace })++ unmountIntegrations()+ integrationsListSpy.mockRestore()+ })++ it('tracks integration loading failures until a retry succeeds', async () => {+ logic = alertNotificationLogic({ alertId: 'alert-123' })+ logic.mount()++ logic.actions.loadIntegrationsFailure('Network error')+ await expectLogic(logic).toMatchValues({ integrationsFailed: true })++ logic.actions.loadIntegrations()+ await expectLogic(logic).toMatchValues({ integrationsFailed: false })++ logic.actions.loadIntegrationsSuccess([])+ await expectLogic(logic).toMatchValues({ integrationsFailed: false })+ })+it('clears the channel when an integrations refresh removes the selected workspace', async () => {logic = alertNotificationLogic({ alertId: 'alert-123' })logic.mount()diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.tsindex f0afc807c950..a2e9b54d441c 100644--- a/products/alerts/frontend/logic/alertNotificationLogic.ts+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts@@ -37,10 +37,12 @@ export interface AlertNotificationLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface alertNotificationLogicValues {+ integrationsLoading: boolean // integrationsLogicslackIntegrations: IntegrationType[] | undefined // integrationsLogiccurrentProjectId: number | null // projectLogicexistingHogFunctions: HogFunctionType[]existingHogFunctionsLoading: boolean+ integrationsFailed: booleanpendingNotifications: PendingAlertNotification[]selectedSlackIntegration: IntegrationType | undefinedselectedSlackIntegrationId: number | null@@ -51,6 +53,14 @@ export interface alertNotificationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface alertNotificationLogicActions {+ loadIntegrations: () => any // integrationsLogic+ loadIntegrationsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ } // integrationsLogicloadIntegrationsSuccess: (integrations: {config: any@@ -227,8 +237,8 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([key(({ alertId }) => alertId ?? 'new'),connect({- values: [projectLogic, ['currentProjectId'], integrationsLogic, ['slackIntegrations']],- actions: [integrationsLogic, ['loadIntegrationsSuccess']],+ values: [projectLogic, ['currentProjectId'], integrationsLogic, ['integrationsLoading', 'slackIntegrations']],+ actions: [integrationsLogic, ['loadIntegrations', 'loadIntegrationsFailure', 'loadIntegrationsSuccess']],}),actions({@@ -256,6 +266,14 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([setPendingNotifications: (_, { notifications }) => notifications,},],+ integrationsFailed: [+ false,+ {+ loadIntegrations: () => false,+ loadIntegrationsFailure: () => true,+ loadIntegrationsSuccess: () => false,+ },+ ],slackChannelValue: [null as string | null,{@@ -300,7 +318,8 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([slackIntegrations: IntegrationType[] | undefined,selectedSlackIntegrationId: number | null): IntegrationType | undefined =>- slackIntegrations?.find((integration) => integration.id === selectedSlackIntegrationId),+ slackIntegrations?.find((integration) => integration.id === selectedSlackIntegrationId) ??+ slackIntegrations?.[0],],}),diff --git a/products/alerts/frontend/logic/alertNotifications.test.ts b/products/alerts/frontend/logic/alertNotifications.test.tsindex a0b3d8d1d4f0..6777d482cf8e 100644--- a/products/alerts/frontend/logic/alertNotifications.test.ts+++ b/products/alerts/frontend/logic/alertNotifications.test.ts@@ -4,10 +4,27 @@ import {PendingAlertNotification,buildAlertFilterConfig,buildHogFunctionPayload,+ getAlertNotificationAddDisabledReason,notificationTypeFromTemplateId,} from './alertNotifications'describe('alertUtils', () => {+ describe('getAlertNotificationAddDisabledReason', () => {+ it.each([+ ['webhook', 'Enter a valid webhook URL'],+ ['discord', 'Enter a valid Discord webhook URL'],+ ['microsoft_teams', 'Enter a valid Microsoft Teams workflow URL'],+ ] as const)('rejects an invalid %s URL', (selectedType, expectedReason) => {+ expect(getAlertNotificationAddDisabledReason(selectedType, false, null, 'not a url')).toBe(expectedReason)+ })++ it('accepts a valid webhook URL', () => {+ expect(+ getAlertNotificationAddDisabledReason('webhook', false, null, 'https://example.com/webhook')+ ).toBeUndefined()+ })+ })+describe('buildAlertFilterConfig', () => {it('builds filter config with the correct event and alert_id property', () => {const result = buildAlertFilterConfig('alert-123')diff --git a/products/alerts/frontend/logic/alertNotifications.ts b/products/alerts/frontend/logic/alertNotifications.tsindex dca9b76d889b..bf9429c9eba5 100644--- a/products/alerts/frontend/logic/alertNotifications.ts+++ b/products/alerts/frontend/logic/alertNotifications.ts@@ -1,3 +1,5 @@+import { z } from 'zod'+import { INSIGHT_ALERT_FIRING_EVENT_ID, INSIGHT_ALERT_FIRING_SUB_TEMPLATE_ID } from 'lib/constants'import {HOG_FUNCTION_SUB_TEMPLATES,@@ -16,6 +18,47 @@ export type AlertNotificationType =| typeof ALERT_NOTIFICATION_TYPE_DISCORD| typeof ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS+const webhookUrlSchema = z.string().url()++export function getAlertNotificationAddDisabledReason(+ selectedType: AlertNotificationType,+ hasSlackIntegration: boolean,+ slackChannelValue: string | null,+ webhookUrl: string+): string | undefined {+ if (selectedType === ALERT_NOTIFICATION_TYPE_SLACK) {+ if (!hasSlackIntegration) {+ return 'Connect Slack first'+ }+ if (!slackChannelValue) {+ return 'Select a Slack channel'+ }+ return undefined+ }++ if (!webhookUrl) {+ if (selectedType === ALERT_NOTIFICATION_TYPE_DISCORD) {+ return 'Enter a Discord webhook URL'+ }+ if (selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) {+ return 'Enter a Microsoft Teams workflow URL'+ }+ return 'Enter a webhook URL'+ }++ if (!webhookUrlSchema.safeParse(webhookUrl).success) {+ if (selectedType === ALERT_NOTIFICATION_TYPE_DISCORD) {+ return 'Enter a valid Discord webhook URL'+ }+ if (selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) {+ return 'Enter a valid Microsoft Teams workflow URL'+ }+ return 'Enter a valid webhook URL'+ }++ return undefined+}+// Single source of truth for which destination HogFunction template each notification type uses.// buildAlertDestination reads it when creating a destination; notificationTypeFromTemplateId inverts// it to label an existing one. Keeping both directions off one map avoids the two drifting apart.diff --git a/products/alerts/frontend/logic/alertSchedulingStale.test.ts b/products/alerts/frontend/logic/alertSchedulingStale.test.tsindex d93e085fed81..526d57696e89 100644--- a/products/alerts/frontend/logic/alertSchedulingStale.test.ts+++ b/products/alerts/frontend/logic/alertSchedulingStale.test.ts@@ -1,12 +1,30 @@+import { dayjs } from 'lib/dayjs'+import { AlertCalculationInterval } from '~/queries/schema/schema-general'import {+ approximateNextAlertRun,isNextPlannedEvaluationStale,normalizeScheduleRestrictionForCompare,type SchedulingSnapshot,} from './alertSchedulingStale'describe('alertSchedulingStale', () => {+ describe('approximateNextAlertRun', () => {+ it.each([+ [AlertCalculationInterval.REAL_TIME, '2026-07-24T16:02:00.000Z'],+ [AlertCalculationInterval.EVERY_15_MINUTES, '2026-07-24T16:15:00.000Z'],+ [AlertCalculationInterval.HOURLY, '2026-07-24T17:00:00.000Z'],+ [AlertCalculationInterval.DAILY, '2026-07-25T05:00:00.000Z'],+ [AlertCalculationInterval.WEEKLY, '2026-07-27T07:00:00.000Z'],+ [AlertCalculationInterval.MONTHLY, '2026-08-01T08:00:00.000Z'],+ ])('matches the backend anchor for %s', (interval, expected) => {+ const now = dayjs.utc('2026-07-24T16:00:00.000Z')++ expect(approximateNextAlertRun(interval, 'America/Toronto', now).toISOString()).toBe(expected)+ })+ })+describe('normalizeScheduleRestrictionForCompare', () => {it('maps missing, null, and empty windows to null', () => {expect(normalizeScheduleRestrictionForCompare(undefined)).toBeNull()diff --git a/products/alerts/frontend/logic/alertSchedulingStale.ts b/products/alerts/frontend/logic/alertSchedulingStale.tsindex eaa036347526..f60178dfd601 100644--- a/products/alerts/frontend/logic/alertSchedulingStale.ts+++ b/products/alerts/frontend/logic/alertSchedulingStale.ts@@ -1,9 +1,46 @@import { deepEqual as equal } from 'fast-equals'+import { Dayjs, dayjs } from 'lib/dayjs'+import { AlertCalculationInterval } from '~/queries/schema/schema-general'import type { ScheduleRestriction } from '../types'+function calendarAnchor(localDate: Dayjs, hour: number, timezone: string): Dayjs {+ return dayjs.tz(`${localDate.format('YYYY-MM-DD')} ${hour}:00`, 'YYYY-MM-DD H:mm', timezone)+}++export function approximateNextAlertRun(+ interval: AlertCalculationInterval,+ timezone: string,+ now: Dayjs = dayjs()+): Dayjs {+ let localNow: Dayjs+ try {+ localNow = now.tz(timezone)+ } catch {+ timezone = 'UTC'+ localNow = now.utc()+ }++ switch (interval) {+ case AlertCalculationInterval.REAL_TIME:+ return localNow.add(2, 'minutes')+ case AlertCalculationInterval.EVERY_15_MINUTES:+ return localNow.add(15, 'minutes')+ case AlertCalculationInterval.HOURLY:+ return localNow.add(1, 'hour')+ case AlertCalculationInterval.DAILY:+ return calendarAnchor(localNow.add(1, 'day'), 1, timezone)+ case AlertCalculationInterval.WEEKLY: {+ const daysUntilMonday = localNow.day() === 0 ? 1 : 8 - localNow.day()+ return calendarAnchor(localNow.add(daysUntilMonday, 'days'), 3, timezone)+ }+ case AlertCalculationInterval.MONTHLY:+ return calendarAnchor(localNow.add(1, 'month').startOf('month'), 4, timezone)+ }+}+export function normalizeScheduleRestrictionForCompare(sr: ScheduleRestriction | null | undefined): ScheduleRestriction | null {diff --git a/products/alerts/frontend/logic/insightAlertsLogic.test.ts b/products/alerts/frontend/logic/insightAlertsLogic.test.tsindex f83fa3ab587e..9f6ef1b65a93 100644--- a/products/alerts/frontend/logic/insightAlertsLogic.test.ts+++ b/products/alerts/frontend/logic/insightAlertsLogic.test.ts@@ -7,7 +7,7 @@ import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { ChartDisplayType, InsightLogicProps, InsightShortId } from '~/types'+import { ChartDisplayType, HogFunctionType, InsightLogicProps, InsightShortId } from '~/types'import type { AlertType } from '../types'import {@@ -44,14 +44,17 @@ const METRICS_QUERY = {describe('insightAlertsLogic', () => {let listSpy: jest.SpyInstance+ let hogFunctionsListSpy: jest.SpyInstancebeforeEach(() => {initKeaTests()listSpy = jest.spyOn(api.alerts, 'list').mockResolvedValue({ results: [], count: 0 })+ hogFunctionsListSpy = jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({ results: [], count: 0 })})afterEach(() => {listSpy.mockRestore()+ hogFunctionsListSpy.mockRestore()})function mountInsightStack(insightLogicProps: InsightLogicProps): void {@@ -218,6 +221,53 @@ describe('insightAlertsLogic', () => {alerts: [expect.objectContaining({ id: 'keep' })],})})++ it('loads destination counts for all alerts in one request', async () => {+ const insightLogicProps: InsightLogicProps = {+ dashboardItemId: Insight42,+ dashboardId: 1,+ cachedInsight: { ...createEmptyInsight(Insight42), id: 42, query: API_QUERY, alerts: [] },+ }+ mountInsightStack(insightLogicProps)+ hogFunctionsListSpy.mockResolvedValue({+ count: 3,+ results: [+ { filters: { properties: [{ key: 'alert_id', value: 'alert-a' }] } },+ { filters: { properties: [{ key: 'alert_id', value: 'alert-a' }] } },+ { filters: { properties: [{ key: 'alert_id', value: 'alert-b' }] } },+ ] as HogFunctionType[],+ })+ const alertsLogic = insightAlertsLogic({ insightId: 42, insightLogicProps, deferInitialAlertsLoad: true })+ alertsLogic.mount()+ const alerts = [{ id: 'alert-a' }, { id: 'alert-b' }] as AlertType[]++ await expectLogic(alertsLogic, () => alertsLogic.actions.loadAlertsSuccess(alerts))+ .toFinishAllListeners()+ .toMatchValues({ alertDestinationCounts: { 'alert-a': 2, 'alert-b': 1 } })++ expect(hogFunctionsListSpy).toHaveBeenCalledTimes(1)+ })++ it('refreshes destination counts after an alert is saved', async () => {+ const insightLogicProps: InsightLogicProps = {+ dashboardItemId: Insight42,+ dashboardId: 1,+ cachedInsight: { ...createEmptyInsight(Insight42), id: 42, query: API_QUERY, alerts: [] },+ }+ mountInsightStack(insightLogicProps)+ hogFunctionsListSpy.mockResolvedValue({+ count: 1,+ results: [{ filters: { properties: [{ key: 'alert_id', value: 'alert-a' }] } }] as HogFunctionType[],+ })+ const alertsLogic = insightAlertsLogic({ insightId: 42, insightLogicProps, deferInitialAlertsLoad: true })+ alertsLogic.mount()++ await expectLogic(alertsLogic, () => alertsLogic.actions.upsertAlert({ id: 'alert-a' } as AlertType))+ .toFinishAllListeners()+ .toMatchValues({ alertDestinationCounts: { 'alert-a': 1 } })++ expect(hogFunctionsListSpy).toHaveBeenCalledTimes(1)+ })})describe('areAlertsSupportedForInsight', () => {diff --git a/products/alerts/frontend/logic/insightAlertsLogic.ts b/products/alerts/frontend/logic/insightAlertsLogic.tsindex 63c8843dcd9f..9779e3be762a 100644--- a/products/alerts/frontend/logic/insightAlertsLogic.ts+++ b/products/alerts/frontend/logic/insightAlertsLogic.ts@@ -20,6 +20,7 @@ import { FunnelVizType, InsightLogicProps } from '~/types'import type { Node } from '../../../../frontend/src/queries/schema/schema-general'import type { QueryBasedInsightModel } from '../../../../frontend/src/types'import { AlertType, AnomalyPoint, isTrendsAlertConfig } from '../types'+import { buildAlertFilterConfig } from './alertNotifications'export interface InsightAlertsLogicProps {insightId: number@@ -132,6 +133,8 @@ export interface insightAlertsLogicValues {breakdownFilter: BreakdownFilter | null | undefined // insightVizDataLogicshowAlertThresholdLines: boolean | null | undefined // insightVizDataLogicalertAnomalyPoints: AnomalyPoint[]+ alertDestinationCounts: Record<string, number>+ alertDestinationCountsLoading: booleanalertThresholdLines: GoalLine[]alerts: AlertType[]alertsLoading: boolean@@ -149,6 +152,21 @@ export interface insightAlertsLogicActions {clearSimulationAnomalyPoints: () => {value: true}+ loadAlertDestinationCounts: (alerts: AlertType[]) => AlertType[]+ loadAlertDestinationCountsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAlertDestinationCountsSuccess: (+ alertDestinationCounts: Record<string, number>,+ payload?: AlertType[]+ ) => {+ alertDestinationCounts: Record<string, number>+ payload?: AlertType[]+ }loadAlerts: () => anyloadAlertsFailure: (error: string,@@ -234,6 +252,33 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([return response.results},},+ alertDestinationCounts: [+ {} as Record<string, number>,+ {+ loadAlertDestinationCounts: async (alerts: AlertType[]) => {+ if (alerts.length === 0) {+ return {}+ }+ const alertIds = new Set(alerts.map((alert) => alert.id))+ const response = await api.hogFunctions.list({+ types: ['internal_destination'],+ filter_groups: alerts.map((alert) => buildAlertFilterConfig(alert.id)),+ full: true,+ limit: 500,+ })+ return response.results.reduce<Record<string, number>>((counts, hogFunction) => {+ const alertIdProperty = hogFunction.filters?.properties?.find(+ (property) => property.key === 'alert_id'+ )+ const alertId = alertIdProperty?.value+ if (typeof alertId === 'string' && alertIds.has(alertId)) {+ counts[alertId] = (counts[alertId] ?? 0) + 1+ }+ return counts+ }, {})+ },+ },+ ],})),reducers({@@ -349,6 +394,12 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([}),listeners(({ actions, values }) => ({+ loadAlertsSuccess: ({ alerts }) => {+ actions.loadAlertDestinationCounts(alerts)+ },+ upsertAlert: () => {+ actions.loadAlertDestinationCounts(values.alerts)+ },setQuery: ({ query }) => {if (values.alerts.length === 0 || areAlertsSupportedForInsight(query)) {actions.setShouldShowAlertDeletionWarning(false)diff --git a/products/alerts/frontend/views/EditAlertModalV2.tsx b/products/alerts/frontend/views/EditAlertModalV2.tsxindex 7a99d288efe4..c67e87856cb2 100644--- a/products/alerts/frontend/views/EditAlertModalV2.tsx+++ b/products/alerts/frontend/views/EditAlertModalV2.tsx@@ -115,6 +115,7 @@ export function EditAlertModalV2({isAlertFormSubmitting,alertFormChanged,alertFormHasErrors,+ alertFormValidationErrors,alertFormSubmitAttempted,simulationResult,simulationResultLoading,@@ -266,6 +267,9 @@ export function EditAlertModalV2({/>)+ const thresholdValidationError =+ typeof alertFormValidationErrors.threshold === 'string' ? alertFormValidationErrors.threshold : undefined+const definitionNode = (<AlertDefinitionSectionalertForm={alertForm}@@ -384,7 +388,7 @@ export function EditAlertModalV2({notifyNode,advancedNode,summary,- thresholdBoundsFormError,+ thresholdValidationError,scheduleRestrictionFormError,alertFormHasErrors,alertName: alertForm.name,diff --git a/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.test.tsx b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.test.tsxindex cb3205f49e60..9ed486d93766 100644--- a/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.test.tsx+++ b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.test.tsx@@ -1,6 +1,12 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { AlertWizard } from 'products/alerts/frontend/components/AlertWizard'+import { buildWizardSteps } from './buildWizardSteps'describe('buildWizardSteps', () => {+ afterEach(cleanup)+const baseInput = {nameNode: null,definitionNode: null,@@ -15,7 +21,7 @@ describe('buildWizardSteps', () => {it.each([['missing name', { alertName: '' }, 'monitor', 'Enter an alert name.'],- ['invalid threshold', { thresholdBoundsFormError: 'Enter a threshold' }, 'monitor', 'Enter a threshold'],+ ['invalid threshold', { thresholdValidationError: 'Enter a threshold' }, 'monitor', 'Enter a threshold'],['invalid schedule',{ alertFormHasErrors: true, scheduleRestrictionFormError: 'Choose an end time' },@@ -28,4 +34,62 @@ describe('buildWizardSteps', () => {expect(step).toMatchObject({ canAdvance: false, cannotAdvanceReason: expectedReason })})++ it('keeps the user on Monitor when its threshold is invalid', () => {+ const onSubmitAttempted = jest.fn()+ const steps = buildWizardSteps({+ ...baseInput,+ thresholdValidationError: 'Enter at least one threshold (less than or more than)',+ })+ render(+ <AlertWizard+ title="New alert"+ steps={steps}+ isSubmitting={false}+ hasChanges+ onBack={jest.fn()}+ onSubmitAttempted={onSubmitAttempted}+ />+ )++ const scheduleStep = screen.getByText('Schedule').closest('button')+ expect((scheduleStep as HTMLButtonElement).disabled).toBe(true)+ fireEvent.click(scheduleStep as HTMLButtonElement)+ expect(screen.getByText('Pick what this alert watches and when it should fire.')).toBeTruthy()++ fireEvent.click(screen.getByText('Continue'))+ expect(onSubmitAttempted).toHaveBeenCalledTimes(1)+ expect(screen.getByText('Enter at least one threshold (less than or more than)')).toBeTruthy()+ expect(screen.getByText('Pick what this alert watches and when it should fire.')).toBeTruthy()+ })++ it('does not advance when Enter is used inside a nested picker', () => {+ const steps = buildWizardSteps({+ ...baseInput,+ notifyNode: (+ <div data-prevent-wizard-submit>+ <input aria-label="Notification recipient" />+ </div>+ ),+ })+ render(+ <AlertWizard+ title="New alert"+ steps={steps}+ isSubmitting={false}+ hasChanges+ onBack={jest.fn()}+ onSubmitAttempted={jest.fn()}+ />+ )+ fireEvent.click(screen.getByText('Notify'))++ const eventWasNotCancelled = fireEvent.keyDown(screen.getByLabelText('Notification recipient'), {+ key: 'Enter',+ })++ expect(eventWasNotCancelled).toBe(false)+ expect(screen.getByText('Who gets told when this alert fires.')).toBeTruthy()+ expect(screen.queryByText('Confirm what this alert will do, then create it.')).toBeNull()+ })})diff --git a/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.tsx b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.tsxindex 148f9d946829..5ca6be7bc442 100644--- a/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.tsx+++ b/products/alerts/frontend/views/EditAlertModalV2/buildWizardSteps.tsx@@ -10,7 +10,7 @@ interface WizardStepInput {notifyNode: ReactNodeadvancedNode: ReactNodesummary: { fires: string; cadence: string; notifies: string }- thresholdBoundsFormError?: string+ thresholdValidationError?: stringscheduleRestrictionFormError?: stringalertFormHasErrors: booleanalertName: string@@ -21,7 +21,7 @@ export function buildWizardSteps(input: WizardStepInput): AlertWizardStep[] {const reviewFires = summary.fires || 'a configured threshold'const reviewCadence = summary.cadence || 'a cadence'const reviewNotifies = summary.notifies || 'no one yet'- const monitorCannotAdvanceReason = !input.alertName ? 'Enter an alert name.' : input.thresholdBoundsFormError+ const monitorCannotAdvanceReason = !input.alertName ? 'Enter an alert name.' : input.thresholdValidationErrorconst monitorCanAdvance = !monitorCannotAdvanceReasonreturn [diff --git a/products/alerts/frontend/views/InlineAlertNotifications.tsx b/products/alerts/frontend/views/InlineAlertNotifications.tsxindex 924d94b5621c..d2b7f4c72263 100644--- a/products/alerts/frontend/views/InlineAlertNotifications.tsx+++ b/products/alerts/frontend/views/InlineAlertNotifications.tsx@@ -19,6 +19,7 @@ import {ALERT_NOTIFICATION_TYPE_WEBHOOK,AlertNotificationType,PendingAlertNotification,+ getAlertNotificationAddDisabledReason,} from 'products/alerts/frontend/logic/alertNotifications'import { ALERT_NOTIFICATION_TYPE_OPTIONS, alertNotificationLogic } from '../logic/alertNotificationLogic'@@ -90,23 +91,26 @@ function getHogFunctionDestination(return { type: hogFunction.name, detail: null }}-function getNotificationLabel(+function getPendingNotificationDestination(notification: PendingAlertNotification,slackIntegrations: IntegrationType[] | undefined-): string {+): Pick<PendingAlertNotificationDestinationView, 'title' | 'detail'> {switch (notification.type) {case ALERT_NOTIFICATION_TYPE_SLACK: {const workspaceName = slackIntegrations?.find((integration) => integration.id === notification.slackWorkspaceId)?.display_name- return `Slack: ${workspaceName ?? 'Unknown workspace'} · #${notification.slackChannelName ?? 'channel'}`+ return {+ title: 'Slack',+ detail: `${workspaceName ?? 'Unknown workspace'} · #${notification.slackChannelName ?? 'channel'}`,+ }}case ALERT_NOTIFICATION_TYPE_DISCORD:- return `Discord: ${notification.webhookUrl}`+ return { title: 'Discord', detail: notification.webhookUrl }case ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS:- return `Microsoft Teams: ${notification.webhookUrl}`+ return { title: 'Microsoft Teams', detail: notification.webhookUrl }case ALERT_NOTIFICATION_TYPE_WEBHOOK:- return `Webhook: ${notification.webhookUrl}`+ return { title: 'Webhook', detail: notification.webhookUrl }default: {const exhaustiveCheck: never = notificationreturn exhaustiveCheck@@ -131,33 +135,6 @@ function getUrlInput(type: AlertNotificationType): AlertNotificationUrlInput | u}}-function getAddDisabledReason(- selectedType: AlertNotificationType,- hasSlackIntegration: boolean,- slackChannelValue: string | null,- webhookUrl: string-): string | undefined {- if (selectedType === ALERT_NOTIFICATION_TYPE_SLACK) {- if (!hasSlackIntegration) {- return 'Connect Slack first'- }- if (!slackChannelValue) {- return 'Select a Slack channel'- }- return undefined- }- if (webhookUrl) {- return undefined- }- if (selectedType === ALERT_NOTIFICATION_TYPE_DISCORD) {- return 'Enter a Discord webhook URL'- }- if (selectedType === ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS) {- return 'Enter a Microsoft Teams workflow URL'- }- return 'Enter a webhook URL'-}-interface InlineAlertNotificationsProps {alertId?: string}@@ -168,6 +145,8 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPrexistingHogFunctions,existingHogFunctionsLoading,pendingNotifications,+ integrationsLoading,+ integrationsFailed,slackIntegrations,selectedSlackIntegration,selectedType,@@ -182,6 +161,7 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPrsetSelectedSlackIntegrationId,setSlackChannelValue,setWebhookUrl,+ loadIntegrations,} = useActions(logic)const buildPendingNotification = (): PendingAlertNotification | null => {@@ -244,8 +224,7 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPrconst pendingDestinations: PendingAlertNotificationDestinationView[] = pendingNotifications.map((notification, index) => ({key: `${notification.type}-${index}`,- label: getNotificationLabel(notification, slackIntegrations),- status: '(pending, click Save to apply)',+ ...getPendingNotificationDestination(notification, slackIntegrations),onRemove: () => removePendingNotification(index),}))@@ -267,6 +246,9 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr}}slack={{notificationType: ALERT_NOTIFICATION_TYPE_SLACK,+ integrationsLoading,+ integrationsFailed,+ onRetryIntegrations: loadIntegrations,integrations: slackIntegrations,integration: selectedSlackIntegration,onIntegrationChange: setSelectedSlackIntegrationId,@@ -276,7 +258,7 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPrurl={urlInput ? { input: urlInput, value: webhookUrl, onChange: setWebhookUrl } : undefined}add={{onClick: handleAdd,- disabledReason: getAddDisabledReason(+ disabledReason: getAlertNotificationAddDisabledReason(selectedType,Boolean(selectedSlackIntegration),slackChannelValue,diff --git a/products/alerts/frontend/views/InsightAlertNotificationSection.tsx b/products/alerts/frontend/views/InsightAlertNotificationSection.tsxindex b1723a5fb086..76aac902ca81 100644--- a/products/alerts/frontend/views/InsightAlertNotificationSection.tsx+++ b/products/alerts/frontend/views/InsightAlertNotificationSection.tsx@@ -44,7 +44,7 @@ export function InsightAlertNotificationSection({<><div className="flex gap-4 items-center"><div>E-mail</div>- <div className="flex-auto">+ <div className="flex-auto" data-prevent-wizard-submit><MemberSelectMultiplevalue={alertForm.subscribed_users?.map((user) => user.id) ?? []}idKey="id"diff --git a/products/alerts/frontend/views/ManageAlertsModal.tsx b/products/alerts/frontend/views/ManageAlertsModal.tsxindex 2abd0ee92142..760a3e379ebb 100644--- a/products/alerts/frontend/views/ManageAlertsModal.tsx+++ b/products/alerts/frontend/views/ManageAlertsModal.tsx@@ -23,6 +23,8 @@ import { AlertType } from '../types'interface AlertListItemProps {alert: AlertType+ destinationCount?: number+ destinationsLoading?: booleanonClick: () => voidredesigned: boolean}@@ -66,10 +68,18 @@ function AlertSummary({ alert }: { alert: AlertType }): JSX.Element | null {)}-export function AlertListItem({ alert, onClick, redesigned }: AlertListItemProps): JSX.Element {- const summary = buildAlertSummary(alert, alert.subscribed_users?.length ?? 0)-+export function AlertListItem({+ alert,+ destinationCount = 0,+ destinationsLoading = false,+ onClick,+ redesigned,+}: AlertListItemProps): JSX.Element {if (redesigned) {+ const summary = buildAlertSummary(alert, alert.subscribed_users?.length ?? 0, destinationCount)+ if (destinationsLoading) {+ summary.notifies = 'Loading…'+ }return (<LemonButton onClick={onClick} data-attr="alert-list-item" fullWidth><AlertSummaryBanner@@ -116,7 +126,7 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {const { push } = useActions(router)const logic = insightAlertsLogic(props)- const { alerts, alertsLoading } = useValues(logic)+ const { alerts, alertsLoading, alertDestinationCounts, alertDestinationCountsLoading } = useValues(logic)const redesigned = useFeatureFlag('ALERTS_REDESIGNED_EDIT_MODAL')const showDeferredListSpinner = props.deferInitialAlertsLoad && props.isOpen && alertsLoading@@ -168,6 +178,8 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {<AlertListItemkey={alert.id}alert={alert}+ destinationCount={alertDestinationCounts[alert.id] ?? 0}+ destinationsLoading={alertDestinationCountsLoading}onClick={() => openAlert(alert.id)}redesigned={redesigned}/>diff --git a/products/alerts/package.json b/products/alerts/package.jsonindex 86d11a745030..468bca6a08a6 100644--- a/products/alerts/package.json+++ b/products/alerts/package.json@@ -13,6 +13,7 @@},"devDependencies": {"@storybook/react": "catalog:",+ "@testing-library/react": "*","kea-test-utils": "catalog:"},"peerDependencies": {diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsxindex 958b15949217..284dd4c32f5a 100644--- a/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertNotifications.tsx@@ -19,14 +19,16 @@ import {resolveGroupLabel,} from './logsAlertUtils'-function getNotificationLabel(notification: PendingLogsAlertNotification): string {+function getPendingNotificationDestination(+ notification: PendingLogsAlertNotification+): Pick<PendingAlertNotificationDestinationView, 'title' | 'detail'> {if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_SLACK) {- return `Slack: #${notification.slackChannelName ?? 'channel'}`+ return { title: 'Slack', detail: `#${notification.slackChannelName ?? 'channel'}` }}if (notification.type === LOGS_ALERT_NOTIFICATION_TYPE_TEAMS) {- return `Microsoft Teams: ${notification.webhookUrl}`+ return { title: 'Microsoft Teams', detail: notification.webhookUrl }}- return `Webhook: ${notification.webhookUrl}`+ return { title: 'Webhook', detail: notification.webhookUrl }}export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.Element {@@ -34,6 +36,9 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.EexistingHogFunctionsLoading,destinationGroups,pendingNotifications,+ integrationsLoading,+ integrationsFailed,+ slackIntegrations,firstSlackIntegration,selectedType,slackChannelValue,@@ -48,6 +53,7 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.EsetSelectedType,setSlackChannelValue,setWebhookUrl,+ loadIntegrations,} = useActions(logsAlertNotificationLogic)const slackLogic = slackIntegrationLogic({ id: firstSlackIntegration?.id ?? 0 })@@ -85,8 +91,7 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.Econst pendingDestinations: PendingAlertNotificationDestinationView[] = pendingNotifications.map((notification, index) => ({key: `${notification.type}-${index}`,- label: getNotificationLabel(notification),- status: alertId ? '(saving...)' : '(pending, save alert to apply)',+ ...getPendingNotificationDestination(notification),onRemove: () => removePendingNotification(index),}))@@ -107,6 +112,10 @@ export function LogsAlertNotifications({ alertId }: { alertId?: string }): JSX.E}}slack={{notificationType: LOGS_ALERT_NOTIFICATION_TYPE_SLACK,+ integrationsLoading,+ integrationsFailed,+ onRetryIntegrations: loadIntegrations,+ integrations: slackIntegrations,integration: firstSlackIntegration,channelValue: slackChannelValue,onChannelValueChange: setSlackChannelValue,diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.tsindex a6a941f43e9f..68a9ea4e781c 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts@@ -35,6 +35,7 @@ export interface LogsAlertNotificationLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsAlertNotificationLogicValues {+ integrationsLoading: boolean // integrationsLogicslackIntegrations: IntegrationType[] | undefined // integrationsLogiccurrentProjectId: number | null // projectLogicaddDisabledReason: string | undefined@@ -42,6 +43,7 @@ export interface logsAlertNotificationLogicValues {existingHogFunctions: HogFunctionType[]existingHogFunctionsLoading: booleanfirstSlackIntegration: IntegrationType | undefined+ integrationsFailed: booleanpendingNotifications: PendingLogsAlertNotification[]selectedType: LogsAlertNotificationTypeslackChannelValue: string | null@@ -51,6 +53,14 @@ export interface logsAlertNotificationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsAlertNotificationLogicActions {+ loadIntegrations: () => any // integrationsLogic+ loadIntegrationsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ } // integrationsLogicloadIntegrationsSuccess: (integrations: {config: any@@ -231,8 +241,8 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([key(({ alertId }) => alertId ?? 'new'),connect({- values: [projectLogic, ['currentProjectId'], integrationsLogic, ['slackIntegrations']],- actions: [integrationsLogic, ['loadIntegrationsSuccess']],+ values: [projectLogic, ['currentProjectId'], integrationsLogic, ['integrationsLoading', 'slackIntegrations']],+ actions: [integrationsLogic, ['loadIntegrations', 'loadIntegrationsFailure', 'loadIntegrationsSuccess']],}),actions({@@ -259,6 +269,14 @@ export const logsAlertNotificationLogic = kea<logsAlertNotificationLogicType>([setPendingNotifications: (_, { notifications }) => notifications,},],+ integrationsFailed: [+ false,+ {+ loadIntegrations: () => false,+ loadIntegrationsFailure: () => true,+ loadIntegrationsSuccess: () => false,+ },+ ],slackChannelValue: [null as string | null,{