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.

fix(crm): clear unread notifications when opening records (#9377)

gbirman013b9c0a7ca6
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index c653806974..10da5e8b49 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -478,8 +478,8 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
- Add Google Meet account hints only to join actions using the displayed calendar's
connected email; keep stored and copied conference links unchanged. See the
[calendar walkthrough](../../docs/agent-guide/calendar.md).
-- Mark loaded calendar and agent-session row notifications through the
- notification source (`markRowNotificationsSeenOnOpen`) so read dots update
+- Mark loaded calendar, agent-session, and CRM company/contact row notifications
+ through the notification source (`markRowNotificationsSeenOnOpen`) so read dots update
immediately and failed writes roll back; calendar grid selections and links
to an event also mark the canonical event read, excluding team projections.
- Route explicit meeting-page exits using the server's `callEnded` result: ended
diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.md
index 824cbfc1f9..05a1d3b353 100644
--- a/apps/web/src/features/crm/README.md
+++ b/apps/web/src/features/crm/README.md
@@ -32,6 +32,13 @@ The root adapters construct production dependencies. `context` defines the
capabilities; it does not import their implementations. Views consume these
capabilities, primitives receive narrow inputs, and components render props.
Core modules remain independent of Solid, service clients, and app state.
+`mark-record-notifications-seen.ts` integrates with shared list activation so
+opening a company or contact clears its row's unread notifications immediately.
+It uses the row's attached notifications before falling back to an entity read;
+the shared notification source owns optimistic state and failure rollback.
+The REST fallback waits for the notification feed before reading its snapshot.
+The discussion's message reader remains visibility-gated and reads a separate
+global feed, so it cannot guarantee that opening a record clears its row's dot.
UI rollout gates read `useFeatureFlag` directly where used; do not pass rollout
booleans through component props or the CRM source contract.
diff --git a/apps/web/src/features/crm/mark-record-notifications-seen.ts b/apps/web/src/features/crm/mark-record-notifications-seen.ts
new file mode 100644
index 0000000000..5574b1d91e
--- /dev/null
+++ b/apps/web/src/features/crm/mark-record-notifications-seen.ts
@@ -0,0 +1,55 @@
+import {
+ type EntityWithRawNotifications,
+ getEntityNotifications,
+} from '@app/features/soup/entity-notifications';
+import { fireAndForget } from '@core/util/fireAndForget';
+import type { EntityData } from '@entity/types/entity';
+import { notificationIsRead } from '@entity/utils/notification';
+import { Telemetry } from '@macro-inc/observability';
+import {
+ ensureNotificationSourceLoaded,
+ markNotificationsForEntityAsRead,
+} from '@notifications/notification-helpers';
+import type { NotificationSource } from '@notifications/notification-source';
+
+/** Clear a company or contact row's unread dot when its details open. */
+export function markCrmNotificationsSeenOnOpen(
+ entity: EntityWithRawNotifications<EntityData>,
+ notificationSource: NotificationSource
+) {
+ if (entity.type !== 'crm_company' && entity.type !== 'crm_contact') return;
+
+ const hasLoadedNotifications =
+ entity.notifications !== undefined ||
+ notificationSource._notificationsQuery.isStarted;
+ const notifications = hasLoadedNotifications
+ ? getEntityNotifications(entity, notificationSource).filter(
+ (notification) => !notificationIsRead(notification)
+ )
+ : [];
+
+ fireAndForget(
+ Telemetry.span('crm.notifications.mark_read', async (span) => {
+ span.setAttr('entity.id', entity.id);
+ span.setAttr('entity.type', entity.type);
+ span.setAttr('notification.count', notifications.length);
+ try {
+ if (notifications.length > 0) {
+ await notificationSource.bulkMarkAsRead(notifications);
+ } else {
+ if (notificationSource._notificationsQuery.transport === 'rest') {
+ await ensureNotificationSourceLoaded(notificationSource);
+ }
+ await markNotificationsForEntityAsRead(notificationSource, {
+ type: entity.type,
+ id: entity.id,
+ });
+ }
+ } catch (error) {
+ span.error(error);
+ throw error;
+ }
+ }),
+ 'crm-notification-read'
+ );
+}
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index 74f4477448..88776b0a01 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -16,6 +16,7 @@ import {
type CalendarViewTarget,
} from '@app/features/calendar-view/types';
import { callsHostedContent } from '@app/features/calls-view/calls-hosted-content';
+import { markCrmNotificationsSeenOnOpen } from '@app/features/crm/mark-record-notifications-seen';
import { driveHostedContent } from '@app/features/drive-view/drive-hosted-content';
import { projectHostedContent } from '@app/features/projects/open-project';
import { reviewsHostedContent } from '@app/features/reviews-view/reviews-hosted-content';
@@ -890,7 +891,7 @@ export function markChannelNotificationsSeenOnOpen(
/**
* Clear the dots of rows whose opened view has no block that marks the row's
- * loaded notifications read: calendar events and agent sessions.
+ * loaded notifications read: calendar events, agent sessions, and CRM records.
*/
export function markRowNotificationsSeenOnOpen(
entity: EntityWithRawNotifications<EntityData>,
@@ -898,6 +899,7 @@ export function markRowNotificationsSeenOnOpen(
) {
markCalendarNotificationSeenOnOpen(entity, notificationSource);
markAgentSessionNotificationsSeenOnOpen(entity, notificationSource);
+ markCrmNotificationsSeenOnOpen(entity, notificationSource);
}
/**
diff --git a/apps/web/src/features/notifications/tests/crm-notification-read.test.ts b/apps/web/src/features/notifications/tests/crm-notification-read.test.ts
new file mode 100644
index 0000000000..125d43c2cd
--- /dev/null
+++ b/apps/web/src/features/notifications/tests/crm-notification-read.test.ts
@@ -0,0 +1,288 @@
+import { markCrmNotificationsSeenOnOpen } from '@app/features/crm/mark-record-notifications-seen';
+import { withEntityNotifications } from '@app/features/soup/entity-notifications';
+import type { CrmCompanyEntity, CrmContactEntity } from '@entity/types/entity';
+import { unreadFilterFn } from '@entity/utils/filter';
+import { Telemetry } from '@macro-inc/observability';
+import type { ConnectionGatewayWebsocket } from '@service-connection/websocket';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createNotificationSource } from '../notification-source';
+import type { UnifiedNotification } from '../types';
+
+const mocks = vi.hoisted(() => ({
+ graphql: true,
+ loading: vi.fn(() => false),
+ seen: vi.fn(),
+ entitySeen: vi.fn(),
+ refetch: vi.fn(),
+ feed: vi.fn<() => UnifiedNotification[] | undefined>(() => []),
+}));
+
+vi.mock('@core/constant/featureFlags', () => ({
+ ENABLE_DOCUMENT_MENTION_NOTIFICATIONS: true,
+ enableGraphqlSoup: { key: 'enable-graphql-soup' },
+ isFeatureEnabled: () => mocks.graphql,
+}));
+vi.mock('@macro-inc/collaboration/websocket', () => ({
+ createSocketEffect: vi.fn(),
+}));
+vi.mock('@queries/notification/user-notifications', () => ({
+ optimisticInsertNotification: vi.fn(),
+ useMarkNotificationsAsSeenMutation: () => ({ mutateAsync: mocks.seen }),
+ useMarkNotificationsAsDoneMutation: () => ({ mutateAsync: vi.fn() }),
+ useUserNotificationsQuery: () => ({
+ get transport() {
+ return mocks.graphql ? 'graphql' : 'rest';
+ },
+ get isStarted() {
+ return !mocks.graphql;
+ },
+ get isLoading() {
+ return mocks.loading();
+ },
+ refetch: mocks.refetch,
+ get data() {
+ return mocks.feed();
+ },
+ }),
+}));
+vi.mock('@queries/notification/notification-soup', () => ({
+ updateSoupForNotification: vi.fn(),
+}));
+vi.mock('@queries/notification/unsubscribes', () => ({
+ useMuteItemMutation: () => ({ mutateAsync: vi.fn() }),
+ useUnmuteItemMutation: () => ({ mutateAsync: vi.fn() }),
+}));
+vi.mock('@queries/soup/graphql/active-queries', () => ({
+ refreshActiveGraphqlSoupQueries: vi.fn(),
+}));
+vi.mock('@service-storage/graphql-notifications', () => ({
+ updateNotificationsForEntities: mocks.entitySeen,
+}));
+vi.mock('@service-storage/graphql-soup', () => ({
+ graphqlCacheEnabled: () => true,
+ mapGraphqlNotification: (value: unknown) => value,
+}));
+vi.mock('@service-storage/graphql-soup-websocket', () => ({
+ subscribeToGraphqlNotificationPatches: () => () => {},
+}));
+vi.mock('../queries/muted-entities-query', () => ({
+ createMutedEntitiesQuery: () => ({ isPending: true }),
+}));
+
+const COMPANY: CrmCompanyEntity = {
+ type: 'crm_company',
+ id: 'company',
+ name: 'Acme',
+ ownerId: 'owner',
+ teamId: 'team',
+ hidden: false,
+ domains: [],
+};
+const CONTACT: CrmContactEntity = {
+ type: 'crm_contact',
+ id: 'contact',
+ name: 'Example Contact',
+ ownerId: 'owner',
+ companyId: COMPANY.id,
+ email: '[email protected]',
+ hidden: false,
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.graphql = true;
+ mocks.loading.mockReturnValue(false);
+ mocks.feed.mockImplementation(() => []);
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe.each([COMPANY, CONTACT])('opening $type notifications', (record) => {
+ const discussion: UnifiedNotification = {
+ id: 'discussion',
+ entity_id: record.id,
+ entity_type: record.type,
+ state: 'unseen',
+ notification_event_type: 'crm_discussion',
+ notification_metadata: {
+ tag: 'crm_discussion',
+ content: {
+ messageId: 'message',
+ threadId: 'thread',
+ reason: 'mention',
+ recordName: record.name,
+ text: 'Please review',
+ },
+ },
+ created_at: '2026-10-22T17:00:00Z',
+ updated_at: '2026-10-22T17:00:00Z',
+ viewed_at: null,
+ sent: true,
+ };
+ it('waits for a loading REST feed before marking a row without attached notifications', async () => {
+ mocks.graphql = false;
+ const [loading, setLoading] = createSignal(true);
+ mocks.loading.mockImplementation(loading);
+ const loaded = Promise.withResolvers<void>();
+ const marked = Promise.withResolvers<void>();
+ const [feed, setFeed] = createSignal<UnifiedNotification[]>();
+ mocks.feed.mockImplementation(feed);
+ mocks.refetch.mockImplementationOnce(async () => {
+ await loaded.promise;
+ setFeed([{ ...discussion, id: `${record.id}-loading` }]);
+ setLoading(false);
+ });
+ mocks.seen.mockImplementationOnce(async () => marked.resolve());
+ const { source, dispose } = createRoot((dispose) => ({
+ source: createNotificationSource({} as ConnectionGatewayWebsocket),
+ dispose,
+ }));
+ try {
+ markCrmNotificationsSeenOnOpen(record, source);
+ expect(mocks.refetch).toHaveBeenCalledOnce();
+ expect(mocks.seen).not.toHaveBeenCalled();
+ loaded.resolve();
+ await marked.promise;
+ expect(mocks.seen).toHaveBeenCalledWith({
+ notificationIds: [`${record.id}-loading`],
+ });
+ expect(mocks.entitySeen).not.toHaveBeenCalled();
+ } finally {
+ loaded.resolve();
+ dispose();
+ }
+ });
+
+ it('reports a failed entity read when the row has no loaded notifications', async () => {
+ const error = new Error('offline');
+ const reported = Promise.withResolvers<void>();
+ const telemetry = vi
+ .spyOn(Telemetry, 'error')
+ .mockImplementation(() => reported.resolve());
+ mocks.entitySeen.mockRejectedValueOnce(error);
+ const { source, dispose } = createRoot((dispose) => ({
+ source: createNotificationSource({} as ConnectionGatewayWebsocket),
+ dispose,
+ }));
+ try {
+ markCrmNotificationsSeenOnOpen({ ...record, notifications: [] }, source);
+ await reported.promise;
+ expect(telemetry).toHaveBeenCalledWith(error, {
+ surface: 'crm-notification-read',
+ });
+ } finally {
+ dispose();
+ }
+ });
+
+ it.each(['array', 'accessor'] as const)(
+ 'clears an attached %s before the write finishes without loading the global feed',
+ async (shape) => {
+ mocks.feed.mockClear();
+ const pending = Promise.withResolvers<void>();
+ mocks.seen.mockReturnValueOnce(pending.promise);
+ const { source, dispose } = createRoot((dispose) => ({
+ source: createNotificationSource({} as ConnectionGatewayWebsocket),
+ dispose,
+ }));
+ const attached = [
+ { ...discussion, id: `${record.id}-pending-${shape}` },
+ {
+ ...discussion,
+ id: `${record.id}-done-${shape}`,
+ state: 'done' as const,
+ },
+ {
+ ...discussion,
+ id: `${record.id}-seen-${shape}`,
+ state: 'seen' as const,
+ },
+ ];
+ const row = {
+ ...record,
+ notifications: shape === 'array' ? attached : () => attached,
+ };
+ const rendered = withEntityNotifications(row, source);
+ try {
+ expect(unreadFilterFn(rendered)).toBe(true);
+ markCrmNotificationsSeenOnOpen(row, source);
+ expect(unreadFilterFn(rendered)).toBe(false);
+ expect(mocks.seen).toHaveBeenLastCalledWith({
+ notificationIds: [`${record.id}-pending-${shape}`],
+ });
+ expect(mocks.feed).not.toHaveBeenCalled();
+ pending.resolve();
+ await pending.promise;
+ // A stale list snapshot must not resurrect the dot after success.
+ expect(unreadFilterFn(withEntityNotifications(row, source))).toBe(
+ false
+ );
+ } finally {
+ pending.resolve();
+ dispose();
+ }
+ }
+ );
+
+ it('restores the dot after a failed write and clears it on a retry', async () => {
+ const pending = Promise.withResolvers<void>();
+ const reported = Promise.withResolvers<void>();
+ vi.spyOn(Telemetry, 'error').mockImplementation(() => reported.resolve());
+ mocks.seen.mockReturnValueOnce(pending.promise);
+ const { source, dispose } = createRoot((dispose) => ({
+ source: createNotificationSource({} as ConnectionGatewayWebsocket),
+ dispose,
+ }));
+ const row = withEntityNotifications(
+ {
+ ...record,
+ notifications: [{ ...discussion, id: `${record.id}-failed-read` }],
+ },
+ source
+ );
+ try {
+ markCrmNotificationsSeenOnOpen(row, source);
+ expect(unreadFilterFn(row)).toBe(false);
+ pending.reject(new Error('offline'));
+ await reported.promise;
+ expect(unreadFilterFn(row)).toBe(true);
+ mocks.seen.mockResolvedValueOnce(undefined);
+ markCrmNotificationsSeenOnOpen(row, source);
+ expect(unreadFilterFn(row)).toBe(false);
+ } finally {
+ dispose();
+ }
+ });
+
+ it.each(['absent', 'empty'] as const)(
+ 'marks the entity with %s row notifications without loading the global feed',
+ async (shape) => {
+ mocks.entitySeen.mockResolvedValueOnce([]);
+ mocks.feed.mockClear();
+ const { source, dispose } = createRoot((dispose) => ({
+ source: createNotificationSource({} as ConnectionGatewayWebsocket),
+ dispose,
+ }));
+ try {
+ markCrmNotificationsSeenOnOpen(
+ { ...record, notifications: shape === 'empty' ? [] : undefined },
+ source
+ );
+ expect(mocks.entitySeen).toHaveBeenLastCalledWith({
+ entities: [
+ {
+ entityType:
+ record.type === 'crm_company' ? 'CRM_COMPANY' : 'CRM_CONTACT',
+ entityId: record.id,
+ },
+ ],
+ operation: 'MARK_SEEN',
+ expectedNotificationIds: [],
+ });
+ expect(mocks.feed).not.toHaveBeenCalled();
+ } finally {
+ dispose();
+ }
+ }
+ );
+});
diff --git a/apps/web/src/lib/queries/notification/entity-mutations.ts b/apps/web/src/lib/queries/notification/entity-mutations.ts
index 9dea6448f1..1f9b16e6f8 100644
--- a/apps/web/src/lib/queries/notification/entity-mutations.ts
+++ b/apps/web/src/lib/queries/notification/entity-mutations.ts
@@ -18,6 +18,7 @@ type SimpleNotificationEntityType =
| 'channel'
| 'chat'
| 'crm_company'
+ | 'crm_contact'
| 'document'
| 'email'
| 'email_thread'
@@ -56,6 +57,7 @@ export function toNotificationEntityRef(
case 'channel':
case 'chat':
case 'crm_company':
+ case 'crm_contact':
case 'document':
case 'email':
case 'email_thread':
@@ -87,6 +89,7 @@ const ENTITY_TYPE_TO_GRAPHQL = {
channel: 'CHANNEL',
chat: 'CHAT',
crm_company: 'CRM_COMPANY',
+ crm_contact: 'CRM_CONTACT',
document: 'DOCUMENT',
email: 'EMAIL_THREAD',
email_thread: 'EMAIL_THREAD',
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index b7908a25cd..5db5a9497d 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -11,6 +11,11 @@ There are no built-in company views or Board/List layout. Companies and People
are plain soup lists with the shared pagination. Existing personal/team saved
views stay in the toolbar's Views menu.
+Opening a company or contact row in Companies or People clears its blue unread
+dot, including desktop preview activation, keyboard opening, and phone navigation.
+The read is saved in the background; a failed request restores the dot so opening
+it again can retry. Marking read does not mark the notification done.
+
**Rollout:** Tasks, Email, Notes, Calls and Databases require PostHog `enable-crm-activity`
(off by default; local override: `VITE_ENABLE_CRM_ACTIVITY=true`). CRM also uses
this flag to decide whether to supply its task-composer preset; the shared