: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): guide users to reconnect Slack when the token is inactive (#73521)
posthog[bot]2e5a7433966c
diff --git a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx b/frontend/src/lib/integrations/SlackChannelPicker.test.tsxindex 7bf40459bfcf..b4e41d6b7280 100644--- a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx+++ b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx@@ -1,9 +1,14 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import '@testing-library/jest-dom'-import { cleanup, render, waitFor } from '@testing-library/react'+import { cleanup, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Provider } from 'kea'+import { OrganizationMembershipLevel } from 'lib/constants'+import { teamLogic } from 'scenes/teamLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { IntegrationType } from '~/types'@@ -290,3 +295,47 @@ describe('SlackChannelPicker', () => {)})})++describe('SlackChannelPicker — inactive integration banner', () => {+ // Reconnecting is an overwrite, which the API reserves for project admins. Offering the OAuth+ // link to a member sends them through the whole flow only to be rejected on the final write.+ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/integrations/:id/channels': () => [+ 400,+ {+ type: 'validation_error',+ code: 'slack_integration_inactive',+ detail: 'Your Slack connection is no longer active.',+ },+ ],+ },+ })+ initKeaTests()+ teamLogic.mount()+ })++ afterEach(() => {+ cleanup()+ })++ it.each([+ [OrganizationMembershipLevel.Admin, true],+ [OrganizationMembershipLevel.Member, false],+ ])('membership level %s renders the reconnect link: %s', async (level, expectsLink) => {+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, effective_membership_level: level })++ render(+ <Provider>+ <SlackChannelPicker integration={INTEGRATION} onChange={jest.fn()} />+ </Provider>+ )++ await waitFor(() => {+ expect(screen.getByText(/Slack connection is no longer active/)).toBeInTheDocument()+ })+ expect(screen.queryByText('Reconnect Slack')).toEqual(expectsLink ? expect.anything() : null)+ expect(screen.queryByText(/Ask a project admin/)).toEqual(expectsLink ? null : expect.anything())+ })+})diff --git a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsxindex 2e3c292325ad..5756578da82a 100644--- a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx+++ b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx@@ -12,7 +12,8 @@ import {} from '@posthog/lemon-ui'import api from 'lib/api'-import { FEATURE_FLAGS } from 'lib/constants'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'import { usePeriodicRerender } from 'lib/hooks/usePeriodicRerender'import { IconSlackExternal } from 'lib/lemon-ui/icons'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -104,8 +105,16 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: SisMemberOfSlackChannel,isPrivateChannelWithoutAccess,getChannelRefreshButtonDisabledReason,+ slackIntegrationInactiveMessage,} = useValues(logic)const { loadAllSlackChannels, loadSlackChannelById, loadSlackChannelByIdSuccess } = useActions(logic)+ // Reconnecting overwrites the existing integration, which the API reserves for project admins+ // (`has_team_management_access`). Without this the banner would send a member through OAuth+ // only to have the write rejected at the end.+ const reconnectRestrictionReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: OrganizationMembershipLevel.Admin,+ })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.@@ -242,6 +251,28 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: Sloading={allSlackChannelsLoading || slackChannelByIdLoading}/>+ {slackIntegrationInactiveMessage ? (+ <LemonBanner type="warning" className="mt-1">+ <div className="flex justify-between gap-2 items-center">+ <span>+ {slackIntegrationInactiveMessage}+ {reconnectRestrictionReason ? ' Ask a project admin to reconnect it.' : ''}+ </span>+ {reconnectRestrictionReason ? null : (+ <Link+ to={api.integrations.authorizeUrl({+ kind: 'slack',+ next: window.location.pathname + '?target_type=slack',+ })}+ disableClientSideRouting+ >+ Reconnect Slack+ </Link>+ )}+ </div>+ </LemonBanner>+ ) : 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.diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts b/frontend/src/lib/integrations/slackIntegrationLogic.test.tsindex 9072ef713e40..e12a93df8590 100644--- a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts+++ b/frontend/src/lib/integrations/slackIntegrationLogic.test.ts@@ -273,6 +273,84 @@ describe('recentSlackChannels store', () => {})})+describe('slackIntegrationLogic — inactive Slack integration', () => {+ let logic: ReturnType<typeof slackIntegrationLogic.build>+ // Toggled per test: when true the channels endpoint responds like a revoked/expired workspace token.+ let respondInactive = false++ const inactiveDetail = 'Your Slack connection is no longer active. Reconnect Slack to load channels.'++ beforeEach(() => {+ respondInactive = false+ useMocks({+ get: {+ '/api/environments/:team_id/integrations/:id/channels': () =>+ respondInactive+ ? [+ 400,+ { type: 'validation_error', code: 'slack_integration_inactive', detail: inactiveDetail },+ ]+ : [+ 200,+ {+ channels: [fixtureChannel('C1', 'general')],+ lastRefreshedAt: '2026-01-01T00:00:00Z',+ },+ ],+ },+ })+ initKeaTests()+ logic = slackIntegrationLogic({ id: 1 })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('surfaces the message inline without a failure toast when the integration is inactive', async () => {+ respondInactive = true++ await expectLogic(logic, () => {+ logic.actions.loadAllSlackChannels()+ })+ .toDispatchActions(['setSlackIntegrationInactive', 'loadAllSlackChannelsSuccess'])+ .toNotHaveDispatchedActions(['loadAllSlackChannelsFailure'])++ expect(logic.values.slackIntegrationInactiveMessage).toBe(inactiveDetail)+ })++ it('keeps previously loaded channels when a later load hits an inactive integration', async () => {+ await expectLogic(logic, () => {+ logic.actions.loadAllSlackChannels()+ }).toFinishAllListeners()+ expect(logic.values.slackChannels.map((c) => c.id)).toEqual(['C1'])++ respondInactive = true+ await expectLogic(logic, () => {+ logic.actions.loadAllSlackChannels()+ }).toFinishAllListeners()++ // The revoked-token load must not wipe the channels the user already had.+ expect(logic.values.slackChannels.map((c) => c.id)).toEqual(['C1'])+ expect(logic.values.slackIntegrationInactiveMessage).toBe(inactiveDetail)+ })++ it('clears the inline message on the next successful load (e.g. after reconnecting)', async () => {+ respondInactive = true+ await expectLogic(logic, () => {+ logic.actions.loadAllSlackChannels()+ }).toFinishAllListeners()+ expect(logic.values.slackIntegrationInactiveMessage).toBe(inactiveDetail)++ respondInactive = false+ await expectLogic(logic, () => {+ logic.actions.loadAllSlackChannels()+ }).toFinishAllListeners()+ expect(logic.values.slackIntegrationInactiveMessage).toBeNull()+ })+})+describe('slackIntegrationLogic — slackChannelsForPicker', () => {let logic: ReturnType<typeof slackIntegrationLogic.build>const allChannels = [diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.ts b/frontend/src/lib/integrations/slackIntegrationLogic.tsindex 631a291b6ad0..157cec7573dc 100644--- a/frontend/src/lib/integrations/slackIntegrationLogic.ts+++ b/frontend/src/lib/integrations/slackIntegrationLogic.ts@@ -12,6 +12,13 @@ import type { PreflightStatus } from '../../types'export const SLACK_CHANNELS_MIN_REFRESH_INTERVAL_SECONDS = 30+// Matches the backend `SlackIntegrationInactiveError.default_code`. When the workspace token is+// revoked/expired the channels endpoint returns this instead of a 500, so we can surface guidance+// inline in the picker rather than spamming a generic error toast on every refresh/search.+export const SLACK_INTEGRATION_INACTIVE_ERROR_CODE = 'slack_integration_inactive'+const SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE =+ 'Your Slack connection is no longer active. Reconnect Slack to load channels and pick a destination.'+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface slackIntegrationLogicValues {preflight: PreflightStatus | null // preflightLogic@@ -32,6 +39,7 @@ export interface slackIntegrationLogicValues {slackChannelByIdLoading: booleanslackChannels: SlackChannelType[]slackChannelsForPicker: SlackChannelType[]+ slackIntegrationInactiveMessage: string | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -55,7 +63,7 @@ export interface slackIntegrationLogicActions {channels: SlackChannelType[]has_more?: boolean | undefinedlastRefreshedAt: string- },+ } | null,payload?: {forceRefresh: booleansearch: string@@ -65,7 +73,7 @@ export interface slackIntegrationLogicActions {channels: SlackChannelType[]has_more?: boolean | undefinedlastRefreshedAt: string- }+ } | nullpayload?: {forceRefresh: booleansearch: string@@ -82,12 +90,12 @@ export interface slackIntegrationLogicActions {errorObject?: any}loadSlackChannelByIdSuccess: (- slackChannelById: SlackChannelType,+ slackChannelById: SlackChannelType | null,payload?: {channelId: string}) => {- slackChannelById: SlackChannelType+ slackChannelById: SlackChannelType | nullpayload?: {channelId: string}@@ -95,6 +103,9 @@ export interface slackIntegrationLogicActions {setRecentlySubscribedChannelIds: (channelIds: string[]) => {channelIds: string[]}+ setSlackIntegrationInactive: (message: string | null) => {+ message: string | null+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -144,9 +155,10 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([loadAllSlackChannels: (forceRefresh: boolean = false, search: string = '') => ({ forceRefresh, search }),loadSlackChannelById: (channelId: string) => ({ channelId }),setRecentlySubscribedChannelIds: (channelIds: string[]) => ({ channelIds }),+ setSlackIntegrationInactive: (message: string | null) => ({ message }),}),- loaders(({ props }) => ({+ loaders(({ props, values, actions }) => ({allSlackChannels: [null as { channels: SlackChannelType[]; lastRefreshedAt: string; has_more?: boolean } | null,{@@ -154,7 +166,17 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([if (search) {await breakpoint(300)}- return await api.integrations.slackChannels(props.id, forceRefresh, { search })+ try {+ return await api.integrations.slackChannels(props.id, forceRefresh, { search })+ } catch (e: any) {+ if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {+ // Keep whatever we had and surface guidance inline instead of throwing,+ // so kea-loaders doesn't fire its generic failure toast on every retry.+ actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)+ return values.allSlackChannels+ }+ throw e+ }},},],@@ -163,8 +185,16 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([{loadSlackChannelById: async ({ channelId }, breakpoint) => {await breakpoint(500)- const res = await api.integrations.slackChannelsById(props.id, channelId)- return res.channels[0] || null+ try {+ const res = await api.integrations.slackChannelsById(props.id, channelId)+ return res.channels[0] || null+ } catch (e: any) {+ if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {+ actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)+ return values.slackChannelById+ }+ throw e+ }},},],@@ -174,7 +204,9 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([_fetchedSlackChannels: [[] as SlackChannelType[],{- loadAllSlackChannelsSuccess: (_, { allSlackChannels }) => allSlackChannels.channels ?? [],+ // allSlackChannels is null when an inactive-integration load resolves with the+ // (empty) prior state instead of throwing — keep the existing channels in that case.+ loadAllSlackChannelsSuccess: (prev, { allSlackChannels }) => allSlackChannels?.channels ?? prev,},],_fetchedSlackChannelById: [@@ -189,6 +221,15 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([setRecentlySubscribedChannelIds: (_, { channelIds }) => channelIds,},],+ slackIntegrationInactiveMessage: [+ null as string | null,+ {+ // Cleared on each fresh fetch attempt so a later success (e.g. after reconnecting) hides the banner.+ loadAllSlackChannels: () => null,+ loadSlackChannelById: () => null,+ setSlackIntegrationInactive: (_, { message }) => message,+ },+ ],})),listeners(({ props, actions }) => ({diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex e8ff5479db59..0ab02a3c27b1 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -2,7 +2,7 @@ import osimport reimport jsonfrom collections.abc import Iterable-from typing import Any, Protocol, cast+from typing import Any, NoReturn, Protocol, castfrom urllib.parse import urlencodefrom django.conf import settings@@ -17,10 +17,11 @@ import structlogfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema, extend_schema_serializerfrom rest_framework import mixins, serializers, status, viewsets-from rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework.exceptions import APIException, PermissionDenied, ValidationErrorfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from slack_sdk.errors import SlackApiErrorfrom posthog.api.github_callback import state as github_callback_statefrom posthog.api.github_callback.team_services import (@@ -103,6 +104,7 @@ from posthog.utils import is_relative_urlfrom products.batch_exports.backend.models.batch_export import get_batch_exports_using_integrationfrom products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integration+from products.slack_app.backend.services.slack_auth import SLACK_AUTH_FAILURE_CODESfrom products.tasks.backend.facade.api import count_in_progress_runs_for_github_integrationfrom products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration@@ -111,6 +113,29 @@ logger = structlog.get_logger(__name__)GITHUB_REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9_.\-]+")+class SlackIntegrationInactiveError(APIException):+ # Actionable 4xx (reconnect Slack) rather than a raw 500, so the channel picker can render+ # guidance inline instead of an unhelpful "server error" toast on every retry.+ status_code = status.HTTP_400_BAD_REQUEST+ default_code = "slack_integration_inactive"+ default_detail = (+ "Your Slack connection is no longer active. Reconnect Slack to load channels and pick a destination."+ )+++def _reraise_slack_api_error(error: SlackApiError) -> NoReturn:+ """Translate an inactive-auth Slack error into an actionable 4xx; re-raise everything else.++ The auth-failure codes come from the Slack auth-state cache, which already decides what+ counts as an install that can no longer authenticate. A second list here would drift from+ it — whatever bricks the workspace there is the same thing the user reconnects to fix.+ """+ error_code = error.response.get("error") if error.response is not None else None+ if error_code in SLACK_AUTH_FAILURE_CODES:+ raise SlackIntegrationInactiveError() from error+ raise error++def _github_account_type(owner_type: str | None) -> str | None:"""Normalize GitHub's account ``type`` ("Organization" / "User") to org vs personal."""if owner_type == "Organization":@@ -1243,7 +1268,10 @@ class IntegrationViewSet(for channel in data["channels"]:if channel["id"] == channel_id:return Response({"channels": [channel]})- channel = slack.get_channel_by_id(channel_id, should_include_private_channels, authed_user)+ try:+ channel = slack.get_channel_by_id(channel_id, should_include_private_channels, authed_user)+ except SlackApiError as e:+ _reraise_slack_api_error(e)if channel:return Response({"channels": [self._serialize_slack_channel(channel)]})return Response({"channels": []})@@ -1257,11 +1285,12 @@ class IntegrationViewSet(data = cache.get(key)if data is None or force_refresh:+ try:+ channels = slack.list_channels(should_include_private_channels, authed_user)+ except SlackApiError as e:+ _reraise_slack_api_error(e)data = {- "channels": [- self._serialize_slack_channel(channel)- for channel in slack.list_channels(should_include_private_channels, authed_user)- ],+ "channels": [self._serialize_slack_channel(channel) for channel in channels],"lastRefreshedAt": timezone.now().isoformat(),}cache.set(key, data, 60 * 60) # one hourdiff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex d945ab6b9bf2..3fe22c970e77 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -18,6 +18,7 @@ import requestsfrom parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.exceptions import ValidationError+from slack_sdk.errors import SlackApiErrorfrom posthog.api.github_callback.state import store_unified_authorize_statefrom posthog.api.github_callback.team_services import (@@ -1943,6 +1944,65 @@ class TestIntegrationAPIKeyAccess:assert response.status_code == status.HTTP_400_BAD_REQUESTassert "authed_user" in response.json()["detail"]+ @pytest.mark.parametrize(+ "slack_error_code,expect_inactive",+ [+ ("account_inactive", True),+ ("invalid_auth", True),+ ("token_revoked", True),+ ("token_expired", True),+ # Slack's answer when the stored bot token is missing or not sent at all — a broken+ # install the user reconnects to fix, not a transient failure.+ ("not_authed", True),+ # A transient/unexpected Slack error must not be masked as an inactive-connection prompt.+ ("ratelimited", False),+ ],+ )+ @patch("posthog.api.integration.SlackIntegration")+ def test_channels_action_inactive_slack_returns_actionable_error(+ self,+ mock_slack_class,+ slack_error_code: str,+ expect_inactive: bool,+ client: HttpClient,+ ):+ slack_integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id=f"T_INACTIVE_{slack_error_code.upper()}",+ 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.list_channels.side_effect = SlackApiError(+ "Slack request failed", {"ok": False, "error": slack_error_code}+ )+ mock_slack_class.return_value = mock_slack_instance++ key_value = f"test_key_inactive_{slack_error_code}"+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scopes=["integration:read"],+ )++ # Don't re-raise the transient case's unhandled error; assert on the 500 response instead.+ client.raise_request_exception = False+ response = client.get(+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/channels/",+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )++ if expect_inactive:+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ body = response.json()+ assert body["code"] == "slack_integration_inactive"+ assert "reconnect slack" in body["detail"].lower()+ else:+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+def test_create_integration_with_api_key_fails(self, client: HttpClient):key_value = "test_key_123"PersonalAPIKey.objects.create(