From 7b2af031c0e4cfdb02bfe9c92c81d14af25750f7 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:00:37 +0800 Subject: [PATCH] fix(webui): make browser notification failures actionable --- docs/guides/ai-agent-webui.md | 26 ++ webui/public/sw.js | 71 ++++++ webui/src/App.tsx | 2 + webui/src/components/BrowserNotifications.tsx | 36 +++ .../src/components/remote/RemoteInstances.tsx | 12 +- .../src/components/remote/useHostSessions.ts | 9 +- .../components/remote/useSidebarHostBridge.ts | 21 +- .../overview/AppearanceSettingsView.tsx | 20 +- .../overview/BrowserNotificationSettings.tsx | 76 ++++++ .../settings/overview/OverviewSettings.tsx | 19 +- webui/src/hooks/useNanobotStream.ts | 30 --- webui/src/i18n/locales/en/common.json | 20 +- webui/src/i18n/locales/es/common.json | 20 +- webui/src/i18n/locales/fr/common.json | 20 +- webui/src/i18n/locales/id/common.json | 20 +- webui/src/i18n/locales/ja/common.json | 20 +- webui/src/i18n/locales/ko/common.json | 20 +- webui/src/i18n/locales/pt-BR/common.json | 20 +- webui/src/i18n/locales/vi/common.json | 20 +- webui/src/i18n/locales/zh-CN/common.json | 20 +- webui/src/i18n/locales/zh-TW/common.json | 20 +- webui/src/lib/browser-notifications.ts | 97 ++++++++ webui/src/lib/nanobot-client.ts | 18 ++ webui/src/tests/app-layout.test.tsx | 1 + .../src/tests/browser-notifications.test.tsx | 232 ++++++++++++++++++ webui/src/tests/host-bridge.test.tsx | 16 +- webui/src/tests/host-sessions.test.tsx | 13 + webui/src/tests/i18n.test.tsx | 14 ++ webui/src/tests/nanobot-client.test.ts | 17 ++ webui/src/tests/sw.test.ts | 85 ++++++- 30 files changed, 919 insertions(+), 96 deletions(-) create mode 100644 webui/src/components/BrowserNotifications.tsx create mode 100644 webui/src/components/settings/overview/BrowserNotificationSettings.tsx create mode 100644 webui/src/lib/browser-notifications.ts create mode 100644 webui/src/tests/browser-notifications.test.tsx diff --git a/docs/guides/ai-agent-webui.md b/docs/guides/ai-agent-webui.md index 0bf72c6fc..ce532f7f5 100644 --- a/docs/guides/ai-agent-webui.md +++ b/docs/guides/ai-agent-webui.md @@ -29,6 +29,32 @@ The launcher checks setup, enables the local WebSocket channel after confirmatio When nanobot edits a file, the WebUI activity timeline can show the changed line counts, a unified diff, and an **Open file** action for a read-only preview. File previews use the chat's current workspace access mode: restricted access stays inside the selected workspace, while Full Access can preview files outside the workspace when the gateway allows it. +## Browser notifications + +In **Settings → Appearance**, enable **Browser notifications** and allow the +browser's permission request. Notifications are off by default and saved in +this browser, separately from the completion sound. Use **Test notification** +to check delivery; a successful submission does not prove that the operating +system displayed it. Check system notification and Do Not Disturb settings if +nothing appears. + +Notifications require HTTPS (or localhost), notification permission, and an +active service worker. On iPhone or iPad, use the web app from the Home Screen; +some browsers, including embedded browsers, cannot provide notifications. +The settings page explains unavailable permissions or browser features. + +While the page is in the background, notifications report completion, failure, +or required recovery for chats connected by that page, including chats you have +switched away from. They do not include chat text or error details. Clicking +opens the chat on the same gateway, with normal authentication. A temporary +chat can only be reopened while its original page connection exists. + +Keep the page open and connected. This is **not Web Push**: a closed or suspended +page cannot receive new task events. This is not a notification feed for every +gateway task. Recent events are deduplicated across tabs and reconnects (up to +256 events within 24 hours); browser storage restrictions can limit deduplication +after a service worker restarts. + ## Production notes - Use `nanobot gateway --background` when you do not want to keep a terminal open, then open the configured WebUI URL in a browser. diff --git a/webui/public/sw.js b/webui/public/sw.js index 6a5fddff0..da652b3fd 100644 --- a/webui/public/sw.js +++ b/webui/public/sw.js @@ -3,6 +3,10 @@ const CACHE_NAME = `${CACHE_PREFIX}v2`; const ICON_CACHE_PREFIX = "nanobot-icons-"; const ICON_CACHE_NAME = `${ICON_CACHE_PREFIX}v1`; const ICON_CACHE_LIMIT = 128; +const NOTICE_CACHE = "nanobot-notification-receipts-v1"; +const NOTICE_RECEIPTS = "/__notification_receipts__"; +let noticeQueue = Promise.resolve(); +let noticeReceipts; const ASSET_MANIFEST_PATH = "/asset-manifest.json"; const PRECACHE = ["/", "/manifest.json", ASSET_MANIFEST_PATH]; const NETWORK_FIRST_STATIC_PATHS = new Set([ @@ -17,6 +21,73 @@ const NETWORK_FIRST_STATIC_PATHS = new Set([ "/brand/nanobot_mark.svg", ]); +function notificationTarget(value) { + try { + const url = new URL(value); + if (url.origin !== self.location.origin || url.username || url.password || url.search || url.pathname !== "/") return null; + return /^#\/(?:chat|temporary)\/[^?]+$/.test(url.hash) + || url.hash === "#/settings?section=appearance" ? url.href : null; + } catch { return null; } +} + +async function notifyClient(source, data) { + const url = notificationTarget(data.url); + if (!url || typeof data.key !== "string" || data.key.length > 2048 || typeof data.body !== "string" || data.body.length > 300) return "displayFailed"; + // One worker serializes all tabs. Retain bounded receipts even after a + // notification is dismissed, so a reconnect does not show it again. + if (!noticeReceipts) { + try { + const saved = await (await caches.open(NOTICE_CACHE)).match(NOTICE_RECEIPTS); + noticeReceipts = saved ? await saved.json() : []; + } catch { noticeReceipts = []; } + } + noticeReceipts = noticeReceipts.filter((item) => item.time > Date.now() - 86_400_000); + if (noticeReceipts.some((item) => item.key === data.key)) return "skipped"; + const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); + const visible = !data.test && windows.some((client) => client.visibilityState === "visible"); + if (!visible) { + await self.registration.showNotification("nanobot", { + body: data.body, tag: data.key, icon: "/brand/nanobot_icon_192.png", + data: { url, clientId: source.id }, + }); + } + noticeReceipts = [...noticeReceipts, { key: data.key, time: Date.now() }].slice(-256); + try { + await (await caches.open(NOTICE_CACHE)).put(NOTICE_RECEIPTS, new Response(JSON.stringify(noticeReceipts))); + } catch { /* Storage is optional; the worker still deduplicates live tabs. */ } + return visible ? "skipped" : "submitted"; +} + +self.addEventListener("message", (event) => { + if (event.data?.type !== "nanobot:notify" || !event.source?.url + || new URL(event.source.url).origin !== self.location.origin) return; + const work = noticeQueue.then(() => notifyClient(event.source, event.data)); + noticeQueue = work.then(() => undefined, () => undefined); + event.waitUntil(work.then( + (result) => event.ports[0]?.postMessage(result), + () => event.ports[0]?.postMessage("displayFailed"), + )); +}); + +self.addEventListener("notificationclick", (event) => { + event.notification.close(); + const url = notificationTarget(event.notification.data?.url); + if (!url) return; + event.waitUntil((async () => { + const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); + const source = windows.find((client) => client.id === event.notification.data.clientId); + const temporary = new URL(url).hash.startsWith("#/temporary/"); + const target = source || (!temporary && windows.find((client) => client.frameType === "top-level")); + if (target) { + target.postMessage({ type: "nanobot:notification-click", url }); + await target.focus(); + } else { + // Temporary chats belong to their original connection, not another tab. + await self.clients.openWindow(temporary ? "/#/new" : url); + } + })()); +}); + function responseMayBeCached(response) { const cacheControl = response.headers?.get("Cache-Control") ?? ""; return response.ok && !/(?:^|,)\s*(?:private|no-cache|no-store)\b/i.test(cacheControl); diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 4e233ca89..01bb63f94 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -73,6 +73,7 @@ import { import { displayTitle, sortSessions } from "@/lib/chat-groups"; import { deriveTitle } from "@/lib/format"; import { NanobotClient } from "@/lib/nanobot-client"; +import { BrowserNotifications } from "@/components/BrowserNotifications"; import { ThreadMessageCache } from "@/lib/thread-message-cache"; import { FilePreviewStore } from "@/hooks/useFilePreviewState"; import { ClientProvider, useClient } from "@/providers/ClientProvider"; @@ -1135,6 +1136,7 @@ export default function App() { ingressLimits={state.ingressLimits} webuiCapabilities={state.webuiCapabilities} > + }) { + 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) => { + 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; +} diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsx index bb12a0147..092bc4a79 100644 --- a/webui/src/components/remote/RemoteInstances.tsx +++ b/webui/src/components/remote/RemoteInstances.tsx @@ -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. diff --git a/webui/src/components/remote/useHostSessions.ts b/webui/src/components/remote/useHostSessions.ts index 5af6eb3bd..1f40b4fd5 100644 --- a/webui/src/components/remote/useHostSessions.ts +++ b/webui/src/components/remote/useHostSessions.ts @@ -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 }; } diff --git a/webui/src/components/remote/useSidebarHostBridge.ts b/webui/src/components/remote/useSidebarHostBridge.ts index 7cd682d32..6808fe813 100644 --- a/webui/src/components/remote/useSidebarHostBridge.ts +++ b/webui/src/components/remote/useSidebarHostBridge.ts @@ -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>, 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(null); const [readyIds, setReadyIds] = useState([]); const [anchor, setAnchor] = useState(null); @@ -13,8 +14,8 @@ export function useSidebarHostBridge(frames: HostFrame[], selectedId: string | u const [hostedManagement, setHostedManagement] = useState(false); const parent = useRef(null); const peers = useRef(new Map()); - 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; diff --git a/webui/src/components/settings/overview/AppearanceSettingsView.tsx b/webui/src/components/settings/overview/AppearanceSettingsView.tsx index e636312a4..237478c44 100644 --- a/webui/src/components/settings/overview/AppearanceSettingsView.tsx +++ b/webui/src/components/settings/overview/AppearanceSettingsView.tsx @@ -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>; - 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")} /> - - - + >; +}) { + const { t } = useTranslation(); + const hintId = useId(); + const [problem, setProblem] = useState(notificationProblem); + const [feedback, setFeedback] = useState(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
+ + void toggle(value)} + ariaLabel={t("settings.rows.browserNotifications")} aria-describedby={hintId} + label={t(localPrefs.browserNotifications ? "settings.values.on" : "settings.values.off")} /> + +
+

