Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): keep session list writes in step with the push handler
Yudhi Armyndharis79d2c94a2e0f
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex f2f7f4da2..9c3104318 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -104,6 +104,7 @@ function resetFetchCalls(): void {qrGate = null;listGate = null;pairingGate = null;+ afterMutation = null;}function findFetchCall(method: string, path: string): FetchCall | undefined {@@ -139,6 +140,9 @@ let qrGate: { sessionId: string; until: Promise<void> } | null = null;let listGate: Promise<void> | null = null;// When set, POST .../pairing-code answers only once this settles.let pairingGate: Promise<void> | null = null;+// When set, runs on the macrotask after a create or delete has answered: a push that lands before+// React has rendered what that answer wrote.+let afterMutation: (() => void) | null = null;let sessionProxy = {enabled: false,proxyType: null as string | null,@@ -180,6 +184,7 @@ function installFetchStub(): void {}if (method === 'POST' && path === '/api/sessions') {+ if (afterMutation) setImmediate(afterMutation);const payload = body as { name?: string; proxyUrl?: string; proxyType?: string } | undefined;const name = payload?.name ?? 'unnamed';return Promise.resolve(@@ -201,6 +206,7 @@ function installFetchStub(): void {: Promise.resolve(jsonResponse({ message: 'not found' }, 404));}if (method === 'DELETE' && sessionIdMatch) {+ if (afterMutation) setImmediate(afterMutation);return Promise.resolve(new Response(null, { status: 204 }));}@@ -1263,6 +1269,41 @@ test('a list read in flight does not undo a create, a stop or a delete', async (}});+// A push for another session, handled before React renders a create or a delete, must patch the list+// that write produced rather than the one on screen before it.+test('a status push landing right after a create or a delete keeps what it wrote', async () => {+ const { screen, fireEvent, within, waitFor, act } = rtl;+ resetFetchCalls();+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ const staleIndex = SESSIONS.indexOf(SESSION_STALE_ENGINE);+ try {+ renderSessions();+ await screen.findByText('new-device');+ const settle = () => act(() => new Promise<void>(resolve => setTimeout(resolve, 50)));++ // `authenticating` starts no list read, so nothing would repair the list afterwards.+ afterMutation = () => pushSessionStatus(SESSION_RECONNECTING.id, 'authenticating');+ 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: 'probe-bot' } });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));+ await waitFor(() => assert.ok(findFetchCall('POST', '/api/sessions')));+ await settle();+ assert.ok(screen.queryByText('probe-bot'), 'the push dropped the created card');++ afterMutation = () => pushSessionStatus(SESSION_RECONNECTING.id, 'qr_ready');+ 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(findFetchCall('DELETE', `/api/sessions/${SESSION_STALE_ENGINE.id}`)));+ await settle();+ assert.ok(!screen.queryByText('stale-engine'), 'the push brought the deleted card back');+ } finally {+ afterMutation = null;+ if (!SESSIONS.includes(SESSION_STALE_ENGINE)) SESSIONS.splice(staleIndex, 0, SESSION_STALE_ENGINE);+ }+});+// The detail modal shows the row as it is now, not as it was when View was clicked.test('an open detail modal follows its session status and phone', async () => {const { screen, fireEvent, within, waitFor } = rtl;diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex d0dd92312..a4e9ed028 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -126,12 +126,20 @@ export function Sessions() {const latestList = useRef<Promise<Session[]>>(Promise.resolve([]));// 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.+ // depending on `sessions` (which would churn the callback identity and re-subscribe the socket). Every+ // writer moves the ref in the same tick as its setState (a list read directly, row writes through+ // `updateSessions`), so a push handled before React re-renders sees what the last write produced. The+ // effect below is only a backstop.const sessionsRef = useRef<Session[]>([]);useEffect(() => {sessionsRef.current = sessions;}, [sessions]);+ // A row write: applied to the ref now, and to state as a functional update, so it builds on every+ // write queued before it instead of replacing the list with an older copy.+ const updateSessions = useCallback((update: (list: Session[]) => Session[]) => {+ sessionsRef.current = update(sessionsRef.current);+ setSessions(update);+ }, []);const readSessions = useCallback(async (): Promise<Session[]> => {listReadFailed.current = false;@@ -214,7 +222,7 @@ export function Sessions() {// 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]);+ updateSessions(current => [...current, newSession]);void invalidateSessionQueries(queryClient, queryKeys.sessions);},onFailed: msg => setError(msg),@@ -230,12 +238,11 @@ export function Sessions() {const applySessionResponse = useCallback(async (updated: Session) => {rowWrites.current += 1;- sessionsRef.current = replaceSession(sessionsRef.current, updated);- setSessions(sessionsRef.current);+ updateSessions(current => replaceSession(current, updated));dismissQrForSession(updated.id);await reconcileSessionCache(queryClient, queryKeys.sessions, updated);},- [queryClient, dismissQrForSession],+ [queryClient, dismissQrForSession, updateSessions],);// A restriction push and a recovered socket mean the same thing to this page: the local list may be@@ -270,10 +277,11 @@ export function Sessions() {// with no engine). Clearing it makes isSessionStarted fall back to the status set until an// authoritative response arrives — and for `disconnected`, where that fallback is knowingly// wrong, the branch below refetches.- sessionsRef.current = sessionsRef.current.map(s =>- s.id === event.sessionId ? { ...s, status: event.status as Session['status'], engineLoaded: undefined } : s,+ updateSessions(current =>+ current.map(s =>+ s.id === event.sessionId ? { ...s, status: event.status as Session['status'], engineLoaded: undefined } : s,+ ),);- setSessions(sessionsRef.current);// Mark the shared session queries stale so sibling views refetch — but ONLY on a real// transition (the dedup guard above already swallows the redundant double-signals, so this// does not re-invalidate on duplicate envelopes).@@ -313,7 +321,7 @@ export function Sessions() {toast.error(t('sessions.toasts.failedTitle'), t('sessions.toasts.failedDesc'));}},- [toast, t, fetchSessions, queryClient, dismissQrForSession, clearQrCodeForSession],+ [toast, t, fetchSessions, queryClient, dismissQrForSession, clearQrCodeForSession, updateSessions],),});@@ -347,7 +355,7 @@ export function Sessions() {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));+ updateSessions(current => current.filter(s => s.id !== id));await invalidateSessionQueries(queryClient, queryKeys.sessions);toast.success(t('sessions.delete.successTitle'),@@ -375,7 +383,7 @@ export function Sessions() {// from before the start, which now includes `engineLoaded` and would leave the card offering// Start for a session that just acquired an engine.const started = await sessionApi.start(id);- setSessions(current => replaceSession(current, started));+ updateSessions(current => replaceSession(current, started));// A 200 does not promise the engine is still there when the list is read back: a concurrent stop// retires the start, and an engine can fail right after answering. Skip the modal when the re-read// shows the session without one. A failed re-read gives no answer, so the start's success decides.