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(workflows): support multiple Slack trigger channels (#95933)

Ben Whitebf1c6046ecf8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d0616fa6e9d7..5d0c3495f8cb 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2080,6 +2080,10 @@ snapshots:
hash: v1.k794b7964.c5f45d681dad559cdf8bed1c8e9d31c5dca4d0973e1fbf5d1515ab30c393b554.SYg7auYBsl2kTK9lzMylWzKKRJ9Bf3sT0lwtvlfXx24
components-slack-channel-picker--alphabetical--light:
hash: v1.k794b7964.726967267332758d5771d2230a569cf7a29bdb38d1244aeb8dcacd86f25f433e.n9EALYKR_pt88G2ZCdyZ4V12Br9qoNbP3w7j2bNQ0Wk
+ components-slack-channel-picker--multiple-selection--dark:
+ hash: v1.k794b7964.2706bc3f6a6a560eeb7c2a7b25b0feafb0438bb7f2b94aa6f584de1eed7338a2.WscXFEXWmTCQX3rgoirWxfA_iSvW47pO5ZaLo7TFx3U
+ components-slack-channel-picker--multiple-selection--light:
+ hash: v1.k794b7964.ab1f574ecf1b582f420f90a56175b32bb1f76c585a6aa79a37d3bb351d21f20c.iPJrGKVub6zHD-M3h6qSWNrHWiqyBOXaSVMB1w1d_-E
components-slack-channel-picker--recently-subscribed-first--dark:
hash: v1.k794b7964.de1b275c97b6eac538ac35f64bf4cf3ec79f224cf500d0078f748c063eb83601.qqYmyCsR4ryfUqltT9sX9UikOHaAkMvWoWGDrQZ164s
components-slack-channel-picker--recently-subscribed-first--light:
diff --git a/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx b/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx
index 8670b6b4ebe8..bfbd4b65d95c 100644
--- a/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx
+++ b/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx
@@ -2,7 +2,7 @@ import { Meta, StoryObj } from '@storybook/react'
import { waitFor, within } from '@testing-library/dom'
import userEvent from '@testing-library/user-event'
import { useActions, useValues } from 'kea'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { LemonTag } from '@posthog/lemon-ui'
@@ -72,6 +72,21 @@ function OrderingScene({ recentlySubscribedChannelIds }: { recentlySubscribedCha
)
}
+function MultipleSelectionScene(): JSX.Element {
+ const [selectedChannels, setSelectedChannels] = useState(['C1|#alerts', 'C5|#incidents'])
+
+ return (
+ <div className="p-4 max-w-md">
+ <SlackChannelPicker
+ integration={integration}
+ mode="multiple"
+ value={selectedChannels}
+ onChange={setSelectedChannels}
+ />
+ </div>
+ )
+}
+
type StoryArgs = { recentlySubscribedChannelIds: string[] }
const meta: Meta<StoryArgs> = {
@@ -107,6 +122,10 @@ export const RecentlySubscribedFirst: Story = {
args: { recentlySubscribedChannelIds: ['C4', 'C1'] },
}
+export const MultipleSelection: Story = {
+ render: () => <MultipleSelectionScene />,
+}
+
// Typing a channel name and clicking away drops the search, because the picker takes an option
// rather than free text. The state below is what tells the user their channel is still unset.
export const SearchDroppedOnBlur: Story = {
diff --git a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
index f6692a195a90..d2b853badd73 100644
--- a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
+++ b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
@@ -46,14 +46,25 @@ const CHANNELS = [
// A channel whose ID is not returned by the bulk /channels endpoint — simulating a workspace
// where the saved channel falls beyond the first page that the backend returns.
-const OFF_PAGE_CHANNEL = {
- id: 'COFFPAGE9XX',
- name: 'off-page-channel',
- is_private: false,
- is_member: true,
- is_ext_shared: false,
- is_private_without_access: false,
-}
+const OFF_PAGE_CHANNELS = [
+ {
+ id: 'COFFPAGE9XX',
+ name: 'off-page-channel',
+ is_private: false,
+ is_member: true,
+ is_ext_shared: false,
+ is_private_without_access: false,
+ },
+ {
+ id: 'COFFPAGE8XX',
+ name: 'another-off-page-channel',
+ is_private: false,
+ is_member: true,
+ is_ext_shared: false,
+ is_private_without_access: false,
+ },
+]
+const OFF_PAGE_CHANNEL = OFF_PAGE_CHANNELS[0]
// Typing a channel name and then clicking away is the interaction that drops a search. Two cases
// below start from it and differ only in what they assert next.
@@ -87,7 +98,7 @@ describe('SlackChannelPicker', () => {
}
const match =
CHANNELS.find((c) => c.id === channelId) ??
- (OFF_PAGE_CHANNEL.id === channelId ? OFF_PAGE_CHANNEL : null)
+ OFF_PAGE_CHANNELS.find((c) => c.id === channelId)
return [200, { channels: match ? [match] : [] }]
}
channelsRequestSearchQueries.push(search)
@@ -168,7 +179,6 @@ describe('SlackChannelPicker', () => {
</Provider>
)
- // loadSlackChannelById has a 500ms breakpoint before fetching, so wait generously.
await waitFor(
() => {
expect(channelIdLookups).toContain('COFFPAGE9XX')
@@ -203,6 +213,27 @@ describe('SlackChannelPicker', () => {
)
})
+ it('resolves every saved channel outside the loaded page in multiple mode', async () => {
+ const { container } = render(
+ <Provider>
+ <SlackChannelPicker
+ integration={INTEGRATION}
+ mode="multiple"
+ value={OFF_PAGE_CHANNELS.map((channel) => channel.id)}
+ onChange={jest.fn()}
+ disabled
+ />
+ </Provider>
+ )
+
+ await waitFor(() => {
+ expect(channelIdLookups).toEqual(expect.arrayContaining(OFF_PAGE_CHANNELS.map((channel) => channel.id)))
+ for (const channel of OFF_PAGE_CHANNELS) {
+ expect(container).toHaveTextContent(`#${channel.name}`)
+ }
+ })
+ })
+
it('does not fire a direct lookup when there is no saved value', async () => {
render(
<Provider>
@@ -214,8 +245,6 @@ describe('SlackChannelPicker', () => {
await waitFor(() => {
expect(channelsRequestSearchQueries).toEqual([''])
})
- // Wait past the by-id breakpoint window so a stray call would have surfaced by now.
- await new Promise((resolve) => setTimeout(resolve, 800))
expect(channelIdLookups).toEqual([])
})
@@ -404,6 +433,30 @@ describe('SlackChannelPicker', () => {
expect(screen.queryByText('No channel selected. Pick one from the list.')).toBeNull()
})
+ it('keeps selected channels when another channel is added in multiple mode', async () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ <Provider>
+ <SlackChannelPicker
+ integration={INTEGRATION}
+ mode="multiple"
+ value={['C0B6HUH9FUH|#test-slack-notifications']}
+ onChange={onChange}
+ />
+ </Provider>
+ )
+ await waitFor(() => {
+ expect(channelsRequestSearchQueries).toEqual([''])
+ })
+
+ const input = container.querySelector<HTMLInputElement>('input[data-attr="select-slack-channel"]')!
+ await userEvent.click(input)
+ await userEvent.type(input, 'general')
+ await userEvent.click(await screen.findByText('#general'))
+
+ expect(onChange).toHaveBeenCalledWith(['C0B6HUH9FUH|#test-slack-notifications', 'C111111111|#general'])
+ })
+
it('still searches when the user actually types a different value', async () => {
// Render without an initial value so the input starts empty and typing isn't appended
// to LemonInputSelect's auto-fill of an existing selection.
diff --git a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
index 8efb426ac3b9..055ef7c875ed 100644
--- a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
+++ b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
LemonBanner,
@@ -94,23 +94,25 @@ const withoutInaccessiblePrivateChannels = (
): LemonInputSelectOption[] => {
return (options ?? []).filter((option) => {
const channelId = slackChannelId(option.key)
- return !isPrivateChannelWithoutAccess(channelId) || visibleIds.includes(channelId)
+ return (
+ !isPrivateChannelWithoutAccess(channelId) ||
+ visibleIds.some((visibleId) => visibleId && slackChannelId(visibleId) === channelId)
+ )
})
}
-// A saved channel beyond the loaded page has no option of its own, so add one labelled by name.
-// Without it the picker renders the raw composite value.
-const withSavedChannelOption = (
+// Saved channels beyond the loaded page need fallback options so their selections stay readable.
+const withSavedChannelOptions = (
options: LemonInputSelectOption[],
- savedValue: string | null | undefined
+ savedValues: string[]
): LemonInputSelectOption[] => {
- if (!savedValue || options.some((option) => option.key === savedValue)) {
- return options
- }
- return [
- ...options,
- { key: savedValue, label: savedValue.includes('|') ? savedValue.split('|')[1] : 'Slack channel' },
- ]
+ const missingOptions = savedValues
+ .filter((savedValue) => !options.some((option) => option.key === savedValue))
+ .map((savedValue) => ({
+ key: savedValue,
+ label: savedValue.includes('|') ? savedValue.split('|')[1] : 'Slack channel',
+ }))
+ return [...options, ...missingOptions]
}
const getSlackUserOptions = (slackUsers: SlackUserApi[]): LemonInputSelectOption[] => {
@@ -305,15 +307,13 @@ export function SlackUserPicker({
)
}
-// Everything the picker reports about the current selection and the loaded list. Reads the same
-// keyed logic as the picker rather than taking eight props for values it can select itself.
function SlackChannelPickerNotices({
integration,
- value,
+ values,
showUnselectedSearchError,
}: {
integration: IntegrationType
- value?: string
+ values: string[]
showUnselectedSearchError: boolean
}): JSX.Element {
const logic = slackIntegrationLogic({ id: integration.id })
@@ -327,7 +327,8 @@ function SlackChannelPickerNotices({
} = useValues(logic)
const { loadAllSlackChannels } = useActions(logic)
- const showSlackMembershipWarning = value && isMemberOfSlackChannel(value) === false
+ const showSlackMembershipWarning = values.some((value) => isMemberOfSlackChannel(value) === false)
+ const showPrivateChannelWarning = values.some((value) => isPrivateChannelWithoutAccess(value))
return (
<>
@@ -351,10 +352,11 @@ function SlackChannelPickerNotices({
<LemonBanner type="info">
<div className="flex gap-2 items-center">
<span>
- The PostHog Slack App is not in this channel. Please add it to the channel otherwise
- Subscriptions will fail to be delivered.{' '}
+ {values.length > 1
+ ? 'The PostHog Slack app is not in every selected channel. Add it to each channel before continuing. '
+ : 'The PostHog Slack app is not in this channel. Add it to the channel before continuing. '}
<Link to="https://posthog.com/docs/webhooks/slack" target="_blank">
- See the Docs for more information
+ See the docs for more information
</Link>
</span>
<LemonButton
@@ -367,10 +369,10 @@ function SlackChannelPickerNotices({
</LemonButton>
</div>
</LemonBanner>
- ) : isPrivateChannelWithoutAccess(value ?? '') ? (
+ ) : showPrivateChannelWarning ? (
<LemonBanner type="info">
- This is a private Slack channel. Ask{' '}
- <ProfilePicture user={integration.created_by} showName size="sm" /> or connect your own Slack
+ {values.length > 1 ? 'One or more selected Slack channels are' : 'This Slack channel is'} private.
+ Ask <ProfilePicture user={integration.created_by} showName size="sm" /> or connect your own Slack
account to configure private channels.
</LemonBanner>
) : null}
@@ -378,20 +380,48 @@ function SlackChannelPickerNotices({
)
}
-export type SlackChannelPickerProps = {
+type SlackChannelPickerCommonProps = {
integration: IntegrationType
- value?: string
- onChange?: (value: string | null) => void
disabled?: boolean
}
-export function SlackChannelPicker({ onChange, value, integration, disabled }: SlackChannelPickerProps): JSX.Element {
+export type SlackChannelPickerProps = SlackChannelPickerCommonProps &
+ (
+ | {
+ mode?: 'single'
+ value?: string
+ onChange?: (value: string | null) => void
+ }
+ | {
+ mode: 'multiple'
+ value?: string[]
+ onChange?: (value: string[]) => void
+ }
+ )
+
+export function SlackChannelPicker(props: SlackChannelPickerProps): JSX.Element {
+ const { integration, disabled } = props
+ const values = useMemo(
+ () => (props.mode === 'multiple' ? (props.value ?? []) : props.value ? [props.value] : []),
+ [props.mode, props.value]
+ )
+ const onValuesChange = useCallback(
+ (nextValues: string[]): void => {
+ if (props.mode === 'multiple') {
+ props.onChange?.(nextValues)
+ } else {
+ props.onChange?.(nextValues[0] ?? null)
+ }
+ },
+ [props.mode, props.onChange]
+ )
const logic = slackIntegrationLogic({ id: integration.id })
const {
slackChannels,
slackChannelsForPicker,
allSlackChannelsLoading,
slackChannelByIdLoading,
+ attemptedSlackChannelIds,
isPrivateChannelWithoutAccess,
getChannelRefreshButtonDisabledReason,
} = useValues(logic)
@@ -426,19 +456,21 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
// A pasted id that is still resolving is a pending selection, not a dropped search, so hold
// the message until the lookup settles.
- const showUnselectedSearchError = blurredWithoutSelection && !value && !pastedChannelId
-
- const modifiedValue = useMemo(() => {
- if (value?.split('|').length === 1) {
- const channel = slackChannels.find((x: SlackChannelType) => x.id === value)
+ const showUnselectedSearchError = blurredWithoutSelection && values.length === 0 && !pastedChannelId
- if (channel) {
- return `${channel.id}|#${channel.name}`
- }
- }
-
- return value
- }, [value, slackChannels])
+ const modifiedValues = useMemo(
+ () =>
+ values.map((value) => {
+ if (value.split('|').length === 1) {
+ const channel = slackChannels.find((x: SlackChannelType) => x.id === value)
+ if (channel) {
+ return `${channel.id}|#${channel.name}`
+ }
+ }
+ return value
+ }),
+ [values, slackChannels]
+ )
useEffect(() => {
// Multiple pickers can mount for the same workspace (e.g. team + per-user channel), so skip
@@ -474,36 +506,43 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
}
setPastedChannelId(null)
clearDroppedSearch()
- if (slackChannelId(value ?? '') !== channel.id) {
- onChange?.(`${channel.id}|#${channel.name}`)
+ if (!values.some((value) => slackChannelId(value) === channel.id)) {
+ const selectedChannel = `${channel.id}|#${channel.name}`
+ onValuesChange(props.mode === 'multiple' ? [...values, selectedChannel] : [selectedChannel])
}
- }, [pastedChannelId, slackChannels, slackChannelByIdLoading, value, onChange])
+ }, [pastedChannelId, slackChannels, slackChannelByIdLoading, values, props.mode, onValuesChange])
- // Read-only pickers still need a direct lookup because the saved channel may not be on the first page.
+ // Read-only pickers still need direct lookups because saved channels may not be on the first page.
useEffect(() => {
- if (value) {
+ for (const value of values) {
const channelId = value.split('|')[0]
- if (channelId) {
+ if (
+ channelId &&
+ !slackChannels.some((channel: SlackChannelType) => channel.id === channelId) &&
+ !attemptedSlackChannelIds[channelId]
+ ) {
loadSlackChannelById(channelId)
}
}
- }, [loadSlackChannelById, value])
-
- const options = withSavedChannelOption(
- withoutInaccessiblePrivateChannels(rawSlackChannelOptions, isPrivateChannelWithoutAccess, [value, localValue]),
- modifiedValue
+ }, [attemptedSlackChannelIds, loadSlackChannelById, slackChannels, values])
+
+ const options = withSavedChannelOptions(
+ withoutInaccessiblePrivateChannels(rawSlackChannelOptions, isPrivateChannelWithoutAccess, [
+ ...values,
+ localValue,
+ ]),
+ modifiedValues
)
return (
<>
<LemonInputSelect
onChange={(val) => {
- const key = val[0] ?? null
// LemonInputSelect blurs the input before it reports a selection, so onBlur has
// already flagged the search as dropped by the time this runs. Both happen on
// one synchronous call stack, so this reset wins and no error renders.
clearDroppedSearch()
- if (key) {
+ for (const key of val) {
// Pin into the by-id slot so the post-select bulk reload can't drop the
// channel from slackChannels and unresolve the label.
const [channelId] = key.split('|')
@@ -512,7 +551,7 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
loadSlackChannelByIdSuccess(channel)
}
}
- onChange?.(key)
+ onValuesChange(props.mode === 'multiple' ? val : val.slice(0, 1))
}}
onInputChange={(val) => {
if (val) {
@@ -524,7 +563,7 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
if (SLACK_CHANNEL_ID_PATTERN.test(idCandidate)) {
loadSlackChannelById(idCandidate)
setPastedChannelId(idCandidate)
- } else if (val !== modifiedValue) {
+ } else if (!modifiedValues.includes(val)) {
setPastedChannelId(null)
// LemonInputSelect auto-fills the input with the selected option's key on
// focus (see LemonInputSelect._onFocus). Don't treat that auto-fill as a
@@ -542,14 +581,14 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
hasActiveSearchRef.current = false
}
}}
- value={modifiedValue ? [modifiedValue] : []}
+ value={modifiedValues}
onFocus={() => !slackChannels.length && !allSlackChannelsLoading && loadAllSlackChannels()}
onBlur={() => setBlurredWithoutSelection(hasUnselectedSearchRef.current)}
status={showUnselectedSearchError ? 'danger' : 'default'}
disabled={disabled}
- mode="single"
+ mode={props.mode ?? 'single'}
data-attr="select-slack-channel"
- placeholder="Select a channel..."
+ placeholder={props.mode === 'multiple' ? 'Select channels...' : 'Select a channel...'}
action={{
children: <span className="Link">Refresh channels</span>,
onClick: () => loadAllSlackChannels(true),
@@ -572,7 +611,7 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
<SlackChannelPickerNotices
integration={integration}
- value={value}
+ values={values}
showUnselectedSearchError={showUnselectedSearchError}
/>
</>
diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.ts b/frontend/src/lib/integrations/slackIntegrationLogic.ts
index b30a9facc19f..99067f39877b 100644
--- a/frontend/src/lib/integrations/slackIntegrationLogic.ts
+++ b/frontend/src/lib/integrations/slackIntegrationLogic.ts
@@ -26,8 +26,8 @@ const SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE =
export interface slackIntegrationLogicValues {
preflight: PreflightStatus | null // preflightLogic
siteUrlMisconfigured: boolean // preflightLogic
- _fetchedSlackChannelById: SlackChannelType | null
_fetchedSlackChannels: SlackChannelType[]
+ _fetchedSlackChannelsById: Record<string, SlackChannelType>
_fetchedSlackUsersById: Record<string, SlackUserApi>
allSlackChannels: {
channels: SlackChannelType[]
@@ -37,6 +37,7 @@ export interface slackIntegrationLogicValues {
allSlackChannelsLoading: boolean
allSlackUsers: SlackUsersResponseApi | null
allSlackUsersLoading: boolean
+ attemptedSlackChannelIds: Record<string, true>
attemptedSlackUserIds: Record<string, true>
getChannelRefreshButtonDisabledReason: () => string
getUsersRefreshButtonDisabledReason: () => string
@@ -178,7 +179,7 @@ export interface slackIntegrationLogicMeta {
__keaTypeGenInternalSelectorTypes: {
slackChannels: (
_fetchedSlackChannels: SlackChannelType[],
- _fetchedSlackChannelById: SlackChannelType | null
+ _fetchedSlackChannelsById: Record<string, SlackChannelType>
) => SlackChannelType[]
slackUsers: (
allSlackUsers: SlackUsersResponseApi | null,
@@ -310,8 +311,7 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
slackChannelById: [
null as SlackChannelType | null,
{
- loadSlackChannelById: async ({ channelId }, breakpoint) => {
- await breakpoint(500)
+ loadSlackChannelById: async ({ channelId }) => {
try {
const res = await api.integrations.slackChannelsById(props.id, channelId)
// The by-id endpoint always calls Slack live, so a success is real proof
@@ -339,10 +339,18 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
loadAllSlackChannelsSuccess: (prev, { allSlackChannels }) => allSlackChannels?.channels ?? prev,
},
],
- _fetchedSlackChannelById: [
- null as SlackChannelType | null,
+ attemptedSlackChannelIds: [
+ {} as Record<string, true>,
+ {
+ loadSlackChannelById: (state, { channelId }) => ({ ...state, [channelId]: true }),
+ loadAllSlackChannels: (state, { forceRefresh }) => (forceRefresh ? {} : state),
+ },
+ ],
+ _fetchedSlackChannelsById: [
+ {} as Record<string, SlackChannelType>,
{
- loadSlackChannelByIdSuccess: (_, { slackChannelById }) => slackChannelById,
+ loadSlackChannelByIdSuccess: (state, { slackChannelById }) =>
+ slackChannelById ? { ...state, [slackChannelById.id]: slackChannelById } : state,
},
],
attemptedSlackUserIds: [
@@ -387,16 +395,16 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
selectors({
slackChannels: [
- (s) => [s._fetchedSlackChannels, s._fetchedSlackChannelById],
+ (s) => [s._fetchedSlackChannels, s._fetchedSlackChannelsById],
(
_fetchedSlackChannels: SlackChannelType[],
- _fetchedSlackChannelById: SlackChannelType | null
+ _fetchedSlackChannelsById: Record<string, SlackChannelType>
): SlackChannelType[] => {
- const channels = [..._fetchedSlackChannels]
- if (_fetchedSlackChannelById && !channels.find((x) => x.id === _fetchedSlackChannelById.id)) {
- channels.push(_fetchedSlackChannelById)
- }
- return channels
+ const listedIds = new Set(_fetchedSlackChannels.map((channel) => channel.id))
+ return [
+ ..._fetchedSlackChannels,
+ ...Object.values(_fetchedSlackChannelsById).filter((channel) => !listedIds.has(channel.id)),
+ ]
},
],
slackUsers: [
diff --git a/products/workflows/backend/test/test_slack_trigger_filters.py b/products/workflows/backend/test/test_slack_trigger_filters.py
index 3a8a4ddfee05..b51b7007e35b 100644
--- a/products/workflows/backend/test/test_slack_trigger_filters.py
+++ b/products/workflows/backend/test/test_slack_trigger_filters.py
@@ -47,8 +47,12 @@ class TestSlackTriggerFilters(ClickhouseTestMixin, APIBaseTest):
bytecode = json.loads(json.dumps(create_bytecode(expr).bytecode))
return execute_bytecode(bytecode, globals or SLACK_MESSAGE_GLOBALS).result is True
- def test_channel_filter_matches_the_bare_id(self):
- assert self._matches([_prop("channel", ["C0ALERTS"], "exact")])
+ def test_channel_filter_matches_any_listed_bare_id(self):
+ properties = [_prop("channel", ["C0ALERTS", "C0INCIDENTS"], "exact")]
+
+ assert self._matches(properties)
+ assert self._matches(properties, _event(channel="C0INCIDENTS"))
+ assert not self._matches(properties, _event(channel="C0OTHER"))
def test_channel_filter_does_not_match_the_picker_composite(self):
# The picker identifies a channel as `C123|#name`; storing that verbatim compiled a filter
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts
index 3bba8f5e6c81..961a7679161d 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts
@@ -151,7 +151,7 @@ describe('hogFlowEditorTestLogic', () => {
describe('createExampleEventForTrigger', () => {
it('builds a slack message example for Slack-connected triggers, seeded from the channel filter', () => {
const properties = encodeSlackFilters({
- channel: 'C0ALERTS|#alerts',
+ channels: ['C0ALERTS|#alerts', 'C0INCIDENTS|#incidents'],
posterMode: 'anyone',
posterIds: [],
topLevelOnly: false,
@@ -228,7 +228,7 @@ describe('hogFlowEditorTestLogic', () => {
],
])('seeds a sample that satisfies the %s poster filter', (posterMode, posterIds, assertion) => {
const properties = encodeSlackFilters({
- channel: 'C0ALERTS',
+ channels: ['C0ALERTS'],
posterMode: posterMode as any,
posterIds,
topLevelOnly: false,
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.test.ts
index 48a165940c04..da224dba0274 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.test.ts
@@ -25,7 +25,7 @@ describe('slack message trigger', () => {
// The editor reads its controls back out of the stored filters, so a mode that encodes
// to something decode can't recognize silently resets the control on reopen.
const filters = {
- channel: 'C0ALERTS',
+ channels: ['C0ALERTS'],
posterMode: mode,
posterIds: ids,
topLevelOnly: true,
@@ -37,7 +37,7 @@ describe('slack message trigger', () => {
it('keeps filters the native controls do not own', () => {
const custom = { key: 'text', value: ['fire'], operator: PropertyOperator.IContains, type: 'event' }
const encoded = encodeSlackFilters({
- channel: 'C0ALERTS',
+ channels: ['C0ALERTS'],
posterMode: 'people',
posterIds: [],
topLevelOnly: false,
@@ -48,24 +48,24 @@ describe('slack message trigger', () => {
expect(decodeSlackFilters(encoded).additional).toEqual([custom])
})
- it('reduces the picker composite to a channel id', () => {
+ it('reduces picker composites to channel ids', () => {
// The picker round-trips `C123|#name`; the event carries `C123`, so storing the
// composite compiles a filter that matches nothing.
const encoded = encodeSlackFilters({
- channel: 'C0ALERTS|#alerts',
+ channels: ['C0ALERTS|#alerts', 'C0INCIDENTS|#incidents'],
posterMode: 'anyone',
posterIds: [],
topLevelOnly: false,
additional: [],
})
- expect(decodeSlackFilters(encoded).channel).toBe('C0ALERTS')
+ expect(decodeSlackFilters(encoded).channels).toEqual(['C0ALERTS', 'C0INCIDENTS'])
})
it('separates top-level posts on thread_ts, not the boolean', () => {
// is_thread_reply is a real boolean on the event, and comparing it against a string
// would never match. Absence of thread_ts is what marks a top-level post.
const encoded = encodeSlackFilters({
- channel: null,
+ channels: [],
posterMode: 'anyone',
posterIds: [],
topLevelOnly: true,
@@ -82,7 +82,7 @@ describe('slack message trigger', () => {
// The control re-derives from the stored filters on every render, so a mode that
// encodes to nothing snaps straight back to "anyone" the moment you pick it.
const encoded = encodeSlackFilters({
- channel: null,
+ channels: [],
posterMode: mode,
posterIds: [],
topLevelOnly: false,
@@ -96,7 +96,11 @@ describe('slack message trigger', () => {
describe('registry entry', () => {
it.each([
{ name: 'no channel filter', properties: [], valid: false },
- { name: 'channel filter present', properties: [{ key: 'channel', value: ['C0ALERTS'] }], valid: true },
+ {
+ name: 'channel filter present',
+ properties: [{ key: 'channel', value: ['C0ALERTS', 'C0INCIDENTS'] }],
+ valid: true,
+ },
{ name: 'other filters alone', properties: [{ key: 'text', value: ['fire'] }], valid: false },
])('validate returns valid=$valid for $name', ({ properties, valid }) => {
const result = getTriggerType().validate!({
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.tsx
index bcb4bd1de572..9ddf2a42ea61 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.tsx
@@ -80,8 +80,8 @@ function StepTriggerConfigurationSlackMessage({ node }: { node: any }): JSX.Elem
return (
<LemonBanner type="warning" className="w-full">
<p className="mb-0">
- This trigger needs a Slack connection, and this project doesn't have one yet. Connect Slack, invite
- the bot to a channel, then come back and pick it.{' '}
+ This trigger needs a Slack connection, and this project doesn't have one yet. Connect Slack, add the
+ bot to the channels you want to use, then come back and select them.{' '}
<Link to={urls.settings('project-integrations')} className="font-semibold">
Connect Slack
</Link>
@@ -93,19 +93,20 @@ function StepTriggerConfigurationSlackMessage({ node }: { node: any }): JSX.Elem
return (
<div className="flex flex-col gap-2 w-full">
<p className="mb-0 text-sm text-muted-alt">
- This workflow runs once for each message posted in the channel you pick. Runs have no associated person,
+ This workflow runs once for each message posted in any selected channel. Runs have no associated person,
so person-dependent steps are unavailable.
</p>
<LemonField.Pure
- label="Channel"
+ label="Channels"
error={validationResult?.errors?.channel}
info="PostHog only receives messages from channels the Slack bot has been invited to."
>
<SlackChannelPicker
integration={integrations[0]}
- value={filters.channel ?? undefined}
- onChange={(value) => update({ channel: value })}
+ mode="multiple"
+ value={filters.channels}
+ onChange={(channels) => update({ channels })}
/>
</LemonField.Pure>
@@ -192,7 +193,7 @@ registerTriggerType({
source: 'internal-events',
events: [{ id: '$slack_message_received', type: 'events' }],
properties: encodeSlackFilters({
- channel: null,
+ channels: [],
posterMode: 'people',
posterIds: [],
topLevelOnly: true,
@@ -205,8 +206,8 @@ registerTriggerType({
return null
}
const filters = decodeSlackFilters(config.filters?.properties)
- if (!filters.channel) {
- return { valid: false, errors: { channel: 'Please pick a Slack channel' } }
+ if (!filters.channels.length) {
+ return { valid: false, errors: { channel: 'Select at least one Slack channel' } }
}
const wantsIds = filters.posterMode === 'specific_people' || filters.posterMode === 'specific_apps'
if (wantsIds && !filters.posterIds.length) {
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slackTriggerFilters.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slackTriggerFilters.ts
index 750b524ac72b..88066351d260 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slackTriggerFilters.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slackTriggerFilters.ts
@@ -72,7 +72,7 @@ export const SLACK_POSTER_MODE_OPTIONS: { value: SlackPosterMode; label: string;
const OWNED_KEYS = new Set(['channel', 'user', 'bot_id', 'app_id', 'thread_ts'])
export interface SlackTriggerFilters {
- channel: string | null
+ channels: string[]
posterMode: SlackPosterMode
posterIds: string[]
topLevelOnly: boolean
@@ -129,7 +129,7 @@ export function decodeSlackFilters(properties: Record<string, any>[] | undefined
}
return {
- channel: values(channelEntry).length ? channelId(values(channelEntry)[0]) : null,
+ channels: values(channelEntry).map(channelId),
posterMode,
posterIds,
topLevelOnly: threadTs?.operator === PropertyOperator.IsNotSet,
@@ -140,8 +140,8 @@ export function decodeSlackFilters(properties: Record<string, any>[] | undefined
export function encodeSlackFilters(filters: SlackTriggerFilters): Record<string, any>[] {
const properties: Record<string, any>[] = []
- if (filters.channel) {
- properties.push(exact('channel', [channelId(filters.channel)]))
+ if (filters.channels.length) {
+ properties.push(exact('channel', filters.channels.map(channelId)))
}
switch (filters.posterMode) {
diff --git a/products/workflows/frontend/Workflows/hogflows/testEventFactory.ts b/products/workflows/frontend/Workflows/hogflows/testEventFactory.ts
index 3d34558047be..2c010856173c 100644
--- a/products/workflows/frontend/Workflows/hogflows/testEventFactory.ts
+++ b/products/workflows/frontend/Workflows/hogflows/testEventFactory.ts
@@ -70,7 +70,7 @@ export const createExampleSlackMessageEvent = (
): CyclotronJobInvocationGlobals => {
const resolvedTeamId = teamId || 1
const projectUrl = `${window.location.origin}/project/${resolvedTeamId}`
- const channel = filters.channel ?? 'C0123456789'
+ const channel = filters.channels?.[0] ?? 'C0123456789'
const posterId = filters.posterIds?.[0]
// Defaults satisfy 'anyone' and 'people' (no bot_id); each other native poster mode
// overrides only the field its own filter reads.
diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.md
index 862caf1eee8c..96aaaec93a8e 100644
--- a/products/workflows/skills/building-workflows/references/graph-schema.md
+++ b/products/workflows/skills/building-workflows/references/graph-schema.md
@@ -73,7 +73,7 @@ Discriminated on `config.type`:
- `tracking_pixel` — a bodyless `GET`, so read query params: `"inputs": { "event": { "value": "{request.query.ph_event}" }, "distinct_id": { "value": "{request.query.ph_distinct_id}" } }`. Body references resolve empty here and the pixel still returns its 200 GIF, so every hit is dropped with no error to retry on.
- `batch` — `{ "type": "batch", "filters": { "properties": [<cond>] } }`. The audience: person-property conditions and/or cohort references. **No event/action filters** (silently dropped, so rejected). Does not fire on enable — dispatch a one-off broadcast with `workflows-run-batch`, or make it **recurring** with `workflows-schedule-create` (attaches an RRULE schedule; each firing re-broadcasts to this same `config.filters.properties` audience). A recurring broadcast is a `batch` trigger plus a schedule. Editing `config.filters` pauses any schedule attached to it, since the confirmed recipient count no longer holds - preview again and re-create the cadence.
- `schedule` — `{ "type": "schedule" }`. One person-less run per occurrence, for jobs that act on their own (for example a "Create AI task" step). Attach the cadence with `workflows-schedule-create`; no audience preview is needed. Changing this trigger to `batch` pauses any schedule already attached, because that cadence was never sized against an audience - re-create it after the blast-radius preview.
-- `internal-event` (flag-gated) — `{ "type": "internal-event", "filters": { "source": "internal-events", "events": [{ "id": "<event>", "type": "events" }], "properties": [<cond>] } }`. Fires once for each matching event on the internal-events stream; `filters.events` must name at least one allowed event id. Runs have no associated person, so person-dependent steps are unavailable. Test-run with an event named in `filters.events` and no person; any other event name is skipped at the trigger. The Slack trigger is this with `$slack_message_received` in `filters.events`: the run's event carries properties `integration_id`, `channel`, `channel_type`, `slack_team_id`, `user`, `bot_id`, `app_id`, `subtype`, `text`, `ts`, `thread_ts`, `is_thread_reply`, `is_ext_shared_channel`, and `slack_event` (the raw Slack payload), and a workflow leaving draft must include an exact `channel` property filter. The GitHub trigger uses `$github_event_received` and requires exact `repository` and `event_type` filters.
+- `internal-event` (flag-gated) — `{ "type": "internal-event", "filters": { "source": "internal-events", "events": [{ "id": "<event>", "type": "events" }], "properties": [<cond>] } }`. Fires once for each matching event on the internal-events stream; `filters.events` must name at least one allowed event id. Runs have no associated person, so person-dependent steps are unavailable. Test-run with an event named in `filters.events` and no person; any other event name is skipped at the trigger. The Slack trigger is this with `$slack_message_received` in `filters.events`: the run's event carries properties `integration_id`, `channel`, `channel_type`, `slack_team_id`, `user`, `bot_id`, `app_id`, `subtype`, `text`, `ts`, `thread_ts`, `is_thread_reply`, `is_ext_shared_channel`, and `slack_event` (the raw Slack payload). A workflow leaving draft must include one exact `channel` property filter whose value contains one or more channel IDs; several IDs match any listed channel. The GitHub trigger uses `$github_event_received` and requires exact `repository` and `event_type` filters.
### Trigger masking (throttling an event trigger)