fix(webui): refine browser notifications (NAN-227)

Reconcile the original notification fix with the integrated main snapshot.

Group notification settings and simplify localized copy and documentation.
Preserve permission opt-out and notification click routing across app transitions.
Suppress late completion notifications for discarded temporary chats and align
notification settings skeletons with the loaded layout.
This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-20 13:45:04 +08:00
1 parent 7b2af031c0
commit 11152626f8
34 files changed
+728 -289

No files matched your search

+87 -18
View File
@@ -1,10 +1,12 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useState } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BrowserNotificationSettings } from "@/components/settings/overview/BrowserNotificationSettings";
import { BrowserNotifications } from "@/components/BrowserNotifications";
import { BrowserNotificationSettings } from "@/components/settings/notifications/BrowserNotificationSettings";
import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings";
import { BrowserNotifications, useBrowserNotificationLifecycle } from "@/components/BrowserNotifications";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { enableBrowserNotifications, NOTIFICATION_OPEN_EVENT, notificationChatUrl, notificationProblem, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";
import { DEFAULT_LOCAL_PREFS, writeLocalPreferences } from "@/lib/local-preferences";
import { DEFAULT_LOCAL_PREFS, readLocalPreferences, writeLocalPreferences } from "@/lib/local-preferences";
import type { TaskNotice } from "@/lib/nanobot-client";
import i18n from "@/i18n";
@@ -12,25 +14,33 @@ const requestPermission = vi.fn();
const postMessage = vi.fn();
const worker = { postMessage };
const getRegistration = vi.fn();
let receive: ((event: MessageEvent) => void) | null;
function Harness({ enabled = false }: { enabled?: boolean }) {
const [preferences, setPreferences] = useState({ ...DEFAULT_LOCAL_PREFS, browserNotifications: enabled });
return <BrowserNotificationSettings localPrefs={preferences} onChangeLocalPrefs={setPreferences} />;
}
function LifecycleHarness({ settings = true }: { settings?: boolean }) {
useBrowserNotificationLifecycle();
const preferences = useLocalPreferences();
return settings ? <BrowserNotificationSettings localPrefs={preferences}
onChangeLocalPrefs={(update) => writeLocalPreferences(typeof update === "function" ? update(readLocalPreferences()) : update)} /> : null;
}
beforeEach(() => {
vi.stubGlobal("isSecureContext", true);
vi.stubGlobal("Notification", { permission: "default", requestPermission });
vi.stubGlobal("MessageChannel", class {
port1 = { onmessage: null as ((event: MessageEvent) => void) | null, close: vi.fn() };
port2 = {};
constructor() { queueMicrotask(() => { receive = this.port1.onmessage; }); }
port2 = { reply: (data: unknown) => this.port1.onmessage?.({ data } as MessageEvent) };
});
Object.defineProperty(navigator, "serviceWorker", { configurable: true, value: Object.assign(new EventTarget(), { getRegistration, controller: worker }) });
getRegistration.mockResolvedValue({ active: worker });
postMessage.mockImplementation(() => { setTimeout(() => receive?.({ data: "submitted" } as MessageEvent), 0); });
requestPermission.mockResolvedValue("granted");
postMessage.mockImplementation((data, ports) => { queueMicrotask(() => ports[0].reply(data.type === "nanobot:notification-probe" ? "ready" : "submitted")); });
requestPermission.mockImplementation(() => {
vi.stubGlobal("Notification", { permission: "granted", requestPermission });
return Promise.resolve("granted");
});
Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, browserNotifications: true });
});
@@ -87,7 +97,17 @@ describe("notification permission and delivery boundary", () => {
postMessage.mockImplementation(() => {});
const showing = showBrowserNotification("Task completed", { key: "one", url: notificationChatUrl("one", false) });
await vi.advanceTimersByTimeAsync(5_001);
expect(await showing).toBe("displayFailed");
expect(await showing).toBe("workerUnavailable");
});
it("reports an older active worker that does not understand the notification protocol", async () => {
vi.useFakeTimers();
vi.stubGlobal("Notification", { permission: "granted" });
postMessage.mockImplementation(() => {});
const enabling = enableBrowserNotifications();
await vi.advanceTimersByTimeAsync(5_001);
expect(await enabling).toBe("workerUnavailable");
expect(requestPermission).not.toHaveBeenCalled();
});
it("uses the worker without constructing Notification, and isolates a post failure", async () => {
@@ -97,7 +117,7 @@ describe("notification permission and delivery boundary", () => {
expect(await showBrowserNotification("Task completed", options)).toBe("submitted");
expect(constructor).not.toHaveBeenCalled();
postMessage.mockImplementation(() => { throw new Error("worker stopped"); });
expect(await showBrowserNotification("Task completed", options)).toBe("displayFailed");
expect(await showBrowserNotification("Task completed", options)).toBe("workerUnavailable");
});
it("does not notify while visible, disabled, or disabled during a lookup", async () => {
@@ -125,11 +145,26 @@ describe("notification permission and delivery boundary", () => {
});
describe("notification settings", () => {
it("keeps completion sound independent when browser notifications are unavailable", () => {
vi.stubGlobal("Notification", undefined);
function Page() {
const [preferences, setPreferences] = useState(DEFAULT_LOCAL_PREFS);
return <NotificationSettings localPrefs={preferences} onChangeLocalPrefs={setPreferences} />;
}
render(<Page />);
expect(screen.getByRole("switch", { name: "Browser notifications" })).toBeDisabled();
const sound = screen.getByRole("switch", { name: "Completion sound" });
expect(sound).toHaveAttribute("aria-checked", "false");
fireEvent.click(sound);
expect(sound).toHaveAttribute("aria-checked", "true");
expect(screen.getByRole("switch", { name: "Browser notifications" })).toHaveAttribute("aria-checked", "false");
});
it("explains unavailable notification support beside a disabled switch", () => {
vi.stubGlobal("Notification", undefined);
render(<Harness />);
expect(screen.getByRole("switch", { name: "Browser notifications" })).toBeDisabled();
expect(screen.getByRole("status")).toHaveTextContent("This browser cannot send notifications");
expect(screen.getByRole("status")).toHaveTextContent("This browser doesn’t support notifications");
});
it("reports dismissal and lets the user retry, test, and disable", async () => {
@@ -144,6 +179,7 @@ describe("notification settings", () => {
expect(toggle).toHaveAttribute("aria-checked", "false");
fireEvent.click(toggle);
await waitFor(() => expect(toggle).toHaveAttribute("aria-checked", "true"));
await waitFor(() => expect(screen.getByRole("button", { name: "Test notification" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Test notification" }));
await screen.findByText(/Sent to the browser/);
fireEvent.click(toggle);
@@ -151,14 +187,37 @@ describe("notification settings", () => {
expect(screen.queryByRole("button", { name: "Test notification" })).not.toBeInTheDocument();
});
it("updates revoked permission on return and still allows opt-out", () => {
it("reconciles revocation outside settings and requires opt-in after regranting permission", async () => {
vi.stubGlobal("Notification", { permission: "granted" });
render(<Harness enabled />);
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, browserNotifications: true, notificationSound: true });
const { rerender } = render(<LifecycleHarness settings={false} />);
vi.stubGlobal("Notification", { permission: "denied" });
fireEvent.focus(window);
expect(screen.getByRole("status")).toHaveTextContent("Notifications are blocked");
expect(readLocalPreferences()).toMatchObject({ browserNotifications: false, notificationSound: true });
rerender(<LifecycleHarness />);
expect(screen.getByRole("status")).toHaveTextContent("Notification permission was revoked");
expect(screen.queryByRole("button", { name: "Test notification" })).not.toBeInTheDocument();
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");
vi.stubGlobal("Notification", { permission: "granted", requestPermission });
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
expect(screen.getByRole("switch")).toBeEnabled();
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");
fireEvent.click(screen.getByRole("switch"));
await waitFor(() => expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "true"));
});
it("allows opt-out and an explicit readiness retry when the worker is unavailable", async () => {
vi.stubGlobal("Notification", { permission: "granted" });
getRegistration.mockResolvedValue(null);
render(<Harness enabled />);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("notification service is not ready"));
fireEvent.click(screen.getByRole("switch"));
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");
getRegistration.mockResolvedValue({ active: worker });
const retry = screen.getByRole("button", { name: "Check again" });
await waitFor(() => expect(retry).toBeEnabled());
fireEvent.click(retry);
await waitFor(() => expect(screen.queryByRole("button", { name: "Check again" })).not.toBeInTheDocument());
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");
});
@@ -184,7 +243,7 @@ it("subscribes outside a chat, uses generic localized text, and cleans up", asyn
const event = { event: "turn_end", chat_id: "other", turn_id: "turn", outcome: "failed", failure_message: "PRIVATE TOKEN" } as const;
handler({ event, temporary: false });
await waitFor(() => expect(postMessage).toHaveBeenCalled());
expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "任务未完成,打开 nanobot 查看详情。", url: notificationChatUrl("other", false) });
expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "任务失败,点击查看详情。", url: notificationChatUrl("other", false) });
expect(JSON.stringify(postMessage.mock.calls[0][0])).not.toContain("PRIVATE TOKEN");
expect(taskNoticeKey({ event, temporary: false })).toBe('["other","turn","end"]');
unmount();
@@ -203,12 +262,16 @@ it("does not report cancellation or interruption as completion", async () => {
expect(postMessage).not.toHaveBeenCalled();
handler({ event: { ...event, outcome: "interrupted" }, temporary: false });
await waitFor(() => expect(postMessage).toHaveBeenCalled());
expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "Task needs attention. Open nanobot to continue." });
expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "Task needs attention. Click to continue." });
});
it("opens a notification only from the controlling worker and reveals the owning host", () => {
it("keeps validated notification navigation alive through sign-out and reveals the owning host", () => {
const client = { onTaskNotice: () => () => {} };
render(<BrowserNotifications client={client} />);
function AuthBoundary({ authenticated }: { authenticated: boolean }) {
useBrowserNotificationLifecycle();
return authenticated ? <BrowserNotifications client={client} /> : null;
}
const { rerender } = render(<AuthBoundary authenticated />);
const reveal = vi.fn();
window.addEventListener(NOTIFICATION_OPEN_EVENT, reveal);
const url = notificationChatUrl("clicked", false);
@@ -221,6 +284,12 @@ it("opens a notification only from the controlling worker and reveals the owning
send(worker, url);
expect(window.location.hash).toBe("#/chat/websocket%3Aclicked");
expect(reveal).toHaveBeenCalledOnce();
window.location.hash = "#/settings?section=notifications";
rerender(<AuthBoundary authenticated={false} />);
send(worker, url);
expect(window.location.hash).toBe("#/chat/websocket%3Aclicked");
rerender(<AuthBoundary authenticated />);
expect(window.location.hash).toBe("#/chat/websocket%3Aclicked");
window.removeEventListener(NOTIFICATION_OPEN_EVENT, reveal);
window.history.replaceState(null, "", "/");
});