Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai/notifications): notification tools for ai (#2924)
teo5f52d5b2e5ae
diff --git a/js/app/packages/core/component/AI/component/tool/Notifications.tsx b/js/app/packages/core/component/AI/component/tool/Notifications.tsxnew file mode 100644index 0000000000..44edf48ec8--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/Notifications.tsx@@ -0,0 +1,113 @@+import Check from '@phosphor-icons/core/regular/check.svg';+import List from '@phosphor-icons/core/regular/list.svg';+import type { ListNotifications as ListNotificationsTool } from '@service-cognition/generated/tools/types';+import { Show } from 'solid-js';+import { BaseTool } from './BaseTool';+import { createToolRenderer } from './ToolRenderer';++type NotificationFilterType = NonNullable<+ ListNotificationsTool['includeTypes']+>[number];++const NOTIFICATION_TYPE_LABELS: Record<NotificationFilterType, string> = {+ email: 'emails',+ message: 'messages',+ channel: 'channels',+ document: 'documents',+ project: 'projects',+ chat: 'chats',+ call: 'calls',+ task: 'tasks',+};++const formatList = (items: string[]) => {+ if (items.length === 0) return '';+ if (items.length === 1) return items[0];+ if (items.length === 2) return `${items[0]} and ${items[1]}`;+ return `${items.slice(0, -1).join(', ')}, and ${items.at(-1)}`;+};++const formatNotificationFilters = (filters: ListNotificationsTool) => {+ const statusFilters = [filters.done ? 'done' : 'not done'];+ if (filters.seen != null) {+ statusFilters.push(filters.seen ? 'seen' : 'unseen');+ }++ let text = `filtered by ${formatList(statusFilters)}`;++ if (filters.includeTypes?.length) {+ text += ` in ${formatList(+ filters.includeTypes.map((type) => NOTIFICATION_TYPE_LABELS[type])+ )}`;+ }++ if (filters.entities?.length) {+ text += ` for ${filters.entities.length} ${+ filters.entities.length === 1 ? 'entity' : 'entities'+ }`;+ }++ return text;+};++const listNotificationsHandler = createToolRenderer({+ name: 'ListNotifications',+ render: (ctx) => {+ const count = () => ctx.response?.data.notifications.length ?? 0;+ const statusText = () => {+ if (!ctx.response) return undefined;+ if (count() === 0) return 'No notifications read';+ if (count() === 1) return 'Read 1 notification';+ return `Read ${count()} notifications`;+ };++ return (+ <BaseTool icon={List} renderContext={ctx.renderContext} type="call">+ <div class="flex min-w-0 flex-1 flex-col gap-1">+ <div class="flex min-w-0 items-center justify-between gap-3">+ <span>Read notifications</span>+ <Show when={statusText()}>+ {(text) => (+ <span class="shrink-0 text-xs text-ink-extra-muted">+ {text()}+ </span>+ )}+ </Show>+ </div>+ <div class="min-w-0 truncate text-xs text-ink-extra-muted">+ {formatNotificationFilters(ctx.tool.data)}+ </div>+ </div>+ </BaseTool>+ );+ },+});++const markNotificationsSeenHandler = createToolRenderer({+ name: 'MarkNotificationsSeen',+ render: (ctx) => (+ <BaseTool icon={Check} renderContext={ctx.renderContext} type="call">+ Mark{' '}+ <span class="text-accent">{ctx.tool.data.notificationIds.length}</span>{' '}+ notification{ctx.tool.data.notificationIds.length === 1 ? '' : 's'} seen+ </BaseTool>+ ),+});++const markNotificationsDoneHandler = createToolRenderer({+ name: 'MarkNotificationsDone',+ render: (ctx) => (+ <BaseTool icon={Check} renderContext={ctx.renderContext} type="call">+ Mark{' '}+ <span class="text-accent">{ctx.tool.data.notificationIds.length}</span>{' '}+ notification{ctx.tool.data.notificationIds.length === 1 ? '' : 's'}{' '}+ {ctx.tool.data.done ? 'done' : 'not done'}+ </BaseTool>+ ),+});++export {+ listNotificationsHandler,+ markNotificationsDoneHandler,+ markNotificationsSeenHandler,+};diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex 20a92f73bd..d885632127 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -10,6 +10,11 @@ import { createDocumentHandler } from './CreateDocument';import { getThreadHandler } from './GetThread';import { listCallRecordsHandler } from './ListCallRecords';import { listEntitiesHandler } from './ListEntities';+import {+ listNotificationsHandler,+ markNotificationsDoneHandler,+ markNotificationsSeenHandler,+} from './Notifications';import {getEntityPropertiesHandler,setEntityPropertyHandler,@@ -43,6 +48,9 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {GetEntityProperties: getEntityPropertiesHandler,ListCallRecords: listCallRecordsHandler,ListEntities: listEntitiesHandler,+ ListNotifications: listNotificationsHandler,+ MarkNotificationsDone: markNotificationsDoneHandler,+ MarkNotificationsSeen: markNotificationsSeenHandler,bash_code_execution: bashCodeExecutionHandler,ContentSearch: contentSearchHandler,CreateDocument: createDocumentHandler,diff --git a/js/app/packages/core/types/index.ts b/js/app/packages/core/types/index.tsindex 70424eb97a..fed035734e 100644--- a/js/app/packages/core/types/index.ts+++ b/js/app/packages/core/types/index.ts@@ -18,7 +18,7 @@ export type Entity = {export type { ApiPaginatedThreadCursor as ThreadPreview } from '@service-email/generated/schemas/apiPaginatedThreadCursor';import type { NotifEvent } from '@service-notification/generated/schemas';-export type NotificationType = NotifEvent['tag'];+export type NotificationType = NotifEvent['tag'] | 'call-started';export type Nullable<T> = T | null;export type Maybe<T> = T | undefined;diff --git a/js/app/packages/entity/src/entity.ts b/js/app/packages/entity/src/entity.tsindex 172863076e..275a5eb960 100644--- a/js/app/packages/entity/src/entity.ts+++ b/js/app/packages/entity/src/entity.ts@@ -14,6 +14,7 @@ import { ContentHits } from './extractors-search';// Notification componentsimport {+ NotificationStackRow,NotificationStacks,MobileNotificationStacks,NotificationIcon,@@ -43,6 +44,7 @@ export const Entity = {ContentHits: ContentHits,},Notification: {+ StackRow: NotificationStackRow,Stacks: NotificationStacks,MobileStacks: MobileNotificationStacks,Icon: NotificationIcon,diff --git a/js/app/packages/entity/src/extractors-notification/index.ts b/js/app/packages/entity/src/extractors-notification/index.tsindex cdd05e92ff..f8de67f2b6 100644--- a/js/app/packages/entity/src/extractors-notification/index.ts+++ b/js/app/packages/entity/src/extractors-notification/index.ts@@ -1,4 +1,7 @@-export { NotificationStacks } from './notification-stacks';+export {+ NotificationStackRow,+ NotificationStacks,+} from './notification-stacks';export { MobileNotificationStacks } from './mobile-notification-stacks';export type { EntityRowConfig } from './mobile-notification-stacks';export { NotificationIcon } from './notification-icon';diff --git a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.tsindex 578d000705..7cb1f3e636 100644--- a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts+++ b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts@@ -34,6 +34,7 @@ export function getActionVerb(type: NotificationType): string {.with('channel_invite', () => 'invited you').with('invite_to_team', () => 'invited you').with('task_assigned', () => 'assigned you')+ .with('call-started', () => 'started a call').exhaustive();}@@ -61,6 +62,7 @@ export function getTypeNoun(type: NotificationType, count: number): string {.with('channel_invite', () => (count === 1 ? 'invite' : 'invites')).with('invite_to_team', () => (count === 1 ? 'invite' : 'invites')).with('task_assigned', () => (count === 1 ? 'task' : 'tasks'))+ .with('call-started', () => (count === 1 ? 'call' : 'calls')).exhaustive();}diff --git a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx b/js/app/packages/entity/src/extractors-notification/notification-icon.tsxindex d75071a80f..13b5219c1a 100644--- a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx+++ b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx@@ -11,6 +11,7 @@ import FilesIcon from '@icon/regular/files.svg';import EnvelopeIcon from '@icon/regular/envelope.svg';import UserPlusIcon from '@icon/regular/user-plus.svg';import CheckIcon from '@icon/regular/check.svg';+import PhoneIcon from '@macro-icons/wide/call.svg';import { cn } from '@ui/utils/classname';interface NotificationIconProps {@@ -38,6 +39,7 @@ function getNotificationIcon(.with('invite_to_team', () => UserPlusIcon).with('task_assigned', () => CheckIcon).with('ai_response', () => ChatIcon)+ .with('call-started', () => PhoneIcon).exhaustive();}diff --git a/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsxindex b8afb012fd..0c9281783b 100644--- a/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx+++ b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx@@ -49,14 +49,17 @@ interface NotificationStacksProps {visibleCount?: number;}-function NotificationStackRow(props: {+export function NotificationStackRow(props: {stack: NotificationStack;entity: EntityData;onClick?: (e: PointerEvent | MouseEvent | KeyboardEvent) => void;content?: JSX.Element;+ showMarkDone?: boolean;}) {const notificationSource = useGlobalNotificationSource();const unread = () => isNotificationUnread(props.stack);+ const canMarkDone = () =>+ props.showMarkDone !== false && props.stack.type !== 'call-started';const { markStackAsDone, markStackAsRead } = useNotificationStackActions({stack: props.stack,@@ -115,7 +118,7 @@ function NotificationStackRow(props: {e.preventDefault();handleClick(e);}- if (e.key === 'e') {+ if (e.key === 'e' && canMarkDone()) {e.preventDefault();e.stopPropagation();handleMarkAsDone();@@ -147,15 +150,17 @@ function NotificationStackRow(props: {{' - '}<NotificationTimestamp stack={props.stack} /></span>- <div class="ml-auto flex items-center gap-1 pr-2 shrink-0">- <Button- onClick={handleMarkAsDone}- tooltip={'Mark notification done'}- class="border border-edge-muted text-xs text-ink-muted grid p-0 place-items-center size-6"- >- <CheckIcon class="size-3" />- </Button>- </div>+ <Show when={canMarkDone()}>+ <div class="ml-auto flex items-center gap-1 pr-2 shrink-0">+ <Button+ onClick={handleMarkAsDone}+ tooltip={'Mark notification done'}+ class="border border-edge-muted text-xs text-ink-muted grid p-0 place-items-center size-6"+ >+ <CheckIcon class="size-3" />+ </Button>+ </div>+ </Show></div><divclass={cn('ph-no-capture mt-1 min-w-0', {@@ -171,7 +176,9 @@ function NotificationStackRow(props: {<ContextMenu.Portal><div onClick={(e) => e.stopPropagation()}><ContextMenuContent class="text-xs text-ink-muted">- <MenuItem text="Mark Done" onClick={() => handleMarkAsDone()} />+ <Show when={canMarkDone()}>+ <MenuItem text="Mark Done" onClick={() => handleMarkAsDone()} />+ </Show><MenuItem text="Mark Read" onClick={handleMarkAsRead} /><MenuItem text="Copy Link" onClick={handleCopyLink} /></ContextMenuContent>diff --git a/js/app/packages/entity/src/utils/notification.ts b/js/app/packages/entity/src/utils/notification.tsindex 0d1db0e245..dcaab30c2f 100644--- a/js/app/packages/entity/src/utils/notification.ts+++ b/js/app/packages/entity/src/utils/notification.ts@@ -1,9 +1,21 @@import { ENABLE_DOCUMENT_MENTION_NOTIFICATIONS } from '@core/constant/featureFlags';+import type { NotificationType } from '@core/types';import { notificationIsRead, type UnifiedNotification } from '@notifications';import type { NotificationStack } from '@notifications/notification-stacking';import { match } from 'ts-pattern';import type { Notification } from '../types/notification';+type CallStartedNotificationMetadata = {+ tag: 'call-started';+ content: {+ channel_name?: string | null;+ };+};++type KnownNotificationMetadata =+ | UnifiedNotification['notification_metadata']+ | CallStartedNotificationMetadata;+/*** Filters out invalid notification types that shouldn't be displayed*/@@ -53,7 +65,7 @@ export function extractNotificationSenderIds(* Returns a short verb phrase like "mentioned", "replied", "shared", etc.*/export function getNotificationActionText(n: Notification): string {- const tag = n.notification_metadata.tag;+ const tag = n.notification_metadata.tag as NotificationType;return match(tag).with('channel_mention', () => 'mentioned')@@ -68,12 +80,13 @@ export function getNotificationActionText(n: Notification): string {.with('invite_to_team', () => 'invited').with('task_assigned', () => 'assigned').with('ai_response', () => 'responded')+ .with('call-started', () => 'called').exhaustive();}export function extractMessageContent(notification: Notification): string {const n = notification as UnifiedNotification;- const meta = n.notification_metadata;+ const meta = n.notification_metadata as KnownNotificationMetadata;return match(meta).with({ tag: 'channel_mention' }, (m) => m.content.messageContent || '')@@ -97,6 +110,7 @@ export function extractMessageContent(notification: Notification): string {.with({ tag: 'ai_response' }, (m) => m.content.summary || '').with({ tag: 'channel_invite' }, () => '').with({ tag: 'invite_to_team' }, () => '')+ .with({ tag: 'call-started' }, (m) => m.content.channel_name ?? '').exhaustive();}diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex 8348fee71d..d558e2a4de 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -159,7 +159,7 @@ function getSupportedHandler(notification: UnifiedNotification,entity?: NotificationEntityOverride): ((layoutManager: SplitManager, newSplit?: boolean) => Promise<void>) | null {- const tag = notification.notification_metadata.tag;+ const tag = notification.notification_metadata.tag as NotificationType;return match(tag).with(@@ -201,6 +201,14 @@ function getSupportedHandler();}).with('invite_to_team', () => null)+ .with(+ 'call-started',+ () =>+ async (lm: SplitManager, newSplit: boolean = false) =>+ openSplitIfNotOpen(lm, 'channel', notification.entity_id, {+ newSplit,+ })+ ).with('task_assigned', () => {const meta = notification.notification_metadata;if (meta.tag !== 'task_assigned') return null;diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.tsindex 75c4ea18dd..4063b298e0 100644--- a/js/app/packages/notifications/notification-preview.ts+++ b/js/app/packages/notifications/notification-preview.ts@@ -13,4 +13,5 @@ export const NOTIFICATION_LABEL_BY_TYPE: Record<NotificationType, string> = {invite_to_team: 'INVITE',task_assigned: 'ASSIGNED',ai_response: 'AI',+ 'call-started': 'CALL',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex 3ecc1ce388..214151613f 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -496,6 +496,80 @@ export const ListEntitiesResponse = z.object({summary: z.string(),});+export const ListNotifications = z.object({+ done: z.union([z.boolean(), z.null()]).default(null),+ entities: z+ .union([+ z.array(+ z.object({+ entityType: z.enum([+ 'email',+ 'message',+ 'channel',+ 'document',+ 'project',+ 'chat',+ 'call',+ 'task',+ ]),+ id: z.string(),+ })+ ),+ z.null(),+ ])+ .default(null),+ includeTypes: z+ .union([+ z.array(+ z.enum([+ 'email',+ 'message',+ 'channel',+ 'document',+ 'project',+ 'chat',+ 'call',+ 'task',+ ])+ ),+ z.null(),+ ])+ .default(null),+ limit: z.union([z.number().int().gte(0), z.null()]).default(null),+ seen: z.union([z.boolean(), z.null()]).default(null),+});++export const ListNotificationsResponse = z.object({+ hasMore: z.boolean(),+ notifications: z.array(+ z.object({+ createdAt: z.string(),+ done: z.boolean(),+ entityId: z.string(),+ entityType: z.string(),+ eventType: z.string(),+ id: z.string().uuid(),+ metadata: z.any(),+ seen: z.boolean(),+ senderId: z.union([z.string(), z.null()]).optional(),+ })+ ),+});++export const MarkNotificationsDone = z.object({+ done: z.boolean(),+ notificationIds: z.array(z.string().uuid()),+});++export const MarkNotificationsResponse = z.object({+ count: z.number().int().gte(0),+ success: z.boolean(),+});++export const MarkNotificationsSeen = z.object({+ notificationIds: z.array(z.string().uuid()),+});+export const NameSearch = z.object({entityTypes: z.array(diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex 7adae31046..a1d348a15c 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -32,6 +32,18 @@ type ToolParserMap = {call: types.ListEntities;response: types.ListEntitiesResponse;};+ ListNotifications: {+ call: types.ListNotifications;+ response: types.ListNotificationsResponse;+ };+ MarkNotificationsDone: {+ call: types.MarkNotificationsDone;+ response: types.MarkNotificationsResponse;+ };+ MarkNotificationsSeen: {+ call: types.MarkNotificationsSeen;+ response: types.MarkNotificationsResponse;+ };NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };ReadCallRecord: {call: types.ReadCallRecord;@@ -103,6 +115,18 @@ const toolParserMap = {call: schemas.ListEntities,response: schemas.ListEntitiesResponse,},+ ListNotifications: {+ call: schemas.ListNotifications,+ response: schemas.ListNotificationsResponse,+ },+ MarkNotificationsDone: {+ call: schemas.MarkNotificationsDone,+ response: schemas.MarkNotificationsResponse,+ },+ MarkNotificationsSeen: {+ call: schemas.MarkNotificationsSeen,+ response: schemas.MarkNotificationsResponse,+ },NameSearch: {call: schemas.NameSearch,response: schemas.SearchToolResponse,@@ -191,6 +215,18 @@ type ToolDataMap = {call: types.ListEntities;response: types.ListEntitiesResponse;};+ ListNotifications: {+ call: types.ListNotifications;+ response: types.ListNotificationsResponse;+ };+ MarkNotificationsDone: {+ call: types.MarkNotificationsDone;+ response: types.MarkNotificationsResponse;+ };+ MarkNotificationsSeen: {+ call: types.MarkNotificationsSeen;+ response: types.MarkNotificationsResponse;+ };NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };ReadCallRecord: {call: types.ReadCallRecord;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 9eb87e2d94..2b7f7fd56c 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -124,6 +124,18 @@ export type SortBy =| 'recently_viewed'| 'recently_updated'| 'recently_created';+/**+ * User-facing notification categories used for list filtering.+ */+export type NotificationItemType =+ | 'email'+ | 'message'+ | 'channel'+ | 'document'+ | 'project'+ | 'chat'+ | 'call'+ | 'task';/*** Direction for reading more messages around a cursor.*/@@ -1130,6 +1142,132 @@ export interface ListEntitiesResponse {items: EntityItem[];summary: string;}+/**+ * List the current user's notifications. By default returns active notifications (not deleted, not done), ordered by most recent first. Use `done` and `seen` to request done/not-done or seen/unseen notifications.+ */+export interface ListNotifications {+ /**+ * Filter by done status. If omitted, only not-done notifications are returned. Set true for done notifications, false for not-done notifications.+ */+ done?: boolean | null;+ /**+ * Filter to notifications for specific entities. Pair each id with entityType to avoid ambiguity. Example: [{"entityType":"email","id":"..."}] returns notifications for one email thread.+ */+ entities?: NotificationEntityRef[] | null;+ /**+ * Filter to specific notification item types. If omitted, returns all types. Example: ["email", "message"] returns only email and message notifications.+ */+ includeTypes?: NotificationItemType[] | null;+ /**+ * Maximum number of notifications to return. Defaults to 20, max 50.+ */+ limit?: number | null;+ /**+ * Filter by seen status. If omitted, both seen and unseen notifications are returned. Set true for seen notifications, false for unseen notifications.+ */+ seen?: boolean | null;+}+/**+ * User-facing reference to one specific entity to filter notifications by.+ */+export interface NotificationEntityRef {+ entityType: NotificationItemType;+ /**+ * Entity id. For `email`, this is the email thread id. For `message`, this is the channel message id.+ */+ id: string;+}+/**+ * Response from listing notifications.+ */+export interface ListNotificationsResponse {+ /**+ * Whether there are more notifications available.+ */+ hasMore: boolean;+ /**+ * The list of notifications.+ */+ notifications: NotificationItem[];+}+/**+ * A single notification item in the list response.+ */+export interface NotificationItem {+ /**+ * When the notification was created (ISO 8601).+ */+ createdAt: string;+ /**+ * Whether the notification is marked as done.+ */+ done: boolean;+ /**+ * The ID of the entity this notification is about.+ */+ entityId: string;+ /**+ * The type of entity this notification is about (e.g. "channel", "document").+ */+ entityType: string;+ /**+ * The notification event type (e.g. "channel_mention").+ */+ eventType: string;+ /**+ * The notification ID.+ */+ id: string;+ /**+ * The notification metadata/payload.+ */+ metadata: {+ [k: string]: unknown;+ };+ /**+ * Whether the notification has been seen.+ */+ seen: boolean;+ /**+ * The user ID of the sender, if any.+ */+ senderId?: string | null;+}+/**+ * Mark one or more notifications as done or not done for the current user. Use this when the user has completed the action associated with a notification.+ */+export interface MarkNotificationsDone {+ /**+ * Whether to mark as done (true) or not done (false).+ */+ done: boolean;+ /**+ * The IDs of the notifications to update.+ */+ notificationIds: string[];+}+/**+ * Response from marking notifications as seen or done.+ */+export interface MarkNotificationsResponse {+ /**+ * The number of notifications updated.+ */+ count: number;+ /**+ * Whether the operation succeeded.+ */+ success: boolean;+}+/**+ * Mark one or more notifications as seen for the current user. Use this when the user has viewed notifications but hasn't acted on them yet.+ */+export interface MarkNotificationsSeen {+ /**+ * The IDs of the notifications to mark as seen.+ */+ notificationIds: string[];+}/*** Search for items by their name or title. For documents, this searches the document name. For emails, this searches the subject line. For chats, this searches the chat title. For projects (folders), this searches the project name. For call records, this searches the channel name the call took place in. This tool finds items based on what they're called, not their content.*/diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 8b17112726..45809c3ce0 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -6603,6 +6603,7 @@ dependencies = ["macro_middleware","macro_user_id","mcp_auth_proxy",+ "notification","properties","readonly_pool","redis",@@ -6662,6 +6663,7 @@ dependencies = ["macro_user_id","macro_uuid","model_user",+ "notification","properties","readonly_pool","search_service_client",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex d322514666..b7ee931cd6 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -47,7 +47,7 @@ models_dcs = { path = "../models_dcs" }models_email = { path = "../models_email" }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions" }-notification = { path = "../notification" }+notification = { path = "../notification", features = ["ai_tool"] }models_properties = { path = "../models_properties" }models_search = { path = "../models_search" }rand.workspace = truediff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex 64ff5540b1..f25622f1a5 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -6,7 +6,7 @@use crate::tool_context::{NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,- NoOpTaskProperties, ToolServiceContext,+ NoOpSnsEndpointManager, NoOpTaskProperties, ToolNotificationQueue, ToolServiceContext,};use anyhow::Context;use comms::domain::service::ChannelServiceImpl;@@ -27,6 +27,9 @@ use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;use macro_env::Environment;use macro_env_var::{env_var, maybe_env_var};+use notification::domain::service::{NotificationReaderService, PlatformArnConfig};+use notification::outbound::queue::SqsQueue;+use notification::outbound::repository::DbNotificationRepository;use readonly_pool::ReadOnlyPool;use search_service_client::SearchServiceClient;use secretsmanager_client::{SecretManager, SecretsManager};@@ -55,6 +58,7 @@ maybe_env_var! {struct ToolContextMaybeEnvVars {InternalApiSecretKey,LexicalServiceUrl,+ NotificationQueue,}}@@ -77,6 +81,7 @@ maybe_env_var! {/// Optional env vars (with fallbacks for local dev):/// - `INTERNAL_API_SECRET_KEY` (defaults to `"local"`)/// - `LEXICAL_SERVICE_URL` (defaults to `http://localhost:8096`)+/// - `NOTIFICATION_QUEUE` (if omitted, notification status updates skip push clearing)#[tracing::instrument(skip(pool), err)]pub async fn build_tool_service_context_from_env(pool: sqlx::PgPool,@@ -96,8 +101,16 @@ pub async fn build_tool_service_context_from_env(.context("expected LEXICAL_SERVICE_URL")?;let aws_config = macro_aws_config::get_macro_aws_config().await;- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))+ let aws_sqs_client = aws_sdk_sqs::Client::new(&aws_config);+ let sqs_client = sqs_client::SQS::new(aws_sqs_client.clone()).email_scheduled_queue(&env.email_scheduled_queue);+ let notification_queue = maybe_env+ .notification_queue+ .as_ref()+ .map(|queue_url| {+ ToolNotificationQueue::Sqs(SqsQueue::new(aws_sqs_client, queue_url.to_string()))+ })+ .unwrap_or(ToolNotificationQueue::NoOp);let secretsmanager_client =SecretsManager::new(aws_sdk_secretsmanager::Client::new(&aws_config));@@ -237,6 +250,18 @@ pub async fn build_tool_service_context_from_env((*entity_access_service).clone(),);+ let notification_reader_service = NotificationReaderService::new(+ DbNotificationRepository::new(pool.clone()),+ notification_queue,+ NoOpSnsEndpointManager,+ PlatformArnConfig {+ apns_platform_arn: String::new(),+ fcm_platform_arn: String::new(),+ },+ );+ let notification_tool_context =+ notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);+let chat_repo = chat::outbound::postgres::PgChatRepo::new(pool.clone());let chat_service = chat::domain::service::ChatServiceImpl::new(chat_repo,@@ -260,6 +285,7 @@ pub async fn build_tool_service_context_from_env(properties_tool_context,email_tool_context,call_tool_context,+ notification_tool_context,chat_tool_context,channel_tool_context,schedule_tool_context: crate::NoOpScheduleContext,diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 884daddd43..5ac97043f3 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -15,6 +15,7 @@ use channels::inbound::toolset::channel_toolset;use chat::inbound::toolset::chat_toolset;use documents::inbound::toolset::document_toolset;use email::inbound::toolset::email_toolset;+use notification::inbound::ai_tool::notification_toolset;use properties::inbound::toolset::properties_toolset;use schemas::{anthropic_tools, read};use soup::inbound::toolset::{ListEntities, SoupToolContext};@@ -61,6 +62,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {/// These are actually sent to the AI providerpub fn all_tools() -> ToolSetWithPrompt {let toolset = subagent_toolset()+ .add_subtoolset::<ToolNotificationToolContext>(notification_toolset()).add_subtoolset::<ToolEmailToolContext>(email_toolset()).add_tool::<Subagent, ToolServiceContext>();let prompt = prompts::TOOLS_PROMPT;diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex e1313e4e4a..c9d29079b4 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -17,6 +17,7 @@ use email::{domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,};use macro_user_id::user_id::MacroUserIdStr;+use notification::inbound::ai_tool::NotificationToolContext;use properties::inbound::toolset::PropertiesToolContext;use soup::{domain::service::SoupImpl, inbound::toolset::SoupToolContext};use std::sync::Arc;@@ -186,6 +187,115 @@ impl notification::domain::service::NotificationIngress for NoOpNotificationIngr}}+/// No-op SNS endpoint manager used by AI notification tools.+///+/// The exposed AI tools list and update notifications. Updating notifications+/// can clear existing push notifications via the notification delivery queue,+/// but it does not create or mutate SNS platform endpoints. Device+/// registration APIs are not exposed through the AI toolset, so SNS endpoint+/// operations intentionally fail if called accidentally.+#[derive(Clone)]+pub struct NoOpSnsEndpointManager;++impl notification::domain::ports::SnsEndpointManager for NoOpSnsEndpointManager {+ async fn create_platform_endpoint(+ &self,+ _platform_arn: &str,+ _token: &str,+ ) -> Result<String, rootcause::Report> {+ rootcause::bail!("SNS endpoint manager not configured for AI tools")+ }++ async fn get_endpoint_attributes(+ &self,+ _endpoint_arn: &str,+ ) -> Result<std::collections::HashMap<String, String>, rootcause::Report> {+ rootcause::bail!("SNS endpoint manager not configured for AI tools")+ }++ async fn set_endpoint_attributes(+ &self,+ _endpoint_arn: &str,+ _attributes: std::collections::HashMap<String, String>,+ ) -> Result<(), rootcause::Report> {+ rootcause::bail!("SNS endpoint manager not configured for AI tools")+ }++ async fn delete_endpoint(&self, _endpoint_arn: &str) -> Result<(), rootcause::Report> {+ rootcause::bail!("SNS endpoint manager not configured for AI tools")+ }+}++/// Notification delivery queue used by AI tools.+///+/// Most production contexts provide the real notification SQS queue so marking+/// notifications seen/done can clear mobile pushes. Some auxiliary binaries+/// that expose the shared tool context do not have a notification queue+/// configured; those can use `NoOp`, which still updates database state but+/// skips push-clearing delivery messages.+#[derive(Clone)]+pub enum ToolNotificationQueue {+ Sqs(notification::outbound::queue::SqsQueue),+ NoOp,+}++impl notification::domain::ports::NotificationQueue for ToolNotificationQueue {+ async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(+ &self,+ messages: Vec<notification::domain::models::queue_message::QueueMessage<'a, T, U>>,+ ) -> Result<(), rootcause::Report> {+ match self {+ ToolNotificationQueue::Sqs(queue) => {+ notification::domain::ports::NotificationQueue::publish(queue, messages).await+ }+ ToolNotificationQueue::NoOp => Ok(()),+ }+ }++ async fn receive_messages(+ &self,+ ) -> Result<Vec<notification::domain::models::queue_message::RawQueueMessage>, rootcause::Report>+ {+ match self {+ ToolNotificationQueue::Sqs(queue) => {+ notification::domain::ports::NotificationQueue::receive_messages(queue).await+ }+ ToolNotificationQueue::NoOp => Ok(Vec::new()),+ }+ }++ async fn delete_message(&self, receipt_handle: &str) -> Result<(), rootcause::Report> {+ match self {+ ToolNotificationQueue::Sqs(queue) => {+ notification::domain::ports::NotificationQueue::delete_message(+ queue,+ receipt_handle,+ )+ .await+ }+ ToolNotificationQueue::NoOp => Ok(()),+ }+ }++ async fn delay_message(+ &self,+ receipt_handle: &str,+ delay: std::time::Duration,+ ) -> Result<(), rootcause::Report> {+ match self {+ ToolNotificationQueue::Sqs(queue) => {+ notification::domain::ports::NotificationQueue::delay_message(+ queue,+ receipt_handle,+ delay,+ )+ .await+ }+ ToolNotificationQueue::NoOp => Ok(()),+ }+ }+}+/// Type alias for the entity access management service implementation used by AI toolspub type ToolEntityAccessManagementService =entity_access_management::domain::service::EntityAccessManagementServiceImpl<@@ -271,6 +381,16 @@ pub type ToolCallRecordQueryService = CallRecordQueryServiceImpl<PgCallRepo>;pub type ToolCallToolContext =CallToolContext<ToolCallService, ToolCallRecordQueryService, ToolEntityAccessService>;+/// Type alias for the notification reader service used by AI tools.+pub type ToolNotificationService = notification::domain::service::NotificationReaderService<+ notification::outbound::repository::DbNotificationRepository<sqlx::PgPool>,+ ToolNotificationQueue,+ NoOpSnsEndpointManager,+>;++/// Type alias for the notification tool context.+pub type ToolNotificationToolContext = NotificationToolContext<ToolNotificationService>;+/// Type alias for the chat service implementation used by AI tools./// Uses an empty toolset — the read-only tool never invokes tool execution.pub type ToolChatService = ChatServiceImpl<PgChatRepo, (), ToolEntityAccessManagementService>;@@ -298,6 +418,7 @@ pub struct ToolServiceContext {pub properties_tool_context: ToolPropertiesToolContext,pub email_tool_context: ToolEmailToolContext,pub call_tool_context: ToolCallToolContext,+ pub notification_tool_context: ToolNotificationToolContext,pub chat_tool_context: ToolChatToolContext,pub channel_tool_context: ToolChannelToolContext,pub schedule_tool_context: NoOpScheduleContext,diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex fa41e58dff..5bc9e39585 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -120,8 +120,11 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Aruse frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;- use notification::domain::service::SqsNotificationIngress;+ use notification::domain::service::{+ NotificationReaderService, PlatformArnConfig, SqsNotificationIngress,+ };use notification::outbound::queue::SqsQueue;+ use notification::outbound::repository::DbNotificationRepository;use search_service_client::SearchServiceClient;use soup::domain::service::SoupImpl;use soup::outbound::pg_soup_repo::PgSoupRepo;@@ -178,13 +181,29 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar));let ingress_queue = SqsQueue::new(- aws_sdk_sqs::Client::from_conf(sqs_config),+ aws_sdk_sqs::Client::from_conf(sqs_config.clone()),"test-notification-ingress-queue".to_string(),);let notification_ingress_service = Arc::new(SqsNotificationIngress {queue: ingress_queue,});+ let notification_reader_queue = SqsQueue::new(+ aws_sdk_sqs::Client::from_conf(sqs_config),+ "test-notification-queue".to_string(),+ );+ let notification_reader_service = NotificationReaderService::new(+ DbNotificationRepository::new(pool.clone()),+ ai_tools::ToolNotificationQueue::Sqs(notification_reader_queue),+ ai_tools::NoOpSnsEndpointManager,+ PlatformArnConfig {+ apns_platform_arn: String::new(),+ fcm_platform_arn: String::new(),+ },+ );+ let notification_tool_context =+ notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);+// Build document tool context for AI toolslet s3_config = aws_sdk_s3::Config::builder().behavior_version(aws_sdk_s3::config::BehaviorVersion::latest())@@ -292,6 +311,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arproperties_tool_context: properties_tool_context.clone(),email_tool_context: email_tool_context.clone(),call_tool_context: call_tool_context.clone(),+ notification_tool_context: notification_tool_context.clone(),chat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),schedule_tool_context: ai_tools::no_op_schedule_context(),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 6d8a0584d5..a8a83e3509 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -30,8 +30,11 @@ use frecency::outbound::postgres::FrecencyPgStorage;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_middleware::auth::internal_access::InternalApiSecretKey;-use notification::domain::service::SqsNotificationIngress;+use notification::domain::service::{+ NotificationReaderService, PlatformArnConfig, SqsNotificationIngress,+};use notification::outbound::queue::SqsQueue;+use notification::outbound::repository::DbNotificationRepository;use readonly_pool::ReadOnlyPool;use search_service_client::SearchServiceClient;use secretsmanager_client::SecretManager;@@ -175,6 +178,22 @@ async fn main() -> anyhow::Result<()> {queue: ingress_queue,});+ let notification_reader_queue = SqsQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.notification_queue.clone(),+ );+ let notification_reader_service = NotificationReaderService::new(+ DbNotificationRepository::new(db.clone()),+ ai_tools::ToolNotificationQueue::Sqs(notification_reader_queue),+ ai_tools::NoOpSnsEndpointManager,+ PlatformArnConfig {+ apns_platform_arn: String::new(),+ fcm_platform_arn: String::new(),+ },+ );+ let notification_tool_context =+ notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);+tracing::info!("initialized notification ingress service");let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone(),@@ -350,6 +369,7 @@ async fn main() -> anyhow::Result<()> {properties_tool_context: properties_tool_context.clone(),email_tool_context: email_tool_context.clone(),call_tool_context: call_tool_context.clone(),+ notification_tool_context: notification_tool_context.clone(),chat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),schedule_tool_context: ai_tools::NoOpScheduleContext,diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.tomlindex f42726f017..0d4ea45b88 100644--- a/rust/cloud-storage/mcp_service/Cargo.toml+++ b/rust/cloud-storage/mcp_service/Cargo.toml@@ -36,6 +36,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"user_permissions",] }macro_user_id = { path = "../macro_user_id" }+notification = { path = "../notification", features = ["ai_tool"] }properties = { path = "../properties", features = ["ai_tools"] }readonly_pool = { path = "../readonly_pool" }redis = { workspace = true, features = ["aio", "tokio-comp"] }diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex 51fb821a70..9aa90affd3 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -2,7 +2,8 @@ use std::sync::Arc;use ai_tools::{NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,- NoOpScheduleContext, NoOpTaskProperties, ToolServiceContext,+ NoOpScheduleContext, NoOpSnsEndpointManager, NoOpTaskProperties, ToolNotificationQueue,+ ToolServiceContext,};use anyhow::Context;use comms::domain::service::ChannelServiceImpl;@@ -27,6 +28,8 @@ use mcp_auth_proxy::{domain::service::McpAuthProxyServiceImpl,outbound::{fusionauth::FusionAuthOAuthProvider, redis::RedisInflightAuth},};+use notification::domain::service::{NotificationReaderService, PlatformArnConfig};+use notification::outbound::repository::DbNotificationRepository;use search_service_client::SearchServiceClient;use secretsmanager_client::LocalOrRemoteSecret;use soup::domain::service::SoupImpl;@@ -263,6 +266,18 @@ async fn build_tool_context(EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),);+ let notification_reader_service = NotificationReaderService::new(+ DbNotificationRepository::new(db.clone()),+ ToolNotificationQueue::NoOp,+ NoOpSnsEndpointManager,+ PlatformArnConfig {+ apns_platform_arn: String::new(),+ fcm_platform_arn: String::new(),+ },+ );+ let notification_tool_context =+ notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);+let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(chat::domain::service::ChatServiceImpl::new(chat::outbound::postgres::PgChatRepo::new(db.clone()),@@ -286,6 +301,7 @@ async fn build_tool_context(properties_tool_context,email_tool_context,call_tool_context,+ notification_tool_context,chat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),schedule_tool_context: NoOpScheduleContext,diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.tomlindex 1527e46769..45fd71163d 100644--- a/rust/cloud-storage/memory/Cargo.toml+++ b/rust/cloud-storage/memory/Cargo.toml@@ -12,6 +12,7 @@ ai_toolset = { path = "../ai_toolset" }anyhow = { workspace = true }axum = { workspace = true }chrono = { workspace = true }+call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }futures = { workspace = true }macro_entrypoint = { path = "../macro_entrypoint" }macro_env = { path = "../macro_env" }@@ -28,7 +29,6 @@ tracing = { workspace = true }utoipa = { workspace = true }# For building ToolServiceContext-call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }comms = { path = "../comms" }documents = { path = "../documents" }email = { path = "../email" }@@ -38,6 +38,7 @@ entity_access_management = { path = "../entity_access_management" }frecency = { path = "../frecency" }lexical_client = { path = "../lexical_client" }macro_aws_config = { path = "../macro_aws_config" }+notification = { path = "../notification", features = ["ai_tool"] }properties = { path = "../properties" }readonly_pool = { path = "../readonly_pool" }search_service_client = { path = "../search_service_client" }diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex f8aa11a02b..62966c10be 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -1,5 +1,7 @@use ai_tools::{- NoOpConnectionService, NoOpNotificationService, NoOpTaskProperties, ToolServiceContext,+ NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,+ NoOpScheduleContext, NoOpSnsEndpointManager, NoOpTaskProperties, ToolNotificationQueue,+ ToolServiceContext,};use comms::domain::service::ChannelServiceImpl;use comms::outbound::postgres::comms_repo::PgCommsRepo;@@ -17,6 +19,8 @@ use entity_access::outbound::PgAccessRepository;use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;+use notification::domain::service::{NotificationReaderService, PlatformArnConfig};+use notification::outbound::repository::DbNotificationRepository;use search_service_client::SearchServiceClient;use soup::domain::service::SoupImpl;use soup::outbound::pg_soup_repo::PgSoupRepo;@@ -168,6 +172,31 @@ pub async fn build_tool_service_context((*entity_access_service).clone(),);+ let notification_reader_service = NotificationReaderService::new(+ DbNotificationRepository::new(pool.clone()),+ ToolNotificationQueue::NoOp,+ NoOpSnsEndpointManager,+ PlatformArnConfig {+ apns_platform_arn: String::new(),+ fcm_platform_arn: String::new(),+ },+ );+ let notification_tool_context =+ notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);++ let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(+ chat::domain::service::ChatServiceImpl::new(+ chat::outbound::postgres::PgChatRepo::new(pool.clone()),+ Arc::new(ai_toolset::AsyncToolSet::new()),+ (),+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(+ entity_access_management::outbound::PgRepository::new(pool.clone()),+ ),+ ),+ (*entity_access_service).clone(),+ );++Ok(ToolServiceContext {search_service_client: search_client,email_service_client: email_ext_client,@@ -177,6 +206,8 @@ pub async fn build_tool_service_context(properties_tool_context,email_tool_context,call_tool_context,+ notification_tool_context,+ chat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),schedule_tool_context: ai_tools::NoOpScheduleContext,})diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rsindex c22b60e9a7..180a7d1e03 100644--- a/rust/cloud-storage/notification/src/domain/models/request.rs+++ b/rust/cloud-storage/notification/src/domain/models/request.rs@@ -15,6 +15,54 @@ use serde::{Deserialize, Serialize};use std::collections::HashSet;use uuid::Uuid;+/// User-facing notification categories used for list filtering.+#[allow(missing_docs)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "ai_tool", derive(schemars::JsonSchema))]+#[serde(rename_all = "camelCase")]+pub enum NotificationItemType {+ Email,+ Message,+ Channel,+ Document,+ Project,+ Chat,+ Call,+ Task,+}++impl NotificationItemType {+ pub(crate) fn filter_token(self) -> &'static str {+ match self {+ Self::Email => "email",+ Self::Message => "message",+ Self::Channel => "channel",+ Self::Document => "document",+ Self::Project => "project",+ Self::Chat => "chat",+ Self::Call => "call",+ Self::Task => "task",+ }+ }+}++/// User-facing reference to one specific entity to filter notifications by.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "ai_tool", derive(schemars::JsonSchema))]+#[serde(rename_all = "camelCase")]+pub struct NotificationEntityRef {+ /// Entity type for the provided id.+ pub entity_type: NotificationItemType,+ /// Entity id. For `email`, this is the email thread id. For `message`, this is the channel message id.+ pub id: String,+}++impl NotificationEntityRef {+ pub(crate) fn filter_token(&self) -> String {+ format!("{}:{}", self.entity_type.filter_token(), self.id)+ }+}+/// Request to send a notification.////// Generic over the notification payload type `T`, which must implement@@ -262,6 +310,45 @@ pub struct UpdateNotificationsRequest<'a> {pub status: NotificationStatus,}+/// Optional filters for listing user notifications.+#[derive(Debug, Clone)]+pub struct NotificationListFilters {+ /// Filter by done status. `None` means include both done and not-done notifications.+ pub done: Option<bool>,+ /// Filter by seen status. `None` means include both seen and unseen notifications.+ pub seen: Option<bool>,+ /// Optional user-facing notification categories to include. Empty means include all types.+ pub include_types: Vec<NotificationItemType>,+ /// Optional specific entities to include. Empty means include all entities.+ pub entities: Vec<NotificationEntityRef>,+}++impl NotificationListFilters {+ /// Default product behavior: list active notifications, which excludes done notifications.+ pub fn active() -> Self {+ Self {+ done: Some(false),+ seen: None,+ include_types: Vec::new(),+ entities: Vec::new(),+ }+ }++ pub(crate) fn include_type_tokens(&self) -> Vec<String> {+ self.include_types+ .iter()+ .map(|item_type| item_type.filter_token().to_string())+ .collect()+ }++ pub(crate) fn entity_tokens(&self) -> Vec<String> {+ self.entities+ .iter()+ .map(NotificationEntityRef::filter_token)+ .collect()+ }+}+/// Request to get a user's notifications filtered by event item IDs.#[derive(Debug)]pub struct GetNotificationsByEventItemIdsRequest<'a> {@@ -273,4 +360,6 @@ pub struct GetNotificationsByEventItemIdsRequest<'a> {pub limit: Option<u32>,/// Cursor for pagination.pub cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ /// Filters to apply to the notification status fields.+ pub filters: NotificationListFilters,}diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex e81e2329e6..e703e92863 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -19,6 +19,7 @@ use crate::domain::models::TaggedContent;use crate::domain::models::device::DeviceType;use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};+use crate::domain::models::request::NotificationListFilters;use crate::domain::models::{DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,SendNotificationRequestBuilder, UserNotificationRow, android::FCMMessage,@@ -111,26 +112,27 @@ pub trait NotificationRepository: Send + Sync + 'static {notification_ids: &[Uuid],) -> impl Future<Output = Result<Vec<NotificationIdAndCollapseKey>, Report>> + Send;- /// Get a user's active (not deleted, not done) notifications with cursor-based pagination.+ /// Get a user's non-deleted notifications with cursor-based pagination.///- /// The metadata JSON column is deserialized into `T`.+ /// The metadata JSON column is deserialized into `T`. `filters` controls done/seen status.fn get_user_notifications<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;- /// Get a user's active notifications filtered by event item IDs, with cursor-based pagination.+ /// Get a user's non-deleted notifications filtered by event item IDs, with cursor-based pagination.///- /// Only returns notifications that are not deleted and not done,- /// matching one of the provided `event_item_ids`.+ /// Only returns notifications matching one of the provided `event_item_ids` and the status filters.fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,event_item_ids: &[Uuid],limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;/// Get a single user notification by ID.diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rsindex c51eea3c64..9bf56c8596 100644--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs@@ -154,6 +154,7 @@ impl NotificationRepository for MockNotifRepo {_: macro_user_id::user_id::MacroUserIdStr<'_>,_: u32,_: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ _: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {unimplemented!()}@@ -163,6 +164,7 @@ impl NotificationRepository for MockNotifRepo {_: &[uuid::Uuid],_: u32,_: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ _: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {unimplemented!()}diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex 97ef8a2450..7ce393d66d 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -13,8 +13,8 @@ use crate::domain::models::queue_message::{QueueMessageNeedsStateMachine, UserApnsEndpoints,};use crate::domain::models::request::{- BuildApnsOutput, GetNotificationsByEventItemIdsRequest, NotificationStatus,- SendNotificationRequest, UpdateNotificationsRequest,+ BuildApnsOutput, GetNotificationsByEventItemIdsRequest, NotificationListFilters,+ NotificationStatus, SendNotificationRequest, UpdateNotificationsRequest,};use crate::domain::models::{DeviceEndpoint, DisabledNotificationType, Notification, NotificationResult,@@ -59,18 +59,19 @@ pub trait NotificationReader: Send + Sync + 'static {req: UpdateNotificationsRequest,) -> impl Future<Output = Result<(), Report>> + Send;- /// Get a user's active notifications, paginated.+ /// Get a user's non-deleted notifications, paginated.///- /// Returns at most `limit` (default 20, max 500) notifications that are- /// not deleted and not done, ordered by creation time descending.+ /// Returns at most `limit` (default 20, max 500) notifications matching+ /// the status filters, ordered by creation time descending.fn get_user_notifications<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,limit: Option<u32>,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send;- /// Get a user's active notifications filtered by event item IDs, paginated.+ /// Get a user's non-deleted notifications filtered by event item IDs, paginated.fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(&self,req: GetNotificationsByEventItemIdsRequest<'_>,@@ -597,12 +598,13 @@ whereuser_id: MacroUserIdStr<'_>,limit: Option<u32>,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> Result<Paginated<UserNotificationRow<T>, String>, Report> {let limit = limit.unwrap_or(20).min(500);let rows = self.repository- .get_user_notifications::<T>(user_id, limit, cursor)+ .get_user_notifications::<T>(user_id, limit, cursor, filters).await?;let paginated = rows@@ -628,6 +630,7 @@ wherereq.event_item_ids,limit,req.cursor,+ req.filters,).await?;diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rsindex e6c2a27925..3834c52fda 100644--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs@@ -121,6 +121,7 @@ impl NotificationRepository for MockNotifRepo {_: macro_user_id::user_id::MacroUserIdStr<'_>,_: u32,_: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ _: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {unimplemented!()}@@ -130,6 +131,7 @@ impl NotificationRepository for MockNotifRepo {_: &[uuid::Uuid],_: u32,_: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ _: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {unimplemented!()}diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex e64b9d5c53..9d5a4fea65 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -277,6 +277,7 @@ impl NotificationRepository for MockRepository {_user_id: MacroUserIdStr<'_>,_limit: u32,_cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ _filters: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {Ok(vec![])}@@ -287,6 +288,7 @@ impl NotificationRepository for MockRepository {_event_item_ids: &[Uuid],_limit: u32,_cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ _filters: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {Ok(vec![])}@@ -456,9 +458,10 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {user_id: MacroUserIdStr<'_>,limit: u32,cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ filters: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {(**self)- .get_user_notifications(user_id, limit, cursor)+ .get_user_notifications(user_id, limit, cursor, filters).await}@@ -468,9 +471,16 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {event_item_ids: &[Uuid],limit: u32,cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ filters: crate::domain::models::request::NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {(**self)- .get_user_notifications_by_event_item_ids(user_id, event_item_ids, limit, cursor)+ .get_user_notifications_by_event_item_ids(+ user_id,+ event_item_ids,+ limit,+ cursor,+ filters,+ ).await}diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rsindex 9345f9c3c0..2d43c74290 100644--- a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs@@ -6,7 +6,10 @@ mod test;use crate::domain::{models::{UserNotificationRow,- request::{NotificationStatus, UpdateNotificationsRequest},+ request::{+ NotificationEntityRef, NotificationItemType, NotificationListFilters,+ NotificationStatus, UpdateNotificationsRequest,+ },},service::NotificationReader,};@@ -62,12 +65,41 @@ where#[serde(rename_all = "camelCase")]#[schemars(title = "ListNotifications",- description = "List the current user's active (not deleted, not done) notifications. Returns notifications ordered by most recent first. Use this to show the user their unread or pending notifications."+ description = "List the current user's notifications. By default returns active notifications (not deleted, not done), ordered by most recent first. Use `done` and `seen` to request done/not-done or seen/unseen notifications.")]pub struct ListNotifications {/// Maximum number of notifications to return. Defaults to 20, max 50.#[schemars(description = "Maximum number of notifications to return. Defaults to 20, max 50.")]+ #[serde(default)]pub limit: Option<u32>,++ /// Filter by done status. If omitted, only not-done notifications are returned.+ #[schemars(+ description = "Filter by done status. If omitted, only not-done notifications are returned. Set true for done notifications, false for not-done notifications."+ )]+ #[serde(default)]+ pub done: Option<bool>,++ /// Filter by seen status. If omitted, both seen and unseen notifications are returned.+ #[schemars(+ description = "Filter by seen status. If omitted, both seen and unseen notifications are returned. Set true for seen notifications, false for unseen notifications."+ )]+ #[serde(default)]+ pub seen: Option<bool>,++ /// Filter to specific notification item types. If omitted, returns all types.+ #[schemars(+ description = "Filter to specific notification item types. If omitted, returns all types. Example: [\"email\", \"message\"] returns only email and message notifications."+ )]+ #[serde(default)]+ pub include_types: Option<Vec<NotificationItemType>>,++ /// Filter to notifications for specific entities. If omitted, returns notifications for all entities.+ #[schemars(+ description = "Filter to notifications for specific entities. Pair each id with entityType to avoid ambiguity. Example: [{\"entityType\":\"email\",\"id\":\"...\"}] returns notifications for one email thread."+ )]+ #[serde(default)]+ pub entities: Option<Vec<NotificationEntityRef>>,}/// A single notification item in the list response.@@ -143,6 +175,12 @@ whereMacroUserIdStr((*request_context.user_id).copied()),Some(limit),models_pagination::Query::Sort(CreatedAt, ()),+ NotificationListFilters {+ done: self.done.or(Some(false)),+ seen: self.seen,+ include_types: self.include_types.clone().unwrap_or_default(),+ entities: self.entities.clone().unwrap_or_default(),+ },).await.map_err(|e| ToolCallError {diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/test.rsindex 20e9618cb8..f486bff84f 100644--- a/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs@@ -26,11 +26,31 @@ fn test_list_notifications_deserialization() {let json = r#"{}"#;let tool: ListNotifications = serde_json::from_str(json).unwrap();assert_eq!(tool.limit, None);+ assert_eq!(tool.done, None);+ assert_eq!(tool.seen, None);+ assert_eq!(tool.include_types, None);+ assert_eq!(tool.entities, None);- // With explicit limit- let json = r#"{"limit": 10}"#;+ // With explicit filters+ let json = r#"{"limit": 10, "done": true, "seen": false, "includeTypes": ["email", "message"], "entities": [{"entityType": "email", "id": "thread-1"}]}"#;let tool: ListNotifications = serde_json::from_str(json).unwrap();assert_eq!(tool.limit, Some(10));+ assert_eq!(tool.done, Some(true));+ assert_eq!(tool.seen, Some(false));+ assert_eq!(+ tool.include_types,+ Some(vec![+ NotificationItemType::Email,+ NotificationItemType::Message+ ])+ );+ assert_eq!(+ tool.entities,+ Some(vec![NotificationEntityRef {+ entity_type: NotificationItemType::Email,+ id: "thread-1".to_string()+ }])+ );}// run `cargo test -p notification --features ai_tool inbound::ai_tool::test::print_list_notifications_input_schema -- --nocapture --include-ignored`diff --git a/rust/cloud-storage/notification/src/inbound/http/mod.rs b/rust/cloud-storage/notification/src/inbound/http/mod.rsindex 6bd4816b08..fbe62ba3c2 100644--- a/rust/cloud-storage/notification/src/inbound/http/mod.rs+++ b/rust/cloud-storage/notification/src/inbound/http/mod.rs@@ -27,7 +27,8 @@ use crate::domain::{models::{UserNotificationRow,request::{- GetNotificationsByEventItemIdsRequest, NotificationStatus, UpdateNotificationsRequest,+ GetNotificationsByEventItemIdsRequest, NotificationListFilters, NotificationStatus,+ UpdateNotificationsRequest,},},service::NotificationReader,@@ -125,6 +126,10 @@ pub fn router<S: NotificationReader, T: Serialize + DeserializeOwned + Send + 'spub struct Params {/// the limit on the number of items to return in a pagepub limit: Option<u32>,+ /// Filter by done status. Defaults to false to preserve active-notification behavior.+ pub done: Option<bool>,+ /// Filter by seen status. Omitted means include both seen and unseen notifications.+ pub seen: Option<bool>,}/// the response from listing the users notifications@@ -143,13 +148,23 @@ pub async fn list_user_notifications<>(service: &NotificationRouterState<S>,decoded_jwt: DecodedJwt,- Query(Params { limit }): Query<Params>,+ Query(Params { limit, done, seen }): Query<Params>,cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {let query = cursor.into_query(CreatedAt, ());let result = service.inner- .get_user_notifications::<T>(decoded_jwt.macro_user_id, limit, query)+ .get_user_notifications::<T>(+ decoded_jwt.macro_user_id,+ limit,+ query,+ NotificationListFilters {+ done: done.or(Some(false)),+ seen,+ include_types: Vec::new(),+ entities: Vec::new(),+ },+ ).await.map_err(|e| {tracing::error!(error=?e, "failed to get user notifications");@@ -182,6 +197,8 @@ pub struct BulkGetByEventItemIdsRequest {path = "/v2/user_notifications/item/bulk",params(("limit" = Option<u32>, Query, description = "Size limit per page. Default 20, max 500."),+ ("done" = Option<bool>, Query, description = "Filter by done status. Defaults to false."),+ ("seen" = Option<bool>, Query, description = "Filter by seen status."),("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),),request_body = BulkGetByEventItemIdsRequest,@@ -198,7 +215,7 @@ pub async fn bulk_get_by_event_item_ids<>(State(service): State<NotificationRouterState<S>>,decoded_jwt: DecodedJwt,- Query(Params { limit }): Query<Params>,+ Query(Params { limit, done, seen }): Query<Params>,cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,Json(req): Json<BulkGetByEventItemIdsRequest>,) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {@@ -209,6 +226,12 @@ pub async fn bulk_get_by_event_item_ids<event_item_ids: &req.event_item_ids,limit,cursor: cursor.into_query(CreatedAt, ()),+ filters: NotificationListFilters {+ done: done.or(Some(false)),+ seen,+ include_types: Vec::new(),+ entities: Vec::new(),+ },}).await.map_err(|e| {@@ -339,6 +362,8 @@ async fn bulk_update<S: NotificationReader>(params(("event_item_id" = Uuid, Path, description = "The event item ID"),("limit" = Option<u32>, Query, description = "Size limit per page. Default 20, max 500."),+ ("done" = Option<bool>, Query, description = "Filter by done status. Defaults to false."),+ ("seen" = Option<bool>, Query, description = "Filter by seen status."),("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),),responses(@@ -352,7 +377,7 @@ pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + DeserialState(service): State<NotificationRouterState<S>>,decoded_jwt: DecodedJwt,Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,- Query(Params { limit }): Query<Params>,+ Query(Params { limit, done, seen }): Query<Params>,cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {let result = service@@ -362,6 +387,12 @@ pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + Deserialevent_item_ids: &[event_item_id],limit,cursor: cursor.into_query(CreatedAt, ()),+ filters: NotificationListFilters {+ done: done.or(Some(false)),+ seen,+ include_types: Vec::new(),+ entities: Vec::new(),+ },}).await.map_err(|e| {diff --git a/rust/cloud-storage/notification/src/inbound/http/test.rs b/rust/cloud-storage/notification/src/inbound/http/test.rsindex 2879637b24..b39361b2d8 100644--- a/rust/cloud-storage/notification/src/inbound/http/test.rs+++ b/rust/cloud-storage/notification/src/inbound/http/test.rs@@ -42,6 +42,7 @@ impl NotificationReader for UnreachableService {_user_id: MacroUserIdStr<'_>,_limit: Option<u32>,_cursor: Query<Uuid, CreatedAt, ()>,+ _filters: crate::domain::models::request::NotificationListFilters,) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send{async { unreachable!("should not be called") }@@ -435,6 +436,7 @@ impl NotificationReader for PresignedTestService {_user_id: MacroUserIdStr<'_>,_limit: Option<u32>,_cursor: Query<Uuid, CreatedAt, ()>,+ _filters: crate::domain::models::request::NotificationListFilters,) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send{async { unreachable!() }diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rsindex 77ac59de13..44493bb012 100644--- a/rust/cloud-storage/notification/src/outbound/repository.rs+++ b/rust/cloud-storage/notification/src/outbound/repository.rs@@ -4,26 +4,238 @@mod test;use crate::domain::models::device::DeviceType;+use crate::domain::models::request::NotificationListFilters;use crate::domain::models::{DeviceEndpoint, DisabledNotificationType, NotificationIdAndCollapseKey,SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,};use crate::domain::ports::NotificationRepository;use crate::outbound::device_registration::DeviceRegistrationDbOps;+use chrono::{DateTime, Utc};use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;use models_pagination::{CreatedAt, Query};use rootcause::Report;-use rootcause::prelude::ResultExt;use serde::Serialize;use serde::de::DeserializeOwned;-use sqlx::PgPool;+use sqlx::{PgPool, Postgres, QueryBuilder};use std::collections::{HashMap, HashSet};use std::str::FromStr;use std::sync::Arc;use uuid::Uuid;+type UserNotificationListRow = (+ String,+ Uuid,+ String,+ String,+ bool,+ bool,+ DateTime<Utc>,+ Option<DateTime<Utc>>,+ DateTime<Utc>,+ Option<DateTime<Utc>>,+ serde_json::Value,+ String,+ Option<String>,+);++struct UserNotificationsQueryArgs<'a> {+ user_id: &'a str,+ event_item_ids: Option<&'a [String]>,+ limit: i64,+ cursor_id: Option<Uuid>,+ cursor_timestamp: Option<DateTime<Utc>>,+ filters: &'a NotificationListFilters,+ include_types: &'a [String],+ entity_tokens: &'a [String],+}++fn build_user_notifications_query<'a>(+ args: UserNotificationsQueryArgs<'a>,+) -> QueryBuilder<'a, Postgres> {+ let UserNotificationsQueryArgs {+ user_id,+ event_item_ids,+ limit,+ cursor_id,+ cursor_timestamp,+ filters,+ include_types,+ entity_tokens,+ } = args;++ let mut builder = QueryBuilder::new(+ r#"+ SELECT+ un.user_id as owner_id,+ un.notification_id,+ n.event_item_id,+ n.event_item_type,+ un.sent,+ un.done,+ un.created_at::timestamptz as created_at,+ un.seen_at::timestamptz as viewed_at,+ un.created_at::timestamptz as updated_at,+ un.deleted_at::timestamptz as deleted_at,+ n.metadata as notification_metadata,+ n.notification_event_type as notification_event_type,+ n.sender_id as sender_id+ FROM user_notification un+ JOIN notification n ON n.id = un.notification_id+ WHERE un.user_id = "#,+ );+ builder.push_bind(user_id);++ push_event_item_ids_filter(&mut builder, event_item_ids);+ push_notification_status_filters(&mut builder, filters);+ push_include_types_filter(&mut builder, include_types);+ push_entities_filter(&mut builder, entity_tokens);+ push_cursor_filter(&mut builder, cursor_timestamp, cursor_id);++ builder.push(" ORDER BY un.created_at DESC, un.notification_id DESC LIMIT ");+ builder.push_bind(limit);++ builder+}++fn push_event_item_ids_filter<'a>(+ builder: &mut QueryBuilder<'a, Postgres>,+ event_item_ids: Option<&'a [String]>,+) {+ if let Some(event_item_ids) = event_item_ids {+ builder.push(" AND n.event_item_id = ANY(");+ builder.push_bind(event_item_ids);+ builder.push(")");+ }+}++fn push_notification_status_filters(+ builder: &mut QueryBuilder<'_, Postgres>,+ filters: &NotificationListFilters,+) {+ builder.push(" AND un.deleted_at IS NULL");++ if let Some(done) = filters.done {+ builder.push(" AND un.done = ");+ builder.push_bind(done);+ }++ if let Some(seen) = filters.seen {+ builder.push(" AND (un.seen_at IS NOT NULL) = ");+ builder.push_bind(seen);+ }+}++fn push_include_types_filter(builder: &mut QueryBuilder<'_, Postgres>, include_types: &[String]) {+ if !include_types.is_empty() {+ builder.push(" AND (");+ let mut needs_or = false;+ for clause in [+ include_types+ .iter()+ .any(|t| t == "email")+ .then_some("n.event_item_type = 'email_thread'"),+ include_types.iter().any(|t| t == "message").then_some(+ r#"(+ n.notification_event_type IN ('channel_mention', 'channel_message_reply', 'channel_message_send')+ OR n.metadata ? 'messageId'+ OR n.metadata ? 'message_id'+ )"#,+ ),+ include_types+ .iter()+ .any(|t| t == "channel")+ .then_some("n.event_item_type = 'channel'"),+ include_types.iter().any(|t| t == "document").then_some(+ "n.event_item_type = 'document' AND COALESCE(n.metadata->>'subType', n.metadata->>'sub_type', '') <> 'task'",+ ),+ include_types.iter().any(|t| t == "task").then_some(+ "n.event_item_type = 'document' AND COALESCE(n.metadata->>'subType', n.metadata->>'sub_type', '') = 'task'",+ ),+ include_types+ .iter()+ .any(|t| t == "project")+ .then_some("n.event_item_type = 'project'"),+ include_types+ .iter()+ .any(|t| t == "chat")+ .then_some("n.event_item_type = 'chat'"),+ include_types+ .iter()+ .any(|t| t == "call")+ .then_some("n.event_item_type = 'call'"),+ ]+ .into_iter()+ .flatten()+ {+ if needs_or {+ builder.push(" OR ");+ }+ builder.push("(");+ builder.push(clause);+ builder.push(")");+ needs_or = true;+ }+ builder.push(")");+ }+}++fn push_entities_filter<'a>(builder: &mut QueryBuilder<'a, Postgres>, entity_tokens: &'a [String]) {+ if !entity_tokens.is_empty() {+ builder.push(" AND (");++ builder.push("(n.event_item_type = 'email_thread' AND 'email:' || n.event_item_id = ANY(");+ builder.push_bind(entity_tokens);+ builder.push(")) OR ");++ builder.push("(n.event_item_type = 'channel' AND 'channel:' || n.event_item_id = ANY(");+ builder.push_bind(entity_tokens);+ builder.push(")) OR ");++ builder.push("(n.event_item_type = 'document' AND 'document:' || n.event_item_id = ANY(");+ builder.push_bind(entity_tokens);+ builder.push(")) OR ");++ builder.push("(n.event_item_type = 'document' AND COALESCE(n.metadata->>'subType', n.metadata->>'sub_type', '') = 'task' AND 'task:' || n.event_item_id = ANY(");+ builder.push_bind(entity_tokens);+ builder.push(")) OR ");++ builder.push("(n.event_item_type = 'project' AND 'project:' || n.event_item_id = ANY(");+ builder.push_bind(entity_tokens);+ builder.push(")) OR ");++ builder.push("(n.event_item_type = 'chat' AND 'chat:' || n.event_item_id = ANY(");+ builder.push_bind(entity_tokens);+ builder.push(")) OR ");++ builder.push("(n.event_item_type = 'call' AND 'call:' || n.event_item_id = ANY(");+ builder.push_bind(entity_tokens);+ builder.push(")) OR ");++ builder.push("('message:' || COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = ANY(");+ builder.push_bind(entity_tokens);+ builder.push("))");++ builder.push(")");+ }+}++fn push_cursor_filter(+ builder: &mut QueryBuilder<'_, Postgres>,+ cursor_timestamp: Option<DateTime<Utc>>,+ cursor_id: Option<Uuid>,+) {+ if let (Some(cursor_timestamp), Some(cursor_id)) = (cursor_timestamp, cursor_id) {+ builder.push(" AND (un.created_at, un.notification_id) < (");+ builder.push_bind(cursor_timestamp);+ builder.push(", ");+ builder.push_bind(cursor_id);+ builder.push(")");+ }+}+/// Local representation of the `notification_device_type_option` Postgres enum/// for compile-time checked sqlx queries.#[derive(Debug, sqlx::Type)]@@ -115,23 +327,25 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {notification_ids: &[Uuid],) -> impl std::future::Future<Output = Result<Vec<NotificationIdAndCollapseKey>, Report>> + Send;- /// Get a user's active (not deleted, not done) notifications with cursor-based pagination.+ /// Get a user's non-deleted notifications with cursor-based pagination.///- /// The metadata JSON column is deserialized into `T`.+ /// The metadata JSON column is deserialized into `T`. `filters` controls done/seen status.fn get_user_notifications<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> impl std::future::Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;- /// Get a user's active notifications filtered by event item IDs, with cursor-based pagination.+ /// Get a user's non-deleted notifications filtered by event item IDs, with cursor-based pagination.fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,event_item_ids: &[Uuid],limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> impl std::future::Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;/// Get a single user notification by ID.@@ -473,94 +687,95 @@ impl NotificationDbOps for PgPool {user_id: MacroUserIdStr<'_>,limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {let query_limit = limit as i64;let (cursor_id, cursor_timestamp) = cursor.vals();-- let rows = sqlx::query!(- r#"- SELECT- un.user_id as owner_id,- un.notification_id,- n.event_item_id,- n.event_item_type,- un.sent,- un.done,- un.created_at::timestamptz as "created_at!",- un.seen_at::timestamptz as viewed_at,- un.created_at::timestamptz as "updated_at!",- un.deleted_at::timestamptz,- n.metadata as "notification_metadata: serde_json::Value",- n.notification_event_type as notification_event_type,- n.sender_id as sender_id- FROM user_notification un- JOIN notification n ON n.id = un.notification_id- WHERE un.user_id = $1- AND un.deleted_at IS NULL- AND un.done = false- AND (($3::timestamptz IS NULL)- OR (un.created_at, un.notification_id) < ($3, $4))- ORDER BY un.created_at DESC, un.notification_id DESC- LIMIT $2- "#,- user_id.as_ref(),- query_limit,- cursor_timestamp,- cursor_id as _,- )+ let include_types = filters.include_type_tokens();+ let entity_tokens = filters.entity_tokens();++ let rows = build_user_notifications_query(UserNotificationsQueryArgs {+ user_id: user_id.as_ref(),+ event_item_ids: None,+ limit: query_limit,+ cursor_id: cursor_id.copied(),+ cursor_timestamp: cursor_timestamp.copied(),+ filters: &filters,+ include_types: &include_types,+ entity_tokens: &entity_tokens,+ })+ .build_query_as::<UserNotificationListRow>().fetch_all(self).await?;- Ok(rows- .into_iter()- .map(- |row| -> Result<UserNotificationRow<T>, rootcause::Report<Uuid>> {- let entity = EntityType::from_str(&row.event_item_type)- .map_err(|e| rootcause::report!(e))- .attach(row.event_item_type)- .context(row.notification_id)?- .with_entity_string(row.event_item_id);-- let sender_id = row- .sender_id- .map(|s| MacroUserIdStr::parse_from_str(&s).map(CowLike::into_owned))- .transpose()- .map_err(|e| rootcause::report!(e))- .context(row.notification_id)?;-- let owner_id = MacroUserIdStr::parse_from_str(&row.owner_id)- .map(CowLike::into_owned)- .map_err(|e| rootcause::report!(e))- .context(row.notification_id)?;-- let notification_metadata =- serde_json::from_value::<T>(row.notification_metadata)- .map_err(|e| rootcause::report!(e))- .context(row.notification_id)?;-- Ok(UserNotificationRow {- owner_id,- notification_id: row.notification_id,- notification_event_type: row.notification_event_type,- entity,- sent: row.sent,- done: row.done,- created_at: row.created_at,- viewed_at: row.viewed_at,- updated_at: row.updated_at,- deleted_at: row.deleted_at,- notification_metadata,- sender_id,- })- },- )- .inspect(|r: &Result<UserNotificationRow<T>, _>| {- if let Err(e) = r {- tracing::warn!("skipping invalid notification: {e:?}");+ let mut notifications = Vec::with_capacity(rows.len());+ for row in rows {+ let (+ owner_id,+ notification_id,+ event_item_id,+ event_item_type,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ notification_event_type,+ sender_id,+ ) = row;++ let entity = match EntityType::from_str(&event_item_type) {+ Ok(entity_type) => entity_type.with_entity_string(event_item_id),+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;}- })- .filter_map(Result::ok)- .collect())+ };+ let sender_id = match sender_id+ .map(|s| MacroUserIdStr::parse_from_str(&s).map(CowLike::into_owned))+ .transpose()+ {+ Ok(sender_id) => sender_id,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };+ let owner_id = match MacroUserIdStr::parse_from_str(&owner_id).map(CowLike::into_owned)+ {+ Ok(owner_id) => owner_id,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };+ let notification_metadata = match serde_json::from_value::<T>(notification_metadata) {+ Ok(metadata) => metadata,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };++ notifications.push(UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ sender_id,+ });+ }++ Ok(notifications)}async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(@@ -569,93 +784,96 @@ impl NotificationDbOps for PgPool {event_item_ids: &[Uuid],limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {let query_limit = limit as i64;let (cursor_id, cursor_timestamp) = cursor.vals();let event_item_ids: Vec<String> = event_item_ids.iter().map(|id| id.to_string()).collect();-- let rows = sqlx::query!(- r#"- SELECT- un.user_id as owner_id,- un.notification_id,- n.event_item_id,- n.event_item_type,- un.sent,- un.done,- un.created_at::timestamptz as "created_at!",- un.seen_at::timestamptz as viewed_at,- un.created_at::timestamptz as "updated_at!",- un.deleted_at::timestamptz,- n.metadata as "notification_metadata: serde_json::Value",- n.notification_event_type as notification_event_type,- n.sender_id as sender_id- FROM user_notification un- JOIN notification n ON n.id = un.notification_id- WHERE un.user_id = $1- AND n.event_item_id = ANY($2)- AND un.deleted_at IS NULL- AND un.done = false- AND (($4::timestamptz IS NULL)- OR (un.created_at, un.notification_id) < ($4, $5))- ORDER BY un.created_at DESC, un.notification_id DESC- LIMIT $3- "#,- user_id.as_ref(),- &event_item_ids,- query_limit,- cursor_timestamp,- cursor_id as _,- )+ let include_types = filters.include_type_tokens();+ let entity_tokens = filters.entity_tokens();++ let rows = build_user_notifications_query(UserNotificationsQueryArgs {+ user_id: user_id.as_ref(),+ event_item_ids: Some(&event_item_ids),+ limit: query_limit,+ cursor_id: cursor_id.copied(),+ cursor_timestamp: cursor_timestamp.copied(),+ filters: &filters,+ include_types: &include_types,+ entity_tokens: &entity_tokens,+ })+ .build_query_as::<UserNotificationListRow>().fetch_all(self).await?;- Ok(rows- .into_iter()- .map(|row| -> Result<UserNotificationRow<T>, Report<Uuid>> {- let entity = EntityType::from_str(&row.event_item_type)- .map_err(|e| rootcause::report!(e))- .context(row.notification_id)?- .with_entity_string(row.event_item_id);-- let sender_id = row- .sender_id- .map(|s| MacroUserIdStr::parse_from_str(&s).map(CowLike::into_owned))- .transpose()- .map_err(|e| rootcause::report!(e))- .context(row.notification_id)?;-- let owner_id = MacroUserIdStr::parse_from_str(&row.owner_id)- .map(CowLike::into_owned)- .map_err(|e| rootcause::report!(e))- .context(row.notification_id)?;+ let mut notifications = Vec::with_capacity(rows.len());+ for row in rows {+ let (+ owner_id,+ notification_id,+ event_item_id,+ event_item_type,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ notification_event_type,+ sender_id,+ ) = row;++ let entity = match EntityType::from_str(&event_item_type) {+ Ok(entity_type) => entity_type.with_entity_string(event_item_id),+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };+ let sender_id = match sender_id+ .map(|s| MacroUserIdStr::parse_from_str(&s).map(CowLike::into_owned))+ .transpose()+ {+ Ok(sender_id) => sender_id,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };+ let owner_id = match MacroUserIdStr::parse_from_str(&owner_id).map(CowLike::into_owned)+ {+ Ok(owner_id) => owner_id,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };+ let notification_metadata = match serde_json::from_value::<T>(notification_metadata) {+ Ok(metadata) => metadata,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };- let notification_metadata = serde_json::from_value::<T>(row.notification_metadata)- .map_err(|e| rootcause::report!(e))- .context(row.notification_id)?;+ notifications.push(UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ sender_id,+ });+ }- Ok(UserNotificationRow {- owner_id,- notification_id: row.notification_id,- notification_event_type: row.notification_event_type,- entity,- sent: row.sent,- done: row.done,- created_at: row.created_at,- viewed_at: row.viewed_at,- updated_at: row.updated_at,- deleted_at: row.deleted_at,- notification_metadata,- sender_id,- })- })- .inspect(|r: &Result<UserNotificationRow<T>, _>| {- if let Err(e) = r {- tracing::warn!("skipping invalid notification: {e:?}");- }- })- .filter_map(Result::ok)- .collect())+ Ok(notifications)}async fn get_user_notification_by_id<T: DeserializeOwned + Send>(@@ -964,8 +1182,11 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificatiuser_id: MacroUserIdStr<'_>,limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {- self.db.get_user_notifications(user_id, limit, cursor).await+ self.db+ .get_user_notifications(user_id, limit, cursor, filters)+ .await}async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(@@ -974,9 +1195,16 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificatievent_item_ids: &[Uuid],limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {self.db- .get_user_notifications_by_event_item_ids(user_id, event_item_ids, limit, cursor)+ .get_user_notifications_by_event_item_ids(+ user_id,+ event_item_ids,+ limit,+ cursor,+ filters,+ ).await}diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rsindex 22215367ab..9a4100176c 100644--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs@@ -309,6 +309,7 @@ async fn test_get_user_notifications(pool: Pool<Postgres>) {MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),10,Query::Sort(CreatedAt, ()),+ NotificationListFilters::active(),).await.unwrap();@@ -329,6 +330,143 @@ async fn test_get_user_notifications(pool: Pool<Postgres>) {assert_eq!(row.notification_metadata.message, "hello");}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_notifications"))+)]+async fn test_get_user_notifications_filters_done_and_seen(pool: Pool<Postgres>) {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();++ pool.mark_notifications_seen(&user, &[notification_id])+ .await+ .unwrap();+ pool.mark_notifications_done(&user, &[notification_id], true)+ .await+ .unwrap();++ let active: Vec<UserNotificationRow<TestNotification>> = pool+ .get_user_notifications(+ user.clone(),+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters::active(),+ )+ .await+ .unwrap();+ assert!(active.is_empty());++ let done_and_seen: Vec<UserNotificationRow<TestNotification>> = pool+ .get_user_notifications(+ user.clone(),+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters {+ done: Some(true),+ seen: Some(true),+ include_types: Vec::new(),+ entities: Vec::new(),+ },+ )+ .await+ .unwrap();+ assert_eq!(done_and_seen.len(), 1);++ let unseen: Vec<UserNotificationRow<TestNotification>> = pool+ .get_user_notifications(+ user,+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters {+ done: None,+ seen: Some(false),+ include_types: Vec::new(),+ entities: Vec::new(),+ },+ )+ .await+ .unwrap();+ assert!(unseen.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_notifications"))+)]+async fn test_get_user_notifications_filters_type_and_entity(pool: Pool<Postgres>) {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let document_results: Vec<UserNotificationRow<TestNotification>> = pool+ .get_user_notifications(+ user.clone(),+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters {+ done: Some(false),+ seen: None,+ include_types: vec![crate::domain::models::request::NotificationItemType::Document],+ entities: Vec::new(),+ },+ )+ .await+ .unwrap();+ assert_eq!(document_results.len(), 1);++ let email_results: Vec<UserNotificationRow<TestNotification>> = pool+ .get_user_notifications(+ user.clone(),+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters {+ done: Some(false),+ seen: None,+ include_types: vec![crate::domain::models::request::NotificationItemType::Email],+ entities: Vec::new(),+ },+ )+ .await+ .unwrap();+ assert!(email_results.is_empty());++ let entity_results: Vec<UserNotificationRow<TestNotification>> = pool+ .get_user_notifications(+ user.clone(),+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters {+ done: Some(false),+ seen: None,+ include_types: Vec::new(),+ entities: vec![crate::domain::models::request::NotificationEntityRef {+ entity_type: crate::domain::models::request::NotificationItemType::Document,+ id: "item-1".to_string(),+ }],+ },+ )+ .await+ .unwrap();+ assert_eq!(entity_results.len(), 1);++ let wrong_entity_results: Vec<UserNotificationRow<TestNotification>> = pool+ .get_user_notifications(+ user,+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters {+ done: Some(false),+ seen: None,+ include_types: Vec::new(),+ entities: vec![crate::domain::models::request::NotificationEntityRef {+ entity_type: crate::domain::models::request::NotificationItemType::Email,+ id: "item-1".to_string(),+ }],+ },+ )+ .await+ .unwrap();+ assert!(wrong_entity_results.is_empty());+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("user_notifications_with_invalid"))@@ -339,6 +477,7 @@ async fn test_get_user_notifications_skips_invalid_entity_type(pool: Pool<PostgrMacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),10,Query::Sort(CreatedAt, ()),+ NotificationListFilters::active(),).await.unwrap();@@ -372,6 +511,7 @@ async fn test_get_user_notifications_by_event_item_ids_skips_invalid(pool: Pool<&[valid_item, invalid_entity_item, invalid_metadata_item],10,Query::Sort(CreatedAt, ()),+ NotificationListFilters::active(),).await.unwrap();@@ -393,6 +533,7 @@ async fn test_get_user_notifications_empty(pool: Pool<Postgres>) {MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),10,Query::Sort(CreatedAt, ()),+ NotificationListFilters::active(),).await.unwrap();@@ -500,7 +641,12 @@ async fn test_create_notification_stores_bare_metadata(pool: Pool<Postgres>) {// Verify round-trip: get_user_notifications deserializes the bare metadata back into Tlet rows: Vec<UserNotificationRow<TestNotification>> = pool- .get_user_notifications(recipient, 10, Query::Sort(CreatedAt, ()))+ .get_user_notifications(+ recipient,+ 10,+ Query::Sort(CreatedAt, ()),+ NotificationListFilters::active(),+ ).await.unwrap();diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rsindex a93ea3b5cf..1f66870c42 100644--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs@@ -1,6 +1,7 @@use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{CreatedAt, Query};use notification::domain::models::TaggedContent;+use notification::domain::models::request::NotificationListFilters;use notification::domain::models::{DeviceEndpoint, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,UserNotificationRow, device::DeviceType,@@ -117,9 +118,10 @@ impl NotificationRepository for SandboxNotificationRepository {user_id: MacroUserIdStr<'_>,limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {self.inner- .get_user_notifications(user_id, limit, cursor)+ .get_user_notifications(user_id, limit, cursor, filters).await}@@ -129,9 +131,16 @@ impl NotificationRepository for SandboxNotificationRepository {event_item_ids: &[Uuid],limit: u32,cursor: Query<Uuid, CreatedAt, ()>,+ filters: NotificationListFilters,) -> Result<Vec<UserNotificationRow<T>>, Report> {self.inner- .get_user_notifications_by_event_item_ids(user_id, event_item_ids, limit, cursor)+ .get_user_notifications_by_event_item_ids(+ user_id,+ event_item_ids,+ limit,+ cursor,+ filters,+ ).await}