Skip to content

Commit 432561a

Browse files
committed
feat(web): notify agent updates with Web Push
1 parent 31e0c83 commit 432561a

39 files changed

Lines changed: 3249 additions & 204 deletions
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
const PAYLOAD_VERSION = 1;
2+
3+
function notificationPayload(value) {
4+
if (typeof value !== "object" || value === null || value.version !== PAYLOAD_VERSION) {
5+
return null;
6+
}
7+
const required = ["title", "body", "path", "tag", "updatedAt"];
8+
if (required.some((key) => typeof value[key] !== "string")) {
9+
return null;
10+
}
11+
if (typeof value.silent !== "boolean" || !value.path.startsWith("/")) {
12+
return null;
13+
}
14+
return value;
15+
}
16+
17+
self.addEventListener("push", (event) => {
18+
event.waitUntil(
19+
(async () => {
20+
let data;
21+
try {
22+
data = event.data?.json();
23+
} catch {
24+
return;
25+
}
26+
const payload = notificationPayload(data);
27+
if (!payload) {
28+
return;
29+
}
30+
31+
const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
32+
const watchingThread = windows.some((client) => {
33+
const url = new URL(client.url);
34+
return client.focused && url.pathname === payload.path;
35+
});
36+
if (watchingThread) {
37+
return;
38+
}
39+
40+
const timestamp = Date.parse(payload.updatedAt);
41+
await self.registration.showNotification(payload.title, {
42+
body: payload.body,
43+
icon: "/apple-touch-icon.png",
44+
badge: "/favicon-32x32.png",
45+
data: { path: payload.path },
46+
tag: payload.tag,
47+
renotify: true,
48+
silent: payload.silent,
49+
...(Number.isNaN(timestamp) ? {} : { timestamp }),
50+
...(payload.silent ? {} : { vibrate: [120, 60, 180] }),
51+
});
52+
})(),
53+
);
54+
});
55+
56+
self.addEventListener("notificationclick", (event) => {
57+
event.notification.close();
58+
const path = event.notification.data?.path;
59+
if (typeof path !== "string" || !path.startsWith("/")) {
60+
return;
61+
}
62+
event.waitUntil(
63+
(async () => {
64+
const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
65+
const existing = windows[0];
66+
if (existing) {
67+
await existing.navigate(path);
68+
await existing.focus();
69+
return;
70+
}
71+
await self.clients.openWindow(path);
72+
})(),
73+
);
74+
});

‎apps/web/src/components/settings/NotificationsSettingsPanel.tsx‎

Lines changed: 53 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
11
import { BellIcon } from "lucide-react";
2+
import { useAtomValue } from "@effect/atom-react";
3+
import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
24
import { DEFAULT_CLIENT_SETTINGS, type ClientSettings } from "@t3tools/contracts/settings";
5+
import { useState } from "react";
36

