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.

fix(integrations): make Slack channel and DM setup recoverable in-app (#100557)

posthog[bot]a63920b12382
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2cb92908a9a8..04c67c757f1a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2480,6 +2480,10 @@ snapshots:
hash: v1.k794b7964.c5f45d681dad559cdf8bed1c8e9d31c5dca4d0973e1fbf5d1515ab30c393b554.SYg7auYBsl2kTK9lzMylWzKKRJ9Bf3sT0lwtvlfXx24
components-slack-channel-picker--alphabetical--light:
hash: v1.k794b7964.726967267332758d5771d2230a569cf7a29bdb38d1244aeb8dcacd86f25f433e.n9EALYKR_pt88G2ZCdyZ4V12Br9qoNbP3w7j2bNQ0Wk
+ components-slack-channel-picker--missing-app-in-channel--dark:
+ hash: v1.k794b7964.38c8b5516744caf6b0d4497e37e96c84dad27af6c1b6f2d3b0798377b7ce77ca.zcp2aiv59l5oZLpcdiTzS0jrBbFcT_Nt2xmRfa8wG1I
+ components-slack-channel-picker--missing-app-in-channel--light:
+ hash: v1.k794b7964.77b1ae6246ae53d3a86fbe872d519c47df3b4c17a85c20089085dccd72ff081c.1Ehyk4lGEihuDr4kYg7SaPSsBUEwoPQBri5rrnnsJK4
components-slack-channel-picker--multiple-selection--dark:
hash: v1.k794b7964.2706bc3f6a6a560eeb7c2a7b25b0feafb0438bb7f2b94aa6f584de1eed7338a2.WscXFEXWmTCQX3rgoirWxfA_iSvW47pO5ZaLo7TFx3U
components-slack-channel-picker--multiple-selection--light:
@@ -11422,6 +11426,10 @@ snapshots:
hash: v1.k794b7964.b47818f5f154dfd4d14fe525e714980ec9f06e8c29802231d4e1ebf6df7a0de2.ru2rUWCNxUOD8UACkmW8-dfV0Q4rNvf-D-E7ut9kdXI
scenes-app-inbox-slacknotificationssection--direct-message-to-me--light:
hash: v1.k794b7964.97016ccf994141237de98a7decd5fa540f8b8fecc6f9b67b6fe070e6fc86c6f6.YSImf6N-fF_YX2F4QDRwBpaQBi2b5C7UgU_s4h3xTDg
+ scenes-app-inbox-slacknotificationssection--direct-message-unavailable--dark:
+ hash: v1.k794b7964.c0919593bf744127f368ed20b2cedf1cfa22e5f1af5ab217374b09e5b3a42967.iWW0VeeKA_6NsRR91wa3UUSdLiW25JlMYf7pKlRi44Y
+ scenes-app-inbox-slacknotificationssection--direct-message-unavailable--light:
+ hash: v1.k794b7964.f0c171d1358f663f0cc699e8b012228fa2c6204569f66e99f5b0ff391ee587f2.n4pCX7buo8bGOu_BswREY22LJiyjDkbuauKq4nDiKCk
scenes-app-inbox-slacknotificationssection--not-connected--dark:
hash: v1.k794b7964.28ba7f9bff784013ccce1e2a2fc0130d6bb7ce265f501308f221cbdf902614ad.Ou8BqYO_9RvcgnW9eECuR7tiWOtkJbX8mFSUXEkXzWw
scenes-app-inbox-slacknotificationssection--not-connected--light:
diff --git a/frontend/src/lib/integrations/IntegrationScopesWarning.tsx b/frontend/src/lib/integrations/IntegrationScopesWarning.tsx
index af69fd1f756c..370f496b4291 100644
--- a/frontend/src/lib/integrations/IntegrationScopesWarning.tsx
+++ b/frontend/src/lib/integrations/IntegrationScopesWarning.tsx
@@ -22,7 +22,7 @@ import { integrationAuthorizeUrl, reconnectReturnUrl } from './integrationsLogic
export function getGrantedScopes(integration: IntegrationType): string[] {
const candidates: string[][] = []
- for (const raw of [integration.config.scope, integration.config.scopes]) {
+ for (const raw of [integration.config?.scope, integration.config?.scopes]) {
if (typeof raw === 'string') {
// Pick the delimiter explicitly. Pushing both comma- and space-split results and
// letting "longest array wins" decide was a heuristic that silently mangled mixed
diff --git a/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx b/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx
index 48fa9a9ab0cc..0b2122a8dc06 100644
--- a/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx
+++ b/frontend/src/lib/integrations/SlackChannelPicker.stories.tsx
@@ -25,6 +25,9 @@ const channel = (id: string, name: string): SlackChannelType => ({
is_private_without_access: false,
})
+// The channel someone picks before inviting the PostHog app to it.
+const notJoinedChannel: SlackChannelType = { ...channel('C7', 'launch-plans'), is_member: false }
+
const channels: SlackChannelType[] = [
channel('C1', 'alerts'),
channel('C2', 'announcements'),
@@ -157,6 +160,38 @@ export const PastedChannelId: Story = {
},
}
+// The app is not in the picked channel yet. "Check again" re-reads that one channel from Slack,
+// so the warning clears as soon as someone runs the invite.
+export const MissingAppInChannel: Story = {
+ decorators: [
+ function NotJoinedMocks(Story) {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:id/integrations/:intId/channels': { channels: [...channels, notJoinedChannel] },
+ '/api/environments/:id/integrations/:intId/channels': {
+ channels: [...channels, notJoinedChannel],
+ },
+ },
+ })
+ return <Story />
+ },
+ ],
+ render: () => (
+ <div className="p-4 max-w-md">
+ <SlackChannelPicker
+ integration={integration}
+ value={`${notJoinedChannel.id}|#${notJoinedChannel.name}`}
+ onChange={() => {}}
+ />
+ </div>
+ ),
+ // The warning renders only once the membership lookup lands, so settle it before the
+ // screenshot rather than racing the banner into frame.
+ play: async ({ canvasElement }) => {
+ await within(canvasElement).findByText('Check again')
+ },
+}
+
// 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 2f934f947480..202df76a9b6d 100644
--- a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
+++ b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
@@ -66,6 +66,17 @@ const OFF_PAGE_CHANNELS = [
]
const OFF_PAGE_CHANNEL = OFF_PAGE_CHANNELS[0]
+// The channel someone picks before inviting the PostHog app to it.
+const NOT_JOINED_CHANNEL = {
+ id: 'CNOTJOINED1',
+ name: 'not-joined',
+ is_private: false,
+ is_member: false,
+ is_ext_shared: false,
+ is_private_without_access: false,
+}
+const MISSING_APP_WARNING = /The PostHog Slack app is not in this channel/
+
// 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> {
@@ -78,13 +89,21 @@ async function dropASearch(container: HTMLElement): Promise<void> {
describe('SlackChannelPicker', () => {
let channelsRequestSearchQueries: (string | null)[] = []
let channelIdLookups: string[] = []
+ let forcedChannelIdLookups: string[] = []
// A test that must observe the by-id lookup mid-flight sets this so the mock waits to respond.
let holdChannelIdLookup: Promise<void> | null = null
+ // Channels the bulk list returns on top of CHANNELS, for a test that needs its own fixture.
+ let extraListedChannels: (typeof NOT_JOINED_CHANNEL)[] = []
+ // Whether Slack now reports the app as a member of NOT_JOINED_CHANNEL.
+ let appJoinedTheChannel = false
beforeEach(() => {
channelsRequestSearchQueries = []
channelIdLookups = []
+ forcedChannelIdLookups = []
holdChannelIdLookup = null
+ extraListedChannels = []
+ appJoinedTheChannel = false
useMocks({
get: {
'/api/environments/:team_id/integrations/:id/channels': async ({ request }) => {
@@ -93,25 +112,32 @@ describe('SlackChannelPicker', () => {
const channelId = url.searchParams.get('channel_id')
if (channelId) {
channelIdLookups.push(channelId)
+ if (url.searchParams.get('force_refresh') === 'true') {
+ forcedChannelIdLookups.push(channelId)
+ }
if (holdChannelIdLookup) {
await holdChannelIdLookup
}
const match =
CHANNELS.find((c) => c.id === channelId) ??
- OFF_PAGE_CHANNELS.find((c) => c.id === channelId)
+ OFF_PAGE_CHANNELS.find((c) => c.id === channelId) ??
+ (channelId === NOT_JOINED_CHANNEL.id
+ ? { ...NOT_JOINED_CHANNEL, is_member: appJoinedTheChannel }
+ : undefined)
return [200, { channels: match ? [match] : [] }]
}
channelsRequestSearchQueries.push(search)
// Server-side search: substring match in name or id (mirrors the backend).
// The bulk endpoint deliberately never returns OFF_PAGE_CHANNEL so we can
// verify name resolution falls back to the direct-by-id lookup.
+ const listed = [...CHANNELS, ...extraListedChannels]
const filtered = search
- ? CHANNELS.filter(
+ ? listed.filter(
(c) =>
c.name.toLowerCase().includes(search.toLowerCase()) ||
c.id.toLowerCase().includes(search.toLowerCase())
)
- : CHANNELS
+ : listed
return [
200,
{
@@ -189,6 +215,32 @@ describe('SlackChannelPicker', () => {
expect(channelIdLookups).not.toContain('COFFPAGE9XX|#off-page-channel')
})
+ // The dead end this replaces: the warning was answered from a copy of the channel that no
+ // button could refresh, so inviting the app changed nothing on screen.
+ it('clears the missing-app warning when a re-check finds the app in the channel', async () => {
+ extraListedChannels = [NOT_JOINED_CHANNEL]
+ const { container } = render(
+ <Provider>
+ <SlackChannelPicker
+ integration={INTEGRATION}
+ value={`${NOT_JOINED_CHANNEL.id}|#${NOT_JOINED_CHANNEL.name}`}
+ onChange={jest.fn()}
+ />
+ </Provider>
+ )
+ expect(await screen.findByText(MISSING_APP_WARNING)).toBeInTheDocument()
+
+ appJoinedTheChannel = true
+ await userEvent.click(screen.getByText('Check again'))
+
+ await waitFor(() => {
+ expect(container).not.toHaveTextContent('The PostHog Slack app is not in this channel')
+ })
+ // One live lookup of the picked channel, not a full re-enumeration of the workspace.
+ expect(forcedChannelIdLookups).toEqual([NOT_JOINED_CHANNEL.id])
+ expect(channelsRequestSearchQueries).toEqual([''])
+ })
+
it('resolves a saved channel name when the picker is disabled without displaying its ID', async () => {
const { container } = render(
<Provider>
diff --git a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
index e76a99d62496..11d4e4abb120 100644
--- a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
+++ b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
@@ -370,14 +370,14 @@ function SlackChannelPickerNotices({
const {
allSlackChannels,
allSlackChannelsLoading,
+ slackChannelByIdLoading,
isMemberOfSlackChannel,
isPrivateChannelWithoutAccess,
- getChannelRefreshButtonDisabledReason,
slackIntegrationInactiveMessage,
} = useValues(logic)
- const { loadAllSlackChannels } = useActions(logic)
+ const { recheckSlackChannelMembership } = useActions(logic)
- const showSlackMembershipWarning = values.some((value) => isMemberOfSlackChannel(value) === false)
+ const channelsMissingTheApp = values.filter((value) => isMemberOfSlackChannel(value) === false)
const showPrivateChannelWarning = values.some((value) => isPrivateChannelWithoutAccess(value))
return (
@@ -398,22 +398,22 @@ function SlackChannelPickerNotices({
</p>
) : null}
- {showSlackMembershipWarning ? (
+ {channelsMissingTheApp.length ? (
<LemonBanner type="info">
<div className="flex gap-2 items-center">
<span>
{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. '}
+ ? 'The PostHog Slack app is not in every selected channel. '
+ : 'The PostHog Slack app is not in this channel. '}
+ Invite it with <code>/invite @PostHog</code> in Slack, then check again.{' '}
<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}
+ onClick={() => recheckSlackChannelMembership(channelsMissingTheApp.map(slackChannelId))}
+ loading={slackChannelByIdLoading}
>
Check again
</LemonButton>
diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts b/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
index eaa17d6a656c..b06f80809ecb 100644
--- a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
+++ b/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
@@ -18,10 +18,14 @@ const FIXED_NOW = new Date('2026-01-01T12:00:00Z')
describe('slackIntegrationLogic — loadAllSlackChannels search & pagination', () => {
let logic: ReturnType<typeof slackIntegrationLogic.build>
let lastChannelsQuery: Record<string, string> = {}
- let nextChannelsResponse: { id: string; name: string }[] = [
+ let lastChannelByIdQuery: Record<string, string> = {}
+ let nextChannelsResponse: { id: string; name: string; is_member?: boolean }[] = [
{ id: 'C1', name: 'general' },
{ id: 'C2', name: 'engineering' },
]
+ let nextChannelByIdResponse: SlackChannelType | null = null
+ // Set by the out-of-order test so the by-id lookup answers only when it releases this.
+ let holdChannelByIdLookup: Promise<void> | null = null
const buildChannel = (id: string, name: string): SlackChannelType => ({
id,
@@ -34,18 +38,32 @@ describe('slackIntegrationLogic — loadAllSlackChannels search & pagination', (
beforeEach(() => {
lastChannelsQuery = {}
+ lastChannelByIdQuery = {}
+ nextChannelByIdResponse = null
+ holdChannelByIdLookup = null
nextChannelsResponse = [
{ id: 'C1', name: 'general' },
{ id: 'C2', name: 'engineering' },
]
useMocks({
get: {
- '/api/environments/:team_id/integrations/:id/channels': ({ request }) => {
- lastChannelsQuery = Object.fromEntries(new URL(request.url).searchParams.entries())
+ '/api/environments/:team_id/integrations/:id/channels': async ({ request }) => {
+ const query = Object.fromEntries(new URL(request.url).searchParams.entries())
+ if (query.channel_id) {
+ lastChannelByIdQuery = query
+ if (holdChannelByIdLookup) {
+ await holdChannelByIdLookup
+ }
+ return [200, { channels: nextChannelByIdResponse ? [nextChannelByIdResponse] : [] }]
+ }
+ lastChannelsQuery = query
return [
200,
{
- channels: nextChannelsResponse.map((c) => buildChannel(c.id, c.name)),
+ channels: nextChannelsResponse.map((c) => ({
+ ...buildChannel(c.id, c.name),
+ ...(c.is_member === undefined ? {} : { is_member: c.is_member }),
+ })),
lastRefreshedAt: '2026-01-01T00:00:00Z',
has_more: true,
},
@@ -109,6 +127,69 @@ describe('slackIntegrationLogic — loadAllSlackChannels search & pagination', (
expect(logic.values.slackChannels.map((c) => c.id).sort()).toEqual(['C_BULK2', 'C_OFFPAGE'])
})
+ it('drops a pinned channel on a forced refresh so its membership can be looked up again', async () => {
+ nextChannelsResponse = [{ id: 'C_BULK', name: 'bulk-channel' }]
+ await expectLogic(logic, () => {
+ logic.actions.loadAllSlackChannels()
+ }).toFinishAllListeners()
+
+ // What the picker pins on selection. The workspace has more channels than one page, so the
+ // pinned channel is the only copy the membership check can read.
+ logic.actions.loadSlackChannelByIdSuccess({ ...buildChannel('C_OFFPAGE', 'off-page'), is_member: false })
+ expect(logic.values.isMemberOfSlackChannel('C_OFFPAGE')).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.loadAllSlackChannels(true)
+ }).toFinishAllListeners()
+
+ // Unknown again rather than still false: the picker only re-looks-up a channel that is
+ // absent from slackChannels, so a surviving pin would answer the check forever.
+ expect(logic.values.isMemberOfSlackChannel('C_OFFPAGE')).toBeNull()
+ })
+
+ it('flips membership from a forced by-id re-check even while the listed copy is stale', async () => {
+ // The backend serves the list from an hour-long cache, so it keeps reporting the app as
+ // missing after someone invites it to the channel.
+ nextChannelsResponse = [{ id: 'C1', name: 'general', is_member: false }]
+ await expectLogic(logic, () => {
+ logic.actions.loadAllSlackChannels()
+ }).toFinishAllListeners()
+ expect(logic.values.isMemberOfSlackChannel('C1')).toBe(false)
+
+ nextChannelByIdResponse = buildChannel('C1', 'general')
+ await expectLogic(logic, () => {
+ logic.actions.recheckSlackChannelMembership(['C1'])
+ }).toFinishAllListeners()
+
+ // force_refresh is what makes the answer live: the backend otherwise serves the channel
+ // from the same hour-old list that reported the app missing.
+ expect(lastChannelByIdQuery).toMatchObject({ channel_id: 'C1', force_refresh: 'true' })
+ expect(logic.values.isMemberOfSlackChannel('C1')).toBe(true)
+ })
+
+ it('discards a by-id answer that a forced refresh overtook', async () => {
+ let releaseLookup: () => void = () => {}
+ holdChannelByIdLookup = new Promise((resolve) => {
+ releaseLookup = resolve
+ })
+ // The lookup is about to answer with the membership the backend cache still holds.
+ nextChannelByIdResponse = { ...buildChannel('C1', 'general'), is_member: false }
+ logic.actions.loadSlackChannelById('C1')
+
+ nextChannelsResponse = [{ id: 'C1', name: 'general' }]
+ // Not toFinishAllListeners: the held by-id lookup is a pending listener of its own.
+ await expectLogic(logic, () => {
+ logic.actions.loadAllSlackChannels(true)
+ }).toDispatchActions(['loadAllSlackChannelsSuccess'])
+ expect(logic.values.isMemberOfSlackChannel('C1')).toBe(true)
+
+ await expectLogic(logic, () => releaseLookup()).toDispatchActions(['loadSlackChannelByIdSuccess'])
+
+ // The refresh fetched its list after the lookup started, so the lookup must not write its
+ // older membership over it.
+ expect(logic.values.isMemberOfSlackChannel('C1')).toBe(true)
+ })
+
it('reloads the full list when a search-then-clear sequence runs', async () => {
// First, narrow the cache with a search — server returns only the matching subset.
nextChannelsResponse = [{ id: 'C2', name: 'engineering' }]
diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.ts b/frontend/src/lib/integrations/slackIntegrationLogic.ts
index 99067f39877b..273faeb91a9a 100644
--- a/frontend/src/lib/integrations/slackIntegrationLogic.ts
+++ b/frontend/src/lib/integrations/slackIntegrationLogic.ts
@@ -8,7 +8,7 @@ import { preflightLogic } from 'lib/logic/preflightLogic'
import { SlackChannelType } from '~/types'
-import { integrationsUsersRetrieve } from 'products/integrations/frontend/generated/api'
+import { integrationsChannelsRetrieve, integrationsUsersRetrieve } from 'products/integrations/frontend/generated/api'
import type { SlackUserApi, SlackUsersResponseApi } from 'products/integrations/frontend/generated/api.schemas'
import type { PreflightStatus } from '../../types'
@@ -39,6 +39,7 @@ export interface slackIntegrationLogicValues {
allSlackUsersLoading: boolean
attemptedSlackChannelIds: Record<string, true>
attemptedSlackUserIds: Record<string, true>
+ channelListGeneration: number
getChannelRefreshButtonDisabledReason: () => string
getUsersRefreshButtonDisabledReason: () => string
isMemberOfSlackChannel: (channel: string) => boolean | null
@@ -118,8 +119,12 @@ export interface slackIntegrationLogicActions {
search: string
}
}
- loadSlackChannelById: (channelId: string) => {
+ loadSlackChannelById: (
+ channelId: string,
+ forceRefresh?: boolean
+ ) => {
channelId: string
+ forceRefresh: boolean
}
loadSlackChannelByIdFailure: (
error: string,
@@ -132,11 +137,13 @@ export interface slackIntegrationLogicActions {
slackChannelById: SlackChannelType | null,
payload?: {
channelId: string
+ forceRefresh: boolean
}
) => {
slackChannelById: SlackChannelType | null
payload?: {
channelId: string
+ forceRefresh: boolean
}
}
loadSlackUserById: (userId: string) => {
@@ -160,6 +167,9 @@ export interface slackIntegrationLogicActions {
userId: string
}
}
+ recheckSlackChannelMembership: (channelIds: string[]) => {
+ channelIds: string[]
+ }
setRecentlySubscribedChannelIds: (channelIds: string[]) => {
channelIds: string[]
}
@@ -220,7 +230,8 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
loadAllSlackChannels: (forceRefresh: boolean = false, search: string = '') => ({ forceRefresh, search }),
loadAllSlackUsers: (forceRefresh: boolean = false, search: string = '') => ({ forceRefresh, search }),
loadSlackUserById: (userId: string) => ({ userId }),
- loadSlackChannelById: (channelId: string) => ({ channelId }),
+ loadSlackChannelById: (channelId: string, forceRefresh: boolean = false) => ({ channelId, forceRefresh }),
+ recheckSlackChannelMembership: (channelIds: string[]) => ({ channelIds }),
setRecentlySubscribedChannelIds: (channelIds: string[]) => ({ channelIds }),
setSlackIntegrationInactive: (message: string | null) => ({ message }),
}),
@@ -311,12 +322,31 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
slackChannelById: [
null as SlackChannelType | null,
{
- loadSlackChannelById: async ({ channelId }) => {
+ loadSlackChannelById: async ({ channelId, forceRefresh }) => {
+ const generation = values.channelListGeneration
try {
- const res = await api.integrations.slackChannelsById(props.id, channelId)
- // The by-id endpoint always calls Slack live, so a success is real proof
- // the connection works again.
- actions.setSlackIntegrationInactive(null)
+ const res = await integrationsChannelsRetrieve(
+ String(ApiConfig.getCurrentProjectId()),
+ props.id,
+ {
+ channel_id: channelId,
+ ...(forceRefresh ? { force_refresh: true } : {}),
+ }
+ )
+ if (values.channelListGeneration !== generation) {
+ // A forced refresh landed while this lookup was in flight. Its list is
+ // the newer answer, and a non-forced lookup can be served from the
+ // backend cache the refresh just replaced, so drop this one whole: null
+ // keeps the by-id record untouched, and returning before the clear below
+ // keeps whatever the refresh said about the connection.
+ return null
+ }
+ if (forceRefresh) {
+ // Matches the list loader: only a forced lookup provably reached Slack,
+ // so only it may hide the reconnect banner. A plain lookup can be served
+ // from the backend's cached list while the token is still revoked.
+ actions.setSlackIntegrationInactive(null)
+ }
return res.channels[0] || null
} catch (e: any) {
if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
@@ -346,11 +376,24 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
loadAllSlackChannels: (state, { forceRefresh }) => (forceRefresh ? {} : state),
},
],
+ channelListGeneration: [
+ 0,
+ {
+ // Counts forced refreshes so a by-id lookup can tell whether the list moved under
+ // it while it was in flight. Read in the loader, never rendered.
+ loadAllSlackChannels: (state, { forceRefresh }) => (forceRefresh ? state + 1 : state),
+ },
+ ],
_fetchedSlackChannelsById: [
{} as Record<string, SlackChannelType>,
{
loadSlackChannelByIdSuccess: (state, { slackChannelById }) =>
slackChannelById ? { ...state, [slackChannelById.id]: slackChannelById } : state,
+ // Cleared with `attemptedSlackChannelIds`, which the picker reads to decide whether a
+ // channel still needs a lookup. Holding a channel here while its marker is gone left
+ // the stale copy answering the membership check with nothing able to replace it, so
+ // "Check again" could never clear the warning for a channel the app had just joined.
+ loadAllSlackChannels: (state, { forceRefresh }) => (forceRefresh ? {} : state),
},
],
attemptedSlackUserIds: [
@@ -391,6 +434,14 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
loadAllSlackChannelsSuccess: () => {
actions.setRecentlySubscribedChannelIds(getRecentSlackChannelIds(props.id))
},
+ // Re-reads the picked channels straight from Slack, which is one call each, rather than
+ // enumerating the workspace. That keeps the re-check off the full list's refresh cooldown,
+ // so someone who has just invited the app does not wait out a cooldown to see it worked.
+ recheckSlackChannelMembership: ({ channelIds }) => {
+ for (const channelId of channelIds) {
+ actions.loadSlackChannelById(channelId, true)
+ }
+ },
})),
selectors({
@@ -402,7 +453,10 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
): SlackChannelType[] => {
const listedIds = new Set(_fetchedSlackChannels.map((channel) => channel.id))
return [
- ..._fetchedSlackChannels,
+ // A by-id lookup is the newest word on that channel, because the map is cleared
+ // whenever the list is force-refreshed. Let it override the listed copy so a live
+ // re-check of one channel's membership is not shadowed by the cached list.
+ ..._fetchedSlackChannels.map((channel) => _fetchedSlackChannelsById[channel.id] ?? channel),
...Object.values(_fetchedSlackChannelsById).filter((channel) => !listedIds.has(channel.id)),
]
},
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index d03ffe04387e..67af063ef3dc 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -190,6 +190,22 @@ def _reraise_slack_api_error(error: SlackApiError) -> NoReturn:
raise error
+def _take_slack_lookup_budget(budget_key: str, limit: int, detail: str) -> None:
+ """Spend one unit of a per-integration, per-minute budget for uncached Slack lookups, or raise.
+
+ A by-id lookup that misses every cache reaches Slack, and the caller chooses the id, so without
+ a budget a loop over fabricated ids drains the workspace's Slack API quota one call at a time.
+ Misses count as well as hits, because a miss caches nothing and can be repeated for free.
+ """
+ try:
+ lookups = 1 if cache.add(budget_key, 1, 60) else cache.incr(budget_key)
+ except ValueError:
+ # The counter expired between the add and the incr, so this request opens the next minute.
+ lookups = 1
+ if lookups > limit:
+ raise Throttled(detail=detail)
+
+
def validate_github_repository_name(repo: str) -> str:
"""Validate repository paths accepted by GitHub integration endpoints."""
parts = repo.split("/")
@@ -556,6 +572,26 @@ class SlackChannelsQuerySerializer(serializers.Serializer):
min_value=0,
help_text="Number of channels to skip before returning results.",
)
+ # Deliberately not nullable: generated clients serialize an explicit null as the literal
+ # query string "channel_id=null", which would then be looked up as a channel id. Omit to skip.
+ channel_id = serializers.CharField(
+ required=False,
+ default="",
+ allow_blank=True,
+ help_text=(
+ "Look up one channel directly by Slack channel ID (e.g. C0123ABC). When set, `search`, `limit`, and "
+ "`offset` are ignored and the response holds at most that channel."
+ ),
+ )
+ force_refresh = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Bypass the 1 hour channel cache, including for a `channel_id` lookup, which is how a caller reads "
+ "the channel's current membership after inviting the app to it. Honored only for browser session "
+ "callers; API key, OAuth, and MCP callers always read through the cache."
+ ),
+ )
class SlackChannelsResponseSerializer(serializers.Serializer):
@@ -579,6 +615,14 @@ class SlackUserSerializer(serializers.Serializer):
)
+# How long a fetched Slack channel list stays cached.
+SLACK_CHANNELS_CACHE_SECONDS = 60 * 60
+
+# Cap on uncached per-id channel lookups per integration per minute; each one reaches Slack's
+# conversations.info endpoint, so distinct fabricated ids must not be able to drain the workspace
+# quota. A re-check spends one per channel it warned about, well inside the cap.
+SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE = 30
+
# Server-side floor between forced member-list refreshes, matching the picker's visible cooldown.
SLACK_USERS_MIN_REFRESH_SECONDS = 30
@@ -1680,7 +1724,11 @@ class IntegrationViewSet(
}
@staticmethod
- def _cache_slack_channel(key: str, channel: dict) -> None:
+ def _mutate_cached_slack_channels(key: str, mutate: Callable[[dict[str, dict]], bool]) -> None:
+ """Apply `mutate` to the cached list's channels, keyed by id, and write the result back.
+
+ `mutate` returns False when it changed nothing, which skips the write.
+ """
backend = caches["default"]
if not isinstance(backend, RedisCache):
return
@@ -1694,7 +1742,8 @@ class IntegrationViewSet(
return
data = client.decode(previous)
channels_by_id = {item["id"]: item for item in data["channels"]}
- channels_by_id[channel["id"]] = channel
+ if not mutate(channels_by_id):
+ return
updated = client.encode({**data, "channels": list(channels_by_id.values())})
# Compare the encoded value so concurrent lookups and list refreshes cannot lose writes.
if redis_client.eval(
@@ -1715,6 +1764,27 @@ class IntegrationViewSet(
# successful lookup into a 500. The next list refresh rebuilds the cache.
logger.warning("slack_channel_cache_update_failed", cache_key=key, exc_info=True)
+ @classmethod
+ def _cache_slack_channel(cls, key: str, channel: dict) -> None:
+ def merge(channels_by_id: dict[str, dict]) -> bool:
+ channels_by_id[channel["id"]] = channel
+ return True
+
+ cls._mutate_cached_slack_channels(key, merge)
+
+ @classmethod
+ def _drop_cached_slack_channel(cls, key: str, channel_id: str) -> None:
+ """Remove a channel Slack no longer returns from the cached list.
+
+ It is gone, or no longer visible to the app, so the list has to stop offering it for the
+ same reason a rejoined one has to replace its stale copy.
+ """
+
+ def drop(channels_by_id: dict[str, dict]) -> bool:
+ return channels_by_id.pop(channel_id, None) is not None
+
+ cls._mutate_cached_slack_channels(key, drop)
+
@staticmethod
def _filter_slack_channels_for_search(channels: list[dict], search: str) -> list[dict]:
visible = [channel for channel in channels if not channel.get("is_private_without_access")]
@@ -1740,10 +1810,12 @@ class IntegrationViewSet(
raise ValidationError("channels endpoint is only supported for Slack integrations")
slack = SlackIntegration(instance)
should_include_private_channels: bool = instance.created_by_id == request.user.id
+ query_serializer = SlackChannelsQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
# force_refresh is only honored for cookie-session callers — MCP / API-key / OAuth
# callers always read through the 1h cache so an agent loop can't bypass it.
is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
- force_refresh: bool = is_session_auth and request.query_params.get("force_refresh", "false").lower() == "true"
+ force_refresh: bool = is_session_auth and query_serializer.validated_data["force_refresh"]
authed_user = cast(str | None, instance.config.get("authed_user", {}).get("id")) if instance.config else None
if not authed_user:
raise ValidationError("SlackIntegration: Missing authed_user_id in integration config")
@@ -1753,13 +1825,21 @@ class IntegrationViewSet(
# install the same workspace must not share cached private-channel lists.
key = f"slack/{instance.id}/{should_include_private_channels}/channels"
- channel_id = request.query_params.get("channel_id")
+ channel_id = query_serializer.validated_data["channel_id"]
if channel_id:
- data = cache.get(key)
- if data is not None:
- for channel in data["channels"]:
- if channel["id"] == channel_id:
- return Response({"channels": [channel]})
+ if not force_refresh:
+ data = cache.get(key)
+ if data is not None:
+ for channel in data["channels"]:
+ if channel["id"] == channel_id:
+ return Response({"channels": [channel]})
+ # Past the cached list every lookup reaches Slack, and a forced one skips the list
+ # altogether, so the same per-minute budget the member lookup uses applies here.
+ _take_slack_lookup_budget(
+ f"slack/{instance.id}/channels_info_budget",
+ SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE,
+ "Too many Slack channel lookups. Try again in a minute.",
+ )
try:
channel = slack.get_channel_by_id(channel_id, should_include_private_channels, authed_user)
except SlackApiError as e:
@@ -1768,10 +1848,11 @@ class IntegrationViewSet(
serialized_channel = self._serialize_slack_channel(channel)
self._cache_slack_channel(key, serialized_channel)
return Response({"channels": [serialized_channel]})
+ # Only a forced lookup reaches Slack for a channel the cached list still holds, so this
+ # drops a channel the workspace no longer offers rather than leaving it pickable.
+ self._drop_cached_slack_channel(key, channel_id)
return Response({"channels": []})
- query_serializer = SlackChannelsQuerySerializer(data=request.query_params)
- query_serializer.is_valid(raise_exception=True)
search = query_serializer.validated_data["search"]
limit = query_serializer.validated_data["limit"]
offset = query_serializer.validated_data["offset"]
@@ -1787,7 +1868,7 @@ class IntegrationViewSet(
"channels": [self._serialize_slack_channel(channel) for channel in channels],
"lastRefreshedAt": timezone.now().isoformat(),
}
- cache.set(key, data, 60 * 60) # one hour
+ cache.set(key, data, SLACK_CHANNELS_CACHE_SECONDS)
filtered_channels = self._filter_slack_channels_for_search(data["channels"], search)
page = filtered_channels[offset : offset + limit]
@@ -1860,13 +1941,11 @@ class IntegrationViewSet(
return Response({"users": cached_lookup})
# The per-id cache doesn't bound a caller cycling through distinct fabricated ids, so
# also cap how many uncached lookups an integration can send to Slack per minute.
- budget_key = f"slack/{instance.id}/users_info_budget"
- try:
- lookups = 1 if cache.add(budget_key, 1, 60) else cache.incr(budget_key)
- except ValueError:
- lookups = 1
- if lookups > SLACK_USERS_INFO_LOOKUPS_PER_MINUTE:
- raise Throttled(detail="Too many Slack member lookups. Try again in a minute.")
+ _take_slack_lookup_budget(
+ f"slack/{instance.id}/users_info_budget",
+ SLACK_USERS_INFO_LOOKUPS_PER_MINUTE,
+ "Too many Slack member lookups. Try again in a minute.",
+ )
try:
member = slack.get_user_by_id(user_id)
except SlackApiError as e:
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 7b91aa364e5f..9062402a8ad0 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -2555,6 +2555,115 @@ class TestIntegrationAPIKeyAccess:
assert cache.get(cache_key) is None
mock_slack_class.return_value.list_channels.assert_not_called()
+ # The write-back runs only against Redis, so the default LocMem cache would make the
+ # assertions below vacuous.
+ @override_settings(
+ CACHES={
+ **settings.CACHES,
+ "default": {
+ "BACKEND": "django_redis.cache.RedisCache",
+ "LOCATION": "redis://slack-channel-recheck-test:6379/0",
+ "OPTIONS": {"CONNECTION_POOL_KWARGS": {"connection_class": FakeConnection}},
+ },
+ }
+ )
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_channels_action_force_refresh_rechecks_one_channel(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_RECHECK",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ # Slack now reports the app as a member, because someone invited it to the channel.
+ mock_slack_instance.get_channel_by_id.return_value = {
+ "id": "C1",
+ "name": "general",
+ "is_private": False,
+ "is_member": True,
+ "is_ext_shared": False,
+ "is_private_without_access": False,
+ }
+ mock_slack_class.return_value = mock_slack_instance
+
+ # The cached list still holds what Slack said before the invite.
+ cache.set(
+ f"slack/{slack_integration.id}/True/channels",
+ {
+ "channels": [
+ {
+ "id": "C1",
+ "name": "general",
+ "is_private": False,
+ "is_member": False,
+ "is_ext_shared": False,
+ "is_private_without_access": False,
+ }
+ ],
+ "lastRefreshedAt": (timezone.now() - timedelta(minutes=5)).isoformat(),
+ },
+ 3600,
+ )
+ base_url = f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/channels/"
+ client.force_login(self.user)
+
+ cached_lookup = client.get(f"{base_url}?channel_id=C1")
+ assert cached_lookup.status_code == status.HTTP_200_OK
+ assert cached_lookup.json()["channels"][0]["is_member"] is False
+ mock_slack_instance.get_channel_by_id.assert_not_called()
+
+ forced_lookup = client.get(f"{base_url}?channel_id=C1&force_refresh=true")
+ assert forced_lookup.status_code == status.HTTP_200_OK
+ assert forced_lookup.json()["channels"][0]["is_member"] is True
+ mock_slack_instance.get_channel_by_id.assert_called_once_with("C1", True, "test_user_id")
+
+ # The live answer replaces its copy in the cached list, so the next plain load of the
+ # picker does not report the app as missing all over again.
+ listed = client.get(base_url)
+ assert listed.status_code == status.HTTP_200_OK
+ assert listed.json()["channels"][0]["is_member"] is True
+ mock_slack_instance.list_channels.assert_not_called()
+
+ # A channel Slack no longer returns leaves the cached list, so the picker stops offering it.
+ mock_slack_instance.get_channel_by_id.return_value = None
+ gone_lookup = client.get(f"{base_url}?channel_id=C1&force_refresh=true")
+ assert gone_lookup.status_code == status.HTTP_200_OK
+ assert gone_lookup.json()["channels"] == []
+
+ listed_after_removal = client.get(base_url)
+ assert listed_after_removal.status_code == status.HTTP_200_OK
+ assert listed_after_removal.json()["channels"] == []
+ mock_slack_instance.list_channels.assert_not_called()
+
+ @patch("posthog.api.integration.SLACK_CHANNELS_INFO_LOOKUPS_PER_MINUTE", 2)
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_channels_action_throttles_distinct_uncached_lookups(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_CHANNELS_BUDGET",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.get_channel_by_id.return_value = None
+ mock_slack_class.return_value = mock_slack_instance
+ client.force_login(self.user)
+
+ base_url = f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/channels/"
+ # A forced lookup skips the cached list, and a miss caches nothing, so distinct ids would
+ # otherwise reach Slack one conversations.info call at a time.
+ for index, expected_status in enumerate(
+ [status.HTTP_200_OK, status.HTTP_200_OK, status.HTTP_429_TOO_MANY_REQUESTS]
+ ):
+ response = client.get(f"{base_url}?channel_id=CPROBE{index}&force_refresh=true")
+ assert response.status_code == expected_status
+ assert mock_slack_instance.get_channel_by_id.call_count == 2
+
@pytest.mark.parametrize(
"query_string,expected_ids,expected_has_more",
[
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index 9f1ea0b3fe3e..e297e0709d78 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -874,6 +874,14 @@ export const IntegrationsListKind = {
} as const
export type IntegrationsChannelsRetrieveParams = {
+ /**
+ * Look up one channel directly by Slack channel ID (e.g. C0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that channel.
+ */
+ channel_id?: string
+ /**
+ * Bypass the 1 hour channel cache, including for a `channel_id` lookup, which is how a caller reads the channel's current membership after inviting the app to it. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache.
+ */
+ force_refresh?: boolean
/**
* Maximum number of channels to return per request (max 200).
* @minimum 1
diff --git a/products/signals/backend/slack_notification_targets.py b/products/signals/backend/slack_notification_targets.py
index 2b477733e9b4..eacb265311b7 100644
--- a/products/signals/backend/slack_notification_targets.py
+++ b/products/signals/backend/slack_notification_targets.py
@@ -38,7 +38,8 @@ _UNRESOLVED_SELF_ERROR = (
)
_SLACK_UNAVAILABLE_ERROR = "Slack did not answer. Try saving this again in a moment."
_SLACK_MISSING_SCOPE_ERROR = (
- "Your Slack connection cannot list workspace members. Reconnect Slack, and then save this setting again."
+ "PostHog cannot look up members in this Slack workspace. Reconnect Slack to give it the users:read "
+ "permission, and then turn this on again."
)
_NO_WORKSPACE_ERROR = "Choose the Slack workspace to send these through."
_MEMBER_LOOKUPS_PER_MINUTE = 30
diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx
index 7ff146acfaeb..67f15db64c5f 100644
--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx
@@ -4,7 +4,13 @@ import { useStorybookMocks } from '~/mocks/browser'
import { SlackNotificationsSection } from './SlackNotificationsSection'
-const WORKSPACE = { id: 1, kind: 'slack', display_name: 'PostHog', config: {}, created_at: '2026-01-01T00:00:00Z' }
+const WORKSPACE = {
+ id: 1,
+ kind: 'slack',
+ display_name: 'PostHog',
+ config: { scope: 'chat:write,channels:read,users:read' },
+ created_at: '2026-01-01T00:00:00Z',
+}
const CHANNELS = [
{ id: 'C0123ABC456', name: 'self-driving', is_private: false, is_member: true, is_ext_shared: false },
@@ -13,6 +19,8 @@ const CHANNELS = [
interface CardsState {
connected?: boolean
+ /** A workspace installed before PostHog asked for the scope a direct message needs. */
+ cannotLookUpMembers?: boolean
teamChannel?: string | null
/** The personal reviewer ping target: the person's own account (`U…|@name`) or a channel. */
myTarget?: string | null
@@ -22,13 +30,15 @@ interface CardsState {
function Cards({
connected = true,
+ cannotLookUpMembers = false,
teamChannel = null,
myTarget = null,
awaitingTarget = false,
}: CardsState): JSX.Element {
+ const workspace = cannotLookUpMembers ? { ...WORKSPACE, config: { scope: 'chat:write,channels:read' } } : WORKSPACE
useStorybookMocks({
get: {
- '/api/projects/:team_id/integrations/': { results: connected ? [WORKSPACE] : [] },
+ '/api/projects/:team_id/integrations/': { results: connected ? [workspace] : [] },
'/api/environments/:team_id/integrations/:id/channels': { channels: CHANNELS, has_more: false },
'/api/projects/:team_id/signals/config/': {
id: 'cfg-1',
@@ -82,6 +92,10 @@ export const DirectMessageToMe: Story = {
render: () => <Cards myTarget="U0123ABC456|@sam" />,
}
+export const DirectMessageUnavailable: Story = {
+ render: () => <Cards cannotLookUpMembers awaitingTarget />,
+}
+
export const PersonalChannel: Story = {
render: () => <Cards teamChannel="C0456DEF789|#engineering" myTarget="C0123ABC456|#self-driving" />,
}
diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx
index 750112cc2b32..3a57f5cad907 100644
--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx
+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx
@@ -9,26 +9,34 @@ import type { IntegrationType } from '~/types'
import { SlackNotificationsSection } from './SlackNotificationsSection'
-const WORKSPACE = { id: 1, kind: 'slack', display_name: 'PostHog' } as IntegrationType
+const WORKSPACE = {
+ id: 1,
+ kind: 'slack',
+ display_name: 'PostHog',
+ // A real install records what Slack granted, and the direct message needs users:read.
+ config: { scope: 'chat:write,channels:read,users:read' },
+} as IntegrationType
const DM_TARGET = 'U0123ABC456|@sam'
const DM_SAVED = 'PostHog sends these to @sam in Slack.'
// Anchored: the team card's copy carries the same sentence, after one of its own.
const CHANNEL_HELP = /^PostHog must be in the channel/
describe('SlackNotificationsSection', () => {
+ let workspace: IntegrationType = WORKSPACE
let autonomyConfig: Record<string, unknown> | null = null
let saves: Record<string, unknown>[] = []
let saveGate: Promise<void> | null = null
beforeEach(() => {
initKeaTests()
+ workspace = WORKSPACE
autonomyConfig = null
saves = []
saveGate = null
// msw handlers reset between tests, so register per test rather than once per file.
useMocks({
get: {
- '/api/projects/:team_id/integrations/': () => [200, { results: [WORKSPACE] }],
+ '/api/projects/:team_id/integrations/': () => [200, { results: [workspace] }],
'/api/environments/:team_id/integrations/:id/channels': () => [200, { channels: [], has_more: false }],
'/api/projects/:team_id/signals/config/': () => [200, { default_slack_notification_channel: null }],
'/api/users/@me/signal_autonomy/': () =>
@@ -111,6 +119,22 @@ describe('SlackNotificationsSection', () => {
expect(await screen.findByText(DM_SAVED)).toBeInTheDocument()
})
+ // A workspace that cannot resolve a member can never deliver a direct message, so the save
+ // only ever came back as a red toast the user could not act on. An install that records no
+ // scopes is the same case: assuming it has users:read is what produced that toast.
+ it.each<[string, Record<string, unknown> | undefined]>([
+ ['users:read was never granted', { scope: 'chat:write,channels:read' }],
+ ['no scopes are recorded', undefined],
+ ])('asks for a reconnect instead of saving a direct message when %s', async (_label, config) => {
+ workspace = { ...WORKSPACE, config } as IntegrationType
+
+ render(<SlackNotificationsSection />)
+ await userEvent.click(await screen.findByLabelText('Enable Slack notifications'))
+
+ expect(await screen.findByText(/Reconnect Slack to grant it/)).toBeInTheDocument()
+ expect(saves).toEqual([])
+ })
+
it('returns to direct message mode after notifications are disabled', async () => {
autonomyConfig = { slack_notification_integration_id: 1, slack_notification_channel: DM_TARGET }
diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx
index 76bbae841f36..6fc8a0c147c5 100644
--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx
+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx
@@ -2,16 +2,27 @@ import { useActions, useMountedLogic, useValues } from 'kea'
import { ReactNode, useState } from 'react'
import { IconChevronRight } from '@posthog/icons'
-import { LemonButton, LemonSegmentedButton, LemonSelect, LemonSkeleton, LemonSwitch, Link } from '@posthog/lemon-ui'
-
+import {
+ LemonBanner,
+ LemonButton,
+ LemonSegmentedButton,
+ LemonSelect,
+ LemonSkeleton,
+ LemonSwitch,
+ Link,
+} from '@posthog/lemon-ui'
+
+import api from 'lib/api'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { useIntegrationManagementRestriction } from 'lib/integrations/integrationPermissions'
+import { getGrantedScopes } from 'lib/integrations/IntegrationScopesWarning'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { isSlackMemberTarget, slackChannelDisplayName } from 'lib/integrations/slackChannel'
import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'
import { IconSlack } from 'lib/lemon-ui/icons'
import { urls } from 'scenes/urls'
-import { IntegrationType } from '~/types'
+import { IntegrationType, SlackIntegrationScope } from '~/types'
import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'
import { userAutonomyLogic } from '../../logics/userAutonomyLogic'
@@ -156,6 +167,38 @@ function readSlackTarget(
}
}
+/**
+ * A workspace connected before PostHog requested `users:read`, or one that records no scopes at
+ * all, cannot resolve anyone's account, so the save that asks Slack for it fails. Saying so here,
+ * with the reconnect, is what the failed save could not do: the API answers it as a validation
+ * error on a setting the user already turned on, so the only recovery left was to guess that Slack
+ * had to be reconnected.
+ */
+function DirectMessageUnavailable({ integration }: { integration: IntegrationType }): JSX.Element {
+ const reconnectRestrictionReason = useIntegrationManagementRestriction()
+ return (
+ <LemonBanner
+ type="warning"
+ action={
+ reconnectRestrictionReason
+ ? undefined
+ : {
+ children: 'Reconnect Slack',
+ disableClientSideRouting: true,
+ to: api.integrations.authorizeUrl({
+ kind: integration.kind,
+ next: window.location.pathname,
+ }),
+ }
+ }
+ >
+ PostHog cannot look up members in this Slack workspace without the users:read permission, so it cannot find
+ your account. Reconnect Slack to grant it, or post to a channel instead.
+ {reconnectRestrictionReason ? ' Ask a project admin to reconnect it.' : ''}
+ </LemonBanner>
+ )
+}
+
function DirectMessageTarget({
recipient,
saving,
@@ -224,6 +267,12 @@ function PerUserNotificationCard({ integrations }: { integrations: IntegrationTy
)
const minPriority = autonomyConfig?.slack_notification_min_priority ?? null
+ // Resolving a direct message costs a `users.info` call, so a workspace that never granted the
+ // scope for it can only fail the save. Decide that here instead of sending a save Slack refuses.
+ // An install that records no scopes at all counts as missing it: assuming the scope is what
+ // produced the error nothing in the app could clear.
+ const canDirectMessage = !!integration && getGrantedScopes(integration).includes(SlackIntegrationScope.USERS_READ)
+
// The toggle is view state only: switching it must never write, or an exploratory click would
// clear a saved target. A direct message is the default because it needs no channel set up.
const [pendingMode, setPendingMode] = useState<SlackTargetMode | null>(null)
@@ -233,7 +282,7 @@ function PerUserNotificationCard({ integrations }: { integrations: IntegrationTy
if (enabled) {
// With one workspace there is nothing to pick, so this also sets the direct message up.
setSlackPickersExpanded(true)
- if (integration && selectedIntegrationId === null) {
+ if (integration && selectedIntegrationId === null && canDirectMessage) {
setPendingMode('dm')
updateSlackNotifications({ integrationId: integration.id, directMessage: true })
}
@@ -251,7 +300,7 @@ function PerUserNotificationCard({ integrations }: { integrations: IntegrationTy
}
const onSendDirectMessages = (): void => {
- if (!integration) {
+ if (!integration || !canDirectMessage) {
return
}
setPendingMode('dm')
@@ -328,11 +377,15 @@ function PerUserNotificationCard({ integrations }: { integrations: IntegrationTy
]}
/>
{mode === 'dm' ? (
- <DirectMessageTarget
- recipient={recipient}
- saving={slackNotificationsSaving}
- onEnable={onSendDirectMessages}
- />
+ canDirectMessage ? (
+ <DirectMessageTarget
+ recipient={recipient}
+ saving={slackNotificationsSaving}
+ onEnable={onSendDirectMessages}
+ />
+ ) : (
+ <DirectMessageUnavailable integration={integration} />
+ )
) : (
<ChannelTarget
integration={integration}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c861ad6a1fa4..4b67648b887e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -120331,6 +120331,14 @@ export namespace Schemas {
} as const;
export type IntegrationsChannelsRetrieveParams = {
+ /**
+ * Look up one channel directly by Slack channel ID (e.g. C0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that channel.
+ */
+ channel_id?: string;
+ /**
+ * Bypass the 1 hour channel cache, including for a `channel_id` lookup, which is how a caller reads the channel's current membership after inviting the app to it. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache.
+ */
+ force_refresh?: boolean;
/**
* Maximum number of channels to return per request (max 200).
* @minimum 1
diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.ts
index bd05f3e40f07..d6d2eb2c3f56 100644
--- a/services/mcp/src/generated/integrations/api.ts
+++ b/services/mcp/src/generated/integrations/api.ts
@@ -104,6 +104,8 @@ export const IntegrationsChannelsRetrieveParams = () => zod.object({
),
})
+export const integrationsChannelsRetrieveQueryChannelIdDefault = ``
+export const integrationsChannelsRetrieveQueryForceRefreshDefault = false
export const integrationsChannelsRetrieveQueryLimitDefault = 50
export const integrationsChannelsRetrieveQueryLimitMax = 200
@@ -113,6 +115,18 @@ export const integrationsChannelsRetrieveQueryOffsetMin = 0
export const integrationsChannelsRetrieveQuerySearchDefault = ``
export const IntegrationsChannelsRetrieveQueryParams = () => zod.object({
+ channel_id: zod
+ .string()
+ .default(integrationsChannelsRetrieveQueryChannelIdDefault)
+ .describe(
+ 'Look up one channel directly by Slack channel ID (e.g. C0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that channel.'
+ ),
+ force_refresh: zod
+ .boolean()
+ .default(integrationsChannelsRetrieveQueryForceRefreshDefault)
+ .describe(
+ "Bypass the 1 hour channel cache, including for a `channel_id` lookup, which is how a caller reads the channel's current membership after inviting the app to it. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache."
+ ),
limit: zod
.number()
.min(1)
diff --git a/services/mcp/src/tools/generated/integrations.ts b/services/mcp/src/tools/generated/integrations.ts
index c118062699ae..eaeb379c6f1d 100644
--- a/services/mcp/src/tools/generated/integrations.ts
+++ b/services/mcp/src/tools/generated/integrations.ts
@@ -70,6 +70,8 @@ const integrationsChannelsRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/integrations/${encodeURIComponent(String(params.id))}/channels/`,
query: {
+ channel_id: params.channel_id,
+ force_refresh: params.force_refresh,
limit: params.limit,
offset: params.offset,
search: params.search,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-channels-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-channels-retrieve.json
index 66c741cfea69..a2828bb06886 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-channels-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-channels-retrieve.json
@@ -1,6 +1,16 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "channel_id": {
+ "default": "",
+ "description": "Look up one channel directly by Slack channel ID (e.g. C0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that channel.",
+ "type": "string"
+ },
+ "force_refresh": {
+ "default": false,
+ "description": "Bypass the 1 hour channel cache, including for a `channel_id` lookup, which is how a caller reads the channel's current membership after inviting the app to it. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache.",
+ "type": "boolean"
+ },
"id": {
"description": "A unique integer value identifying this integration.",
"type": "number"