Skip to content

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(frontend): add browser notification settings to the account page (#14695)

Krzysztof Czerwinski60f056a5e7f8
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/NotificationBanner.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/NotificationBanner.tsx
index 26b5fb1003..6ee0222c81 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/NotificationBanner.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/NotificationBanner.tsx
@@ -3,23 +3,42 @@
import { Button } from "@/components/atoms/Button/Button";
import { Alert, AlertDescription } from "@/components/molecules/Alert/Alert";
import { Key, storage } from "@/services/storage/local-storage";
-import { useEffect, useState } from "react";
+import {
+ type MouseEvent,
+ useEffect,
+ useState,
+ useSyncExternalStore,
+} from "react";
import { useCopilotUIStore } from "../../store";
+import {
+ readPermission,
+ subscribeToPermission,
+} from "@/components/layout/NotificationSettings/helpers";
+import { isPlainLeftClick } from "./helpers";
import { BellRingIcon, Cancel01Icon } from "@hugeicons/core-free-icons";
import { createIconComponent, Icon } from "@/components/atoms/Icon/Icon";
// Alert's `icon` prop takes a component (its defaults come from lucide).
const BellRing = createIconComponent(BellRingIcon);
+function hiddenOnServer() {
+ return "unsupported" as const;
+}
+
export function NotificationBanner() {
- const { setNotificationsEnabled, isNotificationsEnabled } =
- useCopilotUIStore();
+ const isNotificationsEnabled = useCopilotUIStore(
+ (state) => state.isNotificationsEnabled,
+ );
const [dismissed, setDismissed] = useState(
() => storage.get(Key.COPILOT_NOTIFICATION_BANNER_DISMISSED) === "true",
);
- const [permission, setPermission] = useState(() =>
- typeof Notification !== "undefined" ? Notification.permission : "denied",
+ // Live, so granting permission from settings in another tab hides this one
+ // when the user comes back. Hidden on the server and while hydrating.
+ const permission = useSyncExternalStore(
+ subscribeToPermission,
+ readPermission,
+ hiddenOnServer,
);
// Re-read dismissed flag when notifications are toggled off (e.g. clearCopilotLocalData)
@@ -41,18 +60,18 @@ export function NotificationBanner() {
return null;
}
- function handleEnable() {
- Notification.requestPermission().then((result) => {
- setPermission(result);
- if (result === "granted") {
- setNotificationsEnabled(true);
- handleDismiss();
- }
- });
+ function persistDismissed() {
+ storage.set(Key.COPILOT_NOTIFICATION_BANNER_DISMISSED, "true");
+ }
+
+ function handleOpenSettings(event: MouseEvent) {
+ // Only persist — setting state here would unmount the banner, and this
+ // link with it, before Next gets to navigate. A new-tab click keeps it.
+ if (isPlainLeftClick(event)) persistDismissed();
}
function handleDismiss() {
- storage.set(Key.COPILOT_NOTIFICATION_BANNER_DISMISSED, "true");
+ persistDismissed();
setDismissed(true);
}
@@ -60,11 +79,17 @@ export function NotificationBanner() {
<Alert variant="warning" icon={BellRing} aria-live="polite">
<div className="flex flex-wrap items-center gap-3">
<AlertDescription className="min-w-[12rem] flex-1">
- Enable browser notifications to know when your experts finish working,
- even when you switch tabs.
+ Notifications are off. Turn them on in Settings to know when your
+ experts finish working, even when you switch tabs.
</AlertDescription>
- <Button variant="primary" size="small" onClick={handleEnable}>
- Enable
+ <Button
+ as="NextLink"
+ variant="primary"
+ size="small"
+ href="/settings/account"
+ onClick={handleOpenSettings}
+ >
+ Open settings
</Button>
<Button
variant="ghost"
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.tsx
index cb12bc1cae..9b68f2aa28 100644
--- 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.tsx
@@ -1,8 +1,9 @@
import {
+ act,
cleanup,
+ fireEvent,
render,
screen,
- fireEvent,
waitFor,
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -21,6 +22,16 @@ vi.mock("@/services/environment", () => ({
},
}));
+function stubNotification(permission: NotificationPermission) {
+ const requestPermission = vi.fn();
+ Object.defineProperty(globalThis, "Notification", {
+ value: { permission, requestPermission },
+ configurable: true,
+ writable: true,
+ });
+ return requestPermission;
+}
+
function resetStore() {
useCopilotUIStore.setState({
isNotificationsEnabled: false,
@@ -39,24 +50,16 @@ describe("NotificationBanner", () => {
});
it("renders when permission is default and not dismissed", () => {
- Object.defineProperty(globalThis, "Notification", {
- value: { permission: "default", requestPermission: vi.fn() },
- configurable: true,
- writable: true,
- });
+ stubNotification("default");
render(<NotificationBanner />);
- expect(screen.getByText(/enable browser notifications/i)).toBeDefined();
- expect(screen.getByRole("button", { name: /^enable$/i })).toBeDefined();
+ expect(screen.getByText(/notifications are off/i)).toBeDefined();
+ expect(screen.getByRole("link", { name: /open settings/i })).toBeDefined();
});
it("does not render when already dismissed", () => {
- Object.defineProperty(globalThis, "Notification", {
- value: { permission: "default", requestPermission: vi.fn() },
- configurable: true,
- writable: true,
- });
+ stubNotification("default");
window.localStorage.setItem(
"copilot-notification-banner-dismissed",
"true",
@@ -68,11 +71,7 @@ describe("NotificationBanner", () => {
});
it("does not render when notifications are already enabled", () => {
- Object.defineProperty(globalThis, "Notification", {
- value: { permission: "granted", requestPermission: vi.fn() },
- configurable: true,
- writable: true,
- });
+ stubNotification("granted");
useCopilotUIStore.setState({ isNotificationsEnabled: true });
const { container } = render(<NotificationBanner />);
@@ -81,41 +80,26 @@ describe("NotificationBanner", () => {
});
it("does not render when permission is denied", () => {
- Object.defineProperty(globalThis, "Notification", {
- value: { permission: "denied", requestPermission: vi.fn() },
- configurable: true,
- writable: true,
- });
+ stubNotification("denied");
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,
- });
+ it("hands off to account settings instead of prompting for permission", () => {
+ const requestPermission = stubNotification("default");
render(<NotificationBanner />);
- fireEvent.click(screen.getByRole("button", { name: /^enable$/i }));
-
- await waitFor(() => {
- expect(requestPermission).toHaveBeenCalled();
- expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(true);
- });
+ const action = screen.getByRole("link", { name: /open settings/i });
+ expect(action.getAttribute("href")).toBe("/settings/account");
+ expect(screen.queryByRole("button", { name: /^enable$/i })).toBeNull();
+ expect(requestPermission).not.toHaveBeenCalled();
});
it("dismisses banner and sets localStorage on dismiss click", () => {
- Object.defineProperty(globalThis, "Notification", {
- value: { permission: "default", requestPermission: vi.fn() },
- configurable: true,
- writable: true,
- });
+ stubNotification("default");
render(<NotificationBanner />);
@@ -124,23 +108,52 @@ describe("NotificationBanner", () => {
expect(
window.localStorage.getItem("copilot-notification-banner-dismissed"),
).toBe("true");
+ expect(screen.queryByText(/notifications are off/i)).toBeNull();
});
- 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,
- });
+ it("stays mounted when the settings link is clicked", async () => {
+ stubNotification("default");
render(<NotificationBanner />);
- fireEvent.click(screen.getByRole("button", { name: /^enable$/i }));
+ fireEvent.click(screen.getByRole("link", { name: /open settings/i }));
- await waitFor(() => {
- expect(requestPermission).toHaveBeenCalled();
- expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false);
+ // Dismissing via state here would unmount the banner — and this link with
+ // it — before Next got to navigate, so the click must only persist.
+ await waitFor(() =>
+ expect(
+ window.localStorage.getItem("copilot-notification-banner-dismissed"),
+ ).toBe("true"),
+ );
+ expect(screen.getByRole("link", { name: /open settings/i })).toBeDefined();
+ });
+
+ it("stays dismissable when settings is opened in a new tab", () => {
+ stubNotification("default");
+
+ render(<NotificationBanner />);
+
+ const link = screen.getByRole("link", { name: /open settings/i });
+ fireEvent.click(link, { metaKey: true });
+ fireEvent.click(link, { ctrlKey: true });
+ fireEvent.click(link, { shiftKey: true });
+
+ expect(
+ window.localStorage.getItem("copilot-notification-banner-dismissed"),
+ ).toBeNull();
+ expect(screen.getByText(/notifications are off/i)).toBeDefined();
+ });
+
+ it("hides once permission is granted from another tab", () => {
+ stubNotification("default");
+ render(<NotificationBanner />);
+ expect(screen.getByText(/notifications are off/i)).toBeDefined();
+
+ stubNotification("granted");
+ act(() => {
+ window.dispatchEvent(new Event("focus"));
});
+
+ expect(screen.queryByText(/notifications are off/i)).toBeNull();
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..d3aef4d39e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/__tests__/helpers.test.ts
@@ -0,0 +1,30 @@
+import type { MouseEvent } from "react";
+import { describe, expect, it } from "vitest";
+import { isPlainLeftClick } from "../helpers";
+
+function click(overrides: Partial<MouseEvent> = {}) {
+ return {
+ button: 0,
+ metaKey: false,
+ ctrlKey: false,
+ shiftKey: false,
+ altKey: false,
+ ...overrides,
+ } as MouseEvent;
+}
+
+describe("isPlainLeftClick", () => {
+ it("accepts an unmodified primary click", () => {
+ expect(isPlainLeftClick(click())).toBe(true);
+ });
+
+ it.each([
+ ["middle button", { button: 1 }],
+ ["meta", { metaKey: true }],
+ ["ctrl", { ctrlKey: true }],
+ ["shift", { shiftKey: true }],
+ ["alt", { altKey: true }],
+ ])("rejects a %s click", (_, overrides) => {
+ expect(isPlainLeftClick(click(overrides))).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/helpers.ts
new file mode 100644
index 0000000000..d05d12f1a9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/NotificationBanner/helpers.ts
@@ -0,0 +1,12 @@
+import type { MouseEvent } from "react";
+
+// A modified click opens the link somewhere else and leaves this page as it was.
+export function isPlainLeftClick(event: MouseEvent) {
+ return (
+ event.button === 0 &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !event.altKey
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
index 7ab9b11d9c..4ebd8dc8d1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
@@ -469,6 +469,28 @@ describe("SettingsPreferencesPage", () => {
vi.unstubAllGlobals();
});
+ test("renders the Browser notifications card regardless of the flag", async () => {
+ mockUseGetFlag.mockReturnValue(false);
+ Object.defineProperty(globalThis, "Notification", {
+ value: { permission: "default", requestPermission: vi.fn() },
+ configurable: true,
+ writable: true,
+ });
+ setupBaseHandlers();
+
+ try {
+ render(<SettingsPreferencesPage />);
+
+ expect(await screen.findByText("Browser")).toBeDefined();
+ expect(
+ screen.getByRole("switch", { name: "Notifications" }),
+ ).toBeDefined();
+ expect(screen.getByRole("switch", { name: "Sound" })).toBeDefined();
+ } finally {
+ delete (globalThis as { Notification?: unknown }).Notification;
+ }
+ });
+
test("hides the notifications card when settings-notifications is off", async () => {
mockUseGetFlag.mockReturnValue(false);
setupBaseHandlers();
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/components/BrowserNotificationsCard/BrowserNotificationsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/BrowserNotificationsCard/BrowserNotificationsCard.tsx
new file mode 100644
index 0000000000..1b8748b20a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/BrowserNotificationsCard/BrowserNotificationsCard.tsx
@@ -0,0 +1,45 @@
+"use client";
+
+import { motion, useReducedMotion } from "framer-motion";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { NotificationSettingsControls } from "@/components/layout/NotificationSettings/NotificationSettingsControls";
+
+import { EASE_OUT } from "../../helpers";
+
+interface Props {
+ index?: number;
+}
+
+export function BrowserNotificationsCard({ index = 0 }: Props) {
+ const reduceMotion = useReducedMotion();
+
+ return (
+ <motion.section
+ initial={reduceMotion ? false : { opacity: 0, y: 12 }}
+ animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}
+ transition={
+ reduceMotion
+ ? undefined
+ : { duration: 0.32, ease: EASE_OUT, delay: 0.04 + index * 0.05 }
+ }
+ className="flex w-full flex-col"
+ >
+ <div className="flex h-fit flex-col gap-4 rounded-[18px] border border-zinc-200 bg-white px-4 py-3 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">
+ <div className="flex flex-col gap-1">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Browser
+ </Text>
+ {/* Unlike the email settings above, these live in this browser's
+ local storage — they don't follow the account to another device. */}
+ <Text variant="small" as="span" className="text-zinc-500">
+ Set per device. Turning these on here won&apos;t carry over to your
+ phone or another browser.
+ </Text>
+ </div>
+
+ <NotificationSettingsControls />
+ </div>
+ </motion.section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
index 56dbff28c0..d02438109f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
@@ -7,6 +7,7 @@ import { isConsentManagerConfigured } from "@/services/consent/consent";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { AccountCard } from "./components/AccountCard/AccountCard";
+import { BrowserNotificationsCard } from "./components/BrowserNotificationsCard/BrowserNotificationsCard";
import { NotificationsCard } from "./components/NotificationsCard/NotificationsCard";
import { PreferencesHeader } from "./components/PreferencesHeader/PreferencesHeader";
import { CookieSettingsCard } from "./components/CookieSettingsCard/CookieSettingsCard";
@@ -38,6 +39,7 @@ export default function SettingsPreferencesPage() {
} = usePreferencesPage();
const showNotifications = useGetFlag(Flag.SETTINGS_NOTIFICATIONS);
+ const browserCardIndex = showNotifications ? 3 : 2;
if (isError) {
return (
@@ -79,7 +81,11 @@ export default function SettingsPreferencesPage() {
/>
) : null}
- {isConsentManagerConfigured() ? <CookieSettingsCard index={3} /> : null}
+ <BrowserNotificationsCard index={browserCardIndex} />
+
+ {isConsentManagerConfigured() ? (
+ <CookieSettingsCard index={browserCardIndex + 1} />
+ ) : null}
<SaveBar
visible={dirty}
diff --git a/autogpt_platform/frontend/src/components/layout/NotificationSettings/NotificationSettingsControls.tsx b/autogpt_platform/frontend/src/components/layout/NotificationSettings/NotificationSettingsControls.tsx
new file mode 100644
index 0000000000..bfaf5084c8
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/NotificationSettings/NotificationSettingsControls.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { useId } from "react";
+
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { Alert01Icon } from "@hugeicons/core-free-icons";
+
+import { SettingRow } from "./components/SettingRow/SettingRow";
+import { useNotificationSettings } from "./useNotificationSettings";
+
+export function NotificationSettingsControls() {
+ const {
+ isNotificationsEnabled,
+ isSoundEnabled,
+ isSupported,
+ isBlocked,
+ toggleNotifications,
+ toggleSound,
+ } = useNotificationSettings();
+ const blockedExplainerId = useId();
+
+ if (!isSupported) {
+ return (
+ <Text variant="small" as="p" className="text-zinc-500">
+ This browser doesn&apos;t support notifications.
+ </Text>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ <SettingRow
+ label="Notifications"
+ description="Get told when your experts finish, even in another tab."
+ checked={isNotificationsEnabled}
+ disabled={isBlocked}
+ describedBy={isBlocked ? blockedExplainerId : undefined}
+ onCheckedChange={toggleNotifications}
+ />
+ <SettingRow
+ label="Sound"
+ description="Play a chime with each one."
+ checked={isSoundEnabled && isNotificationsEnabled}
+ disabled={!isNotificationsEnabled}
+ onCheckedChange={toggleSound}
+ />
+
+ {/* A browser-level denial is the one state we can't fix from in here —
+ say so rather than leaving a switch that silently refuses to move. */}
+ {isBlocked ? (
+ <div
+ id={blockedExplainerId}
+ className="flex items-start gap-2 rounded-lg bg-zinc-100 px-3 py-2"
+ >
+ <Icon
+ icon={Alert01Icon}
+ className="mt-0.5 size-4 shrink-0 text-zinc-500"
+ />
+ <Text variant="small" as="p" className="text-zinc-600">
+ Your browser is blocking notifications for AutoGPT. Allow them in
+ its site settings to switch this back on.
+ </Text>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/layout/NotificationSettings/__tests__/NotificationSettingsControls.test.tsx b/autogpt_platform/frontend/src/components/layout/NotificationSettings/__tests__/NotificationSettingsControls.test.tsx
new file mode 100644
index 0000000000..0bfaf7b46f
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/NotificationSettings/__tests__/NotificationSettingsControls.test.tsx
@@ -0,0 +1,229 @@
+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";
+import { NotificationSettingsControls } from "../NotificationSettingsControls";
+import { useNotificationSettings } from "../useNotificationSettings";
+
+vi.mock("@sentry/nextjs", () => ({ captureException: vi.fn() }));
+
+const mockToast = vi.hoisted(() => vi.fn());
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: mockToast,
+}));
+
+vi.mock("@/services/environment", () => ({
+ environment: {
+ isServerSide: vi.fn(() => false),
+ isClientSide: vi.fn(() => true),
+ getAGPTServerApiUrl: vi.fn(() => "http://localhost:8006/api"),
+ },
+}));
+
+// Radix reflects a disabled switch as `data-disabled`, not always `disabled`.
+function isDisabled(element: HTMLElement) {
+ return (
+ element.hasAttribute("disabled") ||
+ element.getAttribute("data-disabled") !== null
+ );
+}
+
+function describedByText(element: HTMLElement) {
+ return (element.getAttribute("aria-describedby") ?? "")
+ .split(" ")
+ .map((id) => document.getElementById(id)?.textContent ?? "")
+ .join(" ");
+}
+
+function setPermission(
+ permission: string,
+ requestPermission = vi.fn().mockResolvedValue(permission),
+) {
+ Object.defineProperty(globalThis, "Notification", {
+ value: { permission, requestPermission },
+ configurable: true,
+ writable: true,
+ });
+ return requestPermission;
+}
+
+describe("NotificationSettingsControls", () => {
+ beforeEach(() => {
+ mockToast.mockClear();
+ window.localStorage.clear();
+ useCopilotUIStore.setState({
+ isNotificationsEnabled: false,
+ isSoundEnabled: true,
+ });
+ setPermission("default");
+ });
+
+ afterEach(() => cleanup());
+
+ it("turns notifications back off — the switch is not one-way", async () => {
+ setPermission("granted");
+ useCopilotUIStore.setState({ isNotificationsEnabled: true });
+ render(<NotificationSettingsControls />);
+
+ await userEvent.click(
+ screen.getByRole("switch", { name: "Notifications" }),
+ );
+
+ await waitFor(() =>
+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false),
+ );
+ });
+
+ it("asks the browser for permission when switching on", async () => {
+ // A real browser updates `Notification.permission` before resolving.
+ const requestPermission = setPermission("default");
+ requestPermission.mockImplementation(async () => {
+ setPermission("granted");
+ return "granted";
+ });
+
+ render(<NotificationSettingsControls />);
+ await userEvent.click(
+ screen.getByRole("switch", { name: "Notifications" }),
+ );
+
+ await waitFor(() => {
+ expect(requestPermission).toHaveBeenCalled();
+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(true);
+ });
+ });
+
+ it("explains the browser-level block instead of offering a dead switch", async () => {
+ setPermission("denied");
+ render(<NotificationSettingsControls />);
+
+ await waitFor(() =>
+ expect(
+ screen.getByText(/browser is blocking notifications/i),
+ ).toBeTruthy(),
+ );
+ expect(
+ isDisabled(screen.getByRole("switch", { name: "Notifications" })),
+ ).toBe(true);
+ });
+
+ it("does not call a dismissed prompt a block", async () => {
+ setPermission("default");
+ render(<NotificationSettingsControls />);
+
+ await userEvent.click(
+ screen.getByRole("switch", { name: "Notifications" }),
+ );
+
+ await waitFor(() => expect(mockToast).toHaveBeenCalledTimes(1));
+ expect(mockToast.mock.calls[0][0].title).not.toMatch(/blocked/i);
+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false);
+ expect(screen.queryByText(/browser is blocking notifications/i)).toBeNull();
+ });
+
+ it("switches the flag off when permission is no longer granted", async () => {
+ setPermission("denied");
+ useCopilotUIStore.setState({ isNotificationsEnabled: true });
+
+ render(<NotificationSettingsControls />);
+
+ await waitFor(() =>
+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false),
+ );
+ });
+
+ it("picks up a permission change made in site settings when the tab regains focus", async () => {
+ setPermission("granted");
+ useCopilotUIStore.setState({ isNotificationsEnabled: true });
+ render(<NotificationSettingsControls />);
+ const notifications = screen.getByRole("switch", { name: "Notifications" });
+ expect(notifications.getAttribute("aria-checked")).toBe("true");
+
+ setPermission("denied");
+ act(() => {
+ window.dispatchEvent(new Event("focus"));
+ });
+
+ await waitFor(() =>
+ expect(
+ screen.getByText(/browser is blocking notifications/i),
+ ).toBeTruthy(),
+ );
+ expect(notifications.getAttribute("aria-checked")).toBe("false");
+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false);
+ });
+
+ it("sees a blocked browser as blocked on the very first render", () => {
+ setPermission("denied");
+ const seen: boolean[] = [];
+ function Probe() {
+ seen.push(useNotificationSettings().isBlocked);
+ return null;
+ }
+
+ render(<Probe />);
+
+ // An effect-based read would first render as not blocked, and paint an
+ // enabled switch before correcting itself.
+ expect(seen[0]).toBe(true);
+ });
+
+ it("keeps sound gated behind notifications being on", async () => {
+ render(<NotificationSettingsControls />);
+
+ expect(isDisabled(screen.getByRole("switch", { name: "Sound" }))).toBe(
+ true,
+ );
+ });
+
+ it("toggles sound once notifications are on", async () => {
+ setPermission("granted");
+ useCopilotUIStore.setState({ isNotificationsEnabled: true });
+ render(<NotificationSettingsControls />);
+
+ await userEvent.click(screen.getByRole("switch", { name: "Sound" }));
+
+ expect(useCopilotUIStore.getState().isSoundEnabled).toBe(false);
+ });
+
+ it("toggles from the visible label, not just the switch", async () => {
+ setPermission("granted");
+ useCopilotUIStore.setState({ isNotificationsEnabled: true });
+ render(<NotificationSettingsControls />);
+
+ await userEvent.click(screen.getByText("Notifications"));
+
+ expect(useCopilotUIStore.getState().isNotificationsEnabled).toBe(false);
+ });
+
+ it("describes each switch, including why a blocked one can't move", async () => {
+ setPermission("denied");
+ render(<NotificationSettingsControls />);
+
+ const notifications = screen.getByRole("switch", { name: "Notifications" });
+ await waitFor(() =>
+ expect(describedByText(notifications)).toMatch(
+ /browser is blocking notifications/i,
+ ),
+ );
+ expect(describedByText(notifications)).toMatch(/your experts finish/i);
+ expect(
+ describedByText(screen.getByRole("switch", { name: "Sound" })),
+ ).toMatch(/play a chime/i);
+ });
+
+ it("reports gracefully when the browser has no Notification API", async () => {
+ Object.defineProperty(globalThis, "Notification", {
+ value: undefined,
+ configurable: true,
+ writable: true,
+ });
+
+ render(<NotificationSettingsControls />);
+
+ await waitFor(() =>
+ expect(screen.getByText(/doesn't support notifications/i)).toBeTruthy(),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/NotificationSettings/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/layout/NotificationSettings/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..d0708dc9b8
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/NotificationSettings/__tests__/helpers.test.ts
@@ -0,0 +1,43 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ readPermission,
+ readServerPermission,
+ subscribeToPermission,
+} from "../helpers";
+
+describe("notification permission helpers", () => {
+ afterEach(() => {
+ delete (globalThis as { Notification?: unknown }).Notification;
+ });
+
+ it("reads the browser's permission", () => {
+ Object.defineProperty(globalThis, "Notification", {
+ value: { permission: "denied" },
+ configurable: true,
+ writable: true,
+ });
+ expect(readPermission()).toBe("denied");
+ });
+
+ it("reports a browser without the Notification API as unsupported", () => {
+ expect(readPermission()).toBe("unsupported");
+ });
+
+ it("renders the neutral state on the server", () => {
+ expect(readServerPermission()).toBe("default");
+ });
+
+ it("re-reads on focus and visibility change until unsubscribed", () => {
+ const onChange = vi.fn();
+ const unsubscribe = subscribeToPermission(onChange);
+
+ window.dispatchEvent(new Event("focus"));
+ document.dispatchEvent(new Event("visibilitychange"));
+ expect(onChange).toHaveBeenCalledTimes(2);
+
+ unsubscribe();
+ window.dispatchEvent(new Event("focus"));
+ document.dispatchEvent(new Event("visibilitychange"));
+ expect(onChange).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/layout/NotificationSettings/components/SettingRow/SettingRow.tsx b/autogpt_platform/frontend/src/components/layout/NotificationSettings/components/SettingRow/SettingRow.tsx
new file mode 100644
index 0000000000..7e59647c4f
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/NotificationSettings/components/SettingRow/SettingRow.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { useId } from "react";
+
+import { Switch } from "@/components/atoms/Switch/Switch";
+import { Text } from "@/components/atoms/Text/Text";
+import { cn } from "@/lib/utils";
+
+interface Props {
+ label: string;
+ description: string;
+ checked: boolean;
+ disabled?: boolean;
+ describedBy?: string;
+ onCheckedChange: () => void;
+}
+
+export function SettingRow({
+ label,
+ description,
+ checked,
+ disabled,
+ describedBy,
+ onCheckedChange,
+}: Props) {
+ const switchId = useId();
+ const descriptionId = useId();
+
+ return (
+ <div className="flex items-center justify-between gap-4">
+ <div className={cn("flex flex-col", disabled && "opacity-50")}>
+ <label
+ htmlFor={switchId}
+ className={disabled ? "cursor-not-allowed" : "cursor-pointer"}
+ >
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ {label}
+ </Text>
+ </label>
+ <Text
+ id={descriptionId}
+ variant="small"
+ as="span"
+ className="text-zinc-500"
+ >
+ {description}
+ </Text>
+ </div>
+ <Switch
+ id={switchId}
+ checked={checked}
+ disabled={disabled}
+ onCheckedChange={onCheckedChange}
+ aria-describedby={[descriptionId, describedBy]
+ .filter(Boolean)
+ .join(" ")}
+ />
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/layout/NotificationSettings/helpers.ts b/autogpt_platform/frontend/src/components/layout/NotificationSettings/helpers.ts
new file mode 100644
index 0000000000..5794fed718
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/NotificationSettings/helpers.ts
@@ -0,0 +1,24 @@
+export type NotificationPermissionState =
+ | NotificationPermission
+ | "unsupported";
+
+export function readPermission(): NotificationPermissionState {
+ if (typeof Notification === "undefined") return "unsupported";
+ return Notification.permission;
+}
+
+// The server can't know, and "default" renders the neutral state.
+export function readServerPermission(): NotificationPermissionState {
+ return "default";
+}
+
+// Site settings change permission without firing anything we can listen to,
+// so re-read whenever the tab comes back.
+export function subscribeToPermission(onChange: () => void) {
+ window.addEventListener("focus", onChange);
+ document.addEventListener("visibilitychange", onChange);
+ return () => {
+ window.removeEventListener("focus", onChange);
+ document.removeEventListener("visibilitychange", onChange);
+ };
+}
diff --git a/autogpt_platform/frontend/src/components/layout/NotificationSettings/useNotificationSettings.ts b/autogpt_platform/frontend/src/components/layout/NotificationSettings/useNotificationSettings.ts
new file mode 100644
index 0000000000..323ad1e18a
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/layout/NotificationSettings/useNotificationSettings.ts
@@ -0,0 +1,106 @@
+"use client";
+
+import { useEffect, useReducer, useSyncExternalStore } from "react";
+
+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";
+import { toast } from "@/components/molecules/Toast/use-toast";
+
+import {
+ readPermission,
+ readServerPermission,
+ subscribeToPermission,
+} from "./helpers";
+
+/**
+ * The one place that knows how the browser's three-state permission maps onto
+ * our single app-level switch.
+ *
+ * We can never revoke a granted permission — "off" only ever means our own
+ * flag. Once the user has denied at the browser level, the switch is inert
+ * and the surface has to send them to their browser's site settings.
+ */
+export function useNotificationSettings() {
+ const isNotificationsEnabled = useCopilotUIStore(
+ (s) => s.isNotificationsEnabled,
+ );
+ const setNotificationsEnabled = useCopilotUIStore(
+ (s) => s.setNotificationsEnabled,
+ );
+ const isSoundEnabled = useCopilotUIStore((s) => s.isSoundEnabled);
+ const toggleSound = useCopilotUIStore((s) => s.toggleSound);
+
+ // Read during render, so a blocked or unsupported browser never paints an
+ // enabled switch first. Answering the prompt fires no event, hence the
+ // manual refresh after it.
+ const permission = useSyncExternalStore(
+ subscribeToPermission,
+ readPermission,
+ readServerPermission,
+ );
+ const [, refreshPermission] = useReducer((count: number) => count + 1, 0);
+
+ // The store only checks permission once, at load. A revoke since then must
+ // switch our flag off too, or the switch shows on while nothing can ever be
+ // delivered. This reads the browser directly because the hydration render
+ // still sees the server's "default".
+ useEffect(() => {
+ if (isNotificationsEnabled && readPermission() !== "granted") {
+ setNotificationsEnabled(false);
+ }
+ }, [permission, isNotificationsEnabled, setNotificationsEnabled]);
+
+ const isSupported = permission !== "unsupported";
+ const isBlocked = permission === "denied";
+
+ async function toggleNotifications() {
+ if (isNotificationsEnabled) {
+ setNotificationsEnabled(false);
+ return;
+ }
+
+ if (typeof Notification === "undefined") {
+ toast({
+ title: "Notifications not supported",
+ description: "Your browser does not support notifications.",
+ variant: "destructive",
+ });
+ return;
+ }
+
+ const result = await Notification.requestPermission();
+ refreshPermission();
+
+ if (result === "granted") {
+ setNotificationsEnabled(true);
+ return;
+ }
+
+ // The prompt was dismissed or never shown (Chrome's quiet UI), not
+ // refused, so nothing needs unblocking in browser settings.
+ if (result === "default") {
+ toast({
+ title: "Notifications not turned on",
+ description:
+ "Your browser didn't confirm permission. Try again, or allow them from the icon in the address bar.",
+ });
+ return;
+ }
+
+ toast({
+ title: "Notifications blocked",
+ description:
+ "Please allow notifications in your browser settings to enable this feature.",
+ variant: "destructive",
+ });
+ }
+
+ return {
+ isNotificationsEnabled,
+ isSoundEnabled,
+ isSupported,
+ isBlocked,
+ permission,
+ toggleNotifications,
+ toggleSound,
+ };
+}