Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(alerts): support selecting Slack workspaces for alerts (#72939)

Matt Puaa715b57197e1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 11f2f2f8b41b..b778271145cc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4754,6 +4754,10 @@ snapshots:
hash: v1.k794b7964.3f137bbf7a90843202ca75d89d5dec7f102945cf55f2c4532ccac3b4e8073c9b.phN1IPBCANIC0EsrGxopacxr96qniH5DnAm-ZnKVUz0
products-alerts-shared-components--notifications--light:
hash: v1.k794b7964.240b6085693c57e601cf978fe479a2cb6124c80c7cd743f44ff61744e94c90bb.v4D0nGdwscIlnUoeTqwHQsyEggk4eOm3GBGvgvFkXII
+ products-alerts-shared-components--notifications-multiple-slack-workspaces--dark:
+ hash: v1.k794b7964.44080ef3cc8fb24fb5ad535ee387b4911358d8804045747939750530be5c6235.7UCJ4oJX1LEan-IVOu2iA5Hzz14HQQoZENCw_SMOxss
+ products-alerts-shared-components--notifications-multiple-slack-workspaces--light:
+ hash: v1.k794b7964.7af987b36145b9e49adca1cbc6d1a4616ae94866476f72bc510ab96d286e4133.3H70LHwnl5IAqi3fUW4lQZZ7UT9o23krCbiAdBvWpvY
products-alerts-shared-components--quiet-hours--dark:
hash: v1.k794b7964.3a4e054512c5b607cf75f1cc3e6dd2212333d05e4fb89274b580b47f01e5aeaf.nPp2_jJIgcpjkQgHQA63v-eqzVox-oIfDi3SQKPdRis
products-alerts-shared-components--quiet-hours--light:
diff --git a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
index 5ccf21baf060..ee7bc52e544c 100644
--- a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
+++ b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.tsx
@@ -23,6 +23,7 @@ export type IntegrationConfigureProps = {
schema?: { requiredScopes?: string }
integration?: string
beforeRedirect?: () => void
+ allowClear?: boolean
}
export function IntegrationChoice({
@@ -32,6 +33,7 @@ export function IntegrationChoice({
integration,
redirectUrl,
beforeRedirect,
+ allowClear = true,
}: IntegrationConfigureProps): JSX.Element | null {
const { integrationsLoading, integrations, newIntegrationModalKind, slackAvailable } = useValues(integrationsLogic)
const { newGoogleCloudKey, openNewIntegrationModal, closeNewIntegrationModal, deleteIntegration } =
@@ -139,7 +141,7 @@ export function IntegrationChoice({
label: 'Manage integrations',
sideIcon: <IconExternal />,
},
- value
+ value && allowClear
? {
onClick: () => onChange?.(null),
label: 'Clear selection',
diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsx
index e7030b1b82f2..3283fb0365d5 100644
--- a/products/alerts/frontend/components/AlertComponents.stories.tsx
+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx
@@ -1,16 +1,20 @@
import type { Meta, StoryObj } from '@storybook/react'
-import { kea, path, useValues } from 'kea'
+import { kea, path, useActions, useValues } from 'kea'
import { Form, forms } from 'kea-forms'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import type { LemonSegmentedButtonOption, LemonSelectOptions } from '@posthog/lemon-ui'
import { LemonCheckbox, LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { useStorybookMocks } from '~/mocks/browser'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
+import { IntegrationType } from '~/types'
+import { alertNotificationLogic } from 'products/alerts/frontend/logic/alertNotificationLogic'
import type { ScheduleRestriction } from 'products/alerts/frontend/types'
+import { InlineAlertNotifications } from 'products/alerts/frontend/views/InlineAlertNotifications'
import { AlertAdvancedOptions } from './AlertAdvancedOptions'
import { AlertDefinitionRow, AlertNextEvaluationStatus, AlertTimezoneNotice } from './AlertDefinition'
@@ -225,6 +229,109 @@ function NotificationsStory(): JSX.Element {
)
}
+const STORY_SLACK_WORKSPACES: IntegrationType[] = [
+ {
+ id: 1,
+ kind: 'slack',
+ display_name: 'PostHog',
+ icon_url: '/static/services/slack.png',
+ config: { team: { id: 'T11111', name: 'PostHog' } },
+ created_at: '2026-01-01T00:00:00Z',
+ },
+ {
+ id: 2,
+ kind: 'slack',
+ display_name: 'Acme Workspace',
+ icon_url: '/static/services/slack.png',
+ config: { team: { id: 'T99999', name: 'Acme Workspace' } },
+ created_at: '2026-01-01T00:00:00Z',
+ },
+]
+
+const STORY_SLACK_CHANNELS: Record<string, { id: string; name: string }[]> = {
+ '1': [
+ { id: 'C100', name: 'alerts' },
+ { id: 'C101', name: 'general' },
+ ],
+ '2': [
+ { id: 'C200', name: 'acme-alerts' },
+ { id: 'C201', name: 'acme-eng' },
+ ],
+}
+
+const STORY_EXISTING_HOG_FUNCTIONS = [
+ {
+ id: 'hf1',
+ type: 'internal_destination',
+ name: 'Alert: Slack #alerts',
+ description: '',
+ created_by: null,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ enabled: true,
+ hog: '',
+ template_id: 'template-slack',
+ inputs: {
+ slack_workspace: { value: 1 },
+ channel: { value: 'C100' },
+ },
+ },
+ {
+ id: 'hf2',
+ type: 'internal_destination',
+ name: 'Alert: Slack #acme-alerts',
+ description: '',
+ created_by: null,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ enabled: true,
+ hog: '',
+ template_id: 'template-slack',
+ inputs: {
+ slack_workspace: { value: 2 },
+ channel: { value: 'C200' },
+ },
+ },
+]
+
+function MultipleSlackWorkspacesStory(): JSX.Element {
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/integrations': { results: STORY_SLACK_WORKSPACES, count: 2 },
+ '/api/environments/:team_id/integrations/:id/channels': ({ params, request }) => {
+ const channelId = new URL(request.url).searchParams.get('channel_id')
+ const allChannels = (STORY_SLACK_CHANNELS[String(params.id)] ?? []).map((channel) => ({
+ ...channel,
+ is_private: false,
+ is_ext_shared: false,
+ is_member: true,
+ }))
+ const channels = channelId ? allChannels.filter((channel) => channel.id === channelId) : allChannels
+ return [200, { channels, lastRefreshedAt: '2026-01-01T00:00:00Z' }]
+ },
+ '/api/environments/:team_id/hog_functions': {
+ results: STORY_EXISTING_HOG_FUNCTIONS,
+ count: STORY_EXISTING_HOG_FUNCTIONS.length,
+ },
+ },
+ })
+
+ // Preselect a workspace + channel so the picker doesn't open empty.
+ const { setSelectedSlackIntegrationId, setSlackChannelValue } = useActions(
+ alertNotificationLogic({ alertId: 'alert-1' })
+ )
+ useEffect(() => {
+ setSelectedSlackIntegrationId(2)
+ setSlackChannelValue('C201|#acme-eng')
+ }, [setSelectedSlackIntegrationId, setSlackChannelValue])
+
+ return (
+ <div className="max-w-2xl border rounded bg-surface-primary p-4">
+ <InlineAlertNotifications alertId="alert-1" />
+ </div>
+ )
+}
+
function QuietHoursStory(): JSX.Element {
const [scheduleRestriction, setScheduleRestriction] = useState<ScheduleRestriction | null>({
blocked_windows: [{ start: '22:00', end: '07:00' }],
@@ -296,5 +403,6 @@ export const EditorLoading: Story = {
export const Definition: Story = { render: () => <DefinitionStory /> }
export const AdvancedOptions: Story = { render: () => <AdvancedOptionsStory /> }
export const Notifications: Story = { render: () => <NotificationsStory /> }
+export const NotificationsMultipleSlackWorkspaces: Story = { render: () => <MultipleSlackWorkspacesStory /> }
export const QuietHours: Story = { render: () => <QuietHoursStory /> }
export const EvaluationHistory: Story = { render: () => <EvaluationHistoryStory /> }
diff --git a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
index 98473a79b332..d51c542b6a45 100644
--- a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
+++ b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
@@ -11,6 +11,7 @@ import {
LemonTagType,
} from '@posthog/lemon-ui'
+import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'
import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'
import { IntegrationType } from '~/types'
@@ -32,8 +33,8 @@ interface AlertNotificationDestinationButtonAction {
export interface AlertNotificationDestinationView {
key: string
- title: string
- detail?: string | null
+ title: ReactNode
+ detail?: ReactNode
tags?: { label: string; type?: LemonTagType }[]
viewAction?: AlertNotificationDestinationIconAction | AlertNotificationDestinationButtonAction
onDelete: () => void
@@ -66,7 +67,9 @@ interface AlertNotificationDestinationEditorProps<NotificationType extends strin
}
slack: {
notificationType: NotificationType
+ integrations?: IntegrationType[]
integration?: IntegrationType
+ onIntegrationChange?: (integrationId: number | null) => void
channelValue: string | null
onChannelValueChange: (value: string | null) => void
}
@@ -211,11 +214,31 @@ export function AlertNotificationDestinationEditor<NotificationType extends stri
if (notificationType.value === slack.notificationType) {
if (slack.integration) {
slackDestinationInput = (
- <SlackChannelPicker
- value={slack.channelValue ?? undefined}
- onChange={slack.onChannelValueChange}
- integration={slack.integration}
- />
+ <div className="space-y-3">
+ {(slack.integrations?.length ?? 0) > 1 ? (
+ <fieldset className="space-y-1">
+ <legend className="text-sm font-medium">Slack workspace</legend>
+ <IntegrationChoice
+ integration="slack"
+ value={slack.integration.id}
+ onChange={(integrationId) => {
+ if (integrationId !== slack.integration?.id) {
+ slack.onIntegrationChange?.(integrationId)
+ }
+ }}
+ allowClear={false}
+ />
+ </fieldset>
+ ) : 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}
+ />
+ </fieldset>
+ </div>
)
} else {
slackDestinationInput = <SlackNotConfiguredBanner />
diff --git a/products/alerts/frontend/logic/alertNotificationLogic.test.ts b/products/alerts/frontend/logic/alertNotificationLogic.test.ts
index 1976d9f08b15..801c06b97bb9 100644
--- a/products/alerts/frontend/logic/alertNotificationLogic.test.ts
+++ b/products/alerts/frontend/logic/alertNotificationLogic.test.ts
@@ -3,11 +3,12 @@ import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
import { initKeaTests } from '~/test/init'
-import { HogFunctionType } from '~/types'
+import { HogFunctionType, IntegrationType } from '~/types'
import {
ALERT_NOTIFICATION_TYPE_DISCORD,
ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,
+ ALERT_NOTIFICATION_TYPE_SLACK,
ALERT_NOTIFICATION_TYPE_WEBHOOK,
} from 'products/alerts/frontend/logic/alertNotifications'
@@ -32,6 +33,15 @@ describe('alertNotificationLogic', () => {
listSpy.mockRestore()
})
+ const makeSlackIntegration = (id: number): IntegrationType => ({
+ id,
+ kind: 'slack',
+ display_name: `Workspace ${id}`,
+ icon_url: '',
+ config: {},
+ created_at: '2026-01-01T00:00:00Z',
+ })
+
it('clears staged inputs when the destination type changes', async () => {
logic = alertNotificationLogic({ alertId: 'alert-123' })
logic.mount()
@@ -45,10 +55,64 @@ describe('alertNotificationLogic', () => {
// A staged Slack channel is cleared the same way.
logic.actions.setSlackChannelValue('C123|#general')
await expectLogic(logic).toMatchValues({ slackChannelValue: 'C123|#general' })
+ logic.actions.setSelectedSlackIntegrationId(2)
+ await expectLogic(logic).toMatchValues({ slackChannelValue: null })
+
+ logic.actions.setSlackChannelValue('C456|#alerts')
logic.actions.setSelectedType(ALERT_NOTIFICATION_TYPE_WEBHOOK)
await expectLogic(logic).toMatchValues({ slackChannelValue: null })
})
+ it('clears the channel when an integrations refresh removes the selected workspace', async () => {
+ logic = alertNotificationLogic({ alertId: 'alert-123' })
+ logic.mount()
+
+ const firstWorkspace = makeSlackIntegration(1)
+ const secondWorkspace = makeSlackIntegration(2)
+ logic.actions.loadIntegrationsSuccess([firstWorkspace, secondWorkspace])
+ await expectLogic(logic).toMatchValues({ selectedSlackIntegrationId: 1 })
+
+ logic.actions.setSelectedSlackIntegrationId(2)
+ logic.actions.setSlackChannelValue('C123|#general')
+ logic.actions.loadIntegrationsSuccess([firstWorkspace])
+
+ await expectLogic(logic).toMatchValues({
+ selectedSlackIntegrationId: 1,
+ selectedSlackIntegration: firstWorkspace,
+ slackChannelValue: null,
+ })
+ })
+
+ it('drops staged Slack notifications for a workspace removed by an integrations refresh', async () => {
+ logic = alertNotificationLogic({ alertId: 'alert-123' })
+ logic.mount()
+
+ const firstWorkspace = makeSlackIntegration(1)
+ const secondWorkspace = makeSlackIntegration(2)
+ logic.actions.loadIntegrationsSuccess([firstWorkspace, secondWorkspace])
+
+ logic.actions.addPendingNotification({
+ type: ALERT_NOTIFICATION_TYPE_SLACK,
+ slackWorkspaceId: 2,
+ slackChannelId: 'C1',
+ slackChannelName: 'general',
+ })
+ logic.actions.addPendingNotification({
+ type: ALERT_NOTIFICATION_TYPE_WEBHOOK,
+ webhookUrl: 'https://example.com',
+ })
+ await expectLogic(logic).toMatchValues({ pendingNotifications: [expect.anything(), expect.anything()] })
+
+ logic.actions.loadIntegrationsSuccess([firstWorkspace])
+
+ // The staged Slack destination pointed at the now-removed workspace 2 is dropped;
+ // saving it would create a HogFunction referencing a dead integration. The webhook
+ // notification doesn't reference a workspace, so it's untouched.
+ await expectLogic(logic).toMatchValues({
+ pendingNotifications: [{ type: ALERT_NOTIFICATION_TYPE_WEBHOOK, webhookUrl: 'https://example.com' }],
+ })
+ })
+
it('creates a Discord destination HogFunction end-to-end', async () => {
logic = alertNotificationLogic({ alertId: 'alert-123' })
logic.mount()
diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.ts
index d1105a56736b..f0afc807c950 100644
--- a/products/alerts/frontend/logic/alertNotificationLogic.ts
+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts
@@ -41,8 +41,9 @@ export interface alertNotificationLogicValues {
currentProjectId: number | null // projectLogic
existingHogFunctions: HogFunctionType[]
existingHogFunctionsLoading: boolean
- firstSlackIntegration: IntegrationType | undefined
pendingNotifications: PendingAlertNotification[]
+ selectedSlackIntegration: IntegrationType | undefined
+ selectedSlackIntegrationId: number | null
selectedType: AlertNotificationType
slackChannelValue: string | null
webhookUrl: string
@@ -188,6 +189,9 @@ export interface alertNotificationLogicActions {
setPendingNotifications: (notifications: PendingAlertNotification[]) => {
notifications: PendingAlertNotification[]
}
+ setSelectedSlackIntegrationId: (selectedSlackIntegrationId: number | null) => {
+ selectedSlackIntegrationId: number | null
+ }
setSelectedType: (selectedType: AlertNotificationType) => {
selectedType: AlertNotificationType
}
@@ -203,7 +207,10 @@ export interface alertNotificationLogicActions {
export interface alertNotificationLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
- firstSlackIntegration: (slackIntegrations: IntegrationType[] | undefined) => IntegrationType | undefined
+ selectedSlackIntegration: (
+ slackIntegrations: IntegrationType[] | undefined,
+ selectedSlackIntegrationId: number | null
+ ) => IntegrationType | undefined
}
}
@@ -232,6 +239,9 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
deleteExistingHogFunction: (hogFunction: HogFunctionType) => ({ hogFunction }),
createPendingHogFunctions: (alertId: string, alertName?: string) => ({ alertId, alertName }),
setSelectedType: (selectedType: AlertNotificationType) => ({ selectedType }),
+ setSelectedSlackIntegrationId: (selectedSlackIntegrationId: number | null) => ({
+ selectedSlackIntegrationId,
+ }),
setSlackChannelValue: (slackChannelValue: string | null) => ({ slackChannelValue }),
setWebhookUrl: (webhookUrl: string) => ({ webhookUrl }),
}),
@@ -252,6 +262,13 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
setSlackChannelValue: (_, { slackChannelValue }) => slackChannelValue,
// Reset the input when switching destination type so stale values don't carry over.
setSelectedType: () => null,
+ setSelectedSlackIntegrationId: () => null,
+ },
+ ],
+ selectedSlackIntegrationId: [
+ null as number | null,
+ {
+ setSelectedSlackIntegrationId: (_, { selectedSlackIntegrationId }) => selectedSlackIntegrationId,
},
],
webhookUrl: [
@@ -277,10 +294,13 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
}),
selectors({
- // Use first available Slack integration to determine if Slack should be the default notification type
- firstSlackIntegration: [
- (s) => [s.slackIntegrations],
- (slackIntegrations: IntegrationType[] | undefined): IntegrationType | undefined => slackIntegrations?.[0],
+ selectedSlackIntegration: [
+ (s) => [s.slackIntegrations, s.selectedSlackIntegrationId],
+ (
+ slackIntegrations: IntegrationType[] | undefined,
+ selectedSlackIntegrationId: number | null
+ ): IntegrationType | undefined =>
+ slackIntegrations?.find((integration) => integration.id === selectedSlackIntegrationId),
],
}),
@@ -304,10 +324,30 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
})),
listeners(({ actions, values, props }) => ({
- loadIntegrationsSuccess: () => {
- if (!values.firstSlackIntegration) {
+ loadIntegrationsSuccess: ({ integrations }) => {
+ const availableSlackIntegrations = integrations.filter((integration) => integration.kind === 'slack')
+ const selectedIntegrationIsAvailable = availableSlackIntegrations.some(
+ (integration) => integration.id === values.selectedSlackIntegrationId
+ )
+
+ if (!selectedIntegrationIsAvailable) {
+ actions.setSelectedSlackIntegrationId(availableSlackIntegrations[0]?.id ?? null)
+ }
+ if (availableSlackIntegrations.length === 0) {
actions.setSelectedType(ALERT_NOTIFICATION_TYPE_WEBHOOK)
}
+
+ // Drop any staged Slack notifications pointing at a workspace that's no longer
+ // connected — saving them would create a destination referencing a dead integration.
+ const availableIds = new Set(availableSlackIntegrations.map((integration) => integration.id))
+ const stillValidPending = values.pendingNotifications.filter(
+ (notification) =>
+ notification.type !== ALERT_NOTIFICATION_TYPE_SLACK ||
+ availableIds.has(notification.slackWorkspaceId)
+ )
+ if (stillValidPending.length !== values.pendingNotifications.length) {
+ actions.setPendingNotifications(stillValidPending)
+ }
},
deleteExistingHogFunction: async ({ hogFunction }) => {
// Resolve the type from the closure up front — after the delete the HogFunction is
@@ -324,11 +364,7 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
actions.loadExistingHogFunctions()
return
}
- // Capture only a delete that actually landed: the callback runs after the API
- // call resolves and not at all on failure, and we skip it on undo. Mirrors the
- // create event, which always carries a known type — so skip an unrecognized
- // template rather than emit a null type that can't be classified. A
- // delete-then-undo still counts once — acceptable for optimistic-undo analytics.
+ // Skip on undo and on unrecognized templates so this only counts confirmed deletes with a known type.
if (type) {
posthog.capture('insight alert destination deleted', {
alert_id: props.alertId,
@@ -352,10 +388,7 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
})
)
- // Capture one event per destination that was actually created, tagged with its type,
- // so adoption of each destination (Slack/Discord/Teams/webhook) is measurable. The
- // destination is a separate HogFunction, so no `alert created`/`alert updated` event
- // records it — this is the only signal that ties a destination type to an alert.
+ // No `alert created`/`alert updated` event captures destination type, so this is emitted per created destination instead.
results.forEach((result, i) => {
if (result.status === 'fulfilled') {
posthog.capture('insight alert destination created', {
@@ -375,7 +408,6 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
if (failures.length > 0) {
const labelForType = (type: AlertNotificationType): string =>
ALERT_NOTIFICATION_TYPE_OPTIONS.find((option) => option.value === type)?.label ?? type
- // Log each failure with its destination type + API error so the cause is diagnosable later.
failures.forEach(({ result, notification }) => {
console.error(
`Failed to create ${labelForType(notification.type)} alert notification`,
diff --git a/products/alerts/frontend/views/InlineAlertNotifications.tsx b/products/alerts/frontend/views/InlineAlertNotifications.tsx
index b38569955d35..924d94b5621c 100644
--- a/products/alerts/frontend/views/InlineAlertNotifications.tsx
+++ b/products/alerts/frontend/views/InlineAlertNotifications.tsx
@@ -1,10 +1,10 @@
import { useActions, useValues } from 'kea'
-import { useEffect } from 'react'
+import { ReactNode, useEffect, useState } from 'react'
-import { slackIntegrationLogic } from 'lib/integrations/slackIntegrationLogic'
+import api from 'lib/api'
import { urls } from 'scenes/urls'
-import { HogFunctionType, SlackChannelType } from '~/types'
+import { HogFunctionType, IntegrationType } from '~/types'
import {
AlertNotificationDestinationEditor,
@@ -23,22 +23,57 @@ import {
import { ALERT_NOTIFICATION_TYPE_OPTIONS, alertNotificationLogic } from '../logic/alertNotificationLogic'
-function resolveSlackChannelName(channelValue: string, slackChannels: SlackChannelType[]): string | null {
- const channelId = channelValue.split('|')[0]
- return slackChannels.find((channel) => channel.id === channelId)?.name ?? null
+// Fetched directly rather than through slackIntegrationLogic's loader: that loader keeps a
+// single last-result slot per workspace, so multiple destination rows in the same workspace
+// looking up different channels concurrently would cancel each other's requests.
+function SlackDestinationChannel({ workspaceId, channelId }: { workspaceId: number; channelId: string }): JSX.Element {
+ const [channelName, setChannelName] = useState<string | null>(null)
+
+ useEffect(() => {
+ let cancelled = false
+ api.integrations.slackChannelsById(workspaceId, channelId).then((res) => {
+ if (!cancelled) {
+ setChannelName(res.channels[0]?.name ?? null)
+ }
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [workspaceId, channelId])
+
+ return <>{channelName ? `#${channelName}` : 'channel'}</>
+}
+
+interface SlackDestinationInputs {
+ slack_workspace?: { value: number }
+ channel?: { value: string }
}
function getHogFunctionDestination(
hogFunction: HogFunctionType,
- slackChannels: SlackChannelType[]
-): { type: string; detail: string | null } {
- const channelValue = hogFunction.inputs?.channel?.value
- if (channelValue && typeof channelValue === 'string') {
- const channelName = resolveSlackChannelName(channelValue, slackChannels)
- return { type: 'Slack', detail: channelName ? `#${channelName}` : null }
- }
- if (channelValue) {
- return { type: 'Slack', detail: null }
+ slackIntegrations: IntegrationType[] | undefined
+): { type: string; detail: ReactNode } {
+ const inputs = hogFunction.inputs as SlackDestinationInputs | null | undefined
+ const channelId = inputs?.channel?.value
+ if (channelId) {
+ // Destinations from before `slack_workspace` existed can only be safely attributed to a
+ // workspace when exactly one is connected — with 2+, there's no way to know which one it
+ // was created against, so guessing would risk showing the wrong workspace/channel.
+ const workspaceId =
+ inputs?.slack_workspace?.value ?? (slackIntegrations?.length === 1 ? slackIntegrations[0].id : undefined)
+ if (workspaceId === undefined) {
+ return { type: 'Slack', detail: null }
+ }
+ const workspaceName = slackIntegrations?.find((integration) => integration.id === workspaceId)?.display_name
+ return {
+ type: 'Slack',
+ detail: (
+ <>
+ {workspaceName ?? 'Unknown workspace'} ·{' '}
+ <SlackDestinationChannel workspaceId={workspaceId} channelId={channelId} />
+ </>
+ ),
+ }
}
if (hogFunction.template_id === 'template-discord') {
const webhookUrl = hogFunction.inputs?.webhookUrl?.value
@@ -55,10 +90,17 @@ function getHogFunctionDestination(
return { type: hogFunction.name, detail: null }
}
-function getNotificationLabel(notification: PendingAlertNotification): string {
+function getNotificationLabel(
+ notification: PendingAlertNotification,
+ slackIntegrations: IntegrationType[] | undefined
+): string {
switch (notification.type) {
- case ALERT_NOTIFICATION_TYPE_SLACK:
- return `Slack: #${notification.slackChannelName ?? 'channel'}`
+ case ALERT_NOTIFICATION_TYPE_SLACK: {
+ const workspaceName = slackIntegrations?.find(
+ (integration) => integration.id === notification.slackWorkspaceId
+ )?.display_name
+ return `Slack: ${workspaceName ?? 'Unknown workspace'} · #${notification.slackChannelName ?? 'channel'}`
+ }
case ALERT_NOTIFICATION_TYPE_DISCORD:
return `Discord: ${notification.webhookUrl}`
case ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS:
@@ -126,7 +168,8 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
existingHogFunctions,
existingHogFunctionsLoading,
pendingNotifications,
- firstSlackIntegration,
+ slackIntegrations,
+ selectedSlackIntegration,
selectedType,
slackChannelValue,
webhookUrl,
@@ -136,29 +179,20 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
removePendingNotification,
deleteExistingHogFunction,
setSelectedType,
+ setSelectedSlackIntegrationId,
setSlackChannelValue,
setWebhookUrl,
} = useActions(logic)
- const slackLogic = slackIntegrationLogic({ id: firstSlackIntegration?.id ?? 0 })
- const { slackChannels } = useValues(slackLogic)
- const { loadAllSlackChannels } = useActions(slackLogic)
-
- useEffect(() => {
- if (firstSlackIntegration) {
- loadAllSlackChannels()
- }
- }, [firstSlackIntegration?.id, loadAllSlackChannels, firstSlackIntegration])
-
const buildPendingNotification = (): PendingAlertNotification | null => {
if (selectedType === ALERT_NOTIFICATION_TYPE_SLACK) {
- if (!slackChannelValue || !firstSlackIntegration) {
+ if (!slackChannelValue || !selectedSlackIntegration) {
return null
}
const [channelId, channelLabel] = slackChannelValue.split('|')
return {
type: ALERT_NOTIFICATION_TYPE_SLACK,
- slackWorkspaceId: firstSlackIntegration.id,
+ slackWorkspaceId: selectedSlackIntegration.id,
slackChannelId: channelId,
slackChannelName: channelLabel?.replace('#', '') ?? channelId,
}
@@ -189,7 +223,7 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
}
const existingDestinations: AlertNotificationDestinationView[] = existingHogFunctions.map((hogFunction) => {
- const destination = getHogFunctionDestination(hogFunction, slackChannels)
+ const destination = getHogFunctionDestination(hogFunction, slackIntegrations)
return {
key: hogFunction.id,
title: destination.type,
@@ -210,7 +244,7 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
const pendingDestinations: PendingAlertNotificationDestinationView[] = pendingNotifications.map(
(notification, index) => ({
key: `${notification.type}-${index}`,
- label: getNotificationLabel(notification),
+ label: getNotificationLabel(notification, slackIntegrations),
status: '(pending, click Save to apply)',
onRemove: () => removePendingNotification(index),
})
@@ -233,7 +267,9 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
}}
slack={{
notificationType: ALERT_NOTIFICATION_TYPE_SLACK,
- integration: firstSlackIntegration,
+ integrations: slackIntegrations,
+ integration: selectedSlackIntegration,
+ onIntegrationChange: setSelectedSlackIntegrationId,
channelValue: slackChannelValue,
onChannelValueChange: setSlackChannelValue,
}}
@@ -242,7 +278,7 @@ export function InlineAlertNotifications({ alertId }: InlineAlertNotificationsPr
onClick: handleAdd,
disabledReason: getAddDisabledReason(
selectedType,
- Boolean(firstSlackIntegration),
+ Boolean(selectedSlackIntegration),
slackChannelValue,
webhookUrl
),