Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): ask for notification permission from a settings switch (#702)

Yaowei Zheng48814d391708
diff --git a/changelog/unreleased/2026-09-12-notification-permission.md b/changelog/unreleased/2026-09-12-notification-permission.md
new file mode 100644
index 00000000..8dbd9875
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-notification-permission.md
@@ -0,0 +1,33 @@
+# Task-completion notifications ask the system for permission
+
+- **Date:** 2026-09-12
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#702](https://github.com/Prism-Shadow/penguin-harness/pull/702)
+- **Issue:** [#607](https://github.com/Prism-Shadow/penguin-harness/issues/607)
+
+[中文版](2026-09-12-notification-permission.zh.md)
+
+Nothing in the Web App ever called `Notification.requestPermission()`, and the completion
+notification was gated to the desktop shell, where Electron reports `Notification.permission`
+as `"granted"` without asking anyone. That is Electron's own check rather than the system's:
+on macOS a bundle that never requests authorization has its notifications dropped and never
+appears in System Settings → Notifications, so nothing was ever shown there — and a browser,
+which would have had to be asked, was not eligible in the first place.
+
+## Details
+
+- System settings › General gained a **Task completion notifications** switch, off by
+ default and stored per browser as `penguin.notifications`.
+- Turning the switch on asks the system for permission at that moment, and the preference is
+ stored only if that request comes back granted. A denial keeps the switch off and shows a
+ hint pointing at the system's own notification settings; a prompt closed without an answer,
+ which leaves the permission at `"default"`, says that instead and invites another try.
+ Where the platform has no Notification API at all, the row is disabled and says so.
+- Turning the switch off stops the notifications; the permission the system granted stays
+ granted.
+- The notification no longer requires a desktop-shell session. It is shown wherever the
+ preference is on and the permission is granted, a browser included, and the permission is
+ re-read on every completion so a permission revoked in the meantime stops it. The desktop
+ shell waits for the same switch too: a shell install whose notifications did work stops
+ showing them until it is turned on.
diff --git a/changelog/unreleased/2026-09-12-notification-permission.zh.md b/changelog/unreleased/2026-09-12-notification-permission.zh.md
new file mode 100644
index 00000000..5aa53ff1
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-notification-permission.zh.md
@@ -0,0 +1,24 @@
+# 任务完成通知会向系统申请通知权限
+
+- **Date:** 2026-09-12
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#702](https://github.com/Prism-Shadow/penguin-harness/pull/702)
+- **Issue:** [#607](https://github.com/Prism-Shadow/penguin-harness/issues/607)
+
+[English](2026-09-12-notification-permission.md)
+
+Web App 中从未有任何代码调用过 `Notification.requestPermission()`,而任务完成通知又只对桌面壳开放——
+Electron 在那里不问自答,把 `Notification.permission` 报成 `"granted"`。那只是 Electron 自己的检查,不是
+系统的:在 macOS 上,从不申请授权的 bundle,其通知会被直接丢弃,也永远不会出现在「系统设置 → 通知」里,通知
+因此从未弹出过;而真正需要申请权限的浏览器,从一开始就不在这条路径上。
+
+## 细节
+
+- 系统设置 › 个人新增**任务完成通知**开关,默认关闭,按浏览器存为 `penguin.notifications`。
+- 打开开关即当场向系统申请通知权限,只有申请结果为已授权时才写入该偏好。被拒绝则开关保持关闭,并给出一行提示
+ 指向系统自己的通知设置;提示框被直接关掉、没有给出答复(权限停在 `"default"`)时,提示改为说明这一点并请其
+ 再试一次。平台根本没有 Notification API 时,该行禁用并直接说明。
+- 关闭开关即停止通知;系统已经授予的权限保持授予状态。
+- 通知不再要求是桌面壳的会话:只要偏好已打开且权限已授予即会弹出,浏览器同样如此;权限在每次任务完成时重新读取,
+ 期间被收回即停止弹出。桌面壳现在同样要等这个开关:此前通知确实能弹出的桌面安装,也要先打开它才会继续弹。
diff --git a/packages/web/src/features/settings/general-section.tsx b/packages/web/src/features/settings/general-section.tsx
index 7a3a1b94..4fbc33aa 100644
--- a/packages/web/src/features/settings/general-section.tsx
+++ b/packages/web/src/features/settings/general-section.tsx
@@ -1,11 +1,28 @@
/**
* General page of System settings: per-account preferences that are neither appearance nor
* credentials. Everything applies the moment it is touched — the stores persist each value
- * (language and currency per browser) — so the page carries no Save button and no draft
- * state to lose.
+ * (language, currency and task-completion notifications per browser) — so the page carries
+ * no Save button and no draft state to lose.
+ *
+ * The notification row is the one that reaches outside the app: turning it on asks the
+ * platform for permission then and there (lib/notification-pref explains why the prompt
+ * hangs off this switch rather than off a page load), so it settles on whatever that
+ * request answered rather than on what was clicked.
*/
+import { useState, useSyncExternalStore } from "react";
import { S } from "../../lib/strings";
import { Segmented } from "../../components/ui/segmented";
+import { Switch } from "../../components/ui/switch";
+import {
+ enableNotifications,
+ notificationHintFor,
+ notificationPermission,
+ notificationsEnabledVersion,
+ readNotificationsEnabled,
+ subscribeNotificationsEnabled,
+ writeNotificationsEnabled,
+} from "../../lib/notification-pref";
+import type { NotificationAccess } from "../../lib/notification-pref";
import { useLocale } from "../../state/locale";
import type { LangPref } from "../../state/locale";
import { useTheme } from "../../state/theme";
@@ -17,6 +34,14 @@ export function GeneralSection() {
const { lang, setLang } = useLocale();
const { currency, setCurrency } = useTheme();
+ useSyncExternalStore(subscribeNotificationsEnabled, notificationsEnabledVersion);
+ const notificationsOn = readNotificationsEnabled();
+ // What the platform last answered: its own state, because a refusal has to stay on screen
+ // as a hint after the click that produced it. `asked` goes with it, so a prompt closed
+ // without an answer is told apart from a browser that was simply never asked.
+ const [access, setAccess] = useState<NotificationAccess>(notificationPermission);
+ const [asked, setAsked] = useState(false);
+
const langOptions: ReadonlyArray<{ value: LangPref; label: string }> = [
{ value: "en", label: S.settings.langEn },
{ value: "zh", label: S.settings.langZh },
@@ -27,6 +52,16 @@ export function GeneralSection() {
{ value: "CNY", label: S.models.currencyCny },
];
+ const hint = notificationHintFor(access, asked);
+ const notificationHint =
+ hint === "unsupported"
+ ? S.settings.notificationsUnsupported
+ : hint === "denied"
+ ? S.settings.notificationsDenied
+ : hint === "dismissed"
+ ? S.settings.notificationsDismissed
+ : undefined;
+
return (
<div className="divide-y divide-gray-100 dark:divide-gray-800/60">
<PrefRow label={S.settings.language} info={S.settings.languageInfo}>
@@ -35,6 +70,28 @@ export function GeneralSection() {
<PrefRow label={S.models.currency} info={S.settings.currencyInfo}>
<Segmented options={currencyOptions} value={currency} onChange={setCurrency} cols={2} />
</PrefRow>
+ <PrefRow
+ label={S.settings.notifications}
+ hint={notificationHint}
+ info={S.settings.notificationsInfo}
+ >
+ <Switch
+ checked={notificationsOn}
+ disabled={access === "unsupported"}
+ onChange={(on) => {
+ if (!on) {
+ writeNotificationsEnabled(false);
+ return;
+ }
+ // Only a granted request stores the preference, so anything else leaves the
+ // switch where it was and turns the hint on instead.
+ void enableNotifications().then((answer) => {
+ setAccess(answer);
+ setAsked(true);
+ });
+ }}
+ />
+ </PrefRow>
<TraceImportRow />
</div>
);
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index 087806e7..5f3a9ea6 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -197,6 +197,12 @@ export const KEY_RULES: readonly KeyRule[] = [
scope: "browser",
why: "Steer vs queue-as-follow-up when sending mid-run; a per-user input habit.",
},
+ {
+ kind: "exact",
+ key: "penguin.notifications",
+ scope: "browser",
+ why: "Whether task-completion notifications were asked for; it pairs with an OS permission that belongs to this browser rather than to any data root, and clearing it would silently stop notifications the user opted into.",
+ },
// --------------------------------------------------------------- install-scoped state
{
diff --git a/packages/web/src/lib/notification-pref.ts b/packages/web/src/lib/notification-pref.ts
new file mode 100644
index 00000000..d33317f9
--- /dev/null
+++ b/packages/web/src/lib/notification-pref.ts
@@ -0,0 +1,156 @@
+/**
+ * The task-completion notification's opt-in, and the OS permission it depends on
+ * (state/use-completion-notifications.ts is the only reader of both).
+ *
+ * Two separate facts decide whether a notification can be shown, and neither implies the
+ * other: the user asked for notifications (stored here, `penguin.notifications`, registered
+ * as a browser preference in lib/install-scope.ts), and the platform granted permission to
+ * show them. A browser reports the second as `Notification.permission`, and it starts at
+ * "default" — no code path grants it, and on macOS a window that never calls
+ * `requestPermission()` is not even listed in System Settings → Notifications.
+ *
+ * THE PROMPT IS TIED TO THE SWITCH, never to a page load. `requestPermission()` opens the
+ * system dialog, an unexpected dialog is reflexively dismissed, and a dismissal is not a
+ * question the platform asks twice: once denied, later calls resolve "denied" without
+ * prompting and the only way back is the system's own settings. So permission is asked for
+ * at the moment the user turns the preference on — an action that already says yes — and
+ * the preference is stored only if that request came back granted.
+ *
+ * The store follows features/dock/dock-launcher-state.ts: a module-level version counter
+ * read through `useSyncExternalStore`, with the value itself read separately, so the
+ * settings row and the app-wide hook stay in step without either owning the state.
+ */
+
+/** localStorage key of the opt-in; only NOTIFICATIONS_ON counts as on. */
+export const NOTIFICATIONS_KEY = "penguin.notifications";
+const NOTIFICATIONS_ON = "1";
+const NOTIFICATIONS_OFF = "0";
+
+/** The storage this preference reads and writes — localStorage, or a stub in tests. */
+export type NotificationStorage = Pick<Storage, "getItem" | "setItem">;
+
+function defaultStorage(): NotificationStorage | null {
+ try {
+ return typeof localStorage === "undefined" ? null : localStorage;
+ } catch {
+ return null; // the accessor itself throws where site data is blocked
+ }
+}
+
+let version = 0;
+const listeners = new Set<() => void>();
+/**
+ * The live value, read from storage once and kept in memory afterwards: the hook that reads
+ * it sits in the app layout, which re-renders on every streamed token, and that is no place
+ * for a synchronous storage read. As with the launcher's preference, a change made in
+ * another tab is not seen until a reload.
+ */
+let cache: boolean | null = null;
+
+export function subscribeNotificationsEnabled(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => void listeners.delete(listener);
+}
+
+export function notificationsEnabledVersion(): number {
+ return version;
+}
+
+function enabledIn(storage: NotificationStorage | null): boolean {
+ try {
+ return storage?.getItem(NOTIFICATIONS_KEY) === NOTIFICATIONS_ON;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Whether the user asked for task-completion notifications. Off unless the stored value is
+ * exactly "1" — absent, stale or hand-edited all read as off, because turning this on is
+ * what triggers a system permission prompt and nothing but an explicit choice should.
+ * An explicit storage bypasses the cache.
+ */
+export function readNotificationsEnabled(storage?: NotificationStorage | null): boolean {
+ if (storage !== undefined) return enabledIn(storage);
+ if (cache === null) cache = enabledIn(defaultStorage());
+ return cache;
+}
+
+/** Stores the opt-in and tells everything rendering from it. Never touches OS permission. */
+export function writeNotificationsEnabled(
+ enabled: boolean,
+ storage?: NotificationStorage | null,
+): void {
+ const target = storage === undefined ? defaultStorage() : storage;
+ try {
+ target?.setItem(NOTIFICATIONS_KEY, enabled ? NOTIFICATIONS_ON : NOTIFICATIONS_OFF);
+ } catch {
+ // Private-mode storage failures only cost persistence; this session still updates.
+ }
+ if (storage === undefined) cache = enabled;
+ version += 1;
+ for (const listener of listeners) listener();
+}
+
+/** A platform's answer, plus the case where it has no Notification API to answer with. */
+export type NotificationAccess = NotificationPermission | "unsupported";
+
+/** What the platform currently allows, read live — the OS may revoke it between renders. */
+export function notificationPermission(): NotificationAccess {
+ try {
+ return typeof Notification === "undefined" ? "unsupported" : Notification.permission;
+ } catch {
+ return "unsupported";
+ }
+}
+
+/**
+ * Asks the platform for permission, which prompts the user only while the answer is still
+ * "default"; an earlier grant or denial resolves immediately with that answer.
+ *
+ * The resolved value is checked against the live permission because the API has two
+ * shapes — the promise of modern browsers and an older callback form that resolves
+ * undefined — and a platform that hands back neither still leaves `Notification.permission`
+ * correct.
+ */
+export async function requestNotificationPermission(): Promise<NotificationAccess> {
+ if (typeof Notification === "undefined") return "unsupported";
+ try {
+ const answer = await Notification.requestPermission();
+ return answer === "granted" || answer === "denied" || answer === "default"
+ ? answer
+ : notificationPermission();
+ } catch {
+ return notificationPermission();
+ }
+}
+
+/**
+ * Turning the preference on: permission first, storage only on "granted". Anything else —
+ * a denial, a dismissed prompt (which leaves "default"), a platform without the API — is
+ * returned for the caller to explain, and leaves the preference off, so the switch never
+ * latches on over a notification that cannot be shown.
+ */
+export async function enableNotifications(
+ storage?: NotificationStorage | null,
+): Promise<NotificationAccess> {
+ const access = await requestNotificationPermission();
+ if (access === "granted") writeNotificationsEnabled(true, storage);
+ return access;
+}
+
+/** What the settings row has to say under the switch, or null when it has nothing to add. */
+export type NotificationHint = "unsupported" | "denied" | "dismissed" | null;
+
+/**
+ * The hint for a platform state. `asked` is whether a request has answered in this session,
+ * and it is what separates the two meanings of "default": a platform that was never asked —
+ * where every first visit starts, and nothing to report — from a prompt closed without an
+ * answer, which is a request that failed and has to say so. Without that line the switch
+ * springs back to off with no explanation, which reads as a control that does nothing.
+ */
+export function notificationHintFor(access: NotificationAccess, asked: boolean): NotificationHint {
+ if (access === "unsupported") return "unsupported";
+ if (access === "denied") return "denied";
+ return access === "default" && asked ? "dismissed" : null;
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index e00ae5a4..52063455 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -213,6 +213,14 @@ export const en: Strings = {
toolAliases: "Tool short names",
toolAliasesInfo:
'Tool cards in a conversation name the built-in tools by a short alias: read_file reads as "read". Every other tool (MCP tools included) and the Trace viewer keep the tool\'s own name, and hovering a short name shows it.',
+ notifications: "Task completion notifications",
+ notificationsInfo:
+ "Shows a system notification when a Task finishes while the window is hidden or unfocused; clicking it opens that Session. Turning this on asks the system for permission on the spot — the system asks once, never again after a refusal, and the only way back is its own notification settings.",
+ notificationsDenied:
+ "The system has denied notifications for this app. Allow them in your system notification settings, then turn this on again.",
+ notificationsDismissed:
+ "The permission prompt was closed without an answer, so notifications stay off. Turn this on again to ask once more.",
+ notificationsUnsupported: "This browser does not support system notifications.",
currencyInfo: "Display currency for prices; storage is always USD.",
changePasswordInfo: "Change this account's sign-in password.",
accentNames: {
@@ -362,7 +370,7 @@ export const en: Strings = {
listSeparator: ", ",
},
- /** Desktop task-completion notifications (window unfocused; desktop-shell sessions only). */
+ /** Task-completion notifications (window unfocused; opt-in, see lib/notification-pref). */
notify: {
taskCompleteTitle: "Task completed",
/** `session` is the Session title (defaultSessionTitle when unnamed). */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index e44677fb..8b211cf0 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -228,6 +228,13 @@ export const zh = {
toolAliases: "工具短名",
toolAliasesInfo:
"对话里的工具卡片用短名称呼内置工具,read_file 显示为「读取」。其余工具(含 MCP 工具)与轨迹观测始终是工具原本的名字;悬停短名也能看到它。",
+ notifications: "任务完成通知",
+ notificationsInfo:
+ "Task 在窗口失焦或隐藏时结束,弹一条系统通知,点击即回到该 Session。打开这个开关会当场向系统申请通知权限——系统只问这一次,被拒之后不再询问,只能到系统的通知设置里改回来。",
+ notificationsDenied: "系统已拒绝本应用的通知权限。请先在系统的通知设置中允许,再打开这个开关。",
+ notificationsDismissed:
+ "权限提示被关闭、没有给出答复,通知因此保持关闭。再次打开这个开关可以重新申请。",
+ notificationsUnsupported: "当前浏览器不支持系统通知。",
currencyInfo: "价格显示币种;存储始终为美元。",
changePasswordInfo: "更改当前账号的登录密码。",
accentNames: {
@@ -369,7 +376,7 @@ export const zh = {
listSeparator: "、",
},
- /** Desktop task-completion notifications (window unfocused; desktop-shell sessions only). */
+ /** Task-completion notifications (window unfocused; opt-in, see lib/notification-pref). */
notify: {
taskCompleteTitle: "任务完成",
/** `session` is the Session title (defaultSessionTitle when unnamed). */
diff --git a/packages/web/src/state/use-completion-notifications.ts b/packages/web/src/state/use-completion-notifications.ts
index a6b20ab5..82b0d1ab 100644
--- a/packages/web/src/state/use-completion-notifications.ts
+++ b/packages/web/src/state/use-completion-notifications.ts
@@ -1,24 +1,32 @@
/**
- * Desktop task-completion notifications, renderer-side only (standard Web Notification
- * API — no preload, no private IPC: the desktop window stays a plain browser environment).
+ * Task-completion notifications, renderer-side only (standard Web Notification API — no
+ * preload, no private IPC: the desktop window stays a plain browser environment).
*
* Watches the tracked Session list for active→idle transitions (lib/completion-notify)
* and, when the window is hidden or unfocused, shows a system notification with the
- * Session's title; clicking focuses the window and opens that Session. Gated to
- * sessionVia === "desktop": only the desktop shell's own window qualifies — there the
- * Notification permission is granted by default, so plain browsers (which would face a
- * permission prompt) are never touched.
+ * Session's title; clicking focuses the window and opens that Session.
+ *
+ * Two gates, both from lib/notification-pref: the user turned the preference on, and the
+ * platform grants permission at this moment. The permission is checked every time rather
+ * than trusted from the moment it was granted — an OS can take it back while the app runs,
+ * and a revoked permission must not be read as "show it anyway". There is no gate on the
+ * desktop shell: the switch that opens this feature is the same in a browser, and the
+ * permission prompt it triggers is one the user just asked for.
*/
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useSyncExternalStore } from "react";
import { useNavigate } from "react-router";
import { S } from "../lib/strings";
import { createCompletionTracker } from "../lib/completion-notify";
-import { useAuth } from "./auth";
+import {
+ notificationPermission,
+ notificationsEnabledVersion,
+ readNotificationsEnabled,
+ subscribeNotificationsEnabled,
+} from "../lib/notification-pref";
import { useProject } from "./project";
import { useSessions } from "./sessions";
export function useCompletionNotifications(): void {
- const { sessionVia } = useAuth();
const { sessions } = useSessions();
const { setCurrentAgentId } = useProject();
const navigate = useNavigate();
@@ -30,17 +38,21 @@ export function useCompletionNotifications(): void {
const setCurrentAgentIdRef = useRef(setCurrentAgentId);
setCurrentAgentIdRef.current = setCurrentAgentId;
- const enabled = sessionVia === "desktop";
+ // The settings switch writes the preference; this follows it without a reload.
+ useSyncExternalStore(subscribeNotificationsEnabled, notificationsEnabledVersion);
+ const enabled = readNotificationsEnabled();
useEffect(() => {
- if (!enabled) return;
- // The tracker must see every snapshot (also while focused): completions the user
- // watched happen are consumed silently instead of surfacing on a later blur.
+ // The tracker must see every snapshot — also while focused, and also while the
+ // preference is off: completions the user watched happen, or that happened while
+ // notifications were switched off, are consumed silently here instead of surfacing on
+ // a later blur or replaying the moment the preference is switched back on.
const completed = trackerRef.current.observe(
sessions.map((s) => ({ sessionId: s.sessionId, status: s.status })),
);
+ if (!enabled) return;
if (completed.length === 0) return;
if (!document.hidden && document.hasFocus()) return;
- if (typeof Notification === "undefined" || Notification.permission !== "granted") return;
+ if (notificationPermission() !== "granted") return;
for (const sessionId of completed) {
const session = sessions.find((s) => s.sessionId === sessionId);
const title = session?.title ?? S.chat.defaultSessionTitle;
diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.ts
index 27996d46..c2e21ae5 100644
--- a/packages/web/test/install-scope.test.ts
+++ b/packages/web/test/install-scope.test.ts
@@ -84,6 +84,7 @@ function populated(): ReturnType<typeof memStorage> {
"penguin.files.treeVisible": "0",
"penguin.files.treeWidth": "220",
"penguin.files.editorWrap": "1",
+ "penguin.notifications": "1",
});
}
@@ -110,6 +111,7 @@ const PREFERENCE_KEYS = [
"penguin.files.treeVisible",
"penguin.files.treeWidth",
"penguin.files.editorWrap",
+ "penguin.notifications",
];
const WEB_SRC = fileURLToPath(new URL("../src", import.meta.url));
diff --git a/packages/web/test/notification-pref.test.ts b/packages/web/test/notification-pref.test.ts
new file mode 100644
index 00000000..dd8ea80f
--- /dev/null
+++ b/packages/web/test/notification-pref.test.ts
@@ -0,0 +1,197 @@
+/**
+ * The task-completion notification's opt-in (lib/notification-pref): what the stored
+ * preference reads as, and what a request for OS permission does to it.
+ *
+ * The defect this covers is that the preference and the permission are separate facts.
+ * Nothing may store the opt-in unless the platform granted permission in that same
+ * request, or the switch latches on over notifications that can never be shown — and the
+ * default has to be off, because turning it on is what opens the system prompt.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ NOTIFICATIONS_KEY,
+ enableNotifications,
+ notificationHintFor,
+ notificationPermission,
+ notificationsEnabledVersion,
+ readNotificationsEnabled,
+ requestNotificationPermission,
+ subscribeNotificationsEnabled,
+ writeNotificationsEnabled,
+} from "../src/lib/notification-pref";
+import type { NotificationStorage } from "../src/lib/notification-pref";
+
+/** In-memory storage: vitest runs in a Node environment, so there is no localStorage. */
+function fakeStorage(entries: Record<string, string> = {}): NotificationStorage & {
+ map: Map<string, string>;
+} {
+ const map = new Map(Object.entries(entries));
+ return {
+ map,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ };
+}
+
+/**
+ * A platform whose permission answer is fixed. `requestPermission` records its calls so a
+ * test can tell an answer that came from the platform apart from one assumed by the app.
+ */
+function stubNotification(permission: NotificationPermission): { requests: number } {
+ const calls = { requests: 0 };
+ vi.stubGlobal("Notification", {
+ permission,
+ requestPermission: async () => {
+ calls.requests += 1;
+ return permission;
+ },
+ });
+ return calls;
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("the stored opt-in", () => {
+ it("is off unless the stored value is exactly the on marker", () => {
+ expect(readNotificationsEnabled(fakeStorage())).toBe(false);
+ expect(readNotificationsEnabled(fakeStorage({ [NOTIFICATIONS_KEY]: "1" }))).toBe(true);
+ expect(readNotificationsEnabled(fakeStorage({ [NOTIFICATIONS_KEY]: "0" }))).toBe(false);
+ expect(readNotificationsEnabled(fakeStorage({ [NOTIFICATIONS_KEY]: "true" }))).toBe(false);
+ });
+
+ it("round-trips a write and tells its subscribers", () => {
+ const storage = fakeStorage();
+ let notified = 0;
+ const stop = subscribeNotificationsEnabled(() => {
+ notified += 1;
+ });
+ const before = notificationsEnabledVersion();
+
+ writeNotificationsEnabled(true, storage);
+ expect(readNotificationsEnabled(storage)).toBe(true);
+ writeNotificationsEnabled(false, storage);
+ expect(readNotificationsEnabled(storage)).toBe(false);
+
+ expect(notified).toBe(2);
+ expect(notificationsEnabledVersion()).toBe(before + 2);
+ stop();
+ writeNotificationsEnabled(true, storage);
+ expect(notified).toBe(2);
+ });
+
+ it("survives storage that throws, which only costs persistence", () => {
+ const broken: NotificationStorage = {
+ getItem: () => {
+ throw new Error("site data blocked");
+ },
+ setItem: () => {
+ throw new Error("site data blocked");
+ },
+ };
+ expect(readNotificationsEnabled(broken)).toBe(false);
+ expect(() => writeNotificationsEnabled(true, broken)).not.toThrow();
+ });
+});
+
+describe("asking the platform for permission", () => {
+ it("reports a platform with no Notification API as unsupported, and asks it nothing", async () => {
+ vi.stubGlobal("Notification", undefined);
+ expect(notificationPermission()).toBe("unsupported");
+ await expect(requestNotificationPermission()).resolves.toBe("unsupported");
+ });
+
+ it("passes the platform's own answer through", async () => {
+ stubNotification("default");
+ expect(notificationPermission()).toBe("default");
+ await expect(requestNotificationPermission()).resolves.toBe("default");
+
+ stubNotification("granted");
+ await expect(requestNotificationPermission()).resolves.toBe("granted");
+ });
+
+ it("falls back to the live permission when the request answers with neither", async () => {
+ // The older callback-style API resolves undefined while still setting the permission.
+ vi.stubGlobal("Notification", {
+ permission: "granted",
+ requestPermission: async () => undefined,
+ });
+ await expect(requestNotificationPermission()).resolves.toBe("granted");
+ });
+});
+
+describe("turning the preference on", () => {
+ it("stores the opt-in once the request came back granted", async () => {
+ const storage = fakeStorage();
+ const calls = stubNotification("granted");
+
+ await expect(enableNotifications(storage)).resolves.toBe("granted");
+ expect(calls.requests).toBe(1);
+ expect(readNotificationsEnabled(storage)).toBe(true);
+ });
+
+ it("does not latch on when the platform denies", async () => {
+ const storage = fakeStorage();
+ stubNotification("denied");
+
+ await expect(enableNotifications(storage)).resolves.toBe("denied");
+ expect(readNotificationsEnabled(storage)).toBe(false);
+ expect(storage.map.has(NOTIFICATIONS_KEY)).toBe(false);
+ });
+
+ it("does not latch on when the prompt is dismissed, which leaves the answer at default", async () => {
+ const storage = fakeStorage();
+ stubNotification("default");
+
+ await expect(enableNotifications(storage)).resolves.toBe("default");
+ expect(readNotificationsEnabled(storage)).toBe(false);
+ });
+
+ it("does not latch on where the platform has no notifications at all", async () => {
+ const storage = fakeStorage();
+ vi.stubGlobal("Notification", undefined);
+
+ await expect(enableNotifications(storage)).resolves.toBe("unsupported");
+ expect(readNotificationsEnabled(storage)).toBe(false);
+ });
+
+ it("takes the answer the request gave, not the permission it started from", async () => {
+ // The real sequence, which a stub answering with a fixed permission cannot express:
+ // the permission is "default" until the prompt is answered, and only the request
+ // reports what the user chose.
+ const storage = fakeStorage();
+ let permission: NotificationPermission = "default";
+ vi.stubGlobal("Notification", {
+ get permission() {
+ return permission;
+ },
+ requestPermission: async () => {
+ permission = "granted";
+ return permission;
+ },
+ });
+
+ await expect(enableNotifications(storage)).resolves.toBe("granted");
+ expect(readNotificationsEnabled(storage)).toBe(true);
+ });
+});
+
+describe("what the row says under the switch", () => {
+ it("says nothing to a platform that has simply not been asked yet", () => {
+ expect(notificationHintFor("default", false)).toBeNull();
+ expect(notificationHintFor("granted", false)).toBeNull();
+ expect(notificationHintFor("granted", true)).toBeNull();
+ });
+
+ it("names a prompt closed without an answer, which is the switch springing back", () => {
+ // A dismissal leaves the permission at "default", so nothing is stored and the switch
+ // reverts. With no line under it that click reads as a control that does nothing.
+ expect(notificationHintFor("default", true)).toBe("dismissed");
+ });
+
+ it("keeps a refusal and a missing API on screen whether or not this session asked", () => {
+ expect(notificationHintFor("denied", false)).toBe("denied");
+ expect(notificationHintFor("denied", true)).toBe("denied");
+ expect(notificationHintFor("unsupported", false)).toBe("unsupported");
+ expect(notificationHintFor("unsupported", true)).toBe("unsupported");
+ });
+});