: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
fix(integrations): tell users when a typed Slack channel is dropped (#93088)
Paul D'Ambra24a784e198fb
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 01310122085d..34589507bb88 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2084,6 +2084,10 @@ snapshots:hash: v1.k794b7964.de1b275c97b6eac538ac35f64bf4cf3ec79f224cf500d0078f748c063eb83601.qqYmyCsR4ryfUqltT9sX9UikOHaAkMvWoWGDrQZ164scomponents-slack-channel-picker--recently-subscribed-first--light:hash: v1.k794b7964.54bc88c73e7d32bbab8a32b91162eab1fb1ba78215aa188aa748b65b9fb531b8.YkOXS4kFGcgECAArUGil25uNoJVbhGKe_zYYmpzzu44+ components-slack-channel-picker--search-dropped-on-blur--dark:+ hash: v1.k794b7964.29203af8ae5aa26d4990eb59d3c712c80fa5b154bdb8c6ca31806e711985b82f.BbkuhaxBbHeFVYjs-OwhfeWPkE0aYhGbKdeDCekxIYo+ components-slack-channel-picker--search-dropped-on-blur--light:+ hash: v1.k794b7964.e43a3c7ff18ddecbe2f0aae9a1ec02f012b37a7878cc24d276c6b595868dd007.Le4wa7PaPoGGlMQMjQddH1-ucxII2N5wMBeW3yf50FEcomponents-sparkline--bar-chart--dark:hash: v1.k794b7964.65da75bd15e9d0d9f2e575e4eb04e0aaafdb39e02dbc19ba5006cf3651cb792d.zeJ6dGjiWJ_9biIrGypyok73SsFJJ-NLmGNHZJDCJ-wcomponents-sparkline--bar-chart--light:diff --git a/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx b/frontend/src/lib/integrations/SlackChannelPicker.stories.tsxindex 31c9300075ee..ce1f2a601d25 100644--- a/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx+++ b/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx@@ -1,4 +1,6 @@import { Meta, StoryObj } from '@storybook/react'+import { within } from '@testing-library/dom'+import userEvent from '@testing-library/user-event'import { useActions, useValues } from 'kea'import { useEffect } from 'react'@@ -75,15 +77,20 @@ type StoryArgs = { recentlySubscribedChannelIds: string[] }const meta: Meta<StoryArgs> = {title: 'Components/Slack channel picker',parameters: { layout: 'fullscreen', viewMode: 'story' },- render: ({ recentlySubscribedChannelIds }) => {- useStorybookMocks({- get: {- '/api/projects/:id/integrations/:intId/channels': { channels },- '/api/environments/:id/integrations/:intId/channels': { channels },- },- })- return <OrderingScene recentlySubscribedChannelIds={recentlySubscribedChannelIds} />- },+ decorators: [+ function MocksDecorator(Story) {+ useStorybookMocks({+ get: {+ '/api/projects/:id/integrations/:intId/channels': { channels },+ '/api/environments/:id/integrations/:intId/channels': { channels },+ },+ })+ return <Story />+ },+ ],+ render: ({ recentlySubscribedChannelIds }) => (+ <OrderingScene recentlySubscribedChannelIds={recentlySubscribedChannelIds} />+ ),}export default meta@@ -99,3 +106,19 @@ export const Alphabetical: Story = {export const RecentlySubscribedFirst: Story = {args: { recentlySubscribedChannelIds: ['C4', 'C1'] },}++// 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 = {+ render: () => (+ <div className="p-4 max-w-md">+ <SlackChannelPicker integration={integration} onChange={() => {}} />+ </div>+ ),+ play: async ({ canvasElement }) => {+ const input = canvasElement.querySelector<HTMLInputElement>('input[data-attr="select-slack-channel"]')!+ await userEvent.type(input, 'general')+ await userEvent.click(canvasElement)+ await within(canvasElement).findByText('No channel selected. Pick one from the list.')+ },+}diff --git a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx b/frontend/src/lib/integrations/SlackChannelPicker.test.tsxindex b4e41d6b7280..b78262aefbd3 100644--- a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx+++ b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx@@ -55,6 +55,15 @@ const OFF_PAGE_CHANNEL = {is_private_without_access: false,}+// 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.+async function dropASearch(container: HTMLElement): Promise<void> {+ const input = container.querySelector<HTMLInputElement>('input[data-attr="select-slack-channel"]')!+ await userEvent.click(input)+ await userEvent.type(input, 'general')+ await userEvent.click(document.body)+}+describe('SlackChannelPicker', () => {let channelsRequestSearchQueries: (string | null)[] = []let channelIdLookups: string[] = []@@ -268,6 +277,122 @@ describe('SlackChannelPicker', () => {)})+ it('reports a dropped search when the user types a channel name and clicks away', async () => {+ // LemonInputSelect discards typed text on blur, so without this the input silently empties+ // itself and the user is left thinking the picker reset for no reason.+ const { container } = render(+ <Provider>+ <SlackChannelPicker integration={INTEGRATION} onChange={jest.fn()} />+ </Provider>+ )+ await waitFor(() => {+ expect(channelsRequestSearchQueries).toEqual([''])+ })++ await dropASearch(container)++ expect(await screen.findByText('No channel selected. Pick one from the list.')).toBeInTheDocument()+ })++ it('selects the channel when someone pastes its id', async () => {+ // Pasting an id is already an unambiguous choice, and the option it matches is labelled by+ // name, so leaving it unselected asks the user to recognize a channel they only have an id for.+ const onChange = jest.fn()+ const { container } = render(+ <Provider>+ <SlackChannelPicker integration={INTEGRATION} onChange={onChange} />+ </Provider>+ )++ const input = container.querySelector<HTMLInputElement>('input[data-attr="select-slack-channel"]')!+ await userEvent.click(input)+ // Only reachable through the by-id lookup: the bulk endpoint never returns this channel.+ await userEvent.paste(OFF_PAGE_CHANNEL.id)++ await waitFor(() => expect(onChange).toHaveBeenCalledWith(`${OFF_PAGE_CHANNEL.id}|#off-page-channel`), {+ timeout: 3000,+ })+ expect(screen.queryByText('No channel selected. Pick one from the list.')).toBeNull()+ })++ // The by-id lookup is not instant. Clicking away while it runs must not read as a dropped+ // search, and a paste that resolves to nothing must still say so.+ it.each([+ { settles: 'a channel', pastedId: OFF_PAGE_CHANNEL.id, reportsDroppedSearch: false },+ { settles: 'nothing', pastedId: 'CNOSUCHCHAN', reportsDroppedSearch: true },+ ])('pasting an id that settles on $settles, then clicking away', async ({ pastedId, reportsDroppedSearch }) => {+ const onChange = jest.fn()+ const { container } = render(+ <Provider>+ <SlackChannelPicker integration={INTEGRATION} onChange={onChange} />+ </Provider>+ )++ const input = container.querySelector<HTMLInputElement>('input[data-attr="select-slack-channel"]')!+ await userEvent.click(input)+ await userEvent.paste(pastedId)+ await userEvent.click(document.body)++ // The lookup is still in flight here, so neither outcome may show the message yet.+ expect(screen.queryByText('No channel selected. Pick one from the list.')).toBeNull()++ if (reportsDroppedSearch) {+ expect(+ await screen.findByText('No channel selected. Pick one from the list.', undefined, { timeout: 3000 })+ ).toBeInTheDocument()+ expect(onChange).not.toHaveBeenCalled()+ } else {+ await waitFor(() => expect(onChange).toHaveBeenCalledWith(`${OFF_PAGE_CHANNEL.id}|#off-page-channel`), {+ timeout: 3000,+ })+ expect(screen.queryByText('No channel selected. Pick one from the list.')).toBeNull()+ }+ })++ it('drops the reported search when the caller swaps the workspace', async () => {+ // Some callers swap the integration without unmounting, so an error raised against the old+ // workspace would otherwise sit over a picker now listing a different workspace's channels.+ const { container, rerender } = render(+ <Provider>+ <SlackChannelPicker integration={INTEGRATION} onChange={jest.fn()} />+ </Provider>+ )+ await dropASearch(container)+ expect(await screen.findByText('No channel selected. Pick one from the list.')).toBeInTheDocument()++ rerender(+ <Provider>+ <SlackChannelPicker integration={{ ...INTEGRATION, id: 2 }} onChange={jest.fn()} />+ </Provider>+ )++ await waitFor(() => {+ expect(screen.queryByText('No channel selected. Pick one from the list.')).toBeNull()+ })+ })++ it('reports no dropped search when the user picks a channel from the list', async () => {+ // Selecting an option blurs the input before it reports the new value, so the picker sees+ // the same "blurred with typed text" signal it does for a genuine click-away.+ const onChange = jest.fn()+ const { container } = render(+ <Provider>+ <SlackChannelPicker integration={INTEGRATION} 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('C111111111|#general')+ expect(screen.queryByText('No channel selected. Pick one from the list.')).toBeNull()+ })+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.tsxindex 0309da4ba68e..8efb426ac3b9 100644--- a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx+++ b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx@@ -85,6 +85,34 @@ const getSlackChannelOptions = (slackChannels?: SlackChannelType[] | null): Lemo: null}+// A private channel the connecting user cannot see has no readable name, so keep it out of the list+// unless it is the current selection or the exact id being searched for.+const withoutInaccessiblePrivateChannels = (+ options: LemonInputSelectOption[] | null,+ isPrivateChannelWithoutAccess: (channelId: string) => boolean,+ visibleIds: (string | null | undefined)[]+): LemonInputSelectOption[] => {+ return (options ?? []).filter((option) => {+ const channelId = slackChannelId(option.key)+ return !isPrivateChannelWithoutAccess(channelId) || visibleIds.includes(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 = (+ options: LemonInputSelectOption[],+ savedValue: string | null | undefined+): LemonInputSelectOption[] => {+ if (!savedValue || options.some((option) => option.key === savedValue)) {+ return options+ }+ return [+ ...options,+ { key: savedValue, label: savedValue.includes('|') ? savedValue.split('|')[1] : 'Slack channel' },+ ]+}+const getSlackUserOptions = (slackUsers: SlackUserApi[]): LemonInputSelectOption[] => {return slackUsers.map((user) => {// Display names are not unique in a workspace, so surface the unique handle alongside@@ -277,6 +305,79 @@ 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,+ showUnselectedSearchError,+}: {+ integration: IntegrationType+ value?: string+ showUnselectedSearchError: boolean+}): JSX.Element {+ const logic = slackIntegrationLogic({ id: integration.id })+ const {+ allSlackChannels,+ allSlackChannelsLoading,+ isMemberOfSlackChannel,+ isPrivateChannelWithoutAccess,+ getChannelRefreshButtonDisabledReason,+ slackIntegrationInactiveMessage,+ } = useValues(logic)+ const { loadAllSlackChannels } = useActions(logic)++ const showSlackMembershipWarning = value && isMemberOfSlackChannel(value) === false++ return (+ <>+ {showUnselectedSearchError ? (+ <p className="mt-1 mb-0 text-xs text-danger" role="alert">+ No channel selected. Pick one from the list.+ </p>+ ) : null}++ {slackIntegrationInactiveMessage ? (+ <SlackIntegrationInactiveBanner message={slackIntegrationInactiveMessage} />+ ) : null}++ {allSlackChannels?.has_more && !allSlackChannelsLoading ? (+ <p className="text-secondary text-xs mt-1 mb-0">+ Only the first page of channels is shown. Type to search for a specific channel.+ </p>+ ) : null}++ {showSlackMembershipWarning ? (+ <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.{' '}+ <Link to="https://posthog.com/docs/webhooks/slack" target="_blank">+ See the Docs for more information+ </Link>+ </span>+ <LemonButton+ type="secondary"+ disabledReason={getChannelRefreshButtonDisabledReason()}+ onClick={() => loadAllSlackChannels(true)}+ loading={allSlackChannelsLoading}+ >+ Check again+ </LemonButton>+ </div>+ </LemonBanner>+ ) : isPrivateChannelWithoutAccess(value ?? '') ? (+ <LemonBanner type="info">+ This is a private Slack channel. Ask{' '}+ <ProfilePicture user={integration.created_by} showName size="sm" /> or connect your own Slack+ account to configure private channels.+ </LemonBanner>+ ) : null}+ </>+ )+}+export type SlackChannelPickerProps = {integration: IntegrationTypevalue?: string@@ -289,19 +390,29 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: Sconst {slackChannels,slackChannelsForPicker,- allSlackChannels,allSlackChannelsLoading,slackChannelByIdLoading,- isMemberOfSlackChannel,isPrivateChannelWithoutAccess,getChannelRefreshButtonDisabledReason,- slackIntegrationInactiveMessage,} = useValues(logic)const { loadAllSlackChannels, loadSlackChannelById, loadSlackChannelByIdSuccess } = useActions(logic)const [localValue, setLocalValue] = useState<string | null>(null)// Gates the empty-val recovery reload: LemonInputSelect's setInputValue('') on blur and// after-select would otherwise flicker the "first page of channels" hint on every focus cycle.const hasActiveSearchRef = useRef(false)+ // LemonInputSelect throws typed text away on blur, so someone who types a channel name and+ // clicks away is left with an empty input and no idea why. Track that case to show it back.+ const hasUnselectedSearchRef = useRef(false)+ const [blurredWithoutSelection, setBlurredWithoutSelection] = useState(false)+ // The marker and the state it feeds always clear together: a search that ended in a selection+ // was never dropped.+ const clearDroppedSearch = (): void => {+ hasUnselectedSearchRef.current = false+ setBlurredWithoutSelection(false)+ }+ // A pasted channel id is already an unambiguous choice, so hold it until the lookup resolves and+ // then pick it. Nobody should have to recognize their channel by id in the list.+ const [pastedChannelId, setPastedChannelId] = useState<string | null>(null)const channelRefreshButtonDisabledReason = getChannelRefreshButtonDisabledReason()// 1s tick while the cooldown is active so the countdown updates; otherwise idle the rerender (60s, picker is short-lived).@@ -313,16 +424,9 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S[slackChannelsForPicker])- const slackChannelOptions = (): LemonInputSelectOption[] | null => {- return rawSlackChannelOptions- ? rawSlackChannelOptions.filter((x) => {- const id = slackChannelId(x.key)- // Only show a private channel if searching for the exact channelId or it's currently selected- return !isPrivateChannelWithoutAccess(id) || id === value || id === localValue- })- : []- }- const showSlackMembershipWarning = value && isMemberOfSlackChannel(value) === false+ // 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 && !pastedChannelIdconst modifiedValue = useMemo(() => {if (value?.split('|').length === 1) {@@ -346,6 +450,35 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S}}, [logic, loadAllSlackChannels, disabled])+ useEffect(() => {+ // A caller can swap the integration (switching Slack workspace) without unmounting this+ // picker, so state from the old workspace's search must not leak into the new one.+ hasActiveSearchRef.current = false+ clearDroppedSearch()+ setLocalValue(null)+ setPastedChannelId(null)+ }, [integration.id])++ useEffect(() => {+ if (!pastedChannelId) {+ return+ }+ const channel = slackChannels.find((x: SlackChannelType) => x.id === pastedChannelId)+ if (!channel) {+ // Stop waiting once the lookup settles with nothing. A paste that resolves to no channel+ // has to fall back to the dropped-search message rather than stay silent.+ if (!slackChannelByIdLoading) {+ setPastedChannelId(null)+ }+ return+ }+ setPastedChannelId(null)+ clearDroppedSearch()+ if (slackChannelId(value ?? '') !== channel.id) {+ onChange?.(`${channel.id}|#${channel.name}`)+ }+ }, [pastedChannelId, slackChannels, slackChannelByIdLoading, value, onChange])+// Read-only pickers still need a direct lookup because the saved channel may not be on the first page.useEffect(() => {if (value) {@@ -356,23 +489,20 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S}}, [loadSlackChannelById, value])- const fallbackOption = modifiedValue- ? {- key: modifiedValue,- label: modifiedValue.includes('|') ? modifiedValue.split('|')[1] : 'Slack channel',- }- : null- const availableOptions = slackChannelOptions() ?? []- const options =- fallbackOption && !availableOptions.some((option) => option.key === fallbackOption.key)- ? [...availableOptions, fallbackOption]- : availableOptions+ const options = withSavedChannelOption(+ withoutInaccessiblePrivateChannels(rawSlackChannelOptions, isPrivateChannelWithoutAccess, [value, localValue]),+ modifiedValue+ )return (<><LemonInputSelectonChange={(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) {// Pin into the by-id slot so the post-select bulk reload can't drop the// channel from slackChannels and unresolve the label.@@ -393,7 +523,9 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: Sconst idCandidate = val.trim().toUpperCase()if (SLACK_CHANNEL_ID_PATTERN.test(idCandidate)) {loadSlackChannelById(idCandidate)+ setPastedChannelId(idCandidate)} else if (val !== modifiedValue) {+ 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// search — the composite "id|#name" matches no channel server-side and@@ -402,6 +534,8 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: SloadAllSlackChannels(false, val)hasActiveSearchRef.current = true}+ hasUnselectedSearchRef.current = true+ setBlurredWithoutSelection(false)setLocalValue(val)} else if (hasActiveSearchRef.current) {loadAllSlackChannels()@@ -410,6 +544,8 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S}}value={modifiedValue ? [modifiedValue] : []}onFocus={() => !slackChannels.length && !allSlackChannelsLoading && loadAllSlackChannels()}+ onBlur={() => setBlurredWithoutSelection(hasUnselectedSearchRef.current)}+ status={showUnselectedSearchError ? 'danger' : 'default'}disabled={disabled}mode="single"data-attr="select-slack-channel"@@ -434,43 +570,11 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: Sloading={allSlackChannelsLoading || slackChannelByIdLoading}/>- {slackIntegrationInactiveMessage ? (- <SlackIntegrationInactiveBanner message={slackIntegrationInactiveMessage} />- ) : null}-- {allSlackChannels?.has_more && !allSlackChannelsLoading ? (- <p className="text-secondary text-xs mt-1 mb-0">- Only the first page of channels is shown. Type to search for a specific channel.- </p>- ) : null}-- {showSlackMembershipWarning ? (- <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.{' '}- <Link to="https://posthog.com/docs/webhooks/slack" target="_blank">- See the Docs for more information- </Link>- </span>- <LemonButton- type="secondary"- disabledReason={getChannelRefreshButtonDisabledReason()}- onClick={() => loadAllSlackChannels(true)}- loading={allSlackChannelsLoading}- >- Check again- </LemonButton>- </div>- </LemonBanner>- ) : isPrivateChannelWithoutAccess(value ?? '') ? (- <LemonBanner type="info">- This is a private Slack channel. Ask{' '}- <ProfilePicture user={integration.created_by} showName size="sm" /> or connect your own Slack- account to configure private channels.- </LemonBanner>- ) : null}+ <SlackChannelPickerNotices+ integration={integration}+ value={value}+ showUnselectedSearchError={showUnselectedSearchError}+ /></>)}