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(home): show new notification rows live in notified_at lists (#9626)

teodc38bfc45b67
diff --git a/apps/web/src/lib/queries/notification/notification-soup.ts b/apps/web/src/lib/queries/notification/notification-soup.ts
index d2bd235d91..a69e3089c5 100644
--- a/apps/web/src/lib/queries/notification/notification-soup.ts
+++ b/apps/web/src/lib/queries/notification/notification-soup.ts
@@ -62,7 +62,7 @@ export function updateSoupForNotification(notification: UnifiedNotification) {
}
} else {
fireAndForget(
- refetchSoupEntity(notification.entity_id, soupTag),
+ refetchSoupEntity(notification.entity_id, soupTag, { notified: true }),
'notification-soup'
);
}
@@ -78,7 +78,7 @@ export function updateSoupForNotification(notification: UnifiedNotification) {
}
if (threadRootId && !hasSoupEntity(threadRootId)) {
fireAndForget(
- refetchSoupEntity(threadRootId, 'channelThread'),
+ refetchSoupEntity(threadRootId, 'channelThread', { notified: true }),
'notification-soup'
);
}
diff --git a/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx b/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx
index 7cd0e42858..eacdf025f5 100644
--- a/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx
+++ b/apps/web/src/lib/queries/notification/tests/user-notifications.test.tsx
@@ -1067,7 +1067,8 @@ describe('optimisticInsertNotification', () => {
);
expect(mockRefetchSoupEntity).toHaveBeenCalledWith(
'thread-1',
- 'channelThread'
+ 'channelThread',
+ { notified: true }
);
expect(mockRefetchSoupEntity).not.toHaveBeenCalledWith(
'channel-1',
@@ -1112,7 +1113,8 @@ describe('optimisticInsertNotification', () => {
).toHaveBeenCalledExactlyOnceWith(rootId, reaction.created_at);
expect(mockRefetchSoupEntity).toHaveBeenCalledExactlyOnceWith(
rootId,
- 'channelThread'
+ 'channelThread',
+ { notified: true }
);
expect(
vi.mocked(restoreSoupEntityToDoneFilteredQueries)
@@ -1154,7 +1156,8 @@ describe('optimisticInsertNotification', () => {
expect(mockRefetchSoupEntity).toHaveBeenCalledWith(
'thread-1',
- 'emailThread'
+ 'emailThread',
+ { notified: true }
);
expect(mockOptimisticUpdateSoupItemUpdatedAt).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
index c0c1848fcc..e2bf9d8b38 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
@@ -3,11 +3,12 @@
*/
import { withDocumentTabItemScope } from '@app/features/next-soup/soup-view/document-tab-scope';
+import type { UnifiedNotification } from '@notifications/types';
import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
import type { SoupApiItem } from '@service-storage/generated/schemas';
import type { SoupPage } from '@service-storage/generated/schemas/soupPage';
import type { InfiniteData } from '@tanstack/solid-query';
-import { QueryClient } from '@tanstack/solid-query';
+import { QueryClient, QueryObserver } from '@tanstack/solid-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
let testQueryClient: QueryClient;
@@ -381,6 +382,180 @@ describe('refetchSoupEntity', () => {
'd-1',
]);
});
+
+ describe('for a new notification', () => {
+ const notifiedKey = [
+ ...soupKeys.astItems._def,
+ { params: { sort_method: 'notified_at' } },
+ ];
+ const notifiedPages = () =>
+ testQueryClient.getQueryData<
+ InfiniteData<SoupAstItemsFlatPage, unknown>
+ >(notifiedKey);
+ const notification = {
+ id: 'notification-1',
+ entity_id: 'doc-new',
+ entity_type: 'document',
+ created_at: '2026-01-02T00:00:00.000Z',
+ state: 'unseen',
+ notification_metadata: { tag: 'commented_on_document', content: {} },
+ } as unknown as UnifiedNotification;
+
+ beforeEach(() => {
+ testQueryClient.setQueryData(notifiedKey, {
+ pages: [
+ {
+ kind: 'flat',
+ items: [mockDocumentItem('d-1')],
+ nextCursor: null,
+ },
+ ],
+ pageParams: [null],
+ });
+ });
+
+ const mountNotifiedList = () =>
+ new QueryObserver(testQueryClient, {
+ queryKey: notifiedKey,
+ queryFn: () => notifiedPages() ?? null,
+ staleTime: Number.POSITIVE_INFINITY,
+ }).subscribe(() => {});
+
+ it('adds a row a mounted notified_at list does not have yet', async () => {
+ const unmount = mountNotifiedList();
+
+ updateSoupForNotification(notification);
+
+ await vi.waitFor(() => {
+ expect(notifiedPages()?.pages[0].items.map(getSoupItemId)).toEqual([
+ 'doc-new',
+ 'd-1',
+ ]);
+ });
+ unmount();
+ });
+
+ it('reads a list again when its first read predates the notification', async () => {
+ const pagesOf = (...ids: string[]) => ({
+ pages: [
+ {
+ kind: 'flat',
+ items: ids.map((id) => mockDocumentItem(id)),
+ nextCursor: null,
+ },
+ ],
+ pageParams: [null],
+ });
+ let settleFirstRead = (_data: unknown) => {};
+ const queryFn = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ settleFirstRead = resolve;
+ })
+ )
+ .mockResolvedValue(pagesOf('doc-new', 'd-1'));
+ testQueryClient.removeQueries({ queryKey: notifiedKey });
+ const unmount = new QueryObserver(testQueryClient, {
+ queryKey: notifiedKey,
+ queryFn,
+ staleTime: Number.POSITIVE_INFINITY,
+ }).subscribe(() => {});
+
+ updateSoupForNotification(notification);
+ await vi.waitFor(() => {
+ expect(getSoupItemsMock).toHaveBeenCalledOnce();
+ });
+ await getSoupItemsMock.mock.results[0]?.value;
+ await new Promise((resolve) => setTimeout(resolve));
+ settleFirstRead(pagesOf('d-1'));
+
+ await vi.waitFor(() => {
+ expect(notifiedPages()?.pages[0].items.map(getSoupItemId)).toEqual([
+ 'doc-new',
+ 'd-1',
+ ]);
+ });
+ unmount();
+ });
+
+ it('reads each list again as soon as its own first read settles', async () => {
+ const never = () => new Promise(() => {});
+ const slowKey = [
+ ...soupKeys.astItems._def,
+ { params: { sort_method: 'notified_at' }, body: { slow: true } },
+ ];
+ let settleFirstRead = (_data: unknown) => {};
+ const queryFn = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ settleFirstRead = resolve;
+ })
+ )
+ .mockResolvedValue({
+ pages: [
+ {
+ kind: 'flat',
+ items: [mockDocumentItem('doc-new')],
+ nextCursor: null,
+ },
+ ],
+ pageParams: [null],
+ });
+ testQueryClient.removeQueries({ queryKey: notifiedKey });
+ const unmountFast = new QueryObserver(testQueryClient, {
+ queryKey: notifiedKey,
+ queryFn,
+ staleTime: Number.POSITIVE_INFINITY,
+ }).subscribe(() => {});
+ const unmountSlow = new QueryObserver(testQueryClient, {
+ queryKey: slowKey,
+ queryFn: never,
+ staleTime: Number.POSITIVE_INFINITY,
+ }).subscribe(() => {});
+
+ updateSoupForNotification(notification);
+ await vi.waitFor(() => {
+ expect(getSoupItemsMock).toHaveBeenCalledOnce();
+ });
+ await getSoupItemsMock.mock.results[0]?.value;
+ await new Promise((resolve) => setTimeout(resolve));
+ settleFirstRead({
+ pages: [
+ {
+ kind: 'flat',
+ items: [mockDocumentItem('d-1')],
+ nextCursor: null,
+ },
+ ],
+ pageParams: [null],
+ });
+
+ await vi.waitFor(() => {
+ expect(queryFn).toHaveBeenCalledTimes(2);
+ });
+ unmountFast();
+ unmountSlow();
+ });
+
+ it('fetches nothing when no notified_at list is mounted', async () => {
+ await refetchSoupEntity('doc-new', 'document', { notified: true });
+
+ expect(getSoupItemsMock).not.toHaveBeenCalled();
+ });
+
+ it('fetches nothing for a change that is not a notification', async () => {
+ const unmount = mountNotifiedList();
+
+ await refetchSoupEntity('doc-new', 'document');
+
+ expect(getSoupItemsMock).not.toHaveBeenCalled();
+ unmount();
+ });
+ });
});
});
@@ -795,6 +970,7 @@ import {
soupItemMatchesProjectMembership,
soupItemMatchesQuery,
} from '@app/features/next-soup/filters/query-filters';
+import { updateSoupForNotification } from '../../notification/notification-soup';
import type { GroupByField, GroupMeta } from '../grouped/types';
import { NOT_SET_GROUP_KEY } from '../grouped/types';
import type { SoupAstItemsFlatPage, SoupAstItemsGroupedPage } from '../items';
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
index 3af3c80a18..53a51e9059 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -745,6 +745,9 @@ export function removeSearchEntities(
* `created` marks an entity that did not exist a moment ago, so it sorts first
* in newest-first lists. It is inserted into the REST lists whose filters admit
* it, without refetching any list, in either transport.
+ *
+ * `notified` marks a new notification about the entity, which a mounted
+ * `notified_at` list must show even if the entity isn't cached yet.
*/
export async function refetchSoupEntity(
entityId: string,
@@ -754,6 +757,7 @@ export async function refetchSoupEntity(
ownTouch?: boolean;
refreshGraphql?: boolean;
created?: boolean;
+ notified?: boolean;
}
): Promise<void> {
if (options?.refreshGraphql) {
@@ -762,10 +766,11 @@ export async function refetchSoupEntity(
// GraphQL lists never read this cache, so a miss means no REST list shows
// the entity. Own-touch inserts still land because Home's touched_by_me
- // feed stays on REST.
+ // feed stays on REST, and notified ones because notified_at lists do.
if (
!options?.ownTouch &&
!options?.created &&
+ !(options?.notified && mountedNotifiedLists().length > 0) &&
isFeatureEnabled(enableGraphqlSoup) &&
!hasSoupEntity(entityId)
) {
@@ -807,10 +812,42 @@ export async function refetchSoupEntity(
} else {
invalidateAllSoup();
}
+ if (options?.notified) {
+ fireAndForget(
+ rereadNotifiedListsAfterFirstRead(),
+ 'soup-normalized-cache'
+ );
+ }
}
}
}
+/** Lists on screen ordered by `notified_at`, which only REST serves. */
+function mountedNotifiedLists() {
+ return queryClient
+ .getQueryCache()
+ .findAll({ queryKey: soupKeys.astItems._def, type: 'active' })
+ .filter((query) => JSON.stringify(query.queryKey).includes('notified_at'));
+}
+
+/**
+ * A list's first read has no pages to insert into, and invalidating reuses it
+ * rather than restarting it, so its response can predate a new notification.
+ * Read each of those lists again once its own first read settles.
+ */
+async function rereadNotifiedListsAfterFirstRead(): Promise<void> {
+ const firstReads = mountedNotifiedLists().filter(
+ (query) =>
+ query.state.data === undefined && query.state.fetchStatus === 'fetching'
+ );
+ await Promise.allSettled(
+ firstReads.map(async (query) => {
+ await Promise.allSettled([query.promise]);
+ queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true });
+ })
+ );
+}
+
/**
* `invalidateAllSoup` minus the touched_by_me queries: an own-touch insert
* must survive in the Recent feed until the activity consumer has recorded