Skip to content

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

feat(slack_app): add the web setup after a Slack install (#124196)

Vojta Bartoš2795e93cc1ef
diff --git a/frontend/package.json b/frontend/package.json
index 4857761d82dd..24c2967f72f6 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -151,6 +151,7 @@
"@posthog/products-session-replay": "workspace:*",
"@posthog/products-signals": "workspace:*",
"@posthog/products-skills": "workspace:*",
+ "@posthog/products-slack-app": "workspace:*",
"@posthog/products-stamphog": "workspace:*",
"@posthog/products-streamlit-apps": "workspace:*",
"@posthog/products-subscriptions": "workspace:*",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 47245f8a50f1..eddd39b6ce3e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15866,6 +15866,30 @@ snapshots:
hash: v1.k794b7964.6778108ade1085efcddf4ffe0b16a297e741e790672a3b33bc5d986f28a21ab2.i3oD4nY4Kcn08ehCHaLXHi7UVGVBK6MvVyfBqq-sJ8s
scenes-app-signals-scratchpadpanel--populated-narrow--light:
hash: v1.k794b7964.d816589bb55d55a5f400231ca5e2a0cd6b5a64ce1beb6e78287eca1c3b96e455.2bMTo4YcmA5wtKhveMZguqN_MUW1x_sYovK_8HWwfWs
+ scenes-app-slack-app-workspace-setup--ai-consent--dark:
+ hash: v1.k794b7964.3562512c74ded2a4ccfd488e554f397f86de3610fc0ccaace833062b8638e156.ZLfNbt9W6swUW-oRW0zOw-OWetfVoA1bxzIzxBIWByI
+ scenes-app-slack-app-workspace-setup--ai-consent--light:
+ hash: v1.k794b7964.3c0f11fae0537febc2f7836b28b4307bf499068de4a8852c305a33befd5ddfcb.B-PKcVO9GT_AMVvjbBa2mQ1aHvWrV-y6pUHzCFil2oo
+ scenes-app-slack-app-workspace-setup--channels--dark:
+ hash: v1.k794b7964.eacb39c776002b200eb9a9e406344359d7cfa40e5ed9e74a602eec6e7cee8ece.LYJBtNg-6_QZllgrxIoZPYIvR9ArCcsA_gqphYV3bJc
+ scenes-app-slack-app-workspace-setup--channels--light:
+ hash: v1.k794b7964.5816cbd03786c8232ab2930e08309204fc69395a5d1aa34715e48630868b57b3.g27e0kl61_440b2EyayJJ7iResN5h0aWqPyFELUlZpE
+ scenes-app-slack-app-workspace-setup--channels-without-welcome--dark:
+ hash: v1.k794b7964.e918166a865ed8306cda2f0f5eb9a642b77f1d7d71e1afaa7952f7c8d5ee50c6.ZBFyJZeVbTCYJEOZEyg5IxDcGLaN0k7KRn0-SFtqxzg
+ scenes-app-slack-app-workspace-setup--channels-without-welcome--light:
+ hash: v1.k794b7964.03399474d4150ef279e3ab35528b75278dff4821af6ea6dc01df23f36a492a88.PjlXa1GAqecJhkRH3eXhqbouqWqOGv5FCE8GQ0yLYKU
+ scenes-app-slack-app-workspace-setup--default-project--dark:
+ hash: v1.k794b7964.c2ce24a9a14ef3d096bca60e839a487803bdfe4d5676f0b3ab9077906e1e58e5.EehyzZM8JOj_rzxWZjQBpXrrLnLPm4giy9Gs5236OiU
+ scenes-app-slack-app-workspace-setup--default-project--light:
+ hash: v1.k794b7964.0d44c29790c73b07928bd7e79a6d7bc028e69f5ea40f584a7c7928b425c6a33f.dDQBZafMBLPtu5E7gdTuubqwtwR2Mg_05_HvMIjGfz4
+ scenes-app-slack-app-workspace-setup--done--dark:
+ hash: v1.k794b7964.2dac189f18d8495b4e7ff319ea987051f4f27df06b3590500b6366778537d2d1.geVF0sn736hDd-gGiuJ3J6yemktjXP2VnbhXPIQNhOU
+ scenes-app-slack-app-workspace-setup--done--light:
+ hash: v1.k794b7964.8f5c3b1700cd81b4482899dea9f2a2b8e87855a09237a302939fa59e83274db4._bbA72Xv3JiOG7QOuUVwTcswqM78AN8XkfObnX82-2U
+ scenes-app-slack-app-workspace-setup--done-from-settings--dark:
+ hash: v1.k794b7964.e63dca0640c9531e301e436c81f47fded633e05f46b9a1bd9b04b05bab392527.8Wot76c-chwAyrANL5OXm4Ytw8wbBqa0mP54QtWPNJc
+ scenes-app-slack-app-workspace-setup--done-from-settings--light:
+ hash: v1.k794b7964.36ed36daab731e6b5dff3560bfb3becf79684c6c6cd9dc8fe4ea08f88f05fb1c.914SoPzQ8leWnBnjLf_macALBulhwY4LAGcSEWkCLec
scenes-app-stamphog-digests--digest-expanded--dark:
hash: v1.k794b7964.c37367d7ed65cc0d69dfa67eaa60a4857d0583997d7c46ac61624a459ca66430.LN5ob34i8KQC7FZRnu7UEBIT50kaufpYjSW8Q6z4Gy0
scenes-app-stamphog-digests--digest-expanded--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 2046755e5b3d..3753dc2a098e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -528,6 +528,7 @@ export const FEATURE_FLAGS = {
SHOW_REFERRER_FAVICON: 'show-referrer-favicon', // owner: @jordanm-posthog #team-web-analytics
SHOW_REPLAY_FILTERS_FEEDBACK_BUTTON: 'show-replay-filters-feedback-button', // owner: @ksvat #team-replay
SIGNUP_AA_TEST_4_WAY: 'signup-aa-test-4-way', // owner: @andehen #team-experiments multivariate=control,test-1,test-2,test-3
+ SLACK_APP_WORKSPACE_SETUP: 'slack-app-workspace-setup', // owner: #team-surfaces, sends new Slack app installs to the web setup
SLACK_DWH: 'slack-dwh', // owner: @MarconLP #team-warehouse-sources
SQL_EDITOR_BI_MODE: 'sql-editor-bi-mode', // owner: @mariusandra #team-data-tools
SQL_EDITOR_SAVE_AS_CHOOSER: 'sql-editor-save-as-chooser', // owner: #team-data-tools
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 4c008ff8247a..7e40cc3183b4 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -6,6 +6,7 @@ import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api, { ApiError, getCookie } from 'lib/api'
import { globalSetupLogic } from 'lib/components/ProductSetup'
+import { FEATURE_FLAGS } from 'lib/constants'
import { buildGithubDisconnectDescription } from 'lib/integrations/githubDisconnectCopy'
import { describeGithubSetupError, GITHUB_INSTALL_PENDING_MESSAGE } from 'lib/integrations/githubSetupErrors'
import { describeScopeShortfall, getMissingScopes, requestedScopesForKind } from 'lib/integrations/integrationScopes'
@@ -14,10 +15,12 @@ import {
INTEGRATION_ERROR_PARAM,
OAUTH_STATE_EXPIRED,
} from 'lib/integrations/oauthCallbackErrors'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { isKeyOf } from 'lib/utils/guards'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { retryImport } from 'lib/utils/retryImport'
import { fromParamsGivenUrl } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -103,11 +106,33 @@ export function reconnectReturnUrl(pathname: string, search: string): string {
return query ? `${pathname}?${query}` : pathname
}
+// The Slack landing page offers the setup itself, so only the other entry points get the toast.
+function offerSlackSetupAfterConnect(
+ integration: IntegrationType,
+ pathname: string,
+ {
+ currentTeamId,
+ initiatingTeamId,
+ setupEnabled,
+ }: { currentTeamId: number | null; initiatingTeamId: number | undefined; setupEnabled: boolean }
+): void {
+ const landsOnSlackPage = removeProjectIdIfPresent(pathname) === urls.integration('slack')
+ const otherTeam = initiatingTeamId !== undefined && initiatingTeamId !== currentTeamId
+ if (integration.kind !== 'slack' || !setupEnabled || landsOnSlackPage || otherTeam || !currentTeamId) {
+ return
+ }
+ void retryImport(() => import('products/slack_app/frontend/workspace-setup/offerSlackWorkspaceSetup'))
+ .then(({ offerSlackWorkspaceSetup }) => offerSlackWorkspaceSetup(currentTeamId, integration.id, pathname))
+ .catch(() => {})
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface integrationsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
preflight: PreflightStatus | null // preflightLogic
siteUrlMisconfigured: boolean // preflightLogic
currentProjectId: number | string // teamLogic
+ currentTeamId: number | null // teamLogic
accessRequest: IntegrationKind | null
accessRequestLoading: boolean
accessRequestReason: string
@@ -786,7 +811,14 @@ export type integrationsLogicType = MakeLogicType<
export const integrationsLogic = kea<integrationsLogicType>([
path(['lib', 'integrations', 'integrationsLogic']),
connect(() => ({
- values: [preflightLogic, ['siteUrlMisconfigured', 'preflight'], teamLogic, ['currentProjectId']],
+ values: [
+ preflightLogic,
+ ['siteUrlMisconfigured', 'preflight'],
+ teamLogic,
+ ['currentProjectId', 'currentTeamId'],
+ featureFlagLogic,
+ ['featureFlags'],
+ ],
actions: [
globalSetupLogic,
['markTaskAsCompleted'],
@@ -1370,6 +1402,12 @@ export const integrationsLogic = kea<integrationsLogicType>([
} else {
lemonToast.success(`Integration successful.`)
}
+
+ offerSlackSetupAfterConnect(integration, url.pathname, {
+ currentTeamId: values.currentTeamId,
+ initiatingTeamId,
+ setupEnabled: !!values.featureFlags[FEATURE_FLAGS.SLACK_APP_WORKSPACE_SETUP],
+ })
}
} catch (e) {
toastApiError(e)
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index 4ed8a6e49d02..c49e2d9fe218 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -176,6 +176,8 @@ export const productScenes: Record<string, () => Promise<any>> = {
Skills: () => import('../../products/skills/frontend/LLMSkillsScene'),
Skill: () => import('../../products/skills/frontend/LLMSkillScene'),
CommunitySkills: () => import('../../products/skills/frontend/CommunitySkillsScene'),
+ SlackAppWorkspaceSetup: () =>
+ import('../../products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupScene'),
Stamphog: () => import('../../products/stamphog/frontend/scenes/StamphogScene/StamphogScene'),
StamphogRuns: () => import('../../products/stamphog/frontend/scenes/StamphogRunsScene/StamphogRunsScene'),
StamphogDigests: () => import('../../products/stamphog/frontend/scenes/StamphogDigestsScene/StamphogDigestsScene'),
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index da1f98c32174..45b547103e61 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -323,6 +323,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/skills/review-hog': ['Skills', 'skillsReviewHog'],
'/skills/community': ['CommunitySkills', 'communitySkills'],
'/skills/:name': ['Skill', 'skill'],
+ '/integrations/slack/:integrationId/setup': ['SlackAppWorkspaceSetup', 'slackAppWorkspaceSetup'],
'/stamphog': ['Stamphog', 'stamphog'],
'/stamphog/runs': ['StamphogRuns', 'stamphogRuns'],
'/stamphog/digests': ['StamphogDigests', 'stamphogDigests'],
@@ -1223,6 +1224,7 @@ export const productConfiguration: Record<string, any> = {
layout: 'app-container',
iconType: 'llm_prompts',
},
+ SlackAppWorkspaceSetup: { projectBased: true, name: 'Slack app setup', layout: 'plain' },
Stamphog: { projectBased: true, name: 'Stamphog', iconType: 'stamphog', activityScope: 'StamphogRepoConfig' },
StamphogRuns: { projectBased: true, name: 'Stamphog runs', iconType: 'stamphog' },
StamphogDigests: { projectBased: true, name: 'Stamphog digests', iconType: 'stamphog' },
@@ -1964,6 +1966,7 @@ export const productUrls = {
}
): string => combineUrl(`/skills/${name}`, params).url,
communitySkills: (): string => '/skills/community',
+ slackAppWorkspaceSetup: (integrationId: number | string): string => `/integrations/slack/${integrationId}/setup`,
stamphog: (): string => '/stamphog',
stamphogRuns: (): string => '/stamphog/runs',
stamphogDigests: (): string => '/stamphog/digests',
diff --git a/frontend/src/scenes/integrations/IntegrationFullPage.tsx b/frontend/src/scenes/integrations/IntegrationFullPage.tsx
index a5e28864107b..5ada44019aca 100644
--- a/frontend/src/scenes/integrations/IntegrationFullPage.tsx
+++ b/frontend/src/scenes/integrations/IntegrationFullPage.tsx
@@ -197,7 +197,7 @@ function ConnectedView({
</div>
) : null}
- <ConnectedNextStep />
+ <ConnectedNextStep definition={definition} integrations={integrations} />
</>
)
}
@@ -209,8 +209,15 @@ function ConnectedView({
* provisioned account lands in an onboarding it never started, an unonboarded existing account gets
* bounced there by the onboarding gate, and an onboarded one is pulled away from the run mid-flight.
*/
-function ConnectedNextStep(): JSX.Element {
+function ConnectedNextStep({
+ definition,
+ integrations,
+}: {
+ definition: IntegrationDefinition
+ integrations: IntegrationType[]
+}): JSX.Element {
const { inFlight, resolved } = useSelfDrivingRunState()
+ const setupUrl = definition.useSetupUrl?.(integrations) ?? null
// Until the detector answers, assume the run: this page is reached by clicking through a
// provider's consent screen, which is overwhelmingly something a run sent the user off to do,
@@ -229,6 +236,14 @@ function ConnectedNextStep(): JSX.Element {
)
}
+ if (setupUrl) {
+ return (
+ <LemonButton type="primary" to={setupUrl} data-attr="integration-continue-setup">
+ Continue setup
+ </LemonButton>
+ )
+ }
+
return (
<LemonButton type="primary" to={urls.projectHomepage()}>
Go to PostHog
diff --git a/frontend/src/scenes/integrations/components/SlackIntegration.tsx b/frontend/src/scenes/integrations/components/SlackIntegration.tsx
index d0c78ccb66c8..8687388bcd66 100644
--- a/frontend/src/scenes/integrations/components/SlackIntegration.tsx
+++ b/frontend/src/scenes/integrations/components/SlackIntegration.tsx
@@ -3,11 +3,12 @@ import { useMemo, useState } from 'react'
import { LemonButton, Link } from '@posthog/lemon-ui'
-import api from 'lib/api'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { integrationAuthorizeUrl, integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IntegrationView } from 'lib/integrations/IntegrationView'
+import type { IntegrationConnectSurface } from 'lib/integrations/utils'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -51,9 +52,14 @@ const getSlackAppManifest = (): any => ({
},
})
-export function SlackIntegration({ next, centered }: { next?: string; centered?: boolean } = {}): JSX.Element {
+export function SlackIntegration({
+ next,
+ centered,
+ connectSurface,
+}: { next?: string; centered?: boolean; connectSurface?: IntegrationConnectSurface } = {}): JSX.Element {
const { slackIntegrations, slackAvailable } = useValues(integrationsLogic)
const { startPolling, stopPolling } = useActions(integrationsLogic)
+ const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)
const [showSlackInstructions, setShowSlackInstructions] = useState(false)
useOnMountEffect(() => {
@@ -75,7 +81,16 @@ export function SlackIntegration({ next, centered }: { next?: string; centered?:
<div>
{slackAvailable ? (
<div className={centered ? 'flex flex-col items-center gap-2 text-center' : undefined}>
- <Link to={api.integrations.authorizeUrl({ kind: 'slack', next })} disableClientSideRouting>
+ <Link
+ to={integrationAuthorizeUrl({ kind: 'slack', next })}
+ disableClientSideRouting
+ // Silent without `connectSurface`, because the OAuth landing page reports its own clicks.
+ onClick={
+ connectSurface
+ ? () => reportIntegrationConnectClicked('slack', 'slack', connectSurface)
+ : undefined
+ }
+ >
<img
alt="Connect to Slack workspace"
height="40"
diff --git a/frontend/src/scenes/integrations/definitions/slack.tsx b/frontend/src/scenes/integrations/definitions/slack.tsx
index 3d27011a2e42..6fe543c846ce 100644
--- a/frontend/src/scenes/integrations/definitions/slack.tsx
+++ b/frontend/src/scenes/integrations/definitions/slack.tsx
@@ -1,13 +1,24 @@
+import { useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { getMissingScopes } from 'lib/integrations/integrationScopes'
import { IntegrationScopesWarning } from 'lib/integrations/IntegrationScopesWarning'
+import { OAUTH_INTEGRATION_ID_PARAM } from 'lib/integrations/integrationsLogic'
import { ICONS } from 'lib/integrations/utils'
+import { urls } from 'scenes/urls'
import { IntegrationType } from '~/types'
+import {
+ parseSlackSetupReturnTarget,
+ SLACK_SETUP_RETURN_PARAM,
+} from 'products/slack_app/frontend/workspace-setup/slackSetupReturn'
+
import { SlackIntegration } from '../components/SlackIntegration'
import { useSlackRequiredScopes } from '../components/slackScopes'
import { defineIntegration } from '../integrationDefinition'
-import { IntegrationStatus } from '../integrationTypes'
+import { IntegrationStatus, SettingsSectionComponent } from '../integrationTypes'
// Render the scopes-mismatch banner directly under the OAuth success card so an install with
// the wrong scope set surfaces it while the user is still in the install flow, instead of
@@ -28,6 +39,35 @@ function useSlackStatus(integrations: IntegrationType[]): IntegrationStatus {
return anyNeedsAttention ? 'needs_attention' : 'ok'
}
+// Only the install that the OAuth callback just created has its id in the URL, so a later visit keeps "Go to PostHog".
+function useSlackSetupUrl(integrations: IntegrationType[]): string | null {
+ const enabled = useFeatureFlag('SLACK_APP_WORKSPACE_SETUP')
+ const { searchParams } = useValues(router)
+ const newIntegrationId = Number(searchParams[OAUTH_INTEGRATION_ID_PARAM])
+ if (!enabled || !integrations.some((integration) => integration.id === newIntegrationId)) {
+ return null
+ }
+ const returnTo = parseSlackSetupReturnTarget(searchParams[SLACK_SETUP_RETURN_PARAM])
+ return combineUrl(urls.slackAppWorkspaceSetup(newIntegrationId), {
+ entry: 'slack_page',
+ ...(returnTo ? { [SLACK_SETUP_RETURN_PARAM]: returnTo } : {}),
+ }).url
+}
+
+// A connect from Settings is deliberate, so it continues to the setup and then returns to Settings.
+function SlackSettingsSection({
+ next,
+ centered,
+ connectSurface,
+}: Parameters<SettingsSectionComponent>[0]): JSX.Element {
+ const setupEnabled = useFeatureFlag('SLACK_APP_WORKSPACE_SETUP')
+ const returnNext =
+ setupEnabled && connectSurface === 'settings'
+ ? combineUrl(urls.integration('slack'), { [SLACK_SETUP_RETURN_PARAM]: 'settings' }).url
+ : next
+ return <SlackIntegration next={returnNext} centered={centered} connectSurface={connectSurface} />
+}
+
export const Slack = defineIntegration(
{
slug: 'slack',
@@ -48,6 +88,7 @@ export const Slack = defineIntegration(
docsUrl: 'https://posthog.com/docs/libraries/slack',
PostConnect: SlackPostConnect,
useStatus: useSlackStatus,
+ useSetupUrl: useSlackSetupUrl,
},
- SlackIntegration
+ SlackSettingsSection
)
diff --git a/frontend/src/scenes/integrations/integrationTypes.ts b/frontend/src/scenes/integrations/integrationTypes.ts
index 84a89a59588c..5f5177a28ece 100644
--- a/frontend/src/scenes/integrations/integrationTypes.ts
+++ b/frontend/src/scenes/integrations/integrationTypes.ts
@@ -34,6 +34,9 @@ export type IntegrationStatus = 'ok' | 'needs_attention'
*/
export type IntegrationStatusHook = (integrations: IntegrationType[]) => IntegrationStatus
+/** Must follow the Rules of Hooks, like {@link IntegrationStatusHook}. */
+export type IntegrationSetupUrlHook = (integrations: IntegrationType[]) => string | null
+
/**
* Pure metadata describing an integration. Deliberately holds no components so each
* integration is easy to reason about — components are bundled onto {@link Integration}.
@@ -68,6 +71,8 @@ export interface IntegrationDefinition {
* copy for a warning icon and follow-up copy that points at {@link PostConnect}.
*/
useStatus?: IntegrationStatusHook
+ /** When it returns a URL, the landing page's primary action goes there instead of the app. */
+ useSetupUrl?: IntegrationSetupUrlHook
}
/** A definition bundled with its renderable components. */
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 29aa781516d1..7efe7bf025fd 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -2129,7 +2129,7 @@ export const SETTINGS_MAP: SettingSection[] = [
description:
'Integrate with Slack to subscribe to insights or dashboards for regular reports to channels of your choice.',
docsUrl: Slack.docsUrl,
- component: <Slack.SettingsSection />,
+ component: <Slack.SettingsSection connectSurface="settings" />,
keywords: ['slack', 'channel', 'notification', 'subscribe', 'report'],
},
{
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e4c5675bc655..037abbd361f5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -829,6 +829,9 @@ importers:
'@posthog/products-skills':
specifier: workspace:*
version: link:../products/skills
+ '@posthog/products-slack-app':
+ specifier: workspace:*
+ version: link:../products/slack_app
'@posthog/products-stamphog':
specifier: workspace:*
version: link:../products/stamphog
@@ -5197,7 +5200,39 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
- products/slack_app: {}
+ products/slack_app:
+ dependencies:
+ '@posthog/icons':
+ specifier: 'catalog:'
+ '@posthog/lemon-ui':
+ specifier: '*'
+ version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])))([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))([email protected]([email protected]))([email protected])
+ '@storybook/react':
+ specifier: 'catalog:'
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+ kea-loaders:
+ specifier: 'catalog:'
+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ kea-router:
+ specifier: 'catalog:'
+ version: 3.4.2([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.444.4(@types/[email protected])([email protected])
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ devDependencies:
+ kea-test-utils:
+ specifier: 'catalog:'
+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
products/stamphog:
dependencies:
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 0f802d878b74..d57625abd378 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -3636,6 +3636,16 @@ def _release_channel_onboarding_claim(slack_team_id: str, channel_id: str) -> No
cache.delete(_channel_onboarding_cache_key(slack_team_id, channel_id))
+def skip_channel_welcome(slack_team_id: str, channel_id: str) -> bool:
+ """Hold the welcome slot before the bot joins a channel, so it joins without a welcome message.
+ Returns False when another flow already holds the slot."""
+ return _claim_channel_onboarding(slack_team_id, channel_id)
+
+
+def release_channel_welcome_skip(slack_team_id: str, channel_id: str) -> None:
+ _release_channel_onboarding_claim(slack_team_id, channel_id)
+
+
def _post_channel_onboarding_message(
slack: SlackIntegration,
integration: WorkspaceIntegration,
diff --git a/products/slack_app/backend/facade/api.py b/products/slack_app/backend/facade/api.py
index d9c18c9a1eb3..87bf8d0b6a52 100644
--- a/products/slack_app/backend/facade/api.py
+++ b/products/slack_app/backend/facade/api.py
@@ -4,12 +4,14 @@ The ONLY module other products are allowed to import. Keep the surface narrow:
every function here lives behind a tach contract check, so each addition has a
cost in cross-product coupling.
-Today the facade exists for five jobs: letting core's OAuth callback invalidate
+Today the facade exists for six jobs: letting core's OAuth callback invalidate
the per-integration auth-state cache when a Slack install is reconnected,
answering whether a channel has been approved for PostHog to speak in,
telling a product that posts a report whether the bot can answer a follow-up,
turning an agent's tool calls into the progress lines of a streamed Slack
-reply, and recording that a Slack user used a feature, so feature tips skip it. All are stable re-exports so the implementations can move around inside
+reply, recording that a Slack user used a feature, so feature tips skip it,
+and serving the web setup after a Slack install to this product's presentation
+layer. All are stable re-exports so the implementations can move around inside
slack_app without breaking their callers.
This module's import graph must not reach ``products.signals``. That product now imports this
@@ -20,13 +22,15 @@ body instead, the way the handlers under ``backend/`` already do.
from __future__ import annotations
-from typing import Any
+from typing import TYPE_CHECKING, Any
import structlog
-from posthog.integrations import IntegrationRecord
+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecord
from posthog.models.integration import Integration
+from products.slack_app.backend.facade.enums import SlackSetupEntry
+from products.slack_app.backend.facade.types import ChannelJoinResult, ChannelOption, SlackSetupNotFound, WorkspaceSetup
from products.slack_app.backend.logic.feature_tips.features import SlackFeature
from products.slack_app.backend.logic.feature_tips.state import record_feature_used
from products.slack_app.backend.logic.progress_phases import (
@@ -48,9 +52,14 @@ from products.slack_app.backend.logic.progress_phases import (
)
from products.slack_app.backend.models import SlackChannel
from products.slack_app.backend.services.followup_invite import build_followup_invite, build_followup_invite_text
+from products.slack_app.backend.services.public_channel_catalog import public_channel_options
from products.slack_app.backend.services.slack_auth import invalidate_auth_state
from products.slack_app.backend.services.slack_scopes import SLACK_CANVAS_SCOPE, SLACK_FILE_SCOPE, has_scopes
from products.slack_app.backend.services.slack_user_info import invalidate_workspace_bot_user_id
+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, with_teams
+
+if TYPE_CHECKING:
+ from posthog.models import User
__all__ = [
"ANSWER_LINE_TITLE",
@@ -69,6 +78,10 @@ __all__ = [
"phase_for_tool_call",
"phase_line_title",
"tool_call_from_acp_update",
+ "get_slack_workspace_setup",
+ "join_slack_setup_channels",
+ "list_slack_setup_channels",
+ "set_slack_workspace_default_project",
"invalidate_slack_integration_auth_state",
"record_slack_feature_used",
"slack_artifact_delivery_state_updates",
@@ -159,3 +172,43 @@ def record_slack_feature_used(integration_id: int, slack_user_id: str | None, fe
return
if slack_workspace_id:
record_feature_used(slack_workspace_id, slack_user_id, feature)
+
+
+def _setup_integration(team_id: int, integration_id: int) -> WorkspaceIntegration:
+ try:
+ return with_teams([IntegrationManager.slack.oauth.get(team_id, integration_id)])[0]
+ except IntegrationNotFound as error:
+ raise SlackSetupNotFound(f"No Slack app install {integration_id} in project {team_id}") from error
+
+
+def get_slack_workspace_setup(team_id: int, integration_id: int, user: User, entry: SlackSetupEntry) -> WorkspaceSetup:
+ # The setup logic reaches products.signals through the integration resolver. See the module docstring.
+ from products.slack_app.backend.logic import workspace_setup # noqa: PLC0415
+
+ return workspace_setup.get_workspace_setup(_setup_integration(team_id, integration_id), user, entry)
+
+
+def set_slack_workspace_default_project(
+ team_id: int, integration_id: int, user: User, target_integration_id: int
+) -> WorkspaceSetup:
+ # The setup logic reaches products.signals through the integration resolver. See the module docstring.
+ from products.slack_app.backend.logic import workspace_setup # noqa: PLC0415
+
+ integration = _setup_integration(team_id, integration_id)
+ workspace_setup.set_default_project(integration, user, target_integration_id)
+ return workspace_setup.get_workspace_setup(integration, user, SlackSetupEntry.OTHER)
+
+
+def list_slack_setup_channels(team_id: int, integration_id: int) -> tuple[ChannelOption, ...]:
+ return public_channel_options(_setup_integration(team_id, integration_id))
+
+
+def join_slack_setup_channels(
+ team_id: int, integration_id: int, user: User, channel_ids: list[str], *, post_welcome: bool
+) -> tuple[ChannelJoinResult, ...]:
+ # The setup logic reaches products.signals through the integration resolver. See the module docstring.
+ from products.slack_app.backend.logic import workspace_setup # noqa: PLC0415
+
+ return workspace_setup.join_channels(
+ _setup_integration(team_id, integration_id), user, channel_ids, post_welcome=post_welcome
+ )
diff --git a/products/slack_app/backend/facade/enums.py b/products/slack_app/backend/facade/enums.py
new file mode 100644
index 000000000000..02f6197b928e
--- /dev/null
+++ b/products/slack_app/backend/facade/enums.py
@@ -0,0 +1,12 @@
+from posthog.enums import LabeledStrEnum
+
+
+class SlackSetupStepKey(LabeledStrEnum):
+ AI_CONSENT = "ai_consent", "AI data processing"
+ DEFAULT_PROJECT = "default_project", "Default project"
+ CHANNELS = "channels", "Channels"
+
+
+class SlackSetupEntry(LabeledStrEnum):
+ SLACK_PAGE = "slack_page", "The Slack page in PostHog"
+ OTHER = "other", "Another place, such as a channel picker"
diff --git a/products/slack_app/backend/facade/types.py b/products/slack_app/backend/facade/types.py
new file mode 100644
index 000000000000..e9b60ae55389
--- /dev/null
+++ b/products/slack_app/backend/facade/types.py
@@ -0,0 +1,48 @@
+from posthog.dataclasses import frozen
+
+from products.slack_app.backend.facade.enums import SlackSetupStepKey
+
+# Slack rate limits conversations.join, and a long list in one request would hold the request open.
+MAX_CHANNELS_TO_JOIN = 20
+
+
+class SlackSetupNotFound(Exception):
+ """The project has no Slack app install with this id."""
+
+
+class WorkspaceSettingsError(Exception):
+ """The person cannot change this workspace setting. The message says why."""
+
+
+class ChannelCatalogBusy(Exception):
+ """The workspace cannot list its Slack channels now. The message tells the person what to do."""
+
+
+@frozen
+class ProjectOption:
+ integration_id: int
+ project_name: str
+ organization_name: str
+
+
+@frozen
+class WorkspaceSetup:
+ integration_id: int
+ slack_workspace_name: str | None
+ open_slack_url: str | None
+ steps: tuple[SlackSetupStepKey, ...]
+ project_options: tuple[ProjectOption, ...]
+ can_post_channel_welcome: bool
+
+
+@frozen
+class ChannelOption:
+ id: str
+ name: str
+ is_member: bool
+
+
+@frozen
+class ChannelJoinResult:
+ channel_id: str
+ error: str | None
diff --git a/products/slack_app/backend/logic/workspace_setup.py b/products/slack_app/backend/logic/workspace_setup.py
new file mode 100644
index 000000000000..992b24d0e758
--- /dev/null
+++ b/products/slack_app/backend/logic/workspace_setup.py
@@ -0,0 +1,204 @@
+"""The web setup after a Slack install. It asks only for what blocks the Slack app for everyone; the
+rest of the setup happens in Slack. Steps store no progress: each one reads its status from the
+database every time."""
+
+from collections.abc import Callable
+from functools import cached_property
+from urllib.parse import urlencode
+
+from posthog.dataclasses import frozen
+from posthog.integrations import IntegrationRecord
+from posthog.models import OrganizationMembership, User
+from posthog.models.integration import SlackIntegration
+from posthog.slack.channels import join_channel
+from posthog.user_permissions import UserPermissions
+
+from products.slack_app.backend.analytics import capture_slack_event
+from products.slack_app.backend.facade.enums import SlackSetupEntry, SlackSetupStepKey
+from products.slack_app.backend.facade.types import (
+ ChannelJoinResult,
+ ProjectOption,
+ WorkspaceSettingsError,
+ WorkspaceSetup,
+)
+from products.slack_app.backend.models import ChannelWelcomeMode
+from products.slack_app.backend.services.integration_resolver import accessible_candidates
+from products.slack_app.backend.services.public_channel_catalog import mark_channels_joined, public_channel_options
+from products.slack_app.backend.services.slack_scopes import has_scopes
+from products.slack_app.backend.services.slack_settings import (
+ resolve_channel_welcome_mode,
+ resolve_workspace_default_integration_id,
+ set_workspace_default_integration,
+)
+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration, workspace_integrations
+
+SLACK_APP_REDIRECT_URL = "https://slack.com/app_redirect"
+CHANNELS_JOIN_SCOPE = "channels:join"
+# pinned: analytics property value, the same events can come from other surfaces later
+EVENT_SOURCE = "web_setup"
+
+
+@frozen(slots=False)
+class SetupContext:
+ integration: WorkspaceIntegration
+ user: User
+ entry: SlackSetupEntry
+
+ @property
+ def slack_workspace_id(self) -> str:
+ return self.integration.integration_id or ""
+
+ @cached_property
+ def project_options(self) -> list[WorkspaceIntegration]:
+ """Projects connected to this Slack workspace that the person can open, oldest install first."""
+ return accessible_candidates(workspace_integrations(self.slack_workspace_id), user=self.user)
+
+
+@frozen
+class SetupStep:
+ key: SlackSetupStepKey
+ applies: Callable[[SetupContext], bool]
+ is_done: Callable[[SetupContext], bool]
+
+
+def _ai_consent_applies(ctx: SetupContext) -> bool:
+ return not ctx.integration.team.organization.is_ai_data_processing_approved
+
+
+def _default_project_applies(ctx: SetupContext) -> bool:
+ return len(ctx.project_options) >= 2
+
+
+def _default_project_is_done(ctx: SetupContext) -> bool:
+ return resolve_workspace_default_integration_id(ctx.slack_workspace_id) is not None
+
+
+def _channels_applies(ctx: SetupContext) -> bool:
+ # Only a deliberate setup asks for channels, not a connect in the middle of another task.
+ return ctx.entry == SlackSetupEntry.SLACK_PAGE and has_scopes(ctx.integration, [CHANNELS_JOIN_SCOPE])
+
+
+def _never_done(_: SetupContext) -> bool:
+ return False
+
+
+# Ordered by priority: a step that blocks every answer in Slack comes first.
+SETUP_STEPS: tuple[SetupStep, ...] = (
+ SetupStep(key=SlackSetupStepKey.AI_CONSENT, applies=_ai_consent_applies, is_done=_never_done),
+ SetupStep(
+ key=SlackSetupStepKey.DEFAULT_PROJECT, applies=_default_project_applies, is_done=_default_project_is_done
+ ),
+ SetupStep(key=SlackSetupStepKey.CHANNELS, applies=_channels_applies, is_done=_never_done),
+)
+
+
+def open_slack_url(integration: IntegrationRecord) -> str | None:
+ """A link that opens the app's direct message in the installer's Slack workspace."""
+ app_id = (integration.config or {}).get("app_id")
+ if not app_id or not integration.integration_id:
+ return None
+ return f"{SLACK_APP_REDIRECT_URL}?{urlencode({'app': app_id, 'team': integration.integration_id})}"
+
+
+def get_workspace_setup(integration: WorkspaceIntegration, user: User, entry: SlackSetupEntry) -> WorkspaceSetup:
+ ctx = SetupContext(integration=integration, user=user, entry=entry)
+ # is_done first, because it is cheaper than the project list that some applies checks load.
+ steps = tuple(step.key for step in SETUP_STEPS if not step.is_done(ctx) and step.applies(ctx))
+ return WorkspaceSetup(
+ integration_id=integration.id,
+ slack_workspace_name=((integration.config or {}).get("team") or {}).get("name"),
+ open_slack_url=open_slack_url(integration),
+ steps=steps,
+ project_options=tuple(
+ ProjectOption(
+ integration_id=option.id,
+ project_name=option.team.name,
+ organization_name=option.team.organization.name,
+ )
+ for option in ctx.project_options
+ )
+ if SlackSetupStepKey.DEFAULT_PROJECT in steps
+ else (),
+ can_post_channel_welcome=SlackSetupStepKey.CHANNELS in steps
+ and _can_post_channel_welcome(ctx.slack_workspace_id),
+ )
+
+
+def _can_post_channel_welcome(slack_workspace_id: str) -> bool:
+ # The other modes need the person who added the bot, and a join from the setup has none, so
+ # the channel join handler posts nothing.
+ return resolve_channel_welcome_mode(slack_workspace_id) == ChannelWelcomeMode.CHANNEL
+
+
+def _can_change_workspace_settings(integration: WorkspaceIntegration, user: User) -> bool:
+ # These settings change the Slack workspace for everyone in it.
+ if integration.created_by_id == user.id:
+ return True
+ level = UserPermissions(user=user).team(integration.team).effective_membership_level
+ return level is not None and level >= OrganizationMembership.Level.ADMIN
+
+
+def set_default_project(integration: WorkspaceIntegration, user: User, target_integration_id: int) -> None:
+ if not _can_change_workspace_settings(integration, user):
+ raise WorkspaceSettingsError(
+ "Only the person who installed Slack or a project admin can set the default project."
+ )
+ ctx = SetupContext(integration=integration, user=user, entry=SlackSetupEntry.OTHER)
+ target = next((option for option in ctx.project_options if option.id == target_integration_id), None)
+ if target is None:
+ raise WorkspaceSettingsError("This project is not connected to this Slack workspace, or you can't open it.")
+ set_workspace_default_integration(ctx.slack_workspace_id, target.id)
+ # pinned: analytics event and property names, renaming breaks dashboards
+ capture_slack_event(
+ integration,
+ "slack app workspace default project set",
+ posthog_user=user,
+ source=EVENT_SOURCE,
+ default_integration_id=target.id,
+ project_count=len(ctx.project_options),
+ )
+
+
+def join_channels(
+ integration: WorkspaceIntegration, user: User, channel_ids: list[str], *, post_welcome: bool
+) -> tuple[ChannelJoinResult, ...]:
+ from products.slack_app.backend.api import ( # noqa: PLC0415 — api.py imports the services this module uses
+ release_channel_welcome_skip,
+ skip_channel_welcome,
+ )
+
+ if not _can_change_workspace_settings(integration, user):
+ raise WorkspaceSettingsError(
+ "Only the person who installed Slack or a project admin can add PostHog to channels."
+ )
+ if not has_scopes(integration, [CHANNELS_JOIN_SCOPE]):
+ raise WorkspaceSettingsError("This Slack install can't join channels. Invite PostHog with /invite @PostHog.")
+
+ # The ids come from the browser, so only channels from the same list the page showed are joined.
+ allowed = {option.id for option in public_channel_options(integration)}
+ slack = SlackIntegration(integration)
+ slack_workspace_id = integration.integration_id or ""
+ post_welcome = post_welcome and _can_post_channel_welcome(slack_workspace_id)
+ results: list[ChannelJoinResult] = []
+ for channel_id in dict.fromkeys(channel_ids):
+ if channel_id not in allowed:
+ results.append(ChannelJoinResult(channel_id=channel_id, error="channel_not_available"))
+ continue
+ holds_welcome_slot = not post_welcome and skip_channel_welcome(slack_workspace_id, channel_id)
+ error = join_channel(slack, channel_id)
+ if error is not None and holds_welcome_slot:
+ release_channel_welcome_skip(slack_workspace_id, channel_id)
+ results.append(ChannelJoinResult(channel_id=channel_id, error=error))
+ mark_channels_joined(slack_workspace_id, (result.channel_id for result in results if result.error is None))
+ failed_count = sum(1 for result in results if result.error is not None)
+ # pinned: analytics event and property names, renaming breaks dashboards
+ capture_slack_event(
+ integration,
+ "slack app channels joined",
+ posthog_user=user,
+ source=EVENT_SOURCE,
+ joined_count=len(results) - failed_count,
+ failed_count=failed_count,
+ post_welcome=post_welcome,
+ )
+ return tuple(results)
diff --git a/products/slack_app/backend/presentation/__init__.py b/products/slack_app/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/slack_app/backend/presentation/views.py b/products/slack_app/backend/presentation/views.py
new file mode 100644
index 000000000000..047869d64bca
--- /dev/null
+++ b/products/slack_app/backend/presentation/views.py
@@ -0,0 +1,205 @@
+from typing import Any, cast
+
+from drf_spectacular.utils import OpenApiResponse
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, Throttled
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import User
+
+from products.slack_app.backend.facade.api import (
+ get_slack_workspace_setup,
+ join_slack_setup_channels,
+ list_slack_setup_channels,
+ set_slack_workspace_default_project,
+)
+from products.slack_app.backend.facade.enums import SlackSetupEntry, SlackSetupStepKey
+from products.slack_app.backend.facade.types import (
+ MAX_CHANNELS_TO_JOIN,
+ ChannelCatalogBusy,
+ SlackSetupNotFound,
+ WorkspaceSettingsError,
+)
+
+
+class SlackAppProjectOptionSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(help_text="ID of the Slack integration that connects this project.")
+ project_name = serializers.CharField(help_text="Name of the PostHog project.")
+ organization_name = serializers.CharField(help_text="Name of the organization that owns the project.")
+
+
+class SlackAppWorkspaceSetupSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(help_text="ID of the Slack integration that this setup is for.")
+ slack_workspace_name = serializers.CharField(
+ allow_null=True, help_text="Name of the Slack workspace, as Slack sent it at install time."
+ )
+ open_slack_url = serializers.URLField(
+ allow_null=True,
+ help_text="Link that opens the PostHog app's direct message in this Slack workspace. Null when the install has no app ID.",
+ )
+ steps = serializers.ListField(
+ child=serializers.ChoiceField(choices=SlackSetupStepKey.choices),
+ help_text=(
+ "Setup steps that apply to this install and are not done yet, in display order. "
+ "ai_consent: the organization must allow AI data processing. "
+ "default_project: the Slack workspace connects to 2 or more projects and has no default. "
+ "channels: the install can join channels, and the setup started on the Slack page."
+ ),
+ )
+ project_options = SlackAppProjectOptionSerializer(
+ many=True,
+ help_text="Projects connected to this Slack workspace that the person can open. Empty unless default_project is a step.",
+ )
+ can_post_channel_welcome = serializers.BooleanField(
+ help_text=(
+ "Whether a channel join from this setup can post the welcome message in the channel. "
+ "False when channels is not a step, or when the workspace sends the welcome only to the inviter or turns it off."
+ ),
+ )
+
+
+class SlackAppWorkspaceSetupQuerySerializer(serializers.Serializer):
+ entry = serializers.ChoiceField(
+ choices=SlackSetupEntry.choices,
+ default=SlackSetupEntry.OTHER,
+ help_text="Where the Slack install started. slack_page adds the steps for a person who sets up Slack on purpose.",
+ )
+
+
+class SlackAppDefaultProjectSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(
+ help_text="ID of the Slack integration of the project that becomes the workspace default."
+ )
+
+
+class SlackAppChannelOptionSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Slack channel ID.")
+ name = serializers.CharField(help_text="Channel name, without the leading #.")
+ is_member = serializers.BooleanField(help_text="Whether PostHog is already in the channel.")
+
+
+class SlackAppChannelOptionsSerializer(serializers.Serializer):
+ channels = SlackAppChannelOptionSerializer(
+ many=True, help_text="Public channels that PostHog can join. Shared channels are left out."
+ )
+
+
+class SlackAppJoinChannelsSerializer(serializers.Serializer):
+ channel_ids = serializers.ListField(
+ child=serializers.CharField(),
+ min_length=1,
+ max_length=MAX_CHANNELS_TO_JOIN,
+ help_text="IDs of the public channels that PostHog joins.",
+ )
+ post_welcome = serializers.BooleanField(
+ default=True,
+ help_text="Whether PostHog posts its welcome message in each channel it joins. When false, it joins quietly.",
+ )
+
+
+class SlackAppChannelJoinResultSerializer(serializers.Serializer):
+ channel_id = serializers.CharField(help_text="Slack channel ID.")
+ error = serializers.CharField(
+ allow_null=True, help_text="Slack's error code when PostHog could not join, or null when it joined."
+ )
+
+
+class SlackAppJoinChannelsResultSerializer(serializers.Serializer):
+ results = SlackAppChannelJoinResultSerializer(many=True, help_text="The result for each channel, in request order.")
+
+
+CHANNEL_LIST_THROTTLED = (
+ "Slack's channel list for this workspace is loading in another request, or it was loaded too often recently."
+)
+
+
+class SlackAppWorkspaceSetupViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "integration"
+ scope_object_read_actions = ["retrieve", "channels"]
+ scope_object_write_actions = ["default_project", "join_channels"]
+
+ def _integration_id(self, pk: str | None) -> int:
+ try:
+ return int(pk or "")
+ except ValueError:
+ raise NotFound()
+
+ @validated_request(
+ query_serializer=SlackAppWorkspaceSetupQuerySerializer,
+ responses={200: OpenApiResponse(response=SlackAppWorkspaceSetupSerializer)},
+ summary="Get the web setup steps for a Slack app install",
+ )
+ def retrieve(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ entry = SlackSetupEntry(request.validated_query_data["entry"])
+ try:
+ setup = get_slack_workspace_setup(self.team_id, self._integration_id(pk), cast(User, request.user), entry)
+ except SlackSetupNotFound as error:
+ raise NotFound() from error
+ return Response(SlackAppWorkspaceSetupSerializer(setup).data)
+
+ @validated_request(
+ request_serializer=SlackAppDefaultProjectSerializer,
+ responses={200: OpenApiResponse(response=SlackAppWorkspaceSetupSerializer)},
+ summary="Set the default project for the Slack workspace of a Slack app install",
+ )
+ @action(detail=True, methods=["post"], url_path="default_project")
+ def default_project(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ try:
+ setup = set_slack_workspace_default_project(
+ self.team_id,
+ self._integration_id(pk),
+ cast(User, request.user),
+ request.validated_data["integration_id"],
+ )
+ except SlackSetupNotFound as error:
+ raise NotFound() from error
+ except WorkspaceSettingsError as error:
+ raise PermissionDenied(str(error)) from error
+ return Response(SlackAppWorkspaceSetupSerializer(setup).data)
+
+ @validated_request(
+ responses={
+ 200: OpenApiResponse(response=SlackAppChannelOptionsSerializer),
+ 429: OpenApiResponse(description=CHANNEL_LIST_THROTTLED),
+ },
+ summary="List the public channels that PostHog can join for a Slack app install",
+ )
+ @action(detail=True, methods=["get"], url_path="channels")
+ def channels(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ try:
+ options = list_slack_setup_channels(self.team_id, self._integration_id(pk))
+ except SlackSetupNotFound as error:
+ raise NotFound() from error
+ except ChannelCatalogBusy as error:
+ raise Throttled(detail=str(error)) from error
+ return Response(SlackAppChannelOptionsSerializer({"channels": options}).data)
+
+ @validated_request(
+ request_serializer=SlackAppJoinChannelsSerializer,
+ responses={
+ 200: OpenApiResponse(response=SlackAppJoinChannelsResultSerializer),
+ 429: OpenApiResponse(description=CHANNEL_LIST_THROTTLED),
+ },
+ summary="Add PostHog to public channels of a Slack app install",
+ )
+ @action(detail=True, methods=["post"], url_path="join_channels")
+ def join_channels(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ try:
+ results = join_slack_setup_channels(
+ self.team_id,
+ self._integration_id(pk),
+ cast(User, request.user),
+ request.validated_data["channel_ids"],
+ post_welcome=request.validated_data["post_welcome"],
+ )
+ except SlackSetupNotFound as error:
+ raise NotFound() from error
+ except WorkspaceSettingsError as error:
+ raise PermissionDenied(str(error)) from error
+ except ChannelCatalogBusy as error:
+ raise Throttled(detail=str(error)) from error
+ return Response(SlackAppJoinChannelsResultSerializer({"results": results}).data)
diff --git a/products/slack_app/backend/routes.py b/products/slack_app/backend/routes.py
new file mode 100644
index 000000000000..4d3b3e52592a
--- /dev/null
+++ b/products/slack_app/backend/routes.py
@@ -0,0 +1,12 @@
+from posthog.api.routing import RouterRegistry
+
+from products.slack_app.backend.presentation.views import SlackAppWorkspaceSetupViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(
+ r"slack_app_workspace_setup",
+ SlackAppWorkspaceSetupViewSet,
+ "project_slack_app_workspace_setup",
+ ["team_id"],
+ )
diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.py
index 9f577edcc989..663e9d8bc832 100644
--- a/products/slack_app/backend/services/commands.py
+++ b/products/slack_app/backend/services/commands.py
@@ -343,7 +343,7 @@ def _handle_project_show(
)
-def _handle_project_set(
+def _reachable_project_integration(
slack: SlackIntegration,
channel: str,
thread_ts: str,
@@ -351,12 +351,11 @@ def _handle_project_set(
slack_workspace_id: str,
user_id: int,
target_team_id: int,
- workspace_candidates: Sequence[WorkspaceIntegration] | None = None,
-) -> None:
+ workspace_candidates: Sequence[WorkspaceIntegration] | None,
+) -> WorkspaceIntegration | None:
+ """The workspace's install for the target project, or None after telling the Slack user why not."""
from posthog.models.user import User
- from products.slack_app.backend.models import SlackSettings
-
user = User.objects.get(id=user_id)
if not user.teams.filter(id=target_team_id).exists():
post_slack_ephemeral(
@@ -366,7 +365,7 @@ def _handle_project_set(
thread_ts=thread_ts,
text=f"You don't have access to project `{target_team_id}`.",
)
- return
+ return None
if workspace_candidates is not None:
target = next((c for c in workspace_candidates if c.team_id == target_team_id), None)
@@ -380,6 +379,25 @@ def _handle_project_set(
thread_ts=thread_ts,
text=f"Project `{target_team_id}` isn't connected to this Slack workspace.",
)
+ return target
+
+
+def _handle_project_set(
+ slack: SlackIntegration,
+ channel: str,
+ thread_ts: str,
+ slack_user_id: str,
+ slack_workspace_id: str,
+ user_id: int,
+ target_team_id: int,
+ workspace_candidates: Sequence[WorkspaceIntegration] | None = None,
+) -> None:
+ from products.slack_app.backend.models import SlackSettings
+
+ target = _reachable_project_integration(
+ slack, channel, thread_ts, slack_user_id, slack_workspace_id, user_id, target_team_id, workspace_candidates
+ )
+ if target is None:
return
SlackSettings.objects.update_or_create(
@@ -417,9 +435,8 @@ def _handle_project_set_workspace(
which applies to every Slack user in the workspace without a personal default.
Restricted to Slack workspace admins and owners.
"""
- from posthog.models.user import User
- from products.slack_app.backend.models import SlackSettings
+ from products.slack_app.backend.services.slack_settings import set_workspace_default_integration
from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin
if not is_slack_workspace_admin(slack, integration, slack_user_id):
@@ -432,36 +449,13 @@ def _handle_project_set_workspace(
)
return
- user = User.objects.get(id=user_id)
- if not user.teams.filter(id=target_team_id).exists():
- post_slack_ephemeral(
- slack.client,
- channel=channel,
- user=slack_user_id,
- thread_ts=thread_ts,
- text=f"You don't have access to project `{target_team_id}`.",
- )
- return
-
- if workspace_candidates is not None:
- target = next((c for c in workspace_candidates if c.team_id == target_team_id), None)
- else:
- target = get_team_workspace_integration(target_team_id, slack_workspace_id)
+ target = _reachable_project_integration(
+ slack, channel, thread_ts, slack_user_id, slack_workspace_id, user_id, target_team_id, workspace_candidates
+ )
if target is None:
- post_slack_ephemeral(
- slack.client,
- channel=channel,
- user=slack_user_id,
- thread_ts=thread_ts,
- text=f"Project `{target_team_id}` isn't connected to this Slack workspace.",
- )
return
- SlackSettings.objects.update_or_create(
- slack_workspace_id=slack_workspace_id,
- slack_user_id=None,
- defaults={"default_integration_id": target.id},
- )
+ set_workspace_default_integration(slack_workspace_id, target.id)
post_slack_ephemeral(
slack.client,
channel=channel,
diff --git a/products/slack_app/backend/services/public_channel_catalog.py b/products/slack_app/backend/services/public_channel_catalog.py
new file mode 100644
index 000000000000..fb853d71abe3
--- /dev/null
+++ b/products/slack_app/backend/services/public_channel_catalog.py
@@ -0,0 +1,103 @@
+"""The public channels that the Slack app can join in a workspace, cached per workspace.
+
+Slack rate limits ``conversations.list`` per app and workspace, and one walk can take up to 100
+pages. Every project that installs the app in a workspace shares that quota, so the list is cached
+per workspace, only one request at a time fills it, and a workspace can start only a few fills in
+each window, however often the cache empties.
+"""
+
+import time
+from collections.abc import Iterable
+
+from django.core.cache import cache
+
+from posthog.integrations import IntegrationRecord
+from posthog.models.integration import SlackIntegration
+from posthog.slack.channels import is_shared_channel
+
+from products.slack_app.backend.facade.types import ChannelCatalogBusy, ChannelOption
+
+CATALOG_TTL_SECONDS = 10 * 60
+FILLS_PER_WINDOW = 3
+FILL_WINDOW_SECONDS = 10 * 60
+# Longer than a full walk, so a slow fill does not let a second fill start.
+FILL_LOCK_SECONDS = 60
+# How long a request that lost the fill waits for the winner's list before it gives up.
+FILL_WAIT_SECONDS = 3.0
+FILL_POLL_SECONDS = 0.1
+
+
+def _catalog_key(slack_workspace_id: str) -> str:
+ return f"slack_app:public_channels:v1:{slack_workspace_id}"
+
+
+def _to_options(cached: list[dict]) -> tuple[ChannelOption, ...]:
+ return tuple(ChannelOption(id=item["id"], name=item["name"], is_member=item["is_member"]) for item in cached)
+
+
+def _wait_for_fill(key: str) -> list[dict] | None:
+ deadline = time.monotonic() + FILL_WAIT_SECONDS
+ while time.monotonic() < deadline:
+ time.sleep(FILL_POLL_SECONDS)
+ cached = cache.get(key)
+ if cached is not None:
+ return cached
+ return None
+
+
+def _take_fill_budget(slack_workspace_id: str) -> None:
+ budget_key = f"{_catalog_key(slack_workspace_id)}:fills"
+ try:
+ fills = 1 if cache.add(budget_key, 1, FILL_WINDOW_SECONDS) else cache.incr(budget_key)
+ except ValueError:
+ # The counter expired between the add and the incr, so this fill opens the next window.
+ fills = 1
+ if fills > FILLS_PER_WINDOW:
+ raise ChannelCatalogBusy(
+ "PostHog loaded this workspace's Slack channels too often. Try again in a few minutes."
+ )
+
+
+def public_channel_options(integration: IntegrationRecord) -> tuple[ChannelOption, ...]:
+ """Leaves out shared channels, because people outside the workspace would see the bot there."""
+ slack_workspace_id = integration.integration_id or ""
+ key = _catalog_key(slack_workspace_id)
+ cached = cache.get(key)
+ if cached is not None:
+ return _to_options(cached)
+
+ fill_key = f"{key}:filling"
+ if not cache.add(fill_key, 1, FILL_LOCK_SECONDS):
+ cached = _wait_for_fill(key)
+ if cached is not None:
+ return _to_options(cached)
+ # A winner that died leaves no list, so one waiting request takes over the fill.
+ if not cache.add(fill_key, 1, FILL_LOCK_SECONDS):
+ raise ChannelCatalogBusy("PostHog is still loading the Slack channels. Try again in a moment.")
+
+ try:
+ _take_fill_budget(slack_workspace_id)
+ channels = SlackIntegration(integration).list_public_channels()
+ catalog = [
+ {"id": channel["id"], "name": channel["name"], "is_member": bool(channel.get("is_member"))}
+ for channel in channels
+ if not is_shared_channel(channel)
+ ]
+ cache.set(key, catalog, CATALOG_TTL_SECONDS)
+ finally:
+ cache.delete(fill_key)
+ return _to_options(catalog)
+
+
+def mark_channels_joined(slack_workspace_id: str, channel_ids: Iterable[str]) -> None:
+ """Update the cached list after joins, so the page stops offering those channels without a new walk."""
+ joined = set(channel_ids)
+ key = _catalog_key(slack_workspace_id)
+ cached = cache.get(key)
+ if not joined or cached is None:
+ return
+ cache.set(
+ key,
+ [{**item, "is_member": item["is_member"] or item["id"] in joined} for item in cached],
+ CATALOG_TTL_SECONDS,
+ )
diff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.py
index ab53a3086e36..109ae8ac4e6b 100644
--- a/products/slack_app/backend/services/slack_settings.py
+++ b/products/slack_app/backend/services/slack_settings.py
@@ -188,6 +188,30 @@ def set_auto_model_choice(slack_workspace_id: str, slack_user_id: str, enabled:
)
+def resolve_workspace_default_integration_id(slack_workspace_id: str) -> int | None:
+ """The integration that the workspace-wide row routes mentions to."""
+
+ from products.slack_app.backend.models import SlackSettings
+
+ return (
+ SlackSettings.objects.filter(slack_workspace_id=slack_workspace_id, slack_user_id__isnull=True)
+ .values_list("default_integration_id", flat=True)
+ .first()
+ )
+
+
+def set_workspace_default_integration(slack_workspace_id: str, integration_id: int) -> None:
+ """The caller checks that the actor may set the default."""
+
+ from products.slack_app.backend.models import SlackSettings
+
+ SlackSettings.objects.update_or_create(
+ slack_workspace_id=slack_workspace_id,
+ slack_user_id=None,
+ defaults={"default_integration_id": integration_id},
+ )
+
+
__all__ = [
"AIPreferences",
"resolve_auto_model_choice",
@@ -200,4 +224,6 @@ __all__ = [
"resolve_thread_join_mode",
"set_thread_join_mode",
"resolve_untagged_followup_mode",
+ "resolve_workspace_default_integration_id",
+ "set_workspace_default_integration",
]
diff --git a/products/slack_app/backend/tests/views/test_workspace_setup.py b/products/slack_app/backend/tests/views/test_workspace_setup.py
new file mode 100644
index 000000000000..16dab5437eca
--- /dev/null
+++ b/products/slack_app/backend/tests/views/test_workspace_setup.py
@@ -0,0 +1,266 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import ANY, MagicMock, patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, OrganizationMembership, User
+from posthog.models.integration import Integration
+from posthog.models.team.team import Team
+
+from products.slack_app.backend.api import _channel_onboarding_cache_key
+from products.slack_app.backend.models import SlackSettings
+from products.slack_app.backend.services.public_channel_catalog import FILLS_PER_WINDOW, _catalog_key
+
+SLACK_TEAM_ID = "T12345"
+CATALOG_SLACK = "products.slack_app.backend.services.public_channel_catalog.SlackIntegration"
+
+
+class TestSlackAppWorkspaceSetup(APIBaseTest):
+ def _slack_install(self, team: Team, created_by: User | None = None, scope: str = "") -> Integration:
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id=SLACK_TEAM_ID,
+ config={"app_id": "A777", "team": {"id": SLACK_TEAM_ID, "name": "Hedgebox"}, "scope": scope},
+ sensitive_config={"access_token": "xoxb-test"},
+ created_by=created_by,
+ )
+
+ def _url(self, integration_id: int, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/slack_app_workspace_setup/{integration_id}/{suffix}"
+
+ def _second_project(self) -> Team:
+ return Team.objects.create(organization=self.organization, name="Hedgebox mobile")
+
+ @parameterized.expand(
+ [
+ ("nothing_to_do", True, False, False, "other", "", []),
+ ("ai_not_allowed", False, False, False, "other", "", ["ai_consent"]),
+ ("two_projects_no_default", True, True, False, "other", "", ["default_project"]),
+ ("two_projects_with_default", True, True, True, "other", "", []),
+ ("both", False, True, False, "other", "", ["ai_consent", "default_project"]),
+ ("channels_on_slack_page", True, False, False, "slack_page", "channels:join", ["channels"]),
+ ("channels_need_the_scope", True, False, False, "slack_page", "chat:write", []),
+ ("channels_need_the_slack_page", True, False, False, "other", "channels:join", []),
+ ("all", False, True, False, "slack_page", "channels:join", ["ai_consent", "default_project", "channels"]),
+ ]
+ )
+ def test_steps(
+ self,
+ _name: str,
+ ai_allowed: bool,
+ two_projects: bool,
+ has_default: bool,
+ entry: str,
+ scope: str,
+ expected: list,
+ ) -> None:
+ self.organization.is_ai_data_processing_approved = ai_allowed
+ self.organization.save()
+ integration = self._slack_install(self.team, created_by=self.user, scope=scope)
+ if two_projects:
+ other = self._slack_install(self._second_project())
+ if has_default:
+ SlackSettings.objects.create(
+ slack_workspace_id=SLACK_TEAM_ID, slack_user_id=None, default_integration=other
+ )
+
+ response = self.client.get(self._url(integration.id), {"entry": entry})
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["steps"] == expected
+ assert body["slack_workspace_name"] == "Hedgebox"
+ assert body["open_slack_url"] == f"https://slack.com/app_redirect?app=A777&team={SLACK_TEAM_ID}"
+ expected_options = 2 if "default_project" in expected else 0
+ assert len(body["project_options"]) == expected_options
+
+ @parameterized.expand([("channel", True), ("inviter", False), ("off", False)])
+ def test_channel_welcome_follows_the_workspace_setting(self, mode: str, expected: bool) -> None:
+ integration = self._slack_install(self.team, created_by=self.user, scope="channels:join")
+ SlackSettings.objects.create(slack_workspace_id=SLACK_TEAM_ID, slack_user_id=None, channel_welcome_mode=mode)
+
+ body = self.client.get(self._url(integration.id), {"entry": "slack_page"}).json()
+
+ assert body["steps"] == ["channels"]
+ assert body["can_post_channel_welcome"] is expected
+
+ def test_project_options_leave_out_projects_the_person_cannot_open(self) -> None:
+ integration = self._slack_install(self.team, created_by=self.user)
+ self._slack_install(self._second_project())
+ other_org = Organization.objects.create(name="Other company")
+ self._slack_install(Team.objects.create(organization=other_org, name="Not mine"))
+
+ body = self.client.get(self._url(integration.id)).json()
+
+ assert body["steps"] == ["default_project"]
+ assert [option["project_name"] for option in body["project_options"]] == [self.team.name, "Hedgebox mobile"]
+
+ @parameterized.expand([("other_team",), ("other_kind",)])
+ def test_returns_404_for_an_integration_it_must_not_read(self, case: str) -> None:
+ if case == "other_team":
+ integration = self._slack_install(self._second_project())
+ else:
+ integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})
+
+ response = self.client.get(self._url(integration.id))
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ @patch("products.slack_app.backend.logic.workspace_setup.capture_slack_event")
+ def test_installer_sets_the_workspace_default(self, mock_capture: MagicMock) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ integration = self._slack_install(self.team, created_by=self.user)
+ other = self._slack_install(self._second_project())
+
+ response = self.client.post(self._url(integration.id, "default_project/"), {"integration_id": other.id})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["steps"] == []
+ stored = SlackSettings.objects.get(slack_workspace_id=SLACK_TEAM_ID, slack_user_id__isnull=True)
+ assert stored.default_integration_id == other.id
+ mock_capture.assert_called_once_with(
+ ANY,
+ "slack app workspace default project set",
+ posthog_user=self.user,
+ source="web_setup",
+ default_integration_id=other.id,
+ project_count=2,
+ )
+
+ @parameterized.expand([("not_installer_or_admin",), ("project_not_reachable",)])
+ def test_default_project_is_refused(self, case: str) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ if case == "not_installer_or_admin":
+ installer = User.objects.create_and_join(self.organization, "[email protected]", None)
+ integration = self._slack_install(self.team, created_by=installer)
+ target = self._slack_install(self._second_project())
+ else:
+ integration = self._slack_install(self.team, created_by=self.user)
+ target = self._slack_install(Team.objects.create(organization=Organization.objects.create(name="Other")))
+
+ response = self.client.post(self._url(integration.id, "default_project/"), {"integration_id": target.id})
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not SlackSettings.objects.filter(slack_workspace_id=SLACK_TEAM_ID, slack_user_id__isnull=True).exists()
+
+ @patch(CATALOG_SLACK)
+ def test_channel_options_leave_out_shared_channels_and_are_listed_once_per_workspace(
+ self, mock_slack: MagicMock
+ ) -> None:
+ integration = self._slack_install(self.team, created_by=self.user, scope="channels:join")
+ other_project_install = self._slack_install(self._second_project(), created_by=self.user)
+ mock_slack.return_value.list_public_channels.return_value = [
+ {"id": "C1", "name": "product", "is_member": False},
+ {"id": "C2", "name": "growth", "is_member": True},
+ {"id": "C3", "name": "with-a-customer", "is_member": False, "is_ext_shared": True},
+ ]
+
+ response = self.client.get(self._url(integration.id, "channels/"))
+ other_project_url = f"/api/projects/{other_project_install.team_id}/slack_app_workspace_setup/{other_project_install.id}/channels/"
+ other_project_response = self.client.get(other_project_url)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {
+ "channels": [
+ {"id": "C1", "name": "product", "is_member": False},
+ {"id": "C2", "name": "growth", "is_member": True},
+ ]
+ }
+ assert other_project_response.json() == response.json()
+ mock_slack.return_value.list_public_channels.assert_called_once()
+
+ @parameterized.expand([("quietly", False), ("with_welcome", True)])
+ @patch("products.slack_app.backend.logic.workspace_setup.capture_slack_event")
+ @patch("products.slack_app.backend.logic.workspace_setup.join_channel")
+ @patch(CATALOG_SLACK)
+ def test_join_channels(
+ self, _name: str, post_welcome: bool, mock_slack: MagicMock, mock_join: MagicMock, mock_capture: MagicMock
+ ) -> None:
+ integration = self._slack_install(self.team, created_by=self.user, scope="channels:join")
+ mock_slack.return_value.list_public_channels.return_value = [
+ {"id": "C1", "name": "product", "is_member": False},
+ {"id": "C2", "name": "growth", "is_member": False},
+ {"id": "C9", "name": "with-a-customer", "is_member": False, "is_shared": True},
+ ]
+ mock_join.side_effect = lambda _slack, channel_id: "is_archived" if channel_id == "C2" else None
+ self.client.get(self._url(integration.id, "channels/"))
+
+ response = self.client.post(
+ self._url(integration.id, "join_channels/"),
+ {"channel_ids": ["C1", "C2", "C9"], "post_welcome": post_welcome},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["results"] == [
+ {"channel_id": "C1", "error": None},
+ {"channel_id": "C2", "error": "is_archived"},
+ {"channel_id": "C9", "error": "channel_not_available"},
+ ]
+ assert [call.args[1] for call in mock_join.call_args_list] == ["C1", "C2"]
+ # A quiet join holds the welcome slot of each joined channel, so the join event posts no welcome.
+ assert (cache.get(_channel_onboarding_cache_key(SLACK_TEAM_ID, "C1")) is not None) is not post_welcome
+ assert cache.get(_channel_onboarding_cache_key(SLACK_TEAM_ID, "C2")) is None
+ mock_capture.assert_called_once_with(
+ ANY,
+ "slack app channels joined",
+ posthog_user=self.user,
+ source="web_setup",
+ joined_count=1,
+ failed_count=2,
+ post_welcome=post_welcome,
+ )
+ mock_slack.return_value.list_public_channels.assert_called_once()
+ channels_after_join = self.client.get(self._url(integration.id, "channels/")).json()["channels"]
+ assert [channel["is_member"] for channel in channels_after_join] == [True, False]
+
+ @parameterized.expand(
+ [
+ ("another_request_is_listing", "channels/"),
+ ("refresh_budget_spent", "channels/"),
+ ("refresh_budget_spent", "join_channels/"),
+ ]
+ )
+ @patch("products.slack_app.backend.services.public_channel_catalog.FILL_WAIT_SECONDS", 0)
+ @patch("products.slack_app.backend.logic.workspace_setup.join_channel")
+ @patch(CATALOG_SLACK)
+ def test_channel_list_does_not_call_slack_when_the_workspace_is_throttled(
+ self, case: str, suffix: str, mock_slack: MagicMock, mock_join: MagicMock
+ ) -> None:
+ integration = self._slack_install(self.team, created_by=self.user, scope="channels:join")
+ if case == "another_request_is_listing":
+ cache.add(f"{_catalog_key(SLACK_TEAM_ID)}:filling", 1, 60)
+ else:
+ cache.set(f"{_catalog_key(SLACK_TEAM_ID)}:fills", FILLS_PER_WINDOW, 600)
+
+ if suffix == "channels/":
+ response = self.client.get(self._url(integration.id, suffix))
+ else:
+ response = self.client.post(self._url(integration.id, suffix), {"channel_ids": ["C1"]}, format="json")
+
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ mock_slack.return_value.list_public_channels.assert_not_called()
+ mock_join.assert_not_called()
+
+ @parameterized.expand([("not_installer_or_admin", "channels:join"), ("no_join_scope", "chat:write")])
+ @patch("products.slack_app.backend.logic.workspace_setup.join_channel")
+ def test_join_channels_is_refused(self, case: str, scope: str, mock_join: MagicMock) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ installer = (
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+ if case == "not_installer_or_admin"
+ else self.user
+ )
+ integration = self._slack_install(self.team, created_by=installer, scope=scope)
+
+ response = self.client.post(self._url(integration.id, "join_channels/"), {"channel_ids": ["C1"]}, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_join.assert_not_called()
diff --git a/products/slack_app/frontend/generated/api.schemas.ts b/products/slack_app/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..c79f7bd2de06
--- /dev/null
+++ b/products/slack_app/frontend/generated/api.schemas.ts
@@ -0,0 +1,115 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * * `ai_consent` - AI data processing
+ * * `default_project` - Default project
+ * * `channels` - Channels
+ */
+export type SlackSetupStepKeyEnumApi = (typeof SlackSetupStepKeyEnumApi)[keyof typeof SlackSetupStepKeyEnumApi]
+
+export const SlackSetupStepKeyEnumApi = {
+ AiConsent: 'ai_consent',
+ DefaultProject: 'default_project',
+ Channels: 'channels',
+} as const
+
+export interface SlackAppProjectOptionApi {
+ /** ID of the Slack integration that connects this project. */
+ integration_id: number
+ /** Name of the PostHog project. */
+ project_name: string
+ /** Name of the organization that owns the project. */
+ organization_name: string
+}
+
+export interface SlackAppWorkspaceSetupApi {
+ /** ID of the Slack integration that this setup is for. */
+ integration_id: number
+ /**
+ * Name of the Slack workspace, as Slack sent it at install time.
+ * @nullable
+ */
+ slack_workspace_name: string | null
+ /**
+ * Link that opens the PostHog app's direct message in this Slack workspace. Null when the install has no app ID.
+ * @nullable
+ */
+ open_slack_url: string | null
+ /** Setup steps that apply to this install and are not done yet, in display order. ai_consent: the organization must allow AI data processing. default_project: the Slack workspace connects to 2 or more projects and has no default. channels: the install can join channels, and the setup started on the Slack page. */
+ steps: SlackSetupStepKeyEnumApi[]
+ /** Projects connected to this Slack workspace that the person can open. Empty unless default_project is a step. */
+ project_options: SlackAppProjectOptionApi[]
+ /** Whether a channel join from this setup can post the welcome message in the channel. False when channels is not a step, or when the workspace sends the welcome only to the inviter or turns it off. */
+ can_post_channel_welcome: boolean
+}
+
+export interface SlackAppChannelOptionApi {
+ /** Slack channel ID. */
+ id: string
+ /** Channel name, without the leading #. */
+ name: string
+ /** Whether PostHog is already in the channel. */
+ is_member: boolean
+}
+
+export interface SlackAppChannelOptionsApi {
+ /** Public channels that PostHog can join. Shared channels are left out. */
+ channels: SlackAppChannelOptionApi[]
+}
+
+export interface SlackAppDefaultProjectApi {
+ /** ID of the Slack integration of the project that becomes the workspace default. */
+ integration_id: number
+}
+
+export interface SlackAppJoinChannelsApi {
+ /**
+ * IDs of the public channels that PostHog joins.
+ * @minItems 1
+ * @maxItems 20
+ */
+ channel_ids: string[]
+ /** Whether PostHog posts its welcome message in each channel it joins. When false, it joins quietly. */
+ post_welcome?: boolean
+}
+
+export interface SlackAppChannelJoinResultApi {
+ /** Slack channel ID. */
+ channel_id: string
+ /**
+ * Slack's error code when PostHog could not join, or null when it joined.
+ * @nullable
+ */
+ error: string | null
+}
+
+export interface SlackAppJoinChannelsResultApi {
+ /** The result for each channel, in request order. */
+ results: SlackAppChannelJoinResultApi[]
+}
+
+export type SlackAppWorkspaceSetupRetrieveParams = {
+ /**
+ * Where the Slack install started. slack_page adds the steps for a person who sets up Slack on purpose.
+ *
+ * * `slack_page` - The Slack page in PostHog
+ * * `other` - Another place, such as a channel picker
+ * @minLength 1
+ */
+ entry?: SlackAppWorkspaceSetupRetrieveEntry
+}
+
+export type SlackAppWorkspaceSetupRetrieveEntry =
+ (typeof SlackAppWorkspaceSetupRetrieveEntry)[keyof typeof SlackAppWorkspaceSetupRetrieveEntry]
+
+export const SlackAppWorkspaceSetupRetrieveEntry = {
+ SlackPage: 'slack_page',
+ Other: 'other',
+} as const
diff --git a/products/slack_app/frontend/generated/api.ts b/products/slack_app/frontend/generated/api.ts
new file mode 100644
index 000000000000..6a6b6a7a0fd6
--- /dev/null
+++ b/products/slack_app/frontend/generated/api.ts
@@ -0,0 +1,113 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ SlackAppChannelOptionsApi,
+ SlackAppDefaultProjectApi,
+ SlackAppJoinChannelsApi,
+ SlackAppJoinChannelsResultApi,
+ SlackAppWorkspaceSetupApi,
+ SlackAppWorkspaceSetupRetrieveParams,
+} from './api.schemas'
+
+export const getSlackAppWorkspaceSetupRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: SlackAppWorkspaceSetupRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/slack_app_workspace_setup/${id}/?${stringifiedParams}`
+ : `/api/projects/${projectId}/slack_app_workspace_setup/${id}/`
+}
+
+/**
+ * @summary Get the web setup steps for a Slack app install
+ */
+export const slackAppWorkspaceSetupRetrieve = async (
+ projectId: string,
+ id: string,
+ params?: SlackAppWorkspaceSetupRetrieveParams,
+ options?: RequestInit
+): Promise<SlackAppWorkspaceSetupApi> => {
+ return apiMutator<SlackAppWorkspaceSetupApi>(getSlackAppWorkspaceSetupRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSlackAppWorkspaceSetupChannelsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/slack_app_workspace_setup/${id}/channels/`
+}
+
+/**
+ * @summary List the public channels that PostHog can join for a Slack app install
+ */
+export const slackAppWorkspaceSetupChannelsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SlackAppChannelOptionsApi> => {
+ return apiMutator<SlackAppChannelOptionsApi>(getSlackAppWorkspaceSetupChannelsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSlackAppWorkspaceSetupDefaultProjectCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/slack_app_workspace_setup/${id}/default_project/`
+}
+
+/**
+ * @summary Set the default project for the Slack workspace of a Slack app install
+ */
+export const slackAppWorkspaceSetupDefaultProjectCreate = async (
+ projectId: string,
+ id: string,
+ slackAppDefaultProjectApi: SlackAppDefaultProjectApi,
+ options?: RequestInit
+): Promise<SlackAppWorkspaceSetupApi> => {
+ return apiMutator<SlackAppWorkspaceSetupApi>(getSlackAppWorkspaceSetupDefaultProjectCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(slackAppDefaultProjectApi),
+ })
+}
+
+export const getSlackAppWorkspaceSetupJoinChannelsCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/slack_app_workspace_setup/${id}/join_channels/`
+}
+
+/**
+ * @summary Add PostHog to public channels of a Slack app install
+ */
+export const slackAppWorkspaceSetupJoinChannelsCreate = async (
+ projectId: string,
+ id: string,
+ slackAppJoinChannelsApi: SlackAppJoinChannelsApi,
+ options?: RequestInit
+): Promise<SlackAppJoinChannelsResultApi> => {
+ return apiMutator<SlackAppJoinChannelsResultApi>(getSlackAppWorkspaceSetupJoinChannelsCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(slackAppJoinChannelsApi),
+ })
+}
diff --git a/products/slack_app/frontend/generated/api.zod.ts b/products/slack_app/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..80837e3096e0
--- /dev/null
+++ b/products/slack_app/frontend/generated/api.zod.ts
@@ -0,0 +1,38 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * @summary Set the default project for the Slack workspace of a Slack app install
+ */
+export const SlackAppWorkspaceSetupDefaultProjectCreateBody = /* @__PURE__ */ zod.object({
+ integration_id: zod
+ .number()
+ .describe('ID of the Slack integration of the project that becomes the workspace default.'),
+})
+
+/**
+ * @summary Add PostHog to public channels of a Slack app install
+ */
+export const slackAppWorkspaceSetupJoinChannelsCreateBodyChannelIdsMax = 20
+
+export const slackAppWorkspaceSetupJoinChannelsCreateBodyPostWelcomeDefault = true
+
+export const SlackAppWorkspaceSetupJoinChannelsCreateBody = /* @__PURE__ */ zod.object({
+ channel_ids: zod
+ .array(zod.string())
+ .min(1)
+ .max(slackAppWorkspaceSetupJoinChannelsCreateBodyChannelIdsMax)
+ .describe('IDs of the public channels that PostHog joins.'),
+ post_welcome: zod
+ .boolean()
+ .default(slackAppWorkspaceSetupJoinChannelsCreateBodyPostWelcomeDefault)
+ .describe('Whether PostHog posts its welcome message in each channel it joins. When false, it joins quietly.'),
+})
diff --git a/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupDone.tsx b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupDone.tsx
new file mode 100644
index 000000000000..f8a975c53865
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupDone.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheckCircle } from '@posthog/icons'
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { slackAppWorkspaceSetupLogic } from './slackAppWorkspaceSetupLogic'
+
+export function SlackAppWorkspaceSetupDone(): JSX.Element {
+ const { setup, skippedSteps } = useValues(slackAppWorkspaceSetupLogic)
+ const { openSlackClicked } = useActions(slackAppWorkspaceSetupLogic)
+
+ const workspaceName = setup?.slack_workspace_name || 'Your Slack workspace'
+
+ return (
+ <>
+ <IconCheckCircle className="text-success text-4xl" />
+ <div className="flex flex-col items-center gap-1 text-center">
+ <h1 className="text-2xl font-bold m-0">{workspaceName} is set up. Now open Slack.</h1>
+ <p className="text-secondary m-0">
+ Send PostHog a direct message, or mention @PostHog in any channel to ask a question.
+ </p>
+ </div>
+ {skippedSteps.includes('ai_consent') ? (
+ <LemonBanner type="warning" className="w-full">
+ PostHog can't answer in Slack until an organization admin allows AI data processing.
+ </LemonBanner>
+ ) : null}
+ {setup?.open_slack_url ? (
+ <LemonButton
+ type="primary"
+ to={setup.open_slack_url}
+ targetBlank
+ onClick={openSlackClicked}
+ data-attr="slack-app-workspace-setup-open-slack"
+ >
+ Open PostHog in Slack
+ </LemonButton>
+ ) : null}
+ </>
+ )
+}
diff --git a/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupScene.stories.tsx b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupScene.stories.tsx
new file mode 100644
index 000000000000..c13fdc609b24
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupScene.stories.tsx
@@ -0,0 +1,82 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
+import { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { slackAppWorkspaceSetupLogic } from './slackAppWorkspaceSetupLogic'
+import { SlackAppWorkspaceSetupScene } from './SlackAppWorkspaceSetupScene'
+
+const SETUP = {
+ integration_id: 7,
+ slack_workspace_name: 'Hedgebox',
+ open_slack_url: 'https://slack.com/app_redirect?app=A123&team=T123',
+ project_options: [],
+ can_post_channel_welcome: true,
+}
+
+const PROJECT_OPTIONS = [
+ { integration_id: 7, project_name: 'Hedgebox web', organization_name: 'Hedgebox' },
+ { integration_id: 8, project_name: 'Hedgebox mobile', organization_name: 'Hedgebox' },
+]
+
+function setupDecorator(response: Record<string, unknown>): ReturnType<typeof mswDecorator> {
+ return mswDecorator({
+ get: {
+ '/api/projects/:team_id/slack_app_workspace_setup/:id/': response,
+ '/api/projects/:team_id/slack_app_workspace_setup/:id/channels/': {
+ channels: [
+ { id: 'C1', name: 'product', is_member: false },
+ { id: 'C2', name: 'engineering', is_member: false },
+ { id: 'C3', name: 'growth', is_member: false },
+ { id: 'C4', name: 'general', is_member: true },
+ ],
+ },
+ '/api/organizations/@current/': { ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: false },
+ },
+ })
+}
+
+const meta: Meta<typeof SlackAppWorkspaceSetupScene> = {
+ title: 'Scenes-App/Slack app/Workspace setup',
+ component: SlackAppWorkspaceSetupScene,
+ parameters: { layout: 'fullscreen', viewMode: 'story', mockDate: '2023-01-01' },
+ render: () => (
+ <BindLogic logic={slackAppWorkspaceSetupLogic} props={{ integrationId: 7 }}>
+ <SlackAppWorkspaceSetupScene />
+ </BindLogic>
+ ),
+}
+export default meta
+
+type Story = StoryObj<typeof SlackAppWorkspaceSetupScene>
+
+export const AIConsent: Story = {
+ decorators: [setupDecorator({ ...SETUP, steps: ['ai_consent'] })],
+}
+
+export const DefaultProject: Story = {
+ decorators: [setupDecorator({ ...SETUP, steps: ['default_project'], project_options: PROJECT_OPTIONS })],
+}
+
+export const Channels: Story = {
+ decorators: [setupDecorator({ ...SETUP, steps: ['channels'] })],
+}
+
+export const ChannelsWithoutWelcome: Story = {
+ decorators: [setupDecorator({ ...SETUP, steps: ['channels'], can_post_channel_welcome: false })],
+}
+
+export const Done: Story = {
+ decorators: [setupDecorator({ ...SETUP, steps: [] })],
+}
+
+export const DoneFromSettings: Story = {
+ decorators: [setupDecorator({ ...SETUP, steps: [] })],
+ render: () => (
+ <BindLogic logic={slackAppWorkspaceSetupLogic} props={{ integrationId: 7, returnTo: 'settings' }}>
+ <SlackAppWorkspaceSetupScene />
+ </BindLogic>
+ ),
+}
diff --git a/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupScene.tsx b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupScene.tsx
new file mode 100644
index 000000000000..e6c4e57705d7
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupScene.tsx
@@ -0,0 +1,67 @@
+import { useValues } from 'kea'
+
+import { IconArrowLeft } from '@posthog/icons'
+import { LemonBanner, Link, Spinner } from '@posthog/lemon-ui'
+
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SlackAppWorkspaceSetupDone } from './SlackAppWorkspaceSetupDone'
+import { slackAppWorkspaceSetupLogic, SlackAppWorkspaceSetupLogicProps } from './slackAppWorkspaceSetupLogic'
+import { SlackAppWorkspaceSetupStep } from './SlackAppWorkspaceSetupStep'
+import { parseSlackSetupReturnTarget, SLACK_SETUP_RETURN_PARAM } from './slackSetupReturn'
+
+export const scene: SceneExport<SlackAppWorkspaceSetupLogicProps> = {
+ component: SlackAppWorkspaceSetupScene,
+ logic: slackAppWorkspaceSetupLogic,
+ paramsToProps: ({ params: { integrationId }, searchParams }) => ({
+ integrationId: Number(integrationId),
+ entry: searchParams.entry === 'slack_page' ? 'slack_page' : 'other',
+ returnTo: parseSlackSetupReturnTarget(searchParams[SLACK_SETUP_RETURN_PARAM]),
+ }),
+}
+
+export function SlackAppWorkspaceSetupScene(): JSX.Element {
+ const { setup, setupLoading, steps, currentStep, currentStepNumber, returnLink } =
+ useValues(slackAppWorkspaceSetupLogic)
+
+ return (
+ <div className="flex flex-col items-center justify-center min-h-full w-full p-4">
+ <div className="flex flex-col items-center gap-4 max-w-160 w-full bg-surface-primary border rounded-lg shadow-sm px-8 py-8">
+ {steps.length > 0 ? (
+ <div className="flex items-center gap-3 w-full">
+ <LemonProgress
+ className="flex-1"
+ percent={currentStep ? ((currentStepNumber - 1) / steps.length) * 100 : 100}
+ />
+ <span className="text-xs text-secondary whitespace-nowrap">
+ {currentStep ? `${currentStepNumber} of ${steps.length}` : 'Done'}
+ </span>
+ </div>
+ ) : null}
+
+ {setupLoading && !setup ? (
+ <Spinner className="text-2xl" />
+ ) : !setup ? (
+ <LemonBanner type="error" className="w-full">
+ We couldn't load the Slack setup. Refresh the page, or go back to PostHog and connect Slack
+ again.
+ </LemonBanner>
+ ) : currentStep ? (
+ <SlackAppWorkspaceSetupStep step={currentStep} />
+ ) : (
+ <SlackAppWorkspaceSetupDone />
+ )}
+ </div>
+
+ <Link
+ to={returnLink?.url ?? urls.projectHomepage()}
+ className="flex items-center gap-1 mt-6 text-secondary"
+ >
+ <IconArrowLeft />
+ {returnLink?.label ?? 'Back to PostHog'}
+ </Link>
+ </div>
+ )
+}
diff --git a/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupStep.tsx b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupStep.tsx
new file mode 100644
index 000000000000..6af8b0c10b58
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/SlackAppWorkspaceSetupStep.tsx
@@ -0,0 +1,15 @@
+import type { WorkspaceSetupStepKey } from './slackAppWorkspaceSetupLogic'
+import { AIConsentStep } from './steps/AIConsentStep'
+import { ChannelsStep } from './steps/ChannelsStep'
+import { DefaultProjectStep } from './steps/DefaultProjectStep'
+
+export function SlackAppWorkspaceSetupStep({ step }: { step: WorkspaceSetupStepKey }): JSX.Element {
+ switch (step) {
+ case 'ai_consent':
+ return <AIConsentStep />
+ case 'default_project':
+ return <DefaultProjectStep />
+ case 'channels':
+ return <ChannelsStep />
+ }
+}
diff --git a/products/slack_app/frontend/workspace-setup/offerSlackWorkspaceSetup.ts b/products/slack_app/frontend/workspace-setup/offerSlackWorkspaceSetup.ts
new file mode 100644
index 000000000000..4b65b30c491c
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/offerSlackWorkspaceSetup.ts
@@ -0,0 +1,26 @@
+import { router } from 'kea-router'
+import posthog from 'posthog-js'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { slackAppWorkspaceSetupRetrieve } from '../generated/api'
+
+/** A toast and not a redirect, because the person is in the middle of another task, such as picking a channel. */
+export async function offerSlackWorkspaceSetup(teamId: number, integrationId: number, surface: string): Promise<void> {
+ const setup = await slackAppWorkspaceSetupRetrieve(String(teamId), String(integrationId))
+ if (setup.steps.length === 0) {
+ return
+ }
+ // pinned: analytics event and property names, renaming breaks dashboards
+ posthog.capture('slack app workspace setup offered', { integration_id: integrationId, surface })
+ lemonToast.info('Slack is connected. Finish the Slack setup, so PostHog can answer your team in Slack.', {
+ autoClose: false,
+ button: {
+ label: 'Finish setup',
+ dataAttr: 'slack-app-workspace-setup-offer',
+ action: () => router.actions.push(urls.slackAppWorkspaceSetup(integrationId)),
+ },
+ })
+}
diff --git a/products/slack_app/frontend/workspace-setup/slackAppWorkspaceSetupLogic.test.ts b/products/slack_app/frontend/workspace-setup/slackAppWorkspaceSetupLogic.test.ts
new file mode 100644
index 000000000000..c25f80402fd8
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/slackAppWorkspaceSetupLogic.test.ts
@@ -0,0 +1,123 @@
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ slackAppWorkspaceSetupChannelsRetrieve,
+ slackAppWorkspaceSetupDefaultProjectCreate,
+ slackAppWorkspaceSetupJoinChannelsCreate,
+ slackAppWorkspaceSetupRetrieve,
+} from '../generated/api'
+import { slackAppWorkspaceSetupLogic } from './slackAppWorkspaceSetupLogic'
+
+jest.mock('../generated/api', () => ({
+ slackAppWorkspaceSetupRetrieve: jest.fn(),
+ slackAppWorkspaceSetupDefaultProjectCreate: jest.fn(),
+ slackAppWorkspaceSetupChannelsRetrieve: jest.fn(),
+ slackAppWorkspaceSetupJoinChannelsCreate: jest.fn(),
+}))
+
+const mockRetrieve = slackAppWorkspaceSetupRetrieve as jest.Mock
+const mockSaveDefaultProject = slackAppWorkspaceSetupDefaultProjectCreate as jest.Mock
+const mockChannels = slackAppWorkspaceSetupChannelsRetrieve as jest.Mock
+const mockJoinChannels = slackAppWorkspaceSetupJoinChannelsCreate as jest.Mock
+
+const BASE = {
+ integration_id: 7,
+ slack_workspace_name: 'Hedgebox',
+ open_slack_url: 'https://slack.com/app_redirect?app=A1&team=T1',
+ project_options: [
+ { integration_id: 7, project_name: 'Hedgebox web', organization_name: 'Hedgebox' },
+ { integration_id: 8, project_name: 'Hedgebox mobile', organization_name: 'Hedgebox' },
+ ],
+}
+
+describe('slackAppWorkspaceSetupLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ mockRetrieve.mockResolvedValue({
+ ...BASE,
+ steps: ['ai_consent', 'a_step_this_frontend_does_not_know', 'default_project'],
+ })
+ mockSaveDefaultProject.mockResolvedValue({ ...BASE, steps: [], project_options: [] })
+ })
+
+ it('walks the known steps, saves the picked project, and keeps the step count after the save', async () => {
+ const logic = slackAppWorkspaceSetupLogic({ integrationId: 7 })
+ logic.mount()
+
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({
+ steps: ['ai_consent', 'default_project'],
+ currentStep: 'ai_consent',
+ currentStepNumber: 1,
+ })
+
+ logic.actions.skipStep('ai_consent')
+ logic.actions.selectProject(8)
+ await expectLogic(logic).toMatchValues({ currentStep: 'default_project', currentStepNumber: 2 })
+
+ await expectLogic(logic, () => logic.actions.saveDefaultProject()).toFinishAllListeners()
+
+ expect(mockSaveDefaultProject).toHaveBeenCalledWith(expect.any(String), '7', { integration_id: 8 })
+ await expectLogic(logic).toMatchValues({
+ currentStep: null,
+ steps: ['ai_consent', 'default_project'],
+ skippedSteps: ['ai_consent'],
+ })
+ })
+
+ it('asks for the channels step on the Slack page, and reports the channels it could not join', async () => {
+ mockRetrieve.mockResolvedValue({
+ ...BASE,
+ project_options: [],
+ steps: ['channels'],
+ can_post_channel_welcome: true,
+ })
+ mockChannels.mockResolvedValue({
+ channels: [
+ { id: 'C1', name: 'product', is_member: false },
+ { id: 'C2', name: 'growth', is_member: false },
+ { id: 'C3', name: 'general', is_member: true },
+ ],
+ })
+ mockJoinChannels.mockResolvedValue({
+ results: [
+ { channel_id: 'C1', error: null },
+ { channel_id: 'C2', error: 'is_archived' },
+ ],
+ })
+ const warning = jest.spyOn(lemonToast, 'warning')
+ const capture = jest.spyOn(posthog, 'capture')
+
+ const logic = slackAppWorkspaceSetupLogic({ integrationId: 7, entry: 'slack_page', returnTo: 'settings' })
+ logic.mount()
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({
+ currentStep: 'channels',
+ joinedChannelNames: ['general'],
+ })
+ expect(mockRetrieve).toHaveBeenCalledWith(expect.any(String), '7', { entry: 'slack_page' })
+ expect(capture).toHaveBeenCalledWith('slack app workspace setup viewed', {
+ integration_id: 7,
+ entry: 'slack_page',
+ return_to: 'settings',
+ steps: ['channels'],
+ })
+
+ logic.actions.setSelectedChannelIds(['C1', 'C2'])
+ await expectLogic(logic, () => logic.actions.joinChannels()).toFinishAllListeners()
+
+ expect(mockJoinChannels).toHaveBeenCalledWith(expect.any(String), '7', {
+ channel_ids: ['C1', 'C2'],
+ post_welcome: true,
+ })
+ expect(warning).toHaveBeenCalledWith(expect.stringContaining('#growth'))
+ await expectLogic(logic).toMatchValues({ currentStep: null })
+ })
+})
diff --git a/products/slack_app/frontend/workspace-setup/slackAppWorkspaceSetupLogic.ts b/products/slack_app/frontend/workspace-setup/slackAppWorkspaceSetupLogic.ts
new file mode 100644
index 000000000000..2169df340909
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/slackAppWorkspaceSetupLogic.ts
@@ -0,0 +1,351 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ slackAppWorkspaceSetupChannelsRetrieve,
+ slackAppWorkspaceSetupDefaultProjectCreate,
+ slackAppWorkspaceSetupJoinChannelsCreate,
+ slackAppWorkspaceSetupRetrieve,
+} from '../generated/api'
+import type {
+ SlackAppChannelJoinResultApi,
+ SlackAppChannelOptionApi,
+ SlackAppWorkspaceSetupApi,
+ SlackAppWorkspaceSetupRetrieveEntry,
+ SlackSetupStepKeyEnumApi,
+} from '../generated/api.schemas'
+import { SlackSetupReturnLink, SlackSetupReturnTarget, slackSetupReturnLink } from './slackSetupReturn'
+
+export type WorkspaceSetupStepKey = SlackSetupStepKeyEnumApi
+
+/** The steps this frontend can render. It drops unknown keys from a newer backend. */
+export const WORKSPACE_SETUP_STEP_KEYS: WorkspaceSetupStepKey[] = ['ai_consent', 'default_project', 'channels']
+
+export interface SlackAppWorkspaceSetupLogicProps {
+ integrationId: number
+ /** Where the Slack install started. The Slack page in PostHog adds the optional steps. */
+ entry?: SlackAppWorkspaceSetupRetrieveEntry
+ returnTo?: SlackSetupReturnTarget
+}
+
+// pinned: analytics property names, renaming breaks dashboards
+function setupEventProperties(props: SlackAppWorkspaceSetupLogicProps): Record<string, unknown> {
+ return { integration_id: props.integrationId, entry: props.entry ?? 'other', return_to: props.returnTo ?? null }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface slackAppWorkspaceSetupLogicValues {
+ currentTeamId: number | null // teamLogic
+ channelOptions: SlackAppChannelOptionApi[] | null
+ channelOptionsLoading: boolean
+ currentStep: WorkspaceSetupStepKey | null
+ currentStepNumber: number
+ finishedSteps: WorkspaceSetupStepKey[]
+ initialSteps: WorkspaceSetupStepKey[] | null
+ joinResults: SlackAppChannelJoinResultApi[] | null
+ joinResultsLoading: boolean
+ joinableChannels: SlackAppChannelOptionApi[]
+ joinedChannelNames: string[]
+ postWelcome: boolean
+ returnLink: SlackSetupReturnLink | null
+ selectedChannelIds: string[]
+ selectedProjectIntegrationId: number
+ setup: SlackAppWorkspaceSetupApi | null
+ setupLoading: boolean
+ skippedSteps: WorkspaceSetupStepKey[]
+ steps: WorkspaceSetupStepKey[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface slackAppWorkspaceSetupLogicActions {
+ completeStep: (step: WorkspaceSetupStepKey) => {
+ step: SlackSetupStepKeyEnumApi
+ }
+ joinChannels: () => any
+ joinChannelsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ joinChannelsSuccess: (
+ joinResults: SlackAppChannelJoinResultApi[],
+ payload?: any
+ ) => {
+ joinResults: SlackAppChannelJoinResultApi[]
+ payload?: any
+ }
+ loadChannelOptions: () => any
+ loadChannelOptionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadChannelOptionsSuccess: (
+ channelOptions: SlackAppChannelOptionApi[],
+ payload?: any
+ ) => {
+ channelOptions: SlackAppChannelOptionApi[]
+ payload?: any
+ }
+ loadSetup: () => any
+ loadSetupFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSetupSuccess: (
+ setup: SlackAppWorkspaceSetupApi,
+ payload?: any
+ ) => {
+ setup: SlackAppWorkspaceSetupApi
+ payload?: any
+ }
+ openSlackClicked: () => {
+ value: true
+ }
+ saveDefaultProject: () => any
+ saveDefaultProjectFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveDefaultProjectSuccess: (
+ setup: SlackAppWorkspaceSetupApi,
+ payload?: any
+ ) => {
+ setup: SlackAppWorkspaceSetupApi
+ payload?: any
+ }
+ selectProject: (integrationId: number) => {
+ integrationId: number
+ }
+ setPostWelcome: (postWelcome: boolean) => {
+ postWelcome: boolean
+ }
+ setSelectedChannelIds: (channelIds: string[]) => {
+ channelIds: string[]
+ }
+ skipStep: (step: WorkspaceSetupStepKey) => {
+ step: SlackSetupStepKeyEnumApi
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface slackAppWorkspaceSetupLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ steps: (initialSteps: SlackSetupStepKeyEnumApi[] | null) => WorkspaceSetupStepKey[]
+ currentStep: (
+ steps: SlackSetupStepKeyEnumApi[],
+ finishedSteps: SlackSetupStepKeyEnumApi[]
+ ) => WorkspaceSetupStepKey | null
+ currentStepNumber: (steps: SlackSetupStepKeyEnumApi[], currentStep: SlackSetupStepKeyEnumApi | null) => number
+ returnLink: (arg: any) => SlackSetupReturnLink | null
+ joinableChannels: (channelOptions: SlackAppChannelOptionApi[] | null) => SlackAppChannelOptionApi[]
+ joinedChannelNames: (channelOptions: SlackAppChannelOptionApi[] | null) => string[]
+ }
+}
+
+export type slackAppWorkspaceSetupLogicType = MakeLogicType<
+ slackAppWorkspaceSetupLogicValues,
+ slackAppWorkspaceSetupLogicActions,
+ SlackAppWorkspaceSetupLogicProps,
+ slackAppWorkspaceSetupLogicMeta
+>
+
+export const slackAppWorkspaceSetupLogic = kea<slackAppWorkspaceSetupLogicType>([
+ path((key) => ['products', 'slack_app', 'workspace-setup', 'slackAppWorkspaceSetupLogic', key]),
+ props({} as SlackAppWorkspaceSetupLogicProps),
+ key((props) => props.integrationId),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+ actions({
+ completeStep: (step: WorkspaceSetupStepKey) => ({ step }),
+ skipStep: (step: WorkspaceSetupStepKey) => ({ step }),
+ selectProject: (integrationId: number) => ({ integrationId }),
+ setSelectedChannelIds: (channelIds: string[]) => ({ channelIds }),
+ setPostWelcome: (postWelcome: boolean) => ({ postWelcome }),
+ openSlackClicked: true,
+ }),
+ loaders(({ props, values }) => ({
+ setup: [
+ null as SlackAppWorkspaceSetupApi | null,
+ {
+ loadSetup: async () => {
+ return await slackAppWorkspaceSetupRetrieve(
+ String(values.currentTeamId),
+ String(props.integrationId),
+ {
+ entry: props.entry ?? 'other',
+ }
+ )
+ },
+ saveDefaultProject: async () => {
+ return await slackAppWorkspaceSetupDefaultProjectCreate(
+ String(values.currentTeamId),
+ String(props.integrationId),
+ { integration_id: values.selectedProjectIntegrationId }
+ )
+ },
+ },
+ ],
+ channelOptions: [
+ null as SlackAppChannelOptionApi[] | null,
+ {
+ loadChannelOptions: async () => {
+ const response = await slackAppWorkspaceSetupChannelsRetrieve(
+ String(values.currentTeamId),
+ String(props.integrationId)
+ )
+ return response.channels
+ },
+ },
+ ],
+ joinResults: [
+ null as SlackAppChannelJoinResultApi[] | null,
+ {
+ joinChannels: async () => {
+ const response = await slackAppWorkspaceSetupJoinChannelsCreate(
+ String(values.currentTeamId),
+ String(props.integrationId),
+ {
+ channel_ids: values.selectedChannelIds,
+ post_welcome: values.postWelcome && !!values.setup?.can_post_channel_welcome,
+ }
+ )
+ return response.results
+ },
+ },
+ ],
+ })),
+ reducers(({ props }) => ({
+ finishedSteps: [
+ [] as WorkspaceSetupStepKey[],
+ {
+ completeStep: (state, { step }) => [...state, step],
+ skipStep: (state, { step }) => [...state, step],
+ },
+ ],
+ skippedSteps: [
+ [] as WorkspaceSetupStepKey[],
+ {
+ skipStep: (state, { step }) => [...state, step],
+ },
+ ],
+ // Fixed at the first load, so the progress bar still counts the steps that a save removes.
+ initialSteps: [
+ null as WorkspaceSetupStepKey[] | null,
+ {
+ loadSetupSuccess: (state, { setup }) => state ?? setup.steps,
+ },
+ ],
+ selectedProjectIntegrationId: [
+ props.integrationId,
+ {
+ selectProject: (_, { integrationId }) => integrationId,
+ },
+ ],
+ selectedChannelIds: [
+ [] as string[],
+ {
+ setSelectedChannelIds: (_, { channelIds }) => channelIds,
+ },
+ ],
+ postWelcome: [
+ true,
+ {
+ setPostWelcome: (_, { postWelcome }) => postWelcome,
+ },
+ ],
+ })),
+ selectors({
+ steps: [
+ (s) => [s.initialSteps],
+ (initialSteps: WorkspaceSetupStepKey[] | null): WorkspaceSetupStepKey[] =>
+ (initialSteps ?? []).filter((step) => WORKSPACE_SETUP_STEP_KEYS.includes(step)),
+ ],
+ currentStep: [
+ (s) => [s.steps, s.finishedSteps],
+ (steps: WorkspaceSetupStepKey[], finishedSteps: WorkspaceSetupStepKey[]): WorkspaceSetupStepKey | null =>
+ steps.find((step) => !finishedSteps.includes(step)) ?? null,
+ ],
+ currentStepNumber: [
+ (s) => [s.steps, s.currentStep],
+ (steps: WorkspaceSetupStepKey[], currentStep: WorkspaceSetupStepKey | null): number =>
+ currentStep ? steps.indexOf(currentStep) + 1 : steps.length,
+ ],
+ returnLink: [
+ () => [(_, props) => props.returnTo],
+ (returnTo: SlackSetupReturnTarget | undefined): SlackSetupReturnLink | null =>
+ slackSetupReturnLink(returnTo),
+ ],
+ joinableChannels: [
+ (s) => [s.channelOptions],
+ (channelOptions: SlackAppChannelOptionApi[] | null): SlackAppChannelOptionApi[] =>
+ (channelOptions ?? []).filter((channel) => !channel.is_member),
+ ],
+ joinedChannelNames: [
+ (s) => [s.channelOptions],
+ (channelOptions: SlackAppChannelOptionApi[] | null): string[] =>
+ (channelOptions ?? []).filter((channel) => channel.is_member).map((channel) => channel.name),
+ ],
+ }),
+ listeners(({ actions, values, props }) => ({
+ loadSetupSuccess: ({ setup }) => {
+ if (setup.steps.includes('channels') && values.channelOptions === null) {
+ actions.loadChannelOptions()
+ }
+ // pinned: analytics event and property names, renaming breaks dashboards
+ posthog.capture('slack app workspace setup viewed', {
+ ...setupEventProperties(props),
+ steps: setup.steps,
+ })
+ },
+ loadSetupFailure: () => {
+ posthog.capture('slack app workspace setup load failed', setupEventProperties(props))
+ },
+ saveDefaultProjectSuccess: () => {
+ actions.completeStep('default_project')
+ },
+ joinChannelsSuccess: ({ joinResults }) => {
+ const failed = (joinResults ?? []).filter((result) => result.error)
+ const names = new Map((values.channelOptions ?? []).map((channel) => [channel.id, channel.name]))
+ if (failed.length > 0) {
+ const failedNames = failed.map((result) => `#${names.get(result.channel_id) ?? result.channel_id}`)
+ lemonToast.warning(
+ `PostHog couldn't join ${failedNames.join(', ')}. Invite it with /invite @PostHog in those channels.`
+ )
+ }
+ actions.completeStep('channels')
+ },
+ completeStep: ({ step }) => {
+ posthog.capture('slack app workspace setup step completed', { ...setupEventProperties(props), step })
+ },
+ skipStep: ({ step }) => {
+ posthog.capture('slack app workspace setup step skipped', { ...setupEventProperties(props), step })
+ },
+ openSlackClicked: () => {
+ posthog.capture('slack app workspace setup open slack clicked', {
+ ...setupEventProperties(props),
+ finished_steps: values.finishedSteps,
+ })
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadSetup()
+ }),
+])
diff --git a/products/slack_app/frontend/workspace-setup/slackSetupReturn.test.ts b/products/slack_app/frontend/workspace-setup/slackSetupReturn.test.ts
new file mode 100644
index 000000000000..abae3bbcaddd
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/slackSetupReturn.test.ts
@@ -0,0 +1,14 @@
+import { parseSlackSetupReturnTarget } from './slackSetupReturn'
+
+describe('parseSlackSetupReturnTarget', () => {
+ test.each([
+ ['settings', 'settings'],
+ ['https://example.com', undefined],
+ ['/settings', undefined],
+ ['toString', undefined],
+ [undefined, undefined],
+ [['settings'], undefined],
+ ])('parses %p as %p', (value, expected) => {
+ expect(parseSlackSetupReturnTarget(value)).toEqual(expected)
+ })
+})
diff --git a/products/slack_app/frontend/workspace-setup/slackSetupReturn.ts b/products/slack_app/frontend/workspace-setup/slackSetupReturn.ts
new file mode 100644
index 000000000000..74ce46a401ed
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/slackSetupReturn.ts
@@ -0,0 +1,26 @@
+import { urls } from 'scenes/urls'
+
+// pinned: URL search param, the Settings connect button and bookmarks use it
+export const SLACK_SETUP_RETURN_PARAM = 'return_to'
+
+export interface SlackSetupReturnLink {
+ label: string
+ url: string
+}
+
+// The URL carries only a key from this list, so the param can't send the person to another site.
+const RETURN_TARGETS = {
+ settings: (): SlackSetupReturnLink => ({ label: 'Back to settings', url: urls.settings('project-integrations') }),
+}
+
+export type SlackSetupReturnTarget = keyof typeof RETURN_TARGETS
+
+export function parseSlackSetupReturnTarget(value: unknown): SlackSetupReturnTarget | undefined {
+ return typeof value === 'string' && Object.hasOwn(RETURN_TARGETS, value)
+ ? (value as SlackSetupReturnTarget)
+ : undefined
+}
+
+export function slackSetupReturnLink(target: SlackSetupReturnTarget | undefined): SlackSetupReturnLink | null {
+ return target ? RETURN_TARGETS[target]() : null
+}
diff --git a/products/slack_app/frontend/workspace-setup/steps/AIConsentStep.tsx b/products/slack_app/frontend/workspace-setup/steps/AIConsentStep.tsx
new file mode 100644
index 000000000000..be67254f6c48
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/steps/AIConsentStep.tsx
@@ -0,0 +1,75 @@
+import { useActions, useAsyncActions, useValues } from 'kea'
+import { router } from 'kea-router'
+import { useState } from 'react'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { organizationLogic } from 'scenes/organizationLogic'
+import { AIAccessRequest } from 'scenes/settings/organization/AIAccessRequest'
+import { openAIConsentLegalDialog } from 'scenes/settings/organization/aiConsentCopy'
+
+import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
+
+import { slackAppWorkspaceSetupLogic } from '../slackAppWorkspaceSetupLogic'
+
+export function AIConsentStep(): JSX.Element {
+ const { isAdminOrOwner, currentOrganization } = useValues(organizationLogic)
+ const { dataProcessingApprovalDisabledReason } = useValues(aiConsentLogic)
+ const { setPendingApprovalRedirect } = useActions(aiConsentLogic)
+ const { acceptDataProcessing } = useAsyncActions(aiConsentLogic)
+ const { completeStep, skipStep } = useActions(slackAppWorkspaceSetupLogic)
+ const { location } = useValues(router)
+ const [approving, setApproving] = useState(false)
+
+ const approve = async (): Promise<void> => {
+ if (currentOrganization) {
+ // Approval can need a new login, which reloads the page. The pending redirect brings the person back.
+ setPendingApprovalRedirect({
+ url: location.pathname + location.search,
+ organizationId: currentOrganization.id,
+ setAt: Date.now(),
+ })
+ }
+ setApproving(true)
+ try {
+ await acceptDataProcessing()
+ completeStep('ai_consent')
+ } finally {
+ setApproving(false)
+ }
+ }
+
+ return (
+ <>
+ <div className="flex flex-col items-center gap-1 text-center">
+ <h1 className="text-2xl font-bold m-0">Allow AI data processing</h1>
+ <p className="text-secondary m-0">
+ PostHog in Slack uses AI models to answer from your PostHog data. An organization admin must allow
+ this once for {currentOrganization?.name ?? 'your organization'}. Until then, PostHog can't answer
+ in Slack.
+ </p>
+ </div>
+
+ {isAdminOrOwner ? (
+ <LemonButton
+ type="primary"
+ data-attr="slack-app-workspace-setup-allow-ai"
+ loading={approving}
+ disabledReason={dataProcessingApprovalDisabledReason}
+ onClick={() => openAIConsentLegalDialog({ onConfirm: approve })}
+ >
+ Allow AI data processing
+ </LemonButton>
+ ) : (
+ <div className="flex flex-col items-center gap-2 text-center">
+ <p className="text-secondary m-0">Only an organization admin can allow this. Ask one of them.</p>
+ <AIAccessRequest size="small" />
+ </div>
+ )}
+
+ <LemonButton type="tertiary" size="small" onClick={() => skipStep('ai_consent')}>
+ Skip for now
+ </LemonButton>
+ </>
+ )
+}
diff --git a/products/slack_app/frontend/workspace-setup/steps/ChannelsStep.tsx b/products/slack_app/frontend/workspace-setup/steps/ChannelsStep.tsx
new file mode 100644
index 000000000000..104f2f01e970
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/steps/ChannelsStep.tsx
@@ -0,0 +1,75 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonCheckbox, LemonInputSelect } from '@posthog/lemon-ui'
+
+import { slackAppWorkspaceSetupLogic } from '../slackAppWorkspaceSetupLogic'
+
+export function ChannelsStep(): JSX.Element {
+ const {
+ setup,
+ joinableChannels,
+ joinedChannelNames,
+ channelOptionsLoading,
+ selectedChannelIds,
+ postWelcome,
+ joinResultsLoading,
+ } = useValues(slackAppWorkspaceSetupLogic)
+ const { setSelectedChannelIds, setPostWelcome, joinChannels, skipStep } = useActions(slackAppWorkspaceSetupLogic)
+
+ const count = selectedChannelIds.length
+
+ return (
+ <>
+ <div className="flex flex-col items-center gap-1 text-center">
+ <h1 className="text-2xl font-bold m-0">Which channels should PostHog join?</h1>
+ <p className="text-secondary m-0">
+ PostHog answers only when someone mentions @PostHog. You can invite it to more channels later with
+ /invite @PostHog.
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-2 w-full">
+ <LemonInputSelect
+ mode="multiple"
+ fullWidth
+ loading={channelOptionsLoading}
+ placeholder="Search public channels"
+ value={selectedChannelIds}
+ onChange={setSelectedChannelIds}
+ options={joinableChannels.map((channel) => ({ key: channel.id, label: `#${channel.name}` }))}
+ data-attr="slack-app-workspace-setup-channels"
+ />
+ {joinedChannelNames.length > 0 ? (
+ <p className="text-xs text-secondary m-0">
+ PostHog is already in {joinedChannelNames.map((name) => `#${name}`).join(', ')}.
+ </p>
+ ) : null}
+ <LemonCheckbox
+ checked={postWelcome && !!setup?.can_post_channel_welcome}
+ onChange={setPostWelcome}
+ disabledReason={
+ setup?.can_post_channel_welcome
+ ? undefined
+ : "This workspace's PostHog settings don't post a welcome in channels. A Slack admin can change this under Channel welcome in the PostHog app in Slack."
+ }
+ label="Post a short welcome message in each channel"
+ />
+ </div>
+
+ <div className="flex flex-wrap justify-between items-center gap-2 w-full">
+ <LemonButton type="tertiary" onClick={() => skipStep('channels')}>
+ Skip
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ loading={joinResultsLoading}
+ disabledReason={count === 0 ? 'Choose at least one channel' : undefined}
+ onClick={joinChannels}
+ data-attr="slack-app-workspace-setup-join-channels"
+ >
+ {count > 1 ? `Add PostHog to ${count} channels` : 'Add PostHog to this channel'}
+ </LemonButton>
+ </div>
+ </>
+ )
+}
diff --git a/products/slack_app/frontend/workspace-setup/steps/DefaultProjectStep.tsx b/products/slack_app/frontend/workspace-setup/steps/DefaultProjectStep.tsx
new file mode 100644
index 000000000000..9ccedba945ca
--- /dev/null
+++ b/products/slack_app/frontend/workspace-setup/steps/DefaultProjectStep.tsx
@@ -0,0 +1,50 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
+
+import { slackAppWorkspaceSetupLogic } from '../slackAppWorkspaceSetupLogic'
+
+export function DefaultProjectStep(): JSX.Element {
+ const { setup, selectedProjectIntegrationId, setupLoading } = useValues(slackAppWorkspaceSetupLogic)
+ const { selectProject, saveDefaultProject, skipStep } = useActions(slackAppWorkspaceSetupLogic)
+
+ return (
+ <>
+ <div className="flex flex-col items-center gap-1 text-center">
+ <h1 className="text-2xl font-bold m-0">Which project should PostHog use by default?</h1>
+ <p className="text-secondary m-0">
+ This Slack workspace is connected to more than one project. PostHog uses the default project when a
+ question doesn't name one. Each person can change it for themselves in Slack.
+ </p>
+ </div>
+
+ <LemonRadio
+ className="w-full"
+ aria-label="Default project"
+ value={selectedProjectIntegrationId}
+ onChange={selectProject}
+ options={(setup?.project_options ?? []).map((option) => ({
+ value: option.integration_id,
+ label: option.project_name,
+ description: option.organization_name,
+ }))}
+ />
+
+ <div className="flex flex-wrap justify-between items-center gap-2 w-full">
+ <LemonButton type="tertiary" onClick={() => skipStep('default_project')}>
+ Skip
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ loading={setupLoading}
+ onClick={saveDefaultProject}
+ data-attr="slack-app-workspace-setup-save-default-project"
+ >
+ Use this project
+ </LemonButton>
+ </div>
+ </>
+ )
+}
diff --git a/products/slack_app/manifest.tsx b/products/slack_app/manifest.tsx
new file mode 100644
index 000000000000..84015aa37d05
--- /dev/null
+++ b/products/slack_app/manifest.tsx
@@ -0,0 +1,24 @@
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'Slack app',
+ scenes: {
+ SlackAppWorkspaceSetup: {
+ import: () => import('./frontend/workspace-setup/SlackAppWorkspaceSetupScene'),
+ projectBased: true,
+ name: 'Slack app setup',
+ layout: 'plain',
+ },
+ },
+ routes: {
+ '/integrations/slack/:integrationId/setup': ['SlackAppWorkspaceSetup', 'slackAppWorkspaceSetup'],
+ },
+ redirects: {},
+ urls: {
+ slackAppWorkspaceSetup: (integrationId: number | string): string =>
+ `/integrations/slack/${integrationId}/setup`,
+ },
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/slack_app/package.json b/products/slack_app/package.json
index 6bcd67c5c78d..2b5123eeb28b 100644
--- a/products/slack_app/package.json
+++ b/products/slack_app/package.json
@@ -2,5 +2,21 @@
"name": "@posthog/products-slack-app",
"scripts": {
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/temporal -v --tb=short"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-loaders": "catalog:",
+ "kea-router": "catalog:",
+ "posthog-js": "catalog:"
+ },
+ "devDependencies": {
+ "kea-test-utils": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "catalog:",
+ "@posthog/lemon-ui": "*",
+ "@storybook/react": "catalog:",
+ "@types/react": "*",
+ "react": "*"
}
}
diff --git a/products/slack_app/tsconfig.json b/products/slack_app/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/slack_app/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3936e278e218..0f738656d9b7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -113798,6 +113798,95 @@ export namespace Schemas {
readonly previous_secret_valid_until: string | null;
}
+ export interface SlackAppChannelJoinResult {
+ /** Slack channel ID. */
+ channel_id: string;
+ /**
+ * Slack's error code when PostHog could not join, or null when it joined.
+ * @nullable
+ */
+ error: string | null;
+ }
+
+ export interface SlackAppChannelOption {
+ /** Slack channel ID. */
+ id: string;
+ /** Channel name, without the leading #. */
+ name: string;
+ /** Whether PostHog is already in the channel. */
+ is_member: boolean;
+ }
+
+ export interface SlackAppChannelOptions {
+ /** Public channels that PostHog can join. Shared channels are left out. */
+ channels: SlackAppChannelOption[];
+ }
+
+ export interface SlackAppDefaultProject {
+ /** ID of the Slack integration of the project that becomes the workspace default. */
+ integration_id: number;
+ }
+
+ export interface SlackAppJoinChannels {
+ /**
+ * IDs of the public channels that PostHog joins.
+ * @minItems 1
+ * @maxItems 20
+ */
+ channel_ids: string[];
+ /** Whether PostHog posts its welcome message in each channel it joins. When false, it joins quietly. */
+ post_welcome?: boolean;
+ }
+
+ export interface SlackAppJoinChannelsResult {
+ /** The result for each channel, in request order. */
+ results: SlackAppChannelJoinResult[];
+ }
+
+ export interface SlackAppProjectOption {
+ /** ID of the Slack integration that connects this project. */
+ integration_id: number;
+ /** Name of the PostHog project. */
+ project_name: string;
+ /** Name of the organization that owns the project. */
+ organization_name: string;
+ }
+
+ /**
+ * * `ai_consent` - AI data processing
+ * * `default_project` - Default project
+ * * `channels` - Channels
+ */
+ export type SlackSetupStepKeyEnum = typeof SlackSetupStepKeyEnum[keyof typeof SlackSetupStepKeyEnum];
+
+
+ export const SlackSetupStepKeyEnum = {
+ AiConsent: 'ai_consent',
+ DefaultProject: 'default_project',
+ Channels: 'channels',
+ } as const;
+
+ export interface SlackAppWorkspaceSetup {
+ /** ID of the Slack integration that this setup is for. */
+ integration_id: number;
+ /**
+ * Name of the Slack workspace, as Slack sent it at install time.
+ * @nullable
+ */
+ slack_workspace_name: string | null;
+ /**
+ * Link that opens the PostHog app's direct message in this Slack workspace. Null when the install has no app ID.
+ * @nullable
+ */
+ open_slack_url: string | null;
+ /** Setup steps that apply to this install and are not done yet, in display order. ai_consent: the organization must allow AI data processing. default_project: the Slack workspace connects to 2 or more projects and has no default. channels: the install can join channels, and the setup started on the Slack page. */
+ steps: SlackSetupStepKeyEnum[];
+ /** Projects connected to this Slack workspace that the person can open. Empty unless default_project is a step. */
+ project_options: SlackAppProjectOption[];
+ /** Whether a channel join from this setup can post the welcome message in the channel. False when channels is not a step, or when the workspace sends the welcome only to the inviter or turns it off. */
+ can_post_channel_welcome: boolean;
+ }
+
export interface SlackChannel {
/** Slack channel ID (e.g. C0123ABC) — pass to cdp-functions inputs.channel. */
id: string;
@@ -143980,6 +144069,25 @@ export namespace Schemas {
offset?: number;
};
+ export type SlackAppWorkspaceSetupRetrieveParams = {
+ /**
+ * Where the Slack install started. slack_page adds the steps for a person who sets up Slack on purpose.
+ *
+ * * `slack_page` - The Slack page in PostHog
+ * * `other` - Another place, such as a channel picker
+ * @minLength 1
+ */
+ entry?: SlackAppWorkspaceSetupRetrieveEntry;
+ };
+
+ export type SlackAppWorkspaceSetupRetrieveEntry = typeof SlackAppWorkspaceSetupRetrieveEntry[keyof typeof SlackAppWorkspaceSetupRetrieveEntry];
+
+
+ export const SlackAppWorkspaceSetupRetrieveEntry = {
+ SlackPage: 'slack_page',
+ Other: 'other',
+ } as const;
+
export type StamphogDigestRunsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index ba17aee7f682..581943842caf 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -1644,6 +1644,11 @@
"params": ["categoryTab"],
"scope": "project"
},
+ "slackAppWorkspaceSetup": {
+ "template": "/integrations/slack/{integrationId}/setup",
+ "params": ["integrationId"],
+ "scope": "project"
+ },
"slackTaskContext": {
"template": "/slack-task-context",
"params": [],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index d0a1b79d8947..285efc0e5c10 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/application-observability\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/library/templates/{id}\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/onboarding/simple\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/transactional\n/transactional/library/templates/{id}\n/transactional/new\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/channels/email/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/application-observability\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/library/templates/{id}\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/slack/{integrationId}/setup\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/onboarding/simple\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/transactional\n/transactional/library/templates/{id}\n/transactional/new\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/channels/email/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},