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, "", "/");
});
+18 -1
View File
@@ -178,6 +178,21 @@ const LOCALIZED_SETTINGS_COPY_KEYS = [
"settings.help.codeWrap",
"settings.help.brandLogos",
"settings.help.browserNotifications",
"settings.nav.notifications",
"settings.notifications.scope",
"settings.notifications.intro",
"settings.notifications.pageRequired",
"settings.notifications.revoked",
"settings.notifications.retry",
"settings.notifications.statusOff",
"settings.notifications.statusPermission",
"settings.notifications.statusOn",
"settings.notifications.statusBlocked",
"settings.notifications.statusRevoked",
"settings.notifications.statusUnavailable",
"settings.notifications.statusWorker",
"settings.notifications.statusBusy",
"settings.notifications.statusError",
"settings.notifications.test",
"settings.notifications.testBody",
"settings.notifications.waiting",
@@ -639,7 +654,9 @@ describe("webui i18n", () => {
...LOCALIZED_CHANNEL_SHELL_KEYS,
...LOCALIZED_NEW_SURFACE_KEYS,
].filter(
(key) => current.get(key) === english.get(key),
// “Notifications” is also the native French label.
(key) => current.get(key) === english.get(key)
&& !(locale === "fr" && key === "settings.nav.notifications"),
);
expect({ locale, leaked }).toEqual({ locale, leaked: [] });
+23 -1
View File
@@ -79,15 +79,37 @@ describe("NanobotClient", () => {
const broken = client.onTaskNotice(() => { throw new Error("optional notification failed"); });
const notice = vi.fn();
const unsubscribe = client.onTaskNotice(notice);
client.attach("away");
const event = { event: "turn_end", chat_id: "away", turn_id: "turn", outcome: "completed" };
lastSocket().fakeMessage(event);
expect(notice).toHaveBeenCalledWith({ event, temporary: false });
const replay = vi.fn();
client.onChat("away", replay);
client.onTranscript("away", replay);
expect(replay).toHaveBeenCalledWith(event);
expect(notice).toHaveBeenCalledOnce();
broken(); unsubscribe(); client.close();
});
it("ignores in-flight task notices after a Temporary Chat is discarded", async () => {
const client = new NanobotClient({ url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
const socket = lastSocket();
socket.fakeOpen();
const created = client.newTemporaryChat();
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true });
await created;
const notice = vi.fn();
client.onTaskNotice(notice);
client.sendMessage("temporary", "work", undefined, { turnId: "temporary-turn" });
client.discardTemporaryChat("temporary");
socket.fakeMessage({ event: "turn_end", chat_id: "temporary", turn_id: "temporary-turn" });
expect(notice).not.toHaveBeenCalled();
client.attach("regular");
const event = { event: "turn_end", chat_id: "regular", turn_id: "regular-turn" };
socket.fakeMessage(event);
expect(notice).toHaveBeenCalledWith({ event, temporary: false });
client.close();
});
it("bounds regular replay tails but retains temporary events until discard", async () => {
const client = new NanobotClient({
url: "ws://test", reconnect: false,
+26 -15
View File
@@ -1,12 +1,12 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import { HostNavigationContext } from "@/components/remote/HostSwitcher";
import { AboutSettings, AppearanceSettings } from "@/components/settings/overview/OverviewSettings";
import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
import { VersionCheckRowView } from "@/components/settings/overview/VersionCheckRowView";
import { NanobotClient } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider";
import type { SettingsPayload } from "@/lib/types";
import { DEFAULT_LOCAL_PREFS } from "@/lib/local-preferences";
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, readLocalPreferences, writeLocalPreferences } from "@/lib/local-preferences";
import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
const thirdPartyBrandNotice =
@@ -25,22 +25,33 @@ describe("Settings overview and appearance", () => {
expect(check).toHaveBeenCalledTimes(1);
});
it.each(["granted", "denied"])("updates task notifications only after browser permission is %s", async (permission) => {
const requestPermission = vi.fn().mockResolvedValue(permission);
vi.stubGlobal("Notification", { permission: "default", requestPermission });
const changePreferences = vi.fn();
render(<AppearanceSettings theme="light" onToggleTheme={vi.fn()} localPrefs={DEFAULT_LOCAL_PREFS} onChangeLocalPrefs={changePreferences} />);
fireEvent.click(screen.getByRole("switch", { name: "Task notifications" }));
expect(changePreferences).not.toHaveBeenCalled();
await waitFor(() => expect(requestPermission).toHaveBeenCalledTimes(1));
await act(async () => { await Promise.resolve(); });
if (permission === "granted") {
expect(changePreferences).toHaveBeenCalledTimes(1);
expect(changePreferences.mock.calls[0][0](DEFAULT_LOCAL_PREFS).browserNotifications).toBe(true);
} else expect(changePreferences).not.toHaveBeenCalled();
it("opens the notifications section and preserves independent browser-local channel preferences", () => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });
renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload(), showSidebar: true });
fireEvent.click(screen.getByRole("button", { name: "Notifications" }));
expect(screen.getByRole("switch", { name: "Browser notifications" })).toHaveAttribute("aria-checked", "false");
const sound = screen.getByRole("switch", { name: "Completion sound" });
expect(sound).toHaveAttribute("aria-checked", "true");
fireEvent.click(sound);
expect(readLocalPreferences()).toMatchObject({ browserNotifications: false, notificationSound: false });
});
it.each(["local", "other tab"])("preserves a %s notification opt-out when another preference changes", (source) => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, browserNotifications: true, notificationSound: true });
renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload(), showSidebar: true });
act(() => {
const next = { ...readLocalPreferences(), browserNotifications: false };
if (source === "local") writeLocalPreferences(next);
else {
localStorage.setItem(LOCAL_PREFS_STORAGE_KEY, JSON.stringify(next));
window.dispatchEvent(new StorageEvent("storage", { key: LOCAL_PREFS_STORAGE_KEY }));
}
});
fireEvent.click(screen.getByRole("switch", { name: "Code wrapping" }));
expect(readLocalPreferences()).toMatchObject({ browserNotifications: false, notificationSound: true, codeWrap: false });
});
it("links the host's short commit beside its version", () => {
const commit = "abcdef12".repeat(5);
renderSettingsView({
+27
View File
@@ -152,6 +152,23 @@ describe("browser notification worker", () => {
return reply;
}
it("confirms notification support without displaying a test notification", async () => {
const sw = loadSw();
const reply = await send(sw, { type: "nanobot:notification-probe" });
expect(reply).toHaveBeenCalledWith("ready");
expect(sw.showNotification).not.toHaveBeenCalled();
});
it("returns test clicks to notification settings, including a still-open older page", async () => {
const sw = loadSw();
for (const section of ["notifications", "appearance"]) {
const target = `${ORIGIN}/#/settings?section=${section}`;
expect(await send(sw, { test: true, key: section, url: target })).toHaveBeenCalledWith("submitted");
await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url: target } } });
expect(sw.openWindow).toHaveBeenLastCalledWith(target);
}
});
it("deduplicates concurrent tabs, dismissed notifications, and worker restarts", async () => {
const sw = loadSw();
const replies = await Promise.all([send(sw), send(sw)]);
@@ -201,6 +218,16 @@ describe("browser notification worker", () => {
expect(sw.openWindow).not.toHaveBeenCalled();
});
it("opens the destination when the source closed, even if an older page is still open", async () => {
const sw = loadSw();
const oldTab = { id: "old-page", frameType: "top-level", postMessage: vi.fn(), focus: vi.fn() };
sw.matchClients.mockResolvedValue([oldTab]);
await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url, clientId: "closed" } } });
expect(sw.openWindow).toHaveBeenCalledWith(url);
expect(oldTab.postMessage).not.toHaveBeenCalled();
expect(oldTab.focus).not.toHaveBeenCalled();
});
it("opens the same host with ordinary auth, but cannot restore a closed temporary chat", async () => {
const sw = loadSw();
await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url, clientId: "closed" } } });