Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): leave a deleted session and keep the newest session list
Yudhi Armyndharisd6ac16e747a4
diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.tsindex d96b0d27e..809776730 100644--- a/dashboard/src/pages/Chats.features.test.ts+++ b/dashboard/src/pages/Chats.features.test.ts@@ -40,6 +40,8 @@ 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.let mainDown = false;+// The first account deleted on the server: the list no longer holds it.+let mainDeleted = false;const CREATED_SESSION: Session = {...SESSION,id: 'session-4',@@ -214,7 +216,7 @@ function installFetchStub(): void {if (method === 'GET' && path === '/api/sessions') {// 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,+ ...(mainDeleted ? [] : [mainDown ? { ...SESSION, status: 'disconnected' as const } : SESSION]),...(listSecond ? [secondDown ? { ...SECOND_SESSION, status: 'disconnected' as const } : SECOND_SESSION] : []),...(listOffline ? [offlineUp ? { ...OFFLINE_SESSION, status: 'ready' as const } : OFFLINE_SESSION] : []),...(listCreated ? [listCreated] : []),@@ -418,6 +420,7 @@ afterEach(async () => {secondDown = false;offlineUp = false;mainDown = false;+ mainDeleted = false;listCreated = null;listExtra = false;listDuplicateContact = false;@@ -1116,6 +1119,65 @@ test('a status that lands while the session list is being read is not undone byassert.equal(second().disabled, true, 'the older answer made the session that dropped pickable again');});+test('an open session deleted on the server gives way to the first ready one, and its chat goes with it', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ listSecond = true;+ const { container } = renderPage();+ fireEvent.click(await screen.findByText('Alice'));+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the room did not open'));++ // A status for a session the page does not know reads the list again, which no longer holds the open one.+ mainDeleted = true;+ listCreated = CREATED_SESSION;+ pushSessionStatus(CREATED_SESSION.id, 'qr_ready');+ await waitFor(() => assert.equal(selectedSessionName(container), SECOND_SESSION.name));+ assert.equal(container.querySelector('.room-header') === null, true, "the deleted session's chat stayed open");+ await screen.findByText('Alice');+ fireEvent.click(screen.getByRole('button', { name: 'Actions for Alice' }));+ fireEvent.click(screen.getByRole('button', { name: 'Contact info' }));+ await waitFor(() => assert.ok(container.querySelector('.contact-info-panel'), 'the next session is not usable'));+});++test('an open session deleted on the server with no other one ready leaves none selected and closes its dialogs', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ const { container } = renderPage();+ await screen.findByText('Alice');+ fireEvent.click(screen.getByRole('button', { name: 'Actions for Alice' }));+ fireEvent.click(screen.getByRole('button', { name: 'Mute notifications' }));+ await waitFor(() => assert.ok(screen.getByRole('dialog'), 'the mute dialog did not open'));++ mainDeleted = true;+ listCreated = CREATED_SESSION;+ pushSessionStatus(CREATED_SESSION.id, 'qr_ready');+ await screen.findByText('No connected sessions');+ assert.equal(screen.queryByRole('dialog') === null, true, "the deleted session's mute dialog stayed open");+ assert.equal(container.querySelector('.session-switcher') === null, true);+});++test('the session list read at load does not undo a newer list a status frame read before it answered', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ listOffline = true;+ const sessionReads = () => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;+ // The read at load is taken with the second account down, and held back.+ const release = hold('sessions');+ const { container } = renderPage();+ await waitFor(() => assert.equal(sessionReads(), 1));+ gates.delete('sessions');++ // The account connects, which the page does not know yet: the list is read again and answers at once.+ offlineUp = true;+ pushSessionStatus(OFFLINE_SESSION.id, 'ready');+ await waitFor(() => assert.equal(sessionReads(), 2));+ await settle();+ release();++ await screen.findByText('Alice');+ await settle();+ fireEvent.click(container.querySelector('.session-switcher-btn') as HTMLElement);+ const marie = screen.getAllByRole('option').find(o => o.textContent?.includes('Marie Haas')) as HTMLButtonElement;+ assert.equal(marie.disabled, false, 'the answer from before the status made the connected session unpickable');+});+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.tsx b/dashboard/src/pages/Chats.tsxindex f02512503..1a2e5f2a6 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -177,6 +177,9 @@ export function Chats() {// Every listed session, ready or not: the switcher shows the others with their state.const [listedSessions, setListedSessions] = useState<Session[]>([]);const [selectedSessionId, setSelectedSessionId] = useState<string>('');+ // The session on screen, for requests that answer later to check they still belong to it (synced below, with the+ // socket's refs).+ const selectedSessionRef = useRef(selectedSessionId);const [loadingSessions, setLoadingSessions] = useState<boolean>(true);// Chats list@@ -407,23 +410,44 @@ export function Chats() {// 1. Fetch available connected sessions on mount. A failed read is not "no connected sessions": the gateway may// simply be restarting, so the page says it could not read them and offers the read again.const [sessionsFailure, setSessionsFailure] = useState<string | null>(null);+ // Every read of the session list goes through here and is numbered: an answer is applied only if no read sent+ // after it has been, since the read at load can answer after a relist a status frame started and would put back+ // the states from before it. An answer that is dropped, or fails, after a newer one was applied resolves to that+ // newer list. A selected session the list no longer holds was deleted, so it counts as none selected: the first+ // ready session is opened, or none, and the session effect clears what belonged to it.+ const sessionReadsRef = useRef({ sent: 0, applied: 0, list: [] as Session[] });+ const readSessions = useCallback(async (): Promise<Session[]> => {+ const reads = sessionReadsRef.current;+ const request = ++reads.sent;+ let list: Session[];+ try {+ list = await sessionApi.list();+ } catch (err) {+ if (request < reads.applied) return reads.list;+ throw err;+ }+ if (request < reads.applied) return reads.list;+ reads.applied = request;+ reads.list = list;+ setSessionsFailure(null);+ setListedSessions(list);+ // The open session stays in the switcher when it is down, as it does on a status event.+ setSessions(list.filter(s => s.status === 'ready' || s.id === selectedSessionRef.current));+ const firstReady = list.find(s => s.status === 'ready')?.id ?? '';+ setSelectedSessionId(selected => (list.some(s => s.id === selected) ? selected : firstReady));+ return list;+ }, []);const loadSessions = useCallback(async () => {try {setLoadingSessions(true);setSessionsFailure(null);- const list = await sessionApi.list();- const readySessions = list.filter(s => s.status === 'ready');- setSessions(readySessions);- setListedSessions(list);- if (readySessions.length > 0) {- setSelectedSessionId(readySessions[0].id);- }+ await readSessions();} catch (err) {setSessionsFailure(err instanceof Error ? err.message : '');} finally {setLoadingSessions(false);}- }, []);+ }, [readSessions]);useEffect(() => {void loadSessions();}, [loadSessions]);@@ -578,28 +602,28 @@ export function Chats() {useEffect(() => {const loads = chatsLoadsRef.current;const reloads = backgroundReloadsRef.current;- if (selectedSessionId) {- void loadChats(selectedSessionId);- setActiveChat(null);- setActiveChannel(null);- setActiveStatusContactId(null);- // A staged attachment or reply belongs to a chat in the session being left, so it is dropped here- // rather than carried across — the close/reopen round trip that preserves it is scoped to a- // single session. Clearing previewUrl runs the revoke effect's cleanup; the composer- // unmounts with the closed room and invalidates its own in-flight FileReader.- setAttachment(null);- setPreviewUrl(null);- setReplyingTo(null);- lastRoomIdRef.current = null;- // The new-chat panel lists the address book of the session being left, and an open group dialog- // edits a group through it.- setShowNewChat(false);- setGroupDialogChat(null);- setConfirmAction(null);- setMuteDialogChat(null);- setContactDialogChat(null);- setShowArchived(false);- }+ // A session deleted while it was open leaves none selected when no other is ready: what belonged to it is+ // cleared all the same, with no list to load in its place.+ if (selectedSessionId) void loadChats(selectedSessionId);+ setActiveChat(null);+ setActiveChannel(null);+ setActiveStatusContactId(null);+ // A staged attachment or reply belongs to a chat in the session being left, so it is dropped here+ // rather than carried across — the close/reopen round trip that preserves it is scoped to a+ // single session. Clearing previewUrl runs the revoke effect's cleanup; the composer+ // unmounts with the closed room and invalidates its own in-flight FileReader.+ setAttachment(null);+ setPreviewUrl(null);+ setReplyingTo(null);+ lastRoomIdRef.current = null;+ // The new-chat panel lists the address book of the session being left, and an open group dialog+ // edits a group through it.+ setShowNewChat(false);+ setGroupDialogChat(null);+ setConfirmAction(null);+ setMuteDialogChat(null);+ setContactDialogChat(null);+ setShowArchived(false);return () => {for (const controller of loads) controller.abort();loads.clear();@@ -693,8 +717,6 @@ export function Chats() {// effects flush would otherwise see the previous list, miss the chat and refetch the whole list.const chatsRef = useRef(chats);const activeChatIdRef = useRef<string | undefined>(undefined);- // The session on screen, for requests that answer later to check they still belong to it.- const selectedSessionRef = useRef(selectedSessionId);useLayoutEffect(() => {chatsRef.current = chats;activeChatIdRef.current = activeChat?.id;@@ -972,21 +994,14 @@ export function Chats() {try {do {relist.again = false;- const list = await sessionApi.list();- setSessionsFailure(null);- setListedSessions(list);- // The open session stays in the switcher when it is down, as it does on a status event.- setSessions(list.filter(s => s.status === 'ready' || s.id === selectedSessionRef.current));- // With nothing selected (every session was down at load), the first ready session is opened.- const firstReady = list.find(s => s.status === 'ready');- if (firstReady) setSelectedSessionId(selected => selected || firstReady.id);+ await readSessions();} while (relist.again);} catch {// The next status event, or a search hit in that session, reads the list again.} finally {relist.running = false;}- }, []);+ }, [readSessions]);const handleSessionStatus = useCallback((event: { sessionId: string; status: string }) => {if (!listedSessionsRef.current.some(session => session.id === event.sessionId)) {@@ -1278,21 +1293,18 @@ export function Chats() {// 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 && s.status === 'ready')) {- let ready: Session[];+ let listed: Session[];try {- const listed = await sessionApi.list();- setListedSessions(listed);- ready = listed.filter(s => s.status === 'ready');+ listed = await readSessions();} catch (err) {showLoadError('chats.errors.loadSessions', err);return;}- if (!ready.some(s => s.id === hit.sessionId)) {+ if (!listed.some(s => s.id === hit.sessionId && s.status === 'ready')) {pendingHitRef.current = null;showWarningToast(t('chats.errors.searchHitSessionNotReady'));return;}- setSessions(ready);}const pending = { sessionId: hit.sessionId, chatId: hit.chatId, waMessageId: hit.waMessageId };pendingHitRef.current = pending;@@ -1320,7 +1332,7 @@ export function Chats() {}}},- [selectedSessionId, sessions, chats, switchTab, showLoadError, showWarningToast, t],+ [selectedSessionId, sessions, chats, readSessions, switchTab, showLoadError, showWarningToast, t],);// After a session switch the chats list reloads — pick up the pending chat once it appears.