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: make unrolled notifications good (#1177)
Peter Chinmandcc3c6e87530
diff --git a/js/app/packages/core/user/displayName.ts b/js/app/packages/core/user/displayName.tsindex aa4238683e..4aac395033 100644--- a/js/app/packages/core/user/displayName.ts+++ b/js/app/packages/core/user/displayName.ts@@ -93,21 +93,8 @@ async function batchFetchNames(ids: string[]) {setUserDisplayNames((prev) => ({ ...prev, ...updates }));}-export function useDisplayName(- id: MacroId | undefined | null-): UserNamePreviewFetcher {- if (!id) {- const dummy_accessor = () => {- return '';- };-- const dummy_controls = {- refetch: () => {},- mutate: (_value: UserNameItem) => {},- };-- return [dummy_accessor, dummy_controls];- }+/** Shared hook that handles caching/fetching and returns the underlying UserNameItem */+function useUserNameItem(id: MacroId) {const cached = userDisplayNames[id];const cacheExpired =cached &&@@ -131,24 +118,80 @@ export function useDisplayName(}});- const accessor = () => {- const _item = unwrap(userDisplayNames[id]);- return defaultNameTransform(_item);+ const getItem = () => unwrap(userDisplayNames[id]);++ const refetch = () => {+ setUserDisplayNames(id, {+ loading: true,+ _createdAt: new Date(),+ id: id,+ });+ queueItemsForFetch([id]);};- const controls = {- refetch: () => {- setUserDisplayNames(id, {- loading: true,- _createdAt: new Date(),- id: id,- });- queueItemsForFetch([id]);- },- mutate: (value: UserNameItem) => {- setUserDisplayNames(id, value);- },+ const mutate = (value: UserNameItem) => {+ setUserDisplayNames(id, value);};- return [accessor, controls];+ return { getItem, refetch, mutate };+}++export type DisplayNameParts = {+ firstName: () => string;+ lastName: () => string;+ fullName: () => string;+ refetch: () => void;+};++export function useDisplayNameParts(+ id: MacroId | undefined | null+): DisplayNameParts {+ if (!id) {+ return {+ firstName: () => '',+ lastName: () => '',+ fullName: () => '',+ refetch: () => {},+ };+ }++ const { getItem, refetch } = useUserNameItem(id);++ const firstName = () => {+ const item = getItem();+ if (item?.loading) return '';+ const name = item?.firstName;+ return name && name !== 'N/A' ? name : '';+ };++ const lastName = () => {+ const item = getItem();+ if (item?.loading) return '';+ const name = item?.lastName;+ return name && name !== 'N/A' ? name : '';+ };++ const fullName = () => defaultNameTransform(getItem());++ return { firstName, lastName, fullName, refetch };+}++export function useDisplayName(+ id: MacroId | undefined | null+): UserNamePreviewFetcher {+ if (!id) {+ return [+ () => '',+ {+ refetch: () => {},+ mutate: (_value: UserNameItem) => {},+ },+ ];+ }++ const { getItem, refetch, mutate } = useUserNameItem(id);++ const accessor = () => defaultNameTransform(getItem());++ return [accessor, { refetch, mutate }];}diff --git a/js/app/packages/core/user/index.ts b/js/app/packages/core/user/index.tsindex f0863e2782..257704e455 100644--- a/js/app/packages/core/user/index.ts+++ b/js/app/packages/core/user/index.ts@@ -7,7 +7,11 @@ export {type WithCustomUserInput,} from './combinedRecipient';export { useContacts } from './contactService';-export { useDisplayName } from './displayName';+export {+ type DisplayNameParts,+ useDisplayName,+ useDisplayNameParts,+} from './displayName';export {emailToMacroId,isMacroId,diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsxindex 8bbac1c60f..048a34e3a2 100644--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx@@ -2,22 +2,38 @@ import { EntityIcon } from '@core/component/EntityIcon';import type { Property } from '@core/component/Properties/types';import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';import '@core/directive/dnd';+import { useDragOperation } from '@app/component/ItemDragAndDrop';+import { useEmail, useUserId } from '@core/context/user';import { TOKENS } from '@core/hotkey/tokens';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { matches } from '@core/util/match';+import ArrowBendUpLeftIcon from '@icon/regular/arrow-bend-up-left.svg';+import AtIcon from '@icon/regular/at.svg';+import ChatIcon from '@icon/regular/chat.svg';import CheckIcon from '@icon/regular/check.svg';-import { tryToTypedNotification } from '@notifications';-import { useEmail, useUserId } from '@core/context/user';+import {+ getAllNotificationsFromGroup,+ getMostRecentNotification,+ isChannelMessageReply,+ type NotificationStack,+ stackNotifications,+ type TypedNotification,+ tryToTypedNotification,+} from '@notifications';import { formatDocumentName } from '@service-storage/util/filename';import { syncServiceClient } from '@service-sync/client';import { mergeRefs } from '@solid-primitives/refs';import { createDraggable } from '@thisbeyond/solid-dnd';-import { useDragOperation } from '@app/component/ItemDragAndDrop';import { getIconConfig } from 'core/component/EntityIcon';import { StaticMarkdown } from 'core/component/LexicalMarkdown/component/core/StaticMarkdown';import { unifiedListMarkdownTheme } from 'core/component/LexicalMarkdown/theme';import { UserIcon } from 'core/component/UserIcon';-import { emailToMacroId, tryMacroId, useDisplayName } from 'core/user';+import {+ emailToMacroId,+ tryMacroId,+ useDisplayName,+ useDisplayNameParts,+} from 'core/user';import type { JSX, ParentProps, Ref } from 'solid-js';import {createDeferred,@@ -39,12 +55,17 @@ import {type ProjectContainedEntity,} from '../queries/project';import { isSearchEntity } from '../queries/search';+import type { EntityDragData } from '../types/drag';import {type EntityData,isTaskEntity,type ProjectEntity,} from '../types/entity';-import type { Notification, WithNotification } from '../types/notification';+import type {+ Notification,+ WithNotification,+ WithStackedNotifications,+} from '../types/notification';import type {ChannelContentHitData,ContentHitData,@@ -52,7 +73,6 @@ import type {SearchLocation,WithSearch,} from '../types/search';-import type { EntityDragData } from '../types/drag';import { KeyPropertiesGrid } from './EntityPropertyValues';export type EntityClickEvent = Parameters<@@ -281,6 +301,7 @@ function NotificationRow(props: {notification: Notification;onClick?: NotificationClickHandler;entity: EntityData;+ icon?: (props: { class?: string }) => JSX.Element;}) {const [userName] = useDisplayName(tryMacroId(props.notification.senderId ?? '')@@ -296,6 +317,9 @@ function NotificationRow(props: {if (props.notification.notificationEventType === 'task_assigned') {return 'assigned to you';}+ if (props.notification.notificationEventType === 'channel_mention') {+ return 'mentioned you';+ }const metadata = tryToTypedNotification(props.notification@@ -358,7 +382,12 @@ function NotificationRow(props: {}><div class="flex size-5 shrink-0 items-center justify-center mr-1">- <UserIcon id={props.notification.senderId!} size="xs" />+ <Show+ when={props.icon}+ fallback={<UserIcon id={props.notification.senderId!} size="xs" />}+ >+ <Dynamic component={props.icon} class="size-4 text-ink-muted" />+ </Show></div><div class="flex gap-1 w-full min-w-0 overflow-hidden items-baseline"><div class="w-[20cqw] shrink-0 truncate min-w-0">@@ -376,6 +405,237 @@ function NotificationRow(props: {);}+/**+ * Shared row component for stacked notifications (new messages and replies)+ */+function StackedNotificationRow(props: {+ notifications: TypedNotification[];+ title: JSX.Element;+ icon: (props: { class?: string }) => JSX.Element;+ onClick?: (e: EntityClickEvent) => void;+}) {+ const mostRecent = () => props.notifications[0];++ // Get up to 3 unique sender IDs for avatar display+ const senderIds = createMemo(() => {+ const ids = new Set<string>();+ for (const n of props.notifications) {+ if (n.senderId) {+ ids.add(n.senderId);+ if (ids.size >= 3) break;+ }+ }+ return Array.from(ids);+ });++ // Get the sender of the most recent message+ const mostRecentSenderId = () => mostRecent()?.senderId ?? '';+ const [mostRecentSenderName] = useDisplayName(+ tryMacroId(mostRecentSenderId())+ );++ const messageContent = createMemo(() => {+ const metadata = mostRecent()?.notificationMetadata;+ if (metadata && 'messageContent' in metadata) {+ return metadata.messageContent?.trim() ?? '';+ }+ return '';+ });++ return (+ <CollapsibleListRow showThreadBorder onClick={props.onClick}>+ <div class="flex size-5 shrink-0 items-center justify-center mr-1">+ <props.icon class="size-4 text-ink-muted" />+ </div>+ <div class="flex gap-1 w-full overflow-hidden items-baseline">+ {/* Count + Stacked avatars */}+ <div class="min-w-[20cqw] shrink-0 flex items-center gap-1">+ <span>{props.title}</span>+ <div class="flex shrink-0 items-center">+ <For each={senderIds()}>+ {(id, index) => (+ <div+ class="flex size-5 items-center justify-center"+ classList={{ '-ml-2': index() > 0 }}+ >+ <UserIcon id={id} size="xs" />+ </div>+ )}+ </For>+ </div>+ </div>+ {/* Sender avatar + name + message content */}+ <Show when={mostRecentSenderId()}>+ <div class="flex items-center gap-1 flex-1 min-w-0">+ <span class="shrink-0 font-medium">{mostRecentSenderName()}</span>+ <Show when={messageContent()}>+ {(content) => (+ <div class="text-ink-muted truncate flex items-center flex-1 min-w-0">+ <StaticMarkdown+ markdown={content()}+ theme={unifiedListMarkdownTheme}+ singleLine={true}+ />+ </div>+ )}+ </Show>+ </div>+ </Show>+ </div>+ <div class="shrink-0 font-mono text-xs touch:mobile-width:text-sm uppercase text-ink-extra-muted ml-2">+ {createFormattedDate(mostRecent().createdAt)}+ </div>+ </CollapsibleListRow>+ );+}++/**+ * Row component for stacked new messages+ */+function StackedNewMessagesRow(props: {+ group: NotificationStack & { type: 'channel_message_send' };+ onClick?: StackedNotificationClickHandler;+ entity: EntityData;+}) {+ const count = () => props.group.notifications.length;++ return (+ <StackedNotificationRow+ notifications={props.group.notifications}+ title={<>{count()} New Messages</>}+ icon={ChatIcon}+ onClick={+ props.onClick+ ? (e) =>+ props.onClick?.({+ group: props.group,+ entity: props.entity,+ event: e,+ })+ : undefined+ }+ />+ );+}++/**+ * Row component for stacked replies to a thread+ */+function StackedRepliesRow(props: {+ group: NotificationStack & { type: 'channel_message_reply' };+ onClick?: StackedNotificationClickHandler;+ entity: EntityData;+}) {+ const count = () => props.group.notifications.length;++ // Derive from notifications[0] (mostRecent)+ const threadParentSenderId = () => {+ const notification = props.group.notifications[0];+ if (!notification) return '';+ const typed = tryToTypedNotification(notification);+ if (!typed || !isChannelMessageReply(typed) || !typed.notificationMetadata)+ return '';+ return typed.notificationMetadata.threadParentSenderId ?? '';+ };++ const { firstName } = useDisplayNameParts(tryMacroId(threadParentSenderId()));++ const title = () => (+ <>+ {count()} {count() === 1 ? 'Reply' : 'Replies'}+ <Show when={firstName()}>{(name) => <> to {name}</>}</Show>+ </>+ );++ return (+ <StackedNotificationRow+ notifications={props.group.notifications}+ title={title()}+ icon={ArrowBendUpLeftIcon}+ onClick={+ props.onClick+ ? (e) =>+ props.onClick?.({+ group: props.group,+ entity: props.entity,+ event: e,+ })+ : undefined+ }+ />+ );+}++type StackedNotificationClickHandler<T extends EntityData = EntityData> =+ (args: {+ group: NotificationStack;+ entity: T;+ event: EntityClickEvent;+ }) => void;++/**+ * Renderer component that switches between different stacked notification types+ */+function StackedNotificationRenderer(props: {+ group: NotificationStack;+ onClick?: NotificationClickHandler;+ onClickStacked?: StackedNotificationClickHandler;+ entity: EntityData;+}) {+ return (+ <Switch>+ <Match when={props.group.type === 'channel_message_send' && props.group}>+ {(group) => (+ <StackedNewMessagesRow+ group={+ group() as NotificationStack & { type: 'channel_message_send' }+ }+ onClick={props.onClickStacked}+ entity={props.entity}+ />+ )}+ </Match>+ <Match when={props.group.type === 'channel_message_reply' && props.group}>+ {(group) => (+ <StackedRepliesRow+ group={+ group() as NotificationStack & { type: 'channel_message_reply' }+ }+ onClick={props.onClickStacked}+ entity={props.entity}+ />+ )}+ </Match>+ <Match when={props.group.type === 'channel_mention' && props.group}>+ {(group) => (+ <NotificationRow+ notification={group().notifications[0]}+ onClick={props.onClick}+ entity={props.entity}+ icon={AtIcon}+ />+ )}+ </Match>+ <Match+ when={+ props.group.type !== 'channel_message_send' &&+ props.group.type !== 'channel_message_reply' &&+ props.group.type !== 'channel_mention' &&+ props.group+ }+ >+ {(group) => (+ <NotificationRow+ notification={group().notifications[0]}+ onClick={props.onClick}+ entity={props.entity}+ />+ )}+ </Match>+ </Switch>+ );+}+function ContentHitRow(props: {allData: ContentHitData[];data: ContentHitData;@@ -441,7 +701,9 @@ function ContentHitRow(props: {//type NotificationClickHandler<T extends EntityData = EntityData> =- EntityClickHandler<T & { notification: Notification }>;+ EntityClickHandler<+ WithStackedNotifications<T & { notification: Notification }>+ >;interface EntityProps<T extends WithNotification<EntityData>>extends ParentProps {@@ -540,6 +802,10 @@ export function EntityWithEverything(return validNotifications().filter(({ done }) => !done);};+ const stackedNotificationsGroups = createMemo(() =>+ stackNotifications(notDoneNotifications())+ );+const isSearch = createMemo(() => !!props.searchActive && isSearchEntity(props.entity));@@ -1214,7 +1480,7 @@ export function EntityWithEverything(</CollapsibleList></div></Show>- {/* Notifications */}+ {/* Notifications (stacked by type) */}<Showwhen={props.showUnrollNotifications &&@@ -1223,11 +1489,27 @@ export function EntityWithEverything(}><div class="relative col-2 col-end-4 pb-2 @max-md/uList:col-auto @max-md/uList:w-full @max-md/uList:mt-1">- <CollapsibleList items={notDoneNotifications()} threadBorder>- {(notification) => (- <NotificationRow- notification={notification}+ <CollapsibleList items={stackedNotificationsGroups()} threadBorder>+ {(group) => (+ <StackedNotificationRenderer+ group={group}onClick={props.onClickNotification}+ onClickStacked={(args) => {+ // Navigate to the most recent notification in the stack+ const mostRecent = getMostRecentNotification(args.group);+ props.onClickNotification?.({+ type: 'entity',+ entity: {+ ...args.entity,+ notification: mostRecent,+ // Attach all notifications in the group for bulk operations+ stackedNotifications: getAllNotificationsFromGroup(+ args.group+ ),+ },+ event: args.event,+ });+ }}entity={props.entity}/>)}diff --git a/js/app/packages/macro-entity/src/types/notification.ts b/js/app/packages/macro-entity/src/types/notification.tsindex 5af6a66ee5..d4f3c12e2d 100644--- a/js/app/packages/macro-entity/src/types/notification.ts+++ b/js/app/packages/macro-entity/src/types/notification.ts@@ -7,3 +7,12 @@ export type Notification = Omit<UserNotification, 'ownerId'>;export type WithNotification<T> = T & {notifications?: Accessor<Notification[]>;};++/**+ * Extended notification type that includes stacked notifications for bulk operations.+ * When clicking a stacked notification row, this array contains all notifications in the stack+ * so they can be bulk-marked as done.+ */+export type WithStackedNotifications<T> = T & {+ stackedNotifications?: Notification[];+};diff --git a/js/app/packages/notifications/index.ts b/js/app/packages/notifications/index.tsindex 67b8a11927..c362ec5e5c 100644--- a/js/app/packages/notifications/index.ts+++ b/js/app/packages/notifications/index.ts@@ -83,6 +83,13 @@ export type {export { useNotificationSettings } from './notification-settings';export type { NotificationSource } from './notification-source';export { createNotificationSource } from './notification-source';+export type { NotificationStack } from './notification-stacking';+export {+ getAllNotificationsFromGroup,+ getMostRecentNotification,+ getThreadId,+ stackNotifications,+} from './notification-stacking';export { fetchNotificationsForEntities } from './queries/entities-notifications-query';export { createMutedEntitiesQuery } from './queries/muted-entities-query';export type {diff --git a/js/app/packages/notifications/notification-stacking.ts b/js/app/packages/notifications/notification-stacking.tsnew file mode 100644index 0000000000..ec864e7e29--- /dev/null+++ b/js/app/packages/notifications/notification-stacking.ts@@ -0,0 +1,139 @@+import {+ isChannelMention,+ isChannelMessageReply,+ isChannelMessageSend,+ type TypedNotification,+ tryToTypedNotification,+} from './notification-metadata';+import type { UnifiedNotification } from './types';++export interface NotificationStack {+ type: TypedNotification['notificationEventType'];+ notifications: TypedNotification[];+}++/**+ * Gets the most recent notification from a group (first item, sorted by recency)+ */+export function getMostRecentNotification(+ group: NotificationStack+): UnifiedNotification {+ return group.notifications[0];+}++/**+ * Gets all notifications from a group+ */+export function getAllNotificationsFromGroup(+ group: NotificationStack+): UnifiedNotification[] {+ return group.notifications;+}++/**+ * Gets the threadId from a replies stack+ */+export function getThreadId(group: NotificationStack): string {+ const notification = group.notifications[0];+ if (notification.notificationEventType === 'channel_message_reply') {+ return notification.notificationMetadata?.threadId ?? '';+ }+ return '';+}++/**+ * Stacks notifications by type for unrolled notification display.+ */+export function stackNotifications(+ notifications: UnifiedNotification[]+): NotificationStack[] {+ // Collect mention messageIds for shadowing+ const mentionedMsgIds = new Set(+ notifications+ .filter(isChannelMention)+ .map((n) => n.notificationMetadata?.messageId)+ .filter(Boolean)+ );++ const isShadowed = (n: { notificationMetadata?: { messageId?: string } }) =>+ n.notificationMetadata?.messageId &&+ mentionedMsgIds.has(n.notificationMetadata.messageId);++ // Partition by type+ const mentions = notifications.filter(isChannelMention);+ const newMsgs = notifications+ .filter(isChannelMessageSend)+ .filter((n) => !isShadowed(n));+ const replies = notifications+ .filter(isChannelMessageReply)+ .filter((n) => !isShadowed(n));+ const others = notifications.filter(+ (n) =>+ !isChannelMention(n) &&+ !isChannelMessageSend(n) &&+ !isChannelMessageReply(n)+ );++ // Build groups+ const groups: NotificationStack[] = [+ ...mentions.flatMap((n) => makeStack('channel_mention', [n])),+ ...makeStack('channel_message_send', newMsgs),+ ...makeReplyStacks(replies),+ ...others.flatMap((n) => {+ const typed = tryToTypedNotification(n);+ if (!typed) return [];+ return makeStack(typed.notificationEventType, [typed]);+ }),+ ];++ // Sort: mentions first, then by recency+ return groups.sort((a, b) => {+ if ((a.type === 'channel_mention') !== (b.type === 'channel_mention')) {+ return a.type === 'channel_mention' ? -1 : 1;+ }+ return b.notifications[0].createdAt - a.notifications[0].createdAt;+ });+}++function sortByRecency<T extends { createdAt: number }>(items: T[]): T[] {+ return [...items].sort((a, b) => b.createdAt - a.createdAt);+}++const groupBy: <T, K>(items: T[], keyFn: (item: T) => K) => Map<K, T[]> =+ Map.groupBy ??+ ((items, keyFn) => {+ const map = new Map();+ for (const item of items) {+ const key = keyFn(item);+ const group = map.get(key);+ if (group) {+ group.push(item);+ } else {+ map.set(key, [item]);+ }+ }+ return map;+ });++function makeStack(+ type: TypedNotification['notificationEventType'],+ notifications: TypedNotification[]+): NotificationStack[] {+ if (notifications.length === 0) return [];+ return [{ type, notifications: sortByRecency(notifications) }];+}++function makeReplyStacks(+ replies: TypedNotification<'channel_message_reply'>[]+): NotificationStack[] {+ const byThread = groupBy(+ replies,+ (r) => r.notificationMetadata?.threadId ?? ''+ );+ return [...byThread.entries()]+ .filter(([threadId]) => threadId !== '')+ .map(([, group]) => ({+ type: 'channel_message_reply',+ notifications: sortByRecency(group),+ }));+}diff --git a/js/app/packages/notifications/tests/notification-stacking.test.ts b/js/app/packages/notifications/tests/notification-stacking.test.tsnew file mode 100644index 0000000000..35c04808ac--- /dev/null+++ b/js/app/packages/notifications/tests/notification-stacking.test.ts@@ -0,0 +1,330 @@+import type { NotificationEventType } from '@service-notification/generated/schemas';+import { describe, expect, it } from 'vitest';+import {+ getAllNotificationsFromGroup,+ getMostRecentNotification,+ getThreadId,+ stackNotifications,+} from '../notification-stacking';+import type { UnifiedNotification } from '../types';++// Helper to create a base notification+function createNotification(+ id: string,+ type: NotificationEventType,+ createdAt: number,+ metadata: Record<string, unknown> = {}+): UnifiedNotification {+ return {+ id,+ entity_id: 'channel-1',+ entity_type: 'channel',+ createdAt,+ updatedAt: null,+ viewedAt: null,+ deletedAt: null,+ done: false,+ sent: true,+ senderId: 'user-1',+ notificationEventType: type,+ notificationMetadata: metadata,+ } as UnifiedNotification;+}++function createNewMessageNotification(+ id: string,+ messageId: string,+ createdAt: number+): UnifiedNotification {+ return createNotification(id, 'channel_message_send', createdAt, {+ messageId,+ messageContent: `Message ${id}`,+ sender: 'user-1',+ channelType: 'team',+ });+}++function createReplyNotification(+ id: string,+ messageId: string,+ threadId: string,+ createdAt: number+): UnifiedNotification {+ return createNotification(id, 'channel_message_reply', createdAt, {+ messageId,+ threadId,+ messageContent: `Reply ${id}`,+ userId: 'user-1',+ channelType: 'team',+ });+}++function createMentionNotification(+ id: string,+ messageId: string,+ createdAt: number,+ threadId?: string+): UnifiedNotification {+ return createNotification(id, 'channel_mention', createdAt, {+ messageId,+ messageContent: `Mention ${id}`,+ threadId: threadId ?? null,+ channelType: 'team',+ });+}++describe('stackNotifications', () => {+ describe('basic stacking', () => {+ it('stacks multiple new messages into a single group', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 1000),+ createNewMessageNotification('n2', 'msg-2', 2000),+ createNewMessageNotification('n3', 'msg-3', 3000),+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(1);+ expect(result[0].type).toBe('channel_message_send');+ if (result[0].type === 'channel_message_send') {+ expect(result[0].notifications).toHaveLength(3);+ expect(result[0].notifications[0].id).toBe('n3'); // Most recent+ }+ });++ it('stacks replies by threadId', () => {+ const notifications = [+ createReplyNotification('r1', 'msg-1', 'thread-A', 1000),+ createReplyNotification('r2', 'msg-2', 'thread-A', 2000),+ createReplyNotification('r3', 'msg-3', 'thread-B', 3000),+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(2);++ const threadAStack = result.find(+ (g) =>+ g.type === 'channel_message_reply' && getThreadId(g) === 'thread-A'+ );+ const threadBStack = result.find(+ (g) =>+ g.type === 'channel_message_reply' && getThreadId(g) === 'thread-B'+ );++ expect(threadAStack).toBeDefined();+ expect(threadBStack).toBeDefined();++ if (threadAStack?.type === 'channel_message_reply') {+ expect(threadAStack.notifications).toHaveLength(2);+ expect(getMostRecentNotification(threadAStack).id).toBe('r2'); // Most recent in thread A+ }++ if (threadBStack?.type === 'channel_message_reply') {+ expect(threadBStack.notifications).toHaveLength(1);+ expect(getMostRecentNotification(threadBStack).id).toBe('r3');+ }+ });++ it('keeps mentions as individual items', () => {+ const notifications = [+ createMentionNotification('m1', 'msg-1', 1000),+ createMentionNotification('m2', 'msg-2', 2000),+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(2);+ expect(result.every((g) => g.type === 'channel_mention')).toBe(true);+ });+ });++ describe('mention shadowing', () => {+ it('shadows new message notification when mention exists for same messageId', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 1000),+ createMentionNotification('m1', 'msg-1', 2000), // Same messageId+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(1);+ expect(result[0].type).toBe('channel_mention');+ });++ it('shadows reply notification when mention exists for same messageId', () => {+ const notifications = [+ createReplyNotification('r1', 'msg-1', 'thread-A', 1000),+ createMentionNotification('m1', 'msg-1', 2000), // Same messageId+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(1);+ expect(result[0].type).toBe('channel_mention');+ });++ it('keeps non-shadowed notifications alongside mentions', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 1000),+ createNewMessageNotification('n2', 'msg-2', 2000),+ createMentionNotification('m1', 'msg-1', 3000), // Shadows n1+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(2); // One mention + one new_messages stack++ const mentionGroup = result.find((g) => g.type === 'channel_mention');+ const newMessagesGroup = result.find(+ (g) => g.type === 'channel_message_send'+ );++ expect(mentionGroup).toBeDefined();+ expect(newMessagesGroup).toBeDefined();++ if (newMessagesGroup?.type === 'channel_message_send') {+ expect(newMessagesGroup.notifications).toHaveLength(1);+ expect(newMessagesGroup.notifications[0].id).toBe('n2'); // n1 was shadowed+ }+ });+ });++ describe('sorting', () => {+ it('sorts mentions first', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 5000), // Most recent overall+ createMentionNotification('m1', 'msg-2', 1000), // Oldest+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(2);+ expect(result[0].type).toBe('channel_mention'); // Mention first despite being older+ expect(result[1].type).toBe('channel_message_send');+ });++ it('sorts non-mention groups by timestamp descending', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 1000),+ createReplyNotification('r1', 'msg-2', 'thread-A', 3000),+ ];++ const result = stackNotifications(notifications);++ expect(result).toHaveLength(2);+ expect(result[0].type).toBe('channel_message_reply'); // More recent+ expect(result[1].type).toBe('channel_message_send');+ });+ });++ describe('mixed notifications', () => {+ it('handles complex scenario with all notification types', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 1000),+ createNewMessageNotification('n2', 'msg-2', 2000),+ createReplyNotification('r1', 'msg-3', 'thread-A', 3000),+ createReplyNotification('r2', 'msg-4', 'thread-A', 4000),+ createReplyNotification('r3', 'msg-5', 'thread-B', 5000),+ createMentionNotification('m1', 'msg-6', 6000),+ createMentionNotification('m2', 'msg-2', 7000), // Shadows n2+ ];++ const result = stackNotifications(notifications);++ // Should have: 2 mentions, 1 new_messages stack (only n1), 2 replies stacks+ expect(result).toHaveLength(5);++ const mentions = result.filter((g) => g.type === 'channel_mention');+ const newMessages = result.filter(+ (g) => g.type === 'channel_message_send'+ );+ const replies = result.filter((g) => g.type === 'channel_message_reply');++ expect(mentions).toHaveLength(2);+ expect(newMessages).toHaveLength(1);+ expect(replies).toHaveLength(2);++ // Check mentions come first+ expect(result[0].type).toBe('channel_mention');+ expect(result[1].type).toBe('channel_mention');++ // Check new messages stack only has n1 (n2 was shadowed)+ if (newMessages[0].type === 'channel_message_send') {+ expect(newMessages[0].notifications).toHaveLength(1);+ expect(newMessages[0].notifications[0].id).toBe('n1');+ }+ });++ it('returns empty array for empty input', () => {+ const result = stackNotifications([]);+ expect(result).toEqual([]);+ });+ });+});++describe('getMostRecentNotification', () => {+ it('returns most recent from new_messages stack', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 1000),+ createNewMessageNotification('n2', 'msg-2', 2000),+ ];+ const stacked = stackNotifications(notifications);+ const notification = getMostRecentNotification(stacked[0]);+ expect(notification.id).toBe('n2');+ });++ it('returns most recent from replies stack', () => {+ const notifications = [+ createReplyNotification('r1', 'msg-1', 'thread-A', 1000),+ createReplyNotification('r2', 'msg-2', 'thread-A', 2000),+ ];+ const stacked = stackNotifications(notifications);+ const notification = getMostRecentNotification(stacked[0]);+ expect(notification.id).toBe('r2');+ });++ it('returns the notification from mention group', () => {+ const notifications = [createMentionNotification('m1', 'msg-1', 1000)];+ const stacked = stackNotifications(notifications);+ const notification = getMostRecentNotification(stacked[0]);+ expect(notification.id).toBe('m1');+ });+});++describe('getAllNotificationsFromGroup', () => {+ it('returns all notifications from new_messages stack', () => {+ const notifications = [+ createNewMessageNotification('n1', 'msg-1', 1000),+ createNewMessageNotification('n2', 'msg-2', 2000),+ createNewMessageNotification('n3', 'msg-3', 3000),+ ];+ const stacked = stackNotifications(notifications);+ const allNotifications = getAllNotificationsFromGroup(stacked[0]);+ expect(allNotifications).toHaveLength(3);+ expect(allNotifications.map((n) => n.id).sort()).toEqual([+ 'n1',+ 'n2',+ 'n3',+ ]);+ });++ it('returns all notifications from replies stack', () => {+ const notifications = [+ createReplyNotification('r1', 'msg-1', 'thread-A', 1000),+ createReplyNotification('r2', 'msg-2', 'thread-A', 2000),+ ];+ const stacked = stackNotifications(notifications);+ const allNotifications = getAllNotificationsFromGroup(stacked[0]);+ expect(allNotifications).toHaveLength(2);+ expect(allNotifications.map((n) => n.id).sort()).toEqual(['r1', 'r2']);+ });++ it('returns single notification from mention group', () => {+ const notifications = [createMentionNotification('m1', 'msg-1', 1000)];+ const stacked = stackNotifications(notifications);+ const allNotifications = getAllNotificationsFromGroup(stacked[0]);+ expect(allNotifications).toHaveLength(1);+ expect(allNotifications[0].id).toBe('m1');+ });+});diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.tsindex 3055b24fca..80b0887f05 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.ts@@ -4,6 +4,7 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { ChannelReplyMetadataAllOfThreadParentSenderId } from './channelReplyMetadataAllOfThreadParentSenderId';export type ChannelReplyMetadataAllOf = {/** The message content */@@ -12,6 +13,8 @@ export type ChannelReplyMetadataAllOf = {messageId: string;/** The id of the thread that has the reply */threadId: string;+ /** The user who sent the root message of the thread */+ threadParentSenderId?: ChannelReplyMetadataAllOfThreadParentSenderId;/** The sender id of the reply */userId: string;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfThreadParentSenderId.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfThreadParentSenderId.tsnew file mode 100644index 0000000000..93916917c7--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfThreadParentSenderId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The user who sent the root message of the thread+ */+export type ChannelReplyMetadataAllOfThreadParentSenderId = string | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.tsindex e9036e6ef8..f0fa4f7c37 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts@@ -17,6 +17,7 @@ export * from './channelMessageSendMetadata';export * from './channelMessageSendMetadataAllOf';export * from './channelReplyMetadata';export * from './channelReplyMetadataAllOf';+export * from './channelReplyMetadataAllOfThreadParentSenderId';export * from './channelType';export * from './commonChannelMetadata';export * from './createNotification';diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex ef5ad61239..35b4e4b53b 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -1025,6 +1025,10 @@"type": "string","description": "The id of the thread that has the reply"},+ "threadParentSenderId": {+ "type": ["string", "null"],+ "description": "The user who sent the root message of the thread"+ },"userId": {"type": "string","description": "The sender id of the reply"diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rsindex 4f4a9c184b..2116cfb6aa 100644--- a/rust/cloud-storage/comms_service/src/notification.rs+++ b/rust/cloud-storage/comms_service/src/notification.rs@@ -1,6 +1,7 @@use crate::api::context::AppState;use comms_db_client::{messages::get_count::check_if_channel_has_messages,+ messages::get_message_owner::get_message_owner,model::{Message, SimpleMention},participants::get_participants::get_channel_participants_for_thread_id,};@@ -24,6 +25,7 @@ pub struct ChannelMessageEvent<'a> {document_mentions: &'a [DocumentMetadata],participants: &'a [ChannelParticipant],thread_participants: &'a [MacroUserIdStr<'static>],+ thread_parent_sender_id: Option<MacroUserIdStr<'static>>,}pub struct ChannelInviteEvent<'a> {@@ -151,6 +153,7 @@ impl ChannelMessageEvent<'_> {message_id: self.message.id.to_string(),user_id: self.message.sender_id.clone(),message_content: self.message.content.clone(),+ thread_parent_sender_id: self.thread_parent_sender_id.clone(),common: self.channel_metadata.clone(),},));@@ -249,12 +252,21 @@ pub async fn dispatch_notifications_for_message(.map(|response| response.documents).unwrap_or_default();- let thread_participants = if let Some(thread_id) = message.thread_id {- get_channel_participants_for_thread_id(&api_context.db, &thread_id)+ let (thread_participants, thread_parent_sender_id) = if let Some(thread_id) = message.thread_id+ {+ let participants = get_channel_participants_for_thread_id(&api_context.db, &thread_id).await- .unwrap_or_default()+ .unwrap_or_default();+ // Get the thread parent sender (author of the root message)+ let sender_id = match get_message_owner(&api_context.db, &thread_id).await {+ Ok(id) => MacroUserIdStr::parse_from_str(&id)+ .ok()+ .map(|id| id.into_owned()),+ Err(_) => None,+ };+ (participants, sender_id)} else {- vec![]+ (vec![], None)};let channel_message_event = ChannelMessageEvent {@@ -266,6 +278,7 @@ pub async fn dispatch_notifications_for_message(document_mentions: &document_mentions,participants: &participants,thread_participants: &thread_participants,+ thread_parent_sender_id,};let notifications = channel_message_event.generate_notifications();@@ -404,6 +417,7 @@ mod tests {document_mentions: &[],participants: &participants,thread_participants: &[],+ thread_parent_sender_id: None,};let notifications = event.generate_notifications();@@ -450,6 +464,7 @@ mod tests {document_mentions: &[],participants: &participants,thread_participants: &[],+ thread_parent_sender_id: None,};let notifications = event.generate_notifications();@@ -493,6 +508,7 @@ mod tests {document_mentions: &[],participants: &participants,thread_participants: &[],+ thread_parent_sender_id: None,};let notifications = event.generate_notifications();@@ -541,6 +557,7 @@ mod tests {document_mentions: &[],participants: &participants,thread_participants: &[],+ thread_parent_sender_id: None,};let notifications = event.generate_notifications();@@ -608,6 +625,11 @@ mod tests {MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),];+ let thread_parent_sender_id = Some(+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ );let event = ChannelMessageEvent {channel_id: &channel_id,message: &msg,@@ -617,6 +639,7 @@ mod tests {document_mentions: &[],participants: &participants,thread_participants: &thread_participants,+ thread_parent_sender_id,};let notifications = event.generate_notifications();@@ -675,6 +698,7 @@ mod tests {document_mentions: &doc_mentions,participants: &participants,thread_participants: &[],+ thread_parent_sender_id: None,};let notifications = event.generate_notifications();@@ -728,6 +752,7 @@ mod tests {document_mentions: &[],participants: &participants,thread_participants: &[],+ thread_parent_sender_id: None,};let notifications = event.generate_notifications();diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex 317284ff4f..ae99174092 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -172,6 +172,11 @@ pub struct ChannelReplyMetadata {/// The message content#[serde(alias = "message_content")]pub message_content: String,+ /// The user who sent the root message of the thread+ #[serde(skip_serializing_if = "Option::is_none")]+ #[serde(alias = "thread_parent_sender_id")]+ #[schema(value_type = Option<String>)]+ pub thread_parent_sender_id: Option<MacroUserIdStr<'static>>,#[serde(flatten)]pub common: CommonChannelMetadata,}diff --git a/rust/cloud-storage/model_notifications/src/tests.rs b/rust/cloud-storage/model_notifications/src/tests.rsindex 272f95a802..6b17c87779 100644--- a/rust/cloud-storage/model_notifications/src/tests.rs+++ b/rust/cloud-storage/model_notifications/src/tests.rs@@ -139,6 +139,7 @@ fn test_build_key_channel_message_reply_uses_message_id() {message_id: "reply_msg_123".to_string(),user_id: make_user_id("[email protected]"),message_content: "This is a reply".to_string(),+ thread_parent_sender_id: None,common: CommonChannelMetadata {channel_type: ChannelType::Public,channel_name: "general".to_string(),@@ -157,6 +158,7 @@ fn test_build_key_channel_message_reply_uses_message_id() {message_id: "reply_msg_123".to_string(),user_id: make_user_id("[email protected]"),message_content: "Different reply".to_string(),+ thread_parent_sender_id: None,common: CommonChannelMetadata {channel_type: ChannelType::Private,channel_name: "other".to_string(),