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): assistant + DM support (#61905)

Joshua Snyder3f6765642c04
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 3f4d6a1c2971..4154fc28f8ff 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -376,7 +376,7 @@ def _build_message_blocks(
blocks.append({"type": "actions", "elements": action_elements})
priority_suffix = f" ({priority})" if priority else ""
- fallback_text = f"Inbox item{priority_suffix}: {title_line}"
+ fallback_text = f"Inbox item{priority_suffix}: {_escape_mrkdwn(title_line)}"
return blocks, fallback_text
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 088b03aeeb6f..3f532740f821 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -35,6 +35,7 @@ from posthog.models.integration import (
validate_slack_request,
)
from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.temporal.ai.posthog_code_slack_interactivity import (
@@ -64,7 +65,14 @@ from products.slack_app.backend.slack_link_unfurl import handle_posthog_link_unf
logger = structlog.get_logger(__name__)
-HANDLED_EVENT_TYPES = ["app_mention", "link_shared", "message", "member_joined_channel"]
+HANDLED_EVENT_TYPES = [
+ "app_mention",
+ "link_shared",
+ "message",
+ "member_joined_channel",
+ "assistant_thread_started",
+ "assistant_thread_context_changed",
+]
# The notifications Slack app (`slack`) install carries every scope the coding-agent flow
# needs, so both surfaces share one kind.
@@ -1607,17 +1615,22 @@ def _post_pick_a_project_hint(
event: dict[str, Any],
) -> None:
"""Tell the user that this workspace is connected to multiple PostHog
- projects, and that they should pick one via `@PostHog project <id>`.
+ projects, and that they should pick one.
+
+ The selection command differs by surface: in a channel the user mentions the app
+ (`@PostHog project <id>`), but in a DM there is no app to mention, so they just reply
+ with `project <id>`.
"""
slack_user_id = event.get("user")
channel = event.get("channel")
thread_ts = event.get("thread_ts") or event.get("ts")
if not isinstance(slack_user_id, str) or not isinstance(channel, str) or not isinstance(thread_ts, str):
return
+ pick_command = "`project <id>`" if event.get("channel_type") == "im" else "`@PostHog project <id>`"
text = (
"This Slack workspace is connected to multiple PostHog projects:\n"
f"{format_project_candidate_list(candidates)}\n\n"
- "Use `@PostHog project <id>` to pick one — that also saves it as your default."
+ f"Use {pick_command} to pick one — that also saves it as your default."
)
_post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
@@ -1675,6 +1688,240 @@ def _start_posthog_code_workflow(
)
+_ASSISTANT_FEATURE_FLAG = "slack-app-assistant"
+_ASSISTANT_CONTEXT_TTL_SECONDS = 60 * 60
+_ASSISTANT_SUGGESTED_PROMPTS = [
+ {"title": "Fix a bug", "message": "Open a PR to fix a bug in my connected repo"},
+ {"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."
+)
+
+
+def _assistant_enabled(team: Team) -> bool:
+ # Evaluated on the workspace's team (a stable key) so the flag is a true kill-switch we can
+ # check before resolving the DMing user — i.e. the feature stays dark when off.
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ _ASSISTANT_FEATURE_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id)},
+ )
+ )
+ except Exception:
+ logger.warning("assistant_feature_flag_eval_failed", exc_info=True)
+ return False
+
+
+def _assistant_event_fields(event: dict) -> tuple[str, str | None, str | None, str | None]:
+ """(slack_user_id, dm_channel_id, thread_ts, viewed_channel_id) for assistant events.
+
+ For `message` events the fields live at the top level; for `assistant_thread_*` events
+ they live under `assistant_thread` (with the viewed channel under `context`).
+ """
+ if event.get("type") == "message":
+ ts = event.get("thread_ts") or event.get("ts")
+ return (
+ str(event.get("user") or ""),
+ event.get("channel") if isinstance(event.get("channel"), str) else None,
+ ts if isinstance(ts, str) else None,
+ None,
+ )
+ thread = event.get("assistant_thread") or {}
+ ctx = thread.get("context") or {}
+ return (
+ str(thread.get("user_id") or ""),
+ thread.get("channel_id") if isinstance(thread.get("channel_id"), str) else None,
+ thread.get("thread_ts") if isinstance(thread.get("thread_ts"), str) else None,
+ ctx.get("channel_id") if isinstance(ctx.get("channel_id"), str) else None,
+ )
+
+
+def _assistant_context_cache_key(integration_id: int, channel_id: str, thread_ts: str) -> str:
+ return f"slack_assistant_ctx:{integration_id}:{channel_id}:{thread_ts}"
+
+
+def _store_assistant_channel_context(
+ integration_id: int, channel_id: str, thread_ts: str, viewed_channel_id: str | None
+) -> None:
+ if viewed_channel_id:
+ cache.set(
+ _assistant_context_cache_key(integration_id, channel_id, thread_ts),
+ viewed_channel_id,
+ timeout=_ASSISTANT_CONTEXT_TTL_SECONDS,
+ )
+
+
+def _get_assistant_channel_context(integration_id: int, channel_id: str, thread_ts: str) -> str | None:
+ value = cache.get(_assistant_context_cache_key(integration_id, channel_id, thread_ts))
+ return value if isinstance(value, str) else None
+
+
+def _handle_assistant_thread_started(slack: SlackIntegration, channel_id: str, thread_ts: str) -> str:
+ """Greet the user and offer suggested prompts when they open the agent container."""
+ try:
+ slack.client.assistant_threads_setSuggestedPrompts(
+ channel_id=channel_id,
+ thread_ts=thread_ts,
+ title="What can I help you ship?",
+ prompts=_ASSISTANT_SUGGESTED_PROMPTS,
+ )
+ slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=_ASSISTANT_WELCOME)
+ except Exception:
+ logger.warning("assistant_thread_started_failed", exc_info=True)
+ return ROUTE_HANDLED_LOCALLY
+
+
+def _post_assistant_unavailable(slack: SlackIntegration, channel_id: str, thread_ts: str) -> None:
+ try:
+ slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=_ASSISTANT_UNAVAILABLE)
+ except Exception:
+ logger.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 _assistant_enabled(integration.team):
+ 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)
+
+
+# The DM/agent surface needs the base coding-agent scopes plus the assistant container scopes.
+# Kept separate from POSTHOG_CODE_REQUIRED_SLACK_SCOPES so the mention flow isn't gated on im:history.
+_ASSISTANT_REQUIRED_SLACK_SCOPES = POSTHOG_CODE_REQUIRED_SLACK_SCOPES | frozenset({"assistant:write", "im:history"})
+
+
+def _handle_assistant_dm_message(
+ event: dict,
+ integration: Integration,
+ slack_team_id: str,
+ event_id: str | None,
+ channel_id: str,
+ thread_ts: str,
+ *,
+ posthog_user: User,
+) -> str:
+ slack = SlackIntegration(integration)
+ missing = slack.missing_scopes(_ASSISTANT_REQUIRED_SLACK_SCOPES)
+ if missing:
+ _notify_missing_slack_scopes(slack, event, missing)
+ return ROUTE_HANDLED_LOCALLY
+
+ try:
+ slack.client.assistant_threads_setStatus(channel_id=channel_id, thread_ts=thread_ts, status="Working on it…")
+ except Exception:
+ logger.warning("assistant_set_status_failed", exc_info=True)
+
+ # Carry the channel the user was viewing (from assistant_thread_context_changed) so the agent
+ # can ground a "look into this" DM in that channel's context.
+ viewed = _get_assistant_channel_context(integration.id, channel_id, thread_ts)
+ agent_event = {**event, "assistant_viewed_channel_id": viewed} if viewed else event
+ return _start_mention_workflow(agent_event, integration, slack_team_id, event_id, posthog_user=posthog_user)
+
+
+def _route_assistant_event(
+ request: HttpRequest,
+ event: dict,
+ slack_team_id: str,
+ event_id: str | None,
+ *,
+ proxied: bool,
+ incoming_host: str,
+ other_domain: str,
+ can_defer: bool,
+) -> str:
+ """Route DM / agent-container events through the same region + project resolution as mentions."""
+ event_type = event.get("type")
+ slack_user_id, channel_id, thread_ts, ctx_channel = _assistant_event_fields(event)
+
+ # Only first-party human DMs proceed — ignore channel messages, bot echoes, and edits.
+ if event_type == "message" and (
+ event.get("channel_type") != "im"
+ or event.get("bot_id")
+ or event.get("subtype")
+ or not str(event.get("text") or "").strip()
+ ):
+ return ROUTE_HANDLED_LOCALLY
+ if not (slack_user_id and channel_id and thread_ts):
+ return ROUTE_HANDLED_LOCALLY
+
+ result = load_integrations(
+ slack_team_id=slack_team_id,
+ kinds=[SLACK_INTEGRATION_KIND],
+ slack_user_id=slack_user_id,
+ user=None,
+ channel=channel_id,
+ thread_ts=thread_ts,
+ )
+ region_route = _resolve_region_or_terminal_route(
+ request,
+ slack_team_id,
+ candidates_present=bool(result.candidates),
+ kinds=[SLACK_INTEGRATION_KIND],
+ proxied=proxied,
+ other_domain=other_domain,
+ incoming_host=incoming_host,
+ can_defer=can_defer,
+ )
+ if region_route is not None:
+ return region_route
+
+ probe = result.integration if result.integration in result.candidates else result.candidates[0]
+
+ # Kill-switch first: stay fully dark (no user resolution, no Slack reply) when the flag is off.
+ if not _assistant_enabled(probe.team):
+ return ROUTE_HANDLED_LOCALLY
+
+ # Share the mention path's user resolution + access filter, so the DM only ever sees and runs
+ # against projects the resolved PostHog user can actually access (no cross-org metadata leak).
+ resolution = resolve_user_for_workspace(
+ workspace_result=result,
+ slack_team_id=slack_team_id,
+ slack_user_id=slack_user_id,
+ event_id=event_id,
+ )
+ if resolution.user is None:
+ # Flag is on but the Slack user isn't a resolvable org member — tell them why (DMs only).
+ if event_type == "message":
+ _post_assistant_unavailable(SlackIntegration(probe), channel_id, thread_ts)
+ return ROUTE_HANDLED_LOCALLY
+ posthog_user = resolution.user
+
+ if event_type == "assistant_thread_started":
+ return _handle_assistant_thread_started(SlackIntegration(probe), channel_id, thread_ts)
+ if event_type == "assistant_thread_context_changed":
+ _store_assistant_channel_context(probe.id, channel_id, thread_ts, ctx_channel)
+ return ROUTE_HANDLED_LOCALLY
+
+ # message.im — run the agent against the user's accessible default project, else ask them to pick.
+ accessible = resolution.candidates
+ mention_target = resolution.integration or (accessible[0] if len(accessible) == 1 else None)
+ if mention_target is None:
+ _post_pick_a_project_hint(SlackIntegration(accessible[0]), accessible, event)
+ return ROUTE_HANDLED_LOCALLY
+ return _handle_assistant_dm_message(
+ event, mention_target, slack_team_id, event_id, channel_id, thread_ts, posthog_user=posthog_user
+ )
+
+
def route_posthog_code_event_to_relevant_region(
request: HttpRequest,
event: dict,
@@ -1707,6 +1954,23 @@ def route_posthog_code_event_to_relevant_region(
eu_domain=_eu_region_domain(),
)
+ # Assistant surface: DMs to the app and agent-container events resolve the DMing user and run
+ # against their project. A ``message`` is a DM iff ``channel_type == "im"`` — channel ``message``
+ # events (untagged thread follow-ups) and ``app_mention`` share the pipeline below instead.
+ if event_type in ("assistant_thread_started", "assistant_thread_context_changed") or (
+ event_type == "message" and event.get("channel_type") == "im"
+ ):
+ return _route_assistant_event(
+ request,
+ event,
+ slack_team_id,
+ event_id,
+ proxied=proxied,
+ incoming_host=incoming_host,
+ other_domain=other_domain,
+ can_defer=can_defer_to_other_region,
+ )
+
if event_type in ("app_mention", "message"):
if event_type == "app_mention":
ignore_reason = _app_mention_ignore_reason(event)
@@ -1751,11 +2015,18 @@ def route_posthog_code_event_to_relevant_region(
channel=channel_str,
thread_ts=thread_ts_str,
)
- if not workspace_result.candidates:
- return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
-
- if _us_should_handle_instead(slack_team_id, [SLACK_INTEGRATION_KIND], can_defer_to_other_region, incoming_host):
- return _proxy_event_and_return_route(request, other_domain)
+ region_route = _resolve_region_or_terminal_route(
+ request,
+ slack_team_id,
+ candidates_present=bool(workspace_result.candidates),
+ kinds=[SLACK_INTEGRATION_KIND],
+ proxied=proxied,
+ other_domain=other_domain,
+ incoming_host=incoming_host,
+ can_defer=can_defer_to_other_region,
+ )
+ if region_route is not None:
+ return region_route
# Threads we don't own (and orgs that haven't opted in) are dropped here
# so the rest of the pipeline only runs for actionable messages.
@@ -1946,6 +2217,30 @@ def _route_to_other_region_or_drop(
return _proxy_event_and_return_route(request, other_domain)
+def _resolve_region_or_terminal_route(
+ request: HttpRequest,
+ slack_team_id: str,
+ *,
+ candidates_present: bool,
+ kinds: list[str],
+ proxied: bool,
+ other_domain: str,
+ incoming_host: str,
+ can_defer: bool,
+) -> str | None:
+ """Shared region gate for every coding-agent surface (mentions, channel followups, DMs).
+
+ Returns a terminal route when the event leaves this region — forwarded/dropped because no
+ local integration claims the workspace, or proxied to US under the US-precedence rule — else
+ ``None`` to signal the caller should keep handling the event locally.
+ """
+ if not candidates_present:
+ return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
+ if _us_should_handle_instead(slack_team_id, kinds, can_defer, incoming_host):
+ return _proxy_event_and_return_route(request, other_domain)
+ return None
+
+
def _start_command_workflow(
event: dict,
integrations: list[Integration],
@@ -3215,8 +3510,9 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
integration_id=slack_team_id,
).exists()
elif slack_team_id and dismiss_integration_id:
- # Any reviewer who can see the inbox-item message may dismiss it (team-shared channels),
- # so this isn't gated on a specific Slack user — only on owning the integration locally.
+ # Routing/region-ownership only — this just claims the workspace's integration locally.
+ # Authorization (report-team match + org-member gate) is enforced in _handle_signals_dismiss_report.
+ # Intended trust boundary for dismiss is org membership (any org member can dismiss the org's reports).
local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team
id=dismiss_integration_id, # nosemgrep: idor-taint-user-input-to-model-get
kind=SLACK_INTEGRATION_KIND,
diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.py
index 5a39a35cce25..1dc5d0463389 100644
--- a/products/slack_app/backend/services/integration_resolver.py
+++ b/products/slack_app/backend/services/integration_resolver.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass, field
from typing import Literal
+from django.conf import settings
from django.db.models import Q
import structlog
@@ -237,6 +238,10 @@ def resolve_user_for_workspace(
probe = workspace_result.candidates[0]
slack_email = get_slack_email_for_user(probe, slack_user_id)
+ if settings.DEBUG:
+ # When running locally - match the local user
+ slack_email = "[email protected]"
+
posthog_user = resolve_posthog_user_from_event(
slack_user_id=slack_user_id,
probe_integration=probe,
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index 9677842489cb..1e808b3aa04a 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
@@ -72,6 +72,7 @@ class TestPostHogCodeEventHandler(TestCase):
("app_mention_proxy_failed", "app_mention", "proxy_failed", 502, True),
("app_mention_no_integration", "app_mention", "no_integration", 202, True),
("member_joined_channel_routes", "member_joined_channel", "handled_locally", 202, True),
+ ("message_dm_routes", "message", "handled_locally", 202, True),
("non_handled_event_type_skips_routing", "reaction_added", "handled_locally", 202, False),
]
)
@@ -1068,3 +1069,187 @@ class TestChannelApprovalGate(TestCase):
mock_route.assert_called_once()
assert mock_route.call_args.kwargs["is_ext_shared_channel"] is True
+
+
+class TestAssistantEvents(TestCase):
+ def setUp(self):
+ from products.slack_app.backend.api import POSTHOG_CODE_REQUIRED_SLACK_SCOPES
+
+ cache.clear()
+ self.factory = RequestFactory()
+ self.organization = Organization.objects.create(name="Assistant Org")
+ self.team = Team.objects.create(organization=self.organization, name="Assistant Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="assistant-user-1")
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T12345",
+ config={"scope": ",".join(sorted(POSTHOG_CODE_REQUIRED_SLACK_SCOPES))},
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+ def _route(self, event: dict):
+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region
+
+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
+ with override_settings(DEBUG=False):
+ return route_posthog_code_event_to_relevant_region(request, event, "T12345")
+
+ def _patch_resolution(self, *, user, enabled=True):
+ from products.slack_app.backend.services.integration_resolver import (
+ ResolutionResult,
+ UserAndIntegrationsResolution,
+ )
+
+ load = patch(
+ "products.slack_app.backend.api.load_integrations",
+ return_value=ResolutionResult(
+ integration=self.integration, source="sole_candidate", candidates=[self.integration]
+ ),
+ )
+ resolution = (
+ UserAndIntegrationsResolution(
+ user=user, integration=self.integration, candidates=[self.integration], source="sole_candidate"
+ )
+ if user is not None
+ else UserAndIntegrationsResolution(failure_reason="user_not_found")
+ )
+ resolve = patch("products.slack_app.backend.api.resolve_user_for_workspace", return_value=resolution)
+ enabled_p = patch("products.slack_app.backend.api._assistant_enabled", return_value=enabled)
+ usp = patch("products.slack_app.backend.api._us_should_handle_instead", return_value=False)
+ slack = patch("products.slack_app.backend.api.SlackIntegration")
+ return load, resolve, enabled_p, usp, slack
+
+ def test_assistant_thread_started_sets_prompts_for_member(self):
+ load, resolve, enabled_p, usp, slack = self._patch_resolution(user=self.user)
+ with load, resolve, enabled_p, usp, slack as slack_cls:
+ slack_cls.return_value.missing_scopes.return_value = set()
+ self._route(
+ {
+ "type": "assistant_thread_started",
+ "assistant_thread": {"user_id": "U123", "channel_id": "D001", "thread_ts": "111.222"},
+ }
+ )
+ slack_cls.return_value.client.assistant_threads_setSuggestedPrompts.assert_called_once()
+
+ def test_assistant_thread_started_noop_for_non_member(self):
+ load, resolve, enabled_p, usp, slack = self._patch_resolution(user=None)
+ with load, resolve, enabled_p, usp, slack as slack_cls:
+ self._route(
+ {
+ "type": "assistant_thread_started",
+ "assistant_thread": {"user_id": "U123", "channel_id": "D001", "thread_ts": "111.222"},
+ }
+ )
+ slack_cls.return_value.client.assistant_threads_setSuggestedPrompts.assert_not_called()
+
+ def test_context_changed_caches_viewed_channel(self):
+ from products.slack_app.backend.api import _get_assistant_channel_context
+
+ load, resolve, enabled_p, usp, slack = self._patch_resolution(user=self.user)
+ with load, resolve, enabled_p, usp, slack:
+ self._route(
+ {
+ "type": "assistant_thread_context_changed",
+ "assistant_thread": {
+ "user_id": "U123",
+ "channel_id": "D001",
+ "thread_ts": "111.222",
+ "context": {"channel_id": "C999"},
+ },
+ }
+ )
+ assert _get_assistant_channel_context(self.integration.id, "D001", "111.222") == "C999"
+
+ def test_dm_message_starts_agent(self):
+ load, resolve, enabled_p, usp, slack = self._patch_resolution(user=self.user)
+ start = patch("products.slack_app.backend.api._start_mention_workflow", return_value="handled_locally")
+ with load, resolve, enabled_p, usp, slack as slack_cls, start as mock_start:
+ slack_cls.return_value.missing_scopes.return_value = set()
+ self._route(
+ {
+ "type": "message",
+ "channel_type": "im",
+ "channel": "D001",
+ "user": "U123",
+ "text": "fix the funnel bug",
+ "ts": "111.222",
+ }
+ )
+ slack_cls.return_value.client.assistant_threads_setStatus.assert_called_once()
+ mock_start.assert_called_once()
+
+ def test_dm_message_ignores_bot_and_non_im(self):
+ start = patch("products.slack_app.backend.api._start_mention_workflow", return_value="handled_locally")
+ with start as mock_start:
+ self._route(
+ {"type": "message", "channel_type": "im", "bot_id": "B1", "channel": "D001", "text": "hi", "ts": "1"}
+ )
+ self._route(
+ {"type": "message", "channel_type": "channel", "channel": "C1", "user": "U1", "text": "hi", "ts": "1"}
+ )
+ mock_start.assert_not_called()
+
+ def test_dm_message_flag_off_is_dark(self):
+ # Kill-switch: flag off -> no user resolution, no agent start, and no reply at all.
+ load, resolve, enabled_p, usp, slack = self._patch_resolution(user=self.user, enabled=False)
+ start = patch("products.slack_app.backend.api._start_mention_workflow", return_value="handled_locally")
+ with load, resolve as mock_resolve, enabled_p, usp, slack as slack_cls, start as mock_start:
+ self._route(
+ {
+ "type": "message",
+ "channel_type": "im",
+ "channel": "D001",
+ "user": "U123",
+ "text": "fix it",
+ "ts": "1.2",
+ }
+ )
+ mock_resolve.assert_not_called()
+ mock_start.assert_not_called()
+ slack_cls.return_value.client.chat_postMessage.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._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._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