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.

feat(notifications): port notifications to query package (#641)

teo662ed191d800
diff --git a/js/app/docs/testing-best-practices.md b/js/app/docs/testing-best-practices.md
new file mode 100644
index 0000000000..c29535c6a8
--- /dev/null
+++ b/js/app/docs/testing-best-practices.md
@@ -0,0 +1,269 @@
+# Testing Best Practices: SolidJS & TanStack Query
+
+## Core Principles
+
+1. **Test features, not implementations** - Tests should verify behavior users care about, not internal details
+2. **Isolate each test** - Fresh QueryClient per test, no shared state between tests
+3. **Disable retries** - Prevent timeouts and make tests deterministic
+4. **Avoid `waitFor` when possible** - Solid's signals update synchronously; only use for async operations like router navigation or suspense
+
+## Setup
+
+### Dependencies
+
+```bash
+npm i vitest jsdom @solidjs/testing-library @testing-library/user-event @testing-library/jest-dom -D
+```
+
+### Vitest Configuration
+
+```typescript
+// vitest.config.ts
+import solidPlugin from 'vite-plugin-solid';
+import tsconfigPaths from 'vite-tsconfig-paths';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ plugins: [tsconfigPaths(), solidPlugin()],
+ test: {
+ environment: 'jsdom',
+ globals: true,
+ },
+});
+```
+
+## TanStack Query Testing
+
+### QueryClient Configuration
+
+Always create a fresh QueryClient per test with retries disabled:
+
+```typescript
+let testQueryClient: QueryClient;
+
+beforeEach(() => {
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+});
+
+afterEach(() => {
+ testQueryClient.clear();
+});
+```
+
+### Wrapper Pattern
+
+Create a reusable wrapper for components that need QueryClient context:
+
+```typescript
+function createWrapper() {
+ return function Wrapper(props: { children: JSX.Element }) {
+ return (
+ <QueryClientProvider client={testQueryClient}>
+ {props.children}
+ </QueryClientProvider>
+ );
+ };
+}
+
+function renderWithClient(Component: () => JSX.Element): () => void {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const Wrapper = createWrapper();
+ const dispose = render(
+ () => (
+ <Wrapper>
+ <Component />
+ </Wrapper>
+ ),
+ container
+ );
+ return () => {
+ dispose();
+ container.remove();
+ };
+}
+```
+
+### Testing Mutations
+
+Test mutations by rendering a component that uses the mutation hook:
+
+```typescript
+it('should update cache optimistically', async () => {
+ // Seed cache with initial data
+ seedQueryCache([createMockPage([item1, item2])]);
+
+ // Mock service response
+ mockServiceMethod.mockResolvedValue(ok({ success: true }));
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMyMutation();
+ mutatePromise = mutation.mutateAsync({ id: 'item1' });
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+ await mutatePromise;
+
+ // Assert cache was updated
+ const items = getItemsFromCache();
+ expect(items).toHaveLength(1);
+
+ cleanup();
+});
+```
+
+### Testing Rollback on Error
+
+```typescript
+it('should rollback on error', async () => {
+ seedQueryCache([createMockPage([item1])]);
+
+ mockServiceMethod.mockResolvedValue(err('SERVER_ERROR', 'Failed'));
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMyMutation();
+ mutatePromise = mutation.mutateAsync({ id: 'item1' }).catch(() => {});
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+ await mutatePromise;
+ await new Promise((r) => setTimeout(r, 10)); // Wait for rollback
+
+ // Assert cache was restored
+ const items = getItemsFromCache();
+ expect(items).toHaveLength(1);
+
+ cleanup();
+});
+```
+
+## SolidJS Testing
+
+### Component Testing
+
+```typescript
+import { render } from '@solidjs/testing-library';
+import userEvent from '@testing-library/user-event';
+
+test('button increments counter', async () => {
+ const { getByRole } = render(() => <Counter />);
+ const button = getByRole('button');
+
+ expect(button).toHaveTextContent('0');
+ await userEvent.setup().click(button);
+ expect(button).toHaveTextContent('1');
+});
+```
+
+### Testing Hooks with renderHook
+
+For hooks that don't need DOM:
+
+```typescript
+import { renderHook } from '@solidjs/testing-library';
+
+test('hook returns initial state', () => {
+ const { result } = renderHook(useMyHook);
+ expect(result.value).toBe(0);
+
+ result.increment();
+ expect(result.value).toBe(1);
+});
+```
+
+### Testing Effects with testEffect
+
+For async reactive effects:
+
+```typescript
+import { testEffect } from '@solidjs/testing-library';
+
+test('effect reacts to signal changes', () => {
+ const [value, setValue] = createSignal(0);
+
+ return testEffect((done) =>
+ createEffect((run = 0) => {
+ if (run === 0) {
+ expect(value()).toBe(0);
+ setValue(1);
+ } else {
+ expect(value()).toBe(1);
+ done();
+ }
+ return run + 1;
+ })
+ );
+});
+```
+
+### Query Selectors (Priority Order)
+
+Use accessibility-first selectors:
+
+1. `getByRole` - WAI-ARIA roles (preferred)
+2. `getByLabelText` - Form labels
+3. `getByPlaceholderText` - Placeholders
+4. `getByText` - Text content
+5. `getByTestId` - Last resort
+
+### Context Wrappers
+
+```typescript
+const wrapper = (props) => (
+ <MyContext.Provider value={mockValue} {...props} />
+);
+
+const { getByText } = render(() => <Consumer />, { wrapper });
+```
+
+## What NOT to Test
+
+- Query key structure (implementation detail)
+- That service clients are called with exact params (if behavior test passes, this is proven)
+- Empty array edge cases (unless it's a user-facing feature)
+- Internal function calls between modules
+
+## What TO Test
+
+- Optimistic updates modify cache correctly
+- Rollback restores previous state on error
+- Multi-page/paginated data is handled correctly
+- Error states propagate to callers
+- User-visible behavior changes
+
+## Mocking Service Clients
+
+Mock at the module boundary, not internal functions:
+
+```typescript
+vi.mock('@service/client', () => ({
+ serviceClient: {
+ fetchData: vi.fn(),
+ updateData: vi.fn(),
+ },
+}));
+
+import { serviceClient } from '@service/client';
+
+const mockFetchData = vi.mocked(serviceClient.fetchData);
+const mockUpdateData = vi.mocked(serviceClient.updateData);
+```
+
+## References
+
+- [SolidJS Testing Guide](https://docs.solidjs.com/guides/testing)
+- [Solid Testing Library](https://github.com/solidjs/solid-testing-library)
+- [TanStack Query Testing](https://tanstack.com/query/v5/docs/framework/react/guides/testing)
+- [TanStack Query Optimistic Updates](https://tanstack.com/query/v5/docs/react/guides/optimistic-updates)
+- [Testing Library Intro](https://testing-library.com/docs/solid-testing-library/intro/)
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
index d347d88db5..d522803465 100644
--- a/js/app/packages/app/component/Soup.tsx
+++ b/js/app/packages/app/component/Soup.tsx
@@ -31,6 +31,7 @@ import {
useQueryClient as useEntityQueryClient,
} from '@macro-entity';
import { createEffectOnEntityTypeNotification } from '@notifications';
+import { invalidateEntityNotifications } from '@queries/notification/user-notifications';
import { storageServiceClient } from '@service-storage/client';
import { Navigate } from '@solidjs/router';
import { useMutation, useQueryClient } from '@tanstack/solid-query';
@@ -311,11 +312,7 @@ export function Soup() {
entityQueryClient.invalidateQueries({
queryKey: queryKeys.all.channel,
});
- entityQueryClient.invalidateQueries({
- queryKey: queryKeys.notification({
- entity_id: notification.entity_id,
- }),
- });
+ invalidateEntityNotifications(notification.entity_id);
}
);
diff --git a/js/app/packages/core/types/index.ts b/js/app/packages/core/types/index.ts
index 4fb6574952..f1aa93a43e 100644
--- a/js/app/packages/core/types/index.ts
+++ b/js/app/packages/core/types/index.ts
@@ -16,3 +16,8 @@ export type Entity = {
export type { ApiPaginatedThreadCursor as ThreadPreview } from '@service-email/generated/schemas/apiPaginatedThreadCursor';
export { NotificationEventType as NotificationType } from '@service-notification/generated/schemas/notificationEventType';
+
+export type Nullable<T> = T | null;
+export type Maybe<T> = T | undefined;
+
+export type MaybePromise<T> = T | Promise<T>;
diff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsx
index dc35af6556..5acb9cb50f 100644
--- a/js/app/packages/macro-entity/src/index.tsx
+++ b/js/app/packages/macro-entity/src/index.tsx
@@ -22,13 +22,7 @@ export {
export { createEmailsInfiniteQuery } from './queries/email';
export type { EntityInfiniteQuery, EntityQuery } from './queries/entity';
export { queryKeys } from './queries/key';
-export {
- createEntityNotificationsInfiniteQuery,
- createNotificationsInfiniteQuery,
- createUnseenNotificationIds,
- createUnseenNotifications,
- enhanceWithNotifications,
-} from './queries/notification';
+export { enhanceWithNotifications } from './queries/notification';
export * from './queries/search';
export { createEmailSource, type EmailSource, useEmails } from './source/email';
export * from './types/entity';
diff --git a/js/app/packages/macro-entity/src/queries/key.ts b/js/app/packages/macro-entity/src/queries/key.ts
index 129dc85036..b2fd310f5d 100644
--- a/js/app/packages/macro-entity/src/queries/key.ts
+++ b/js/app/packages/macro-entity/src/queries/key.ts
@@ -10,7 +10,6 @@ const BASE_ENTITY = {
channel: [ENTITY, 'channel'],
dss: [ENTITY, 'dss'],
email: [ENTITY, 'email'],
- notification: [ENTITY, 'notification'],
search: [ENTITY, 'search'],
};
@@ -28,10 +27,6 @@ type InfiniteKeyOptions =
type EmailKeyOptions = InfiniteKeyOptions & {
view: PreviewViewStandardLabel;
};
-type NotificationKeyOptions = InfiniteKeyOptions & {
- eventItemId?: string;
- eventItemIds?: string[];
-};
type SearchKeyOptions = {
infinite: true;
} & PaginatedSearchArgs;
@@ -60,10 +55,6 @@ export const queryKeys = {
],
dss: (args?: InfiniteKeyOptions) => [...BASE_ENTITY.dss, { ...args }],
email: (args: EmailKeyOptions) => [...BASE_ENTITY.email, { ...args }],
- notification: (args?: NotificationKeyOptions) => [
- ...BASE_ENTITY.notification,
- { ...args },
- ],
project: (args: { projectId: string }) => [
'project',
{ projectId: args.projectId },
diff --git a/js/app/packages/macro-entity/src/queries/notification.ts b/js/app/packages/macro-entity/src/queries/notification.ts
index 40eb2719ec..249a554323 100644
--- a/js/app/packages/macro-entity/src/queries/notification.ts
+++ b/js/app/packages/macro-entity/src/queries/notification.ts
@@ -1,224 +1,22 @@
-import type { BulkGetUserNotificationsByEventItemIdRequest } from '@service-notification/generated/schemas/bulkGetUserNotificationsByEventItemIdRequest';
-import type { GetAllUserNotificationsResponse } from '@service-notification/generated/schemas/getAllUserNotificationsResponse';
-import type { UserNotification } from '@service-notification/generated/schemas/userNotification';
-import {
- type UseInfiniteQueryResult,
- useInfiniteQuery,
-} from '@tanstack/solid-query';
-import { SERVER_HOSTS } from 'core/constant/servers';
-import { platformFetch } from 'core/util/platformFetch';
-import { createEffect, createMemo, createSelector } from 'solid-js';
+import { useEntityNotificationsQuery } from '@queries/notification/user-notifications';
+import { createEffect } from 'solid-js';
import { unwrap } from 'solid-js/store';
import type { EntityData } from '../types/entity';
-import type { Notification, WithNotification } from '../types/notification';
-import { createApiTokenQuery } from './auth';
-import type { EntityQuery } from './entity';
-import { queryKeys } from './key';
-
-const fetchPaginatedNotifications = async ({
- apiToken,
- cursor,
- limit = 20,
-}: {
- apiToken?: string;
- cursor?: string;
- limit?: number;
-}) => {
- if (!apiToken) throw new Error('No API token provided');
- const Authorization = `Bearer ${apiToken}`;
-
- const response = await platformFetch(
- `${SERVER_HOSTS['notification-service']}/user_notifications?limit=${limit}${cursor ? `&cursor=${cursor}` : ''}`,
- {
- headers: { Authorization },
- }
- );
- if (!response.ok)
- throw new Error('Failed to fetch notifications', { cause: response });
-
- const result: GetAllUserNotificationsResponse = await response.json();
- return result;
-};
-
-export function createNotificationsInfiniteQuery(args?: { limit?: number }) {
- const limit =
- args?.limit && args.limit > 0 && args.limit <= 500 ? args.limit : 20;
- const authQuery = createApiTokenQuery();
- return useInfiniteQuery(() => ({
- queryKey: queryKeys.notification({ infinite: true, limit }),
- queryFn: ({ pageParam }) =>
- fetchPaginatedNotifications({ apiToken: authQuery.data, ...pageParam }),
- initialPageParam: { limit },
- getNextPageParam: ({ next_cursor }) =>
- next_cursor ? { cursor: next_cursor, limit } : null,
- select: (data) => data.pages.flatMap(({ items }) => items),
- enabled: authQuery.isSuccess,
- staleTime: 1000 * 60 * 5, // 5 minutes
- gcTime: 1000 * 60 * 10, // 10 minutes
- }));
-}
-
-const fetchEntityNotifications = async ({
- apiToken,
- cursor,
- limit = 20,
- eventItemIds,
-}: {
- apiToken?: string;
- cursor?: string;
- limit?: number;
-} & BulkGetUserNotificationsByEventItemIdRequest) => {
- if (!apiToken) throw new Error('No API token provided');
- const Authorization = `Bearer ${apiToken}`;
-
- const response = await platformFetch(
- `${SERVER_HOSTS['notification-service']}/user_notifications/item/bulk?limit=${limit}${cursor ? `&cursor=${cursor}` : ''}`,
- {
- method: 'POST',
- headers: { Authorization, 'Content-Type': 'application/json' },
- body: JSON.stringify({ eventItemIds }),
- }
- );
- if (!response.ok)
- throw new Error('Failed to fetch entity notifications', {
- cause: response,
- });
-
- const result: GetAllUserNotificationsResponse = await response.json();
- return result;
-};
-
-export function createEntityNotificationsInfiniteQuery(args: {
- entityQueries: Array<EntityQuery>;
- limit?: number;
-}) {
- const limit =
- args?.limit && args.limit > 0 && args.limit <= 500 ? args.limit : 20;
- const authQuery = createApiTokenQuery();
- const entityIds = createMemo<string[]>(() => {
- if (args.entityQueries.length === 0) return [];
- if (args.entityQueries.some((query) => !query.isSuccess)) return [];
-
- return args.entityQueries.flatMap((query) =>
- query.isSuccess ? query.data.map((entity) => entity.id) : []
- );
- });
- return useInfiniteQuery(() => ({
- queryKey: queryKeys.notification({
- infinite: true,
- limit,
- ids: entityIds(),
- }),
- queryFn: ({ pageParam }) =>
- fetchEntityNotifications({ apiToken: authQuery.data, ...pageParam }),
- initialPageParam: { limit, eventItemIds: entityIds() },
- getNextPageParam: ({ next_cursor }) =>
- next_cursor
- ? { cursor: next_cursor, limit, eventItemIds: entityIds() }
- : null,
- select: (data) => data.pages.flatMap(({ items }) => items),
- enabled: authQuery.isSuccess && entityIds().length > 0,
- }));
-}
-
-export function createUnseenNotifications(
- notificationsQuery: UseInfiniteQueryResult<UserNotification[]>
-) {
- createEffect(() => {
- if (notificationsQuery.isSuccess) {
- if (notificationsQuery.hasNextPage && !notificationsQuery.isFetching) {
- notificationsQuery.fetchNextPage();
- }
- }
- });
-
- return createMemo<Notification[]>(() => {
- if (!notificationsQuery.isSuccess) return [];
-
- return notificationsQuery.data.flatMap((notification) => {
- if (notification.viewedAt) return [];
-
- return [notification];
- });
- });
-}
-
-export function createUnseenNotificationIds(
- notificationsQuery: UseInfiniteQueryResult<UserNotification[]>
-) {
- const unseenNotifications = createUnseenNotifications(notificationsQuery);
-
- return createMemo<string[]>(() => {
- const unseen = unseenNotifications().flatMap((notification) => {
- if (notification.viewedAt) return [];
-
- return [notification.entity_id];
- });
-
- return [...new Set(unseen)];
- });
-}
-
-export function createUnseenNotificationSelector(
- entityQueries: Array<EntityQuery>
-) {
- const notificationsQuery = createEntityNotificationsInfiniteQuery({
- entityQueries,
- });
- const unseenNotificationIds = createUnseenNotificationIds(notificationsQuery);
-
- return createSelector(unseenNotificationIds, (id: string, unseenIds) =>
- unseenIds.includes(id)
- );
-}
-
-const fetchPaginatedEntityNotifications = async ({
- apiToken,
- cursor,
- eventItemId,
- limit = 20,
-}: {
- apiToken?: string;
- cursor?: string;
- eventItemId: string;
- limit?: number;
-}) => {
- if (!apiToken) throw new Error('No API token provided');
- const Authorization = `Bearer ${apiToken}`;
-
- const response = await platformFetch(
- `${SERVER_HOSTS['notification-service']}/user_notifications/item/${eventItemId}?limit=${limit}${cursor ? `&cursor=${cursor}` : ''}`,
- {
- headers: { Authorization },
- }
- );
- if (!response.ok)
- throw new Error('Failed to fetch email', { cause: response });
-
- const result: GetAllUserNotificationsResponse = await response.json();
- return result;
-};
+import type { WithNotification } from '../types/notification';
+/**
+ * Enhances an entity with its notifications as an accessor.
+ */
export function enhanceWithNotifications<T extends EntityData>(
entity: T
): WithNotification<T> {
const eventItemId = entity.id;
const limit = 100;
- const authQuery = createApiTokenQuery();
- const notificationsQuery = useInfiniteQuery(() => ({
- queryKey: queryKeys.notification({ infinite: true, eventItemId, limit }),
- queryFn: ({ pageParam }) =>
- fetchPaginatedEntityNotifications({
- apiToken: authQuery.data,
- ...pageParam,
- }),
- initialPageParam: { eventItemId, limit },
- getNextPageParam: ({ next_cursor }) =>
- next_cursor ? { cursor: next_cursor, eventItemId, limit } : null,
- select: (data) => data.pages.flatMap(({ items }) => items),
- enabled: authQuery.isSuccess,
- gcTime: 1000 * 60 * 10, // 10 minutes
- }));
+
+ const notificationsQuery = useEntityNotificationsQuery({
+ eventItemId: () => eventItemId,
+ limit,
+ });
createEffect(() => {
if (notificationsQuery.isSuccess) {
diff --git a/js/app/packages/notifications/notification-source.ts b/js/app/packages/notifications/notification-source.ts
index 543a2ca12d..d0de1d7a14 100644
--- a/js/app/packages/notifications/notification-source.ts
+++ b/js/app/packages/notifications/notification-source.ts
@@ -1,5 +1,9 @@
import type { Entity } from '@core/types';
-import { createNotificationsInfiniteQuery as createNotificationQuery } from '@macro-entity';
+import {
+ useMarkNotificationsAsDoneMutation,
+ useMarkNotificationsAsSeenMutation,
+ useUserNotificationsQuery,
+} from '@queries/notification/user-notifications';
import type { ConnectionGatewayWebsocket } from '@service-connection/websocket';
import { notificationServiceClient } from '@service-notification/client';
import type { UserUnsubscribe } from '@service-notification/generated/schemas';
@@ -16,13 +20,7 @@ import {
createMemo,
createSignal,
} from 'solid-js';
-import {
- createStore,
- produce,
- reconcile,
- type Store,
- unwrap,
-} from 'solid-js/store';
+import { createStore, reconcile, type Store, unwrap } from 'solid-js/store';
import { fetchNotificationsForEntities } from './queries/entities-notifications-query';
import { createMutedEntitiesQuery } from './queries/muted-entities-query';
import {
@@ -51,6 +49,7 @@ export type NotificationSource = {
UnifiedNotification[],
Error
>;
+
readonly _mutedEntitiesQuery: UseQueryResult<UserUnsubscribe[], Error>;
/** Mark a single notification as done */
@@ -92,9 +91,13 @@ export function createNotificationSource(
const [mutedEntities, setMutedEntities] = createSignal<UserUnsubscribe[]>([]);
- const notificationsQuery = createNotificationQuery({ limit: QUERY_LIMIT });
+ const notificationsQuery = useUserNotificationsQuery({ limit: QUERY_LIMIT });
const mutedEntitiesQuery = createMutedEntitiesQuery({ limit: QUERY_LIMIT });
+ const markNotificationsAsSeenMutation = useMarkNotificationsAsSeenMutation();
+
+ const markNotificationsAsDoneMutation = useMarkNotificationsAsDoneMutation();
+
/** Reconcile new notifications into the store */
const reconcileNotifications = (
notifications: UnifiedNotification[],
@@ -183,34 +186,15 @@ export function createNotificationSource(
});
const bulkMarkAsDone = async (notifications: UnifiedNotification[]) => {
- // optimistically update
- setStore(
- produce((state) => {
- notifications.forEach((notification) => {
- const notDoneNotification = state[
- compositeEntity(notificationEntity(notification))
- ]?.find(({ id }) => id === notification.id);
-
- if (notDoneNotification) notDoneNotification.done = true;
- });
- })
- );
-
- const notificationIds = notifications.map(({ id }) => id);
-
- await notificationServiceClient.bulkMarkNotificationAsDone({
- notificationIds,
+ await markNotificationsAsDoneMutation.mutateAsync({
+ notificationIds: notifications.map((n) => n.id),
});
- refetchAndReconcileNotifications(notifications);
};
const bulkMarkAsRead = async (notifications: UnifiedNotification[]) => {
- const notificationIds = notifications.map(({ id }) => id);
- await notificationServiceClient.bulkMarkNotificationAsSeen({
- notificationIds,
+ await markNotificationsAsSeenMutation.mutateAsync({
+ notificationIds: notifications.map((n) => n.id),
});
-
- refetchAndReconcileNotifications(notifications);
};
const markAsDone = async (notification: UnifiedNotification) => {
diff --git a/js/app/packages/notifications/vitest.config.ts b/js/app/packages/notifications/vitest.config.ts
new file mode 100644
index 0000000000..5341010ede
--- /dev/null
+++ b/js/app/packages/notifications/vitest.config.ts
@@ -0,0 +1,16 @@
+import solidPlugin from 'vite-plugin-solid';
+import tsconfigPaths from 'vite-tsconfig-paths';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ plugins: [
+ tsconfigPaths({
+ root: '../../',
+ }),
+ solidPlugin(),
+ ],
+ test: {
+ environment: 'jsdom',
+ globals: true,
+ },
+} as any);
diff --git a/js/app/packages/queries/notification/keys.ts b/js/app/packages/queries/notification/keys.ts
new file mode 100644
index 0000000000..e32e0e5c5e
--- /dev/null
+++ b/js/app/packages/queries/notification/keys.ts
@@ -0,0 +1,19 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const notificationKeys = createQueryKeys('notification', {
+ all: null,
+ user: (params: { limit?: number }) => ({
+ queryKey: ['user', { infinite: true, ...params }],
+ }),
+ entity: (params: { eventItemId: string; limit?: number }) => ({
+ queryKey: [
+ 'entity',
+ params.eventItemId,
+ { infinite: true, limit: params.limit },
+ ],
+ }),
+ entities: (params: { eventItemIds: string[]; limit?: number }) => ({
+ queryKey: ['entities', { infinite: true, ...params }],
+ }),
+ unsubscribes: null,
+});
diff --git a/js/app/packages/queries/notification/tests/user-notifications.test.tsx b/js/app/packages/queries/notification/tests/user-notifications.test.tsx
new file mode 100644
index 0000000000..e3ab01b6b3
--- /dev/null
+++ b/js/app/packages/queries/notification/tests/user-notifications.test.tsx
@@ -0,0 +1,321 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { err, ok } from '@core/util/maybeResult';
+import type { GetAllUserNotificationsResponse } from '@service-notification/generated/schemas/getAllUserNotificationsResponse';
+import type { UserNotification } from '@service-notification/generated/schemas/userNotification';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import type { JSX } from 'solid-js';
+import { render } from 'solid-js/web';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { notificationKeys } from '../keys';
+import {
+ useMarkNotificationsAsDoneMutation,
+ useMarkNotificationsAsSeenMutation,
+} from '../user-notifications';
+
+vi.mock('@service-notification/client', () => ({
+ notificationServiceClient: {
+ userNotifications: vi.fn(),
+ bulkGetUserNotificationsByEventItemId: vi.fn(),
+ bulkMarkNotificationAsSeen: vi.fn(),
+ bulkMarkNotificationAsDone: vi.fn(),
+ },
+ channelMentionMetadata: {},
+ documentMentionMetadata: {},
+}));
+
+import { notificationServiceClient } from '@service-notification/client';
+
+const mockBulkMarkNotificationAsSeen = vi.mocked(
+ notificationServiceClient.bulkMarkNotificationAsSeen
+);
+const mockBulkMarkNotificationAsDone = vi.mocked(
+ notificationServiceClient.bulkMarkNotificationAsDone
+);
+
+let testQueryClient: QueryClient;
+
+vi.mock('../../client', () => ({
+ get queryClient() {
+ return testQueryClient;
+ },
+}));
+
+type UserNotificationsPageParam = { limit: number; cursor?: string };
+
+function createMockNotification(
+ overrides: Partial<UserNotification> = {}
+): UserNotification {
+ return {
+ id: `notification-${Math.random().toString(36).slice(2)}`,
+ entity_id: 'entity-1',
+ entity_type: 'document',
+ createdAt: Date.now(),
+ updatedAt: null,
+ viewedAt: null,
+ deletedAt: null,
+ done: false,
+ sent: true,
+ notificationEventType: 'ItemShared',
+ notificationMetadata: {
+ sharer_id: 'user-1',
+ permission_level: 'editor',
+ },
+ ...overrides,
+ } as UserNotification;
+}
+
+function createMockNotificationPage(
+ notifications: UserNotification[],
+ nextCursor?: string
+): GetAllUserNotificationsResponse {
+ return {
+ items: notifications,
+ next_cursor: nextCursor,
+ };
+}
+
+function seedQueryCache(pages: GetAllUserNotificationsResponse[], limit = 20) {
+ const queryKey = notificationKeys.user({ limit }).queryKey;
+ testQueryClient.setQueryData(queryKey, {
+ pages,
+ pageParams: pages.map((_, i) => ({
+ limit,
+ cursor: i > 0 ? `cursor-${i}` : undefined,
+ })),
+ });
+ return queryKey;
+}
+
+function getNotificationsFromCache(limit = 20) {
+ const queryKey = notificationKeys.user({ limit }).queryKey;
+ const data = testQueryClient.getQueryData<{
+ pages: GetAllUserNotificationsResponse[];
+ pageParams: UserNotificationsPageParam[];
+ }>(queryKey);
+ return data?.pages.flatMap((p) => p.items) ?? [];
+}
+
+function createWrapper() {
+ return function Wrapper(props: { children: JSX.Element }) {
+ return (
+ <QueryClientProvider client={testQueryClient}>
+ {props.children}
+ </QueryClientProvider>
+ );
+ };
+}
+
+function renderWithClient(Component: () => JSX.Element): () => void {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const Wrapper = createWrapper();
+ const dispose = render(
+ () => (
+ <Wrapper>
+ <Component />
+ </Wrapper>
+ ),
+ container
+ );
+ return () => {
+ dispose();
+ container.remove();
+ };
+}
+
+describe('notification mutations', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ });
+
+ afterEach(() => {
+ testQueryClient.clear();
+ });
+
+ describe('useMarkNotificationsAsSeenMutation', () => {
+ it('should optimistically update viewedAt when marking as seen', async () => {
+ const n1 = createMockNotification({ id: 'n1', viewedAt: null });
+ const n2 = createMockNotification({ id: 'n2', viewedAt: null });
+ seedQueryCache([createMockNotificationPage([n1, n2])]);
+
+ mockBulkMarkNotificationAsSeen.mockResolvedValue(ok({ success: true }));
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMarkNotificationsAsSeenMutation();
+ mutatePromise = mutation.mutateAsync({ notificationIds: ['n1'] });
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+
+ await mutatePromise;
+
+ const notifications = getNotificationsFromCache();
+ expect(notifications[0].viewedAt).not.toBeNull();
+ expect(notifications[1].viewedAt).toBeNull();
+
+ cleanup();
+ });
+
+ it('should rollback optimistic update on error', async () => {
+ const n1 = createMockNotification({ id: 'n1', viewedAt: null });
+ seedQueryCache([createMockNotificationPage([n1])]);
+
+ mockBulkMarkNotificationAsSeen.mockResolvedValue(
+ err('SERVER_ERROR', 'Failed to mark as seen')
+ );
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMarkNotificationsAsSeenMutation();
+ mutatePromise = mutation
+ .mutateAsync({ notificationIds: ['n1'] })
+ .catch(() => {});
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+
+ await mutatePromise;
+ // Wait for rollback to complete
+ await new Promise((r) => setTimeout(r, 10));
+
+ const notifications = getNotificationsFromCache();
+ expect(notifications[0].viewedAt).toBeNull();
+
+ cleanup();
+ });
+
+ it('should handle marking notifications across multiple pages', async () => {
+ const n1 = createMockNotification({ id: 'n1', viewedAt: null });
+ const n2 = createMockNotification({ id: 'n2', viewedAt: null });
+ seedQueryCache([
+ createMockNotificationPage([n1]),
+ createMockNotificationPage([n2]),
+ ]);
+
+ mockBulkMarkNotificationAsSeen.mockResolvedValue(ok({ success: true }));
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMarkNotificationsAsSeenMutation();
+ mutatePromise = mutation.mutateAsync({ notificationIds: ['n2'] });
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+
+ await mutatePromise;
+
+ const notifications = getNotificationsFromCache();
+ expect(notifications[0].viewedAt).toBeNull(); // n1 unchanged
+ expect(notifications[1].viewedAt).not.toBeNull(); // n2 updated
+
+ cleanup();
+ });
+ });
+
+ describe('useMarkNotificationsAsDoneMutation', () => {
+ it('should optimistically remove notifications when marking as done', async () => {
+ const n1 = createMockNotification({ id: 'n1' });
+ const n2 = createMockNotification({ id: 'n2' });
+ const n3 = createMockNotification({ id: 'n3' });
+ seedQueryCache([createMockNotificationPage([n1, n2, n3])]);
+
+ mockBulkMarkNotificationAsDone.mockResolvedValue(ok({ success: true }));
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMarkNotificationsAsDoneMutation();
+ mutatePromise = mutation.mutateAsync({ notificationIds: ['n1', 'n3'] });
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+
+ await mutatePromise;
+
+ const notifications = getNotificationsFromCache();
+ expect(notifications).toHaveLength(1);
+ expect(notifications[0].id).toBe('n2');
+
+ cleanup();
+ });
+
+ it('should rollback optimistic removal on error', async () => {
+ const n1 = createMockNotification({ id: 'n1' });
+ const n2 = createMockNotification({ id: 'n2' });
+ seedQueryCache([createMockNotificationPage([n1, n2])]);
+
+ mockBulkMarkNotificationAsDone.mockResolvedValue(
+ err('NETWORK_ERROR', 'Connection failed')
+ );
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMarkNotificationsAsDoneMutation();
+ mutatePromise = mutation
+ .mutateAsync({ notificationIds: ['n1'] })
+ .catch(() => {});
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+
+ await mutatePromise;
+ // Wait for rollback to complete
+ await new Promise((r) => setTimeout(r, 10));
+
+ const notifications = getNotificationsFromCache();
+ expect(notifications).toHaveLength(2);
+ expect(notifications.find((n) => n.id === 'n1')).toBeDefined();
+
+ cleanup();
+ });
+
+ it('should handle removing notifications across multiple pages', async () => {
+ const n1 = createMockNotification({ id: 'n1' });
+ const n2 = createMockNotification({ id: 'n2' });
+ const n3 = createMockNotification({ id: 'n3' });
+ seedQueryCache([
+ createMockNotificationPage([n1, n2]),
+ createMockNotificationPage([n3]),
+ ]);
+
+ mockBulkMarkNotificationAsDone.mockResolvedValue(ok({ success: true }));
+
+ let mutatePromise: Promise<unknown> | undefined;
+
+ const TestComponent = () => {
+ const mutation = useMarkNotificationsAsDoneMutation();
+ mutatePromise = mutation.mutateAsync({ notificationIds: ['n2', 'n3'] });
+ return null;
+ };
+
+ const cleanup = renderWithClient(TestComponent);
+
+ await mutatePromise;
+
+ const notifications = getNotificationsFromCache();
+ expect(notifications).toHaveLength(1);
+ expect(notifications[0].id).toBe('n1');
+
+ cleanup();
+ });
+ });
+});
diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.ts
new file mode 100644
index 0000000000..1d210dfce8
--- /dev/null
+++ b/js/app/packages/queries/notification/user-notifications.ts
@@ -0,0 +1,361 @@
+import type { Maybe } from '@core/types';
+import { type MaybeResult, throwOnErr } from '@core/util/maybeResult';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import { notificationServiceClient } from '@service-notification/client';
+import type { GetAllUserNotificationsResponse } from '@service-notification/generated/schemas/getAllUserNotificationsResponse';
+import {
+ type InfiniteData,
+ type MutationFunction,
+ useInfiniteQuery,
+ useMutation,
+} from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { notificationKeys } from './keys';
+
+export { notificationKeys } from './keys';
+
+const DEFAULT_NOTIFICATION_LIMIT = 20;
+const NOTIFICATION_STALE_TIME = 5 * 60 * 1000; // 5 minutes
+const NOTIFICATION_GC_TIME = 10 * 60 * 1000; // 10 minutes
+
+function normalizeLimit(limit?: number): number {
+ return limit && limit > 0 && limit <= 500
+ ? limit
+ : DEFAULT_NOTIFICATION_LIMIT;
+}
+
+type UserNotificationsPageParam = { limit: number; cursor?: string };
+
+function userNotificationsQueryOptions(limit: number) {
+ return {
+ queryKey: notificationKeys.user({ limit }).queryKey,
+ queryFn: async ({
+ pageParam,
+ }: {
+ pageParam: UserNotificationsPageParam;
+ }) => {
+ return await throwOnErr(
+ async () =>
+ await notificationServiceClient.userNotifications({
+ limit: pageParam.limit,
+ cursor: pageParam.cursor,
+ })
+ );
+ },
+ initialPageParam: { limit } as UserNotificationsPageParam,
+ getNextPageParam: (lastPage: GetAllUserNotificationsResponse) =>
+ lastPage.next_cursor ? { cursor: lastPage.next_cursor, limit } : null,
+ staleTime: NOTIFICATION_STALE_TIME,
+ gcTime: NOTIFICATION_GC_TIME,
+ };
+}
+
+/** Paginated query for all notifications for the current user. */
+export function useUserNotificationsQuery(args?: { limit?: number }) {
+ const limit = normalizeLimit(args?.limit);
+
+ return useInfiniteQuery(() => ({
+ ...userNotificationsQueryOptions(limit),
+ select: (
+ data: InfiniteData<
+ GetAllUserNotificationsResponse,
+ UserNotificationsPageParam
+ >
+ ) => data.pages.flatMap(({ items }) => items),
+ }));
+}
+
+type EntityNotificationsPageParam = {
+ eventItemId: string;
+ limit: number;
+ cursor?: string;
+};
+
+function entityNotificationsQueryOptions(eventItemId: string, limit: number) {
+ return {
+ queryKey: notificationKeys.entity({ eventItemId, limit }).queryKey,
+ queryFn: async ({
+ pageParam,
+ }: {
+ pageParam: EntityNotificationsPageParam;
+ }) => {
+ return await throwOnErr(
+ async () =>
+ await notificationServiceClient.bulkGetUserNotificationsByEventItemId(
+ {
+ eventItemIds: [pageParam.eventItemId],
+ limit: pageParam.limit,
+ cursor: pageParam.cursor,
+ }
+ )
+ );
+ },
+ initialPageParam: { eventItemId, limit } as EntityNotificationsPageParam,
+ getNextPageParam: (lastPage: GetAllUserNotificationsResponse) =>
+ lastPage.next_cursor
+ ? { cursor: lastPage.next_cursor, eventItemId, limit }
+ : null,
+ gcTime: NOTIFICATION_GC_TIME,
+ };
+}
+
+/** Paginated query for notifications for a single entity. */
+export function useEntityNotificationsQuery(args: {
+ eventItemId: () => string;
+ limit?: number;
+}) {
+ const limit = normalizeLimit(args.limit);
+
+ return useInfiniteQuery(() => ({
+ ...entityNotificationsQueryOptions(args.eventItemId(), limit),
+ select: (
+ data: InfiniteData<
+ GetAllUserNotificationsResponse,
+ EntityNotificationsPageParam
+ >
+ ) => data.pages.flatMap(({ items }) => items),
+ }));
+}
+
+type EntitiesNotificationsPageParam = {
+ eventItemIds: string[];
+ limit: number;
+ cursor?: string;
+};
+
+function entitiesNotificationsQueryOptions(
+ eventItemIds: string[],
+ limit: number
+) {
+ return {
+ queryKey: notificationKeys.entities({ eventItemIds, limit }).queryKey,
+ queryFn: async ({
+ pageParam,
+ }: {
+ pageParam: EntitiesNotificationsPageParam;
+ }) => {
+ return await throwOnErr(
+ async () =>
+ await notificationServiceClient.bulkGetUserNotificationsByEventItemId(
+ {
+ eventItemIds: pageParam.eventItemIds,
+ limit: pageParam.limit,
+ cursor: pageParam.cursor,
+ }
+ )
+ );
+ },
+ initialPageParam: { limit, eventItemIds } as EntitiesNotificationsPageParam,
+ getNextPageParam: (lastPage: GetAllUserNotificationsResponse) =>
+ lastPage.next_cursor
+ ? { cursor: lastPage.next_cursor, limit, eventItemIds }
+ : null,
+ };
+}
+
+/** Paginated query for notifications across multiple entities. */
+export function useEntitiesNotificationsQuery(args: {
+ eventItemIds: () => string[];
+ limit?: number;
+}) {
+ const limit = normalizeLimit(args.limit);
+
+ return useInfiniteQuery(() => ({
+ ...entitiesNotificationsQueryOptions(args.eventItemIds(), limit),
+ select: (
+ data: InfiniteData<
+ GetAllUserNotificationsResponse,
+ EntitiesNotificationsPageParam
+ >
+ ) => data.pages.flatMap(({ items }) => items),
+ enabled: args.eventItemIds().length > 0,
+ }));
+}
+
+export function invalidateUserNotifications() {
+ return queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ });
+}
+
+export function invalidateEntityNotifications(eventItemId: string) {
+ return queryClient.invalidateQueries({
+ queryKey: [...notificationKeys.entity._def, eventItemId],
+ });
+}
+
+export function invalidateAllNotifications() {
+ return queryClient.invalidateQueries({
+ queryKey: notificationKeys._def,
+ });
+}
+
+type NotificationsMutationParams = {
+ notificationIds: string[];
+};
+
+type NotificationData<T> = InfiniteData<GetAllUserNotificationsResponse, T>;
+
+type NotificationsMutationContext = {
+ /**
+ * Snapshot of all cached `notificationKeys.user(...)` queries so we can rollback
+ * optimistic updates regardless of what limit a caller used.
+ */
+ previousData: Array<
+ readonly [unknown, NotificationData<UserNotificationsPageParam> | undefined]
+ >;
+};
+
+type UpdaterWithParams<T, P> = (input: Maybe<T>, params: P) => Maybe<T>;
+
+type NotificationsUpdater = UpdaterWithParams<
+ NotificationData<UserNotificationsPageParam>,
+ NotificationsMutationParams
+>;
+
+type NotificationsMutationCallbacks<T> = MutationCallbacks<
+ T,
+ Error,
+ NotificationsMutationParams,
+ NotificationsMutationContext
+>;
+
+type NotificationsMutationFn<T> = MutationFunction<
+ MaybeResult<string, T>,
+ NotificationsMutationParams
+>;
+
+type NotificationsOnMutateFn = (
+ variables: NotificationsMutationParams
+) => Promise<NotificationsMutationContext>;
+
+function notificationsMutationSuccessCallback<T>(
+ _: T,
+ _params: NotificationsMutationParams
+) {
+ queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ });
+}
+
+/** Creates an optimistic update handler that snapshots previous data for rollback. */
+function createNotificationsMutateFn(
+ updaterFn: NotificationsUpdater
+): NotificationsOnMutateFn {
+ return async (params) => {
+ await queryClient.cancelQueries({
+ queryKey: notificationKeys.user._def,
+ });
+
+ const previousData = queryClient.getQueriesData<
+ NotificationData<UserNotificationsPageParam>
+ >({
+ queryKey: notificationKeys.user._def,
+ });
+
+ queryClient.setQueriesData(
+ { queryKey: notificationKeys.user._def },
+ (input) =>
+ updaterFn(
+ input as Maybe<NotificationData<UserNotificationsPageParam>>,
+ params
+ )
+ );
+
+ return { previousData };
+ };
+}
+
+function createNotificationsMutation<T>(
+ mutationFn: NotificationsMutationFn<T>,
+ parentCallbacks?: NotificationsMutationCallbacks<T>
+) {
+ return (callbacks?: NotificationsMutationCallbacks<T>) => {
+ return useMutation(() => ({
+ mutationFn: async (params, ctx) =>
+ await throwOnErr(async () => await mutationFn(params, ctx)),
+ ...withCallbacks<
+ T,
+ Error,
+ NotificationsMutationParams,
+ NotificationsMutationContext
+ >(
+ {
+ onSuccess: notificationsMutationSuccessCallback,
+ },
+ { ...parentCallbacks, ...callbacks }
+ ),
+ }));
+ };
+}
+
+function notificationsMutationErrorFn(
+ _: Error,
+ _params: NotificationsMutationParams,
+ context: NotificationsMutationContext
+) {
+ for (const [queryKey, data] of context.previousData) {
+ queryClient.setQueryData(
+ queryKey as readonly unknown[],
+ data as NotificationData<UserNotificationsPageParam> | undefined
+ );
+ }
+}
+
+const mapNotificationsAsSeen = (
+ input: Maybe<NotificationData<UserNotificationsPageParam>>,
+ params: NotificationsMutationParams
+) => {
+ return (
+ input && {
+ ...input,
+ pages: input.pages.map((page) => ({
+ ...page,
+ items: page.items.map((n) =>
+ params.notificationIds.includes(n.id)
+ ? { ...n, viewedAt: Date.now() }
+ : n
+ ),
+ })),
+ }
+ );
+};
+
+/** Marks notifications as seen with optimistic update. */
+export const useMarkNotificationsAsSeenMutation = createNotificationsMutation(
+ async (params: NotificationsMutationParams) =>
+ await notificationServiceClient.bulkMarkNotificationAsSeen({
+ notificationIds: params.notificationIds,
+ }),
+ {
+ onMutate: createNotificationsMutateFn(mapNotificationsAsSeen),
+ onError: notificationsMutationErrorFn,
+ }
+);
+
+const filterOutDoneNotifications = (
+ input: Maybe<NotificationData<UserNotificationsPageParam>>,
+ params: NotificationsMutationParams
+) => {
+ return (
+ input && {
+ ...input,
+ pages: input.pages.map((page) => ({
+ ...page,
+ items: page.items.filter((n) => !params.notificationIds.includes(n.id)),
+ })),
+ }
+ );
+};
+
+/** Marks notifications as done (removes from list) with optimistic update. */
+export const useMarkNotificationsAsDoneMutation = createNotificationsMutation(
+ async (params: NotificationsMutationParams) =>
+ await notificationServiceClient.bulkMarkNotificationAsDone({
+ notificationIds: params.notificationIds,
+ }),
+ {
+ onMutate: createNotificationsMutateFn(filterOutDoneNotifications),
+ onError: notificationsMutationErrorFn,
+ }
+);
diff --git a/js/app/packages/queries/vitest.config.ts b/js/app/packages/queries/vitest.config.ts
new file mode 100644
index 0000000000..bab86f5b34
--- /dev/null
+++ b/js/app/packages/queries/vitest.config.ts
@@ -0,0 +1,23 @@
+import solidPlugin from 'vite-plugin-solid';
+import tsconfigPaths from 'vite-tsconfig-paths';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ plugins: [
+ tsconfigPaths({
+ root: '../../',
+ }),
+ solidPlugin(),
+ ],
+ test: {
+ environment: 'jsdom',
+ globals: true,
+ deps: {
+ optimizer: {
+ web: {
+ include: ['solid-js', '@tanstack/solid-query', 'zod'],
+ },
+ },
+ },
+ },
+} as any);
diff --git a/js/app/vitest.config.ts b/js/app/vitest.config.ts
index 68c62c19fc..7974096772 100644
--- a/js/app/vitest.config.ts
+++ b/js/app/vitest.config.ts
@@ -23,6 +23,14 @@ export default defineConfig({
name: 'core',
},
},
+ {
+ // Queries package tests
+ extends: './packages/queries/vitest.config.ts',
+ test: {
+ include: ['packages/queries/**/*.{test,spec}.{ts,tsx}'],
+ name: 'queries',
+ },
+ },
],
},
});