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 per-entity notification snoozing (#7065)

teob0bd70ce800f
diff --git a/.sqlx/query-f6600a8a539ce77dbd8b5332ea8994e58da416d649dc4963c510b3f6906db5fd.json b/.sqlx/query-01e581d687addf3e085627acfc7831d40ebf321ee9a993c34081c10dd67457b3.json
similarity index 54%
rename from .sqlx/query-f6600a8a539ce77dbd8b5332ea8994e58da416d649dc4963c510b3f6906db5fd.json
rename to .sqlx/query-01e581d687addf3e085627acfc7831d40ebf321ee9a993c34081c10dd67457b3.json
index 0257874645..db394ea65f 100644
--- a/.sqlx/query-f6600a8a539ce77dbd8b5332ea8994e58da416d649dc4963c510b3f6906db5fd.json
+++ b/.sqlx/query-01e581d687addf3e085627acfc7831d40ebf321ee9a993c34081c10dd67457b3.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n 'item' as unsubscribe_type,\n unsubscribe_item.item_id as \"item_id!\",\n unsubscribe_item.item_type as \"item_type!\"\n FROM\n user_notification_item_unsubscribe unsubscribe_item\n WHERE\n unsubscribe_item.user_id = $1\n ",
+ "query": "\n SELECT\n 'item' as unsubscribe_type,\n unsubscribe_item.item_id as \"item_id!\",\n unsubscribe_item.item_type as \"item_type!\",\n unsubscribe_item.snoozed_until\n FROM\n user_notification_item_unsubscribe unsubscribe_item\n WHERE\n unsubscribe_item.user_id = $1\n AND (snoozed_until IS NULL OR snoozed_until > NOW())\n ",
"describe": {
"columns": [
{
@@ -17,6 +17,11 @@
"ordinal": 2,
"name": "item_type!",
"type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "snoozed_until",
+ "type_info": "Timestamptz"
}
],
"parameters": {
@@ -27,8 +32,9 @@
"nullable": [
null,
false,
- false
+ false,
+ true
]
},
- "hash": "f6600a8a539ce77dbd8b5332ea8994e58da416d649dc4963c510b3f6906db5fd"
+ "hash": "01e581d687addf3e085627acfc7831d40ebf321ee9a993c34081c10dd67457b3"
}
diff --git a/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json b/.sqlx/query-1f4dd3aa9143ebcd2b53dad3f41210a2abd11ad2e98d52c86013189a375d9393.json
similarity index 71%
rename from .sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json
rename to .sqlx/query-1f4dd3aa9143ebcd2b53dad3f41210a2abd11ad2e98d52c86013189a375d9393.json
index a8e7326c35..617c921b9a 100644
--- a/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json
+++ b/.sqlx/query-1f4dd3aa9143ebcd2b53dad3f41210a2abd11ad2e98d52c86013189a375d9393.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT user_id FROM user_notification_item_unsubscribe\n WHERE item_id = $1 AND user_id = ANY($2)\n ",
+ "query": "\n SELECT user_id FROM user_notification_item_unsubscribe\n WHERE item_id = $1 AND user_id = ANY($2)\n AND (snoozed_until IS NULL OR snoozed_until > NOW())\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
false
]
},
- "hash": "765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67"
+ "hash": "1f4dd3aa9143ebcd2b53dad3f41210a2abd11ad2e98d52c86013189a375d9393"
}
diff --git a/.sqlx/query-6b45324af9f3354b5b894dd7d46a944fc33313ab10f71c6b0ababf5e57842d28.json b/.sqlx/query-6b45324af9f3354b5b894dd7d46a944fc33313ab10f71c6b0ababf5e57842d28.json
new file mode 100644
index 0000000000..4594d44eb1
--- /dev/null
+++ b/.sqlx/query-6b45324af9f3354b5b894dd7d46a944fc33313ab10f71c6b0ababf5e57842d28.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT item_id, item_type, snoozed_until\n FROM user_notification_item_unsubscribe\n WHERE user_id = $1 AND (snoozed_until IS NULL OR snoozed_until > NOW())\n ORDER BY snoozed_until NULLS LAST, item_id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "item_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "item_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "snoozed_until",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "6b45324af9f3354b5b894dd7d46a944fc33313ab10f71c6b0ababf5e57842d28"
+}
diff --git a/.sqlx/query-49044852c3fc5c0183d7253e27ec923e43d1d9abcfa5ad3fd714ce35c3c0e3f0.json b/.sqlx/query-85ad383f14e74e41639dd84ca0fddbd9fa8c2cc3f73e2a35ea1725f09b11f47c.json
similarity index 72%
rename from .sqlx/query-49044852c3fc5c0183d7253e27ec923e43d1d9abcfa5ad3fd714ce35c3c0e3f0.json
rename to .sqlx/query-85ad383f14e74e41639dd84ca0fddbd9fa8c2cc3f73e2a35ea1725f09b11f47c.json
index 223773f5ff..3742be6e84 100644
--- a/.sqlx/query-49044852c3fc5c0183d7253e27ec923e43d1d9abcfa5ad3fd714ce35c3c0e3f0.json
+++ b/.sqlx/query-85ad383f14e74e41639dd84ca0fddbd9fa8c2cc3f73e2a35ea1725f09b11f47c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT u.user_id\n FROM user_notification_item_unsubscribe u\n WHERE u.item_id = $1\n ",
+ "query": "\n SELECT u.user_id\n FROM user_notification_item_unsubscribe u\n WHERE u.item_id = $1\n AND (u.snoozed_until IS NULL OR u.snoozed_until > NOW())\n ",
"describe": {
"columns": [
{
@@ -18,5 +18,5 @@
false
]
},
- "hash": "49044852c3fc5c0183d7253e27ec923e43d1d9abcfa5ad3fd714ce35c3c0e3f0"
+ "hash": "85ad383f14e74e41639dd84ca0fddbd9fa8c2cc3f73e2a35ea1725f09b11f47c"
}
diff --git a/.sqlx/query-907b6b77f7daa15a82f752162222c43c23ad1924e39d2f99822d545ba3975609.json b/.sqlx/query-907b6b77f7daa15a82f752162222c43c23ad1924e39d2f99822d545ba3975609.json
new file mode 100644
index 0000000000..64a96f399c
--- /dev/null
+++ b/.sqlx/query-907b6b77f7daa15a82f752162222c43c23ad1924e39d2f99822d545ba3975609.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM user_notification_item_unsubscribe WHERE user_id = $1 AND item_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "907b6b77f7daa15a82f752162222c43c23ad1924e39d2f99822d545ba3975609"
+}
diff --git a/.sqlx/query-aafdb1ce7a388f30424d723dbe90e3944925343a0004d78fbeaf9151cbd6a606.json b/.sqlx/query-aafdb1ce7a388f30424d723dbe90e3944925343a0004d78fbeaf9151cbd6a606.json
new file mode 100644
index 0000000000..e0ed69ea1f
--- /dev/null
+++ b/.sqlx/query-aafdb1ce7a388f30424d723dbe90e3944925343a0004d78fbeaf9151cbd6a606.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO user_notification_item_unsubscribe (user_id, item_id, item_type, snoozed_until)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (user_id, item_id) DO UPDATE\n SET item_type = EXCLUDED.item_type, snoozed_until = EXCLUDED.snoozed_until",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "aafdb1ce7a388f30424d723dbe90e3944925343a0004d78fbeaf9151cbd6a606"
+}
diff --git a/.sqlx/query-9c4e25c3a319934aa1bbf165f19683f34a3f5684edaa965cbdb1b09e422cab8b.json b/.sqlx/query-f6978cb5982563e5d302c18795a2004295fce2b25829dfd9bfe0ca122bed1b90.json
similarity index 65%
rename from .sqlx/query-9c4e25c3a319934aa1bbf165f19683f34a3f5684edaa965cbdb1b09e422cab8b.json
rename to .sqlx/query-f6978cb5982563e5d302c18795a2004295fce2b25829dfd9bfe0ca122bed1b90.json
index 5363a116e1..7233e8a526 100644
--- a/.sqlx/query-9c4e25c3a319934aa1bbf165f19683f34a3f5684edaa965cbdb1b09e422cab8b.json
+++ b/.sqlx/query-f6978cb5982563e5d302c18795a2004295fce2b25829dfd9bfe0ca122bed1b90.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO user_notification_item_unsubscribe (user_id, item_id, item_type)\n VALUES ($1, $2, $3)\n ON CONFLICT (user_id, item_id) DO NOTHING\n ",
+ "query": "\n INSERT INTO user_notification_item_unsubscribe (user_id, item_id, item_type)\n VALUES ($1, $2, $3)\n ON CONFLICT (user_id, item_id) DO UPDATE SET snoozed_until = NULL\n ",
"describe": {
"columns": [],
"parameters": {
@@ -12,5 +12,5 @@
},
"nullable": []
},
- "hash": "9c4e25c3a319934aa1bbf165f19683f34a3f5684edaa965cbdb1b09e422cab8b"
+ "hash": "f6978cb5982563e5d302c18795a2004295fce2b25829dfd9bfe0ca122bed1b90"
}
diff --git a/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx b/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx
index 346bbff349..5f348898dd 100644
--- a/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx
+++ b/apps/web/src/components/ui/components/CommandMenuPrimitives.tsx
@@ -168,6 +168,7 @@ export const CommandMenuShell = Object.assign(CommandMenuShellRoot, {
});
export function CommandMenuList<T>(props: {
+ id?: string;
items: readonly T[];
selectedIndex: number;
scrollSelectedIntoView?: boolean;
@@ -218,6 +219,7 @@ export function CommandMenuList<T>(props: {
return (
<div
+ id={props.id}
ref={listRef}
role="listbox"
class={cn(
@@ -234,6 +236,8 @@ export function CommandMenuList<T>(props: {
{props.beforeItem?.(item, index())}
<CommandMenuListItem
as="div"
+ role="option"
+ aria-selected={isSelected(index())}
id={itemId(item, index())}
selected={isSelected(index())}
disabled={props.itemDisabled?.(item, index())}
@@ -269,6 +273,8 @@ export function CommandMenuSearchInput(
export function CommandMenuListItem(
props: ParentProps<{
id?: string;
+ role?: JSX.HTMLAttributes<HTMLElement>['role'];
+ 'aria-selected'?: boolean;
as?: 'button' | 'div';
class?: string;
selected?: boolean;
@@ -282,6 +288,8 @@ export function CommandMenuListItem(
component={props.as ?? 'button'}
type={props.as === 'div' ? undefined : 'button'}
id={props.id}
+ role={props.role}
+ aria-selected={props['aria-selected']}
disabled={props.as === 'div' ? undefined : props.disabled}
aria-disabled={props.disabled || undefined}
class={cn(
diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
index 775d1393ca..0f6f68d7fe 100644
--- a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
@@ -1,9 +1,11 @@
+import { useBlockEntityCommands } from '@app/features/next-soup/actions';
import { getChannelEntityTarget } from '@app/features/next-soup/utils';
import {
ChannelDetail,
ChannelDetailTopBar,
} from '@channel/Channel/ChannelDetail';
import type { ChannelTargetRequest } from '@channel/Channel/ChannelSurface';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import type { ChannelEntity } from '@entity';
import { createMemo } from 'solid-js';
@@ -15,6 +17,13 @@ import { createMemo } from 'solid-js';
* applied the same rule via its stringified navigation key).
*/
export function ChannelDetailView(props: { channel: ChannelEntity }) {
+ const panel = useSplitPanelOrThrow();
+ useBlockEntityCommands({
+ id: props.channel.id,
+ scopeId: panel.splitHotkeyScope,
+ resolveEntity: () => props.channel,
+ });
+
let lastTargetKey: string | undefined;
const target = createMemo<ChannelTargetRequest | undefined>((previous) => {
const key = `${props.channel.id}:${props.channel.target?.messageId ?? ''}:${
diff --git a/apps/web/src/features/entity/queries/email.ts b/apps/web/src/features/entity/queries/email.ts
index 33e0ef4364..520aa4e90f 100644
--- a/apps/web/src/features/entity/queries/email.ts
+++ b/apps/web/src/features/entity/queries/email.ts
@@ -1,13 +1,12 @@
/** Email queries adapted to the entity data model. */
-import type { SafeFetchInit } from '@core/util/safeFetch';
+import { throwOnErr } from '@core/util/result';
import { emailClient } from '@service-email/client';
import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';
import type { PreviewsInboxCursorParams } from '@service-email/generated/schemas/previewsInboxCursorParams';
import { useInfiniteQuery } from '@tanstack/solid-query';
-import { type Accessor, createMemo } from 'solid-js';
+import type { Accessor } from 'solid-js';
import type { EmailEntity } from '../types/entity';
-import { createApiTokenQuery, withApiTokenRetry } from './auth';
import { queryKeys } from './key';
type FetchPaginatedEmailsParams = PreviewsInboxCursorParams & {
@@ -16,32 +15,19 @@ type FetchPaginatedEmailsParams = PreviewsInboxCursorParams & {
};
const fetchPaginatedEmails = async ({
- apiToken,
view,
...params
-}: FetchPaginatedEmailsParams & { apiToken: string }) => {
- const Authorization = `Bearer ${apiToken}`;
- const init: SafeFetchInit = {
- headers: { Authorization },
- };
-
- const result = await emailClient.getPreviews(
- {
+}: FetchPaginatedEmailsParams) =>
+ // The email client already authenticates with the current session.
+ throwOnErr(() =>
+ emailClient.getPreviews({
view,
limit: params.limit,
sort_method: params.sort_method,
cursor: params.cursor,
- },
- init
+ })
);
- if (result.isErr()) {
- throw new Error('Failed to fetch email');
- }
-
- return result.value;
-};
-
export function createEmailsInfiniteQuery(
args?: Accessor<FetchPaginatedEmailsParams>,
options?: {
@@ -63,17 +49,10 @@ export function createEmailsInfiniteQuery(
};
};
- const authQuery = createApiTokenQuery();
- const enabled = createMemo(
- () => authQuery.isSuccess && !options?.disabled?.()
- );
return useInfiniteQuery(() => {
return {
queryKey: queryKeys.email({ infinite: true, ...params() }),
- queryFn: ({ pageParam }) =>
- withApiTokenRetry(authQuery, (apiToken) =>
- fetchPaginatedEmails({ apiToken, ...pageParam })
- ),
+ queryFn: ({ pageParam }) => fetchPaginatedEmails(pageParam),
initialPageParam: params(),
getNextPageParam: ({ next_cursor: cursor }) =>
cursor ? { ...params(), cursor } : undefined,
@@ -102,7 +81,7 @@ export function createEmailsInfiniteQuery(
};
})
),
- enabled: enabled(),
+ enabled: !options?.disabled?.(),
refetchInterval: options?.refetchInterval?.(),
};
});
diff --git a/apps/web/src/features/entity/utils/notification.ts b/apps/web/src/features/entity/utils/notification.ts
index e90d1d0e83..cf6d671a43 100644
--- a/apps/web/src/features/entity/utils/notification.ts
+++ b/apps/web/src/features/entity/utils/notification.ts
@@ -166,7 +166,8 @@ export function isMutedItem(
return muted.some(
(entry) =>
entry.item_id === item.item_id &&
- normalizeMuteItemType(entry.item_type) === type
+ normalizeMuteItemType(entry.item_type) === type &&
+ (!entry.snoozed_until || Date.parse(entry.snoozed_until) > Date.now())
);
}
diff --git a/apps/web/src/features/next-soup/actions/make-mute-action.ts b/apps/web/src/features/next-soup/actions/make-mute-action.ts
index 9b54079e58..7b50abccf1 100644
--- a/apps/web/src/features/next-soup/actions/make-mute-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-mute-action.ts
@@ -2,6 +2,7 @@ import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
import { entityIsMuted, muteItemForEntity } from '@entity/utils/notification';
import type { NotificationSource } from '@notifications';
+import { openSnoozeNotifications } from '@notifications/SnoozeNotificationsDialog';
import {
useMuteItemMutation,
useUnmuteItemMutation,
@@ -24,6 +25,15 @@ export const makeMuteAction = (options: MakeMuteActionOptions) => {
const muteMutation = useMuteItemMutation();
const unmuteMutation = useUnmuteItemMutation();
+ const snooze = (entities: EntityData[]) => {
+ openSnoozeNotifications(
+ entities.flatMap((entity) => {
+ const item = muteItemForEntity(entity);
+ return item ? [item] : [];
+ })
+ );
+ };
+
const canExecute = (entity: EntityData): boolean =>
muteItemForEntity(entity) !== undefined;
@@ -86,5 +96,5 @@ export const makeMuteAction = (options: MakeMuteActionOptions) => {
await execute(entities);
};
- return { canExecute, isMuted, execute, executeWithSoup };
+ return { canExecute, isMuted, execute, executeWithSoup, snooze };
};
diff --git a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
index 1acf13ae2f..930d6244d6 100644
--- a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
+++ b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
@@ -322,6 +322,24 @@ export const useBlockEntityCommands = (
}).withGroup(group);
// Mute notifications (command menu only, no keybinding)
+ registerHotkey({
+ scopeId,
+ description: 'Snooze notifications…',
+ keywords: ['pause', 'morning', 'weekend', 'notifications'],
+ keyDownHandler: () => {
+ const entity = getEntity();
+ if (!entity || !muteAction.canExecute(entity)) return false;
+ muteAction.snooze([entity]);
+ return true;
+ },
+ condition: () => {
+ const entity = getEntity();
+ return entity !== undefined && muteAction.canExecute(entity);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ }).withGroup(group);
+
registerHotkey({
hotkeyToken: TOKENS.entity.action.mute,
scopeId,
diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
index c0d44e3126..55ccdbd488 100644
--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
@@ -387,6 +387,26 @@ export const useEntityActionHotkeys = (
}).withGroup(group);
// Mute notifications (command menu only, no keybinding)
+ registerHotkey({
+ scopeId,
+ description: 'Snooze notifications…',
+ keywords: ['pause', 'morning', 'weekend', 'notifications'],
+ keyDownHandler: () => {
+ const entities = getEntitiesForAction();
+ if (!entities.length || !entities.every(muteAction.canExecute))
+ return false;
+ muteAction.snooze(entities);
+ return true;
+ },
+ condition: () => {
+ if (condition && !condition()) return false;
+ const entities = getEntitiesForAction();
+ return entities.length > 0 && entities.every(muteAction.canExecute);
+ },
+ displayPriority: 10,
+ tags: [HotkeyTags.SelectionModification],
+ }).withGroup(group);
+
registerHotkey({
hotkeyToken: TOKENS.entity.action.mute,
scopeId,
diff --git a/apps/web/src/features/notifications/SnoozeNotificationsDialog.tsx b/apps/web/src/features/notifications/SnoozeNotificationsDialog.tsx
new file mode 100644
index 0000000000..9379ff73c7
--- /dev/null
+++ b/apps/web/src/features/notifications/SnoozeNotificationsDialog.tsx
@@ -0,0 +1,88 @@
+import { toast } from '@core/component/Toast/Toast';
+import { useDateSearch } from '@core/util/dateSearch/useDateSearch';
+import { useMuteItemMutation } from '@queries/notification/unsubscribes';
+import type { UserUnsubscribe } from '@service-notification/generated/schemas/userUnsubscribe';
+import {
+ type ManagedDialogProps,
+ type OpenDialogOptions,
+ openDialog,
+} from '@ui';
+import { createSignal } from 'solid-js';
+import { SnoozePicker } from './components/SnoozePicker';
+import {
+ formatSnoozeDeadline,
+ type SnoozeOption,
+ snoozePresets,
+} from './core/snooze';
+import { createSnoozeController } from './primitives/create-snooze-controller';
+
+function SnoozeNotificationsDialog(
+ props: ManagedDialogProps & { items: UserUnsubscribe[] }
+) {
+ const mutation = useMuteItemMutation();
+ const [query, setQuery] = createSignal('');
+ const dates = useDateSearch({ query, defaultTime: { hours: 9, minutes: 0 } });
+ const options = (): SnoozeOption[] => {
+ const presets = snoozePresets(new Date());
+ const search = query().trim().toLowerCase();
+ if (!search) return presets;
+ const matches = presets.filter(
+ (preset) =>
+ preset.label.toLowerCase().includes(search) ||
+ preset.id.includes(search)
+ );
+ const parsed = dates()
+ .filter((date) => date.date.getTime() > Date.now())
+ .map((date) => ({
+ id: date.id,
+ label: date.displayText,
+ until: date.date,
+ }));
+ const seen = new Set<number>();
+ return [...matches, ...parsed].filter((option) => {
+ const time = option.until.getTime();
+ if (seen.has(time)) return false;
+ seen.add(time);
+ return true;
+ });
+ };
+ const controller = createSnoozeController({
+ items: props.items,
+ saveItem: (item, until) =>
+ mutation.mutateAsync({ ...item, snoozed_until: until }),
+ onSaved: (until, count) => {
+ props.onOpenChange(false);
+ toast.success(
+ `Snoozed ${count} ${count === 1 ? 'item' : 'items'} until ${formatSnoozeDeadline(until)}`
+ );
+ },
+ });
+ return (
+ <SnoozePicker
+ {...props}
+ count={controller.remainingCount()}
+ query={query()}
+ onQueryChange={setQuery}
+ options={options()}
+ pending={controller.pending()}
+ error={controller.error()}
+ onSelect={(until) => void controller.submit(until)}
+ />
+ );
+}
+
+/** Shared entry point for entity commands, context menus, and notification settings. */
+export function openSnoozeNotifications(
+ items: UserUnsubscribe[],
+ options?: OpenDialogOptions
+) {
+ const unique = [
+ ...new Map(
+ items.map((item) => [`${item.item_type}:${item.item_id}`, item])
+ ).values(),
+ ];
+ // Context menus use the app host's lifetime; persistent hosts can supply
+ // their owner so mobile drawers inherit the parent's dismissal layer.
+ if (unique.length)
+ openDialog(SnoozeNotificationsDialog, { items: unique }, options);
+}
diff --git a/apps/web/src/features/notifications/components/SnoozePicker.tsx b/apps/web/src/features/notifications/components/SnoozePicker.tsx
new file mode 100644
index 0000000000..2f73a03cf8
--- /dev/null
+++ b/apps/web/src/features/notifications/components/SnoozePicker.tsx
@@ -0,0 +1,131 @@
+import {
+ CommandMenuEmptyState,
+ CommandMenuList,
+ CommandMenuSearchInput,
+ CommandMenuShell,
+ createCommandListController,
+ Dialog,
+ type ManagedDialogProps,
+} from '@ui';
+import { createUniqueId, Show } from 'solid-js';
+import { formatSnoozeDeadline, type SnoozeOption } from '../core/snooze';
+
+export function SnoozePicker(
+ props: ManagedDialogProps & {
+ count: number;
+ query: string;
+ onQueryChange: (query: string) => void;
+ options: SnoozeOption[];
+ pending: boolean;
+ error?: string;
+ onSelect: (until: Date) => void;
+ }
+) {
+ const id = createUniqueId();
+ const select = (option: SnoozeOption) => {
+ if (!props.pending) props.onSelect(option.until);
+ };
+ const list = createCommandListController({
+ items: () => props.options,
+ onSelect: select,
+ });
+ return (
+ <Dialog open={props.open} onOpenChange={props.onOpenChange} visibleScrim>
+ <CommandMenuShell>
+ <CommandMenuShell.Header>
+ <CommandMenuSearchInput
+ aria-label="Snooze until"
+ role="combobox"
+ aria-expanded="true"
+ aria-controls={`${id}-options`}
+ aria-activedescendant={
+ props.options.length ? `${id}-${list.selectedIndex()}` : undefined
+ }
+ placeholder="Choose a time, or type tomorrow 10am…"
+ value={props.query}
+ disabled={props.pending}
+ onInput={(event) => {
+ props.onQueryChange(event.currentTarget.value);
+ list.setSelectedIndex(0);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ list.selectNext();
+ }
+ if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ list.selectPrevious();
+ }
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ list.selectSelected();
+ }
+ }}
+ />
+ </CommandMenuShell.Header>
+ <CommandMenuShell.Toolbar class="flex-col items-start gap-1 px-4 py-3">
+ <Dialog.Title class="text-sm font-medium text-ink">
+ Snooze notifications
+ {props.count > 1 ? ` for ${props.count} items` : ''}
+ </Dialog.Title>
+ <Dialog.Description class="text-xs text-ink-muted">
+ Notifications resume automatically. Times are in your local time
+ zone.
+ </Dialog.Description>
+ </CommandMenuShell.Toolbar>
+ <CommandMenuShell.Body class="flex flex-col">
+ <CommandMenuList
+ id={`${id}-options`}
+ items={props.options}
+ selectedIndex={list.selectedIndex()}
+ scrollSelectedIntoView={list.shouldScrollSelectedIntoView()}
+ itemId={(_, index) => `${id}-${index}`}
+ itemDisabled={() => props.pending}
+ onItemMouseMove={list.setSelectedIndexFromPointer}
+ onSelect={select}
+ class="min-h-0 max-h-80 mobile:[&_[role=option]]:h-auto mobile:[&_[role=option]]:min-h-12 mobile:[&_[role=option]]:py-2"
+ >
+ {(option) => (
+ <div class="flex min-w-0 flex-1 items-center gap-2 mobile:flex-col mobile:items-start mobile:gap-0.5">
+ <span class="flex-1 font-medium mobile:flex-none">
+ {option.label}
+ </span>
+ <span class="text-xs font-normal text-ink-muted">
+ {formatSnoozeDeadline(option.until)}
+ </span>
+ </div>
+ )}
+ </CommandMenuList>
+ <Show when={!props.options.length}>
+ <CommandMenuEmptyState>
+ Enter a future time, like 2h or tomorrow 10am.
+ </CommandMenuEmptyState>
+ </Show>
+ <Show when={props.error}>
+ <p role="alert" class="px-4 pb-3 text-sm text-failure-ink">
+ {props.error}
+ </p>
+ </Show>
+ </CommandMenuShell.Body>
+ <CommandMenuShell.Footer>
+ <span role="status">
+ <Show when={!props.pending} fallback="Snoozing…">
+ <span class="mobile:hidden">
+ ↑ ↓ to choose · Enter to snooze · Esc to cancel
+ </span>
+ <span class="hidden mobile:inline">Tap a time to snooze</span>
+ </Show>
+ </span>
+ <button
+ type="button"
+ class="ml-auto shrink-0 text-ink-muted hover:text-ink mobile:min-h-11 mobile:px-2"
+ onClick={() => props.onOpenChange(false)}
+ >
+ Cancel
+ </button>
+ </CommandMenuShell.Footer>
+ </CommandMenuShell>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/notifications/core/snooze.ts b/apps/web/src/features/notifications/core/snooze.ts
new file mode 100644
index 0000000000..95b295503a
--- /dev/null
+++ b/apps/web/src/features/notifications/core/snooze.ts
@@ -0,0 +1,61 @@
+export type SnoozeOption = {
+ id: string;
+ label: string;
+ until: Date;
+};
+
+/** Use calendar dates, so morning stays at 9 AM across daylight saving changes. */
+export function snoozePresets(now: Date): SnoozeOption[] {
+ const morning = new Date(now);
+ morning.setHours(9, 0, 0, 0);
+ if (morning <= now) morning.setDate(morning.getDate() + 1);
+
+ const monday = new Date(now);
+ monday.setDate(monday.getDate() + ((8 - monday.getDay()) % 7 || 7));
+ monday.setHours(9, 0, 0, 0);
+
+ const week = new Date(now);
+ week.setDate(week.getDate() + 7);
+ week.setHours(9, 0, 0, 0);
+
+ return [
+ {
+ id: '30-minutes',
+ label: 'For 30 minutes',
+ until: new Date(now.getTime() + 30 * 60_000),
+ },
+ {
+ id: '1-hour',
+ label: 'For 1 hour',
+ until: new Date(now.getTime() + 60 * 60_000),
+ },
+ {
+ id: '3-hours',
+ label: 'For 3 hours',
+ until: new Date(now.getTime() + 180 * 60_000),
+ },
+ { id: 'morning', label: 'Until the morning', until: morning },
+ {
+ id: 'weekend',
+ label:
+ now.getDay() === 0 || now.getDay() >= 5
+ ? 'For the weekend'
+ : 'Until Monday',
+ until: monday,
+ },
+ { id: 'week', label: 'For a week', until: week },
+ ];
+}
+
+export function formatSnoozeDeadline(until: Date | string): string {
+ const date = new Date(until);
+ return new Intl.DateTimeFormat(undefined, {
+ year:
+ date.getFullYear() === new Date().getFullYear() ? undefined : 'numeric',
+ weekday: 'short',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ }).format(date);
+}
diff --git a/apps/web/src/features/notifications/primitives/create-snooze-controller.ts b/apps/web/src/features/notifications/primitives/create-snooze-controller.ts
new file mode 100644
index 0000000000..afa978d46b
--- /dev/null
+++ b/apps/web/src/features/notifications/primitives/create-snooze-controller.ts
@@ -0,0 +1,46 @@
+import { createSignal } from 'solid-js';
+
+/** Keep failures in the picker so a rejected write can be retried. */
+export function createSnoozeController<Item>(options: {
+ items: readonly Item[];
+ saveItem: (item: Item, until: string) => Promise<void>;
+ onSaved: (until: string, count: number) => void;
+ now?: () => number;
+}) {
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal<string>();
+ const [remainingItems, setRemainingItems] = createSignal(options.items);
+ const remainingCount = () => remainingItems().length;
+ const submit = async (until: Date) => {
+ if (pending() || !remainingCount()) return;
+ if (
+ !Number.isFinite(until.getTime()) ||
+ until.getTime() <= (options.now?.() ?? Date.now())
+ ) {
+ setError('Choose a time in the future.');
+ return;
+ }
+ setPending(true);
+ setError(undefined);
+ const deadline = until.toISOString();
+ const items = remainingItems();
+ const results = await Promise.allSettled(
+ items.map(async (item) => options.saveItem(item, deadline))
+ );
+ setRemainingItems(
+ items.filter((_, index) => results[index].status === 'rejected')
+ );
+ setPending(false);
+ if (remainingCount()) {
+ const saved = options.items.length - remainingCount();
+ setError(
+ saved
+ ? `${saved} of ${options.items.length} items snoozed. Choose a time to retry the ${remainingCount()} remaining. Closing keeps saved snoozes.`
+ : 'Could not snooze the selected items. Please try again.'
+ );
+ return;
+ }
+ options.onSaved(deadline, items.length);
+ };
+ return { pending, error, remainingCount, submit };
+}
diff --git a/apps/web/src/features/notifications/tests/snooze-controller.test.ts b/apps/web/src/features/notifications/tests/snooze-controller.test.ts
new file mode 100644
index 0000000000..90d504a118
--- /dev/null
+++ b/apps/web/src/features/notifications/tests/snooze-controller.test.ts
@@ -0,0 +1,104 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { createSnoozeController } from '../primitives/create-snooze-controller';
+
+describe('snoozing notifications', () => {
+ it('rejects expired and invalid selections without sending a request', async () => {
+ const save = vi.fn();
+ const controller = createRoot(() =>
+ createSnoozeController({
+ items: ['one'],
+ saveItem: save,
+ onSaved: vi.fn(),
+ now: () => 1000,
+ })
+ );
+ await controller.submit(new Date(1000));
+ await controller.submit(new Date('invalid'));
+ expect(save).not.toHaveBeenCalled();
+ expect(controller.error()).toBe('Choose a time in the future.');
+ });
+
+ it('keeps a failed write retryable and closes only after persistence succeeds', async () => {
+ const save = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce(undefined);
+ const onSaved = vi.fn();
+ const controller = createRoot(() =>
+ createSnoozeController({
+ items: ['one'],
+ saveItem: save,
+ onSaved,
+ now: () => 0,
+ })
+ );
+ await controller.submit(new Date(1000));
+ expect(onSaved).not.toHaveBeenCalled();
+ expect(controller.error()).toBeTruthy();
+ expect(controller.pending()).toBe(false);
+ await controller.submit(new Date(1000));
+ expect(onSaved).toHaveBeenCalledWith('1970-01-01T00:00:01.000Z', 1);
+ expect(controller.error()).toBeUndefined();
+ });
+
+ it('ignores repeated submissions while a write is pending', async () => {
+ let finish!: () => void;
+ const save = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ })
+ );
+ const controller = createRoot(() =>
+ createSnoozeController({
+ items: ['one'],
+ saveItem: save,
+ onSaved: vi.fn(),
+ now: () => 0,
+ })
+ );
+ const first = controller.submit(new Date(1000));
+ await controller.submit(new Date(2000));
+ expect(save).toHaveBeenCalledTimes(1);
+ finish();
+ await first;
+ expect(controller.pending()).toBe(false);
+ });
+
+ it('reports partial success and retries only unsaved items at the new deadline', async () => {
+ const saved = new Map<string, string>();
+ const saveItem = vi.fn(async (item: string, until: string) => {
+ if (item === 'two' && until === '1970-01-01T00:00:01.000Z') {
+ throw new Error('offline');
+ }
+ saved.set(item, until);
+ });
+ const onSaved = vi.fn();
+ const controller = createRoot(() =>
+ createSnoozeController({
+ items: ['one', 'two'],
+ saveItem,
+ onSaved,
+ now: () => 0,
+ })
+ );
+ await controller.submit(new Date(1000));
+ expect(onSaved).not.toHaveBeenCalled();
+ expect(controller.remainingCount()).toBe(1);
+ expect(controller.error()).toBe(
+ '1 of 2 items snoozed. Choose a time to retry the 1 remaining. Closing keeps saved snoozes.'
+ );
+ expect(saved.size).toBe(1);
+
+ await controller.submit(new Date(2000));
+ expect(saveItem).toHaveBeenCalledTimes(3);
+ expect(saved.get('one')).toBe('1970-01-01T00:00:01.000Z');
+ expect(saved.get('two')).toBe('1970-01-01T00:00:02.000Z');
+ expect(controller.error()).toBeUndefined();
+ expect(controller.remainingCount()).toBe(0);
+ expect(onSaved).toHaveBeenCalledWith('1970-01-01T00:00:02.000Z', 1);
+ await controller.submit(new Date(3000));
+ expect(saveItem).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/apps/web/src/features/notifications/tests/snooze.test.ts b/apps/web/src/features/notifications/tests/snooze.test.ts
new file mode 100644
index 0000000000..7885937680
--- /dev/null
+++ b/apps/web/src/features/notifications/tests/snooze.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+import { snoozePresets } from '../core/snooze';
+
+describe('notification snooze presets', () => {
+ it('keeps Monday at 9 AM across daylight saving weekends', () => {
+ for (const now of [new Date(2026, 2, 7, 12), new Date(2026, 9, 31, 12)]) {
+ const monday = snoozePresets(now).find(
+ (preset) => preset.id === 'weekend'
+ )!.until;
+ expect(monday.getDay()).toBe(1);
+ expect(monday.getHours()).toBe(9);
+ expect(monday.getMinutes()).toBe(0);
+ }
+ });
+
+ it('uses the next local morning, including before 9 AM', () => {
+ const before = new Date(2026, 8, 25, 8, 59);
+ const at = new Date(2026, 8, 25, 9);
+ expect(
+ snoozePresets(before).find((p) => p.id === 'morning')?.until
+ ).toEqual(new Date(2026, 8, 25, 9));
+ expect(snoozePresets(at).find((p) => p.id === 'morning')?.until).toEqual(
+ new Date(2026, 8, 26, 9)
+ );
+ });
+
+ it('snoozes through the weekend to Monday morning', () => {
+ for (const day of [25, 26, 27]) {
+ const preset = snoozePresets(new Date(2026, 8, day, 17)).find(
+ (p) => p.id === 'weekend'
+ );
+ expect(preset?.label).toBe('For the weekend');
+ expect(preset?.until).toEqual(new Date(2026, 8, 28, 9));
+ }
+ });
+
+ it('always offers future deadlines at month and year boundaries', () => {
+ for (const now of [
+ new Date(2026, 8, 28, 12),
+ new Date(2026, 11, 31, 23, 59),
+ ]) {
+ expect(snoozePresets(now).every((option) => option.until > now)).toBe(
+ true
+ );
+ expect(snoozePresets(now)[0].until.getTime() - now.getTime()).toBe(
+ 30 * 60_000
+ );
+ }
+ });
+});
diff --git a/apps/web/src/features/settings/MutedItemRow.tsx b/apps/web/src/features/settings/MutedItemRow.tsx
index 2c1a1969c6..4047c61fa8 100644
--- a/apps/web/src/features/settings/MutedItemRow.tsx
+++ b/apps/web/src/features/settings/MutedItemRow.tsx
@@ -11,6 +11,7 @@ import {
muteItemPreviewEntity,
normalizeMuteItemType,
} from '@entity/utils/notification';
+import { formatSnoozeDeadline } from '@notifications/core/snooze';
import { mutedEntityTypeLabel } from '@notifications/notification-event-catalog';
import {
type ItemEntity,
@@ -27,6 +28,8 @@ import { createMemo, Show } from 'solid-js';
export function MutedItemRow(props: {
item: UserUnsubscribe;
onUnmute: () => void;
+ onSnooze?: () => void;
+ pending?: boolean;
}) {
const entity = createMemo(() => muteItemPreviewEntity(props.item));
return (
@@ -38,6 +41,8 @@ export function MutedItemRow(props: {
name={mutedEntityTypeLabel(props.item.item_type)}
iconType={muteItemFallbackIconType(props.item.item_type)}
onUnmute={props.onUnmute}
+ onSnooze={props.onSnooze}
+ pending={props.pending}
/>
}
>
@@ -46,6 +51,8 @@ export function MutedItemRow(props: {
item={props.item}
entity={previewEntity()}
onUnmute={props.onUnmute}
+ onSnooze={props.onSnooze}
+ pending={props.pending}
/>
)}
</Show>
@@ -56,6 +63,8 @@ function MutedItemPreviewRow(props: {
item: UserUnsubscribe;
entity: ItemEntity;
onUnmute: () => void;
+ onSnooze?: () => void;
+ pending?: boolean;
}) {
const [preview] = useItemPreview(() => props.entity);
const name = () => {
@@ -78,6 +87,8 @@ function MutedItemPreviewRow(props: {
name={name()}
iconType={iconType()}
onUnmute={props.onUnmute}
+ onSnooze={props.onSnooze}
+ pending={props.pending}
/>
);
}
@@ -87,11 +98,13 @@ function MutedItemLayout(props: {
name: string;
iconType: EntityIconSelector;
onUnmute: () => void;
+ onSnooze?: () => void;
+ pending?: boolean;
}) {
const dmRecipientId = useMutedChannelDmRecipientId(() => props.item);
return (
- <div class="flex items-center gap-3 px-6 py-3.5 min-h-[60px]">
+ <div class="flex items-center gap-3 px-6 py-3.5 min-h-[60px] mobile:grid mobile:grid-cols-[1.25rem_minmax(0,1fr)] mobile:gap-y-1 mobile:px-4">
<div class="size-5 shrink-0 flex items-center justify-center">
<Show
when={dmRecipientId()}
@@ -109,14 +122,38 @@ function MutedItemLayout(props: {
)}
</Show>
</div>
- <div class="min-w-0 flex-1 truncate text-sm text-ink">{props.name}</div>
- <button
- type="button"
- class="shrink-0 text-sm text-ink-muted hover:text-ink"
- onClick={props.onUnmute}
- >
- Unmute
- </button>
+ <div class="min-w-0 flex-1 text-sm text-ink">
+ <div class="truncate" title={props.name}>
+ {props.name}
+ </div>
+ <Show when={props.item.snoozed_until}>
+ {(until) => (
+ <div class="text-xs text-ink-muted">
+ Until {formatSnoozeDeadline(until())}
+ </div>
+ )}
+ </Show>
+ </div>
+ <div class="flex shrink-0 items-center gap-3 mobile:col-start-2 mobile:gap-2">
+ <Show when={props.onSnooze}>
+ <button
+ type="button"
+ class="shrink-0 text-sm text-ink-muted hover:text-ink disabled:opacity-50 mobile:min-h-11 mobile:rounded-full mobile:bg-ink/5 mobile:px-3"
+ disabled={props.pending}
+ onClick={props.onSnooze}
+ >
+ {props.item.snoozed_until ? 'Change time' : 'Snooze instead'}
+ </button>
+ </Show>
+ <button
+ type="button"
+ class="shrink-0 text-sm text-ink-muted hover:text-ink disabled:opacity-50 mobile:min-h-11 mobile:rounded-full mobile:bg-ink/5 mobile:px-3"
+ onClick={props.onUnmute}
+ disabled={props.pending}
+ >
+ {props.item.snoozed_until ? 'Resume' : 'Unmute'}
+ </button>
+ </div>
</div>
);
}
diff --git a/apps/web/src/features/settings/Notifications.tsx b/apps/web/src/features/settings/Notifications.tsx
index 81463d7656..829351adf0 100644
--- a/apps/web/src/features/settings/Notifications.tsx
+++ b/apps/web/src/features/settings/Notifications.tsx
@@ -6,6 +6,7 @@ import {
NOTIFICATION_EVENT_GROUPS,
} from '@notifications/notification-event-catalog';
import { useNotificationSettings } from '@notifications/notification-settings';
+import { openSnoozeNotifications } from '@notifications/SnoozeNotificationsDialog';
import { queryReadyGate } from '@queries/gate';
import {
useNotificationTypePreferencesQuery,
@@ -16,7 +17,7 @@ import {
useUnmuteItemMutation,
} from '@queries/notification/unsubscribes';
import { ToggleSwitch } from '@ui';
-import { For, Show } from 'solid-js';
+import { For, getOwner, Show } from 'solid-js';
import { MutedItemRow } from './MutedItemRow';
import {
SettingsCard,
@@ -26,6 +27,7 @@ import {
} from './primitives';
export function Notifications() {
+ const dialogOwner = getOwner();
const analytics = useAnalytics();
const platformSettings = useNotificationSettings();
const preferencesQuery = useNotificationTypePreferencesQuery();
@@ -45,6 +47,10 @@ export function Notifications() {
? preferencesQuery.data.disabled_types
: []
);
+ const snoozedEntities = () =>
+ mutedEntities().filter((item) => item.snoozed_until);
+ const permanentlyMutedEntities = () =>
+ mutedEntities().filter((item) => !item.snoozed_until);
const isTypeEnabled = (type: string) => !disabledTypes().has(type);
@@ -147,13 +153,64 @@ export function Notifications() {
)}
</For>
+ <SettingsSection
+ title="Snoozed items"
+ description="Notifications pause until the time you choose. Items stay visible in your inbox."
+ >
+ <SettingsCard>
+ <Show when={mutedEntitiesQuery.isError}>
+ <SettingsRow label="Could not load snoozed items">
+ <button
+ type="button"
+ onClick={() => void mutedEntitiesQuery.refetch()}
+ >
+ Retry
+ </button>
+ </SettingsRow>
+ </Show>
+ <Show
+ when={
+ !mutedEntitiesQuery.isError && queryReadyGate(mutedEntitiesQuery)
+ }
+ fallback={
+ !mutedEntitiesQuery.isError && (
+ <SettingsRow label="Loading snoozed items…" />
+ )
+ }
+ >
+ <Show
+ when={snoozedEntities().length > 0}
+ fallback={
+ <SettingsRow
+ label="Nothing snoozed"
+ description="Right-click an item or use the command menu and choose Snooze notifications."
+ />
+ }
+ >
+ <For each={snoozedEntities()}>
+ {(item) => (
+ <MutedItemRow
+ item={item}
+ onUnmute={() => void unmuteEntity(item)}
+ onSnooze={() =>
+ openSnoozeNotifications([item], { owner: dialogOwner })
+ }
+ pending={unmuteItem.isPending}
+ />
+ )}
+ </For>
+ </Show>
+ </Show>
+ </SettingsCard>
+ </SettingsSection>
+
<SettingsSection
title="Muted items"
description="These items will not send you notifications."
>
<SettingsCard>
<Show
- when={mutedEntities().length > 0}
+ when={permanentlyMutedEntities().length > 0}
fallback={
<SettingsRow
label="Nothing muted"
@@ -161,11 +218,15 @@ export function Notifications() {
/>
}
>
- <For each={mutedEntities()}>
+ <For each={permanentlyMutedEntities()}>
{(item) => (
<MutedItemRow
item={item}
onUnmute={() => void unmuteEntity(item)}
+ onSnooze={() =>
+ openSnoozeNotifications([item], { owner: dialogOwner })
+ }
+ pending={unmuteItem.isPending}
/>
)}
</For>
diff --git a/apps/web/src/features/settings/SnoozeMobileDialog.test.tsx b/apps/web/src/features/settings/SnoozeMobileDialog.test.tsx
new file mode 100644
index 0000000000..dff2945a3c
--- /dev/null
+++ b/apps/web/src/features/settings/SnoozeMobileDialog.test.tsx
@@ -0,0 +1,120 @@
+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
+import { openSnoozeNotifications } from '@notifications/SnoozeNotificationsDialog';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@solidjs/testing-library';
+import { ImperativeDialogHost } from '@ui/components/ImperativeDialog';
+import { createSignal, getOwner } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const save = vi.hoisted(() => vi.fn(async () => {}));
+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => true }));
+vi.mock('@core/mobile/virtualKeyboard', () => ({
+ virtualKeyboardVisible: () => false,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: vi.fn() },
+}));
+vi.mock('@core/util/dateSearch/useDateSearch', () => ({
+ useDateSearch: () => () => [],
+}));
+vi.mock('@queries/notification/unsubscribes', () => ({
+ useMuteItemMutation: () => ({ mutateAsync: save }),
+}));
+
+beforeEach(() => {
+ save.mockClear();
+ vi.stubGlobal('scrollTo', vi.fn());
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+function tap(element: HTMLElement) {
+ fireEvent.pointerDown(element, { pointerType: 'touch', button: 0 });
+ fireEvent.pointerUp(element, { pointerType: 'touch', button: 0 });
+ fireEvent.click(element);
+}
+
+function setup() {
+ const [open, setOpen] = createSignal(true);
+ function SettingsActions() {
+ const owner = getOwner();
+ return (
+ <button
+ type="button"
+ onClick={() =>
+ openSnoozeNotifications(
+ [{ item_id: 'document-one', item_type: 'document' }],
+ { owner }
+ )
+ }
+ >
+ Change time
+ </button>
+ );
+ }
+ render(() => (
+ <>
+ <MobileDrawer
+ open={open()}
+ onOpenChange={setOpen}
+ closeOnOutsidePointerStrategy="pointerdown"
+ >
+ <MobileDrawer.Portal>
+ <MobileDrawer.Content aria-label="Settings">
+ <SettingsActions />
+ </MobileDrawer.Content>
+ </MobileDrawer.Portal>
+ </MobileDrawer>
+ <ImperativeDialogHost />
+ </>
+ ));
+ return { open };
+}
+
+describe('snooze pickers opened from mobile settings', () => {
+ it.each(['save', 'cancel'] as const)(
+ 'keeps settings open while changing time and after %s',
+ async (action) => {
+ const settings = setup();
+ tap(screen.getByRole('button', { name: 'Change time' }));
+ const picker = await screen.findByRole('dialog', {
+ name: 'Snooze notifications',
+ });
+ expect(settings.open()).toBe(true);
+ expect(picker.hasAttribute('data-corvu-drawer-content')).toBe(true);
+ tap(within(picker).getByRole('combobox'));
+ expect(settings.open()).toBe(true);
+ if (action === 'save') {
+ tap(within(picker).getByRole('option', { name: /For 30 minutes/ }));
+ await waitFor(() => expect(save).toHaveBeenCalledOnce());
+ } else {
+ tap(within(picker).getByRole('button', { name: 'Cancel' }));
+ expect(save).not.toHaveBeenCalled();
+ }
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'Snooze notifications' })
+ ).toBeNull()
+ );
+ expect(settings.open()).toBe(true);
+ expect(screen.getByRole('dialog', { name: 'Settings' })).toBeTruthy();
+ }
+ );
+});
diff --git a/apps/web/src/features/soup/createSoupEntityActions.ts b/apps/web/src/features/soup/createSoupEntityActions.ts
index 00e1424c4f..75c58f0cfd 100644
--- a/apps/web/src/features/soup/createSoupEntityActions.ts
+++ b/apps/web/src/features/soup/createSoupEntityActions.ts
@@ -343,6 +343,11 @@ export function createSoupEntityActions(): {
}
if (canExecuteAll(muteAction.canExecute)) {
+ middleItems.push({
+ id: 'snooze',
+ label: 'Snooze notifications…',
+ onClick: () => muteAction.snooze(entities),
+ });
const allMuted = entities.every((entity) => muteAction.isMuted(entity));
middleItems.push({
id: 'mute',
diff --git a/apps/web/src/lib/queries/notification/tests/unsubscribes.test.tsx b/apps/web/src/lib/queries/notification/tests/unsubscribes.test.tsx
new file mode 100644
index 0000000000..95a6263851
--- /dev/null
+++ b/apps/web/src/lib/queries/notification/tests/unsubscribes.test.tsx
@@ -0,0 +1,147 @@
+import { cleanup, render, waitFor } from '@solidjs/testing-library';
+import { focusManager, QueryClientProvider } from '@tanstack/solid-query';
+import { ok } from 'neverthrow';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { queryClient } from '../../client';
+import { notificationKeys } from '../keys';
+import {
+ useMutedEntitiesQuery,
+ useMuteItemMutation,
+ useUnmuteItemMutation,
+} from '../unsubscribes';
+
+const client = vi.hoisted(() => ({
+ unsubscribeItem: vi.fn(),
+ removeUnsubscribeItem: vi.fn(),
+ getUnsubscribes: vi.fn(),
+}));
+vi.mock('@service-notification/client', () => ({
+ notificationServiceClient: client,
+}));
+vi.mock('../../client', async () => {
+ const { QueryClient } = await import('@tanstack/solid-query');
+ return {
+ queryClient: new QueryClient({
+ defaultOptions: { mutations: { retry: false } },
+ }),
+ };
+});
+
+const item = { item_id: 'one', item_type: 'document' };
+const original = { ...item, snoozed_until: '2030-09-28T09:00:00.000Z' };
+const key = notificationKeys.unsubscribes.queryKey;
+
+function setup() {
+ let mute!: ReturnType<typeof useMuteItemMutation>;
+ let unmute!: ReturnType<typeof useUnmuteItemMutation>;
+ function Test() {
+ mute = useMuteItemMutation();
+ unmute = useUnmuteItemMutation();
+ return null;
+ }
+ render(() => (
+ <QueryClientProvider client={queryClient}>
+ <Test />
+ </QueryClientProvider>
+ ));
+ queryClient.setQueryData(key, [original]);
+ return { mute, unmute };
+}
+
+afterEach(() => {
+ cleanup();
+ queryClient.clear();
+ focusManager.setFocused(undefined);
+ vi.clearAllMocks();
+ vi.useRealTimers();
+});
+
+describe('snooze query refresh', () => {
+ function setupQuery() {
+ function Test() {
+ useMutedEntitiesQuery();
+ return null;
+ }
+ render(() => (
+ <QueryClientProvider client={queryClient}>
+ <Test />
+ </QueryClientProvider>
+ ));
+ }
+
+ it.each([
+ { items: [] },
+ { items: [item] },
+ { items: [original] },
+ { items: [{ ...item, snoozed_until: '2000-01-01T00:00:00.000Z' }] },
+ ])('does not poll: $items', async ({ items }) => {
+ vi.useFakeTimers();
+ client.getUnsubscribes.mockResolvedValue(ok({ data: items }));
+ setupQuery();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(client.getUnsubscribes).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect(client.getUnsubscribes).toHaveBeenCalledTimes(1);
+ });
+
+ it('refreshes expired snoozes when the window regains focus', async () => {
+ vi.useFakeTimers();
+ const until = new Date(Date.now() + 90_000).toISOString();
+ client.getUnsubscribes.mockImplementation(async () =>
+ ok({
+ data:
+ Date.parse(until) > Date.now()
+ ? [{ ...item, snoozed_until: until }]
+ : [],
+ })
+ );
+ setupQuery();
+ await vi.advanceTimersByTimeAsync(90_100);
+ expect(client.getUnsubscribes).toHaveBeenCalledTimes(1);
+ focusManager.setFocused(false);
+ focusManager.setFocused(true);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(client.getUnsubscribes).toHaveBeenCalledTimes(2);
+ expect(queryClient.getQueryData(key)).toEqual([]);
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect(client.getUnsubscribes).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('item snooze mutations', () => {
+ it('replaces a cached deadline and sends it to the server', async () => {
+ client.unsubscribeItem.mockResolvedValueOnce(ok({}));
+ const { mute } = setup();
+ const updated = { ...item, snoozed_until: '2030-10-01T09:00:00.000Z' };
+ await mute.mutateAsync(updated);
+ expect(client.unsubscribeItem).toHaveBeenCalledWith(updated);
+ expect(queryClient.getQueryData(key)).toEqual([updated]);
+ });
+
+ it('restores the previous deadline when rescheduling fails', async () => {
+ let reject!: (error: Error) => void;
+ client.unsubscribeItem.mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail;
+ })
+ );
+ const { mute } = setup();
+ const updated = { ...item, snoozed_until: '2030-10-01T09:00:00.000Z' };
+ const result = mute.mutateAsync(updated);
+ const rejected = expect(result).rejects.toThrow('offline');
+ await waitFor(() =>
+ expect(queryClient.getQueryData(key)).toEqual([updated])
+ );
+ reject(new Error('offline'));
+ await rejected;
+ expect(queryClient.getQueryData(key)).toEqual([original]);
+ });
+
+ it('restores the deadline when an early resume fails, even from a bare entity reference', async () => {
+ client.removeUnsubscribeItem.mockRejectedValueOnce(new Error('offline'));
+ const { unmute } = setup();
+ await expect(unmute.mutateAsync(item)).rejects.toThrow('offline');
+ expect(queryClient.getQueryData(key)).toEqual([original]);
+ });
+});
diff --git a/apps/web/src/lib/queries/notification/unsubscribes.ts b/apps/web/src/lib/queries/notification/unsubscribes.ts
index bcf0cd65d2..b8c5f65128 100644
--- a/apps/web/src/lib/queries/notification/unsubscribes.ts
+++ b/apps/web/src/lib/queries/notification/unsubscribes.ts
@@ -35,6 +35,7 @@ export function useMutedEntitiesQuery(args?: { limit?: number }) {
initialPageParam: { limit },
staleTime: 1000 * 60 * 5,
gcTime: 1000 * 60 * 10,
+ refetchOnWindowFocus: 'always',
}));
}
@@ -66,9 +67,10 @@ function updateUnsubscribes(
}
function addUnsubscribe(item: UserUnsubscribe) {
- updateUnsubscribes((prev) =>
- prev.some((entry) => sameMuteItem(entry, item)) ? prev : [...prev, item]
- );
+ updateUnsubscribes((prev) => [
+ ...prev.filter((entry) => !sameMuteItem(entry, item)),
+ item,
+ ]);
}
function removeUnsubscribe(item: UserUnsubscribe) {
@@ -100,9 +102,16 @@ export function useMuteItemMutation() {
},
onMutate: async (item) => {
await cancelUnsubscribesFetch();
+ const previous = queryClient
+ .getQueryData<UserUnsubscribe[]>(notificationKeys.unsubscribes.queryKey)
+ ?.find((entry) => sameMuteItem(entry, item));
addUnsubscribe(item);
+ return { previous };
+ },
+ onError: (_error, item, context) => {
+ if (context?.previous) addUnsubscribe(context.previous);
+ else removeUnsubscribe(item);
},
- onError: (_error, item) => removeUnsubscribe(item),
onSettled: () => {
void invalidateUnsubscribesWhenIdle();
},
@@ -119,9 +128,15 @@ export function useUnmuteItemMutation() {
},
onMutate: async (item) => {
await cancelUnsubscribesFetch();
+ const previous = queryClient
+ .getQueryData<UserUnsubscribe[]>(notificationKeys.unsubscribes.queryKey)
+ ?.find((entry) => sameMuteItem(entry, item));
removeUnsubscribe(item);
+ return { previous };
+ },
+ onError: (_error, _item, context) => {
+ if (context?.previous) addUnsubscribe(context.previous);
},
- onError: (_error, item) => addUnsubscribe(item),
onSettled: () => {
void invalidateUnsubscribesWhenIdle();
},
diff --git a/apps/web/src/lib/service-clients/service-notification/client.ts b/apps/web/src/lib/service-clients/service-notification/client.ts
index 9a9006a822..301522b8c2 100644
--- a/apps/web/src/lib/service-clients/service-notification/client.ts
+++ b/apps/web/src/lib/service-clients/service-notification/client.ts
@@ -236,9 +236,12 @@ export const notificationServiceClient = {
})
).map((result) => ({ data: result }));
},
- async unsubscribeItem(args: WithItem) {
+ async unsubscribeItem(args: WithItem & { snoozed_until?: string | null }) {
+ const query = args.snoozed_until
+ ? `?snoozed_until=${encodeURIComponent(args.snoozed_until)}`
+ : '';
return notificationFetch<{}>(
- `/unsubscribe/item/${args.item_type}/${args.item_id}`,
+ `/unsubscribe/item/${encodeURIComponent(args.item_type)}/${encodeURIComponent(args.item_id)}${query}`,
{
method: 'POST',
}
@@ -246,7 +249,7 @@ export const notificationServiceClient = {
},
async removeUnsubscribeItem(args: WithItem) {
return notificationFetch<{}>(
- `/unsubscribe/item/${args.item_type}/${args.item_id}`,
+ `/unsubscribe/item/${encodeURIComponent(args.item_type)}/${encodeURIComponent(args.item_id)}`,
{
method: 'DELETE',
}
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
index d235d2f668..3985106b6a 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
@@ -214,5 +214,7 @@ export * from './taskAssignedMetadata';
export * from './taskAssignedMetadataSenderProfilePictureUrl';
export * from './taskAssignedMetadataSubType';
export * from './taskAssignedMetadataTaskName';
+export * from './unsubscribeItemParams';
export * from './unsubscribeItemPathParams';
export * from './userUnsubscribe';
+export * from './userUnsubscribeSnoozedUntil';
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/unsubscribeItemParams.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/unsubscribeItemParams.ts
new file mode 100644
index 0000000000..456f0f37f5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/unsubscribeItemParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type UnsubscribeItemParams = {
+ /**
+ * A future resume time. Omit to mute indefinitely.
+ */
+ snoozed_until?: string | null;
+};
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/unsubscribeItemPathParams.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/unsubscribeItemPathParams.ts
index 692fcbcfaa..e2137310e8 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/unsubscribeItemPathParams.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/unsubscribeItemPathParams.ts
@@ -4,8 +4,9 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
+import type { EntityType } from './entityType';
export interface UnsubscribeItemPathParams {
item_id: string;
- item_type: string;
+ item_type: EntityType;
}
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/userUnsubscribe.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/userUnsubscribe.ts
index bb0eb774ce..d2792115ef 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/userUnsubscribe.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/userUnsubscribe.ts
@@ -4,10 +4,13 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
+import type { UserUnsubscribeSnoozedUntil } from './userUnsubscribeSnoozedUntil';
export interface UserUnsubscribe {
/** The item id */
item_id: string;
/** The item type */
item_type: string;
+ /** None for permanent mutes; notifications resume automatically at this deadline. */
+ snoozed_until?: UserUnsubscribeSnoozedUntil;
}
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/userUnsubscribeSnoozedUntil.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/userUnsubscribeSnoozedUntil.ts
new file mode 100644
index 0000000000..07b02c983e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/userUnsubscribeSnoozedUntil.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * None for permanent mutes; notifications resume automatically at this deadline.
+ */
+export type UserUnsubscribeSnoozedUntil = string | null;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
index 2aabdf8af9..ccc5d11811 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
@@ -21,6 +21,12 @@ export const healthHandlerResponse = zod
export const getUnsubscribesResponseItem = zod.object({
item_id: zod.string().describe('The item id'),
item_type: zod.string().describe('The item type'),
+ snoozed_until: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'None for permanent mutes; notifications resume automatically at this deadline.'
+ ),
});
export const getUnsubscribesResponse = zod.array(getUnsubscribesResponseItem);
@@ -37,10 +43,37 @@ export const unsubscribeEmailResponse = zod
* @summary Unsubscribes a user from a given item for notifications.
*/
export const unsubscribeItemParams = zod.object({
- item_type: zod.string(),
+ item_type: zod.enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'calendar_event',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ 'reminder',
+ 'skill',
+ 'agent_session',
+ 'scheduled_action',
+ 'initiative',
+ ]),
item_id: zod.string(),
});
+export const unsubscribeItemQueryParams = zod.object({
+ snoozed_until: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('A future resume time. Omit to mute indefinitely.'),
+});
+
export const unsubscribeItemResponse = zod
.object({})
.describe(
@@ -51,7 +84,27 @@ export const unsubscribeItemResponse = zod
* @summary Removes a unsubscribe item for a user.
*/
export const removeUnsubscribeItemParams = zod.object({
- item_type: zod.string(),
+ item_type: zod.enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'calendar_event',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ 'reminder',
+ 'skill',
+ 'agent_session',
+ 'scheduled_action',
+ 'initiative',
+ ]),
item_id: zod.string(),
});
diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.json
index f58d433a39..4684a5b91f 100644
--- a/apps/web/src/lib/service-clients/service-notification/openapi.json
+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json
@@ -121,7 +121,7 @@
"in": "path",
"required": true,
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/EntityType"
}
},
{
@@ -131,6 +131,16 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "snoozed_until",
+ "in": "query",
+ "description": "A future resume time. Omit to mute indefinitely.",
+ "required": false,
+ "schema": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ }
}
],
"responses": {
@@ -144,6 +154,16 @@
}
}
},
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
@@ -176,7 +196,7 @@
"in": "path",
"required": true,
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/EntityType"
}
},
{
@@ -2849,7 +2869,7 @@
"type": "string"
},
"item_type": {
- "type": "string"
+ "$ref": "#/components/schemas/EntityType"
}
}
},
@@ -2864,6 +2884,11 @@
"item_type": {
"type": "string",
"description": "The item type"
+ },
+ "snoozed_until": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "None for permanent mutes; notifications resume automatically at this deadline."
}
}
}
diff --git a/crates/macro_db_client/migrations/20260926043014_entity_notification_snooze.sql b/crates/macro_db_client/migrations/20260926043014_entity_notification_snooze.sql
new file mode 100644
index 0000000000..73037c0687
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260926043014_entity_notification_snooze.sql
@@ -0,0 +1,6 @@
+-- Add migration script here
+ALTER TABLE user_notification_item_unsubscribe
+ ADD COLUMN snoozed_until TIMESTAMPTZ;
+
+COMMENT ON COLUMN user_notification_item_unsubscribe.snoozed_until IS
+ 'NULL means muted indefinitely; a future deadline pauses notifications until then.';
diff --git a/crates/model_notifications/src/unsubscribe.rs b/crates/model_notifications/src/unsubscribe.rs
index fa29ad5e60..58db56b1a6 100644
--- a/crates/model_notifications/src/unsubscribe.rs
+++ b/crates/model_notifications/src/unsubscribe.rs
@@ -8,4 +8,7 @@ pub struct UserUnsubscribe {
pub item_id: String,
/// The item type
pub item_type: String,
+ /// None for permanent mutes; notifications resume automatically at this deadline.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub snoozed_until: Option<chrono::DateTime<chrono::Utc>>,
}
diff --git a/crates/notification/fixtures/legacy_item_preferences.sql b/crates/notification/fixtures/legacy_item_preferences.sql
new file mode 100644
index 0000000000..d00432c7ec
--- /dev/null
+++ b/crates/notification/fixtures/legacy_item_preferences.sql
@@ -0,0 +1,13 @@
+INSERT INTO user_notification_item_unsubscribe (user_id, item_id, item_type, snoozed_until)
+VALUES
+ ('macro|[email protected]', 'document-snoozed', 'document', NOW() + INTERVAL '1 hour'),
+ ('macro|[email protected]', 'channel-muted', 'channel', NULL),
+ ('macro|[email protected]', 'email-alias', 'email', NULL),
+ ('macro|[email protected]', 'thread-alias', 'thread', NULL),
+ ('macro|[email protected]', 'foreign-alias', 'foreign', NULL),
+ ('macro|[email protected]', 'unknown-note', 'note', NULL),
+ ('macro|[email protected]', 'unknown-task', 'task', NULL),
+ ('macro|[email protected]', 'unknown-dm', 'dm', NULL),
+ ('macro|[email protected]', 'unknown-thread', 'channel_thread', NULL),
+ ('macro|[email protected]', 'expired', 'document', NOW() - INTERVAL '1 hour'),
+ ('macro|[email protected]', 'other-user', 'document', NULL);
diff --git a/crates/notification/src/domain.rs b/crates/notification/src/domain.rs
index 901e625fda..db2c301ff3 100644
--- a/crates/notification/src/domain.rs
+++ b/crates/notification/src/domain.rs
@@ -1,3 +1,4 @@
+pub mod item_preferences;
pub mod models;
pub mod ports;
pub mod service;
diff --git a/crates/notification/src/domain/item_preferences.rs b/crates/notification/src/domain/item_preferences.rs
new file mode 100644
index 0000000000..127883f431
--- /dev/null
+++ b/crates/notification/src/domain/item_preferences.rs
@@ -0,0 +1,95 @@
+//! User-owned notification mute and snooze preferences.
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use rootcause::Report;
+use std::future::Future;
+
+/// An item whose notifications are muted, indefinitely or until a deadline.
+#[derive(Debug, Clone)]
+pub struct ItemNotificationPreference {
+ /// The notification's primary entity.
+ pub entity: Entity<'static>,
+ /// None denotes a permanent mute.
+ pub snoozed_until: Option<DateTime<Utc>>,
+}
+
+/// Persistence of preferences scoped to their authenticated owner.
+pub trait ItemNotificationPreferenceRepository: Send + Sync {
+ /// Return only permanent mutes and unexpired snoozes.
+ fn list(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<ItemNotificationPreference>, Report>> + Send;
+ /// Replace this user's preference for an item.
+ fn set(
+ &self,
+ user: MacroUserIdStr<'_>,
+ entity: Entity<'_>,
+ until: Option<DateTime<Utc>>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+ /// Resume notifications for this user's item.
+ fn remove(
+ &self,
+ user: MacroUserIdStr<'_>,
+ entity: Entity<'_>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
+
+/// A rejected preference change.
+#[derive(Debug, thiserror::Error)]
+pub enum ItemNotificationPreferenceError {
+ /// Snoozes must end in the future.
+ #[error("Choose a snooze time in the future")]
+ InvalidDeadline,
+ /// Persistence failed.
+ #[error("Could not update notification preference: {0}")]
+ Repository(Report),
+}
+
+/// Manages personal preferences; these never change another user's delivery or entity access.
+#[derive(Clone)]
+pub struct ItemNotificationPreferenceService<R> {
+ repository: R,
+}
+
+impl<R: ItemNotificationPreferenceRepository> ItemNotificationPreferenceService<R> {
+ /// Construct with the owning notification repository.
+ pub fn new(repository: R) -> Self {
+ Self { repository }
+ }
+
+ /// List the authenticated user's active preferences.
+ pub async fn list(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> Result<Vec<ItemNotificationPreference>, Report> {
+ self.repository.list(user).await
+ }
+
+ /// Replace a mute or snooze. Only the authenticated user's preference can change.
+ pub async fn set(
+ &self,
+ user: MacroUserIdStr<'_>,
+ entity: Entity<'_>,
+ until: Option<DateTime<Utc>>,
+ now: DateTime<Utc>,
+ ) -> Result<(), ItemNotificationPreferenceError> {
+ if until.is_some_and(|deadline| deadline <= now) {
+ return Err(ItemNotificationPreferenceError::InvalidDeadline);
+ }
+ self.repository
+ .set(user, entity, until)
+ .await
+ .map_err(ItemNotificationPreferenceError::Repository)
+ }
+
+ /// Resume delivery without modifying existing notifications or read state.
+ pub async fn remove(&self, user: MacroUserIdStr<'_>, entity: Entity<'_>) -> Result<(), Report> {
+ self.repository.remove(user, entity).await
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/notification/src/domain/item_preferences/test.rs b/crates/notification/src/domain/item_preferences/test.rs
new file mode 100644
index 0000000000..019e254369
--- /dev/null
+++ b/crates/notification/src/domain/item_preferences/test.rs
@@ -0,0 +1,68 @@
+use super::*;
+use chrono::Duration;
+use model_entity::EntityType;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct FakeRepository {
+ writes: Mutex<Vec<(String, Option<DateTime<Utc>>)>>,
+}
+
+impl ItemNotificationPreferenceRepository for FakeRepository {
+ async fn list(&self, _: MacroUserIdStr<'_>) -> Result<Vec<ItemNotificationPreference>, Report> {
+ Ok(vec![])
+ }
+ async fn set(
+ &self,
+ user: MacroUserIdStr<'_>,
+ _: Entity<'_>,
+ until: Option<DateTime<Utc>>,
+ ) -> Result<(), Report> {
+ self.writes.lock().unwrap().push((user.to_string(), until));
+ Ok(())
+ }
+ async fn remove(&self, _: MacroUserIdStr<'_>, _: Entity<'_>) -> Result<(), Report> {
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn only_future_deadlines_are_saved_for_the_authenticated_user() {
+ let service = ItemNotificationPreferenceService::new(FakeRepository::default());
+ let now = Utc::now();
+ for until in [now - Duration::seconds(1), now] {
+ let result = service
+ .set(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ EntityType::Document.with_entity_str("document"),
+ Some(until),
+ now,
+ )
+ .await;
+ assert!(matches!(
+ result,
+ Err(ItemNotificationPreferenceError::InvalidDeadline)
+ ));
+ }
+ assert!(service.repository.writes.lock().unwrap().is_empty());
+ for until in [Some(now + Duration::hours(1)), None] {
+ service
+ .set(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ EntityType::Document.with_entity_str("document"),
+ until,
+ now,
+ )
+ .await
+ .unwrap();
+ }
+ let writes = service.repository.writes.lock().unwrap();
+ assert_eq!(writes.len(), 2);
+ assert!(
+ writes
+ .iter()
+ .all(|(user, _)| user == "macro|[email protected]")
+ );
+ assert!(writes[0].1.is_some());
+ assert!(writes[1].1.is_none());
+}
diff --git a/crates/notification/src/outbound.rs b/crates/notification/src/outbound.rs
index dd5401903a..0c376c61b8 100644
--- a/crates/notification/src/outbound.rs
+++ b/crates/notification/src/outbound.rs
@@ -11,6 +11,7 @@ mod entity_notifications;
pub mod fanout_notification_realtime;
/// Realtime notification fanout across multiple delivery adapters.
pub mod fanout_realtime;
+pub mod item_preferences;
/// Kafka-backed notification status update publication.
pub mod kafka_notification_realtime;
/// Kafka-backed realtime notification delivery.
diff --git a/crates/notification/src/outbound/item_preferences.rs b/crates/notification/src/outbound/item_preferences.rs
new file mode 100644
index 0000000000..3418482187
--- /dev/null
+++ b/crates/notification/src/outbound/item_preferences.rs
@@ -0,0 +1,85 @@
+//! Postgres persistence for user-owned item notification preferences.
+
+use crate::domain::item_preferences::{
+ ItemNotificationPreference, ItemNotificationPreferenceRepository,
+};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+use rootcause::Report;
+use sqlx::PgPool;
+
+/// Adapter for the notification domain's item unsubscribe table.
+#[derive(Clone)]
+pub struct PgItemNotificationPreferenceRepository(pub PgPool);
+
+impl ItemNotificationPreferenceRepository for PgItemNotificationPreferenceRepository {
+ async fn list(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> Result<Vec<ItemNotificationPreference>, Report> {
+ let rows = sqlx::query!(
+ r#"SELECT item_id, item_type, snoozed_until
+ FROM user_notification_item_unsubscribe
+ WHERE user_id = $1 AND (snoozed_until IS NULL OR snoozed_until > NOW())
+ ORDER BY snoozed_until NULLS LAST, item_id"#,
+ user.as_ref()
+ )
+ .fetch_all(&self.0)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| {
+ let entity_type: EntityType = match row.item_type.as_str() {
+ "email" | "thread" => EntityType::EmailThread,
+ "foreign" => EntityType::ForeignEntity,
+ value => match value.parse() {
+ Ok(entity_type) => entity_type,
+ Err(error) => {
+ tracing::warn!(
+ item_type = value,
+ ?error,
+ "Skipping unknown notification preference type"
+ );
+ return None;
+ }
+ },
+ };
+ Some(ItemNotificationPreference {
+ entity: entity_type.with_entity_string(row.item_id),
+ snoozed_until: row.snoozed_until,
+ })
+ })
+ .collect())
+ }
+
+ async fn set(
+ &self,
+ user: MacroUserIdStr<'_>,
+ entity: Entity<'_>,
+ until: Option<DateTime<Utc>>,
+ ) -> Result<(), Report> {
+ sqlx::query!(
+ r#"INSERT INTO user_notification_item_unsubscribe (user_id, item_id, item_type, snoozed_until)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (user_id, item_id) DO UPDATE
+ SET item_type = EXCLUDED.item_type, snoozed_until = EXCLUDED.snoozed_until"#,
+ user.as_ref(), entity.entity_id.as_ref(), entity.entity_type.as_ref(), until
+ ).execute(&self.0).await?;
+ Ok(())
+ }
+
+ async fn remove(&self, user: MacroUserIdStr<'_>, entity: Entity<'_>) -> Result<(), Report> {
+ sqlx::query!(
+ "DELETE FROM user_notification_item_unsubscribe WHERE user_id = $1 AND item_id = $2",
+ user.as_ref(),
+ entity.entity_id.as_ref()
+ )
+ .execute(&self.0)
+ .await?;
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/notification/src/outbound/item_preferences/test.rs b/crates/notification/src/outbound/item_preferences/test.rs
new file mode 100644
index 0000000000..41e31e23ad
--- /dev/null
+++ b/crates/notification/src/outbound/item_preferences/test.rs
@@ -0,0 +1,95 @@
+use super::*;
+use crate::outbound::repository::NotificationDbOps;
+use chrono::Duration;
+use cowlike::CowLike;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+fn user(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str(&format!("macro|{email}@example.com"))
+ .unwrap()
+ .into_owned()
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("legacy_item_preferences"))
+)]
+async fn lists_supported_preferences_despite_unknown_legacy_types(pool: PgPool) {
+ let repo = PgItemNotificationPreferenceRepository(pool);
+ let listed = repo.list(user("alice")).await.unwrap();
+ let preferences: Vec<_> = listed
+ .iter()
+ .map(|item| (item.entity.entity_id.as_ref(), item.entity.entity_type))
+ .collect();
+ assert_eq!(
+ preferences,
+ vec![
+ ("document-snoozed", EntityType::Document),
+ ("channel-muted", EntityType::Channel),
+ ("email-alias", EntityType::EmailThread),
+ ("foreign-alias", EntityType::ForeignEntity),
+ ("thread-alias", EntityType::EmailThread),
+ ]
+ );
+ assert!(listed[0].snoozed_until.is_some());
+ assert!(listed[1..].iter().all(|item| item.snoozed_until.is_none()));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn snooze_expiry_replacement_and_owner_isolation(pool: PgPool) {
+ let repo = PgItemNotificationPreferenceRepository(pool.clone());
+ let entity = || EntityType::Document.with_entity_str("document-one");
+ let future = Utc::now() + Duration::hours(1);
+ repo.set(user("alice"), entity(), Some(future))
+ .await
+ .unwrap();
+ repo.set(user("bob"), entity(), None).await.unwrap();
+
+ let listed = repo.list(user("alice")).await.unwrap();
+ assert_eq!(listed.len(), 1);
+ assert_eq!(
+ listed[0].snoozed_until.unwrap().timestamp(),
+ future.timestamp()
+ );
+ let recipients = [user("alice"), user("bob"), user("carol")];
+ let muted = pool
+ .get_unsubscribed_users("document-one", &recipients)
+ .await
+ .unwrap();
+ assert_eq!(muted.len(), 2);
+ assert!(!muted.contains(&user("carol")));
+
+ // Simulate the clock moving past expiry without requiring a running client or cleanup job.
+ repo.set(
+ user("alice"),
+ entity(),
+ Some(Utc::now() - Duration::seconds(1)),
+ )
+ .await
+ .unwrap();
+ assert!(repo.list(user("alice")).await.unwrap().is_empty());
+ let muted = pool
+ .get_unsubscribed_users("document-one", &recipients)
+ .await
+ .unwrap();
+ assert!(!muted.contains(&user("alice")));
+ assert!(muted.contains(&user("bob")));
+
+ repo.set(user("alice"), entity(), None).await.unwrap();
+ assert!(
+ repo.list(user("alice")).await.unwrap()[0]
+ .snoozed_until
+ .is_none()
+ );
+ repo.set(user("alice"), entity(), Some(future))
+ .await
+ .unwrap();
+ assert!(
+ repo.list(user("alice")).await.unwrap()[0]
+ .snoozed_until
+ .is_some()
+ );
+ repo.remove(user("alice"), entity()).await.unwrap();
+ assert!(repo.list(user("alice")).await.unwrap().is_empty());
+ assert_eq!(repo.list(user("bob")).await.unwrap().len(), 1);
+}
diff --git a/crates/notification/src/outbound/repository.rs b/crates/notification/src/outbound/repository.rs
index 73f1afd3f3..fdda7cb4c7 100644
--- a/crates/notification/src/outbound/repository.rs
+++ b/crates/notification/src/outbound/repository.rs
@@ -603,6 +603,7 @@ impl NotificationDbOps for PgPool {
r#"
SELECT user_id FROM user_notification_item_unsubscribe
WHERE item_id = $1 AND user_id = ANY($2)
+ AND (snoozed_until IS NULL OR snoozed_until > NOW())
"#,
item_id,
&ids
diff --git a/crates/notification_db_client/src/unsubscribe/get.rs b/crates/notification_db_client/src/unsubscribe/get.rs
index 645a64c062..75eb91bb2f 100644
--- a/crates/notification_db_client/src/unsubscribe/get.rs
+++ b/crates/notification_db_client/src/unsubscribe/get.rs
@@ -11,17 +11,20 @@ pub async fn get_user_unsubscribes(
SELECT
'item' as unsubscribe_type,
unsubscribe_item.item_id as "item_id!",
- unsubscribe_item.item_type as "item_type!"
+ unsubscribe_item.item_type as "item_type!",
+ unsubscribe_item.snoozed_until
FROM
user_notification_item_unsubscribe unsubscribe_item
WHERE
unsubscribe_item.user_id = $1
+ AND (snoozed_until IS NULL OR snoozed_until > NOW())
"#,
user_id
)
.map(|row| UserUnsubscribe {
item_id: row.item_id,
item_type: row.item_type,
+ snoozed_until: row.snoozed_until,
})
.fetch_all(db)
.await?;
diff --git a/crates/notification_db_client/src/unsubscribe/item.rs b/crates/notification_db_client/src/unsubscribe/item.rs
index 99c87fbc6b..6c70f5dbd9 100644
--- a/crates/notification_db_client/src/unsubscribe/item.rs
+++ b/crates/notification_db_client/src/unsubscribe/item.rs
@@ -9,6 +9,7 @@ pub async fn get_unsubscribed_item_users(
SELECT u.user_id
FROM user_notification_item_unsubscribe u
WHERE u.item_id = $1
+ AND (u.snoozed_until IS NULL OR u.snoozed_until > NOW())
"#,
item_id
)
@@ -31,7 +32,7 @@ pub async fn upsert_unsubscribed_item_user(
r#"
INSERT INTO user_notification_item_unsubscribe (user_id, item_id, item_type)
VALUES ($1, $2, $3)
- ON CONFLICT (user_id, item_id) DO NOTHING
+ ON CONFLICT (user_id, item_id) DO UPDATE SET snoozed_until = NULL
"#,
user_id,
item_id,
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 1fd22ab566..f0be58fee2 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1267,6 +1267,46 @@ or remove the signature.
The inbox row's trash icon removes the inbox through the existing confirmation;
it is separate from the signature editor's close control.
+### Notification snoozes
+
+Open **Settings → Notifications** to see **Snoozed items** and their local resume
+times. **Change time** opens the same searchable time picker used by entity
+actions; **Resume** cancels a snooze immediately. Permanent mutes appear separately
+under **Muted items**, with **Snooze instead** to replace one with a timed pause.
+
+The Chat detail pane also supplies these commands for its current channel or DM;
+focus the conversation before opening the command menu.
+
+To snooze an entity, right-click its row (long-press on mobile) and choose
+**Snooze notifications…**, or select/open the entity and search for that command
+in Cmd/Ctrl+K. Multi-selection applies the chosen deadline to all selected items.
+Use arrow keys and Enter, click a preset, or type a future date/time such as
+`2h` or `tomorrow 10am`. The next morning means the next local 9 AM; the weekend
+preset resumes on Monday at 9 AM. The picker displays the exact local date and
+time before saving. Escape closes the picker; before choosing a time, it makes
+no changes.
+
+Snoozing pauses notifications only: it does not hide, archive, mark read, or mark
+done. Channel message/thread rows target their parent channel, matching mute.
+The server enforces expiration even when no client is open. Displayed snooze
+state refreshes when the window regains focus or a mute/snooze changes; the
+client does not poll. A failed save keeps the picker open for retry; a successful
+save appears in notification settings.
+If only some selected items save, the picker shows the saved count and retries
+only the remaining items. Closing it keeps any snoozes already saved.
+
+On phones, long-press opens the entity actions drawer. The snooze time picker
+uses the same responsive `Dialog`, width, and `CommandMenuShell` as Cmd/Ctrl+K,
+with larger touch targets and tap instructions. Swipe the preset list when the
+viewport is short. In **More views → Settings → Notifications**, item names and
+deadlines sit above **Change time** and **Resume**. Saving or cancelling a picker
+returns to the settings sheet. Start new snoozes from an entity's actions or
+Cmd/Ctrl+K; Settings manages existing snoozes and mutes.
+
+Design references: [Slack notification pause/resume](https://slack.com/help/articles/214908388-Pause-your-Slack-notifications)
+and [Superhuman's keyboard-driven Remind Me picker](https://new.superhuman.com/remind-me-29124).
+Macro applies the temporary pause per entity and keeps the entity visible.
+
### Team membership
Team membership has no size cap, including free teams. Invitations and domain
diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.ts
index f00fa36080..5f62a8d6ed 100644
--- a/packages/sdk/generated/notification/types.gen.ts
+++ b/packages/sdk/generated/notification/types.gen.ts
@@ -1201,7 +1201,7 @@ export type TaskAssignedMetadata = {
export type UnsubscribeItemPathParams = {
item_id: string;
- item_type: string;
+ item_type: EntityType;
};
export type UserUnsubscribe = {
@@ -1213,6 +1213,10 @@ export type UserUnsubscribe = {
* The item type
*/
item_type: string;
+ /**
+ * None for permanent mutes; notifications resume automatically at this deadline.
+ */
+ snoozed_until?: string | null;
};
export type HealthHandlerData = {
@@ -1274,7 +1278,7 @@ export type UnsubscribeEmailResponse = UnsubscribeEmailResponses[keyof Unsubscri
export type RemoveUnsubscribeItemData = {
body?: never;
path: {
- item_type: string;
+ item_type: EntityType;
item_id: string;
};
query?: never;
@@ -1297,14 +1301,20 @@ export type RemoveUnsubscribeItemResponse = RemoveUnsubscribeItemResponses[keyof
export type UnsubscribeItemData = {
body?: never;
path: {
- item_type: string;
+ item_type: EntityType;
item_id: string;
};
- query?: never;
+ query?: {
+ /**
+ * A future resume time. Omit to mute indefinitely.
+ */
+ snoozed_until?: string | null;
+ };
url: '/unsubscribe/item/{item_type}/{item_id}';
};
export type UnsubscribeItemErrors = {
+ 400: ErrorResponse;
401: ErrorResponse;
500: ErrorResponse;
};
diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.json
index f58d433a39..4684a5b91f 100644
--- a/packages/sdk/specs/notification.json
+++ b/packages/sdk/specs/notification.json
@@ -121,7 +121,7 @@
"in": "path",
"required": true,
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/EntityType"
}
},
{
@@ -131,6 +131,16 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "snoozed_until",
+ "in": "query",
+ "description": "A future resume time. Omit to mute indefinitely.",
+ "required": false,
+ "schema": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ }
}
],
"responses": {
@@ -144,6 +154,16 @@
}
}
},
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
@@ -176,7 +196,7 @@
"in": "path",
"required": true,
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/EntityType"
}
},
{
@@ -2849,7 +2869,7 @@
"type": "string"
},
"item_type": {
- "type": "string"
+ "$ref": "#/components/schemas/EntityType"
}
}
},
@@ -2864,6 +2884,11 @@
"item_type": {
"type": "string",
"description": "The item type"
+ },
+ "snoozed_until": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "None for permanent mutes; notifications resume automatically at this deadline."
}
}
}
diff --git a/services/notification_service/src/api/context.rs b/services/notification_service/src/api/context.rs
index 8b77912ed1..5698aa234e 100644
--- a/services/notification_service/src/api/context.rs
+++ b/services/notification_service/src/api/context.rs
@@ -8,9 +8,14 @@ use sqlx::PgPool;
use std::sync::Arc;
pub(crate) type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
+pub(crate) type ItemPreferences =
+ notification::domain::item_preferences::ItemNotificationPreferenceService<
+ notification::outbound::item_preferences::PgItemNotificationPreferenceRepository,
+ >;
#[derive(Clone, FromRef)]
pub struct ApiContext {
+ pub item_preferences: ItemPreferences,
pub db: PgPool,
pub sns_client: Arc<sns_client::SNS>,
pub config: Arc<Config>,
diff --git a/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs b/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
index 1eda899745..22e6f113d2 100644
--- a/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
+++ b/services/notification_service/src/api/unsubscribe/get_unsubscribes.rs
@@ -26,21 +26,28 @@ pub async fn handler(
State(ctx): State<ApiContext>,
user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Response, Response> {
- let unsubscribe_items = notification_db_client::unsubscribe::get::get_user_unsubscribes(
- &ctx.db,
- &user.authorization.user.user_context.user_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to unsubscribe item");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to unsubscribe item".into(),
- }),
- )
- .into_response()
- })?;
+ let unsubscribe_items = ctx
+ .item_preferences
+ .list(user.authorization.user.macro_user_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to unsubscribe item");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to unsubscribe item".into(),
+ }),
+ )
+ .into_response()
+ })?;
- Ok((StatusCode::OK, Json(unsubscribe_items)).into_response())
+ let items: Vec<UserUnsubscribe> = unsubscribe_items
+ .into_iter()
+ .map(|item| UserUnsubscribe {
+ item_id: item.entity.entity_id.into_owned(),
+ item_type: item.entity.entity_type.to_string(),
+ snoozed_until: item.snoozed_until,
+ })
+ .collect();
+ Ok((StatusCode::OK, Json(items)).into_response())
}
diff --git a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
index c627313269..ad51a4acfe 100644
--- a/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
+++ b/services/notification_service/src/api/unsubscribe/remove_unsubscribe_item.rs
@@ -29,22 +29,22 @@ pub async fn handler(
user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,
) -> Result<Response, Response> {
- notification_db_client::unsubscribe::item::remove_unsubscribed_item_user(
- &ctx.db,
- &user.authorization.user.user_context.user_id,
- &item_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to remove unsubscribe item");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to remove unsubscribe item".into(),
- }),
+ ctx.item_preferences
+ .remove(
+ user.authorization.user.macro_user_id,
+ item_type.with_entity_string(item_id),
)
- .into_response()
- })?;
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to remove unsubscribe item");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to remove unsubscribe item".into(),
+ }),
+ )
+ .into_response()
+ })?;
Ok((StatusCode::OK, Json(EmptyResponse {})).into_response())
}
diff --git a/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs b/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
index de2fae2018..d48ea4be04 100644
--- a/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
+++ b/services/notification_service/src/api/unsubscribe/unsubscribe_item.rs
@@ -1,11 +1,13 @@
use axum::{
Json,
- extract::{Path, State},
+ extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Response},
};
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::{EmptyResponse, ErrorResponse};
+use model_entity::EntityType;
+use notification::domain::item_preferences::ItemNotificationPreferenceError;
use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
@@ -13,18 +15,37 @@ use crate::api::context::{ApiContext, AuthorizationService};
#[derive(Deserialize, Serialize, ToSchema, IntoParams)]
pub struct UnsubscribeItemPathParams {
- pub item_type: String,
+ #[serde(deserialize_with = "deserialize_item_type")]
+ pub item_type: EntityType,
pub item_id: String,
}
+fn deserialize_item_type<'de, D: serde::Deserializer<'de>>(
+ deserializer: D,
+) -> Result<EntityType, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ match value.as_str() {
+ "email" | "thread" => Ok(EntityType::EmailThread),
+ "foreign" => Ok(EntityType::ForeignEntity),
+ value => value.parse().map_err(serde::de::Error::custom),
+ }
+}
+
+#[derive(Debug, Deserialize, IntoParams)]
+pub struct SnoozeParams {
+ /// A future resume time. Omit to mute indefinitely.
+ pub snoozed_until: Option<chrono::DateTime<chrono::Utc>>,
+}
+
/// Unsubscribes a user from a given item for notifications.
#[utoipa::path(
post,
operation_id = "unsubscribe_item",
path = "/unsubscribe/item/{item_type}/{item_id}",
- params(UnsubscribeItemPathParams),
+ params(UnsubscribeItemPathParams, SnoozeParams),
responses(
(status = 200, body=EmptyResponse),
+ (status = 400, body=ErrorResponse),
(status = 401, body=ErrorResponse),
(status = 500, body=ErrorResponse),
)
@@ -34,24 +55,35 @@ pub async fn handler(
State(ctx): State<ApiContext>,
user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
Path(UnsubscribeItemPathParams { item_type, item_id }): Path<UnsubscribeItemPathParams>,
+ Query(params): Query<SnoozeParams>,
) -> Result<Response, Response> {
- notification_db_client::unsubscribe::item::upsert_unsubscribed_item_user(
- &ctx.db,
- &user.authorization.user.user_context.user_id,
- &item_id,
- &item_type,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to unsubscribe item");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to unsubscribe item".into(),
- }),
+ ctx.item_preferences
+ .set(
+ user.authorization.user.macro_user_id,
+ item_type.with_entity_string(item_id),
+ params.snoozed_until,
+ chrono::Utc::now(),
)
- .into_response()
- })?;
+ .await
+ .map_err(|e| {
+ if matches!(e, ItemNotificationPreferenceError::InvalidDeadline) {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: e.to_string().into(),
+ }),
+ )
+ .into_response();
+ }
+ tracing::error!(error=?e, "unable to unsubscribe item");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to unsubscribe item".into(),
+ }),
+ )
+ .into_response()
+ })?;
Ok((StatusCode::OK, Json(EmptyResponse {})).into_response())
}
diff --git a/services/notification_service/src/main.rs b/services/notification_service/src/main.rs
index cc5a7bcc03..abe5eb6699 100644
--- a/services/notification_service/src/main.rs
+++ b/services/notification_service/src/main.rs
@@ -349,6 +349,9 @@ pub async fn main() -> anyhow::Result<()> {
api::setup_and_serve(
ApiContext {
+ item_preferences: ::notification::domain::item_preferences::ItemNotificationPreferenceService::new(
+ ::notification::outbound::item_preferences::PgItemNotificationPreferenceRepository(db.clone()),
+ ),
internal_api_key: config.internal_api_key.clone(),
db,
sns_client: Arc::new(sns_client),