Skip to content

Commit 87ecc40

Browse files
authored
feat(webui): auto-request notification permission on first chat send (#122446)
* feat(webui): auto-request notification permission on first chat send The Control UI now asks for notification permission automatically on the first chat message you send (once per browser/origin; web push in browsers, native prompt in the macOS app; denied permission is never re-asked automatically — Settings -> Notifications stays the manual path). * fix(webui): preserve notification prompt gesture boundary Restrict the one-shot notification prompt to direct non-command composer sends, invoke browser permission synchronously, and keep Settings documented as the management and recovery path. * fix(webui): exclude deferred notification sends Require an actively dispatching browser input event before consuming the notification one-shot, so retained catalog handoffs and other deferred sends cannot suppress the first real composer prompt.
1 parent 3dcd494 commit 87ecc40

4 files changed

Lines changed: 333 additions & 4 deletions

File tree

‎docs/web/notifications.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ read_when:
77
- Comparing Control UI notifications with mobile push
88
---
99

10-
OpenClaw can ping you when something needs your attention — in the browser that runs the Control UI, or through native macOS notifications when you use the OpenClaw macOS app. Everything lives under **Settings → Notifications**: enable the current device, check its status, and send yourself a test.
10+
OpenClaw can ping you when something needs your attention — in the browser that runs the Control UI, or through native macOS notifications when you use the OpenClaw macOS app. Your first chat send may request permission automatically; **Settings → Notifications** remains the place to enable or repair the current device, check its status, and send yourself a test.
1111

1212
This page covers those two surfaces. It does not control channel reaction notifications, Android notification forwarding, or iOS background push — the mobile apps register for push through their own node paths; see [iOS](/platforms/ios) and [Nodes](/nodes).
1313

@@ -25,6 +25,8 @@ The macOS app deliberately uses the native permission flow instead of browser pu
2525

2626
## Enable browser notifications
2727

28+
The Control UI asks for notification permission automatically the first time you send a chat message, once per browser and origin. **Settings → Notifications** remains the manual path for enabling or repairing notifications, including after you deny the automatic prompt.
29+
2830
1. Open the Control UI in a browser that supports service workers, `PushManager`, and notifications.
2931
2. Make sure the Control UI is connected to the Gateway.
3032
3. Open **Settings → Notifications** and select **Enable notifications**.
@@ -37,6 +39,8 @@ Behind the scenes, enabling creates a push subscription in this browser and regi
3739

3840
## Enable notifications in the macOS app
3941

42+
The macOS app also asks automatically on your first chat send, but only while permission is **Not requested**. It never opens System Settings automatically after a denial; use **Settings → Notifications** to manage permission manually.
43+
4044
1. Open **Settings → Notifications** in the OpenClaw macOS app.
4145
2. Select **Enable notifications** while the permission shows **Not requested**.
4246
3. Approve the macOS permission prompt.
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
/* @vitest-environment jsdom */
2+
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import { createStorageMock } from "../test-helpers/storage.ts";
5+
import {
6+
autoPromptNotificationsOnSend,
7+
hasActiveNotificationPromptGesture,
8+
shouldAutoPromptNotificationsOnSend,
9+
} from "./notifications-auto-prompt.ts";
10+
11+
const STORAGE_KEY = "openclaw.control.notificationsAutoPrompt.v1";
12+
13+
type AutoPromptContext = Parameters<typeof autoPromptNotificationsOnSend>[0];
14+
type NativePermission = "granted" | "denied" | "notDetermined" | "unknown";
15+
16+
let storage: Storage;
17+
let browserRequestPermission: ReturnType<typeof vi.fn>;
18+
19+
beforeEach(() => {
20+
storage = createStorageMock();
21+
vi.stubGlobal("localStorage", storage);
22+
browserRequestPermission = vi.fn(() => Promise.resolve("granted" as NotificationPermission));
23+
vi.stubGlobal("Notification", { requestPermission: browserRequestPermission });
24+
});
25+
26+
afterEach(() => {
27+
vi.unstubAllGlobals();
28+
vi.restoreAllMocks();
29+
});
30+
31+
function createContext(
32+
overrides: {
33+
supported?: boolean;
34+
permission?: NotificationPermission | "unsupported";
35+
subscribed?: boolean;
36+
loading?: boolean;
37+
nativePermission?: NativePermission | null;
38+
} = {},
39+
) {
40+
const enable = vi.fn(async () => undefined);
41+
const requestPermission = vi.fn();
42+
const nativePermission = overrides.nativePermission ?? null;
43+
const context = {
44+
nativeNotifications:
45+
nativePermission === null
46+
? null
47+
: { snapshot: { permission: nativePermission }, requestPermission },
48+
webPush: {
49+
snapshot: {
50+
supported: overrides.supported ?? true,
51+
permission: overrides.permission ?? "default",
52+
subscribed: overrides.subscribed ?? false,
53+
loading: overrides.loading ?? false,
54+
error: null,
55+
},
56+
enable,
57+
},
58+
} as unknown as AutoPromptContext;
59+
return { context, enable, requestPermission };
60+
}
61+
62+
describe("notification auto-prompt", () => {
63+
it("requests browser permission synchronously and enables web push only once", async () => {
64+
const { context, enable } = createContext();
65+
66+
autoPromptNotificationsOnSend(context);
67+
autoPromptNotificationsOnSend(context);
68+
69+
expect(browserRequestPermission).toHaveBeenCalledOnce();
70+
expect(enable).not.toHaveBeenCalled();
71+
await Promise.resolve();
72+
expect(enable).toHaveBeenCalledOnce();
73+
expect(storage.getItem(STORAGE_KEY)).toBe("1");
74+
});
75+
76+
it("records a dismissed browser prompt without enabling web push", async () => {
77+
browserRequestPermission.mockResolvedValue("default");
78+
const { context, enable } = createContext();
79+
80+
autoPromptNotificationsOnSend(context);
81+
autoPromptNotificationsOnSend(context);
82+
await Promise.resolve();
83+
84+
expect(browserRequestPermission).toHaveBeenCalledOnce();
85+
expect(enable).not.toHaveBeenCalled();
86+
expect(storage.getItem(STORAGE_KEY)).toBe("1");
87+
});
88+
89+
it("does nothing when the one-shot flag is already set", () => {
90+
storage.setItem(STORAGE_KEY, "1");
91+
const { context, enable } = createContext();
92+
93+
autoPromptNotificationsOnSend(context);
94+
95+
expect(enable).not.toHaveBeenCalled();
96+
});
97+
98+
it.each(["denied", "granted"] as const)(
99+
"does not enable web push when permission is %s",
100+
(permission) => {
101+
const { context, enable } = createContext({ permission });
102+
103+
autoPromptNotificationsOnSend(context);
104+
105+
expect(enable).not.toHaveBeenCalled();
106+
expect(storage.getItem(STORAGE_KEY)).toBeNull();
107+
},
108+
);
109+
110+
it.each([
111+
["subscribed", { subscribed: true }],
112+
["loading", { loading: true }],
113+
["unsupported", { supported: false, permission: "unsupported" as const }],
114+
])("does not enable web push when it is %s", (_name, overrides) => {
115+
const { context, enable } = createContext(overrides);
116+
117+
autoPromptNotificationsOnSend(context);
118+
119+
expect(enable).not.toHaveBeenCalled();
120+
expect(storage.getItem(STORAGE_KEY)).toBeNull();
121+
});
122+
123+
it("prefers the native permission flow when permission is not determined", () => {
124+
const { context, enable, requestPermission } = createContext({
125+
nativePermission: "notDetermined",
126+
});
127+
128+
autoPromptNotificationsOnSend(context);
129+
130+
expect(requestPermission).toHaveBeenCalledOnce();
131+
expect(enable).not.toHaveBeenCalled();
132+
expect(storage.getItem(STORAGE_KEY)).toBe("1");
133+
});
134+
135+
it.each(["denied", "unknown"] as const)(
136+
"does not request native permission when it is %s",
137+
(nativePermission) => {
138+
const { context, enable, requestPermission } = createContext({ nativePermission });
139+
140+
autoPromptNotificationsOnSend(context);
141+
142+
expect(requestPermission).not.toHaveBeenCalled();
143+
expect(enable).not.toHaveBeenCalled();
144+
expect(storage.getItem(STORAGE_KEY)).toBeNull();
145+
},
146+
);
147+
148+
it("fails closed when the localStorage getter throws", () => {
149+
Object.defineProperty(globalThis, "localStorage", {
150+
configurable: true,
151+
get() {
152+
throw new Error("opaque origin");
153+
},
154+
});
155+
const { context, enable, requestPermission } = createContext({
156+
nativePermission: "notDetermined",
157+
});
158+
159+
expect(() => autoPromptNotificationsOnSend(context)).not.toThrow();
160+
expect(requestPermission).not.toHaveBeenCalled();
161+
expect(enable).not.toHaveBeenCalled();
162+
});
163+
});
164+
165+
describe("notification auto-prompt send boundary", () => {
166+
const candidate = {
167+
connected: true,
168+
directComposerSend: true,
169+
message: "hello",
170+
hasAttachments: false,
171+
isCommand: false,
172+
};
173+
174+
it("accepts a direct composer prompt or attachment", () => {
175+
expect(shouldAutoPromptNotificationsOnSend(candidate)).toBe(true);
176+
expect(
177+
shouldAutoPromptNotificationsOnSend({ ...candidate, message: "", hasAttachments: true }),
178+
).toBe(true);
179+
});
180+
181+
it("recognizes only the synchronous browser event dispatch", async () => {
182+
const button = document.createElement("button");
183+
let duringDispatch = false;
184+
let afterDispatch = true;
185+
button.addEventListener("click", () => {
186+
duringDispatch = hasActiveNotificationPromptGesture();
187+
queueMicrotask(() => {
188+
afterDispatch = hasActiveNotificationPromptGesture();
189+
});
190+
});
191+
192+
button.click();
193+
await Promise.resolve();
194+
195+
expect(duringDispatch).toBe(true);
196+
expect(afterDispatch).toBe(false);
197+
});
198+
199+
it.each([
200+
["programmatic send", { directComposerSend: false }],
201+
["recognized command", { isCommand: true }],
202+
["disconnected composer", { connected: false }],
203+
["empty composer", { message: "" }],
204+
])("rejects a %s", (_name, override) => {
205+
expect(shouldAutoPromptNotificationsOnSend({ ...candidate, ...override })).toBe(false);
206+
});
207+
});
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import type { ApplicationContext } from "./context.ts";
2+
3+
const NOTIFICATIONS_AUTO_PROMPT_KEY = "openclaw.control.notificationsAutoPrompt.v1";
4+
5+
type NotificationsContext = Pick<ApplicationContext, "nativeNotifications" | "webPush">;
6+
7+
type NotificationsAutoPromptCandidate = {
8+
connected: boolean;
9+
directComposerSend: boolean;
10+
message: string;
11+
hasAttachments: boolean;
12+
isCommand: boolean;
13+
};
14+
15+
export function hasActiveNotificationPromptGesture(): boolean {
16+
// User activation can survive awaited work. window.event exists only while
17+
// the originating input event is dispatching, so deferred sends stay out.
18+
return typeof window !== "undefined" && window.event !== undefined;
19+
}
20+
21+
export function shouldAutoPromptNotificationsOnSend(
22+
candidate: NotificationsAutoPromptCandidate,
23+
): boolean {
24+
return (
25+
candidate.connected &&
26+
candidate.directComposerSend &&
27+
!candidate.isCommand &&
28+
(candidate.message.trim().length > 0 || candidate.hasAttachments)
29+
);
30+
}
31+
32+
function markAutoPrompted(storage: Storage): void {
33+
// Persist the one-shot contract before asking so re-entrant sends cannot prompt twice.
34+
try {
35+
storage.setItem(NOTIFICATIONS_AUTO_PROMPT_KEY, "1");
36+
} catch {
37+
// Permission state still prevents repeat prompts after a completed decision.
38+
}
39+
}
40+
41+
export function autoPromptNotificationsOnSend(context: NotificationsContext): void {
42+
let storage: Storage;
43+
try {
44+
storage = localStorage;
45+
if (storage.getItem(NOTIFICATIONS_AUTO_PROMPT_KEY) !== null) {
46+
return;
47+
}
48+
} catch {
49+
return;
50+
}
51+
52+
const nativeNotifications = context.nativeNotifications;
53+
if (nativeNotifications) {
54+
// Denied is terminal for auto-asks; the manual path may open System Settings.
55+
if (nativeNotifications.snapshot.permission !== "notDetermined") {
56+
return;
57+
}
58+
markAutoPrompted(storage);
59+
// Keep the permission request in the user-gesture tick for Safari transient activation.
60+
try {
61+
nativeNotifications.requestPermission();
62+
} catch {
63+
// Notification prompting must never interrupt chat sending.
64+
}
65+
return;
66+
}
67+
68+
const snapshot = context.webPush.snapshot;
69+
if (
70+
!snapshot.supported ||
71+
snapshot.permission !== "default" ||
72+
snapshot.subscribed ||
73+
snapshot.loading
74+
) {
75+
// Denied and granted permissions are terminal for automatic prompts.
76+
return;
77+
}
78+
markAutoPrompted(storage);
79+
try {
80+
// Invoke the browser prompt before leaving the user-gesture tick. Web-push
81+
// subscription can continue asynchronously after permission is granted.
82+
const permission = Notification.requestPermission();
83+
void permission
84+
.then((next) => {
85+
if (next === "granted") {
86+
void context.webPush.enable();
87+
}
88+
})
89+
.catch(() => {});
90+
} catch {
91+
// Notification prompting must never interrupt chat sending.
92+
}
93+
}

‎ui/src/pages/chat/chat-state-page.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@ import type { GatewayBrowserClient } from "../../api/gateway.ts";
22
import type { AgentsListResult } from "../../api/types.ts";
33
import { fetchAssistantIdentity } from "../../app/assistant-identity.ts";
44
import type { ApplicationContext } from "../../app/context.ts";
5+
import {
6+
autoPromptNotificationsOnSend,
7+
hasActiveNotificationPromptGesture,
8+
shouldAutoPromptNotificationsOnSend,
9+
} from "../../app/notifications-auto-prompt.ts";
510
import { loadLocalUserIdentity, loadSettings, patchSettings } from "../../app/settings.ts";
611
import { t } from "../../i18n/index.ts";
12+
import { parseSlashCommand } from "../../lib/chat/commands.ts";
713
import { resolveSafeExternalUrl } from "../../lib/open-external-url.ts";
814
import {
915
canonicalUiSessionKeyForPersistence,
@@ -29,7 +35,7 @@ import {
2935
} from "./input-history.ts";
3036
import { beginQueuedMessageEdit, cancelQueuedMessageEdit } from "./queued-message-edit.ts";
3137
import type { RenderLifecycle } from "./render-lifecycle.ts";
32-
import { handleAbortChat } from "./run-lifecycle.ts";
38+
import { handleAbortChat, hasAbortableSessionRun, isChatStopCommand } from "./run-lifecycle.ts";
3339
import { handleChatScroll, resetChatScroll, scheduleChatScroll } from "./scroll.ts";
3440
import type { ChatMessageCache } from "./session-message-cache.ts";
3541
import {
@@ -277,8 +283,27 @@ export function createPageState(
277283
};
278284
attachChatRealtimeActions(state);
279285
state.loadAssistantIdentity = () => loadPageAssistantIdentity(state);
280-
state.handleSendChat = (messageOverride, options) =>
281-
handleSendChat(state, messageOverride, options as never);
286+
state.handleSendChat = (messageOverride, options) => {
287+
const message = messageOverride ?? state.chatMessage;
288+
const isCommand =
289+
parseSlashCommand(message) !== null ||
290+
(isChatStopCommand(message) && hasAbortableSessionRun(state));
291+
if (
292+
shouldAutoPromptNotificationsOnSend({
293+
connected: state.connected,
294+
directComposerSend:
295+
messageOverride === undefined &&
296+
options === undefined &&
297+
hasActiveNotificationPromptGesture(),
298+
message,
299+
hasAttachments: state.chatAttachments.length > 0,
300+
isCommand,
301+
})
302+
) {
303+
autoPromptNotificationsOnSend(context);
304+
}
305+
return handleSendChat(state, messageOverride, options as never);
306+
};
282307
state.handleAbortChat = async (options) => {
283308
await handleAbortChat(state, options as never);
284309
renderLifecycle.invalidate();

0 commit comments

Comments
 (0)