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
chg/fix(notifications): use tanstack as source of truth for optimistic updating, simplifies source (#815)
teo7275d8a04175
diff --git a/js/app/packages/core/component/Notifications.tsx b/js/app/packages/core/component/Notifications.tsxindex 6f8b581654..ed519cab6f 100644--- a/js/app/packages/core/component/Notifications.tsx+++ b/js/app/packages/core/component/Notifications.tsx@@ -20,7 +20,7 @@ export type NotificationsProps = {export function Notifications(props: NotificationsProps) {const notifications = createMemo(() => {const entityNotifications =- props.notificationSource.store[+ props.notificationSource.notificationsByEntity()[`${props.entity.type}@${props.entity.id}`] ?? [];return entityNotifications.sort((a, b) => {diff --git a/js/app/packages/notifications/notification-helpers.ts b/js/app/packages/notifications/notification-helpers.tsindex 94517e2430..c45bd475c4 100644--- a/js/app/packages/notifications/notification-helpers.ts+++ b/js/app/packages/notifications/notification-helpers.ts@@ -15,7 +15,8 @@ export function useNotificationsForEntity(entity: Entity): Accessor<UnifiedNotification[]> {return createMemo(- () => notificationSource.store[compositeEntity(entity)] ?? []+ () =>+ notificationSource.notificationsByEntity()[compositeEntity(entity)] ?? []);}@@ -61,7 +62,8 @@ export function entityHasUnreadNotifications(notificationSource: NotificationSource,entity: Entity): boolean {- const notifications = notificationSource.store[compositeEntity(entity)] ?? [];+ const notifications =+ notificationSource.notificationsByEntity()[compositeEntity(entity)] ?? [];return notifications.some((notification) => {return (@@ -140,7 +142,7 @@ export function markNotificationsForEntityAsDone(entity: Entity): Promise<void> {return notificationSource.bulkMarkAsDone(- notificationSource.store[compositeEntity(entity)] ?? []+ notificationSource.notificationsByEntity()[compositeEntity(entity)] ?? []);}@@ -166,7 +168,7 @@ export function markNotificationsForEntityAsRead(entity: Entity): Promise<void> {return notificationSource.bulkMarkAsRead(- notificationSource.store[compositeEntity(entity)] ?? []+ notificationSource.notificationsByEntity()[compositeEntity(entity)] ?? []);}diff --git a/js/app/packages/notifications/notification-source.ts b/js/app/packages/notifications/notification-source.tsindex 65cc89a2ce..d807489c5d 100644--- a/js/app/packages/notifications/notification-source.ts+++ b/js/app/packages/notifications/notification-source.ts@@ -1,5 +1,6 @@import type { Entity } from '@core/types';import {+ optimisticInsertNotification,useMarkNotificationsAsDoneMutation,useMarkNotificationsAsSeenMutation,useUserNotificationsQuery,@@ -7,7 +8,6 @@ import {import type { ConnectionGatewayWebsocket } from '@service-connection/websocket';import { notificationServiceClient } from '@service-notification/client';import type { UserUnsubscribe } from '@service-notification/generated/schemas';-import { trackStore } from '@solid-primitives/deep';import type {UseInfiniteQueryResult,UseQueryResult,@@ -15,13 +15,11 @@ import type {import { createSocketEffect } from '@websocket/index';import {type Accessor,- batch,createEffect,createMemo,createSignal,} from 'solid-js';-import { createStore, reconcile, type Store, unwrap } from 'solid-js/store';-import { fetchNotificationsForEntities } from './queries/entities-notifications-query';+import { reconcile } from 'solid-js/store';import { createMutedEntitiesQuery } from './queries/muted-entities-query';import {type CompositeEntity,@@ -30,17 +28,13 @@ import {type UnifiedNotification,} from './types';-type NotificationStoreInner = Record<CompositeEntity, UnifiedNotification[]>;--type AssertKey<T, K extends keyof T & string> = K;--const NOTIFICATION_KEY: AssertKey<UnifiedNotification, 'id'> = 'id';+type NotificationsByEntity = Record<CompositeEntity, UnifiedNotification[]>;type UnsubscribeFn = () => void;type SubscribeFn = (newNotification: UnifiedNotification) => void;export type NotificationSource = {- readonly store: Store<NotificationStoreInner>;+ readonly notificationsByEntity: Accessor<NotificationsByEntity>;readonly notifications: Accessor<UnifiedNotification[]>;readonly mutedEntities: Accessor<UserUnsubscribe[]>;readonly isLoading: Accessor<boolean>;@@ -82,12 +76,7 @@ export function createNotificationSource(ws: ConnectionGatewayWebsocket,onNotification?: (notification: UnifiedNotification) => void): NotificationSource {- const [store, setStore] = createStore<NotificationStoreInner>({});- const notifications = createMemo(() =>- Object.values(trackStore(store)).flat()- );-- let subscriptions: Set<SubscribeFn> = new Set();+ const subscriptions: Set<SubscribeFn> = new Set();const [mutedEntities, setMutedEntities] = createSignal<UserUnsubscribe[]>([]);@@ -95,58 +84,22 @@ export function createNotificationSource(const mutedEntitiesQuery = createMutedEntitiesQuery({ limit: QUERY_LIMIT });const markNotificationsAsSeenMutation = useMarkNotificationsAsSeenMutation();-const markNotificationsAsDoneMutation = useMarkNotificationsAsDoneMutation();- /** Reconcile new notifications into the store */- const reconcileNotifications = (- notifications: UnifiedNotification[],- entities: Entity[] = []- ) => {- const newNotificationMap: NotificationStoreInner = Object.fromEntries(- entities.map((entity) => [compositeEntity(entity), []])- );+ const notifications = createMemo(() => notificationsQuery.data ?? []);++ const notificationsByEntity = createMemo(() => {+ const data = notifications();+ const grouped: NotificationsByEntity = {};- for (const notification of notifications) {+ for (const notification of data) {const composite = compositeEntity(notificationEntity(notification));- newNotificationMap[composite] = [- ...(newNotificationMap[composite] ?? []),- notification,- ];+ grouped[composite] ??= [];+ grouped[composite].push(notification);}- batch(() => {- const currentKeys: Set<CompositeEntity> = new Set(- Object.keys(store) as CompositeEntity[]- );- const newKeys: Set<CompositeEntity> = new Set(- Object.keys(newNotificationMap) as CompositeEntity[]- );- for (const key of currentKeys) {- if (!newKeys.has(key)) {- setStore(key, reconcile([], { key: NOTIFICATION_KEY }));- }- }-- for (const [composite, notifications] of Object.entries(- newNotificationMap- )) {- setStore(- composite as CompositeEntity,- reconcile(notifications, { key: NOTIFICATION_KEY })- );- }- });- };-- const entitiesFromNotifications = (notifications: UnifiedNotification[]) => {- return Array.from(new Set(notifications.map(notificationEntity)));- };-- const refetchAndReconcileEntities = async (entities: Entity[]) => {- const notifications = await fetchNotificationsForEntities(entities);- reconcileNotifications(notifications, entities);- };+ return grouped;+ });createEffect(() => {if (!notificationsQuery.isSuccess) return;@@ -155,13 +108,6 @@ export function createNotificationSource(}});- const refetchAndReconcileNotifications = async (- notifications: UnifiedNotification[]- ) => {- const entities = entitiesFromNotifications(notifications);- await refetchAndReconcileEntities(entities);- };-const isLoading = () => {return notificationsQuery.isLoading || mutedEntitiesQuery.isLoading;};@@ -172,13 +118,6 @@ export function createNotificationSource(setMutedEntities(reconcile(mutedEntities));});- createEffect(() => {- // Only update notifications if query is successful- if (!notificationsQuery.isSuccess) return;-- reconcileNotifications(unwrap(notificationsQuery.data));- });-createSocketEffect(ws, (wsData) => {if (wsData.type !== NOTIFICATION_EVENT_TYPE) {return;@@ -194,7 +133,7 @@ export function createNotificationSource(subscriptions.forEach((subscribe) => subscribe(parsedNotification));- refetchAndReconcileNotifications([parsedNotification]);+ optimisticInsertNotification(parsedNotification);});const bulkMarkAsDone = async (notifications: UnifiedNotification[]) => {@@ -243,7 +182,7 @@ export function createNotificationSource(};return {- store,+ notificationsByEntity,notifications,mutedEntities,isLoading,diff --git a/js/app/packages/queries/notification/tests/user-notifications.test.tsx b/js/app/packages/queries/notification/tests/user-notifications.test.tsxindex e3ab01b6b3..e878673e37 100644--- a/js/app/packages/queries/notification/tests/user-notifications.test.tsx+++ b/js/app/packages/queries/notification/tests/user-notifications.test.tsx@@ -11,6 +11,7 @@ import { render } from 'solid-js/web';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { notificationKeys } from '../keys';import {+ optimisticInsertNotification,useMarkNotificationsAsDoneMutation,useMarkNotificationsAsSeenMutation,} from '../user-notifications';@@ -319,3 +320,48 @@ describe('notification mutations', () => {});});});++describe('optimisticInsertNotification', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ testQueryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });+ });++ afterEach(() => {+ testQueryClient.clear();+ });++ it('should insert notification at the beginning of the first page', () => {+ const n1 = createMockNotification({ id: 'n1' });+ const n2 = createMockNotification({ id: 'n2' });+ seedQueryCache([createMockNotificationPage([n1, n2])]);++ const newNotification = createMockNotification({ id: 'new-notification' });+ optimisticInsertNotification(newNotification);++ const notifications = getNotificationsFromCache();+ expect(notifications).toHaveLength(3);+ expect(notifications[0].id).toBe('new-notification');+ expect(notifications[1].id).toBe('n1');+ expect(notifications[2].id).toBe('n2');+ });++ it('should not insert duplicate notifications', () => {+ const n1 = createMockNotification({ id: 'n1' });+ const n2 = createMockNotification({ id: 'n2' });+ seedQueryCache([createMockNotificationPage([n1, n2])]);++ const duplicateNotification = createMockNotification({ id: 'n1' });+ optimisticInsertNotification(duplicateNotification);++ const notifications = getNotificationsFromCache();+ expect(notifications).toHaveLength(2);+ expect(notifications[0].id).toBe('n1');+ expect(notifications[1].id).toBe('n2');+ });+});diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.tsindex 1d210dfce8..3b3a6d92dc 100644--- a/js/app/packages/queries/notification/user-notifications.ts+++ b/js/app/packages/queries/notification/user-notifications.ts@@ -359,3 +359,32 @@ export const useMarkNotificationsAsDoneMutation = createNotificationsMutation(onError: notificationsMutationErrorFn,});++type NotificationItem = GetAllUserNotificationsResponse['items'][number];++export function optimisticInsertNotification(+ notification: Omit<NotificationItem, 'ownerId'>+) {+ const item = notification as NotificationItem;++ queryClient.setQueriesData<NotificationData<UserNotificationsPageParam>>(+ { queryKey: notificationKeys.user._def },+ (data) => {+ if (!data) return data;++ const exists = data.pages.some((page) =>+ page.items.some((n) => n.id === item.id)+ );+ if (exists) return data;++ return {+ ...data,+ pages: data.pages.map((page, index) =>+ index === 0 ? { ...page, items: [item, ...page.items] } : page+ ),+ };+ }+ );++ invalidateUserNotifications();+}