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): mobile push notifications for task run state changes (#58434)

Dylan Martin226e7e93cef7
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index e29abc6eb08d..6bb39056d80e 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -684,6 +684,7 @@ rules:
|PersonalAPIKey
|ScoreDefinitionVersion
|SignalUserAutonomyConfig
+ |UserPushToken
|WebauthnCredential
)$
- focus-metavariable: $SINK
@@ -735,6 +736,7 @@ rules:
|PersonalAPIKey
|ScoreDefinitionVersion
|SignalUserAutonomyConfig
+ |UserPushToken
|WebauthnCredential
)$
- pattern-not: $M.objects. ... .$METHOD2(..., user=$U, ...)
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f4ba6569b91b..3eab3b407fb5 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3254,6 +3254,56 @@ export interface OnboardingSkipRequestApi {
step_at_skip?: string
}
+/**
+ * * `ios` - iOS
+ * `android` - Android
+ * `web` - Web
+ */
+export type PushTokenPlatformEnumApi = (typeof PushTokenPlatformEnumApi)[keyof typeof PushTokenPlatformEnumApi]
+
+export const PushTokenPlatformEnumApi = {
+ Ios: 'ios',
+ Android: 'android',
+ Web: 'web',
+} as const
+
+export interface UserPushTokenRegisterRequestApi {
+ /**
+ * Opaque push token issued by the device's platform push service (e.g. an Expo push token).
+ * @maxLength 512
+ */
+ token: string
+ /** Device platform the token was issued for. One of `ios`, `android`, or `web`.
+
+ * `ios` - iOS
+ * `android` - Android
+ * `web` - Web */
+ platform: PushTokenPlatformEnumApi
+}
+
+export interface UserPushTokenItemApi {
+ /** PostHog UserPushToken row id. */
+ id: string
+ /** Device platform the token was issued for.
+
+ * `ios` - iOS
+ * `android` - Android
+ * `web` - Web */
+ platform: PushTokenPlatformEnumApi
+ /** When this token was first registered. */
+ created_at: string
+ /** Last time the mobile app re-registered this token. */
+ last_seen_at: string
+}
+
+export interface UserPushTokenUnregisterRequestApi {
+ /**
+ * The opaque push token to remove for the authenticated user.
+ * @maxLength 512
+ */
+ token: string
+}
+
export type SubscriptionsDeliveriesListParams = {
/**
* The pagination cursor value.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index e8820a5b9258..2aa28103d710 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -61,6 +61,9 @@ import type {
SubscriptionsListParams,
SubscriptionsSummaryQuotaRetrieve200,
UserApi,
+ UserPushTokenItemApi,
+ UserPushTokenRegisterRequestApi,
+ UserPushTokenUnregisterRequestApi,
UsersListParams,
} from './api.schemas'
@@ -1989,6 +1992,48 @@ export const usersOnboardingSkipCreate = async (
})
}
+export const getUsersPushTokensCreateUrl = (uuid: string) => {
+ return `/api/users/${uuid}/push_tokens/`
+}
+
+/**
+ * Idempotent upsert: if the (user, token) pair already exists, `platform` and `last_seen_at` are refreshed. Otherwise a new row is created.
+ * @summary Register a push notification token
+ */
+export const usersPushTokensCreate = async (
+ uuid: string,
+ userPushTokenRegisterRequestApi: UserPushTokenRegisterRequestApi,
+ options?: RequestInit
+): Promise<UserPushTokenItemApi> => {
+ return apiMutator<UserPushTokenItemApi>(getUsersPushTokensCreateUrl(uuid), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(userPushTokenRegisterRequestApi),
+ })
+}
+
+export const getUsersPushTokensUnregisterCreateUrl = (uuid: string) => {
+ return `/api/users/${uuid}/push_tokens/unregister/`
+}
+
+/**
+ * Delete the row matching `(user, token)`. Returns 204 even if no row matches so the mobile client can call this unconditionally when the user opts out.
+ * @summary Unregister a push notification token
+ */
+export const usersPushTokensUnregisterCreate = async (
+ uuid: string,
+ userPushTokenUnregisterRequestApi: UserPushTokenUnregisterRequestApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getUsersPushTokensUnregisterCreateUrl(uuid), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(userPushTokenUnregisterRequestApi),
+ })
+}
+
export const getUsersScenePersonalisationCreateUrl = (uuid: string) => {
return `/api/users/${uuid}/scene_personalisation/`
}
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 3adc0145ca77..8db91bfad87a 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -3146,6 +3146,38 @@ export const UsersOnboardingSkipCreateBody = /* @__PURE__ */ zod
'Request body for POST \/api\/users\/{id}\/onboarding\/skip\/.\n\nSource of truth for OpenAPI \/ generated TS \/ zod \/ MCP — bind this serializer at\nruntime so the contract clients believe is enforced (length cap, choice validation,\nno extra fields) is actually enforced server-side.'
)
+/**
+ * Idempotent upsert: if the (user, token) pair already exists, `platform` and `last_seen_at` are refreshed. Otherwise a new row is created.
+ * @summary Register a push notification token
+ */
+export const usersPushTokensCreateBodyTokenMax = 512
+
+export const UsersPushTokensCreateBody = /* @__PURE__ */ zod.object({
+ token: zod
+ .string()
+ .max(usersPushTokensCreateBodyTokenMax)
+ .describe("Opaque push token issued by the device's platform push service (e.g. an Expo push token)."),
+ platform: zod
+ .enum(['ios', 'android', 'web'])
+ .describe('\* `ios` - iOS\n\* `android` - Android\n\* `web` - Web')
+ .describe(
+ 'Device platform the token was issued for. One of `ios`, `android`, or `web`.\n\n\* `ios` - iOS\n\* `android` - Android\n\* `web` - Web'
+ ),
+})
+
+/**
+ * Delete the row matching `(user, token)`. Returns 204 even if no row matches so the mobile client can call this unconditionally when the user opts out.
+ * @summary Unregister a push notification token
+ */
+export const usersPushTokensUnregisterCreateBodyTokenMax = 512
+
+export const UsersPushTokensUnregisterCreateBody = /* @__PURE__ */ zod.object({
+ token: zod
+ .string()
+ .max(usersPushTokensUnregisterCreateBodyTokenMax)
+ .describe('The opaque push token to remove for the authenticated user.'),
+})
+
export const usersScenePersonalisationCreateBodyFirstNameMax = 150
export const usersScenePersonalisationCreateBodyLastNameMax = 150
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index cae4bd9ca07c..b3135525cd85 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -11,6 +11,7 @@ from posthog.api import (
my_notifications,
project,
user_integration,
+ user_push_token,
)
from posthog.api.batch_imports import BatchImportViewSet
from posthog.api.csp_reporting import CSPReportingViewSet
@@ -755,6 +756,12 @@ users_router.register(
"user_integration",
["uuid"],
)
+users_router.register(
+ r"push_tokens",
+ user_push_token.UserPushTokenViewSet,
+ "user_push_token",
+ ["uuid"],
+)
router.register(
r"user_home_settings",
user_home_settings.UserHomeSettingsViewSet,
diff --git a/posthog/api/test/test_user_push_token.py b/posthog/api/test/test_user_push_token.py
new file mode 100644
index 000000000000..7f0f5b14a49b
--- /dev/null
+++ b/posthog/api/test/test_user_push_token.py
@@ -0,0 +1,257 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+from posthog.models.user_push_token import UserPushToken
+from posthog.push_notifications import send_push_to_user
+
+
+class TestUserPushTokenEndpoints(APIBaseTest):
+ def test_register_creates_row(self):
+ response = self.client.post(
+ "/api/users/@me/push_tokens/",
+ {"token": "ExponentPushToken[abc]", "platform": "ios"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertEqual(body["platform"], "ios")
+ self.assertEqual(UserPushToken.objects.filter(user=self.user, token="ExponentPushToken[abc]").count(), 1)
+
+ def test_register_is_idempotent_and_updates_platform(self):
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[abc]", platform="ios")
+
+ response = self.client.post(
+ "/api/users/@me/push_tokens/",
+ {"token": "ExponentPushToken[abc]", "platform": "android"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ tokens = UserPushToken.objects.filter(user=self.user, token="ExponentPushToken[abc]")
+ self.assertEqual(tokens.count(), 1)
+ token_row = tokens.first()
+ assert token_row is not None
+ self.assertEqual(token_row.platform, "android")
+
+ def test_register_rejects_invalid_platform(self):
+ response = self.client.post(
+ "/api/users/@me/push_tokens/",
+ {"token": "ExponentPushToken[abc]", "platform": "blackberry"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_register_requires_token(self):
+ response = self.client.post(
+ "/api/users/@me/push_tokens/",
+ {"platform": "ios"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_unregister_deletes_row(self):
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[abc]", platform="ios")
+
+ response = self.client.post(
+ "/api/users/@me/push_tokens/unregister/",
+ {"token": "ExponentPushToken[abc]"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertFalse(UserPushToken.objects.filter(user=self.user, token="ExponentPushToken[abc]").exists())
+
+ def test_unregister_unknown_token_is_a_noop(self):
+ response = self.client.post(
+ "/api/users/@me/push_tokens/unregister/",
+ {"token": "ExponentPushToken[never-registered]"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+
+ def test_unregister_does_not_touch_other_users_tokens(self):
+ other_user = self._create_user("[email protected]")
+ UserPushToken.objects.create(user=other_user, token="ExponentPushToken[shared]", platform="ios")
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[shared]", platform="ios")
+
+ response = self.client.post(
+ "/api/users/@me/push_tokens/unregister/",
+ {"token": "ExponentPushToken[shared]"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertFalse(UserPushToken.objects.filter(user=self.user, token="ExponentPushToken[shared]").exists())
+ self.assertTrue(UserPushToken.objects.filter(user=other_user, token="ExponentPushToken[shared]").exists())
+
+ def test_register_does_not_leak_across_users(self):
+ other_user = self._create_user("[email protected]")
+ UserPushToken.objects.create(user=other_user, token="ExponentPushToken[abc]", platform="ios")
+
+ response = self.client.post(
+ "/api/users/@me/push_tokens/",
+ {"token": "ExponentPushToken[abc]", "platform": "ios"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ # Both users now own a row for that token (unique together is per-user).
+ self.assertEqual(UserPushToken.objects.filter(token="ExponentPushToken[abc]").count(), 2)
+
+ def test_unauthenticated_requests_are_rejected(self):
+ self.client.logout()
+ response = self.client.post(
+ "/api/users/@me/push_tokens/",
+ {"token": "ExponentPushToken[abc]", "platform": "ios"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+ def test_staff_cannot_register_token_for_another_user(self):
+ """Even staff get rejected at /users/{uuid}/push_tokens/ — registration is device-self only.
+
+ Without this guard a staff session could register their own device token against
+ another user's account, routing that user's task push notifications to the staff
+ member's phone.
+ """
+ self.user.is_staff = True
+ self.user.save(update_fields=["is_staff"])
+ victim = self._create_user("[email protected]")
+
+ response = self.client.post(
+ f"/api/users/{victim.uuid}/push_tokens/",
+ {"token": "ExponentPushToken[attacker]", "platform": "ios"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(UserPushToken.objects.filter(user=victim).exists())
+ self.assertFalse(UserPushToken.objects.filter(user=self.user).exists())
+
+ def test_per_user_token_cap_evicts_oldest(self):
+ """Registering more than MAX_TOKENS_PER_USER trims oldest rows on insert."""
+ from posthog.api.user_push_token import MAX_TOKENS_PER_USER
+
+ # Pre-populate up to the cap. We bypass last_seen_at's auto_now by an explicit
+ # save right after — ordering is by last_seen_at desc, then created_at desc.
+ for i in range(MAX_TOKENS_PER_USER):
+ UserPushToken.objects.create(
+ user=self.user,
+ token=f"ExponentPushToken[old-{i}]",
+ platform="ios",
+ )
+
+ response = self.client.post(
+ "/api/users/@me/push_tokens/",
+ {"token": "ExponentPushToken[new]", "platform": "ios"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ # New token survives, total count stays at the cap.
+ self.assertEqual(UserPushToken.objects.filter(user=self.user).count(), MAX_TOKENS_PER_USER)
+ self.assertTrue(UserPushToken.objects.filter(user=self.user, token="ExponentPushToken[new]").exists())
+
+
+class TestPushNotifications(APIBaseTest):
+ def _stub_response(self, *, ok: list[str], not_registered: list[str] | None = None):
+ not_registered = not_registered or []
+ tickets = [{"status": "ok"} for _ in ok] + [
+ {"status": "error", "details": {"error": "DeviceNotRegistered"}} for _ in not_registered
+ ]
+
+ class _StubResponse:
+ status_code = 200
+
+ def json(self_inner):
+ return {"data": tickets}
+
+ @property
+ def text(self_inner):
+ return ""
+
+ return _StubResponse()
+
+ def test_send_push_to_user_returns_zero_with_no_tokens(self):
+ sent = send_push_to_user(self.user, title="t", body="b")
+ self.assertEqual(sent, 0)
+
+ @patch("posthog.push_notifications.requests.post")
+ def test_send_push_to_user_calls_expo(self, mock_post):
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[a]", platform="ios")
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[b]", platform="android")
+ mock_post.return_value = self._stub_response(ok=["a", "b"])
+
+ accepted = send_push_to_user(
+ self.user,
+ title="PostHog Code",
+ body="task done",
+ data={"taskId": "t1", "taskRunId": "r1"},
+ )
+
+ self.assertEqual(accepted, 2)
+ self.assertEqual(mock_post.call_count, 1)
+ payload = mock_post.call_args.kwargs["json"]
+ self.assertEqual(len(payload), 2)
+ self.assertEqual(payload[0]["title"], "PostHog Code")
+ self.assertEqual(payload[0]["body"], "task done")
+ self.assertEqual(payload[0]["data"], {"taskId": "t1", "taskRunId": "r1"})
+
+ @patch("posthog.push_notifications.requests.post")
+ def test_send_push_prunes_invalid_tokens(self, mock_post):
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[a]", platform="ios")
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[b]", platform="android")
+ mock_post.return_value = self._stub_response(ok=["a"], not_registered=["b"])
+
+ accepted = send_push_to_user(self.user, title="t", body="b")
+ self.assertEqual(accepted, 1)
+ remaining = list(UserPushToken.objects.filter(user=self.user).values_list("token", flat=True))
+ self.assertEqual(remaining, ["ExponentPushToken[a]"])
+
+ @patch("posthog.push_notifications.requests.post")
+ def test_send_push_prune_is_scoped_to_user(self, mock_post):
+ """DeviceNotRegistered prune must not delete the same token if another user owns it."""
+ other_user = self._create_user("[email protected]")
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[shared]", platform="ios")
+ UserPushToken.objects.create(user=other_user, token="ExponentPushToken[shared]", platform="ios")
+ mock_post.return_value = self._stub_response(ok=[], not_registered=["shared"])
+
+ send_push_to_user(self.user, title="t", body="b")
+
+ self.assertFalse(UserPushToken.objects.filter(user=self.user, token="ExponentPushToken[shared]").exists())
+ self.assertTrue(UserPushToken.objects.filter(user=other_user, token="ExponentPushToken[shared]").exists())
+
+ @patch("posthog.push_notifications.logger.warning")
+ @patch("posthog.push_notifications.requests.post")
+ def test_send_push_logs_when_expo_returns_fewer_tickets(self, mock_post, mock_warning):
+ """If Expo ever returns fewer tickets than messages, zip silently drops the tail —
+ log a warning so the contract violation surfaces in monitoring."""
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[a]", platform="ios")
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[b]", platform="ios")
+
+ class _ShortResponse:
+ status_code = 200
+ text = ""
+
+ def json(self_inner):
+ return {"data": [{"status": "ok"}]} # one ticket for two messages
+
+ mock_post.return_value = _ShortResponse()
+ send_push_to_user(self.user, title="t", body="b")
+ events = [call.args[0] for call in mock_warning.call_args_list]
+ self.assertIn("expo_push.ticket_count_mismatch", events)
+
+ @patch("posthog.push_notifications.requests.post")
+ def test_send_push_swallows_http_errors(self, mock_post):
+ UserPushToken.objects.create(user=self.user, token="ExponentPushToken[a]", platform="ios")
+
+ class _BadResponse:
+ status_code = 500
+ text = "boom"
+
+ def json(self_inner):
+ raise ValueError("not json")
+
+ mock_post.return_value = _BadResponse()
+
+ accepted = send_push_to_user(self.user, title="t", body="b")
+ self.assertEqual(accepted, 0)
+ # Token preserved — only DeviceNotRegistered prunes.
+ self.assertTrue(UserPushToken.objects.filter(token="ExponentPushToken[a]").exists())
diff --git a/posthog/api/user_push_token.py b/posthog/api/user_push_token.py
new file mode 100644
index 000000000000..74fbae14bc23
--- /dev/null
+++ b/posthog/api/user_push_token.py
@@ -0,0 +1,169 @@
+"""`/api/users/@me/push_tokens/` — register and unregister mobile push tokens.
+
+The mobile app uploads its Expo push token after the user grants notification
+permission. The backend fans out push notifications to every stored token
+belonging to a user when something relevant happens (e.g. a PostHog Code task
+run finishes or needs the user's input).
+
+This is **device self-registration only**: every request acts on the
+authenticated user, never on someone else. The nested URL prefix is here only
+to match the rest of `/api/users/@me/…`.
+"""
+
+from typing import cast
+
+from django.utils import timezone as django_timezone
+
+import structlog
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import exceptions, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import validated_request
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models.user import User
+from posthog.models.user_push_token import UserPushToken
+from posthog.permissions import APIScopePermission
+from posthog.rate_limit import UserAuthenticationThrottle
+
+logger = structlog.get_logger(__name__)
+
+# Hard cap on how many push tokens a single user can register. Realistic users
+# have 1-3 devices; the cap exists to prevent an authenticated user from
+# amplifying every task-run state change into N outbound Expo requests.
+# When the cap is hit, the oldest tokens are evicted to make room — that
+# matches the natural "I lost my old phone" use case.
+MAX_TOKENS_PER_USER = 20
+
+
+class UserPushTokenRegisterRequestSerializer(serializers.Serializer):
+ token = serializers.CharField(
+ max_length=512,
+ help_text="Opaque push token issued by the device's platform push service (e.g. an Expo push token).",
+ )
+ platform = serializers.ChoiceField(
+ choices=UserPushToken.Platform.choices,
+ help_text="Device platform the token was issued for. One of `ios`, `android`, or `web`.",
+ )
+
+
+class UserPushTokenItemSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="PostHog UserPushToken row id.")
+ platform = serializers.ChoiceField(
+ choices=UserPushToken.Platform.choices,
+ help_text="Device platform the token was issued for.",
+ )
+ created_at = serializers.DateTimeField(help_text="When this token was first registered.")
+ last_seen_at = serializers.DateTimeField(help_text="Last time the mobile app re-registered this token.")
+
+
+class UserPushTokenUnregisterRequestSerializer(serializers.Serializer):
+ token = serializers.CharField(
+ max_length=512,
+ help_text="The opaque push token to remove for the authenticated user.",
+ )
+
+
+@extend_schema(tags=["core"])
+class UserPushTokenViewSet(viewsets.GenericViewSet):
+ """`/api/users/@me/push_tokens/` — manage the authenticated user's push notification tokens."""
+
+ scope_object = "user"
+ required_scopes: list[str] | None = None
+ scope_object_read_actions: list[str] = []
+ scope_object_write_actions = ["create", "unregister"]
+
+ authentication_classes = [
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ SessionAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ throttle_classes = [UserAuthenticationThrottle]
+ http_method_names = ["post"]
+ serializer_class = UserPushTokenItemSerializer
+
+ def _get_user(self) -> User:
+ """Always return the authenticated user.
+
+ Push tokens are inherently device-self-registration: there's no admin
+ flow where a staff member should register a device on someone else's
+ behalf (doing so would route that user's notifications to the staff
+ member's device). So we explicitly reject any non-``@me`` path even
+ for staff, rather than inheriting the impersonation behaviour from
+ ``UserViewSet``.
+ """
+ request_user = cast(User, self.request.user)
+ uuid_param = self.kwargs.get("parent_lookup_uuid")
+ if uuid_param is not None and uuid_param != "@me":
+ raise exceptions.PermissionDenied("Push tokens can only be managed via the `@me` path.")
+ return request_user
+
+ @validated_request(
+ request_serializer=UserPushTokenRegisterRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=UserPushTokenItemSerializer,
+ description="Token was registered or refreshed.",
+ ),
+ },
+ summary="Register a push notification token",
+ description=(
+ "Idempotent upsert: if the (user, token) pair already exists, `platform` and "
+ "`last_seen_at` are refreshed. Otherwise a new row is created."
+ ),
+ )
+ def create(self, request: Request, **_kwargs) -> Response:
+ user = self._get_user()
+ data = request.validated_data
+ token: str = data["token"]
+ platform: str = data["platform"]
+
+ # `last_seen_at` is explicit in defaults (rather than relying on the
+ # model's `auto_now=True`) because `update_or_create` passes
+ # `defaults.keys()` as `update_fields` on the update path — fields not
+ # listed there won't be written even though `pre_save` ran for them.
+ push_token, created = UserPushToken.objects.update_or_create(
+ user=user,
+ token=token,
+ defaults={"platform": platform, "last_seen_at": django_timezone.now()},
+ )
+
+ if created:
+ self._enforce_per_user_cap(user)
+
+ return Response(UserPushTokenItemSerializer(push_token).data)
+
+ @validated_request(
+ request_serializer=UserPushTokenUnregisterRequestSerializer,
+ responses={204: OpenApiResponse(description="Token removed (or never existed).")},
+ summary="Unregister a push notification token",
+ description=(
+ "Delete the row matching `(user, token)`. Returns 204 even if no row matches so "
+ "the mobile client can call this unconditionally when the user opts out."
+ ),
+ )
+ @action(methods=["POST"], detail=False, url_path="unregister")
+ def unregister(self, request: Request, **_kwargs) -> Response:
+ token = request.validated_data["token"]
+ UserPushToken.objects.filter(user=self._get_user(), token=token).delete()
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ @staticmethod
+ def _enforce_per_user_cap(user: User) -> None:
+ """Trim the user's tokens back down to ``MAX_TOKENS_PER_USER``, evicting oldest first."""
+ excess_ids = list(
+ UserPushToken.objects.filter(user=user)
+ .order_by("-last_seen_at", "-created_at")
+ .values_list("id", flat=True)[MAX_TOKENS_PER_USER:]
+ )
+ if excess_ids:
+ # Belt-and-braces: include user=user in the delete filter as well.
+ # excess_ids was already derived from this user's rows, but the
+ # extra qualifier is defence-in-depth (and satisfies the
+ # idor-lookup-without-user semgrep rule for UserPushToken).
+ UserPushToken.objects.filter(user=user, id__in=excess_ids).delete()
+ logger.info("user_push_token.evicted_excess", user_id=user.id, count=len(excess_ids))
diff --git a/posthog/migrations/1154_userpushtoken.py b/posthog/migrations/1154_userpushtoken.py
new file mode 100644
index 000000000000..5c16fba037cf
--- /dev/null
+++ b/posthog/migrations/1154_userpushtoken.py
@@ -0,0 +1,59 @@
+# Generated by Django 5.2.13 on 2026-05-13
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+from posthog.models.utils import uuid7
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1153_subscription_hourly_frequency"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="UserPushToken",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ (
+ "token",
+ models.TextField(
+ help_text="Opaque push token issued by the platform push service (e.g. Expo push token).",
+ ),
+ ),
+ (
+ "platform",
+ models.CharField(
+ choices=[("ios", "iOS"), ("android", "Android"), ("web", "Web")],
+ help_text="Device platform the token was issued for.",
+ max_length=16,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "last_seen_at",
+ models.DateTimeField(
+ auto_now=True,
+ help_text="Last time the mobile app re-registered this token. Bumped on every save.",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="push_tokens",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_user_push_token",
+ "unique_together": {("user", "token")},
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index bda98e00146d..d1258c0c8d71 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1153_subscription_hourly_frequency
+1154_userpushtoken
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 02223389291a..497aeafa7b80 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -91,6 +91,7 @@ from .uploaded_media import UploadedMedia
from .user import User, UserManager
from .user_group import UserGroup, UserGroupMembership
from .user_integration import UserIntegration
+from .user_push_token import UserPushToken
from .repo_routing_rule import RepoRoutingRule
from .user_repo_preference import UserRepoPreference
from .user_scene_personalisation import UserScenePersonalisation
@@ -237,6 +238,7 @@ __all__ = [
"UserGroup",
"UserGroupMembership",
"UserIntegration",
+ "UserPushToken",
"DataWarehouseTable",
"ScheduledChange",
"WebAnalyticsFilterPreset",
diff --git a/posthog/models/user_push_token.py b/posthog/models/user_push_token.py
new file mode 100644
index 000000000000..585e8b8159e0
--- /dev/null
+++ b/posthog/models/user_push_token.py
@@ -0,0 +1,41 @@
+from django.db import models
+
+from posthog.models.utils import UUIDModel
+
+
+class UserPushToken(UUIDModel):
+ """Per-user push notification token for a mobile device.
+
+ A user may register multiple tokens (one per device). Tokens are uploaded
+ by the mobile app after the user grants notification permission, and used
+ by backend services to fan out push notifications via the platform-native
+ push service (Expo for the PostHog Code mobile app).
+ """
+
+ class Platform(models.TextChoices):
+ IOS = "ios", "iOS"
+ ANDROID = "android", "Android"
+ WEB = "web", "Web"
+
+ user = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.CASCADE,
+ related_name="push_tokens",
+ )
+ token = models.TextField(
+ help_text="Opaque push token issued by the platform push service (e.g. Expo push token).",
+ )
+ platform = models.CharField(
+ max_length=16,
+ choices=Platform.choices,
+ help_text="Device platform the token was issued for.",
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ last_seen_at = models.DateTimeField(
+ auto_now=True,
+ help_text="Last time the mobile app re-registered this token. Bumped on every save.",
+ )
+
+ class Meta:
+ db_table = "posthog_user_push_token"
+ unique_together = [("user", "token")]
diff --git a/posthog/push_notifications.py b/posthog/push_notifications.py
new file mode 100644
index 000000000000..f240c2decbe4
--- /dev/null
+++ b/posthog/push_notifications.py
@@ -0,0 +1,155 @@
+"""Send push notifications to mobile devices via the Expo push service.
+
+The Expo push API accepts up to 100 messages per HTTP call and returns one
+ticket per message. Tickets carry transient errors (delivery failed, push token
+invalid) but final delivery success is only confirmed by polling receipts.
+
+For the PostHog Code mobile app the only thing we care about is best-effort
+fan-out plus pruning tokens the device push service has rejected as
+permanently invalid (`DeviceNotRegistered`). Receipt polling is deferred until
+we have a real reason to surface delivery status.
+
+Reference: https://docs.expo.dev/push-notifications/sending-notifications/
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import Any, cast
+
+import requests
+import structlog
+
+from posthog.models.user import User
+from posthog.models.user_push_token import UserPushToken
+
+logger = structlog.get_logger(__name__)
+
+EXPO_PUSH_API_URL = "https://exp.host/--/api/v2/push/send"
+EXPO_PUSH_API_TIMEOUT_SECONDS = 10
+EXPO_PUSH_BATCH_SIZE = 100
+
+
+def send_push_to_user(
+ user: User,
+ *,
+ title: str,
+ body: str,
+ data: dict[str, Any] | None = None,
+) -> int:
+ """Send a push notification to every device registered for ``user``.
+
+ 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))
+ if not tokens:
+ return 0
+
+ accepted = 0
+ for batch in _chunk(tokens, EXPO_PUSH_BATCH_SIZE):
+ accepted += _send_batch(user, batch, title=title, body=body, data=data)
+ return accepted
+
+
+def _send_batch(
+ user: User,
+ tokens: list[str],
+ *,
+ title: str,
+ body: str,
+ data: dict[str, Any] | None,
+) -> int:
+ payload = [
+ {
+ "to": token,
+ "title": title,
+ "body": body,
+ "sound": "default",
+ "data": data or {},
+ }
+ for token in tokens
+ ]
+
+ try:
+ response = requests.post(
+ EXPO_PUSH_API_URL,
+ json=payload,
+ headers={"Accept": "application/json", "Content-Type": "application/json"},
+ timeout=EXPO_PUSH_API_TIMEOUT_SECONDS,
+ )
+ except requests.RequestException as exc:
+ logger.warning("expo_push.request_failed", error=str(exc), token_count=len(tokens))
+ return 0
+
+ if response.status_code >= 500:
+ logger.warning(
+ "expo_push.server_error",
+ status_code=response.status_code,
+ token_count=len(tokens),
+ )
+ return 0
+ if response.status_code >= 400:
+ logger.warning(
+ "expo_push.client_error",
+ status_code=response.status_code,
+ token_count=len(tokens),
+ body=response.text[:500],
+ )
+ return 0
+
+ try:
+ body_json = response.json()
+ except ValueError:
+ logger.warning("expo_push.invalid_response", body=response.text[:500])
+ return 0
+
+ tickets = body_json.get("data", []) if isinstance(body_json, dict) else []
+ if not isinstance(tickets, list):
+ return 0
+
+ # Expo's contract is one ticket per message in order. If we ever get a
+ # mismatch, `zip` silently truncates and the tail tokens fall into a hole
+ # — never counted as accepted, never pruned. Log so a contract regression
+ # shows up in monitoring instead of looking like quiet success.
+ if len(tickets) != len(tokens):
+ logger.warning(
+ "expo_push.ticket_count_mismatch",
+ expected=len(tokens),
+ received=len(tickets),
+ )
+
+ accepted = 0
+ invalid_tokens: list[str] = []
+ for token, ticket in zip(tokens, tickets):
+ if not isinstance(ticket, dict):
+ continue
+ if ticket.get("status") == "ok":
+ accepted += 1
+ continue
+ details = ticket.get("details") if isinstance(ticket.get("details"), dict) else {}
+ error_code = cast(dict, details).get("error")
+ if error_code == "DeviceNotRegistered":
+ invalid_tokens.append(token)
+ else:
+ logger.warning(
+ "expo_push.ticket_error",
+ error=error_code,
+ message=ticket.get("message"),
+ )
+
+ if invalid_tokens:
+ # Scope pruning to this user — the same opaque token string could
+ # theoretically belong to another user (e.g. shared test device), and
+ # we should never delete a row we don't own the dispatch context for.
+ UserPushToken.objects.filter(user=user, token__in=invalid_tokens).delete()
+ logger.info("expo_push.pruned_invalid_tokens", count=len(invalid_tokens), user_id=user.id)
+
+ return accepted
+
+
+def _chunk(items: list[str], size: int) -> Iterable[list[str]]:
+ for i in range(0, len(items), size):
+ yield items[i : i + size]
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index dbed9af9806d..19b74caa235d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -418,6 +418,7 @@ SPECTACULAR_SETTINGS = {
"SavedQueryStatusEnum": "products.data_warehouse.backend.models.datawarehouse_saved_query.DataWarehouseSavedQuery.Status",
"DesktopRecordingStatusEnum": "products.desktop_recordings.backend.models.DesktopRecording.Status",
"MeetingPlatformEnum": "products.desktop_recordings.backend.models.DesktopRecording.Platform",
+ "PushTokenPlatformEnum": "posthog.models.user_push_token.UserPushToken.Platform",
"PropertyDefinitionTypeEnum": "products.event_definitions.backend.models.property_definition.PropertyType",
"ExternalDataSourceTypeEnum": "products.data_warehouse.backend.types.ExternalDataSourceType",
"ExperimentMetricKindEnum": "products.llm_analytics.backend.models.score_definitions.ScoreDefinition.Kind",
diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.py
index c02d0e9ba529..a70a2bc3f9e9 100644
--- a/posthog/tasks/__init__.py
+++ b/posthog/tasks/__init__.py
@@ -18,6 +18,7 @@ from . import (
llm_prompt_cache,
plugin_server,
process_scheduled_changes,
+ push_notifications,
remote_config,
split_person,
surveys,
@@ -48,6 +49,7 @@ __all__ = [
"llm_prompt_cache",
"plugin_server",
"process_scheduled_changes",
+ "push_notifications",
"remote_config",
"split_person",
"surveys",
diff --git a/posthog/tasks/push_notifications.py b/posthog/tasks/push_notifications.py
new file mode 100644
index 000000000000..2e4cbf1c481f
--- /dev/null
+++ b/posthog/tasks/push_notifications.py
@@ -0,0 +1,41 @@
+"""Celery task wrapper around the synchronous Expo push helper.
+
+The helper does sync ``requests.post`` with a 10-second timeout — fine in a
+worker, dangerous inside a request/response cycle or an async Temporal
+activity. Schedule this task via ``transaction.on_commit(lambda: …delay(…))``
+to dispatch pushes off the hot path.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+from celery import shared_task
+
+from posthog.models.user import User
+from posthog.push_notifications import send_push_to_user
+from posthog.scoping_audit import skip_team_scope_audit
+
+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:
+ """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.
+ """
+ try:
+ user = User.objects.get(pk=user_id)
+ except User.DoesNotExist:
+ logger.warning("send_user_push.user_not_found", user_id=user_id)
+ return
+
+ try:
+ send_push_to_user(user, title=title, body=body, data=data)
+ except Exception:
+ logger.warning("send_user_push.failed", user_id=user_id, exc_info=True)
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 535e4f14d7d4..32e4fc9a545f 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -88,6 +88,7 @@
'posthog.tasks.llm_prompt_cache.invalidate_archived_prompt_versions_cache_task',
'posthog.tasks.plugin_server.fatal_plugin_error',
'posthog.tasks.plugin_server.hog_function_state_transition',
+ 'posthog.tasks.push_notifications.send_user_push',
'posthog.tasks.remote_config.sync_all_remote_configs',
'posthog.tasks.remote_config.update_team_remote_config',
'posthog.tasks.split_person.split_person',
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index e013be4555e5..ada38ee38211 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -1192,6 +1192,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
new_status,
request.validated_data.get("error_message"),
)
+ # mark_completed / mark_failed fire pushes from the model. Cancellation
+ # transitions only flow through this PATCH path, so dispatch here.
+ if new_status == TaskRun.Status.CANCELLED:
+ from products.tasks.backend.push_dispatcher import notify_task_run_cancelled
+
+ notify_task_run_cancelled(task_run)
new_environment = request.validated_data.get("environment")
if new_environment == "local" and old_environment == TaskRun.Environment.CLOUD:
self._signal_workflow_completion(task_run, "cancelled", "handoff")
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index bd3167507b63..eee4a3b6916d 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -875,6 +875,9 @@ class TaskRun(models.Model):
"task_run_completed",
{"duration_seconds": self._duration_seconds()},
)
+ from products.tasks.backend.push_dispatcher import notify_task_run_completed
+
+ notify_task_run_completed(self)
def track_structured_result(self):
"""Track a structured result event with properties from the run output."""
@@ -904,6 +907,9 @@ class TaskRun(models.Model):
"duration_seconds": self._duration_seconds(),
},
)
+ from products.tasks.backend.push_dispatcher import notify_task_run_failed
+
+ notify_task_run_failed(self)
def build_stream_state_event(self) -> dict[str, Any]:
return {
diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.py
new file mode 100644
index 000000000000..66ada6df574d
--- /dev/null
+++ b/products/tasks/backend/push_dispatcher.py
@@ -0,0 +1,141 @@
+"""Dispatch push notifications to the task creator's mobile devices.
+
+Schedules the underlying Expo HTTP call as a Celery task via
+``transaction.on_commit`` so nothing here can block a request/response cycle
+or a Temporal activity's event loop.
+
+Three guards before we enqueue:
+
+1. **Feature flag.** ``posthog-code-mobile-push`` must be enabled for the
+ user. Off by default — flip on once the mobile build is ready and
+ tokens start arriving.
+2. **Cooldown.** A per-``(task_run, kind)`` Redis lock collapses duplicate
+ triggers in a short window. A workflow that retries ``mark_completed``
+ or an agent that fires several rapid end-of-turn events results in one
+ push, not five.
+3. **Anonymous task.** Runs without a ``created_by`` user get skipped
+ silently — there's no one to notify.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Literal
+
+from django.core.cache import cache
+from django.db import transaction
+
+import structlog
+import posthoganalytics
+
+from posthog.tasks.push_notifications import send_user_push
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
+
+logger = structlog.get_logger(__name__)
+
+PUSH_TITLE = "PostHog Code"
+FEATURE_FLAG_KEY = "posthog-code-mobile-push"
+
+# Cooldown windows per push kind. Terminal pushes get a longer window because
+# 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"]
+_COOLDOWN_SECONDS: dict[PushKind, int] = {
+ "completed": 600,
+ "failed": 600,
+ "cancelled": 600,
+ "awaiting": 30,
+}
+
+
+def notify_task_run_completed(task_run: TaskRun) -> None:
+ """Fire a push notification when ``task_run`` finishes successfully."""
+ _enqueue(task_run, kind="completed", body=f'"{_task_title(task_run)}" finished')
+
+
+def notify_task_run_failed(task_run: TaskRun) -> None:
+ """Fire a push notification when ``task_run`` ends with a failure."""
+ _enqueue(task_run, kind="failed", body=f'"{_task_title(task_run)}" failed')
+
+
+def notify_task_run_cancelled(task_run: TaskRun) -> None:
+ """Fire a push notification when ``task_run`` is cancelled."""
+ _enqueue(task_run, kind="cancelled", body=f'"{_task_title(task_run)}" was cancelled')
+
+
+def notify_task_run_awaiting_input(task_run: TaskRun) -> None:
+ """Fire a push notification when an interactive run is waiting for user input."""
+ _enqueue(task_run, kind="awaiting", body=f'"{_task_title(task_run)}" needs your input')
+
+
+def _task_title(task_run: TaskRun) -> str:
+ title = (task_run.task.title or "").strip()
+ return title or "Untitled task"
+
+
+def _enqueue(task_run: TaskRun, *, kind: PushKind, body: str) -> None:
+ """Best-effort: this function MUST NOT raise.
+
+ Wrap the whole body in a bare ``except Exception`` so a DB outage,
+ Redis hiccup, flag-service failure, or any other surprise can't bubble
+ out of ``mark_completed`` / ``mark_failed`` / the API cancel handler
+ and fail the surrounding task-lifecycle activity.
+ """
+ try:
+ _enqueue_inner(task_run, kind=kind, body=body)
+ except Exception:
+ logger.warning(
+ "push_dispatcher.enqueue_failed",
+ run_id=str(task_run.id),
+ task_id=str(task_run.task_id),
+ kind=kind,
+ exc_info=True,
+ )
+
+
+def _enqueue_inner(task_run: TaskRun, *, kind: PushKind, body: str) -> None:
+ user = task_run.task.created_by
+ if user is None:
+ return
+
+ # If the user has lost access to the task's team (e.g. removed from the
+ # organization), don't push them task titles for runs they shouldn't see
+ # anymore. The push body and data payload both carry the task identity.
+ # `user.teams` already accounts for both org membership and project-level
+ # RBAC, so it's the most accurate "can this user still see this run" gate.
+ if not user.teams.filter(id=task_run.team_id).exists():
+ logger.debug(
+ "push_dispatcher.recipient_lost_access",
+ user_id=user.id,
+ run_id=str(task_run.id),
+ team_id=task_run.team_id,
+ )
+ return
+
+ distinct_id = user.distinct_id or f"user_{user.id}"
+ try:
+ flag_enabled = posthoganalytics.feature_enabled(
+ FEATURE_FLAG_KEY,
+ distinct_id,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ # Failing closed on flag-evaluation errors keeps an outage from
+ # silently flipping pushes on for the whole user base.
+ logger.warning("push_dispatcher.flag_check_failed", user_id=user.id, exc_info=True)
+ return
+ if not flag_enabled:
+ return
+
+ cooldown_key = f"push_notification:{task_run.id}:{kind}"
+ if not cache.add(cooldown_key, True, timeout=_COOLDOWN_SECONDS[kind]):
+ logger.debug("push_dispatcher.cooldown_hit", run_id=str(task_run.id), kind=kind)
+ return
+
+ data = {"taskId": str(task_run.task_id), "taskRunId": str(task_run.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))
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
index bb452af3faa3..73ca33d8962f 100644
--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
@@ -99,6 +99,7 @@ async def relay_sandbox_events(input: RelaySandboxEventsInput) -> None:
task_id=input.task_id,
sandbox_id=input.sandbox_id,
background_logs_enabled=background_logs_enabled,
+ task_run=task_run,
)
except asyncio.CancelledError:
logger.info("relay_sandbox_events_cancelled", run_id=input.run_id)
@@ -220,6 +221,7 @@ async def _relay_loop(
task_id: str,
sandbox_id: str | None = None,
background_logs_enabled: bool = False,
+ task_run: TaskRunModel | None = None,
) -> None:
"""Connect to sandbox SSE and relay events to Redis. Reconnects on transient failures."""
reconnect_count = 0
@@ -294,6 +296,12 @@ async def _relay_loop(
agent_active[0] = False
if sandbox_id and background_logs_enabled:
asyncio.create_task(_emit_agentsh_events(sandbox_id, run_id, last_audit_ts_ns))
+ if task_run is not None and task_run.mode == "interactive":
+ # Interactive run finished a turn — the agent is now idle waiting
+ # for the user. Hop off the event loop because the dispatcher
+ # does sync Redis (cache.add) and a potential network call to
+ # the feature-flag service.
+ asyncio.create_task(asyncio.to_thread(_safe_dispatch_awaiting_input, task_run))
elif not agent_active[0] and _is_session_update(event_data):
agent_active[0] = True
@@ -433,3 +441,23 @@ def _is_terminal_event(event_data: dict) -> bool:
notification = event_data.get("notification", {})
method = notification.get("method", "")
return method in TERMINAL_NOTIFICATION_METHODS
+
+
+def _safe_dispatch_awaiting_input(task_run: TaskRunModel) -> None:
+ """Schedule a push when an interactive run idles waiting on the user.
+
+ Must be called via ``asyncio.to_thread`` (as the caller does) because the
+ dispatcher performs sync I/O: a Redis write (``cache.add``) and a potential
+ network call to the feature-flag service. Wrapped in a try so a failed
+ dispatch never bubbles into the relay loop.
+ """
+ try:
+ from products.tasks.backend.push_dispatcher import notify_task_run_awaiting_input
+
+ notify_task_run_awaiting_input(task_run)
+ except Exception:
+ logger.warning(
+ "relay_sandbox_events_push_dispatch_failed",
+ run_id=str(task_run.id),
+ exc_info=True,
+ )
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index e0f62c8e7dd3..d25c316730f0 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -2679,6 +2679,39 @@ class TestTaskRunAPI(BaseTaskAPITest):
call_args = mock_signal.call_args
self.assertEqual(call_args[0][1], "cancelled")
+ @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.push_dispatcher.notify_task_run_cancelled")
+ def test_update_run_status_to_cancelled_triggers_push(self, mock_notify, _mock_signal):
+ """Cancellation only flows through the API PATCH path — mark_completed / mark_failed
+ cover the other terminal transitions. A regression that removes this hook would go
+ undetected without an integration test here."""
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
+ {"status": "cancelled"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_notify.assert_called_once()
+ self.assertEqual(str(mock_notify.call_args.args[0].id), str(run.id))
+
+ @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.push_dispatcher.notify_task_run_cancelled")
+ def test_update_run_status_to_non_cancelled_terminal_does_not_trigger_cancel_push(self, mock_notify, _mock_signal):
+ """Sanity check: a PATCH to completed/failed must NOT fire the cancelled push."""
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
+ {"status": "completed"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_notify.assert_not_called()
+
@patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
def test_update_run_non_terminal_status_does_not_signal(self, mock_signal):
task = self.create_task()
diff --git a/products/tasks/backend/tests/test_push_dispatcher.py b/products/tasks/backend/tests/test_push_dispatcher.py
new file mode 100644
index 000000000000..ba5e136892c7
--- /dev/null
+++ b/products/tasks/backend/tests/test_push_dispatcher.py
@@ -0,0 +1,139 @@
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import TransactionTestCase
+
+from parameterized import parameterized
+
+from posthog.models import Organization, OrganizationMembership, Team, User
+
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.push_dispatcher import (
+ notify_task_run_awaiting_input,
+ notify_task_run_cancelled,
+ notify_task_run_completed,
+ notify_task_run_failed,
+)
+
+
+# TransactionTestCase so transaction.on_commit callbacks (which we use to defer
+# the Celery dispatch) actually fire during the test instead of being rolled back.
+class TestPushDispatcher(TransactionTestCase):
+ 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="Push", password="password")
+ # Push dispatch requires the recipient to still be a member of the team's org —
+ # see the access check in push_dispatcher._enqueue.
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
+ self.task = Task.objects.create(
+ team=self.team,
+ title="My Task",
+ description="desc",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=self.user,
+ )
+ self.task_run = TaskRun.objects.create(task=self.task, team=self.team)
+
+ @parameterized.expand(
+ [
+ ("completed", notify_task_run_completed, "finished"),
+ ("failed", notify_task_run_failed, "failed"),
+ ("cancelled", notify_task_run_cancelled, "cancelled"),
+ ("awaiting", notify_task_run_awaiting_input, "needs your input"),
+ ]
+ )
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ 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
+ 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))
+
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=False)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_feature_flag_off_skips_dispatch(self, mock_delay, _flag):
+ notify_task_run_completed(self.task_run)
+ mock_delay.assert_not_called()
+
+ @patch(
+ "products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled",
+ side_effect=RuntimeError("flag service down"),
+ )
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_flag_error_fails_closed(self, mock_delay, _flag):
+ notify_task_run_completed(self.task_run)
+ mock_delay.assert_not_called()
+
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_cooldown_collapses_duplicates(self, mock_delay, _flag):
+ notify_task_run_completed(self.task_run)
+ notify_task_run_completed(self.task_run)
+ notify_task_run_completed(self.task_run)
+ self.assertEqual(mock_delay.call_count, 1)
+
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_cooldown_is_per_kind(self, mock_delay, _flag):
+ # Different push kinds on the same run shouldn't share a cooldown key.
+ notify_task_run_completed(self.task_run)
+ notify_task_run_awaiting_input(self.task_run)
+ self.assertEqual(mock_delay.call_count, 2)
+
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_recipient_without_team_access_is_skipped(self, mock_delay, _flag):
+ """A user who has been removed from the task's organization must not receive
+ pushes carrying that task's title — losing access should mean losing notifications."""
+ outsider = User.objects.create_user(email="[email protected]", first_name="Out", password="x")
+ outsider_task = Task.objects.create(
+ team=self.team,
+ title="Sensitive Task",
+ description="desc",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=outsider,
+ )
+ outsider_run = TaskRun.objects.create(task=outsider_task, team=self.team)
+
+ notify_task_run_completed(outsider_run)
+ mock_delay.assert_not_called()
+
+ @patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
+ def test_anonymous_task_is_noop(self, mock_delay, _flag):
+ anonymous_task = Task.objects.create(
+ team=self.team,
+ title="Anon",
+ description="desc",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=None,
+ )
+ anonymous_run = TaskRun.objects.create(task=anonymous_task, team=self.team)
+ notify_task_run_completed(anonymous_run)
+ mock_delay.assert_not_called()
+
+ @patch("products.tasks.backend.push_dispatcher._enqueue_inner", side_effect=RuntimeError("redis is down"))
+ def test_enqueue_swallows_unexpected_errors(self, _mock_inner):
+ """The dispatcher MUST NOT raise. Any DB / Redis / flag-service hiccup
+ must be swallowed so it can't fail the task lifecycle activity that
+ triggered the push."""
+ # The bare except in _enqueue should catch the RuntimeError. If it
+ # doesn't, this test raises and fails — which is the regression signal.
+ notify_task_run_completed(self.task_run)
+
+ @patch("products.tasks.backend.push_dispatcher.notify_task_run_completed")
+ def test_mark_completed_triggers_push(self, mock_notify):
+ self.task_run.mark_completed()
+ mock_notify.assert_called_once_with(self.task_run)
+
+ @patch("products.tasks.backend.push_dispatcher.notify_task_run_failed")
+ def test_mark_failed_triggers_push(self, mock_notify):
+ self.task_run.mark_failed("nope")
+ mock_notify.assert_called_once_with(self.task_run)
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index fdc6d2e60951..2f60f11cd521 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -821,6 +821,12 @@ tools:
users-onboarding-skip-create:
operation: users_onboarding_skip_create
enabled: false
+ users-push-tokens-create:
+ operation: users_push_tokens_create
+ enabled: false
+ users-push-tokens-unregister-create:
+ operation: users_push_tokens_unregister_create
+ enabled: false
users-request-email-verification-create:
operation: users_request_email_verification_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0437b33f75cd..b825fc8f315d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31172,6 +31172,20 @@ export namespace Schemas {
max_proxy_records: number;
}
+ /**
+ * * `ios` - iOS
+ * `android` - Android
+ * `web` - Web
+ */
+ export type PushTokenPlatformEnum = typeof PushTokenPlatformEnum[keyof typeof PushTokenPlatformEnum];
+
+
+ export const PushTokenPlatformEnum = {
+ Ios: 'ios',
+ Android: 'android',
+ Web: 'web',
+ } as const;
+
export interface QuarantineInput {
/** @maxLength 512 */
identifier: string;
@@ -35014,6 +35028,43 @@ export namespace Schemas {
connect_flow: string;
}
+ export interface UserPushTokenItem {
+ /** PostHog UserPushToken row id. */
+ id: string;
+ /** Device platform the token was issued for.
+
+ * `ios` - iOS
+ * `android` - Android
+ * `web` - Web */
+ platform: PushTokenPlatformEnum;
+ /** When this token was first registered. */
+ created_at: string;
+ /** Last time the mobile app re-registered this token. */
+ last_seen_at: string;
+ }
+
+ export interface UserPushTokenRegisterRequest {
+ /**
+ * Opaque push token issued by the device's platform push service (e.g. an Expo push token).
+ * @maxLength 512
+ */
+ token: string;
+ /** Device platform the token was issued for. One of `ios`, `android`, or `web`.
+
+ * `ios` - iOS
+ * `android` - Android
+ * `web` - Web */
+ platform: PushTokenPlatformEnum;
+ }
+
+ export interface UserPushTokenUnregisterRequest {
+ /**
+ * The opaque push token to remove for the authenticated user.
+ * @maxLength 512
+ */
+ token: string;
+ }
+
export interface UtmEvent {
/** UTM campaign value from pageview events */
utm_campaign: string;