: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(tasks): notify task authors and mentioned users (#74812)
Shy Alter438b2aac1139
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 6ebc062681f0..4dd582d6014c 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -18,7 +18,7 @@ Functions that bridge to those heavy surfaces import them lazily inside the funcimport reimport hashlibimport logging-from collections.abc import Iterable, Sequence+from collections.abc import Collection, Iterable, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclassfrom datetime import datetime, timedelta@@ -5883,23 +5883,30 @@ def create_thread_message(except Exception:logger.exception("Failed to project thread message activity", extra={"message_id": str(message.id)})try:- _index_thread_message_mentions(message)+ mentioned_user_ids = resolve_mentioned_user_ids(+ User, message.content, team_id=message.team_id, author_id=message.author_id+ )+ except Exception:+ mentioned_user_ids = []+ logger.exception("Failed to resolve thread message mentions", extra={"message_id": str(message.id)})+ try:+ _index_thread_message_mentions(message, mentioned_user_ids)except Exception:- # Mentions are best-effort: an indexing failure must never fail message creation.+ # Mention indexing is best-effort: a failure must never fail message creation or discard resolved recipients.logger.exception("Failed to index thread message mentions", extra={"message_id": str(message.id)})+ from products.tasks.backend.push_dispatcher import notify_task_thread_message # noqa: PLC0415++ notify_task_thread_message(message, mentioned_user_ids)# Fresh message: forwarded_by is None (no query) and author lazy-loads once.return _thread_message_to_dto(message)-def _index_thread_message_mentions(message: TaskThreadMessage) -> None:+def _index_thread_message_mentions(message: TaskThreadMessage, mentioned_user_ids: Collection[int]) -> None:"""Create mention index rows for @[Name](email) tokens in the message content.Emails resolve case-insensitively, only to members of the team's organization;self-mentions are skipped (they are never notifications)."""- mentioned_user_ids = resolve_mentioned_user_ids(- User, message.content, team_id=message.team_id, author_id=message.author_id- )mentions = [TaskThreadMessageMention(team_id=message.team_id,@@ -6165,7 +6172,10 @@ def _create_agent_thread_message(task: Task, content: str, *, event: str, payloa)project_thread_message_activity(message)try:- _index_thread_message_mentions(message)+ mentioned_user_ids = resolve_mentioned_user_ids(+ User, message.content, team_id=message.team_id, author_id=message.author_id+ )+ _index_thread_message_mentions(message, mentioned_user_ids)except Exception:logger.exception("Failed to index thread message mentions", extra={"message_id": str(message.id)})diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.pyindex f8f4caa24e37..18966e3e493f 100644--- a/products/tasks/backend/push_dispatcher.py+++ b/products/tasks/backend/push_dispatcher.py@@ -1,4 +1,4 @@-"""Dispatch push notifications to the task creator's mobile devices.+"""Dispatch task notifications to the relevant users' mobile devices.Schedules the underlying Expo HTTP call as a Celery task via``transaction.on_commit`` so nothing here can block a request/response cycle@@ -9,34 +9,35 @@ Three guards before we enqueue:1. **Feature flag.** ``posthog-code-mobile-push`` must be enabled for theuser. Off by default — flip on once the mobile build is ready andtokens start arriving.-2. **Cooldown.** A per-``(task_run, kind)`` Redis lock collapses duplicate- triggers in a short window. A workflow that retries ``mark_completed``- or an agent that fires several rapid end-of-turn events results in one- push, not five.-3. **Anonymous task.** Runs without a ``created_by`` user get skipped- silently — there's no one to notify.+2. **Cooldown.** A per-source Redis lock collapses duplicate triggers in a+ short window.+3. **Access.** Recipients must still be able to view the task."""from __future__ import annotations-from typing import TYPE_CHECKING, Literal+from collections.abc import Collection+from typing import TYPE_CHECKING, Literal, castfrom django.conf import settingsfrom django.db import InterfaceError, OperationalError, close_old_connections, transaction+from django.db.models import Exists, OuterReffrom django.utils import timezoneimport structlogimport posthoganalytics+from posthog.models.user import Userfrom posthog.models.user_push_token import UserPushTokenfrom posthog.tasks.push_notifications import send_user_pushfrom products.tasks.backend.metrics import PUSH_DISPATCHER_FAILURES_TOTAL-from products.tasks.backend.models import TaskPresence+from products.tasks.backend.models import Task, TaskPresencefrom products.tasks.backend.redis import get_tasks_cache+from products.tasks.backend.visibility import task_visibility_qif TYPE_CHECKING:- from products.tasks.backend.models import TaskRun+ from products.tasks.backend.models import TaskRun, TaskThreadMessagelogger = structlog.get_logger(__name__)@@ -47,13 +48,14 @@ FEATURE_FLAG_KEY = "posthog-code-mobile-push"# they should only fire once per run lifetime — anything more is a retry.# Interactive turn-end can legitimately fire again after the user replies,# so a short cooldown is enough to absorb rapid duplicate triggers.-PushKind = Literal["completed", "failed", "cancelled", "awaiting", "turn_completed"]+PushKind = Literal["completed", "failed", "cancelled", "awaiting", "turn_completed", "thread_message"]_COOLDOWN_SECONDS: dict[PushKind, int] = {"completed": 600,"failed": 600,"cancelled": 600,"awaiting": 30,"turn_completed": 30,+ "thread_message": 600,}@@ -84,6 +86,64 @@ def notify_task_run_turn_completed(task_run: TaskRun) -> None:_enqueue(task_run, kind="turn_completed", body=f'"{_task_title(task_run)}" finished')+def notify_task_thread_message(message: TaskThreadMessage, mentioned_user_ids: Collection[int]) -> None:+ try:+ _notify_task_thread_message(message, mentioned_user_ids)+ except Exception as exc:+ PUSH_DISPATCHER_FAILURES_TOTAL.labels(kind="thread_message", reason=_failure_reason(exc)).inc()+ logger.warning(+ "push_dispatcher.enqueue_failed",+ task_id=str(message.task_id),+ message_id=str(message.id),+ kind="thread_message",+ exc_info=True,+ )+++def _notify_task_thread_message(message: TaskThreadMessage, mentioned_user_ids: Collection[int]) -> None:+ recipient_ids = set(mentioned_user_ids)+ if message.task.created_by_id is not None:+ recipient_ids.add(message.task.created_by_id)+ if message.author_id is not None:+ recipient_ids.discard(message.author_id)++ mentioned = set(mentioned_user_ids)+ author = message.author+ author_name = (author.first_name.strip() or author.email) if author else "PostHog"+ task_title = (message.task.title or "").strip() or "Untitled task"+ data = {+ "taskId": str(message.task_id),+ "messageId": str(message.id),+ }+ visible_task = Task.objects.filter(team_id=message.team_id, deleted=False).filter(+ task_visibility_q(cast(int, OuterRef("id"))), id=message.task_id+ )+ recipients = User.objects.filter(id__in=recipient_ids).filter(Exists(visible_task))+ for user in recipients:+ if not user.teams.filter(id=message.team_id).exists():+ continue+ action = "mentioned you" if user.id in mentioned else "replied"+ try:+ _enqueue_user(+ user,+ task=message.task,+ kind="thread_message",+ cooldown_subject=f"{message.id}:{user.id}",+ body=f'{author_name} {action} in "{task_title}"',+ data=data,+ )+ except Exception as exc:+ PUSH_DISPATCHER_FAILURES_TOTAL.labels(kind="thread_message", reason=_failure_reason(exc)).inc()+ logger.warning(+ "push_dispatcher.enqueue_failed",+ task_id=str(message.task_id),+ message_id=str(message.id),+ user_id=user.id,+ kind="thread_message",+ exc_info=True,+ )++def _project_awaiting_input_activity(task_run: TaskRun) -> None:"""Surface the wait in the in-app Activity feed.@@ -151,20 +211,34 @@ def _enqueue_inner(task_run: TaskRun, *, kind: PushKind, body: str) -> None:if user is None:return- # If the user has lost access to the task's team (e.g. removed from the- # organization), don't push them task titles for runs they shouldn't see- # anymore. The push body and data payload both carry the task identity.- # `user.teams` already accounts for both org membership and project-level- # RBAC, so it's the most accurate "can this user still see this run" gate.if not user.teams.filter(id=task_run.team_id).exists():logger.debug("push_dispatcher.recipient_lost_access",user_id=user.id,- run_id=str(task_run.id),+ task_id=str(task_run.task_id),team_id=task_run.team_id,)return+ _enqueue_user(+ user,+ task=task_run.task,+ kind=kind,+ cooldown_subject=str(task_run.id),+ body=body,+ data={"taskId": str(task_run.task_id), "taskRunId": str(task_run.id)},+ )+++def _enqueue_user(+ user: User,+ *,+ task: Task,+ kind: PushKind,+ cooldown_subject: str,+ body: str,+ data: dict[str, str],+) -> None:distinct_id = user.distinct_id or f"user_{user.id}"try:flag_enabled = posthoganalytics.feature_enabled(@@ -180,13 +254,12 @@ def _enqueue_inner(task_run: TaskRun, *, kind: PushKind, body: str) -> None:if not flag_enabled:return- cooldown_key = f"push_notification:{task_run.id}:{kind}"+ cooldown_key = f"push_notification:{cooldown_subject}:{kind}"if not get_tasks_cache().add(cooldown_key, True, timeout=_COOLDOWN_SECONDS[kind]):- logger.debug("push_dispatcher.cooldown_hit", run_id=str(task_run.id), kind=kind)+ logger.debug("push_dispatcher.cooldown_hit", subject=cooldown_subject, kind=kind)return- data = {"taskId": str(task_run.task_id), "taskRunId": str(task_run.id)}- suppressed = _suppressed_push_token_ids_for_task(user_id=user.id, task_id=task_run.task_id)+ suppressed = _suppressed_push_token_ids_for_task(user_id=user.id, task_id=task.id)# on_commit so we never schedule a push for a write that ends up rolling# back. Outside an atomic block this fires immediately, which is fine.diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex 2a420493a155..f337bb495a91 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -351,6 +351,44 @@ class TaskMentionsAPITestCase(ChannelTaskAPITestCase):# The author wasn't mentioned, so their own feed stays empty.self.assertEqual(self.author_client.get(self._mentions_url()).json(), [])+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ def test_thread_message_notifies_creator_and_mentions_only(self, mock_delay, _flag):+ mentioned = User.objects.create_user(email="[email protected]", first_name="Mina", password="password")+ unmentioned = User.objects.create_user(email="[email protected]", first_name="Other", password="password")+ self.organization.members.add(mentioned, unmentioned)++ with self.captureOnCommitCallbacks(execute=True):+ message = self._post_message(self.peer_client, "ping @[Mina]([email protected])")++ calls_by_user_id = {call.args[0]: call.args for call in mock_delay.call_args_list}+ self.assertEqual(set(calls_by_user_id), {self.author.id, mentioned.id})+ self.assertEqual(calls_by_user_id[self.author.id][3]["messageId"], message["id"])+ self.assertIn("replied", calls_by_user_id[self.author.id][2])+ self.assertIn("mentioned you", calls_by_user_id[mentioned.id][2])++ @patch("products.tasks.backend.push_dispatcher._enqueue_user")+ def test_thread_message_recipient_failures_are_isolated(self, mock_enqueue):+ mentioned = User.objects.create_user(email="[email protected]", first_name="Mina", password="password")+ self.organization.members.add(mentioned)+ mock_enqueue.side_effect = [RuntimeError("redis is down"), None]++ self._post_message(self.peer_client, "ping @[Mina]([email protected])")++ self.assertEqual(mock_enqueue.call_count, 2)++ @patch("products.tasks.backend.facade.api.TaskActivity.record", side_effect=RuntimeError("db is down"))+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ def test_mention_activity_failure_does_not_discard_push_recipients(self, mock_delay, _flag, _record):+ mentioned = User.objects.create_user(email="[email protected]", first_name="Mina", password="password")+ self.organization.members.add(mentioned)++ with self.captureOnCommitCallbacks(execute=True):+ self._post_message(self.peer_client, "ping @[Mina]([email protected])")++ self.assertEqual({call.args[0] for call in mock_delay.call_args_list}, {self.author.id, mentioned.id})+def test_mentions_resolve_case_insensitively(self):self._post_message(self.author_client, "cc @[Bob]([email protected])")self.assertEqual(len(self.peer_client.get(self._mentions_url()).json()), 1)@@ -383,7 +421,9 @@ class TaskMentionsAPITestCase(ChannelTaskAPITestCase):response = self.peer_client.get(self._mentions_url(), {"since": "not-a-date"})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- def test_mention_on_invisible_task_is_hidden(self):+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ def test_mention_on_invisible_task_is_hidden(self, mock_delay, _flag):private_task = Task.objects.create(team=self.team,created_by=self.author,@@ -391,8 +431,10 @@ class TaskMentionsAPITestCase(ChannelTaskAPITestCase):description="d",origin_product=Task.OriginProduct.USER_CREATED,)- self._post_message(self.author_client, "fyi @[Bob]([email protected])", task=private_task)+ with self.captureOnCommitCallbacks(execute=True):+ self._post_message(self.author_client, "fyi @[Bob]([email protected])", task=private_task)self.assertEqual(self.peer_client.get(self._mentions_url()).json(), [])+ mock_delay.assert_not_called()def test_mentions_are_team_scoped(self):other_team = Team.objects.create(organization=self.organization, name="Other Team")