: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, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api, { ApiConfig } from 'lib/api'
import { HealthIssueKind, KIND_LABELS } from 'scenes/health/healthCategories'
import { SAMPLE_GLOBALS_CONTEXTS } from 'scenes/hog-functions/configuration/sampleGlobalsContexts'
import {
HOG_FUNCTION_SUB_TEMPLATES,
HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES,
} from 'scenes/hog-functions/sub-templates/sub-templates'
import {
CyclotronJobFiltersType,
CyclotronJobInputType,
CyclotronJobInvocationGlobals,
HogFunctionConfigurationContextId,
HogFunctionSubTemplateIdType,
HogFunctionTemplateType,
HogFunctionType,
PropertyFilterType,
PropertyOperator,
} from '~/types'
import { hogFunctionsInvocationsCreate } from 'products/cdp/frontend/generated/api'
import type { HogFunctionApi, HogFunctionInvocationApi } from 'products/cdp/frontend/generated/api.schemas'
import type { CyclotronJobInputSchemaType, HogFunctionSubTemplateType } from '../../../../types'
export enum WizardStep {
Destination = 'destination',
Trigger = 'trigger',
Configure = 'configure',
}
export enum AlertCreationView {
None = 'none',
Wizard = 'wizard',
Traditional = 'traditional',
}
export interface WizardDestination {
key: string
name: string
description: string
icon: string
templateId: string
}
export interface WizardTrigger {
key: HogFunctionSubTemplateIdType
name: string
description: string
}
export interface AlertWizardLogicProps {
logicKey: string
subTemplateIds: HogFunctionSubTemplateIdType[]
triggers: WizardTrigger[]
destinations: WizardDestination[]
disableUrlSync?: boolean
presetTriggerKey?: HogFunctionSubTemplateIdType
// When set, the wizard pre-applies a `kind IN (...)` property filter on the
// first event of the created HogFunction. Used by the health-alerts family
// so a per-page entry point (e.g. the SDK Health scene) can scope the alert
// to one or more health-check kinds. Pass an empty array to mean "all kinds"
// explicitly; omit the prop to leave filters untouched.
presetTriggerKinds?: string[]
// When set, the "Test" button populates the test event via the matching
// SAMPLE_GLOBALS_CONTEXTS loader (real product data) instead of a stub event.
contextId?: HogFunctionConfigurationContextId
onAlertCreated?: () => void
}
const PRIMARY_DESTINATION_LIMIT = 3
function hasSubTemplateForDestination(
triggerKey: HogFunctionSubTemplateIdType,
destination: WizardDestination
): boolean {
const subTemplates = HOG_FUNCTION_SUB_TEMPLATES[triggerKey]
return subTemplates?.some((t) => t.template_id === destination.templateId) ?? false
}
// Not every trigger has a sub-template for every destination (e.g. GitHub only
// covers "issue created", not "issue reopened"). Entry points that lock the
// trigger skip the trigger step, so the destination list is the only place left
// to keep uncreatable combinations out of the wizard.
function creatableDestinations(
triggerKey: HogFunctionSubTemplateIdType | null | undefined,
destinations: WizardDestination[]
): WizardDestination[] {
if (!triggerKey) {
return destinations
}
return destinations.filter((destination) => hasSubTemplateForDestination(triggerKey, destination))
}
interface WizardUrlState {
step: WizardStep
destinationKey: string | null
triggerKey: HogFunctionSubTemplateIdType | null
}
// The wizard mirrors its position into the URL, so a link can point at a
// destination/trigger pair that has no sub-template (hand-edited, or a pair that
// used to exist). Rewind such a state to the last step that is still valid
// instead of restoring into a configure step that can never be submitted.
function sanitizeWizardState(state: WizardUrlState, allDestinations: WizardDestination[]): WizardUrlState {
const destination = allDestinations.find((d) => d.key === state.destinationKey) ?? null
if (!destination) {
return { step: WizardStep.Destination, destinationKey: null, triggerKey: null }
}
const triggerKey =
state.triggerKey && hasSubTemplateForDestination(state.triggerKey, destination) ? state.triggerKey : null
if (!triggerKey && state.step === WizardStep.Configure) {
return { step: WizardStep.Trigger, destinationKey: destination.key, triggerKey: null }
}
return { step: state.step, destinationKey: destination.key, triggerKey }
}
// Pre-applies `kind IN (selectedKinds)` as a top-level property filter on the
// sub-template's filter group. A null or empty `selectedKinds` leaves filters
// untouched (matches every kind). Used by the health-alerts family so a per-page
// entry point can scope the resulting HogFunction to specific kinds.
//
// Top-level (vs `events[0].properties`) matches the convention of the trigger
// UI in HogFunctionFiltersInternal, so the kind filter remains visible and
// editable on the new-function page, and survives a trigger change (which
// rewrites `events`).
export function applyKindFilter(
baseFilters: CyclotronJobFiltersType | null | undefined,
selectedKinds: string[] | null
): CyclotronJobFiltersType | null | undefined {
if (!baseFilters || !selectedKinds || selectedKinds.length === 0) {
return baseFilters
}
return {
...baseFilters,
properties: [
{
key: 'kind',
value: selectedKinds,
operator: PropertyOperator.Exact,
type: PropertyFilterType.Event,
},
],
}
}
// Renders a selectedKinds list as a short, human-readable parenthetical suffix
// (e.g. "(SDK outdated)" or "(SDK outdated, External data failures)") that can
// be appended to a sub-template's generic name/description, so the created
// HogFunction is immediately identifiable in lists.
function formatKindsSuffix(selectedKinds: string[] | null | undefined): string {
if (!selectedKinds || selectedKinds.length === 0) {
return ''
}
const labels = selectedKinds.map((k) => KIND_LABELS[k as HealthIssueKind] ?? k)
return ` (${labels.join(', ')})`
}
export function decorateAlertName(baseName: string, selectedKinds: string[] | null | undefined): string {
return `${baseName}${formatKindsSuffix(selectedKinds)}`
}
function lastErrorLogMessage(logs: readonly unknown[]): string | null {
for (const entry of [...logs].reverse()) {
const { level, message } = (entry ?? {}) as { level?: unknown; message?: unknown }
if (typeof level === 'string' && level.toLowerCase() === 'error' && typeof message === 'string') {
return message
}
}
return null
}
// The test endpoint answers HTTP 200 when the destination rejects the message, and reports the
// rejection in the logs. Returns the message to show, or null when the test went through.
// A skipped result covers two cases: the filters excluded the event, or the inputs failed to
// build. Only the second case writes an error log.
export function testInvocationFailureMessage(result: Pick<HogFunctionInvocationApi, 'status' | 'logs'>): string | null {
if (result.status === 'success') {
return null
}
const reason = lastErrorLogMessage(result.logs)
if (reason) {
return `Test failed: ${reason}`
}
return result.status === 'skipped'
? "Test not sent. The test event didn't match this alert's filters."
: 'Test failed. Check the destination settings and try again.'
}
export function buildAlertInputs(
inputsSchema: CyclotronJobInputSchemaType[] | null | undefined,
subTemplateInputs: Record<string, CyclotronJobInputType> | null | undefined,
inputValues: Record<string, CyclotronJobInputType>
): Record<string, CyclotronJobInputType> {
const inputs: Record<string, CyclotronJobInputType> = {}
for (const schema of inputsSchema ?? []) {
if (schema.default !== undefined) {
inputs[schema.key] = { value: schema.default }
}
}
return { ...inputs, ...subTemplateInputs, ...inputValues }
}
export interface AlertHogFunctionConfiguration {
type: 'internal_destination'
template_id: string
name: string
description: string
filters: CyclotronJobFiltersType | null | undefined
enabled: true
masking: null
inputs: Record<string, CyclotronJobInputType>
}
/** The hog function an alert creates: an enabled internal destination with the template's merged inputs. */
export function buildAlertHogFunctionConfiguration({
templateId,
name,
description,
filters,
inputs,
}: {
templateId: string
name: string
description: string
filters: CyclotronJobFiltersType | null | undefined
inputs: Record<string, CyclotronJobInputType>
}): AlertHogFunctionConfiguration {
return {
type: 'internal_destination',
template_id: templateId,
name,
description,
filters,
enabled: true,
masking: null,
inputs,
}
}
function extractDestinationKeyFromAlert(alert: HogFunctionType, allDestinations: WizardDestination[]): string | null {
const templateId = alert.template?.id
if (!templateId) {
return null
}
for (const destination of allDestinations) {
if (templateId.startsWith(destination.templateId)) {
return destination.key
}
}
return null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertWizardLogicValues {
activeSubTemplate: HogFunctionSubTemplateType | null
alertCreated: boolean
alertCreationView: AlertCreationView
allDestinations: WizardDestination[]
availableDestinations: WizardDestination[]
availableTriggers: WizardTrigger[]
configuration: {
inputs: Record<
string,
{
bytecode?: any
order?: number | undefined
secret?: boolean | undefined
templating?: 'hog' | 'liquid' | undefined
value: any
}
>
inputs_schema: CyclotronJobInputSchemaType[]
}
currentStep: WizardStep
existingAlerts: HogFunctionType[]
existingAlertsLoading: boolean
extraDestinations: WizardDestination[]
inputValues: Record<string, CyclotronJobInputType>
primaryDestinations: WizardDestination[]
requiredInputsSchema: CyclotronJobInputSchemaType[]
selectedDestinationKey: string | null
selectedKinds: string[] | null
selectedTemplate: HogFunctionTemplateType | null
selectedTemplateLoading: boolean
selectedTriggerKey: HogFunctionSubTemplateIdType | null
sortedDestinations: WizardDestination[]
subTemplateIds: HogFunctionSubTemplateIdType[]
submitting: boolean
testing: boolean
triggers: WizardTrigger[]
usedDestinationKeys: Set<string>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertWizardLogicActions {
createAlertSuccess: () => {
value: true
}
loadExistingAlerts: () => any
loadExistingAlertsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadExistingAlertsSuccess: (
existingAlerts: HogFunctionType[],
payload?: any
) => {
existingAlerts: HogFunctionType[]
payload?: any
}
loadTemplate: (templateId: string) => string
loadTemplateFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadTemplateSuccess: (
selectedTemplate: HogFunctionTemplateType,
payload?: string
) => {
selectedTemplate: HogFunctionTemplateType
payload?: string
}
resetWizard: () => {
value: true
}
restoreWizardState: (state: {
destinationKey: string | null
step: WizardStep
triggerKey: HogFunctionSubTemplateIdType | null
}) => {
state: {
destinationKey: string | null
step: WizardStep
triggerKey: HogFunctionSubTemplateIdType | null
}
}
setAlertCreationView: (view: AlertCreationView) => {
view: AlertCreationView
}
setDestinationKey: (destinationKey: string) => {
destinationKey: string
}
setInputValue: (
key: string,
value: CyclotronJobInputType
) => {
key: string
value: {
bytecode?: any
order?: number | undefined
secret?: boolean | undefined
templating?: 'hog' | 'liquid' | undefined
value: any
}
}
setStep: (step: WizardStep) => {
step: WizardStep
}
setTriggerKey: (triggerKey: HogFunctionSubTemplateIdType) => {
triggerKey: HogFunctionSubTemplateIdType
}
submitConfiguration: () => {
value: true
}
submitConfigurationComplete: () => {
value: true
}
testConfiguration: () => {
value: true
}
testConfigurationComplete: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertWizardLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
availableDestinations: (allDestinations: WizardDestination[]) => WizardDestination[]
usedDestinationKeys: (existingAlerts: HogFunctionType[], allDestinations: WizardDestination[]) => Set<string>
sortedDestinations: (
usedDestinationKeys: Set<string>,
availableDestinations: WizardDestination[]
) => WizardDestination[]
primaryDestinations: (sortedDestinations: WizardDestination[]) => WizardDestination[]
extraDestinations: (sortedDestinations: WizardDestination[]) => WizardDestination[]
availableTriggers: (
selectedDestinationKey: string | null,
triggers: WizardTrigger[],
allDestinations: WizardDestination[]
) => WizardTrigger[]
activeSubTemplate: (
selectedDestinationKey: string | null,
selectedTriggerKey: HogFunctionSubTemplateIdType | null,
allDestinations: WizardDestination[]
) => HogFunctionSubTemplateType | null
requiredInputsSchema: (
selectedTemplate: HogFunctionTemplateType | null,
activeSubTemplate: HogFunctionSubTemplateType | null
) => CyclotronJobInputSchemaType[]
configuration: (
selectedTemplate: HogFunctionTemplateType | null,
inputValues: Record<
string,
{
bytecode?: any
order?: number | undefined
secret?: boolean | undefined
templating?: 'hog' | 'liquid' | undefined
value: any
}
>
) => {
inputs: Record<
string,
{
bytecode?: any
order?: number | undefined
secret?: boolean | undefined
templating?: 'hog' | 'liquid' | undefined
value: any
}
>
inputs_schema: CyclotronJobInputSchemaType[]
}
}
}
export type alertWizardLogicType = MakeLogicType<
alertWizardLogicValues,
alertWizardLogicActions,
AlertWizardLogicProps,
alertWizardLogicMeta
>
export const alertWizardLogic = kea<alertWizardLogicType>([
props({} as AlertWizardLogicProps),
key((p) => p.logicKey),
path((key) => ['lib', 'components', 'Alerting', 'AlertWizard', 'alertWizardLogic', key]),
actions({
setAlertCreationView: (view: AlertCreationView) => ({ view }),
setStep: (step: WizardStep) => ({ step }),
setDestinationKey: (destinationKey: string) => ({ destinationKey }),
setTriggerKey: (triggerKey: HogFunctionSubTemplateIdType) => ({ triggerKey }),
setInputValue: (key: string, value: CyclotronJobInputType) => ({ key, value }),
restoreWizardState: (state: {
step: WizardStep
destinationKey: string | null
triggerKey: HogFunctionSubTemplateIdType | null
}) => ({ state }),
resetWizard: true,
createAlertSuccess: true,
submitConfiguration: true,
submitConfigurationComplete: true,
testConfiguration: true,
testConfigurationComplete: true,
}),
reducers(({ props: logicProps }) => ({
subTemplateIds: [logicProps.subTemplateIds, {}],
triggers: [logicProps.triggers as WizardTrigger[], {}],
allDestinations: [logicProps.destinations as WizardDestination[], {}],
alertCreationView: [
AlertCreationView.None as AlertCreationView,
{
setAlertCreationView: (_, { view }) => view,
restoreWizardState: () => AlertCreationView.Wizard as AlertCreationView,
createAlertSuccess: () => AlertCreationView.None as AlertCreationView,
},
],
currentStep: [
WizardStep.Destination as WizardStep,
{
setStep: (_, { step }) => step,
setDestinationKey: () =>
(logicProps.presetTriggerKey ? WizardStep.Configure : WizardStep.Trigger) as WizardStep,
restoreWizardState: (_, { state }) => state.step,
resetWizard: () => WizardStep.Destination as WizardStep,
},
],
selectedDestinationKey: [
null as string | null,
{
setDestinationKey: (_, { destinationKey }) => destinationKey,
restoreWizardState: (_, { state }) => state.destinationKey,
resetWizard: () => null,
},
],
selectedTriggerKey: [
(logicProps.presetTriggerKey ?? null) as HogFunctionSubTemplateIdType | null,
{
setTriggerKey: (_, { triggerKey }) => triggerKey,
restoreWizardState: (_, { state }) => state.triggerKey,
resetWizard: () => (logicProps.presetTriggerKey ?? null) as HogFunctionSubTemplateIdType | null,
},
],
selectedKinds: [
(logicProps.presetTriggerKinds ?? null) as string[] | null,
{
resetWizard: () => (logicProps.presetTriggerKinds ?? null) as string[] | null,
},
],
alertCreated: [
false,
{
createAlertSuccess: () => true,
resetWizard: () => false,
},
],
inputValues: [
{} as Record<string, CyclotronJobInputType>,
{
setInputValue: (state, { key, value }) => ({ ...state, [key]: value }),
resetWizard: () => ({}),
setDestinationKey: () => ({}),
setTriggerKey: () => ({}),
},
],
submitting: [
false,
{
submitConfiguration: () => true,
submitConfigurationComplete: () => false,
createAlertSuccess: () => false,
},
],
testing: [
false,
{
testConfiguration: () => true,
testConfigurationComplete: () => false,
},
],
})),
loaders(({ props: logicProps }) => ({
existingAlerts: [
[] as HogFunctionType[],
{
loadExistingAlerts: async () => {
const filters = logicProps.subTemplateIds
.map((id) => HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES[id]?.filters)
.filter(Boolean)
const response = await api.hogFunctions.list({
types: ['internal_destination'],
filter_groups: filters as any[],
limit: 100,
})
return response.results
},
},
],
selectedTemplate: [
null as HogFunctionTemplateType | null,
{
loadTemplate: async (templateId: string) => {
return await api.hogFunctions.getTemplate(templateId)
},
},
],
})),
selectors(({ props: logicProps }) => ({
availableDestinations: [
(s) => [s.allDestinations],
(allDestinations: WizardDestination[]): WizardDestination[] =>
creatableDestinations(logicProps.presetTriggerKey, allDestinations),
],
usedDestinationKeys: [
(s) => [s.existingAlerts, s.allDestinations],
(existingAlerts: HogFunctionType[], allDestinations: WizardDestination[]): Set<string> => {
const used = new Set<string>()
for (const alert of existingAlerts) {
const key = extractDestinationKeyFromAlert(alert, allDestinations)
if (key) {
used.add(key)
}
}
return used
},
],
sortedDestinations: [
(s) => [s.usedDestinationKeys, s.availableDestinations],
(usedDestinationKeys: Set<string>, availableDestinations: WizardDestination[]): WizardDestination[] => {
return [...availableDestinations].sort((a, b) => {
const aUsed = usedDestinationKeys.has(a.key) ? 1 : 0
const bUsed = usedDestinationKeys.has(b.key) ? 1 : 0
return bUsed - aUsed
})
},
],
primaryDestinations: [
(s) => [s.sortedDestinations],
(sortedDestinations: WizardDestination[]): WizardDestination[] =>
sortedDestinations.slice(0, PRIMARY_DESTINATION_LIMIT),
],
extraDestinations: [
(s) => [s.sortedDestinations],
(sortedDestinations: WizardDestination[]): WizardDestination[] =>
sortedDestinations.slice(PRIMARY_DESTINATION_LIMIT),
],
availableTriggers: [
(s) => [s.selectedDestinationKey, s.triggers, s.allDestinations],
(
selectedDestinationKey: string | null,
triggers: WizardTrigger[],
allDestinations: WizardDestination[]
): WizardTrigger[] => {
if (!selectedDestinationKey) {
return triggers
}
const destination = allDestinations.find((d) => d.key === selectedDestinationKey)
if (!destination) {
return triggers
}
return triggers.filter((trigger) => hasSubTemplateForDestination(trigger.key, destination))
},
],
activeSubTemplate: [
(s) => [s.selectedDestinationKey, s.selectedTriggerKey, s.allDestinations],
(
selectedDestinationKey: string | null,
selectedTriggerKey: HogFunctionSubTemplateIdType | null,
allDestinations: WizardDestination[]
) => {
if (!selectedDestinationKey || !selectedTriggerKey) {
return null
}
const destination = allDestinations.find((d) => d.key === selectedDestinationKey)
if (!destination) {
return null
}
const subTemplates = HOG_FUNCTION_SUB_TEMPLATES[selectedTriggerKey]
return subTemplates?.find((t) => t.template_id === destination.templateId) ?? null
},
],
requiredInputsSchema: [
(s) => [s.selectedTemplate, s.activeSubTemplate],
(
selectedTemplate: HogFunctionTemplateType | null,
activeSubTemplate: null | import('~/types').HogFunctionSubTemplateType
) => {
if (!selectedTemplate) {
return []
}
const prefilledKeys = new Set(Object.keys(activeSubTemplate?.inputs ?? {}))
return (selectedTemplate.inputs_schema ?? []).filter(
(s) =>
s.required &&
!prefilledKeys.has(s.key) &&
(s.type === 'integration' ||
s.type === 'integration_field' ||
s.type === 'string' ||
s.type === 'choice')
)
},
],
configuration: [
(s) => [s.selectedTemplate, s.inputValues],
(selectedTemplate: HogFunctionTemplateType | null, inputValues: Record<string, CyclotronJobInputType>) => ({
inputs_schema: selectedTemplate?.inputs_schema ?? [],
inputs: inputValues,
}),
],
})),
listeners(({ values, actions, props: logicProps }) => ({
createAlertSuccess: () => {
actions.resetWizard()
actions.loadExistingAlerts()
logicProps.onAlertCreated?.()
},
setAlertCreationView: ({ view }) => {
if (view === AlertCreationView.Wizard) {
actions.loadExistingAlerts()
}
},
restoreWizardState: ({ state }) => {
if (state.destinationKey && state.triggerKey) {
const destination = values.allDestinations.find((d) => d.key === state.destinationKey)
if (destination) {
actions.loadTemplate(destination.templateId)
}
}
actions.loadExistingAlerts()
},
setTriggerKey: () => {
const destinationKey = values.selectedDestinationKey
if (destinationKey) {
const destination = values.allDestinations.find((d) => d.key === destinationKey)!
actions.loadTemplate(destination.templateId)
}
actions.setStep(WizardStep.Configure)
},
setDestinationKey: ({ destinationKey }) => {
if (logicProps.presetTriggerKey) {
const destination = values.allDestinations.find((d) => d.key === destinationKey)
if (destination) {
actions.loadTemplate(destination.templateId)
}
}
},
testConfiguration: async (_, breakpoint) => {
const destinationKey = values.selectedDestinationKey
const triggerKey = values.selectedTriggerKey
if (!destinationKey || !triggerKey) {
return
}
const destination = values.allDestinations.find((d) => d.key === destinationKey)!
const subTemplates = HOG_FUNCTION_SUB_TEMPLATES[triggerKey]
const subTemplate = subTemplates.find((t) => t.template_id === destination.templateId)
if (!subTemplate) {
lemonToast.error('Template not found for this combination')
return
}
const selectedTemplate = values.selectedTemplate
if (!selectedTemplate) {
lemonToast.error('Template not loaded yet')
actions.testConfigurationComplete()
return
}
const mergedInputs = buildAlertInputs(
selectedTemplate.inputs_schema,
subTemplate.inputs,
values.inputValues
)
const configuration: Record<string, any> = {
type: 'internal_destination',
template_id: destination.templateId,
filters: subTemplate.filters,
enabled: true,
masking: null,
inputs: mergedInputs,
inputs_schema: selectedTemplate.inputs_schema,
hog: selectedTemplate.code,
}
let globals: CyclotronJobInvocationGlobals = {
event: {
uuid: 'test-event-uuid',
distinct_id: 'test-distinct-id',
timestamp: new Date().toISOString(),
event: subTemplate.filters?.events?.[0]?.id || triggerKey,
elements_chain: '',
url: '',
properties: {
name: 'Test issue',
description: 'This is a test alert from PostHog',
},
},
project: {
id: 0,
name: 'Test project',
url: window.location.origin,
},
source: {
name: 'Alert wizard',
url: window.location.href,
},
}
const sampleGlobalsLoader = logicProps.contextId ? SAMPLE_GLOBALS_CONTEXTS[logicProps.contextId] : undefined
if (sampleGlobalsLoader) {
try {
globals = await sampleGlobalsLoader(
globals,
applyKindFilter(subTemplate.filters, values.selectedKinds)
)
} catch {
// Fall back to the stub test event
}
}
try {
const result = await hogFunctionsInvocationsCreate(String(ApiConfig.getCurrentTeamId()), 'new', {
configuration: configuration as HogFunctionApi,
globals,
mock_async_functions: false,
})
breakpoint()
const failure = testInvocationFailureMessage(result)
if (failure) {
lemonToast.error(failure)
} else {
lemonToast.success('Test invocation sent')
}
} catch (e: any) {
breakpoint()
lemonToast.error(e.detail || 'Test invocation failed')
}
actions.testConfigurationComplete()
},
submitConfiguration: async () => {
try {
const destinationKey = values.selectedDestinationKey
const triggerKey = values.selectedTriggerKey
if (!destinationKey || !triggerKey) {
return
}
const destination = values.allDestinations.find((d) => d.key === destinationKey)!
const subTemplates = HOG_FUNCTION_SUB_TEMPLATES[triggerKey]
const subTemplate = subTemplates.find((t) => t.template_id === destination.templateId)
if (!subTemplate) {
lemonToast.error('Template not found for this combination')
return
}
const selectedTemplate = values.selectedTemplate
if (!selectedTemplate) {
lemonToast.error('Template not loaded yet')
return
}
const mergedInputs = buildAlertInputs(
selectedTemplate.inputs_schema,
subTemplate.inputs,
values.inputValues
)
const filters = applyKindFilter(subTemplate.filters, values.selectedKinds)
const name = decorateAlertName(subTemplate.name ?? '', values.selectedKinds)
const description = decorateAlertName(subTemplate.description ?? '', values.selectedKinds)
const configuration = buildAlertHogFunctionConfiguration({
templateId: destination.templateId,
name,
description,
filters,
inputs: mergedInputs,
})
await api.hogFunctions.create(configuration)
posthog.capture('error_tracking_alert_created', {
ui_source: 'wizard',
trigger_event: subTemplate.filters?.events?.[0]?.id ?? null,
subtemplate_id: triggerKey,
destination_key: destination.key,
destination_template_id: destination.templateId,
enabled: true,
})
lemonToast.success('Alert created successfully')
actions.createAlertSuccess()
} catch (e: any) {
lemonToast.error(e.detail || 'Failed to create alert')
} finally {
actions.submitConfigurationComplete()
}
},
})),
actionToUrl(({ values, props: logicProps }) => {
if (logicProps.disableUrlSync) {
return {}
}
const buildURL = (): [string, Record<string, any>, Record<string, any>] => {
const { currentLocation } = router.values
const searchParams = { ...currentLocation.searchParams }
if (values.alertCreationView === AlertCreationView.Wizard) {
searchParams.wizard_step = values.currentStep
if (values.selectedDestinationKey) {
searchParams.wizard_dest = values.selectedDestinationKey
} else {
delete searchParams.wizard_dest
}
if (values.selectedTriggerKey) {
searchParams.wizard_trigger = values.selectedTriggerKey
} else {
delete searchParams.wizard_trigger
}
} else {
delete searchParams.wizard_step
delete searchParams.wizard_dest
delete searchParams.wizard_trigger
}
return [currentLocation.pathname, searchParams, currentLocation.hashParams]
}
return {
setAlertCreationView: buildURL,
setStep: buildURL,
setDestinationKey: buildURL,
setTriggerKey: buildURL,
resetWizard: buildURL,
createAlertSuccess: buildURL,
}
}),
urlToAction(({ actions, values, props: logicProps }) => ({
'**': (_, searchParams) => {
if (logicProps.disableUrlSync) {
return
}
const wizardStep = searchParams.wizard_step as WizardStep | undefined
const wizardDest = searchParams.wizard_dest as string | undefined
const wizardTrigger = searchParams.wizard_trigger as HogFunctionSubTemplateIdType | undefined
if (wizardStep && values.alertCreationView !== AlertCreationView.Wizard) {
actions.restoreWizardState(
sanitizeWizardState(
{
step: wizardStep,
destinationKey: wizardDest ?? null,
triggerKey: wizardTrigger ?? null,
},
values.availableDestinations
)
)
}
},
})),
afterMount(({ actions }) => {
actions.loadExistingAlerts()
}),
])