fix(webui): make browser notification failures actionable

This commit is contained in:
Xubin Ren authored and chengyongru committed 2026-10-20 13:45:04 +08:00
1 parent 909b277e7a
commit 7b2af031c0
30 files changed
+919 -96

No files matched your search

+1
View File
@@ -246,6 +246,7 @@ vi.mock("@/lib/bootstrap", () => ({
vi.mock("@/lib/nanobot-client", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/nanobot-client")>();
class MockClient {
onTaskNotice = () => () => {};
status = "idle" as const;
defaultChatId = mockDefaultChatId;
sendSystemCommand = sendSystemCommandSpy;
@@ -0,0 +1,232 @@
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 { enableBrowserNotifications, NOTIFICATION_OPEN_EVENT, notificationChatUrl, notificationProblem, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";
import { DEFAULT_LOCAL_PREFS, writeLocalPreferences } from "@/lib/local-preferences";
import type { TaskNotice } from "@/lib/nanobot-client";
import i18n from "@/i18n";
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} />;
}
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; }); }
});
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");
Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, browserNotifications: true });
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
vi.restoreAllMocks();
vi.clearAllMocks();
vi.useRealTimers();
delete (navigator as unknown as { serviceWorker?: unknown }).serviceWorker;
Reflect.deleteProperty(document, "visibilityState");
localStorage.clear();
});
describe("notification permission and delivery boundary", () => {
it("distinguishes insecure contexts, missing APIs, and browser denial", () => {
vi.stubGlobal("isSecureContext", false);
expect(notificationProblem()).toBe("insecure");
vi.stubGlobal("isSecureContext", true); // Includes localhost, decided by the browser.
vi.stubGlobal("Notification", undefined);
expect(notificationProblem()).toBe("unsupported");
vi.stubGlobal("Notification", { permission: "denied" });
expect(notificationProblem()).toBe("denied");
});
it.each(["default", "denied"])("reports a permission response of %s", async (permission) => {
requestPermission.mockResolvedValue(permission);
expect(await enableBrowserNotifications()).toBe(permission === "default" ? "dismissed" : "denied");
});
it("requests permission synchronously from the user gesture and requires an active worker", async () => {
const enabling = enableBrowserNotifications();
expect(requestPermission).toHaveBeenCalledTimes(1);
expect(await enabling).toBeNull();
getRegistration.mockResolvedValue({ installing: worker });
expect(await enableBrowserNotifications()).toBe("workerUnavailable");
});
it("handles permission and registration failures without rejected promises", async () => {
requestPermission.mockRejectedValue(new Error("permission blocked"));
expect(await enableBrowserNotifications()).toBe("permissionFailed");
requestPermission.mockResolvedValue("granted");
getRegistration.mockRejectedValue(new Error("storage blocked"));
expect(await enableBrowserNotifications()).toBe("workerUnavailable");
});
it("bounds registration and worker response waits", async () => {
vi.useFakeTimers();
vi.stubGlobal("Notification", { permission: "granted" });
getRegistration.mockImplementationOnce(() => new Promise(() => {}));
const enabling = enableBrowserNotifications();
await vi.advanceTimersByTimeAsync(5_001);
expect(await enabling).toBe("workerUnavailable");
postMessage.mockImplementation(() => {});
const showing = showBrowserNotification("Task completed", { key: "one", url: notificationChatUrl("one", false) });
await vi.advanceTimersByTimeAsync(5_001);
expect(await showing).toBe("displayFailed");
});
it("uses the worker without constructing Notification, and isolates a post failure", async () => {
const constructor = vi.fn(() => { throw new TypeError("Mobile constructor unavailable"); });
vi.stubGlobal("Notification", Object.assign(constructor, { permission: "granted" }));
const options = { key: "one", url: notificationChatUrl("one", false) };
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");
});
it("does not notify while visible, disabled, or disabled during a lookup", async () => {
vi.stubGlobal("Notification", { permission: "granted" });
const options = { key: "one", url: notificationChatUrl("one", false) };
Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" });
expect(await showBrowserNotification("Task completed", options)).toBe("skipped");
Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });
let finish!: (registration: unknown) => void;
getRegistration.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const pending = showBrowserNotification("Task completed", options);
writeLocalPreferences(DEFAULT_LOCAL_PREFS);
finish({ active: worker });
expect(await pending).toBe("skipped");
expect(await showBrowserNotification("Task completed", options)).toBe("skipped");
expect(postMessage).not.toHaveBeenCalled();
});
it("keeps links on this gateway without copying query credentials", () => {
window.history.replaceState(null, "", "/?token=secret#/chat/old");
expect(notificationChatUrl("a/b", false)).toBe(`${window.location.origin}/#/chat/websocket%3Aa%2Fb`);
expect(notificationChatUrl("temp", true)).toBe(`${window.location.origin}/#/temporary/temp`);
window.history.replaceState(null, "", "/");
});
});
describe("notification settings", () => {
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");
});
it("reports dismissal and lets the user retry, test, and disable", async () => {
requestPermission.mockResolvedValueOnce("default").mockImplementationOnce(() => {
vi.stubGlobal("Notification", { permission: "granted", requestPermission });
return Promise.resolve("granted");
});
render(<Harness />);
const toggle = screen.getByRole("switch", { name: "Browser notifications" });
fireEvent.click(toggle);
await screen.findByText("Permission was not granted. Turn on notifications and choose Allow.");
expect(toggle).toHaveAttribute("aria-checked", "false");
fireEvent.click(toggle);
await waitFor(() => expect(toggle).toHaveAttribute("aria-checked", "true"));
fireEvent.click(screen.getByRole("button", { name: "Test notification" }));
await screen.findByText(/Sent to the browser/);
fireEvent.click(toggle);
expect(toggle).toHaveAttribute("aria-checked", "false");
expect(screen.queryByRole("button", { name: "Test notification" })).not.toBeInTheDocument();
});
it("updates revoked permission on return and still allows opt-out", () => {
vi.stubGlobal("Notification", { permission: "granted" });
render(<Harness enabled />);
vi.stubGlobal("Notification", { permission: "denied" });
fireEvent.focus(window);
expect(screen.getByRole("status")).toHaveTextContent("Notifications are blocked");
expect(screen.queryByRole("button", { name: "Test notification" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("switch"));
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");
});
it("does not save late permission results after leaving settings", async () => {
let resolve!: (permission: string) => void;
requestPermission.mockImplementation(() => new Promise((done) => { resolve = done; }));
const save = vi.fn();
const { unmount } = render(<BrowserNotificationSettings localPrefs={DEFAULT_LOCAL_PREFS} onChangeLocalPrefs={save} />);
fireEvent.click(screen.getByRole("switch"));
unmount();
await act(async () => { resolve("granted"); });
expect(save).not.toHaveBeenCalled();
});
});
it("subscribes outside a chat, uses generic localized text, and cleans up", async () => {
vi.stubGlobal("Notification", { permission: "granted" });
await i18n.changeLanguage("zh-CN");
let handler!: (notice: TaskNotice) => void;
const unsubscribe = vi.fn();
const client = { onTaskNotice: (value: typeof handler) => { handler = value; return unsubscribe; } };
const { unmount } = render(<BrowserNotifications client={client} />);
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(JSON.stringify(postMessage.mock.calls[0][0])).not.toContain("PRIVATE TOKEN");
expect(taskNoticeKey({ event, temporary: false })).toBe('["other","turn","end"]');
unmount();
expect(unsubscribe).toHaveBeenCalledOnce();
});
it("does not report cancellation or interruption as completion", async () => {
vi.stubGlobal("Notification", { permission: "granted" });
await i18n.changeLanguage("en");
let handler!: (notice: TaskNotice) => void;
const client = { onTaskNotice: (value: typeof handler) => { handler = value; return () => {}; } };
render(<BrowserNotifications client={client} />);
const event = { event: "turn_end", chat_id: "one", turn_id: "turn", outcome: "cancelled" } as const;
handler({ event, temporary: false });
expect(taskNoticeKey({ event, temporary: false })).toBeNull();
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." });
});
it("opens a notification only from the controlling worker and reveals the owning host", () => {
const client = { onTaskNotice: () => () => {} };
render(<BrowserNotifications client={client} />);
const reveal = vi.fn();
window.addEventListener(NOTIFICATION_OPEN_EVENT, reveal);
const url = notificationChatUrl("clicked", false);
const send = (source: unknown, target: string) => navigator.serviceWorker.dispatchEvent(new MessageEvent("message", {
source: source as Window, data: { type: "nanobot:notification-click", url: target },
}));
send(window, url);
send(worker, "https://wrong-host.example/#/chat/other");
expect(reveal).not.toHaveBeenCalled();
send(worker, url);
expect(window.location.hash).toBe("#/chat/websocket%3Aclicked");
expect(reveal).toHaveBeenCalledOnce();
window.removeEventListener(NOTIFICATION_OPEN_EVENT, reveal);
window.history.replaceState(null, "", "/");
});
it("keys recovery alerts by recovery identity, not by chat mounting", () => {
const event = { event: "recovery_state", chat_id: "one", recovery_id: "attempt", status: "awaiting_user" } as const;
expect(taskNoticeKey({ event, temporary: false })).toBe('["one","attempt","awaiting_user"]');
expect(taskNoticeKey({ event: { ...event, status: "recovered" }, temporary: false })).toBeNull();
});
+14 -2
View File
@@ -19,13 +19,13 @@ function addFrame() {
function send(source: Window, data: Record<string, unknown>, from = origin) {
act(() => { window.dispatchEvent(new MessageEvent("message", { source, origin: from, data: { channel: HOST_BRIDGE, ...data } })); });
}
function parentView() {
function parentView(onReveal?: (id: string) => void) {
const node = addFrame();
const source = node.contentWindow!;
const post = vi.spyOn(source, "postMessage").mockImplementation(() => {});
const nodes = { current: new Map([["host-a", node]]) };
const restore = vi.fn();
const hook = renderHook(({ selectedId }) => useSidebarHostBridge([makeFrame()], selectedId, nodes, restore, {}), {
const hook = renderHook(({ selectedId }) => useSidebarHostBridge([makeFrame()], selectedId, nodes, restore, {}, false, undefined, onReveal), {
initialProps: { selectedId: "host-a" as string | undefined },
});
send(source, { type: "hello" });
@@ -35,6 +35,18 @@ function parentView() {
afterEach(() => { cleanup(); document.querySelectorAll("iframe").forEach((node) => node.remove()); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
describe("sidebar host bridge", () => {
it("reveals only the notification sender's existing host with a verified peer", () => {
const reveal = vi.fn();
const { source, init, rerender } = parentView(reveal);
rerender({ selectedId: undefined });
send(source, { type: "reveal-notification", nonce: "wrong" });
send(window, { type: "reveal-notification", nonce: init.nonce });
send(source, { type: "reveal-notification", nonce: init.nonce }, "https://attacker.example");
expect(reveal).not.toHaveBeenCalled();
send(source, { type: "reveal-notification", nonce: init.nonce, id: "another-host", url: "https://attacker.example" });
expect(reveal).toHaveBeenCalledOnce();
expect(reveal).toHaveBeenCalledWith("host-a");
});
it("sends only current display identity, never secrets, profiles or filesystem paths", () => {
const { post, init } = parentView();
expect(post).toHaveBeenCalledWith(expect.objectContaining({ type: "init", name: "Team server", hostname: "team-host" }), origin);
+13
View File
@@ -43,6 +43,19 @@ beforeEach(() => {
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
describe("host session lifecycle", () => {
it("reveals only a loaded live view for notifications, without connecting", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
await ready(result, 1);
mocks.request.mockClear();
act(() => { expect(result.current.reveal(ids[0])).toBe(true); });
expect(result.current.selected?.id).toBe(ids[0]);
act(() => { expect(result.current.reveal(ids[3])).toBe(false); });
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) => ({ ...p, connected: false })) });
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
act(() => { expect(result.current.reveal(ids[1])).toBe(false); });
expect(mocks.request).not.toHaveBeenCalled();
});
it("clears a failed reconnect only after that host's loaded view recovers", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
+14
View File
@@ -178,6 +178,20 @@ const LOCALIZED_SETTINGS_COPY_KEYS = [
"settings.help.codeWrap",
"settings.help.brandLogos",
"settings.help.browserNotifications",
"settings.notifications.test",
"settings.notifications.testBody",
"settings.notifications.waiting",
"settings.notifications.insecure",
"settings.notifications.unsupported",
"settings.notifications.denied",
"settings.notifications.dismissed",
"settings.notifications.permissionFailed",
"settings.notifications.workerUnavailable",
"settings.notifications.displayFailed",
"settings.notifications.submitted",
"settings.notifications.completed",
"settings.notifications.failed",
"settings.notifications.interrupted",
"settings.help.notificationSound",
"settings.help.currentModel",
"settings.help.localServiceAccess",
+17
View File
@@ -71,6 +71,23 @@ afterEach(() => {
});
describe("NanobotClient", () => {
it("emits live task notices without mounted chats, not when the chat replays", () => {
const client = new NanobotClient({ url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
lastSocket().fakeOpen();
const broken = client.onTaskNotice(() => { throw new Error("optional notification failed"); });
const notice = vi.fn();
const unsubscribe = client.onTaskNotice(notice);
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);
expect(replay).toHaveBeenCalledWith(event);
expect(notice).toHaveBeenCalledOnce();
broken(); unsubscribe(); client.close();
});
it("bounds regular replay tails but retains temporary events until discard", async () => {
const client = new NanobotClient({
url: "ws://test", reconnect: false,
+83 -2
View File
@@ -49,17 +49,25 @@ interface LoadedSw {
fetchMock: ReturnType<typeof vi.fn>;
skipWaitingMock: ReturnType<typeof vi.fn>;
claimMock: ReturnType<typeof vi.fn>;
showNotification: ReturnType<typeof vi.fn>;
matchClients: ReturnType<typeof vi.fn>;
openWindow: ReturnType<typeof vi.fn>;
noticeStore: FakeCacheStore;
fire: (type: string, event?: Record<string, unknown>) => Promise<void>;
}
function loadSw(): LoadedSw {
function loadSw(noticeStore = new FakeCacheStore()): LoadedSw {
const listeners = new Map<string, Array<(event: Record<string, unknown>) => void>>();
const skipWaitingMock = vi.fn();
const claimMock = vi.fn();
const showNotification = vi.fn().mockResolvedValue(undefined);
const matchClients = vi.fn().mockResolvedValue([]);
const openWindow = vi.fn().mockResolvedValue(null);
const self = {
location: { origin: ORIGIN },
skipWaiting: skipWaitingMock,
clients: { claim: claimMock },
clients: { claim: claimMock, matchAll: matchClients, openWindow },
registration: { showNotification },
addEventListener: (type: string, cb: (event: Record<string, unknown>) => void) => {
listeners.set(type, [...(listeners.get(type) ?? []), cb]);
},
@@ -69,6 +77,7 @@ function loadSw(): LoadedSw {
const stores = new Map<string, FakeCacheStore>([
[CACHE_NAME, store],
[ICON_CACHE_NAME, iconStore],
["nanobot-notification-receipts-v1", noticeStore],
]);
const deletedCacheNames: string[] = [];
const caches = {
@@ -125,10 +134,82 @@ function loadSw(): LoadedSw {
fetchMock,
skipWaitingMock,
claimMock,
showNotification,
matchClients,
openWindow,
noticeStore,
fire,
};
}
describe("browser notification worker", () => {
const source = { id: "tab-1", url: `${ORIGIN}/?token=private` };
const url = `${ORIGIN}/#/chat/websocket%3Aone`;
const data = { type: "nanobot:notify", key: "turn-1", body: "Task completed", url };
async function send(sw: LoadedSw, overrides = {}) {
const reply = vi.fn();
await sw.fire("message", { data: { ...data, ...overrides }, source, ports: [{ postMessage: reply }] });
return reply;
}
it("deduplicates concurrent tabs, dismissed notifications, and worker restarts", async () => {
const sw = loadSw();
const replies = await Promise.all([send(sw), send(sw)]);
expect(sw.showNotification).toHaveBeenCalledOnce();
expect(replies[0]).toHaveBeenCalledWith("submitted");
expect(replies[1]).toHaveBeenCalledWith("skipped");
const restarted = loadSw(sw.noticeStore);
expect(await send(restarted)).toHaveBeenCalledWith("skipped");
expect(restarted.showNotification).not.toHaveBeenCalled();
expect(sw.showNotification).toHaveBeenCalledWith("nanobot", expect.objectContaining({
body: "Task completed", data: { url, clientId: "tab-1" },
}));
});
it("isolates display rejection, then allows a later test or task", async () => {
const sw = loadSw();
sw.showNotification.mockRejectedValueOnce(new TypeError("unsupported display"));
expect(await send(sw)).toHaveBeenCalledWith("displayFailed");
expect(await send(sw)).toHaveBeenCalledWith("submitted");
});
it("suppresses background tabs if another tab on the host is visible, but permits testing", async () => {
const sw = loadSw();
sw.matchClients.mockResolvedValue([{ visibilityState: "visible" }]);
expect(await send(sw)).toHaveBeenCalledWith("skipped");
expect(sw.showNotification).not.toHaveBeenCalled();
expect(await send(sw, { key: "test-1", test: true })).toHaveBeenCalledWith("submitted");
});
it.each(["https://evil.test/#/chat/one", `${ORIGIN}/?token=secret#/chat/one`, `${ORIGIN}/admin`, `https://user:pass@nanobot.test/#/chat/one`])("rejects an unsafe destination %s", async (unsafe) => {
const sw = loadSw();
expect(await send(sw, { url: unsafe })).toHaveBeenCalledWith("displayFailed");
await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url: unsafe } } });
expect(sw.showNotification).not.toHaveBeenCalled();
expect(sw.openWindow).not.toHaveBeenCalled();
});
it("focuses the original tab without reloading its connection or drafts", async () => {
const sw = loadSw();
const tab = { id: "tab-1", frameType: "top-level", postMessage: vi.fn(), focus: vi.fn().mockResolvedValue(null) };
sw.matchClients.mockResolvedValue([tab]);
const close = vi.fn();
await sw.fire("notificationclick", { notification: { close, data: { url, clientId: "tab-1" } } });
expect(close).toHaveBeenCalledOnce();
expect(tab.postMessage).toHaveBeenCalledWith({ type: "nanobot:notification-click", url });
expect(tab.focus).toHaveBeenCalledOnce();
expect(sw.openWindow).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" } } });
expect(sw.openWindow).toHaveBeenCalledWith(url);
await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url: `${ORIGIN}/#/temporary/one`, clientId: "closed" } } });
expect(sw.openWindow).toHaveBeenLastCalledWith("/#/new");
});
});
function indexHtml(assetPaths: string[]): Response {
const refs = assetPaths
.map(