{t("settings.help.browserNotifications")}

+

{busy ? t("settings.notifications.waiting") : status && status !== "skipped" ? t(`settings.notifications.${status}`) : null}

+ {enabled && } +
+
; +} diff --git a/webui/src/components/settings/overview/OverviewSettings.tsx b/webui/src/components/settings/overview/OverviewSettings.tsx index fd47dce61..c1c95dc78 100644 --- a/webui/src/components/settings/overview/OverviewSettings.tsx +++ b/webui/src/components/settings/overview/OverviewSettings.tsx @@ -192,25 +192,8 @@ export function AppearanceSettings({ theme, onToggleTheme, localPrefs, onChangeL localPrefs: LocalPreferences; onChangeLocalPrefs: Dispatch>; }) { - 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 ; + localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs} />; } function OverviewRowIcon({ diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index e2cf21318..91c61b3d5 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -1,10 +1,8 @@ import { acceptsCompactionPhase } from "../../../packages/client-events/notifications"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { useTranslation } from "react-i18next"; import { useThreadVisibility } from "@/hooks/useThreadVisibility"; import { useClient } from "@/providers/ClientProvider"; -import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure"; import { hasPendingAgentActivity } from "@/lib/activity-timeline"; import type { StreamError } from "@/lib/nanobot-client"; import { @@ -22,7 +20,6 @@ import type { UIMessageTurnFields, } from "@/lib/thread-event-projection"; import { formatQuotedUserMessage } from "@/lib/user-message-quote"; -import { readLocalPreferences } from "@/lib/local-preferences"; import { playTurnCompleteSound } from "@/lib/notification-sound"; import type { InboundEvent, @@ -176,7 +173,6 @@ export function useNanobotStream( const threadVisible = useThreadVisibility(); const threadVisibleRef = useRef(threadVisible); threadVisibleRef.current = threadVisible; - const { t } = useTranslation(); const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null; const [messages, setRenderedMessages] = useState(initialMessages); const messagesRef = useRef(messages); @@ -216,16 +212,6 @@ export function useNanobotStream( const dismissStreamError = useCallback(() => setStreamError(null), []); - const notifyInBackground = useCallback((body: string) => { - if ( - typeof Notification === "undefined" - || Notification.permission !== "granted" - || document.visibilityState === "visible" - || !readLocalPreferences().browserNotifications - ) return; - new Notification("nanobot", { body }); - }, []); - const clearPendingStreamWork = useCallback(() => { if (streamFrameRef.current !== null) { window.cancelAnimationFrame(streamFrameRef.current); @@ -816,13 +802,6 @@ export function useNanobotStream( : null; if (modelFailure) setStreamError(modelFailure); applyProjectionEvent(ev); - notifyInBackground( - modelFailure - ? resolveModelRequestFailureCopy(modelFailure, t).body - : ev.outcome === "failed" - ? ev.failure_message || "This turn failed and has ended." - : t("recovery.completed", { defaultValue: "Task completed" }), - ); playTurnCompleteSound(); onTurnEnd?.(); return; @@ -859,13 +838,6 @@ export function useNanobotStream( clearPendingStreamWork(); closeActiveAssistantStream(); clearActivitySegment(); - if (ev.status !== "recovered") { - notifyInBackground( - ev.status === "failed" - ? t("recovery.failed", { defaultValue: "Task recovery failed" }) - : t("recovery.interrupted", { defaultValue: "Task interrupted" }), - ); - } } return; } @@ -927,12 +899,10 @@ export function useNanobotStream( clearPendingStreamWork, flushPendingStreamEvents, isSideChannelEvent, - notifyInBackground, onTurnEnd, onStreamDetach, schedulePendingStreamFlush, setMessages, - t, ]); const send = useCallback( diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 75640eea6..596e9a33b 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -771,6 +771,22 @@ "autoProviderCustomOnly": "Enter a model ID manually when using automatic provider selection.", "availableCount": "Models available: {{count}}" }, + "notifications": { + "test": "Test notification", + "testBody": "This is a test notification from nanobot.", + "waiting": "Waiting for the browser…", + "insecure": "Open nanobot over HTTPS or on localhost to use notifications.", + "unsupported": "This browser cannot send notifications. Try a supported browser. On iPhone or iPad, open nanobot from the Home Screen.", + "denied": "Notifications are blocked. Allow them in this site's browser settings, then try again.", + "dismissed": "Permission was not granted. Turn on notifications and choose Allow.", + "permissionFailed": "Could not request permission. Try again in a supported browser.", + "workerUnavailable": "The notification service is not ready. Reload this page and try again.", + "displayFailed": "The browser could not send the notification. Check site permissions, then try again.", + "submitted": "Sent to the browser. If nothing appears, check system notifications and Do Not Disturb.", + "completed": "Task completed. Open nanobot to view the result.", + "failed": "Task failed. Open nanobot for details.", + "interrupted": "Task needs attention. Open nanobot to continue." + }, "rows": { "theme": "Theme", "language": "Language", @@ -789,7 +805,7 @@ "fileEditDisplay": "Edit preview", "codeWrap": "Code wrapping", "brandLogos": "Brand logos", - "browserNotifications": "Task notifications", + "browserNotifications": "Browser notifications", "notificationSound": "Completion sound", "maxResults": "Result limit", "timeout": "Search timeout", @@ -835,7 +851,7 @@ "fileEditDisplay": "Show edit line counts or expanded changes by default.", "codeWrap": "Wrap long code lines for easier reading.", "brandLogos": "Show provider and app logos in Settings.\n\nShow third-party provider and CLI logos in Settings.", - "browserNotifications": "Notify when this page is in the background. Off by default.", + "browserNotifications": "Alert when a task ends or needs attention while this page is in the background. Keep the page open; closed or suspended pages cannot receive new alerts.", "notificationSound": "Play a sound when replies finish. Off by default.\n\nPlay a short chime when a turn finishes, even when this page is in the background. Off by default.", "maxResults": "Maximum results per search.", "timeout": "Maximum wait per search, in seconds.", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index baf76d5ec..9e77e7a29 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -516,6 +516,22 @@ "hostSafety": "Seguridad de la app", "voiceInput": "Transcripción" }, + "notifications": { + "test": "Probar notificaciones", + "testBody": "Esta es una notificación de prueba de nanobot.", + "waiting": "Esperando al navegador…", + "insecure": "Abre nanobot por HTTPS o en localhost para usar las notificaciones.", + "unsupported": "Este navegador no admite notificaciones. Prueba uno compatible. En iPhone o iPad, abre nanobot desde la pantalla de inicio.", + "denied": "Las notificaciones están bloqueadas. Permítelas en los ajustes de este sitio y vuelve a intentarlo.", + "dismissed": "No se concedió permiso. Activa las notificaciones y elige Permitir.", + "permissionFailed": "No se pudo solicitar permiso. Vuelve a intentarlo en un navegador compatible.", + "workerUnavailable": "El servicio de notificaciones no está listo. Recarga la página y vuelve a intentarlo.", + "displayFailed": "El navegador no pudo enviar la notificación. Comprueba los permisos del sitio y vuelve a intentarlo.", + "submitted": "Enviada al navegador. Si no aparece, comprueba las notificaciones del sistema y el modo No molestar.", + "completed": "Tarea completada. Abre nanobot para ver el resultado.", + "failed": "La tarea falló. Abre nanobot para ver los detalles.", + "interrupted": "La tarea necesita atención. Abre nanobot para continuar." + }, "rows": { "theme": "Tema", "language": "Idioma", @@ -550,7 +566,7 @@ "webuiDefaultAccess": "Acceso predeterminado", "currentModel": "Configuración actual", "brandLogos": "Logos de marca", - "browserNotifications": "Notificaciones de tareas", + "browserNotifications": "Notificaciones del navegador", "notificationSound": "Sonido al finalizar", "cliAppsCatalog": "Catálogo", "cliAppsFilter": "Filtro", @@ -594,7 +610,7 @@ "selectedModelProvider": "Definido por el modelo seleccionado.", "selectedModelValue": "Definido por el modelo seleccionado.", "brandLogos": "Muestra los logos de proveedores y apps en Ajustes.\n\nMuestra logos de proveedores de terceros y CLI en Ajustes.", - "browserNotifications": "Notifica cuando la página está en segundo plano. Desactivado por defecto.", + "browserNotifications": "Recibe avisos cuando una tarea termina o necesita atención mientras esta página está en segundo plano. Déjala abierta: si se cierra o suspende, no puede recibir nuevos avisos.", "notificationSound": "Suena al terminar las respuestas. Desactivado por defecto.\n\nReproduce un breve sonido cuando termina un turno, incluso si esta página está en segundo plano. Desactivado por defecto.", "cliAppsCatalog": "Instala herramientas CLI para nanobot; las apps de escritorio no cambian.\n\nInstala las herramientas de línea de comandos que nanobot puede usar en este equipo. Las aplicaciones de escritorio no se modifican.", "cliAppsFilter": "Busca por nombre, categoría o función.", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index af5a97c36..c30cf6c7c 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -516,6 +516,22 @@ "hostSafety": "Sécurité de l’app", "voiceInput": "Transcription" }, + "notifications": { + "test": "Tester les notifications", + "testBody": "Ceci est une notification de test de nanobot.", + "waiting": "En attente du navigateur…", + "insecure": "Ouvrez nanobot via HTTPS ou localhost pour utiliser les notifications.", + "unsupported": "Ce navigateur ne prend pas en charge les notifications. Essayez un navigateur compatible. Sur iPhone ou iPad, ouvrez nanobot depuis l’écran d’accueil.", + "denied": "Les notifications sont bloquées. Autorisez-les dans les paramètres du site, puis réessayez.", + "dismissed": "L’autorisation n’a pas été accordée. Activez les notifications et choisissez Autoriser.", + "permissionFailed": "Impossible de demander l’autorisation. Réessayez dans un navigateur compatible.", + "workerUnavailable": "Le service de notifications n’est pas prêt. Rechargez la page et réessayez.", + "displayFailed": "Le navigateur n’a pas pu envoyer la notification. Vérifiez les autorisations du site, puis réessayez.", + "submitted": "Envoyée au navigateur. Si rien ne s’affiche, vérifiez les notifications système et le mode Ne pas déranger.", + "completed": "Tâche terminée. Ouvrez nanobot pour voir le résultat.", + "failed": "La tâche a échoué. Ouvrez nanobot pour les détails.", + "interrupted": "La tâche demande votre attention. Ouvrez nanobot pour continuer." + }, "rows": { "theme": "Thème", "language": "Langue", @@ -550,7 +566,7 @@ "webuiDefaultAccess": "Accès par défaut", "currentModel": "Configuration actuelle", "brandLogos": "Logos de marque", - "browserNotifications": "Notifications de tâches", + "browserNotifications": "Notifications du navigateur", "notificationSound": "Son de fin", "cliAppsCatalog": "Catalogue", "cliAppsFilter": "Filtre", @@ -594,7 +610,7 @@ "selectedModelProvider": "Défini par le modèle sélectionné.", "selectedModelValue": "Défini par le modèle sélectionné.", "brandLogos": "Affichez les logos des fournisseurs et applications dans les réglages.\n\nAffiche les logos de fournisseurs tiers et CLI dans les Réglages.", - "browserNotifications": "Notifiez quand cette page est en arrière-plan. Désactivé par défaut.", + "browserNotifications": "Recevez une alerte à la fin d’une tâche ou si elle demande votre attention, lorsque cette page est en arrière-plan. Gardez-la ouverte : une page fermée ou suspendue ne reçoit plus d’alertes.", "notificationSound": "Émettez un son à la fin des réponses. Désactivé par défaut.\n\nJoue un bref carillon lorsqu’un tour se termine, même si cette page est en arrière-plan. Désactivé par défaut.", "cliAppsCatalog": "Installez des outils CLI pour nanobot ; les applications de bureau restent inchangées.\n\nInstalle les outils en ligne de commande que nanobot peut utiliser sur cette machine. Les applications de bureau ne sont pas modifiées.", "cliAppsFilter": "Recherchez par nom, catégorie ou fonction.", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index dcbce2a2d..01d82c848 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -516,6 +516,22 @@ "hostSafety": "Keamanan aplikasi", "voiceInput": "Transkripsi" }, + "notifications": { + "test": "Uji notifikasi", + "testBody": "Ini adalah notifikasi uji dari nanobot.", + "waiting": "Menunggu browser…", + "insecure": "Buka nanobot melalui HTTPS atau localhost untuk menggunakan notifikasi.", + "unsupported": "Browser ini tidak mendukung notifikasi. Gunakan browser yang mendukungnya. Di iPhone atau iPad, buka nanobot dari Layar Utama.", + "denied": "Notifikasi diblokir. Izinkan di pengaturan situs ini pada browser, lalu coba lagi.", + "dismissed": "Izin belum diberikan. Aktifkan notifikasi dan pilih Izinkan.", + "permissionFailed": "Tidak dapat meminta izin. Coba lagi di browser yang mendukung notifikasi.", + "workerUnavailable": "Layanan notifikasi belum siap. Muat ulang halaman dan coba lagi.", + "displayFailed": "Browser tidak dapat mengirim notifikasi. Periksa izin situs, lalu coba lagi.", + "submitted": "Dikirim ke browser. Jika tidak muncul, periksa notifikasi sistem dan mode Jangan Ganggu.", + "completed": "Tugas selesai. Buka nanobot untuk melihat hasilnya.", + "failed": "Tugas gagal. Buka nanobot untuk melihat detailnya.", + "interrupted": "Tugas perlu perhatian. Buka nanobot untuk melanjutkan." + }, "rows": { "theme": "Tema", "language": "Bahasa", @@ -550,7 +566,7 @@ "webuiDefaultAccess": "Akses bawaan", "currentModel": "Konfigurasi saat ini", "brandLogos": "Logo merek", - "browserNotifications": "Notifikasi tugas", + "browserNotifications": "Notifikasi browser", "notificationSound": "Suara selesai", "cliAppsCatalog": "Katalog", "cliAppsFilter": "Saring", @@ -594,7 +610,7 @@ "selectedModelProvider": "Ditentukan oleh model yang dipilih.", "selectedModelValue": "Ditentukan oleh model yang dipilih.", "brandLogos": "Tampilkan logo penyedia dan aplikasi di Pengaturan.\n\nTampilkan logo penyedia pihak ketiga dan CLI di Pengaturan.", - "browserNotifications": "Beri notifikasi saat halaman di latar belakang. Nonaktif secara default.", + "browserNotifications": "Beri tahu saat tugas selesai atau perlu perhatian ketika halaman ini berada di latar belakang. Biarkan halaman terbuka; halaman yang ditutup atau ditangguhkan tidak dapat menerima notifikasi baru.", "notificationSound": "Putar suara saat balasan selesai. Nonaktif secara default.\n\nPutar dentang singkat saat giliran selesai, meskipun halaman ini berada di latar belakang. Nonaktif secara default.", "cliAppsCatalog": "Pasang alat CLI untuk nanobot; aplikasi desktop tetap tidak berubah.\n\nMemasang alat baris perintah yang dapat digunakan nanobot di komputer ini. Aplikasi desktop tidak diubah.", "cliAppsFilter": "Cari berdasarkan nama, kategori, atau kemampuan.", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 3241fd28b..f9b12284c 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -516,6 +516,22 @@ "hostSafety": "アプリの安全性", "voiceInput": "音声の文字起こし" }, + "notifications": { + "test": "通知をテスト", + "testBody": "nanobot からのテスト通知です。", + "waiting": "ブラウザーの応答を待っています…", + "insecure": "通知を使うには、HTTPS または localhost で nanobot を開いてください。", + "unsupported": "このブラウザーは通知に対応していません。対応ブラウザーをお使いください。iPhone や iPad ではホーム画面から nanobot を開いてください。", + "denied": "通知がブロックされています。ブラウザーのサイト設定で通知を許可してから再試行してください。", + "dismissed": "通知が許可されていません。通知を有効にして「許可」を選んでください。", + "permissionFailed": "通知の許可を要求できませんでした。対応ブラウザーで再試行してください。", + "workerUnavailable": "通知サービスの準備ができていません。ページを再読み込みして再試行してください。", + "displayFailed": "通知を送信できませんでした。サイトの通知権限を確認して再試行してください。", + "submitted": "ブラウザーに送信しました。表示されない場合は、システムの通知とおやすみモードを確認してください。", + "completed": "タスクが完了しました。nanobot で結果を確認してください。", + "failed": "タスクが失敗しました。nanobot で詳細を確認してください。", + "interrupted": "対応が必要です。nanobot を開いて続行してください。" + }, "rows": { "theme": "テーマ", "language": "言語", @@ -550,7 +566,7 @@ "webuiDefaultAccess": "既定の権限", "currentModel": "現在の設定", "brandLogos": "ブランドロゴ", - "browserNotifications": "タスク通知", + "browserNotifications": "ブラウザー通知", "notificationSound": "完了時の音", "cliAppsCatalog": "カタログ", "cliAppsFilter": "フィルター", @@ -594,7 +610,7 @@ "selectedModelProvider": "選択したモデルによって設定されます。", "selectedModelValue": "選択したモデルによって設定されます。", "brandLogos": "設定画面にプロバイダーとアプリのロゴを表示します。\n\n設定で第三者プロバイダーと CLI のロゴを表示します。", - "browserNotifications": "ページがバックグラウンドのとき通知します。既定はオフです。", + "browserNotifications": "ページがバックグラウンドにあるとき、タスクの終了や対応が必要な状態を通知します。ページを開いたままにしてください。閉じたり休止したりすると新しい通知は届きません。", "notificationSound": "返信完了時に音を鳴らします。既定はオフです。\n\nターンが完了したら、ページがバックグラウンドにあっても短いチャイムを再生します。既定ではオフです。", "cliAppsCatalog": "nanobot 用の CLI ツールをインストールします。デスクトップアプリは変わりません。\n\nnanobot がこのマシンで使用できるコマンドラインツールをインストールします。デスクトップアプリは変更しません。", "cliAppsFilter": "名前、分類、機能で検索します。", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 460e9807c..060c3cd07 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -516,6 +516,22 @@ "hostSafety": "앱 보안", "voiceInput": "음성 텍스트 변환" }, + "notifications": { + "test": "알림 테스트", + "testBody": "nanobot 테스트 알림입니다.", + "waiting": "브라우저 응답 대기 중…", + "insecure": "알림을 사용하려면 HTTPS 또는 localhost로 nanobot을 여세요.", + "unsupported": "이 브라우저는 알림을 지원하지 않습니다. 지원하는 브라우저를 사용하세요. iPhone이나 iPad에서는 홈 화면에서 nanobot을 여세요.", + "denied": "알림이 차단되었습니다. 브라우저의 사이트 설정에서 알림을 허용한 후 다시 시도하세요.", + "dismissed": "알림 권한을 받지 못했습니다. 알림을 켜고 허용을 선택하세요.", + "permissionFailed": "권한을 요청할 수 없습니다. 지원하는 브라우저에서 다시 시도하세요.", + "workerUnavailable": "알림 서비스가 준비되지 않았습니다. 페이지를 새로 고침한 후 다시 시도하세요.", + "displayFailed": "브라우저가 알림을 보내지 못했습니다. 사이트 알림 권한을 확인하고 다시 시도하세요.", + "submitted": "브라우저에 전송했습니다. 표시되지 않으면 시스템 알림과 방해 금지 설정을 확인하세요.", + "completed": "작업이 완료되었습니다. nanobot에서 결과를 확인하세요.", + "failed": "작업이 실패했습니다. nanobot에서 자세히 확인하세요.", + "interrupted": "확인이 필요합니다. nanobot을 열어 계속하세요." + }, "rows": { "theme": "테마", "language": "언어", @@ -550,7 +566,7 @@ "webuiDefaultAccess": "기본 권한", "currentModel": "현재 설정", "brandLogos": "브랜드 로고", - "browserNotifications": "작업 알림", + "browserNotifications": "브라우저 알림", "notificationSound": "완료 알림음", "cliAppsCatalog": "카탈로그", "cliAppsFilter": "필터", @@ -594,7 +610,7 @@ "selectedModelProvider": "선택한 모델에 의해 설정됩니다.", "selectedModelValue": "선택한 모델에 의해 설정됩니다.", "brandLogos": "설정에 제공업체와 앱 로고를 표시합니다.\n\n설정에서 타사 제공업체와 CLI 로고를 표시합니다.", - "browserNotifications": "페이지가 백그라운드일 때 알립니다. 기본은 꺼짐입니다.", + "browserNotifications": "페이지가 백그라운드에 있을 때 작업 종료 또는 확인이 필요한 상태를 알립니다. 페이지를 열어 두세요. 닫히거나 일시 중지되면 새 알림을 받을 수 없습니다.", "notificationSound": "답변이 끝나면 알림음을 재생합니다. 기본은 꺼짐입니다.\n\n턴이 끝나면 이 페이지가 백그라운드에 있어도 짧은 알림음을 재생합니다. 기본적으로 꺼져 있습니다.", "cliAppsCatalog": "nanobot용 CLI 도구를 설치합니다. 데스크톱 앱은 변경되지 않습니다.\n\nnanobot이 이 컴퓨터에서 사용할 수 있는 명령줄 도구를 설치합니다. 데스크톱 앱은 변경하지 않습니다.", "cliAppsFilter": "이름, 분류 또는 기능으로 검색하세요.", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 64b3203a7..df701b45e 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -585,6 +585,22 @@ "providerNotConfigured": "Configure este provedor antes de carregar modelos.", "autoProviderCustomOnly": "Digite um ID de modelo para usar a seleção automática de provedor." }, + "notifications": { + "test": "Testar notificações", + "testBody": "Esta é uma notificação de teste do nanobot.", + "waiting": "Aguardando o navegador…", + "insecure": "Abra o nanobot por HTTPS ou em localhost para usar notificações.", + "unsupported": "Este navegador não oferece suporte a notificações. Use um navegador compatível. No iPhone ou iPad, abra o nanobot pela Tela de Início.", + "denied": "As notificações estão bloqueadas. Permita-as nas configurações deste site e tente novamente.", + "dismissed": "A permissão não foi concedida. Ative as notificações e escolha Permitir.", + "permissionFailed": "Não foi possível solicitar permissão. Tente novamente em um navegador compatível.", + "workerUnavailable": "O serviço de notificações não está pronto. Recarregue a página e tente novamente.", + "displayFailed": "O navegador não conseguiu enviar a notificação. Verifique as permissões do site e tente novamente.", + "submitted": "Enviada ao navegador. Se nada aparecer, verifique as notificações do sistema e o modo Não Perturbe.", + "completed": "Tarefa concluída. Abra o nanobot para ver o resultado.", + "failed": "A tarefa falhou. Abra o nanobot para ver os detalhes.", + "interrupted": "A tarefa precisa de atenção. Abra o nanobot para continuar." + }, "rows": { "theme": "Tema", "language": "Idioma", @@ -603,7 +619,7 @@ "fileEditDisplay": "Prévia de alterações", "codeWrap": "Quebra de linha no código", "brandLogos": "Logos de marca", - "browserNotifications": "Notificações de tarefas", + "browserNotifications": "Notificações do navegador", "notificationSound": "Som de conclusão", "maxResults": "Limite de resultados", "timeout": "Tempo limite de busca", @@ -649,7 +665,7 @@ "fileEditDisplay": "Mostre por padrão a contagem de linhas ou as alterações completas.", "codeWrap": "Quebre linhas longas de código para facilitar a leitura.", "brandLogos": "Mostre logos de provedores e apps nos Ajustes.\n\nMostra logotipos de provedores terceiros e de CLIs em Configurações.", - "browserNotifications": "Notifique quando a página estiver em segundo plano. Desativado por padrão.", + "browserNotifications": "Receba um aviso quando uma tarefa terminar ou precisar de atenção com esta página em segundo plano. Mantenha-a aberta: páginas fechadas ou suspensas não recebem novos avisos.", "notificationSound": "Toque um som ao concluir respostas. Desativado por padrão.\n\nToca um breve sinal sonoro quando um turno termina, mesmo quando esta página está em segundo plano. Desativado por padrão.", "maxResults": "Máximo de resultados por busca.", "timeout": "Espera máxima por busca, em segundos.", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 7ed947950..3105b5cf5 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -516,6 +516,22 @@ "hostSafety": "An toàn ứng dụng", "voiceInput": "Chép lời" }, + "notifications": { + "test": "Thử thông báo", + "testBody": "Đây là thông báo thử từ nanobot.", + "waiting": "Đang chờ trình duyệt…", + "insecure": "Mở nanobot qua HTTPS hoặc localhost để dùng thông báo.", + "unsupported": "Trình duyệt này không hỗ trợ thông báo. Hãy dùng trình duyệt có hỗ trợ. Trên iPhone hoặc iPad, mở nanobot từ Màn hình chính.", + "denied": "Thông báo đã bị chặn. Hãy cho phép trong cài đặt trang web của trình duyệt rồi thử lại.", + "dismissed": "Chưa được cấp quyền. Bật thông báo và chọn Cho phép.", + "permissionFailed": "Không thể yêu cầu quyền. Hãy thử lại trên trình duyệt có hỗ trợ.", + "workerUnavailable": "Dịch vụ thông báo chưa sẵn sàng. Tải lại trang và thử lại.", + "displayFailed": "Trình duyệt không thể gửi thông báo. Kiểm tra quyền của trang web rồi thử lại.", + "submitted": "Đã gửi đến trình duyệt. Nếu không thấy, hãy kiểm tra thông báo hệ thống và chế độ Không làm phiền.", + "completed": "Tác vụ đã hoàn tất. Mở nanobot để xem kết quả.", + "failed": "Tác vụ thất bại. Mở nanobot để xem chi tiết.", + "interrupted": "Tác vụ cần chú ý. Mở nanobot để tiếp tục." + }, "rows": { "theme": "Chủ đề", "language": "Ngôn ngữ", @@ -550,7 +566,7 @@ "webuiDefaultAccess": "Quyền mặc định", "currentModel": "Cấu hình hiện tại", "brandLogos": "Logo thương hiệu", - "browserNotifications": "Thông báo tác vụ", + "browserNotifications": "Thông báo trình duyệt", "notificationSound": "Âm báo hoàn thành", "cliAppsCatalog": "Danh mục", "cliAppsFilter": "Bộ lọc", @@ -594,7 +610,7 @@ "selectedModelProvider": "Được đặt bởi mô hình đã chọn.", "selectedModelValue": "Được đặt bởi mô hình đã chọn.", "brandLogos": "Hiện logo nhà cung cấp và ứng dụng trong Thiết lập.\n\nHiển thị logo nhà cung cấp bên thứ ba và CLI trong Cài đặt.", - "browserNotifications": "Thông báo khi trang ở nền. Mặc định tắt.", + "browserNotifications": "Thông báo khi tác vụ kết thúc hoặc cần chú ý trong lúc trang này ở nền. Hãy giữ trang mở; trang đã đóng hoặc tạm ngưng không thể nhận thông báo mới.", "notificationSound": "Phát âm báo khi trả lời xong. Mặc định tắt.\n\nPhát một tiếng chuông ngắn khi lượt kết thúc, ngay cả khi trang này đang ở nền. Tắt theo mặc định.", "cliAppsCatalog": "Cài công cụ CLI cho nanobot; giữ nguyên ứng dụng máy tính.\n\nCài các công cụ dòng lệnh mà nanobot có thể dùng trên máy này. Các ứng dụng trên máy tính không bị thay đổi.", "cliAppsFilter": "Tìm theo tên, danh mục hoặc chức năng.", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index d7aba45f0..7433c91b1 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -771,6 +771,22 @@ "autoProviderCustomOnly": "自动选择提供商时,请手动输入模型 ID。", "availableCount": "可用模型:{{count}} 个" }, + "notifications": { + "test": "测试通知", + "testBody": "这是一条 nanobot 测试通知。", + "waiting": "等待浏览器响应…", + "insecure": "请通过 HTTPS 或 localhost 打开 nanobot,再开启通知。", + "unsupported": "此浏览器不支持通知,请换用支持的浏览器。iPhone 或 iPad 需从主屏幕打开 nanobot。", + "denied": "通知已被浏览器阻止。请在本站的浏览器设置中允许通知,再重试。", + "dismissed": "尚未获得通知权限。请重新开启,并选择“允许”。", + "permissionFailed": "无法请求通知权限,请在支持的浏览器中重试。", + "workerUnavailable": "通知服务尚未就绪,请刷新页面后重试。", + "displayFailed": "浏览器未能发送通知,请检查本站的通知权限后重试。", + "submitted": "已提交给浏览器。如未看到通知,请检查系统通知和勿扰设置。", + "completed": "任务已完成,打开 nanobot 查看结果。", + "failed": "任务未完成,打开 nanobot 查看详情。", + "interrupted": "任务需要处理,打开 nanobot 继续。" + }, "rows": { "theme": "主题", "language": "语言", @@ -789,7 +805,7 @@ "fileEditDisplay": "修改预览", "codeWrap": "代码换行", "brandLogos": "品牌图标", - "browserNotifications": "任务通知", + "browserNotifications": "浏览器通知", "notificationSound": "完成音效", "maxResults": "结果上限", "timeout": "搜索超时", @@ -835,7 +851,7 @@ "fileEditDisplay": "默认显示行数或展开修改内容", "codeWrap": "长代码自动换行,方便阅读", "brandLogos": "在设置中显示提供商与应用图标\n\n在设置中显示提供商和命令行应用的品牌图标。", - "browserNotifications": "页面在后台时通知,默认关闭", + "browserNotifications": "网页在后台时,提醒任务结束或需要处理。请保持网页打开;关闭或挂起后无法接收新通知。", "notificationSound": "回复结束播放提示音,默认关闭\n\n回合结束时播放短促提示音,页面在后台时也会播放。默认关闭。", "maxResults": "每次搜索最多显示多少条结果", "timeout": "每次搜索最长等待时间,单位秒", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index dbf447472..6af7e2232 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -516,6 +516,22 @@ "hostSafety": "應用程式安全", "voiceInput": "語音轉寫" }, + "notifications": { + "test": "測試通知", + "testBody": "這是一則 nanobot 測試通知。", + "waiting": "等待瀏覽器回應…", + "insecure": "請透過 HTTPS 或 localhost 開啟 nanobot,再啟用通知。", + "unsupported": "此瀏覽器不支援通知,請換用支援的瀏覽器。iPhone 或 iPad 需從主畫面開啟 nanobot。", + "denied": "通知已被瀏覽器封鎖。請在本站的瀏覽器設定中允許通知,再重試。", + "dismissed": "尚未取得通知權限。請重新啟用,並選擇「允許」。", + "permissionFailed": "無法要求通知權限,請在支援的瀏覽器中重試。", + "workerUnavailable": "通知服務尚未就緒,請重新整理頁面後重試。", + "displayFailed": "瀏覽器未能傳送通知,請檢查本站的通知權限後重試。", + "submitted": "已提交給瀏覽器。如未看到通知,請檢查系統通知和勿擾設定。", + "completed": "任務已完成,開啟 nanobot 查看結果。", + "failed": "任務未完成,開啟 nanobot 查看詳情。", + "interrupted": "任務需要處理,開啟 nanobot 繼續。" + }, "rows": { "theme": "主題", "language": "語言", @@ -550,7 +566,7 @@ "webuiDefaultAccess": "預設存取權", "currentModel": "目前設定", "brandLogos": "品牌圖示", - "browserNotifications": "任務通知", + "browserNotifications": "瀏覽器通知", "notificationSound": "完成音效", "cliAppsCatalog": "應用程式清單", "cliAppsFilter": "篩選", @@ -594,7 +610,7 @@ "selectedModelProvider": "由選取的模型決定。", "selectedModelValue": "由選取的模型決定。", "brandLogos": "在設定中顯示提供商與應用圖示\n\n在設定中顯示提供商和命令列應用的品牌圖示。", - "browserNotifications": "頁面在後臺時通知,預設關閉", + "browserNotifications": "網頁在背景時,提醒任務結束或需要處理。請保持網頁開啟;關閉或暫停後無法接收新通知。", "notificationSound": "回覆結束播放提示音,預設關閉\n\n回合結束時播放短促提示音,頁面在後臺時也會播放。預設關閉。", "cliAppsCatalog": "安裝 CLI 工具,不改桌面應用\n\n安裝供 nanobot 使用的命令列工具,不會安裝或修改對應的桌面應用。", "cliAppsFilter": "按名稱、分類或功能搜尋", diff --git a/webui/src/lib/browser-notifications.ts b/webui/src/lib/browser-notifications.ts new file mode 100644 index 000000000..5327c0202 --- /dev/null +++ b/webui/src/lib/browser-notifications.ts @@ -0,0 +1,97 @@ +import { readLocalPreferences } from "./local-preferences"; +import type { TaskNotice } from "./nanobot-client"; + +export type NotificationProblem = "insecure" | "unsupported" | "denied" | "dismissed" | "permissionFailed" | "workerUnavailable" | "displayFailed"; +export type NotificationResult = "submitted" | "skipped" | NotificationProblem; +const TIMEOUT_MS = 5_000; +export const NOTIFICATION_STATUS_EVENT = "nanobot:notification-status"; +export const NOTIFICATION_OPEN_EVENT = "nanobot:notification-open"; +let lastProblem: NotificationProblem | null = null; +export function lastNotificationProblem() { return lastProblem; } + +// Do not infer browser support from its user agent (including embedded browsers). +export function notificationProblem(): NotificationProblem | null { + if (!window.isSecureContext) return "insecure"; + if (typeof Notification === "undefined" || !("serviceWorker" in navigator)) return "unsupported"; + if (Notification.permission === "denied") return "denied"; + return null; +} + +function bounded(operation: Promise, timeoutMs = TIMEOUT_MS): Promise { + return new Promise((resolve, reject) => { + const timer = window.setTimeout(() => reject(new Error("Notification timeout")), timeoutMs); + operation.then(resolve, reject).finally(() => window.clearTimeout(timer)); + }); +} + +async function activeWorker(): Promise { + // `ready` can wait forever when registration is blocked. An absent or still + // installing worker is retryable; it must not leave the settings switch busy. + const registration = await bounded(navigator.serviceWorker.getRegistration()); + return registration?.active ?? null; +} + +export async function enableBrowserNotifications(): Promise { + const problem = notificationProblem(); + if (problem) return problem; + // Request permission before the first await to preserve the user gesture. + try { + const permission = Notification.permission === "granted" + ? "granted" : await bounded(Notification.requestPermission(), 60_000); + if (permission !== "granted") return permission === "denied" ? "denied" : "dismissed"; + } catch { return "permissionFailed"; } + try { return await activeWorker() ? null : "workerUnavailable"; } + catch { return "workerUnavailable"; } +} + +export function taskNoticeKey(notice: TaskNotice): string | null { + const event = notice.event; + if (event.event === "turn_end") { + if (event.outcome === "cancelled") return null; + return event.turn_id ? JSON.stringify([event.chat_id, event.turn_id, "end"]) : null; + } + return ["awaiting_user", "failed"].includes(event.status) + ? JSON.stringify([event.chat_id, event.recovery_id, event.status]) : null; +} + +export function notificationChatUrl(chatId: string, temporary: boolean): string { + // The page origin identifies the gateway, including isolated remote views. + // Never copy the page's query, fragment, userinfo, or any auth token. + return `${window.location.origin}/${temporary ? "#/temporary/" : "#/chat/"}${encodeURIComponent(temporary ? chatId : `websocket:${chatId}`)}`; +} + +export async function showBrowserNotification(body: string, options: { + key: string; + url: string; + test?: boolean; +}): Promise { + const result = await submitNotification(body, options).catch(() => "displayFailed" as const); + if (result !== "skipped") { + lastProblem = result === "submitted" ? null : result; + window.dispatchEvent(new Event(NOTIFICATION_STATUS_EVENT)); + } + return result; +} + +async function submitNotification(body: string, options: { key: string; url: string; test?: boolean }): Promise { + const eligible = () => options.test || (readLocalPreferences().browserNotifications && document.visibilityState !== "visible"); + if (!eligible()) return "skipped"; + const problem = notificationProblem(); + if (problem) return problem; + if (Notification.permission !== "granted") return "dismissed"; + let worker: ServiceWorker | null; + try { worker = await activeWorker(); } + catch { return "workerUnavailable"; } + if (!worker) return "workerUnavailable"; + if (!eligible()) return "skipped"; + const channel = new MessageChannel(); + try { + return await bounded(new Promise((resolve) => { + channel.port1.onmessage = ({ data }: MessageEvent) => { + resolve(data === "submitted" || data === "skipped" ? data : "displayFailed"); + }; + worker.postMessage({ type: "nanobot:notify", body, ...options }, [channel.port2]); + })); + } catch { return "displayFailed"; } + finally { channel.port1.close(); } +} diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index 76499b85d..06051e25d 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -73,6 +73,10 @@ function summarizeInboundWsPayload(ev: InboundEvent): unknown { type Unsubscribe = () => void; type EventHandler = (ev: InboundEvent) => void; +export interface TaskNotice { + event: Extract; + temporary: boolean; +} type StatusHandler = (status: ConnectionStatus) => void; type RunCompletionHandler = (chatId: string) => void; type RuntimeModelHandler = (modelName: string | null, modelPreset?: string | null) => void; @@ -214,6 +218,7 @@ export class NanobotClient { private runStatusHandlers = new Set(); private runCompletionHandlers = new Set(); private errorHandlers = new Set(); + private taskNoticeHandlers = new Set<(notice: TaskNotice) => void>(); private chatHandlers = new Map>(); private transcriptHandlers = new Map(); /** Inbound frames received while the transcript owner is absent, regardless of observers. */ @@ -310,6 +315,12 @@ export class NanobotClient { }; } + /** Live lifecycle events, independent of mounted chats. Never replays history. */ + onTaskNotice(handler: (notice: TaskNotice) => void): Unsubscribe { + this.taskNoticeHandlers.add(handler); + return () => { this.taskNoticeHandlers.delete(handler); }; + } + /** Subscribe to transport-level faults (see :type:`StreamError`). */ onError(handler: ErrorHandler): Unsubscribe { this.errorHandlers.add(handler); @@ -992,6 +1003,13 @@ export class NanobotClient { if (correlatedChatId) { this.recordGoalStateSnapshot(correlatedChatId, parsed); + if (parsed.event === "turn_end" || parsed.event === "recovery_state") { + for (const handler of this.taskNoticeHandlers) { + // Optional browser features must never interrupt delivery or cleanup. + try { handler({ event: parsed, temporary: this.temporaryChatIds.has(correlatedChatId) }); } + catch { /* The notification owner reports its own delivery failure. */ } + } + } this.dispatch(correlatedChatId, parsed); } } diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index c7008add9..e44343674 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -246,6 +246,7 @@ vi.mock("@/lib/bootstrap", () => ({ vi.mock("@/lib/nanobot-client", async (importOriginal) => { const actual = await importOriginal(); class MockClient { + onTaskNotice = () => () => {}; status = "idle" as const; defaultChatId = mockDefaultChatId; sendSystemCommand = sendSystemCommandSpy; diff --git a/webui/src/tests/browser-notifications.test.tsx b/webui/src/tests/browser-notifications.test.tsx new file mode 100644 index 000000000..753dc0631 --- /dev/null +++ b/webui/src/tests/browser-notifications.test.tsx @@ -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 ; +} + +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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); +}); diff --git a/webui/src/tests/host-bridge.test.tsx b/webui/src/tests/host-bridge.test.tsx index 9f450a3a9..4428da089 100644 --- a/webui/src/tests/host-bridge.test.tsx +++ b/webui/src/tests/host-bridge.test.tsx @@ -19,13 +19,13 @@ function addFrame() { function send(source: Window, data: Record, 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); diff --git a/webui/src/tests/host-sessions.test.tsx b/webui/src/tests/host-sessions.test.tsx index 0e4b6a23f..3f04fed4a 100644 --- a/webui/src/tests/host-sessions.test.tsx +++ b/webui/src/tests/host-sessions.test.tsx @@ -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); diff --git a/webui/src/tests/i18n.test.tsx b/webui/src/tests/i18n.test.tsx index a6d9c7300..76733a6d0 100644 --- a/webui/src/tests/i18n.test.tsx +++ b/webui/src/tests/i18n.test.tsx @@ -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", diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index 1ad4ae4fb..fc8c05a3f 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -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, diff --git a/webui/src/tests/sw.test.ts b/webui/src/tests/sw.test.ts index 53e4645a6..7040fcdfc 100644 --- a/webui/src/tests/sw.test.ts +++ b/webui/src/tests/sw.test.ts @@ -49,17 +49,25 @@ interface LoadedSw { fetchMock: ReturnType; skipWaitingMock: ReturnType; claimMock: ReturnType; + showNotification: ReturnType; + matchClients: ReturnType; + openWindow: ReturnType; + noticeStore: FakeCacheStore; fire: (type: string, event?: Record) => Promise; } -function loadSw(): LoadedSw { +function loadSw(noticeStore = new FakeCacheStore()): LoadedSw { const listeners = new Map) => 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) => void) => { listeners.set(type, [...(listeners.get(type) ?? []), cb]); }, @@ -69,6 +77,7 @@ function loadSw(): LoadedSw { const stores = new Map([ [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(