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

@@ -0,0 +1,36 @@
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { NOTIFICATION_OPEN_EVENT, notificationChatUrl, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";
import type { NanobotClient } from "@/lib/nanobot-client";
export function BrowserNotifications({ client }: { client: Pick<NanobotClient, "onTaskNotice"> }) {
const { t } = useTranslation();
useEffect(() => client.onTaskNotice((notice) => {
const key = taskNoticeKey(notice);
if (!key) return;
const event = notice.event;
const outcome = event.event === "turn_end"
? event.outcome === "failed" ? "failed" : event.outcome === "interrupted" ? "interrupted" : "completed"
: event.status === "failed" ? "failed" : "interrupted";
// Never expose conversation text, titles, model errors, or paths on a lock screen.
void showBrowserNotification(t(`settings.notifications.${outcome}`), {
key, url: notificationChatUrl(event.chat_id, notice.temporary),
});
}), [client, t]);
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));
}
};
navigator.serviceWorker.addEventListener("message", navigate);
return () => navigator.serviceWorker.removeEventListener("message", navigate);
}, []);
return null;
}
@@ -11,6 +11,7 @@ import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker }
import { useSidebarHostBridge } from "./useSidebarHostBridge";
import { readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { RemoteContext, type HostConnectionState } from "./remote-context";
import { NOTIFICATION_OPEN_EVENT } from "@/lib/browser-notifications";
/** Keep host views alive; navigation belongs in each view's sidebar, not a second header. */
export function RemoteInstances({ children }: { children: ReactNode }) {
@@ -34,7 +35,16 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
if (lastLocalFocus.current?.isConnected) lastLocalFocus.current.focus({ preventScroll: true });
};
const message = error ? t(`remote.errors.${error}`, { defaultValue: t("remote.errors.unknown") }) : "";
const bridge = useSidebarHostBridge(frames, selected?.id, frameNodes, restoreLocalFocus, { pendingName: pending?.name, error: message }, managing, () => changeManagement(false));
const bridge = useSidebarHostBridge(frames, selected?.id, frameNodes, restoreLocalFocus, { pendingName: pending?.name, error: message }, managing, () => changeManagement(false), (id) => {
if (hosts.reveal(id)) changeManagement(false);
});
useEffect(() => {
const revealLocal = () => {
if (window.parent === window) { returnLocal(); setManaging(false); }
};
window.addEventListener(NOTIFICATION_OPEN_EVENT, revealLocal);
return () => window.removeEventListener(NOTIFICATION_OPEN_EVENT, revealLocal);
}, [returnLocal]);
useEffect(() => {
if (!managing || !selected || !bridge.surface?.theme) return;
// Management is drawn by the local shell, beside this host's sidebar.
@@ -58,6 +58,13 @@ export function useHostSessions() {
publish();
}, [publish]);
const local = useCallback(() => { cancel(); select(null); }, [cancel, select]);
// A notification may reveal its existing view, never reconnect a host.
const reveal = useCallback((id: string) => {
const frame = cache.current.get(id);
if (!frame?.loaded || frame.offline) return false;
cancel(); select(frame.connection);
return true;
}, [cancel, select]);
const applyDirectory = useCallback((next: RemoteDirectory) => {
setDirectory(next); setDirectoryError(false);
// Names are metadata, not a new host session. Keep iframe URLs, drafts,
@@ -263,5 +270,5 @@ export function useHostSessions() {
};
}, [applyDirectory, client, getToken, publish]);
return { directory, directoryError, refresh, rename, selected, recentIds, frames, pending,
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, remove, loaded };
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, reveal, disconnect, remove, loaded };
}
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { HOST_BRIDGE, bridgeMessage, isLocalShellOrigin, readEmbeddedHost, readHostAnchor, type EmbeddedHost, type HostAnchor } from "./host-bridge";
import type { HostFrame } from "./useHostSessions";
import { NOTIFICATION_OPEN_EVENT } from "@/lib/browser-notifications";
interface Peer { source: Window; origin: string; nonce: string }
export function useSidebarHostBridge(frames: HostFrame[], selectedId: string | undefined,
nodes: RefObject<Map<string, HTMLIFrameElement>>, restoreLocalFocus: () => void,
activity: { pendingName?: string; error?: string }, managing = false, onLeaveManagement?: () => void) {
activity: { pendingName?: string; error?: string }, managing = false, onLeaveManagement?: () => void, onReveal?: (id: string) => void) {
const [embedded, setEmbedded] = useState<EmbeddedHost | null>(null);
const [readyIds, setReadyIds] = useState<string[]>([]);
const [anchor, setAnchor] = useState<HostAnchor | null>(null);
@@ -13,8 +14,8 @@ export function useSidebarHostBridge(frames: HostFrame[], selectedId: string | u
const [hostedManagement, setHostedManagement] = useState(false);
const parent = useRef<Peer | null>(null);
const peers = useRef(new Map<string, Peer>());
const latest = useRef({ frames, selectedId, restoreLocalFocus, activity, managing, onLeaveManagement });
latest.current = { frames, selectedId, restoreLocalFocus, activity, managing, onLeaveManagement };
const latest = useRef({ frames, selectedId, restoreLocalFocus, activity, managing, onLeaveManagement, onReveal });
latest.current = { frames, selectedId, restoreLocalFocus, activity, managing, onLeaveManagement, onReveal };
const initialize = useCallback((id: string) => {
const frame = latest.current.frames.find((item) => item.connection.id === id);
const source = nodes.current?.get(id)?.contentWindow;
@@ -70,13 +71,25 @@ export function useSidebarHostBridge(frames: HostFrame[], selectedId: string | u
if (rect && rect.left >= 0 && rect.top >= 0) setSurfaces((previous) => ({ ...previous, [id]: { ...rect, theme } }));
} else if (message.type === "leave-management" && latest.current.selectedId === id) {
latest.current.onLeaveManagement?.();
} else if (message.type === "reveal-notification" && frame.loaded && !frame.offline) {
// Source/origin/nonce above select only this already-open view. No
// requested host id, destination URL, or connection command is accepted.
latest.current.onReveal?.(id);
}
// No select/connect/disconnect action is accepted from an embedded page.
};
window.addEventListener("message", receive);
const revealNotification = () => {
const peer = parent.current;
if (peer) window.parent.postMessage({ channel: HOST_BRIDGE, type: "reveal-notification", nonce: peer.nonce }, peer.origin);
};
window.addEventListener(NOTIFICATION_OPEN_EVENT, revealNotification);
// A public capability probe carries no identity, settings or credentials.
if (window.parent !== window) window.parent.postMessage({ channel: HOST_BRIDGE, type: "hello" }, "*");
return () => window.removeEventListener("message", receive);
return () => {
window.removeEventListener("message", receive);
window.removeEventListener(NOTIFICATION_OPEN_EVENT, revealNotification);
};
}, [initialize, nodes]);
useEffect(() => { setAnchor(null); }, [selectedId]);
const selectedName = frames.find((frame) => frame.connection.id === selectedId)?.connection.name;
@@ -2,6 +2,7 @@ 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";
@@ -12,13 +13,11 @@ export function AppearanceSettingsView({
onToggleTheme,
localPrefs,
onChangeLocalPrefs,
onChangeBrowserNotifications,
}: {
theme: "light" | "dark";
onToggleTheme: () => void;
localPrefs: LocalPreferences;
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
onChangeBrowserNotifications: (enabled: boolean) => void;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
@@ -102,22 +101,7 @@ export function AppearanceSettingsView({
label={localPrefs.brandLogos ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
</SettingsRow>
<SettingsRow
title={tx("settings.rows.browserNotifications", "Task notifications")}
description={tx(
"settings.help.browserNotifications",
"Notify only when this page is in the background. Off by default.",
)}
>
<ToggleButton
checked={localPrefs.browserNotifications}
onChange={onChangeBrowserNotifications}
ariaLabel={tx("settings.rows.browserNotifications", "Task notifications")}
label={localPrefs.browserNotifications
? 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(
@@ -0,0 +1,76 @@
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>;
}
@@ -192,25 +192,8 @@ export function AppearanceSettings({ theme, onToggleTheme, localPrefs, onChangeL
localPrefs: LocalPreferences;
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
}) {
const changeBrowserNotifications = (enabled: boolean) => {
if (!enabled) {
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: false }));
return;
}
if (typeof Notification === "undefined") return;
if (Notification.permission === "granted") {
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
return;
}
void Notification.requestPermission().then((permission) => {
if (permission === "granted") {
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
}
});
};
return <AppearanceSettingsView theme={theme} onToggleTheme={onToggleTheme}
localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs}
onChangeBrowserNotifications={changeBrowserNotifications} />;
localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs} />;
}
function OverviewRowIcon({