Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(notifications): add notification sounds with per-type choices (#9173)

Jacob Beckermanf2fe22458919
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index cbe898a1b9..a6257680bc 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -798,6 +798,7 @@ See the [download walkthrough](../../docs/agent-guide/files.md#downloading-files
- Reuse `CreateMenuItem` for explanatory New menu entries: original icons, a title, and muted wrapping descriptions, preserving the existing `ViewCreateButton` trigger and each action's feature gates.
- Keep transient toasts in their bounded stack and persistent prompts/reminders in separate regions; preserve keyboard dismissal, full mobile descriptions, and remaining-time pause on hover/focus.
+- Notification sounds are off by default and saved per user per device; map each new notification event in `features/notification-sounds/core/categories.ts` and keep system alerts silent when Macro plays its own sound. See the [notification sounds walkthrough](../../docs/agent-guide/notifications.md#notification-sounds).
### Sidebar tag dragging
diff --git a/apps/web/src/components/app/AppProviders.tsx b/apps/web/src/components/app/AppProviders.tsx
index 0c16aeae65..f73ccd6127 100644
--- a/apps/web/src/components/app/AppProviders.tsx
+++ b/apps/web/src/components/app/AppProviders.tsx
@@ -1,5 +1,9 @@
import { useAccessRequestInvalidations } from '@app/features/access-requests/use-access-request-invalidations';
import { IncomingMeetingInvitationsProvider } from '@app/features/meetings/incoming-meeting-invitations';
+import {
+ notificationSoundFor,
+ useNotificationSounds,
+} from '@app/features/notification-sounds/use-notification-sounds';
import { usePendingNotificationNavigationEffect } from '@app/features/notifications/PendingNotificationNavigationEffect';
import { SearchProvider } from '@app/features/soup/search/context';
import { useInterfaceLanguageSync } from '@app/lib/i18n/use-interface-language-sync';
@@ -48,6 +52,7 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {
useInvalidateQueriesOnReconnect();
}
+ const userId = useUserId();
let notificationUpdatePrompted = false;
async function deliverNotification(notification: UnifiedNotification) {
if (notifInterface === 'not-supported') return;
@@ -57,7 +62,8 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {
await maybeHandlePlatformNotification(
notification,
notifInterface,
- layoutManager
+ layoutManager,
+ { silent: notificationSoundFor(notification, userId()) !== null }
);
} catch (error) {
console.error('Failed to deliver platform notification', error);
@@ -77,6 +83,7 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {
() => authenticated() === true
);
useNotificationUpdates(notificationSource);
+ useNotificationSounds(notificationSource, userId);
useAccessRequestInvalidations();
useReactiveFavicon(notificationSource);
diff --git a/apps/web/src/features/notification-sounds/browser-test/fixture.tsx b/apps/web/src/features/notification-sounds/browser-test/fixture.tsx
new file mode 100644
index 0000000000..c36b40b3ed
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/browser-test/fixture.tsx
@@ -0,0 +1,77 @@
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { fireAndForget } from '@core/util/fireAndForget';
+import type { UnifiedNotification } from '@notifications/types';
+import { onMount } from 'solid-js';
+import { render } from 'solid-js/web';
+import { SettingsPage } from '../../settings/primitives';
+import { macroDarkTheme } from '../../theme/themes/macro-dark';
+import { macroLightTheme } from '../../theme/themes/macro-light';
+import { themeCssVars } from '../../theme/utils/themeCssVars';
+import { NotificationSoundSection } from '../components/NotificationSoundSection';
+import { playNotificationSound } from '../primitives/sound-player';
+import { createNotificationSoundSettings } from '../primitives/sound-settings';
+import { useNotificationSounds } from '../use-notification-sounds';
+
+const USER_ID = 'fixture-user';
+
+declare global {
+ interface Window {
+ deliverNotification: (tag: string) => void;
+ }
+}
+
+function Fixture() {
+ const sounds = createNotificationSoundSettings(USER_ID);
+ const listeners = new Set<(notification: UnifiedNotification) => void>();
+ useNotificationSounds(
+ {
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ },
+ () => USER_ID
+ );
+ window.deliverNotification = (tag) => {
+ // The hook reads only the event tag and lifecycle state.
+ const notification = {
+ id: crypto.randomUUID(),
+ state: 'unseen',
+ notification_metadata: { tag },
+ } as unknown as UnifiedNotification;
+ for (const listener of listeners) listener(notification);
+ };
+
+ onMount(() => {
+ const dark = new URLSearchParams(location.search).has('dark');
+ for (const [key, value] of Object.entries(
+ themeCssVars(dark ? macroDarkTheme : macroLightTheme)
+ ))
+ document.documentElement.style.setProperty(key, value);
+ document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
+ document.documentElement.dataset.themeLight = String(!dark);
+ });
+
+ return (
+ <main class="h-dvh bg-panel text-ink">
+ <SettingsPage title="Notifications">
+ <NotificationSoundSection
+ settings={sounds.settings()}
+ onEnabledChange={sounds.setEnabled}
+ onVolumeChange={sounds.setVolume}
+ onCategoryChange={sounds.setCategory}
+ onPreview={(sound) =>
+ fireAndForget(
+ playNotificationSound(sound, sounds.settings().volume),
+ 'notification-sounds'
+ )
+ }
+ />
+ </SettingsPage>
+ </main>
+ );
+}
+
+const root = document.getElementById('root');
+if (root) render(() => <Fixture />, root);
diff --git a/apps/web/src/features/notification-sounds/browser-test/index.html b/apps/web/src/features/notification-sounds/browser-test/index.html
new file mode 100644
index 0000000000..02a3c57338
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/browser-test/index.html
@@ -0,0 +1 @@
+<!doctype html><html lang="en" data-modality="keyboard"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><title>Notification sounds preview</title></head><body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body></html>
diff --git a/apps/web/src/features/notification-sounds/browser-test/notification-sounds.browser.e2e.ts b/apps/web/src/features/notification-sounds/browser-test/notification-sounds.browser.e2e.ts
new file mode 100644
index 0000000000..a714a70833
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/browser-test/notification-sounds.browser.e2e.ts
@@ -0,0 +1,102 @@
+import { expect, type Page, test } from '@playwright/test';
+
+declare global {
+ interface Window {
+ tonesPlayed: number;
+ }
+}
+
+/** Counts scheduled tones, so a test can tell which sound played. */
+test.beforeEach(async ({ page }) => {
+ await page.addInitScript(() => {
+ window.tonesPlayed = 0;
+ const createOscillator = AudioContext.prototype.createOscillator;
+ AudioContext.prototype.createOscillator = function (this: AudioContext) {
+ window.tonesPlayed += 1;
+ return createOscillator.call(this);
+ };
+ });
+ await page.goto('/');
+});
+
+const tonesPlayed = (page: Page) => page.evaluate(() => window.tonesPlayed);
+
+/** Switch inputs are visually hidden behind their track, so use the keyboard. */
+async function toggle(page: Page, name: string) {
+ const control = page.getByRole('switch', { name, exact: true });
+ await control.focus();
+ await control.press('Space');
+}
+
+test('sounds stay off until turned on, then reveal per-type choices', async ({
+ page,
+}) => {
+ const master = page.getByRole('switch', { name: 'Notification sounds' });
+ await expect(master).not.toBeChecked();
+ await expect(page.getByText('Thread replies')).toHaveCount(0);
+
+ await page.evaluate(() => window.deliverNotification('channel_mention'));
+ expect(await tonesPlayed(page)).toBe(0);
+
+ await toggle(page, 'Notification sounds');
+ await expect(page.getByRole('slider', { name: 'Volume' })).toBeVisible();
+ for (const label of ['Messages', 'Mentions', 'Email', 'Meetings & reminders'])
+ await expect(
+ page.getByRole('switch', { name: label, exact: true })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('switch', { name: 'Email', exact: true })
+ ).not.toBeChecked();
+ await expect(
+ page.getByRole('switch', { name: 'Mentions', exact: true })
+ ).toBeChecked();
+});
+
+test('choosing a sound previews it, persists, and plays for that type', async ({
+ page,
+}) => {
+ await toggle(page, 'Notification sounds');
+
+ await page.getByRole('button', { name: /^Mentions sound/ }).click();
+ await page.getByRole('option', { name: 'Bloom' }).click();
+ // Bloom is a four-note arpeggio.
+ await expect.poll(() => tonesPlayed(page)).toBe(4);
+
+ await page.reload();
+ await expect(
+ page.getByRole('switch', { name: 'Notification sounds' })
+ ).toBeChecked();
+ await expect(
+ page.getByRole('button', { name: /^Mentions sound/ })
+ ).toContainText('Bloom');
+
+ // A gesture lets the reloaded page start audio, as a real person would.
+ await page.getByRole('heading', { name: 'Notifications' }).click();
+ // Email is off by default. Had it played, the burst limit would have
+ // swallowed the mention's four-note sound.
+ await page.evaluate(() => {
+ window.deliverNotification('new_email');
+ window.deliverNotification('channel_mention');
+ });
+ await expect.poll(() => tonesPlayed(page)).toBe(4);
+});
+
+test('play buttons preview each type and a muted type stays quiet', async ({
+ page,
+}) => {
+ await toggle(page, 'Notification sounds');
+ await page
+ .getByRole('button', { name: 'Play Meetings & reminders sound' })
+ .click();
+ // Chime is two notes.
+ await expect.poll(() => tonesPlayed(page)).toBe(2);
+
+ await toggle(page, 'Meetings & reminders');
+ // A reply plays the one-note Pop. Had the muted reminder played, the burst
+ // limit would have swallowed the reply instead.
+ await page.evaluate(() => {
+ window.deliverNotification('calendar_event_reminder');
+ window.deliverNotification('channel_message_reply');
+ });
+ await expect.poll(() => tonesPlayed(page)).toBe(3);
+});
diff --git a/apps/web/src/features/notification-sounds/browser-test/playwright.config.ts b/apps/web/src/features/notification-sounds/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..2b2f1289a9
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/browser-test/playwright.config.ts
@@ -0,0 +1,35 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const web = fileURLToPath(new URL('../../../../', import.meta.url));
+const port = Number(process.env.NOTIFICATION_SOUNDS_BROWSER_PORT ?? 3097);
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 45_000,
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ contextOptions: { reducedMotion: 'reduce' },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ webServer: {
+ command: `bunx vite --config src/features/notification-sounds/browser-test/vite.config.ts --port ${port}`,
+ cwd: web,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: false,
+ timeout: 120_000,
+ },
+ projects: [
+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },
+ {
+ name: 'phone',
+ use: { ...devices['iPhone 13'], defaultBrowserType: 'chromium' },
+ },
+ ],
+});
diff --git a/apps/web/src/features/notification-sounds/browser-test/vite.config.ts b/apps/web/src/features/notification-sounds/browser-test/vite.config.ts
new file mode 100644
index 0000000000..c5a0746984
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/browser-test/vite.config.ts
@@ -0,0 +1,27 @@
+import { fileURLToPath } from 'node:url';
+import tailwind from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solid from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const web = fileURLToPath(new URL('../../../../', import.meta.url));
+const workspace = fileURLToPath(new URL('../../../../../../', import.meta.url));
+
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [
+ solid(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${web}/tsconfig.json`] }),
+ tailwind(),
+ ],
+ resolve: { dedupe: ['solid-js'] },
+ server: {
+ host: '127.0.0.1',
+ strictPort: true,
+ fs: { allow: [workspace] },
+ },
+});
diff --git a/apps/web/src/features/notification-sounds/components/NotificationSoundSection.tsx b/apps/web/src/features/notification-sounds/components/NotificationSoundSection.tsx
new file mode 100644
index 0000000000..0be961cec0
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/components/NotificationSoundSection.tsx
@@ -0,0 +1,132 @@
+import { SettingsSelect } from '@app/features/settings/components/settings-select';
+import {
+ SettingsCard,
+ SettingsRow,
+ SettingsSection,
+} from '@app/features/settings/primitives';
+import PlayIcon from '@icon/system/regular/play.svg';
+import { Button, Slider, ToggleSwitch } from '@ui';
+import { For, Show } from 'solid-js';
+import {
+ NOTIFICATION_SOUND_CATEGORIES,
+ type NotificationSoundCategoryId,
+} from '../core/categories';
+import type {
+ NotificationSoundCategorySettings,
+ NotificationSoundSettings,
+} from '../core/settings';
+import {
+ isNotificationSoundId,
+ NOTIFICATION_SOUNDS,
+ type NotificationSoundId,
+} from '../core/sounds';
+
+const SOUND_OPTIONS = NOTIFICATION_SOUNDS.map((sound) => ({
+ id: sound.id,
+ name: sound.label,
+}));
+
+/** Sound settings for the Notifications page. */
+export function NotificationSoundSection(props: {
+ settings: NotificationSoundSettings;
+ onEnabledChange: (enabled: boolean) => void;
+ onVolumeChange: (volume: number) => void;
+ onCategoryChange: (
+ id: NotificationSoundCategoryId,
+ change: Partial<NotificationSoundCategorySettings>
+ ) => void;
+ onPreview: (sound: NotificationSoundId) => void;
+}) {
+ const volumePercent = () => Math.round(props.settings.volume * 100);
+
+ return (
+ <SettingsSection
+ title="Sounds"
+ description="Play a sound when a notification arrives. Saved on this device."
+ >
+ <SettingsCard>
+ <SettingsRow
+ label="Notification sounds"
+ description="Off by default. Incoming calls always ring."
+ >
+ <ToggleSwitch
+ size="md"
+ label="Notification sounds"
+ labelClass="sr-only"
+ checked={props.settings.enabled}
+ onChange={props.onEnabledChange}
+ />
+ </SettingsRow>
+ <Show when={props.settings.enabled}>
+ <SettingsRow stackOnNarrow label="Volume">
+ <Slider
+ aria-label="Volume"
+ class="w-full @[460px]:w-48"
+ value={[volumePercent()]}
+ minValue={0}
+ maxValue={100}
+ step={5}
+ onChange={([percent]) => props.onVolumeChange(percent / 100)}
+ onChangeEnd={() =>
+ props.onPreview(props.settings.categories.mentions.sound)
+ }
+ >
+ <Slider.Track>
+ <Slider.Fill />
+ <Slider.Thumb aria-valuetext={`${volumePercent()}%`}>
+ <Slider.Input aria-label="Volume" />
+ </Slider.Thumb>
+ </Slider.Track>
+ </Slider>
+ <span class="w-10 shrink-0 text-right text-sm tabular-nums text-ink-muted">
+ {volumePercent()}%
+ </span>
+ </SettingsRow>
+ <For each={NOTIFICATION_SOUND_CATEGORIES}>
+ {(category) => {
+ const current = () => props.settings.categories[category.id];
+ return (
+ <SettingsRow
+ stackOnNarrow
+ label={category.label}
+ description={category.description}
+ muted={!current().enabled}
+ >
+ <SettingsSelect
+ label={`${category.label} sound`}
+ class="min-w-0 w-32"
+ options={SOUND_OPTIONS}
+ value={current().sound}
+ onChange={(sound) => {
+ if (!isNotificationSoundId(sound)) return;
+ props.onCategoryChange(category.id, { sound });
+ props.onPreview(sound);
+ }}
+ />
+ <Button
+ variant="ghost"
+ size="icon-md"
+ aria-label={`Play ${category.label} sound`}
+ tooltip="Play"
+ onClick={() => props.onPreview(current().sound)}
+ >
+ <PlayIcon class="size-4" />
+ </Button>
+ <ToggleSwitch
+ size="md"
+ label={category.label}
+ labelClass="sr-only"
+ checked={current().enabled}
+ onChange={(enabled) =>
+ props.onCategoryChange(category.id, { enabled })
+ }
+ />
+ </SettingsRow>
+ );
+ }}
+ </For>
+ </Show>
+ </SettingsCard>
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/features/notification-sounds/core/categories.ts b/apps/web/src/features/notification-sounds/core/categories.ts
new file mode 100644
index 0000000000..af2a787a1a
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/core/categories.ts
@@ -0,0 +1,145 @@
+import type { NotifEvent } from '@service-notification/generated/schemas';
+import type { NotificationSoundId } from './sounds';
+
+export type NotificationSoundCategoryId =
+ | 'messages'
+ | 'mentions'
+ | 'replies'
+ | 'email'
+ | 'meetings'
+ | 'tasks'
+ | 'agents'
+ | 'other';
+
+export type NotificationSoundCategory = {
+ id: NotificationSoundCategoryId;
+ label: string;
+ description: string;
+ defaultEnabled: boolean;
+ defaultSound: NotificationSoundId;
+};
+
+/** Settings rows, in display order. */
+export const NOTIFICATION_SOUND_CATEGORIES: readonly NotificationSoundCategory[] =
+ [
+ {
+ id: 'messages',
+ label: 'Messages',
+ description: 'New messages in channels and direct messages',
+ defaultEnabled: true,
+ defaultSound: 'knock',
+ },
+ {
+ id: 'mentions',
+ label: 'Mentions',
+ description: 'When someone mentions you anywhere',
+ defaultEnabled: true,
+ defaultSound: 'ding',
+ },
+ {
+ id: 'replies',
+ label: 'Thread replies',
+ description: 'Replies in threads and comment threads you are part of',
+ defaultEnabled: true,
+ defaultSound: 'pop',
+ },
+ {
+ id: 'email',
+ label: 'Email',
+ description: 'When a new email arrives',
+ defaultEnabled: false,
+ defaultSound: 'pluck',
+ },
+ {
+ id: 'meetings',
+ label: 'Meetings & reminders',
+ description: 'Event reminders, requests to join, and your reminders',
+ defaultEnabled: true,
+ defaultSound: 'chime',
+ },
+ {
+ id: 'tasks',
+ label: 'Tasks',
+ description: 'When a task is assigned to you',
+ defaultEnabled: true,
+ defaultSound: 'bloom',
+ },
+ {
+ id: 'agents',
+ label: 'AI & agents',
+ description: 'AI replies, and agents that finish or need an answer',
+ defaultEnabled: false,
+ defaultSound: 'ping',
+ },
+ {
+ id: 'other',
+ label: 'Everything else',
+ description: 'Comments, reactions, sharing, GitHub, and invites',
+ defaultEnabled: false,
+ defaultSound: 'pop',
+ },
+ ];
+
+/**
+ * The sound category for each notification event. `null` events never make a
+ * sound: incoming calls ring on their own, and document mentions are not
+ * delivered as alerts.
+ */
+const CATEGORY_BY_EVENT: Record<
+ NotifEvent['tag'],
+ NotificationSoundCategoryId | null
+> = {
+ channel_message_send: 'messages',
+ external_chat_message: 'messages',
+ channel_mention: 'mentions',
+ mentioned_in_document_comment: 'mentions',
+ agent_session_mentioned: 'mentions',
+ github_pr_mention: 'mentions',
+ channel_message_reply: 'replies',
+ replied_to_document_comment_thread: 'replies',
+ new_email: 'email',
+ calendar_event_reminder: 'meetings',
+ calendar_event_join_request: 'meetings',
+ reminder: 'meetings',
+ task_assigned: 'tasks',
+ ai_response: 'agents',
+ agent_session_settled: 'agents',
+ agent_session_waiting_for_input: 'agents',
+ commented_on_document: 'other',
+ channel_message_reaction: 'other',
+ channel_invite: 'other',
+ initiative_discussion: 'other',
+ crm_discussion: 'other',
+ entity_access_requested: 'other',
+ entity_access_granted: 'other',
+ invite_to_team: 'other',
+ inbox_reauth_required: 'other',
+ github_pr_status_changed: 'other',
+ github_pr_check_run: 'other',
+ github_review_requested: 'other',
+ github_pr_comment: 'other',
+ github_pr_review: 'other',
+ call_started: null,
+ document_mention: null,
+};
+
+function isMappedEvent(tag: string): tag is NotifEvent['tag'] {
+ return Object.hasOwn(CATEGORY_BY_EVENT, tag);
+}
+
+/** Events a newer backend adds have no category until mapped here. */
+export function soundCategoryForEvent(
+ tag: string
+): NotificationSoundCategoryId | null {
+ return isMappedEvent(tag) ? CATEGORY_BY_EVENT[tag] : null;
+}
+
+export function notificationSoundCategory(
+ id: NotificationSoundCategoryId
+): NotificationSoundCategory {
+ const category = NOTIFICATION_SOUND_CATEGORIES.find(
+ (candidate) => candidate.id === id
+ );
+ if (!category) throw new Error(`Unknown notification sound category: ${id}`);
+ return category;
+}
diff --git a/apps/web/src/features/notification-sounds/core/settings.test.ts b/apps/web/src/features/notification-sounds/core/settings.test.ts
new file mode 100644
index 0000000000..777960b502
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/core/settings.test.ts
@@ -0,0 +1,79 @@
+import { expect, it } from 'vitest';
+import {
+ DEFAULT_NOTIFICATION_SOUND_SETTINGS,
+ parseNotificationSoundSettings,
+ soundForNotification,
+} from './settings';
+
+it('keeps sounds off until they are turned on', () => {
+ expect(parseNotificationSoundSettings(null).enabled).toBe(false);
+ expect(
+ soundForNotification('channel_mention', DEFAULT_NOTIFICATION_SOUND_SETTINGS)
+ ).toBeNull();
+});
+
+it('falls back to defaults for unreadable storage', () => {
+ expect(parseNotificationSoundSettings('{not json')).toEqual(
+ DEFAULT_NOTIFICATION_SOUND_SETTINGS
+ );
+ expect(parseNotificationSoundSettings('{"volume":4}')).toEqual(
+ DEFAULT_NOTIFICATION_SOUND_SETTINGS
+ );
+});
+
+it('keeps valid saved choices and defaults unknown sounds and categories', () => {
+ const settings = parseNotificationSoundSettings(
+ JSON.stringify({
+ enabled: true,
+ volume: 0.4,
+ categories: {
+ email: { enabled: true, sound: 'chime' },
+ mentions: { enabled: false, sound: 'removed-sound' },
+ retired_category: { enabled: true, sound: 'ding' },
+ },
+ })
+ );
+
+ expect(settings.enabled).toBe(true);
+ expect(settings.volume).toBe(0.4);
+ expect(settings.categories.email).toEqual({ enabled: true, sound: 'chime' });
+ expect(settings.categories.mentions).toEqual({
+ enabled: false,
+ sound: DEFAULT_NOTIFICATION_SOUND_SETTINGS.categories.mentions.sound,
+ });
+ expect(settings.categories.messages).toEqual(
+ DEFAULT_NOTIFICATION_SOUND_SETTINGS.categories.messages
+ );
+});
+
+it('plays the sound chosen for the notification category', () => {
+ const settings = parseNotificationSoundSettings(
+ JSON.stringify({
+ enabled: true,
+ categories: {
+ mentions: { enabled: true, sound: 'bloom' },
+ email: { enabled: false, sound: 'chime' },
+ },
+ })
+ );
+
+ expect(soundForNotification('channel_mention', settings)).toBe('bloom');
+ expect(soundForNotification('mentioned_in_document_comment', settings)).toBe(
+ 'bloom'
+ );
+ expect(soundForNotification('new_email', settings)).toBeNull();
+});
+
+it('stays quiet for calls, muted volume, and unknown events', () => {
+ const settings = parseNotificationSoundSettings(
+ JSON.stringify({ enabled: true })
+ );
+
+ expect(soundForNotification('call_started', settings)).toBeNull();
+ expect(soundForNotification('event_from_a_newer_backend', settings)).toBe(
+ null
+ );
+ expect(
+ soundForNotification('channel_mention', { ...settings, volume: 0 })
+ ).toBeNull();
+});
diff --git a/apps/web/src/features/notification-sounds/core/settings.ts b/apps/web/src/features/notification-sounds/core/settings.ts
new file mode 100644
index 0000000000..3da3e906b8
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/core/settings.ts
@@ -0,0 +1,113 @@
+import { z } from 'zod';
+import {
+ type NotificationSoundCategoryId,
+ notificationSoundCategory,
+ soundCategoryForEvent,
+} from './categories';
+import { isNotificationSoundId, type NotificationSoundId } from './sounds';
+
+export type NotificationSoundCategorySettings = {
+ enabled: boolean;
+ sound: NotificationSoundId;
+};
+
+export type NotificationSoundSettings = {
+ /** Master switch; sounds are off until the person turns them on. */
+ enabled: boolean;
+ /** 0 to 1. */
+ volume: number;
+ categories: Record<
+ NotificationSoundCategoryId,
+ NotificationSoundCategorySettings
+ >;
+};
+
+function categorySettings(
+ settingsFor: (
+ id: NotificationSoundCategoryId
+ ) => NotificationSoundCategorySettings
+): NotificationSoundSettings['categories'] {
+ return {
+ messages: settingsFor('messages'),
+ mentions: settingsFor('mentions'),
+ replies: settingsFor('replies'),
+ email: settingsFor('email'),
+ meetings: settingsFor('meetings'),
+ tasks: settingsFor('tasks'),
+ agents: settingsFor('agents'),
+ other: settingsFor('other'),
+ };
+}
+
+/** Notifications arriving closer together than this share one sound. */
+export const NOTIFICATION_SOUND_MIN_GAP_MS = 1_500;
+
+export const DEFAULT_NOTIFICATION_SOUND_SETTINGS: NotificationSoundSettings = {
+ enabled: false,
+ volume: 0.7,
+ categories: categorySettings((id) => {
+ const category = notificationSoundCategory(id);
+ return { enabled: category.defaultEnabled, sound: category.defaultSound };
+ }),
+};
+
+const storedSettingsSchema = z.object({
+ enabled: z.boolean().optional(),
+ volume: z.number().min(0).max(1).optional(),
+ categories: z
+ .record(
+ z.string(),
+ z.object({ enabled: z.boolean().optional(), sound: z.unknown() })
+ )
+ .optional(),
+});
+
+/**
+ * Reads saved settings, keeping each valid field and defaulting the rest, so
+ * a category or sound added or removed later never discards the others.
+ */
+export function parseNotificationSoundSettings(
+ raw: string | null
+): NotificationSoundSettings {
+ if (!raw) return DEFAULT_NOTIFICATION_SOUND_SETTINGS;
+ let json: unknown;
+ try {
+ json = JSON.parse(raw);
+ } catch {
+ return DEFAULT_NOTIFICATION_SOUND_SETTINGS;
+ }
+ const parsed = storedSettingsSchema.safeParse(json);
+ if (!parsed.success) return DEFAULT_NOTIFICATION_SOUND_SETTINGS;
+
+ const defaults = DEFAULT_NOTIFICATION_SOUND_SETTINGS;
+ const stored = parsed.data;
+ return {
+ enabled: stored.enabled ?? defaults.enabled,
+ volume: stored.volume ?? defaults.volume,
+ categories: categorySettings((id) => {
+ const saved = stored.categories?.[id];
+ const sound = saved?.sound;
+ return {
+ enabled: saved?.enabled ?? defaults.categories[id].enabled,
+ sound: isNotificationSoundId(sound)
+ ? sound
+ : defaults.categories[id].sound,
+ };
+ }),
+ };
+}
+
+/**
+ * The sound a notification should make, or null when it should stay quiet:
+ * sounds are off, its category is off, or it is not a sound-making event.
+ */
+export function soundForNotification(
+ eventTag: string,
+ settings: NotificationSoundSettings
+): NotificationSoundId | null {
+ if (!settings.enabled || settings.volume === 0) return null;
+ const categoryId = soundCategoryForEvent(eventTag);
+ if (!categoryId) return null;
+ const category = settings.categories[categoryId];
+ return category.enabled ? category.sound : null;
+}
diff --git a/apps/web/src/features/notification-sounds/core/sounds.ts b/apps/web/src/features/notification-sounds/core/sounds.ts
new file mode 100644
index 0000000000..c7756eac41
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/core/sounds.ts
@@ -0,0 +1,130 @@
+/**
+ * Notification sounds, synthesized with Web Audio so the app ships no audio
+ * files. Each sound is a short list of tones scheduled from its start.
+ */
+
+export type NotificationSoundId =
+ | 'ding'
+ | 'chime'
+ | 'pop'
+ | 'knock'
+ | 'pluck'
+ | 'ping'
+ | 'bloom';
+
+export type NotificationTone = {
+ /** Start frequency in Hz. */
+ frequency: number;
+ /** Frequency the tone glides to by its end, for swept sounds. */
+ glideTo?: number;
+ /** Offset from the sound's start, in seconds. */
+ start: number;
+ /** Time until the tone has decayed to silence, in seconds. */
+ duration: number;
+ /** Relative loudness, 0 to 1, before the volume setting applies. */
+ gain: number;
+ wave: OscillatorType;
+};
+
+export type NotificationSound = {
+ id: NotificationSoundId;
+ label: string;
+ tones: readonly NotificationTone[];
+};
+
+export const NOTIFICATION_SOUNDS: readonly NotificationSound[] = [
+ {
+ id: 'ding',
+ label: 'Ding',
+ tones: [
+ { frequency: 1318.5, start: 0, duration: 0.9, gain: 1, wave: 'sine' },
+ { frequency: 2637, start: 0, duration: 0.35, gain: 0.25, wave: 'sine' },
+ ],
+ },
+ {
+ id: 'chime',
+ label: 'Chime',
+ tones: [
+ { frequency: 880, start: 0, duration: 0.45, gain: 0.9, wave: 'sine' },
+ {
+ frequency: 1318.5,
+ start: 0.12,
+ duration: 0.7,
+ gain: 0.9,
+ wave: 'sine',
+ },
+ ],
+ },
+ {
+ id: 'pop',
+ label: 'Pop',
+ tones: [
+ {
+ frequency: 480,
+ glideTo: 1150,
+ start: 0,
+ duration: 0.09,
+ gain: 1,
+ wave: 'sine',
+ },
+ ],
+ },
+ {
+ id: 'knock',
+ label: 'Knock',
+ tones: [
+ { frequency: 196, start: 0, duration: 0.09, gain: 1, wave: 'triangle' },
+ {
+ frequency: 174.6,
+ start: 0.13,
+ duration: 0.09,
+ gain: 0.85,
+ wave: 'triangle',
+ },
+ ],
+ },
+ {
+ id: 'pluck',
+ label: 'Pluck',
+ tones: [
+ { frequency: 659.3, start: 0, duration: 0.25, gain: 1, wave: 'triangle' },
+ {
+ frequency: 987.8,
+ start: 0.07,
+ duration: 0.3,
+ gain: 0.7,
+ wave: 'triangle',
+ },
+ ],
+ },
+ {
+ id: 'ping',
+ label: 'Ping',
+ tones: [
+ { frequency: 1760, start: 0, duration: 0.35, gain: 0.75, wave: 'sine' },
+ ],
+ },
+ {
+ id: 'bloom',
+ label: 'Bloom',
+ tones: [523.25, 659.25, 783.99, 1046.5].map((frequency, index) => ({
+ frequency,
+ start: index * 0.06,
+ duration: 0.4,
+ gain: 0.7,
+ wave: 'sine' as const,
+ })),
+ },
+];
+
+export function isNotificationSoundId(
+ value: unknown
+): value is NotificationSoundId {
+ return NOTIFICATION_SOUNDS.some((sound) => sound.id === value);
+}
+
+export function notificationSound(id: NotificationSoundId): NotificationSound {
+ const sound = NOTIFICATION_SOUNDS.find((candidate) => candidate.id === id);
+ if (!sound) throw new Error(`Unknown notification sound: ${id}`);
+ return sound;
+}
diff --git a/apps/web/src/features/notification-sounds/primitives/sound-player.ts b/apps/web/src/features/notification-sounds/primitives/sound-player.ts
new file mode 100644
index 0000000000..c780c3d123
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/primitives/sound-player.ts
@@ -0,0 +1,75 @@
+import { type NotificationSoundId, notificationSound } from '../core/sounds';
+
+/** Loudest a tone gets at full volume; notification sounds stay gentle. */
+const MAX_GAIN = 0.3;
+const ATTACK_S = 0.005;
+/** Lead time so the first tone is never scheduled in the past. */
+const START_DELAY_S = 0.01;
+
+let sharedContext: AudioContext | undefined;
+
+function audioContext(): AudioContext | undefined {
+ if (sharedContext) return sharedContext;
+ if (typeof AudioContext === 'undefined') return undefined;
+ try {
+ sharedContext = new AudioContext();
+ } catch (error) {
+ console.warn(
+ 'Could not create an AudioContext for notification sounds',
+ error
+ );
+ return undefined;
+ }
+ return sharedContext;
+}
+
+/**
+ * Resumes audio from inside a user gesture. iOS only lets a page start audio
+ * during one, so a sound arriving later can play.
+ */
+export async function unlockNotificationSounds(): Promise<void> {
+ const context = audioContext();
+ if (context?.state === 'suspended') await context.resume();
+}
+
+/**
+ * Plays a notification sound at `volume` (0 to 1). Browsers keep audio
+ * suspended until the page has had a user gesture; a sound arriving before
+ * any interaction stays silent instead of playing late once audio resumes.
+ */
+export async function playNotificationSound(
+ id: NotificationSoundId,
+ volume: number
+): Promise<void> {
+ const context = audioContext();
+ if (!context || volume <= 0) return;
+ if (context.state === 'suspended') {
+ if (navigator.userActivation?.hasBeenActive === false) return;
+ await context.resume();
+ }
+ if (context.state !== 'running') return;
+
+ const start = context.currentTime + START_DELAY_S;
+ for (const tone of notificationSound(id).tones) {
+ const toneStart = start + tone.start;
+ const toneEnd = toneStart + tone.duration;
+ const peak = MAX_GAIN * volume * tone.gain;
+
+ const gain = context.createGain();
+ gain.connect(context.destination);
+ gain.gain.setValueAtTime(0, toneStart);
+ gain.gain.linearRampToValueAtTime(peak, toneStart + ATTACK_S);
+ gain.gain.exponentialRampToValueAtTime(0.0001, toneEnd);
+
+ const oscillator = context.createOscillator();
+ oscillator.type = tone.wave;
+ oscillator.frequency.setValueAtTime(tone.frequency, toneStart);
+ if (tone.glideTo) {
+ oscillator.frequency.exponentialRampToValueAtTime(tone.glideTo, toneEnd);
+ }
+ oscillator.connect(gain);
+ oscillator.onended = () => gain.disconnect();
+ oscillator.start(toneStart);
+ oscillator.stop(toneEnd);
+ }
+}
diff --git a/apps/web/src/features/notification-sounds/primitives/sound-settings.ts b/apps/web/src/features/notification-sounds/primitives/sound-settings.ts
new file mode 100644
index 0000000000..55f9fed81b
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/primitives/sound-settings.ts
@@ -0,0 +1,57 @@
+import { makePersistedState } from '@app/lib/persistence';
+import { createUserScopedStorage } from '@core/util/userScopedStorage';
+import { createSignal } from 'solid-js';
+import type { NotificationSoundCategoryId } from '../core/categories';
+import {
+ DEFAULT_NOTIFICATION_SOUND_SETTINGS,
+ type NotificationSoundCategorySettings,
+ type NotificationSoundSettings,
+ parseNotificationSoundSettings,
+} from '../core/settings';
+
+/** Per person and per device: each computer or phone chooses its own sounds. */
+const STORAGE = createUserScopedStorage('macro:notification-sounds');
+
+/**
+ * The saved settings, read fresh so a change made in another tab applies to
+ * the next notification here.
+ */
+export function readNotificationSoundSettings(
+ userId: string
+): NotificationSoundSettings {
+ return parseNotificationSoundSettings(STORAGE.read(userId));
+}
+
+/** Editable sound settings for the settings page. */
+export function createNotificationSoundSettings(userId: string) {
+ const [settings, setSettings] = makePersistedState(
+ createSignal<NotificationSoundSettings>(
+ DEFAULT_NOTIFICATION_SOUND_SETTINGS
+ ),
+ {
+ storages: {
+ restore: () => readNotificationSoundSettings(userId),
+ write: (value) => STORAGE.write(userId, JSON.stringify(value)),
+ },
+ }
+ );
+
+ return {
+ settings,
+ setEnabled: (enabled: boolean) =>
+ setSettings((current) => ({ ...current, enabled })),
+ setVolume: (volume: number) =>
+ setSettings((current) => ({ ...current, volume })),
+ setCategory: (
+ id: NotificationSoundCategoryId,
+ change: Partial<NotificationSoundCategorySettings>
+ ) =>
+ setSettings((current) => ({
+ ...current,
+ categories: {
+ ...current.categories,
+ [id]: { ...current.categories[id], ...change },
+ },
+ })),
+ };
+}
diff --git a/apps/web/src/features/notification-sounds/primitives/sound-tab.ts b/apps/web/src/features/notification-sounds/primitives/sound-tab.ts
new file mode 100644
index 0000000000..ea4d2026d9
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/primitives/sound-tab.ts
@@ -0,0 +1,39 @@
+/**
+ * Picks one tab to play notification sounds, so a notification open in
+ * several tabs dings once. The tab the person last focused or touched plays:
+ * it is the one they are using, and its recent gesture lets it start audio.
+ */
+
+const SOUND_TAB_KEY = 'macro:notification-sounds:tab';
+const TAB_ID = crypto.randomUUID();
+
+export function claimNotificationSoundTab(): void {
+ try {
+ localStorage.setItem(SOUND_TAB_KEY, TAB_ID);
+ } catch {
+ // Without storage every tab plays, as before any tab claims.
+ }
+}
+
+export function isNotificationSoundTab(): boolean {
+ try {
+ const owner = localStorage.getItem(SOUND_TAB_KEY);
+ return owner === null || owner === TAB_ID;
+ } catch {
+ return true;
+ }
+}
+
+/**
+ * Hands sound back to the other tabs when this one closes, so they don't stay
+ * silent until one of them is focused.
+ */
+export function releaseNotificationSoundTab(): void {
+ try {
+ if (localStorage.getItem(SOUND_TAB_KEY) === TAB_ID) {
+ localStorage.removeItem(SOUND_TAB_KEY);
+ }
+ } catch {
+ // Without storage every tab plays already.
+ }
+}
diff --git a/apps/web/src/features/notification-sounds/use-notification-sounds.test.ts b/apps/web/src/features/notification-sounds/use-notification-sounds.test.ts
new file mode 100644
index 0000000000..887fc1111b
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/use-notification-sounds.test.ts
@@ -0,0 +1,131 @@
+import type { UnifiedNotification } from '@notifications/types';
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { playNotificationSound } from './primitives/sound-player';
+import { useNotificationSounds } from './use-notification-sounds';
+
+vi.mock('./primitives/sound-player', () => ({
+ playNotificationSound: vi.fn().mockResolvedValue(undefined),
+ unlockNotificationSounds: vi.fn().mockResolvedValue(undefined),
+}));
+
+const USER_ID = 'user-1';
+const SETTINGS_KEY = `macro:notification-sounds:${USER_ID}`;
+const TAB_KEY = 'macro:notification-sounds:tab';
+
+function notification(
+ tag: 'channel_mention' | 'new_email',
+ state: UnifiedNotification['state'] = 'unseen'
+): UnifiedNotification {
+ return {
+ id: crypto.randomUUID(),
+ entity_id: 'entity-1',
+ entity_type: 'channel',
+ created_at: '2026-10-29T12:00:00Z',
+ updated_at: '2026-10-29T12:00:00Z',
+ state,
+ sent: true,
+ notification_event_type: tag,
+ notification_metadata: { tag, content: {} },
+ } as unknown as UnifiedNotification;
+}
+
+function mountSounds() {
+ let deliver: (notification: UnifiedNotification) => void = () => {};
+ const dispose = createRoot((dispose) => {
+ useNotificationSounds(
+ {
+ subscribe: (handler) => {
+ deliver = handler;
+ return () => {};
+ },
+ },
+ () => USER_ID
+ );
+ return dispose;
+ });
+ return { deliver: (n: UnifiedNotification) => deliver(n), dispose };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ localStorage.clear();
+ vi.mocked(playNotificationSound).mockClear();
+});
+
+afterEach(() => vi.useRealTimers());
+
+it('stays silent until sounds are turned on', () => {
+ const { deliver, dispose } = mountSounds();
+ deliver(notification('channel_mention'));
+ expect(playNotificationSound).not.toHaveBeenCalled();
+ dispose();
+});
+
+it('plays the chosen sound once for a burst of notifications', () => {
+ localStorage.setItem(
+ SETTINGS_KEY,
+ JSON.stringify({
+ enabled: true,
+ volume: 0.5,
+ categories: { mentions: { enabled: true, sound: 'chime' } },
+ })
+ );
+ const { deliver, dispose } = mountSounds();
+
+ deliver(notification('channel_mention'));
+ deliver(notification('channel_mention'));
+ expect(playNotificationSound).toHaveBeenCalledTimes(1);
+ expect(playNotificationSound).toHaveBeenCalledWith('chime', 0.5);
+
+ vi.advanceTimersByTime(2_000);
+ deliver(notification('channel_mention'));
+ expect(playNotificationSound).toHaveBeenCalledTimes(2);
+ dispose();
+});
+
+it('skips read notifications, muted categories, and tabs not in use', () => {
+ localStorage.setItem(SETTINGS_KEY, JSON.stringify({ enabled: true }));
+ const { deliver, dispose } = mountSounds();
+
+ deliver(notification('channel_mention', 'seen'));
+ deliver(notification('new_email'));
+ localStorage.setItem(TAB_KEY, 'another-tab');
+ deliver(notification('channel_mention'));
+ expect(playNotificationSound).not.toHaveBeenCalled();
+
+ window.dispatchEvent(new Event('focus'));
+ deliver(notification('channel_mention'));
+ expect(playNotificationSound).toHaveBeenCalledTimes(1);
+ dispose();
+});
+
+it('hands sound to the other tabs when the playing tab closes', () => {
+ const { dispose } = mountSounds();
+ window.dispatchEvent(new Event('focus'));
+ expect(localStorage.getItem(TAB_KEY)).not.toBeNull();
+
+ window.dispatchEvent(new Event('pagehide'));
+ expect(localStorage.getItem(TAB_KEY)).toBeNull();
+ dispose();
+});
+
+it('leaves another tab playing when a background tab closes', () => {
+ const { dispose } = mountSounds();
+ localStorage.setItem(TAB_KEY, 'another-tab');
+
+ window.dispatchEvent(new Event('pagehide'));
+ expect(localStorage.getItem(TAB_KEY)).toBe('another-tab');
+ dispose();
+});
+
+it('reclaims sound when a focused page returns from the back/forward cache', () => {
+ const { dispose } = mountSounds();
+ vi.spyOn(document, 'hasFocus').mockReturnValue(true);
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ expect(localStorage.getItem(TAB_KEY)).not.toBeNull();
+ vi.mocked(document.hasFocus).mockRestore();
+ dispose();
+});
diff --git a/apps/web/src/features/notification-sounds/use-notification-sounds.ts b/apps/web/src/features/notification-sounds/use-notification-sounds.ts
new file mode 100644
index 0000000000..c6c37fe9c9
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/use-notification-sounds.ts
@@ -0,0 +1,83 @@
+import { fireAndForget } from '@core/util/fireAndForget';
+import type { NotificationSource } from '@notifications/notification-source';
+import type { UnifiedNotification } from '@notifications/types';
+import { makeEventListener } from '@solid-primitives/event-listener';
+import { type Accessor, onCleanup } from 'solid-js';
+import {
+ NOTIFICATION_SOUND_MIN_GAP_MS,
+ soundForNotification,
+} from './core/settings';
+import type { NotificationSoundId } from './core/sounds';
+import {
+ playNotificationSound,
+ unlockNotificationSounds,
+} from './primitives/sound-player';
+import { readNotificationSoundSettings } from './primitives/sound-settings';
+import {
+ claimNotificationSoundTab,
+ isNotificationSoundTab,
+ releaseNotificationSoundTab,
+} from './primitives/sound-tab';
+
+/**
+ * The sound Macro plays for an incoming notification, if any. System alerts
+ * for it stay silent so the person hears one sound, not two.
+ */
+export function notificationSoundFor(
+ notification: Pick<UnifiedNotification, 'state' | 'notification_metadata'>,
+ userId: string | undefined
+): { id: NotificationSoundId; volume: number } | null {
+ if (!userId || notification.state !== 'unseen') return null;
+ const settings = readNotificationSoundSettings(userId);
+ const id = soundForNotification(
+ notification.notification_metadata.tag,
+ settings
+ );
+ return id ? { id, volume: settings.volume } : null;
+}
+
+/** Plays the chosen sound for each incoming notification, when turned on. */
+export function useNotificationSounds(
+ notificationSource: Pick<NotificationSource, 'subscribe'>,
+ userId: Accessor<string | undefined>
+) {
+ let lastPlayedAt = Number.NEGATIVE_INFINITY;
+
+ const soundsEnabled = () => {
+ const id = userId();
+ return !!id && readNotificationSoundSettings(id).enabled;
+ };
+
+ if (document.hasFocus()) claimNotificationSoundTab();
+ makeEventListener(window, 'focus', claimNotificationSoundTab);
+ makeEventListener(window, 'pagehide', releaseNotificationSoundTab);
+ // A page restored from the back/forward cache released its claim on hide.
+ makeEventListener(window, 'pageshow', (event) => {
+ if (event.persisted && document.hasFocus()) claimNotificationSoundTab();
+ });
+ makeEventListener(
+ window,
+ 'pointerdown',
+ () => {
+ claimNotificationSoundTab();
+ if (soundsEnabled()) {
+ fireAndForget(unlockNotificationSounds(), 'notification-sounds');
+ }
+ },
+ { capture: true, passive: true }
+ );
+
+ const unsubscribe = notificationSource.subscribe((notification) => {
+ if (!isNotificationSoundTab()) return;
+ const sound = notificationSoundFor(notification, userId());
+ if (!sound) return;
+ const now = Date.now();
+ if (now - lastPlayedAt < NOTIFICATION_SOUND_MIN_GAP_MS) return;
+ lastPlayedAt = now;
+ fireAndForget(
+ playNotificationSound(sound.id, sound.volume),
+ 'notification-sounds'
+ );
+ });
+ onCleanup(unsubscribe);
+}
diff --git a/apps/web/src/features/notification-sounds/views/NotificationSoundSettingsView.tsx b/apps/web/src/features/notification-sounds/views/NotificationSoundSettingsView.tsx
new file mode 100644
index 0000000000..7358d3ddd9
--- /dev/null
+++ b/apps/web/src/features/notification-sounds/views/NotificationSoundSettingsView.tsx
@@ -0,0 +1,32 @@
+import { useUserId } from '@core/context/user';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Show } from 'solid-js';
+import { NotificationSoundSection } from '../components/NotificationSoundSection';
+import { playNotificationSound } from '../primitives/sound-player';
+import { createNotificationSoundSettings } from '../primitives/sound-settings';
+
+/** The Sounds section of the Notifications settings page. */
+export function NotificationSoundSettingsView() {
+ const userId = useUserId();
+ return (
+ <Show when={userId()} keyed>
+ {(id) => {
+ const sounds = createNotificationSoundSettings(id);
+ return (
+ <NotificationSoundSection
+ settings={sounds.settings()}
+ onEnabledChange={sounds.setEnabled}
+ onVolumeChange={sounds.setVolume}
+ onCategoryChange={sounds.setCategory}
+ onPreview={(sound) =>
+ fireAndForget(
+ playNotificationSound(sound, sounds.settings().volume),
+ 'notification-sounds'
+ )
+ }
+ />
+ );
+ }}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/notifications/notification-platform.ts b/apps/web/src/features/notifications/notification-platform.ts
index 7a4622f9fb..edaa3d6aac 100644
--- a/apps/web/src/features/notifications/notification-platform.ts
+++ b/apps/web/src/features/notifications/notification-platform.ts
@@ -157,7 +157,8 @@ export async function toPlatformNotificationData(
export async function maybeHandlePlatformNotification(
notification: UnifiedNotification,
notificationInterface: PlatformNotificationState,
- splitLayoutManager: SplitManager
+ splitLayoutManager: SplitManager,
+ delivery: { silent?: boolean } = {}
) {
// Ignore notification types that should not show as browser notifications.
// GitHub PR notifications should remain visible in-app, but should not
@@ -181,6 +182,7 @@ export async function maybeHandlePlatformNotification(
if (platformNotificationData) {
let notificationHandle = await notificationInterface.showNotification({
...platformNotificationData,
+ options: { ...platformNotificationData.options, silent: delivery.silent },
notificationId: notification.id,
});
if (
diff --git a/apps/web/src/features/notifications/tests/notification-platform.test.ts b/apps/web/src/features/notifications/tests/notification-platform.test.ts
index 9f456c3187..a8202be7bf 100644
--- a/apps/web/src/features/notifications/tests/notification-platform.test.ts
+++ b/apps/web/src/features/notifications/tests/notification-platform.test.ts
@@ -250,6 +250,26 @@ describe('maybeHandlePlatformNotification', () => {
expect(handle.onClick).toHaveBeenCalledOnce();
});
+ it('silences the system alert when Macro plays its own sound', async () => {
+ const showNotification = vi.fn<
+ PlatformNotificationState['showNotification']
+ >(async () => createNotificationHandle());
+ const notificationInterface = createNotificationInterface(showNotification);
+
+ await maybeHandlePlatformNotification(
+ createChannelInviteNotification(),
+ notificationInterface,
+ {} as SplitManager,
+ { silent: true }
+ );
+
+ expect(showNotification).toHaveBeenCalledWith(
+ expect.objectContaining({
+ options: expect.objectContaining({ silent: true }),
+ })
+ );
+ });
+
it('opens the original notification target only when its platform handle is clicked', async () => {
const focus = vi.spyOn(window, 'focus').mockImplementation(() => {});
vi.mocked(openNotification).mockClear();
diff --git a/apps/web/src/features/settings/Notifications.tsx b/apps/web/src/features/settings/Notifications.tsx
index 71b66373c9..338a76045a 100644
--- a/apps/web/src/features/settings/Notifications.tsx
+++ b/apps/web/src/features/settings/Notifications.tsx
@@ -1,3 +1,4 @@
+import { NotificationSoundSettingsView } from '@app/features/notification-sounds/views/NotificationSoundSettingsView';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { toast } from '@core/component/Toast/Toast';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
@@ -156,6 +157,8 @@ export function Notifications() {
</SettingsCard>
</SettingsSection>
+ <NotificationSoundSettingsView />
+
<For each={NOTIFICATION_EVENT_GROUPS}>
{(group) => (
<SettingsSection title={group.label}>
diff --git a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
index 71516adb9d..8970757e47 100644
--- a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx
@@ -25,6 +25,10 @@ vi.mock(
vi.mock('@app/features/soup/search/context', () => ({
SearchProvider: (props: { children: unknown }) => props.children,
}));
+vi.mock('@app/features/notification-sounds/use-notification-sounds', () => ({
+ notificationSoundFor: () => null,
+ useNotificationSounds: () => {},
+}));
vi.mock('@app/lib/i18n/use-interface-language-sync', () => ({
useInterfaceLanguageSync: () => {},
}));
diff --git a/apps/web/src/lib/tauri/notification.ts b/apps/web/src/lib/tauri/notification.ts
index 98575671f2..c106764968 100644
--- a/apps/web/src/lib/tauri/notification.ts
+++ b/apps/web/src/lib/tauri/notification.ts
@@ -79,6 +79,8 @@ export function createTauriNotificationInterface(
subtitle: sender ? conversation?.name : undefined,
threadId: conversation?.id,
sender,
+ // Older native builds ignore this and keep the system sound.
+ silent: data.options?.silent,
});
} catch (error) {
// OTA frontend updates can reach an older native app. Its legacy
diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
index a28cb6c627..d731e04d0e 100644
--- a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission.rs
@@ -162,6 +162,7 @@ fn notification_content(
subtitle: Option<&str>,
body: Option<&str>,
thread_id: Option<&str>,
+ play_sound: bool,
) -> Retained<UNMutableNotificationContent> {
let content = UNMutableNotificationContent::new();
content.setTitle(&NSString::from_str(title));
@@ -173,7 +174,10 @@ fn notification_content(
if let Some(thread_id) = thread_id {
content.setThreadIdentifier(&NSString::from_str(thread_id));
}
- content.setSound(Some(&UNNotificationSound::defaultSound()));
+ // Silent when the app plays its own notification sound for this alert.
+ if play_sound {
+ content.setSound(Some(&UNNotificationSound::defaultSound()));
+ }
content
}
@@ -217,6 +221,7 @@ pub async fn send_macos_notification(
subtitle: Option<String>,
thread_id: Option<String>,
sender: Option<communication::Sender>,
+ silent: Option<bool>,
) -> Result<(), NotificationError> {
let span = tracing::Span::current();
if let Some(notification_id) = &notification_id {
@@ -235,6 +240,7 @@ pub async fn send_macos_notification(
subtitle.as_deref(),
body.as_deref(),
thread_id.as_deref(),
+ !silent.unwrap_or(false),
);
let content = match &sender {
Some(sender) => communication::from_sender(
diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs
index bfaa528f06..101a5c70fe 100644
--- a/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs
+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs
@@ -65,6 +65,7 @@ fn immediate_notifications_preserve_the_title_and_optional_body() {
None,
Some("Hello 👋\nSecond line"),
None,
+ true,
),
None,
);
@@ -75,8 +76,10 @@ fn immediate_notifications_preserve_the_title_and_optional_body() {
);
assert!(request.trigger().is_none());
- let title_only =
- notification_request(&notification_content("Reminder", None, None, None), None);
+ let title_only = notification_request(
+ &notification_content("Reminder", None, None, None, true),
+ None,
+ );
assert_eq!(title_only.content().title().to_string(), "Reminder");
assert!(title_only.content().body().is_empty());
}
@@ -84,7 +87,13 @@ fn immediate_notifications_preserve_the_title_and_optional_body() {
#[test]
fn conversation_notifications_name_and_stack_their_conversation() {
let request = notification_request(
- &notification_content("Ada", Some("design"), Some("Ship it"), Some("channel-1")),
+ &notification_content(
+ "Ada",
+ Some("design"),
+ Some("Ship it"),
+ Some("channel-1"),
+ true,
+ ),
None,
);
assert_eq!(request.content().subtitle().to_string(), "design");
@@ -94,15 +103,30 @@ fn conversation_notifications_name_and_stack_their_conversation() {
);
assert!(request.content().sound().is_some());
- let direct = notification_request(&notification_content("Ada", None, None, None), None);
+ let direct = notification_request(&notification_content("Ada", None, None, None, true), None);
assert!(direct.content().subtitle().is_empty());
assert!(direct.content().threadIdentifier().is_empty());
}
+#[test]
+fn silent_notifications_leave_the_sound_to_the_app() {
+ let request = notification_request(
+ &notification_content("Ada", None, Some("Ship it"), None, false),
+ None,
+ );
+ assert!(request.content().sound().is_none());
+}
+
#[test]
fn repeated_notifications_do_not_replace_each_other() {
- let first = notification_request(&notification_content("Same title", None, None, None), None);
- let second = notification_request(&notification_content("Same title", None, None, None), None);
+ let first = notification_request(
+ &notification_content("Same title", None, None, None, true),
+ None,
+ );
+ let second = notification_request(
+ &notification_content("Same title", None, None, None, true),
+ None,
+ );
assert_ne!(first.identifier(), second.identifier());
assert!(Uuid::parse_str(&first.identifier().to_string()).is_ok());
}
@@ -110,15 +134,15 @@ fn repeated_notifications_do_not_replace_each_other() {
#[test]
fn delivered_notifications_keep_their_destination_without_webview_callbacks() {
let request = notification_request(
- &notification_content("Message", None, None, None),
+ &notification_content("Message", None, None, None, true),
Some("first-notification"),
);
let second = notification_request(
- &notification_content("Message", None, None, None),
+ &notification_content("Message", None, None, None, true),
Some("second-notification"),
);
let repeated = notification_request(
- &notification_content("Message", None, None, None),
+ &notification_content("Message", None, None, None, true),
Some("first-notification"),
);
assert_ne!(request.identifier(), repeated.identifier());
diff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.md
index 83f0e2875c..ef905a3054 100644
--- a/docs/agent-guide/notifications.md
+++ b/docs/agent-guide/notifications.md
@@ -50,7 +50,8 @@ response delegate or repair destinations in previously delivered alerts.
In a signed macOS release, an alert from a person shows their avatar in place of
the app icon, their name as the title, and the channel or document name beneath
for group conversations; direct messages show only the sender. Alerts from one
-conversation stack together in Notification Center and play the default sound.
+conversation stack together in Notification Center and play the default sound,
+unless Macro plays its own notification sound for that alert (see below).
Verify a channel message, a direct message, a document comment, and a reminder
(no sender: app icon and the combined title). Local and ad-hoc builds lack the
communication entitlement and show the app icon with the sender and subtitle.
@@ -174,3 +175,35 @@ default root size. Supporting `text-sm` text is 14px and `text-xs` is 12px.
Desktop and mobile share this scale, with accessibility text scaling preserved.
Desktop channel and AI composers use an `Attach files` paperclip that opens the file picker directly, without a plus menu. Comment composers open the image picker directly. Channels and DMs always open in message mode; create tasks through the task creation dialog. Shift+Enter, including an empty new line, expands channel and AI inputs so text starts above the toolbar at the left inset. Sent AI message bubbles use the ink fill with a contrasting foreground in each theme.
+
+## Notification sounds
+
+**Settings → Notifications → Sounds** turns on an in-app sound for incoming
+notifications. It is off by default and saved per person on each device
+(user-scoped localStorage), so a laptop and a phone choose separately. With
+sounds on, it shows a volume slider and one row per type (Messages, Mentions,
+Thread replies, Email, Meetings & reminders, Tasks, AI & agents, Everything
+else), each with its own on/off switch, sound picker, and play button. Picking
+a sound previews it. Email, AI & agents, and Everything else start off.
+
+Sounds are synthesized with Web Audio (`features/notification-sounds`); there
+are no audio files. Event types map to rows in `core/categories.ts`; a new
+backend event type stays quiet until it is mapped there. Incoming calls keep
+their own ring and never use these sounds. Only unseen notifications play,
+notifications within 1.5 s of a sound share it, and only the Macro tab the
+person last focused or touched plays, so several tabs ding once. Closing that
+tab hands sound back to the others until one is focused. Browsers keep
+audio suspended until the page has had a gesture; a notification before that
+stays silent rather than playing late.
+
+When Macro plays a sound for a notification, its browser or macOS alert is
+sent silent so the person hears one sound. macOS builds older than the
+`silent` argument on `send_macos_notification` ignore it and still play the
+system sound.
+
+The backend-free desktop/phone regression drives the real settings section,
+persistence, previews, and delivery through a stand-in notification feed:
+`bunx playwright test --config src/features/notification-sounds/browser-test/playwright.config.ts`
+(from `apps/web`). To check real delivery, turn sounds on, click anywhere in
+Macro, and trigger a mention from another session; then turn Mentions off and
+check that the next mention is quiet.