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
fix(external-chat): keep an older page when the timeline refreshes (#9764)
teoec3033e874c3
diff --git a/apps/web/src/features/external-chat/AGENTS.md b/apps/web/src/features/external-chat/AGENTS.mdindex e8fe6f4a28..5ffbcb4d47 100644--- a/apps/web/src/features/external-chat/AGENTS.md+++ b/apps/web/src/features/external-chat/AGENTS.md@@ -44,6 +44,9 @@ belong to `features/external-view`. Architecture:## Gotchas+- Refetch a timeline through `invalidateExternalChatMessages`. A plain refetch+ cancels an older page that is loading, and the page is lost. It waits at most+ 10 s, so a hung older page can't block refreshes; past that it cancels the page.- `kind` is `group` or `direct`. A direct chat has no members list (headershows the person) and only its owner sends; shared viewers see "Only<owner> can reply in this chat" (`sendReason: 'not_added'`).diff --git a/apps/web/src/features/external-chat/queries/capabilities.ts b/apps/web/src/features/external-chat/queries/capabilities.tsindex 8e3a822258..481211b135 100644--- a/apps/web/src/features/external-chat/queries/capabilities.ts+++ b/apps/web/src/features/external-chat/queries/capabilities.ts@@ -5,6 +5,7 @@ import {type ExternalChatApi,invalidateExternalChat,invalidateExternalChatList,+ invalidateExternalChatMessages,refreshExternalChatTimeline,useExternalChatDeliveryQuery,useExternalChatQueries,@@ -126,7 +127,10 @@ export function createExternalChatCapabilities(return queries.messages.isError;},refetch: () =>- fireAndForget(queries.messages.refetch(), 'external-chat.refresh'),+ fireAndForget(+ invalidateExternalChatMessages(userId(), chatId()),+ 'external-chat.refresh'+ ),},hasOlder: () => queries.messages.hasNextPage,loadingOlder: () => queries.messages.isFetchingNextPage,diff --git a/apps/web/src/lib/queries/external-chats/index.test.ts b/apps/web/src/lib/queries/external-chats/index.test.tsnew file mode 100644index 0000000000..499d6bf36f--- /dev/null+++ b/apps/web/src/lib/queries/external-chats/index.test.ts@@ -0,0 +1,112 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { InfiniteQueryObserver } from '@tanstack/solid-query';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { queryClient } from '../client';+import { invalidateExternalChatMessages } from './index';+import { externalChatsKeys } from './keys';++type Page = { rows: string[]; before?: string };++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++describe('invalidateExternalChatMessages', () => {+ afterEach(() => {+ vi.useRealTimers();+ queryClient.clear();+ });++ /** A send settling or a live push refetches while the viewer loads history. */+ it('keeps an older page that was loading when the refresh started', async () => {+ const older = deferred<Page>();+ const queryKey = externalChatsKeys.messages('user', 'chat').queryKey;+ const observer = new InfiniteQueryObserver(queryClient, {+ queryKey,+ queryFn: ({ pageParam }: { pageParam: string | undefined }) =>+ pageParam+ ? older.promise+ : Promise.resolve<Page>({ rows: ['newest'], before: 'cursor' }),+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (page: Page) => page.before,+ });+ const unsubscribe = observer.subscribe(() => {});+ await queryClient.getQueryCache().find({ queryKey })?.promise;++ const loading = observer.fetchNextPage();+ const refreshed = invalidateExternalChatMessages('user', 'chat');+ older.resolve({ rows: ['older'] });+ await Promise.all([loading, refreshed]);++ expect(+ observer.getCurrentResult().data?.pages.flatMap((page) => page.rows)+ ).toContain('older');+ unsubscribe();+ });++ /** The older page request has no timeout of its own, so it can hang. */+ it('refreshes once an older page has hung for too long', async () => {+ vi.useFakeTimers();+ const queryKey = externalChatsKeys.messages('user', 'chat').queryKey;+ let newestFetches = 0;+ const observer = new InfiniteQueryObserver(queryClient, {+ queryKey,+ queryFn: ({ pageParam }: { pageParam: string | undefined }) => {+ if (pageParam) return new Promise<Page>(() => {});+ newestFetches += 1;+ return Promise.resolve<Page>({ rows: ['newest'], before: 'cursor' });+ },+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (page: Page) => page.before,+ });+ const unsubscribe = observer.subscribe(() => {});+ await queryClient.getQueryCache().find({ queryKey })?.promise;+ expect(newestFetches).toBe(1);++ fireAndForget(observer.fetchNextPage(), 'external-chat-test');+ const refreshed = invalidateExternalChatMessages('user', 'chat');+ await vi.advanceTimersByTimeAsync(60_000);+ await refreshed;++ expect(newestFetches).toBe(2);+ unsubscribe();+ });++ /** A quote click loads history too, replacing the fetch a refresh waits on. */+ it('does not cancel an older page that replaced the one it waited for', async () => {+ const pages = [deferred<Page>(), deferred<Page>()];+ let olderFetches = 0;+ const queryKey = externalChatsKeys.messages('user', 'chat').queryKey;+ const observer = new InfiniteQueryObserver(queryClient, {+ queryKey,+ queryFn: ({ pageParam }: { pageParam: string | undefined }) => {+ if (!pageParam) {+ return Promise.resolve<Page>({ rows: ['newest'], before: 'cursor' });+ }+ olderFetches += 1;+ return pages[olderFetches - 1].promise;+ },+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (page: Page) => page.before,+ });+ const unsubscribe = observer.subscribe(() => {});+ await queryClient.getQueryCache().find({ queryKey })?.promise;++ const first = observer.fetchNextPage();+ const refreshed = invalidateExternalChatMessages('user', 'chat');+ const replacement = observer.fetchNextPage();+ // Let a waiter that doesn't look again reach its refetch.+ await new Promise((done) => setTimeout(done, 0));+ pages[1].resolve({ rows: ['older'] });+ await Promise.all([first, replacement, refreshed]);++ expect(+ observer.getCurrentResult().data?.pages.flatMap((page) => page.rows)+ ).toContain('older');+ unsubscribe();+ });+});diff --git a/apps/web/src/lib/queries/external-chats/index.ts b/apps/web/src/lib/queries/external-chats/index.tsindex abf94ac8e0..bac43fdc01 100644--- a/apps/web/src/lib/queries/external-chats/index.ts+++ b/apps/web/src/lib/queries/external-chats/index.ts@@ -8,6 +8,7 @@ import type {} from '@app/features/external-chat/core/chat';import {infiniteQueryOptions,+ type QueryKey,queryOptions,useInfiniteQuery,useQuery,@@ -145,12 +146,55 @@ export function invalidateExternalChat(chatId: string) {predicate: (query) => query.queryKey.at(-1) === chatId,});}+/**+ * How long a refresh waits for an older page. The request has no timeout of its+ * own, so a hung one would otherwise block every refresh of this chat.+ */+const OLDER_PAGE_WAIT_MS = 10_000;++/**+ * Waits while an older page loads. Looks again after each wait, because loading+ * history can replace the fetch that was being waited on (a quote click does).+ * The limit covers the whole wait, so replacements can't extend it.+ */+async function waitForOlderPage(queryKey: QueryKey) {+ const deadline = Date.now() + OLDER_PAGE_WAIT_MS;+ for (;;) {+ const query = queryClient.getQueryCache().find({ queryKey });+ const loadingOlder =+ query?.state.fetchStatus === 'fetching' &&+ query.state.fetchMeta?.fetchMore;+ const remaining = deadline - Date.now();+ if (!loadingOlder || remaining <= 0) return;++ let timer: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([+ Promise.allSettled([query.promise]),+ new Promise((done) => {+ timer = setTimeout(done, remaining);+ }),+ ]);+ clearTimeout(timer);+ }+}++/**+ * Refetches one chat's timeline. A refetch cancels whatever fetch is in flight,+ * and when that is the older page a viewer asked for, the page is lost and the+ * button just reappears, so wait for it first, up to a limit.+ */+export async function invalidateExternalChatMessages(+ userId: string,+ chatId: string+) {+ const queryKey = externalChatsKeys.messages(userId, chatId).queryKey;+ await waitForOlderPage(queryKey);+ return queryClient.invalidateQueries({ queryKey });+}/** A send was recorded: its row and the chat's place in lists follow. */export function refreshExternalChatTimeline(userId: string, chatId: string) {return Promise.all([- queryClient.invalidateQueries({- queryKey: externalChatsKeys.messages(userId, chatId).queryKey,- }),+ invalidateExternalChatMessages(userId, chatId),queryClient.invalidateQueries({queryKey: externalChatsKeys.delivery(userId, chatId).queryKey,}),diff --git a/apps/web/src/lib/queries/external-chats/sync.ts b/apps/web/src/lib/queries/external-chats/sync.tsindex dcbd67b7f8..f8318b1084 100644--- a/apps/web/src/lib/queries/external-chats/sync.ts+++ b/apps/web/src/lib/queries/external-chats/sync.ts@@ -9,6 +9,7 @@ import { z } from 'zod';import { queryClient } from '../client';import { parseMessageData } from '../storage/databases-sync';import { whatsappLinkedKeys } from '../whatsapp-linked/keys';+import { invalidateExternalChatMessages } from './index';import { externalChatsKeys } from './keys';/** DSS pings this with no data; readers re-fetch. */@@ -69,13 +70,13 @@ export function useExternalChatListsSync() {}function refreshChat(userId: string, chatId: string) {- return Promise.all(- [+ return Promise.all([+ invalidateExternalChatMessages(userId, chatId),+ ...[externalChatsKeys.detail(userId, chatId).queryKey,- externalChatsKeys.messages(userId, chatId).queryKey,externalChatsKeys.delivery(userId, chatId).queryKey,- ].map((queryKey) => queryClient.invalidateQueries({ queryKey }))- );+ ].map((queryKey) => queryClient.invalidateQueries({ queryKey })),+ ]);}/** While one chat is open: its members, timeline and send outcomes. */diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.tsindex 4341ad32e6..882b9c5423 100644--- a/apps/web/tests/functional/whatsapp-linked.spec.ts+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts@@ -1278,6 +1278,41 @@ function everyMessageType() {];}+test('a send settling keeps an older page that is still loading', async ({+ page,+}) => {+ const state = server();+ await mount(page, state, `?chat=${CHAT_ID}`);+ await expect(+ page.getByRole('button', { name: 'Load earlier messages' })+ ).toBeVisible();+ let releaseOlder = () => {};+ const older = new Promise<void>((resolve) => {+ releaseOlder = resolve;+ });+ let olderRequested = false;+ await page.route(+ (url) =>+ url.pathname.endsWith('/messages') && url.searchParams.has('before'),+ async (route) => {+ olderRequested = true;+ await older;+ await route.fallback();+ }+ );+ await page.getByRole('button', { name: 'Load earlier messages' }).click();+ await expect.poll(() => olderRequested).toBe(true);+ await typeInComposer(page, 'Sent while history loads');+ await page.getByRole('button', { name: 'Send message' }).click();+ await expect.poll(() => state.outgoing.length).toBe(1);+ // The send's reply has reached the page, and its refresh with it.+ await expect(+ page.getByText('Sent while history loads', { exact: true })+ ).toBeVisible();+ releaseOlder();+ await expect(page.getByText('Previous day discussion')).toBeVisible();+});+test('every WhatsApp message type renders with Chat parts and small cards', async ({page,}) => {