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.

fix(slack): drop untagged follow-ups meant for another app (#102785)

Vojta Bartošb2c9b7548c3d
diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.py
index e77847a49a87..dd712a18ee3d 100644
--- a/posthog/temporal/ai/slack_app/activities/classifiers.py
+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py
@@ -31,6 +31,7 @@ from products.slack_app.backend.models import SlackThreadTaskMapping
from products.slack_app.backend.prompt_templates import PromptTemplates
from products.slack_app.backend.services.integration_resolver import format_project_candidate_list, routable_projects
from products.slack_app.backend.services.slack_messages import SlackThreadMessage
+from products.slack_app.backend.services.slack_user_info import find_addressed_bot_user_id
logger = structlog.get_logger(__name__)
@@ -338,8 +339,9 @@ def classify_untagged_followup_activity(
Runs the LLM + Slack thread-history fetch inside the workflow rather than
the webhook handler so they're retriable under Temporal and don't block
the Slack webhook's 3-second ack budget. Returns ``True`` to forward,
- ``False`` to drop. Conservative defaults: missing mapping → drop, history
- fetch failure → classify on text alone, classifier failure → drop.
+ ``False`` to drop. Conservative defaults: missing mapping → drop, a reply
+ that tags another app → drop, history fetch failure → classify on text
+ alone, classifier failure → drop.
"""
from products.slack_app.backend.services.slack_messages import cached_collect_thread_messages
@@ -361,6 +363,19 @@ def classify_untagged_followup_activity(
integration = mapping.integration
slack = SlackIntegration(integration)
+ # Asked before the history fetch and the model call, because reading the reply cannot
+ # answer it.
+ addressed_bot_user_id = find_addressed_bot_user_id(slack, integration, event_text)
+ if addressed_bot_user_id:
+ logger.info(
+ "posthog_code_thread_message_addressed_to_another_app",
+ channel=channel,
+ thread_ts=thread_ts,
+ slack_user_id=slack_user_id,
+ addressed_bot_user_id=addressed_bot_user_id,
+ )
+ return False
+
try:
# Cached: the next activity in this workflow run (the forwarder) re-fetches the
# same thread to compute its diff; a cache hit there avoids a second Slack call.
diff --git a/posthog/temporal/ai/slack_app/activities/prompts/message_is_agent_directed.md.j2 b/posthog/temporal/ai/slack_app/activities/prompts/message_is_agent_directed.md.j2
index 0bd0cf6258ab..ed5407e9865f 100644
--- a/posthog/temporal/ai/slack_app/activities/prompts/message_is_agent_directed.md.j2
+++ b/posthog/temporal/ai/slack_app/activities/prompts/message_is_agent_directed.md.j2
@@ -3,13 +3,14 @@ The PostHog agent is working on a task in this Slack thread. People in the threa
Answer true only when the message is addressed to the agent:
- An order or request to do something, with the agent as the only plausible audience ('also handle the empty case', 'skip the migration', 'open a PR for that too', 'try again with the other helper').
- A question put to the agent about its own work ('why did you skip the redesign commit?', 'does your PR cover the mobile breakpoint?').
- - An answer to something the agent just asked in this thread.
+ - An answer to something the PostHog agent itself just asked in this thread.
- A correction of what the agent said or did ('no, the bug is in the handler, not the wrapper').
Answer false for everything else. This is the common case, and the mistake to avoid — people talk about the work far more often than they talk to the agent:
- Opinions and discussion about the task or the product, addressed to the room ('this needs a stronger label', 'it should probably live under settings', 'I've seen this set back and forth so much'). Relevant to the task is not the same as addressed to the agent.
- Talk about the agent in the third person ('why is the bot reacting to me?', 'it keeps replying', 'is it supposed to do that?'). Being the topic is not being the audience.
- Conversation between humans — answering each other, tagging each other, deciding something among themselves.
+ - A message meant for a different bot or coding agent working in the same thread ('take another look at the migration' right after that agent reported back, 'yes, go ahead' answering its question). Other apps are posted in these threads under their own names, and the thread history below says who said what. Only the PostHog agent's own lines are yours to answer for; nothing said to another app is.
- An instruction or request aimed at a named person, even with no @mention ('sam go ahead and add yourself as the owner', 'jake, can you take this one'). A name in the thread is the audience; an order is not addressed to the agent just because it is phrased as one.
- A request only a person could carry out — joining a call, meeting a customer, updating an account in a system the agent has no access to — even when it says 'you', and even when it directly follows something the agent said.
- Someone taking the work on themselves ('let me fix that', 'I'm on it', 'I'll take a look'). That stands the agent down; it is not a handoff to it.
diff --git a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_message_is_agent_directed.ambr b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_message_is_agent_directed.ambr
index 9342fa30bdf3..b24255b4e35b 100644
--- a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_message_is_agent_directed.ambr
+++ b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_classify_message_is_agent_directed.ambr
@@ -6,13 +6,14 @@
Answer true only when the message is addressed to the agent:
- An order or request to do something, with the agent as the only plausible audience ('also handle the empty case', 'skip the migration', 'open a PR for that too', 'try again with the other helper').
- A question put to the agent about its own work ('why did you skip the redesign commit?', 'does your PR cover the mobile breakpoint?').
- - An answer to something the agent just asked in this thread.
+ - An answer to something the PostHog agent itself just asked in this thread.
- A correction of what the agent said or did ('no, the bug is in the handler, not the wrapper').
Answer false for everything else. This is the common case, and the mistake to avoid — people talk about the work far more often than they talk to the agent:
- Opinions and discussion about the task or the product, addressed to the room ('this needs a stronger label', 'it should probably live under settings', 'I've seen this set back and forth so much'). Relevant to the task is not the same as addressed to the agent.
- Talk about the agent in the third person ('why is the bot reacting to me?', 'it keeps replying', 'is it supposed to do that?'). Being the topic is not being the audience.
- Conversation between humans — answering each other, tagging each other, deciding something among themselves.
+ - A message meant for a different bot or coding agent working in the same thread ('take another look at the migration' right after that agent reported back, 'yes, go ahead' answering its question). Other apps are posted in these threads under their own names, and the thread history below says who said what. Only the PostHog agent's own lines are yours to answer for; nothing said to another app is.
- An instruction or request aimed at a named person, even with no @mention ('sam go ahead and add yourself as the owner', 'jake, can you take this one'). A name in the thread is the audience; an order is not addressed to the agent just because it is phrased as one.
- A request only a person could carry out — joining a call, meeting a customer, updating an account in a system the agent has no access to — even when it says 'you', and even when it directly follows something the agent said.
- Someone taking the work on themselves ('let me fix that', 'I'm on it', 'I'll take a look'). That stands the agent down; it is not a handoff to it.
diff --git a/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py b/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py
index 6595285e7d2e..c466ea43a115 100644
--- a/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py
+++ b/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py
@@ -2,6 +2,7 @@ from unittest.mock import patch
from django.apps import apps
from django.test import TestCase
+from django.utils import timezone
from posthog.models.integration import Integration
from posthog.models.organization import Organization
@@ -9,7 +10,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.temporal.ai.slack_app import PostHogCodeSlackMentionWorkflowInputs, classify_untagged_followup_activity
-from products.slack_app.backend.models import SlackThreadTaskMapping
+from products.slack_app.backend.models import SlackThreadTaskMapping, SlackUserProfileCache
class TestClassifyUntaggedFollowupActivity(TestCase):
@@ -93,6 +94,28 @@ class TestClassifyUntaggedFollowupActivity(TestCase):
):
assert self._call("thanks team!") is False
+ def test_a_reply_that_tags_another_app_never_reaches_the_classifier(self):
+ SlackUserProfileCache.objects.create(
+ integration=self.integration,
+ slack_user_id="U0OTHERAPP",
+ display_name="Other agent",
+ is_bot=True,
+ refreshed_at=timezone.now(),
+ )
+ with (
+ patch("products.slack_app.backend.services.slack_messages.cached_collect_thread_messages", return_value=[]),
+ patch(
+ "products.slack_app.backend.services.slack_user_info.get_cached_bot_user_id",
+ return_value="U0OURBOT",
+ ),
+ patch(
+ "posthog.temporal.ai.slack_app.activities.classifiers.classify_message_is_agent_directed",
+ return_value=True,
+ ) as mock_classify,
+ ):
+ assert self._call("<@U0OTHERAPP> take another look at the export filter") is False
+ mock_classify.assert_not_called()
+
def test_history_fetch_failure_classifies_on_empty_history(self):
"""A Slack hiccup on ``conversations_replies`` falls back to classifying
on the message text alone rather than dropping silently."""
diff --git a/products/slack_app/backend/services/slack_user_info.py b/products/slack_app/backend/services/slack_user_info.py
index b6acb4b53962..6c742f6dc83c 100644
--- a/products/slack_app/backend/services/slack_user_info.py
+++ b/products/slack_app/backend/services/slack_user_info.py
@@ -17,6 +17,7 @@ dependency. Living in `services/` lets all of them import normally and
keeps `api.py` focused on routes.
"""
+import re
from datetime import timedelta
from typing import Any
@@ -332,3 +333,52 @@ def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) ->
if integration.integration_id:
cache_workspace_bot_user_id(integration.integration_id, bot_user_id)
return bot_user_id
+
+
+_USER_MENTION_RE = re.compile(r"<@([A-Z0-9]+)(?:\|[^>]*)?>")
+
+
+def find_addressed_bot_user_id(slack: SlackIntegration, integration: Integration, text: str) -> str | None:
+ """The user id of a bot other than ours that this message tags, or ``None``.
+
+ Callers ask this to tell a message addressed to another app from one addressed to us.
+ Other apps work in the same channels and threads we do, and a message that tags one is
+ that app's to answer. Nothing in the text says so by the time an agent reads it:
+ ``resolve_user_mentions_text`` strips bot mentions, which leaves a bare instruction to
+ whoever is listening.
+
+ Wire format cannot answer it either. A bot user id and a human's are both
+ ``U…``-prefixed, so the ``is_bot`` flag is the only authoritative signal, and it comes
+ from ``users.info`` through the same cache every other lookup here uses.
+
+ A message that tags our own bot answers ``None``, whoever else it tags. Somebody typed
+ our name, so the message is ours to answer even when it names another app in the same
+ breath.
+
+ Answers ``None`` when a lookup fails as well as when the message tags no bot. An
+ unresolved mention is no evidence the message was meant for someone else. That covers
+ our own id too: without it our bot's mention is indistinguishable from another app's,
+ and a message that tagged us is the worse one to get wrong.
+ """
+ mentioned_ids = dict.fromkeys(_USER_MENTION_RE.findall(text))
+ if not mentioned_ids:
+ return None
+
+ our_bot_user_id = get_cached_bot_user_id(slack, integration)
+ if not our_bot_user_id or our_bot_user_id in mentioned_ids:
+ return None
+
+ for user_id in mentioned_ids:
+ try:
+ user_info = get_slack_user_info(slack, integration, user_id)
+ except Exception:
+ logger.warning(
+ "slack_app_mention_bot_lookup_failed",
+ integration_id=integration.id,
+ mentioned_user_id=user_id,
+ exc_info=True,
+ )
+ continue
+ if user_info.get("user", {}).get("is_bot"):
+ return user_id
+ return None
diff --git a/products/slack_app/backend/tests/services/test_find_addressed_bot_user_id.py b/products/slack_app/backend/tests/services/test_find_addressed_bot_user_id.py
new file mode 100644
index 000000000000..2332ab0057f0
--- /dev/null
+++ b/products/slack_app/backend/tests/services/test_find_addressed_bot_user_id.py
@@ -0,0 +1,92 @@
+import pytest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from posthog.models.integration import Integration, SlackIntegration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+
+from products.slack_app.backend.models import SlackUserProfileCache
+from products.slack_app.backend.services.slack_user_info import find_addressed_bot_user_id
+
+OUR_BOT = "U0OURBOT"
+
+
+class TestFindAddressedBotUserId:
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_SLACK",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+ self._cache_profile(OUR_BOT, is_bot=True)
+ self._cache_profile("U0OTHERAPP", is_bot=True)
+ self._cache_profile("U0ALICE", is_bot=False)
+
+ def _cache_profile(self, slack_user_id: str, *, is_bot: bool) -> None:
+ SlackUserProfileCache.objects.create(
+ integration=self.integration,
+ slack_user_id=slack_user_id,
+ display_name=slack_user_id,
+ is_bot=is_bot,
+ refreshed_at=timezone.now(),
+ )
+
+ def _find(self, text: str) -> str | None:
+ with patch(
+ "products.slack_app.backend.services.slack_user_info.get_cached_bot_user_id",
+ return_value=OUR_BOT,
+ ):
+ return find_addressed_bot_user_id(SlackIntegration(self.integration), self.integration, text)
+
+ @pytest.mark.parametrize(
+ ("text", "expected"),
+ [
+ pytest.param("<@U0OTHERAPP> take another look", "U0OTHERAPP", id="another_app"),
+ pytest.param("<@U0OTHERAPP|other agent> take another look", "U0OTHERAPP", id="labeled_mention"),
+ pytest.param("<@U0ALICE> can you take this one", None, id="a_teammate"),
+ pytest.param("<@U0OURBOT> fix the export filter", None, id="our_own_bot"),
+ pytest.param("i like <@U0OTHERAPP> and i like <@U0OURBOT>", None, id="our_own_bot_and_another_app"),
+ pytest.param("<@U0ALICE> and <@U0OTHERAPP> already looked", "U0OTHERAPP", id="a_teammate_and_an_app"),
+ pytest.param("could you also check the export filter", None, id="no_mention"),
+ pytest.param("<@U0OTHERAPP>/checkout-sdk still fails", "U0OTHERAPP", id="package_path"),
+ ],
+ )
+ def test_answers_which_mention_belongs_to_another_app(self, text, expected):
+ assert self._find(text) == expected
+
+ def test_an_unresolvable_mention_answers_none(self):
+ # A Slack outage must not silence a genuine follow-up, so an id we cannot classify
+ # is treated as no evidence at all.
+ with (
+ patch(
+ "products.slack_app.backend.services.slack_user_info.get_cached_bot_user_id",
+ return_value=OUR_BOT,
+ ),
+ patch(
+ "products.slack_app.backend.services.slack_user_info.get_slack_user_info",
+ side_effect=RuntimeError("slack hiccup"),
+ ),
+ ):
+ result = find_addressed_bot_user_id(
+ SlackIntegration(self.integration), self.integration, "<@U0UNKNOWN> take another look"
+ )
+ assert result is None
+
+ def test_an_unresolvable_own_bot_id_answers_none(self):
+ # Our own mention is indistinguishable from another app's without our id, and the
+ # webhook lets a tagged reply through on the same failure, so dropping it here
+ # would silently swallow a message that did tag us.
+ with patch(
+ "products.slack_app.backend.services.slack_user_info.get_cached_bot_user_id",
+ return_value=None,
+ ):
+ result = find_addressed_bot_user_id(
+ SlackIntegration(self.integration), self.integration, "<@U0OTHERAPP> take another look"
+ )
+ assert result is None
diff --git a/products/slack_app/evals/eval_followup_classifier.py b/products/slack_app/evals/eval_followup_classifier.py
index f60cab447ebf..22d259a819fa 100644
--- a/products/slack_app/evals/eval_followup_classifier.py
+++ b/products/slack_app/evals/eval_followup_classifier.py
@@ -33,7 +33,7 @@ SUITE_KIND = SuiteKind.ONE_SHOT
TASK_TITLE = "Fix the checkout button not firing autocapture events"
-# The thread every case continues: a human asked, the agent acknowledged.
+# The thread most cases continue: a human asked, the agent acknowledged.
THREAD = [
SlackThreadMessage(
user="alice", text="@PostHog autocapture isn't picking up clicks on our checkout button", ts="1.0"
@@ -41,11 +41,42 @@ THREAD = [
SlackThreadMessage(user="posthog", text="Looking into it — checking how the button is rendered.", ts="2.0"),
]
+# Threads where a second coding agent works alongside us. A reply that tags it never
+# reaches the classifier (``_bot_addressed_by_reply`` drops it), so these cases are the
+# replies that name nobody, and only what each agent said says who they answer.
+THREAD_OTHER_AGENT_ASKED = [
+ *THREAD,
+ SlackThreadMessage(
+ user="cursor",
+ text="I have the checkout page open for the layout refactor. Shall I move the click handler out of the wrapper while I am in there?",
+ ts="3.0",
+ ),
+]
+THREAD_POSTHOG_ASKED = [
+ *THREAD,
+ SlackThreadMessage(user="cursor", text="Heads up, that whole file moves in my refactor branch.", ts="3.0"),
+ SlackThreadMessage(
+ user="posthog",
+ text="Do you want the handler fixed where it is now, or should I wait for that refactor to land?",
+ ts="4.0",
+ ),
+]
+
+THREADS = {
+ "default": THREAD,
+ "other_agent_asked": THREAD_OTHER_AGENT_ASKED,
+ "posthog_asked": THREAD_POSTHOG_ASKED,
+}
+
def _routes(agent_directed: bool) -> dict:
return {FOLLOWUP_KEY: {"agent_directed": agent_directed}}
+def _in_thread(name: str) -> dict:
+ return {"thread": name}
+
+
# Instructions. Only the first addresses the agent by name; the rest are what people
# actually type once they have stopped tagging.
DIRECTED_CASES = [
@@ -74,6 +105,13 @@ DIRECTED_CASES = [
prompt="that's the wrong file — it's the one under components/, not lib/",
expected=_routes(True),
),
+ # A second agent in the thread must not make us deaf to an answer we asked for.
+ BaseEvalCase(
+ name="answer_to_our_own_question",
+ prompt="fix it where it is now, we can rebase later",
+ expected=_routes(True),
+ metadata=_in_thread("posthog_asked"),
+ ),
BaseEvalCase(
name="follow_up_ask",
prompt="can you add a test for the logged-out case as well",
@@ -157,6 +195,14 @@ CHATTER_CASES = [
prompt="hmm, I'd be more inclined to drop the wrapper entirely and handle it at the call site",
expected=_routes(False),
),
+ # Every word of it is about our task; the only thing that says it is not for us is
+ # which agent asked.
+ BaseEvalCase(
+ name="answer_to_another_agents_question",
+ prompt="that's fine, pull it out of the wrapper while you're in there",
+ expected=_routes(False),
+ metadata=_in_thread("other_agent_asked"),
+ ),
# A thread kept as a running list. The item carries an implicit work item, which is a
# sharper lure than a bare link.
BaseEvalCase(
@@ -175,7 +221,10 @@ async def eval_followup_classifier(ctx: EvalContext) -> None:
# Sync and blocking on the gateway — off the event loop so cases still run
# concurrently under the harness's limiter.
agent_directed = await asyncio.to_thread(
- classifiers.classify_message_is_agent_directed, case.prompt, TASK_TITLE, THREAD
+ classifiers.classify_message_is_agent_directed,
+ case.prompt,
+ TASK_TITLE,
+ THREADS[case.metadata.get("thread", "default")],
)
except Exception as error:
return {