Skip to content

Commit f992f5c

Browse files
committed
feat(web): add opt-in thread notifications and sounds
1 parent fcbe457 commit f992f5c

12 files changed

Lines changed: 330 additions & 0 deletions

‎apps/desktop/src/settings/DesktopClientSettings.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import * as DesktopClientSettings from "./DesktopClientSettings.ts";
1818

1919
const clientSettings: ClientSettings = {
2020
...DEFAULT_CLIENT_SETTINGS,
21+
notificationMode: "notifications-and-sound",
2122
appearanceContrast: 100,
2223
browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },
2324
browserDefaultZoomFactor: 1.25,
11.7 KB
Binary file not shown.
11.4 KB
Binary file not shown.
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import { useNavigate } from "@tanstack/react-router";
3+
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4+
import * as Option from "effect/Option";
5+
import { useEffect, useRef } from "react";
6+
7+
import { getClientSettings, useClientSettings } from "../hooks/useSettings";
8+
import { useEnvironments } from "../state/environments";
9+
import { environmentShell } from "../state/shell";
10+
import {
11+
hasDesktopNotifications,
12+
hasNotificationSound,
13+
playNotificationSound,
14+
unlockNotificationAudio,
15+
} from "../threadNotifications";
16+
import { resolveSidebarThreadStatus } from "./Sidebar.logic";
17+
18+
export function ThreadNotificationCoordinator() {
19+
const { environments } = useEnvironments();
20+
const mode = useClientSettings((settings) => settings.notificationMode);
21+
22+
useEffect(() => {
23+
if (!hasNotificationSound(mode)) return;
24+
document.addEventListener("pointerdown", unlockNotificationAudio);
25+
document.addEventListener("keydown", unlockNotificationAudio);
26+
return () => {
27+
document.removeEventListener("pointerdown", unlockNotificationAudio);
28+
document.removeEventListener("keydown", unlockNotificationAudio);
29+
};
30+
}, [mode]);
31+
32+
if (mode === "off") return null;
33+
34+
return environments.map((environment) => (
35+
<EnvironmentNotifications
36+
key={environment.environmentId}
37+
environmentId={environment.environmentId}
38+
/>
39+
));
40+
}
41+
42+
function EnvironmentNotifications({ environmentId }: { environmentId: EnvironmentId }) {
43+
const shell = useAtomValue(environmentShell.stateValueAtom(environmentId));
44+
const mode = useClientSettings((settings) => settings.notificationMode);
45+
const navigate = useNavigate();
46+
const previous = useRef(new Map<ThreadId, { input: string | null; completion: string | null }>());
47+
48+
useEffect(() => {
49+
if (shell.status !== "live" || Option.isNone(shell.snapshot)) {
50+
previous.current.clear();
51+
return;
52+
}
53+
const next = new Map<ThreadId, { input: string | null; completion: string | null }>();
54+
for (const thread of shell.snapshot.value.threads) {
55+
const status = resolveSidebarThreadStatus(thread);
56+
const prior = previous.current.get(thread.id);
57+
const input =
58+
status === "input" || status === "approval"
59+
? `${thread.latestTurn?.turnId ?? ""}:${status}`
60+
: null;
61+
const completion =
62+
status === "ready" && thread.latestTurn?.state === "completed"
63+
? thread.latestTurn.completedAt
64+
: (prior?.completion ?? null);
65+
next.set(thread.id, { input, completion });
66+
if (!prior || mode === "off" || thread.archivedAt !== null) continue;
67+
const kind =
68+
input && input !== prior.input
69+
? "input"
70+
: completion && completion !== prior.completion
71+
? "completion"
72+
: null;
73+
if (!kind) continue;
74+
if (hasNotificationSound(mode)) {
75+
void playNotificationSound(kind, () =>
76+
hasNotificationSound(getClientSettings().notificationMode),
77+
);
78+
}
79+
if (
80+
!hasDesktopNotifications(mode) ||
81+
typeof Notification === "undefined" ||
82+
Notification.permission !== "granted"
83+
)
84+
continue;
85+
try {
86+
const notification = new Notification(
87+
kind === "completion"
88+
? "Thread completed"
89+
: status === "approval"
90+
? "Approval needed"
91+
: "Input needed",
92+
{ body: thread.title, tag: `${environmentId}:${thread.id}`, silent: true },
93+
);
94+
notification.addEventListener("click", () => {
95+
notification.close();
96+
window.focus();
97+
void navigate({
98+
to: "/$environmentId/$threadId",
99+
params: { environmentId, threadId: thread.id },
100+
});
101+
});
102+
} catch {
103+
// Some browsers expose Notification but reject desktop presentation.
104+
}
105+
}
106+
previous.current = next;
107+
}, [environmentId, mode, navigate, shell]);
108+
109+
return null;
110+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import { useState } from "react";
2+
3+
import {
4+
hasDesktopNotifications,
5+
hasNotificationSound,
6+
NOTIFICATION_MODE_LABELS,
7+
unlockNotificationAudio,
8+
} from "../../threadNotifications";
9+
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
10+
import { SettingsRow } from "./settingsLayout";
11+
import { searchableSetting } from "./settingsSearch";
12+
import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
13+
14+
export function NotificationSettings() {
15+
const mode = useScopedSettings((settings) => settings.notificationMode);
16+
const updateSettings = useUpdateScopedSettings();
17+
const [permissionMessage, setPermissionMessage] = useState<string | null>(null);
18+
const [requesting, setRequesting] = useState(false);
19+
20+
return (
21+
<SettingsRow
22+
{...searchableSetting("thread-notifications")}
23+
description={
24+
permissionMessage ??
25+
"Alert when a thread finishes or needs input. Applies to this device while T3 Code is open."
26+
}
27+
control={
28+
<Select
29+
value={mode}
30+
disabled={requesting}
31+
onValueChange={async (value) => {
32+
if (
33+
value !== "off" &&
34+
value !== "notifications" &&
35+
value !== "sound" &&
36+
value !== "notifications-and-sound"
37+
)
38+
return;
39+
setPermissionMessage(null);
40+
if (hasNotificationSound(value)) unlockNotificationAudio();
41+
if (hasDesktopNotifications(value)) {
42+
if (typeof Notification === "undefined" || !window.isSecureContext) {
43+
setPermissionMessage(
44+
"Notifications need a supported browser over HTTPS, or the desktop app. Sound only is still available.",
45+
);
46+
return;
47+
}
48+
setRequesting(true);
49+
try {
50+
const permission = await Notification.requestPermission();
51+
if (permission !== "granted") {
52+
setPermissionMessage(
53+
"Allow notifications in your browser or system settings, then choose this option again. Sound only is still available.",
54+
);
55+
return;
56+
}
57+
} catch {
58+
setPermissionMessage(
59+
"Notifications are unavailable in this browser. Sound only is still available.",
60+
);
61+
return;
62+
} finally {
63+
setRequesting(false);
64+
}
65+
}
66+
updateSettings({ notificationMode: value });
67+
}}
68+
>
69+
<SelectTrigger size="sm" className="w-full sm:w-56" aria-label="Thread notifications">
70+
<SelectValue>{NOTIFICATION_MODE_LABELS[mode]}</SelectValue>
71+
</SelectTrigger>
72+
<SelectPopup align="end" alignItemWithTrigger={false}>
73+
{Object.entries(NOTIFICATION_MODE_LABELS).map(([value, label]) => (
74+
<SelectItem key={value} hideIndicator value={value}>
75+
{label}
76+
</SelectItem>
77+
))}
78+
</SelectPopup>
79+
</Select>
80+
}
81+
/>
82+
);
83+
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Spinner } from "~/components/ui/spinner";
2+
import { NotificationSettings } from "./NotificationSettings";
23
import { ArchiveIcon, ArchiveX, ChevronRightIcon, SettingsIcon } from "lucide-react";
34
import { Link, useNavigate } from "@tanstack/react-router";
45
import type { CSSProperties, ReactNode } from "react";
@@ -517,6 +518,9 @@ export function useSettingsRestore(onRestored?: () => void) {
517518
...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
518519
? ["Time format"]
519520
: []),
521+
...(settings.notificationMode !== DEFAULT_UNIFIED_SETTINGS.notificationMode
522+
? ["Thread notifications"]
523+
: []),
520524
...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount
521525
? ["Visible threads"]
522526
: []),
@@ -632,6 +636,7 @@ export function useSettingsRestore(onRestored?: () => void) {
632636
settings.sidebarThreadPreviewCount,
633637
settings.showSkillsInSlashMenu,
634638
settings.timestampFormat,
639+
settings.notificationMode,
635640
settings.wordWrap,
636641
followSystem,
637642
theme,
@@ -705,6 +710,7 @@ export function useSettingsRestore(onRestored?: () => void) {
705710
appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast,
706711
diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme,
707712
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
713+
notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode,
708714
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
709715
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
710716
diffLayout: DEFAULT_UNIFIED_SETTINGS.diffLayout,
@@ -2238,6 +2244,7 @@ export function GeneralSettingsPanel() {
22382244
</SettingsSection>
22392245

22402246
<SettingsSection id="behavior" title="Behavior">
2247+
<NotificationSettings />
22412248
<SettingsRow
22422249
{...searchableSetting("time-format")}
22432250
description="System default follows your browser or OS clock preference."

‎apps/web/src/components/settings/settingsSearch.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,12 @@ export const SETTINGS_SEARCH_ITEMS = [
235235
requiresThreadAutoSettlement: true,
236236
scope: "project-defaults",
237237
},
238+
{
239+
id: "thread-notifications",
240+
title: "Thread notifications",
241+
to: "/settings/general",
242+
searchTerms: ["notification sound alert completion input approval desktop"],
243+
},
238244
{
239245
id: "time-format",
240246
title: "Time format",

‎apps/web/src/routes/__root.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPrompt
2424
import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";
2525
import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
2626
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
27+
import { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";
2728
import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
2829
import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
2930
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
@@ -197,6 +198,7 @@ function RootRouteView() {
197198
<ConnectOnboardingDialog />
198199
<SshPasswordPromptDialog />
199200
<SnapShotCoordinator />
201+
<ThreadNotificationCoordinator />
200202
<ConfirmDialogHost />
201203
<SlowRpcRequestToastCoordinator />
202204
<HostedStaticEnvironmentBootstrap />
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import type { ClientSettings } from "@t3tools/contracts/settings";
2+
3+
import completionUrl from "./assets/notification-completion.mp3";
4+
import inputUrl from "./assets/notification-input.mp3";
5+
6+
type NotificationMode = ClientSettings["notificationMode"];
7+
export const NOTIFICATION_MODE_LABELS = {
8+
off: "Off",
9+
notifications: "Notifications only",
10+
sound: "Sound only",
11+
"notifications-and-sound": "Notifications with sound",
12+
} satisfies Record<NotificationMode, string>;
13+
14+
export function hasNotificationSound(mode: NotificationMode) {
15+
return mode === "sound" || mode === "notifications-and-sound";
16+
}
17+
18+
export function hasDesktopNotifications(mode: NotificationMode) {
19+
return mode === "notifications" || mode === "notifications-and-sound";
20+
}
21+
22+
let audioContext: AudioContext | undefined;
23+
const buffers = new Map<string, Promise<AudioBuffer>>();
24+
25+
/** Called from a gesture so browsers allow later background playback. */
26+
export function unlockNotificationAudio() {
27+
audioContext ??= new AudioContext();
28+
void audioContext.resume().catch(() => undefined);
29+
}
30+
31+
export async function playNotificationSound(
32+
kind: "completion" | "input",
33+
shouldPlay: () => boolean,
34+
) {
35+
if (!audioContext || audioContext.state !== "running") return;
36+
const context = audioContext;
37+
const url = kind === "completion" ? completionUrl : inputUrl;
38+
try {
39+
let buffer = buffers.get(url);
40+
if (!buffer) {
41+
buffer = fetch(url)
42+
.then((response) => response.arrayBuffer())
43+
.then((data) => context.decodeAudioData(data));
44+
buffers.set(url, buffer);
45+
}
46+
const decoded = await buffer;
47+
if (!shouldPlay() || context.state !== "running") return;
48+
const source = context.createBufferSource();
49+
source.buffer = decoded;
50+
source.connect(context.destination);
51+
source.start();
52+
} catch {
53+
buffers.delete(url);
54+
}
55+
}

‎packages/contracts/src/settings.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,32 @@ describe("ClaudeSettings auto-compaction", () => {
164164
});
165165
});
166166

167+
describe("ClientSettings notifications", () => {
168+
it("requires opt-in when existing settings omit notification preferences", () => {
169+
expect(decodeClientSettings({}).notificationMode).toBe("off");
170+
expect(decodeClientSettingsPatch({})).not.toHaveProperty("notificationMode");
171+
});
172+
173+
it.each(["off", "notifications", "sound", "notifications-and-sound"])(
174+
"round-trips the %s mode",
175+
(notificationMode) => {
176+
const settings = decodeClientSettings({ notificationMode });
177+
expect(encodeClientSettings(settings).notificationMode).toBe(notificationMode);
178+
expect(decodeClientSettingsPatch({ notificationMode }).notificationMode).toBe(
179+
notificationMode,
180+
);
181+
},
182+
);
183+
184+
it.each(["always", true, null])(
185+
"rejects unsupported notification mode %s",
186+
(notificationMode) => {
187+
expect(() => decodeClientSettings({ notificationMode })).toThrow();
188+
expect(() => decodeClientSettingsPatch({ notificationMode })).toThrow();
189+
},
190+
);
191+
});
192+
167193
describe("ClientSettings diff colors", () => {
168194
it("keeps red and green for existing settings without a saved palette", () => {
169195
expect(decodeClientSettings({}).diffColorScheme).toBe("red-green");

0 commit comments

Comments
 (0)