47
import { isElectron } from "~/env";
58
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
9+
import {
10+
disableWebPushNotifications,
11+
enableWebPushNotifications,
12+
isWebPushSupported,
13+
} from "~/notifications/webPush";
614
import { Switch } from "../ui/switch";
715
import {
816
SettingResetButton,
@@ -47,55 +55,73 @@ const NOTIFICATION_TOGGLES: ReadonlyArray<{
4755
{
4856
key: "desktopNotificationSound",
4957
searchId: "notification-sound",
50-
description: "Play the system notification sound.",
58+
description: "Play an alert sound.",
5159
resetLabel: "notification sound",
5260
},
5361
];
5462

5563
export function NotificationsSettingsPanel() {
5664
const settings = useClientSettings();
5765
const updateSettings = useUpdateClientSettings();
66+
const relaySession = useAtomValue(managedRelaySessionAtom);
67+
const [webPushError, setWebPushError] = useState<string | null>(null);
68+
const [webPushPending, setWebPushPending] = useState(false);
69+
const enabledKey = isElectron
70+
? ("desktopNotificationsEnabled" as const)
71+
: ("webPushNotificationsEnabled" as const);
72+
const notificationsEnabled = settings[enabledKey];
73+
const notificationsDisabled = isElectron && !notificationsEnabled;
74+
const webPushAvailable = isWebPushSupported() && relaySession !== null;
5875

59-
if (!isElectron) {
60-
return (
61-
<SettingsPageContainer>
62-
<SettingsSection title="Notifications" icon={<BellIcon className="size-4" />}>
63-
<p className="px-3 text-[13px] text-muted-foreground/80 sm:px-4">
64-
Native notifications are available in the desktop app.
65-
</p>
66-
</SettingsSection>
67-
</SettingsPageContainer>
68-
);
69-
}
70-
71-
const notificationsDisabled = !settings.desktopNotificationsEnabled;
76+
const setNotificationsEnabled = async (checked: boolean) => {
77+
if (isElectron) {
78+
updateSettings({ desktopNotificationsEnabled: checked });
79+
return;
80+
}
81+
setWebPushPending(true);
82+
setWebPushError(null);
83+
try {
84+
if (checked) {
85+
await enableWebPushNotifications({
86+
...settings,
87+
webPushNotificationsEnabled: true,
88+
});
89+
} else {
90+
await disableWebPushNotifications();
91+
}
92+
updateSettings({ webPushNotificationsEnabled: checked });
93+
} catch (error) {
94+
setWebPushError(error instanceof Error ? error.message : "Web Push setup failed.");
95+
} finally {
96+
setWebPushPending(false);
97+
}
98+
};
7299

73100
return (
74101
<SettingsPageContainer>
75102
<SettingsSection title="Notifications" icon={<BellIcon className="size-4" />}>
76103
<SettingsRow
77104
{...searchableSetting("notifications")}
78-
description="Show a native notification when an agent needs you. Suppressed while you are looking at that thread."
105+
title={isElectron ? "Notifications" : "Web Push"}
106+
description={
107+
webPushError ??
108+
(!isElectron && !webPushAvailable
109+
? "Sign in to T3 Connect to enable Web Push."
110+
: "Notify when an agent needs you. Suppressed while you are looking at that thread.")
111+
}
79112
resetAction={
80-
settings.desktopNotificationsEnabled !==
81-
DEFAULT_CLIENT_SETTINGS.desktopNotificationsEnabled ? (
113+
notificationsEnabled !== DEFAULT_CLIENT_SETTINGS[enabledKey] ? (
82114
<SettingResetButton
83115
label="notifications"
84-
onClick={() =>
85-
updateSettings({
86-
desktopNotificationsEnabled:
87-
DEFAULT_CLIENT_SETTINGS.desktopNotificationsEnabled,
88-
})
89-
}
116+
onClick={() => void setNotificationsEnabled(DEFAULT_CLIENT_SETTINGS[enabledKey])}
90117
/>
91118
) : null
92119
}
93120
control={
94121
<Switch
95-
checked={settings.desktopNotificationsEnabled}
96-
onCheckedChange={(checked) =>
97-
updateSettings({ desktopNotificationsEnabled: Boolean(checked) })
98-
}
122+
checked={notificationsEnabled}
123+
disabled={webPushPending || (!isElectron && !webPushAvailable)}
124+
onCheckedChange={(checked) => void setNotificationsEnabled(Boolean(checked))}
99125
aria-label="Enable notifications"
100126
/>
101127
}

‎apps/web/src/notifications/DesktopThreadNotifications.tsx‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
import { useEffect, useRef } from "react";
2+
import { useAtomValue } from "@effect/atom-react";
23
import { useNavigate } from "@tanstack/react-router";
4+
import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
35
import type { ClientSettings } from "@t3tools/contracts/settings";
46
import type { ScopedThreadRef } from "@t3tools/contracts";
57
import type {
68
EnvironmentThread,
79
EnvironmentThreadShell,
810
} from "@t3tools/client-runtime/state/shell";
911

10-
import { getClientSettings } from "~/hooks/useSettings";
12+
import { isElectron } from "~/env";
13+
import { getClientSettings, useClientSettings } from "~/hooks/useSettings";
1114
import { useActiveThreadRefFromRoute } from "~/hooks/useActiveThreadRef";
1215
import { appAtomRegistry } from "~/rpc/atomRegistry";
1316
import { environmentThreadDetails, environmentThreadShells } from "~/state/threads";
@@ -30,6 +33,7 @@ import {
3033
THREAD_ALERT_FOCUSED_TTL_MS,
3134
THREAD_ALERT_MAX_TTL_MS,
3235
} from "./threadAlertStore";
36+
import { reconcileWebPushRegistration } from "./webPush";
3337

3438
/**
3539
* Latest assistant text for a thread, but only when that thread's detail atom
@@ -239,6 +243,29 @@ function DesktopThreadNotifications() {
239243
return null;
240244
}
241245

246+
function WebPushRegistrationHost() {
247+
const settings = useClientSettings();
248+
const relaySession = useAtomValue(managedRelaySessionAtom);
249+
250+
useEffect(() => {
251+
if (isElectron) {
252+
return;
253+
}
254+
void reconcileWebPushRegistration(settings).catch((error: unknown) => {
255+
console.error("[WEB_PUSH] subscription reconciliation failed", { error });
256+
});
257+
}, [
258+
relaySession?.accountId,
259+
settings.desktopNotificationSound,
260+
settings.desktopNotifyApprovalNeeded,
261+
settings.desktopNotifyTaskCompleted,
262+
settings.desktopNotifyTaskFailed,
263+
settings.webPushNotificationsEnabled,
264+
]);
265+
266+
return null;
267+
}
268+
242269
/**
243270
* Alerts for agent task transitions: the native OS banner on desktop, plus the
244271
* chime and sidebar highlights that survive Do Not Disturb.
@@ -249,5 +276,10 @@ function DesktopThreadNotifications() {
249276
* discard them for no reason.
250277
*/
251278
export function DesktopThreadNotificationsHost() {
252-
return <DesktopThreadNotifications />;
279+
return (
280+
<>
281+
<DesktopThreadNotifications />
282+
<WebPushRegistrationHost />
283+
</>
284+
);
253285
}

‎apps/web/src/notifications/desktopNotifications.logic.ts‎

Lines changed: 2 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,10 @@ import type {
44
EnvironmentThreadShell,
55
} from "@t3tools/client-runtime/state/shell";
66
import { projectThreadAwareness, type AgentAwarenessPhase } from "@t3tools/shared/agentAwareness";
7+
import { agentNotificationKind } from "@t3tools/shared/agentNotifications";
78

89
import { notificationBody, notificationTitle } from "./notificationCopy";
910

10-
/**
11-
* Phases a thread must be leaving for its next phase to be worth announcing.
12-
* Requiring an active predecessor is what makes a thread that is merely
13-
* *observed* as finished (a cached snapshot, a resync, a reconnect) stay quiet:
14-
* nothing happened, we just learned about it.
15-
*/
16-
const ACTIVE_PHASES: ReadonlySet<AgentAwarenessPhase> = new Set([
17-
"starting",
18-
"running",
19-
"waiting_for_input",
20-
"waiting_for_approval",
21-
]);
22-
23-
/** Phases that can precede an approval prompt and still count as progress. */
24-
const PRE_APPROVAL_PHASES: ReadonlySet<AgentAwarenessPhase> = new Set([
25-
"starting",
26-
"running",
27-
"waiting_for_input",
28-
]);
29-
3011
export interface ThreadNotificationSettings {
3112
readonly enabled: boolean;
3213
readonly taskCompleted: boolean;
@@ -108,19 +89,7 @@ export function notifiableKind(
10889
previousPhase: AgentAwarenessPhase | null,
10990
nextPhase: AgentAwarenessPhase | null,
11091
): DesktopNotificationKind | null {
111-
if (previousPhase === null || nextPhase === null) {
112-
return null;
113-
}
114-
if (nextPhase === "completed" && ACTIVE_PHASES.has(previousPhase)) {
115-
return "task-completed";
116-
}
117-
if (nextPhase === "failed" && ACTIVE_PHASES.has(previousPhase)) {
118-
return "task-failed";
119-
}
120-
if (nextPhase === "waiting_for_approval" && PRE_APPROVAL_PHASES.has(previousPhase)) {
121-
return "approval-needed";
122-
}
123-
return null;
92+
return agentNotificationKind(previousPhase, nextPhase);
12493
}
12594

12695
function isNotificationKindEnabled(

0 commit comments

Comments
 (0)