: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
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { Breadcrumb, HogFunctionType, IntegrationType } from '~/types'
import {
buildLogsAlertFilterConfig,
getHogFunctionEventKind,
groupLogsAlertDestinations,
LOGS_ALERT_EVENT_KIND_META,
LogsAlertDestinationGroup,
} from 'products/logs/frontend/components/LogsAlerting/logsAlertUtils'
import {
logsAlertsDestinationsDeleteCreate,
logsAlertsDestinationsSendsList,
logsAlertsRetrieve,
} from 'products/logs/frontend/generated/api'
import type { LogsAlertConfigurationDetailApi, LogsAlertDestinationSendApi } from '../../generated/api.schemas'
export interface LogsAlertNotificationDetailSceneLogicProps {
alertId: string
hogFunctionId: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertNotificationDetailSceneLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
slackIntegrations: IntegrationType[] | undefined // integrationsLogic
currentTeamId: number | null // teamLogic
alert: LogsAlertConfigurationDetailApi | null
alertId: string
alertLoading: boolean
breadcrumbs: Breadcrumb[]
destinationGroup: LogsAlertDestinationGroup | null
eventLabelByHogFunctionId: Record<string, string>
firstSlackIntegration: IntegrationType | undefined
hasLoaded: boolean
hogFunctionId: string
hogFunctions: HogFunctionType[]
hogFunctionsError: string | null
hogFunctionsLoading: boolean
isDeleting: boolean
messageCustomized: boolean
recentSends: LogsAlertDestinationSendApi[] | null
recentSendsDue: boolean
recentSendsError: boolean
recentSendsLoading: boolean
togglingHogFunctionIds: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertNotificationDetailSceneLogicActions {
deleteDestination: (displayLabel: string) => {
displayLabel: string
}
deleteDestinationDone: () => {
value: true
}
loadAlert: () => any
loadAlertFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAlertSuccess: (
alert: LogsAlertConfigurationDetailApi | null,
payload?: any
) => {
alert: LogsAlertConfigurationDetailApi | null
payload?: any
}
loadHogFunctions: () => any
loadHogFunctionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadHogFunctionsSuccess: (
hogFunctions: HogFunctionType[],
payload?: any
) => {
hogFunctions: HogFunctionType[]
payload?: any
}
loadRecentSends: () => any
loadRecentSendsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadRecentSendsSuccess: (
recentSends: LogsAlertDestinationSendApi[] | null,
payload?: any
) => {
recentSends: LogsAlertDestinationSendApi[] | null
payload?: any
}
setHogFunctionEnabled: (
hogFunctionId: string,
enabled: boolean
) => {
enabled: boolean
hogFunctionId: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertNotificationDetailSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
alertId: (arg: any) => string
hogFunctionId: (arg: any) => string
firstSlackIntegration: (slackIntegrations: IntegrationType[] | undefined) => IntegrationType | undefined
destinationGroup: (hogFunctions: HogFunctionType[], hogFunctionId: string) => LogsAlertDestinationGroup | null
recentSendsDue: (
featureFlags: FeatureFlagsSet,
destinationGroup: LogsAlertDestinationGroup | null,
recentSends: LogsAlertDestinationSendApi[] | null,
recentSendsLoading: boolean,
recentSendsError: boolean
) => boolean
eventLabelByHogFunctionId: (destinationGroup: LogsAlertDestinationGroup | null) => Record<string, string>
messageCustomized: (
alert: LogsAlertConfigurationDetailApi | null,
destinationGroup: LogsAlertDestinationGroup | null
) => boolean
breadcrumbs: (
alert: LogsAlertConfigurationDetailApi | null,
destinationGroup: LogsAlertDestinationGroup | null,
alertId: string
) => Breadcrumb[]
}
}
export type logsAlertNotificationDetailSceneLogicType = MakeLogicType<
logsAlertNotificationDetailSceneLogicValues,
logsAlertNotificationDetailSceneLogicActions,
LogsAlertNotificationDetailSceneLogicProps,
logsAlertNotificationDetailSceneLogicMeta
>
export const logsAlertNotificationDetailSceneLogic = kea<logsAlertNotificationDetailSceneLogicType>([
path((key) => [
'products',
'logs',
'frontend',
'scenes',
'LogsAlertNotificationDetailScene',
'logsAlertNotificationDetailSceneLogic',
key,
]),
props({} as LogsAlertNotificationDetailSceneLogicProps),
key((props) => `${props.alertId}:${props.hogFunctionId}`),
connect({
values: [
teamLogic,
['currentTeamId'],
integrationsLogic,
['slackIntegrations'],
featureFlagLogic,
['featureFlags'],
],
}),
actions({
deleteDestination: (displayLabel: string) => ({ displayLabel }),
deleteDestinationDone: true,
setHogFunctionEnabled: (hogFunctionId: string, enabled: boolean) => ({ hogFunctionId, enabled }),
}),
reducers({
hasLoaded: [
false,
{
loadHogFunctionsSuccess: () => true,
},
],
hogFunctionsError: [
null as string | null,
{
loadHogFunctions: () => null,
loadHogFunctionsSuccess: () => null,
loadHogFunctionsFailure: (_, { error }: { error: string }) => error || 'Failed to load destinations',
},
],
isDeleting: [
false,
{
deleteDestination: () => true,
deleteDestinationDone: () => false,
},
],
recentSendsError: [
false,
{
loadRecentSends: () => false,
loadRecentSendsFailure: () => true,
},
],
togglingHogFunctionIds: [
[] as string[],
{
setHogFunctionEnabled: (state, { hogFunctionId }) =>
state.includes(hogFunctionId) ? state : [...state, hogFunctionId],
loadHogFunctionsSuccess: () => [],
loadHogFunctionsFailure: () => [],
},
],
}),
loaders(({ values, props }) => ({
alert: [
null as LogsAlertConfigurationDetailApi | null,
{
loadAlert: async () => {
if (!values.currentTeamId) {
return null
}
return logsAlertsRetrieve(String(values.currentTeamId), props.alertId)
},
},
],
hogFunctions: [
[] as HogFunctionType[],
{
loadHogFunctions: async () => {
if (!values.currentTeamId) {
return []
}
const response = await api.hogFunctions.list({
types: ['internal_destination'],
filter_groups: [buildLogsAlertFilterConfig(props.alertId)],
full: true,
})
return response.results
},
},
],
recentSends: [
null as LogsAlertDestinationSendApi[] | null,
{
loadRecentSends: async () => {
const group = values.destinationGroup
if (!values.currentTeamId || !group) {
return null
}
return logsAlertsDestinationsSendsList(String(values.currentTeamId), props.alertId, {
hog_function_ids: group.hogFunctions.map((hogFunction) => hogFunction.id),
})
},
},
],
})),
selectors({
alertId: [() => [(_, props) => props.alertId], (alertId: string): string => alertId],
hogFunctionId: [() => [(_, props) => props.hogFunctionId], (id: string): string => id],
firstSlackIntegration: [
(s) => [s.slackIntegrations],
(slackIntegrations: IntegrationType[] | undefined): IntegrationType | undefined => slackIntegrations?.[0],
],
destinationGroup: [
(s) => [s.hogFunctions, s.hogFunctionId],
(hogFunctions: HogFunctionType[], hogFunctionId: string): LogsAlertDestinationGroup | null => {
const groups = groupLogsAlertDestinations(hogFunctions, () => null)
return groups.find((g) => g.hogFunctions.some((hf) => hf.id === hogFunctionId)) ?? null
},
],
// Due once per page: a pause or enable reloads the functions but changes no past send, and a
// failed load waits for Retry. Watched rather than checked after the functions load, so a flag
// that turns on later still loads the sends.
recentSendsDue: [
(s) => [s.featureFlags, s.destinationGroup, s.recentSends, s.recentSendsLoading, s.recentSendsError],
(
featureFlags: FeatureFlagsSet,
group: LogsAlertDestinationGroup | null,
recentSends: LogsAlertDestinationSendApi[] | null,
loading: boolean,
error: boolean
): boolean =>
!!featureFlags[FEATURE_FLAGS.ALERTS_DESTINATION_CUSTOMIZATION] &&
group !== null &&
recentSends === null &&
!loading &&
!error,
],
eventLabelByHogFunctionId: [
(s) => [s.destinationGroup],
(group: LogsAlertDestinationGroup | null): Record<string, string> =>
Object.fromEntries(
(group?.hogFunctions ?? []).flatMap((hogFunction) => {
const kind = getHogFunctionEventKind(hogFunction)
return kind ? [[hogFunction.id, LOGS_ALERT_EVENT_KIND_META[kind].label]] : []
})
),
],
messageCustomized: [
(s) => [s.alert, s.destinationGroup],
(alert: LogsAlertConfigurationDetailApi | null, group: LogsAlertDestinationGroup | null): boolean => {
const groupIds = new Set(group?.hogFunctions.map((hogFunction) => hogFunction.id))
return (alert?.destinations ?? []).some(
(destination) =>
destination.message_customized && destination.hog_function_ids.some((id) => groupIds.has(id))
)
},
],
breadcrumbs: [
(s) => [s.alert, s.destinationGroup, s.alertId],
(
alert: LogsAlertConfigurationDetailApi | null,
group: LogsAlertDestinationGroup | null,
alertId: string
): Breadcrumb[] => [
{
key: Scene.Logs,
name: 'Logs',
path: `${urls.logs()}?activeTab=alerts`,
iconType: 'logs',
},
{
key: Scene.LogsAlertDetail,
name: alert?.name ?? 'Alert',
path: urls.logsAlertDetail(alertId, 'notifications'),
iconType: 'logs',
},
{
key: Scene.LogsAlertNotificationDetail,
name: group?.label ?? 'Destination',
iconType: 'logs',
},
],
],
}),
listeners(({ actions, values, props }) => ({
deleteDestination: async ({ displayLabel }) => {
const group = values.destinationGroup
if (!group || !values.currentTeamId) {
actions.deleteDestinationDone()
return
}
try {
await logsAlertsDestinationsDeleteCreate(String(values.currentTeamId), props.alertId, {
hog_function_ids: group.hogFunctions.map((hf) => hf.id),
})
lemonToast.success(`Removed ${displayLabel}`)
router.actions.push(urls.logsAlertDetail(props.alertId, 'notifications'))
} catch (error: unknown) {
posthog.captureException(error, { tag: 'logs-alert-destination-delete' })
const detail =
(error as { detail?: string; message?: string })?.detail ?? (error as { message?: string })?.message
lemonToast.error(
detail ? `Failed to remove ${displayLabel}: ${detail}` : `Failed to remove ${displayLabel}`
)
} finally {
actions.deleteDestinationDone()
}
},
setHogFunctionEnabled: async ({ hogFunctionId, enabled }) => {
try {
await api.hogFunctions.update(hogFunctionId, { enabled })
} catch (error: unknown) {
posthog.captureException(error, { tag: 'logs-alert-hog-function-toggle' })
const detail =
(error as { detail?: string; message?: string })?.detail ?? (error as { message?: string })?.message
lemonToast.error(
detail
? `Failed to ${enabled ? 'enable' : 'pause'} notification: ${detail}`
: `Failed to ${enabled ? 'enable' : 'pause'} notification`
)
}
// Refresh whether the update succeeded or failed — the success path picks up the new state,
// the failure path reverts the UI to the server's truth. `togglingHogFunctionIds` clears
// on loadHogFunctions{Success,Failure}, so the LemonSwitch stays disabled until the
// refreshed list lands (prevents the double-click race against stale local state).
actions.loadHogFunctions()
},
})),
subscriptions(({ values, actions }) => ({
recentSendsDue: (due: boolean) => {
if (due) {
actions.loadRecentSends()
}
},
currentTeamId: (currentTeamId: number | null) => {
if (!currentTeamId) {
return
}
if (!values.alert && !values.alertLoading) {
actions.loadAlert()
}
if (!values.hasLoaded && !values.hogFunctionsLoading) {
actions.loadHogFunctions()
}
},
})),
afterMount(({ actions, values }) => {
if (values.currentTeamId) {
actions.loadAlert()
actions.loadHogFunctions()
}
}),
])