AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): add Web Push notifications via VAPID for background delivery (#12723)
Krzysztof Czerwinskie0f9146d542a
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex b17d187b99..3b6ba6ce12 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -37,6 +37,23 @@ JWT_VERIFY_KEY=your-super-secret-jwt-token-with-at-least-32-characters-longENCRYPTION_KEY=dvziYgz0KSK8FENhju0ZYi8-fRTfAdlz6YLhdB_jhNw=UNSUBSCRIBE_SECRET_KEY=HlP8ivStJjmbf6NKi78m_3FnOogut0t5ckzjsIqeaio=+# Web Push (VAPID) — generate with: poetry run python -c "+# from py_vapid import Vapid; import base64+# from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat+# v = Vapid(); v.generate_keys()+# raw_priv = v.private_key.private_numbers().private_value.to_bytes(32, 'big')+# print('VAPID_PRIVATE_KEY=' + base64.urlsafe_b64encode(raw_priv).rstrip(b'=').decode())+# raw_pub = v.public_key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)+# print('VAPID_PUBLIC_KEY=' + base64.urlsafe_b64encode(raw_pub).rstrip(b'=').decode())+# "+# Dev-only keypair below — DO NOT use in staging/production. Regenerate+# your own with the snippet above before any non-local deployment.+VAPID_PRIVATE_KEY=17hBPdSdn6TR_yAgQxA0TjTcvRj3Lf6znHnASZ4rOKc+VAPID_PUBLIC_KEY=BBg49iVTWthVbRYphwmZNvZyiSJDqtSO4nmLxDzLKe3Oo9jbtu0Usa14xX4HQQNLUeiEfzD42zWSlrvY1PR12bs+# Per RFC 8292 push services use this in 410 Gone reports; set to a real+# mailbox in production. Defaults to a placeholder for local dev.+VAPID_CLAIM_EMAIL=mailto:[email protected]+## ===== IMPORTANT OPTIONAL CONFIGURATION ===== ### Platform URLs (set these for webhooks and OAuth to work)PLATFORM_BASE_URL=http://localhost:8000diff --git a/autogpt_platform/backend/backend/api/features/push/__init__.py b/autogpt_platform/backend/backend/api/features/push/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/push/model.py b/autogpt_platform/backend/backend/api/features/push/model.pynew file mode 100644index 0000000000..1ff96473de--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/push/model.py@@ -0,0 +1,20 @@+import pydantic+++class PushSubscriptionKeys(pydantic.BaseModel):+ p256dh: str = pydantic.Field(min_length=1, max_length=512)+ auth: str = pydantic.Field(min_length=1, max_length=512)+++class PushSubscribeRequest(pydantic.BaseModel):+ endpoint: str = pydantic.Field(min_length=1, max_length=2048)+ keys: PushSubscriptionKeys+ user_agent: str | None = pydantic.Field(default=None, max_length=512)+++class PushUnsubscribeRequest(pydantic.BaseModel):+ endpoint: str = pydantic.Field(min_length=1, max_length=2048)+++class VapidPublicKeyResponse(pydantic.BaseModel):+ public_key: strdiff --git a/autogpt_platform/backend/backend/api/features/push/routes.py b/autogpt_platform/backend/backend/api/features/push/routes.pynew file mode 100644index 0000000000..a96316e4d7--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/push/routes.py@@ -0,0 +1,64 @@+from typing import Annotated++from autogpt_libs.auth import get_user_id, requires_user+from fastapi import APIRouter, HTTPException, Security+from starlette.status import HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST++from backend.api.features.push.model import (+ PushSubscribeRequest,+ PushUnsubscribeRequest,+ VapidPublicKeyResponse,+)+from backend.data.push_subscription import (+ delete_push_subscription,+ upsert_push_subscription,+ validate_push_endpoint,+)+from backend.util.settings import Settings++router = APIRouter()+_settings = Settings()+++ "/vapid-key",+ summary="Get VAPID public key for push subscription",+)+async def get_vapid_public_key() -> VapidPublicKeyResponse:+ return VapidPublicKeyResponse(public_key=_settings.secrets.vapid_public_key)+++ "/subscribe",+ summary="Register a push subscription for the current user",+ status_code=HTTP_204_NO_CONTENT,+ dependencies=[Security(requires_user)],+)+async def subscribe_push(+ user_id: Annotated[str, Security(get_user_id)],+ body: PushSubscribeRequest,+) -> None:+ try:+ await validate_push_endpoint(body.endpoint)+ await upsert_push_subscription(+ user_id=user_id,+ endpoint=body.endpoint,+ p256dh=body.keys.p256dh,+ auth=body.keys.auth,+ user_agent=body.user_agent,+ )+ except ValueError as e:+ raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=str(e))+++ "/unsubscribe",+ summary="Remove a push subscription",+ status_code=HTTP_204_NO_CONTENT,+ dependencies=[Security(requires_user)],+)+async def unsubscribe_push(+ user_id: Annotated[str, Security(get_user_id)],+ body: PushUnsubscribeRequest,+) -> None:+ await delete_push_subscription(user_id, body.endpoint)diff --git a/autogpt_platform/backend/backend/api/features/push/routes_test.py b/autogpt_platform/backend/backend/api/features/push/routes_test.pynew file mode 100644index 0000000000..5e44003bf7--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/push/routes_test.py@@ -0,0 +1,240 @@+"""Tests for push notification routes."""++from unittest.mock import AsyncMock, MagicMock++import fastapi+import fastapi.testclient+import pytest++from backend.api.features.push.routes import router++app = fastapi.FastAPI()+app.include_router(router)+client = fastapi.testclient.TestClient(app)++[email protected](autouse=True)+def setup_app_auth(mock_jwt_user):+ from autogpt_libs.auth.jwt_utils import get_jwt_payload++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ yield+ app.dependency_overrides.clear()+++def test_get_vapid_public_key(mocker):+ mock_settings = MagicMock()+ mock_settings.secrets.vapid_public_key = "test-vapid-public-key-base64url"+ mocker.patch(+ "backend.api.features.push.routes._settings",+ mock_settings,+ )++ response = client.get("/vapid-key")++ assert response.status_code == 200+ data = response.json()+ assert data["public_key"] == "test-vapid-public-key-base64url"+++def test_get_vapid_public_key_empty(mocker):+ mock_settings = MagicMock()+ mock_settings.secrets.vapid_public_key = ""+ mocker.patch(+ "backend.api.features.push.routes._settings",+ mock_settings,+ )++ response = client.get("/vapid-key")++ assert response.status_code == 200+ data = response.json()+ assert data["public_key"] == ""+++def test_subscribe_push(mocker, test_user_id):+ mock_upsert = mocker.patch(+ "backend.api.features.push.routes.upsert_push_subscription",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/subscribe",+ json={+ "endpoint": "https://fcm.googleapis.com/fcm/send/abc123",+ "keys": {+ "p256dh": "test-p256dh-key",+ "auth": "test-auth-key",+ },+ "user_agent": "Mozilla/5.0 Test",+ },+ )++ assert response.status_code == 204+ mock_upsert.assert_awaited_once_with(+ user_id=test_user_id,+ endpoint="https://fcm.googleapis.com/fcm/send/abc123",+ p256dh="test-p256dh-key",+ auth="test-auth-key",+ user_agent="Mozilla/5.0 Test",+ )+++def test_subscribe_push_without_user_agent(mocker, test_user_id):+ mock_upsert = mocker.patch(+ "backend.api.features.push.routes.upsert_push_subscription",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/subscribe",+ json={+ "endpoint": "https://fcm.googleapis.com/fcm/send/abc123",+ "keys": {+ "p256dh": "test-p256dh-key",+ "auth": "test-auth-key",+ },+ },+ )++ assert response.status_code == 204+ mock_upsert.assert_awaited_once_with(+ user_id=test_user_id,+ endpoint="https://fcm.googleapis.com/fcm/send/abc123",+ p256dh="test-p256dh-key",+ auth="test-auth-key",+ user_agent=None,+ )+++def test_subscribe_push_missing_keys():+ response = client.post(+ "/subscribe",+ json={+ "endpoint": "https://fcm.googleapis.com/fcm/send/abc123",+ },+ )++ assert response.status_code == 422+++def test_subscribe_push_missing_endpoint():+ response = client.post(+ "/subscribe",+ json={+ "keys": {+ "p256dh": "test-p256dh-key",+ "auth": "test-auth-key",+ },+ },+ )++ assert response.status_code == 422+++def test_subscribe_push_rejects_empty_crypto_keys():+ response = client.post(+ "/subscribe",+ json={+ "endpoint": "https://fcm.googleapis.com/fcm/send/abc123",+ "keys": {"p256dh": "", "auth": ""},+ },+ )++ assert response.status_code == 422+++def test_subscribe_push_rejects_oversized_endpoint():+ response = client.post(+ "/subscribe",+ json={+ "endpoint": "https://fcm.googleapis.com/fcm/send/" + "x" * 3000,+ "keys": {"p256dh": "k", "auth": "a"},+ },+ )++ assert response.status_code == 422+++def test_unsubscribe_push(mocker, test_user_id):+ mock_delete = mocker.patch(+ "backend.api.features.push.routes.delete_push_subscription",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/unsubscribe",+ json={+ "endpoint": "https://fcm.googleapis.com/fcm/send/abc123",+ },+ )++ assert response.status_code == 204+ mock_delete.assert_awaited_once_with(+ test_user_id,+ "https://fcm.googleapis.com/fcm/send/abc123",+ )+++def test_unsubscribe_push_missing_endpoint():+ response = client.post(+ "/unsubscribe",+ json={},+ )++ assert response.status_code == 422+++ "untrusted_endpoint",+ [+ "https://localhost/evil",+ "https://127.0.0.1/evil",+ "https://169.254.169.254/latest/meta-data/",+ "https://internal-service.local/api",+ "https://attacker.example.com/push",+ "http://fcm.googleapis.com/fcm/send/abc",+ "file:///etc/passwd",+ ],+)+def test_subscribe_push_rejects_untrusted_endpoints(mocker, untrusted_endpoint):+ mock_upsert = mocker.patch(+ "backend.api.features.push.routes.upsert_push_subscription",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/subscribe",+ json={+ "endpoint": untrusted_endpoint,+ "keys": {+ "p256dh": "test-p256dh-key",+ "auth": "test-auth-key",+ },+ },+ )++ assert response.status_code == 400+ mock_upsert.assert_not_awaited()+++def test_subscribe_push_surfaces_cap_as_400(mocker):+ mocker.patch(+ "backend.api.features.push.routes.upsert_push_subscription",+ new_callable=AsyncMock,+ side_effect=ValueError("Subscription limit of 20 per user reached"),+ )++ response = client.post(+ "/subscribe",+ json={+ "endpoint": "https://fcm.googleapis.com/fcm/send/abc123",+ "keys": {+ "p256dh": "test-p256dh-key",+ "auth": "test-auth-key",+ },+ },+ )++ assert response.status_code == 400+ assert "Subscription limit" in response.json()["detail"]diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex 87190410e8..7443dce954 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -34,6 +34,7 @@ import backend.api.features.oauthimport backend.api.features.otto.routesimport backend.api.features.platform_linking.routesimport backend.api.features.postmark.postmark+import backend.api.features.push.routes as push_routesimport backend.api.features.store.modelimport backend.api.features.store.routesimport backend.api.features.v1@@ -393,6 +394,11 @@ app.include_router(tags=["oauth"],prefix="/api/oauth",)+app.include_router(+ push_routes.router,+ tags=["push"],+ prefix="/api/push",+)app.include_router(backend.api.features.platform_linking.routes.router,tags=["platform-linking"],diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex e06fec1b58..f8f7f8c158 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -98,6 +98,12 @@ from backend.data.notifications import ()from backend.data.onboarding import increment_onboarding_runsfrom backend.data.platform_cost import log_platform_cost+from backend.data.push_subscription import (+ cleanup_failed_subscriptions,+ delete_push_subscription,+ get_user_push_subscriptions,+ increment_fail_count,+)from backend.data.understanding import (get_business_understanding,upsert_business_understanding,@@ -339,6 +345,16 @@ class DatabaseManager(AppService):# ============ Platform Cost Tracking ============ #log_platform_cost = _(log_platform_cost)+ # ============ Push Notifications ============ #+ get_user_push_subscriptions = _(get_user_push_subscriptions)+ delete_push_subscription = _(delete_push_subscription)+ increment_push_fail_count = _(+ increment_fail_count, name="increment_push_fail_count"+ )+ cleanup_failed_push_subscriptions = _(+ cleanup_failed_subscriptions, name="cleanup_failed_push_subscriptions"+ )+# ============ Platform Linking ============ #find_server_link_owner = _(platform_linking_db.find_server_link_owner)find_user_link_owner = _(platform_linking_db.find_user_link_owner)@@ -557,6 +573,12 @@ class DatabaseManagerAsyncClient(AppServiceClient):# ============ Platform Cost Tracking ============ #log_platform_cost = d.log_platform_cost+ # ============ Push Notifications ============ #+ get_user_push_subscriptions = d.get_user_push_subscriptions+ delete_push_subscription = d.delete_push_subscription+ increment_push_fail_count = d.increment_push_fail_count+ cleanup_failed_push_subscriptions = d.cleanup_failed_push_subscriptions+# ============ Platform Linking ============ #find_server_link_owner = d.find_server_link_ownerfind_user_link_owner = d.find_user_link_ownerdiff --git a/autogpt_platform/backend/backend/data/notification_bus.py b/autogpt_platform/backend/backend/data/notification_bus.pyindex f20e571ced..f7ab10a375 100644--- a/autogpt_platform/backend/backend/data/notification_bus.py+++ b/autogpt_platform/backend/backend/data/notification_bus.py@@ -1,15 +1,23 @@from __future__ import annotations+import asyncio+import loggingfrom typing import AsyncGeneratorfrom pydantic import BaseModel, field_serializerfrom backend.api.model import NotificationPayloadfrom backend.data.event_bus import AsyncRedisEventBus+from backend.data.push_sender import send_push_for_userfrom backend.util.settings import Settings+logger = logging.getLogger(__name__)_settings = Settings()+# Strong refs for in-flight push fanout tasks. asyncio only keeps weak refs+# to tasks, so a fire-and-forget create_task can be GC'd mid-run.+_push_tasks: set[asyncio.Task] = set()+class NotificationEvent(BaseModel):"""Generic notification event destined for websocket delivery."""@@ -23,6 +31,14 @@ class NotificationEvent(BaseModel):return payload.model_dump()+async def _safe_send_push(user_id: str, payload: NotificationPayload) -> None:+ """Deliver web push for a notification, swallowing errors."""+ try:+ await send_push_for_user(user_id, payload)+ except Exception:+ logger.exception("Failed to send web push for user %s", user_id)++class AsyncRedisNotificationEventBus(AsyncRedisEventBus[NotificationEvent]):Model = NotificationEvent # type: ignore@@ -32,6 +48,12 @@ class AsyncRedisNotificationEventBus(AsyncRedisEventBus[NotificationEvent]):async def publish(self, event: NotificationEvent) -> None:await self.publish_event(event, event.user_id)+ # Fan out to web push subscriptions in parallel. Fire-and-forget so+ # publishers never wait on the push service; held in _push_tasks so+ # the task survives until completion.+ task = asyncio.create_task(_safe_send_push(event.user_id, event.payload))+ _push_tasks.add(task)+ task.add_done_callback(_push_tasks.discard)async def listen(self, user_id: str) -> AsyncGenerator[NotificationEvent, None]:"""Stream notifications for a specific user."""diff --git a/autogpt_platform/backend/backend/data/notification_bus_test.py b/autogpt_platform/backend/backend/data/notification_bus_test.pyindex b55b692947..285aae1bea 100644--- a/autogpt_platform/backend/backend/data/notification_bus_test.py+++ b/autogpt_platform/backend/backend/data/notification_bus_test.py@@ -70,3 +70,51 @@ def test_event_bus_name_is_configured() -> None:so WS exec channels and notification channels never collide."""bus = AsyncRedisNotificationEventBus()assert bus.event_bus_name # non-empty, configured via Settings+++async def test_publish_fans_out_to_web_push():+ """publish() must also kick off web-push fanout for the user."""+ bus = AsyncRedisNotificationEventBus()+ event = NotificationEvent(+ user_id="user-42", payload=NotificationPayload(type="info", event="hi")+ )++ with (+ patch.object(AsyncRedisNotificationEventBus, "publish_event", AsyncMock()),+ patch(+ "backend.data.notification_bus.send_push_for_user",+ new_callable=AsyncMock,+ ) as mock_push,+ ):+ await bus.publish(event)+ # create_task is fire-and-forget — let the event loop drain the task.+ import asyncio++ for _ in range(3):+ await asyncio.sleep(0)++ mock_push.assert_awaited_once_with("user-42", event.payload)+++async def test_publish_swallows_push_errors():+ """A failing push must not propagate or fail the publish."""+ bus = AsyncRedisNotificationEventBus()+ event = NotificationEvent(+ user_id="user-42", payload=NotificationPayload(type="info", event="hi")+ )++ with (+ patch.object(AsyncRedisNotificationEventBus, "publish_event", AsyncMock()),+ patch(+ "backend.data.notification_bus.send_push_for_user",+ new_callable=AsyncMock,+ side_effect=RuntimeError("push backend down"),+ ),+ ):+ await bus.publish(event) # must not raise+ import asyncio++ for _ in range(3):+ await asyncio.sleep(0)diff --git a/autogpt_platform/backend/backend/data/push_sender.py b/autogpt_platform/backend/backend/data/push_sender.pynew file mode 100644index 0000000000..a721639b92--- /dev/null+++ b/autogpt_platform/backend/backend/data/push_sender.py@@ -0,0 +1,139 @@+"""Fire-and-forget Web Push delivery for notification events."""++import asyncio+import json+import logging+import re+import time+import uuid++from cachetools import TTLCache+from pywebpush import WebPushException, webpush++from backend.api.model import NotificationPayload+from backend.data.push_subscription import PushSubscriptionDTO, validate_push_endpoint+from backend.util.clients import get_database_manager_async_client+from backend.util.settings import Settings++logger = logging.getLogger(__name__)++_settings = Settings()++DEBOUNCE_SECONDS = 5.0+# Per-user debounce timestamps, bounded + auto-evicted so the process doesn't+# accumulate one entry per user forever. Process-local — ineffective across+# multiple WS replicas; acceptable since debounce is a best-effort UX nicety.+_user_last_push: TTLCache[str, float] = TTLCache(maxsize=10_000, ttl=DEBOUNCE_SECONDS)++# Fields to forward from the notification payload to the push message+_FORWARDED_FIELDS = ("session_id", "step", "status", "graph_id", "execution_id")+++def _extract_status_code(e: WebPushException) -> int | None:+ """Extract HTTP status code from a pywebpush exception."""+ if e.response is not None:+ return e.response.status_code+ # Fallback: parse "Push failed: <code> <reason>" out of the message in+ # case a future pywebpush version raises without attaching the Response.+ match = re.search(r"Push failed:\s*(\d{3})\b", str(e))+ return int(match.group(1)) if match else None+++def _build_push_payload(payload: NotificationPayload) -> str:+ """Build a compact JSON payload (<4KB) for the push message.++ ``id`` is a per-push UUID used by the service worker to build a unique+ notification tag, so repeat pushes don't get coalesced by the OS.+ """+ data = payload.model_dump(mode="json")+ compact: dict[str, object] = {+ "id": uuid.uuid4().hex,+ "type": data.get("type", ""),+ "event": data.get("event", ""),+ }+ for key in _FORWARDED_FIELDS:+ if key in data:+ compact[key] = data[key]+ return json.dumps(compact)+++async def send_push_for_user(user_id: str, payload: NotificationPayload) -> None:+ """Send push notifications to all of a user's subscriptions.++ - Skips silently if VAPID keys are not configured.+ - Debounces per-user (collapses pushes within DEBOUNCE_SECONDS).+ - Cleans up stale subscriptions on 410/404 responses.+ """+ vapid_private = _settings.secrets.vapid_private_key+ vapid_public = _settings.secrets.vapid_public_key+ vapid_claim_email = _settings.secrets.vapid_claim_email+ if not vapid_private or not vapid_public or not vapid_claim_email:+ logger.debug("VAPID keys not fully configured, skipping push")+ return+ # py_vapid rejects unprefixed strings deep in webpush(), where they'd+ # surface once per subscription as an "Unexpected error". Catch the+ # misconfiguration here and skip cleanly.+ if not vapid_claim_email.startswith(("mailto:", "https://")):+ logger.warning(+ "VAPID_CLAIM_EMAIL must start with 'mailto:' or 'https://', got %r — "+ "skipping push",+ vapid_claim_email[:40],+ )+ return++ if user_id in _user_last_push:+ logger.debug("Debouncing push for user %s", user_id)+ return+ _user_last_push[user_id] = time.monotonic()++ db_client = get_database_manager_async_client()+ subscriptions = await db_client.get_user_push_subscriptions(user_id)+ if not subscriptions:+ return++ push_data = _build_push_payload(payload)+ vapid_claims: dict[str, str | int] = {"sub": vapid_claim_email}++ async def _send_one(sub: PushSubscriptionDTO) -> None:+ try:+ # Defense-in-depth: reject endpoints that somehow bypassed the+ # subscribe-time check (rows written before the validator existed,+ # direct DB writes, or DNS changes that shifted a trusted host to+ # a blocked IP).+ await validate_push_endpoint(sub.endpoint)+ await asyncio.to_thread(+ webpush,+ subscription_info={+ "endpoint": sub.endpoint,+ "keys": {"p256dh": sub.p256dh, "auth": sub.auth},+ },+ data=push_data,+ vapid_private_key=vapid_private,+ vapid_claims=vapid_claims,+ )+ except ValueError as e:+ logger.warning(+ "Refusing push to untrusted endpoint %s: %s",+ sub.endpoint[:60],+ e,+ )+ await db_client.delete_push_subscription(sub.user_id, sub.endpoint)+ return+ except WebPushException as e:+ status = _extract_status_code(e)+ if status in (410, 404):+ logger.info(+ "Push subscription gone (%s), removing: %s",+ status,+ sub.endpoint[:60],+ )+ await db_client.delete_push_subscription(sub.user_id, sub.endpoint)+ else:+ logger.warning("Push failed for %s: %s", sub.endpoint[:60], e)+ await db_client.increment_push_fail_count(sub.user_id, sub.endpoint)+ except Exception:+ logger.exception("Unexpected error sending push to %s", sub.endpoint[:60])++ await asyncio.gather(+ *[_send_one(sub) for sub in subscriptions], return_exceptions=True+ )diff --git a/autogpt_platform/backend/backend/data/push_sender_test.py b/autogpt_platform/backend/backend/data/push_sender_test.pynew file mode 100644index 0000000000..2d095141ac--- /dev/null+++ b/autogpt_platform/backend/backend/data/push_sender_test.py@@ -0,0 +1,348 @@+"""Tests for fire-and-forget Web Push delivery."""++from unittest.mock import AsyncMock, MagicMock++import pytest++from backend.api.model import NotificationPayload+from backend.data import push_sender+from backend.data.push_subscription import PushSubscriptionDTO++[email protected](autouse=True)+def clear_debounce():+ """Reset the per-user debounce state between tests."""+ push_sender._user_last_push.clear()+ yield+ push_sender._user_last_push.clear()+++def mock_db_client(mocker):+ """Provides a mocked DatabaseManagerAsyncClient with stub async methods."""+ client = MagicMock()+ client.get_user_push_subscriptions = AsyncMock(return_value=[])+ client.delete_push_subscription = AsyncMock()+ client.increment_push_fail_count = AsyncMock()+ mocker.patch(+ "backend.data.push_sender.get_database_manager_async_client",+ return_value=client,+ )+ return client+++def _make_settings(+ private: str = "vapid-private",+ public: str = "vapid-public",+ email: str = "mailto:[email protected]",+) -> MagicMock:+ settings = MagicMock()+ settings.secrets.vapid_private_key = private+ settings.secrets.vapid_public_key = public+ settings.secrets.vapid_claim_email = email+ return settings+++def _make_subscription(+ user_id: str = "user-1",+ endpoint: str = "https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh: str = "test-p256dh",+ auth: str = "test-auth",+) -> PushSubscriptionDTO:+ return PushSubscriptionDTO(+ user_id=user_id, endpoint=endpoint, p256dh=p256dh, auth=auth+ )+++def _make_payload(**kwargs) -> NotificationPayload:+ defaults = {"type": "agent_run", "event": "completed"}+ defaults.update(kwargs)+ return NotificationPayload(**defaults)+++class TestBuildPushPayload:+ def test_includes_type_and_event(self):+ payload = _make_payload(type="agent_run", event="completed")++ result = push_sender._build_push_payload(payload)++ import json++ parsed = json.loads(result)+ assert parsed["type"] == "agent_run"+ assert parsed["event"] == "completed"++ def test_forwards_known_fields(self):+ payload = _make_payload(+ execution_id="exec-1",+ graph_id="graph-1",+ status="completed",+ )++ result = push_sender._build_push_payload(payload)++ import json++ parsed = json.loads(result)+ assert parsed["execution_id"] == "exec-1"+ assert parsed["graph_id"] == "graph-1"+ assert parsed["status"] == "completed"++ def test_excludes_unknown_fields(self):+ payload = _make_payload(+ custom_field="should-not-appear",+ )++ result = push_sender._build_push_payload(payload)++ import json++ parsed = json.loads(result)+ assert "custom_field" not in parsed++ def test_uses_model_dump_json_mode(self):+ """Ensure model_dump(mode='json') serializes enums to strings."""+ payload = _make_payload(type="agent_run", event="completed")++ result = push_sender._build_push_payload(payload)++ import json++ parsed = json.loads(result)+ assert isinstance(parsed["type"], str)+ assert isinstance(parsed["event"], str)++ def test_includes_unique_id_per_call(self):+ """Each push gets a fresh UUID so repeats don't collapse under the same SW tag."""+ import json++ payload = _make_payload(type="agent_run", event="completed")++ first = json.loads(push_sender._build_push_payload(payload))+ second = json.loads(push_sender._build_push_payload(payload))++ assert "id" in first and "id" in second+ assert first["id"] != second["id"]+++class TestSendPushForUser:+ @pytest.mark.asyncio+ async def test_skips_when_vapid_private_key_missing(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings(private=""))++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.get_user_push_subscriptions.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_skips_when_vapid_public_key_missing(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings(public=""))++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.get_user_push_subscriptions.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_skips_when_vapid_email_missing(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings(email=""))++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.get_user_push_subscriptions.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_debounces_rapid_calls(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings())++ await push_sender.send_push_for_user("user-1", _make_payload())+ assert mock_db_client.get_user_push_subscriptions.await_count == 1++ await push_sender.send_push_for_user("user-1", _make_payload())+ assert mock_db_client.get_user_push_subscriptions.await_count == 1++ @pytest.mark.asyncio+ async def test_different_users_not_debounced(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings())++ await push_sender.send_push_for_user("user-1", _make_payload())+ await push_sender.send_push_for_user("user-2", _make_payload())++ assert mock_db_client.get_user_push_subscriptions.await_count == 2++ @pytest.mark.asyncio+ async def test_returns_early_when_no_subscriptions(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings())+ mock_webpush = mocker.patch("backend.data.push_sender.webpush")++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_webpush.assert_not_called()++ @pytest.mark.asyncio+ async def test_calls_webpush_for_each_subscription(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub1 = _make_subscription(endpoint="https://fcm.googleapis.com/fcm/send/sub/1")+ sub2 = _make_subscription(endpoint="https://fcm.googleapis.com/fcm/send/sub/2")+ mock_db_client.get_user_push_subscriptions.return_value = [sub1, sub2]+ mock_webpush = mocker.patch("backend.data.push_sender.webpush")++ await push_sender.send_push_for_user("user-1", _make_payload())++ assert mock_webpush.call_count == 2++ calls = mock_webpush.call_args_list+ endpoints_called = [c.kwargs["subscription_info"]["endpoint"] for c in calls]+ assert "https://fcm.googleapis.com/fcm/send/sub/1" in endpoints_called+ assert "https://fcm.googleapis.com/fcm/send/sub/2" in endpoints_called++ @pytest.mark.asyncio+ async def test_webpush_called_with_correct_args(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub = _make_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="key-p256dh",+ auth="key-auth",+ )+ mock_db_client.get_user_push_subscriptions.return_value = [sub]+ mock_webpush = mocker.patch("backend.data.push_sender.webpush")++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_webpush.assert_called_once()+ call_kwargs = mock_webpush.call_args.kwargs+ assert call_kwargs["subscription_info"] == {+ "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1",+ "keys": {"p256dh": "key-p256dh", "auth": "key-auth"},+ }+ assert call_kwargs["vapid_private_key"] == "vapid-private"+ assert call_kwargs["vapid_claims"] == {"sub": "mailto:[email protected]"}+ assert isinstance(call_kwargs["data"], str)++ @pytest.mark.asyncio+ async def test_removes_subscription_on_410_gone(self, mocker, mock_db_client):+ from pywebpush import WebPushException++ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub = _make_subscription()+ mock_db_client.get_user_push_subscriptions.return_value = [sub]++ mock_response = MagicMock()+ mock_response.status_code = 410+ exc = WebPushException("Gone", response=mock_response)+ mocker.patch("backend.data.push_sender.webpush", side_effect=exc)++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.delete_push_subscription.assert_awaited_once_with(+ sub.user_id, sub.endpoint+ )++ @pytest.mark.asyncio+ async def test_removes_subscription_on_404(self, mocker, mock_db_client):+ from pywebpush import WebPushException++ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub = _make_subscription()+ mock_db_client.get_user_push_subscriptions.return_value = [sub]++ mock_response = MagicMock()+ mock_response.status_code = 404+ exc = WebPushException("Not Found", response=mock_response)+ mocker.patch("backend.data.push_sender.webpush", side_effect=exc)++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.delete_push_subscription.assert_awaited_once_with(+ sub.user_id, sub.endpoint+ )++ @pytest.mark.asyncio+ async def test_removes_subscription_when_status_only_in_message(+ self, mocker, mock_db_client+ ):+ """Some pywebpush versions don't expose .response.status_code; the+ sender must still detect 410 from the exception message and clean up."""+ from pywebpush import WebPushException++ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub = _make_subscription()+ mock_db_client.get_user_push_subscriptions.return_value = [sub]++ # No usable response object — only the message carries the status.+ exc = WebPushException("Push failed: 410 Gone\nResponse body:gone")+ exc.response = None # type: ignore[assignment]+ mocker.patch("backend.data.push_sender.webpush", side_effect=exc)++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.delete_push_subscription.assert_awaited_once_with(+ sub.user_id, sub.endpoint+ )++ @pytest.mark.asyncio+ async def test_increments_fail_count_on_other_webpush_error(+ self, mocker, mock_db_client+ ):+ from pywebpush import WebPushException++ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub = _make_subscription()+ mock_db_client.get_user_push_subscriptions.return_value = [sub]++ mock_response = MagicMock()+ mock_response.status_code = 429+ exc = WebPushException("Too Many Requests", response=mock_response)+ mocker.patch("backend.data.push_sender.webpush", side_effect=exc)++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.increment_push_fail_count.assert_awaited_once_with(+ sub.user_id, sub.endpoint+ )++ @pytest.mark.asyncio+ async def test_increments_fail_count_when_no_response_object(+ self, mocker, mock_db_client+ ):+ from pywebpush import WebPushException++ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub = _make_subscription()+ mock_db_client.get_user_push_subscriptions.return_value = [sub]++ exc = WebPushException("Connection error")+ mocker.patch("backend.data.push_sender.webpush", side_effect=exc)++ await push_sender.send_push_for_user("user-1", _make_payload())++ mock_db_client.increment_push_fail_count.assert_awaited_once_with(+ sub.user_id, sub.endpoint+ )++ @pytest.mark.asyncio+ async def test_handles_unexpected_exception_gracefully(+ self, mocker, mock_db_client+ ):+ mocker.patch.object(push_sender, "_settings", _make_settings())+ sub = _make_subscription()+ mock_db_client.get_user_push_subscriptions.return_value = [sub]+ mocker.patch(+ "backend.data.push_sender.webpush",+ side_effect=RuntimeError("network down"),+ )++ await push_sender.send_push_for_user("user-1", _make_payload())++ @pytest.mark.asyncio+ async def test_debounce_expires_after_threshold(self, mocker, mock_db_client):+ mocker.patch.object(push_sender, "_settings", _make_settings())++ await push_sender.send_push_for_user("user-1", _make_payload())+ assert mock_db_client.get_user_push_subscriptions.await_count == 1++ # Simulate TTL expiry (cachetools evicts on access after TTL elapses).+ push_sender._user_last_push.pop("user-1", None)++ await push_sender.send_push_for_user("user-1", _make_payload())+ assert mock_db_client.get_user_push_subscriptions.await_count == 2diff --git a/autogpt_platform/backend/backend/data/push_subscription.py b/autogpt_platform/backend/backend/data/push_subscription.pynew file mode 100644index 0000000000..2cfc6d5c7d--- /dev/null+++ b/autogpt_platform/backend/backend/data/push_subscription.py@@ -0,0 +1,142 @@+"""CRUD operations for Web Push subscriptions (PushSubscription model)."""++import logging+from datetime import datetime, timezone++from prisma.models import PushSubscription+from pydantic import BaseModel++from backend.util.request import validate_url_host++logger = logging.getLogger(__name__)+++# Hostnames of legitimate Web Push services. Endpoints submitted by+# clients must match one of these; everything else is rejected to prevent+# the backend (which POSTs to the stored URL via pywebpush) from being+# used as an SSRF primitive against internal infrastructure. Covers Chrome/+# Edge/Brave (FCM), Firefox (Autopush), and Safari/macOS (Apple Web Push).+_PUSH_SERVICE_HOSTNAMES: list[str] = [+ "fcm.googleapis.com",+ "updates.push.services.mozilla.com",+ "web.push.apple.com",+]++# Cap on concurrent push subscriptions per user — one entry per device/browser+# is typical, so this comfortably covers real usage while preventing an+# authenticated user from registering unbounded endpoints to amplify outbound+# traffic from the backend.+MAX_SUBSCRIPTIONS_PER_USER = 20++# Delete subscriptions with this many failed push attempts during periodic+# cleanup. Web Push sends occasionally fail transiently; beyond this threshold+# the endpoint is effectively dead and should be removed.+MAX_PUSH_FAILURES = 5+++async def validate_push_endpoint(endpoint: str) -> None:+ """Ensure a push-subscription endpoint is an HTTPS URL hosted on a known+ Web Push provider. Raises ``ValueError`` otherwise.++ Called at subscribe time and again before dispatch (defense-in-depth against+ rows written before this check existed or via future codepaths).+ """+ parsed, is_trusted, _ = await validate_url_host(+ endpoint, trusted_hostnames=_PUSH_SERVICE_HOSTNAMES+ )+ if parsed.scheme != "https":+ raise ValueError("Push endpoint must use https://")+ if not is_trusted:+ raise ValueError(+ f"Push endpoint host '{parsed.hostname}' is not a recognised "+ "Web Push service"+ )+++class PushSubscriptionDTO(BaseModel):+ """RPC-serializable projection of PushSubscription."""++ user_id: str+ endpoint: str+ p256dh: str+ auth: str++ @staticmethod+ def from_db(model: PushSubscription) -> "PushSubscriptionDTO":+ return PushSubscriptionDTO(+ user_id=model.userId,+ endpoint=model.endpoint,+ p256dh=model.p256dh,+ auth=model.auth,+ )+++async def upsert_push_subscription(+ user_id: str,+ endpoint: str,+ p256dh: str,+ auth: str,+ user_agent: str | None = None,+) -> PushSubscription:+ existing = await PushSubscription.prisma().find_many(+ where={"userId": user_id},+ )+ # Allow updates to an existing endpoint; only block when adding a *new* one+ # past the cap.+ has_this_endpoint = any(row.endpoint == endpoint for row in existing)+ if len(existing) >= MAX_SUBSCRIPTIONS_PER_USER and not has_this_endpoint:+ raise ValueError(+ f"Subscription limit of {MAX_SUBSCRIPTIONS_PER_USER} per user reached"+ )+ return await PushSubscription.prisma().upsert(+ where={"userId_endpoint": {"userId": user_id, "endpoint": endpoint}},+ data={+ "create": {+ "userId": user_id,+ "endpoint": endpoint,+ "p256dh": p256dh,+ "auth": auth,+ "userAgent": user_agent,+ },+ "update": {+ "p256dh": p256dh,+ "auth": auth,+ "userAgent": user_agent,+ "failCount": 0,+ "lastFailedAt": None,+ },+ },+ )+++async def get_user_push_subscriptions(user_id: str) -> list[PushSubscriptionDTO]:+ rows = await PushSubscription.prisma().find_many(where={"userId": user_id})+ return [PushSubscriptionDTO.from_db(row) for row in rows]+++async def delete_push_subscription(user_id: str, endpoint: str) -> None:+ await PushSubscription.prisma().delete_many(+ where={"userId": user_id, "endpoint": endpoint}+ )+++async def increment_fail_count(user_id: str, endpoint: str) -> None:+ await PushSubscription.prisma().update_many(+ where={"userId": user_id, "endpoint": endpoint},+ data={+ "failCount": {"increment": 1},+ "lastFailedAt": datetime.now(timezone.utc),+ },+ )+++async def cleanup_failed_subscriptions(+ max_failures: int = MAX_PUSH_FAILURES,+) -> int:+ """Delete subscriptions that have exceeded the failure threshold."""+ result = await PushSubscription.prisma().delete_many(+ where={"failCount": {"gte": max_failures}}+ )+ if result:+ logger.info(f"Cleaned up {result} failed push subscriptions")+ return result or 0diff --git a/autogpt_platform/backend/backend/data/push_subscription_test.py b/autogpt_platform/backend/backend/data/push_subscription_test.pynew file mode 100644index 0000000000..282e8f6306--- /dev/null+++ b/autogpt_platform/backend/backend/data/push_subscription_test.py@@ -0,0 +1,325 @@+"""Tests for Web Push subscription CRUD operations."""++from datetime import datetime+from unittest.mock import AsyncMock, MagicMock++import pytest++from backend.data import push_subscription+++def mock_prisma(mocker):+ """Mock PushSubscription.prisma() and return the mock client."""+ mock_client = MagicMock()+ mock_client.upsert = AsyncMock()+ mock_client.find_many = AsyncMock(return_value=[])+ mock_client.delete_many = AsyncMock()+ mock_client.update_many = AsyncMock()+ mocker.patch(+ "backend.data.push_subscription.PushSubscription.prisma",+ return_value=mock_client,+ )+ return mock_client+++class TestUpsertPushSubscription:+ @pytest.mark.asyncio+ async def test_calls_prisma_upsert_with_correct_params(self, mock_prisma):+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="test-p256dh",+ auth="test-auth",+ user_agent="Mozilla/5.0",+ )++ mock_prisma.upsert.assert_awaited_once()+ call_kwargs = mock_prisma.upsert.call_args.kwargs+ assert call_kwargs["where"] == {+ "userId_endpoint": {+ "userId": "user-1",+ "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1",+ }+ }+ assert call_kwargs["data"]["create"] == {+ "userId": "user-1",+ "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1",+ "p256dh": "test-p256dh",+ "auth": "test-auth",+ "userAgent": "Mozilla/5.0",+ }+ assert call_kwargs["data"]["update"] == {+ "p256dh": "test-p256dh",+ "auth": "test-auth",+ "userAgent": "Mozilla/5.0",+ "failCount": 0,+ "lastFailedAt": None,+ }++ @pytest.mark.asyncio+ async def test_upsert_without_user_agent(self, mock_prisma):+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ call_kwargs = mock_prisma.upsert.call_args.kwargs+ assert call_kwargs["data"]["create"]["userAgent"] is None+ assert call_kwargs["data"]["update"]["userAgent"] is None++ @pytest.mark.asyncio+ async def test_upsert_returns_prisma_result(self, mock_prisma):+ expected = MagicMock()+ mock_prisma.upsert.return_value = expected++ result = await push_subscription.upsert_push_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ assert result is expected++ @pytest.mark.asyncio+ async def test_upsert_resets_fail_count_on_update(self, mock_prisma):+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ call_kwargs = mock_prisma.upsert.call_args.kwargs+ assert call_kwargs["data"]["update"]["failCount"] == 0+ assert call_kwargs["data"]["update"]["lastFailedAt"] is None++ @pytest.mark.asyncio+ async def test_rejects_new_endpoint_past_cap(self, mock_prisma):+ existing = [+ MagicMock(endpoint=f"https://fcm.googleapis.com/fcm/send/sub/{i}")+ for i in range(push_subscription.MAX_SUBSCRIPTIONS_PER_USER)+ ]+ mock_prisma.find_many.return_value = existing++ with pytest.raises(ValueError, match="Subscription limit"):+ await push_subscription.upsert_push_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/NEW",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ mock_prisma.upsert.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_allows_update_of_existing_endpoint_at_cap(self, mock_prisma):+ existing = [+ MagicMock(endpoint=f"https://fcm.googleapis.com/fcm/send/sub/{i}")+ for i in range(push_subscription.MAX_SUBSCRIPTIONS_PER_USER)+ ]+ mock_prisma.find_many.return_value = existing+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/0",+ p256dh="rotated-p256dh",+ auth="rotated-auth",+ )++ mock_prisma.upsert.assert_awaited_once()+++class TestGetUserPushSubscriptions:+ @pytest.mark.asyncio+ async def test_returns_list_of_subscription_dtos(self, mock_prisma):+ sub1 = MagicMock(+ userId="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="key1",+ auth="auth1",+ )+ sub2 = MagicMock(+ userId="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/2",+ p256dh="key2",+ auth="auth2",+ )+ mock_prisma.find_many.return_value = [sub1, sub2]++ result = await push_subscription.get_user_push_subscriptions("user-1")++ assert [r.endpoint for r in result] == [+ "https://fcm.googleapis.com/fcm/send/sub/1",+ "https://fcm.googleapis.com/fcm/send/sub/2",+ ]+ assert all(r.user_id == "user-1" for r in result)+ mock_prisma.find_many.assert_awaited_once_with(where={"userId": "user-1"})++ @pytest.mark.asyncio+ async def test_returns_empty_list_when_no_subscriptions(self, mock_prisma):+ mock_prisma.find_many.return_value = []++ result = await push_subscription.get_user_push_subscriptions("user-1")++ assert result == []+++class TestDeletePushSubscription:+ @pytest.mark.asyncio+ async def test_deletes_by_user_id_and_endpoint(self, mock_prisma):+ await push_subscription.delete_push_subscription(+ "user-1",+ "https://fcm.googleapis.com/fcm/send/sub/1",+ )++ mock_prisma.delete_many.assert_awaited_once_with(+ where={+ "userId": "user-1",+ "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1",+ }+ )+++class TestIncrementFailCount:+ @pytest.mark.asyncio+ async def test_includes_user_id_in_where(self, mock_prisma):+ await push_subscription.increment_fail_count(+ "user-1",+ "https://fcm.googleapis.com/fcm/send/sub/1",+ )++ mock_prisma.update_many.assert_awaited_once()+ call_kwargs = mock_prisma.update_many.call_args.kwargs+ assert call_kwargs["where"] == {+ "userId": "user-1",+ "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1",+ }++ @pytest.mark.asyncio+ async def test_increments_fail_count_by_one(self, mock_prisma):+ await push_subscription.increment_fail_count(+ "user-1",+ "https://fcm.googleapis.com/fcm/send/sub/1",+ )++ call_kwargs = mock_prisma.update_many.call_args.kwargs+ assert call_kwargs["data"]["failCount"] == {"increment": 1}++ @pytest.mark.asyncio+ async def test_sets_last_failed_at_to_utc_now(self, mock_prisma):+ await push_subscription.increment_fail_count(+ "user-1",+ "https://fcm.googleapis.com/fcm/send/sub/1",+ )++ call_kwargs = mock_prisma.update_many.call_args.kwargs+ last_failed = call_kwargs["data"]["lastFailedAt"]+ assert isinstance(last_failed, datetime)+ assert last_failed.tzinfo is not None+++class TestCleanupFailedSubscriptions:+ @pytest.mark.asyncio+ async def test_deletes_subscriptions_exceeding_threshold(self, mock_prisma):+ mock_prisma.delete_many.return_value = 3++ result = await push_subscription.cleanup_failed_subscriptions(+ max_failures=5,+ )++ assert result == 3+ mock_prisma.delete_many.assert_awaited_once_with(+ where={"failCount": {"gte": 5}}+ )++ @pytest.mark.asyncio+ async def test_uses_default_max_failures(self, mock_prisma):+ mock_prisma.delete_many.return_value = 0++ await push_subscription.cleanup_failed_subscriptions()++ call_kwargs = mock_prisma.delete_many.call_args.kwargs+ assert call_kwargs["where"]["failCount"]["gte"] == 5++ @pytest.mark.asyncio+ async def test_returns_zero_when_none_deleted(self, mock_prisma):+ mock_prisma.delete_many.return_value = 0++ result = await push_subscription.cleanup_failed_subscriptions()++ assert result == 0++ @pytest.mark.asyncio+ async def test_returns_zero_when_result_is_none(self, mock_prisma):+ mock_prisma.delete_many.return_value = None++ result = await push_subscription.cleanup_failed_subscriptions()++ assert result == 0+++class TestValidatePushEndpoint:+ """Endpoints from clients must land on a known Web Push service — otherwise+ the backend can be coerced into POSTing to internal hosts (SSRF)."""++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "endpoint",+ [+ "https://fcm.googleapis.com/fcm/send/abc",+ "https://updates.push.services.mozilla.com/wpush/v2/xyz",+ "https://web.push.apple.com/some-token",+ ],+ )+ async def test_allows_known_push_services(self, endpoint):+ await push_subscription.validate_push_endpoint(endpoint)++ @pytest.mark.asyncio+ async def test_rejects_http_scheme(self):+ with pytest.raises(ValueError):+ await push_subscription.validate_push_endpoint(+ "http://fcm.googleapis.com/fcm/send/abc"+ )++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "endpoint",+ [+ "https://localhost/evil",+ "https://127.0.0.1/evil",+ "https://169.254.169.254/latest/meta-data/",+ "https://internal-service.local/api",+ "https://attacker.example.com/push",+ ],+ )+ async def test_rejects_untrusted_hosts(self, endpoint):+ with pytest.raises(ValueError):+ await push_subscription.validate_push_endpoint(endpoint)++ @pytest.mark.asyncio+ async def test_rejects_non_http_scheme(self):+ with pytest.raises(ValueError):+ await push_subscription.validate_push_endpoint("file:///etc/passwd")++ @pytest.mark.asyncio+ async def test_custom_max_failures_threshold(self, mock_prisma):+ mock_prisma.delete_many.return_value = 1++ result = await push_subscription.cleanup_failed_subscriptions(+ max_failures=10,+ )++ assert result == 1+ call_kwargs = mock_prisma.delete_many.call_args.kwargs+ assert call_kwargs["where"]["failCount"]["gte"] == 10diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.pyindex 74af3a3830..890061ab3f 100644--- a/autogpt_platform/backend/backend/executor/scheduler.py+++ b/autogpt_platform/backend/backend/executor/scheduler.py@@ -259,6 +259,16 @@ def cleanup_oauth_tokens():run_async(_cleanup())+def cleanup_failed_push_subscriptions():+ """Delete push subscriptions that have exceeded the failure threshold."""++ async def _cleanup():+ db = get_database_manager_async_client()+ return await db.cleanup_failed_push_subscriptions()++ run_async(_cleanup())++def execution_accuracy_alerts():"""Check execution accuracy and send alerts if drops are detected."""return report_execution_accuracy_alerts()@@ -582,6 +592,16 @@ class Scheduler(AppService):jobstore=Jobstores.EXECUTION.value,)+ # Failed Push Subscription Cleanup - configurable interval+ self.scheduler.add_job(+ cleanup_failed_push_subscriptions,+ id="cleanup_failed_push_subscriptions",+ trigger="interval",+ replace_existing=True,+ seconds=config.push_subscription_cleanup_interval_hours * 3600,+ jobstore=Jobstores.EXECUTION.value,+ )+# Execution Accuracy Monitoring - configurable intervalself.scheduler.add_job(execution_accuracy_alerts,diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 486953fdaa..4dc774432e 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -420,6 +420,13 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):description="Hours between OAuth token cleanup runs (1-24 hours)",)+ push_subscription_cleanup_interval_hours: int = Field(+ default=24,+ ge=1,+ le=168,+ description="Hours between failed push subscription cleanup runs (1-168 hours)",+ )+upload_file_size_limit_mb: int = Field(default=256,ge=1,@@ -621,6 +628,16 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):description="The secret key to use for the unsubscribe user by token",)+ vapid_private_key: str = Field(+ default="", description="VAPID private key for Web Push"+ )+ vapid_public_key: str = Field(+ default="", description="VAPID public key for Web Push (base64url)"+ )+ vapid_claim_email: str = Field(+ default="mailto:[email protected]", description="VAPID contact email"+ )+# OAuth server credentials for integrations# --8<-- [start:OAuthServerCredentialsExample]github_client_id: str = Field(default="", description="GitHub OAuth client ID")diff --git a/autogpt_platform/backend/migrations/20260427110000_add_push_subscription/migration.sql b/autogpt_platform/backend/migrations/20260427110000_add_push_subscription/migration.sqlnew file mode 100644index 0000000000..6272d365d6--- /dev/null+++ b/autogpt_platform/backend/migrations/20260427110000_add_push_subscription/migration.sql@@ -0,0 +1,21 @@+-- CreateTable+CREATE TABLE "PushSubscription" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,+ "userId" TEXT NOT NULL,+ "endpoint" TEXT NOT NULL,+ "p256dh" TEXT NOT NULL,+ "auth" TEXT NOT NULL,+ "userAgent" TEXT,+ "failCount" INTEGER NOT NULL DEFAULT 0,+ "lastFailedAt" TIMESTAMP(3),++ CONSTRAINT "PushSubscription_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "PushSubscription_userId_endpoint_key" ON "PushSubscription"("userId", "endpoint");++-- AddForeignKey+ALTER TABLE "PushSubscription" ADD CONSTRAINT "PushSubscription_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/autogpt_platform/backend/poetry.lock b/autogpt_platform/backend/poetry.lockindex a9aafef96f..ae08dedaf7 100644--- a/autogpt_platform/backend/poetry.lock+++ b/autogpt_platform/backend/poetry.lock@@ -2645,6 +2645,20 @@ files = [{file = "html2text-2024.2.26.tar.gz", hash = "sha256:05f8e367d15aaabc96415376776cdd11afd5127a77fce6e36afc60c563ca2c32"},]+[[package]]+name = "http-ece"+version = "1.2.1"+description = "Encrypted Content Encoding for HTTP"+optional = false+python-versions = "*"+groups = ["main"]+files = [+ {file = "http_ece-1.2.1.tar.gz", hash = "sha256:8c6ab23116bbf6affda894acfd5f2ca0fb8facbcbb72121c11c75c33e7ce8cff"},+]++[package.dependencies]+cryptography = ">=2.5"+[[package]]name = "httpcore"version = "1.0.9"@@ -5396,6 +5410,24 @@ files = [{file = "psycopg2_binary-2.9.11-cp39-cp39-win_amd64.whl", hash = "sha256:875039274f8a2361e5207857899706da840768e2a775bf8c65e82f60b197df02"},]+[[package]]+name = "py-vapid"+version = "1.9.4"+description = "Simple VAPID header generation library"+optional = false+python-versions = "*"+groups = ["main"]+files = [+ {file = "py_vapid-1.9.4-py2.py3-none-any.whl", hash = "sha256:f165a5bf90dcf966b226114f01f178f137579a09784c7f0628fa2f0a299741b6"},+ {file = "py_vapid-1.9.4.tar.gz", hash = "sha256:a004023560cbc54e34fc06380a0580f04ffcc788e84fb6d19e9339eeb6551a28"},+]++[package.dependencies]+cryptography = ">=46"++[package.extras]+test = ["coverage", "flake8", "mock (>=1.0)", "pytest"]+[[package]]name = "pyarrow"version = "23.0.1"@@ -6307,6 +6339,28 @@ files = [{file = "pytz-2025.2.tar.gz", hash = "sha256:360b9e3dbb49a209c21ad61809c7fb453643e048b38924c765813546746e81c3"},]+[[package]]+name = "pywebpush"+version = "2.3.0"+description = "WebPush publication library"+optional = false+python-versions = ">=3.10"+groups = ["main"]+files = [+ {file = "pywebpush-2.3.0-py3-none-any.whl", hash = "sha256:3d97469fb14d4323c362319d438183737249a4115b50e146ce233e7f01e3cf98"},+ {file = "pywebpush-2.3.0.tar.gz", hash = "sha256:d1e27db8de9e6757c1875f67292554bd54c41874c36f4b5c4ebb5442dce204f2"},+]++[package.dependencies]+aiohttp = "*"+cryptography = ">=2.6.1"+http-ece = ">=1.1.0"+py-vapid = ">=1.7.0"+requests = ">=2.21.0"++[package.extras]+dev = ["black", "mock", "pytest"]+[[package]]name = "pywin32"version = "311"@@ -8931,4 +8985,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt[metadata]lock-version = "2.1"python-versions = ">=3.10,<3.14"-content-hash = "529e1acbb1213421ef617f9dab309787cf81ea5d787eeffebc1bd38a42daf976"+content-hash = "8b33b42305e8168e4427c57daba0ea91f96809a08f428ec491a47bd11e80b1a8"diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.tomlindex 6b02a120a4..834724b92b 100644--- a/autogpt_platform/backend/pyproject.toml+++ b/autogpt_platform/backend/pyproject.toml@@ -60,6 +60,7 @@ psutil = "^7.0.0"psycopg2-binary = "^2.9.10"pydantic = { extras = ["email"], version = "^2.12.5" }pydantic-settings = "^2.12.0"+pywebpush = "^2.3"pytest = "^8.4.1"pytest-asyncio = "^1.1.0"python-dotenv = "^1.1.1"diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex a689151934..c578f8f74e 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -72,6 +72,7 @@ model User {APIKeys APIKey[]IntegrationWebhooks IntegrationWebhook[]NotificationBatches UserNotificationBatch[]+ PushSubscriptions PushSubscription[]PendingHumanReviews PendingHumanReview[]Workspace UserWorkspace?PlatformCostLogs PlatformCostLog[]@@ -426,6 +427,25 @@ model UserNotificationBatch {@@unique([userId, type])}+model PushSubscription {+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ userId String+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)++ endpoint String+ p256dh String+ auth String++ userAgent String?+ failCount Int @default(0)+ lastFailedAt DateTime?++ @@unique([userId, endpoint])+}+// For the library page// It is a user controlled list of agents, that they will see in their librarymodel LibraryAgent {diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.defaultindex 7a9d81e39e..ca663b054d 100644--- a/autogpt_platform/frontend/.env.default+++ b/autogpt_platform/frontend/.env.default@@ -35,5 +35,8 @@ NEXT_PUBLIC_PREVIEW_STEALING_DEV=NEXT_PUBLIC_POSTHOG_KEY=NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com+# Web Push VAPID public key (same as backend VAPID_PUBLIC_KEY)+NEXT_PUBLIC_VAPID_PUBLIC_KEY=BBg49iVTWthVbRYphwmZNvZyiSJDqtSO4nmLxDzLKe3Oo9jbtu0Usa14xX4HQQNLUeiEfzD42zWSlrvY1PR12bs+# OpenAI (for voice transcription)OPENAI_API_KEY=diff --git a/autogpt_platform/frontend/public/push-sw.js b/autogpt_platform/frontend/public/push-sw.jsnew file mode 100644index 0000000000..2a52701797--- /dev/null+++ b/autogpt_platform/frontend/public/push-sw.js@@ -0,0 +1,284 @@+// push-sw.js — Generic Web Push service worker for AutoGPT Platform.+// Handles push events for ALL notification types.+// Plain JS (not TypeScript) because Next.js serves public/ files as-is.++/** @type {Record<string, Record<string, {title: string, body: string, url: string}>>} */+var NOTIFICATION_MAP = {+ copilot_completion: {+ session_completed: {+ title: "AutoPilot is ready",+ body: "A response is waiting for you.",+ url: "/copilot",+ },+ session_failed: {+ title: "AutoPilot session failed",+ body: "Something went wrong with your session.",+ url: "/copilot",+ },+ },+ onboarding: {+ step_completed: {+ title: "Onboarding progress",+ body: "You completed an onboarding step!",+ url: "/",+ },+ },+};++function getNotificationConfig(data) {+ var typeMap = NOTIFICATION_MAP[data.type];+ if (typeMap) {+ var eventConfig = typeMap[data.event];+ if (eventConfig) return eventConfig;+ }+ return {+ title: "AutoGPT Notification",+ body: data.event || "Something happened.",+ url: "/",+ };+}++self.addEventListener("install", function () {+ self.skipWaiting();+});++self.addEventListener("activate", function (event) {+ event.waitUntil(self.clients.claim());+});++// Chrome's WindowClient.url doesn't update for Next.js client-side navigation+// (history.pushState), so the SW sees stale URLs. Pages postMessage their+// current pathname+search whenever it changes; we cache it per client id and+// use it for suppression decisions instead of trusting client.url.+var _clientUrls = {};++// User-controlled master toggle. Pages postMessage on mount and on change.+// Default true: if the SW restarts and no tab has reported yet, pushes still+// fire — the worst case is one notification before the page mounts and+// re-syncs the flag.+var _notificationsEnabled = true;++self.addEventListener("message", function (event) {+ if (!event.data) return;+ if (event.data.type === "CLIENT_URL") {+ if (!event.source || !event.source.id) return;+ if (typeof event.data.url !== "string") return;+ // Only accept same-origin relative paths. Defends against a hostile+ // (e.g. XSS-injected) page pinning an attacker-controlled URL that+ // would later be passed to clients.openWindow on notification click.+ if (!event.data.url.startsWith("/") || event.data.url.startsWith("//")) {+ return;+ }+ if (event.data.url.length > 2048) return;+ _clientUrls[event.source.id] = event.data.url;+ return;+ }+ if (event.data.type === "NOTIFICATIONS_ENABLED") {+ _notificationsEnabled = event.data.value !== false;+ return;+ }+});++function _effectiveUrl(client) {+ var cached = _clientUrls[client.id];+ if (typeof cached === "string") {+ // Cached value is pathname + search; the URL constructor needs an origin+ // to parse it, so resolve against this SW's origin.+ return new URL(cached, self.location.origin).href;+ }+ return client.url;+}++function isClientViewingTarget(client, targetUrl) {+ if (client.visibilityState !== "visible" || !client.focused) return false;+ try {+ var clientUrl = new URL(client.url);+ var target = new URL(targetUrl, self.location.origin);+ // Pathname-only — any /copilot page covers any session: the sidebar's+ // green-check indicator already surfaces completed sessions, so an OS+ // popup on top of that is noise. The only thing this suppression+ // *prevents* is duplicates while the user is already in the feature.+ return clientUrl.pathname === target.pathname;+ } catch (_) {+ return false;+ }+}++self.addEventListener("push", function (event) {+ if (!event.data) return;+ if (!_notificationsEnabled) return;++ var data;+ try {+ data = event.data.json();+ } catch (_) {+ return;+ }++ var config = getNotificationConfig(data);++ var targetUrl = config.url;+ if (data.type === "copilot_completion" && data.session_id) {+ targetUrl = "/copilot?sessionId=" + data.session_id;+ }++ event.waitUntil(+ self.clients+ .matchAll({ type: "window", includeUncontrolled: true })+ .then(function (clients) {+ // Drop URL cache entries for clients that no longer exist.+ var liveIds = {};+ clients.forEach(function (c) {+ liveIds[c.id] = true;+ });+ Object.keys(_clientUrls).forEach(function (id) {+ if (!liveIds[id]) delete _clientUrls[id];+ });+ var userIsAlreadyLooking = clients.some(function (c) {+ return isClientViewingTarget(+ {+ visibilityState: c.visibilityState,+ focused: c.focused,+ url: _effectiveUrl(c),+ },+ targetUrl,+ );+ });+ if (userIsAlreadyLooking) return;++ // Unique tag per push so repeat notifications aren't coalesced by the OS.+ // Falls back to Date.now() if the backend omitted `id`.+ var tag = data.type + ":" + data.event + ":" + (data.id || Date.now());++ var options = {+ body: config.body,+ icon: "/favicon.ico",+ badge: "/favicon.ico",+ tag: tag,+ data: Object.assign({ url: targetUrl }, data),+ renotify: true,+ };++ return self.registration.showNotification(config.title, options);+ }),+ );+});++self.addEventListener("notificationclick", function (event) {+ event.notification.close();+ var url = (event.notification.data && event.notification.data.url) || "/";++ function openFresh() {+ return self.clients.openWindow ? self.clients.openWindow(url) : undefined;+ }++ event.waitUntil(+ self.clients+ .matchAll({ type: "window", includeUncontrolled: true })+ .then(function (clientList) {+ // Use _effectiveUrl(c), not c.url — c.url is stale for SPA navigation.+ // Only focus a tab whose pathname already matches the target; never+ // navigate an unrelated tab away from what the user was doing.+ // Substring matching (.includes) is wrong here: a fallback target of+ // "/" would match every URL, and "/copilot" would match+ // "/copilot-archive".+ var targetPath;+ try {+ targetPath = new URL(url, self.location.origin).pathname;+ } catch (_) {+ return openFresh();+ }+ for (var i = 0; i < clientList.length; i++) {+ var client = clientList[i];+ if (!("focus" in client)) continue;+ try {+ if (new URL(_effectiveUrl(client)).pathname === targetPath) {+ return client.focus().catch(openFresh);+ }+ } catch (_) {+ // skip clients with unparseable URLs+ }+ }+ return openFresh();+ }),+ );+});++// Decodes a base64url-encoded string (no padding) into a Uint8Array.+// Needed because PushManager.subscribe wants applicationServerKey as bytes+// but the backend serves the VAPID key as a base64url string.+function _base64UrlToUint8(value) {+ var padded = value + "===".slice((value.length + 3) % 4);+ var b64 = padded.replace(/-/g, "+").replace(/_/g, "/");+ var raw = atob(b64);+ var out = new Uint8Array(raw.length);+ for (var i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);+ return out;+}++function _resubscribeOptions(oldSubscription) {+ if (oldSubscription && oldSubscription.options.applicationServerKey) {+ return Promise.resolve({+ userVisibleOnly: true,+ applicationServerKey: oldSubscription.options.applicationServerKey,+ });+ }+ // Firefox occasionally fires pushsubscriptionchange with no oldSubscription;+ // without applicationServerKey the new sub can't be VAPID-authenticated and+ // every push from the backend will fail. Pull the public key from the API.+ return fetch("/api/proxy/api/push/vapid-key", { credentials: "include" })+ .then(function (r) {+ return r.ok ? r.json() : null;+ })+ .then(function (data) {+ if (!data || !data.public_key) return { userVisibleOnly: true };+ return {+ userVisibleOnly: true,+ applicationServerKey: _base64UrlToUint8(data.public_key),+ };+ })+ .catch(function () {+ return { userVisibleOnly: true };+ });+}++self.addEventListener("pushsubscriptionchange", function (event) {+ event.waitUntil(+ (event.newSubscription+ ? Promise.resolve(event.newSubscription)+ : _resubscribeOptions(event.oldSubscription).then(function (opts) {+ return self.registration.pushManager.subscribe(opts);+ }))+ .then(function (newSub) {+ if (!newSub) return;+ // toJSON() returns base64url-encoded keys per the Web Push spec, which+ // is what pywebpush on the backend expects. Building the keys via+ // btoa(...) would produce standard base64 (with +/=) and break decoding.+ var json = newSub.toJSON();+ return fetch("/api/proxy/api/push/subscribe", {+ method: "POST",+ credentials: "include",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ endpoint: json.endpoint,+ keys: {+ p256dh: (json.keys && json.keys.p256dh) || "",+ auth: (json.keys && json.keys.auth) || "",+ },+ }),+ });+ })+ .catch(function () {+ // If re-subscription fails, notify open clients so they can retry.+ // Return the promise so event.waitUntil keeps the SW alive until+ // every postMessage has been delivered.+ return self.clients+ .matchAll({ type: "window" })+ .then(function (clientList) {+ for (var i = 0; i < clientList.length; i++) {+ clientList[i].postMessage({ type: "PUSH_SUBSCRIPTION_CHANGED" });+ }+ });+ }),+ );+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.tsnew file mode 100644index 0000000000..168720660e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.ts@@ -0,0 +1,196 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotNotifications } from "../useCopilotNotifications";++type WsHandler = (notification: Record<string, unknown>) => void;+let capturedHandler: WsHandler | null = null;++const mockApi = {+ onWebSocketMessage: vi.fn((_method: string, handler: WsHandler) => {+ capturedHandler = handler;+ return () => {+ capturedHandler = null;+ };+ }),+};++vi.mock("@/lib/autogpt-server-api/context", () => ({+ useBackendAPI: () => mockApi,+}));++const mockStoreState = {+ completedSessionIDs: new Set<string>(),+ addCompletedSession: vi.fn(),+ isNotificationsEnabled: true,+ isSoundEnabled: false,+};++vi.mock("../store", () => ({+ useCopilotUIStore: {+ getState: () => mockStoreState,+ setState: vi.fn(),+ },+}));++vi.mock("../helpers", () => ({+ ORIGINAL_TITLE: "AutoGPT",+ formatNotificationTitle: (count: number) => `(${count}) AutoPilot is ready`,+ parseSessionIDs: () => new Set<string>(),+}));++vi.mock("@/services/storage/local-storage", () => ({+ Key: { COPILOT_COMPLETED_SESSIONS: "copilot-completed-sessions" },+ storage: { get: vi.fn(), set: vi.fn(), remove: vi.fn() },+}));++vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ getGetV2ListSessionsQueryKey: () => ["sessions"],+}));++vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),+}));++const mockNotificationCtor = vi.fn();++function fireCompletion(sessionID: string) {+ if (!capturedHandler) throw new Error("handler not captured");+ capturedHandler({+ type: "copilot_completion",+ event: "session_completed",+ session_id: sessionID,+ });+}++describe("useCopilotNotifications — push SW suppression", () => {+ beforeEach(() => {+ capturedHandler = null;+ mockApi.onWebSocketMessage.mockClear();+ mockStoreState.completedSessionIDs = new Set();+ mockStoreState.isNotificationsEnabled = true;+ mockStoreState.isSoundEnabled = false;+ mockStoreState.addCompletedSession.mockClear();++ mockNotificationCtor.mockClear();+ const NotificationStub = function Notification(+ this: unknown,+ title: string,+ opts: unknown,+ ) {+ mockNotificationCtor(title, opts);+ } as unknown as typeof Notification;+ (NotificationStub as unknown as { permission: string }).permission =+ "granted";+ Object.defineProperty(globalThis, "Notification", {+ value: NotificationStub,+ configurable: true,+ writable: true,+ });++ const AudioStub = function AudioStub(this: Record<string, unknown>) {+ this.volume = 0;+ this.play = () => Promise.resolve();+ } as unknown as typeof Audio;+ vi.stubGlobal("Audio", AudioStub);++ // Start with "user away" so the hook triggers the notification path:+ // blur fires after mount; simulate by setting visibilityState to hidden.+ Object.defineProperty(document, "visibilityState", {+ value: "hidden",+ configurable: true,+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ function installServiceWorker(args: {+ registration: unknown | null;+ pushSubscription?: unknown | null;+ }) {+ const swReg =+ args.registration === null+ ? null+ : {+ pushManager: {+ getSubscription: vi+ .fn()+ .mockResolvedValue(args.pushSubscription ?? null),+ },+ };+ Object.defineProperty(navigator, "serviceWorker", {+ value: {+ getRegistration: vi.fn().mockResolvedValue(swReg),+ },+ configurable: true,+ });+ }++ it("skips in-page Notification when push SW subscription is active", async () => {+ installServiceWorker({+ registration: {},+ pushSubscription: { endpoint: "https://fcm.googleapis.com/x" },+ });++ renderHook(() => useCopilotNotifications(null));++ await act(async () => {+ fireCompletion("session-1");+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mockStoreState.addCompletedSession).toHaveBeenCalledWith(+ "session-1",+ );+ expect(mockNotificationCtor).not.toHaveBeenCalled();+ });++ it("uses in-page Notification when SW registration has no push subscription", async () => {+ installServiceWorker({+ registration: {},+ pushSubscription: null,+ });++ renderHook(() => useCopilotNotifications(null));++ await act(async () => {+ fireCompletion("session-2");+ });+ await waitFor(() => {+ expect(mockNotificationCtor).toHaveBeenCalledTimes(1);+ });+ expect(mockNotificationCtor.mock.calls[0][0]).toBe("AutoPilot is ready");+ });++ it("uses in-page Notification when no SW registration exists", async () => {+ installServiceWorker({ registration: null });++ renderHook(() => useCopilotNotifications(null));++ await act(async () => {+ fireCompletion("session-3");+ });+ await waitFor(() => {+ expect(mockNotificationCtor).toHaveBeenCalledTimes(1);+ });+ });++ it("uses in-page Notification when serviceWorker API is unavailable", async () => {+ Object.defineProperty(navigator, "serviceWorker", {+ value: undefined,+ configurable: true,+ });++ renderHook(() => useCopilotNotifications(null));++ await act(async () => {+ fireCompletion("session-4");+ });+ await waitFor(() => {+ expect(mockNotificationCtor).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/NotificationToggle/__tests__/NotificationToggle.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/NotificationToggle/__tests__/NotificationToggle.test.tsxnew file mode 100644index 0000000000..6584fb68ab--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/components/NotificationToggle/__tests__/NotificationToggle.test.tsx@@ -0,0 +1,141 @@+import {+ cleanup,+ render,+ screen,+ fireEvent,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotUIStore } from "../../../../../store";+import { NotificationToggle } from "../NotificationToggle";++vi.mock("@sentry/nextjs", () => ({+ captureException: vi.fn(),+}));++vi.mock("@/services/environment", () => ({+ environment: {+ isServerSide: vi.fn(() => false),+ isClientSide: vi.fn(() => true),+ getAGPTServerApiUrl: vi.fn(() => "http://localhost:8006/api"),+ },+}));++function resetStore() {+ useCopilotUIStore.setState({+ isNotificationsEnabled: false,+ isSoundEnabled: true,+ showNotificationDialog: false,+ });+}++function clickTrigger() {+ const triggers = screen.getAllByLabelText("Notification settings");+ fireEvent.click(triggers[0]);+}++describe("NotificationToggle", () => {+ beforeEach(() => {+ window.localStorage.clear();+ resetStore();+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });+ });++ afterEach(() => {+ cleanup();+ });++ it("renders notification settings button", () => {+ render(<NotificationToggle />);++ expect(+ screen.getAllByLabelText("Notification settings").length,+ ).toBeGreaterThan(0);+ });++ it("shows popover with toggles when clicked", async () => {+ render(<NotificationToggle />);++ clickTrigger();++ expect(await screen.findByText("Notifications")).toBeDefined();+ expect(screen.getByText("Sound")).toBeDefined();+ });++ it("enables notifications when toggled on with granted permission", async () => {+ const requestPermission = vi.fn().mockResolvedValue("granted");+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission },+ configurable: true,+ writable: true,+ });++ render(<NotificationToggle />);++ clickTrigger();++ const notifSwitch = await screen.findByRole("switch", {+ name: /notifications/i,+ });+ fireEvent.click(notifSwitch);++ await waitFor(() => {+ expect(requestPermission).toHaveBeenCalled();+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(true);+ });+ });++ it("disables notifications when toggled off", async () => {+ useCopilotUIStore.setState({ isNotificationsEnabled: true });++ render(<NotificationToggle />);++ clickTrigger();++ const notifSwitch = await screen.findByRole("switch", {+ name: /notifications/i,+ });+ fireEvent.click(notifSwitch);++ await waitFor(() => {+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false);+ });+ });++ it("disables sound switch when notifications are off", async () => {+ useCopilotUIStore.setState({ isNotificationsEnabled: false });++ render(<NotificationToggle />);++ clickTrigger();++ const soundSwitch = await screen.findByRole("switch", {+ name: /sound/i,+ });+ expect(+ soundSwitch.hasAttribute("disabled") ||+ soundSwitch.getAttribute("data-disabled") !== null,+ ).toBe(true);+ });++ it("toggles sound when clicked", async () => {+ useCopilotUIStore.setState({ isNotificationsEnabled: true });++ render(<NotificationToggle />);++ clickTrigger();++ const soundSwitch = await screen.findByRole("switch", {+ name: /sound/i,+ });+ fireEvent.click(soundSwitch);++ await waitFor(() => {+ expect(useCopilotUIStore.getState().isSoundEnabled).toBe(false);+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/__tests__/NotificationBanner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/__tests__/NotificationBanner.test.tsxnew file mode 100644index 0000000000..cb12bc1cae--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/__tests__/NotificationBanner.test.tsx@@ -0,0 +1,146 @@+import {+ cleanup,+ render,+ screen,+ fireEvent,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotUIStore } from "../../../store";+import { NotificationBanner } from "../NotificationBanner";++vi.mock("@sentry/nextjs", () => ({+ captureException: vi.fn(),+}));++vi.mock("@/services/environment", () => ({+ environment: {+ isServerSide: vi.fn(() => false),+ isClientSide: vi.fn(() => true),+ getAGPTServerApiUrl: vi.fn(() => "http://localhost:8006/api"),+ },+}));++function resetStore() {+ useCopilotUIStore.setState({+ isNotificationsEnabled: false,+ isSoundEnabled: true,+ });+}++describe("NotificationBanner", () => {+ beforeEach(() => {+ window.localStorage.clear();+ resetStore();+ });++ afterEach(() => {+ cleanup();+ });++ it("renders when permission is default and not dismissed", () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });++ render(<NotificationBanner />);++ expect(screen.getByText(/enable browser notifications/i)).toBeDefined();+ expect(screen.getByRole("button", { name: /^enable$/i })).toBeDefined();+ });++ it("does not render when already dismissed", () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });+ window.localStorage.setItem(+ "copilot-notification-banner-dismissed",+ "true",+ );++ const { container } = render(<NotificationBanner />);++ expect(container.innerHTML).toBe("");+ });++ it("does not render when notifications are already enabled", () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "granted", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });+ useCopilotUIStore.setState({ isNotificationsEnabled: true });++ const { container } = render(<NotificationBanner />);++ expect(container.innerHTML).toBe("");+ });++ it("does not render when permission is denied", () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "denied", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });++ const { container } = render(<NotificationBanner />);++ expect(container.innerHTML).toBe("");+ });++ it("requests permission and enables notifications on Enable click", async () => {+ const requestPermission = vi.fn().mockResolvedValue("granted");+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission },+ configurable: true,+ writable: true,+ });++ render(<NotificationBanner />);++ fireEvent.click(screen.getByRole("button", { name: /^enable$/i }));++ await waitFor(() => {+ expect(requestPermission).toHaveBeenCalled();+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(true);+ });+ });++ it("dismisses banner and sets localStorage on dismiss click", () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });++ render(<NotificationBanner />);++ fireEvent.click(screen.getByLabelText("Dismiss"));++ expect(+ window.localStorage.getItem("copilot-notification-banner-dismissed"),+ ).toBe("true");+ });++ it("does not enable notifications when permission is denied", async () => {+ const requestPermission = vi.fn().mockResolvedValue("denied");+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission },+ configurable: true,+ writable: true,+ });++ render(<NotificationBanner />);++ fireEvent.click(screen.getByRole("button", { name: /^enable$/i }));++ await waitFor(() => {+ expect(requestPermission).toHaveBeenCalled();+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false);+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationDialog/__tests__/NotificationDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationDialog/__tests__/NotificationDialog.test.tsxnew file mode 100644index 0000000000..a798eb33ca--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationDialog/__tests__/NotificationDialog.test.tsx@@ -0,0 +1,133 @@+import {+ cleanup,+ render,+ screen,+ fireEvent,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotUIStore } from "../../../store";+import { NotificationDialog } from "../NotificationDialog";++vi.mock("@sentry/nextjs", () => ({+ captureException: vi.fn(),+}));++vi.mock("@/services/environment", () => ({+ environment: {+ isServerSide: vi.fn(() => false),+ isClientSide: vi.fn(() => true),+ getAGPTServerApiUrl: vi.fn(() => "http://localhost:8006/api"),+ },+}));++function resetStore() {+ useCopilotUIStore.setState({+ isNotificationsEnabled: false,+ isSoundEnabled: true,+ showNotificationDialog: false,+ });+}++describe("NotificationDialog", () => {+ beforeEach(() => {+ window.localStorage.clear();+ resetStore();+ });++ afterEach(() => {+ cleanup();+ });++ it("shows dialog when permission is default and not dismissed", async () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });++ render(<NotificationDialog />);++ expect(await screen.findByText(/AutoPilot can notify you/i)).toBeDefined();+ expect(screen.getByText("Enable notifications")).toBeDefined();+ expect(screen.getByText("Not now")).toBeDefined();+ });++ it("does not show when already dismissed", () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });+ window.localStorage.setItem(+ "copilot-notification-dialog-dismissed",+ "true",+ );++ render(<NotificationDialog />);++ expect(screen.queryByText(/AutoPilot can notify you/i)).toBeNull();+ });++ it("does not show when permission is already granted", () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "granted", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });++ render(<NotificationDialog />);++ expect(screen.queryByText(/AutoPilot can notify you/i)).toBeNull();+ });++ it("requests permission on Enable click and enables notifications", async () => {+ const requestPermission = vi.fn().mockResolvedValue("granted");+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission },+ configurable: true,+ writable: true,+ });++ render(<NotificationDialog />);++ fireEvent.click(await screen.findByText("Enable notifications"));++ await waitFor(() => {+ expect(requestPermission).toHaveBeenCalled();+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(true);+ });+ });++ it("dismisses dialog on Not now click", async () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });++ render(<NotificationDialog />);++ fireEvent.click(await screen.findByText("Not now"));++ await waitFor(() => {+ expect(+ window.localStorage.getItem("copilot-notification-dialog-dismissed"),+ ).toBe("true");+ });+ });++ it("shows dialog when showNotificationDialog is set in store", async () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "denied", requestPermission: vi.fn() },+ configurable: true,+ writable: true,+ });+ // permission is denied and would not auto-show, but store flag overrides+ useCopilotUIStore.setState({ showNotificationDialog: true });++ render(<NotificationDialog />);++ expect(await screen.findByText(/AutoPilot can notify you/i)).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.tsindex bfd5ce3998..5e8c837837 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotNotifications.ts@@ -15,13 +15,25 @@ const NOTIFICATION_SOUND_PATH = "/notification.mp3";/*** Show a browser notification with click-to-navigate behaviour.- * Wrapped in try-catch so it degrades gracefully in service-worker or- * other restricted contexts where the Notification constructor throws.+ * If a push service worker subscription is active, the SW handles+ * notifications via the Push API — skip the in-page Notification to+ * avoid duplicates.*/-function showBrowserNotification(+async function showBrowserNotification(title: string,opts: { body: string; icon: string; sessionID: string },) {+ try {+ // If the push SW is handling notifications, skip the in-page fallback+ const swReg = await navigator.serviceWorker?.getRegistration?.("/");+ if (swReg) {+ const pushSub = await swReg.pushManager?.getSubscription?.();+ if (pushSub) return;+ }+ } catch {+ // serviceWorker API unavailable — fall through to Notification()+ }+try {const n = new Notification(title, { body: opts.body, icon: opts.icon });n.onclick = () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/layout.tsxindex 0d72326e17..c5db541ea8 100644--- a/autogpt_platform/frontend/src/app/(platform)/layout.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/layout.tsx@@ -1,5 +1,6 @@import { Navbar } from "@/components/layout/Navbar/Navbar";import { NetworkStatusMonitor } from "@/services/network-status/NetworkStatusMonitor";+import { PushNotificationProvider } from "@/services/push-notifications/PushNotificationProvider";import { ReactNode } from "react";import { AdminImpersonationBanner } from "./admin/components/AdminImpersonationBanner";import { AutoPilotBridgeProvider } from "@/contexts/AutoPilotBridgeContext";@@ -9,6 +10,7 @@ export default function PlatformLayout({ children }: { children: ReactNode }) {<AutoPilotBridgeProvider><main className="flex h-screen w-full flex-col"><NetworkStatusMonitor />+ <PushNotificationProvider /><Navbar /><AdminImpersonationBanner /><section className="flex-1">{children}</section>diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 7c068bbb22..9554bc00c4 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -7375,6 +7375,87 @@}}},+ "/api/push/subscribe": {+ "post": {+ "tags": ["push"],+ "summary": "Register a push subscription for the current user",+ "operationId": "postPushRegister a push subscription for the current user",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/PushSubscribeRequest" }+ }+ },+ "required": true+ },+ "responses": {+ "204": { "description": "Successful Response" },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },+ "/api/push/unsubscribe": {+ "post": {+ "tags": ["push"],+ "summary": "Remove a push subscription",+ "operationId": "postPushRemove a push subscription",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PushUnsubscribeRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "204": { "description": "Successful Response" },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },+ "/api/push/vapid-key": {+ "get": {+ "tags": ["push"],+ "summary": "Get VAPID public key for push subscription",+ "operationId": "getPushGet vapid public key for push subscription",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/VapidPublicKeyResponse"+ }+ }+ }+ }+ }+ }+ },"/api/review/action": {"post": {"tags": ["v2", "executions", "review", "v2", "executions", "review"],@@ -14559,6 +14640,59 @@"required": ["providers", "pagination"],"title": "ProviderResponse"},+ "PushSubscribeRequest": {+ "properties": {+ "endpoint": {+ "type": "string",+ "maxLength": 2048,+ "minLength": 1,+ "title": "Endpoint"+ },+ "keys": { "$ref": "#/components/schemas/PushSubscriptionKeys" },+ "user_agent": {+ "anyOf": [+ { "type": "string", "maxLength": 512 },+ { "type": "null" }+ ],+ "title": "User Agent"+ }+ },+ "type": "object",+ "required": ["endpoint", "keys"],+ "title": "PushSubscribeRequest"+ },+ "PushSubscriptionKeys": {+ "properties": {+ "p256dh": {+ "type": "string",+ "maxLength": 512,+ "minLength": 1,+ "title": "P256Dh"+ },+ "auth": {+ "type": "string",+ "maxLength": 512,+ "minLength": 1,+ "title": "Auth"+ }+ },+ "type": "object",+ "required": ["p256dh", "auth"],+ "title": "PushSubscriptionKeys"+ },+ "PushUnsubscribeRequest": {+ "properties": {+ "endpoint": {+ "type": "string",+ "maxLength": 2048,+ "minLength": 1,+ "title": "Endpoint"+ }+ },+ "type": "object",+ "required": ["endpoint"],+ "title": "PushUnsubscribeRequest"+ },"QueuePendingMessageRequest": {"properties": {"message": {@@ -18242,6 +18376,14 @@"required": ["loc", "msg", "type"],"title": "ValidationError"},+ "VapidPublicKeyResponse": {+ "properties": {+ "public_key": { "type": "string", "title": "Public Key" }+ },+ "type": "object",+ "required": ["public_key"],+ "title": "VapidPublicKeyResponse"+ },"Webhook": {"properties": {"id": { "type": "string", "title": "Id" },diff --git a/autogpt_platform/frontend/src/services/push-notifications/PushNotificationProvider.tsx b/autogpt_platform/frontend/src/services/push-notifications/PushNotificationProvider.tsxnew file mode 100644index 0000000000..fdb3e652b7--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/PushNotificationProvider.tsx@@ -0,0 +1,12 @@+"use client";++import { usePushNotifications } from "./usePushNotifications";+import { useReportClientUrl } from "./useReportClientUrl";+import { useReportNotificationsEnabled } from "./useReportNotificationsEnabled";++export function PushNotificationProvider() {+ usePushNotifications();+ useReportClientUrl();+ useReportNotificationsEnabled();+ return null;+}diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/api.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/api.test.tsnew file mode 100644index 0000000000..4282961e14--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/api.test.ts@@ -0,0 +1,218 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ fetchVapidPublicKey,+ removeSubscriptionFromServer,+ sendSubscriptionToServer,+} from "../api";++describe("fetchVapidPublicKey", () => {+ beforeEach(() => {+ vi.stubGlobal("fetch", vi.fn());+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("returns public key on success", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ public_key: "BFakeKey123" }),+ } as Response);++ const key = await fetchVapidPublicKey();++ expect(key).toBe("BFakeKey123");+ expect(fetch).toHaveBeenCalledWith("/api/proxy/api/push/vapid-key");+ });++ it("returns null when response is not ok", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: false,+ status: 500,+ } as Response);++ const key = await fetchVapidPublicKey();++ expect(key).toBeNull();+ });++ it("returns null when public_key is missing from response", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({}),+ } as Response);++ const key = await fetchVapidPublicKey();++ expect(key).toBeNull();+ });++ it("returns null on network error", async () => {+ vi.mocked(fetch).mockRejectedValue(new Error("Network error"));++ const key = await fetchVapidPublicKey();++ expect(key).toBeNull();+ });+});++describe("sendSubscriptionToServer", () => {+ const mockSubscription = {+ toJSON: () => ({+ endpoint: "https://push.example.com/sub/123",+ keys: { p256dh: "key-p256dh", auth: "key-auth" },+ }),+ } as unknown as PushSubscription;++ beforeEach(() => {+ vi.stubGlobal("fetch", vi.fn());+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("sends correct payload via proxy", async () => {+ vi.mocked(fetch).mockResolvedValue({ ok: true } as Response);++ await sendSubscriptionToServer(mockSubscription);++ expect(fetch).toHaveBeenCalledWith("/api/proxy/api/push/subscribe", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ endpoint: "https://push.example.com/sub/123",+ keys: { p256dh: "key-p256dh", auth: "key-auth" },+ user_agent: navigator.userAgent,+ }),+ });+ });++ it("returns true on 200 response", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 200,+ } as Response);++ const result = await sendSubscriptionToServer(mockSubscription);++ expect(result).toBe(true);+ });++ it("returns true on 204 response", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 204,+ } as Response);++ const result = await sendSubscriptionToServer(mockSubscription);++ expect(result).toBe(true);+ });++ it("returns false on failure", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: false,+ status: 500,+ } as Response);++ const result = await sendSubscriptionToServer(mockSubscription);++ expect(result).toBe(false);+ });++ it("returns false on network error", async () => {+ vi.mocked(fetch).mockRejectedValue(new Error("Network error"));++ const result = await sendSubscriptionToServer(mockSubscription);++ expect(result).toBe(false);+ });++ it("handles missing keys gracefully", async () => {+ const subWithoutKeys = {+ toJSON: () => ({+ endpoint: "https://push.example.com/sub/123",+ keys: undefined,+ }),+ } as PushSubscription;++ vi.mocked(fetch).mockResolvedValue({ ok: true } as Response);++ await sendSubscriptionToServer(subWithoutKeys);++ const body = JSON.parse(vi.mocked(fetch).mock.calls[0][1]?.body as string);+ expect(body.keys).toEqual({ p256dh: "", auth: "" });+ });+});++describe("removeSubscriptionFromServer", () => {+ beforeEach(() => {+ vi.stubGlobal("fetch", vi.fn());+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("sends endpoint via proxy", async () => {+ vi.mocked(fetch).mockResolvedValue({ ok: true } as Response);++ await removeSubscriptionFromServer("https://push.example.com/sub/123");++ expect(fetch).toHaveBeenCalledWith("/api/proxy/api/push/unsubscribe", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ endpoint: "https://push.example.com/sub/123",+ }),+ });+ });++ it("returns true on success", async () => {+ vi.mocked(fetch).mockResolvedValue({ ok: true } as Response);++ const result = await removeSubscriptionFromServer(+ "https://push.example.com/sub/123",+ );++ expect(result).toBe(true);+ });++ it("returns true on 204 response", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 204,+ } as Response);++ const result = await removeSubscriptionFromServer(+ "https://push.example.com/sub/123",+ );++ expect(result).toBe(true);+ });++ it("returns false on failure", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: false,+ status: 500,+ } as Response);++ const result = await removeSubscriptionFromServer(+ "https://push.example.com/sub/123",+ );++ expect(result).toBe(false);+ });++ it("returns false on network error", async () => {+ vi.mocked(fetch).mockRejectedValue(new Error("Network error"));++ const result = await removeSubscriptionFromServer(+ "https://push.example.com/sub/123",+ );++ expect(result).toBe(false);+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/helpers.test.tsnew file mode 100644index 0000000000..1ab70f0460--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/helpers.test.ts@@ -0,0 +1,160 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setupPushSubscription, teardownPushSubscription } from "../helpers";++const mockIsPushSupported = vi.fn(() => true);+const mockRegisterServiceWorker = vi.fn();+const mockSubscribeToPush = vi.fn();+const mockUnsubscribeFromPush = vi.fn();++vi.mock("../registration", () => ({+ isPushSupported: () => mockIsPushSupported(),+ registerServiceWorker: () => mockRegisterServiceWorker(),+ subscribeToPush: (...args: [unknown, unknown]) =>+ mockSubscribeToPush(...args),+ unsubscribeFromPush: (reg: unknown) => mockUnsubscribeFromPush(reg),+}));++const mockFetchVapidPublicKey = vi.fn();+const mockSendSubscriptionToServer = vi.fn();+const mockRemoveSubscriptionFromServer = vi.fn();++vi.mock("../api", () => ({+ fetchVapidPublicKey: () => mockFetchVapidPublicKey(),+ sendSubscriptionToServer: (sub: unknown) => mockSendSubscriptionToServer(sub),+ removeSubscriptionFromServer: (endpoint: string) =>+ mockRemoveSubscriptionFromServer(endpoint),+}));++const mockSubscription = { endpoint: "https://push.example.com/sub/1" };+const mockRegistration = {+ pushManager: { getSubscription: vi.fn() },+};++beforeEach(() => {+ vi.clearAllMocks();+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "granted" },+ configurable: true,+ writable: true,+ });+ Object.defineProperty(navigator, "serviceWorker", {+ value: {+ ready: Promise.resolve(mockRegistration),+ getRegistration: vi.fn().mockResolvedValue(mockRegistration),+ },+ configurable: true,+ });+ mockRegistration.pushManager.getSubscription = vi+ .fn()+ .mockResolvedValue(mockSubscription);+ mockIsPushSupported.mockReturnValue(true);+ mockRegisterServiceWorker.mockResolvedValue(mockRegistration);+ mockSubscribeToPush.mockResolvedValue(mockSubscription);+ mockFetchVapidPublicKey.mockResolvedValue("vapid-key-123");+ mockSendSubscriptionToServer.mockResolvedValue(true);+ mockUnsubscribeFromPush.mockResolvedValue(true);+ mockRemoveSubscriptionFromServer.mockResolvedValue(true);+ delete process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("setupPushSubscription", () => {+ it("returns true on the full happy path", async () => {+ const result = await setupPushSubscription();+ expect(result).toBe(true);+ expect(mockSendSubscriptionToServer).toHaveBeenCalledWith(mockSubscription);+ });++ it("returns false when push is not supported", async () => {+ mockIsPushSupported.mockReturnValue(false);+ const result = await setupPushSubscription();+ expect(result).toBe(false);+ expect(mockRegisterServiceWorker).not.toHaveBeenCalled();+ });++ it("returns false when notification permission is not granted", async () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default" },+ configurable: true,+ writable: true,+ });+ const result = await setupPushSubscription();+ expect(result).toBe(false);+ expect(mockRegisterServiceWorker).not.toHaveBeenCalled();+ });++ it("returns false when service worker registration fails", async () => {+ mockRegisterServiceWorker.mockResolvedValue(null);+ const result = await setupPushSubscription();+ expect(result).toBe(false);+ expect(mockSubscribeToPush).not.toHaveBeenCalled();+ });++ it("returns false when no vapid key is available", async () => {+ mockFetchVapidPublicKey.mockResolvedValue(null);+ const result = await setupPushSubscription();+ expect(result).toBe(false);+ expect(mockSubscribeToPush).not.toHaveBeenCalled();+ });++ it("uses NEXT_PUBLIC_VAPID_PUBLIC_KEY when set, skipping the server fetch", async () => {+ process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY = "build-time-key";+ await setupPushSubscription();+ expect(mockFetchVapidPublicKey).not.toHaveBeenCalled();+ expect(mockSubscribeToPush).toHaveBeenCalledWith(+ mockRegistration,+ "build-time-key",+ );+ });++ it("returns false when subscribeToPush fails", async () => {+ mockSubscribeToPush.mockResolvedValue(null);+ const result = await setupPushSubscription();+ expect(result).toBe(false);+ expect(mockSendSubscriptionToServer).not.toHaveBeenCalled();+ });+});++describe("teardownPushSubscription", () => {+ it("removes server subscription and unsubscribes locally", async () => {+ await teardownPushSubscription();+ expect(mockRemoveSubscriptionFromServer).toHaveBeenCalledWith(+ mockSubscription.endpoint,+ );+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockRegistration);+ });++ it("no-ops when serviceWorker is unavailable", async () => {+ Object.defineProperty(navigator, "serviceWorker", {+ value: undefined,+ configurable: true,+ });+ await teardownPushSubscription();+ expect(mockRemoveSubscriptionFromServer).not.toHaveBeenCalled();+ expect(mockUnsubscribeFromPush).not.toHaveBeenCalled();+ });++ it("no-ops when no registration exists", async () => {+ Object.defineProperty(navigator, "serviceWorker", {+ value: {+ getRegistration: vi.fn().mockResolvedValue(null),+ },+ configurable: true,+ });+ await teardownPushSubscription();+ expect(mockRemoveSubscriptionFromServer).not.toHaveBeenCalled();+ expect(mockUnsubscribeFromPush).not.toHaveBeenCalled();+ });++ it("no-ops when there is no active subscription", async () => {+ mockRegistration.pushManager.getSubscription = vi+ .fn()+ .mockResolvedValue(null);+ await teardownPushSubscription();+ expect(mockRemoveSubscriptionFromServer).not.toHaveBeenCalled();+ expect(mockUnsubscribeFromPush).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/push-sw-helpers.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/push-sw-helpers.test.tsnew file mode 100644index 0000000000..51ffd97f12--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/push-sw-helpers.test.ts@@ -0,0 +1,198 @@+import { readFileSync } from "fs";+import { dirname, resolve } from "path";+import { fileURLToPath } from "url";+import { runInNewContext } from "vm";+import { describe, expect, it } from "vitest";++/**+ * Loads public/push-sw.js into a sandbox and exposes the helpers it defines+ * as top-level vars. The SW file has to be hand-written JS (Next.js serves+ * public/ as-is), so these tests are our only guarantee that the routing+ * and suppression logic stays correct.+ */+function loadServiceWorkerHelpers() {+ const here = dirname(fileURLToPath(import.meta.url));+ const swPath = resolve(here, "../../../../public/push-sw.js");+ const source = readFileSync(swPath, "utf8");++ const sandbox: Record<string, unknown> = {+ self: {+ skipWaiting: () => undefined,+ clients: { claim: () => Promise.resolve(), matchAll: () => [] },+ addEventListener: () => undefined,+ location: { origin: "https://example.com" },+ registration: { pushManager: {} },+ },+ URL,+ Array,+ Object,+ };+ runInNewContext(source, sandbox);+ return sandbox as {+ NOTIFICATION_MAP: Record<+ string,+ Record<string, { title: string; body: string; url: string }>+ >;+ getNotificationConfig: (data: { type?: string; event?: string }) => {+ title: string;+ body: string;+ url: string;+ };+ isClientViewingTarget: (+ client: { visibilityState: string; focused: boolean; url: string },+ targetUrl: string,+ ) => boolean;+ _clientUrls: Record<string, string>;+ _effectiveUrl: (client: { id: string; url: string }) => string;+ };+}++describe("push-sw getNotificationConfig", () => {+ const sw = loadServiceWorkerHelpers();++ it("returns copilot session_completed config", () => {+ const config = sw.getNotificationConfig({+ type: "copilot_completion",+ event: "session_completed",+ });+ expect(config.title).toBe("AutoPilot is ready");+ expect(config.url).toBe("/copilot");+ });++ it("returns copilot session_failed config", () => {+ const config = sw.getNotificationConfig({+ type: "copilot_completion",+ event: "session_failed",+ });+ expect(config.title).toBe("AutoPilot session failed");+ });++ it("falls back to generic notification for unknown type", () => {+ const config = sw.getNotificationConfig({+ type: "unknown_type",+ event: "anything",+ });+ expect(config.title).toBe("AutoGPT Notification");+ expect(config.url).toBe("/");+ });++ it("falls back when event is unknown within a known type", () => {+ const config = sw.getNotificationConfig({+ type: "copilot_completion",+ event: "never_seen_event",+ });+ expect(config.title).toBe("AutoGPT Notification");+ });+});++describe("push-sw isClientViewingTarget", () => {+ const sw = loadServiceWorkerHelpers();++ function client(args: {+ url: string;+ visibilityState?: string;+ focused?: boolean;+ }) {+ return {+ visibilityState: args.visibilityState ?? "visible",+ focused: args.focused ?? true,+ url: args.url,+ };+ }++ it("returns false when tab is not visible", () => {+ const result = sw.isClientViewingTarget(+ client({ url: "https://example.com/copilot", visibilityState: "hidden" }),+ "/copilot",+ );+ expect(result).toBe(false);+ });++ it("returns false when window is not focused", () => {+ const result = sw.isClientViewingTarget(+ client({ url: "https://example.com/copilot", focused: false }),+ "/copilot",+ );+ expect(result).toBe(false);+ });++ it("returns true when pathname matches and no query params expected", () => {+ const result = sw.isClientViewingTarget(+ client({ url: "https://example.com/copilot" }),+ "/copilot",+ );+ expect(result).toBe(true);+ });++ it("returns false when pathname differs", () => {+ const result = sw.isClientViewingTarget(+ client({ url: "https://example.com/library" }),+ "/copilot",+ );+ expect(result).toBe(false);+ });++ it("returns true when sessionId matches", () => {+ const result = sw.isClientViewingTarget(+ client({ url: "https://example.com/copilot?sessionId=A" }),+ "/copilot?sessionId=A",+ );+ expect(result).toBe(true);+ });++ it("returns true when on a different session of the same feature page — sidebar shows the green check, OS popup would be noise", () => {+ const result = sw.isClientViewingTarget(+ client({ url: "https://example.com/copilot?sessionId=A" }),+ "/copilot?sessionId=B",+ );+ expect(result).toBe(true);+ });++ it("ignores query params on either side", () => {+ const result = sw.isClientViewingTarget(+ client({ url: "https://example.com/copilot?utm_source=email" }),+ "/copilot",+ );+ expect(result).toBe(true);+ });+});++describe("push-sw _effectiveUrl", () => {+ const sw = loadServiceWorkerHelpers();++ it("falls back to client.url when no cached URL is set", () => {+ const result = sw._effectiveUrl({+ id: "no-cache",+ url: "https://example.com/copilot",+ });+ expect(result).toBe("https://example.com/copilot");+ });++ it("returns the cached URL when present (resolves against SW origin)", () => {+ sw._clientUrls["client-1"] = "/library";+ const result = sw._effectiveUrl({+ id: "client-1",+ url: "https://example.com/copilot?sessionId=stale",+ });+ expect(result).toBe("https://example.com/library");+ });++ it("preserves query string from the cached URL", () => {+ sw._clientUrls["client-2"] = "/copilot?sessionId=fresh";+ const result = sw._effectiveUrl({+ id: "client-2",+ url: "https://example.com/copilot?sessionId=stale",+ });+ expect(result).toBe("https://example.com/copilot?sessionId=fresh");+ });+});++describe("push-sw notifications toggle", () => {+ const sw = loadServiceWorkerHelpers() as ReturnType<+ typeof loadServiceWorkerHelpers+ > & { _notificationsEnabled: boolean };++ it("defaults to enabled so a freshly-restarted SW still delivers", () => {+ expect(sw._notificationsEnabled).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/registration.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/registration.test.tsnew file mode 100644index 0000000000..212bbc0759--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/registration.test.ts@@ -0,0 +1,228 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ isPushSupported,+ registerServiceWorker,+ subscribeToPush,+ unsubscribeFromPush,+} from "../registration";++describe("isPushSupported", () => {+ const savedNavigator = globalThis.navigator;++ afterEach(() => {+ Object.defineProperty(globalThis, "navigator", {+ value: savedNavigator,+ configurable: true,+ });+ });++ it("returns true when all browser APIs exist", () => {+ Object.defineProperty(globalThis.navigator, "serviceWorker", {+ value: {},+ configurable: true,+ });+ Object.defineProperty(window, "PushManager", {+ value: class {},+ configurable: true,+ });+ Object.defineProperty(window, "Notification", {+ value: class {},+ configurable: true,+ });++ expect(isPushSupported()).toBe(true);+ });++ it("returns false when serviceWorker is missing", () => {+ const nav = {} as Navigator;+ Object.defineProperty(globalThis, "navigator", {+ value: nav,+ configurable: true,+ });+ Object.defineProperty(window, "PushManager", {+ value: class {},+ configurable: true,+ });+ Object.defineProperty(window, "Notification", {+ value: class {},+ configurable: true,+ });++ expect(isPushSupported()).toBe(false);+ });++ it("returns false when PushManager is missing", () => {+ Object.defineProperty(globalThis.navigator, "serviceWorker", {+ value: {},+ configurable: true,+ });+ // @ts-expect-error — intentionally removing PushManager+ delete window.PushManager;+ Object.defineProperty(window, "Notification", {+ value: class {},+ configurable: true,+ });++ expect(isPushSupported()).toBe(false);+ });++ it("returns false when Notification is missing", () => {+ Object.defineProperty(globalThis.navigator, "serviceWorker", {+ value: {},+ configurable: true,+ });+ Object.defineProperty(window, "PushManager", {+ value: class {},+ configurable: true,+ });+ // @ts-expect-error — intentionally removing Notification+ delete window.Notification;++ expect(isPushSupported()).toBe(false);+ });+});++describe("registerServiceWorker", () => {+ it("registers a service worker at /push-sw.js", async () => {+ const mockRegistration = { scope: "/" } as ServiceWorkerRegistration;+ Object.defineProperty(globalThis.navigator, "serviceWorker", {+ value: {+ register: vi.fn().mockResolvedValue(mockRegistration),+ },+ configurable: true,+ });++ const result = await registerServiceWorker();++ expect(navigator.serviceWorker.register).toHaveBeenCalledWith(+ "/push-sw.js",+ { scope: "/" },+ );+ expect(result).toBe(mockRegistration);+ });++ it("returns null when registration fails", async () => {+ Object.defineProperty(globalThis.navigator, "serviceWorker", {+ value: {+ register: vi.fn().mockRejectedValue(new Error("SW failed")),+ },+ configurable: true,+ });++ const result = await registerServiceWorker();++ expect(result).toBeNull();+ });++ it("returns null when serviceWorker is not in navigator", async () => {+ const nav = {} as Navigator;+ const original = globalThis.navigator;+ Object.defineProperty(globalThis, "navigator", {+ value: nav,+ configurable: true,+ });++ const result = await registerServiceWorker();++ expect(result).toBeNull();++ Object.defineProperty(globalThis, "navigator", {+ value: original,+ configurable: true,+ });+ });+});++describe("subscribeToPush", () => {+ it("returns existing subscription if one exists", async () => {+ const existingSub = { endpoint: "https://push.example.com" };+ const registration = {+ pushManager: {+ getSubscription: vi.fn().mockResolvedValue(existingSub),+ subscribe: vi.fn(),+ },+ } as unknown as ServiceWorkerRegistration;++ const result = await subscribeToPush(registration, "fake-vapid-key");++ expect(result).toBe(existingSub);+ expect(registration.pushManager.subscribe).not.toHaveBeenCalled();+ });++ it("creates new subscription when none exists", async () => {+ const newSub = { endpoint: "https://push.example.com/new" };+ const registration = {+ pushManager: {+ getSubscription: vi.fn().mockResolvedValue(null),+ subscribe: vi.fn().mockResolvedValue(newSub),+ },+ } as unknown as ServiceWorkerRegistration;++ // Valid base64url — decodes to 4 bytes (AAAA in base64url = 3 zero bytes)+ const vapidKey = "AAAA";++ const result = await subscribeToPush(registration, vapidKey);++ expect(result).toBe(newSub);+ expect(registration.pushManager.subscribe).toHaveBeenCalledWith({+ userVisibleOnly: true,+ applicationServerKey: expect.any(ArrayBuffer),+ });+ });++ it("returns null on subscribe failure", async () => {+ const registration = {+ pushManager: {+ getSubscription: vi.fn().mockResolvedValue(null),+ subscribe: vi.fn().mockRejectedValue(new Error("denied")),+ },+ } as unknown as ServiceWorkerRegistration;++ const result = await subscribeToPush(registration, "fake-vapid-key");++ expect(result).toBeNull();+ });+});++describe("unsubscribeFromPush", () => {+ it("unsubscribes existing subscription", async () => {+ const subscription = { unsubscribe: vi.fn().mockResolvedValue(true) };+ const registration = {+ pushManager: {+ getSubscription: vi.fn().mockResolvedValue(subscription),+ },+ } as unknown as ServiceWorkerRegistration;++ const result = await unsubscribeFromPush(registration);++ expect(result).toBe(true);+ expect(subscription.unsubscribe).toHaveBeenCalled();+ });++ it("returns true when no subscription exists", async () => {+ const registration = {+ pushManager: {+ getSubscription: vi.fn().mockResolvedValue(null),+ },+ } as unknown as ServiceWorkerRegistration;++ const result = await unsubscribeFromPush(registration);++ expect(result).toBe(true);+ });++ it("returns false when unsubscribe fails", async () => {+ const subscription = {+ unsubscribe: vi.fn().mockRejectedValue(new Error("failed")),+ };+ const registration = {+ pushManager: {+ getSubscription: vi.fn().mockResolvedValue(subscription),+ },+ } as unknown as ServiceWorkerRegistration;++ const result = await unsubscribeFromPush(registration);++ expect(result).toBe(false);+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/usePushNotifications.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/usePushNotifications.test.tsnew file mode 100644index 0000000000..ebf68e028a--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/usePushNotifications.test.ts@@ -0,0 +1,200 @@+import { renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { usePushNotifications } from "../usePushNotifications";++const mockUser = { id: "user-1", email: "[email protected]" };++vi.mock("@/lib/supabase/hooks/useSupabase", () => ({+ useSupabase: vi.fn(() => ({ user: mockUser })),+}));++const mockIsPushSupported = vi.fn(() => true);+const mockRegisterServiceWorker = vi.fn();+const mockSubscribeToPush = vi.fn();+const mockUnsubscribeFromPush = vi.fn();++vi.mock("../registration", () => ({+ isPushSupported: () => mockIsPushSupported(),+ registerServiceWorker: () => mockRegisterServiceWorker(),+ subscribeToPush: (...args: [unknown, unknown]) =>+ mockSubscribeToPush(...args),+ unsubscribeFromPush: (reg: unknown) => mockUnsubscribeFromPush(reg),+}));++const mockFetchVapidPublicKey = vi.fn();+const mockSendSubscriptionToServer = vi.fn();+const mockRemoveSubscriptionFromServer = vi.fn();++vi.mock("../api", () => ({+ fetchVapidPublicKey: () => mockFetchVapidPublicKey(),+ sendSubscriptionToServer: (sub: unknown) => mockSendSubscriptionToServer(sub),+ removeSubscriptionFromServer: (endpoint: string) =>+ mockRemoveSubscriptionFromServer(endpoint),+}));++describe("usePushNotifications", () => {+ const mockRegistration = {+ pushManager: {+ getSubscription: vi.fn(),+ },+ };+ const mockSubscription = { endpoint: "https://push.example.com/sub/1" };++ beforeEach(async () => {+ vi.clearAllMocks();+ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ vi.mocked(useSupabase).mockReturnValue({+ user: mockUser,+ } as ReturnType<typeof useSupabase>);+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "granted" },+ configurable: true,+ writable: true,+ });+ Object.defineProperty(navigator, "serviceWorker", {+ value: {+ register: vi.fn(),+ getRegistration: vi.fn().mockResolvedValue(mockRegistration),+ ready: Promise.resolve(mockRegistration),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ },+ configurable: true,+ });+ mockRegistration.pushManager.getSubscription = vi+ .fn()+ .mockResolvedValue(mockSubscription);+ mockIsPushSupported.mockReturnValue(true);+ mockRegisterServiceWorker.mockResolvedValue(mockRegistration);+ mockSubscribeToPush.mockResolvedValue(mockSubscription);+ mockFetchVapidPublicKey.mockResolvedValue("vapid-key-123");+ mockSendSubscriptionToServer.mockResolvedValue(true);+ mockRemoveSubscriptionFromServer.mockResolvedValue(true);+ mockUnsubscribeFromPush.mockResolvedValue(true);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("registers push subscription when all conditions are met", async () => {+ renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockSendSubscriptionToServer).toHaveBeenCalledWith(+ mockSubscription,+ );+ });+ });++ it("skips when push is not supported", async () => {+ mockIsPushSupported.mockReturnValue(false);++ renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockRegisterServiceWorker).not.toHaveBeenCalled();+ });+ });++ it("skips when Notification permission is not granted", async () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default" },+ configurable: true,+ writable: true,+ });++ renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockRegisterServiceWorker).not.toHaveBeenCalled();+ });+ });++ it("skips when no user is authenticated", async () => {+ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ vi.mocked(useSupabase).mockReturnValue({+ user: null,+ } as ReturnType<typeof useSupabase>);++ renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockIsPushSupported).not.toHaveBeenCalled();+ });+ });++ it("skips when service worker registration fails", async () => {+ mockRegisterServiceWorker.mockResolvedValue(null);++ renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockSubscribeToPush).not.toHaveBeenCalled();+ });+ });++ it("skips when VAPID key is not available", async () => {+ mockFetchVapidPublicKey.mockResolvedValue(null);+ delete process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;++ renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockSubscribeToPush).not.toHaveBeenCalled();+ });+ });++ it("skips when push subscription fails", async () => {+ mockSubscribeToPush.mockResolvedValue(null);++ renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockSendSubscriptionToServer).not.toHaveBeenCalled();+ });+ });++ it("listens for PUSH_SUBSCRIPTION_CHANGED messages", () => {+ renderHook(() => usePushNotifications());++ expect(navigator.serviceWorker.addEventListener).toHaveBeenCalledWith(+ "message",+ expect.any(Function),+ );+ });++ it("unsubscribes on logout after having been authenticated", async () => {+ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ const { rerender } = renderHook(() => usePushNotifications());++ await waitFor(() => {+ expect(mockSendSubscriptionToServer).toHaveBeenCalled();+ });++ vi.mocked(useSupabase).mockReturnValue({+ user: null,+ } as ReturnType<typeof useSupabase>);+ rerender();++ await waitFor(() => {+ expect(mockRemoveSubscriptionFromServer).toHaveBeenCalledWith(+ mockSubscription.endpoint,+ );+ });+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockRegistration);+ });++ it("does not call teardown when user is null from the start", async () => {+ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ vi.mocked(useSupabase).mockReturnValue({+ user: null,+ } as ReturnType<typeof useSupabase>);++ renderHook(() => usePushNotifications());++ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(mockRemoveSubscriptionFromServer).not.toHaveBeenCalled();+ expect(mockUnsubscribeFromPush).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportClientUrl.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportClientUrl.test.tsnew file mode 100644index 0000000000..4308fe4f8c--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportClientUrl.test.ts@@ -0,0 +1,95 @@+import { renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useReportClientUrl } from "../useReportClientUrl";++const mockPathname = vi.fn(() => "/copilot");+const mockSearchParams = vi.fn(() => new URLSearchParams("sessionId=A"));++vi.mock("next/navigation", () => ({+ usePathname: () => mockPathname(),+ useSearchParams: () => mockSearchParams(),+}));++const mockPostMessage = vi.fn();+const swListeners: Record<string, ((e?: unknown) => void) | undefined> = {};++beforeEach(() => {+ vi.clearAllMocks();+ mockPathname.mockReturnValue("/copilot");+ mockSearchParams.mockReturnValue(new URLSearchParams("sessionId=A"));+ Object.defineProperty(navigator, "serviceWorker", {+ value: {+ controller: { postMessage: mockPostMessage },+ addEventListener: (name: string, fn: () => void) => {+ swListeners[name] = fn;+ },+ removeEventListener: (name: string) => {+ swListeners[name] = undefined;+ },+ },+ configurable: true,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("useReportClientUrl", () => {+ it("posts the current URL on mount", () => {+ renderHook(() => useReportClientUrl());+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/copilot?sessionId=A",+ });+ });++ it("includes the pathname only when there are no query params", () => {+ mockSearchParams.mockReturnValue(new URLSearchParams());+ renderHook(() => useReportClientUrl());+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/copilot",+ });+ });++ it("re-posts when pathname changes", () => {+ const { rerender } = renderHook(() => useReportClientUrl());+ expect(mockPostMessage).toHaveBeenLastCalledWith({+ type: "CLIENT_URL",+ url: "/copilot?sessionId=A",+ });++ mockPathname.mockReturnValue("/library");+ mockSearchParams.mockReturnValue(new URLSearchParams());+ rerender();++ expect(mockPostMessage).toHaveBeenLastCalledWith({+ type: "CLIENT_URL",+ url: "/library",+ });+ });++ it("re-posts when the SW controller changes", async () => {+ renderHook(() => useReportClientUrl());+ mockPostMessage.mockClear();++ swListeners.controllerchange?.();++ await waitFor(() => {+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/copilot?sessionId=A",+ });+ });+ });++ it("does nothing when serviceWorker API is unavailable", () => {+ Object.defineProperty(navigator, "serviceWorker", {+ value: undefined,+ configurable: true,+ });+ renderHook(() => useReportClientUrl());+ expect(mockPostMessage).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportNotificationsEnabled.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportNotificationsEnabled.test.tsnew file mode 100644index 0000000000..1c2f62b6c5--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportNotificationsEnabled.test.ts@@ -0,0 +1,92 @@+import { renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useReportNotificationsEnabled } from "../useReportNotificationsEnabled";++const mockGetState = vi.fn(() => true);+vi.mock("@/app/(platform)/copilot/store", () => ({+ useCopilotUIStore: (+ selector: (s: { isNotificationsEnabled: boolean }) => unknown,+ ) => selector({ isNotificationsEnabled: mockGetState() }),+}));++const mockPostMessage = vi.fn();+const swListeners: Record<string, ((e?: unknown) => void) | undefined> = {};++beforeEach(() => {+ vi.clearAllMocks();+ Object.defineProperty(navigator, "serviceWorker", {+ value: {+ controller: { postMessage: mockPostMessage },+ addEventListener: (name: string, fn: () => void) => {+ swListeners[name] = fn;+ },+ removeEventListener: (name: string) => {+ swListeners[name] = undefined;+ },+ },+ configurable: true,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("useReportNotificationsEnabled", () => {+ it("posts the toggle value on mount when enabled", () => {+ mockGetState.mockReturnValue(true);+ renderHook(() => useReportNotificationsEnabled());+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: true,+ });+ });++ it("posts the toggle value on mount when disabled", () => {+ mockGetState.mockReturnValue(false);+ renderHook(() => useReportNotificationsEnabled());+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: false,+ });+ });++ it("re-posts when the toggle flips", () => {+ mockGetState.mockReturnValue(true);+ const { rerender } = renderHook(() => useReportNotificationsEnabled());+ expect(mockPostMessage).toHaveBeenLastCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: true,+ });++ mockGetState.mockReturnValue(false);+ rerender();++ expect(mockPostMessage).toHaveBeenLastCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: false,+ });+ });++ it("re-posts on SW controllerchange", () => {+ mockGetState.mockReturnValue(false);+ renderHook(() => useReportNotificationsEnabled());+ mockPostMessage.mockClear();++ swListeners.controllerchange?.();++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: false,+ });+ });++ it("does nothing when serviceWorker API is unavailable", () => {+ Object.defineProperty(navigator, "serviceWorker", {+ value: undefined,+ configurable: true,+ });+ renderHook(() => useReportNotificationsEnabled());+ expect(mockPostMessage).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/api.ts b/autogpt_platform/frontend/src/services/push-notifications/api.tsnew file mode 100644index 0000000000..99fdd5fddb--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/api.ts@@ -0,0 +1,50 @@+const PROXY_BASE = "/api/proxy/api/push";++export async function fetchVapidPublicKey(): Promise<string | null> {+ try {+ const response = await fetch(`${PROXY_BASE}/vapid-key`);+ if (!response.ok) return null;+ const data = await response.json();+ return data.public_key || null;+ } catch {+ return null;+ }+}++export async function sendSubscriptionToServer(+ subscription: PushSubscription,+): Promise<boolean> {+ const json = subscription.toJSON();+ try {+ const response = await fetch(`${PROXY_BASE}/subscribe`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ endpoint: json.endpoint,+ keys: {+ p256dh: json.keys?.p256dh ?? "",+ auth: json.keys?.auth ?? "",+ },+ user_agent: navigator.userAgent,+ }),+ });+ return response.ok;+ } catch {+ return false;+ }+}++export async function removeSubscriptionFromServer(+ endpoint: string,+): Promise<boolean> {+ try {+ const response = await fetch(`${PROXY_BASE}/unsubscribe`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ endpoint }),+ });+ return response.ok;+ } catch {+ return false;+ }+}diff --git a/autogpt_platform/frontend/src/services/push-notifications/helpers.ts b/autogpt_platform/frontend/src/services/push-notifications/helpers.tsnew file mode 100644index 0000000000..d8687466c1--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/helpers.ts@@ -0,0 +1,43 @@+import {+ fetchVapidPublicKey,+ removeSubscriptionFromServer,+ sendSubscriptionToServer,+} from "./api";+import {+ isPushSupported,+ registerServiceWorker,+ subscribeToPush,+ unsubscribeFromPush,+} from "./registration";++export async function setupPushSubscription(): Promise<boolean> {+ if (!isPushSupported()) return false;+ if (Notification.permission !== "granted") return false;++ const registration = await registerServiceWorker();+ if (!registration) return false;++ await navigator.serviceWorker.ready;++ const vapidKey =+ process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || (await fetchVapidPublicKey());+ if (!vapidKey) return false;++ const subscription = await subscribeToPush(registration, vapidKey);+ if (!subscription) return false;++ return sendSubscriptionToServer(subscription);+}++export async function teardownPushSubscription(): Promise<void> {+ if (!navigator.serviceWorker) return;+ const registration = await navigator.serviceWorker.getRegistration("/");+ if (!registration) return;+ const subscription = await registration.pushManager.getSubscription();+ if (!subscription) return;++ // Tell the backend first — if the row is deleted but the browser keeps the+ // subscription, future pushes 404 and get cleaned up anyway.+ await removeSubscriptionFromServer(subscription.endpoint);+ await unsubscribeFromPush(registration);+}diff --git a/autogpt_platform/frontend/src/services/push-notifications/registration.ts b/autogpt_platform/frontend/src/services/push-notifications/registration.tsnew file mode 100644index 0000000000..e493af9904--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/registration.ts@@ -0,0 +1,67 @@+const SW_PATH = "/push-sw.js";++/**+ * Convert a base64url VAPID key to a Uint8Array for the Push API.+ */+function urlBase64ToUint8Array(base64String: string): ArrayBuffer {+ const padding = "=".repeat((4 - (base64String.length % 4)) % 4);+ const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");+ const rawData = window.atob(base64);+ const arr = new Uint8Array(rawData.length);+ for (let i = 0; i < rawData.length; i++) {+ arr[i] = rawData.charCodeAt(i);+ }+ return arr.buffer as ArrayBuffer;+}++export function isPushSupported(): boolean {+ return (+ typeof window !== "undefined" &&+ "serviceWorker" in navigator &&+ "PushManager" in window &&+ "Notification" in window+ );+}++export async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {+ if (!("serviceWorker" in navigator)) return null;+ try {+ return await navigator.serviceWorker.register(SW_PATH, { scope: "/" });+ } catch (error) {+ console.error("Failed to register push service worker:", error);+ return null;+ }+}++export async function subscribeToPush(+ registration: ServiceWorkerRegistration,+ vapidPublicKey: string,+): Promise<PushSubscription | null> {+ try {+ const existing = await registration.pushManager.getSubscription();+ if (existing) return existing;++ return await registration.pushManager.subscribe({+ userVisibleOnly: true,+ applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),+ });+ } catch (error) {+ console.error("Failed to subscribe to push:", error);+ return null;+ }+}++export async function unsubscribeFromPush(+ registration: ServiceWorkerRegistration,+): Promise<boolean> {+ try {+ const subscription = await registration.pushManager.getSubscription();+ if (subscription) {+ return await subscription.unsubscribe();+ }+ return true;+ } catch (error) {+ console.error("Failed to unsubscribe from push:", error);+ return false;+ }+}diff --git a/autogpt_platform/frontend/src/services/push-notifications/types.ts b/autogpt_platform/frontend/src/services/push-notifications/types.tsnew file mode 100644index 0000000000..9848a6706a--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/types.ts@@ -0,0 +1,2 @@+/** Messages the service worker can post to page clients. */+export type PushSWMessage = { type: "PUSH_SUBSCRIPTION_CHANGED" };diff --git a/autogpt_platform/frontend/src/services/push-notifications/usePushNotifications.ts b/autogpt_platform/frontend/src/services/push-notifications/usePushNotifications.tsnew file mode 100644index 0000000000..599c40b37b--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/usePushNotifications.ts@@ -0,0 +1,65 @@+"use client";++import { useSupabase } from "@/lib/supabase/hooks/useSupabase";+import { useEffect, useRef, useState } from "react";+import { setupPushSubscription, teardownPushSubscription } from "./helpers";+import type { PushSWMessage } from "./types";++/**+ * Registers the push service worker and sends the subscription to the backend.+ * Should be mounted once at the platform layout level.+ *+ * Only activates when:+ * 1. The browser supports Push API + Service Workers+ * 2. Notification permission is already "granted" (requested by copilot flow)+ * 3. The user is authenticated+ *+ * On logout, unsubscribes both locally and on the backend so the previous+ * user doesn't keep receiving OS notifications.+ */+export function usePushNotifications() {+ const { user } = useSupabase();+ const registeredRef = useRef(false);+ const wasAuthedRef = useRef(false);+ const [renewCount, setRenewCount] = useState(0);++ useEffect(() => {+ if (typeof window === "undefined") return;++ if (user) {+ wasAuthedRef.current = true;+ if (registeredRef.current) return;+ setupPushSubscription()+ .then((sent) => {+ if (sent) registeredRef.current = true;+ })+ .catch((error) =>+ console.error("Push notification setup failed:", error),+ );+ return;+ }++ if (!wasAuthedRef.current) return;+ wasAuthedRef.current = false;+ registeredRef.current = false;+ teardownPushSubscription().catch((error) =>+ console.error("Push notification teardown failed:", error),+ );+ }, [user, renewCount]);++ useEffect(() => {+ if (typeof window === "undefined") return;+ if (!("serviceWorker" in navigator)) return;++ function handleMessage(event: MessageEvent<PushSWMessage>) {+ if (event.data?.type === "PUSH_SUBSCRIPTION_CHANGED") {+ registeredRef.current = false;+ setRenewCount((c) => c + 1);+ }+ }++ navigator.serviceWorker.addEventListener("message", handleMessage);+ return () =>+ navigator.serviceWorker.removeEventListener("message", handleMessage);+ }, []);+}diff --git a/autogpt_platform/frontend/src/services/push-notifications/useReportClientUrl.ts b/autogpt_platform/frontend/src/services/push-notifications/useReportClientUrl.tsnew file mode 100644index 0000000000..dad691c816--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/useReportClientUrl.ts@@ -0,0 +1,39 @@+"use client";++import { usePathname, useSearchParams } from "next/navigation";+import { useEffect } from "react";++/**+ * Tells the push service worker the current page URL on every navigation.+ *+ * Why: Chrome's `WindowClient.url` doesn't update for Next.js client-side+ * navigation (history.pushState), so the SW's suppression check sees stale+ * URLs and wrongly suppresses notifications when the user has navigated+ * away from the completed session's page.+ */+export function useReportClientUrl() {+ const pathname = usePathname();+ const searchParams = useSearchParams();++ useEffect(() => {+ if (typeof navigator === "undefined") return;+ if (!navigator.serviceWorker) return;+ const query = searchParams?.toString();+ const url = pathname + (query ? `?${query}` : "");++ function send() {+ navigator.serviceWorker.controller?.postMessage({+ type: "CLIENT_URL",+ url,+ });+ }++ send();+ // Also send when control of the page transfers to a new SW (first install+ // after subscribe, or after an update). Otherwise the very first navigation+ // after registration races against controller availability.+ navigator.serviceWorker.addEventListener("controllerchange", send);+ return () =>+ navigator.serviceWorker.removeEventListener("controllerchange", send);+ }, [pathname, searchParams]);+}diff --git a/autogpt_platform/frontend/src/services/push-notifications/useReportNotificationsEnabled.ts b/autogpt_platform/frontend/src/services/push-notifications/useReportNotificationsEnabled.tsnew file mode 100644index 0000000000..049de03fb9--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/useReportNotificationsEnabled.ts@@ -0,0 +1,33 @@+"use client";++import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { useEffect } from "react";++/**+ * Forwards the user's notification toggle to the push service worker so that+ * disabling notifications also suppresses OS-level pushes (which arrive+ * directly via FCM and bypass any in-page gating).+ *+ * SW state resets on every restart, so the hook also re-sends on mount and+ * on `controllerchange` to re-sync after updates/installs.+ */+export function useReportNotificationsEnabled() {+ const isEnabled = useCopilotUIStore((s) => s.isNotificationsEnabled);++ useEffect(() => {+ if (typeof navigator === "undefined") return;+ if (!navigator.serviceWorker) return;++ function send() {+ navigator.serviceWorker.controller?.postMessage({+ type: "NOTIFICATIONS_ENABLED",+ value: isEnabled,+ });+ }++ send();+ navigator.serviceWorker.addEventListener("controllerchange", send);+ return () =>+ navigator.serviceWorker.removeEventListener("controllerchange", send);+ }, [isEnabled]);+}diff --git a/autogpt_platform/frontend/src/services/storage/local-storage.ts b/autogpt_platform/frontend/src/services/storage/local-storage.tsindex b5c0392ecd..29762fa680 100644--- a/autogpt_platform/frontend/src/services/storage/local-storage.ts+++ b/autogpt_platform/frontend/src/services/storage/local-storage.ts@@ -19,6 +19,7 @@ export enum Key {COPILOT_MODE = "copilot-mode",COPILOT_MODEL = "copilot-model",COPILOT_COMPLETED_SESSIONS = "copilot-completed-sessions",+ PUSH_SUBSCRIPTION_REGISTERED = "push-subscription-registered",COPILOT_DRY_RUN = "copilot-dry-run",}