: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
feat(mobile): scope push notifications and transfer chat alerts (#120742)
Chris Volzer230da673179d
diff --git a/docs/internal/task-run-api.md b/docs/internal/task-run-api.mdindex 2c267309c4d7..17e690b497e2 100644--- a/docs/internal/task-run-api.md+++ b/docs/internal/task-run-api.md@@ -49,6 +49,7 @@ A request may send the previous base branch or a branch that run worked on; anyThe bootstrap endpoint, `POST .../tasks/{task_id}/runs/`, does not accept the agent source.Agent-sourced runs use the read-only MCP permission preset.Run state updates cannot change or remove the run source or base branch.+The Slack actor fields `interaction_origin`, `slack_actor_user_id`, and `slack_actor_slack_user_id` are server-owned and cannot be changed, removed, or appended through run state updates.The `state` field must be a JSON object.Run responses omit internal cost accounting, including gateway request IDs.@@ -90,6 +91,7 @@ Successful captures are recorded for the event ingest token's lifetime so compleInteractive permission requests and questions can send a mobile push notification to the run's creator.Event ingest, the agent-proxy callback and the sandbox relay share a notification gate keyed by run and permission request ID.The gate retains each request for 24 hours after its push is successfully enqueued, so reconnecting does not repeat that notification.+This also applies when implementation or research work routes the push through report notifications.Enqueue failures and transaction rollbacks leave only the short cooldown, allowing a later callback or relay replay to retry.Requests share a 30-second per-run cooldown, applied before allocating a request deduplication key.The push dispatcher also shares its per-run cooldown with turn-end awaiting-input notifications.@@ -121,3 +123,40 @@ Other task streams include the effective summary.The two run-start tools require the agent-run feature flag.Sandbox tokens can use them only within the sandbox rules above.These operations are not idempotent. If a response is lost, inspect the task and its runs before you retry.++## Mobile notifications and task pickup++Use `X-PostHog-Client-Platform: mobile` to identify mobile requests.+Tasks created on mobile can send task notifications.+A successful mobile run start, resume, user message, or permission response also enables notifications for that user.+Reads, presence updates, configuration changes, and failed actions do not enable notifications.+This choice persists when the user returns to the web app.++Continuing a task on mobile stops that user's automatic Slack mentions and proactive private-thread updates.+Shared replies and answers to direct Slack requests remain available.+This includes replies that restart a completed task.+Other participants keep their notifications.++Task notifications cover run results, input requests, replies, handoffs, and verified PR merges or closes.+Active task presence suppresses notifications on those devices.+The server prevents duplicate PR outcome notifications.++Report notifications cover new reports, work updates, and PR review or outcome updates, regardless of task origin.+Active presence in the report's implementation or research task suppresses its work-update notifications across that user's devices.+Report discussions use task notification preferences.+Reports with `output_destinations.inbox: false` do not send notifications.+Report notifications require `posthog-code-mobile-push`.+Ordinary task notifications do not require this flag.++`PATCH /api/users/@me/` sets four booleans under `notification_settings`:++| Key | Controls |+| ------------------------------------ | ------------------------ |+| `mobile_push_enabled` | All mobile notifications |+| `mobile_push_tasks_enabled` | Chat and task updates |+| `mobile_push_reports_enabled` | New reports |+| `mobile_push_report_updates_enabled` | Report updates |++All four default to `true`.+The delivery worker checks that the account is active, along with current preferences and access, before it sends a queued notification.+Task notifications require current viewer access to the task resource when queued and when delivered.diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 4d864c6f1926..eab2e24f1d7c 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2524,6 +2524,7 @@ class TestUserAPI(APIBaseTest):{"notification_settings": {"plugin_disabled": False,+ "mobile_push_tasks_enabled": False,"discussions_mentioned": False,"error_tracking_issue_assigned": False,"project_weekly_digest_disabled": {123: True},@@ -2542,6 +2543,10 @@ class TestUserAPI(APIBaseTest):"plugin_disabled": False,"discussions_mentioned": False,"task_comments_slack_dm": True,+ "mobile_push_enabled": True,+ "mobile_push_tasks_enabled": False,+ "mobile_push_reports_enabled": True,+ "mobile_push_report_updates_enabled": True,"project_weekly_digest_disabled": {"123": True}, # Note: JSON converts int keys to strings"all_weekly_digest_disabled": True,"error_tracking_issue_assigned": False,@@ -2570,6 +2575,10 @@ class TestUserAPI(APIBaseTest):"plugin_disabled": False,"discussions_mentioned": False,"task_comments_slack_dm": True,+ "mobile_push_enabled": True,+ "mobile_push_tasks_enabled": False,+ "mobile_push_reports_enabled": True,+ "mobile_push_report_updates_enabled": True,"project_weekly_digest_disabled": {"123": True},"all_weekly_digest_disabled": True,"error_tracking_issue_assigned": False,@@ -2845,7 +2854,11 @@ class TestUserAPI(APIBaseTest):{"plugin_disabled": True, # Default value"discussions_mentioned": True, # Default value- "task_comments_slack_dm": True, # Default value+ "task_comments_slack_dm": True,+ "mobile_push_enabled": True,+ "mobile_push_tasks_enabled": True,+ "mobile_push_reports_enabled": True,+ "mobile_push_report_updates_enabled": True,"project_weekly_digest_disabled": {}, # Default value"all_weekly_digest_disabled": True,"error_tracking_issue_assigned": True, # Default valuediff --git a/posthog/api/test/test_user_push_token.py b/posthog/api/test/test_user_push_token.pyindex 882f750eeda9..141e9dc3ca81 100644--- a/posthog/api/test/test_user_push_token.py+++ b/posthog/api/test/test_user_push_token.py@@ -1,10 +1,20 @@-from posthog.test.base import APIBaseTest+from posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import patch+from django.db import connection+from django.test.utils import CaptureQueriesContext++from parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, Userfrom posthog.models.user_push_token import UserPushToken-from posthog.push_notifications import send_push_to_user+from posthog.push_notifications import mobile_push_delivery_allowed, send_push_to_user++from products.access_control.backend.models.access_control import AccessControl+from products.access_control.backend.models.role import Role, RoleMembership+from products.signals.backend.models import SignalReportclass TestUserPushTokenEndpoints(APIBaseTest):@@ -297,3 +307,72 @@ class TestPushNotifications(APIBaseTest):self.assertEqual(accepted, 0)# Token preserved — only DeviceNotRegistered prunes.self.assertTrue(UserPushToken.objects.filter(token="ExponentPushToken[a]").exists())+++class TestReportPushDelivery(BaseTest):+ @parameterized.expand(+ [+ ("member", True),+ ("project_denied", False),+ ("inactive", False),+ ("removed_member", False),+ ("organization_admin", True),+ ("reports_denied", False),+ ("role_granted", True),+ ("role_denied", False),+ ]+ )+ @patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=True)+ def test_report_delivery_checks_only_recipient_access(self, state: str, allowed: bool, _flag: object) -> None:+ self.organization.available_product_features = [+ {"key": feature, "name": feature}+ for feature in [AvailableFeature.ACCESS_CONTROL, AvailableFeature.ROLE_BASED_ACCESS]+ ]+ self.organization.save()+ membership = OrganizationMembership.objects.get(organization=self.organization, user=self.user)+ membership.level = (+ OrganizationMembership.Level.ADMIN if state == "organization_admin" else OrganizationMembership.Level.MEMBER+ )+ membership.save()+ User.objects.create_and_join(self.organization, "[email protected]", None)+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="Example report")+ AccessControl.objects.create(+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"+ )+ if state.startswith("role_"):+ role = Role.objects.create(organization=self.organization, name="Report readers")+ RoleMembership.objects.create(role=role, user=self.user, organization_member=membership)+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ role=role,+ access_level="member" if state == "role_granted" else "none",+ )+ else:+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ organization_member=membership,+ access_level="none" if state in {"project_denied", "organization_admin"} else "member",+ )+ if state == "inactive":+ User.objects.filter(id=self.user.id).update(is_active=False)+ elif state == "removed_member":+ membership.delete()+ elif state == "reports_denied":+ AccessControl.objects.create(team=self.team, resource="task", access_level="none")++ with CaptureQueriesContext(connection) as queries:+ result = mobile_push_delivery_allowed(+ self.user,+ {"type": "report", "project_id": self.team.id, "report_id": str(report.id)},+ )++ self.assertEqual(result, allowed)+ membership_queries = [+ query["sql"] for query in queries if 'FROM "posthog_organizationmembership"' in query["sql"]+ ]+ for query in membership_queries:+ self.assertIn(f'"user_id" = {self.user.id}', query)diff --git a/posthog/models/user.py b/posthog/models/user.pyindex a19aa97a13d8..dd7556fc1c3e 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -52,6 +52,10 @@ class Notifications(TypedDict, total=False):] # Maps team_id (str) to enabled status (True = included). None/missing = not configured (auto-select on first digest).discussions_mentioned: booltask_comments_slack_dm: bool # Slack DM for task comment mentions, replies, and owned items+ mobile_push_enabled: bool+ mobile_push_tasks_enabled: bool+ mobile_push_reports_enabled: bool+ mobile_push_report_updates_enabled: boolproject_weekly_digest_disabled: dict[str, Any] # Maps project ID to disabled status, str is the team_id as a stringall_weekly_digest_disabled: booldata_pipeline_error_threshold: (@@ -85,6 +89,10 @@ NOTIFICATION_DEFAULTS: Notifications = {"error_tracking_weekly_digest": True, # Error tracking weekly digest enabled by default"discussions_mentioned": True, # Mentions in comments enabled by default"task_comments_slack_dm": True,+ "mobile_push_enabled": True,+ "mobile_push_tasks_enabled": True,+ "mobile_push_reports_enabled": True,+ "mobile_push_report_updates_enabled": True,"project_weekly_digest_disabled": {}, # Empty dict by default - no projects disabled"all_weekly_digest_disabled": False, # Weekly digests enabled by default"data_pipeline_error_threshold": 0.01, # Default: notify when failure rate exceeds 1%diff --git a/posthog/push_notifications.py b/posthog/push_notifications.pyindex aad2d8c71456..e9a4dd4420a5 100644--- a/posthog/push_notifications.py+++ b/posthog/push_notifications.py@@ -16,10 +16,11 @@ from __future__ import annotationsimport uuidfrom collections.abc import Iterable-from typing import Any, cast+from typing import Any, Literal, castimport requestsimport structlog+import posthoganalyticsfrom posthog.models.user import Userfrom posthog.models.user_push_token import UserPushToken@@ -31,6 +32,76 @@ EXPO_PUSH_API_TIMEOUT_SECONDS = 10EXPO_PUSH_BATCH_SIZE = 100+MobilePushCategory = Literal["tasks", "reports", "report_updates"]+++def mobile_push_preference_enabled(user: User, category: MobilePushCategory) -> bool:+ preferences = user.notification_settings+ enabled = {+ "tasks": preferences.get("mobile_push_tasks_enabled", True),+ "reports": preferences.get("mobile_push_reports_enabled", True),+ "report_updates": preferences.get("mobile_push_report_updates_enabled", True),+ }+ return preferences.get("mobile_push_enabled", True) and enabled[category]+++def mobile_push_delivery_allowed(user: User, data: dict[str, Any] | None) -> bool:+ if not user.is_active:+ return False++ # Re-read eligibility on the worker: a queued push can outlive a preference or access change.+ payload = data or {}+ if payload.get("type") == "report":+ if not posthoganalytics.feature_enabled(+ "posthog-code-mobile-push", user.distinct_id or f"user_{user.id}", send_feature_flag_events=False+ ):+ return False+ from products.access_control.backend.facade.user_access_control import (+ UserAccessControl, # noqa: PLC0415 — keep access control off the startup path+ )+ from products.signals.backend.models import SignalReport # noqa: PLC0415 — keep signals off the startup path+ from products.signals.backend.report_access import may_read_reports # noqa: PLC0415+ from products.signals.backend.scout_authorship import report_is_hidden_from_inbox # noqa: PLC0415++ category: MobilePushCategory = (+ "reports" if payload.get("notificationKind") == "report_visible" else "report_updates"+ )+ if not mobile_push_preference_enabled(user, category):+ return False+ project_id = payload.get("project_id")+ report_id = payload.get("report_id")+ if not isinstance(project_id, (int, str)) or not isinstance(report_id, str):+ return False+ report = (+ SignalReport.objects.filter(team_id=project_id, id=report_id)+ .exclude(status__in=[SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED])+ .select_related("team")+ .first()+ )+ return bool(+ report+ and not report_is_hidden_from_inbox(report.team_id, str(report.id))+ and User.objects.filter(+ id=user.id,+ is_active=True,+ organization_membership__organization_id=report.team.organization_id,+ ).exists()+ and UserAccessControl(user=user, team=report.team).has_project_access+ and may_read_reports(user=user, team=report.team)+ )++ if not mobile_push_preference_enabled(user, "tasks") or not payload.get("taskId"):+ return False+ project_id = payload.get("projectId")+ if not isinstance(project_id, int) or not user.teams.filter(id=project_id).exists():+ return False+ from products.tasks.backend.facade.api import (+ task_mobile_push_delivery_allowed, # noqa: PLC0415 — keep product imports lazy+ )++ return task_mobile_push_delivery_allowed(task_id=str(payload["taskId"]), team_id=project_id, user_id=user.id)++def send_push_to_user(user: User,*,@@ -54,6 +125,16 @@ def send_push_to_user(``DeviceNotRegistered`` are deleted for this user so we stop trying todeliver to dead devices."""+ category: MobilePushCategory = (+ "reports"+ if (data or {}).get("notificationKind") == "report_visible"+ else "report_updates"+ if (data or {}).get("type") == "report"+ else "tasks"+ )+ if not mobile_push_preference_enabled(user, category):+ return 0+qs = UserPushToken.objects.filter(user=user)if suppressed_push_token_ids:qs = qs.exclude(id__in=list(suppressed_push_token_ids))diff --git a/posthog/tasks/push_notifications.py b/posthog/tasks/push_notifications.pyindex 29d5874128ba..f88b59a1921a 100644--- a/posthog/tasks/push_notifications.py+++ b/posthog/tasks/push_notifications.py@@ -15,7 +15,7 @@ from celery import shared_taskfrom prometheus_client import Counterfrom posthog.models.user import User-from posthog.push_notifications import send_push_to_user+from posthog.push_notifications import mobile_push_delivery_allowed, send_push_to_userfrom posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)@@ -56,6 +56,9 @@ def send_user_push(returntry:+ if not mobile_push_delivery_allowed(user, data):+ PUSH_DELIVERY_OUTCOMES_TOTAL.labels(kind=notification_kind, outcome="ineligible").inc()+ returnaccepted = send_push_to_user(user,title=title,diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex 4dfdc677a309..e7b3d88d5ed1 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -1741,3 +1741,27 @@ def disable_scout_for_product(*, team_id: int, skill_name: str, source_product:.delete())return deleted > 0+++def notify_report_task_push(+ *,+ team_id: int,+ task_id: str,+ run_id: str,+ kind: str,+ pull_request_url: str | None = None,+ on_enqueued: Callable[[], None] | None = None,+) -> bool:+ from products.signals.backend.inbox_push_notifications import (+ notify_report_task_update, # noqa: PLC0415 — keep the sender off the facade import path+ )+ from products.tasks.backend.models import TaskRun # noqa: PLC0415 — legacy task storage shared with signals++ task_run = TaskRun.objects.filter(team_id=team_id, task_id=task_id, id=run_id).select_related("task").first()+ return (+ notify_report_task_update(+ task_run=task_run, kind=kind, pull_request_url=pull_request_url, on_enqueued=on_enqueued+ )+ if task_run is not None+ else False+ )diff --git a/products/signals/backend/inbox_push_notifications.py b/products/signals/backend/inbox_push_notifications.pyindex 39d74dc7c39d..9857e35437e7 100644--- a/products/signals/backend/inbox_push_notifications.py+++ b/products/signals/backend/inbox_push_notifications.py@@ -1,9 +1,9 @@"""Mobile push notifications for inbox reports.-Two events reach the PostHog mobile app: a report first surfaces with the person as a suggested-reviewer, and a report's pull request becomes ready for review. Both use the Expo sender and the-feature flag of the task-run pushes in `products.tasks.backend.push_dispatcher`, so one flag turns-all mobile pushes on or off for a person.+Reports notify when first visible to a suggested reviewer, when their pull requests become ready+for review, and at meaningful milestones of implementation or research work. Report pushes use the+Expo sender and the `posthog-code-mobile-push` feature flag. Task notification preferences and+source eligibility apply independently; ordinary task pushes do not require the report feature flag.Recipients resolve on a worker after the triggering write commits, because a report born visiblegets its reviewers later in the same transaction, and the queries must not hold up a summary@@ -13,19 +13,40 @@ transition or the pull request sync that triggered it.from __future__ import annotations-from collections.abc import Collection+import hashlib+from collections.abc import Callable, Collection+from typing import TYPE_CHECKINGfrom django.db import transaction+from django.db.models import Qimport structlogimport posthoganalyticsfrom posthog.models.user import User+from posthog.push_notifications import MobilePushCategory, mobile_push_preference_enabledfrom posthog.tasks.push_notifications import send_user_push+from products.signals.backend.artefact_schemas import (+ SIGNALS_PRODUCT,+ TASK_RUN_TYPE_IMPLEMENTATION,+ TASK_RUN_TYPE_RESEARCH,+)from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest+from products.signals.backend.report_access import may_read_reportsfrom products.signals.backend.report_claims import get_active_claims, responsible_user+from products.signals.backend.scout_authorship import report_is_hidden_from_inboxfrom products.signals.backend.slack_inbox_notifications import resolve_org_suggested_reviewer_user_ids+from products.tasks.backend.facade.api import (+ claim_mobile_push_cooldown,+ enqueue_task_mobile_pr_outcome,+ release_mobile_push_cooldown,+ task_mobile_push_suppressed_token_ids,+ task_mobile_push_user_ids,+)++if TYPE_CHECKING:+ from products.tasks.backend.models import TaskRunlogger = structlog.get_logger(__name__)@@ -152,13 +173,107 @@ def notify_pull_request_ready(*, team_id: int, pull_request_id: str) -> list[intkind="pull_request_ready",title=PULL_REQUEST_READY_TITLE,body=report.title or f"{pull_request.repository}#{pull_request.number}",+ dedupe_subject=f"pull_request:{pull_request.id}:ready",+ pull_request_id=str(pull_request.id),))return pushed-def _push_report(report: SignalReport, users: Collection[User], *, kind: str, title: str, body: str) -> list[int]:- if not users:+def notify_report_task_update(+ *,+ task_run: TaskRun,+ kind: str,+ pull_request_url: str | None = None,+ on_enqueued: Callable[[], None] | None = None,+) -> bool:+ """Route meaningful milestones of actual report work through report preferences and links."""+ task = task_run.task+ reports = list(+ SignalReport.objects.filter(team_id=task.team_id)+ .filter(Q(id=task.signal_report_id) | SignalReport.reports_for_task_ids_filter([task.id], team_id=task.team_id))+ .select_related("team")+ .order_by("created_at", "id")+ )+ task_runs = SignalReport.associated_task_runs_for_reports(+ report_ids=[str(report.id) for report in reports], team_id=task.team_id+ )+ reports = [+ report+ for report in reports+ if any(+ run.task_id == str(task.id)+ and run.product == SIGNALS_PRODUCT+ and run.type in {TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_RESEARCH}+ for run in task_runs.get(str(report.id), [])+ )+ ]+ if not reports:+ return False+ if task.is_scout_experiment:+ return True+ report_ids = [str(report.id) for report in reports]+ reviewers = resolve_org_suggested_reviewer_user_ids(team_id=task.team_id, report_ids=report_ids)+ claims = get_active_claims(team_id=task.team_id, report_ids=report_ids)+ mobile_recipient_ids = task_mobile_push_user_ids(task_id=str(task.id), team_id=task.team_id)+ pushed: set[int] = set()+ for report in reports:+ if report.status in _HIDDEN_STATUSES or report.first_visible_at is None:+ continue+ recipient_ids = reviewers.get(str(report.id), set()) | mobile_recipient_ids+ claim = claims.get(str(report.id))+ claimant = responsible_user(claim) if claim is not None else None+ if claimant is not None:+ recipient_ids.add(claimant.id)+ if task.created_by_id is not None:+ recipient_ids.add(task.created_by_id)+ milestone = {+ "completed": "work finished",+ "turn_completed": "work finished",+ "failed": "work failed",+ "cancelled": "work was cancelled",+ "awaiting": "needs your input",+ "pr_merged": "pull request was merged",+ "pr_closed": "pull request was closed",+ }[kind]+ pushed.update(+ _push_report(+ report,+ list(report.team.all_users_with_access().filter(id__in=recipient_ids - pushed).order_by("id")),+ kind=f"report_{kind}",+ title="Report update",+ body=f'"{report.title or "Untitled report"}" {milestone}',+ dedupe_subject=(+ f"pr:{task.id}:{hashlib.sha256(pull_request_url.encode()).hexdigest()}:{kind}"+ if pull_request_url+ else f"task_run:{task_run.id}:{kind}"+ ),+ cooldown_seconds=30 if kind in {"awaiting", "turn_completed"} else 600,+ task_run_id=str(task_run.id),+ pull_request_url=pull_request_url,+ task_id=str(task.id),+ on_enqueued=on_enqueued,+ )+ )+ return True+++def _push_report(+ report: SignalReport,+ users: Collection[User],+ *,+ kind: str,+ title: str,+ body: str,+ dedupe_subject: str | None = None,+ cooldown_seconds: int = 600,+ task_run_id: str | None = None,+ pull_request_id: str | None = None,+ pull_request_url: str | None = None,+ task_id: str | None = None,+ on_enqueued: Callable[[], None] | None = None,+) -> list[int]:+ if not users or report_is_hidden_from_inbox(report.team_id, str(report.id)):return []data = {"type": "report",@@ -167,12 +282,73 @@ def _push_report(report: SignalReport, users: Collection[User], *, kind: str, ti"notificationKind": kind,"url": f"posthog://inbox/{report.id}",}+ if task_run_id is not None:+ data["taskRunId"] = task_run_id+ if pull_request_id is not None:+ data["pullRequestId"] = pull_request_id+ if pull_request_url is not None:+ data["pullRequestUrl"] = pull_request_urlpushed: list[int] = []+ # The project access check also covers a claimant who has since lost access to the project.for user in users:try:- if not _push_enabled(user):+ category: MobilePushCategory = "reports" if kind == "report_visible" else "report_updates"+ if not mobile_push_preference_enabled(user, category) or not _push_enabled(user):+ continue+ if not may_read_reports(user=user, team=report.team):continue- send_user_push.delay(user.id, title, body, data)+ subject = dedupe_subject or f"{report.id}:{kind}"+ cooldown_key = f"report_push:{subject}:{user.id}"++ def dispatch(user: User = user, cooldown_key: str = cooldown_key) -> bool:+ try:+ if not claim_mobile_push_cooldown(cooldown_key, timeout_seconds=cooldown_seconds):+ return False+ try:++ def enqueue() -> None:+ if task_id is not None:+ suppressed = task_mobile_push_suppressed_token_ids(+ user_id=user.id, task_id=task_id, team_id=report.team_id+ )+ send_user_push.delay(user.id, title, body, data, suppressed)+ else:+ send_user_push.delay(user.id, title, body, data)++ if pull_request_url is not None and task_id is not None:+ enqueued = enqueue_task_mobile_pr_outcome(+ task_id=task_id,+ team_id=report.team_id,+ user_id=user.id,+ pr_url=pull_request_url,+ kind=kind,+ enqueue=enqueue,+ )+ else:+ enqueue()+ enqueued = True+ if enqueued and on_enqueued is not None:+ on_enqueued()+ return enqueued+ except Exception:+ release_mobile_push_cooldown(cooldown_key)+ raise+ except Exception:+ logger.warning(+ "signals.inbox_push.enqueue_failed",+ team_id=report.team_id,+ report_id=str(report.id),+ user_id=user.id,+ kind=kind,+ exc_info=True,+ )+ return False++ if kind in {"report_visible", "pull_request_ready"}:+ if not dispatch():+ continue+ else:+ transaction.on_commit(dispatch, robust=True)pushed.append(user.id)except Exception:logger.warning(diff --git a/products/signals/backend/test/test_inbox_push_notifications.py b/products/signals/backend/test/test_inbox_push_notifications.pyindex 4f44e7bacdc5..0e16cee4c3fa 100644--- a/products/signals/backend/test/test_inbox_push_notifications.py+++ b/products/signals/backend/test/test_inbox_push_notifications.py@@ -4,19 +4,28 @@ from datetime import UTC, datetime, timedeltafrom posthog.test.base import BaseTestfrom unittest.mock import call, patch-from django.db import connection+from django.db import connection, transactionfrom django.test.utils import CaptureQueriesContext+from django.utils import timezonefrom parameterized import parameterizedfrom social_django.models import UserSocialAuthfrom posthog.constants import AvailableFeaturefrom posthog.models import Team, User+from posthog.models.user_push_token import UserPushToken+from posthog.tasks.push_notifications import send_user_pushfrom products.access_control.backend.models.access_control import AccessControlfrom products.signals.backend.artefact_attribution import ArtefactAttribution-from products.signals.backend.inbox_push_notifications import notify_pull_request_ready-from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest+from products.signals.backend.inbox_push_notifications import _push_report, notify_pull_request_ready+from products.signals.backend.models import (+ SignalReport,+ SignalReportArtefact,+ SignalReportPullRequest,+ SignalScoutConfig,+ SignalScoutRun,+)from products.signals.backend.pull_requests import (PullRequestStateSource,link_pull_request,@@ -24,9 +33,20 @@ from products.signals.backend.pull_requests import (update_pull_request_state,)from products.signals.backend.report_assignments import PullRequestDetails, create_claim+from products.signals.backend.task_run_artefacts import append_task_run_artefact+from products.tasks.backend.facade.testing import (+ create_task_presence,+ notify_task_pull_request_outcome,+ notify_task_run_awaiting_input,+ notify_task_run_cancelled,+ notify_task_run_completed,+ notify_task_run_failed,+ notify_task_run_turn_completed,+ tasks_cache,+)# Task ORM model needed for a task-claim fixture; the tasks facade exposes DTOs only.-from products.tasks.backend.models import Task+from products.tasks.backend.models import Task, TaskRunPR_URL = "https://github.com/posthog/posthog/pull/123"VISIBLE_AT = datetime(2026, 1, 1, tzinfo=UTC)@@ -35,6 +55,7 @@ VISIBLE_AT = datetime(2026, 1, 1, tzinfo=UTC)class TestInboxPushNotifications(BaseTest):def setUp(self) -> None:super().setUp()+ tasks_cache().clear()self.reviewer = User.objects.create_and_join(self.organization, "[email protected]", None)send_patch = patch("products.signals.backend.inbox_push_notifications.send_user_push.delay")flag_patch = patch(@@ -216,6 +237,7 @@ class TestInboxPushNotifications(BaseTest):expected_users = sorted([self.user.id, self.reviewer.id, login_reviewer.id]) if has_project_access else []assert first_pushed == expected_usersself.send_push.reset_mock()+ tasks_cache().clear()for index in range(1, 5):add_linked_report(index)@@ -236,3 +258,294 @@ class TestInboxPushNotifications(BaseTest):assert [push.args[0] for push in self.send_push.call_args_list] == expected_usersassert all(push.args[3]["report_id"] == str(oldest_report.id) for push in self.send_push.call_args_list)assert len(many_report_queries) == len(one_report_queries)++ @parameterized.expand(+ [+ ("web_implementation", "implementation", False, True, notify_task_run_completed),+ ("cross_team_implementation", "implementation", False, False, notify_task_run_completed),+ ("slack_implementation", "implementation", False, True, notify_task_run_failed),+ ("web_research", "research", False, True, notify_task_run_awaiting_input),+ ("web_discussion", "discussion", False, False, notify_task_run_cancelled),+ ("mobile_discussion", "discussion", True, True, notify_task_run_turn_completed),+ ("cancelled_implementation", "implementation", False, True, notify_task_run_cancelled),+ ("turn_implementation", "implementation", False, True, notify_task_run_turn_completed),+ ("picked_up_implementation", "implementation", False, True, notify_task_run_completed),+ ]+ )+ def test_report_work_and_discussions_use_their_own_channels(self, name, relationship, mobile, expect_push, notify):+ report = self._report(SignalReport.Status.READY, first_visible_at=VISIBLE_AT)+ self._add_reviewers(report, self.user)+ task = Task.objects.create(+ team=self.team,+ title="Internal task",+ created_by=self.user,+ origin_product=Task.OriginProduct.SLACK if name.startswith("slack") else Task.OriginProduct.SIGNAL_REPORT,+ signal_report=None if name == "cross_team_implementation" else report,+ state={"created_on_mobile": mobile},+ )+ if name == "picked_up_implementation":+ picked = User.objects.create_and_join(self.organization, "[email protected]", None)+ task.state = {**(task.state or {}), "mobile_push_user_ids": [picked.id]}+ task.save(update_fields=["state"])+ run = TaskRun.objects.create(task=task, team=self.team)+ artefact = append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type=relationship,+ task_id=str(task.id),+ run_id=str(run.id),+ )+ if name == "cross_team_implementation":+ other_team = Team.objects.create(organization=self.organization)+ SignalReportArtefact.objects.filter(team_id=self.team.id, id=artefact.id).update(team_id=other_team.id)+ with (+ self.captureOnCommitCallbacks(execute=True),+ patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=True),+ ):+ notify(task_run_id=str(run.id), team_id=run.team_id)+ notify(task_run_id=str(run.id), team_id=run.team_id)+ self.assertEqual(self.send_push.call_count, 2 if name == "picked_up_implementation" else int(expect_push))+ if expect_push and relationship != "discussion":+ self.assertEqual(self.send_push.call_args.args[3]["type"], "report")+ self.assertEqual(self.send_push.call_args.args[3]["taskRunId"], str(run.id))+ self.assertIn(report.title, self.send_push.call_args.args[2])+ self.assertNotIn(task.title, self.send_push.call_args.args[2])++ @parameterized.expand(+ [+ ("active", "implementation", notify_task_run_completed),+ ("expired", "research", notify_task_run_awaiting_input),+ ("other_task", "implementation", notify_task_run_turn_completed),+ ]+ )+ def test_report_work_respects_task_presence(self, presence, relationship, notify) -> None:+ report = self._report(SignalReport.Status.READY, first_visible_at=VISIBLE_AT)+ self._add_reviewers(report, self.user, self.reviewer)+ task = Task.objects.create(team=self.team, created_by=self.user, signal_report=report)+ run = TaskRun.objects.create(task=task, team=self.team)+ append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type=relationship,+ task_id=str(task.id),+ run_id=str(run.id),+ )+ tokens = [+ UserPushToken.objects.create(user=self.user, token=f"ExponentPushToken[device-{index}]", platform="ios")+ for index in range(2)+ ]+ watched_task = Task.objects.create(team=self.team, created_by=self.user) if presence == "other_task" else task+ create_task_presence(+ team_id=self.team.id,+ task_id=watched_task.id,+ user_id=self.user.id,+ push_token_id=tokens[0].id,+ expires_at=timezone.now() + timedelta(minutes=-1 if presence == "expired" else 1),+ )+ with self.captureOnCommitCallbacks(execute=True):+ notify(task_run_id=str(run.id), team_id=run.team_id)+ pushes = {push.args[0]: push.args for push in self.send_push.call_args_list}+ self.assertEqual(set(pushes), {self.user.id, self.reviewer.id})+ self.assertEqual(pushes[self.user.id][3]["type"], "report")+ self.assertCountEqual(+ pushes[self.user.id][4], [str(token.id) for token in tokens] if presence == "active" else []+ )+ self.assertEqual(pushes[self.reviewer.id][4], [])++ @parameterized.expand(+ [+ (outcome, merged, failure)+ for outcome, merged in [("merged", True), ("closed", False)]+ for failure in (None, "redis", "broker", "rollback")+ ]+ )+ def test_report_pr_outcomes_use_report_preferences_and_pr_identity(self, outcome, merged, failure):+ self.user.partial_notification_settings = {"mobile_push_tasks_enabled": False}+ self.user.save(update_fields=["partial_notification_settings"])+ report = self._report(SignalReport.Status.READY, first_visible_at=VISIBLE_AT)+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Internal work",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report=report,+ )+ run = TaskRun.objects.create(task=task, team=self.team)+ append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type="implementation",+ task_id=str(task.id),+ run_id=str(run.id),+ )+ if failure is not None:++ def notify() -> None:+ notify_task_pull_request_outcome(+ task_id=str(task.id),+ run_id=str(run.id),+ team_id=self.team.id,+ pr_url="https://github.com/example/project/pull/1",+ merged=merged,+ )++ if failure == "rollback":+ with self.captureOnCommitCallbacks(execute=True):+ with self.assertRaises(RuntimeError), transaction.atomic():+ notify()+ raise RuntimeError("rollback")+ else:+ boundary = (+ patch.object(tasks_cache(), "add", side_effect=RuntimeError("redis unavailable"))+ if failure == "redis"+ else patch.object(self.send_push, "side_effect", RuntimeError("broker unavailable"))+ )+ with boundary, self.captureOnCommitCallbacks(execute=True):+ notify()+ task.refresh_from_db()+ self.assertEqual((task.state or {}).get("mobile_push_pr_outcomes", []), [])+ self.send_push.reset_mock(side_effect=True)+ for number in (1, 1, 2):+ if number == 2 or self.send_push.call_count:+ tasks_cache().clear()+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_pull_request_outcome(+ task_id=str(task.id),+ run_id=str(run.id),+ team_id=self.team.id,+ pr_url=f"https://github.com/example/project/pull/{number}",+ merged=merged,+ )+ self.assertEqual(self.send_push.call_count, 2)+ args = self.send_push.call_args.args+ self.assertEqual(args[1:3], ("Report update", f'"{report.title}" pull request was {outcome}'))+ self.assertEqual(args[3]["type"], "report")+ self.assertEqual(args[3]["notificationKind"], f"report_pr_{outcome}")+ self.assertEqual(args[3]["pullRequestUrl"], "https://github.com/example/project/pull/2")++ @parameterized.expand([("unpublished",), ("hidden",), ("preferences",), ("lost_access",)])+ def test_report_work_suppresses_unavailable_updates(self, reason):+ report = self._report(+ SignalReport.Status.SUPPRESSED if reason == "hidden" else SignalReport.Status.READY,+ first_visible_at=None if reason == "unpublished" else VISIBLE_AT,+ )+ self._add_reviewers(report, self.user)+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Internal work",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report=report,+ )+ run = TaskRun.objects.create(task=task, team=self.team)+ append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type="implementation",+ task_id=str(task.id),+ run_id=str(run.id),+ )+ if reason == "preferences":+ self.user.partial_notification_settings = {"mobile_push_report_updates_enabled": False}+ self.user.save(update_fields=["partial_notification_settings"])+ if reason == "lost_access":+ self.organization.members.remove(self.user)+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_run_completed(task_run_id=str(run.id), team_id=run.team_id)+ self.send_push.assert_not_called()++ @parameterized.expand(+ [+ ("mobile_push_enabled", "report_visible", False),+ ("mobile_push_reports_enabled", "report_visible", False),+ ("mobile_push_report_updates_enabled", "report_completed", False),+ ("mobile_push_tasks_enabled", "report_completed", True),+ ("mobile_push_reports_enabled", "report_completed", True),+ ("mobile_push_report_updates_enabled", "report_visible", True),+ ]+ )+ @patch("posthog.tasks.push_notifications.send_push_to_user", return_value=1)+ def test_report_preferences_select_category_at_delivery(self, key, kind, allowed, mock_send):+ report = self._report(SignalReport.Status.READY, first_visible_at=VISIBLE_AT)+ self.user.partial_notification_settings = {key: False}+ self.user.save(update_fields=["partial_notification_settings"])+ send_user_push(+ self.user.id,+ "Report",+ "Update",+ {"type": "report", "project_id": self.team.id, "report_id": str(report.id), "notificationKind": kind},+ )+ self.assertEqual(mock_send.call_count, int(allowed))++ @parameterized.expand(+ [+ ("report_visible", False, False, False),+ ("pull_request_ready", False, False, False),+ ("report_completed", False, False, False),+ ("report_pr_merged", False, False, False),+ ("report_completed", None, False, True),+ ("report_completed", True, False, True),+ ("report_completed", False, True, True),+ ]+ )+ @patch("posthog.tasks.push_notifications.send_push_to_user", return_value=1)+ def test_report_inbox_destination_gates_producer_and_queued_delivery(+ self, kind: str, inbox: bool | None, editor_only: bool, allowed: bool, mock_send+ ) -> None:+ report = self._report(SignalReport.Status.READY, first_visible_at=VISIBLE_AT)+ config = SignalScoutConfig.objects.for_team(self.team.id).create(+ team=self.team,+ skill_name="signals-scout-example",+ output_destinations={} if inbox is None else {"inbox": inbox},+ )+ task = Task.objects.create(team=self.team, created_by=self.user)+ run = TaskRun.objects.create(task=task, team=self.team)+ SignalScoutRun.objects.for_team(self.team.id).create(+ team=self.team,+ task_run=run,+ scout_config=config,+ skill_name=config.skill_name,+ skill_version=1,+ emitted_report_ids=[] if editor_only else [str(report.id)],+ edited_report_ids=[str(report.id)] if editor_only else [],+ )+ with self.captureOnCommitCallbacks(execute=True):+ _push_report(report, [self.user], kind=kind, title="Report update", body="Updated")+ self.assertEqual(self.send_push.call_count, int(allowed))+ if kind == "report_completed" and not allowed:+ task.state = {"created_on_mobile": True}+ task.signal_report = report+ task.save(update_fields=["state", "signal_report"])+ append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type="implementation",+ task_id=str(task.id),+ run_id=str(run.id),+ )+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_run_completed(task_run_id=str(run.id), team_id=run.team_id)+ self.send_push.assert_not_called()+ send_user_push(+ self.user.id,+ "Report update",+ "Updated",+ {+ "type": "report",+ "project_id": self.team.id,+ "report_id": str(report.id),+ "notificationKind": kind,+ },+ )+ self.assertEqual(mock_send.call_count, int(allowed))+ if allowed and not editor_only:+ config.output_destinations = {"inbox": False}+ config.save(update_fields=["output_destinations"])+ queued_user_id, queued_title, queued_body, queued_data = self.send_push.call_args.args+ send_user_push(queued_user_id, queued_title, queued_body, queued_data)+ self.assertEqual(mock_send.call_count, 1)diff --git a/products/slack_app/backend/services/task_notifications.py b/products/slack_app/backend/services/task_notifications.pynew file mode 100644index 000000000000..7c950a6facb0--- /dev/null+++ b/products/slack_app/backend/services/task_notifications.py@@ -0,0 +1,40 @@+from posthog.models.user_integration import UserIntegration++from products.slack_app.backend.models import SlackThreadTaskMapping+++def task_slack_notifications_muted(+ *, integration_id: int, channel: str, thread_ts: str, slack_user_id: str | None, private_only: bool = False+) -> bool:+ if not slack_user_id and not private_only:+ return False+ mappings = SlackThreadTaskMapping.objects.filter(+ integration_id=integration_id, channel=channel, thread_ts=thread_ts+ )+ if private_only:+ mappings = mappings.filter(conversation_type=SlackThreadTaskMapping.ConversationType.IM)+ mapping = mappings.first()+ if mapping is None:+ return False+ slack_user_id = slack_user_id or mapping.mentioning_slack_user_id++ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415 — keeps tasks off Slack startup++ user_ids = set(+ UserIntegration.objects.filter(+ kind=UserIntegration.IntegrationKind.SLACK,+ integration_id=slack_user_id,+ config__slack_team_id=mapping.slack_workspace_id,+ ).values_list("user_id", flat=True)+ )+ run = tasks_facade.get_task_run(mapping.task_run_id, team_id=mapping.team_id)+ if run is not None:+ actor_id = run.state.get("slack_actor_user_id")+ if run.state.get("slack_actor_slack_user_id") == slack_user_id and type(actor_id) is int:+ user_ids.add(actor_id)+ elif mapping.mentioning_slack_user_id == slack_user_id and run.created_by_id is not None:+ user_ids.add(run.created_by_id)+ return any(+ tasks_facade.task_mobile_push_taken_over(task_id=str(mapping.task_id), team_id=mapping.team_id, user_id=user_id)+ for user_id in user_ids+ )diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex f59de50935de..2503c5772067 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -42,6 +42,7 @@ from products.slack_app.backend.services.slack_messages import (slack_message_exists,turn_feedback_block,)+from products.slack_app.backend.services.task_notifications import task_slack_notifications_mutedif TYPE_CHECKING:from posthog.models.user import User@@ -258,6 +259,7 @@ class SlackThreadHandler:) -> None:self.context = contextself.run_footer = run_footer or RunFooter()+ self.task_run_id = self.run_footer.run_id# Beside the footer rather than in it: a trace id belongs to one turn, and the# next turn in the same thread has its own.self.turn_trace_id = turn_trace_id@@ -271,6 +273,8 @@ class SlackThreadHandler:self._bot_user_id: str | None = Noneself._fork_flag: bool | None = Noneself._last_answer: _PostedAnswer | None = None+ # Safe to keep for the handler's life: each activity call builds a fresh handler.+ self._muted_cache: dict[tuple[str | None, bool], bool] = {}self.stream_ended = False@classmethod@@ -288,7 +292,7 @@ class SlackThreadHandler:The footer's project segment is judged against the install this context posts through,so the footer always loads with ``context.integration_id``."""- return cls(+ handler = cls(context,load_run_footer(run_id, integration_id=context.integration_id),actor_slack_user_id=actor_slack_user_id,@@ -296,6 +300,36 @@ class SlackThreadHandler:turn_person_message=turn_person_message,)+ handler.task_run_id = str(run_id) if run_id is not None else None+ return handler++ def notification_target(self, slack_user_id: str | None) -> str | None:+ if not self.task_run_id:+ return slack_user_id+ if self._notifications_muted(slack_user_id, private_only=False):+ return None+ return slack_user_id++ def notification_text(self, text: str, slack_user_id: str | None) -> str:+ if slack_user_id and self.notification_target(slack_user_id) is None:+ return re.sub(rf"^\s*<@{re.escape(slack_user_id)}(?:\|[^>]+)?>\s*", "", text, count=1)+ return text++ def proactive_notifications_muted(self) -> bool:+ return self._notifications_muted(self.context.mentioning_slack_user_id, private_only=True)++ def _notifications_muted(self, slack_user_id: str | None, *, private_only: bool) -> bool:+ key = (slack_user_id, private_only)+ if key not in self._muted_cache:+ self._muted_cache[key] = task_slack_notifications_muted(+ integration_id=self.context.integration_id,+ channel=self.context.channel,+ thread_ts=self.context.thread_ts,+ slack_user_id=slack_user_id,+ private_only=private_only,+ )+ return self._muted_cache[key]+def _get_integration(self) -> Integration:if self._integration is None:# nosemgrep: idor-lookup-without-team (internal context, ID from Slack event mapping)@@ -459,7 +493,8 @@ class SlackThreadHandler:"""chat.startStream in plan-block mode. Seed with plan-block steps, amarkdown_text chunk, or both. The plan block stays where its first steplands, and later task_update chunks change that block in place."""- if not self.actor_slack_user_id:+ recipient = self.notification_target(self.actor_slack_user_id)+ if not recipient:return Noneif first_markdown_text:first_markdown_text = self._with_leading_mention(first_markdown_text)@@ -477,7 +512,7 @@ class SlackThreadHandler:response = client.chat_startStream(channel=self.context.channel,thread_ts=self.context.thread_ts,- recipient_user_id=self.actor_slack_user_id,+ recipient_user_id=recipient,recipient_team_id=integration.integration_id,task_display_mode="plan",chunks=chunks,@@ -512,7 +547,7 @@ class SlackThreadHandler:def stop_status_stream(self,- ts: str,+ ts: str | None,complete_task_id: str | None = None,complete_task_title: str | None = None,final_markdown: str | None = None,@@ -529,8 +564,17 @@ class SlackThreadHandler:chart cards sit under the text that describes them. The provenance footer is a `blocks`chunk because a `context` block is the only way to get muted text.- When Slack already closed the stream, the answer goes out as a plain thread reply,+ With no stream timestamp, the answer goes out as an ordinary thread reply.+ When Slack already closed the stream, the answer also goes out as a plain thread reply,and nothing else is sent to the closed stream."""+ if ts is None:+ self.stream_ended = True+ if final_markdown:+ delivered = self._post_answer_outside_stream(final_markdown)+ if delivered:+ self.offer_reply_suggestions(reply_suggestions_for)+ self.capture_reply_posted(ReplyKind.ANSWER, delivered=delivered)+ returnanswer_chunks: list[dict[str, Any]] = []if plan_title:answer_chunks.append(_plan_update_chunk(plan_title))@@ -574,7 +618,7 @@ class SlackThreadHandler:placed = self._append_reply_suggestions(ts, reply_suggestions_for) if reply_suggestions_for else []final_chunks: list[dict[str, Any]] = []- recipient = self.actor_slack_user_id+ recipient = self.notification_target(self.actor_slack_user_id)if recipient and not final_markdown and not mention_sent:# Newlines keep the mention off the tail of the last streamed prose chunk.final_chunks.append({"type": "markdown_text", "text": f"\n\n<@{recipient}>"})@@ -609,7 +653,8 @@ class SlackThreadHandler:return all(posted)def _with_leading_mention(self, markdown: str) -> str:- return leading_mention_prefix(markdown, self.actor_slack_user_id) + markdown+ markdown = self.notification_text(markdown, self.actor_slack_user_id)+ return leading_mention_prefix(markdown, self.notification_target(self.actor_slack_user_id)) + markdowndef attach_files(self, ts: str, file_ids: list[str]) -> bool:"""Attach uploaded files to a message whose stream has closed, keeping its blocks and text.@@ -715,6 +760,7 @@ class SlackThreadHandler:becomes visible, and it is the only surface guaranteed to reach someonewho only ever talks to @PostHog from Slack."""+ reply_target_slack_user_id = self.notification_target(reply_target_slack_user_id)mention_prefix = f"<@{reply_target_slack_user_id}> " if reply_target_slack_user_id else ""header = f"{mention_prefix}*Pull request opened* :rocket:"@@ -740,6 +786,7 @@ class SlackThreadHandler:It leaves any progress message alone, because the run can still be working.Returns whether the card went out. A Slack failure is logged, never raised."""+ reply_target_slack_user_id = self.notification_target(reply_target_slack_user_id)mention_prefix = f"<@{reply_target_slack_user_id}> " if reply_target_slack_user_id else ""outcome = "*Pull request merged* :tada:" if merged else "*Pull request closed without merging*"header = f"{mention_prefix}{outcome}"diff --git a/products/slack_app/backend/tests/services/test_task_notifications.py b/products/slack_app/backend/tests/services/test_task_notifications.pynew file mode 100644index 000000000000..b5ceac25d82e--- /dev/null+++ b/products/slack_app/backend/tests/services/test_task_notifications.py@@ -0,0 +1,76 @@+from django.test import TestCase++from posthog.models import Organization, Team, User+from posthog.models.integration import Integration+from posthog.models.user_integration import UserIntegration++from products.slack_app.backend.models import SlackThreadTaskMapping+from products.slack_app.backend.services.task_notifications import task_slack_notifications_muted+from products.tasks.backend.models import Task, TaskRun+++class TestTaskNotificationTakeover(TestCase):+ def setUp(self) -> None:+ organization = Organization.objects.create(name="Test organization")+ self.team = Team.objects.create(organization=organization)+ self.user = User.objects.create_user(email="[email protected]", password="password", first_name="Mobile")+ self.other = User.objects.create_user(email="[email protected]", password="password", first_name="Other")+ self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T123")+ self.task = Task.objects.create(+ team=self.team, created_by=self.user, state={"mobile_push_user_ids": [self.user.id]}+ )+ self.task_run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ state={"slack_actor_user_id": self.user.id, "slack_actor_slack_user_id": "U123"},+ )+ self.mapping = SlackThreadTaskMapping.objects.create(+ team=self.team,+ integration=self.integration,+ slack_workspace_id="T123",+ channel="C123",+ thread_ts="123.456",+ task=self.task,+ task_run=self.task_run,+ mentioning_slack_user_id="U123",+ conversation_type=SlackThreadTaskMapping.ConversationType.PUBLIC_CHANNEL,+ )++ def muted(self, slack_user_id: str = "U123", *, private_only: bool = False) -> bool:+ return task_slack_notifications_muted(+ integration_id=self.integration.id,+ channel="C123",+ thread_ts="123.456",+ slack_user_id=slack_user_id,+ private_only=private_only,+ )++ def test_only_the_picked_up_users_task_notifications_are_muted(self) -> None:+ UserIntegration.objects.create(+ user=self.other, kind="slack", integration_id="UOTHER", config={"slack_team_id": "T123"}+ )+ assert self.muted()+ assert not self.muted("UOTHER")+ self.task.state = {}+ self.task.save(update_fields=["state"])+ assert not self.muted()++ def test_proactive_messages_are_muted_only_in_the_users_private_dm(self) -> None:+ assert not self.muted(private_only=True)+ self.mapping.conversation_type = SlackThreadTaskMapping.ConversationType.IM+ self.mapping.save(update_fields=["conversation_type"])+ assert self.muted(private_only=True)++ def test_report_threads_without_task_mapping_are_unchanged(self) -> None:+ self.mapping.delete()+ assert not self.muted()++ def test_linked_slack_identity_is_scoped_to_its_workspace(self) -> None:+ self.task_run.state = {}+ self.task_run.save(update_fields=["state"])+ UserIntegration.objects.create(+ user=self.user, kind="slack", integration_id="UPICKUP", config={"slack_team_id": "TOTHER"}+ )+ assert not self.muted("UPICKUP")+ UserIntegration.objects.filter(user=self.user).update(config={"slack_team_id": "T123"})+ assert self.muted("UPICKUP")diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.pyindex 56aa7fa73434..a8bbfaef4f41 100644--- a/products/slack_app/backend/tests/test_slack_thread.py+++ b/products/slack_app/backend/tests/test_slack_thread.py@@ -585,6 +585,7 @@ def _stop_with_answer(handler: SlackThreadHandler) -> None:handler.stop_status_stream(ts="1.0", final_markdown="Done.")+@patch("products.slack_app.backend.slack_thread.task_slack_notifications_muted", new=lambda **kwargs: False)class TestReplyPostedCapture(SimpleTestCase):@parameterized.expand([@@ -921,3 +922,37 @@ class TestMarkdownAnswerBlocks(SimpleTestCase):retry = mock_client.chat_postMessage.call_args_list[1].kwargsassert retry["text"] == "the answer"assert not retry.get("blocks")+++class TestMobileTaskNotificationTargets(SimpleTestCase):+ @patch("products.slack_app.backend.slack_thread.task_slack_notifications_muted", return_value=True)+ @patch.object(SlackThreadHandler, "_get_client")+ def test_moved_recipient_does_not_start_a_targeted_stream(self, client: MagicMock, _muted: MagicMock) -> None:+ handler = SlackThreadHandler(+ SlackThreadContext(integration_id=1, channel="C123", thread_ts="1.2", mentioning_slack_user_id="U123"),+ RunFooter(run_id="run-1"),+ )+ assert handler.start_status_stream(first_markdown_text="Finished") is None+ client.assert_not_called()++ @parameterized.expand([("bare", "<@U123> Finished"), ("labeled", "<@U123|Mobile user> Finished")])+ @patch("products.slack_app.backend.slack_thread.task_slack_notifications_muted", return_value=True)+ def test_shared_answer_keeps_its_text_without_leading_mention(+ self, _name: str, text: str, _muted: MagicMock+ ) -> None:+ handler = SlackThreadHandler(+ SlackThreadContext(integration_id=1, channel="C123", thread_ts="1.2", mentioning_slack_user_id="U123"),+ RunFooter(run_id="run-1"),+ )+ assert handler._with_leading_mention(text) == "Finished"+ assert handler._with_leading_mention("Finished with <@UOTHER>.") == "Finished with <@UOTHER>."++ @patch("products.slack_app.backend.slack_thread.task_slack_notifications_muted", return_value=True)+ @patch.object(SlackThreadHandler, "_delete_progress_and_post")+ def test_shared_pr_card_keeps_the_card_without_ping(self, post: MagicMock, _muted: MagicMock) -> None:+ handler = SlackThreadHandler(+ SlackThreadContext(integration_id=1, channel="C123", thread_ts="1.2", mentioning_slack_user_id="U123"),+ RunFooter(run_id="run-1"),+ )+ handler.post_pr_opened("https://example.com/pr/1", None, reply_target_slack_user_id="U123")+ assert post.call_args.args[0] == "*Pull request opened* :rocket:"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 989ffaf282b3..f2a98c5acafa 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -383,6 +383,14 @@ __all__ = ["mark_task_run_stream_watched","read_task_run_logs","record_comment_activity",+ "record_task_mobile_pickup",+ "task_mobile_push_taken_over",+ "task_mobile_push_delivery_allowed",+ "task_mobile_push_user_ids",+ "task_mobile_push_suppressed_token_ids",+ "enqueue_task_mobile_pr_outcome",+ "claim_mobile_push_cooldown",+ "release_mobile_push_cooldown","record_run_failure_cause","signal_task_run_client_activity","redispatch_task_run",@@ -3045,6 +3053,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(# interaction_origin is "slack"; a removed actor falls back to the task creator."interaction_origin","slack_actor_user_id",+ "slack_actor_slack_user_id",# Names the autoresearch training run this TaskRun finalizes when it ends (training.ingestion)."autoresearch_training_run_id",}@@ -8155,6 +8164,9 @@ def create_task(description = (validated_data.get("description") or "").strip()requested_title = (validated_data.get("title") or "").strip()update_fields: list[str] = []+ if "created_on_mobile" not in (warm_task.state or {}):+ warm_task.state = {**(warm_task.state or {}), **validated_data.get("state", {})}+ update_fields.append("state")if requested_title and not (warm_task.title or "").strip():warm_task.title = requested_titlewarm_task.title_manually_set = True@@ -12664,3 +12676,88 @@ def is_current_task_run_actor(team_id: int, run_id: UUID, user_id: int) -> bool:run = TaskRun.objects.select_related("task__created_by", "team__organization").get(id=run_id, team_id=team_id)actor = get_task_run_actor_user(run.task, run.state, allow_task_creator_fallback=False)return actor is not None and actor.id == user_id and user_has_current_team_access(actor, run.team)+++def record_task_mobile_pickup(*, task_id: str, team_id: int, user_id: int | None) -> None:+ from products.tasks.backend.mobile_push import (+ record_mobile_pickup, # noqa: PLC0415 — keep notification helpers off the facade import path+ )++ if user_id is None:+ return++ try:+ record_mobile_pickup(task_id=task_id, team_id=team_id, user_id=user_id)+ except Exception:+ logger.exception(+ "mobile_push.pickup_failed", extra={"task_id": task_id, "team_id": team_id, "user_id": user_id}+ )+++def task_mobile_push_taken_over(*, task_id: str, team_id: int, user_id: int) -> bool:+ from products.tasks.backend.mobile_push import (+ mobile_push_user_ids, # noqa: PLC0415 — keep notification helpers off the facade import path+ )++ task = Task.objects.filter(id=task_id, team_id=team_id).only("state").first()+ return task is not None and user_id in mobile_push_user_ids(task)+++def task_mobile_push_delivery_allowed(*, task_id: str, team_id: int, user_id: int) -> bool:+ from products.tasks.backend.mobile_push import (+ task_mobile_push_eligible, # noqa: PLC0415 — keep notification helpers off the facade import path+ )++ task = (+ Task.objects.filter(id=task_id, team_id=team_id, deleted=False)+ .filter(task_visibility_q(user_id))+ .select_related("team")+ .first()+ )+ if task is None or not task_mobile_push_eligible(task, user_id):+ return False+ user = User.objects.filter(id=user_id, is_active=True).first()+ return user is not None and UserAccessControl(user=user, team=task.team).check_access_level_for_resource(+ "task", "viewer"+ )+++def task_mobile_push_user_ids(*, task_id: str, team_id: int) -> set[int]:+ from products.tasks.backend.mobile_push import (+ mobile_push_user_ids, # noqa: PLC0415 — keep notification helpers off the facade import path+ )++ task = Task.objects.filter(id=task_id, team_id=team_id).only("state").first()+ return mobile_push_user_ids(task) if task is not None else set()+++def task_mobile_push_suppressed_token_ids(*, user_id: int, task_id: str, team_id: int) -> list[str]:+ from products.tasks.backend.mobile_push import (+ suppressed_push_token_ids_for_task, # noqa: PLC0415 — keep notification helpers off the facade import path+ )++ return suppressed_push_token_ids_for_task(user_id=user_id, task_id=task_id, team_id=team_id)+++def enqueue_task_mobile_pr_outcome(+ *, task_id: str, team_id: int, user_id: int, pr_url: str, kind: str, enqueue: Callable[[], None]+) -> bool:+ from products.tasks.backend.mobile_push import (+ enqueue_mobile_pr_outcome, # noqa: PLC0415 — keep notification helpers off the facade import path+ )++ return enqueue_mobile_pr_outcome(+ task_id=task_id, team_id=team_id, user_id=user_id, pr_url=pr_url, kind=kind, enqueue=enqueue+ )+++def claim_mobile_push_cooldown(key: str, *, timeout_seconds: int) -> bool:+ from products.tasks.backend.redis import get_tasks_cache # noqa: PLC0415 — keep redis off the api import path++ return bool(get_tasks_cache().add(key, True, timeout=timeout_seconds))+++def release_mobile_push_cooldown(key: str) -> None:+ from products.tasks.backend.redis import get_tasks_cache # noqa: PLC0415 — keep redis off the api import path++ get_tasks_cache().delete(key)diff --git a/products/tasks/backend/facade/testing.py b/products/tasks/backend/facade/testing.pyindex 07981625c11f..e451feb9c01c 100644--- a/products/tasks/backend/facade/testing.py+++ b/products/tasks/backend/facade/testing.py@@ -1,6 +1,24 @@+from datetime import datetimefrom uuid import UUID-from products.tasks.backend.models import TaskArtifact+from django.core.cache import BaseCache++from products.tasks.backend import push_dispatcher+from products.tasks.backend.models import TaskArtifact, TaskPresence, TaskRun+from products.tasks.backend.push_dispatcher import notify_task_pull_request_outcome+from products.tasks.backend.redis import get_tasks_cache++__all__ = [+ "create_task_artifact",+ "create_task_presence",+ "notify_task_pull_request_outcome",+ "notify_task_run_awaiting_input",+ "notify_task_run_cancelled",+ "notify_task_run_completed",+ "notify_task_run_failed",+ "notify_task_run_turn_completed",+ "tasks_cache",+]def create_task_artifact(*, team_id: int, task_id: UUID, task_run_id: UUID, name: str) -> UUID:@@ -16,3 +34,47 @@ def create_task_artifact(*, team_id: int, task_id: UUID, task_run_id: UUID, name).id)+++def create_task_presence(+ *, team_id: int, task_id: UUID, user_id: int, push_token_id: UUID, expires_at: datetime+) -> UUID:+ return (+ TaskPresence.objects.for_team(team_id)+ .create(+ team_id=team_id,+ task_id=task_id,+ user_id=user_id,+ push_token_id=push_token_id,+ expires_at=expires_at,+ )+ .id+ )+++def _task_run(task_run_id: str, team_id: int) -> TaskRun:+ return TaskRun.objects.select_related("task").get(id=task_run_id, team_id=team_id)+++def notify_task_run_completed(*, task_run_id: str, team_id: int) -> None:+ push_dispatcher.notify_task_run_completed(_task_run(task_run_id, team_id))+++def notify_task_run_failed(*, task_run_id: str, team_id: int) -> None:+ push_dispatcher.notify_task_run_failed(_task_run(task_run_id, team_id))+++def notify_task_run_cancelled(*, task_run_id: str, team_id: int) -> None:+ push_dispatcher.notify_task_run_cancelled(_task_run(task_run_id, team_id))+++def notify_task_run_awaiting_input(*, task_run_id: str, team_id: int) -> None:+ push_dispatcher.notify_task_run_awaiting_input(_task_run(task_run_id, team_id))+++def notify_task_run_turn_completed(*, task_run_id: str, team_id: int) -> None:+ push_dispatcher.notify_task_run_turn_completed(_task_run(task_run_id, team_id))+++def tasks_cache() -> BaseCache:+ return get_tasks_cache()diff --git a/products/tasks/backend/logic/services/slack_pr_cards.py b/products/tasks/backend/logic/services/slack_pr_cards.pyindex 7ea96ac0586f..a32dd2a24dcf 100644--- a/products/tasks/backend/logic/services/slack_pr_cards.py+++ b/products/tasks/backend/logic/services/slack_pr_cards.py@@ -56,6 +56,8 @@ def _post_pr_closed_card(run_id: str, pr_url: str, *, merged: bool) -> bool:return Falsehandler = SlackThreadHandler.for_run(SlackThreadContext.from_mapping(mapping), task_run.id)+ if handler.proactive_notifications_muted():+ return Falseposted = handler.post_pr_closed(pr_url,handler.reader_task_url(),diff --git a/products/tasks/backend/mobile_push.py b/products/tasks/backend/mobile_push.pynew file mode 100644index 000000000000..d903d990b08c--- /dev/null+++ b/products/tasks/backend/mobile_push.py@@ -0,0 +1,104 @@+import hashlib+from collections.abc import Callable+from uuid import UUID++from django.db import transaction+from django.utils import timezone++from posthog.models.user_push_token import UserPushToken++from products.tasks.backend.models import Task, TaskPresence+from products.tasks.backend.visibility import task_control_q++MOBILE_PUSH_USER_IDS = "mobile_push_user_ids"+++def mobile_push_user_ids(task: Task) -> set[int]:+ values = (task.state or {}).get(MOBILE_PUSH_USER_IDS, [])+ return {value for value in values if type(value) is int} if isinstance(values, list) else set()+++def task_mobile_push_eligible(task: Task, user_id: int) -> bool:+ return user_id in mobile_push_user_ids(task) or (+ (task.state or {}).get("created_on_mobile") is True and task.origin_product != Task.OriginProduct.SLACK+ )+++def suppressed_push_token_ids_for_task(*, user_id: int, task_id: str | UUID, team_id: int) -> list[str]:+ """Return all of the user's UserPushToken UUIDs (as strings) when at least one device+ has beaconed presence for this task, otherwise an empty list.++ The contract documented on the beacon endpoint is "if any device is+ provably watching, suppress the others". The watching device doesn't need+ a push either because it already renders the task UI in real time, so when+ any presence row is active we suppress the entire fanout for the user.+ Computed at enqueue time; the Celery dispatch is essentially instant so+ the race window against the 30-second beacon cadence is irrelevant.+ """+ has_active_presence = (+ TaskPresence.objects.for_team(team_id)+ .filter(task_id=task_id, user_id=user_id, expires_at__gt=timezone.now())+ .exists()+ )+ if not has_active_presence:+ return []+ return [str(pid) for pid in UserPushToken.objects.filter(user_id=user_id).values_list("id", flat=True)]+++def record_mobile_pickup(*, task_id: str | UUID, team_id: int, user_id: int) -> None:+ with transaction.atomic():+ task = (+ Task.objects.select_for_update(no_key=True, of=("self",))+ .filter(id=task_id, team_id=team_id, deleted=False)+ .filter(task_control_q(user_id))+ .first()+ )+ if task is None:+ return+ recipients = mobile_push_user_ids(task)+ if user_id in recipients:+ return+ task.state = {**(task.state or {}), MOBILE_PUSH_USER_IDS: sorted(recipients | {user_id})}+ task.save(update_fields=["state", "updated_at"])+++def _mobile_pr_outcome_event_id(user_id: int, kind: str, pr_url: str) -> str:+ return f"{user_id}:{kind.removeprefix('report_')}:{hashlib.sha256(pr_url.encode()).hexdigest()}"+++def _release_mobile_pr_outcome(*, task_id: str | UUID, team_id: int, event_id: str) -> None:+ with transaction.atomic():+ task = Task.objects.select_for_update(no_key=True).only("id", "state").get(id=task_id, team_id=team_id)+ state = dict(task.state or {})+ outcomes = state.get("mobile_push_pr_outcomes", [])+ task.state = {**state, "mobile_push_pr_outcomes": [value for value in outcomes if value != event_id]}+ task.save(update_fields=["state", "updated_at"])+++def claim_mobile_pr_outcome(*, task_id: str | UUID, team_id: int, user_id: int, pr_url: str, kind: str) -> bool:+ event_id = _mobile_pr_outcome_event_id(user_id, kind, pr_url)+ with transaction.atomic():+ task = Task.objects.select_for_update(no_key=True).only("id", "state").get(id=task_id, team_id=team_id)+ state = dict(task.state or {})+ outcomes = state.get("mobile_push_pr_outcomes", [])+ outcomes = outcomes if isinstance(outcomes, list) else []+ if event_id in outcomes:+ return False+ task.state = {**state, "mobile_push_pr_outcomes": [*outcomes, event_id]}+ task.save(update_fields=["state", "updated_at"])+ return True+++def enqueue_mobile_pr_outcome(+ *, task_id: str | UUID, team_id: int, user_id: int, pr_url: str, kind: str, enqueue: Callable[[], None]+) -> bool:+ if not claim_mobile_pr_outcome(task_id=task_id, team_id=team_id, user_id=user_id, pr_url=pr_url, kind=kind):+ return False+ try:+ enqueue()+ except Exception:+ _release_mobile_pr_outcome(+ task_id=task_id, team_id=team_id, event_id=_mobile_pr_outcome_event_id(user_id, kind, pr_url)+ )+ raise+ return Truediff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 880d7d331e4f..7d4e9356a291 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -844,6 +844,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def create(self, request, **kwargs):serializer = self._write_serializer(request.data, serializer_class=TaskCreateSerializer)validated_data = dict(serializer.validated_data)+ validated_data["state"] = {"created_on_mobile": request.headers.get("X-PostHog-Client-Platform") == "mobile"}start_run = validated_data.pop("start_run", False)run_data = validated_data.pop("run_data", {})origin_product = validated_data.get("origin_product", tasks_facade.TaskOriginProduct.USER_CREATED)@@ -1600,6 +1601,12 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()if result.error is not None:return self._task_error_response(result.error)+ if (+ not result.run_error+ and result.run_id is not None+ and request.headers.get("X-PostHog-Client-Platform") == "mobile"+ ):+ tasks_facade.record_task_mobile_pickup(task_id=str(pk), team_id=self.team_id, user_id=self._user_id())response_data = TaskSerializer(result.task).dataif result.run_error:response_data["run_error"] = result.run_error@@ -3872,6 +3879,9 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):status=status.HTTP_409_CONFLICT,)+ if request.headers.get("X-PostHog-Client-Platform") == "mobile":+ tasks_facade.record_task_mobile_pickup(task_id=task_id, team_id=self.team_id, user_id=self._user_id())+# A warm Run has now received a human message — drop the warm flag so the warm-pool cap# (see products/tasks/backend/logic/services/warm.py) stops counting it. No-op for Runs# that were never warm; best-effort, since a failure only over-counts the pool until terminal.@@ -4026,6 +4036,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):tasks_facade.capture_relay_command_telemetry(pk, task_id, self.team_id, method=method, params=params, success=success)+ if (+ success+ and method == "permission_response"+ and request.headers.get("X-PostHog-Client-Platform") == "mobile"+ ):+ tasks_facade.record_task_mobile_pickup(task_id=task_id, team_id=self.team_id, user_id=self._user_id())if agent_response.ok:tasks_facade.signal_task_run_client_activity(pk, task_id, self.team_id)return Response(response_data)@@ -4358,6 +4374,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):status=status.HTTP_502_BAD_GATEWAY,)+ if request.headers.get("X-PostHog-Client-Platform") == "mobile":+ tasks_facade.record_task_mobile_pickup(task_id=task_id, team_id=self.team_id, user_id=self._user_id())return Response(TaskRunDetailSerializer(run).data)@staticmethoddiff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.pyindex 9d101a028b47..eec8f604c0ec 100644--- a/products/tasks/backend/push_dispatcher.py+++ b/products/tasks/backend/push_dispatcher.py@@ -4,7 +4,10 @@ Schedules the underlying Expo HTTP call as a Celery task via``transaction.on_commit`` so nothing here can block a request/response cycleor a Temporal activity's event loop.-Two guards before we enqueue:+Guards before we enqueue:++Tasks created or actively continued on mobile use task pushes; report research and implementation+use the report notification channel instead. User preferences apply to both.1. **Cooldown.** A per-source Redis lock collapses duplicate triggers in ashort window.@@ -13,29 +16,36 @@ Two guards before we enqueue:from __future__ import annotations+import hashlibfrom collections.abc import Callable, Collectionfrom typing import TYPE_CHECKING, Literal, castfrom django.conf import settingsfrom django.db import InterfaceError, OperationalError, close_old_connections, transactionfrom django.db.models import Exists, OuterRef-from django.utils import timezoneimport structlogfrom posthog.models.user import User-from posthog.models.user_push_token import UserPushToken+from posthog.push_notifications import mobile_push_preference_enabledfrom posthog.tasks.push_notifications import send_user_push+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.tasks.backend.metrics import PUSH_DISPATCHER_FAILURES_TOTAL, PUSH_DISPATCHER_OUTCOMES_TOTAL-from products.tasks.backend.models import Task, TaskPresence+from products.tasks.backend.mobile_push import (+ enqueue_mobile_pr_outcome,+ mobile_push_user_ids,+ suppressed_push_token_ids_for_task,+ task_mobile_push_eligible,+)+from products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.redis import get_tasks_cachefrom products.tasks.backend.visibility import task_visibility_qif TYPE_CHECKING:from uuid import UUID- from products.tasks.backend.models import TaskRun, TaskThreadMessage+ from products.tasks.backend.models import TaskThreadMessagelogger = structlog.get_logger(__name__)@@ -46,7 +56,17 @@ AWAITING_INPUT_COOLDOWN_SECONDS = 30# 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", "thread_message", "handoff"]+PushKind = Literal[+ "completed",+ "failed",+ "cancelled",+ "awaiting",+ "turn_completed",+ "thread_message",+ "handoff",+ "pr_merged",+ "pr_closed",+]_COOLDOWN_SECONDS: dict[PushKind, int] = {"completed": 600,"failed": 600,@@ -55,6 +75,8 @@ _COOLDOWN_SECONDS: dict[PushKind, int] = {"turn_completed": 30,"thread_message": 600,"handoff": 600,+ "pr_merged": 600,+ "pr_closed": 600,}@@ -87,6 +109,22 @@ 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_pull_request_outcome(*, task_id: str, run_id: str, team_id: int, pr_url: str, merged: bool) -> None:+ """Push a verified PR outcome independently of whether Slack announced the PR."""+ kind: PushKind = "pr_merged" if merged else "pr_closed"+ try:+ task_run = TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).select_related("task").first()+ if task_run is None:+ return+ outcome = "merged" if merged else "closed"+ _enqueue_inner(+ task_run, kind=kind, body=f'"{_task_title(task_run)}" pull request was {outcome}', pull_request_url=pr_url+ )+ except Exception as exc:+ PUSH_DISPATCHER_FAILURES_TOTAL.labels(kind=kind, reason=_failure_reason(exc)).inc()+ logger.warning("push_dispatcher.pr_outcome_failed", task_id=task_id, team_id=team_id, exc_info=True)++def notify_task_handoff(task: Task, *, recipient: User, actor: User | None, message_id: UUID) -> None:"""Fire a push notification when a task is handed off to ``recipient``.@@ -129,7 +167,8 @@ def notify_task_thread_message(message: TaskThreadMessage, mentioned_user_ids: Cdef _notify_task_thread_message(message: TaskThreadMessage, mentioned_user_ids: Collection[int]) -> None:- recipient_ids = set(mentioned_user_ids)+ message.task.refresh_from_db(fields=["state"])+ recipient_ids = set(mentioned_user_ids) | mobile_push_user_ids(message.task)if message.task.created_by_id is not None:recipient_ids.add(message.task.created_by_id)if message.author_id is not None:@@ -139,7 +178,7 @@ def _notify_task_thread_message(message: TaskThreadMessage, mentioned_user_ids:author = message.authorauthor_name = (author.first_name.strip() or author.email) if author else "PostHog"task_title = (message.task.title or "").strip() or "Untitled task"- data = {+ data: dict[str, str | int] = {"taskId": str(message.task_id),"messageId": str(message.id),}@@ -233,35 +272,61 @@ def _failure_reason(exc: BaseException) -> str:def _enqueue_inner(- task_run: TaskRun, *, kind: PushKind, body: str, on_enqueued: Callable[[], None] | None = None+ task_run: TaskRun,+ *,+ kind: PushKind,+ body: str,+ pull_request_url: str | None = None,+ on_enqueued: Callable[[], None] | None = None,) -> bool:if not settings.TEST:close_old_connections()- user = task_run.task.created_by- if user is None:- PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="no_recipient").inc()- return False-- if not user.teams.filter(id=task_run.team_id).exists():- PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="access_denied").inc()- logger.debug(- "push_dispatcher.recipient_lost_access",- user_id=user.id,- task_id=str(task_run.task_id),- team_id=task_run.team_id,- )- return False+ from products.signals.backend.facade.api import ( # noqa: PLC0415 — avoid a product import cycle+ notify_report_task_push,+ )- return _enqueue_user(- user,- task=task_run.task,+ if notify_report_task_push(+ team_id=task_run.team_id,+ task_id=str(task_run.task_id),+ run_id=str(task_run.id),kind=kind,- cooldown_subject=str(task_run.id),- body=body,- data={"taskId": str(task_run.task_id), "taskRunId": str(task_run.id)},+ pull_request_url=pull_request_url,on_enqueued=on_enqueued,+ ):+ return True++ task = Task.objects.filter(id=task_run.task_id, team_id=task_run.team_id).first()+ if task is None:+ return False+ recipient_ids = mobile_push_user_ids(task)+ if task.created_by_id is not None:+ recipient_ids.add(task.created_by_id)+ if not recipient_ids:+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="no_recipient").inc()+ return False+ subject = (+ f"pr:{task.id}:{hashlib.sha256(pull_request_url.encode()).hexdigest()}"+ if pull_request_url+ else str(task_run.id))+ accepted = False+ for user in User.objects.filter(id__in=recipient_ids):+ data: dict[str, str | int] = {"taskId": str(task.id), "taskRunId": str(task_run.id)}+ if pull_request_url is not None:+ data["pullRequestUrl"] = pull_request_url+ enqueued = _enqueue_user(+ user,+ task=task,+ kind=kind,+ cooldown_subject=f"{subject}:{user.id}",+ body=body,+ data=data,+ pull_request_url=pull_request_url,+ on_enqueued=on_enqueued,+ )+ accepted = accepted or enqueued+ return accepteddef _enqueue_user(@@ -271,21 +336,33 @@ def _enqueue_user(kind: PushKind,cooldown_subject: str,body: str,- data: dict[str, str],+ data: dict[str, str | int],+ pull_request_url: str | None = None,on_enqueued: Callable[[], None] | None = None,) -> bool:+ task.refresh_from_db(fields=["state"])if task.is_scout_experiment:return False-- cooldown_key = f"push_notification:{cooldown_subject}:{kind}"- if not get_tasks_cache().add(cooldown_key, True, timeout=_COOLDOWN_SECONDS[kind]):- PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="cooldown_deduped").inc()- logger.debug("push_dispatcher.cooldown_hit", subject=cooldown_subject, kind=kind)+ if not task_mobile_push_eligible(task, user.id):+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="source_disabled").inc()return False-- suppressed = _suppressed_push_token_ids_for_task(user_id=user.id, task_id=task.id)+ if not mobile_push_preference_enabled(user, "tasks"):+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="preferences_disabled").inc()+ return False+ if (+ not user.teams.filter(id=task.team_id).exists()+ or not UserAccessControl(user=user, team=task.team).check_access_level_for_resource("task", "viewer")+ or not Task.objects.filter(id=task.id, team_id=task.team_id, deleted=False)+ .filter(task_visibility_q(user.id))+ .exists()+ ):+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="access_denied").inc()+ return False+ cooldown_key = f"push_notification:{cooldown_subject}:{kind}"+ suppressed = suppressed_push_token_ids_for_task(user_id=user.id, task_id=task.id, team_id=task.team_id)+ data["type"] = "task"data["notificationKind"] = kind- data["projectId"] = str(task.team_id)+ data["projectId"] = task.team_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.@@ -294,41 +371,43 @@ def _enqueue_user(def dispatch() -> None:nonlocal acceptedtry:- send_user_push.delay(user.id, PUSH_TITLE, body, data, suppressed)+ if not get_tasks_cache().add(cooldown_key, True, timeout=_COOLDOWN_SECONDS[kind]):+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome="cooldown_deduped").inc()+ accepted = False+ return+ try:++ def enqueue() -> None:+ send_user_push.delay(user.id, PUSH_TITLE, body, data, suppressed)++ if pull_request_url is not None:+ enqueued = enqueue_mobile_pr_outcome(+ task_id=task.id,+ team_id=task.team_id,+ user_id=user.id,+ pr_url=pull_request_url,+ kind=kind,+ enqueue=enqueue,+ )+ else:+ enqueue()+ enqueued = True+ if enqueued:+ outcome = "presence_suppressed" if suppressed else "enqueued"+ PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome=outcome).inc()+ if on_enqueued is not None:+ on_enqueued()+ else:+ accepted = False+ except Exception:+ get_tasks_cache().delete(cooldown_key)+ raiseexcept Exception as exc:accepted = FalsePUSH_DISPATCHER_FAILURES_TOTAL.labels(kind=kind, reason=_failure_reason(exc)).inc()- logger.warning("push_dispatcher.enqueue_failed", task_id=str(task.id), kind=kind, exc_info=True)- return- outcome = "presence_suppressed" if suppressed else "enqueued"- PUSH_DISPATCHER_OUTCOMES_TOTAL.labels(kind=kind, outcome=outcome).inc()- if on_enqueued is not None:- on_enqueued()+ logger.warning(+ "push_dispatcher.enqueue_failed", task_id=str(task.id), user_id=user.id, kind=kind, exc_info=True+ )transaction.on_commit(dispatch)return accepted---def _suppressed_push_token_ids_for_task(*, user_id: int, task_id) -> list[str]:- """Return all of the user's UserPushToken UUIDs (as strings) when at least one device- has beaconed presence for this task — otherwise an empty list.-- The contract documented on the beacon endpoint is "if any device is- provably watching, suppress the others". The watching device doesn't need- a push either — it's already rendering the task UI in real time — so when- any presence row is active we suppress the entire fanout for the user.- Computed at enqueue time; the Celery dispatch is essentially instant so- the race window against the 30-second beacon cadence is irrelevant.-- ``unscoped`` is the right escape hatch here: the dispatcher fires from a- mix of Temporal activities and model methods that don't have the DRF- team-context ContextVar set. Both queries are scoped through- ``user_id`` and ``task_id`` and the presence rows are tenant-safe by- virtue of their FK to a team-scoped Task.- """- has_active_presence = (- TaskPresence.objects.unscoped().filter(task_id=task_id, user_id=user_id, expires_at__gt=timezone.now()).exists()- )- if not has_active_presence:- return []- return [str(pid) for pid in UserPushToken.objects.filter(user_id=user_id).values_list("id", flat=True)]diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.pyindex acaeb5a8ca73..79e36c0d7734 100644--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py@@ -119,6 +119,9 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:try:context = SlackThreadContext.from_dict(input.slack_thread_context)handler = SlackThreadHandler.for_run(context, task_run.id)+ if handler.proactive_notifications_muted():+ handler.delete_progress()+ return# The buttons lead where the footer's link does.task_url = handler.reader_task_url()pr_url = (task_run.output or {}).get("pr_url")diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.pyindex fd063eb547cb..51cffc7b829c 100644--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py@@ -41,7 +41,8 @@ class StartSlackAgentDesignStreamInput:@frozenclass SlackAgentDesignStream:- ts: str+ # None keeps the turn collecting its answer for an ordinary, untargeted reply.+ ts: Optional[str]# Whether the message has a plan block, so closing it can set the plan title.has_plan: bool# Who the reply tags, so closing the stream tags the same person.@@ -51,7 +52,7 @@ class SlackAgentDesignStream:@frozenclass AppendSlackAgentDesignStepsInput:slack_thread_context: dict[str, Any]- ts: str+ ts: Optional[str]task_updates: list[TaskUpdateChunk] = field(default_factory=list)plan_title: Optional[str] = None@@ -59,7 +60,7 @@ class AppendSlackAgentDesignStepsInput:@frozenclass StopSlackAgentDesignStreamInput:slack_thread_context: dict[str, Any]- ts: str+ ts: Optional[str]complete_task_id: Optional[str] = Nonecomplete_task_title: Optional[str] = None# Streamed as markdown_text chunks below the plan block right before stopStream.@@ -114,12 +115,16 @@ def _chunk_dicts(task_updates: list[TaskUpdateChunk]) -> list[dict[str, Any]]:@activity.defn@close_db_connectionsdef start_slack_agent_design_stream(input: StartSlackAgentDesignStreamInput) -> Optional[SlackAgentDesignStream]:- """Open the turn's stream and seed it. Returns None when no stream opened."""+ """Start streaming, or keep the turn for an ordinary reply when its recipient is muted."""from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandlertry:context = SlackThreadContext.from_dict(input.slack_thread_context)- handler = SlackThreadHandler(context, actor_slack_user_id=_reply_target(input.run_id, input.message_id))+ handler = SlackThreadHandler.for_run(+ context, input.run_id, actor_slack_user_id=_reply_target(input.run_id, input.message_id)+ )+ if handler.actor_slack_user_id and handler.notification_target(handler.actor_slack_user_id) is None:+ return SlackAgentDesignStream(ts=None, has_plan=False, actor_slack_user_id=handler.actor_slack_user_id)markdown_text = _rewrite_object_tags(input.first_markdown_text, handler.project_url)new_ts = handler.start_status_stream(task_updates=_chunk_dicts(input.task_updates),@@ -142,9 +147,14 @@ def append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) ->"""Append plan-block step transitions and a new plan title. Returns False once Slack has closed the stream."""from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler+ if input.ts is None:+ return Truetry:context = SlackThreadContext.from_dict(input.slack_thread_context)handler = SlackThreadHandler(context)+ if handler.proactive_notifications_muted():+ handler.stop_status_stream(ts=input.ts, mention_sent=True)+ return Falsereturn handler.append_status_chunks(ts=input.ts,task_updates=_chunk_dicts(input.task_updates),@@ -167,10 +177,11 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> Nostream_pending_slack_attachments,)from products.tasks.backend.models import TaskRun- from products.tasks.backend.temporal.process_task.utils import turn_person_message+ from products.tasks.backend.temporal.process_task.utils import is_explicit_slack_reply, turn_person_messagetry:context = SlackThreadContext.from_dict(input.slack_thread_context)+ task_run = TaskRun.objects.get(id=input.run_id) if input.run_id else Nonehandler = SlackThreadHandler.for_run(context,input.run_id,@@ -178,15 +189,23 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> Noturn_trace_id=input.trace_id,turn_person_message=turn_person_message(input.run_id, input.message_id, mention=input.mention),)- task_run = TaskRun.objects.get(id=input.run_id) if input.run_id else None+ if (+ task_run is not None+ and handler.proactive_notifications_muted()+ and not is_explicit_slack_reply(task_run, input.message_id)+ ):+ if input.ts is not None:+ handler.stop_status_stream(ts=input.ts, final_markdown=None, mention_sent=True)+ returndeliveries: list[SlackFileDeliveryResult] = []def _append_attachments() -> None:- if task_run is None:+ ts = input.ts+ if task_run is None or ts is None:returndeliveries.append(stream_pending_slack_attachments(- task_run, append_blocks=lambda blocks: handler.append_status_blocks(input.ts, blocks)+ task_run, append_blocks=lambda blocks: handler.append_status_blocks(ts, blocks)))@@ -194,16 +213,20 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> Nots=input.ts,complete_task_id=input.complete_task_id,complete_task_title=input.complete_task_title,- final_markdown=_rewrite_object_tags(input.final_markdown, handler.project_url),+ final_markdown=_rewrite_object_tags(+ (input.answer_markdown or input.final_markdown) if input.ts is None else input.final_markdown,+ handler.project_url,+ ),plan_title=input.plan_title,append_attachments=_append_attachments,mention_sent=input.mention_sent,reply_suggestions_for=input.answer_markdown,)+ ts = input.tsfor delivery in deliveries:- if task_run is not None:+ if task_run is not None and ts is not None:attach_streamed_slack_files(- task_run, delivery, attach_files=lambda file_ids: handler.attach_files(input.ts, file_ids)+ task_run, delivery, attach_files=lambda file_ids: handler.attach_files(ts, file_ids))if handler.stream_ended and task_run is not None:# A closed stream takes no cards, so whatever is still pending posts under the answer as its own message.diff --git a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.pyindex 2f97353ce4f6..cf870014251e 100644--- a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py+++ b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py@@ -12,11 +12,14 @@ from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from products.slack_app.backend.models import SlackThreadTaskMappingfrom products.slack_app.backend.slack_thread import SlackThreadHandlerfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.process_task.activities.slack_agent_design import (+ AppendSlackAgentDesignStepsInput,StartSlackAgentDesignStreamInput,StopSlackAgentDesignStreamInput,+ append_slack_agent_design_steps,start_slack_agent_design_stream,stop_slack_agent_design_stream,)@@ -218,3 +221,127 @@ class TestSlackAgentDesignStream(TestCase):assert mock_start.call_args.args[0].actor_slack_user_id == expected_targetassert stream is not None and stream.actor_slack_user_id == expected_target++ @parameterized.expand(+ [+ ("shared_channel", "C1", False, None),+ ("direct_request", "D1", False, "slack_message"),+ ("slack_successor", "D1", False, "slack_run"),+ ("web_after_slack_successor", "D1", False, "web_message_after_slack_run"),+ ("answer_at_start", "C1", True, None),+ ("private_proactive", "D1", False, None),+ ]+ )+ @patch("products.tasks.backend.logic.services.living_artifacts.deliver_pending_slack_file_artifacts")+ @patch("products.slack_app.backend.slack_thread.task_slack_notifications_muted")+ @patch.object(SlackThreadHandler, "_get_client")+ def test_mobile_pickup_keeps_the_answer_without_a_targeted_stream(+ self, _name, channel, answer_at_start, request_origin, mock_get_client, mock_muted, mock_deliver+ ) -> None:+ mock_muted.side_effect = lambda **kwargs: channel == "D1" or not kwargs.get("private_only", False)+ message_id = request_origin if request_origin in {"slack_message", "web_message_after_slack_run"} else None+ if request_origin in {"slack_run", "web_message_after_slack_run"}:+ self.task_run.state = {**self.task_run.state, "interaction_origin": "slack"}+ self.task_run.save(update_fields=["state"])+ if request_origin == "slack_message":+ record_delivered_message(+ str(self.task_run.id), "slack_message", actor_slack_user_id="U456", person_message="How are signups?"+ )+ client = mock_get_client.return_value+ client.chat_postMessage.return_value = {"ts": "2.0"}+ context = {+ "integration_id": self.integration.id,+ "channel": channel,+ "thread_ts": "1.0",+ "mentioning_slack_user_id": "U123",+ }+ answer = "<@U456> Signups grew."+ stream = start_slack_agent_design_stream(+ StartSlackAgentDesignStreamInput(+ slack_thread_context=context,+ run_id=str(self.task_run.id),+ first_markdown_text=answer if answer_at_start else None,+ message_id=message_id,+ )+ )+ assert stream is not None+ assert append_slack_agent_design_steps(+ AppendSlackAgentDesignStepsInput(slack_thread_context=context, ts=stream.ts)+ )+ stop_slack_agent_design_stream(+ StopSlackAgentDesignStreamInput(+ slack_thread_context=context,+ ts=stream.ts,+ run_id=str(self.task_run.id),+ actor_slack_user_id=stream.actor_slack_user_id,+ final_markdown=None if answer_at_start else answer,+ answer_markdown=answer,+ mention_sent=answer_at_start,+ message_id=message_id,+ )+ )++ client.chat_startStream.assert_not_called()+ client.chat_appendStream.assert_not_called()+ client.chat_stopStream.assert_not_called()+ if channel == "D1" and request_origin not in {"slack_message", "slack_run"}:+ client.chat_postMessage.assert_not_called()+ mock_deliver.assert_not_called()+ else:+ assert client.chat_postMessage.call_args.kwargs["text"] == "Signups grew."+ mock_deliver.assert_called_once_with(self.task_run)++ @parameterized.expand([("private", True), ("shared_other_participant", False)])+ @patch.object(SlackThreadHandler, "stop_status_stream")+ @patch.object(SlackThreadHandler, "append_status_chunks", return_value=True)+ def test_pickup_closes_only_the_sole_recipients_stream(+ self, _name: str, private: bool, append: MagicMock, stop: MagicMock+ ) -> None:+ user = User.objects.create_and_join(self.org, "[email protected]", None)+ task = Task.objects.create(+ team=self.team,+ title="Picked up task",+ description="desc",+ origin_product=Task.OriginProduct.SLACK,+ created_by=user,+ state={"mobile_push_user_ids": [user.id]},+ )+ task_run = TaskRun.objects.create(+ task=task,+ team=self.team,+ state={"slack_actor_user_id": user.id, "slack_actor_slack_user_id": "U123"},+ )+ SlackThreadTaskMapping.objects.create(+ team=self.team,+ integration=self.integration,+ slack_workspace_id="T123",+ channel="C123",+ thread_ts="123.456",+ task=task,+ task_run=task_run,+ mentioning_slack_user_id="U123",+ conversation_type=(+ SlackThreadTaskMapping.ConversationType.IM+ if private+ else SlackThreadTaskMapping.ConversationType.PUBLIC_CHANNEL+ ),+ )+ result = append_slack_agent_design_steps(+ AppendSlackAgentDesignStepsInput(+ slack_thread_context={+ "integration_id": self.integration.id,+ "channel": "C123",+ "thread_ts": "123.456",+ "mentioning_slack_user_id": "U123",+ },+ ts="stream-ts",+ )+ )+ if private:+ assert result is False+ append.assert_not_called()+ stop.assert_called_once_with(ts="stream-ts", mention_sent=True)+ else:+ assert result is True+ append.assert_called_once()+ stop.assert_not_called()diff --git a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.pyindex d7338a1cc153..b3a27faf8977 100644--- a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py+++ b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py@@ -35,7 +35,8 @@ CHECKING = [("agent_text_delta", "Checking."), ("agent_status_update", {"phase":class _SlackCalls:- def __init__(self, stream_closed: bool = False) -> None:+ def __init__(self, stream_closed: bool = False, plain_reply: bool = False) -> None:+ self.plain_reply = plain_reply# Slack has closed every stream, so each append reports it.self.stream_closed = stream_closedself.starts: list[StartSlackAgentDesignStreamInput] = []@@ -46,7 +47,11 @@ class _SlackCalls:@activity.defn(name="start_slack_agent_design_stream")async def start(input: StartSlackAgentDesignStreamInput) -> SlackAgentDesignStream:self.starts.append(input)- return SlackAgentDesignStream(ts="2.0", has_plan=bool(input.task_updates), actor_slack_user_id="U9")+ return SlackAgentDesignStream(+ ts=None if self.plain_reply else "2.0",+ has_plan=bool(input.task_updates),+ actor_slack_user_id="U9",+ )@activity.defn(name="append_slack_agent_design_steps")async def append(input: AppendSlackAgentDesignStepsInput) -> bool:@@ -88,9 +93,10 @@ async def _run_relay(setup_title: str | None = None,cancel: bool = False,stream_closed: bool = False,+ plain_reply: bool = False,turn_trace_id: str | None = TRACE_ID,) -> _SlackCalls:- calls = _SlackCalls(stream_closed=stream_closed)+ calls = _SlackCalls(stream_closed=stream_closed, plain_reply=plain_reply)async with await WorkflowEnvironment.start_time_skipping() as env:task_queue = f"test-{uuid.uuid4()}"async with Worker(@@ -123,6 +129,19 @@ async def _run_relay(class TestSlackAgentDesignRelay:+ @pytest.mark.parametrize("setup_title", [None, "Starting sandbox"])+ @pytest.mark.timeout(60, func_only=True)+ async def test_untargeted_reply_keeps_collecting_the_final_answer(self, setup_title: str | None) -> None:+ calls = await _run_relay(+ [("agent_text_delta", "Signups grew.")],+ setup_title=setup_title,+ plain_reply=True,+ )++ assert len(calls.stops) == 1+ assert calls.stops[0].ts is None+ assert calls.stops[0].answer_markdown == "Signups grew."+@pytest.mark.timeout(60, func_only=True)async def test_tool_calls_collapse_into_one_line_per_phase(self) -> None:calls = await _run_relay(diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex a0048407d0b0..4efdf1f3906e 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -1923,6 +1923,14 @@ def get_message_actor(run_id: str, message_id: str) -> str | None:return get_tasks_cache().get(_message_record_key("actor", run_id, message_id))+def is_explicit_slack_reply(task_run: TaskRun, message_id: str | None) -> bool:+ if message_id:+ return bool(get_message_actor(str(task_run.id), message_id))+ # The opening turn starts with the sandbox, before per-message sender records exist.+ state = task_run.state or {}+ return state.get("interaction_origin") == "slack" and bool(state.get("slack_actor_slack_user_id"))++def turn_person_message(run_id: str | None, message_id: str | None, *, mention: str | None = None) -> str | None:"""What the person said to start the turn that answers ``message_id``.diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.pyindex 9d91a96920f0..a7e90b2d4bbf 100644--- a/products/tasks/backend/temporal/slack_relay/activities.py+++ b/products/tasks/backend/temporal/slack_relay/activities.py@@ -204,7 +204,11 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:)from products.slack_app.backend.slack_thread import ReplyKind, SlackThreadContext, SlackThreadHandlerfrom products.tasks.backend.models import TaskRun- from products.tasks.backend.temporal.process_task.utils import slack_reply_target, turn_person_message+ from products.tasks.backend.temporal.process_task.utils import (+ is_explicit_slack_reply,+ slack_reply_target,+ turn_person_message,+ )try:task_run = TaskRun.objects.get(id=input.run_id)@@ -260,8 +264,13 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:turn_person_message=person_message,)+ if handler.proactive_notifications_muted() and not is_explicit_slack_reply(task_run, input.message_id):+ handler.delete_progress()+ return+ text = handler.notification_text(text, target)+# The mention opens the answer, in the same line, so the reply reads as one message.- mention_prefix = leading_mention_prefix(text, target)+ mention_prefix = leading_mention_prefix(text, handler.notification_target(target))compose_with_charts = has_pending_slack_files and has_pending_slack_image_artifacts(task_run)diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex 35cb50c01b77..5d97d1b0e6d2 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py@@ -23,6 +23,7 @@ from products.tasks.backend.logic.services.living_artifacts import (stream_pending_slack_attachments,)from products.tasks.backend.models import Task, TaskArtifact, TaskRun+from products.tasks.backend.temporal.process_task.utils import record_delivered_messagefrom products.tasks.backend.temporal.slack_relay.activities import (RelaySlackMessageInput,_append_unconfirmed_attachment_notice,@@ -82,6 +83,49 @@ class TestRelaySlackMessage(TestCase):self.task_run.save(update_fields=["artifacts", "state", "updated_at"])SlackThreadTaskMapping.objects.filter(task_run=self.task_run).update(latest_actor_slack_user_id=None)+ @parameterized.expand(+ [+ ("mobile_private", True, None, False),+ ("explicit_slack_private", True, "slack_message", True),+ ("slack_successor_private", True, "slack_run", True),+ ("web_after_slack_successor", True, "web_message_after_slack_run", False),+ ("shared_mobile", False, None, True),+ ]+ )+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")+ def test_mobile_takeover_preserves_shared_and_explicit_slack_answers(+ self, _name, private, request_origin, expected_post, _delete_progress, post+ ) -> None:+ self.task.state = {"mobile_push_user_ids": [self.user.id]}+ self.task.save(update_fields=["state"])+ SlackThreadTaskMapping.objects.filter(task_run=self.task_run).update(+ conversation_type=(+ SlackThreadTaskMapping.ConversationType.IM+ if private+ else SlackThreadTaskMapping.ConversationType.PUBLIC_CHANNEL+ )+ )+ message_id = request_origin if request_origin in {"slack_message", "web_message_after_slack_run"} else None+ if request_origin in {"slack_run", "web_message_after_slack_run"}:+ self.task_run.state = {"interaction_origin": "slack", "slack_actor_slack_user_id": "U123"}+ self.task_run.save(update_fields=["state"])+ if request_origin == "slack_message":+ record_delivered_message(+ str(self.task_run.id), "slack_message", actor_slack_user_id="U123", person_message="Continue"+ )+ relay_slack_message(+ RelaySlackMessageInput(+ run_id=str(self.task_run.id),+ relay_id=f"relay-{_name}",+ message_id=message_id,+ text="<@U123> Finished with <@UOTHER>.",+ )+ )+ assert post.called is expected_post+ if expected_post:+ assert post.call_args.args[0] == "Finished with <@UOTHER>."+@parameterized.expand([("no_reaction_emoji", "relay-1", "Which license should I use?", None, "Which license should I use?"),diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex a578cc65fa8c..565fabd80797 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -2002,7 +2002,8 @@ class TestTaskAPI(BaseTaskAPITest):},)- def test_create_task(self):+ @parameterized.expand([("mobile", True), ("web", False), ("", False)])+ def test_create_task(self, platform: str, mobile_origin: bool):response = self.client.post("/api/projects/@current/tasks/",{@@ -2012,6 +2013,7 @@ class TestTaskAPI(BaseTaskAPITest):"repository": "posthog/posthog",},format="json",+ HTTP_X_POSTHOG_CLIENT_PLATFORM=platform,)self.assertEqual(response.status_code, status.HTTP_201_CREATED)@@ -2023,6 +2025,8 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(data["runtime"], Task.Runtime.ACP)self.assertIsNone(data["latest_run"])+ self.assertIs((Task.objects.get(id=data["id"]).state or {})["created_on_mobile"], mobile_origin)+@parameterized.expand([False, True])@patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")@@ -7709,6 +7713,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"prior_run_tags": ["prior-tag"],"interaction_origin": "slack","slack_actor_user_id": self.user.id,+ "slack_actor_slack_user_id": "U_ORIGINAL_ACTOR","run_source": "manual",},)@@ -7804,6 +7809,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"prior_run_tags": ["forged-prior-tag"],"interaction_origin": "desktop","slack_actor_user_id": credential_target.id,+ "slack_actor_slack_user_id": "U_OTHER_ACTOR","run_source": "signal_report","dev_stack_preview": {"port": 8080, "sandbox_id": "sb-real"},"scratch": "ok",@@ -7874,6 +7880,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["prior_run_tags"] == ["prior-tag"]assert run.state["interaction_origin"] == "slack"assert run.state["slack_actor_user_id"] == self.user.id+ assert run.state["slack_actor_slack_user_id"] == "U_ORIGINAL_ACTOR"assert run.state["run_source"] == "manual"assert run.state["scratch"] == "ok" # non-protected keys still mergeassert run.state["systemPrompt"] == system_prompt@@ -7940,6 +7947,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"prior_run_tags","interaction_origin","slack_actor_user_id",+ "slack_actor_slack_user_id","run_source","scratch",],@@ -7994,6 +8002,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["prior_run_tags"] == ["prior-tag"]assert run.state["interaction_origin"] == "slack"assert run.state["slack_actor_user_id"] == self.user.id+ assert run.state["slack_actor_slack_user_id"] == "U_ORIGINAL_ACTOR"assert run.state["run_source"] == "manual"assert "scratch" not in run.state # non-protected key removedassert run.state["systemPrompt"] == system_prompt@@ -8016,6 +8025,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"task_management_ci_idle_skips": 0,"task_management_ci_wait_checks": 0,"pending_external_followups_checkpoint": {"generation": 99},+ "slack_actor_slack_user_id": ["U_OTHER_ACTOR"],"scratch": "ok",}},@@ -8034,6 +8044,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["task_management_ci_idle_skips"] == 1assert run.state["task_management_ci_wait_checks"] == 10assert run.state["pending_external_followups_checkpoint"] == {"generation": 8}+ assert run.state["slack_actor_slack_user_id"] == "U_ORIGINAL_ACTOR"@patch("products.tasks.backend.facade.api.signal_workflow_completion")def test_update_run_status_to_completed_signals_workflow(self, mock_signal):@@ -14239,13 +14250,18 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self._command_url(task, run),self._make_user_message(),format="json",+ HTTP_X_POSTHOG_CLIENT_PLATFORM="mobile",)if not subscription_owner_matches:assert response.status_code == status.HTTP_403_FORBIDDEN+ task.refresh_from_db()+ self.assertNotIn(self.user.id, (task.state or {}).get("mobile_push_user_ids", []))mock_signal_followup.assert_not_called()returnself.assertEqual(response.status_code, status.HTTP_200_OK)+ task.refresh_from_db()+ self.assertEqual((task.state or {})["mobile_push_user_ids"], [self.user.id])data = response.json()self.assertEqual(data["jsonrpc"], "2.0")self.assertTrue(data["result"]["queued"])@@ -14254,6 +14270,22 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):run.workflow_id, "Hello agent", [], "req-1", self.user.id, None, steer=False)+ @patch("products.tasks.backend.mobile_push.record_mobile_pickup", side_effect=RuntimeError("database unavailable"))+ @patch("products.tasks.backend.temporal.client.signal_task_followup_message")+ def test_successful_message_survives_mobile_pickup_persistence_failure(self, mock_signal, mock_pickup):+ task = self.create_task()+ run = self._create_run_with_sandbox(task)+ response = self.client.post(+ self._command_url(task, run),+ self._make_user_message(),+ format="json",+ HTTP_X_POSTHOG_CLIENT_PLATFORM="mobile",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json()["result"]["queued"])+ mock_signal.assert_called_once()+ mock_pickup.assert_called_once()+@patch("products.tasks.backend.temporal.client.signal_task_followup_message")def test_command_signals_steer_intent(self, mock_signal_followup):task = self.create_task()@@ -14551,11 +14583,15 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self._command_url(task, run),self._make_user_message(),format="json",+ HTTP_X_POSTHOG_CLIENT_PLATFORM="mobile",)self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)self.assertEqual(response.json()["error"], "Failed to queue user message for task run")+ task.refresh_from_db()+ self.assertNotIn("mobile_push_user_ids", task.state or {})+@parameterized.expand([("workflow_missing", TaskRun.Status.IN_PROGRESS, False, 409),@@ -15119,13 +15155,14 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertTrue(response.json()["result"]["closed"])+ @parameterized.expand([("accepted", True), ("rejected", False)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.presentation.views.api.http_requests.post")- def test_command_proxies_permission_response(self, mock_post):+ def test_command_proxies_permission_response(self, _name, acknowledged, mock_post):reset_sandbox_jwt_key_cache()self._mock_agent_response(mock_post,- {"jsonrpc": "2.0", "id": "req-4", "result": {"acknowledged": True}},+ {"jsonrpc": "2.0", "id": "req-4", "result": {"resolved": acknowledged}},)task = self.create_task()@@ -15140,6 +15177,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):"id": "req-4",},format="json",+ HTTP_X_POSTHOG_CLIENT_PLATFORM="mobile",)self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -15148,6 +15186,9 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(call_kwargs["json"]["params"]["requestId"], "perm-1")self.assertEqual(call_kwargs["json"]["params"]["optionId"], "allow")+ task.refresh_from_db()+ self.assertEqual((task.state or {}).get("mobile_push_user_ids", []), [self.user.id] if acknowledged else [])+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.presentation.views.api.http_requests.post")def test_command_proxies_set_config_option(self, mock_post):@@ -15169,6 +15210,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):"id": "req-5",},format="json",+ HTTP_X_POSTHOG_CLIENT_PLATFORM="mobile",)self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -15177,6 +15219,9 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(call_kwargs["json"]["params"]["configId"], "mode")self.assertEqual(call_kwargs["json"]["params"]["value"], "plan")+ task.refresh_from_db()+ self.assertNotIn("mobile_push_user_ids", task.state or {})+@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")def test_patch_cannot_forge_the_gateway_pin_stamp(self, _mock_publish):task = self.create_task()@@ -16605,12 +16650,16 @@ class TestSandboxEnvironmentAPI(BaseTaskAPITest):f"/api/projects/@current/tasks/{task.id}/run/",{"mode": "background", "sandbox_environment_id": str(env.id)},format="json",+ HTTP_X_POSTHOG_CLIENT_PLATFORM="mobile",)self.assertEqual(response.status_code, status.HTTP_200_OK)task_run = TaskRun.objects.filter(task=task).latest("created_at")self.assertEqual(task_run.state.get("sandbox_environment_id"), str(env.id))+ task.refresh_from_db()+ self.assertEqual((task.state or {})["mobile_push_user_ids"], [self.user.id])+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_task_rejects_invalid_sandbox_environment_id(self, mock_workflow):task = self.create_task()@@ -17046,11 +17095,17 @@ class TestCloudUsageGate(BaseTaskAPITest):state={"pr_authorship_mode": "bot"},)- response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/")+ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/",+ HTTP_X_POSTHOG_CLIENT_PLATFORM="mobile",+ )self.assertEqual(response.status_code, status.HTTP_200_OK)mock_resume.assert_called_once()+ task.refresh_from_db()+ self.assertEqual((task.state or {})["mobile_push_user_ids"], [self.user.id])+@parameterized.expand([("inbox_task", True, status.HTTP_200_OK),diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex 136af39356c2..084e612de371 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -1090,8 +1090,15 @@ class TaskMentionsAPITestCase(ChannelTaskAPITestCase):# The author wasn't mentioned, so their own feed stays empty.self.assertEqual(self.author_client.get(self._mentions_url()).json(), [])+ @parameterized.expand([("mobile", True), ("web", False), ("slack", False), ("picked_up_web", True)])@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")- def test_thread_message_notifies_creator_and_mentions_only(self, mock_delay):+ def test_thread_message_notifies_creator_and_mentions_only(self, source, eligible, mock_delay):+ self.task.state = {"created_on_mobile": source == "mobile"}+ if source == "picked_up_web":+ self.task.state["mobile_push_user_ids"] = [self.author.id, self.peer.id]+ if source == "slack":+ self.task.origin_product = Task.OriginProduct.SLACK+ self.task.save(update_fields=["state", "origin_product"])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)@@ -1099,11 +1106,18 @@ class TaskMentionsAPITestCase(ChannelTaskAPITestCase):with self.captureOnCommitCallbacks(execute=True):message = self._post_message(self.peer_client, "ping @[Mina]([email protected])")+ if not eligible:+ mock_delay.assert_not_called()+ return+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(+ set(calls_by_user_id), {self.author.id} if source == "picked_up_web" else {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])+ if source != "picked_up_web":+ 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):@@ -1118,6 +1132,8 @@ class TaskMentionsAPITestCase(ChannelTaskAPITestCase):@patch("products.tasks.backend.facade.api.TaskActivity.record", side_effect=RuntimeError("db is down"))@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")def test_mention_activity_failure_does_not_discard_push_recipients(self, mock_delay, _record):+ self.task.state = {"created_on_mobile": True}+ self.task.save(update_fields=["state"])mentioned = User.objects.create_user(email="[email protected]", first_name="Mina", password="password")self.organization.members.add(mentioned)diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex a4ea8010f683..7e4cecbda412 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -666,15 +666,19 @@ class TestTaskRunEventIngest(TestCase):@parameterized.expand([- ("interactive", "interactive", True),- ("background", "background", False),+ ("interactive", "interactive", True, True),+ ("background", "background", True, False),+ ("web", "interactive", False, False),])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)- def test_permission_request_ingest_pushes_awaiting_input(self, _name: str, mode: str, expect_push: bool) -> None:+ def test_permission_request_ingest_pushes_awaiting_input(+ self, _name: str, mode: str, created_on_mobile: bool, expect_push: bool+ ) -> None:creator = User.objects.create_and_join(self.organization, "[email protected]", None)self.task.created_by = creator- self.task.save(update_fields=["created_by"])+ self.task.state = {"created_on_mobile": created_on_mobile}+ self.task.save(update_fields=["created_by", "state"])self.task_run.state = {**(self.task_run.state or {}), "mode": mode}self.task_run.save(update_fields=["state"])token = self._create_token()@@ -710,10 +714,11 @@ class TestTaskRunEventIngest(TestCase):self.assertEqual(data,{+ "type": "task","taskId": str(self.task.id),"taskRunId": str(self.task_run.id),"notificationKind": "awaiting",- "projectId": str(self.task.team_id),+ "projectId": self.task.team_id,},)diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.pyindex 9fab7b2adb24..da6043956776 100644--- a/products/tasks/backend/tests/test_post_slack_update.py+++ b/products/tasks/backend/tests/test_post_slack_update.py@@ -57,6 +57,18 @@ class TestPostSlackUpdate(TestCase):setattr(mock_run, k, v)return mock_run+ @patch.object(SlackThreadHandler, "proactive_notifications_muted", return_value=True)+ @patch.object(SlackThreadHandler, "delete_progress")+ @patch.object(SlackThreadHandler, "post_completion")+ @patch("products.tasks.backend.models.TaskRun")+ def test_mobile_takeover_silences_private_lifecycle_notifications(+ self, runs: MagicMock, completion: MagicMock, delete_progress: MagicMock, _muted: MagicMock+ ) -> None:+ runs.objects.select_related.return_value.get.return_value = self._make_mock_run(runs.Status.COMPLETED)+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))+ completion.assert_not_called()+ delete_progress.assert_called_once()+@patch.object(SlackThreadHandler, "post_pr_opened")@patch.object(SlackThreadHandler, "update_reaction")@patch("products.tasks.backend.models.TaskRun")diff --git a/products/tasks/backend/tests/test_presence.py b/products/tasks/backend/tests/test_presence.pyindex 9bac8ab3d23b..06d7ff39a268 100644--- a/products/tasks/backend/tests/test_presence.py+++ b/products/tasks/backend/tests/test_presence.py@@ -186,6 +186,7 @@ class PresenceFanoutSuppressionTestCase(TestCase):team=self.team,created_by=self.user,title="Watching Task",+ state={"created_on_mobile": True},description="d",origin_product=Task.OriginProduct.USER_CREATED,)diff --git a/products/tasks/backend/tests/test_push_dispatcher.py b/products/tasks/backend/tests/test_push_dispatcher.pyindex 3a9cefe52c9d..b42dfb17e8f7 100644--- a/products/tasks/backend/tests/test_push_dispatcher.py+++ b/products/tasks/backend/tests/test_push_dispatcher.py@@ -2,28 +2,35 @@ from contextlib import nullcontextfrom uuid import uuid4import time_machine-from unittest.mock import patch+from unittest.mock import Mock, patch-from django.core.cache import cachefrom django.db import InterfaceError, OperationalError, transactionfrom django.test import TestCasefrom parameterized import parameterizedfrom prometheus_client import REGISTRY+from posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, Team, User+from posthog.models.user_push_token import UserPushTokenfrom posthog.tasks.push_notifications import send_user_push+from products.access_control.backend.models.access_control import AccessControl+from products.signals.backend.models import SignalReport+from products.signals.backend.task_run_artefacts import append_task_run_artefactfrom products.tasks.backend.awaiting_input import dispatch_awaiting_input+from products.tasks.backend.mobile_push import mobile_push_user_ids, record_mobile_pickupfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.push_dispatcher import (notify_task_handoff,+ notify_task_pull_request_outcome,notify_task_run_awaiting_input,notify_task_run_cancelled,notify_task_run_completed,notify_task_run_failed,notify_task_run_turn_completed,)+from products.tasks.backend.redis import get_tasks_cache# The Celery dispatch is deferred via transaction.on_commit, which never fires@@ -32,7 +39,7 @@ from products.tasks.backend.push_dispatcher import (# none was registered) without TransactionTestCase's per-test full-DB flush.class TestPushDispatcher(TestCase):def setUp(self) -> None:- cache.clear()+ get_tasks_cache().clear()self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")self.user = User.objects.create_user(email="[email protected]", first_name="Push", password="password")@@ -44,6 +51,7 @@ class TestPushDispatcher(TestCase):title="My Task",description="desc",origin_product=Task.OriginProduct.USER_CREATED,+ state={"created_on_mobile": True},created_by=self.user,)self.task_run = TaskRun.objects.create(task=self.task, team=self.team)@@ -67,7 +75,7 @@ class TestPushDispatcher(TestCase):self.assertEqual(title, "PostHog")self.assertIn(expected_body_fragment, body)self.assertEqual(data["taskId"], str(self.task.id))- self.assertEqual(data["projectId"], str(self.task.team_id))+ self.assertEqual(data["projectId"], self.task.team_id)self.assertEqual(data["taskRunId"], str(self.task_run.id))self.assertEqual(data["notificationKind"], _name)# No presence rows in this test's setUp, so nothing to suppress.@@ -105,10 +113,31 @@ class TestPushDispatcher(TestCase):notify_task_run_turn_completed(self.task_run)self.assertEqual(mock_delay.call_count, 3)+ def _link_report_work(self, relationship: str) -> None:+ report = SignalReport.objects.create(+ team=self.team, status=SignalReport.Status.READY, first_visible_at="2026-10-20T12:00:00Z"+ )+ self.task.signal_report = report+ self.task.save(update_fields=["signal_report"])+ append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type=relationship,+ task_id=str(self.task.id),+ run_id=str(self.task_run.id),+ )++ @parameterized.expand([None, "implementation", "research"])@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")- def test_awaiting_cooldown_is_shared_by_permission_requests_and_turn_end(self, mock_delay) -> None:+ @patch("products.signals.backend.inbox_push_notifications.posthoganalytics.feature_enabled", return_value=True)+ def test_awaiting_cooldown_is_shared_by_permission_requests_and_turn_end(+ self, relationship: str | None, _flag: Mock, mock_delay: Mock+ ) -> None:self.task_run.state = {"mode": "interactive"}with time_machine.travel("2026-10-20T12:00:00Z", tick=False) as clock:+ if relationship is not None:+ self._link_report_work(relationship)with self.captureOnCommitCallbacks(execute=True):dispatch_awaiting_input(self.task_run, request_id="request-1")dispatch_awaiting_input(self.task_run, request_id="request-2")@@ -117,34 +146,47 @@ class TestPushDispatcher(TestCase):clock.shift(31)with self.captureOnCommitCallbacks(execute=True):- dispatch_awaiting_input(self.task_run, request_id="request-1")- dispatch_awaiting_input(self.task_run, request_id="request-3")+ self.assertFalse(dispatch_awaiting_input(self.task_run, request_id="request-1"))+ self.assertTrue(dispatch_awaiting_input(self.task_run, request_id="request-3"))self.assertEqual(mock_delay.call_count, 2)+ self.assertEqual(mock_delay.call_args.args[3]["type"], "report" if relationship else "task")- @parameterized.expand(["prepare", "immediate", "deferred", "rollback"])- def test_awaiting_request_can_retry_after_failed_enqueue(self, failure: str) -> None:+ @parameterized.expand(+ [(failure, None) for failure in ("prepare", "immediate", "deferred", "rollback")]+ + [+ (failure, relationship)+ for failure in ("immediate", "deferred", "rollback")+ for relationship in ("implementation", "research")+ ]+ )+ def test_awaiting_request_can_retry_after_failed_enqueue(self, failure: str, relationship: str | None) -> None:self.task_run.state = {"mode": "interactive"}with (time_machine.travel("2026-10-20T12:00:00Z", tick=False) as clock,+ patch(+ "products.signals.backend.inbox_push_notifications.posthoganalytics.feature_enabled", return_value=True+ ),patch("products.tasks.backend.push_dispatcher._project_awaiting_input_activity"),patch("products.tasks.backend.push_dispatcher.send_user_push.delay") as send_push,):+ if relationship is not None:+ self._link_report_work(relationship)send_push.side_effect = RuntimeError("broker unavailable")with (patch(- "products.tasks.backend.push_dispatcher._suppressed_push_token_ids_for_task",+ "products.tasks.backend.push_dispatcher.suppressed_push_token_ids_for_task",side_effect=OperationalError("connection unavailable"),)if failure == "prepare"else nullcontext(),- patch("products.tasks.backend.push_dispatcher.transaction.on_commit", side_effect=lambda fn: fn())+ patch("products.tasks.backend.push_dispatcher.transaction.on_commit", side_effect=lambda fn, **_: fn())if failure == "immediate"else nullcontext(),self.captureOnCommitCallbacks(execute=True),transaction.atomic(),):scheduled = dispatch_awaiting_input(self.task_run, request_id="retry-request")- self.assertEqual(scheduled, failure in ("deferred", "rollback"))+ self.assertEqual(scheduled, relationship is not None or failure in ("deferred", "rollback"))if failure == "rollback":transaction.set_rollback(True)self.assertEqual(send_push.call_count, int(failure in ("immediate", "deferred")))@@ -231,6 +273,201 @@ class TestPushDispatcher(TestCase):after = REGISTRY.get_sample_value("posthog_tasks_push_dispatcher_failures_total", labels) or 0.0self.assertEqual(after, before + 1)+ @parameterized.expand(+ [+ ("web", {}, Task.OriginProduct.USER_CREATED),+ ("web_later_run_mobile", {"created_on_mobile": False}, Task.OriginProduct.USER_CREATED),+ ("slack", {"created_on_mobile": True}, Task.OriginProduct.SLACK),+ ]+ )+ @patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ def test_nonmobile_tasks_never_enqueue(self, _name, state, origin, mock_delay, _flag):+ self.task.state = state+ self.task.origin_product = origin+ self.task.save(update_fields=["state", "origin_product"])+ self.task_run.state = {"client_platform": "mobile"}+ self.task_run.save(update_fields=["state"])+ with self.captureOnCommitCallbacks(execute=True):+ for notify in (+ notify_task_run_completed,+ notify_task_run_failed,+ notify_task_run_cancelled,+ notify_task_run_awaiting_input,+ notify_task_run_turn_completed,+ ):+ notify(self.task_run)+ notify_task_handoff(self.task, recipient=self.user, actor=self.user, message_id=uuid4())+ mock_delay.assert_not_called()++ @parameterized.expand([("mobile_push_enabled",), ("mobile_push_tasks_enabled",)])+ @patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ @patch("posthog.tasks.push_notifications.send_push_to_user")+ def test_preferences_stop_new_and_queued_pushes(self, key, mock_send, mock_delay, _flag):+ self.user.partial_notification_settings = {key: False}+ self.user.save(update_fields=["partial_notification_settings"])+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_run_completed(self.task_run)+ send_user_push(+ self.user.id, "PostHog", "Finished", {"taskId": str(self.task.id), "projectId": self.task.team_id}+ )+ mock_delay.assert_not_called()+ mock_send.assert_not_called()++ @parameterized.expand(+ [+ ("web_active", Task.OriginProduct.USER_CREATED, True),+ ("web_inactive", Task.OriginProduct.USER_CREATED, False),+ ("slack_active", Task.OriginProduct.SLACK, True),+ ("slack_inactive", Task.OriginProduct.SLACK, False),+ ]+ )+ @patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ @patch("posthog.push_notifications.requests.post")+ def test_mobile_pickup_enables_existing_task_and_queued_delivery(+ self, _name: str, origin: str, is_active: bool, mock_post: Mock, mock_delay: Mock, _flag: Mock+ ) -> None:+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[mobile-pickup]", platform="ios")+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"data": [{"status": "ok"}]}+ self.task.origin_product = origin+ self.task.state = {"created_on_mobile": False}+ self.task.save(update_fields=["origin_product", "state"])+ record_mobile_pickup(task_id=self.task.id, team_id=self.team.id, user_id=self.user.id)+ record_mobile_pickup(task_id=self.task.id, team_id=self.team.id, user_id=self.user.id)+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_run_completed(self.task_run)+ mock_delay.assert_called_once()+ User.objects.filter(id=self.user.id).update(is_active=is_active)+ send_user_push(*mock_delay.call_args.args)+ if is_active:+ mock_post.assert_called_once()+ else:+ mock_post.assert_not_called()+ self.task.refresh_from_db()+ self.assertEqual(mobile_push_user_ids(self.task), {self.user.id})+ self.assertIs(self.task.state["created_on_mobile"], False)++ @parameterized.expand([None, "enqueue", "delivery"])+ @patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ @patch("posthog.push_notifications.requests.post")+ def test_mobile_pickup_fanout_is_per_user_and_refreshes_cached_task(+ self, revoke_at: str | None, mock_post: Mock, mock_delay: Mock, _flag: Mock+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(team=self.team, resource="task", access_level="none")+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"data": [{"status": "ok"}]}+ self.task.origin_product = Task.OriginProduct.WORKFLOW+ self.task.state = {}+ self.task.save(update_fields=["origin_product", "state"])+ picked = [+ User.objects.create_and_join(self.organization, f"picked-{index}@example.com", None) for index in range(2)+ ]+ for user in picked:+ record_mobile_pickup(task_id=self.task.id, team_id=self.team.id, user_id=user.id)+ AccessControl.objects.create(+ team=self.team,+ resource="task",+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=user),+ access_level="viewer",+ )+ UserPushToken.objects.create(user=user, token=f"ExponentPushToken[picked-{user.id}]", platform="ios")++ def revoke_access() -> None:+ AccessControl.objects.filter(team=self.team, resource="task", organization_member__user=picked[0]).update(+ access_level="none"+ )++ if revoke_at == "enqueue":+ revoke_access()+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_run_completed(self.task_run)+ notify_task_run_completed(self.task_run)+ enqueued_users = picked[1:] if revoke_at == "enqueue" else picked+ self.assertEqual({call.args[0] for call in mock_delay.call_args_list}, {user.id for user in enqueued_users})+ self.assertEqual(mock_delay.call_count, len(enqueued_users))+ if revoke_at == "delivery":+ revoke_access()+ for call in mock_delay.call_args_list:+ send_user_push(*call.args)+ delivered_users = picked if revoke_at is None else picked[1:]+ self.assertEqual(+ {call.kwargs["json"][0]["to"] for call in mock_post.call_args_list},+ {f"ExponentPushToken[picked-{user.id}]" for user in delivered_users},+ )++ @parameterized.expand(+ [+ (outcome, merged, failure)+ for outcome, merged in [("merged", True), ("closed", False)]+ for failure in (None, "redis", "broker", "rollback")+ ]+ )+ @patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")+ def test_pr_outcomes_are_durable_per_user_and_pr(self, outcome, merged, failure, mock_delay, _flag):+ self.task.origin_product = Task.OriginProduct.SLACK+ self.task.state = {"mobile_push_user_ids": [self.user.id]}+ self.task.save(update_fields=["origin_product", "state"])+ pr_url = "https://github.com/example/project/pull/1"+ if failure is not None:++ def notify() -> None:+ notify_task_pull_request_outcome(+ task_id=str(self.task.id),+ run_id=str(self.task_run.id),+ team_id=self.team.id,+ pr_url=pr_url,+ merged=merged,+ )++ if failure == "rollback":+ with self.captureOnCommitCallbacks(execute=True):+ with self.assertRaises(RuntimeError), transaction.atomic():+ notify()+ raise RuntimeError("rollback")+ else:+ boundary = (+ patch.object(get_tasks_cache(), "add", side_effect=RuntimeError("redis unavailable"))+ if failure == "redis"+ else patch.object(mock_delay, "side_effect", RuntimeError("broker unavailable"))+ )+ with boundary, self.captureOnCommitCallbacks(execute=True):+ notify()+ self.task.refresh_from_db()+ self.assertEqual((self.task.state or {}).get("mobile_push_pr_outcomes", []), [])+ mock_delay.reset_mock(side_effect=True)+ for _ in range(2):+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_pull_request_outcome(+ task_id=str(self.task.id),+ run_id=str(self.task_run.id),+ team_id=self.team.id,+ pr_url=pr_url,+ merged=merged,+ )+ get_tasks_cache().clear()+ mock_delay.assert_called_once()+ self.assertEqual(mock_delay.call_args.args[1:3], ("PostHog", f'"My Task" pull request was {outcome}'))+ self.assertEqual(mock_delay.call_args.args[3]["pullRequestUrl"], pr_url)+ self.assertEqual(mock_delay.call_args.args[3]["notificationKind"], f"pr_{outcome}")+ with self.captureOnCommitCallbacks(execute=True):+ notify_task_pull_request_outcome(+ task_id=str(self.task.id),+ run_id=str(self.task_run.id),+ team_id=self.team.id,+ pr_url="https://github.com/example/project/pull/2",+ merged=merged,+ )+ self.assertEqual(mock_delay.call_count, 2)+@patch("products.tasks.backend.push_dispatcher.notify_task_run_completed")def test_mark_completed_triggers_push(self, mock_notify):self.task_run.mark_completed()@@ -241,8 +478,9 @@ class TestPushDispatcher(TestCase):self.task_run.mark_failed("nope")mock_notify.assert_called_once_with(self.task_run)+ @patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=False)@patch("posthog.tasks.push_notifications.send_push_to_user", return_value=2)- def test_delivery_task_records_expo_acceptance(self, mock_send):+ def test_delivery_task_records_expo_acceptance(self, mock_send, _flag):labels = {"kind": "completed", "outcome": "accepted"}before = REGISTRY.get_sample_value("posthog_push_delivery_outcomes_total", labels) or 0.0@@ -250,7 +488,7 @@ class TestPushDispatcher(TestCase):self.user.id,"posthog","Finished",- {"notificationKind": "completed"},+ {"notificationKind": "completed", "taskId": str(self.task.id), "projectId": self.task.team_id},)mock_send.assert_called_once()diff --git a/products/tasks/backend/tests/test_slack_pr_cards.py b/products/tasks/backend/tests/test_slack_pr_cards.pyindex 59507aeb949b..541867baf5f5 100644--- a/products/tasks/backend/tests/test_slack_pr_cards.py+++ b/products/tasks/backend/tests/test_slack_pr_cards.py@@ -58,6 +58,17 @@ class TestPostPrClosedSlackUpdate(TestCase):footer_patcher.start()self.addCleanup(footer_patcher.stop)+ @patch.object(SlackThreadHandler, "post_pr_closed", return_value=True)+ def test_mobile_takeover_silences_proactive_private_pr_cards(self, post: MagicMock) -> None:+ SlackThreadTaskMapping.objects.create(+ **self.mapping_kwargs, conversation_type=SlackThreadTaskMapping.ConversationType.IM+ )+ self.task.state = {**(self.task.state or {}), "mobile_push_user_ids": [self.task.created_by_id]}+ self.task.save(update_fields=["state"])++ assert not post_pr_closed_slack_update(str(self.task_run.id), PR_URL)+ post.assert_not_called()+@parameterized.expand([("announced_pr", PR_URL, True, [1, 0]),diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex 66d5ee8f4186..679b5815275f 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -560,17 +560,21 @@ class TestGitHubPRWebhook(TestCase):@parameterized.expand([- ("announced_pr_closed", "https://github.com/posthog/posthog/pull/790", False, 1),- ("announced_pr_merged", "https://github.com/posthog/posthog/pull/790", True, 1),- ("unannounced_pr_closed", "https://github.com/posthog/posthog/pull/791", False, 0),+ ("announced_pr_closed", "https://github.com/posthog/posthog/pull/790", False, 1, False),+ ("announced_pr_merged", "https://github.com/posthog/posthog/pull/790", True, 1, False),+ ("unannounced_pr_closed", "https://github.com/posthog/posthog/pull/791", False, 0, False),+ ("picked_before_pr_open_closed", "https://github.com/posthog/posthog/pull/791", False, 0, True),+ ("picked_before_pr_open_merged", "https://github.com/posthog/posthog/pull/791", True, 0, True),])@patch("posthog.credentials_service.instance_settings.get_instance_setting")@patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_closed_queues_slack_thread_notice(- self, _name, pr_url, merged, expected_enqueues, _mock_capture, mock_get_secret+ self, _name, pr_url, merged, expected_enqueues, picked_up, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret+ if picked_up:+ self.organization.members.add(self.user)task = Task.objects.create(team=self.team,created_by=self.user,@@ -578,7 +582,9 @@ class TestGitHubPRWebhook(TestCase):description="",origin_product=Task.OriginProduct.SLACK,repository="posthog/posthog",- state={"slack_notified_pr_url": "https://github.com/posthog/posthog/pull/790"},+ state={"mobile_push_user_ids": [self.user.id]}+ if picked_up+ else {"slack_notified_pr_url": "https://github.com/posthog/posthog/pull/790"},)run = TaskRun.objects.create(task=task,@@ -589,9 +595,18 @@ class TestGitHubPRWebhook(TestCase):)payload = self._merged_pr_payload(pr_url) if merged else self._closed_pr_payload(pr_url)- with patch("products.tasks.backend.tasks.tasks.notify_slack_thread_pr_closed.delay") as mock_delay:+ with (+ patch("products.tasks.backend.tasks.tasks.notify_slack_thread_pr_closed.delay") as mock_delay,+ patch("products.tasks.backend.push_dispatcher.send_user_push.delay") as mock_push,+ patch("posthog.push_notifications.posthoganalytics.feature_enabled", return_value=True),+ ):with self.captureOnCommitCallbacks(execute=True):response = self._make_webhook_request(payload)+ if picked_up:+ cache.clear()+ with self.captureOnCommitCallbacks(execute=True):+ self._make_webhook_request(payload)+ self.assertEqual(mock_push.call_count, int(picked_up))self.assertEqual(response.status_code, 202)self.assertEqual(mock_delay.call_count, expected_enqueues)diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex d02f303b94ff..8dde06c63c39 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -316,6 +316,20 @@ def handle_pull_request_event(payload: dict) -> None:_cancel_wizard_run_on_close(task_run)if action == "closed" and task_run and pr_url in claimed_pr_urls:+ from products.tasks.backend.push_dispatcher import (+ notify_task_pull_request_outcome, # noqa: PLC0415 — keep push imports off the webhook import path+ )++ transaction.on_commit(+ lambda: notify_task_pull_request_outcome(+ task_id=str(task_run.task_id),+ run_id=str(task_run.id),+ team_id=task_run.team_id,+ pr_url=pr_url,+ merged=merged,+ ),+ robust=True,+ )_notify_slack_thread_on_close(task_run, pr_url, merged=merged)