Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): refine browser notifications (NAN-227)
chengyongru11152626f88e
diff --git a/docs/guides/ai-agent-webui.md b/docs/guides/ai-agent-webui.mdindex ce532f7f5..3533aa6ca 100644--- a/docs/guides/ai-agent-webui.md+++ b/docs/guides/ai-agent-webui.md@@ -31,29 +31,14 @@ When nanobot edits a file, the WebUI activity timeline can show the changed line## 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.+When the WebUI is in the background, browser notifications tell you when a task finishes, fails, or needs attention. Click a notification to return to its chat.++1. Open **Settings → Notifications**.+2. Turn on **Browser notifications** and allow the browser's permission request.+3. Select **Test notification** to try it. If nothing appears, check the browser's site permissions, system notification settings, and Do Not Disturb.+4. Enable **Completion sound** separately if you want a page chime.++Keep the page open and connected, and use HTTPS or localhost. On iPhone or iPad, open the web app from the Home Screen. If your browser cannot enable notifications, follow the guidance shown in Settings.## Production notesdiff --git a/webui/browser/skeleton-additions-fixture.tsx b/webui/browser/skeleton-additions-fixture.tsxindex 7855e15d2..a437dd5c9 100644--- a/webui/browser/skeleton-additions-fixture.tsx+++ b/webui/browser/skeleton-additions-fixture.tsx@@ -47,6 +47,10 @@ const previewSettings: SettingsPayload = {let detailState = "loaded";export function installSkeletonPreviewApi() {+ // Windows headless Chromium can report denied even after a context permission grant.+ if (new URLSearchParams(location.search).get("notificationPermission") === "granted") {+ Object.defineProperty(Notification, "permission", { configurable: true, value: "granted" });+ }const fetch = window.fetch.bind(window);window.fetch = async (input, init) => {const url = new URL(input instanceof Request ? input.url : String(input), location.href);diff --git a/webui/browser/skeleton-additions.spec.ts b/webui/browser/skeleton-additions.spec.tsindex d681fb0f0..225ab84cc 100644--- a/webui/browser/skeleton-additions.spec.ts+++ b/webui/browser/skeleton-additions.spec.ts@@ -54,18 +54,38 @@ for (const width of [390, 1440]) for (const locale of ["en", "zh-CN"]) {}});- test("settings sections preserve their loaded row layout", async ({ page }) => {- for (const section of ["appearance", "capabilities", "runtime", "advanced", "overview", "models", "about"]) {- await page.goto(fixture("settings", "loaded", `§ion=${section}`));+ test("settings sections preserve their loaded row layout", async ({ page }, testInfo) => {+ for (const section of ["appearance", "notifications", "capabilities", "runtime", "advanced", "overview", "models", "about"]) {+ const extra = `§ion=${section}${section === "notifications" ? "¬ificationPermission=granted" : ""}`;+ await page.goto(fixture("settings", "loaded", extra));+ const target = page.locator("[data-settings-section]");+ if (section === "notifications") {+ await page.context().grantPermissions(["notifications"]);+ await page.evaluate(async () => {+ await navigator.serviceWorker.register("/sw.js", { scope: "/browser/" });+ await navigator.serviceWorker.ready;+ window.dispatchEvent(new Event("focus"));+ });+ await expect(target.getByRole("status")).toBeEmpty();+ await expect(target.getByRole("switch")).toHaveCount(2);+ await expect(target.getByRole("switch").first()).toBeEnabled();+ }if (section === "runtime") await expect(page.locator('[data-settings-section] button').filter({ hasText: locale === "en" ? "Start API server" : "启动 API 服务" })).toBeVisible();await settle(page);- const target = page.locator("[data-settings-section]");const selector = section === "overview" ? "section button.group" : section === "models" ? '[data-testid^="model-call-order-row"], .settings-footer' : section === "about" ? ".settings-list-row" : ".settings-row";- const loaded = await boxes(target.locator(selector));- await page.goto(fixture("settings", "loading", `§ion=${section}`));+ const notificationDetails = section === "notifications" ? ", .settings-list-inset > .border-t, section > p" : "";+ const loaded = await boxes(target.locator(selector + notificationDetails));+ const loadedControls = section === "notifications" ? await boxes(target.getByRole("switch")) : null;+ await page.goto(fixture("settings", "loading", extra));await settle(page);const skeletonSelector = section === "overview" ? "[data-overview-skeleton-row]" : section === "models" ? "[data-model-preset-skeleton], .settings-footer" : section === "about" ? ".settings-list-row" : "[data-settings-skeleton-row]";- sameBoxes(await boxes(target.locator(skeletonSelector)), loaded);+ const skeleton = await boxes(target.locator(skeletonSelector + notificationDetails));+ sameBoxes(skeleton, loaded);+ if (loadedControls) {+ const skeletonControls = await boxes(target.locator("[data-skeleton-switch]"));+ sameBoxes(skeletonControls, loadedControls);+ await testInfo.attach("notifications-layout", { body: JSON.stringify({ loaded, skeleton, loadedControls, skeletonControls }, null, 2), contentType: "application/json" });+ }await accessibleSkeleton(page);}});diff --git a/webui/public/sw.js b/webui/public/sw.jsindex da652b3fd..76a7c4293 100644--- a/webui/public/sw.js+++ b/webui/public/sw.js@@ -26,7 +26,8 @@ function notificationTarget(value) {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;+ || url.hash === "#/settings?section=appearance"+ || url.hash === "#/settings?section=notifications" ? url.href : null;} catch { return null; }}@@ -59,8 +60,12 @@ async function notifyClient(source, data) {}self.addEventListener("message", (event) => {- if (event.data?.type !== "nanobot:notify" || !event.source?.url- || new URL(event.source.url).origin !== self.location.origin) return;+ if (!event.source?.url || new URL(event.source.url).origin !== self.location.origin) return;+ if (event.data?.type === "nanobot:notification-probe") {+ event.ports[0]?.postMessage(typeof self.registration.showNotification === "function" ? "ready" : "workerUnavailable");+ return;+ }+ if (event.data?.type !== "nanobot:notify") return;const work = noticeQueue.then(() => notifyClient(event.source, event.data));noticeQueue = work.then(() => undefined, () => undefined);event.waitUntil(work.then(@@ -77,11 +82,12 @@ self.addEventListener("notificationclick", (event) => {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();+ if (source) {+ source.postMessage({ type: "nanobot:notification-click", url });+ await source.focus();} else {+ // Other tabs may run older code without the click receiver. Open the+ // destination normally instead of silently focusing an unrelated page.// Temporary chats belong to their original connection, not another tab.await self.clients.openWindow(temporary ? "/#/new" : url);}diff --git a/webui/src/App.tsx b/webui/src/App.tsxindex 01bb63f94..c49804e6c 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -73,7 +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 { BrowserNotifications, useBrowserNotificationLifecycle } from "@/components/BrowserNotifications";import { ThreadMessageCache } from "@/lib/thread-message-cache";import { FilePreviewStore } from "@/hooks/useFilePreviewState";import { ClientProvider, useClient } from "@/providers/ClientProvider";@@ -176,6 +176,7 @@ const SETTINGS_SECTION_KEYS: SettingsSectionKey[] = ["overview","about","appearance",+ "notifications","models","image","voice",@@ -938,6 +939,7 @@ function resolveRuntimeSurface(export default function App() {useAppViewport();+ useBrowserNotificationLifecycle();const { t } = useTranslation();const [state, setState] = useState<BootState>({ status: "loading" });const bootstrapSecretRef = useRef("");diff --git a/webui/src/components/BrowserNotifications.tsx b/webui/src/components/BrowserNotifications.tsxindex 73198ca3c..236bbff1a 100644--- a/webui/src/components/BrowserNotifications.tsx+++ b/webui/src/components/BrowserNotifications.tsx@@ -1,6 +1,6 @@import { useEffect } from "react";import { useTranslation } from "react-i18next";-import { NOTIFICATION_OPEN_EVENT, notificationChatUrl, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";+import { NOTIFICATION_OPEN_EVENT, notificationChatUrl, reconcileNotificationPermission, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";import type { NanobotClient } from "@/lib/nanobot-client";export function BrowserNotifications({ client }: { client: Pick<NanobotClient, "onTaskNotice"> }) {@@ -17,20 +17,36 @@ export function BrowserNotifications({ client }: { client: Pick<NanobotClient, "key, url: notificationChatUrl(event.chat_id, notice.temporary),});}), [client, t]);+ return null;+}++// Permission and click ownership survives authentication and route transitions.+export function useBrowserNotificationLifecycle() {+ useEffect(() => {+ reconcileNotificationPermission();+ window.addEventListener("focus", reconcileNotificationPermission);+ document.addEventListener("visibilitychange", reconcileNotificationPermission);+ return () => {+ window.removeEventListener("focus", reconcileNotificationPermission);+ document.removeEventListener("visibilitychange", reconcileNotificationPermission);+ };+ }, []);useEffect(() => {if (!("serviceWorker" in navigator)) return;const navigate = (event: MessageEvent<unknown>) => {const data = event.data as { type?: string; url?: unknown } | null;if (event.source !== navigator.serviceWorker.controller || data?.type !== "nanobot:notification-click" || typeof data.url !== "string") return;- const url = new URL(data.url);- if (url.origin === window.location.origin) {- window.location.hash = url.hash;- window.dispatchEvent(new Event(NOTIFICATION_OPEN_EVENT));- }+ let url: URL;+ try { url = new URL(data.url); } catch { return; }+ if (url.origin !== window.location.origin || url.username || url.password || url.search || url.pathname !== "/") return;+ if (!/^#\/(?:chat|temporary)\/[^?]+$/.test(url.hash)+ && url.hash !== "#/settings?section=notifications"+ && url.hash !== "#/settings?section=appearance") return;+ window.location.hash = url.hash;+ window.dispatchEvent(new Event(NOTIFICATION_OPEN_EVENT));};navigator.serviceWorker.addEventListener("message", navigate);return () => navigator.serviceWorker.removeEventListener("message", navigate);}, []);- return null;}diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsxindex 0d79bd8b2..53e86d899 100644--- a/webui/src/components/settings/SettingsPage.tsx+++ b/webui/src/components/settings/SettingsPage.tsx@@ -23,6 +23,7 @@ import {} from "@/components/settings/models/ProviderSettings";import { providerFormFromRow } from "@/components/settings/models/providerForm";import { AboutSettings, AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings";+import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings";import { SettingsSidebar, standaloneSectionTitle } from "@/components/settings/SettingsSidebar";import {NanobotFeatureInstallDialog,@@ -217,6 +218,8 @@ export function SettingsPage({);case "about":return <AboutSettings settings={settings} />;+ case "notifications":+ return <NotificationSettings localPrefs={localPrefs} onChangeLocalPrefs={setLocalPrefs} />;case "appearance":return (<AppearanceSettingsdiff --git a/webui/src/components/settings/SettingsSidebar.tsx b/webui/src/components/settings/SettingsSidebar.tsxindex c7bd407f4..5845875f7 100644--- a/webui/src/components/settings/SettingsSidebar.tsx+++ b/webui/src/components/settings/SettingsSidebar.tsx@@ -10,7 +10,7 @@ import {} from "@/components/icons/product-icons";import { useContext, useRef, useState } from "react";import { HostNavigationContext, HostSwitcher } from "@/components/remote/HostSwitcher";-import { Check, ChevronDown, ChevronLeft, LogOut, Loader2, type LucideIcon } from "lucide-react";+import { Bell, Check, ChevronDown, ChevronLeft, LogOut, Loader2, type LucideIcon } from "lucide-react";import { useTranslation } from "react-i18next";import {@@ -32,6 +32,7 @@ import { cn } from "@/lib/utils";const SETTINGS_NAV_ITEMS: Array<{ key: SettingsSectionKey; icon: LucideIcon; fallback: string }> = [{ key: "overview", icon: OverviewIcon, fallback: "Overview" },{ key: "appearance", icon: AppearanceIcon, fallback: "Appearance" },+ { key: "notifications", icon: Bell, fallback: "Notifications" },{ key: "models", icon: ModelsIcon, fallback: "Models" },{ key: "capabilities", icon: CapabilitiesIcon, fallback: "Capabilities" },{ key: "runtime", icon: SystemIcon, fallback: "System" },diff --git a/webui/src/components/settings/contracts.ts b/webui/src/components/settings/contracts.tsindex c617d6f5a..ddb2cc345 100644--- a/webui/src/components/settings/contracts.ts+++ b/webui/src/components/settings/contracts.ts@@ -6,6 +6,7 @@ export type SettingsSectionKey =| "overview"| "about"| "appearance"+ | "notifications"| "models"| "capabilities"| "image"diff --git a/webui/src/components/settings/notifications/BrowserNotificationSettings.tsx b/webui/src/components/settings/notifications/BrowserNotificationSettings.tsxnew file mode 100644index 000000000..255047ea8--- /dev/null+++ b/webui/src/components/settings/notifications/BrowserNotificationSettings.tsx@@ -0,0 +1,119 @@+import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";+import { useTranslation } from "react-i18next";+import { BellRing, Loader2 } from "lucide-react";+import { SettingsRow } from "@/components/settings/shared/SettingsControls";+import { ToggleButton } from "@/components/ui/toggle-button";+import { Button } from "@/components/ui/button";+import { HoverHint } from "@/components/ui/tooltip";+import { enableBrowserNotifications, lastNotificationProblem, NOTIFICATION_STATUS_EVENT, notificationProblem, notificationWorkerProblem, showBrowserNotification, type NotificationResult } from "@/lib/browser-notifications";+import type { LocalPreferences } from "@/lib/local-preferences";++export function BrowserNotificationSettings({ localPrefs, onChangeLocalPrefs }: {+ localPrefs: LocalPreferences;+ onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;+}) {+ const { t } = useTranslation();+ const hintId = useId();+ const [problem, setProblem] = useState(notificationProblem);+ const [workerProblem, setWorkerProblem] = useState<"workerUnavailable" | null>(null);+ const [feedback, setFeedback] = useState<NotificationResult | null>(lastNotificationProblem);+ const [busy, setBusy] = useState(false);+ const [checking, setChecking] = useState(false);+ const operation = useRef(0);+ const workerCheck = useRef(0);+ const refreshRef = useRef(() => {});++ useEffect(() => {+ const refresh = () => {+ const next = notificationProblem();+ setProblem(next);+ const id = ++workerCheck.current;+ setChecking(!next);+ if (!next) {+ void notificationWorkerProblem().then((value) => {+ if (id === workerCheck.current) {+ setWorkerProblem(value);+ setChecking(false);+ }+ });+ }+ };+ refreshRef.current = refresh;+ const deliveryStatus = () => { setFeedback(lastNotificationProblem()); refresh(); };+ refresh();+ window.addEventListener("focus", refresh);+ window.addEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);+ document.addEventListener("visibilitychange", refresh);+ navigator.serviceWorker?.addEventListener("controllerchange", refresh);+ return () => {+ workerCheck.current++;+ window.removeEventListener("focus", refresh);+ window.removeEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);+ document.removeEventListener("visibilitychange", refresh);+ navigator.serviceWorker?.removeEventListener("controllerchange", refresh);+ };+ }, []);+ useEffect(() => () => { operation.current++; }, []);++ const granted = typeof Notification !== "undefined" && Notification.permission === "granted";+ const enabled = localPrefs.browserNotifications && granted;+ const revoked = feedback === "revoked" && typeof Notification !== "undefined" && !granted;+ const detail = revoked ? "revoked" : problem || (feedback === "revoked" ? null : feedback) || workerProblem;+ const message = busy || checking ? t("settings.notifications.waiting")+ : detail && detail !== "skipped" ? t(`settings.notifications.${detail}`) : null;+ const canRetry = !!(problem || workerProblem || revoked || feedback === "workerUnavailable");++ async function toggle(value: boolean) {+ const id = ++operation.current;+ setFeedback(null);+ if (!value) {+ onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: false }));+ return;+ }+ setBusy(true);+ const result = await enableBrowserNotifications();+ if (id !== operation.current) return;+ setBusy(false);+ setProblem(notificationProblem());+ setWorkerProblem(result === "workerUnavailable" ? result : null);+ setFeedback(result);+ if (!result) {+ onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: true }));+ }+ }+ async function test() {+ const id = ++operation.current;+ setBusy(true);+ const result = await showBrowserNotification(t("settings.notifications.testBody"), {+ key: `test:${crypto.randomUUID()}`, url: `${window.location.origin}/#/settings?section=notifications`, test: true,+ });+ if (id !== operation.current) return;+ setBusy(false);+ setProblem(notificationProblem());+ setFeedback(lastNotificationProblem() ?? result);+ }+ return <div>+ <SettingsRow title={t("settings.rows.browserNotifications")}+ description={t("settings.help.browserNotifications")}>+ <>+ {enabled && <HoverHint content={t("settings.notifications.test")}>+ <Button type="button" variant="ghost" size="icon" aria-label={t("settings.notifications.test")}+ className="-my-1 me-3 h-11 w-11 shrink-0 text-muted-foreground sm:my-0 sm:h-9 sm:w-9"+ disabled={busy || checking || !!problem || !!workerProblem} onClick={() => void test()}>+ {busy ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : <BellRing className="h-4 w-4" aria-hidden />}+ </Button>+ </HoverHint>}+ <ToggleButton checked={enabled} disabled={busy || (!!problem && !localPrefs.browserNotifications)}+ onChange={(value) => void toggle(value)}+ ariaLabel={t("settings.rows.browserNotifications")} aria-describedby={message ? hintId : undefined}+ label={t(enabled ? "settings.values.on" : "settings.values.off")} />+ </>+ </SettingsRow>+ <div className={message || canRetry ? "settings-list-inset pb-3 text-[12px] leading-5 text-muted-foreground" : undefined}>+ <p id={hintId} role="status" aria-live="polite" aria-atomic="true">{message}</p>+ {canRetry && <Button type="button" variant="ghost" size="sm" disabled={busy || checking}+ className="-ms-2 mt-1 h-8 rounded-full px-2 text-[12px] text-muted-foreground"+ onClick={() => { setFeedback(null); refreshRef.current(); }}>{t("settings.notifications.retry")}</Button>}+ </div>+ </div>;+}diff --git a/webui/src/components/settings/notifications/NotificationSettings.tsx b/webui/src/components/settings/notifications/NotificationSettings.tsxnew file mode 100644index 000000000..28cbf8a06--- /dev/null+++ b/webui/src/components/settings/notifications/NotificationSettings.tsx@@ -0,0 +1,35 @@+import type { Dispatch, SetStateAction } from "react";+import { useTranslation } from "react-i18next";+import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";+import { ToggleButton } from "@/components/ui/toggle-button";+import type { LocalPreferences } from "@/lib/local-preferences";+import { BrowserNotificationSettings } from "./BrowserNotificationSettings";++export function NotificationSettings({ localPrefs, onChangeLocalPrefs }: {+ localPrefs: LocalPreferences;+ onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;+}) {+ const { t } = useTranslation();+ return (+ <div className="settings-stack">+ <section>+ <SettingsSectionTitle>{t("settings.notifications.scope")}</SettingsSectionTitle>+ <SettingsGroup>+ <BrowserNotificationSettings localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs} />+ <div className="settings-list-inset" aria-hidden="true">+ <div className="border-t border-border/40" />+ </div>+ <SettingsRow title={t("settings.rows.notificationSound")} description={t("settings.help.notificationSound")}>+ <ToggleButton checked={localPrefs.notificationSound}+ onChange={(notificationSound) => onChangeLocalPrefs((previous) => ({ ...previous, notificationSound }))}+ ariaLabel={t("settings.rows.notificationSound")}+ label={t(localPrefs.notificationSound ? "settings.values.on" : "settings.values.off")} />+ </SettingsRow>+ </SettingsGroup>+ <p className="settings-list-inset mt-3 text-[12px] leading-5 text-muted-foreground">+ {t("settings.notifications.pageRequired")}+ </p>+ </section>+ </div>+ );+}diff --git a/webui/src/components/settings/overview/AppearanceSettingsView.tsx b/webui/src/components/settings/overview/AppearanceSettingsView.tsxindex 237478c44..576543cee 100644--- a/webui/src/components/settings/overview/AppearanceSettingsView.tsx+++ b/webui/src/components/settings/overview/AppearanceSettingsView.tsx@@ -2,7 +2,6 @@ import type { Dispatch, SetStateAction } from "react";import { useTranslation } from "react-i18next";import { LanguageSwitcher } from "@/components/LanguageSwitcher";-import { BrowserNotificationSettings } from "./BrowserNotificationSettings";import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";import { ToggleButton } from "@/components/ui/toggle-button";import { SegmentedControl } from "@/components/ui/segmented-control";@@ -101,24 +100,6 @@ export function AppearanceSettingsView({label={localPrefs.brandLogos ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}/></SettingsRow>- <BrowserNotificationSettings localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs} />- <SettingsRow- title={tx("settings.rows.notificationSound", "Completion sound")}- description={tx(- "settings.help.notificationSound",- "Play a short chime when a turn finishes, even when this page is in the background. Off by default.",- )}- >- <ToggleButton- checked={localPrefs.notificationSound}- onChange={(notificationSound) =>- onChangeLocalPrefs((prev) => ({ ...prev, notificationSound }))}- ariaLabel={tx("settings.rows.notificationSound", "Completion sound")}- label={localPrefs.notificationSound- ? tx("settings.values.on", "On")- : tx("settings.values.off", "Off")}- />- </SettingsRow></SettingsGroup></section></div>diff --git a/webui/src/components/settings/overview/BrowserNotificationSettings.tsx b/webui/src/components/settings/overview/BrowserNotificationSettings.tsxdeleted file mode 100644index 115aacdde..000000000--- a/webui/src/components/settings/overview/BrowserNotificationSettings.tsx+++ /dev/null@@ -1,76 +0,0 @@-import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";-import { useTranslation } from "react-i18next";-import { SettingsRow } from "@/components/settings/shared/SettingsControls";-import { ToggleButton } from "@/components/ui/toggle-button";-import { Button } from "@/components/ui/button";-import { enableBrowserNotifications, lastNotificationProblem, NOTIFICATION_STATUS_EVENT, notificationProblem, showBrowserNotification, type NotificationResult } from "@/lib/browser-notifications";-import type { LocalPreferences } from "@/lib/local-preferences";--export function BrowserNotificationSettings({ localPrefs, onChangeLocalPrefs }: {- localPrefs: LocalPreferences;- onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;-}) {- const { t } = useTranslation();- const hintId = useId();- const [problem, setProblem] = useState(notificationProblem);- const [feedback, setFeedback] = useState<NotificationResult | null>(lastNotificationProblem);- const [busy, setBusy] = useState(false);- const operation = useRef(0);- useEffect(() => {- const refresh = () => {- setProblem(notificationProblem());- setFeedback((current) => current === "submitted" || current === "displayFailed" || current === "workerUnavailable" ? current : null);- };- const deliveryStatus = () => setFeedback(lastNotificationProblem());- window.addEventListener("focus", refresh);- window.addEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);- document.addEventListener("visibilitychange", refresh);- return () => {- operation.current++;- window.removeEventListener("focus", refresh);- window.removeEventListener(NOTIFICATION_STATUS_EVENT, deliveryStatus);- document.removeEventListener("visibilitychange", refresh);- };- }, []);- const enabled = localPrefs.browserNotifications && !problem && Notification.permission === "granted";- const status = problem || feedback || (localPrefs.browserNotifications && !enabled ? "dismissed" : null);- async function toggle(value: boolean) {- const id = ++operation.current;- setFeedback(null);- if (!value) {- onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: false }));- return;- }- setBusy(true);- const result = await enableBrowserNotifications();- if (id !== operation.current) return;- setBusy(false);- setProblem(notificationProblem());- setFeedback(result);- if (!result) onChangeLocalPrefs((previous) => ({ ...previous, browserNotifications: true }));- }- async function test() {- const id = ++operation.current;- setBusy(true);- const result = await showBrowserNotification(t("settings.notifications.testBody"), {- key: `test:${crypto.randomUUID()}`, url: `${window.location.origin}/#/settings?section=appearance`, test: true,- });- if (id !== operation.current) return;- setBusy(false);- setProblem(notificationProblem());- setFeedback(result);- }- return <div>- <SettingsRow title={t("settings.rows.browserNotifications")}>- <ToggleButton checked={localPrefs.browserNotifications} disabled={busy || (!!problem && !localPrefs.browserNotifications)}- onChange={(value) => void toggle(value)}- ariaLabel={t("settings.rows.browserNotifications")} aria-describedby={hintId}- label={t(localPrefs.browserNotifications ? "settings.values.on" : "settings.values.off")} />- </SettingsRow>- <div id={hintId} className="px-[var(--settings-inset,16px)] pb-4 text-[12px] leading-5 text-muted-foreground">- <p>{t("settings.help.browserNotifications")}</p>- <p role="status" aria-live="polite">{busy ? t("settings.notifications.waiting") : status && status !== "skipped" ? t(`settings.notifications.${status}`) : null}</p>- {enabled && <Button variant="ghost" size="sm" className="mt-1 h-8 px-2 text-xs" disabled={busy} onClick={() => void test()}>{t("settings.notifications.test")}</Button>}- </div>- </div>;-}diff --git a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsxindex 1d7078253..5c9cac626 100644--- a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx+++ b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx@@ -23,7 +23,7 @@ function Row({ control }: { control: Control }) {<div className="settings-control">{control === "feature" ? <div className={cn(block, "mr-3 h-3 w-14")} /> : null}{control === "duration" ? <div className="w-full"><div className={cn(block, "h-9 w-full rounded-full")} /><div className="mt-1.5 flex h-4 items-center"><div className={cn(block, "h-2.5 w-4/5 opacity-60")} /></div></div> : <div data-skeleton-switch={toggle ? "" : undefined} className={cn(block,- toggle ? "h-5 w-[38px] shrink-0 rounded-full" : control === "input" ? "h-9 w-full rounded-full"+ toggle ? "h-5 w-9 shrink-0 rounded-full" : control === "input" ? "h-9 w-full rounded-full": control === "segments" || control === "theme" ? "segmented-control w-44 rounded-full" : control === "edit" ? "ml-auto h-9 w-9 rounded-full" : "h-[19.5px] w-24",control === "segments" && "h-[34px]", control === "theme" && "h-8",)} />}@@ -52,7 +52,14 @@ export function SettingsSectionSkeleton({ section, showRestart = false }: { sect</>;else switch (section) {case "appearance":- content = <><Group controls={["theme", "input"]} /><Group controls={["segments", "segments", "switch", "switch", "switch", "switch"]} /></>;+ content = <><Group controls={["theme", "input"]} /><Group controls={["segments", "segments", "switch", "switch"]} /></>;+ break;+ case "notifications":+ content = <section><Title /><SettingsGroup>+ <Row control="switch" />+ <div className="settings-list-inset" aria-hidden="true"><div className="border-t border-border/40" /></div>+ <Row control="switch" />+ </SettingsGroup><p className="settings-list-inset mt-3 text-[12px] leading-5"><span className={cn(block, "text-transparent")}>{t("settings.notifications.pageRequired")}</span></p></section>;break;case "overview":content = <>diff --git a/webui/src/components/settings/useSettingsController.ts b/webui/src/components/settings/useSettingsController.tsindex e87668f41..3323f1390 100644--- a/webui/src/components/settings/useSettingsController.ts+++ b/webui/src/components/settings/useSettingsController.ts@@ -37,6 +37,7 @@ import { usePageVisibility } from "@/hooks/usePageVisibility";import { useAutoSave } from "@/components/settings/shared/useAutoSave";import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api";import {+ LOCAL_PREFS_CHANGED_EVENT,readLocalPreferences,writeLocalPreferences,type LocalPreferences,@@ -257,6 +258,18 @@ export function useSettingsController({pageVisible,});+ useEffect(() => {+ const synchronize = (event: Event) => setLocalPrefs((event as CustomEvent<LocalPreferences>).detail);+ const reload = () => setLocalPrefs(readLocalPreferences());+ window.addEventListener(LOCAL_PREFS_CHANGED_EVENT, synchronize);+ window.addEventListener("storage", reload);+ window.addEventListener("focus", reload);+ return () => {+ window.removeEventListener(LOCAL_PREFS_CHANGED_EVENT, synchronize);+ window.removeEventListener("storage", reload);+ window.removeEventListener("focus", reload);+ };+ }, []);useEffect(() => {writeLocalPreferences(localPrefs);}, [localPrefs]);diff --git a/webui/src/dev/gallery/runtime-settings.tsx b/webui/src/dev/gallery/runtime-settings.tsxindex d91b740a1..679e76018 100644--- a/webui/src/dev/gallery/runtime-settings.tsx+++ b/webui/src/dev/gallery/runtime-settings.tsx@@ -81,8 +81,7 @@ function AppearancePreview() {const [theme, setTheme] = useState<"light" | "dark">("light");const [preferences, setPreferences] = useState(DEFAULT_LOCAL_PREFS);return <><AppearanceSettingsView theme={theme} onToggleTheme={() => setTheme((current) => current === "light" ? "dark" : "light")}- localPrefs={preferences} onChangeLocalPrefs={setPreferences}- onChangeBrowserNotifications={(enabled) => setPreferences((current) => ({ ...current, browserNotifications: enabled }))} />+ localPrefs={preferences} onChangeLocalPrefs={setPreferences} /><pre role="status" className="mt-4 overflow-auto rounded-control bg-muted p-4 text-xs">{JSON.stringify({ theme, ...preferences }, null, 2)}</pre></>;}diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.tsindex 91c61b3d5..6a7464eac 100644--- a/webui/src/hooks/useNanobotStream.ts+++ b/webui/src/hooks/useNanobotStream.ts@@ -1,5 +1,6 @@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";@@ -173,6 +174,7 @@ 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<UIMessage[]>(initialMessages);const messagesRef = useRef(messages);@@ -903,6 +905,7 @@ export function useNanobotStream(onStreamDetach,schedulePendingStreamFlush,setMessages,+ t,]);const send = useCallback(diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex 596e9a33b..c00efffd8 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -665,6 +665,7 @@"byok": "BYOK","overview": "Overview","appearance": "Appearance",+ "notifications": "Notifications","models": "Models","providers": "Providers","image": "Image",@@ -772,20 +773,34 @@"availableCount": "Models available: {{count}}"},"notifications": {+ "scope": "This browser",+ "intro": "Choose how to be notified when a task finishes.",+ "pageRequired": "No new alerts when this page is closed, suspended, or disconnected.",+ "revoked": "Notification permission was revoked. Notifications are now off. Allow notifications in this browser’s site settings, then turn them on here.",+ "retry": "Check again",+ "statusOff": "Off",+ "statusPermission": "Permission needed",+ "statusOn": "On",+ "statusBlocked": "Blocked",+ "statusRevoked": "Permission revoked",+ "statusUnavailable": "Unavailable",+ "statusWorker": "Not ready",+ "statusBusy": "Checking…",+ "statusError": "Could not send","test": "Test notification",- "testBody": "This is a test notification from nanobot.",+ "testBody": "This is a test notification.","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.",+ "unsupported": "This browser doesn’t support notifications. Try another browser; on iPhone or iPad, open nanobot from the Home Screen.",+ "denied": "Notifications are blocked. Allow notifications in this browser’s site settings, then turn them on here.","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.",+ "workerUnavailable": "The notification service is not ready. Check again or reload this page.","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."+ "completed": "Task completed. Click to view the result.",+ "failed": "Task failed. Click for details.",+ "interrupted": "Task needs attention. Click to continue."},"rows": {"theme": "Theme",@@ -851,8 +866,8 @@"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": "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.",+ "browserNotifications": "Get task status notifications while this page is in the background.",+ "notificationSound": "Play a chime when a reply ends, even in the background.","maxResults": "Maximum results per search.","timeout": "Maximum wait per search, in seconds.","jinaReader": "Prefer Jina Reader for reading pages.\n\nUse Jina Reader to read web pages when available.",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 9e77e7a29..723329cf0 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "Resumen","appearance": "Apariencia",+ "notifications": "Notificaciones","models": "Modelos","providers": "Proveedores","image": "Imagen",@@ -517,20 +518,34 @@"voiceInput": "Transcripción"},"notifications": {+ "scope": "Este navegador",+ "intro": "Elige cómo recibir avisos cuando termine una tarea.",+ "pageRequired": "No recibirás nuevos avisos si esta página está cerrada, suspendida o desconectada.",+ "revoked": "Se ha revocado el permiso de notificaciones y se han desactivado los avisos. Permite las notificaciones en los ajustes de este sitio en el navegador y luego actívalas aquí.",+ "retry": "Volver a comprobar",+ "statusOff": "Desactivadas",+ "statusPermission": "Permiso necesario",+ "statusOn": "Activadas",+ "statusBlocked": "Bloqueadas",+ "statusRevoked": "Permiso revocado",+ "statusUnavailable": "No disponibles",+ "statusWorker": "Aún no está listo",+ "statusBusy": "Comprobando…",+ "statusError": "No se pudo enviar","test": "Probar notificaciones",- "testBody": "Esta es una notificación de prueba de nanobot.",+ "testBody": "Esta es una notificación de prueba.","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.",+ "unsupported": "Este navegador no admite notificaciones. Prueba otro; 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 en el navegador y luego actívalas aquí.","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.",+ "workerUnavailable": "El servicio de notificaciones no está listo. Vuelve a comprobarlo o recarga esta página.","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."+ "completed": "Tarea completada. Haz clic para ver el resultado.",+ "failed": "La tarea falló. Haz clic para ver los detalles.",+ "interrupted": "La tarea necesita atención. Haz clic para continuar."},"rows": {"theme": "Tema",@@ -610,8 +625,8 @@"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": "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.",+ "browserNotifications": "Recibe avisos del estado de las tareas con esta página en segundo plano.",+ "notificationSound": "Reproduce un sonido al terminar una respuesta, incluso en segundo plano.","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.","logs": "Abre la carpeta de registros del motor de la app de escritorio.",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex c30cf6c7c..0b8e8f9f4 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "Vue d’ensemble","appearance": "Apparence",+ "notifications": "Notifications","models": "Modèles","providers": "Fournisseurs","image": "Images",@@ -517,20 +518,34 @@"voiceInput": "Transcription"},"notifications": {+ "scope": "Ce navigateur",+ "intro": "Choisissez comment recevoir une alerte à la fin d’une tâche.",+ "pageRequired": "Aucune nouvelle alerte si cette page est fermée, suspendue ou déconnectée.",+ "revoked": "L’autorisation d’afficher des notifications a été révoquée. Les notifications sont désormais désactivées. Autorisez-les dans les paramètres du navigateur pour ce site, puis activez-les ici.",+ "retry": "Vérifier à nouveau",+ "statusOff": "Désactivées",+ "statusPermission": "Autorisation requise",+ "statusOn": "Activées",+ "statusBlocked": "Bloquées",+ "statusRevoked": "Autorisation révoquée",+ "statusUnavailable": "Indisponibles",+ "statusWorker": "Pas prêt",+ "statusBusy": "Vérification…",+ "statusError": "Échec de l’envoi","test": "Tester les notifications",- "testBody": "Ceci est une notification de test de nanobot.",+ "testBody": "Ceci est une notification de test.","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.",+ "unsupported": "Ce navigateur ne prend pas en charge les notifications. Essayez-en un autre ; sur iPhone ou iPad, ouvrez nanobot depuis l’écran d’accueil.",+ "denied": "Les notifications sont bloquées. Autorisez-les dans les paramètres du navigateur pour ce site, puis activez-les ici.","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.",+ "workerUnavailable": "Le service de notifications n’est pas prêt. Vérifiez à nouveau ou rechargez cette page.","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."+ "submitted": "Transmise au navigateur. Si elle n’apparaît pas, vérifiez les notifications système et le mode Ne pas déranger.",+ "completed": "Tâche terminée. Cliquez pour voir le résultat.",+ "failed": "La tâche a échoué. Cliquez pour les détails.",+ "interrupted": "La tâche demande votre attention. Cliquez pour continuer."},"rows": {"theme": "Thème",@@ -610,8 +625,8 @@"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": "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.",+ "browserNotifications": "Recevez les notifications des tâches lorsque cette page est en arrière-plan.",+ "notificationSound": "Joue un son à la fin d’une réponse, même en arrière-plan.","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.","logs": "Ouvrez le dossier des journaux du moteur de l’application de bureau.",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 01d82c848..6f825b291 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "Ringkasan","appearance": "Tampilan",+ "notifications": "Notifikasi","models": "Model","providers": "Penyedia","image": "Gambar",@@ -517,20 +518,34 @@"voiceInput": "Transkripsi"},"notifications": {+ "scope": "Browser ini",+ "intro": "Pilih cara menerima notifikasi saat tugas selesai.",+ "pageRequired": "Notifikasi baru tidak diterima jika halaman ditutup, ditangguhkan, atau terputus.",+ "revoked": "Izin notifikasi telah dicabut. Notifikasi kini dinonaktifkan. Izinkan notifikasi di pengaturan situs pada browser ini, lalu aktifkan di sini.",+ "retry": "Periksa lagi",+ "statusOff": "Nonaktif",+ "statusPermission": "Perlu izin",+ "statusOn": "Aktif",+ "statusBlocked": "Diblokir",+ "statusRevoked": "Izin dicabut",+ "statusUnavailable": "Tidak tersedia",+ "statusWorker": "Belum siap",+ "statusBusy": "Memeriksa…",+ "statusError": "Gagal mengirim","test": "Uji notifikasi",- "testBody": "Ini adalah notifikasi uji dari nanobot.",+ "testBody": "Ini adalah notifikasi uji.","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.",+ "unsupported": "Browser ini tidak mendukung notifikasi. Coba browser lain; di iPhone atau iPad, buka nanobot dari Layar Utama.",+ "denied": "Notifikasi diblokir. Izinkan notifikasi di pengaturan situs pada browser ini, lalu aktifkan di sini.","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.",+ "workerUnavailable": "Layanan notifikasi belum siap. Periksa lagi atau muat ulang halaman ini.","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."+ "completed": "Tugas selesai. Klik untuk melihat hasilnya.",+ "failed": "Tugas gagal. Klik untuk melihat detailnya.",+ "interrupted": "Tugas perlu perhatian. Klik untuk melanjutkan."},"rows": {"theme": "Tema",@@ -610,8 +625,8 @@"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 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.",+ "browserNotifications": "Terima notifikasi status tugas saat halaman ini di latar belakang.",+ "notificationSound": "Putar nada saat balasan selesai, termasuk di latar belakang.","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.","logs": "Buka folder log mesin aplikasi desktop.",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex f9b12284c..3ea82b892 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "概要","appearance": "外観",+ "notifications": "通知","models": "モデル","providers": "プロバイダー","image": "画像",@@ -517,20 +518,34 @@"voiceInput": "音声の文字起こし"},"notifications": {+ "scope": "このブラウザー",+ "intro": "タスク終了時の通知方法を選んでください。",+ "pageRequired": "ページの終了・一時停止・切断中は、新しい通知を受信できません。",+ "revoked": "通知の許可が取り消されたため、通知をオフにしました。このブラウザーのサイト設定で通知を許可してから、ここでオンにしてください。",+ "retry": "再確認",+ "statusOff": "オフ",+ "statusPermission": "許可が必要",+ "statusOn": "オン",+ "statusBlocked": "ブロック中",+ "statusRevoked": "許可が取り消されました",+ "statusUnavailable": "利用不可",+ "statusWorker": "準備未完了",+ "statusBusy": "確認中…",+ "statusError": "送信失敗","test": "通知をテスト",- "testBody": "nanobot からのテスト通知です。",+ "testBody": "これはテスト通知です。","waiting": "ブラウザーの応答を待っています…","insecure": "通知を使うには、HTTPS または localhost で nanobot を開いてください。",- "unsupported": "このブラウザーは通知に対応していません。対応ブラウザーをお使いください。iPhone や iPad ではホーム画面から nanobot を開いてください。",- "denied": "通知がブロックされています。ブラウザーのサイト設定で通知を許可してから再試行してください。",+ "unsupported": "このブラウザーは通知に非対応です。別のブラウザーをお試しください。iPhone や iPad ではホーム画面から nanobot を開いてください。",+ "denied": "通知がブロックされています。このブラウザーのサイト設定で通知を許可してから、ここでオンにしてください。","dismissed": "通知が許可されていません。通知を有効にして「許可」を選んでください。","permissionFailed": "通知の許可を要求できませんでした。対応ブラウザーで再試行してください。",- "workerUnavailable": "通知サービスの準備ができていません。ページを再読み込みして再試行してください。",+ "workerUnavailable": "通知サービスの準備ができていません。再確認するか、このページを再読み込みしてください。","displayFailed": "通知を送信できませんでした。サイトの通知権限を確認して再試行してください。","submitted": "ブラウザーに送信しました。表示されない場合は、システムの通知とおやすみモードを確認してください。",- "completed": "タスクが完了しました。nanobot で結果を確認してください。",- "failed": "タスクが失敗しました。nanobot で詳細を確認してください。",- "interrupted": "対応が必要です。nanobot を開いて続行してください。"+ "completed": "タスクが完了しました。クリックして結果を確認。",+ "failed": "タスクが失敗しました。クリックして詳細を確認。",+ "interrupted": "対応が必要です。クリックして続行。"},"rows": {"theme": "テーマ",@@ -610,8 +625,8 @@"selectedModelProvider": "選択したモデルによって設定されます。","selectedModelValue": "選択したモデルによって設定されます。","brandLogos": "設定画面にプロバイダーとアプリのロゴを表示します。\n\n設定で第三者プロバイダーと CLI のロゴを表示します。",- "browserNotifications": "ページがバックグラウンドにあるとき、タスクの終了や対応が必要な状態を通知します。ページを開いたままにしてください。閉じたり休止したりすると新しい通知は届きません。",- "notificationSound": "返信完了時に音を鳴らします。既定はオフです。\n\nターンが完了したら、ページがバックグラウンドにあっても短いチャイムを再生します。既定ではオフです。",+ "browserNotifications": "ページがバックグラウンドのときにタスクの状況を通知します。",+ "notificationSound": "返信の終了時に、バックグラウンドでも通知音を鳴らします。","cliAppsCatalog": "nanobot 用の CLI ツールをインストールします。デスクトップアプリは変わりません。\n\nnanobot がこのマシンで使用できるコマンドラインツールをインストールします。デスクトップアプリは変更しません。","cliAppsFilter": "名前、分類、機能で検索します。","logs": "デスクトップアプリのエンジンログを開きます。",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 060c3cd07..2c52b25dd 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "개요","appearance": "외관",+ "notifications": "알림","models": "모델","providers": "제공업체","image": "이미지",@@ -517,20 +518,34 @@"voiceInput": "음성 텍스트 변환"},"notifications": {+ "scope": "이 브라우저",+ "intro": "작업이 끝났을 때 알림을 받을 방법을 선택하세요.",+ "pageRequired": "페이지가 닫히거나 일시 중지되거나 연결이 끊기면 새 알림을 받을 수 없습니다.",+ "revoked": "알림 권한이 취소되어 알림이 꺼졌습니다. 이 브라우저의 사이트 설정에서 알림을 허용한 후 여기에서 다시 켜세요.",+ "retry": "다시 확인",+ "statusOff": "꺼짐",+ "statusPermission": "권한 필요",+ "statusOn": "켜짐",+ "statusBlocked": "차단됨",+ "statusRevoked": "권한 취소됨",+ "statusUnavailable": "사용 불가",+ "statusWorker": "준비되지 않음",+ "statusBusy": "확인 중…",+ "statusError": "전송 실패","test": "알림 테스트",- "testBody": "nanobot 테스트 알림입니다.",+ "testBody": "테스트 알림입니다.","waiting": "브라우저 응답 대기 중…","insecure": "알림을 사용하려면 HTTPS 또는 localhost로 nanobot을 여세요.",- "unsupported": "이 브라우저는 알림을 지원하지 않습니다. 지원하는 브라우저를 사용하세요. iPhone이나 iPad에서는 홈 화면에서 nanobot을 여세요.",- "denied": "알림이 차단되었습니다. 브라우저의 사이트 설정에서 알림을 허용한 후 다시 시도하세요.",+ "unsupported": "이 브라우저는 알림을 지원하지 않습니다. 다른 브라우저를 사용하세요. iPhone이나 iPad에서는 홈 화면에서 nanobot을 여세요.",+ "denied": "알림이 차단되었습니다. 이 브라우저의 사이트 설정에서 알림을 허용한 후 여기에서 켜세요.","dismissed": "알림 권한을 받지 못했습니다. 알림을 켜고 허용을 선택하세요.","permissionFailed": "권한을 요청할 수 없습니다. 지원하는 브라우저에서 다시 시도하세요.",- "workerUnavailable": "알림 서비스가 준비되지 않았습니다. 페이지를 새로 고침한 후 다시 시도하세요.",+ "workerUnavailable": "알림 서비스가 준비되지 않았습니다. 다시 확인하거나 이 페이지를 새로 고침하세요.","displayFailed": "브라우저가 알림을 보내지 못했습니다. 사이트 알림 권한을 확인하고 다시 시도하세요.",- "submitted": "브라우저에 전송했습니다. 표시되지 않으면 시스템 알림과 방해 금지 설정을 확인하세요.",- "completed": "작업이 완료되었습니다. nanobot에서 결과를 확인하세요.",- "failed": "작업이 실패했습니다. nanobot에서 자세히 확인하세요.",- "interrupted": "확인이 필요합니다. nanobot을 열어 계속하세요."+ "submitted": "브라우저에 전달했습니다. 표시되지 않으면 시스템 알림과 방해 금지 설정을 확인하세요.",+ "completed": "작업이 완료되었습니다. 눌러서 결과를 확인하세요.",+ "failed": "작업이 실패했습니다. 눌러서 자세히 확인하세요.",+ "interrupted": "확인이 필요합니다. 눌러서 계속하세요."},"rows": {"theme": "테마",@@ -610,8 +625,8 @@"selectedModelProvider": "선택한 모델에 의해 설정됩니다.","selectedModelValue": "선택한 모델에 의해 설정됩니다.","brandLogos": "설정에 제공업체와 앱 로고를 표시합니다.\n\n설정에서 타사 제공업체와 CLI 로고를 표시합니다.",- "browserNotifications": "페이지가 백그라운드에 있을 때 작업 종료 또는 확인이 필요한 상태를 알립니다. 페이지를 열어 두세요. 닫히거나 일시 중지되면 새 알림을 받을 수 없습니다.",- "notificationSound": "답변이 끝나면 알림음을 재생합니다. 기본은 꺼짐입니다.\n\n턴이 끝나면 이 페이지가 백그라운드에 있어도 짧은 알림음을 재생합니다. 기본적으로 꺼져 있습니다.",+ "browserNotifications": "페이지가 백그라운드에 있을 때 작업 상태를 알립니다.",+ "notificationSound": "응답이 끝나면 백그라운드에서도 알림음을 재생합니다.","cliAppsCatalog": "nanobot용 CLI 도구를 설치합니다. 데스크톱 앱은 변경되지 않습니다.\n\nnanobot이 이 컴퓨터에서 사용할 수 있는 명령줄 도구를 설치합니다. 데스크톱 앱은 변경하지 않습니다.","cliAppsFilter": "이름, 분류 또는 기능으로 검색하세요.","logs": "데스크톱 앱의 엔진 로그 폴더를 엽니다.",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex df701b45e..1d323cadc 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "Visão geral","appearance": "Aparência",+ "notifications": "Notificações","models": "Modelos","providers": "Provedores","image": "Imagem",@@ -586,20 +587,34 @@"autoProviderCustomOnly": "Digite um ID de modelo para usar a seleção automática de provedor."},"notifications": {+ "scope": "Este navegador",+ "intro": "Escolha como receber um aviso quando uma tarefa terminar.",+ "pageRequired": "Sem novos alertas se esta página estiver fechada, suspensa ou desconectada.",+ "revoked": "A permissão para notificações foi revogada. Os avisos agora estão desativados. Permita notificações nas configurações deste site no navegador e depois ative-as aqui.",+ "retry": "Verificar novamente",+ "statusOff": "Desativadas",+ "statusPermission": "Permissão necessária",+ "statusOn": "Ativadas",+ "statusBlocked": "Bloqueadas",+ "statusRevoked": "Permissão revogada",+ "statusUnavailable": "Indisponíveis",+ "statusWorker": "Não está pronto",+ "statusBusy": "Verificando…",+ "statusError": "Não foi possível enviar","test": "Testar notificações",- "testBody": "Esta é uma notificação de teste do nanobot.",+ "testBody": "Esta é uma notificação de teste.","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.",+ "unsupported": "Este navegador não oferece suporte a notificações. Tente outro; 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 no navegador e depois ative-as aqui.","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.",+ "workerUnavailable": "O serviço de notificações não está pronto. Verifique novamente ou recarregue esta página.","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."+ "submitted": "Enviada ao navegador. Se não aparecer, verifique as notificações do sistema e o modo Não Perturbe.",+ "completed": "Tarefa concluída. Clique para ver o resultado.",+ "failed": "A tarefa falhou. Clique para ver os detalhes.",+ "interrupted": "A tarefa precisa de atenção. Clique para continuar."},"rows": {"theme": "Tema",@@ -665,8 +680,8 @@"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": "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.",+ "browserNotifications": "Receba avisos sobre o estado das tarefas com esta página em segundo plano.",+ "notificationSound": "Toca um som ao terminar uma resposta, mesmo em segundo plano.","maxResults": "Máximo de resultados por busca.","timeout": "Espera máxima por busca, em segundos.","jinaReader": "Prefira Jina Reader para ler páginas.\n\nUsa o Jina Reader para ler páginas web quando disponível.",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex 3105b5cf5..541a5f840 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "Tổng quan","appearance": "Giao diện",+ "notifications": "Thông báo","models": "Mô hình","providers": "Nhà cung cấp","image": "Hình ảnh",@@ -517,20 +518,34 @@"voiceInput": "Chép lời"},"notifications": {+ "scope": "Trình duyệt này",+ "intro": "Chọn cách nhận thông báo khi tác vụ kết thúc.",+ "pageRequired": "Không nhận được thông báo mới khi trang này bị đóng, tạm ngưng hoặc mất kết nối.",+ "revoked": "Quyền thông báo đã bị thu hồi. Thông báo hiện đã tắt. Hãy cho phép thông báo trong cài đặt trang web của trình duyệt này, rồi bật tại đây.",+ "retry": "Kiểm tra lại",+ "statusOff": "Đã tắt",+ "statusPermission": "Cần cấp quyền",+ "statusOn": "Đã bật",+ "statusBlocked": "Bị chặn",+ "statusRevoked": "Quyền đã bị thu hồi",+ "statusUnavailable": "Không khả dụng",+ "statusWorker": "Chưa sẵn sàng",+ "statusBusy": "Đang kiểm tra…",+ "statusError": "Không thể gửi","test": "Thử thông báo",- "testBody": "Đây là thông báo thử từ nanobot.",+ "testBody": "Đây là thông báo thử.","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.",+ "unsupported": "Trình duyệt này không hỗ trợ thông báo. Hãy thử trình duyệt khác; 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 thông báo trong cài đặt trang web của trình duyệt này, rồi bật tại đây.","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.",+ "workerUnavailable": "Dịch vụ thông báo chưa sẵn sàng. Hãy kiểm tra lại hoặc tải lại trang này.","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."+ "completed": "Tác vụ đã hoàn tất. Nhấp để xem kết quả.",+ "failed": "Tác vụ thất bại. Nhấp để xem chi tiết.",+ "interrupted": "Tác vụ cần chú ý. Nhấp để tiếp tục."},"rows": {"theme": "Chủ đề",@@ -610,8 +625,8 @@"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 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.",+ "browserNotifications": "Nhận thông báo trạng thái tác vụ khi trang này ở nền.",+ "notificationSound": "Phát âm báo khi phản hồi kết thúc, kể cả khi trang ở nền.","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.","logs": "Mở thư mục nhật ký engine của ứng dụng máy tính.",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 7433c91b1..a32a30177 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -665,6 +665,7 @@"byok": "BYOK","overview": "总览","appearance": "外观",+ "notifications": "通知","models": "模型","providers": "提供商","image": "图片",@@ -772,20 +773,34 @@"availableCount": "可用模型:{{count}} 个"},"notifications": {+ "scope": "本浏览器",+ "intro": "选择任务结束时的提醒方式。",+ "pageRequired": "页面关闭、挂起或断开连接后,无法接收新提醒。",+ "revoked": "通知权限已撤销,已关闭提醒。请先在浏览器站点设置中允许通知,再在此开启。",+ "retry": "重新检查",+ "statusOff": "未开启",+ "statusPermission": "需要授权",+ "statusOn": "已开启",+ "statusBlocked": "已被拒绝",+ "statusRevoked": "权限已撤销",+ "statusUnavailable": "不可用",+ "statusWorker": "尚未就绪",+ "statusBusy": "检查中…",+ "statusError": "发送失败","test": "测试通知",- "testBody": "这是一条 nanobot 测试通知。",+ "testBody": "这是一条测试通知。","waiting": "等待浏览器响应…","insecure": "请通过 HTTPS 或 localhost 打开 nanobot,再开启通知。",- "unsupported": "此浏览器不支持通知,请换用支持的浏览器。iPhone 或 iPad 需从主屏幕打开 nanobot。",- "denied": "通知已被浏览器阻止。请在本站的浏览器设置中允许通知,再重试。",+ "unsupported": "此浏览器不支持通知,请更换浏览器。iPhone 或 iPad 请从主屏幕打开 nanobot。",+ "denied": "通知已被浏览器阻止。请先在浏览器站点设置中允许通知,再在此开启。","dismissed": "尚未获得通知权限。请重新开启,并选择“允许”。","permissionFailed": "无法请求通知权限,请在支持的浏览器中重试。",- "workerUnavailable": "通知服务尚未就绪,请刷新页面后重试。",+ "workerUnavailable": "通知服务尚未就绪,请重新检查或刷新页面。","displayFailed": "浏览器未能发送通知,请检查本站的通知权限后重试。",- "submitted": "已提交给浏览器。如未看到通知,请检查系统通知和勿扰设置。",- "completed": "任务已完成,打开 nanobot 查看结果。",- "failed": "任务未完成,打开 nanobot 查看详情。",- "interrupted": "任务需要处理,打开 nanobot 继续。"+ "submitted": "已发送至浏览器。若未显示,请检查系统通知和勿扰设置。",+ "completed": "任务已完成,点击查看结果。",+ "failed": "任务失败,点击查看详情。",+ "interrupted": "任务需要处理,点击继续。"},"rows": {"theme": "主题",@@ -851,8 +866,8 @@"fileEditDisplay": "默认显示行数或展开修改内容","codeWrap": "长代码自动换行,方便阅读","brandLogos": "在设置中显示提供商与应用图标\n\n在设置中显示提供商和命令行应用的品牌图标。",- "browserNotifications": "网页在后台时,提醒任务结束或需要处理。请保持网页打开;关闭或挂起后无法接收新通知。",- "notificationSound": "回复结束播放提示音,默认关闭\n\n回合结束时播放短促提示音,页面在后台时也会播放。默认关闭。",+ "browserNotifications": "页面在后台时提醒任务状态。",+ "notificationSound": "回复结束时播放提示音,后台也会播放。","maxResults": "每次搜索最多显示多少条结果","timeout": "每次搜索最长等待时间,单位秒","jinaReader": "优先用 Jina Reader 读取网页\n\n读取网页时,优先使用可用的 Jina Reader。",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 6af7e2232..1b19c600b 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -479,6 +479,7 @@"byok": "BYOK","overview": "總覽","appearance": "外觀",+ "notifications": "通知","models": "模型","providers": "供應商","image": "圖片",@@ -517,20 +518,34 @@"voiceInput": "語音轉寫"},"notifications": {+ "scope": "此瀏覽器",+ "intro": "選擇任務結束時的提醒方式。",+ "pageRequired": "頁面關閉、暫停或中斷連線後,無法接收新提醒。",+ "revoked": "通知權限已撤銷,已關閉提醒。請先在瀏覽器的網站設定中允許通知,再於此處開啟。",+ "retry": "重新檢查",+ "statusOff": "未開啟",+ "statusPermission": "需要授權",+ "statusOn": "已開啟",+ "statusBlocked": "已遭封鎖",+ "statusRevoked": "權限已撤銷",+ "statusUnavailable": "無法使用",+ "statusWorker": "尚未就緒",+ "statusBusy": "檢查中…",+ "statusError": "傳送失敗","test": "測試通知",- "testBody": "這是一則 nanobot 測試通知。",+ "testBody": "這是一則測試通知。","waiting": "等待瀏覽器回應…","insecure": "請透過 HTTPS 或 localhost 開啟 nanobot,再啟用通知。",- "unsupported": "此瀏覽器不支援通知,請換用支援的瀏覽器。iPhone 或 iPad 需從主畫面開啟 nanobot。",- "denied": "通知已被瀏覽器封鎖。請在本站的瀏覽器設定中允許通知,再重試。",+ "unsupported": "此瀏覽器不支援通知,請更換瀏覽器。iPhone 或 iPad 請從主畫面開啟 nanobot。",+ "denied": "通知已被瀏覽器封鎖。請先在瀏覽器的網站設定中允許通知,再於此處開啟。","dismissed": "尚未取得通知權限。請重新啟用,並選擇「允許」。","permissionFailed": "無法要求通知權限,請在支援的瀏覽器中重試。",- "workerUnavailable": "通知服務尚未就緒,請重新整理頁面後重試。",+ "workerUnavailable": "通知服務尚未就緒,請重新檢查或重新整理頁面。","displayFailed": "瀏覽器未能傳送通知,請檢查本站的通知權限後重試。",- "submitted": "已提交給瀏覽器。如未看到通知,請檢查系統通知和勿擾設定。",- "completed": "任務已完成,開啟 nanobot 查看結果。",- "failed": "任務未完成,開啟 nanobot 查看詳情。",- "interrupted": "任務需要處理,開啟 nanobot 繼續。"+ "submitted": "已傳送至瀏覽器。若未顯示,請檢查系統通知和勿擾設定。",+ "completed": "任務已完成,點選查看結果。",+ "failed": "任務失敗,點選查看詳情。",+ "interrupted": "任務需要處理,點選繼續。"},"rows": {"theme": "主題",@@ -610,8 +625,8 @@"selectedModelProvider": "由選取的模型決定。","selectedModelValue": "由選取的模型決定。","brandLogos": "在設定中顯示提供商與應用圖示\n\n在設定中顯示提供商和命令列應用的品牌圖示。",- "browserNotifications": "網頁在背景時,提醒任務結束或需要處理。請保持網頁開啟;關閉或暫停後無法接收新通知。",- "notificationSound": "回覆結束播放提示音,預設關閉\n\n回合結束時播放短促提示音,頁面在後臺時也會播放。預設關閉。",+ "browserNotifications": "頁面在背景時提醒任務狀態。",+ "notificationSound": "回覆結束時播放音效,背景也會播放。","cliAppsCatalog": "安裝 CLI 工具,不改桌面應用\n\n安裝供 nanobot 使用的命令列工具,不會安裝或修改對應的桌面應用。","cliAppsFilter": "按名稱、分類或功能搜尋","logs": "開啟桌面應用的引擎日誌資料夾",diff --git a/webui/src/lib/browser-notifications.ts b/webui/src/lib/browser-notifications.tsindex 5327c0202..3b2f95ced 100644--- a/webui/src/lib/browser-notifications.ts+++ b/webui/src/lib/browser-notifications.ts@@ -1,7 +1,7 @@-import { readLocalPreferences } from "./local-preferences";+import { readLocalPreferences, writeLocalPreferences } from "./local-preferences";import type { TaskNotice } from "./nanobot-client";-export type NotificationProblem = "insecure" | "unsupported" | "denied" | "dismissed" | "permissionFailed" | "workerUnavailable" | "displayFailed";+export type NotificationProblem = "insecure" | "unsupported" | "denied" | "revoked" | "dismissed" | "permissionFailed" | "workerUnavailable" | "displayFailed";export type NotificationResult = "submitted" | "skipped" | NotificationProblem;const TIMEOUT_MS = 5_000;export const NOTIFICATION_STATUS_EVENT = "nanobot:notification-status";@@ -12,11 +12,20 @@ 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 (typeof Notification === "undefined") return "unsupported";if (Notification.permission === "denied") return "denied";+ if (!("serviceWorker" in navigator)) return "workerUnavailable";return null;}+export function reconcileNotificationPermission(): void {+ const preferences = readLocalPreferences();+ if (!preferences.browserNotifications || (typeof Notification !== "undefined" && Notification.permission === "granted")) return;+ writeLocalPreferences({ ...preferences, browserNotifications: false });+ lastProblem = typeof Notification === "undefined" ? "unsupported" : "revoked";+ window.dispatchEvent(new Event(NOTIFICATION_STATUS_EVENT));+}+function bounded<T>(operation: Promise<T>, timeoutMs = TIMEOUT_MS): Promise<T> {return new Promise((resolve, reject) => {const timer = window.setTimeout(() => reject(new Error("Notification timeout")), timeoutMs);@@ -31,6 +40,24 @@ async function activeWorker(): Promise<ServiceWorker | null> {return registration?.active ?? null;}+async function workerRequest(worker: ServiceWorker, message: object): Promise<unknown> {+ const channel = new MessageChannel();+ try {+ return await bounded(new Promise<unknown>((resolve) => {+ channel.port1.onmessage = ({ data }: MessageEvent<unknown>) => resolve(data);+ worker.postMessage(message, [channel.port2]);+ }));+ } finally { channel.port1.close(); }+}++export async function notificationWorkerProblem(): Promise<"workerUnavailable" | null> {+ try {+ const worker = await activeWorker();+ return worker && await workerRequest(worker, { type: "nanobot:notification-probe" }) === "ready"+ ? null : "workerUnavailable";+ } catch { return "workerUnavailable"; }+}+export async function enableBrowserNotifications(): Promise<NotificationProblem | null> {const problem = notificationProblem();if (problem) return problem;@@ -40,8 +67,9 @@ export async function enableBrowserNotifications(): Promise<NotificationProblem? "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"; }+ const workerProblem = await notificationWorkerProblem();+ if (!workerProblem) lastProblem = null;+ return workerProblem;}export function taskNoticeKey(notice: TaskNotice): string | null {@@ -74,6 +102,7 @@ export async function showBrowserNotification(body: string, options: {}async function submitNotification(body: string, options: { key: string; url: string; test?: boolean }): Promise<NotificationResult> {+ reconcileNotificationPermission();const eligible = () => options.test || (readLocalPreferences().browserNotifications && document.visibilityState !== "visible");if (!eligible()) return "skipped";const problem = notificationProblem();@@ -84,14 +113,8 @@ async function submitNotification(body: string, options: { key: string; url: strcatch { return "workerUnavailable"; }if (!worker) return "workerUnavailable";if (!eligible()) return "skipped";- const channel = new MessageChannel();try {- return await bounded(new Promise<NotificationResult>((resolve) => {- channel.port1.onmessage = ({ data }: MessageEvent<unknown>) => {- resolve(data === "submitted" || data === "skipped" ? data : "displayFailed");- };- worker.postMessage({ type: "nanobot:notify", body, ...options }, [channel.port2]);- }));- } catch { return "displayFailed"; }- finally { channel.port1.close(); }+ const data = await workerRequest(worker, { type: "nanobot:notify", body, ...options });+ return data === "submitted" || data === "skipped" ? data : "displayFailed";+ } catch { return "workerUnavailable"; }}diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.tsindex 06051e25d..b7a3b43b7 100644--- a/webui/src/lib/nanobot-client.ts+++ b/webui/src/lib/nanobot-client.ts@@ -1003,9 +1003,10 @@ export class NanobotClient {if (correlatedChatId) {this.recordGoalStateSnapshot(correlatedChatId, parsed);- if (parsed.event === "turn_end" || parsed.event === "recovery_state") {+ if ((parsed.event === "turn_end" || parsed.event === "recovery_state")+ && (this.knownChats.has(correlatedChatId) || this.temporaryChatIds.has(correlatedChatId))) {for (const handler of this.taskNoticeHandlers) {- // Optional browser features must never interrupt delivery or cleanup.+ // Optional browser features must not interrupt delivery or cleanup.try { handler({ event: parsed, temporary: this.temporaryChatIds.has(correlatedChatId) }); }catch { /* The notification owner reports its own delivery failure. */ }}diff --git a/webui/src/tests/browser-notifications.test.tsx b/webui/src/tests/browser-notifications.test.tsxindex 753dc0631..9d16bc6ff 100644--- a/webui/src/tests/browser-notifications.test.tsx+++ b/webui/src/tests/browser-notifications.test.tsx@@ -1,10 +1,12 @@import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { useState } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { BrowserNotificationSettings } from "@/components/settings/overview/BrowserNotificationSettings";-import { BrowserNotifications } from "@/components/BrowserNotifications";+import { BrowserNotificationSettings } from "@/components/settings/notifications/BrowserNotificationSettings";+import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings";+import { BrowserNotifications, useBrowserNotificationLifecycle } from "@/components/BrowserNotifications";+import { useLocalPreferences } from "@/hooks/useLocalPreferences";import { enableBrowserNotifications, NOTIFICATION_OPEN_EVENT, notificationChatUrl, notificationProblem, showBrowserNotification, taskNoticeKey } from "@/lib/browser-notifications";-import { DEFAULT_LOCAL_PREFS, writeLocalPreferences } from "@/lib/local-preferences";+import { DEFAULT_LOCAL_PREFS, readLocalPreferences, writeLocalPreferences } from "@/lib/local-preferences";import type { TaskNotice } from "@/lib/nanobot-client";import i18n from "@/i18n";@@ -12,25 +14,33 @@ const requestPermission = vi.fn();const postMessage = vi.fn();const worker = { postMessage };const getRegistration = vi.fn();-let receive: ((event: MessageEvent) => void) | null;function Harness({ enabled = false }: { enabled?: boolean }) {const [preferences, setPreferences] = useState({ ...DEFAULT_LOCAL_PREFS, browserNotifications: enabled });return <BrowserNotificationSettings localPrefs={preferences} onChangeLocalPrefs={setPreferences} />;}+function LifecycleHarness({ settings = true }: { settings?: boolean }) {+ useBrowserNotificationLifecycle();+ const preferences = useLocalPreferences();+ return settings ? <BrowserNotificationSettings localPrefs={preferences}+ onChangeLocalPrefs={(update) => writeLocalPreferences(typeof update === "function" ? update(readLocalPreferences()) : update)} /> : null;+}+beforeEach(() => {vi.stubGlobal("isSecureContext", true);vi.stubGlobal("Notification", { permission: "default", requestPermission });vi.stubGlobal("MessageChannel", class {port1 = { onmessage: null as ((event: MessageEvent) => void) | null, close: vi.fn() };- port2 = {};- constructor() { queueMicrotask(() => { receive = this.port1.onmessage; }); }+ port2 = { reply: (data: unknown) => this.port1.onmessage?.({ data } as MessageEvent) };});Object.defineProperty(navigator, "serviceWorker", { configurable: true, value: Object.assign(new EventTarget(), { getRegistration, controller: worker }) });getRegistration.mockResolvedValue({ active: worker });- postMessage.mockImplementation(() => { setTimeout(() => receive?.({ data: "submitted" } as MessageEvent), 0); });- requestPermission.mockResolvedValue("granted");+ postMessage.mockImplementation((data, ports) => { queueMicrotask(() => ports[0].reply(data.type === "nanobot:notification-probe" ? "ready" : "submitted")); });+ requestPermission.mockImplementation(() => {+ vi.stubGlobal("Notification", { permission: "granted", requestPermission });+ return Promise.resolve("granted");+ });Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, browserNotifications: true });});@@ -87,7 +97,17 @@ describe("notification permission and delivery boundary", () => {postMessage.mockImplementation(() => {});const showing = showBrowserNotification("Task completed", { key: "one", url: notificationChatUrl("one", false) });await vi.advanceTimersByTimeAsync(5_001);- expect(await showing).toBe("displayFailed");+ expect(await showing).toBe("workerUnavailable");+ });++ it("reports an older active worker that does not understand the notification protocol", async () => {+ vi.useFakeTimers();+ vi.stubGlobal("Notification", { permission: "granted" });+ postMessage.mockImplementation(() => {});+ const enabling = enableBrowserNotifications();+ await vi.advanceTimersByTimeAsync(5_001);+ expect(await enabling).toBe("workerUnavailable");+ expect(requestPermission).not.toHaveBeenCalled();});it("uses the worker without constructing Notification, and isolates a post failure", async () => {@@ -97,7 +117,7 @@ describe("notification permission and delivery boundary", () => {expect(await showBrowserNotification("Task completed", options)).toBe("submitted");expect(constructor).not.toHaveBeenCalled();postMessage.mockImplementation(() => { throw new Error("worker stopped"); });- expect(await showBrowserNotification("Task completed", options)).toBe("displayFailed");+ expect(await showBrowserNotification("Task completed", options)).toBe("workerUnavailable");});it("does not notify while visible, disabled, or disabled during a lookup", async () => {@@ -125,11 +145,26 @@ describe("notification permission and delivery boundary", () => {});describe("notification settings", () => {+ it("keeps completion sound independent when browser notifications are unavailable", () => {+ vi.stubGlobal("Notification", undefined);+ function Page() {+ const [preferences, setPreferences] = useState(DEFAULT_LOCAL_PREFS);+ return <NotificationSettings localPrefs={preferences} onChangeLocalPrefs={setPreferences} />;+ }+ render(<Page />);+ expect(screen.getByRole("switch", { name: "Browser notifications" })).toBeDisabled();+ const sound = screen.getByRole("switch", { name: "Completion sound" });+ expect(sound).toHaveAttribute("aria-checked", "false");+ fireEvent.click(sound);+ expect(sound).toHaveAttribute("aria-checked", "true");+ expect(screen.getByRole("switch", { name: "Browser notifications" })).toHaveAttribute("aria-checked", "false");+ });+it("explains unavailable notification support beside a disabled switch", () => {vi.stubGlobal("Notification", undefined);render(<Harness />);expect(screen.getByRole("switch", { name: "Browser notifications" })).toBeDisabled();- expect(screen.getByRole("status")).toHaveTextContent("This browser cannot send notifications");+ expect(screen.getByRole("status")).toHaveTextContent("This browser doesn’t support notifications");});it("reports dismissal and lets the user retry, test, and disable", async () => {@@ -144,6 +179,7 @@ describe("notification settings", () => {expect(toggle).toHaveAttribute("aria-checked", "false");fireEvent.click(toggle);await waitFor(() => expect(toggle).toHaveAttribute("aria-checked", "true"));+ await waitFor(() => expect(screen.getByRole("button", { name: "Test notification" })).toBeEnabled());fireEvent.click(screen.getByRole("button", { name: "Test notification" }));await screen.findByText(/Sent to the browser/);fireEvent.click(toggle);@@ -151,15 +187,38 @@ describe("notification settings", () => {expect(screen.queryByRole("button", { name: "Test notification" })).not.toBeInTheDocument();});- it("updates revoked permission on return and still allows opt-out", () => {+ it("reconciles revocation outside settings and requires opt-in after regranting permission", async () => {vi.stubGlobal("Notification", { permission: "granted" });- render(<Harness enabled />);+ writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, browserNotifications: true, notificationSound: true });+ const { rerender } = render(<LifecycleHarness settings={false} />);vi.stubGlobal("Notification", { permission: "denied" });fireEvent.focus(window);- expect(screen.getByRole("status")).toHaveTextContent("Notifications are blocked");+ expect(readLocalPreferences()).toMatchObject({ browserNotifications: false, notificationSound: true });+ rerender(<LifecycleHarness />);+ expect(screen.getByRole("status")).toHaveTextContent("Notification permission was revoked");expect(screen.queryByRole("button", { name: "Test notification" })).not.toBeInTheDocument();+ expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");+ vi.stubGlobal("Notification", { permission: "granted", requestPermission });+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));+ expect(screen.getByRole("switch")).toBeEnabled();+ expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");+ fireEvent.click(screen.getByRole("switch"));+ await waitFor(() => expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "true"));+ });++ it("allows opt-out and an explicit readiness retry when the worker is unavailable", async () => {+ vi.stubGlobal("Notification", { permission: "granted" });+ getRegistration.mockResolvedValue(null);+ render(<Harness enabled />);+ await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("notification service is not ready"));fireEvent.click(screen.getByRole("switch"));expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");+ getRegistration.mockResolvedValue({ active: worker });+ const retry = screen.getByRole("button", { name: "Check again" });+ await waitFor(() => expect(retry).toBeEnabled());+ fireEvent.click(retry);+ await waitFor(() => expect(screen.queryByRole("button", { name: "Check again" })).not.toBeInTheDocument());+ expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");});it("does not save late permission results after leaving settings", async () => {@@ -184,7 +243,7 @@ it("subscribes outside a chat, uses generic localized text, and cleans up", asynconst event = { event: "turn_end", chat_id: "other", turn_id: "turn", outcome: "failed", failure_message: "PRIVATE TOKEN" } as const;handler({ event, temporary: false });await waitFor(() => expect(postMessage).toHaveBeenCalled());- expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "任务未完成,打开 nanobot 查看详情。", url: notificationChatUrl("other", false) });+ expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "任务失败,点击查看详情。", url: notificationChatUrl("other", false) });expect(JSON.stringify(postMessage.mock.calls[0][0])).not.toContain("PRIVATE TOKEN");expect(taskNoticeKey({ event, temporary: false })).toBe('["other","turn","end"]');unmount();@@ -203,12 +262,16 @@ it("does not report cancellation or interruption as completion", async () => {expect(postMessage).not.toHaveBeenCalled();handler({ event: { ...event, outcome: "interrupted" }, temporary: false });await waitFor(() => expect(postMessage).toHaveBeenCalled());- expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "Task needs attention. Open nanobot to continue." });+ expect(postMessage.mock.calls[0][0]).toMatchObject({ body: "Task needs attention. Click to continue." });});-it("opens a notification only from the controlling worker and reveals the owning host", () => {+it("keeps validated notification navigation alive through sign-out and reveals the owning host", () => {const client = { onTaskNotice: () => () => {} };- render(<BrowserNotifications client={client} />);+ function AuthBoundary({ authenticated }: { authenticated: boolean }) {+ useBrowserNotificationLifecycle();+ return authenticated ? <BrowserNotifications client={client} /> : null;+ }+ const { rerender } = render(<AuthBoundary authenticated />);const reveal = vi.fn();window.addEventListener(NOTIFICATION_OPEN_EVENT, reveal);const url = notificationChatUrl("clicked", false);@@ -221,6 +284,12 @@ it("opens a notification only from the controlling worker and reveals the owningsend(worker, url);expect(window.location.hash).toBe("#/chat/websocket%3Aclicked");expect(reveal).toHaveBeenCalledOnce();+ window.location.hash = "#/settings?section=notifications";+ rerender(<AuthBoundary authenticated={false} />);+ send(worker, url);+ expect(window.location.hash).toBe("#/chat/websocket%3Aclicked");+ rerender(<AuthBoundary authenticated />);+ expect(window.location.hash).toBe("#/chat/websocket%3Aclicked");window.removeEventListener(NOTIFICATION_OPEN_EVENT, reveal);window.history.replaceState(null, "", "/");});diff --git a/webui/src/tests/i18n.test.tsx b/webui/src/tests/i18n.test.tsxindex 76733a6d0..a939b325a 100644--- a/webui/src/tests/i18n.test.tsx+++ b/webui/src/tests/i18n.test.tsx@@ -178,6 +178,21 @@ const LOCALIZED_SETTINGS_COPY_KEYS = ["settings.help.codeWrap","settings.help.brandLogos","settings.help.browserNotifications",+ "settings.nav.notifications",+ "settings.notifications.scope",+ "settings.notifications.intro",+ "settings.notifications.pageRequired",+ "settings.notifications.revoked",+ "settings.notifications.retry",+ "settings.notifications.statusOff",+ "settings.notifications.statusPermission",+ "settings.notifications.statusOn",+ "settings.notifications.statusBlocked",+ "settings.notifications.statusRevoked",+ "settings.notifications.statusUnavailable",+ "settings.notifications.statusWorker",+ "settings.notifications.statusBusy",+ "settings.notifications.statusError","settings.notifications.test","settings.notifications.testBody","settings.notifications.waiting",@@ -639,7 +654,9 @@ describe("webui i18n", () => {...LOCALIZED_CHANNEL_SHELL_KEYS,...LOCALIZED_NEW_SURFACE_KEYS,].filter(- (key) => current.get(key) === english.get(key),+ // “Notifications” is also the native French label.+ (key) => current.get(key) === english.get(key)+ && !(locale === "fr" && key === "settings.nav.notifications"),);expect({ locale, leaked }).toEqual({ locale, leaked: [] });diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.tsindex fc8c05a3f..ebd5f3a6a 100644--- a/webui/src/tests/nanobot-client.test.ts+++ b/webui/src/tests/nanobot-client.test.ts@@ -79,15 +79,37 @@ describe("NanobotClient", () => {const broken = client.onTaskNotice(() => { throw new Error("optional notification failed"); });const notice = vi.fn();const unsubscribe = client.onTaskNotice(notice);+ client.attach("away");const event = { event: "turn_end", chat_id: "away", turn_id: "turn", outcome: "completed" };lastSocket().fakeMessage(event);expect(notice).toHaveBeenCalledWith({ event, temporary: false });const replay = vi.fn();- client.onChat("away", replay);+ client.onTranscript("away", replay);expect(replay).toHaveBeenCalledWith(event);expect(notice).toHaveBeenCalledOnce();broken(); unsubscribe(); client.close();});+ it("ignores in-flight task notices after a Temporary Chat is discarded", async () => {+ const client = new NanobotClient({ url: "ws://test", reconnect: false,+ socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });+ client.connect();+ const socket = lastSocket();+ socket.fakeOpen();+ const created = client.newTemporaryChat();+ socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true });+ await created;+ const notice = vi.fn();+ client.onTaskNotice(notice);+ client.sendMessage("temporary", "work", undefined, { turnId: "temporary-turn" });+ client.discardTemporaryChat("temporary");+ socket.fakeMessage({ event: "turn_end", chat_id: "temporary", turn_id: "temporary-turn" });+ expect(notice).not.toHaveBeenCalled();+ client.attach("regular");+ const event = { event: "turn_end", chat_id: "regular", turn_id: "regular-turn" };+ socket.fakeMessage(event);+ expect(notice).toHaveBeenCalledWith({ event, temporary: false });+ client.close();+ });it("bounds regular replay tails but retains temporary events until discard", async () => {const client = new NanobotClient({url: "ws://test", reconnect: false,diff --git a/webui/src/tests/settings-overview.test.tsx b/webui/src/tests/settings-overview.test.tsxindex 9daa91038..96a9d55cc 100644--- a/webui/src/tests/settings-overview.test.tsx+++ b/webui/src/tests/settings-overview.test.tsx@@ -1,12 +1,12 @@import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import { expect, it, vi } from "vitest";import { HostNavigationContext } from "@/components/remote/HostSwitcher";-import { AboutSettings, AppearanceSettings } from "@/components/settings/overview/OverviewSettings";+import { AboutSettings } from "@/components/settings/overview/OverviewSettings";import { VersionCheckRowView } from "@/components/settings/overview/VersionCheckRowView";import { NanobotClient } from "@/lib/nanobot-client";import { ClientProvider } from "@/providers/ClientProvider";import type { SettingsPayload } from "@/lib/types";-import { DEFAULT_LOCAL_PREFS } from "@/lib/local-preferences";+import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, readLocalPreferences, writeLocalPreferences } from "@/lib/local-preferences";import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";const thirdPartyBrandNotice =@@ -25,22 +25,33 @@ describe("Settings overview and appearance", () => {expect(check).toHaveBeenCalledTimes(1);});- it.each(["granted", "denied"])("updates task notifications only after browser permission is %s", async (permission) => {- const requestPermission = vi.fn().mockResolvedValue(permission);- vi.stubGlobal("Notification", { permission: "default", requestPermission });- const changePreferences = vi.fn();- render(<AppearanceSettings theme="light" onToggleTheme={vi.fn()} localPrefs={DEFAULT_LOCAL_PREFS} onChangeLocalPrefs={changePreferences} />);- fireEvent.click(screen.getByRole("switch", { name: "Task notifications" }));- expect(changePreferences).not.toHaveBeenCalled();- await waitFor(() => expect(requestPermission).toHaveBeenCalledTimes(1));- await act(async () => { await Promise.resolve(); });- if (permission === "granted") {- expect(changePreferences).toHaveBeenCalledTimes(1);- expect(changePreferences.mock.calls[0][0](DEFAULT_LOCAL_PREFS).browserNotifications).toBe(true);- } else expect(changePreferences).not.toHaveBeenCalled();+ it("opens the notifications section and preserves independent browser-local channel preferences", () => {+ writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });+ renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload(), showSidebar: true });+ fireEvent.click(screen.getByRole("button", { name: "Notifications" }));+ expect(screen.getByRole("switch", { name: "Browser notifications" })).toHaveAttribute("aria-checked", "false");+ const sound = screen.getByRole("switch", { name: "Completion sound" });+ expect(sound).toHaveAttribute("aria-checked", "true");+ fireEvent.click(sound);+ expect(readLocalPreferences()).toMatchObject({ browserNotifications: false, notificationSound: false });});+ it.each(["local", "other tab"])("preserves a %s notification opt-out when another preference changes", (source) => {+ writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, browserNotifications: true, notificationSound: true });+ renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload(), showSidebar: true });+ act(() => {+ const next = { ...readLocalPreferences(), browserNotifications: false };+ if (source === "local") writeLocalPreferences(next);+ else {+ localStorage.setItem(LOCAL_PREFS_STORAGE_KEY, JSON.stringify(next));+ window.dispatchEvent(new StorageEvent("storage", { key: LOCAL_PREFS_STORAGE_KEY }));+ }+ });+ fireEvent.click(screen.getByRole("switch", { name: "Code wrapping" }));+ expect(readLocalPreferences()).toMatchObject({ browserNotifications: false, notificationSound: true, codeWrap: false });+ });+it("links the host's short commit beside its version", () => {const commit = "abcdef12".repeat(5);renderSettingsView({diff --git a/webui/src/tests/sw.test.ts b/webui/src/tests/sw.test.tsindex 7040fcdfc..861ac8191 100644--- a/webui/src/tests/sw.test.ts+++ b/webui/src/tests/sw.test.ts@@ -152,6 +152,23 @@ describe("browser notification worker", () => {return reply;}+ it("confirms notification support without displaying a test notification", async () => {+ const sw = loadSw();+ const reply = await send(sw, { type: "nanobot:notification-probe" });+ expect(reply).toHaveBeenCalledWith("ready");+ expect(sw.showNotification).not.toHaveBeenCalled();+ });++ it("returns test clicks to notification settings, including a still-open older page", async () => {+ const sw = loadSw();+ for (const section of ["notifications", "appearance"]) {+ const target = `${ORIGIN}/#/settings?section=${section}`;+ expect(await send(sw, { test: true, key: section, url: target })).toHaveBeenCalledWith("submitted");+ await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url: target } } });+ expect(sw.openWindow).toHaveBeenLastCalledWith(target);+ }+ });+it("deduplicates concurrent tabs, dismissed notifications, and worker restarts", async () => {const sw = loadSw();const replies = await Promise.all([send(sw), send(sw)]);@@ -201,6 +218,16 @@ describe("browser notification worker", () => {expect(sw.openWindow).not.toHaveBeenCalled();});+ it("opens the destination when the source closed, even if an older page is still open", async () => {+ const sw = loadSw();+ const oldTab = { id: "old-page", frameType: "top-level", postMessage: vi.fn(), focus: vi.fn() };+ sw.matchClients.mockResolvedValue([oldTab]);+ await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url, clientId: "closed" } } });+ expect(sw.openWindow).toHaveBeenCalledWith(url);+ expect(oldTab.postMessage).not.toHaveBeenCalled();+ expect(oldTab.focus).not.toHaveBeenCalled();+ });+it("opens the same host with ordinary auth, but cannot restore a closed temporary chat", async () => {const sw = loadSw();await sw.fire("notificationclick", { notification: { close: vi.fn(), data: { url, clientId: "closed" } } });