Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): keep the session switcher current after a reconnect
Yudhi Armyndharisd6108b1512b2
diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.tsindex 8b3b77047..6210d1708 100644--- a/dashboard/src/pages/Chats.features.test.ts+++ b/dashboard/src/pages/Chats.features.test.ts@@ -33,6 +33,9 @@ let listOffline = false;// session's fixtures, so both list the same chats: the shared chat id a late result must not cross over.const SECOND_SESSION: Session = { ...SESSION, id: 'session-3', name: 'Second', phone: '15559876543' };let listSecond = false;+// Served as the list reads them once a test turns them on: the second session dropped, the offline one connected.+let secondDown = false;+let offlineUp = false;// The first account down at load (every session down, with `listOffline`), and an account created after the page// read the list, served once a test turns `listCreated` on.@@ -209,14 +212,14 @@ function installFetchStub(): void {gates.get(name)?.then(response) ?? Promise.resolve(response());if (method === 'GET' && path === '/api/sessions') {- return Promise.resolve(- jsonResponse([- mainDown ? { ...SESSION, status: 'disconnected' } : SESSION,- ...(listSecond ? [SECOND_SESSION] : []),- ...(listOffline ? [OFFLINE_SESSION] : []),- ...(listCreated ? [listCreated] : []),- ]),- );+ // Taken when the request is made, so an answer a test holds back is as stale as one still in flight.+ const sessions: Session[] = [+ mainDown ? { ...SESSION, status: 'disconnected' } : SESSION,+ ...(listSecond ? [secondDown ? { ...SECOND_SESSION, status: 'disconnected' as const } : SECOND_SESSION] : []),+ ...(listOffline ? [offlineUp ? { ...OFFLINE_SESSION, status: 'ready' as const } : OFFLINE_SESSION] : []),+ ...(listCreated ? [listCreated] : []),+ ];+ return gated('sessions', () => jsonResponse(sessions));}if (method === 'GET' && path.startsWith(`${base}/chats?`)) {return gated('chats', () =>@@ -412,6 +415,8 @@ afterEach(async () => {fetchCalls.length = 0;listOffline = false;listSecond = false;+ secondDown = false;+ offlineUp = false;mainDown = false;listCreated = null;listExtra = false;@@ -994,21 +999,81 @@ test('a session created after the page loaded joins the switcher, and can be picconst sessionReads = () => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;assert.equal(sessionReads(), 1);- listCreated = CREATED_SESSION;+ // A session still pairing has no number yet.+ listCreated = { ...CREATED_SESSION, phone: null };pushSessionStatus(CREATED_SESSION.id, 'qr_ready');await waitFor(() => assert.equal(sessionReads(), 2, 'a status for an unknown session did not read the list again'));fireEvent.click(container.querySelector('.session-switcher-btn') as HTMLElement);const option = () => screen.getAllByRole('option').find(o => o.textContent?.includes(CREATED_SESSION.name));await waitFor(() => assert.ok(option(), 'the new session is not in the switcher'));assert.equal((option() as HTMLButtonElement).disabled, true, 'a session still pairing can be picked');+ assert.ok(option()?.textContent?.includes('No phone'));- // Known now, so its next status is applied from the feed alone.+ // Known now, so a status short of ready is applied from the feed alone.+ pushSessionStatus(CREATED_SESSION.id, 'authenticating');+ await settle();+ assert.equal(sessionReads(), 2, 'a status short of ready for a listed session read the list again');++ // Once it connects it can be picked at once, and the list is read again for the number it now has.+ listCreated = { ...CREATED_SESSION, status: 'ready' };pushSessionStatus(CREATED_SESSION.id, 'ready');assert.equal((option() as HTMLButtonElement).disabled, false, 'the new session stayed unpickable once it connected');- assert.equal(sessionReads(), 2, 'a status for a listed session read the list again');+ await waitFor(() => assert.equal(sessionReads(), 3, 'a session that connected was not read again'));+ await waitFor(() =>+ assert.ok(!option()?.textContent?.includes('No phone'), 'the number it connected with is missing'),+ );assert.equal(selectedSessionName(container), SESSION.name, 'the open session changed');});+test('a socket reconnect reads the session list again, so a session that connected during the gap can be picked', async () => {+ const { screen, fireEvent, waitFor, act } = rtl;+ listOffline = true;+ const { container } = renderPage();+ await screen.findByText('Alice');+ const sessionReads = () => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;+ const reads = sessionReads();++ // Its status frame was sent while the socket was down.+ offlineUp = true;+ const socket = lastSocket();+ 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(sessionReads(), reads + 1, 'the reconnect did not read the session list'));++ fireEvent.click(container.querySelector('.session-switcher-btn') as HTMLElement);+ const marie = () =>+ screen.getAllByRole('option').find(o => o.textContent?.includes('Marie Haas')) as HTMLButtonElement;+ await waitFor(() =>+ assert.equal(marie().disabled, false, 'the session that connected during the gap stayed unpickable'),+ );+});++test('a status that lands while the session list is being read is not undone by that read', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ listSecond = true;+ const { container } = renderPage();+ await screen.findByText('Alice');+ const sessionReads = () => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;++ // A new session starts a read, answered with the list as it stood then.+ const release = hold('sessions');+ listCreated = CREATED_SESSION;+ pushSessionStatus(CREATED_SESSION.id, 'qr_ready');+ await waitFor(() => assert.equal(sessionReads(), 2));+ // The second session drops while that answer is out.+ secondDown = true;+ pushSessionStatus(SECOND_SESSION.id, 'disconnected');+ release();++ await waitFor(() => assert.equal(sessionReads(), 3, 'the status that landed during the read did not read again'));+ fireEvent.click(container.querySelector('.session-switcher-btn') as HTMLElement);+ const second = () => screen.getAllByRole('option').find(o => o.textContent?.includes('Second')) as HTMLButtonElement;+ await waitFor(() => assert.ok(second()));+ await settle();+ assert.equal(second().disabled, true, 'the older answer made the session that dropped pickable again');+});+test('the session switcher links to pairing another number only for a key that may create a session', async () => {const { screen, fireEvent } = rtl;const { MemoryRouter } = await import('react-router-dom');diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 51ac202c0..de87c3202 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -2314,6 +2314,33 @@ test('a search hit in a session that connected after the page loaded opens it',await within(container.querySelector('.room-header') as HTMLElement).findByText('Alice');});+test('a search hit in a session that dropped while it was open, and was left since, is refused', async () => {+ const { screen, waitFor, act } = rtl;+ thirdSessionStatus = 'ready';+ searchHits = [THIRD_SESSION_HIT];+ const { container } = renderChats();+ await screen.findByText('Alice');+ selectSession(container, SESSION_3.id);+ await waitFor(() => assert.equal(selectedSessionId(container), SESSION_3.id));++ // The open session stays in the switcher when it drops; the operator then goes back to the first one.+ thirdSessionStatus = 'disconnected';+ act(() =>+ lastSocket()?.receive('message', {+ type: 'event',+ timestamp: new Date(1_700_003_000_000).toISOString(),+ payload: { event: 'session.status', sessionId: SESSION_3.id, data: { status: 'disconnected' } },+ }),+ );+ selectSession(container, SESSION.id);+ await waitFor(() => assert.equal(selectedSessionId(container), SESSION.id));++ await clickSearchHit(container);+ await screen.findByText('The session of this message is not connected');+ await flush();+ assert.equal(selectedSessionId(container), SESSION.id, 'the hit opened a session that is not connected');+});+test("a search hit in another session opens that session's chat, not the one the previous list held", async () => {const { screen, fireEvent, within, waitFor } = rtl;twoSessions = true;@@ -3622,6 +3649,44 @@ const feedFrames = (): unknown[] =>.map(frame => frame.args[0] as { sessionId?: string; events?: string[] }).filter(frame => frame.sessionId !== '*' && !frame.events?.includes('session.status'));+const SESSION_FEED_EVENTS = ['session.status', 'session.qr', 'session.restriction'];+const sessionFeedFrames = () =>+ (lastSocket()?.emitted ?? [])+ .map(frame => frame.args[0] as { type?: string; sessionId?: string; events?: string[] })+ .filter(frame => frame.events?.includes('session.status'));++test("the page follows every session's status on the wildcard room, and each listed session for a key refused it", async () => {+ const { screen, waitFor, act } = rtl;+ twoSessions = true;+ try {+ renderChats();+ await screen.findByText('Alice');+ await waitFor(() => assert.ok(sessionFeedFrames().length > 0, 'the page did not join the session feed'));+ for (const frame of sessionFeedFrames()) {+ assert.deepEqual(frame, { type: 'subscribe', sessionId: '*', events: SESSION_FEED_EVENTS });+ }++ const joined = sessionFeedFrames().length;+ const socket = lastSocket();+ assert.ok(socket, 'expected the page to have opened a socket');+ act(() =>+ socket.receive('message', { type: 'error', code: 'FORBIDDEN_SESSION', message: 'Scoped keys cannot join *' }),+ );+ await waitFor(() =>+ assert.deepEqual(+ sessionFeedFrames()+ .slice(joined)+ .map(frame => frame.sessionId)+ .sort(),+ [SESSION.id, SESSION_2.id].sort(),+ ),+ );+ for (const frame of sessionFeedFrames().slice(joined)) assert.deepEqual(frame.events, SESSION_FEED_EVENTS);+ } finally {+ twoSessions = false;+ }+});+test("the page joins the open session's message events once connected, and moves to the next session on a switch", async () => {const { waitFor } = rtl;twoSessions = true;diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 21c408399..71abba806 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -1005,6 +1005,10 @@ export function Chats() {// loadSessions selects the first ready session; when every session was down at load nothing is selected, so// the first one that connects is (the switcher would be blank and the list empty otherwise).if (status === 'ready') setSelectedSessionId(selected => selected || event.sessionId);+ // A session that connects has its number and push name written as it does, which the status frame does not+ // carry, so the list is read again. A read already out may have been answered before this change, so it is+ // followed by one more.+ if (status === 'ready' || relistRef.current.running) void relistSessions();},[relistSessions],);@@ -1080,6 +1084,8 @@ export function Chats() {// Statuses are live now (status.received): a story posted during the socket gap would// otherwise stay invisible until a focus refetch.queryClient.invalidateQueries({ queryKey: ['contact-statuses', selectedSessionId] });+ // So is a session.status frame: a session that connected or dropped during the gap is read from the list.+ void relistSessions();// The sidebar list is local state, so previews, unread counts and chats started during the gap// only show after a refetch. Background mode keeps the current list on screen meanwhile.// The open chat's gap messages are read on screen, so once the refetch has applied this session's@@ -1106,6 +1112,7 @@ export function Chats() {canWrite,markChatRead,markRowRead,+ relistSessions,]);// The threads cache at staleTime: Infinity, and this session's events were not delivered while@@ -1266,7 +1273,7 @@ export function Chats() {// Search covers stored messages of every session, but the page can only open a ready one, and// its list is read on mount. A session missing from it is looked up again, since it may have// connected since; one that still is not ready is refused rather than selected with no chats.- if (hit.sessionId !== selectedSessionId && !sessions.some(s => s.id === hit.sessionId)) {+ if (hit.sessionId !== selectedSessionId && !sessions.some(s => s.id === hit.sessionId && s.status === 'ready')) {let ready: Session[];try {const listed = await sessionApi.list();