Skip to content

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

feat(tasks): per-device presence beacon for push fanout (#59313)

Dylan Martined2c31e92df1
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 9f0b0ee51d4f..69798d074e8a 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -210,6 +210,7 @@ rules:
|Tagger
|Task
|TaskAutomation
+ |TaskPresence
|TaskRun
|EmailChannel
|EvaluationReport
@@ -431,6 +432,7 @@ rules:
|Tagger
|Task
|TaskAutomation
+ |TaskPresence
|TaskRun
|EmailChannel
|EvaluationReport
diff --git a/posthog/push_notifications.py b/posthog/push_notifications.py
index f240c2decbe4..314eb7056297 100644
--- a/posthog/push_notifications.py
+++ b/posthog/push_notifications.py
@@ -14,6 +14,7 @@ Reference: https://docs.expo.dev/push-notifications/sending-notifications/
from __future__ import annotations
+import uuid
from collections.abc import Iterable
from typing import Any, cast
@@ -36,15 +37,27 @@ def send_push_to_user(
title: str,
body: str,
data: dict[str, Any] | None = None,
+ suppressed_push_token_ids: Iterable[uuid.UUID | str] | None = None,
) -> int:
"""Send a push notification to every device registered for ``user``.
+ ``suppressed_push_token_ids`` lets the caller (typically a feature-specific
+ dispatcher) drop devices that have proven they're already watching the
+ relevant context — e.g. presence beacons on a PostHog Code task. Tokens
+ whose ``UserPushToken.id`` is in the set are skipped before fanout, even
+ if that leaves the user with zero recipients. The contract is "if any
+ device is provably watching, suppress the others", so an empty post-filter
+ list intentionally results in no push being sent.
+
Returns the number of messages the Expo service accepted (i.e. for which
a non-error ticket was returned). Tokens flagged by Expo as
``DeviceNotRegistered`` are deleted for this user so we stop trying to
deliver to dead devices.
"""
- tokens = list(UserPushToken.objects.filter(user=user).values_list("token", flat=True))
+ qs = UserPushToken.objects.filter(user=user)
+ if suppressed_push_token_ids:
+ qs = qs.exclude(id__in=list(suppressed_push_token_ids))
+ tokens = list(qs.values_list("token", flat=True))
if not tokens:
return 0
diff --git a/posthog/tasks/push_notifications.py b/posthog/tasks/push_notifications.py
index 2e4cbf1c481f..3cdf24b2b598 100644
--- a/posthog/tasks/push_notifications.py
+++ b/posthog/tasks/push_notifications.py
@@ -22,12 +22,23 @@ logger = structlog.get_logger(__name__)
@shared_task(ignore_result=True)
@skip_team_scope_audit
-def send_user_push(user_id: int, title: str, body: str, data: dict[str, Any] | None = None) -> None:
+def send_user_push(
+ user_id: int,
+ title: str,
+ body: str,
+ data: dict[str, Any] | None = None,
+ suppressed_push_token_ids: list[str] | None = None,
+) -> None:
"""Fan out a push notification to every device registered for ``user_id``.
User push tokens are user-scoped, not team-scoped, so this task intentionally
operates outside the team-scoping audit. The downstream ``send_push_to_user``
helper filters tokens by ``user=user`` — there is no cross-team query happening.
+
+ ``suppressed_push_token_ids`` (UUIDs of ``UserPushToken`` rows) are dropped
+ from the fanout, so callers can pre-compute a "skip these devices" set —
+ e.g. devices whose presence beacon says they're already watching the task
+ that triggered this push.
"""
try:
user = User.objects.get(pk=user_id)
@@ -36,6 +47,12 @@ def send_user_push(user_id: int, title: str, body: str, data: dict[str, Any] | N
return
try:
- send_push_to_user(user, title=title, body=body, data=data)
+ send_push_to_user(
+ user,
+ title=title,
+ body=body,
+ data=data,
+ suppressed_push_token_ids=suppressed_push_token_ids,
+ )
except Exception:
logger.warning("send_user_push.failed", user_id=user_id, exc_info=True)
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index d451c54b27a6..1a5e01aafcc5 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -5,7 +5,7 @@ import asyncio
import logging
import builtins
from collections.abc import AsyncGenerator
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any, cast
from django.conf import settings
@@ -34,6 +34,7 @@ from posthog.api.utils import ServerTimingsGathered
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.event_usage import groups
from posthog.models.integration import Integration
+from posthog.models.user_push_token import UserPushToken
from posthog.permissions import APIScopePermission
from posthog.rate_limit import CodeInviteThrottle
from posthog.renderers import ServerSentEventRenderer
@@ -48,7 +49,16 @@ from .automation_service import (
sync_automation_schedule,
update_automation_run_result,
)
-from .models import CodeInvite, CodeInviteRedemption, SandboxEnvironment, Task, TaskAutomation, TaskRun
+from .models import (
+ TASK_PRESENCE_TTL_SECONDS,
+ CodeInvite,
+ CodeInviteRedemption,
+ SandboxEnvironment,
+ Task,
+ TaskAutomation,
+ TaskPresence,
+ TaskRun,
+)
from .repository_readiness import compute_repository_readiness
from .serializers import (
CodeInviteRedeemRequestSerializer,
@@ -59,6 +69,7 @@ from .serializers import (
SandboxEnvironmentSerializer,
TaskAutomationSerializer,
TaskListQuerySerializer,
+ TaskPresenceBeaconRequestSerializer,
TaskRepositoriesResponseSerializer,
TaskRunAppendLogRequestSerializer,
TaskRunArtifactPresignRequestSerializer,
@@ -839,6 +850,67 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return Response(TaskSerializer(task, context=self.get_serializer_context()).data)
+ @validated_request(
+ request_serializer=TaskPresenceBeaconRequestSerializer,
+ responses={
+ 204: OpenApiResponse(description="Presence recorded for this device."),
+ 404: OpenApiResponse(description="`device_id` does not match a push token registered by the caller."),
+ },
+ summary="Beacon presence for a device watching this task",
+ description=(
+ "Idempotent upsert: marks the calling user + `device_id` as actively watching this task "
+ "for the next ~60 seconds. While at least one device for the user has a non-expired "
+ "presence row for this task, the push fanout will skip ALL of that user's other "
+ "registered devices for task notifications — the contract is 'if any device is "
+ "demonstrably watching, suppress the others'. Clients call this every ~30s while the "
+ "task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row."
+ ),
+ )
+ @action(
+ detail=True,
+ methods=["post", "delete"],
+ url_path="presence",
+ required_scopes=["task:write"],
+ )
+ def presence(self, request, **kwargs):
+ if request.method == "DELETE":
+ return self._presence_leave(request)
+ return self._presence_beacon(request)
+
+ def _presence_beacon(self, request) -> Response:
+ task = cast(Task, self.get_object())
+ device_id = request.validated_data["device_id"]
+ push_token = UserPushToken.objects.filter(user=request.user, id=device_id).first()
+ if push_token is None:
+ raise NotFound("device_id does not match a push token registered by the caller")
+
+ # Lookup mirrors the unique constraint exactly so a stray row with a
+ # mismatched team/user (e.g. from a bug elsewhere) gets corrected on
+ # upsert instead of crashing into the constraint a second time.
+ # nosemgrep: idor-lookup-without-team — team scope is enforced by
+ # TaskScopedManager (DRF view sets the ContextVar) and via `task` FK
+ # whose row is fetched through self.get_object() above.
+ now = timezone.now()
+ TaskPresence.objects.update_or_create(
+ task=task,
+ push_token=push_token,
+ defaults={
+ "team": task.team,
+ "user": request.user,
+ "expires_at": now + timedelta(seconds=TASK_PRESENCE_TTL_SECONDS),
+ },
+ )
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ def _presence_leave(self, request) -> Response:
+ task = cast(Task, self.get_object())
+ device_id = request.validated_data["device_id"]
+ # No 404 on missing rows — the beacon-leave path runs from blur/background
+ # handlers that should be safe to call unconditionally without the client
+ # having to track whether a beacon was ever sent.
+ TaskPresence.objects.filter(task=task, push_token_id=device_id, user=request.user).delete()
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
@extend_schema(tags=["task-automations"])
class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
diff --git a/products/tasks/backend/migrations/0034_taskpresence.py b/products/tasks/backend/migrations/0034_taskpresence.py
new file mode 100644
index 000000000000..5cde22b93dd2
--- /dev/null
+++ b/products/tasks/backend/migrations/0034_taskpresence.py
@@ -0,0 +1,68 @@
+import uuid
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1166_oauth_impersonated_by"),
+ ("tasks", "0033_task_archived_idx"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TaskPresence",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
+ ),
+ ("last_seen_at", models.DateTimeField(auto_now=True)),
+ ("expires_at", models.DateTimeField(db_index=True)),
+ (
+ "task",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="tasks.task",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "push_token",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.userpushtoken",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_task_presence",
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="taskpresence",
+ constraint=models.UniqueConstraint(
+ fields=("task", "push_token"),
+ name="task_presence_task_push_token_unique",
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 18161e199045..c4da893389f1 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0033_task_archived_idx
+0034_taskpresence
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 39f2cb9dc6c6..a97003e7abd7 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -28,6 +28,7 @@ import posthoganalytics
from posthog.event_usage import groups
from posthog.helpers.encrypted_fields import EncryptedJSONStringField
from posthog.models.integration import Integration
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import DeletedMetaFields, UUIDModel
@@ -1306,6 +1307,61 @@ class CodeInviteRedemption(UUIDModel):
return f"{self.user} redeemed {self.invite_code}"
+# How long a single beacon keeps a device "present" before the row is treated as stale.
+# Clients beacon every ~30s; expiring after 60s gives them one missed POST of slack.
+TASK_PRESENCE_TTL_SECONDS = 60
+
+
+class TaskPresence(TeamScopedRootMixin):
+ """Per-device 'this user is actively watching this task' beacon.
+
+ Created/refreshed by the desktop and mobile PostHog Code clients while a
+ task screen is foregrounded. The push fanout consults this table to skip
+ devices that are demonstrably already watching the task, so we don't fire
+ phantom notifications at a phone while the user is mid-conversation with
+ the agent on their laptop.
+
+ Rows are ephemeral (expire after ``TASK_PRESENCE_TTL_SECONDS``). Cleanup is
+ lazy: every push fanout filters on ``expires_at > now``, so stale rows are
+ ignored automatically. We can layer a periodic sweep on top later if the
+ row count ever becomes a problem; for now there's nothing to maintain.
+ """
+
+ # nosemgrep: prefer-uuid7-django-pk -- mirrors sibling task models in this app
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ # `related_name="+"` on every FK so Django doesn't add reverse accessors
+ # (`user.task_presences`, etc.). Presence is always queried forward — by
+ # (task, user) or by push_token id — and skipping the reverse manager
+ # keeps frameworks that walk all reverse relations on related models
+ # (notably the User activity-logger) from tripping on this model's
+ # fail-closed manager when no team context is set.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
+ task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="+")
+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+")
+ # Identifies the device that's watching. Push fanout joins on this FK to
+ # decide which tokens to suppress, and CASCADE means unregistering the push
+ # token automatically clears the presence too.
+ push_token = models.ForeignKey(
+ "posthog.UserPushToken",
+ on_delete=models.CASCADE,
+ related_name="+",
+ )
+ last_seen_at = models.DateTimeField(auto_now=True)
+ expires_at = models.DateTimeField(db_index=True)
+
+ class Meta:
+ db_table = "posthog_task_presence"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["task", "push_token"],
+ name="task_presence_task_push_token_unique",
+ ),
+ ]
+
+ def __str__(self):
+ return f"Presence: user {self.user_id} on task {self.task_id} via device {self.push_token_id}"
+
+
@receiver(post_save, sender=TaskRun)
def track_task_run_completion(sender, instance: TaskRun, created: bool, **kwargs):
try:
diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.py
index 66ada6df574d..e2e7b6133fde 100644
--- a/products/tasks/backend/push_dispatcher.py
+++ b/products/tasks/backend/push_dispatcher.py
@@ -23,12 +23,16 @@ from typing import TYPE_CHECKING, Literal
from django.core.cache import cache
from django.db import transaction
+from django.utils import timezone
import structlog
import posthoganalytics
+from posthog.models.user_push_token import UserPushToken
from posthog.tasks.push_notifications import send_user_push
+from products.tasks.backend.models import TaskPresence
+
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
@@ -135,7 +139,33 @@ def _enqueue_inner(task_run: TaskRun, *, kind: PushKind, body: str) -> None:
return
data = {"taskId": str(task_run.task_id), "taskRunId": str(task_run.id)}
+ suppressed = _suppressed_push_token_ids_for_task(user_id=user.id, task_id=task_run.task_id)
# 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.
- transaction.on_commit(lambda: send_user_push.delay(user.id, PUSH_TITLE, body, data))
+ transaction.on_commit(lambda: send_user_push.delay(user.id, PUSH_TITLE, body, data, suppressed))
+
+
+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/serializers.py b/products/tasks/backend/serializers.py
index f7cf62f3afd6..faeb028e8bac 100644
--- a/products/tasks/backend/serializers.py
+++ b/products/tasks/backend/serializers.py
@@ -1679,3 +1679,19 @@ class SandboxEnvironmentListSerializer(serializers.ModelSerializer):
"created_at",
"updated_at",
]
+
+
+class TaskPresenceBeaconRequestSerializer(serializers.Serializer):
+ """Request body for the presence beacon and beacon-leave endpoints.
+
+ `device_id` is the UUID of the caller's `UserPushToken` row, which the
+ client received when it registered for push via `/api/users/@me/push_tokens/`.
+ The client is expected to use the same identifier on the beacon and leave
+ calls; if the user has unregistered the underlying push token, the value
+ won't resolve and the call returns 404 — at which point pushes were
+ already not going there anyway.
+ """
+
+ device_id = serializers.UUIDField(
+ help_text="UUID of the caller's UserPushToken (returned by `/api/users/@me/push_tokens/` on register).",
+ )
diff --git a/products/tasks/backend/tests/test_presence.py b/products/tasks/backend/tests/test_presence.py
new file mode 100644
index 000000000000..c12b38825b71
--- /dev/null
+++ b/products/tasks/backend/tests/test_presence.py
@@ -0,0 +1,292 @@
+from datetime import timedelta
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import TestCase, TransactionTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.test import APIClient
+
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.user_push_token import UserPushToken
+from posthog.push_notifications import send_push_to_user
+
+from products.tasks.backend.models import TASK_PRESENCE_TTL_SECONDS, Task, TaskPresence, TaskRun
+from products.tasks.backend.push_dispatcher import notify_task_run_completed
+
+
+def _flag_check_factory():
+ """Return a side_effect that turns on both the tasks-access flag and the push flag."""
+
+ def check_flag(flag_name, *_args, **_kwargs):
+ return flag_name in {"tasks", "posthog-code-mobile-push"}
+
+ return check_flag
+
+
+def _make_presence(
+ *, team: Team, task: Task, user: User, push_token: UserPushToken, expires_in: timedelta
+) -> TaskPresence:
+ """Create a presence row directly without needing a team_scope context.
+
+ ``Model(...).save()`` sidesteps ``TeamScopedManager.get_queryset`` so test
+ setUp doesn't have to wrap every helper in ``team_scope``. Production
+ writers (the DRF beacon endpoint) come in through ``objects`` and are
+ auto-scoped via ``TeamAndOrgViewSetMixin``.
+ """
+ instance = TaskPresence(
+ team=team,
+ task=task,
+ user=user,
+ push_token=push_token,
+ expires_at=timezone.now() + expires_in,
+ )
+ instance.save()
+ return instance
+
+
+class PresenceAPITestCase(TestCase):
+ def setUp(self) -> None:
+ 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="P", password="password")
+ self.organization.members.add(self.user)
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(
+ level=OrganizationMembership.Level.ADMIN
+ )
+ self.task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="A Task",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ self.push_token = UserPushToken.objects.create(
+ user=self.user,
+ token="ExponentPushToken[device-A]",
+ platform=UserPushToken.Platform.IOS,
+ )
+
+ self.client = APIClient()
+ self.client.force_authenticate(self.user)
+
+ self.flag_patcher = patch("posthoganalytics.feature_enabled", side_effect=_flag_check_factory())
+ self.flag_patcher.start()
+ self.addCleanup(self.flag_patcher.stop)
+
+ def _presence_url(self) -> str:
+ return f"/api/projects/{self.team.id}/tasks/{self.task.id}/presence/"
+
+ def _all_presence(self):
+ # Assertions run outside the DRF team-scope context, so go through
+ # the cross-team queryset explicitly.
+ return TaskPresence.objects.unscoped()
+
+ def test_beacon_creates_presence_row(self) -> None:
+ response = self.client.post(self._presence_url(), {"device_id": str(self.push_token.id)}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertEqual(self._all_presence().filter(task=self.task, push_token=self.push_token).count(), 1)
+ presence = self._all_presence().get(task=self.task, push_token=self.push_token)
+ self.assertEqual(presence.user_id, self.user.id)
+ self.assertEqual(presence.team_id, self.team.id)
+ # expires_at lands ~TTL seconds in the future. A loose lower bound
+ # avoids flake if the clock advances between the view and the assert.
+ delta = (presence.expires_at - timezone.now()).total_seconds()
+ self.assertGreater(delta, TASK_PRESENCE_TTL_SECONDS - 5)
+ self.assertLessEqual(delta, TASK_PRESENCE_TTL_SECONDS + 1)
+
+ def test_second_beacon_refreshes_without_duplicating(self) -> None:
+ self.client.post(self._presence_url(), {"device_id": str(self.push_token.id)}, format="json")
+ first = self._all_presence().get(task=self.task, push_token=self.push_token)
+
+ # Drag expires_at into the past so we can prove the upsert refreshed it.
+ self._all_presence().filter(pk=first.pk).update(expires_at=timezone.now() - timedelta(minutes=5))
+
+ response = self.client.post(self._presence_url(), {"device_id": str(self.push_token.id)}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertEqual(self._all_presence().filter(task=self.task, push_token=self.push_token).count(), 1)
+ refreshed = self._all_presence().get(task=self.task, push_token=self.push_token)
+ self.assertEqual(refreshed.pk, first.pk)
+ self.assertGreater(refreshed.expires_at, timezone.now())
+
+ def test_beacon_leave_removes_row(self) -> None:
+ _make_presence(
+ team=self.team,
+ task=self.task,
+ user=self.user,
+ push_token=self.push_token,
+ expires_in=timedelta(seconds=60),
+ )
+ response = self.client.delete(self._presence_url(), {"device_id": str(self.push_token.id)}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertFalse(self._all_presence().filter(task=self.task, push_token=self.push_token).exists())
+
+ def test_beacon_leave_on_missing_row_is_idempotent(self) -> None:
+ response = self.client.delete(self._presence_url(), {"device_id": str(self.push_token.id)}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+
+ @parameterized.expand(
+ [
+ ("unknown_device_id", "unknown"),
+ ("device_id_belonging_to_another_user", "other_user"),
+ ]
+ )
+ def test_beacon_rejects_invalid_device_id(self, _name, kind) -> None:
+ if kind == "unknown":
+ device_id = "00000000-0000-0000-0000-000000000000"
+ else:
+ other = User.objects.create_user(email="[email protected]", first_name="O", password="x")
+ self.organization.members.add(other)
+ other_token = UserPushToken.objects.create(
+ user=other,
+ token="ExponentPushToken[other-device]",
+ platform=UserPushToken.Platform.IOS,
+ )
+ device_id = str(other_token.id)
+
+ response = self.client.post(self._presence_url(), {"device_id": device_id}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertFalse(self._all_presence().exists())
+
+ def test_beacon_on_inaccessible_task_returns_404(self) -> None:
+ other_user = User.objects.create_user(email="[email protected]", first_name="To", password="x")
+ self.organization.members.add(other_user)
+ their_task = Task.objects.create(
+ team=self.team,
+ created_by=other_user,
+ title="Not Yours",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ url = f"/api/projects/{self.team.id}/tasks/{their_task.id}/presence/"
+ response = self.client.post(url, {"device_id": str(self.push_token.id)}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+
+class PresenceFanoutSuppressionTestCase(TransactionTestCase):
+ """``send_user_push`` is dispatched via ``transaction.on_commit``; we need a
+ TransactionTestCase so the callback actually fires.
+
+ The contract under test: any non-expired presence row for this user/task
+ suppresses fanout to ALL of that user's push tokens — including the
+ watching device itself, which is already rendering the task UI live.
+ """
+
+ def setUp(self) -> None:
+ 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="F", password="password")
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
+ self.task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Watching Task",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ self.task_run = TaskRun.objects.create(task=self.task, team=self.team)
+ self.device_a = UserPushToken.objects.create(
+ user=self.user, token="ExponentPushToken[A]", platform=UserPushToken.Platform.IOS
+ )
+ self.device_b = UserPushToken.objects.create(
+ user=self.user, token="ExponentPushToken[B]", platform=UserPushToken.Platform.ANDROID
+ )
+
+ def _present(self, device: UserPushToken, *, on_task: Task | None = None, expires_in: timedelta) -> None:
+ _make_presence(
+ team=self.team,
+ task=on_task or self.task,
+ user=self.user,
+ push_token=device,
+ expires_in=expires_in,
+ )
+
+ # Each case sets up a different presence layout and asserts which devices
+ # the dispatcher told the celery task to suppress. The "all devices" cases
+ # cover the documented contract: any active presence -> blanket suppression.
+ @parameterized.expand(
+ [
+ # (label, scenario_id, expected_suppressed_kind)
+ # "all" -> both device_a and device_b
+ # "none" -> no devices
+ ("one_device_watching_suppresses_all", "one_active", "all"),
+ ("both_devices_watching_suppresses_all", "both_active", "all"),
+ ("only_expired_presence_suppresses_none", "expired_only", "none"),
+ ("presence_on_other_task_suppresses_none", "other_task_only", "none"),
+ ]
+ )
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_fanout_suppression_matrix(self, _name, scenario, expected, mock_delay, _flag) -> None:
+ if scenario == "one_active":
+ self._present(self.device_a, expires_in=timedelta(seconds=30))
+ elif scenario == "both_active":
+ self._present(self.device_a, expires_in=timedelta(seconds=30))
+ self._present(self.device_b, expires_in=timedelta(seconds=30))
+ elif scenario == "expired_only":
+ self._present(self.device_a, expires_in=-timedelta(seconds=1))
+ elif scenario == "other_task_only":
+ other_task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Other Task",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ self._present(self.device_a, on_task=other_task, expires_in=timedelta(seconds=30))
+
+ notify_task_run_completed(self.task_run)
+
+ mock_delay.assert_called_once()
+ suppressed = mock_delay.call_args.args[4]
+
+ if expected == "all":
+ self.assertEqual(set(suppressed), {str(self.device_a.id), str(self.device_b.id)})
+ else:
+ self.assertEqual(suppressed, [])
+
+
+class PresencePushHelperSuppressionTestCase(TestCase):
+ """Direct test of ``send_push_to_user`` honouring the suppression set,
+ so we cover the helper without exercising the dispatcher path."""
+
+ def setUp(self) -> None:
+ 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="H", password="password")
+ self.device_a = UserPushToken.objects.create(
+ user=self.user, token="ExponentPushToken[helper-A]", platform=UserPushToken.Platform.IOS
+ )
+ self.device_b = UserPushToken.objects.create(
+ user=self.user, token="ExponentPushToken[helper-B]", platform=UserPushToken.Platform.ANDROID
+ )
+
+ @patch("posthog.push_notifications._send_batch")
+ def test_excludes_suppressed_tokens_from_fanout(self, mock_send_batch) -> None:
+ mock_send_batch.return_value = 1
+
+ send_push_to_user(
+ self.user,
+ title="t",
+ body="b",
+ suppressed_push_token_ids=[str(self.device_a.id)],
+ )
+
+ mock_send_batch.assert_called_once()
+ sent_tokens = mock_send_batch.call_args.args[1]
+ self.assertEqual(sent_tokens, [self.device_b.token])
+
+ @patch("posthog.push_notifications._send_batch")
+ def test_no_call_when_every_token_is_suppressed(self, mock_send_batch) -> None:
+ send_push_to_user(
+ self.user,
+ title="t",
+ body="b",
+ suppressed_push_token_ids=[str(self.device_a.id), str(self.device_b.id)],
+ )
+
+ mock_send_batch.assert_not_called()
diff --git a/products/tasks/backend/tests/test_push_dispatcher.py b/products/tasks/backend/tests/test_push_dispatcher.py
index ba5e136892c7..805ce70b1953 100644
--- a/products/tasks/backend/tests/test_push_dispatcher.py
+++ b/products/tasks/backend/tests/test_push_dispatcher.py
@@ -49,12 +49,14 @@ class TestPushDispatcher(TransactionTestCase):
def test_notify_enqueues_push(self, _name, notify_fn, expected_body_fragment, mock_delay, _flag):
notify_fn(self.task_run)
mock_delay.assert_called_once()
- user_id, title, body, data = mock_delay.call_args.args
+ user_id, title, body, data, suppressed = mock_delay.call_args.args
self.assertEqual(user_id, self.user.id)
self.assertEqual(title, "PostHog Code")
self.assertIn(expected_body_fragment, body)
self.assertEqual(data["taskId"], str(self.task.id))
self.assertEqual(data["taskRunId"], str(self.task_run.id))
+ # No presence rows in this test's setUp, so nothing to suppress.
+ self.assertEqual(suppressed, [])
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=False)
@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index c9dffe19eb29..7d8bb9a2756f 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -346,6 +346,21 @@ export interface PatchedTaskApi {
ci_prompt?: string | null
}
+/**
+ * Request body for the presence beacon and beacon-leave endpoints.
+
+`device_id` is the UUID of the caller's `UserPushToken` row, which the
+client received when it registered for push via `/api/users/@me/push_tokens/`.
+The client is expected to use the same identifier on the beacon and leave
+calls; if the user has unregistered the underlying push token, the value
+won't resolve and the call returns 404 — at which point pushes were
+already not going there anyway.
+ */
+export interface TaskPresenceBeaconRequestApi {
+ /** UUID of the caller's UserPushToken (returned by `/api/users/@me/push_tokens/` on register). */
+ device_id: string
+}
+
/**
* * `interactive` - interactive
* `background` - background
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 9142a846d0ea..40193b02eb39 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -25,6 +25,7 @@ import type {
TaskApi,
TaskAutomationApi,
TaskAutomationsListParams,
+ TaskPresenceBeaconRequestApi,
TaskRepositoriesResponseApi,
TaskRunAppendLogRequestApi,
TaskRunArtifactPresignRequestApi,
@@ -322,6 +323,43 @@ export const tasksDestroy = async (projectId: string, id: string, options?: Requ
})
}
+export const getTasksPresenceCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${id}/presence/`
+}
+
+/**
+ * Idempotent upsert: marks the calling user + `device_id` as actively watching this task for the next ~60 seconds. While at least one device for the user has a non-expired presence row for this task, the push fanout will skip ALL of that user's other registered devices for task notifications — the contract is 'if any device is demonstrably watching, suppress the others'. Clients call this every ~30s while the task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row.
+ * @summary Beacon presence for a device watching this task
+ */
+export const tasksPresenceCreate = async (
+ projectId: string,
+ id: string,
+ taskPresenceBeaconRequestApi: TaskPresenceBeaconRequestApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getTasksPresenceCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(taskPresenceBeaconRequestApi),
+ })
+}
+
+export const getTasksPresenceDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${id}/presence/`
+}
+
+/**
+ * Idempotent upsert: marks the calling user + `device_id` as actively watching this task for the next ~60 seconds. While at least one device for the user has a non-expired presence row for this task, the push fanout will skip ALL of that user's other registered devices for task notifications — the contract is 'if any device is demonstrably watching, suppress the others'. Clients call this every ~30s while the task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row.
+ * @summary Beacon presence for a device watching this task
+ */
+export const tasksPresenceDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getTasksPresenceDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getTasksRunCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/tasks/${id}/run/`
}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index fbaacd0a0be4..4175fe87eab9 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -239,6 +239,22 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
})
+/**
+ * Idempotent upsert: marks the calling user + `device_id` as actively watching this task for the next ~60 seconds. While at least one device for the user has a non-expired presence row for this task, the push fanout will skip ALL of that user's other registered devices for task notifications — the contract is 'if any device is demonstrably watching, suppress the others'. Clients call this every ~30s while the task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row.
+ * @summary Beacon presence for a device watching this task
+ */
+export const TasksPresenceCreateBody = /* @__PURE__ */ zod
+ .object({
+ device_id: zod
+ .uuid()
+ .describe(
+ "UUID of the caller's UserPushToken (returned by `\/api\/users\/@me\/push_tokens\/` on register)."
+ ),
+ })
+ .describe(
+ "Request body for the presence beacon and beacon-leave endpoints.\n\n`device_id` is the UUID of the caller's `UserPushToken` row, which the\nclient received when it registered for push via `\/api\/users\/@me\/push_tokens\/`.\nThe client is expected to use the same identifier on the beacon and leave\ncalls; if the user has unregistered the underlying push token, the value\nwon't resolve and the call returns 404 — at which point pushes were\nalready not going there anyway."
+ )
+
/**
* Create a new task run and kick off the workflow.
* @summary Run task
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a5d3eb8da1b6..a9cea5e0ae7e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35985,6 +35985,21 @@ export namespace Schemas {
deleted?: boolean;
}
+ /**
+ * Request body for the presence beacon and beacon-leave endpoints.
+
+ `device_id` is the UUID of the caller's `UserPushToken` row, which the
+ client received when it registered for push via `/api/users/@me/push_tokens/`.
+ The client is expected to use the same identifier on the beacon and leave
+ calls; if the user has unregistered the underlying push token, the value
+ won't resolve and the call returns 404 — at which point pushes were
+ already not going there anyway.
+ */
+ export interface TaskPresenceBeaconRequest {
+ /** UUID of the caller's UserPushToken (returned by `/api/users/@me/push_tokens/` on register). */
+ device_id: string;
+ }
+
export interface TaskRepositoriesResponse {
/** Distinct repositories in use by non-deleted, non-internal tasks for the current team. */
repositories: string[];