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

+23 -7
View File
@@ -1,6 +1,6 @@
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { NOTIFICATION_OPEN_EVENT, notificationChatUrl, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";
import { NOTIFICATION_OPEN_EVENT, notificationChatUrl, reconcileNotificationPermission, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";
import type { NanobotClient } from "@/lib/nanobot-client";
export function BrowserNotifications({ client }: { client: Pick<NanobotClient, "onTaskNotice"> }) {
@@ -17,20 +17,36 @@ export function BrowserNotifications({ client }: { client: Pick<NanobotClient, "
key, url: notificationChatUrl(event.chat_id, notice.temporary),
});
}), [client, t]);
return null;
}
// Permission and click ownership survives authentication and route transitions.
export function useBrowserNotificationLifecycle() {
useEffect(() => {
reconcileNotificationPermission();
window.addEventListener("focus", reconcileNotificationPermission);
document.addEventListener("visibilitychange", reconcileNotificationPermission);
return () => {
window.removeEventListener("focus", reconcileNotificationPermission);
document.removeEventListener("visibilitychange", reconcileNotificationPermission);
};
}, []);
useEffect(() => {
if (!("serviceWorker" in navigator)) return;
const navigate = (event: MessageEvent<unknown>) => {
const data = event.data as { type?: string; url?: unknown } | null;
if (event.source !== navigator.serviceWorker.controller || data?.type !== "nanobot:notification-click" || typeof data.url !== "string") return;
const url = new URL(data.url);
if (url.origin === window.location.origin) {
window.location.hash = url.hash;
window.dispatchEvent(new Event(NOTIFICATION_OPEN_EVENT));
}
let url: URL;
try { url = new URL(data.url); } catch { return; }
if (url.origin !== window.location.origin || url.username || url.password || url.search || url.pathname !== "/") return;
if (!/^#\/(?:chat|temporary)\/[^?]+$/.test(url.hash)
&& url.hash !== "#/settings?section=notifications"
&& url.hash !== "#/settings?section=appearance") return;
window.location.hash = url.hash;
window.dispatchEvent(new Event(NOTIFICATION_OPEN_EVENT));
};
navigator.serviceWorker.addEventListener("message", navigate);
return () => navigator.serviceWorker.removeEventListener("message", navigate);
}, []);
return null;
}
@@ -23,6 +23,7 @@ import {
} from "@/components/settings/models/ProviderSettings";
import { providerFormFromRow } from "@/components/settings/models/providerForm";
import { AboutSettings, AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings";
import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings";
import { SettingsSidebar, standaloneSectionTitle } from "@/components/settings/SettingsSidebar";
import {
NanobotFeatureInstallDialog,
@@ -217,6 +218,8 @@ export function SettingsPage({
);
case "about":
return <AboutSettings settings={settings} />;
case "notifications":
return <NotificationSettings localPrefs={localPrefs} onChangeLocalPrefs={setLocalPrefs} />;
case "appearance":
return (
<AppearanceSettings
@@ -10,7 +10,7 @@ import {
} from "@/components/icons/product-icons";
import { useContext, useRef, useState } from "react";
import { HostNavigationContext, HostSwitcher } from "@/components/remote/HostSwitcher";
import { Check, ChevronDown, ChevronLeft, LogOut, Loader2, type LucideIcon } from "lucide-react";
import { Bell, Check, ChevronDown, ChevronLeft, LogOut, Loader2, type LucideIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
@@ -32,6 +32,7 @@ import { cn } from "@/lib/utils";
const SETTINGS_NAV_ITEMS: Array<{ key: SettingsSectionKey; icon: LucideIcon; fallback: string }> = [
{ key: "overview", icon: OverviewIcon, fallback: "Overview" },
{ key: "appearance", icon: AppearanceIcon, fallback: "Appearance" },
{ key: "notifications", icon: Bell, fallback: "Notifications" },
{ key: "models", icon: ModelsIcon, fallback: "Models" },
{ key: "capabilities", icon: CapabilitiesIcon, fallback: "Capabilities" },
{ key: "runtime", icon: SystemIcon, fallback: "System" },
@@ -6,6 +6,7 @@ export type SettingsSectionKey =
| "overview"
| "about"
| "appearance"
| "notifications"
| "models"
| "capabilities"
| "image"
@@ -0,0 +1,119 @@
import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import { BellRing, Loader2 } from "lucide-react";
import { SettingsRow } from "@/components/settings/shared/SettingsControls";
import { ToggleButton } from "@/components/ui/toggle-button";
import { Button } from "@/components/ui/button";
import { HoverHint } from "@/components/ui/tooltip";
import { enableBrowserNotifications, lastNotificationProblem, NOTIFICATION_STATUS_EVENT, notificationProblem, notificationWorkerProblem, showBrowserNotification, type NotificationResult } from "@/lib/browser-notifications";
import type { LocalPreferences } from "@/lib/local-preferences";
export function BrowserNotificationSettings({ localPrefs, onChangeLocalPrefs }: {
localPrefs: LocalPreferences;
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
}) {
const { t } = useTranslation();
const hintId = useId();
const [problem, setProblem] = useState(notificationProblem);
const [workerProblem, setWorkerProblem] = useState<"workerUnavailable" | null>(null);
const [feedback, setFeedback] = useState<NotificationResult | null>(lastNotificationProblem);
const [busy, setBusy] = useState(false);
const [checking, setChecking] = useState(false);
const operation = useRef(0);
const workerCheck = useRef(0);
const refreshRef = useRef(() => {});
useEffect(() => {
const refresh = () => {
const next = notificationProblem();
setProblem(next);
const id = ++workerCheck.current;
setChecking(!next);
if (!next) {
void notificationWorkerProblem().then((value) => {
if (id === workerCheck.current) {
setWorkerProblem(value);
setChecking(false);
}
});
}
};
refreshRef.current = refresh;
const deliveryStatus = () => { setFeedback(lastNotificationProblem()); refresh(); };
refresh();
window.addEventListener("focus", refresh);
window.addEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);
document.addEventListener("visibilitychange", refresh);
navigator.serviceWorker?.addEventListener("controllerchange", refresh);
return () => {
workerCheck.current++;
window.removeEventListener("focus", refresh);
window.removeEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);
document.removeEventListener("visibilitychange", refresh);
navigator.serviceWorker?.removeEventListener("controllerchange", refresh);
};
}, []);
useEffect(() => () => { operation.current++; }, []);
const granted = typeof Notification !== "undefined" && Notification.permission === "granted";
const enabled = localPrefs.browserNotifications && granted;
const revoked = feedback === "revoked" && typeof Notification !== "undefined" && !granted;
const detail = revoked ? "revoked" : problem || (feedback === "revoked" ? null : feedback) || workerProblem;
const message = busy || checking ? t("settings.notifications.waiting")
: detail && detail !== "skipped" ? t(`settings.notifications.${detail}`) : null;
const canRetry = !!(problem || workerProblem || revoked || feedback === "workerUnavailable");
async function toggle(value: boolean) {
const id = ++operation.current;
setFeedback(null);
if (!value) {
onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: false }));
return;
}
setBusy(true);
const result = await enableBrowserNotifications();
if (id !== operation.current) return;
setBusy(false);
setProblem(notificationProblem());
setWorkerProblem(result === "workerUnavailable" ? result : null);
setFeedback(result);
if (!result) {
onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: true }));
}
}
async function test() {
const id = ++operation.current;
setBusy(true);
const result = await showBrowserNotification(t("settings.notifications.testBody"), {
key: `test:${crypto.randomUUID()}`, url: `${window.location.origin}/#/settings?section=notifications`, test: true,
});
if (id !== operation.current) return;
setBusy(false);
setProblem(notificationProblem());
setFeedback(lastNotificationProblem() ?? result);
}
return <div>
<SettingsRow title={t("settings.rows.browserNotifications")}
description={t("settings.help.browserNotifications")}>
<>
{enabled && <HoverHint content={t("settings.notifications.test")}>
<Button type="button" variant="ghost" size="icon" aria-label={t("settings.notifications.test")}
className="-my-1 me-3 h-11 w-11 shrink-0 text-muted-foreground sm:my-0 sm:h-9 sm:w-9"
disabled={busy || checking || !!problem || !!workerProblem} onClick={() => void test()}>
{busy ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : <BellRing className="h-4 w-4" aria-hidden />}
</Button>
</HoverHint>}
<ToggleButton checked={enabled} disabled={busy || (!!problem && !localPrefs.browserNotifications)}
onChange={(value) => void toggle(value)}
ariaLabel={t("settings.rows.browserNotifications")} aria-describedby={message ? hintId : undefined}
label={t(enabled ? "settings.values.on" : "settings.values.off")} />
</>
</SettingsRow>
<div className={message || canRetry ? "settings-list-inset pb-3 text-[12px] leading-5 text-muted-foreground" : undefined}>
<p id={hintId} role="status" aria-live="polite" aria-atomic="true">{message}</p>
{canRetry && <Button type="button" variant="ghost" size="sm" disabled={busy || checking}
className="-ms-2 mt-1 h-8 rounded-full px-2 text-[12px] text-muted-foreground"
onClick={() => { setFeedback(null); refreshRef.current(); }}>{t("settings.notifications.retry")}</Button>}
</div>
</div>;
}
@@ -0,0 +1,35 @@
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";
import { ToggleButton } from "@/components/ui/toggle-button";
import type { LocalPreferences } from "@/lib/local-preferences";
import { BrowserNotificationSettings } from "./BrowserNotificationSettings";
export function NotificationSettings({ localPrefs, onChangeLocalPrefs }: {
localPrefs: LocalPreferences;
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
}) {
const { t } = useTranslation();
return (
<div className="settings-stack">
<section>
<SettingsSectionTitle>{t("settings.notifications.scope")}</SettingsSectionTitle>
<SettingsGroup>
<BrowserNotificationSettings localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs} />
<div className="settings-list-inset" aria-hidden="true">
<div className="border-t border-border/40" />
</div>
<SettingsRow title={t("settings.rows.notificationSound")} description={t("settings.help.notificationSound")}>
<ToggleButton checked={localPrefs.notificationSound}
onChange={(notificationSound) => onChangeLocalPrefs((previous) => ({ ...previous, notificationSound }))}
ariaLabel={t("settings.rows.notificationSound")}
label={t(localPrefs.notificationSound ? "settings.values.on" : "settings.values.off")} />
</SettingsRow>
</SettingsGroup>
<p className="settings-list-inset mt-3 text-[12px] leading-5 text-muted-foreground">
{t("settings.notifications.pageRequired")}
</p>
</section>
</div>
);
}
@@ -2,7 +2,6 @@ import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { BrowserNotificationSettings } from "./BrowserNotificationSettings";
import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";
import { ToggleButton } from "@/components/ui/toggle-button";
import { SegmentedControl } from "@/components/ui/segmented-control";
@@ -101,24 +100,6 @@ export function AppearanceSettingsView({
label={localPrefs.brandLogos ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
</SettingsRow>
<BrowserNotificationSettings localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs} />
<SettingsRow
title={tx("settings.rows.notificationSound", "Completion sound")}
description={tx(
"settings.help.notificationSound",
"Play a short chime when a turn finishes, even when this page is in the background. Off by default.",
)}
>
<ToggleButton
checked={localPrefs.notificationSound}
onChange={(notificationSound) =>
onChangeLocalPrefs((prev) => ({ ...prev, notificationSound }))}
ariaLabel={tx("settings.rows.notificationSound", "Completion sound")}
label={localPrefs.notificationSound
? tx("settings.values.on", "On")
: tx("settings.values.off", "Off")}
/>
</SettingsRow>
</SettingsGroup>
</section>
</div>
@@ -1,76 +0,0 @@
import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings/shared/SettingsControls";
import { ToggleButton } from "@/components/ui/toggle-button";
import { Button } from "@/components/ui/button";
import { enableBrowserNotifications, lastNotificationProblem, NOTIFICATION_STATUS_EVENT, notificationProblem, showBrowserNotification, type NotificationResult } from "@/lib/browser-notifications";
import type { LocalPreferences } from "@/lib/local-preferences";
export function BrowserNotificationSettings({ localPrefs, onChangeLocalPrefs }: {
localPrefs: LocalPreferences;
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
}) {
const { t } = useTranslation();
const hintId = useId();
const [problem, setProblem] = useState(notificationProblem);
const [feedback, setFeedback] = useState<NotificationResult | null>(lastNotificationProblem);
const [busy, setBusy] = useState(false);
const operation = useRef(0);
useEffect(() => {
const refresh = () => {
setProblem(notificationProblem());
setFeedback((current) => current === "submitted" || current === "displayFailed" || current === "workerUnavailable" ? current : null);
};
const deliveryStatus = () => setFeedback(lastNotificationProblem());
window.addEventListener("focus", refresh);
window.addEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);
document.addEventListener("visibilitychange", refresh);
return () => {
operation.current++;
window.removeEventListener("focus", refresh);
window.removeEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);
document.removeEventListener("visibilitychange", refresh);
};
}, []);
const enabled = localPrefs.browserNotifications && !problem && Notification.permission === "granted";
const status = problem || feedback || (localPrefs.browserNotifications && !enabled ? "dismissed" : null);
async function toggle(value: boolean) {
const id = ++operation.current;
setFeedback(null);
if (!value) {
onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: false }));
return;
}
setBusy(true);
const result = await enableBrowserNotifications();
if (id !== operation.current) return;
setBusy(false);
setProblem(notificationProblem());
setFeedback(result);
if (!result) onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: true }));
}
async function test() {
const id = ++operation.current;
setBusy(true);
const result = await showBrowserNotification(t("settings.notifications.testBody"), {
key: `test:${crypto.randomUUID()}`, url: `${window.location.origin}/#/settings?section=appearance`, test: true,
});
if (id !== operation.current) return;
setBusy(false);
setProblem(notificationProblem());
setFeedback(result);
}
return <div>
<SettingsRow title={t("settings.rows.browserNotifications")}>
<ToggleButton checked={localPrefs.browserNotifications} disabled={busy || (!!problem && !localPrefs.browserNotifications)}
onChange={(value) => void toggle(value)}
ariaLabel={t("settings.rows.browserNotifications")} aria-describedby={hintId}
label={t(localPrefs.browserNotifications ? "settings.values.on" : "settings.values.off")} />
</SettingsRow>
<div id={hintId} className="px-[var(--settings-inset,16px)] pb-4 text-[12px] leading-5 text-muted-foreground">
<p>{t("settings.help.browserNotifications")}</p>
<p role="status" aria-live="polite">{busy ? t("settings.notifications.waiting") : status && status !== "skipped" ? t(`settings.notifications.${status}`) : null}</p>
{enabled && <Button variant="ghost" size="sm" className="mt-1 h-8 px-2 text-xs" disabled={busy} onClick={() => void test()}>{t("settings.notifications.test")}</Button>}
</div>
</div>;
}
@@ -23,7 +23,7 @@ function Row({ control }: { control: Control }) {
<div className="settings-control">
{control === "feature" ? <div className={cn(block, "mr-3 h-3 w-14")} /> : null}
{control === "duration" ? <div className="w-full"><div className={cn(block, "h-9 w-full rounded-full")} /><div className="mt-1.5 flex h-4 items-center"><div className={cn(block, "h-2.5 w-4/5 opacity-60")} /></div></div> : <div data-skeleton-switch={toggle ? "" : undefined} className={cn(block,
toggle ? "h-5 w-[38px] shrink-0 rounded-full" : control === "input" ? "h-9 w-full rounded-full"
toggle ? "h-5 w-9 shrink-0 rounded-full" : control === "input" ? "h-9 w-full rounded-full"
: control === "segments" || control === "theme" ? "segmented-control w-44 rounded-full" : control === "edit" ? "ml-auto h-9 w-9 rounded-full" : "h-[19.5px] w-24",
control === "segments" && "h-[34px]", control === "theme" && "h-8",
)} />}
@@ -52,7 +52,14 @@ export function SettingsSectionSkeleton({ section, showRestart = false }: { sect
</>;
else switch (section) {
case "appearance":
content = <><Group controls={["theme", "input"]} /><Group controls={["segments", "segments", "switch", "switch", "switch", "switch"]} /></>;
content = <><Group controls={["theme", "input"]} /><Group controls={["segments", "segments", "switch", "switch"]} /></>;
break;
case "notifications":
content = <section><Title /><SettingsGroup>
<Row control="switch" />
<div className="settings-list-inset" aria-hidden="true"><div className="border-t border-border/40" /></div>
<Row control="switch" />
</SettingsGroup><p className="settings-list-inset mt-3 text-[12px] leading-5"><span className={cn(block, "text-transparent")}>{t("settings.notifications.pageRequired")}</span></p></section>;
break;
case "overview":
content = <>
@@ -37,6 +37,7 @@ import { usePageVisibility } from "@/hooks/usePageVisibility";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api";
import {
LOCAL_PREFS_CHANGED_EVENT,
readLocalPreferences,
writeLocalPreferences,
type LocalPreferences,
@@ -257,6 +258,18 @@ export function useSettingsController({
pageVisible,
});
useEffect(() => {
const synchronize = (event: Event) => setLocalPrefs((event as CustomEvent<LocalPreferences>).detail);
const reload = () => setLocalPrefs(readLocalPreferences());
window.addEventListener(LOCAL_PREFS_CHANGED_EVENT, synchronize);
window.addEventListener("storage", reload);
window.addEventListener("focus", reload);
return () => {
window.removeEventListener(LOCAL_PREFS_CHANGED_EVENT, synchronize);
window.removeEventListener("storage", reload);
window.removeEventListener("focus", reload);
};
}, []);
useEffect(() => {
writeLocalPreferences(localPrefs);
}, [localPrefs]);