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.
fix(platform): stop sending a previous account's notifications after switching accounts (#15567)
Krzysztof Czerwinskic31ec68f7d3e
diff --git a/autogpt_platform/backend/backend/data/push_subscription.py b/autogpt_platform/backend/backend/data/push_subscription.pyindex 10c509d18d..3fc318368c 100644--- a/autogpt_platform/backend/backend/data/push_subscription.py+++ b/autogpt_platform/backend/backend/data/push_subscription.py@@ -3,9 +3,11 @@import loggingfrom datetime import datetime, timezone+from prisma.errors import RecordNotFoundError, UniqueViolationErrorfrom prisma.models import PushSubscriptionfrom pydantic import BaseModel+from backend.data.db import transactionfrom backend.util.request import parse_url, validate_url_hostlogger = logging.getLogger(__name__)@@ -86,35 +88,72 @@ async def upsert_push_subscription(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,+ try:+ return await _subscribe(user_id, endpoint, p256dh, auth, user_agent)+ except (UniqueViolationError, RecordNotFoundError):+ # Prisma runs the upsert as a read then a write, and a concurrent write+ # changed the endpoint's row in between: another subscribe created it,+ # or the failed-push cleanup deleted it. The transaction rolled back,+ # so one more run sees the row as it is now.+ return await _subscribe(user_id, endpoint, p256dh, auth, user_agent)+++async def _subscribe(+ user_id: str,+ endpoint: str,+ p256dh: str,+ auth: str,+ user_agent: str | None,+) -> PushSubscription:+ """Check the cap, make room if needed and claim the endpoint, all or nothing.++ An endpoint belongs to one browser profile (``endpoint`` is unique), so+ whoever subscribed it last owns it. Signing into a second account on the+ same browser then stops the first account's notifications arriving there.+ """+ async with transaction() as tx:+ subscriptions = PushSubscription.prisma(tx)+ existing = await subscriptions.find_many(where={"userId": user_id})+ # The cap stops one account registering unbounded endpoints to amplify+ # outbound pushes. Refreshing its own endpoint is always fine. A new+ # endpoint past the cap is refused, but taking over one another+ # account registered (the same browser after switching accounts) is+ # not: refusing would leave that account's notifications arriving on+ # this browser. That makes room instead, dropping the device most+ # likely gone: the one failing most, else the least recently+ # refreshed. Failures bump updatedAt too, so it only measures a+ # refresh among rows that aren't failing (a subscribe resets+ # failCount).+ if len(existing) >= MAX_SUBSCRIPTIONS_PER_USER and not any(+ row.endpoint == endpoint for row in existing+ ):+ if await subscriptions.find_unique(where={"endpoint": endpoint}) is None:+ raise ValueError(+ f"Subscription limit of {MAX_SUBSCRIPTIONS_PER_USER} "+ "per user reached"+ )+ stalest = min(existing, key=lambda row: (-row.failCount, row.updatedAt))+ await subscriptions.delete_many(where={"id": stalest.id})+ return await subscriptions.upsert(+ where={"endpoint": endpoint},+ data={+ "create": {+ "userId": user_id,+ "endpoint": endpoint,+ "p256dh": p256dh,+ "auth": auth,+ "userAgent": user_agent,+ },+ "update": {+ "User": {"connect": {"id": user_id}},+ "p256dh": p256dh,+ "auth": auth,+ "userAgent": user_agent,+ "failCount": 0,+ "lastFailedAt": None,+ },},- },- )+ )async def get_user_push_subscriptions(user_id: str) -> list[PushSubscriptionDTO]:diff --git a/autogpt_platform/backend/backend/data/push_subscription_test.py b/autogpt_platform/backend/backend/data/push_subscription_test.pyindex f41085465a..d9a99f4088 100644--- a/autogpt_platform/backend/backend/data/push_subscription_test.py+++ b/autogpt_platform/backend/backend/data/push_subscription_test.py@@ -1,9 +1,11 @@"""Tests for Web Push subscription CRUD operations."""-from datetime import datetime-from unittest.mock import AsyncMock, MagicMock+from contextlib import asynccontextmanager+from datetime import datetime, timezone+from unittest.mock import AsyncMock, MagicMock, callimport pytest+from prisma.errors import RecordNotFoundError, UniqueViolationErrorfrom backend.data import push_subscription@@ -14,9 +16,17 @@ def mock_prisma(mocker):mock_client = MagicMock()mock_client.upsert = AsyncMock()mock_client.find_many = AsyncMock(return_value=[])+ mock_client.find_unique = AsyncMock(return_value=None)mock_client.delete_many = AsyncMock()mock_client.update_many = AsyncMock()- mocker.patch(+ mock_client.tx = MagicMock(name="tx")++ @asynccontextmanager+ async def fake_transaction():+ yield mock_client.tx++ mocker.patch("backend.data.push_subscription.transaction", fake_transaction)+ mock_client.model_prisma = mocker.patch("backend.data.push_subscription.PushSubscription.prisma",return_value=mock_client,)@@ -39,10 +49,7 @@ class TestUpsertPushSubscription:mock_prisma.upsert.assert_awaited_once()call_kwargs = mock_prisma.upsert.call_args.kwargsassert call_kwargs["where"] == {- "userId_endpoint": {- "userId": "user-1",- "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1",- }+ "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1"}assert call_kwargs["data"]["create"] == {"userId": "user-1",@@ -52,6 +59,7 @@ class TestUpsertPushSubscription:"userAgent": "Mozilla/5.0",}assert call_kwargs["data"]["update"] == {+ "User": {"connect": {"id": "user-1"}},"p256dh": "test-p256dh","auth": "test-auth","userAgent": "Mozilla/5.0",@@ -139,6 +147,179 @@ class TestUpsertPushSubscription:mock_prisma.upsert.assert_awaited_once()+ @pytest.mark.asyncio+ async def test_takes_over_another_users_endpoint_at_the_cap(self, mock_prisma):+ # Refusing the takeover would keep the previous account's+ # notifications arriving on this browser, so the user's least+ # recently refreshed subscription makes room and they stay at the cap.+ existing = [+ MagicMock(+ id=f"row-{i}",+ endpoint=f"https://fcm.googleapis.com/fcm/send/sub/{i}",+ updatedAt=datetime(2026, 10, 1 + i, tzinfo=timezone.utc),+ failCount=0,+ )+ for i in range(push_subscription.MAX_SUBSCRIPTIONS_PER_USER)+ ]+ existing[0], existing[5] = existing[5], existing[0]+ mock_prisma.find_many.return_value = existing+ mock_prisma.find_unique.return_value = MagicMock(userId="user-1")+ writes: list[str] = []+ mock_prisma.delete_many.side_effect = lambda **_: writes.append("delete")+ mock_prisma.upsert.side_effect = lambda **_: writes.append("upsert")++ await push_subscription.upsert_push_subscription(+ user_id="user-2",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/TAKEN",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ mock_prisma.find_unique.assert_awaited_once_with(+ where={"endpoint": "https://fcm.googleapis.com/fcm/send/sub/TAKEN"}+ )+ # Exactly one of the user's rows, the stalest, goes before the one+ # taken over is added, so they end at the cap rather than one past it.+ mock_prisma.delete_many.assert_awaited_once_with(where={"id": "row-0"})+ assert writes == ["delete", "upsert"]++ @pytest.mark.asyncio+ async def test_takeover_at_the_cap_drops_a_failing_device_first(self, mock_prisma):+ # A failing push bumps updatedAt, so a dying device looks freshly+ # refreshed; it must still go before a healthy idle one.+ existing = [+ MagicMock(+ id=f"row-{i}",+ endpoint=f"https://fcm.googleapis.com/fcm/send/sub/{i}",+ updatedAt=datetime(2026, 10, 1 + i, tzinfo=timezone.utc),+ failCount=0,+ )+ for i in range(push_subscription.MAX_SUBSCRIPTIONS_PER_USER)+ ]+ existing[-1].failCount = 3+ mock_prisma.find_many.return_value = existing+ mock_prisma.find_unique.return_value = MagicMock(userId="user-1")+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-2",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/TAKEN",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ mock_prisma.delete_many.assert_awaited_once_with(+ where={"id": f"row-{push_subscription.MAX_SUBSCRIPTIONS_PER_USER - 1}"}+ )++ @pytest.mark.asyncio+ async def test_cap_check_eviction_and_claim_share_one_transaction(+ self, mock_prisma+ ):+ # A claim that fails after the eviction must roll the eviction back,+ # or the account loses a registration for nothing.+ mock_prisma.find_many.return_value = [+ MagicMock(+ id=f"row-{i}",+ endpoint=f"https://fcm.googleapis.com/fcm/send/sub/{i}",+ updatedAt=datetime(2026, 10, 1 + i, tzinfo=timezone.utc),+ failCount=0,+ )+ for i in range(push_subscription.MAX_SUBSCRIPTIONS_PER_USER)+ ]+ mock_prisma.find_unique.return_value = MagicMock(userId="user-1")+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-2",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/TAKEN",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ assert mock_prisma.model_prisma.call_args_list == [call(mock_prisma.tx)]+ mock_prisma.delete_many.assert_awaited_once()+ mock_prisma.upsert.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_retries_once_when_the_row_vanished_mid_upsert(self, mock_prisma):+ # The failed-push cleanup can delete the row between Prisma's read+ # and write; the second run creates it.+ expected = MagicMock()+ mock_prisma.upsert.side_effect = [+ RecordNotFoundError(MagicMock()),+ expected,+ ]++ result = await push_subscription.upsert_push_subscription(+ user_id="user-2",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ assert result is expected+ assert mock_prisma.upsert.await_count == 2++ @pytest.mark.asyncio+ async def test_refreshing_own_endpoint_at_the_cap_drops_nothing(self, mock_prisma):+ mock_prisma.find_many.return_value = [+ MagicMock(endpoint=f"https://fcm.googleapis.com/fcm/send/sub/{i}")+ for i in range(push_subscription.MAX_SUBSCRIPTIONS_PER_USER)+ ]+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-1",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/3",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ mock_prisma.find_unique.assert_not_awaited()+ mock_prisma.delete_many.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_moves_the_endpoint_to_the_subscribing_user(self, mock_prisma):+ # A browser has one push endpoint: after switching accounts on it, the+ # previous account must stop receiving pushes there. The row is keyed+ # by endpoint alone, so the upsert hands it to the new user.+ mock_prisma.upsert.return_value = MagicMock()++ await push_subscription.upsert_push_subscription(+ user_id="user-2",+ 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["where"] == {+ "endpoint": "https://fcm.googleapis.com/fcm/send/sub/1"+ }+ assert call_kwargs["data"]["update"]["User"] == {"connect": {"id": "user-2"}}+ mock_prisma.delete_many.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_retries_once_when_a_concurrent_subscribe_created_the_row(+ self, mock_prisma+ ):+ expected = MagicMock()+ mock_prisma.upsert.side_effect = [+ UniqueViolationError(MagicMock()),+ expected,+ ]++ result = await push_subscription.upsert_push_subscription(+ user_id="user-2",+ endpoint="https://fcm.googleapis.com/fcm/send/sub/1",+ p256dh="test-p256dh",+ auth="test-auth",+ )++ assert result is expected+ assert mock_prisma.upsert.await_count == 2+class TestGetUserPushSubscriptions:@pytest.mark.asynciodiff --git a/autogpt_platform/backend/migrations/20261019120000_push_subscription_unique_endpoint/migration.sql b/autogpt_platform/backend/migrations/20261019120000_push_subscription_unique_endpoint/migration.sqlnew file mode 100644index 0000000000..11b9272739--- /dev/null+++ b/autogpt_platform/backend/migrations/20261019120000_push_subscription_unique_endpoint/migration.sql@@ -0,0 +1,16 @@+-- A browser has one push endpoint, so it can only belong to one account.+-- Rows were unique per (userId, endpoint), which let the same browser be+-- registered to several accounts after switching between them; keep the most+-- recently updated row per endpoint (the account signed in there last).+DELETE FROM "PushSubscription" AS older+USING "PushSubscription" AS newer+WHERE older."endpoint" = newer."endpoint"+ AND (+ older."updatedAt" < newer."updatedAt"+ OR (older."updatedAt" = newer."updatedAt" AND older."id" < newer."id")+ );++-- CreateIndex+-- "PushSubscription_userId_endpoint_key" stays: backend pods still running+-- the previous release upsert on it during a rolling deploy.+CREATE UNIQUE INDEX "PushSubscription_endpoint_key" ON "PushSubscription"("endpoint");diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex ca3d7b5d31..40e0d0d09a 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -1108,7 +1108,9 @@ model PushSubscription {userId StringUser User @relation(fields: [userId], references: [id], onDelete: Cascade)- endpoint String+ // An endpoint belongs to one browser profile, so to one account at a time:+ // subscribing moves it to whoever signed in last.+ endpoint String @uniquep256dh Stringauth String@@ -1116,6 +1118,10 @@ model PushSubscription {failCount Int @default(0)lastFailedAt DateTime?+ // Implied by the unique endpoint and kept only so a backend release that+ // still upserts on (userId, endpoint) keeps working through a rolling+ // deploy; it also serves per-user lookups. Safe to drop once no deployed+ // release upserts on it.@@unique([userId, endpoint])}diff --git a/autogpt_platform/frontend/src/lib/auth/hooks/__tests__/useAuthStore.test.ts b/autogpt_platform/frontend/src/lib/auth/hooks/__tests__/useAuthStore.test.tsindex e778b3b54e..0dc72a9efe 100644--- a/autogpt_platform/frontend/src/lib/auth/hooks/__tests__/useAuthStore.test.ts+++ b/autogpt_platform/frontend/src/lib/auth/hooks/__tests__/useAuthStore.test.ts@@ -14,6 +14,19 @@ vi.mock("../../helpers", () => ({setWebSocketDisconnectIntent: vi.fn(),setupSessionEventListeners: vi.fn(() => ({ cleanup: vi.fn() })),}));+vi.mock("@/services/push-notifications/helpers", () => ({+ teardownPushSubscriptionBeforeLogout: vi.fn(),+}));+const { mockClearAllCompletedSessions } = vi.hoisted(() => ({+ mockClearAllCompletedSessions: vi.fn(),+}));+vi.mock("@/app/(platform)/copilot/store", () => ({+ useCopilotUIStore: {+ getState: () => ({+ clearAllCompletedSessions: mockClearAllCompletedSessions,+ }),+ },+}));vi.mock("../helpers", () => ({fetchUser: vi.fn(),handleStorageEvent: vi.fn(),@@ -21,6 +34,8 @@ vi.mock("../helpers", () => ({validateSession: vi.fn(),}));+import { teardownPushSubscriptionBeforeLogout } from "@/services/push-notifications/helpers";+import { serverLogout } from "../../actions";import type { User } from "../../types";import { validateSession as validateSessionHelper } from "../helpers";import { useAuthStore } from "../useAuthStore";@@ -178,3 +193,55 @@ describe("useAuthStore.validateSession", () => {expect(router.push).not.toHaveBeenCalled();});});++describe("useAuthStore.logOut", () => {+ afterEach(async () => {+ useAuthStore.setState({ user: null, hasLoadedUser: false });+ await vi.dynamicImportSettled();+ vi.clearAllMocks();+ });++ it("waits for this browser's push subscription to go before the server signs out", async () => {+ let finishTeardown: () => void = () => {};+ vi.mocked(teardownPushSubscriptionBeforeLogout).mockReturnValue(+ new Promise<void>((resolve) => (finishTeardown = resolve)),+ );+ useAuthStore.setState({ user: { id: "user-1" } as User });++ const loggingOut = useAuthStore.getState().logOut();+ await Promise.resolve();++ expect(teardownPushSubscriptionBeforeLogout).toHaveBeenCalledOnce();+ expect(serverLogout).not.toHaveBeenCalled();++ finishTeardown();+ await loggingOut;++ expect(serverLogout).toHaveBeenCalledOnce();+ });+});++describe("useAuthStore account change", () => {+ afterEach(async () => {+ useAuthStore.setState({ user: null });+ await vi.dynamicImportSettled();+ vi.clearAllMocks();+ });++ it("clears the finished-chats list when the user signs out", async () => {+ useAuthStore.setState({ user: { id: "user-1" } as User });+ useAuthStore.setState({ user: null });++ await vi.waitFor(() =>+ expect(mockClearAllCompletedSessions).toHaveBeenCalledOnce(),+ );+ });++ it("keeps the finished-chats list when the same user is refreshed", async () => {+ useAuthStore.setState({ user: { id: "user-1" } as User });+ useAuthStore.setState({ user: { id: "user-1" } as User });+ await vi.dynamicImportSettled();++ expect(mockClearAllCompletedSessions).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.ts b/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.tsindex eabb532c4c..fc4acb5877 100644--- a/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.ts+++ b/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.ts@@ -2,6 +2,7 @@import type BackendAPI from "@/lib/autogpt-server-api/client";import { resetAnalyticsIdentity } from "@/services/analytics/reset-identity";+import { teardownPushSubscriptionBeforeLogout } from "@/services/push-notifications/helpers";import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";import { create } from "zustand";import { serverLogout, type ServerLogoutOptions } from "../actions";@@ -132,6 +133,8 @@ export const useAuthStore = create<AuthStoreState>((set, get) => {const api = params?.api ?? get().apiRef;const options = params?.options ?? {};+ await teardownPushSubscriptionBeforeLogout();+setWebSocketDisconnectIntent();if (api) {@@ -297,5 +300,17 @@ export const useAuthStore = create<AuthStoreState>((set, get) => {useAuthStore.subscribe((state, previousState) => {if (previousState.user && previousState.user.id !== state.user?.id) {resetAnalyticsIdentity();+ clearCopilotCompletedSessions();}});++// Loaded lazily: the copilot store pulls in React hooks the auth store+// otherwise has no reason to load.+function clearCopilotCompletedSessions() {+ if (typeof window === "undefined") return;+ import("@/app/(platform)/copilot/store")+ .then(({ useCopilotUIStore }) =>+ useCopilotUIStore.getState().clearAllCompletedSessions(),+ )+ .catch(() => {});+}diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/PushNotificationProvider.test.tsx b/autogpt_platform/frontend/src/services/push-notifications/__tests__/PushNotificationProvider.test.tsxindex bff0694d93..1096a3e3fa 100644--- a/autogpt_platform/frontend/src/services/push-notifications/__tests__/PushNotificationProvider.test.tsx+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/PushNotificationProvider.test.tsx@@ -52,7 +52,7 @@ vi.mock("../registration", () => ({registerServiceWorker: () => mockRegisterServiceWorker(),subscribeToPush: (...args: [unknown, unknown]) =>mockSubscribeToPush(...args),- unsubscribeFromPush: (reg: unknown) => mockUnsubscribeFromPush(reg),+ unsubscribeFromPush: (sub: unknown) => mockUnsubscribeFromPush(sub),}));const mockFetchVapidPublicKey = vi.fn();@@ -333,7 +333,7 @@ describe("PushNotificationProvider", () => {mockSubscription.endpoint,);});- expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockRegistration);+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockSubscription);});it("does not call teardown when user is null from the start", async () => {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.tsindex 1ab70f0460..4a145aff19 100644--- a/autogpt_platform/frontend/src/services/push-notifications/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/helpers.test.ts@@ -1,5 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { setupPushSubscription, teardownPushSubscription } from "../helpers";+import {+ setupPushSubscription,+ teardownPushSubscription,+ teardownPushSubscriptionBeforeLogout,+} from "../helpers";const mockIsPushSupported = vi.fn(() => true);const mockRegisterServiceWorker = vi.fn();@@ -11,7 +15,7 @@ vi.mock("../registration", () => ({registerServiceWorker: () => mockRegisterServiceWorker(),subscribeToPush: (...args: [unknown, unknown]) =>mockSubscribeToPush(...args),- unsubscribeFromPush: (reg: unknown) => mockUnsubscribeFromPush(reg),+ unsubscribeFromPush: (sub: unknown) => mockUnsubscribeFromPush(sub),}));const mockFetchVapidPublicKey = vi.fn();@@ -124,7 +128,7 @@ describe("teardownPushSubscription", () => {expect(mockRemoveSubscriptionFromServer).toHaveBeenCalledWith(mockSubscription.endpoint,);- expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockRegistration);+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockSubscription);});it("no-ops when serviceWorker is unavailable", async () => {@@ -158,3 +162,125 @@ describe("teardownPushSubscription", () => {expect(mockUnsubscribeFromPush).not.toHaveBeenCalled();});});++describe("teardownPushSubscriptionBeforeLogout", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("removes the subscription from the server and the browser", async () => {+ await teardownPushSubscriptionBeforeLogout();+ expect(mockRemoveSubscriptionFromServer).toHaveBeenCalledWith(+ mockSubscription.endpoint,+ );+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockSubscription);+ });++ it("unsubscribes the browser without waiting for the server", async () => {+ mockRemoveSubscriptionFromServer.mockReturnValue(new Promise(() => {}));++ void teardownPushSubscriptionBeforeLogout();++ await vi.waitFor(() =>+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockSubscription),+ );+ });++ it("never unsubscribes the next account's subscription after timing out", async () => {+ vi.useFakeTimers();+ let answerServer: (ok: boolean) => void = () => {};+ mockRemoveSubscriptionFromServer.mockReturnValue(+ new Promise<boolean>((resolve) => (answerServer = resolve)),+ );++ await Promise.all([+ teardownPushSubscriptionBeforeLogout(),+ vi.advanceTimersByTimeAsync(5_000),+ ]);+ const nextAccountSubscription = {+ endpoint: "https://push.example.com/sub/2",+ };+ mockRegistration.pushManager.getSubscription = vi+ .fn()+ .mockResolvedValue(nextAccountSubscription);+ answerServer(true);+ await vi.advanceTimersByTimeAsync(0);++ expect(mockUnsubscribeFromPush.mock.calls).toEqual([[mockSubscription]]);+ });++ it("does not hold up logout when the server never answers", async () => {+ vi.useFakeTimers();+ mockRemoveSubscriptionFromServer.mockReturnValue(new Promise(() => {}));++ const done = vi.fn();+ void teardownPushSubscriptionBeforeLogout().then(done);+ await vi.advanceTimersByTimeAsync(5_000);++ expect(done).toHaveBeenCalled();+ });++ it("does not throw when tearing down fails", async () => {+ mockRemoveSubscriptionFromServer.mockRejectedValue(new Error("offline"));+ const consoleError = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});++ await expect(+ teardownPushSubscriptionBeforeLogout(),+ ).resolves.toBeUndefined();++ consoleError.mockRestore();+ });+});++describe("push subscription lock across tabs", () => {+ afterEach(() => {+ Object.defineProperty(navigator, "locks", {+ value: undefined,+ configurable: true,+ });+ });++ // A first-come, first-served lock like the browser's, shared by "tabs"+ // that are just concurrent calls here.+ function installSerialLock() {+ let tail: Promise<unknown> = Promise.resolve();+ const request = vi.fn(+ (+ _name: string,+ _options: unknown,+ action: () => Promise<unknown>,+ ): Promise<unknown> => {+ const run = tail.then(action);+ tail = run.catch(() => undefined);+ return run;+ },+ );+ Object.defineProperty(navigator, "locks", {+ value: { request },+ configurable: true,+ });+ }++ it("makes another tab's subscribe wait until this tab has unsubscribed", async () => {+ installSerialLock();+ let finishUnsubscribe: (ok: boolean) => void = () => {};+ mockUnsubscribeFromPush.mockReturnValue(+ new Promise<boolean>((resolve) => (finishUnsubscribe = resolve)),+ );++ const tearingDown = teardownPushSubscription();+ const settingUp = setupPushSubscription();+ await vi.waitFor(() =>+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockSubscription),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(mockSubscribeToPush).not.toHaveBeenCalled();++ finishUnsubscribe(true);+ await Promise.all([tearingDown, settingUp]);++ expect(mockSubscribeToPush).toHaveBeenCalledOnce();+ });+});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.tsindex 212bbc0759..3218d2011b 100644--- a/autogpt_platform/frontend/src/services/push-notifications/__tests__/registration.test.ts+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/registration.test.ts@@ -185,44 +185,30 @@ describe("subscribeToPush", () => {});describe("unsubscribeFromPush", () => {- it("unsubscribes existing subscription", async () => {+ it("unsubscribes the given 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);+ const result = await unsubscribeFromPush(+ subscription as unknown as PushSubscription,+ );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 consoleError = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});- const result = await unsubscribeFromPush(registration);+ const result = await unsubscribeFromPush(+ subscription as unknown as PushSubscription,+ );expect(result).toBe(false);+ consoleError.mockRestore();});});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/subscription-lock.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/subscription-lock.test.tsnew file mode 100644index 0000000000..43ced30c9d--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/subscription-lock.test.ts@@ -0,0 +1,100 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { withPushSubscriptionLock } from "../subscription-lock";++afterEach(() => {+ Object.defineProperty(navigator, "locks", {+ value: undefined,+ configurable: true,+ });+});++describe("withPushSubscriptionLock", () => {+ it("runs the action under the browser-wide push subscription lock", async () => {+ const request = vi.fn(+ (_name: string, _options: unknown, action: () => Promise<string>) =>+ action(),+ );+ Object.defineProperty(navigator, "locks", {+ value: { request },+ configurable: true,+ });++ await expect(withPushSubscriptionLock(async () => "done")).resolves.toBe(+ "done",+ );+ expect(request).toHaveBeenCalledWith(+ "autogpt-push-subscription",+ expect.anything(),+ expect.any(Function),+ );+ });++ it("runs the action directly where Web Locks are missing", async () => {+ await expect(withPushSubscriptionLock(async () => "done")).resolves.toBe(+ "done",+ );+ });+});++describe("withPushSubscriptionLock with a wait limit", () => {+ afterEach(() => {+ vi.useRealTimers();+ Object.defineProperty(navigator, "locks", {+ value: undefined,+ configurable: true,+ });+ });++ // Another tab holds the lock and never lets go; the request only ends+ // when its signal aborts, as the browser's does.+ function installHeldLock() {+ const request = vi.fn(+ (_name: string, options: { signal?: AbortSignal }) =>+ new Promise((_resolve, reject) => {+ options.signal?.addEventListener("abort", () =>+ reject(new DOMException("aborted", "AbortError")),+ );+ }),+ );+ Object.defineProperty(navigator, "locks", {+ value: { request },+ configurable: true,+ });+ }++ it("runs the action unlocked once the wait runs out", async () => {+ vi.useFakeTimers();+ installHeldLock();+ const action = vi.fn(async () => "done");++ const running = withPushSubscriptionLock(action, { maxWaitMs: 2_000 });+ await vi.advanceTimersByTimeAsync(1_999);+ expect(action).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(1);+ await expect(running).resolves.toBe("done");+ expect(action).toHaveBeenCalledOnce();+ });++ it("runs the action once under the lock when it is granted in time", async () => {+ vi.useFakeTimers();+ const request = vi.fn(+ (_name: string, _options: unknown, action: () => Promise<unknown>) =>+ action(),+ );+ Object.defineProperty(navigator, "locks", {+ value: { request },+ configurable: true,+ });+ const action = vi.fn(async () => {+ await new Promise((resolve) => setTimeout(resolve, 5_000));+ return "done";+ });++ const running = withPushSubscriptionLock(action, { maxWaitMs: 2_000 });+ await vi.advanceTimersByTimeAsync(5_000);++ await expect(running).resolves.toBe("done");+ expect(action).toHaveBeenCalledOnce();+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/helpers.ts b/autogpt_platform/frontend/src/services/push-notifications/helpers.tsindex d8687466c1..2330f8b5f2 100644--- a/autogpt_platform/frontend/src/services/push-notifications/helpers.ts+++ b/autogpt_platform/frontend/src/services/push-notifications/helpers.ts@@ -9,6 +9,10 @@ import {subscribeToPush,unsubscribeFromPush,} from "./registration";+import { withPushSubscriptionLock } from "./subscription-lock";++const LOGOUT_TEARDOWN_TIMEOUT_MS = 3_000;+const TEARDOWN_LOCK_WAIT_MS = 2_000;export async function setupPushSubscription(): Promise<boolean> {if (!isPushSupported()) return false;@@ -23,7 +27,9 @@ export async function setupPushSubscription(): Promise<boolean> {process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || (await fetchVapidPublicKey());if (!vapidKey) return false;- const subscription = await subscribeToPush(registration, vapidKey);+ const subscription = await withPushSubscriptionLock(() =>+ subscribeToPush(registration, vapidKey),+ );if (!subscription) return false;return sendSubscriptionToServer(subscription);@@ -33,11 +39,41 @@ 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;+ // The server call starts at once but runs outside the lock: only the+ // browser side has to finish before another tab may subscribe. Unsubscribe+ // the subscription read here, never a later one, so a slow server can't+ // leave this browser subscribed or touch the next account's subscription.+ // A row the server misses points at a dead endpoint and is dropped on the+ // next send.+ let serverRemoval: Promise<boolean> | undefined;+ await withPushSubscriptionLock(+ async () => {+ const subscription = await registration.pushManager.getSubscription();+ if (!subscription) return;+ serverRemoval = removeSubscriptionFromServer(subscription.endpoint);+ await unsubscribeFromPush(subscription);+ },+ // Inside the logout bound, so a tab stuck holding the lock can't make+ // logout finish before this browser is unsubscribed.+ { maxWaitMs: TEARDOWN_LOCK_WAIT_MS },+ );+ await serverRemoval;+}- // 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);+/**+ * Remove this browser's push subscription while the session is still valid.+ * The `/logout` page sits outside the platform layout, so the provider's own+ * teardown never sees the user turn null; without this the next account to+ * sign in here keeps receiving the previous account's notifications. Bounded+ * so a slow or offline network never blocks the logout itself.+ */+export async function teardownPushSubscriptionBeforeLogout(): Promise<void> {+ await Promise.race([+ teardownPushSubscription().catch((error) =>+ console.error("Push notification teardown failed:", error),+ ),+ new Promise<void>((resolve) =>+ setTimeout(resolve, LOGOUT_TEARDOWN_TIMEOUT_MS),+ ),+ ]);}diff --git a/autogpt_platform/frontend/src/services/push-notifications/registration.ts b/autogpt_platform/frontend/src/services/push-notifications/registration.tsindex e493af9904..c55a7c4ff9 100644--- a/autogpt_platform/frontend/src/services/push-notifications/registration.ts+++ b/autogpt_platform/frontend/src/services/push-notifications/registration.ts@@ -52,14 +52,10 @@ export async function subscribeToPush(}export async function unsubscribeFromPush(- registration: ServiceWorkerRegistration,+ subscription: PushSubscription,): Promise<boolean> {try {- const subscription = await registration.pushManager.getSubscription();- if (subscription) {- return await subscription.unsubscribe();- }- return true;+ return await subscription.unsubscribe();} catch (error) {console.error("Failed to unsubscribe from push:", error);return false;diff --git a/autogpt_platform/frontend/src/services/push-notifications/subscription-lock.ts b/autogpt_platform/frontend/src/services/push-notifications/subscription-lock.tsnew file mode 100644index 0000000000..c04cf214a6--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/subscription-lock.ts@@ -0,0 +1,50 @@+const PUSH_SUBSCRIPTION_LOCK = "autogpt-push-subscription";++interface Options {+ /**+ * Stop waiting for the lock after this long and run `action` unlocked.+ * For logout, where removing the subscription late or racily still beats+ * not removing it before the tab closes.+ */+ maxWaitMs?: number;+}++/**+ * Run `action` holding a lock shared by every tab of this browser. All tabs+ * share one push subscription, so a tab subscribing for the next account+ * must not read it while another tab is still unsubscribing it for the last.+ *+ * Every browser with the Push API also has Web Locks (Safari added locks in+ * 15.4, push in 16), so the unlocked fallback only runs where push does not.+ */+export async function withPushSubscriptionLock<T>(+ action: () => Promise<T>,+ { maxWaitMs }: Options = {},+): Promise<T> {+ if (typeof navigator === "undefined" || !navigator.locks) return action();++ const controller = new AbortController();+ const timer =+ maxWaitMs === undefined+ ? undefined+ : setTimeout(() => controller.abort(), maxWaitMs);+ let granted = false;+ let result!: T;+ try {+ await navigator.locks.request(+ PUSH_SUBSCRIPTION_LOCK,+ { signal: controller.signal },+ async () => {+ granted = true;+ clearTimeout(timer);+ result = await action();+ },+ );+ } catch (error) {+ if (granted || !controller.signal.aborted) throw error;+ return action();+ } finally {+ clearTimeout(timer);+ }+ return result;+}