:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack_app): refresh the welcome messages and send one on install (#103003)
Vojta Bartoš21e2daa0f9ce
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex a029c37c49dc..680e0d606715 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -55,7 +55,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import get_instance_region-from products.slack_app.backend import inbox_channel, onboarding+from products.slack_app.backend import inbox_channelfrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.discussion_replies import try_ingest_discussion_replyfrom products.slack_app.backend.feature_flags import (@@ -65,7 +65,7 @@ from products.slack_app.backend.feature_flags import ()from products.slack_app.backend.helpers import local_dev_slack_emailfrom products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping, UntaggedFollowupMode-from products.slack_app.backend.services import inbox_interactivity, turn_feedback+from products.slack_app.backend.services import inbox_interactivity, slack_welcome_messages, turn_feedbackfrom products.slack_app.backend.services.commands import SLASH_COMMAND_PREFIXfrom products.slack_app.backend.services.integration_resolver import (UserResolutionFailure,@@ -108,6 +108,11 @@ from products.slack_app.backend.services.slack_user_oauth import (find_linked_posthog_user,post_link_invite_message,)+from products.slack_app.backend.services.slack_welcome_messages import (+ build_assistant_pane_welcome,+ build_channel_welcome,+ build_team_join_welcome,+)from products.slack_app.backend.slack_link_unfurl import (handle_posthog_link_unfurl,link_url_region,@@ -145,7 +150,6 @@ SLACK_PLACEHOLDER_USER_ID = "U00"# cutover. A real re-join after this window should re-onboard — most likely the# person forgot how it works.ONBOARDING_DEDUPE_TTL_SECONDS = 60 * 10-CHANNEL_ONBOARDING_DOCS_URL = "https://posthog.com/docs/slack-app"ROUTE_HANDLED_LOCALLY = "handled_locally"ROUTE_PROXIED = "proxied"@@ -1779,23 +1783,10 @@ _ASSISTANT_SUGGESTED_PROMPTS = [{"title": "Investigate an issue", "message": "Investigate why one of my insights is slow"},{"title": "Work an inbox item", "message": "Pick up a signals inbox item that needs a code fix"},]-_ASSISTANT_WELCOME = (- "Hi! I'm PostHog, an AI agent. DM me to investigate issues using your PostHog data and "- "open PRs in your connected repos to fix them!"-)-_ASSISTANT_INSTALL_WELCOME = (- "Thanks for adding PostHog! :tada: I'm an AI agent - DM me here or @mention me in a channel "- "to investigate issues or open PRs in your connected repos"-)_ASSISTANT_UNAVAILABLE = ("I can only help PostHog org members whose project has a connected repo. Make sure your Slack ""email matches your PostHog account and that a repo is connected, then try again.")-_ASSISTANT_MEMBER_JOIN_WELCOME = (- ":wave: Welcome! I'm PostHog, an AI agent your team uses. DM me here to investigate issues "- "using your PostHog data or open PRs in your connected repos - you can also @mention me in "- "any channel."-)@frozen@@ -1860,7 +1851,7 @@ def _handle_assistant_thread_started(slack: SlackIntegration, channel_id: str, tprompts=_ASSISTANT_SUGGESTED_PROMPTS,)# Slack's own assistant container thread, not a reply to a user message that can be deleted.- slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=_ASSISTANT_WELCOME)+ slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=build_assistant_pane_welcome())except Exception:logger.warning("assistant_thread_started_failed", exc_info=True)return ROUTE_HANDLED_LOCALLY@@ -1874,19 +1865,6 @@ def _post_assistant_unavailable(slack: SlackIntegration, channel_id: str, threadlogger.warning("assistant_unavailable_post_failed", exc_info=True)-def send_assistant_install_welcome(integration: Integration) -> None:- """DM the installing user the moment the app is added, when the assistant is enabled for their team."""- if not is_slack_app_assistant_enabled(integration):- return- slack_user_id = ((integration.config or {}).get("authed_user") or {}).get("id")- if not slack_user_id:- return- try:- SlackIntegration(integration).client.chat_postMessage(channel=slack_user_id, text=_ASSISTANT_INSTALL_WELCOME)- except Exception:- logger.warning("assistant_install_welcome_failed", exc_info=True)--def _handle_assistant_dm_message(event: dict,integration: Integration,@@ -2869,47 +2847,12 @@ def _release_channel_onboarding_claim(slack_team_id: str, channel_id: str) -> Nodef _post_channel_onboarding_message(slack: SlackIntegration, integration: Integration, channel_id: str) -> bool:"""Post the welcome message. Returns True on success."""- blocks: list[dict[str, Any]] = [- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": (- ":wave: Thanks for adding the PostHog app to this channel! "- "Mention me with `@PostHog` to get started – I can answer "- "questions about your PostHog data, research your codebase, "- "and kick off coding tasks backed by real usage data. "- "I'll also unfurl PostHog links you share here."- ),- },- },- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": (- "*Try one of these:*\n"- "• `@PostHog what's our weekly active user count this month?`\n"- "• `@PostHog open a PR that adds a unit test for src/utils.py`"- ),- },- },- {- "type": "actions",- "elements": [- {- "type": "button",- "text": {"type": "plain_text", "text": "Read the docs"},- "url": CHANNEL_ONBOARDING_DOCS_URL,- }- ],- },- ]+ text, blocks = build_channel_welcome(integration)try:slack.client.chat_postMessage(channel=channel_id,- text="Thanks for adding the PostHog app – mention me with @PostHog to get started.",+ text=text,blocks=blocks,unfurl_links=False,unfurl_media=False,@@ -2991,9 +2934,10 @@ def _team_join_onboarding_cache_key(slack_team_id: str, slack_user_id: str) -> sdef _post_team_join_welcome(integration: Integration, slack_user_id: str) -> bool:+ text, blocks = build_team_join_welcome(integration)try:SlackIntegration(integration).client.chat_postMessage(- channel=slack_user_id, text=_ASSISTANT_MEMBER_JOIN_WELCOME+ channel=slack_user_id, text=text, blocks=blocks, unfurl_links=False, unfurl_media=False)logger.info("slack_app_team_join_welcome_posted",@@ -5086,13 +5030,13 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return _handle_signals_dismiss_report(payload)if action_id in (INSIGHT_ALERT_SNOOZE_ACTION_ID, INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID):return _handle_insight_alert_snooze(payload)- if action_id == onboarding.INBOX_CREATE_ACTION_ID:+ if action_id == slack_welcome_messages.INBOX_CREATE_ACTION_ID:return inbox_interactivity.handle_inbox_create(payload)- if action_id == onboarding.INBOX_JOIN_ACTION_ID:+ if action_id == slack_welcome_messages.INBOX_JOIN_ACTION_ID:return inbox_interactivity.handle_inbox_join(payload)- if action_id == onboarding.INBOX_SOURCES_CHECKBOXES_ACTION:+ if action_id == slack_welcome_messages.INBOX_SOURCES_CHECKBOXES_ACTION:return inbox_interactivity.handle_inbox_sources(payload)- if action_id == onboarding.INBOX_AI_APPROVAL_ACTION_ID:+ if action_id == slack_welcome_messages.INBOX_AI_APPROVAL_ACTION_ID:return inbox_interactivity.handle_inbox_ai_approval(payload)if action_id in _AI_PREFERENCES_ACTION_IDS:return _handle_ai_preferences_block_action(payload, action)diff --git a/products/slack_app/backend/onboarding.py b/products/slack_app/backend/onboarding.pyindex f8cc2985a1e4..5ffc3f35d392 100644--- a/products/slack_app/backend/onboarding.py+++ b/products/slack_app/backend/onboarding.py@@ -1,49 +1,39 @@-"""Inbox onboarding DM: a product intro built from four steps (GitHub, sources, reports/channel, AI approval).+"""Inbox onboarding: what the reader's four answers do (GitHub, sources, reports/channel, AI approval).-Block builders assemble the message, ``send_onboarding_dm`` delivers it, and the interactivity helpers-(called from ``api.py``) handle each click. ``run_install_onboarding`` is the install entrypoint.+``send_onboarding_dm`` delivers the message, the interactivity helpers (called from ``api.py``)+handle each click, and ``run_install_onboarding`` is the install entrypoint. The message itself is+built in ``services/slack_welcome_messages.py`` with the rest of the first-contact copy."""from __future__ import annotations-import jsonfrom enum import StrEnum-from django.conf import settings-import structlogfrom slack_sdk.errors import SlackApiErrorfrom posthog.models import OrganizationMembership, Teamfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.user_integration import UserIntegration-from posthog.utils import absolute_urifrom products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.inbox_channel import (- INBOX_CHANNEL_REQUIRED_SCOPES,- _channel_exists,_get_team_channel,_is_channel_member,channel_id_from_target,- channel_name_from_target,ensure_inbox_channel,has_inbox_scopes,invite_user_to_inbox,)+from products.slack_app.backend.services.slack_messages import context_block+from products.slack_app.backend.services.slack_welcome_messages import (+ INBOX_CREATE_ACTION_ID,+ INBOX_JOIN_ACTION_ID,+ build_onboarding_dm,+)logger = structlog.get_logger(__name__)-# Block Kit action ids for the onboarding DM, kept in sync with the interactivity router.-INBOX_CREATE_ACTION_ID = "slack_inbox_create"-INBOX_JOIN_ACTION_ID = "slack_inbox_join"-# The block_id carries the integration id so the checkbox interaction can be region-routed.-INBOX_SOURCES_CHECKBOXES_ACTION = "slack_inbox_sources_select"-INBOX_SOURCES_BLOCK_PREFIX = "slack_inbox_sources_block"-# AI approval is a hard prerequisite — without it no signals are emitted. block_id carries the integration id.-INBOX_AI_APPROVAL_ACTION_ID = "slack_inbox_ai_approval"-INBOX_AI_APPROVAL_BLOCK_PREFIX = "slack_inbox_ai_approval_block"-class OnboardingStep(StrEnum):AI_APPROVAL = "ai_approval"@@ -60,184 +50,10 @@ EVENT_SOURCE_ENABLED = "slack_onboarding_source_enabled"_REQUIRED_STEPS = (OnboardingStep.AI_APPROVAL, OnboardingStep.CHANNEL, OnboardingStep.GITHUB, OnboardingStep.SOURCES)-# =====================================================================-# Block Kit primitives + per-step block builders-# =====================================================================---def _section(text: str) -> dict:- return {"type": "section", "text": {"type": "mrkdwn", "text": text}}---def _button(label: str, action_id: str, value: str) -> dict:- return {- "type": "button",- "text": {"type": "plain_text", "text": label},- "action_id": action_id,- "value": value,- "style": "primary",- }---def _public_url(path: str) -> str:- """Public base URL for links delivered to Slack. In local dev, prefer the ngrok tunnel so the link- is reachable from outside (mirrors ``OauthIntegration.redirect_uri``)."""- if settings.DEBUG and settings.NGROK_URL:- return f"{settings.NGROK_URL.rstrip('/')}{path}"- return absolute_uri(path)---def _done(text: str) -> dict:- return _context(f":white_check_mark: {text}")---def _context(text: str) -> dict:- return {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]}---def _github_connect_url(team_id: int) -> str:- """GitHub OAuth entry that returns to Slack — one flow connects the team install and the user's personal GitHub."""- return _public_url(f"/integrations/connect/github/?project_id={team_id}&connect_from=slack")---def _github_blocks(integration: Integration, *, done: bool) -> list[dict]:- blocks: list[dict] = [- _section(- "*1. Connect your codebase* :wrench:\nConnect GitHub so I can fix things, not just flag them - "- "when I spot a problem in your product I'll proactively open a pull request with the fix for you to review."- )- ]- if done:- blocks.append(_done("Connected"))- return blocks- # Pure URL button (no action_id): clicking just opens OAuth in the browser and fires no- # interaction. The callback returns to Slack; the message updates next time it's rebuilt.- button = {- "type": "button",- "text": {"type": "plain_text", "text": "Connect GitHub"},- "url": _github_connect_url(integration.team_id),- "style": "primary",- }- blocks.append({"type": "actions", "elements": [button]})- return blocks---def _sources_blocks(integration: Integration) -> list[dict]:- """Inline checkboxes (current state pre-checked) — ticking sets a source up immediately, unticking turns it off."""- from products.signals.backend.facade.api import (- onboarding_sources, # noqa: PLC0415 — keeps the signals stack off the slack import path- )-- sources = onboarding_sources(integration.team_id)- tickable = [source for source in sources if source.togglable]- options = [- {- "text": {"type": "mrkdwn", "text": f"*{source.label}*: {source.description}"},- "value": source.key,- }- for source in tickable- ]- checkboxes: dict = {"type": "checkboxes", "action_id": INBOX_SOURCES_CHECKBOXES_ACTION, "options": options}- initial = [option for option, source in zip(options, tickable) if source.enabled]- if initial:- checkboxes["initial_options"] = initial- blocks = [- _section("*2. Choose what I watch* :eyes:\nTick the signals I should monitor and investigate."),- {"type": "actions", "block_id": f"{INBOX_SOURCES_BLOCK_PREFIX}:{integration.id}", "elements": [checkboxes]},- ]- # Sources set up elsewhere have no checkbox, so say what's already watching. Without this the- # step reads as done with nothing ticked.- elsewhere = [source.label for source in sources if not source.togglable and source.enabled]- if elsewhere:- blocks.append(- {"type": "context", "elements": [{"type": "mrkdwn", "text": f"Already watching: {', '.join(elsewhere)}"}]}- )- return blocks---def _channel_blocks(integration: Integration, slack: SlackIntegration, *, done: bool) -> list[dict]:- blocks: list[dict] = [- _section(- "*3. Where I report* :inbox_tray:\nEverything I find lands in one shared channel so the team stays in the loop."- )- ]- if done:- blocks.append(_done("Posting to #posthog-inbox"))- return blocks- configured = _get_team_channel(integration.team_id)- channel_exists = configured is not None and _channel_exists(slack, channel_id_from_target(configured))- has_scope = not slack.missing_scopes(INBOX_CHANNEL_REQUIRED_SCOPES)- value = json.dumps({"integration_id": integration.id})- name = channel_name_from_target(configured or "") if channel_exists else "#posthog-inbox"- if channel_exists and has_scope:- blocks.append({"type": "actions", "elements": [_button(f"Join {name}", INBOX_JOIN_ACTION_ID, value)]})- elif channel_exists:- blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": f"Join {name} in your workspace."}]})- elif has_scope:- blocks.append(- {"type": "actions", "elements": [_button("Create #posthog-inbox", INBOX_CREATE_ACTION_ID, value)]}- )- else:- blocks.append(- {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": f"Create a #posthog-inbox channel, then set it in your <{_public_url('/inbox')}|inbox>.",- }- ],- }- )- return blocks---def _ai_approval_blocks(integration: Integration, *, is_admin: bool) -> list[dict]:- """The approval prompt — only rendered when not yet approved. Admins tick a checkbox to approve;- non-admins get an 'ask an admin' note, since only ADMIN+ can toggle org settings."""- blocks: list[dict] = [- _section(- "*4. Approve AI data processing*\nTo investigate your product I use external AI "- "providers (Anthropic, OpenAI, Google, Microsoft). This can involve transferring identifying user data, "- "and is never used to train third-party models. FYI it's not HIPAA-compliant yet, and any BAA you have "- "with PostHog won't cover these features."- )- ]- if not is_admin:- blocks.append(- {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": ":warning: Ask an org admin to approve. Until then I can't get started.",- }- ],- }- )- return blocks- blocks.append(- {- "type": "actions",- "block_id": f"{INBOX_AI_APPROVAL_BLOCK_PREFIX}:{integration.id}",- "elements": [- {- "type": "checkboxes",- "action_id": INBOX_AI_APPROVAL_ACTION_ID,- "options": [- {"text": {"type": "plain_text", "text": "Approve AI data processing"}, "value": "approve"}- ],- }- ],- }- )- return blocks--# Slack has no disabled buttons; a context block is the idiomatic greyed/done state.def _replace_actions_with_context(blocks: list[dict], action_ids: set[str], text: str) -> list[dict]:return [- _context(text)+ context_block(text)if (block.get("type") == "actions"and any(el.get("action_id") in action_ids for el in block.get("elements", []))@@ -248,49 +64,10 @@ def _replace_actions_with_context(blocks: list[dict], action_ids: set[str], text# =====================================================================-# Assembly, delivery, status, completion+# Status, delivery, completion# =====================================================================-def build_onboarding_dm(- integration: Integration,- slack: SlackIntegration,- *,- needs_ai_approval: bool = False,- ai_approval_is_admin: bool = True,- needs_github: bool = False,- already_in_channel: bool = False,-) -> tuple[str, list[dict]]:- """Return (fallback_text, Block Kit blocks) for the inbox onboarding DM.-- Every step is always shown with its state (done steps render a '✅' line). AI approval is the one- exception: omitted once approved. Always returns a full message — the DM is posted unconditionally.- """- intro = _section(- "👋 *Hi, I'm PostHog - self-driving for your product*\nI'm an AI agent on autopilot: I watch your product "- "for problems, investigate them myself, and open pull requests to fix them - so issues get handled before "- "they reach your backlog."- )- blocks: list[dict] = [intro, {"type": "divider"}]- blocks += _github_blocks(integration, done=not needs_github)- blocks += _sources_blocks(integration)- blocks += _channel_blocks(integration, slack, done=already_in_channel)- if needs_ai_approval:- blocks += _ai_approval_blocks(integration, is_admin=ai_approval_is_admin)- blocks.append(- {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": "🎉 Once you're set up, I'll start watching your product and send your first report to #posthog-inbox as soon as I spot something.",- }- ],- }- )- return "Set up PostHog - self-driving for your product", blocks--def _has_team_github(team_id: int) -> bool:return Integration.objects.filter(team_id=team_id, kind="github").exists()diff --git a/products/slack_app/backend/services/inbox_interactivity.py b/products/slack_app/backend/services/inbox_interactivity.pyindex 18b9daa747ec..f03ac6fc0526 100644--- a/products/slack_app/backend/services/inbox_interactivity.py+++ b/products/slack_app/backend/services/inbox_interactivity.py@@ -18,6 +18,7 @@ import structlogfrom posthog.models.integration import Integrationfrom products.slack_app.backend import inbox_channel, onboarding+from products.slack_app.backend.services import slack_welcome_messageslogger = structlog.get_logger(__name__)@@ -30,8 +31,8 @@ def extract_inbox_hints(payload: dict) -> int | None:for action in payload.get("actions", []):action_id = action.get("action_id")if action_id in (- onboarding.INBOX_CREATE_ACTION_ID,- onboarding.INBOX_JOIN_ACTION_ID,+ slack_welcome_messages.INBOX_CREATE_ACTION_ID,+ slack_welcome_messages.INBOX_JOIN_ACTION_ID,):try:value = json.loads(action.get("value") or "{}")@@ -42,7 +43,10 @@ def extract_inbox_hints(payload: dict) -> int | None:return integration_idcontinueblock_id = action.get("block_id", "")- for prefix in (onboarding.INBOX_SOURCES_BLOCK_PREFIX, onboarding.INBOX_AI_APPROVAL_BLOCK_PREFIX):+ for prefix in (+ slack_welcome_messages.INBOX_SOURCES_BLOCK_PREFIX,+ slack_welcome_messages.INBOX_AI_APPROVAL_BLOCK_PREFIX,+ ):if block_id.startswith(f"{prefix}:"):suffix = block_id.split(":", 1)[1]return int(suffix) if suffix.isdigit() else None@@ -146,7 +150,11 @@ def handle_inbox_ai_approval(payload: dict) -> HttpResponse:integration = _inbox_integration_from_payload(payload)slack_user_id = payload.get("user", {}).get("id", "")action = next(- (a for a in payload.get("actions", []) if a.get("action_id") == onboarding.INBOX_AI_APPROVAL_ACTION_ID),+ (+ a+ for a in payload.get("actions", [])+ if a.get("action_id") == slack_welcome_messages.INBOX_AI_APPROVAL_ACTION_ID+ ),None,)ticked = any(o.get("value") == "approve" for o in (action or {}).get("selected_options", []))@@ -166,7 +174,11 @@ def handle_inbox_sources(payload: dict) -> HttpResponse:if integration is None or not slack_user_id:return HttpResponse(status=200)action = next(- (a for a in payload.get("actions", []) if a.get("action_id") == onboarding.INBOX_SOURCES_CHECKBOXES_ACTION),+ (+ a+ for a in payload.get("actions", [])+ if a.get("action_id") == slack_welcome_messages.INBOX_SOURCES_CHECKBOXES_ACTION+ ),None,)selected = [o.get("value") for o in (action or {}).get("selected_options", []) if o.get("value")]diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex 3a4a4871f76b..2e59b91f6ac3 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -880,6 +880,11 @@ def thread_permalink(slack: SlackIntegration, channel: str, thread_ts: str) -> sreturn None+def section_block(text: str) -> dict[str, Any]:+ """One block of mrkdwn body text."""+ return {"type": "section", "text": {"type": "mrkdwn", "text": text}}++def context_block(text: str) -> dict[str, Any]:"""A line of muted supporting text.diff --git a/products/slack_app/backend/services/slack_welcome_messages.py b/products/slack_app/backend/services/slack_welcome_messages.pynew file mode 100644index 000000000000..11a1aaf0b42a--- /dev/null+++ b/products/slack_app/backend/services/slack_welcome_messages.py@@ -0,0 +1,375 @@+"""What PostHog says the first time someone meets it in Slack.++Four moments: a fresh install, the app is added to a channel, someone joins a workspace+that already has it, or someone opens the assistant pane. Keeping them in one module is+what stops the list of things worth knowing from drifting apart per surface.++A builder takes the integration and returns the ``(fallback_text, blocks)`` pair+``chat_postMessage`` wants. The fallback text is what a notification and a screen reader+get, so it says the one thing the message is for rather than repeating the whole of it.+Delivery stays in ``api.py`` with the event router, welded to region routing and the+dedupe claim.+"""++from __future__ import annotations++import json+from typing import Any++from django.conf import settings++from posthog.helpers.slack_subscription_explore import BOT_SETUP_DOCS_URL+from posthog.models.integration import Integration, SlackIntegration+from posthog.utils import absolute_uri++from products.slack_app.backend.feature_flags import is_slack_app_assistant_enabled+from products.slack_app.backend.inbox_channel import (+ INBOX_CHANNEL_REQUIRED_SCOPES,+ _channel_exists,+ _get_team_channel,+ channel_id_from_target,+ channel_name_from_target,+)+from products.slack_app.backend.services.slack_messages import app_home_url, context_block, section_block++# Block Kit action ids for the onboarding DM, kept in sync with the interactivity router.+INBOX_CREATE_ACTION_ID = "slack_inbox_create"+INBOX_JOIN_ACTION_ID = "slack_inbox_join"+# The block_id carries the integration id so the checkbox interaction can be region-routed.+INBOX_SOURCES_CHECKBOXES_ACTION = "slack_inbox_sources_select"+INBOX_SOURCES_BLOCK_PREFIX = "slack_inbox_sources_block"+# AI approval is a hard prerequisite — without it no signals are emitted. block_id carries the integration id.+INBOX_AI_APPROVAL_ACTION_ID = "slack_inbox_ai_approval"+INBOX_AI_APPROVAL_BLOCK_PREFIX = "slack_inbox_ai_approval_block"+++def _bullets(title: str, lines: tuple[str, ...]) -> dict[str, Any]:+ return section_block("*{}*\n{}".format(title, "\n".join(f"• {line}" for line in lines)))+++def _docs_button_block() -> dict[str, Any]:+ return {+ "type": "actions",+ "elements": [+ {+ "type": "button",+ "text": {"type": "plain_text", "text": "Read the docs"},+ "url": BOT_SETUP_DOCS_URL,+ }+ ],+ }+++def _feedback_block() -> dict[str, Any]:+ """The ask for a rating, in the one wording all three messages share.++ Every welcome carries it because the thumbs are the only channel a Slack reader has+ back to us, and nothing else in the product points at them. Only the clicked thumbs+ asks for a reason, so the reaction is named after it rather than beside it.+ """+ return section_block(+ "*Tell me when I get it wrong*\nHit the thumbs under my replies. A thumbs down asks what went "+ "wrong, and that goes straight to the team building me. You can also react with :thumbsup: or "+ ":thumbsdown:."+ )+++def _home_tab(integration: Integration, label: str = "my Home tab") -> str:+ """``label``, linked to this install's Home tab where there is one to link to.++ An install that predates the app id on its config has no deep link, and the tab is+ still there to be opened by hand, so the sentence around this has to read the same+ either way. A link rather than a button: Slack renders ``slack://`` in mrkdwn, and the+ reader is already in Slack, so the tab opens in place.+ """+ url = app_home_url(integration)+ return f"<{url}|{label}>" if url else label+++def build_assistant_pane_welcome() -> str:+ """Greets someone opening Slack's assistant container, beside the suggested prompts.++ Plain text and no blocks, because the container takes a ``text`` payload, so none of the+ section and button structure the other two share transfers here. The pane runs the same+ mention workflow, so the model and project classifiers answer in it as well. No+ ``/posthog``: the slash commands are not reachable from a DM.+ """+ return (+ "Hi! I'm PostHog, an AI agent. Ask me about your product data, or tell me what to fix and "+ "I'll open a pull request in a connected repo.\n"+ "• Keep replying here while I'm working and I'll pick up what you say.\n"+ "• Want a different model? Say so: `use fable for this one`.\n"+ "• Answering from the wrong project? Name the one you want: `give me DAU for Staging please`.\n"+ "• Hit the thumbs under my replies when I get something wrong."+ )+++def build_channel_welcome(integration: Integration) -> tuple[str, list[dict[str, Any]]]:+ """Posted in a channel the moment the app is added to it.++ Written for everyone in the channel rather than for whoever did the adding.+ """+ worth_knowing = [+ "Tag me again in the thread while I'm working and I'll pick up what you say.",+ "Want a different model? Say so: `@PostHog use fable for this one`, or "+ "`@PostHog run this on opus 5 at high effort`.",+ "Answering from the wrong project? Name the one you want: `@PostHog give me DAU for "+ "Staging please`. `/posthog project` shows your default.",+ ]+ # Unlike the DM welcome, this path posts to whichever install serves the workspace, so the+ # scopes are unchecked until here. An install without them never receives the `message.im`+ # event, so the DM would go unanswered with nothing to tell the reader why.+ if is_slack_app_assistant_enabled(integration):+ worth_knowing.append("You can DM me instead of tagging me here.")+ blocks: list[dict[str, Any]] = [+ section_block(+ ":wave: Hey, I'm PostHog. Tag me with `@PostHog` and I'll dig into your product data, poke "+ "around your codebase, or open a pull request to fix something."+ ),+ # One analytics question and one code change, so nobody reads the app as only the+ # half they happened to see first.+ _bullets(+ "Try asking me",+ (+ "`@PostHog why did signups drop in the EU last week?`",+ "`@PostHog open a PR that adds a unit test for src/utils.py`",+ ),+ ),+ _bullets("A few things worth knowing", tuple(worth_knowing)),+ _feedback_block(),+ context_block(+ "I also unfurl PostHog links shared in this channel. `/posthog` lists my commands, and your "+ f"default model and thread follow-ups live in {_home_tab(integration)}."+ ),+ _docs_button_block(),+ ]+ return "Hey, I'm PostHog. Tag me with @PostHog to get started.", blocks+++def build_team_join_welcome(integration: Integration) -> tuple[str, list[dict[str, Any]]]:+ """DM'd to someone who just joined a workspace that already has the app.++ They inherited a tool nobody introduced them to, so this says what it is before it+ says what it can do. The examples drop the `@PostHog` prefix because a DM needs none.+ """+ blocks: list[dict[str, Any]] = [+ section_block(+ ":wave: Hey, welcome! I'm PostHog, an AI agent your team already uses here. Message me, or tag "+ "`@PostHog` in any channel, and I'll dig into your product data or open a pull request in a "+ "connected repo."+ ),+ _bullets(+ "Try asking me",+ (+ "`why did signups drop in the EU last week?`",+ "`fix the flaky billing CI job`",+ ),+ ),+ _bullets(+ "A few things worth knowing",+ (+ "Keep replying in the thread while I'm working and I'll pick up what you say. "+ "In a channel, tag me in the reply.",+ "Want a different model? Say so: `use fable for this one`.",+ ),+ ),+ _feedback_block(),+ context_block(+ "In a channel, `/posthog` lists my commands. Your default model, thread follow-ups and "+ f"linked accounts live in {_home_tab(integration)}."+ ),+ _docs_button_block(),+ ]+ return "Hey, welcome! I'm PostHog. Message me to get started.", blocks+++# The install onboarding DM. `onboarding.py` owns what the reader's answers do: the status+# queries, the click handlers and the install flow.+++def _button(label: str, action_id: str, value: str) -> dict:+ return {+ "type": "button",+ "text": {"type": "plain_text", "text": label},+ "action_id": action_id,+ "value": value,+ "style": "primary",+ }+++def _public_url(path: str) -> str:+ """Public base URL for links delivered to Slack. In local dev, prefer the ngrok tunnel so the link+ is reachable from outside (mirrors ``OauthIntegration.redirect_uri``)."""+ if settings.DEBUG and settings.NGROK_URL:+ return f"{settings.NGROK_URL.rstrip('/')}{path}"+ return absolute_uri(path)+++def _done(text: str) -> dict:+ return context_block(f":white_check_mark: {text}")+++def _github_connect_url(team_id: int) -> str:+ """GitHub OAuth entry that returns to Slack — one flow connects the team install and the user's personal GitHub."""+ return _public_url(f"/integrations/connect/github/?project_id={team_id}&connect_from=slack")+++def _github_blocks(integration: Integration, *, done: bool) -> list[dict]:+ blocks: list[dict] = [+ section_block(+ "*1. Connect your codebase* :wrench:\nConnect GitHub so I can fix things, not just flag them - "+ "when I spot a problem in your product I'll proactively open a pull request with the fix for you to review."+ )+ ]+ if done:+ blocks.append(_done("Connected"))+ return blocks+ # Pure URL button (no action_id): clicking just opens OAuth in the browser and fires no+ # interaction. The callback returns to Slack; the message updates next time it's rebuilt.+ button = {+ "type": "button",+ "text": {"type": "plain_text", "text": "Connect GitHub"},+ "url": _github_connect_url(integration.team_id),+ "style": "primary",+ }+ blocks.append({"type": "actions", "elements": [button]})+ return blocks+++def _sources_blocks(integration: Integration) -> list[dict]:+ """Inline checkboxes (current state pre-checked) — ticking sets a source up immediately, unticking turns it off."""+ from products.signals.backend.facade.api import (+ onboarding_sources, # noqa: PLC0415 — keeps the signals stack off the slack import path+ )++ sources = onboarding_sources(integration.team_id)+ tickable = [source for source in sources if source.togglable]+ options = [+ {+ "text": {"type": "mrkdwn", "text": f"*{source.label}*: {source.description}"},+ "value": source.key,+ }+ for source in tickable+ ]+ checkboxes: dict = {"type": "checkboxes", "action_id": INBOX_SOURCES_CHECKBOXES_ACTION, "options": options}+ initial = [option for option, source in zip(options, tickable) if source.enabled]+ if initial:+ checkboxes["initial_options"] = initial+ blocks = [+ section_block("*2. Choose what I watch* :eyes:\nTick the signals I should monitor and investigate."),+ {"type": "actions", "block_id": f"{INBOX_SOURCES_BLOCK_PREFIX}:{integration.id}", "elements": [checkboxes]},+ ]+ # Sources set up elsewhere have no checkbox, so say what's already watching. Without this the+ # step reads as done with nothing ticked.+ elsewhere = [source.label for source in sources if not source.togglable and source.enabled]+ if elsewhere:+ blocks.append(context_block(f"Already watching: {', '.join(elsewhere)}"))+ return blocks+++def _channel_blocks(integration: Integration, slack: SlackIntegration, *, done: bool) -> list[dict]:+ blocks: list[dict] = [+ section_block(+ "*3. Where I report* :inbox_tray:\nEverything I find lands in one shared channel so the team stays in the loop."+ )+ ]+ if done:+ blocks.append(_done("Posting to #posthog-inbox"))+ return blocks+ configured = _get_team_channel(integration.team_id)+ channel_exists = configured is not None and _channel_exists(slack, channel_id_from_target(configured))+ has_scope = not slack.missing_scopes(INBOX_CHANNEL_REQUIRED_SCOPES)+ value = json.dumps({"integration_id": integration.id})+ name = channel_name_from_target(configured or "") if channel_exists else "#posthog-inbox"+ if channel_exists and has_scope:+ blocks.append({"type": "actions", "elements": [_button(f"Join {name}", INBOX_JOIN_ACTION_ID, value)]})+ elif channel_exists:+ blocks.append(context_block(f"Join {name} in your workspace."))+ elif has_scope:+ blocks.append(+ {"type": "actions", "elements": [_button("Create #posthog-inbox", INBOX_CREATE_ACTION_ID, value)]}+ )+ else:+ blocks.append(+ context_block(f"Create a #posthog-inbox channel, then set it in your <{_public_url('/inbox')}|inbox>.")+ )+ return blocks+++def _ai_approval_blocks(integration: Integration, *, is_admin: bool) -> list[dict]:+ """The approval prompt — only rendered when not yet approved. Admins tick a checkbox to approve;+ non-admins get an 'ask an admin' note, since only ADMIN+ can toggle org settings."""+ blocks: list[dict] = [+ section_block(+ "*4. Approve AI data processing*\nTo investigate your product I use external AI "+ "providers (Anthropic, OpenAI, Google, Microsoft). This can involve transferring identifying user data, "+ "and is never used to train third-party models. FYI it's not HIPAA-compliant yet, and any BAA you have "+ "with PostHog won't cover these features."+ )+ ]+ if not is_admin:+ blocks.append(context_block(":warning: Ask an org admin to approve. Until then I can't get started."))+ return blocks+ blocks.append(+ {+ "type": "actions",+ "block_id": f"{INBOX_AI_APPROVAL_BLOCK_PREFIX}:{integration.id}",+ "elements": [+ {+ "type": "checkboxes",+ "action_id": INBOX_AI_APPROVAL_ACTION_ID,+ "options": [+ {"text": {"type": "plain_text", "text": "Approve AI data processing"}, "value": "approve"}+ ],+ }+ ],+ }+ )+ return blocks+++def build_onboarding_dm(+ integration: Integration,+ slack: SlackIntegration,+ *,+ needs_ai_approval: bool = False,+ ai_approval_is_admin: bool = True,+ needs_github: bool = False,+ already_in_channel: bool = False,+) -> tuple[str, list[dict]]:+ """Return (fallback_text, Block Kit blocks) for the inbox onboarding DM.++ Every step is always shown with its state (done steps render a '✅' line). AI approval is the one+ exception: omitted once approved. Always returns a full message — the DM is posted unconditionally.+ """+ intro = section_block(+ "👋 *Hi, I'm PostHog - self-driving for your product*\nI'm an AI agent on autopilot: I watch your product "+ "for problems, investigate them myself, and open pull requests to fix them - so issues get handled before "+ "they reach your backlog."+ )+ # Above the steps because it is the half of the product the steps never describe, and a reader+ # who stops at the setup checklist would otherwise never learn the agent answers questions.+ interactive = section_block(+ "💬 *You can also just talk to me*\nTag `@PostHog` in any channel, or message me here, to dig into your "+ "product data or open a pull request. Name a project to route one question: `@PostHog give me DAU for "+ "Staging please`. In a channel, `/posthog` lists my commands."+ )+ blocks: list[dict] = [intro, interactive, {"type": "divider"}]+ blocks += _github_blocks(integration, done=not needs_github)+ blocks += _sources_blocks(integration)+ blocks += _channel_blocks(integration, slack, done=already_in_channel)+ if needs_ai_approval:+ blocks += _ai_approval_blocks(integration, is_admin=ai_approval_is_admin)+ blocks.append(+ context_block(+ "🎉 Once you're set up, I'll start watching your product and send your first report to "+ "#posthog-inbox as soon as I spot something."+ )+ )+ blocks.append(+ context_block(+ "👍 Hit the thumbs under my replies when I get something wrong. Your default model and linked "+ f"accounts live in {_home_tab(integration)}."+ )+ )+ return "Set up PostHog - self-driving for your product", blocksdiff --git a/products/slack_app/backend/tests/helpers.py b/products/slack_app/backend/tests/helpers.pyindex 93346927dfa0..a0ed65a25e4e 100644--- a/products/slack_app/backend/tests/helpers.py+++ b/products/slack_app/backend/tests/helpers.py@@ -1,3 +1,63 @@+from typing import Any+from posthog.models.integration import sign_slack_request-__all__ = ["sign_slack_request"]+__all__ = ["action_ids", "all_block_text", "render_blocks", "sign_slack_request", "url_buttons"]+++def render_blocks(blocks: list[dict[str, Any]]) -> str:+ """Block Kit as a reader sees it, so a copy snapshot diffs as prose rather than as JSON."""+ lines = []+ for block in blocks:+ if block["type"] == "section":+ lines.append(block["text"]["text"])+ for field in block.get("fields", []):+ lines.append(field.get("text", ""))+ accessory = block.get("accessory") or {}+ if accessory.get("type") == "button":+ lines.append(f"[{accessory['text']['text']}]({accessory.get('url', accessory.get('action_id'))})")+ elif block["type"] == "context":+ lines.append(" ".join(e.get("text", "") for e in block["elements"] if isinstance(e.get("text"), str)))+ elif block["type"] == "header":+ lines.append(f"# {block['text']['text']}")+ elif block["type"] == "divider":+ lines.append("---")+ elif block["type"] == "actions":+ rendered = []+ for element in block["elements"]:+ if element.get("type") == "button":+ target = element.get("url") or element.get("action_id")+ rendered.append(f"[{element['text']['text']}]({target})")+ elif element.get("type") == "checkboxes":+ for option in element.get("options", []):+ rendered.append(f"[ ] {option['text']['text']}")+ else:+ rendered.append(f"<{element.get('type')}>")+ lines.append(" ".join(rendered))+ return "\n\n".join(lines)+++def action_ids(blocks: list[dict[str, Any]]) -> list[str]:+ ids = [el["action_id"] for b in blocks if b["type"] == "actions" for el in b["elements"] if "action_id" in el]+ ids += [b["accessory"]["action_id"] for b in blocks if (b.get("accessory") or {}).get("action_id")]+ return ids+++def url_buttons(blocks: list[dict[str, Any]]) -> list[str]:+ urls = [el["url"] for b in blocks if b["type"] == "actions" for el in b["elements"] if "url" in el]+ urls += [b["accessory"]["url"] for b in blocks if (b.get("accessory") or {}).get("url")]+ return urls+++def all_block_text(blocks: list[dict[str, Any]]) -> str:+ """Every string a reader could see, flattened for a substring assertion."""+ parts: list[str] = []+ for b in blocks:+ if (b.get("text") or {}).get("text"):+ parts.append(b["text"]["text"])+ for f in b.get("fields", []):+ parts.append(f.get("text", ""))+ for el in b.get("elements", []):+ txt = el.get("text")+ parts.append(txt if isinstance(txt, str) else (txt or {}).get("text", ""))+ return " ".join(parts)diff --git a/products/slack_app/backend/tests/services/__snapshots__/test_slack_welcome_messages.ambr b/products/slack_app/backend/tests/services/__snapshots__/test_slack_welcome_messages.ambrnew file mode 100644index 000000000000..afdfb20ff107--- /dev/null+++ b/products/slack_app/backend/tests/services/__snapshots__/test_slack_welcome_messages.ambr@@ -0,0 +1,94 @@+# serializer version: 1+# name: test_assistant_pane_welcome_copy+ '''+ Hi! I'm PostHog, an AI agent. Ask me about your product data, or tell me what to fix and I'll open a pull request in a connected repo.+ • Keep replying here while I'm working and I'll pick up what you say.+ • Want a different model? Say so: `use fable for this one`.+ • Answering from the wrong project? Name the one you want: `give me DAU for Staging please`.+ • Hit the thumbs under my replies when I get something wrong.+ '''+# ---+# name: test_welcome_copy[channel]+ '''+ Hey, I'm PostHog. Tag me with @PostHog to get started.++ ---++ :wave: Hey, I'm PostHog. Tag me with `@PostHog` and I'll dig into your product data, poke around your codebase, or open a pull request to fix something.++ *Try asking me*+ • `@PostHog why did signups drop in the EU last week?`+ • `@PostHog open a PR that adds a unit test for src/utils.py`++ *A few things worth knowing*+ • Tag me again in the thread while I'm working and I'll pick up what you say.+ • Want a different model? Say so: `@PostHog use fable for this one`, or `@PostHog run this on opus 5 at high effort`.+ • Answering from the wrong project? Name the one you want: `@PostHog give me DAU for Staging please`. `/posthog project` shows your default.+ • You can DM me instead of tagging me here.++ *Tell me when I get it wrong*+ Hit the thumbs under my replies. A thumbs down asks what went wrong, and that goes straight to the team building me. You can also react with :thumbsup: or :thumbsdown:.++ I also unfurl PostHog links shared in this channel. `/posthog` lists my commands, and your default model and thread follow-ups live in <slack://app?team=T_WELCOME&id=A_WELCOME&tab=home|my Home tab>.++ [Read the docs](https://posthog.com/docs/slack-app)+ '''+# ---+# name: test_welcome_copy[team_join]+ '''+ Hey, welcome! I'm PostHog. Message me to get started.++ ---++ :wave: Hey, welcome! I'm PostHog, an AI agent your team already uses here. Message me, or tag `@PostHog` in any channel, and I'll dig into your product data or open a pull request in a connected repo.++ *Try asking me*+ • `why did signups drop in the EU last week?`+ • `fix the flaky billing CI job`++ *A few things worth knowing*+ • Keep replying in the thread while I'm working and I'll pick up what you say. In a channel, tag me in the reply.+ • Want a different model? Say so: `use fable for this one`.++ *Tell me when I get it wrong*+ Hit the thumbs under my replies. A thumbs down asks what went wrong, and that goes straight to the team building me. You can also react with :thumbsup: or :thumbsdown:.++ In a channel, `/posthog` lists my commands. Your default model, thread follow-ups and linked accounts live in <slack://app?team=T_WELCOME&id=A_WELCOME&tab=home|my Home tab>.++ [Read the docs](https://posthog.com/docs/slack-app)+ '''+# ---+# name: TestOnboardingDm.test_onboarding_dm_copy+ '''+ Set up PostHog - self-driving for your product++ ---++ 👋 *Hi, I'm PostHog - self-driving for your product*+ I'm an AI agent on autopilot: I watch your product for problems, investigate them myself, and open pull requests to fix them - so issues get handled before they reach your backlog.++ 💬 *You can also just talk to me*+ Tag `@PostHog` in any channel, or message me here, to dig into your product data or open a pull request. Name a project to route one question: `@PostHog give me DAU for Staging please`. In a channel, `/posthog` lists my commands.++ ---++ *1. Connect your codebase* :wrench:+ Connect GitHub so I can fix things, not just flag them - when I spot a problem in your product I'll proactively open a pull request with the fix for you to review.++ [Connect GitHub](http://localhost:8010/integrations/connect/github/?project_id=<team_id>&connect_from=slack)++ *2. Choose what I watch* :eyes:+ Tick the signals I should monitor and investigate.++ [ ] *Error tracking*: new, reopened & spiking issues++ *3. Where I report* :inbox_tray:+ Everything I find lands in one shared channel so the team stays in the loop.++ [Create #posthog-inbox](slack_inbox_create)++ 🎉 Once you're set up, I'll start watching your product and send your first report to #posthog-inbox as soon as I spot something.++ 👍 Hit the thumbs under my replies when I get something wrong. Your default model and linked accounts live in my Home tab.+ '''+# ---diff --git a/products/slack_app/backend/tests/services/test_slack_welcome_messages.py b/products/slack_app/backend/tests/services/test_slack_welcome_messages.pynew file mode 100644index 000000000000..53e3f51684ba--- /dev/null+++ b/products/slack_app/backend/tests/services/test_slack_welcome_messages.py@@ -0,0 +1,325 @@+import json++import pytest+from unittest.mock import MagicMock, patch++from django.core.cache import cache+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models.integration import Integration, SlackIntegration+from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User++from products.signals.backend.facade.api import set_default_slack_notification_channel+from products.slack_app.backend.feature_flags import ASSISTANT_REQUIRED_SCOPES+from products.slack_app.backend.services.slack_welcome_messages import (+ INBOX_AI_APPROVAL_ACTION_ID,+ INBOX_AI_APPROVAL_BLOCK_PREFIX,+ INBOX_CREATE_ACTION_ID,+ INBOX_JOIN_ACTION_ID,+ INBOX_SOURCES_BLOCK_PREFIX,+ INBOX_SOURCES_CHECKBOXES_ACTION,+ build_assistant_pane_welcome,+ build_channel_welcome,+ build_onboarding_dm,+ build_team_join_welcome,+)+from products.slack_app.backend.tests.helpers import action_ids, all_block_text, render_blocks, url_buttons++BUILDERS = [+ ("channel", build_channel_welcome),+ ("team_join", build_team_join_welcome),+]+++# An install that granted everything, so the copy a snapshot files is the whole of it.+ASSISTANT_SCOPE_CONFIG = {"scope": ",".join(sorted(ASSISTANT_REQUIRED_SCOPES))}+++def _integration(**config) -> Integration:+ # Unsaved: every builder reads `config` and `integration_id` only.+ return Integration(kind="slack", integration_id="T_WELCOME", config={**ASSISTANT_SCOPE_CONFIG, **config})+++# Keyed by name rather than by builder so each snapshot is filed under a readable id.[email protected]("name", [name for name, _ in BUILDERS])+def test_welcome_copy(name, snapshot):+ build = dict(BUILDERS)[name]+ text, blocks = build(_integration(app_id="A_WELCOME"))++ assert snapshot == f"{text}\n\n---\n\n{render_blocks(blocks)}"+++def test_assistant_pane_welcome_copy(snapshot):+ assert snapshot == build_assistant_pane_welcome()+++def test_assistant_pane_welcome_names_no_slash_command():+ # The pane is a DM, where the slash commands are not reachable.+ assert "/posthog" not in build_assistant_pane_welcome()+++def test_assistant_pane_welcome_carries_no_markup_the_container_drops():+ # Posted as `text`, which renders mrkdwn but no blocks, so a link or a block-only+ # construct would reach the reader as literal characters.+ pane = build_assistant_pane_welcome()++ assert "<" not in pane and ">" not in pane+++class TestWelcomeMessages(SimpleTestCase):+ @parameterized.expand(BUILDERS)+ def test_links_the_home_tab_when_the_app_id_is_known(self, _name, build):+ _, blocks = build(_integration(app_id="A_WELCOME"))++ assert "<slack://app?team=T_WELCOME&id=A_WELCOME&tab=home|" in json.dumps(blocks)++ @parameterized.expand(BUILDERS)+ def test_names_the_home_tab_in_plain_words_without_an_app_id(self, _name, build):+ _, blocks = build(_integration())+ rendered = json.dumps(blocks)++ assert "Home tab" in rendered+ assert "slack://" not in rendered+ assert "None" not in rendered++ @parameterized.expand(BUILDERS)+ def test_asks_for_a_rating(self, _name, build):+ _, blocks = build(_integration(app_id="A_WELCOME"))+ rendered = json.dumps(blocks)++ assert ":thumbsup:" in rendered and ":thumbsdown:" in rendered++ @parameterized.expand(BUILDERS)+ def test_carries_fallback_text_for_the_notification(self, _name, build):+ text, blocks = build(_integration(app_id="A_WELCOME"))++ assert text+ # Slack drops `blocks` from a notification preview, so text that leaked mrkdwn or a+ # link would show as raw markup on a lock screen.+ assert "<" not in text and "*" not in text and "`" not in text+ assert blocks++ @parameterized.expand([("with_scopes", True), ("without_scopes", False)])+ def test_channel_welcome_points_at_dms_only_where_they_answer(self, _name, has_assistant_scopes):+ # Slack never delivers `message.im` to an install without the assistant scopes, so on+ # those workspaces the advice sends the reader to a bot that stays silent.+ scope = ",".join(ASSISTANT_REQUIRED_SCOPES) if has_assistant_scopes else "chat:write"+ _, blocks = build_channel_welcome(+ Integration(kind="slack", integration_id="T_WELCOME", config={"scope": scope})+ )++ assert ("DM me" in all_block_text(blocks)) is has_assistant_scopes+++class TestOnboardingDm:+ """The install onboarding DM: which blocks each step renders, and what the copy says."""++ @pytest.fixture(autouse=True)+ def setup(self, db):+ cache.clear()+ self.organization = Organization.objects.create(name="Org")+ self.team = Team.objects.create(organization=self.organization, name="Team")+ self.user = User.objects.create(email="[email protected]", first_name="Installer")+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T12345",+ config={"scope": "channels:manage,chat:write"},+ sensitive_config={"access_token": "xoxb-test"},+ )++ def _client(self, mock_webclient_class):+ client = MagicMock()+ # Default: empty membership so onboarding DMs render normally unless a test says otherwise.+ client.conversations_members.return_value = {"members": [], "response_metadata": {"next_cursor": ""}}+ mock_webclient_class.return_value = client+ return client++ @patch("posthog.models.integration.slack.WebClient")+ def test_dm_join_button_when_channel_exists_with_scope(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert INBOX_JOIN_ACTION_ID in action_ids(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_dm_instructions_when_channel_exists_without_scope(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ self.integration.config = {"scope": "chat:write"}+ self.integration.save()+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert INBOX_JOIN_ACTION_ID not in action_ids(blocks)+ assert "workspace" in all_block_text(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_dm_create_button_when_no_channel_with_scope(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert INBOX_CREATE_ACTION_ID in action_ids(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_dm_instructions_with_inbox_link_when_no_channel_no_scope(self, mock_webclient_class):+ self._client(mock_webclient_class)+ self.integration.config = {"scope": "chat:write"}+ self.integration.save()++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert INBOX_CREATE_ACTION_ID not in action_ids(blocks)+ assert "/inbox" in all_block_text(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_appends_github_button_when_missing(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration), needs_github=True)++ urls = url_buttons(blocks)+ assert any(+ f"/integrations/connect/github/?project_id={self.team.id}" in u and "connect_from=slack" in u for u in urls+ )+ assert INBOX_CREATE_ACTION_ID in action_ids(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_omits_join_when_already_member(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_github=False, already_in_channel=True+ )++ assert blocks != []+ assert INBOX_JOIN_ACTION_ID not in action_ids(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_already_member_shows_only_github(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_github=True, already_in_channel=True+ )++ assert any("/integrations/connect/github/" in u for u in url_buttons(blocks))+ assert INBOX_JOIN_ACTION_ID not in action_ids(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_onboarding_dm_copy(self, mock_webclient_class, snapshot):+ self._client(mock_webclient_class)++ text, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration), needs_github=True)++ # The connect link carries the team's autoincrement id, which differs every run. Anchored+ # on the query parameter, because a bare id substitution also rewrites the port number.+ rendered = render_blocks(blocks).replace(f"project_id={self.team.id}", "project_id=<team_id>")+ assert snapshot == f"{text}\n\n---\n\n{rendered}"++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_no_github_block_when_connected(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert not any("/integrations/connect/github" in u for u in url_buttons(blocks))++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_sources_inline_checkboxes(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert INBOX_SOURCES_CHECKBOXES_ACTION in action_ids(blocks)+ checkboxes = next(+ el for b in blocks if b["type"] == "actions" for el in b["elements"] if el.get("type") == "checkboxes"+ )+ # only the two built-in toggle sources, no Linear / GitHub issues+ assert {o["value"] for o in checkboxes["options"]} == {"error_tracking"}+ block = next(b for b in blocks if b.get("block_id", "").startswith(INBOX_SOURCES_BLOCK_PREFIX))+ assert block["block_id"] == f"{INBOX_SOURCES_BLOCK_PREFIX}:{self.integration.id}"+ assert "Choose what I watch" in all_block_text(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_shows_done_steps_as_checks(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration), already_in_channel=True)++ # done steps render as '✅' lines, not pruned+ text = all_block_text(blocks)+ assert "Connected" in text+ assert "Posting to #posthog-inbox" in text+ assert INBOX_SOURCES_CHECKBOXES_ACTION in action_ids(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_omits_ai_approval_when_done(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration), needs_github=True)++ assert "AI data processing" not in " ".join(str(b) for b in blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_always_returns_message_even_when_all_done(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, all_done = build_onboarding_dm(self.integration, SlackIntegration(self.integration), already_in_channel=True)++ assert all_done != [] # posted unconditionally on install+ assert INBOX_JOIN_ACTION_ID not in action_ids(all_done)+ assert not any("/integrations/connect/github" in u for u in url_buttons(all_done))++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_ai_approval_checkbox_for_admin_and_trails(self, mock_webclient_class):+ self._client(mock_webclient_class)++ text, blocks = build_onboarding_dm(+ self.integration,+ SlackIntegration(self.integration),+ needs_ai_approval=True,+ ai_approval_is_admin=True,+ needs_github=True,+ )++ # Admin gets an inline checkbox (no browser/url) — approval happens in Slack.+ assert INBOX_AI_APPROVAL_ACTION_ID in action_ids(blocks)+ assert not any("organization-details" in u for u in url_buttons(blocks))+ ai_block = next(b for b in blocks if b.get("block_id", "").startswith(INBOX_AI_APPROVAL_BLOCK_PREFIX))+ assert ai_block["elements"][0]["type"] == "checkboxes"+ assert "AI data processing" not in text # fixed notification text, not the step copy++ @patch("posthog.models.integration.slack.WebClient")+ def test_build_dm_ai_approval_note_for_non_admin_no_button(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_ai_approval=True, ai_approval_is_admin=False+ )++ assert INBOX_AI_APPROVAL_ACTION_ID not in action_ids(blocks)+ assert "Ask an org admin" in all_block_text(blocks)++ @patch("posthog.models.integration.slack.WebClient")+ def test_dm_leads_with_self_driving_intro(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = build_onboarding_dm(self.integration, SlackIntegration(self.integration), needs_github=True)++ assert blocks[0]["type"] == "section"+ assert "self-driving" in blocks[0]["text"]["text"]+ assert "first report" in all_block_text(blocks)diff --git a/products/slack_app/backend/tests/test_onboarding.py b/products/slack_app/backend/tests/test_onboarding.pyindex f84e299852b7..c232752a927b 100644--- a/products/slack_app/backend/tests/test_onboarding.py+++ b/products/slack_app/backend/tests/test_onboarding.py@@ -5,7 +5,7 @@ from django.core.cache import cachefrom slack_sdk.errors import SlackApiError-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -15,6 +15,8 @@ from products.signals.backend.facade.api import (set_default_slack_notification_channel,)from products.slack_app.backend import onboarding+from products.slack_app.backend.services import slack_welcome_messages+from products.slack_app.backend.tests.helpers import action_ids, all_block_text, url_buttonsclass TestOnboarding:@@ -39,70 +41,6 @@ class TestOnboarding:mock_webclient_class.return_value = clientreturn client- def _action_ids(self, blocks):- ids = [el["action_id"] for b in blocks if b["type"] == "actions" for el in b["elements"] if "action_id" in el]- ids += [b["accessory"]["action_id"] for b in blocks if (b.get("accessory") or {}).get("action_id")]- return ids-- def _url_buttons(self, blocks):- urls = [el["url"] for b in blocks if b["type"] == "actions" for el in b["elements"] if "url" in el]- urls += [b["accessory"]["url"] for b in blocks if (b.get("accessory") or {}).get("url")]- return urls-- def _all_text(self, blocks):- parts: list[str] = []- for b in blocks:- if (b.get("text") or {}).get("text"):- parts.append(b["text"]["text"])- for f in b.get("fields", []):- parts.append(f.get("text", ""))- for el in b.get("elements", []):- txt = el.get("text")- parts.append(txt if isinstance(txt, str) else (txt or {}).get("text", ""))- return " ".join(parts)-- @patch("posthog.models.integration.slack.WebClient")- def test_dm_join_button_when_channel_exists_with_scope(self, mock_webclient_class):- client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")- client.conversations_info.return_value = {"channel": {"id": "C1"}}-- _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))-- assert onboarding.INBOX_JOIN_ACTION_ID in self._action_ids(blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_dm_instructions_when_channel_exists_without_scope(self, mock_webclient_class):- client = self._client(mock_webclient_class)- self.integration.config = {"scope": "chat:write"}- self.integration.save()- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")- client.conversations_info.return_value = {"channel": {"id": "C1"}}-- _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))-- assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)- assert "workspace" in self._all_text(blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_dm_create_button_when_no_channel_with_scope(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))-- assert onboarding.INBOX_CREATE_ACTION_ID in self._action_ids(blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_dm_instructions_with_inbox_link_when_no_channel_no_scope(self, mock_webclient_class):- self._client(mock_webclient_class)- self.integration.config = {"scope": "chat:write"}- self.integration.save()-- _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))-- assert onboarding.INBOX_CREATE_ACTION_ID not in self._action_ids(blocks)- assert "/inbox" in self._all_text(blocks)-@patch("posthog.models.integration.slack.WebClient")def test_send_onboarding_dm_posts_each_call(self, mock_webclient_class):# No per-user dedupe — onboarding is sent once because the install hook fires once, not@@ -139,7 +77,7 @@ class TestOnboarding:@patch("posthog.models.integration.slack.WebClient")def test_run_install_onboarding_noop_when_missing_scope(self, mock_webclient_class):client = self._client(mock_webclient_class)- # No channels:manage scope -> onboarding is gated off for this install.+ # No channels:manage -> the message would describe a channel we cannot open for them.self.integration.config = {"scope": "chat:write", "authed_user": {"id": "U_INSTALL"}}self.integration.save()@@ -160,46 +98,6 @@ class TestOnboarding:assert onboarding.send_onboarding_dm(self.integration, "U1") is Trueassert client.chat_postMessage.call_count == 2- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_appends_github_button_when_missing(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), needs_github=True- )-- urls = self._url_buttons(blocks)- assert any(- f"/integrations/connect/github/?project_id={self.team.id}" in u and "connect_from=slack" in u for u in urls- )- assert onboarding.INBOX_CREATE_ACTION_ID in self._action_ids(blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_omits_join_when_already_member(self, mock_webclient_class):- client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")- client.conversations_info.return_value = {"channel": {"id": "C1"}}-- _, blocks = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), needs_github=False, already_in_channel=True- )-- assert blocks != []- assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_already_member_shows_only_github(self, mock_webclient_class):- client = self._client(mock_webclient_class)- set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")- client.conversations_info.return_value = {"channel": {"id": "C1"}}-- _, blocks = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), needs_github=True, already_in_channel=True- )-- assert any("/integrations/connect/github/" in u for u in self._url_buttons(blocks))- assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)-@patch("products.slack_app.backend.onboarding._has_enabled_source", return_value=True)@patch("products.slack_app.backend.onboarding._has_team_github", return_value=True)@patch("products.slack_app.backend.onboarding._has_personal_github", return_value=True)@@ -217,14 +115,6 @@ class TestOnboarding:assert onboarding.send_onboarding_dm(self.integration, "U1") is Trueclient.chat_postMessage.assert_called_once()- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_no_github_block_when_connected(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))-- assert not any("/integrations/connect/github" in u for u in self._url_buttons(blocks))-@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=123)@patch("products.slack_app.backend.onboarding._has_personal_github", return_value=False)@patch("products.slack_app.backend.onboarding._has_team_github", return_value=False)@@ -236,61 +126,9 @@ class TestOnboarding:assert onboarding.send_onboarding_dm(self.integration, "U1") is True- urls = self._url_buttons(client.chat_postMessage.call_args.kwargs["blocks"])+ urls = url_buttons(client.chat_postMessage.call_args.kwargs["blocks"])assert any("/integrations/connect/github/" in u and "connect_from=slack" in u for u in urls)- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_sources_inline_checkboxes(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))-- assert onboarding.INBOX_SOURCES_CHECKBOXES_ACTION in self._action_ids(blocks)- checkboxes = next(- el for b in blocks if b["type"] == "actions" for el in b["elements"] if el.get("type") == "checkboxes"- )- # only the two built-in toggle sources, no Linear / GitHub issues- assert {o["value"] for o in checkboxes["options"]} == {"error_tracking"}- block = next(b for b in blocks if b.get("block_id", "").startswith(onboarding.INBOX_SOURCES_BLOCK_PREFIX))- assert block["block_id"] == f"{onboarding.INBOX_SOURCES_BLOCK_PREFIX}:{self.integration.id}"- assert "Choose what I watch" in self._all_text(blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_shows_done_steps_as_checks(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), already_in_channel=True- )-- # done steps render as '✅' lines, not pruned- text = self._all_text(blocks)- assert "Connected" in text- assert "Posting to #posthog-inbox" in text- assert onboarding.INBOX_SOURCES_CHECKBOXES_ACTION in self._action_ids(blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_omits_ai_approval_when_done(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), needs_github=True- )-- assert "AI data processing" not in " ".join(str(b) for b in blocks)-- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_always_returns_message_even_when_all_done(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, all_done = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), already_in_channel=True- )-- assert all_done != [] # posted unconditionally on install- assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(all_done)- assert not any("/integrations/connect/github" in u for u in self._url_buttons(all_done))-@patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)@patch("posthog.models.integration.slack.WebClient")def test_apply_sources_selection_syncs_checkboxes(self, mock_webclient_class, _resolve):@@ -313,38 +151,6 @@ class TestOnboarding:set_sources(self.team.id, None, ["error_tracking"])assert has_enabled_source(self.team.id) is True- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_ai_approval_checkbox_for_admin_and_trails(self, mock_webclient_class):- self._client(mock_webclient_class)-- text, blocks = onboarding.build_onboarding_dm(- self.integration,- SlackIntegration(self.integration),- needs_ai_approval=True,- ai_approval_is_admin=True,- needs_github=True,- )-- # Admin gets an inline checkbox (no browser/url) — approval happens in Slack.- assert onboarding.INBOX_AI_APPROVAL_ACTION_ID in self._action_ids(blocks)- assert not any("organization-details" in u for u in self._url_buttons(blocks))- ai_block = next(- b for b in blocks if b.get("block_id", "").startswith(onboarding.INBOX_AI_APPROVAL_BLOCK_PREFIX)- )- assert ai_block["elements"][0]["type"] == "checkboxes"- assert "AI data processing" not in text # fixed notification text, not the step copy-- @patch("posthog.models.integration.slack.WebClient")- def test_build_dm_ai_approval_note_for_non_admin_no_button(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), needs_ai_approval=True, ai_approval_is_admin=False- )-- assert onboarding.INBOX_AI_APPROVAL_ACTION_ID not in self._action_ids(blocks)- assert "Ask an org admin" in self._all_text(blocks)-def test_has_ai_approval_reflects_org(self):assert onboarding._has_ai_approval(self.team.id) is True # default-approved orgself.organization.is_ai_data_processing_approved = False@@ -398,7 +204,7 @@ class TestOnboarding:# Everything else satisfied, but the unapproved org still triggers a DM — admin gets the button.assert onboarding.send_onboarding_dm(self.integration, "U1") is Trueblocks = client.chat_postMessage.call_args.kwargs["blocks"]- assert onboarding.INBOX_AI_APPROVAL_ACTION_ID in self._action_ids(blocks)+ assert slack_welcome_messages.INBOX_AI_APPROVAL_ACTION_ID in action_ids(blocks)@patch("products.slack_app.backend.onboarding._is_org_admin", return_value=False)@patch("products.slack_app.backend.onboarding._has_enabled_source", return_value=True)@@ -419,8 +225,8 @@ class TestOnboarding:# A member can't approve, so they get an informational note (no button) and aren't blocked.assert onboarding.send_onboarding_dm(self.integration, "U1") is Trueblocks = client.chat_postMessage.call_args.kwargs["blocks"]- assert onboarding.INBOX_AI_APPROVAL_ACTION_ID not in self._action_ids(blocks)- assert "Ask an org admin" in self._all_text(blocks)+ assert slack_welcome_messages.INBOX_AI_APPROVAL_ACTION_ID not in action_ids(blocks)+ assert "Ask an org admin" in all_block_text(blocks)def test_slack_event_props_bundle(self):from products.slack_app.backend.analytics import slack_event_props@@ -479,18 +285,6 @@ class TestOnboarding:assert onboarding.EVENT_COMPLETED not in [c.args[1] for c in mock_capture.call_args_list]- @patch("posthog.models.integration.slack.WebClient")- def test_dm_leads_with_self_driving_intro(self, mock_webclient_class):- self._client(mock_webclient_class)-- _, blocks = onboarding.build_onboarding_dm(- self.integration, SlackIntegration(self.integration), needs_github=True- )-- assert blocks[0]["type"] == "section"- assert "self-driving" in blocks[0]["text"]["text"]- assert "first report" in self._all_text(blocks)-@patch("products.slack_app.backend.onboarding.run_install_onboarding")def test_onboarding_workflow_activity_runs_for_integration(self, mock_run):from posthog.temporal.ai.slack_app.activities.onboarding import run_posthog_slack_inbox_onboardingdiff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex cc3d10384150..20945e8cd904 100644--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py@@ -1583,51 +1583,6 @@ class TestAssistantEvents(TestCase):mock_start.assert_not_called()-class TestAssistantInstallWelcome(TestCase):- def setUp(self):- self.organization = Organization.objects.create(name="Install Org")- self.team = Team.objects.create(organization=self.organization, name="Install Team")- self.integration = Integration.objects.create(- team=self.team,- kind="slack",- integration_id="T_INSTALL",- config={"authed_user": {"id": "U_INSTALLER"}},- sensitive_config={"access_token": "xoxb-test"},- )-- def _run(self, *, enabled: bool):- from products.slack_app.backend.api import _ASSISTANT_INSTALL_WELCOME, send_assistant_install_welcome-- enabled_p = patch("products.slack_app.backend.api.is_slack_app_assistant_enabled", return_value=enabled)- slack = patch("products.slack_app.backend.api.SlackIntegration")- with enabled_p, slack as slack_cls:- send_assistant_install_welcome(self.integration)- return slack_cls, _ASSISTANT_INSTALL_WELCOME-- def test_dms_installer_when_enabled(self):- slack_cls, welcome = self._run(enabled=True)- slack_cls.return_value.client.chat_postMessage.assert_called_once_with(channel="U_INSTALLER", text=welcome)-- def test_silent_when_flag_off(self):- slack_cls, _ = self._run(enabled=False)- slack_cls.return_value.client.chat_postMessage.assert_not_called()-- def test_no_post_without_authed_user(self):- self.integration.config = {}- self.integration.save()- slack_cls, _ = self._run(enabled=True)- slack_cls.return_value.client.chat_postMessage.assert_not_called()-- def test_slack_error_is_swallowed(self):- from products.slack_app.backend.api import send_assistant_install_welcome-- enabled_p = patch("products.slack_app.backend.api.is_slack_app_assistant_enabled", return_value=True)- slack = patch("products.slack_app.backend.api.SlackIntegration")- with enabled_p, slack as slack_cls:- slack_cls.return_value.client.chat_postMessage.side_effect = Exception("slack down")- send_assistant_install_welcome(self.integration) # must not raise--class TestQueueWorkflowDispatch(TestCase):def setUp(self):from django.utils import timezone