Skip to content

armgit / macro

Public Imported from GitHub
0

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

Seanaye/perf/channel notifs (#7291)

Sean Ayea4b975c47b7d
diff --git a/apps/web/src/features/channel/Channel/ChannelUnreadNotifications.tsx b/apps/web/src/features/channel/Channel/ChannelUnreadNotifications.tsx
index 8efd72b344..004f34f6ee 100644
--- a/apps/web/src/features/channel/Channel/ChannelUnreadNotifications.tsx
+++ b/apps/web/src/features/channel/Channel/ChannelUnreadNotifications.tsx
@@ -2,8 +2,9 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { enableGraphqlSoup } from '@core/constant/featureFlags';
import { isTransientRequestError } from '@core/util/request-error';
-import { MessageNotificationSourceContext } from '@notifications/components/MarkMessageNotifications';
+import { MessageNotificationIndexContext } from '@notifications/components/MarkMessageNotifications';
import { compositeEntity } from '@notifications/types';
+import { indexUnreadMessageNotifications } from '@notifications/unread-message-notifications';
import { createChannelNotificationsQuery } from '@queries/channel/notifications';
import { queryReadyGate } from '@queries/gate';
import { useMessageTimelineByIdsQuery } from '@queries/messages/timeline';
@@ -51,6 +52,9 @@ export function ChannelUnreadNotifications(props: {
? records.map(notificationSource.withLocalOverrides)
: records;
});
+ const unreadByMessage = createMemo(() =>
+ indexUnreadMessageNotifications(notifications())
+ );
const unread = createMemo(() => unreadThreads(notifications()));
// A reply's timestamp says nothing about where its parent sits in history.
// Resolve only the target parent without loading the timeline around it.
@@ -101,8 +105,8 @@ export function ChannelUnreadNotifications(props: {
});
return (
- <MessageNotificationSourceContext.Provider value={notifications}>
+ <MessageNotificationIndexContext.Provider value={unreadByMessage}>
{props.children(unreadChip)}
- </MessageNotificationSourceContext.Provider>
+ </MessageNotificationIndexContext.Provider>
);
}
diff --git a/apps/web/src/features/channel/Channel/tests/ChannelUnreadNotifications.test.tsx b/apps/web/src/features/channel/Channel/tests/ChannelUnreadNotifications.test.tsx
index ccb40e76ca..d692644fc7 100644
--- a/apps/web/src/features/channel/Channel/tests/ChannelUnreadNotifications.test.tsx
+++ b/apps/web/src/features/channel/Channel/tests/ChannelUnreadNotifications.test.tsx
@@ -1,7 +1,8 @@
+import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';
import type { UnifiedNotification } from '@notifications/types';
import type { MessageListItem } from '@service-storage/messages';
-import { render } from '@solidjs/testing-library';
-import { createSignal, Show } from 'solid-js';
+import { render, waitFor } from '@solidjs/testing-library';
+import { createSignal, For, Show } from 'solid-js';
import { expect, it, vi } from 'vitest';
import { ChannelUnreadNotifications } from '../ChannelUnreadNotifications';
import { UnreadNotificationsOverlay } from '../UnreadNotificationsOverlay';
@@ -48,6 +49,79 @@ function notification(threadId: string, time: number): UnifiedNotification {
};
}
+it('shares unread lookups across mounted messages without rescanning history per row', async () => {
+ const reply = notification('root-1', 12);
+ const metadata = reply.notification_metadata;
+ const readMetadata = vi.fn(() => metadata);
+ Object.defineProperty(reply, 'notification_metadata', { get: readMetadata });
+ const history = Array.from({ length: 200 }, (_, index) => ({
+ ...notification('root-1', 12),
+ id: `done-${index}`,
+ state: 'done' as const,
+ get notification_metadata(): UnifiedNotification['notification_metadata'] {
+ throw new Error('Read historical notification metadata');
+ },
+ }));
+ const [records, setRecords] = createSignal<UnifiedNotification[]>([
+ ...history,
+ reply,
+ ]);
+ const [messageIds, setMessageIds] = createSignal(['root-1']);
+ const globalRead = vi.fn(() => {
+ throw new Error('Read global notifications');
+ });
+ const bulkMarkAsRead = vi.fn(async () => {
+ setRecords([...history, { ...reply, state: 'seen' }]);
+ });
+ mocks.source.mockReturnValue({
+ notificationsByEntity: globalRead,
+ withLocalOverrides: (n: UnifiedNotification) => n,
+ bulkMarkAsRead,
+ });
+ mocks.query.mockReturnValue({
+ isEnabled: true,
+ isPending: false,
+ get data() {
+ return records();
+ },
+ });
+ const view = render(() => (
+ <ChannelUnreadNotifications
+ channelId="channel"
+ messages={() => []}
+ scrollState={() => undefined}
+ container={() => undefined}
+ insets={() => ({ start: 0, end: 0 })}
+ >
+ {() => (
+ <For each={messageIds()}>
+ {(messageId) => (
+ <MarkMessageNotifications
+ messageId={messageId}
+ parent={{ type: 'channel', id: 'channel' }}
+ >
+ <span>{messageId}</span>
+ </MarkMessageNotifications>
+ )}
+ </For>
+ )}
+ </ChannelUnreadNotifications>
+ ));
+ const initialReads = readMetadata.mock.calls.length;
+ expect(initialReads).toBeGreaterThan(0);
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+
+ setMessageIds(Array.from({ length: 50 }, (_, index) => `other-${index}`));
+ expect(view.container.querySelectorAll('span')).toHaveLength(50);
+ expect(readMetadata).toHaveBeenCalledTimes(initialReads);
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+
+ setMessageIds([...messageIds(), 'reply-12']);
+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());
+ expect(bulkMarkAsRead).toHaveBeenCalledWith([reply]);
+ expect(globalRead).not.toHaveBeenCalled();
+});
+
it('updates one chip live without suspending the channel or loading the global feed', () => {
const [pending, setPending] = createSignal(true);
const [notifications, setNotifications] = createSignal<UnifiedNotification[]>(
diff --git a/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx b/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx
index da7b5beb10..a6fbf3de7f 100644
--- a/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx
+++ b/apps/web/src/features/notifications/components/MarkMessageNotifications.tsx
@@ -11,9 +11,9 @@ import {
useContext,
} from 'solid-js';
-/** A channel can supply its complete edge without activating the global feed. */
-export const MessageNotificationSourceContext =
- createContext<Accessor<UnifiedNotification[]>>();
+/** Share exact unread matches so each message avoids scanning the channel history. */
+export const MessageNotificationIndexContext =
+ createContext<Accessor<ReadonlyMap<string, UnifiedNotification[]>>>();
const MAX_MARK_ATTEMPTS = 3;
@@ -27,10 +27,10 @@ export function MarkMessageNotifications(props: {
// matches metadata.messageId only; the current CHANNEL_MESSAGE entity scope
// is thread-aware, so targeting a root also includes reply notifications.
const notificationSource = useGlobalNotificationSource();
- const scopedNotifications = useContext(MessageNotificationSourceContext);
- const notifications =
- scopedNotifications ??
- useNotificationsForEntity(notificationSource, props.parent);
+ const scopedIndex = useContext(MessageNotificationIndexContext);
+ const notifications = scopedIndex
+ ? () => scopedIndex().get(props.messageId) ?? []
+ : useNotificationsForEntity(notificationSource, props.parent);
const isMessageNotification = (n: UnifiedNotification) => {
const content = n.notification_metadata.content;
return (
@@ -56,7 +56,8 @@ export function MarkMessageNotifications(props: {
createEffect(() => {
const unread = notifications().filter(
(notification) =>
- isMessageNotification(notification) && notification.state === 'unseen'
+ notification.state === 'unseen' &&
+ (scopedIndex !== undefined || isMessageNotification(notification))
);
if (unread.length === 0 || inFlight()) return;
const ids = JSON.stringify(
diff --git a/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsx b/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsx
index 828947c278..23bcaf1e15 100644
--- a/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsx
+++ b/apps/web/src/features/notifications/tests/mark-message-notifications.test.tsx
@@ -1,12 +1,14 @@
import type { NotificationSource } from '@notifications/notification-source';
import type { UnifiedNotification } from '@notifications/types';
import { render, waitFor } from '@solidjs/testing-library';
-import { createSignal } from 'solid-js';
+import { createMemo, createSignal } from 'solid-js';
+import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
MarkMessageNotifications,
- MessageNotificationSourceContext,
+ MessageNotificationIndexContext,
} from '../components/MarkMessageNotifications';
+import { indexUnreadMessageNotifications } from '../unread-message-notifications';
const mocks = vi.hoisted(() => ({
notificationSource: undefined as NotificationSource | undefined,
@@ -95,16 +97,21 @@ describe('MarkMessageNotifications', () => {
const [notifications, setNotifications] = createSignal(
matchingNotifications
);
- const view = render(() => (
- <MessageNotificationSourceContext.Provider value={notifications}>
- <MarkMessageNotifications
- messageId="message-1"
- parent={{ type: 'channel', id: 'channel-1' }}
- >
- <span>Message</span>
- </MarkMessageNotifications>
- </MessageNotificationSourceContext.Provider>
- ));
+ const view = render(() => {
+ const index = createMemo(() =>
+ indexUnreadMessageNotifications(notifications())
+ );
+ return (
+ <MessageNotificationIndexContext.Provider value={index}>
+ <MarkMessageNotifications
+ messageId="message-1"
+ parent={{ type: 'channel', id: 'channel-1' }}
+ >
+ <span>Message</span>
+ </MarkMessageNotifications>
+ </MessageNotificationIndexContext.Provider>
+ );
+ });
expect(globalRead).not.toHaveBeenCalled();
await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());
expect(bulkMarkAsRead).toHaveBeenCalledWith(matchingNotifications);
@@ -119,6 +126,48 @@ describe('MarkMessageNotifications', () => {
expect(view.container.firstElementChild?.tagName).toBe('SPAN');
});
+ it('marks a newly unread store record and a new batch arriving while a mark is pending', async () => {
+ const [notifications, setNotifications] = createStore([
+ { ...documentMentionNotification('first'), state: 'seen' as const },
+ ] as UnifiedNotification[]);
+ let finishMark: (() => void) | undefined;
+ bulkMarkAsRead.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finishMark = resolve;
+ })
+ );
+ render(() => {
+ const index = createMemo(() =>
+ indexUnreadMessageNotifications(notifications)
+ );
+ return (
+ <MessageNotificationIndexContext.Provider value={index}>
+ <MarkMessageNotifications
+ messageId="message-1"
+ parent={{ type: 'channel', id: 'channel-1' }}
+ >
+ <span>Message</span>
+ </MarkMessageNotifications>
+ </MessageNotificationIndexContext.Provider>
+ );
+ });
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+ setNotifications(0, 'state', 'unseen');
+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledOnce());
+
+ setNotifications(0, 'state', 'seen');
+ setNotifications(1, documentMentionNotification('second'));
+ expect(bulkMarkAsRead).toHaveBeenCalledOnce();
+ finishMark!();
+ await waitFor(() => expect(bulkMarkAsRead).toHaveBeenCalledTimes(2));
+ expect(bulkMarkAsRead.mock.calls[1][0].map((n) => n.id)).toEqual([
+ 'second',
+ ]);
+ setNotifications(1, 'state', 'seen');
+ finishMark!();
+ });
+
it('bounds retries for the same notifications and retries a new batch after exhaustion', async () => {
const error = new Error('mark failed');
bulkMarkAsRead.mockRejectedValue(error);
@@ -130,16 +179,21 @@ describe('MarkMessageNotifications', () => {
);
try {
- render(() => (
- <MessageNotificationSourceContext.Provider value={notifications}>
- <MarkMessageNotifications
- messageId="message-1"
- parent={{ type: 'channel', id: 'channel-1' }}
- >
- <span>Message</span>
- </MarkMessageNotifications>
- </MessageNotificationSourceContext.Provider>
- ));
+ render(() => {
+ const index = createMemo(() =>
+ indexUnreadMessageNotifications(notifications())
+ );
+ return (
+ <MessageNotificationIndexContext.Provider value={index}>
+ <MarkMessageNotifications
+ messageId="message-1"
+ parent={{ type: 'channel', id: 'channel-1' }}
+ >
+ <span>Message</span>
+ </MarkMessageNotifications>
+ </MessageNotificationIndexContext.Provider>
+ );
+ });
await waitFor(() => {
expect(bulkMarkAsRead).toHaveBeenCalledTimes(3);
diff --git a/apps/web/src/features/notifications/tests/unread-message-notifications.test.ts b/apps/web/src/features/notifications/tests/unread-message-notifications.test.ts
new file mode 100644
index 0000000000..b1c5c7005e
--- /dev/null
+++ b/apps/web/src/features/notifications/tests/unread-message-notifications.test.ts
@@ -0,0 +1,141 @@
+import { createMemo, createRoot, createSignal } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { describe, expect, it, vi } from 'vitest';
+import type { UnifiedNotification } from '../types';
+import { indexUnreadMessageNotifications } from '../unread-message-notifications';
+
+function notification(
+ id: string,
+ content: Record<string, unknown>,
+ state: UnifiedNotification['state'] = 'unseen'
+): UnifiedNotification {
+ return {
+ id,
+ entity_id: 'channel',
+ entity_type: 'channel',
+ created_at: '2026-09-01T00:00:00.000Z',
+ updated_at: '2026-09-01T00:00:00.000Z',
+ state,
+ sent: true,
+ viewed_at: null,
+ notification_event_type: 'document_mention',
+ notification_metadata: {
+ tag: 'document_mention',
+ content: {
+ channelType: 'private',
+ documentName: 'Document',
+ owner: 'user',
+ messageContent: 'Message',
+ ...content,
+ },
+ } as UnifiedNotification['notification_metadata'],
+ };
+}
+
+describe('indexUnreadMessageNotifications', () => {
+ it('groups every notification for the exact message, not its thread root', () => {
+ const first = notification('mention-1', { messageId: 'root' });
+ const second = notification('mention-2', { messageId: 'root' });
+ const reply = notification('reply', {
+ messageId: 'reply-message',
+ threadId: 'root',
+ });
+ const index = indexUnreadMessageNotifications([
+ first,
+ second,
+ reply,
+ notification('thread-only', { threadId: 'root' }),
+ notification('unrelated', {}),
+ ]);
+
+ expect([...index.keys()]).toEqual(['root', 'reply-message']);
+ expect(index.get('root')).toEqual([first, second]);
+ expect(index.get('reply-message')).toEqual([reply]);
+ });
+
+ it('stringifies comment IDs and preserves both matching fields without duplicates', () => {
+ const comment = notification('comment', { commentId: 42 });
+ const both = notification('both', { messageId: 'message', commentId: 43 });
+ const same = notification('same', { messageId: '44', commentId: 44 });
+ const index = indexUnreadMessageNotifications([comment, both, same]);
+
+ expect(index.get('42')).toEqual([comment]);
+ expect(index.get('message')).toEqual([both]);
+ expect(index.get('43')).toEqual([both]);
+ expect(index.get('44')).toEqual([same]);
+ });
+
+ it('does not read metadata for seen or done notifications', () => {
+ const records = (['seen', 'done'] as const).map((state) => {
+ const record = notification(state, { messageId: 'message' }, state);
+ const content = record.notification_metadata;
+ const metadata = vi.fn(() => content);
+ Object.defineProperty(record, 'notification_metadata', { get: metadata });
+ return { record, metadata };
+ });
+
+ expect(
+ indexUnreadMessageNotifications(records.map(({ record }) => record)).size
+ ).toBe(0);
+ for (const { metadata } of records) expect(metadata).not.toHaveBeenCalled();
+ });
+
+ it('reacts to in-place state changes, new records, and notification removal', () => {
+ createRoot((dispose) => {
+ try {
+ const [records, setRecords] = createStore([
+ notification('one', { messageId: 'message' }, 'seen'),
+ ]);
+ const index = createMemo(() =>
+ indexUnreadMessageNotifications(records)
+ );
+ expect(index().size).toBe(0);
+
+ setRecords(0, 'state', 'unseen');
+ expect(
+ index()
+ .get('message')
+ ?.map((n) => n.id)
+ ).toEqual(['one']);
+ setRecords(0, 'state', 'done');
+ expect(index().size).toBe(0);
+
+ setRecords([notification('two', { messageId: 'reply' })]);
+ expect(
+ index()
+ .get('reply')
+ ?.map((n) => n.id)
+ ).toEqual(['two']);
+ setRecords([]);
+ expect(index().size).toBe(0);
+ } finally {
+ dispose();
+ }
+ });
+ });
+
+ it('tracks local state overrides and recovers when an override is rolled back', () => {
+ createRoot((dispose) => {
+ try {
+ const [seen, setSeen] = createSignal(false);
+ const record = notification('local', { messageId: 'message' });
+ const overridden: UnifiedNotification = {
+ ...record,
+ get state() {
+ return seen() ? 'seen' : record.state;
+ },
+ };
+ const index = createMemo(() =>
+ indexUnreadMessageNotifications([overridden])
+ );
+ expect(index().get('message')).toEqual([overridden]);
+ setSeen(true);
+ expect(index().size).toBe(0);
+ setSeen(false);
+ expect(index().get('message')).toEqual([overridden]);
+ } finally {
+ dispose();
+ }
+ });
+ });
+});
diff --git a/apps/web/src/features/notifications/unread-message-notifications.ts b/apps/web/src/features/notifications/unread-message-notifications.ts
new file mode 100644
index 0000000000..a1670afd2e
--- /dev/null
+++ b/apps/web/src/features/notifications/unread-message-notifications.ts
@@ -0,0 +1,26 @@
+import type { UnifiedNotification } from './types';
+
+/** Index exact message/comment matches once, without tracking read history metadata. */
+export function indexUnreadMessageNotifications(
+ notifications: readonly UnifiedNotification[]
+): ReadonlyMap<string, UnifiedNotification[]> {
+ const byMessage = new Map<string, UnifiedNotification[]>();
+ const append = (id: string, notification: UnifiedNotification) => {
+ const matches = byMessage.get(id);
+ if (matches) matches.push(notification);
+ else byMessage.set(id, [notification]);
+ };
+
+ for (const notification of notifications) {
+ if (notification.state !== 'unseen') continue;
+ const content = notification.notification_metadata.content;
+ const messageId = 'messageId' in content ? content.messageId : undefined;
+ const commentId =
+ 'commentId' in content ? String(content.commentId) : undefined;
+ if (messageId !== undefined) append(messageId, notification);
+ if (commentId !== undefined && commentId !== messageId)
+ append(commentId, notification);
+ }
+
+ return byMessage;
+}