Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): keep an older session list read off newer rows
Yudhi Armyndharis0443063813da
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex a00cfa186..05368723e 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -102,6 +102,7 @@ function resetFetchCalls(): void {startResult = null;stopFailure = null;qrGate = null;+ listGate = null;}function findFetchCall(method: string, path: string): FetchCall | undefined {@@ -132,6 +133,9 @@ let stopFailure: { status: number; message: string } | null = null;let startGate: Promise<void> | null = null;// When set, GET .../qr for that one session answers only once `until` settles.let qrGate: { sessionId: string; until: Promise<void> } | null = null;+// When set, the next GET /api/sessions reads the rows as they are when it arrives but answers only once+// this settles, so a test can land an older read after a newer one. Spent by that one read.+let listGate: Promise<void> | null = null;let sessionProxy = {enabled: false,proxyType: null as string | null,@@ -163,6 +167,12 @@ function installFetchStub(): void {: 'gateway unavailable';return Promise.resolve(jsonResponse({ message }, 503));}+ if (listGate) {+ const until = listGate;+ listGate = null;+ const snapshot: unknown = JSON.parse(JSON.stringify(SESSIONS));+ return until.then(() => jsonResponse(snapshot));+ }return Promise.resolve(jsonResponse(SESSIONS));}@@ -1023,6 +1033,144 @@ test('a disconnected push keeps the QR modal when the re-read fails', async () =}});+// Two reads of the list can be in flight at once, one per status push, and nothing makes them answer+// in the order they were sent. The older one must not put its snapshot back over the newer.+test('a list read that answers after a newer one does not overwrite it', async () => {+ const { screen, within, waitFor, act } = rtl;+ resetFetchCalls();+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ const row: Session = { ...SESSION_QR, id: 'sess-flap-1', name: 'flapping', status: 'authenticating' };+ SESSIONS.push(row);+ try {+ renderSessions();+ const card = (await screen.findByText('flapping')).closest('.session-card') as HTMLElement;+ const reads = () => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;++ // The ready push's read sees the row ready, then answers late.+ let release: () => void = () => {};+ listGate = new Promise<void>(resolve => (release = resolve));+ Object.assign(row, { status: 'ready' });+ const before = reads();+ pushSessionStatus(row.id, 'ready');+ await waitFor(() => assert.equal(reads(), before + 1));++ // The session drops straight away; this read answers first.+ Object.assign(row, { status: 'disconnected', engineLoaded: false });+ pushSessionStatus(row.id, 'disconnected');+ await waitFor(() => assert.equal(reads(), before + 2));+ await act(() => new Promise<void>(resolve => setTimeout(resolve, 20)));+ assert.ok(within(card).queryByText('Disconnected'));++ release();+ await act(() => new Promise<void>(resolve => setTimeout(resolve, 20)));+ assert.ok(within(card).queryByText('Disconnected'), 'an older list read put the session back to ready');+ assert.ok(+ within(card).queryByRole('button', { name: 'Start' }),+ 'an older list read put the session back to ready',+ );+ } finally {+ SESSIONS.pop();+ }+});++// A status push carries no fields but the status, and a push that starts no read of its own (qr_ready,+// initializing, connecting) is newer than a read already in flight. That read must not undo it.+test('a list read that started before a status push does not undo the pushed status', async () => {+ const { screen, within, waitFor, act } = rtl;+ resetFetchCalls();+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ const row: Session = { ...SESSION_QR, id: 'sess-backoff-2', name: 'bouncing', status: 'ready', phone: '15550004444' };+ SESSIONS.push(row);+ try {+ renderSessions();+ const card = (await screen.findByText('bouncing')).closest('.session-card') as HTMLElement;+ const reads = () => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;++ // The disconnect's read sees the row disconnected, then answers late.+ let release: () => void = () => {};+ listGate = new Promise<void>(resolve => (release = resolve));+ Object.assign(row, { status: 'disconnected' });+ const before = reads();+ pushSessionStatus(row.id, 'disconnected');+ await waitFor(() => assert.equal(reads(), before + 1));++ // The engine is already reconnecting when that answer arrives.+ Object.assign(row, { status: 'initializing' });+ pushSessionStatus(row.id, 'initializing');+ await within(card).findByText('Starting...');++ release();+ await act(() => new Promise<void>(resolve => setTimeout(resolve, 20)));+ assert.ok(+ within(card).queryByText('Starting...'),+ 'a read older than the push put the session back to disconnected',+ );+ } finally {+ SESSIONS.pop();+ }+});++// The page's own writes (a created row, a stop's answer, a deleted row) are newer than any list read+// already in flight, the same as a status push.+test('a list read in flight does not undo a create, a stop or a delete', async () => {+ const { screen, fireEvent, within, waitFor, act } = rtl;+ resetFetchCalls();+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ const qrRow = { ...SESSION_QR };+ const staleIndex = SESSIONS.indexOf(SESSION_STALE_ENGINE);+ try {+ renderSessions();+ const qrCard = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;+ const reads = () => fetchCalls.filter(c => c.method === 'GET' && c.path === '/api/sessions').length;+ const settle = () => act(() => new Promise<void>(resolve => setTimeout(resolve, 20)));+ // Starts a read (the push's own) that snapshots the rows now and answers only on release.+ const holdRead = async (): Promise<() => void> => {+ let release: () => void = () => {};+ listGate = new Promise<void>(resolve => (release = resolve));+ const before = reads();+ pushSessionStatus(SESSION_TIMELOCKED.id, 'action_required');+ await waitFor(() => assert.equal(reads(), before + 1));+ return release;+ };++ let release = await holdRead();+ fireEvent.click(within(qrCard).getByRole('button', { name: 'Stop' }));+ await within(qrCard).findByRole('button', { name: 'Start' });+ Object.assign(SESSION_QR, { status: 'disconnected', engineLoaded: false });+ release();+ await settle();+ assert.ok(+ within(qrCard).queryByRole('button', { name: 'Start' }),+ 'a read older than the stop put the engine back',+ );++ release = await holdRead();+ fireEvent.click(screen.getByRole('button', { name: 'New Session' }));+ const dialog = await screen.findByRole('dialog');+ fireEvent.change(within(dialog).getByPlaceholderText('e.g., marketing-bot'), { target: { value: 'late-bot' } });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));+ await screen.findByText('late-bot');+ SESSIONS.push({ ...SESSION_QR, id: 'sess-new-late-bot', name: 'late-bot', status: 'created' as Session['status'] });+ release();+ await settle();+ assert.ok(screen.queryByText('late-bot'), 'a read older than the create dropped the new row');+ SESSIONS.pop();++ release = await holdRead();+ const staleCard = screen.getByText('stale-engine').closest('.session-card') as HTMLElement;+ fireEvent.click(within(staleCard).getByRole('button', { name: 'Delete' }));+ fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete' }));+ await waitFor(() => assert.ok(!screen.queryByText('stale-engine')));+ SESSIONS.splice(staleIndex, 1);+ release();+ await settle();+ assert.ok(!screen.queryByText('stale-engine'), 'a read older than the delete brought the row back');+ } finally {+ Object.assign(SESSION_QR, qrRow);+ if (!SESSIONS.includes(SESSION_STALE_ENGINE)) SESSIONS.splice(staleIndex, 0, SESSION_STALE_ENGINE);+ }+});+test('a restricted session shows the restriction on its card, even while it is ready', async () => {const { screen, within } = rtl;resetFetchCalls();diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex b573a118b..37474f3d2 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -109,15 +109,44 @@ export function Sessions() {// Spends the one retry the recovery effect below is allowed per connect. Given back by a read that// actually succeeded, so a later independent failure on the same connection is retried too.const retriedThisConnect = useRef(false);+ // List reads overlap (every status push that needs server fields starts one) and can answer out of+ // order, and a read is a snapshot from before any row the page wrote while it was in flight. So a+ // read is applied only if no newer read has been applied and no row was written since it started;+ // `rowWrites` counts those writes. A read that loses to a write is sent again, unless a newer read+ // is already on its way, so what it would have brought (a restriction, the rows after a socket gap)+ // still arrives. A dropped read returns the newest rows the page holds, which is what its callers+ // must decide on.+ const listRequest = useRef(0);+ const listApplied = useRef(0);+ const rowWrites = useRef(0);++ // Mirror the latest sessions in a ref so the WS handler can compare against the current status without+ // depending on `sessions` (which would churn the callback identity and re-subscribe the socket). Kept+ // in sync with every state update (fetch / create / delete / WS) via the effect below.+ const sessionsRef = useRef<Session[]>([]);+ useEffect(() => {+ sessionsRef.current = sessions;+ }, [sessions]);const fetchSessions = useCallback(async (): Promise<Session[]> => {listReadFailed.current = false;+ let request = 0;try {// Background refetches — a websocket push, a mutation reloading the list — would otherwise// replace the whole page with a spinner for the length of a round-trip, so a restriction// arriving on a live page reads as a full reload.if (!initialLoadDone.current) setLoading(true);- const data = await sessionApi.list();+ let data: Session[];+ for (;;) {+ request = ++listRequest.current;+ const writes = rowWrites.current;+ data = await sessionApi.list();+ if (request < listApplied.current) return sessionsRef.current;+ if (rowWrites.current === writes) break;+ if (request !== listRequest.current) return sessionsRef.current;+ }+ listApplied.current = request;+ sessionsRef.current = data;setSessions(data);// The list is current again, so an error left by an earlier failed read (or a create, whose toast// already reported it) no longer describes the page, and the recovery retry is available again.@@ -133,6 +162,8 @@ export function Sessions() {void invalidateSessionQueries(queryClient, queryKeys.sessions);return data;} catch (err) {+ // A failure older than a read already applied says nothing about the list on screen.+ if (request < listApplied.current) return sessionsRef.current;listReadFailed.current = true;setError(err instanceof Error ? err.message : t('sessions.create.errorDefault'));return [];@@ -142,14 +173,6 @@ export function Sessions() {}}, [t, queryClient]);- // Mirror the latest sessions in a ref so the WS handler can compare against the current status without- // depending on `sessions` (which would churn the callback identity and re-subscribe the socket). Kept- // in sync with every state update (fetch / create / delete / WS) via the effect below.- const sessionsRef = useRef<Session[]>([]);- useEffect(() => {- sessionsRef.current = sessions;- }, [sessions]);-const {qrData,pairingMode,@@ -183,6 +206,7 @@ export function Sessions() {onCreated: newSession => {// Functional append: never capture a stale `sessions` (a WS or fetch between the await and the// setState would otherwise drop a row). Then invalidate the prefix so stats/groups/chats refresh.+ rowWrites.current += 1;setSessions(current => [...current, newSession]);void invalidateSessionQueries(queryClient, queryKeys.sessions);},@@ -198,6 +222,7 @@ export function Sessions() {// disconnected session's stale code.const applySessionResponse = useCallback(async (updated: Session) => {+ rowWrites.current += 1;sessionsRef.current = replaceSession(sessionsRef.current, updated);setSessions(sessionsRef.current);setSelectedSession(current => (current?.id === updated.id ? updated : current));@@ -230,6 +255,9 @@ export function Sessions() {// and the failed-refresh don't fire on every redundant envelope. Update the ref synchronously so// a duplicate arriving in the same tick (before the sync effect runs) is also caught.if (prev && prev.status === event.status) return;+ // A push for a row the page does not hold yet changes nothing, so it must not void the read+ // that is about to bring that row (the mount read, before any row is on screen).+ if (prev) rowWrites.current += 1;// Drop `engineLoaded` alongside the status patch: it is server-owned live state the status// envelope does not carry, so keeping the previous value would pair a fresh status with a// stale engine answer and the card could offer Start to a running session (or Unlink to one@@ -312,6 +340,7 @@ export function Sessions() {try {await sessionApi.delete(id);// Functional removal (no stale `sessions` capture), then invalidate the prefix.+ rowWrites.current += 1;setSessions(current => current.filter(s => s.id !== id));await invalidateSessionQueries(queryClient, queryKeys.sessions);toast.success(