Skip to content

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

feat(slack-app): answer a mention that carries no request without a run (#108468)

Vojta Bartošfb15668fa0c8
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 119b65f99c8f..a44f24d7e218 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -66,6 +66,7 @@ from products.slack_app.backend.feature_flags import (
from products.slack_app.backend.helpers import local_dev_slack_email
from products.slack_app.backend.models import SlackChannel, SlackSettings, SlackThreadTaskMapping, UntaggedFollowupMode
from products.slack_app.backend.services import (
+ bare_mention,
inbox_interactivity,
project_picker,
slack_welcome_messages,
@@ -1395,6 +1396,59 @@ def _edited_mention_ignore_cause(event: dict[str, Any], slack_team_id: str) -> s
return None
+def _awaits_request_from_author(event: dict[str, Any], slack_team_id: str, probe: Integration) -> bool:
+ """Whether this threaded message is the request a bare mention in its thread asked for."""
+ channel = event.get("channel")
+ thread_ts = event.get("thread_ts")
+ awaited_from = bare_mention.awaited_request_from(
+ slack_team_id,
+ channel if isinstance(channel, str) else None,
+ thread_ts if isinstance(thread_ts, str) else None,
+ now=time.time(),
+ )
+ if awaited_from is None:
+ return False
+ if awaited_from != event.get("user"):
+ if event.get("type") == "message":
+ _report_slack_mention_dropped(
+ event, slack_team_id, reason="awaited_reply_other_user", replied=False, integration=probe
+ )
+ return False
+ return True
+
+
+def _answer_bare_mention(
+ event: dict[str, Any], integration: Integration, slack_team_id: str, *, posthog_user: User
+) -> str:
+ channel = event.get("channel")
+ message_ts = event.get("ts")
+ slack_user_id = event.get("user")
+ replied = False
+ if isinstance(channel, str) and isinstance(message_ts, str) and isinstance(slack_user_id, str):
+ if bare_mention.await_request(slack_team_id, channel, message_ts, slack_user_id=slack_user_id):
+ replied = _post_slack_user_feedback(
+ SlackIntegration(integration),
+ channel,
+ slack_user_id,
+ message_ts,
+ bare_mention.BARE_MENTION_REPLY,
+ prefer_thread_message=True,
+ )
+ # No run started, so an edit that adds the request must be free to start one.
+ handled_key = _message_handled_cache_key(slack_team_id, event)
+ if handled_key is not None:
+ cache.delete(handled_key)
+ _report_slack_mention_dropped(
+ event,
+ slack_team_id,
+ reason="bare_mention",
+ replied=replied,
+ integration=integration,
+ posthog_user=posthog_user,
+ )
+ return ROUTE_HANDLED_LOCALLY
+
+
def _thread_message_event_has_files(event: dict[str, Any]) -> bool:
files = event.get("files")
return isinstance(files, list) and len(files) > 0
@@ -2370,6 +2424,7 @@ def _dispatch_mention_to_target(
posthog_user: User,
untagged_followup_mapping: SlackThreadTaskMapping | None,
is_ext_shared_channel: bool,
+ awaited_request_reply: bool = False,
) -> str:
"""Run the gates that need a resolved project, then start the mention workflow."""
slack = SlackIntegration(mention_target)
@@ -2430,6 +2485,19 @@ def _dispatch_mention_to_target(
if untagged_followup_mapping is not None:
_mark_message_handled(slack_team_id, event, "untagged_followup")
+ channel = event.get("channel")
+ thread_ts = event.get("thread_ts") or event.get("ts")
+ if awaited_request_reply and isinstance(channel, str) and isinstance(thread_ts, str):
+ bare_mention.clear_awaited_request(slack_team_id, channel, thread_ts)
+ _mark_message_handled(slack_team_id, event, "mention")
+ elif event.get("type") == "app_mention":
+ if bare_mention.is_bare_mention(event):
+ return _answer_bare_mention(event, mention_target, slack_team_id, posthog_user=posthog_user)
+ # An edit that adds the request to a bare mention starts the run here, so the
+ # thread must stop waiting for a reply that would otherwise start a second one.
+ if event.get("edited") and isinstance(channel, str) and isinstance(thread_ts, str):
+ bare_mention.clear_awaited_request(slack_team_id, channel, thread_ts)
+
return _start_mention_workflow(
event,
mention_target,
@@ -2438,6 +2506,7 @@ def _dispatch_mention_to_target(
posthog_user=posthog_user,
untagged_followup=untagged_followup_mapping is not None,
is_ext_shared_channel=is_ext_shared_channel,
+ awaited_request_reply=awaited_request_reply,
)
@@ -2664,6 +2733,7 @@ def route_posthog_code_event_to_relevant_region(
# Threads we don't own are dropped here so the rest of the pipeline
# only runs for actionable messages.
untagged_followup_mapping: SlackThreadTaskMapping | None = None
+ awaited_request_reply = False
if event_type == "message":
untagged_followup_mapping = _resolve_untagged_followup_mapping(
candidates=workspace_result.candidates,
@@ -2671,11 +2741,18 @@ def route_posthog_code_event_to_relevant_region(
thread_ts=thread_ts_str,
)
if untagged_followup_mapping is None:
- return ROUTE_HANDLED_LOCALLY
+ if not _awaits_request_from_author(event, slack_team_id, workspace_result.candidates[0]):
+ return ROUTE_HANDLED_LOCALLY
+ awaited_request_reply = True
# A tagged reply also arrives as its own ``app_mention`` event, which owns
# it. Letting this copy through would run the untagged-followup classifier
# (and the ``ask`` prompt) on a message that explicitly addressed the app.
- if _message_tags_bot(event, untagged_followup_mapping.integration):
+ if _message_tags_bot(
+ event,
+ untagged_followup_mapping.integration
+ if untagged_followup_mapping is not None
+ else workspace_result.candidates[0],
+ ):
logger.info(
"slack_app_thread_message_ignored",
reason="tagged_reply",
@@ -2684,6 +2761,8 @@ def route_posthog_code_event_to_relevant_region(
message_ts=event.get("ts"),
)
return ROUTE_HANDLED_LOCALLY
+ elif mention_is_threaded:
+ awaited_request_reply = _awaits_request_from_author(event, slack_team_id, workspace_result.candidates[0])
# Both event types share the rest of the pipeline. Mention-only side
# effects (failure reply, scope notice, approval prompt, rules command,
@@ -2830,6 +2909,7 @@ def route_posthog_code_event_to_relevant_region(
posthog_user=posthog_user,
untagged_followup_mapping=untagged_followup_mapping,
is_ext_shared_channel=is_ext_shared_channel,
+ awaited_request_reply=awaited_request_reply,
)
if event_type == "member_joined_channel":
@@ -3712,6 +3792,7 @@ def _report_slack_mention_received(
slack_team_id: str,
*,
posthog_user: User | None = None,
+ awaited_request_reply: bool = False,
) -> User | None:
"""Capture a product-analytics event each time the @PostHog bot is mentioned.
@@ -3769,6 +3850,7 @@ def _report_slack_mention_received(
# add up to a funnel.
"slack_event_type": event.get("type"),
"slack_message_edited": bool(event.get("edited")),
+ "awaited_request_reply": awaited_request_reply,
# "im" marks an assistant DM; channel mentions carry "channel"/"group" or no type at all.
"slack_channel_type": event.get("channel_type"),
"posthog_user_identified": identified_distinct_id is not None,
@@ -3867,6 +3949,7 @@ def _start_mention_workflow(
untagged_followup: bool = False,
untagged_followup_confirmed: bool = False,
is_ext_shared_channel: bool = False,
+ awaited_request_reply: bool = False,
fork_source_channel: str | None = None,
fork_source_thread_ts: str | None = None,
fork_source_message_ts: str | None = None,
@@ -3890,7 +3973,13 @@ def _start_mention_workflow(
"""
is_fork = bool(fork_source_channel and fork_source_thread_ts)
if not untagged_followup and not is_fork:
- _report_slack_mention_received(event, integration, slack_team_id, posthog_user=posthog_user)
+ _report_slack_mention_received(
+ event,
+ integration,
+ slack_team_id,
+ posthog_user=posthog_user,
+ awaited_request_reply=awaited_request_reply,
+ )
if _resolve_pending_repo_picker_from_followup(event, integration):
return ROUTE_HANDLED_LOCALLY
workflow_inputs = PostHogCodeSlackMentionWorkflowInputs(
diff --git a/products/slack_app/backend/services/bare_mention.py b/products/slack_app/backend/services/bare_mention.py
new file mode 100644
index 000000000000..a92b5bb14680
--- /dev/null
+++ b/products/slack_app/backend/services/bare_mention.py
@@ -0,0 +1,58 @@
+import re
+from typing import Any
+
+from django.core.cache import cache
+
+from products.slack_app.backend.services.slack_messages import extract_message_text
+
+AWAITED_REQUEST_TTL_SECONDS = 60 * 60
+
+BARE_MENTION_REPLY = (
+ "Hi! What would you like to know? Reply in this thread with your question. For example:\n"
+ "• How many people signed up last week?\n"
+ "• Were there any new errors after yesterday's deploy?\n"
+ "• Which feature flags have not been used in 30 days?\n"
+ "If you reply more than an hour from now, mention me in the reply."
+)
+
+_USER_TAG = re.compile(r"<@[^>]+>")
+
+
+def is_bare_mention(event: dict[str, Any]) -> bool:
+ thread_ts = event.get("thread_ts")
+ # Inside a thread, the earlier messages are the request.
+ if isinstance(thread_ts, str) and thread_ts != event.get("ts"):
+ return False
+ if event.get("files"):
+ return False
+ return not _USER_TAG.sub("", extract_message_text(event)).strip()
+
+
+def thread_is_recent(thread_ts: str | None, *, now: float) -> bool:
+ try:
+ return thread_ts is not None and now - float(thread_ts) <= AWAITED_REQUEST_TTL_SECONDS
+ except ValueError:
+ return False
+
+
+def _key(slack_team_id: str, channel: str, thread_ts: str) -> str:
+ return f"slack_app:awaited_request:v1:{slack_team_id}:{channel}:{thread_ts}"
+
+
+def await_request(slack_team_id: str, channel: str, thread_ts: str, *, slack_user_id: str) -> bool:
+ """Claim the thread for the person's next message. False when the thread is already claimed."""
+ return bool(cache.add(_key(slack_team_id, channel, thread_ts), slack_user_id, timeout=AWAITED_REQUEST_TTL_SECONDS))
+
+
+def awaited_request_from(slack_team_id: str, channel: str | None, thread_ts: str | None, *, now: float) -> str | None:
+ """The Slack user whose request this thread waits for, or None."""
+ # Threaded messages arrive in high volume. The age check keeps the cache read to
+ # threads that can still hold a claim.
+ if channel is None or thread_ts is None or not thread_is_recent(thread_ts, now=now):
+ return None
+ slack_user_id = cache.get(_key(slack_team_id, channel, thread_ts))
+ return slack_user_id if isinstance(slack_user_id, str) else None
+
+
+def clear_awaited_request(slack_team_id: str, channel: str, thread_ts: str) -> None:
+ cache.delete(_key(slack_team_id, channel, thread_ts))
diff --git a/products/slack_app/backend/tests/services/test_bare_mention.py b/products/slack_app/backend/tests/services/test_bare_mention.py
new file mode 100644
index 000000000000..73cb1c2e810a
--- /dev/null
+++ b/products/slack_app/backend/tests/services/test_bare_mention.py
@@ -0,0 +1,49 @@
+import pytest
+
+from products.slack_app.backend.services.bare_mention import (
+ AWAITED_REQUEST_TTL_SECONDS,
+ is_bare_mention,
+ thread_is_recent,
+)
+
+NOW = 1_800_000_000.0
+
+
+def _mention(**overrides) -> dict:
+ return {"type": "app_mention", "channel": "C001", "user": "U123", "ts": "1234.5678", **overrides}
+
+
+ "event, expected",
+ [
+ pytest.param(_mention(text="<@U0BOT>"), True, id="tag_only"),
+ pytest.param(_mention(text=" <@U0BOT|posthog> "), True, id="labeled_tag_with_whitespace"),
+ pytest.param(_mention(text="<@U0BOT>", thread_ts="1234.5678"), True, id="thread_root"),
+ pytest.param(_mention(text="<@U0BOT> how many signups"), False, id="tag_with_a_question"),
+ pytest.param(
+ _mention(
+ text="<@U0BOT>",
+ blocks=[{"type": "section", "text": {"type": "mrkdwn", "text": "Checkout errors doubled"}}],
+ ),
+ False,
+ id="words_only_in_blocks",
+ ),
+ pytest.param(_mention(text="<@U0BOT>", files=[{"id": "F1", "mimetype": "image/png"}]), False, id="file"),
+ pytest.param(_mention(text="<@U0BOT>", thread_ts="1000.0000"), False, id="reply_inside_a_thread"),
+ ],
+)
+def test_only_a_top_level_mention_with_nothing_in_it_is_bare(event, expected):
+ assert is_bare_mention(event) is expected
+
+
+ "thread_ts, expected",
+ [
+ pytest.param(f"{NOW - 20:.6f}", True, id="started_seconds_ago"),
+ pytest.param(f"{NOW - AWAITED_REQUEST_TTL_SECONDS - 1:.6f}", False, id="older_than_the_claim_can_live"),
+ pytest.param("not-a-timestamp", False, id="malformed"),
+ pytest.param(None, False, id="missing"),
+ ],
+)
+def test_thread_is_recent_only_while_a_claim_can_exist(thread_ts, expected):
+ assert thread_is_recent(thread_ts, now=NOW) is expected
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 5699067e19fa..3b28c5db7720 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
@@ -1,4 +1,5 @@
import json
+import time
from typing import Any, cast
from unittest.mock import MagicMock, patch
@@ -220,7 +221,13 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
# without calling the Slack API. New tests that exercise the unauthorised
# paths override this row (or delete it) deliberately.
self._seed_slack_user_cache("U123", "[email protected]")
- self.event = {"type": "app_mention", "channel": "C001", "user": "U123", "ts": "1234.5678"}
+ self.event = {
+ "type": "app_mention",
+ "channel": "C001",
+ "user": "U123",
+ "ts": "1234.5678",
+ "text": "<@U0BOT> how many signups last week",
+ }
def _seed_slack_user_cache(self, slack_user_id: str, email: str | None) -> SlackUserProfileCache:
from django.utils import timezone
@@ -506,6 +513,80 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
for key, value in expected_extra_properties.items():
assert capture_kwargs["properties"][key] == value
+ @parameterized.expand(
+ [
+ ("bare_top_level_mention", {"text": "<@U0BOT>"}, False),
+ ("bare_mention_inside_a_thread", {"text": "<@U0BOT>", "thread_ts": "1000.0000"}, True),
+ ("mention_with_a_request", {"text": "<@U0BOT> how many signups last week"}, True),
+ ]
+ )
+ @patch("products.slack_app.backend.api.posthoganalytics.capture")
+ @patch("products.slack_app.backend.api._post_slack_user_feedback", return_value=True)
+ @patch("products.slack_app.backend.api.asyncio.run")
+ @patch("products.slack_app.backend.api.sync_connect")
+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
+ def test_bare_mention_is_answered_without_a_run(
+ self,
+ _name,
+ overrides,
+ expect_workflow,
+ mock_sync_connect,
+ mock_asyncio_run,
+ mock_post_feedback,
+ mock_capture,
+ ):
+ from products.slack_app.backend.api import (
+ SLACK_MENTION_DROPPED_EVENT,
+ route_posthog_code_event_to_relevant_region,
+ )
+ from products.slack_app.backend.services.bare_mention import BARE_MENTION_REPLY, awaited_request_from
+
+ message_ts = f"{time.time() - 5:.6f}"
+ event = {**self.event, "ts": message_ts, **overrides}
+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
+
+ route_posthog_code_event_to_relevant_region(request, event, "T12345")
+
+ assert mock_sync_connect.called is expect_workflow
+ awaited_from = awaited_request_from("T12345", "C001", message_ts, now=time.time())
+ if expect_workflow:
+ mock_post_feedback.assert_not_called()
+ assert awaited_from is None
+ else:
+ assert mock_post_feedback.call_args.args[4] == BARE_MENTION_REPLY
+ assert awaited_from == "U123"
+ captured = {call.kwargs["event"]: call.kwargs["properties"] for call in mock_capture.call_args_list}
+ assert captured[SLACK_MENTION_DROPPED_EVENT]["drop_reason"] == "bare_mention"
+ assert captured[SLACK_MENTION_DROPPED_EVENT]["replied"] is True
+
+ @patch("products.slack_app.backend.api._post_slack_user_feedback", return_value=True)
+ @patch("products.slack_app.backend.api.asyncio.run")
+ @patch("products.slack_app.backend.api.sync_connect")
+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
+ def test_edit_that_adds_the_request_to_a_bare_mention_starts_a_run(
+ self, mock_sync_connect, mock_asyncio_run, mock_post_feedback
+ ):
+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region
+ from products.slack_app.backend.services.bare_mention import awaited_request_from
+
+ now = time.time()
+ message_ts = f"{now - 20:.6f}"
+ bare = {**self.event, "ts": message_ts, "text": "<@U0BOT>"}
+ edited = {
+ **bare,
+ "text": "<@U0BOT> how many signups last week",
+ "edited": {"user": "U123", "ts": f"{now:.6f}"},
+ }
+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
+
+ route_posthog_code_event_to_relevant_region(request, bare, "T12345")
+ mock_sync_connect.assert_not_called()
+ assert awaited_request_from("T12345", "C001", message_ts, now=now) == "U123"
+ route_posthog_code_event_to_relevant_region(request, edited, "T12345")
+
+ mock_sync_connect.return_value.start_workflow.assert_called_once()
+ assert awaited_request_from("T12345", "C001", message_ts, now=now) is None
+
@patch("products.slack_app.backend.api.posthoganalytics.capture")
@patch("products.slack_app.backend.api._post_slack_user_feedback")
@patch("products.slack_app.backend.api.asyncio.run")
@@ -1228,6 +1309,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
"user": "U123",
"ts": "1234.5678",
"thread_ts": "1234.5678",
+ "text": "<@U0BOT> how many signups last week",
}
result = route_posthog_code_event_to_relevant_region(request, event, "T12345")
@@ -1274,6 +1356,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
"user": "U123",
"ts": "1234.5678",
"thread_ts": "1234.5678",
+ "text": "<@U0BOT> how many signups last week",
}
result = route_posthog_code_event_to_relevant_region(request, event, "T12345")
@@ -1333,6 +1416,7 @@ class TestChannelApprovalGate(TestCase):
"channel": "C_EXT",
"user": "U123",
"ts": "1234.5678",
+ "text": "<@U0BOT> how many signups last week",
}
@patch("products.slack_app.backend.api._post_channel_approval_prompt")
@@ -1624,7 +1708,13 @@ class TestQueueWorkflowDispatch(TestCase):
from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
mock_slack.return_value.missing_scopes.return_value = set()
- event = {"type": "app_mention", "channel": "C001", "user": "U123", "ts": "1234.5678"}
+ event = {
+ "type": "app_mention",
+ "channel": "C001",
+ "user": "U123",
+ "ts": "1234.5678",
+ "text": "<@U0BOT> how many signups last week",
+ }
if thread_ts:
event["thread_ts"] = thread_ts
request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.py
index d7d5d58c64aa..332425cb61f7 100644
--- a/products/slack_app/backend/tests/test_thread_message_routing.py
+++ b/products/slack_app/backend/tests/test_thread_message_routing.py
@@ -596,6 +596,80 @@ class TestRouteThreadMessage(TestCase):
("ignored:edit", expected_ignore_cause)
]
+ # --- Reply to a bare mention -------------------------------------------
+
+ @parameterized.expand(
+ [
+ ("same_person", "U_BOB", 30, "and how many signups last week", False, True, []),
+ ("no_bare_mention_in_the_thread", None, 30, "and how many signups last week", False, False, []),
+ (
+ "another_person",
+ "U_ALICE",
+ 30,
+ "and how many signups last week",
+ False,
+ False,
+ ["awaited_reply_other_user"],
+ ),
+ (
+ "another_person_but_the_thread_has_a_run",
+ "U_ALICE",
+ 30,
+ "and how many signups last week",
+ True,
+ True,
+ [],
+ ),
+ ("tagged_copy", "U_BOB", 30, "<@U0BOT> how many signups last week", False, False, []),
+ (
+ "thread_older_than_a_claim_can_live",
+ "U_BOB",
+ 2 * 60 * 60,
+ "and how many signups last week",
+ False,
+ False,
+ [],
+ ),
+ ]
+ )
+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
+ def test_untagged_reply_runs_only_when_the_thread_awaits_its_author(
+ self, _name, awaited_from, thread_age_seconds, text, thread_has_run, expect_workflow, expected_drop_reasons
+ ):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, SLACK_MENTION_DROPPED_EVENT
+ from products.slack_app.backend.services.bare_mention import await_request
+
+ now = time.time()
+ thread_ts = f"{now - thread_age_seconds:.6f}"
+ if awaited_from is not None:
+ await_request("T_SLACK", "C001", thread_ts, slack_user_id=awaited_from)
+ if thread_has_run:
+ self.mapping.thread_ts = thread_ts
+ self.mapping.save(update_fields=["thread_ts"])
+ event = self._make_event(user="U_BOB", thread_ts=thread_ts, ts=f"{now:.6f}", text=text)
+
+ with (
+ patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False),
+ patch("products.slack_app.backend.api.get_cached_bot_user_id", return_value="U0BOT"),
+ patch(
+ "products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY
+ ) as mock_start,
+ patch("products.slack_app.backend.api.posthoganalytics.capture") as mock_capture,
+ ):
+ result = self._route(event)
+
+ assert result == ROUTE_HANDLED_LOCALLY
+ assert mock_start.called is expect_workflow
+ if expect_workflow:
+ assert mock_start.call_args.kwargs["untagged_followup"] is thread_has_run
+ assert mock_start.call_args.kwargs["awaited_request_reply"] is not thread_has_run
+ drop_reasons = [
+ call.kwargs["properties"]["drop_reason"]
+ for call in mock_capture.call_args_list
+ if call.kwargs["event"] == SLACK_MENTION_DROPPED_EVENT
+ ]
+ assert drop_reasons == expected_drop_reasons
+
class TestMirrorSlackMessageEventTask(SimpleTestCase):
"""The queued mirror task owns the claims probe, so the webhook-side tests above cannot