Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): load all authorized chat pages
Yudhi Armyndharisd739002a4f7a
diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.tsindex 0a531b3d8..b8c90db1d 100644--- a/dashboard/src/hooks/queries.ts+++ b/dashboard/src/hooks/queries.ts@@ -68,7 +68,7 @@ export function useSessionGroupsQuery(sessionId: string, enabled: boolean) {export function useSessionChatsQuery(sessionId: string, enabled: boolean) {return useQuery({queryKey: queryKeys.sessionChats(sessionId),- queryFn: () => sessionApi.getChats(sessionId),+ queryFn: ({ signal }) => sessionApi.getChats(sessionId, signal),enabled: enabled && !!sessionId,staleTime: 60_000,});diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 8682b1541..f14753beb 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -55,7 +55,8 @@ let statuses: StatusUpdate[] = [];// Answers a session's chat list in place of the fixture, keyed by the session id in the URL (before// the rewrite below folds session-2 onto session-1), so a test can land two lists in any order.-let chatsResponder: ((sessionId: string) => Promise<Response>) | null = null;+let chatsResponder: ((sessionId: string, offset: number, signal?: AbortSignal | null) => Promise<Response>) | null =+ null;const CHAT: Chat = {id: '[email protected]',@@ -301,8 +302,13 @@ function installFetchStub(): void {if (method === 'GET' && path === `/api/sessions/${SESSION.id}/channels`) {return Promise.resolve(jsonResponse(channels));}- if (method === 'GET' && path === `/api/sessions/${SESSION.id}/chats`) {- if (chatsResponder) return chatsResponder(url.includes(`/sessions/${SESSION_2.id}/`) ? SESSION_2.id : SESSION.id);+ if (method === 'GET' && /^\/api\/sessions\/[^/]+\/chats(?:\?|$)/.test(path)) {+ if (chatsResponder)+ return chatsResponder(+ url.includes(`/sessions/${SESSION_2.id}/`) ? SESSION_2.id : SESSION.id,+ Number(new URL(url, 'http://localhost').searchParams.get('offset')),+ init?.signal,+ );return Promise.resolve(jsonResponse([CHAT, CHAT_2]));}if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/contacts/profile-pictures`)) {@@ -851,7 +857,11 @@ test('a message arriving the moment the chat list commits updates the listed rowawait waitFor(() => assert.ok(screen.queryByLabelText('3 unread messages'), 'the arrival did not reach the row'));await flush();assert.ok(delivered, 'the frame was never delivered');- assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1, 'a listed chat refetched the list');+ assert.equal(+ countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`),+ 1,+ 'a listed chat refetched the list',+ );assert.ok(screen.queryByLabelText('3 unread messages'), 'a refetch overwrote the live row');} finally {observer.disconnect();@@ -863,7 +873,7 @@ test('a socket reconnect refetches the chat list so the sidebar shows what arrivresetFetchCalls();renderChats();await screen.findByText('Alice');- const chatsPath = `/api/sessions/${SESSION.id}/chats`;+ const chatsPath = `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`;assert.equal(countFetchCalls('GET', chatsPath), 1);// While the socket was down, Alice wrote again and a new chat started.@@ -899,7 +909,7 @@ test('a message that lands while a reconnect refetch is out survives the older sassert.ok(socket, 'expected the page to have opened a socket');act(() => socket.receive('disconnect', 'transport close'));act(() => socket.receive('connect'));- await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 2));+ await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`), 2));act(() =>socket.receive('message', {@@ -998,7 +1008,7 @@ test('a reconnect whose refetch fails while the engine starts sends no mark-as-ract(() => socket.receive('connect'));await new Promise(resolve => setTimeout(resolve, 1_000));- assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1);+ assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`), 1);assert.ok(!findFetchCall('POST', `/api/sessions/${SESSION.id}/chats/read`),'a mark-as-read went out while the engine was starting',@@ -1024,7 +1034,7 @@ test('a reconnect refetch that settles after the open chat was left keeps its unassert.ok(socket, 'expected the page to have opened a socket');act(() => socket.receive('disconnect', 'transport close'));act(() => socket.receive('connect'));- await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1));+ await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`), 1));// The user moves on to Carol before the refetch lands; Alice's new message was never seen.fireEvent.click(await screen.findByText('Carol'));@@ -1062,7 +1072,7 @@ test('a reconnect refetch that settles after the page was left sends no mark-as-assert.ok(socket, 'expected the page to have opened a socket');act(() => socket.receive('disconnect', 'transport close'));act(() => socket.receive('connect'));- await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1));+ await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`), 1));// The operator opens another page before the refetch lands; the gap messages were never seen.unmount();@@ -1129,7 +1139,7 @@ test('a reconnect refetch overtaken by a newer list still marks the open chat reassert.ok(socket, 'expected the page to have opened a socket');act(() => socket.receive('disconnect', 'transport close'));act(() => socket.receive('connect'));- await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1));+ await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`), 1));act(() =>socket.receive('message', {@@ -1190,7 +1200,9 @@ test("a reconnect refetch that settles after a session switch leaves the new sesassert.ok(socket, 'expected the page to have opened a socket');act(() => socket.receive('disconnect', 'transport close'));act(() => socket.receive('connect'));- await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`) >= 2, true));+ await waitFor(() =>+ assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`) >= 2, true),+ );fireEvent.change(container.querySelector('select.session-selector') as HTMLSelectElement, {target: { value: SESSION_2.id },@@ -1894,7 +1906,7 @@ test('every message for a chat the sidebar does not list refetches the list, and},});// Each arrival renders before the next, the shape of live traffic.- const chatsPath = `/api/sessions/${SESSION.id}/chats`;+ const chatsPath = `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`;for (const [index, id] of ['wamid.dave.1', 'wamid.dave.2', 'wamid.dave.3'].entries()) {receive(id);await waitFor(() => assert.equal(countFetchCalls('GET', chatsPath), index + 1, 'an arrival did not refetch'));@@ -1948,7 +1960,7 @@ test('a message deleted for everyone in a chat never opened refetches the chat lresetFetchCalls();revoke(CHAT_2.id, 'wamid.carol.1');- await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1));+ await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`), 1));});test('a delayed poll echo cannot restore a revoked message or its sidebar preview', async () => {@@ -2831,3 +2843,110 @@ test('an edit arriving after the newest message was deleted for everyone does no);assert.ok(!within(room).queryByText('late edit'), 'the edit of a deleted message came back into the thread');});++const LARGE_CHAT_PAGE: Chat[] = [+ CHAT,+ ...Array.from({ length: 999 }, (_, i) => ({ ...CHAT_2, id: `large-${i}@c.us`, name: `Conversation ${i}` })),+];+const TAIL_CHAT: Chat = { ...CHAT_2, id: '[email protected]', name: 'Tail conversation' };++test('a conversation past the first 1000 is searchable and opens from the sidebar', async () => {+ chatsResponder = (_sessionId, offset) => Promise.resolve(jsonResponse(offset === 0 ? LARGE_CHAT_PAGE : [TAIL_CHAT]));+ const { container } = renderChats();+ await rtl.screen.findByText('Tail conversation');+ rtl.fireEvent.change(rtl.screen.getByPlaceholderText('Search chats...'), { target: { value: 'Tail conversation' } });+ assert.equal(container.querySelectorAll('.chat-item-card').length, 1);+ rtl.fireEvent.click(rtl.screen.getByText('Tail conversation'));+ await rtl.within(container.querySelector('.room-header') as HTMLElement).findByText('Tail conversation');+});++for (const action of ['switch session', 'unmount'] as const) {+ test(`a chat list stops paging after ${action}`, async () => {+ twoSessions = true;+ const offsets: number[] = [];+ let signal: AbortSignal | null | undefined;+ let release!: (response: Response) => void;+ const pending = new Promise<Response>(resolve => {+ release = resolve;+ });+ chatsResponder = (sessionId, offset, requestSignal) => {+ if (sessionId === SESSION_2.id) return Promise.resolve(jsonResponse([CHAT_2]));+ offsets.push(offset);+ signal = requestSignal;+ return offset === 0 ? Promise.resolve(jsonResponse(LARGE_CHAT_PAGE)) : pending;+ };+ const view = renderChats();+ await rtl.waitFor(() => assert.deepEqual(offsets, [0, 1000]));+ if (action === 'switch session') {+ rtl.fireEvent.change(view.container.querySelector('select.session-selector') as HTMLSelectElement, {+ target: { value: SESSION_2.id },+ });+ await rtl.screen.findByText('Carol');+ } else view.unmount();+ assert.equal(signal?.aborted, true);+ await rtl.act(async () => {+ release(jsonResponse(LARGE_CHAT_PAGE));+ await new Promise(resolve => setImmediate(resolve));+ });+ assert.deepEqual(offsets, [0, 1000]);+ if (action === 'switch session') assert.equal(rtl.screen.queryByText('Alice'), null);+ twoSessions = false;+ });+}++test('a failed later chat page keeps the previously loaded sidebar', async () => {+ renderChats();+ await rtl.screen.findByText('Alice');+ chatsResponder = (_sessionId, offset) =>+ Promise.resolve(+ offset === 0 ? jsonResponse(LARGE_CHAT_PAGE) : jsonResponse({ message: 'Later page unavailable' }, 500),+ );+ const socket = lastSocket()!;+ rtl.act(() => socket.receive('disconnect', 'transport close'));+ rtl.act(() => socket.receive('connect'));+ await rtl.waitFor(() => assert.ok(findFetchCall('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=1000`)));+ await flush();+ assert.ok(rtl.screen.queryByText('Alice'));+ assert.equal(rtl.screen.queryByText('Conversation 1'), null);+});++test('a live sidebar row survives movement outside a paginated reconnect snapshot', async () => {+ renderChats();+ await rtl.screen.findByText('Alice');+ let release!: (response: Response) => void;+ const pending = new Promise<Response>(resolve => {+ release = resolve;+ });+ chatsResponder = (_sessionId, offset) =>+ offset === 0+ ? Promise.resolve(+ jsonResponse(+ Array.from({ length: 1000 }, (_, i) => ({ ...CHAT_2, id: `snapshot-${i}@c.us`, name: `Snapshot ${i}` })),+ ),+ )+ : pending;+ const socket = lastSocket()!;+ rtl.act(() => socket.receive('disconnect', 'transport close'));+ rtl.act(() => socket.receive('connect'));+ await rtl.waitFor(() => assert.ok(findFetchCall('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=1000`)));+ rtl.act(() =>+ receiveEvent('message.received', {+ id: 'live-during-paging',+ chatId: CHAT.id,+ from: CHAT.id,+ to: 'me',+ body: 'Updated during paging',+ type: 'text',+ fromMe: false,+ timestamp: 1_700_004_000,+ }),+ );+ await rtl.screen.findByText('Updated during paging');+ await rtl.act(async () => {+ release(jsonResponse([TAIL_CHAT]));+ await new Promise(resolve => setImmediate(resolve));+ });+ await rtl.screen.findByText('Tail conversation');+ assert.equal(rtl.screen.getAllByText('Updated during paging').length, 1);+ assert.ok(rtl.screen.queryByLabelText('3 unread messages'));+});diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 0c41423d6..f9c30ecb8 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -313,6 +313,7 @@ export function Chats() {// answer is dropped only once a newer one has landed: dropping every answer a newer call overtook// left a burst of realtime refetches with no list at all, each miss firing the next refetch.// A realtime refetch runs in the background, keeping the current list on screen.+ const chatsLoadsRef = useRef(new Set<AbortController>());const chatsRequestRef = useRef(0);const chatsAppliedRef = useRef(0);const chatsSessionRef = useRef('');@@ -324,15 +325,18 @@ export function Chats() {const loadChats = useCallback(async (sessionId: string, { background = false } = {}): Promise<boolean> => {if (!sessionId) return false;+ const controller = new AbortController();+ chatsLoadsRef.current.add(controller);const request = ++chatsRequestRef.current;chatsSessionRef.current = sessionId;- const stale = () => sessionId !== chatsSessionRef.current || request < chatsAppliedRef.current;+ const stale = () =>+ controller.signal.aborted || sessionId !== chatsSessionRef.current || request < chatsAppliedRef.current;// A stale answer for the session still selected was overtaken by a newer list that has applied,// so this session's list on screen is as fresh as this call's would have been.- const overtaken = () => sessionId === chatsSessionRef.current;+ const overtaken = () => !controller.signal.aborted && sessionId === chatsSessionRef.current;try {if (!background) setLoadingChats(true);- const data = await sessionApi.getChats(sessionId);+ const data = await sessionApi.getChats(sessionId, controller.signal);if (stale()) return overtaken();chatsAppliedRef.current = request;// A live frame can move a row past the snapshot a background refetch was built from while it is@@ -342,7 +346,9 @@ export function Chats() {listedSessionRef.current = sessionId;setChats(prev => {const live = new Map(merge ? prev.map(c => [c.id, c] as const) : []);- return data+ const fetchedIds = new Set(data.map(c => c.id));+ const rows = [...data, ...prev.filter(c => merge && moved(c.id) && !fetchedIds.has(c.id))];+ return rows.map(c => {const row = live.get(c.id);return row && moved(c.id) && (row.timestamp || 0) > (c.timestamp || 0) ? row : c;@@ -359,9 +365,10 @@ export function Chats() {setChats([]);return false;} finally {+ chatsLoadsRef.current.delete(controller);// Only the call that raised the spinner clears it: a background refetch settling first would// otherwise uncover the previous session's list while the switch's own load is still out.- if (!background && sessionId === chatsSessionRef.current) setLoadingChats(false);+ if (!background && !controller.signal.aborted && sessionId === chatsSessionRef.current) setLoadingChats(false);}},[showLoadError],@@ -376,6 +383,7 @@ export function Chats() {}, []);useEffect(() => {+ const loads = chatsLoadsRef.current;if (selectedSessionId) {void loadChats(selectedSessionId);setActiveChat(null);@@ -390,6 +398,10 @@ export function Chats() {setReplyingTo(null);lastRoomIdRef.current = null;}+ return () => {+ for (const controller of loads) controller.abort();+ loads.clear();+ };}, [selectedSessionId, loadChats]);// Coalesce mark-as-read RPCs per chat: every incoming message in the visible chat raises adiff --git a/dashboard/src/services/api.test.ts b/dashboard/src/services/api.test.tsindex 0019868ff..a3475d339 100644--- a/dashboard/src/services/api.test.ts+++ b/dashboard/src/services/api.test.ts@@ -276,3 +276,80 @@ test('the contact list rejects instead of returning a partial list when a later(err: Error & { status?: number }) => err.status === 429 && err.message === 'Too Many Requests',);});++function chatResponse(data: unknown, status = 200): Response {+ return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });+}++for (const size of [1001, 2000, 11001]) {+ test(`the chat list loads all ${size} conversations in bounded pages`, async () => {+ const offsets: number[] = [];+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ const url = new URL(String(input), 'http://localhost');+ const offset = Number(url.searchParams.get('offset'));+ assert.equal(url.searchParams.get('limit'), '1000');+ offsets.push(offset);+ return chatResponse(+ Array.from({ length: Math.min(1000, size - offset) }, (_, i) => ({ id: `chat-${offset + i}` })),+ );+ }) as typeof fetch;+ const chats = await sessionApi.getChats('s1');+ assert.equal(chats.length, size);+ assert.equal(chats.at(-1)?.id, `chat-${size - 1}`);+ assert.deepEqual(+ offsets,+ Array.from({ length: Math.floor(size / 1000) + 1 }, (_, i) => i * 1000),+ );+ });+}++test('chat pagination preserves first-seen order and deduplicates moving rows', async () => {+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ const offset = Number(new URL(String(input), 'http://localhost').searchParams.get('offset'));+ return chatResponse(+ offset === 0+ ? Array.from({ length: 1000 }, (_, i) => ({ id: `chat-${i}` }))+ : [{ id: 'chat-999' }, { id: 'tail' }],+ );+ }) as typeof fetch;+ const chats = await sessionApi.getChats('s1');+ assert.equal(chats.length, 1001);+ assert.equal(chats[999].id, 'chat-999');+ assert.equal(chats[1000].id, 'tail');+});++for (const status of [500, 429]) {+ test(`chat pagination rejects a later ${status} without returning a partial list`, async () => {+ let attempts = 0;+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ const offset = Number(new URL(String(input), 'http://localhost').searchParams.get('offset'));+ if (offset === 0) return chatResponse(Array.from({ length: 1000 }, (_, i) => ({ id: `chat-${i}` })));+ attempts++;+ return chatResponse({ message: 'Later page failed' }, status);+ }) as typeof fetch;+ await assert.rejects(sessionApi.getChats('s1'), (err: Error & { status?: number }) => err.status === status);+ assert.equal(attempts, status === 429 ? 3 : 1);+ });+}++for (const change of ['replace key', 'sign out', 'abort'] as const) {+ test(`chat pagination stops before the next page after ${change}`, async () => {+ let release!: (response: Response) => void;+ let requests = 0;+ const pending = new Promise<Response>(resolve => {+ release = resolve;+ });+ const controller = new AbortController();+ globalThis.fetch = (async () => {+ requests++;+ return pending;+ }) as typeof fetch;+ const result = sessionApi.getChats('s1', controller.signal);+ if (change === 'replace key') sessionStorage.setItem('openwa_api_key', 'next-key');+ if (change === 'sign out') sessionStorage.removeItem('openwa_api_key');+ if (change === 'abort') controller.abort();+ release(chatResponse(Array.from({ length: 1000 }, (_, i) => ({ id: `chat-${i}` }))));+ await assert.rejects(result, change === 'abort' ? { name: 'AbortError' } : /Signed out/);+ assert.equal(requests, 1);+ });+}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 56289f90c..245c214f4 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -879,7 +879,32 @@ export const sessionApi = {getStats: () => request<SessionStats>('/sessions/stats/overview'),getGroups: (id: string) =>request<{ id: string; name?: string; linkedParentJID?: string | null }[]>(`/sessions/${id}/groups`),- getChats: (id: string) => request<Chat[]>(`/sessions/${id}/chats`),+ getChats: async (id: string, signal?: AbortSignal) => {+ let lastError: unknown;+ const { items, throttled } = await fetchAllPages<Chat>(+ async (limit, offset) => {+ signal?.throwIfAborted();+ try {+ const data = await request<Chat[]>(`/sessions/${id}/chats?limit=${limit}&offset=${offset}`, { signal });+ return { data, total: data.length < limit ? offset + data.length : Infinity };+ } catch (err) {+ lastError = err;+ throw err;+ } finally {+ signal?.throwIfAborted();+ }+ },+ { pageSize: 1000, maxItems: Infinity },+ );+ // A later throttled page must fail the load rather than present an incomplete sidebar.+ if (throttled) throw lastError;+ const seen = new Set<string>();+ return items.filter(chat => {+ if (seen.has(chat.id)) return false;+ seen.add(chat.id);+ return true;+ });+ },markChatRead: (id: string, chatId: string) =>request<{ success: boolean }>(`/sessions/${id}/chats/read`, {method: 'POST',