:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(slack_app): resolve user mentions in PostHog Code trigger text (#63495)
Vojta Bartošde4bda8519bf
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex 0e49108ea043..54b41b70db5f 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -127,8 +127,17 @@ def create_posthog_code_task_for_repo_activity(if user_message_ts:safe_react(slack.client, channel, user_message_ts, "eyes")- user_text = re.sub(r"<@[A-Z0-9]+>", "", event.get("text", "")).strip()- title = user_text[:255] if user_text else "Task from Slack"+ from products.slack_app.backend.services.slack_messages import ( # noqa: PLC0415+ decode_slack_event_text,+ labeled_mentions_to_display_names,+ )++ user_text = decode_slack_event_text(slack, integration, event.get("text", ""))+ # Title is shown in PostHog Code's UI (task lists, PR titles) where the+ # labeled `<@U…|name>` form would render as literal noise; the description+ # keeps the labeled form so the agent can echo tokens back as real pings.+ title_text = labeled_mentions_to_display_names(user_text)+ title = title_text[:255] if title_text else "Task from Slack"description = _build_posthog_code_task_description(user_text, thread_messages, user_message_ts)slack_thread_context = SlackThreadContext(@@ -352,7 +361,9 @@ def forward_posthog_code_followup_activity()return True- user_text = re.sub(r"<@[A-Z0-9]+>", "", event_text).strip()+ from products.slack_app.backend.services.slack_messages import decode_slack_event_text # noqa: PLC0415++ user_text = decode_slack_event_text(slack, integration, event_text)if not user_text:return Trueif followup_user_text_prefix:@@ -427,10 +438,12 @@ def _resume_task_with_new_run(user_text_prefix: str | None = None,) -> bool:"""Create a new run on the same task when a follow-up arrives after the previous run completed."""+ from products.slack_app.backend.services.slack_messages import decode_slack_event_text # noqa: PLC0415from products.slack_app.backend.slack_thread import SlackThreadContextfrom products.tasks.backend.temporal.client import execute_task_processing_workflow- user_text = re.sub(r"<@[A-Z0-9]+>", "", event_text).strip()+ integration = slack.integration+ user_text = decode_slack_event_text(slack, integration, event_text)if not user_text:return Trueif user_text_prefix:diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex a8909e68faf6..b13c137632ee 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -5,14 +5,12 @@ import uuidimport asyncioimport hashlibfrom dataclasses import dataclass-from datetime import timedeltafrom typing import Any, Literalfrom urllib.parse import urlparse, urlunparsefrom django.conf import settingsfrom django.core import signingfrom django.core.cache import cache-from django.db.utils import DatabaseErrorfrom django.http import HttpRequest, HttpResponse, JsonResponsefrom django.utils import timezonefrom django.views.decorators.csrf import csrf_exempt@@ -20,7 +18,6 @@ from django.views.decorators.csrf import csrf_exemptimport requestsimport structlogimport posthoganalytics-from slack_sdk.errors import SlackApiErrorfrom slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandlerfrom temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy@@ -53,7 +50,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.models import SlackChannel, SlackThreadTaskMapping, SlackUserProfileCache+from products.slack_app.backend.models import SlackChannel, SlackThreadTaskMappingfrom products.slack_app.backend.services.integration_resolver import (UserResolutionFailure,format_project_candidate_list,@@ -61,6 +58,13 @@ from products.slack_app.backend.services.integration_resolver import (resolve_user_for_workspace,user_resolution_failure_reply,)+from products.slack_app.backend.services.slack_messages import resolve_user_mentions_text+from products.slack_app.backend.services.slack_user_info import (+ get_cached_bot_user_id,+ get_slack_user_info,+ normalize_slack_response,+ persist_slack_user_info,+)from products.slack_app.backend.slack_link_unfurl import handle_posthog_link_unfurllogger = structlog.get_logger(__name__)@@ -104,9 +108,6 @@ POSTHOG_CODE_REQUIRED_SLACK_SCOPES: frozenset[str] = frozenset(# this window should re-onboard — most likely the person forgot how it works.CHANNEL_ONBOARDING_DEDUPE_TTL_SECONDS = 60 * 10CHANNEL_ONBOARDING_DOCS_URL = "https://posthog.com/docs/slack-app"-# Slack assigns a stable bot user id per install; a few hours is enough to pick-# up a reinstall while keeping ``auth.test`` traffic negligible.-SLACK_BOT_USER_ID_CACHE_TTL_SECONDS = 60 * 60 * 6ROUTE_HANDLED_LOCALLY = "handled_locally"ROUTE_PROXIED = "proxied"@@ -115,7 +116,6 @@ ROUTE_NO_INTEGRATION = "no_integration"PICKER_TOKEN_SALT = "posthog_code_repo_picker"PICKER_TOKEN_MAX_AGE_SECONDS = 900-SLACK_USER_PROFILE_TTL = timedelta(hours=1)CHANNEL_APPROVAL_BLOCK_ID_PREFIX = "posthog_code_channel_approval"CHANNEL_APPROVAL_ACTION_APPROVE = "posthog_code_channel_approve"@@ -208,166 +208,6 @@ class RulesCommand:project_team_id: int | None = None-def _format_slack_user_info_payload(- *, email: str | None, display_name: str, real_name: str, is_admin: bool, is_owner: bool-) -> dict[str, Any]:- return {- "user": {- "is_admin": is_admin,- "is_owner": is_owner,- "profile": {- "email": email,- "display_name": display_name,- "real_name": real_name,- },- }- }---def _normalize_slack_response(payload: Any) -> dict[str, Any]:- if isinstance(payload, dict):- return payload-- data = getattr(payload, "data", None)- if isinstance(data, dict):- return data-- return {}---def _get_slack_user_info_from_db(integration: Integration, slack_user_id: str) -> dict[str, Any] | None:- try:- profile = SlackUserProfileCache.objects.filter(- integration_id=integration.id, slack_user_id=slack_user_id- ).first()- except DatabaseError:- logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)- return None- if not profile or not profile.refreshed_at or timezone.now() - profile.refreshed_at >= SLACK_USER_PROFILE_TTL:- return None-- return _format_slack_user_info_payload(- email=profile.email,- display_name=profile.display_name,- real_name=profile.real_name,- is_admin=profile.is_admin,- is_owner=profile.is_owner,- )---def _persist_slack_user_info(integration: Integration, slack_user_id: str, user_info: dict[str, Any]) -> None:- user = user_info.get("user", {})- profile = user.get("profile", {})- try:- SlackUserProfileCache.objects.update_or_create(- integration_id=integration.id,- slack_user_id=slack_user_id,- defaults={- "email": profile.get("email") or None,- "display_name": profile.get("display_name") or "",- "real_name": profile.get("real_name") or "",- "is_admin": bool(user.get("is_admin")),- "is_owner": bool(user.get("is_owner")),- "refreshed_at": timezone.now(),- },- )- except DatabaseError:- logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)---def _get_slack_user_info(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> dict[str, Any]:- cached_db = _get_slack_user_info_from_db(integration, slack_user_id)- if isinstance(cached_db, dict):- return cached_db-- user_info = _normalize_slack_response(slack.client.users_info(user=slack_user_id))- if user_info:- _persist_slack_user_info(integration, slack_user_id, user_info)- return user_info- return {}---def is_slack_workspace_admin(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> bool:- """Whether the Slack user is a workspace admin or owner."""- user_info = _get_slack_user_info(slack, integration, slack_user_id)- slack_user = user_info.get("user", {}) if isinstance(user_info, dict) else {}- return bool(slack_user.get("is_admin") or slack_user.get("is_owner"))---def _get_slack_user_id_by_email_from_db(integration: Integration, normalized_email: str) -> str | None:- try:- profile = SlackUserProfileCache.objects.filter(- integration_id=integration.id,- email__iexact=normalized_email,- ).first()- except DatabaseError:- logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)- return None- if not profile or not profile.refreshed_at or timezone.now() - profile.refreshed_at >= SLACK_USER_PROFILE_TTL:- return None- return profile.slack_user_id---def lookup_slack_user_id_by_email(- slack: SlackIntegration,- integration: Integration,- email: str,-) -> str | None:- """Resolve a Slack user ID from a PostHog user email.-- Uses ``SlackUserProfileCache`` (populated by ``resolve_slack_user`` and prior lookups),- then ``users.lookupByEmail``.- """- normalized_email = email.strip().lower()- if not normalized_email:- return None-- slack_user_id = _get_slack_user_id_by_email_from_db(integration, normalized_email)- if slack_user_id:- return slack_user_id-- try:- user_info = _normalize_slack_response(slack.client.users_lookupByEmail(email=email))- except SlackApiError as exc:- error_code = exc.response.get("error") if exc.response else None- if error_code != "users_not_found":- logger.warning(- "slack_user_id_by_email_lookup_failed",- integration_id=integration.id,- email=email,- error=error_code,- )- return None-- if not user_info.get("ok"):- return None-- user = user_info.get("user")- if not isinstance(user, dict) or not user.get("id"):- return None-- slack_user_id = str(user["id"])- _persist_slack_user_info(integration, slack_user_id, user_info)- _purge_stale_email_rows(integration, normalized_email, slack_user_id)- return slack_user_id---def _purge_stale_email_rows(integration: Integration, normalized_email: str, keep_slack_user_id: str) -> None:- """Drop rows that share an email with the authoritative Slack user ID we just resolved.-- Without this, an orphan row (same email, older Slack user ID) can outrank the fresh one- in ``_get_slack_user_id_by_email_from_db`` and trigger a fresh ``users.lookupByEmail`` call- on every request.- """- try:- SlackUserProfileCache.objects.filter(- integration_id=integration.id,- email__iexact=normalized_email,- ).exclude(slack_user_id=keep_slack_user_id).delete()- except DatabaseError:- logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)--QUOTA_EXHAUSTED_MESSAGE = ("Your team has used its monthly PostHog AI credits. ""Top up at https://us.posthog.com/organization/billing to continue."@@ -443,12 +283,12 @@ def resolve_slack_user() -> SlackUserContext | None:"""Resolve a Slack user to a PostHog user. Posts an ephemeral error message and returns None on failure (unless post_feedback is False)."""try:- slack_user_info = _get_slack_user_info(slack, integration, slack_user_id)+ slack_user_info = get_slack_user_info(slack, integration, slack_user_id)slack_email = slack_user_info.get("user", {}).get("profile", {}).get("email")if not slack_email:- fresh_user_info = _normalize_slack_response(slack.client.users_info(user=slack_user_id))+ fresh_user_info = normalize_slack_response(slack.client.users_info(user=slack_user_id))if fresh_user_info:- _persist_slack_user_info(integration, slack_user_id, fresh_user_info)+ persist_slack_user_info(integration, slack_user_id, fresh_user_info)slack_email = fresh_user_info.get("user", {}).get("profile", {}).get("email")if not slack_email:@@ -902,7 +742,7 @@ def _post_repo_picker_message()if workflow_id:- response_data = _normalize_slack_response(response)+ response_data = normalize_slack_response(response)message_ts = response_data.get("ts") if isinstance(response_data.get("ts"), str) else None_set_pending_repo_picker(integration_id=integration.id,@@ -1032,19 +872,13 @@ def _collect_thread_messages(def resolve_user(uid: str) -> str:if uid not in user_cache:try:- user_info = _get_slack_user_info(slack, integration, uid)+ user_info = get_slack_user_info(slack, integration, uid)profile = user_info.get("user", {}).get("profile", {})user_cache[uid] = profile.get("display_name") or profile.get("real_name") or "Unknown"except Exception:user_cache[uid] = "Unknown"return user_cache[uid]- def replace_user_mentions(text: str) -> str:- def replace_mention(match: re.Match) -> str:- return f"@{resolve_user(match.group(1))}"-- return re.sub(r"<@([A-Z0-9]+)>", replace_mention, text)-messages = []for index, msg in enumerate(raw_messages):# Skip our own bot's posts to avoid loops where the agent ingests its own replies.@@ -1063,7 +897,7 @@ def _collect_thread_messages(else:username = "Unknown"- text = replace_user_mentions(_extract_message_text(msg))+ text = resolve_user_mentions_text(slack, integration, _extract_message_text(msg))# `ts` lets downstream callers distinguish the initiator message from surrounding thread# context, since `app_mention` events surface only the initiator's ts.messages.append({"user": username, "text": text, "ts": msg.get("ts") or ""})@@ -1547,12 +1381,12 @@ def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str)"""slack_client = SlackIntegration(probe_integration)try:- user_info = _get_slack_user_info(slack_client, probe_integration, slack_user_id)+ user_info = get_slack_user_info(slack_client, probe_integration, slack_user_id)slack_email = user_info.get("user", {}).get("profile", {}).get("email")if not slack_email:- fresh = _normalize_slack_response(slack_client.client.users_info(user=slack_user_id))+ fresh = normalize_slack_response(slack_client.client.users_info(user=slack_user_id))if fresh:- _persist_slack_user_info(probe_integration, slack_user_id, fresh)+ persist_slack_user_info(probe_integration, slack_user_id, fresh)slack_email = fresh.get("user", {}).get("profile", {}).get("email")return slack_email or Noneexcept Exception:@@ -2333,7 +2167,7 @@ def _route_member_joined_channel(integration = workspace_result.candidates[0]slack = SlackIntegration(integration)- bot_user_id = _get_cached_bot_user_id(slack, integration)+ bot_user_id = get_cached_bot_user_id(slack, integration)if bot_user_id is None or joined_user != bot_user_id:# We only care about our own bot joining a channel. Every other join# (humans, third-party bots) is ignored silently — Slack fires this@@ -2357,31 +2191,6 @@ def _route_member_joined_channel(return ROUTE_HANDLED_LOCALLY-def _bot_user_id_cache_key(integration_id: int) -> str:- return f"slack_app:bot_user_id:v1:{integration_id}"---def _get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) -> str | None:- cache_key = _bot_user_id_cache_key(integration.id)- cached = cache.get(cache_key)- if isinstance(cached, str) and cached:- return cached- try:- response = slack.client.auth_test()- bot_user_id = response.get("user_id")- except Exception:- logger.warning(- "slack_app_bot_user_id_lookup_failed",- integration_id=integration.id,- exc_info=True,- )- return None- if not isinstance(bot_user_id, str) or not bot_user_id:- return None- cache.set(cache_key, bot_user_id, timeout=SLACK_BOT_USER_ID_CACHE_TTL_SECONDS)- return bot_user_id--def _channel_onboarding_cache_key(slack_team_id: str, channel_id: str) -> str:return f"slack_app:channel_onboarded:v1:{slack_team_id}:{channel_id}"diff --git a/products/slack_app/backend/migrations/0007_slackuserprofilecache_is_bot.py b/products/slack_app/backend/migrations/0007_slackuserprofilecache_is_bot.pynew file mode 100644index 000000000000..28dd7a1822d4--- /dev/null+++ b/products/slack_app/backend/migrations/0007_slackuserprofilecache_is_bot.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-06-15 13:09++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("slack_app", "0006_slackthreadtaskmapping_latest_actor_slack_user_id"),+ ]++ operations = [+ migrations.AddField(+ model_name="slackuserprofilecache",+ name="is_bot",+ field=models.BooleanField(db_default=False, default=False),+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex 6fb7332ded81..f0f2c25fe322 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_slackthreadtaskmapping_latest_actor_slack_user_id+0007_slackuserprofilecache_is_botdiff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex 75d6a5a950c4..1d718ac93e07 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -52,6 +52,7 @@ class SlackUserProfileCache(UUIDModel):real_name = models.CharField(max_length=255, blank=True, default="")is_admin = models.BooleanField(default=False, db_default=False)is_owner = models.BooleanField(default=False, db_default=False)+ is_bot = models.BooleanField(default=False, db_default=False)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)# Null is treated as stale (rows predating this field).diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pyindex 1934827d19fe..416602cdd798 100644--- a/products/slack_app/backend/services/commands.py+++ b/products/slack_app/backend/services/commands.py@@ -10,7 +10,7 @@ if TYPE_CHECKING:def _handle_help(slack: SlackIntegration, integration: Integration, channel: str, thread_ts: str, slack_user_id: str) -> None:- from products.slack_app.backend.api import is_slack_workspace_admin+ from products.slack_app.backend.services.slack_user_info import is_slack_workspace_adminlines = ["*Available commands:*\n",@@ -298,8 +298,8 @@ def _handle_project_set_workspace("""from posthog.models.user import User- from products.slack_app.backend.api import is_slack_workspace_adminfrom products.slack_app.backend.models import SlackSettings+ from products.slack_app.backend.services.slack_user_info import is_slack_workspace_adminif not is_slack_workspace_admin(slack, integration, slack_user_id):slack.client.chat_postEphemeral(diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex 1dc5d0463389..865e2405f417 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -218,7 +218,7 @@ def resolve_user_for_workspace(and the membership query."""# The user resolver lives in api.py alongside the Slack-API helpers it- # depends on (``_get_slack_user_info`` etc). Inline-imported to break the+ # depends on (``get_slack_user_info`` etc). Inline-imported to break the# cycle until those helpers are factored out into a shared module.from products.slack_app.backend.api import get_slack_email_for_user, resolve_posthog_user_from_eventdiff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pynew file mode 100644index 000000000000..42cb4017c386--- /dev/null+++ b/products/slack_app/backend/services/slack_messages.py@@ -0,0 +1,100 @@+"""Slack message text processing helpers.++The bot strips its own self-mention and enriches every other `<@U…>` reference+with a `|displayname` label before handing the text to the agent. Slack accepts+the labeled form `<@U_ID|displayname>` on both inbound and outbound messages —+the agent gets a human-readable name to reason about *and* a wire-format token+it can echo verbatim to ping the user back, so no outbound transformation is+needed.++Kept separate from the HTTP-facing code in `api.py` so the text logic stays+testable in isolation.+"""++import re++from posthog.models.integration import Integration, SlackIntegration++from products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id, get_slack_user_info+++def resolve_user_mentions_text(+ slack: SlackIntegration,+ integration: Integration,+ text: str,+ *,+ strip_bot_user_id: str | None = None,+) -> str:+ """Label human `<@U…>` mentions with display names; drop every bot mention.++ Slack delivers events with bare `<@U_ID>` references — opaque to an LLM,+ and easily paraphrased away into plain prose. For real users we enrich to+ Slack's labeled form `<@U_ID|displayname>`: the agent gets both a+ human-readable handle to reason about *and* the exact wire-format token it+ can echo verbatim to ping the user back. Slack accepts the labeled form on+ the way out, so no outbound transformation is needed.++ Bot users (our own, plus any other workspace bot — Grafana, GitHub, etc.)+ are stripped entirely. There's nothing useful for the agent to do with a+ bot mention, and echoing it would re-ping the bot. The `is_bot` flag comes+ from `users.info` via the cached profile; `strip_bot_user_id` is a fast+ path for the trigger's own self-mention that avoids the lookup.++ Wire format alone can't distinguish a bot user ID from a human's — both+ are `U…`-prefixed. The flag is the only authoritative signal.+ """+ cache: dict[str, tuple[str, bool]] = {}++ def resolve_user(uid: str) -> tuple[str, bool]:+ if uid not in cache:+ try:+ user_info = get_slack_user_info(slack, integration, uid)+ user = user_info.get("user", {})+ profile = user.get("profile", {})+ display = profile.get("display_name") or profile.get("real_name") or "Unknown"+ cache[uid] = (display, bool(user.get("is_bot")))+ except Exception:+ # Lookup failed — degrade to a labeled mention so a ping still+ # works; treating an unknown user as a bot would silently drop+ # a real user's mention, which is the bug this module exists+ # to prevent.+ cache[uid] = ("Unknown", False)+ return cache[uid]++ def replace_mention(match: re.Match) -> str:+ uid = match.group(1)+ if strip_bot_user_id and uid == strip_bot_user_id:+ return ""+ display, is_bot = resolve_user(uid)+ if is_bot:+ return ""+ return f"<@{uid}|{display}>"++ resolved = re.sub(r"<@([A-Z0-9]+)>", replace_mention, text)+ # Tidy gaps left where bot mentions were removed.+ resolved = re.sub(r"[ \t]{2,}", " ", resolved).strip()+ return resolved+++def decode_slack_event_text(slack: SlackIntegration, integration: Integration, text: str) -> str:+ """Strip the bot's own self-mention from a Slack event and label the rest for the agent.++ Trigger sites all want the same thing: drop the bot's self-ping (it's just+ the activation, no information for the agent) and enrich every other+ `<@U…>` reference with a `|displayname` label so the agent can echo the+ token verbatim to ping the user back. Centralised here so a new trigger+ handler can't drift back into the original mention-eating bug.+ """+ bot_user_id = get_cached_bot_user_id(slack, integration)+ return resolve_user_mentions_text(slack, integration, text, strip_bot_user_id=bot_user_id).strip()+++def labeled_mentions_to_display_names(text: str) -> str:+ """Render labeled `<@U…|name>` mentions as plain `@name` for human-facing display.++ The labeled wire format is what we feed the agent so its replies round-trip as+ real Slack pings, but in human-facing contexts — task titles, PR titles, anywhere+ a UI surfaces the string without Slack rendering — the angle-bracket form shows+ up as literal noise. This unwraps it back to the readable form.+ """+ return re.sub(r"<@[A-Z0-9]+\|([^>]+)>", r"@\1", text)diff --git a/products/slack_app/backend/services/slack_user_info.py b/products/slack_app/backend/services/slack_user_info.pynew file mode 100644index 000000000000..3aee10faa31e--- /dev/null+++ b/products/slack_app/backend/services/slack_user_info.py@@ -0,0 +1,230 @@+"""Slack user/profile lookup with DB caching.++`users.info` and `users.lookupByEmail` are the only sources of truth for+display names, email-to-user-id mappings, and the `is_bot` flag — and both+are rate-limited. Every lookup goes through `SlackUserProfileCache` in+Postgres so repeated requests don't burn the Slack API quota.++The bot's own user id (from `auth_test()`) is cached separately in Redis;+it changes only when a workspace reinstalls the app, so a 6-hour TTL is+comfortable.++These helpers used to live in `api.py` alongside the HTTP-facing code,+which forced every service-layer caller (`slack_messages.py`,+`integration_resolver.py`) into a deferred import to dodge the circular+dependency. Living in `services/` lets all of them import normally and+keeps `api.py` focused on routes.+"""++from datetime import timedelta+from typing import Any++from django.core.cache import cache+from django.db.utils import DatabaseError+from django.utils import timezone++import structlog+from slack_sdk.errors import SlackApiError++from posthog.models.integration import Integration, SlackIntegration++from products.slack_app.backend.models import SlackUserProfileCache++logger = structlog.get_logger(__name__)++SLACK_USER_PROFILE_TTL = timedelta(hours=1)+SLACK_BOT_USER_ID_CACHE_TTL_SECONDS = 60 * 60 * 6+++def _format_slack_user_info_payload(+ *,+ email: str | None,+ display_name: str,+ real_name: str,+ is_admin: bool,+ is_owner: bool,+ is_bot: bool,+) -> dict[str, Any]:+ return {+ "user": {+ "is_admin": is_admin,+ "is_owner": is_owner,+ "is_bot": is_bot,+ "profile": {+ "email": email,+ "display_name": display_name,+ "real_name": real_name,+ },+ }+ }+++def normalize_slack_response(payload: Any) -> dict[str, Any]:+ if isinstance(payload, dict):+ return payload++ data = getattr(payload, "data", None)+ if isinstance(data, dict):+ return data++ return {}+++def _get_slack_user_info_from_db(integration: Integration, slack_user_id: str) -> dict[str, Any] | None:+ try:+ profile = SlackUserProfileCache.objects.filter(+ integration_id=integration.id, slack_user_id=slack_user_id+ ).first()+ except DatabaseError:+ logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)+ return None+ if not profile or not profile.refreshed_at or timezone.now() - profile.refreshed_at >= SLACK_USER_PROFILE_TTL:+ return None++ return _format_slack_user_info_payload(+ email=profile.email,+ display_name=profile.display_name,+ real_name=profile.real_name,+ is_admin=profile.is_admin,+ is_owner=profile.is_owner,+ is_bot=profile.is_bot,+ )+++def persist_slack_user_info(integration: Integration, slack_user_id: str, user_info: dict[str, Any]) -> None:+ user = user_info.get("user", {})+ profile = user.get("profile", {})+ try:+ SlackUserProfileCache.objects.update_or_create(+ integration_id=integration.id,+ slack_user_id=slack_user_id,+ defaults={+ "email": profile.get("email") or None,+ "display_name": profile.get("display_name") or "",+ "real_name": profile.get("real_name") or "",+ "is_admin": bool(user.get("is_admin")),+ "is_owner": bool(user.get("is_owner")),+ "is_bot": bool(user.get("is_bot")),+ "refreshed_at": timezone.now(),+ },+ )+ except DatabaseError:+ logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)+++def get_slack_user_info(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> dict[str, Any]:+ cached_db = _get_slack_user_info_from_db(integration, slack_user_id)+ if isinstance(cached_db, dict):+ return cached_db++ user_info = normalize_slack_response(slack.client.users_info(user=slack_user_id))+ if user_info:+ persist_slack_user_info(integration, slack_user_id, user_info)+ return user_info+ return {}+++def is_slack_workspace_admin(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> bool:+ """Whether the Slack user is a workspace admin or owner."""+ user_info = get_slack_user_info(slack, integration, slack_user_id)+ slack_user = user_info.get("user", {}) if isinstance(user_info, dict) else {}+ return bool(slack_user.get("is_admin") or slack_user.get("is_owner"))+++def _get_slack_user_id_by_email_from_db(integration: Integration, normalized_email: str) -> str | None:+ try:+ profile = SlackUserProfileCache.objects.filter(+ integration_id=integration.id,+ email__iexact=normalized_email,+ ).first()+ except DatabaseError:+ logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)+ return None+ if not profile or not profile.refreshed_at or timezone.now() - profile.refreshed_at >= SLACK_USER_PROFILE_TTL:+ return None+ return profile.slack_user_id+++def lookup_slack_user_id_by_email(+ slack: SlackIntegration,+ integration: Integration,+ email: str,+) -> str | None:+ """Resolve a Slack user ID from a PostHog user email.++ Uses ``SlackUserProfileCache`` (populated by ``resolve_slack_user`` and prior lookups),+ then ``users.lookupByEmail``.+ """+ normalized_email = email.strip().lower()+ if not normalized_email:+ return None++ slack_user_id = _get_slack_user_id_by_email_from_db(integration, normalized_email)+ if slack_user_id:+ return slack_user_id++ try:+ user_info = normalize_slack_response(slack.client.users_lookupByEmail(email=email))+ except SlackApiError as exc:+ error_code = exc.response.get("error") if exc.response else None+ if error_code != "users_not_found":+ logger.warning(+ "slack_user_id_by_email_lookup_failed",+ integration_id=integration.id,+ email=email,+ error=error_code,+ )+ return None++ if not user_info.get("ok"):+ return None++ user = user_info.get("user")+ if not isinstance(user, dict) or not user.get("id"):+ return None++ slack_user_id = str(user["id"])+ persist_slack_user_info(integration, slack_user_id, user_info)+ _purge_stale_email_rows(integration, normalized_email, slack_user_id)+ return slack_user_id+++def _purge_stale_email_rows(integration: Integration, normalized_email: str, keep_slack_user_id: str) -> None:+ """Drop rows that share an email with the authoritative Slack user ID we just resolved.++ Without this, an orphan row (same email, older Slack user ID) can outrank the fresh one+ in ``_get_slack_user_id_by_email_from_db`` and trigger a fresh ``users.lookupByEmail`` call+ on every request.+ """+ try:+ SlackUserProfileCache.objects.filter(+ integration_id=integration.id,+ email__iexact=normalized_email,+ ).exclude(slack_user_id=keep_slack_user_id).delete()+ except DatabaseError:+ logger.warning("posthog_code_slack_user_cache_db_unavailable", integration_id=integration.id)+++def bot_user_id_cache_key(integration_id: int) -> str:+ return f"slack_app:bot_user_id:v1:{integration_id}"+++def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) -> str | None:+ cache_key = bot_user_id_cache_key(integration.id)+ cached = cache.get(cache_key)+ if isinstance(cached, str) and cached:+ return cached+ try:+ response = slack.client.auth_test()+ bot_user_id = response.get("user_id")+ except Exception:+ logger.warning(+ "slack_app_bot_user_id_lookup_failed",+ integration_id=integration.id,+ exc_info=True,+ )+ return None+ if not isinstance(bot_user_id, str) or not bot_user_id:+ return None+ cache.set(cache_key, bot_user_id, timeout=SLACK_BOT_USER_ID_CACHE_TTL_SECONDS)+ return bot_user_iddiff --git a/products/slack_app/backend/tests/test_channel_approval_interactivity.py b/products/slack_app/backend/tests/test_channel_approval_interactivity.pyindex a10d2b945af1..2a8c8030af54 100644--- a/products/slack_app/backend/tests/test_channel_approval_interactivity.py+++ b/products/slack_app/backend/tests/test_channel_approval_interactivity.py@@ -115,7 +115,7 @@ class TestChannelApprovalInteractivity(_ChannelApprovalTestBase):def _stub_slack_user_email(self, email: str) -> Any:return patch(- "products.slack_app.backend.api._get_slack_user_info",+ "products.slack_app.backend.api.get_slack_user_info",return_value={"user": {"profile": {"email": email}}},)@@ -170,7 +170,7 @@ class TestChannelApprovalInteractivity(_ChannelApprovalTestBase):self._set_signing_secret(mock_slack_cls)with patch(- "products.slack_app.backend.api._get_slack_user_info",+ "products.slack_app.backend.api.get_slack_user_info",return_value={"user": {"profile": {}}},):response = self._post_interactivity(self._approve_payload("U_NO_EMAIL"))diff --git a/products/slack_app/backend/tests/test_channel_onboarding_routing.py b/products/slack_app/backend/tests/test_channel_onboarding_routing.pyindex 80b8472674c1..258219b750ba 100644--- a/products/slack_app/backend/tests/test_channel_onboarding_routing.py+++ b/products/slack_app/backend/tests/test_channel_onboarding_routing.py@@ -13,10 +13,10 @@ from products.slack_app.backend.api import (POSTHOG_CODE_REQUIRED_SLACK_SCOPES,ROUTE_HANDLED_LOCALLY,ROUTE_NO_INTEGRATION,- _bot_user_id_cache_key,_channel_onboarding_cache_key,route_posthog_code_event_to_relevant_region,)+from products.slack_app.backend.services.slack_user_info import bot_user_id_cache_key@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")@@ -165,4 +165,4 @@ class TestMemberJoinedChannelRouting(TestCase):route_posthog_code_event_to_relevant_region(self._request(), self._event(channel="C_OTHER"), self.SLACK_TEAM_ID)assert instance.client.auth_test.call_count == 1- assert cache.get(_bot_user_id_cache_key(self.integration.id)) == self.BOT_USER_ID+ assert cache.get(bot_user_id_cache_key(self.integration.id)) == self.BOT_USER_IDdiff --git a/products/slack_app/backend/tests/test_collect_thread_messages.py b/products/slack_app/backend/tests/test_collect_thread_messages.pyindex 482f2feeea2c..b0dc1c0a59a6 100644--- a/products/slack_app/backend/tests/test_collect_thread_messages.py+++ b/products/slack_app/backend/tests/test_collect_thread_messages.py@@ -9,6 +9,11 @@ from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom products.slack_app.backend.api import _collect_thread_messages, _extract_message_text, _flatten_block_text+from products.slack_app.backend.services.slack_messages import (+ decode_slack_event_text,+ labeled_mentions_to_display_names,+ resolve_user_mentions_text,+)class TestFlattenBlockText:@@ -162,10 +167,144 @@ class TestExtractMessageText:assert _extract_message_text(msg) == expected-@patch("products.slack_app.backend.api._get_slack_user_info")+@patch("products.slack_app.backend.services.slack_messages.get_slack_user_info")+class TestResolveUserMentionsText:+ def setup_method(self) -> None:+ self.slack = MagicMock(spec=SlackIntegration)+ self.integration = MagicMock(spec=Integration)++ def _profiles(self, mapping: dict[str, str]):+ def _lookup(_slack, _integration, uid):+ return {"user": {"profile": {"display_name": mapping.get(uid, "")}}}++ return _lookup++ def test_strips_bot_mention_keeps_and_labels_user_mention(self, mock_get_user_info):+ mock_get_user_info.side_effect = self._profiles({"UCLEO": "cleo"})++ result = resolve_user_mentions_text(+ self.slack,+ self.integration,+ "<@UBOT> can you do what <@UCLEO> asked",+ strip_bot_user_id="UBOT",+ )++ assert result == "can you do what <@UCLEO|cleo> asked"++ def test_keeps_user_mention_when_no_bot_id_given(self, mock_get_user_info):+ mock_get_user_info.side_effect = self._profiles({"UCLEO": "cleo"})++ result = resolve_user_mentions_text(self.slack, self.integration, "ping <@UCLEO>")++ assert result == "ping <@UCLEO|cleo>"++ def test_unresolvable_user_becomes_unknown(self, mock_get_user_info):+ mock_get_user_info.side_effect = RuntimeError("slack down")++ result = resolve_user_mentions_text(self.slack, self.integration, "hey <@UCLEO>")++ assert result == "hey <@UCLEO|Unknown>"++ def test_no_mentions_passes_through_unchanged(self, mock_get_user_info):+ result = resolve_user_mentions_text(self.slack, self.integration, "just some text", strip_bot_user_id="UBOT")++ assert result == "just some text"+ mock_get_user_info.assert_not_called()++ def test_collapses_gap_left_by_removed_bot_mention(self, mock_get_user_info):+ result = resolve_user_mentions_text(+ self.slack, self.integration, "do <@UBOT> the thing", strip_bot_user_id="UBOT"+ )++ assert result == "do the thing"++ def test_strips_bot_user_mentions_via_is_bot_flag(self, mock_get_user_info):+ # A workspace bot (e.g. Grafana) is identified by ``users.info``'s ``is_bot``+ # flag, not by wire-format syntax — bot user IDs are ``U…``-prefixed just+ # like humans. The mention should be dropped, not labeled, so the agent+ # doesn't echo it and ping the bot back.+ def lookup(_slack, _integration, uid):+ if uid == "UGRAFANA":+ return {"user": {"is_bot": True, "profile": {"display_name": "grafana"}}}+ return {"user": {"is_bot": False, "profile": {"display_name": "cleo"}}}++ mock_get_user_info.side_effect = lookup++ result = resolve_user_mentions_text(self.slack, self.integration, "<@UGRAFANA> is paging <@UCLEO> again")++ assert result == "is paging <@UCLEO|cleo> again"++ def test_failed_lookup_falls_back_to_labeled_unknown_not_stripped(self, mock_get_user_info):+ # An exception during ``users.info`` lookup must not be mistaken for+ # ``is_bot=True``: silently dropping the mention would re-introduce the+ # original bug where real users get erased from the agent's context.+ mock_get_user_info.side_effect = RuntimeError("slack down")++ result = resolve_user_mentions_text(self.slack, self.integration, "ping <@UCLEO>")++ assert result == "ping <@UCLEO|Unknown>"+++class TestDecodeSlackEventText:+ """The wrapper at the 3 trigger sites — look up the bot, label the rest, strip."""++ def setup_method(self) -> None:+ self.slack = MagicMock(spec=SlackIntegration)+ self.integration = MagicMock(spec=Integration)++ @patch("products.slack_app.backend.services.slack_messages.get_cached_bot_user_id")+ @patch("products.slack_app.backend.services.slack_messages.get_slack_user_info")+ def test_strips_bot_self_mention_when_lookup_succeeds(self, mock_get_user_info, mock_get_bot_user_id):+ mock_get_bot_user_id.return_value = "UBOT"+ mock_get_user_info.return_value = {"user": {"profile": {"display_name": "cleo"}}}++ result = decode_slack_event_text(self.slack, self.integration, "<@UBOT> ping <@UCLEO> ")++ assert result == "ping <@UCLEO|cleo>"++ @patch("products.slack_app.backend.services.slack_messages.get_cached_bot_user_id")+ @patch("products.slack_app.backend.services.slack_messages.get_slack_user_info")+ def test_leaves_bot_mention_labeled_when_lookup_returns_none(self, mock_get_user_info, mock_get_bot_user_id):+ # auth_test() failure → no bot user id → the bot's own mention falls+ # through the strip_bot_user_id fast path, but is_bot stripping still+ # catches it once the lookup returns is_bot=True.+ mock_get_bot_user_id.return_value = None+ mock_get_user_info.return_value = {"user": {"is_bot": True, "profile": {"display_name": "bot"}}}++ result = decode_slack_event_text(self.slack, self.integration, "<@UBOT> ping")++ assert result == "ping"++ @patch("products.slack_app.backend.services.slack_messages.get_cached_bot_user_id")+ @patch("products.slack_app.backend.services.slack_messages.get_slack_user_info")+ def test_strips_surrounding_whitespace_from_result(self, mock_get_user_info, mock_get_bot_user_id):+ mock_get_bot_user_id.return_value = "UBOT"+ mock_get_user_info.return_value = {"user": {"profile": {"display_name": ""}}}++ result = decode_slack_event_text(self.slack, self.integration, " <@UBOT> hello world ")++ assert result == "hello world"+++class TestLabeledMentionsToDisplayNames:+ def test_unwraps_labeled_mention(self):+ assert labeled_mentions_to_display_names("ping <@UCLEO|cleo> please") == "ping @cleo please"++ def test_unwraps_multiple_labeled_mentions(self):+ assert labeled_mentions_to_display_names("<@UA|andy> and <@UB|bob>") == "@andy and @bob"++ def test_leaves_bare_id_mention_alone(self):+ # Bare `<@U…>` (no label) is something we never emit on the agent path,+ # but if it shows up we leave it as-is rather than dropping the user id.+ assert labeled_mentions_to_display_names("hi <@UCLEO>") == "hi <@UCLEO>"++ def test_no_op_on_plain_text(self):+ assert labeled_mentions_to_display_names("just some text") == "just some text"++class TestCollectThreadMessages:@pytest.fixture(autouse=True)- def setup(self, db):+ def setup(self, db, monkeypatch):self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")self.integration = Integration.objects.create(@@ -176,11 +315,20 @@ class TestCollectThreadMessages:)self.slack = MagicMock(spec=SlackIntegration)self.slack.client = MagicMock()+ # `_collect_thread_messages` looks up authors via api.py's binding and+ # message-text mentions via slack_messages.py's resolver — each module+ # imported `get_slack_user_info` at load time, so both bindings have to+ # point at the same mock for a single test to see consistent behaviour.+ self.mock_get_user_info = MagicMock()+ monkeypatch.setattr("products.slack_app.backend.api.get_slack_user_info", self.mock_get_user_info)+ monkeypatch.setattr(+ "products.slack_app.backend.services.slack_messages.get_slack_user_info", self.mock_get_user_info+ )def _set_thread(self, messages: list[dict]) -> None:self.slack.client.conversations_replies.return_value = {"messages": messages}- def test_alert_blocks_only_message_is_included(self, mock_get_user_info):+ def test_alert_blocks_only_message_is_included(self):# PostHog alert: substantive content lives only in blocks, no text field.self._set_thread([@@ -205,7 +353,7 @@ class TestCollectThreadMessages:{"user": "U_ANDY", "text": "<@UBOT> was that really an anomaly?"},])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id="B_OUR_CODE_BOT")@@ -216,7 +364,7 @@ class TestCollectThreadMessages:assert result[1]["user"] == "andy"assert "was that really an anomaly?" in result[1]["text"]- def test_skips_our_own_bot_reply_messages(self, mock_get_user_info):+ def test_skips_our_own_bot_reply_messages(self):# Our own bot replies (e.g. "Working on it...") must be filtered so the agent# doesn't ingest its own status updates as context on a re-mention.self._set_thread(@@ -226,14 +374,14 @@ class TestCollectThreadMessages:{"user": "U_ANDY", "text": "thanks", "ts": "3.000"},])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id="B_OUR_CODE_BOT")assert [m["ts"] for m in result] == ["1.000", "3.000"]assert all(m["user"] == "andy" for m in result)- def test_keeps_thread_root_even_when_bot_id_matches_our_own(self, mock_get_user_info):+ def test_keeps_thread_root_even_when_bot_id_matches_our_own(self):# Regression: in workspaces where the alerting Slack app and the `@PostHog` code# app share an installation identity, the alert that opened the thread has the same# `bot_id` as `our_bot_id`. We must still include it — the agent only posts as a@@ -262,7 +410,7 @@ class TestCollectThreadMessages:{"user": "U_ANDY", "text": "<@UBOT> lets investigate this one", "ts": "2.000"},])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id="B_OUR_CODE_BOT")@@ -271,7 +419,7 @@ class TestCollectThreadMessages:assert "Alert 'Headline anomaly: Trial activated'" in result[0]["text"]assert result[1]["user"] == "andy"- def test_other_bot_uses_bot_profile_name(self, mock_get_user_info):+ def test_other_bot_uses_bot_profile_name(self):self._set_thread([{@@ -286,37 +434,37 @@ class TestCollectThreadMessages:result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id="B_OUR_CODE_BOT")assert result == [{"user": "Grafana", "text": "alert: latency p95 above 2s", "ts": "1.000"}]- mock_get_user_info.assert_not_called()+ self.mock_get_user_info.assert_not_called()- def test_bot_without_profile_falls_back_to_username_field(self, mock_get_user_info):+ def test_bot_without_profile_falls_back_to_username_field(self):self._set_thread([{"bot_id": "B_HOOK", "username": "PostHog Webhook", "text": "ping", "ts": "2.000"}])result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id=None)assert result == [{"user": "PostHog Webhook", "text": "ping", "ts": "2.000"}]- def test_includes_ts_for_initiator_disambiguation(self, mock_get_user_info):+ def test_includes_ts_for_initiator_disambiguation(self):self._set_thread([{"user": "U_ANDY", "text": "context", "ts": "1.000"},{"user": "U_ANDY", "text": "@PostHog fix this", "ts": "2.000"},])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id="B_OUR")assert [m["ts"] for m in result] == ["1.000", "2.000"]- def test_preserves_user_mention_replacement(self, mock_get_user_info):+ def test_preserves_user_mention_replacement(self):self._set_thread([{"user": "U_ANDY", "text": "hey <@UBOT> can you help"}])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "posthog-code"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "posthog-code"}}}result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id=None)- assert result[0]["text"] == "hey @posthog-code can you help"+ assert result[0]["text"] == "hey <@UBOT|posthog-code> can you help"- def test_includes_thread_root_when_our_bot_id_is_none(self, mock_get_user_info):+ def test_includes_thread_root_when_our_bot_id_is_none(self):# Defensive: if auth_test() somehow returned no bot_id we still process the thread.self._set_thread([@@ -324,16 +472,16 @@ class TestCollectThreadMessages:{"user": "U_ANDY", "text": "follow up"},])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}result = _collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id=None)assert [m["user"] for m in result] == ["PostHog", "andy"]- def test_registers_rate_limit_retry_handler(self, mock_get_user_info):+ def test_registers_rate_limit_retry_handler(self):self.slack.client.retry_handlers = []self._set_thread([{"user": "U_ANDY", "text": "hi"}])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}_collect_thread_messages(self.slack, self.integration, "C001", "1.234", our_bot_id=None)@@ -354,7 +502,7 @@ class TestCollectThreadMessages:{"user": "U_ANDY", "text": "still here"},])- mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}+ self.mock_get_user_info.return_value = {"user": {"profile": {"display_name": "andy"}}}with patch("products.slack_app.backend.api._flatten_block_text",diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex 749fbf4c84fb..c5fb909577f0 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -154,6 +154,16 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):self.team = Team.objects.create(organization=self.org, name="TestTeam")self.user = User.objects.create(email="[email protected]", distinct_id="user-1")self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})+ # The mock SlackIntegration doesn't stub `auth_test`, so `get_cached_bot_user_id`+ # would return None and the bot-mention fast-path strip wouldn't kick in. Force+ # it to return the literal "BOT" so `<@BOT>` in test inputs is stripped from+ # the agent prompt as it would be in production.+ bot_id_patcher = patch(+ "products.slack_app.backend.services.slack_messages.get_cached_bot_user_id",+ return_value="BOT",+ )+ bot_id_patcher.start()+ self.addCleanup(bot_id_patcher.stop)@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")@@ -544,6 +554,15 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):self.team = Team.objects.create(organization=self.org, name="TestTeam")self.user = User.objects.create(email="[email protected]")self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})+ # See note in TestCreatePostHogCodeTaskForRepoActivity.setUp: force the+ # bot-id lookup so `<@BOT>` mentions in test inputs strip the way they+ # do in production.+ bot_id_patcher = patch(+ "products.slack_app.backend.services.slack_messages.get_cached_bot_user_id",+ return_value="BOT",+ )+ bot_id_patcher.start()+ self.addCleanup(bot_id_patcher.stop)self.task = self.Task.objects.create(team=self.team,title="Test task",diff --git a/products/slack_app/backend/tests/test_project_set_workspace.py b/products/slack_app/backend/tests/test_project_set_workspace.pyindex 5dc4093da602..922e2635ea11 100644--- a/products/slack_app/backend/tests/test_project_set_workspace.py+++ b/products/slack_app/backend/tests/test_project_set_workspace.py@@ -44,7 +44,7 @@ class TestHandleProjectSetWorkspace:workspace_candidates=[self.integration],)- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_admin_sets_workspace_default(self, mock_info):mock_info.return_value = _slack_user_info(is_admin=True)@@ -54,7 +54,7 @@ class TestHandleProjectSetWorkspace:assert row.default_integration_id == self.integration.idself.slack.client.chat_postEphemeral.assert_called_once()- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_owner_sets_workspace_default(self, mock_info):mock_info.return_value = _slack_user_info(is_owner=True)@@ -62,7 +62,7 @@ class TestHandleProjectSetWorkspace:assert SlackSettings.objects.filter(slack_workspace_id="T_WS", slack_user_id__isnull=True).exists()- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_non_admin_is_refused(self, mock_info):mock_info.return_value = _slack_user_info(is_admin=False, is_owner=False)@@ -72,7 +72,7 @@ class TestHandleProjectSetWorkspace:text = self.slack.client.chat_postEphemeral.call_args.kwargs["text"]assert "admins or owners" in text- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_admin_without_team_access_is_refused(self, mock_info):mock_info.return_value = _slack_user_info(is_admin=True)@@ -82,7 +82,7 @@ class TestHandleProjectSetWorkspace:text = self.slack.client.chat_postEphemeral.call_args.kwargs["text"]assert "don't have access" in text- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_workspace_default_replaces_existing(self, mock_info):mock_info.return_value = _slack_user_info(is_admin=True)second_team = Team.objects.create(organization=self.organization, name="Team C")@@ -122,17 +122,17 @@ class TestHandleHelp:_handle_help(self.slack, self.integration, "C1", "111.1", "U1")return self.slack.client.chat_postMessage.call_args.kwargs["text"]- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_admin_sees_workspace_line(self, mock_info):mock_info.return_value = _slack_user_info(is_admin=True)assert WORKSPACE_HELP_LINE in self._help_text()- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_owner_sees_workspace_line(self, mock_info):mock_info.return_value = _slack_user_info(is_owner=True)assert WORKSPACE_HELP_LINE in self._help_text()- @patch("products.slack_app.backend.api._get_slack_user_info")+ @patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")def test_non_admin_does_not_see_workspace_line(self, mock_info):mock_info.return_value = _slack_user_info(is_admin=False, is_owner=False)text = self._help_text()diff --git a/products/slack_app/backend/tests/test_resolve_slack_user.py b/products/slack_app/backend/tests/test_resolve_slack_user.pyindex 3650899b3011..161c702f4704 100644--- a/products/slack_app/backend/tests/test_resolve_slack_user.py+++ b/products/slack_app/backend/tests/test_resolve_slack_user.py@@ -10,8 +10,9 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.slack_app.backend.api import SLACK_USER_PROFILE_TTL, lookup_slack_user_id_by_email, resolve_slack_user+from products.slack_app.backend.api import resolve_slack_userfrom products.slack_app.backend.models import SlackUserProfileCache+from products.slack_app.backend.services.slack_user_info import SLACK_USER_PROFILE_TTL, lookup_slack_user_id_by_emailclass TestResolveSlackUser: