Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): do not hold a null phone for a day

Yudhi Armyndharis5f02690f2de7
diff --git a/dashboard/src/hooks/useResolvedPhone.test.ts b/dashboard/src/hooks/useResolvedPhone.test.ts
new file mode 100644
index 000000000..0195a44cc
--- /dev/null
+++ b/dashboard/src/hooks/useResolvedPhone.test.ts
@@ -0,0 +1,102 @@
+// The phone a privacy id resolves to is stable, so a found one is held for a day. A null is not: the route answers
+// it both for "the account knows no phone for this id" and for a lookup that failed in the engine, and holding a
+// failure for a day left Save contact disabled for the open chat until the tab was reloaded.
+import '../test-helpers/register-hooks.ts';
+import { test, before, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { createElement, type ReactNode } from 'react';
+import { QueryClient, QueryClientProvider, focusManager } from '@tanstack/react-query';
+import type { useResolvedPhone as useResolvedPhoneFn } from './useResolvedPhone.ts';
+
+type RTL = typeof import('@testing-library/react');
+
+let rtl: RTL;
+let useResolvedPhone: typeof useResolvedPhoneFn;
+const clients: QueryClient[] = [];
+
+const MINUTE = 60 * 1000;
+const HOUR = 60 * MINUTE;
+
+// What the route answers for the id, and every lookup it was asked for.
+let phone: string | null = null;
+const lookups: string[] = [];
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+before(async () => {
+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');
+ await installJsdomGlobals();
+ globalThis.fetch = ((input: RequestInfo | URL) => {
+ const match = /\/sessions\/([^/]+)\/contacts\/([^/]+)\/phone$/.exec(String(input));
+ if (!match) return Promise.resolve(json({ message: `unstubbed ${String(input)}` }, 404));
+ lookups.push(decodeURIComponent(match[2]));
+ return Promise.resolve(json({ contactId: decodeURIComponent(match[2]), phone }));
+ }) as typeof fetch;
+ rtl = await import('@testing-library/react');
+ ({ useResolvedPhone } = await import('./useResolvedPhone.ts'));
+});
+
+afterEach(async () => {
+ rtl.cleanup();
+ for (const client of clients.splice(0)) {
+ await client.cancelQueries();
+ client.clear();
+ }
+ lookups.length = 0;
+ phone = null;
+ focusManager.setFocused(undefined);
+});
+
+function renderPhone() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
+ clients.push(client);
+ const wrapper = ({ children }: { children: ReactNode }) => createElement(QueryClientProvider, { client }, children);
+ return rtl.renderHook(() => useResolvedPhone('s1', '262813461250071@lid'), { wrapper });
+}
+
+const regainFocus = () =>
+ rtl.act(() => {
+ focusManager.setFocused(false);
+ focusManager.setFocused(true);
+ });
+
+test('a phone that resolved is held for the day, and asked for again after it', async t => {
+ let clock = 1_800_000_000_000;
+ t.mock.method(Date, 'now', () => clock);
+ phone = '628111';
+ const { result } = renderPhone();
+ await rtl.waitFor(() => assert.equal(result.current.data, '628111'));
+
+ clock += 23 * HOUR;
+ regainFocus();
+ await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(lookups.length, 1, 'a resolved phone was asked for again within the day');
+
+ clock += 2 * HOUR;
+ regainFocus();
+ await rtl.waitFor(() => assert.equal(lookups.length, 2));
+});
+
+test('a null answer is asked for again after a minute, so a failed lookup does not last the day', async t => {
+ let clock = 1_800_000_000_000;
+ t.mock.method(Date, 'now', () => clock);
+ phone = null;
+ const { result } = renderPhone();
+ await rtl.waitFor(() => assert.equal(result.current.isSuccess, true));
+ assert.equal(result.current.data, null);
+
+ // Within the minute the null stands, so a restless focus does not hammer the engine.
+ clock += 30 * 1000;
+ regainFocus();
+ await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(lookups.length, 1, 'a null was asked for again within the minute');
+
+ // The engine has recovered by the time the window is focused after it.
+ phone = '628111';
+ clock += 40 * 1000;
+ regainFocus();
+ await rtl.waitFor(() => assert.equal(result.current.data, '628111'));
+ assert.equal(lookups.length, 2);
+});
diff --git a/dashboard/src/hooks/useResolvedPhone.ts b/dashboard/src/hooks/useResolvedPhone.ts
index abd76b63c..11207f6fc 100644
--- a/dashboard/src/hooks/useResolvedPhone.ts
+++ b/dashboard/src/hooks/useResolvedPhone.ts
@@ -1,11 +1,16 @@
-import { useQuery } from '@tanstack/react-query';
+import { useQuery, type Query } from '@tanstack/react-query';
import { contactApi } from '../services/api';
+const DAY_MS = 24 * 60 * 60 * 1000;
+// The route answers null both when the account knows no phone for the id and when the lookup failed in the engine,
+// and the two look alike, so a null is not held for the day a phone is.
+const NULL_STALE_MS = 60 * 1000;
+
/**
* Lazily resolve a contact id (e.g. an @lid privacy id) to its phone number (MSISDN digits) for
* one (sessionId, contactId). Returns null when the engine can't map it — the caller keeps its
- * fallback label in that case. An @lid ↔ phone mapping is stable, so the result is cached for a
- * day; `retry: false` keeps an unmappable id from spamming the server.
+ * fallback label in that case. An @lid ↔ phone mapping is stable, so a phone is cached for a
+ * day, a null for a minute; `retry: false` keeps an unmappable id from spamming the server.
*
* Call it with `enabled` inputs only when the cheap local formatting already failed
* (formatPhoneForDisplay returned null) — normal @c.us chats never need the engine round-trip.
@@ -24,6 +29,7 @@ export function resolvedPhoneQuery(sessionId: string, contactId: string) {
return {
queryKey: ['resolvedPhone', sessionId, contactId] as const,
queryFn: () => contactApi.resolvePhone(sessionId, contactId).then(r => r.phone),
- staleTime: 24 * 60 * 60 * 1000, // 1 day — lid→phone mappings don't churn
+ // lid→phone mappings don't churn, so a phone is held for the day; a null is not (see NULL_STALE_MS).
+ staleTime: (query: Query<string | null, Error>) => (query.state.data === null ? NULL_STALE_MS : DAY_MS),
};
}
diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.ts
index 364d66734..de1834750 100644
--- a/dashboard/src/pages/Chats.features.test.ts
+++ b/dashboard/src/pages/Chats.features.test.ts
@@ -2074,6 +2074,36 @@ test('the address book is not read again when the window regains focus, unless t
assert.equal(contactReads().length, 3);
});
+test('Save contact is offered again for the open privacy-id chat once the engine knows its phone, with no reload', async t => {
+ const { screen, fireEvent, act, waitFor, within } = rtl;
+ let clock = 1_800_000_000_000;
+ t.mock.method(Date, 'now', () => clock);
+ listExtra = true;
+ const { container } = renderPage();
+ fireEvent.click(await screen.findByText('Lia'));
+ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the room did not open'));
+ // The route answers null for an id it found no phone for and for a lookup that failed alike.
+ await waitFor(() => assert.ok(phoneRequests().length >= 1, 'the phone was not asked for'));
+ fireEvent.click(container.querySelector('.room-menu-trigger') as HTMLElement);
+ const saveEntry = () =>
+ within(container.querySelector('.room-menu-popover') as HTMLElement).getByRole('button', {
+ name: /^Save contact/,
+ }) as HTMLButtonElement;
+ assert.equal(saveEntry().disabled, true, 'Save contact is offered without a phone to save under');
+
+ // The engine answers a minute later, and the open menu follows once the window is focused again.
+ lidPhones[LID_CHAT.id] = '15550004444';
+ clock += 61_000;
+ act(() => {
+ focusManager.setFocused(false);
+ focusManager.setFocused(true);
+ });
+ // The check reads the page and changes nothing: a callback that touched the DOM would re-run itself forever.
+ await waitFor(() =>
+ assert.equal(saveEntry().disabled, false, 'Save contact stayed disabled after the engine answered'),
+ );
+});
+
test('a chat keyed by a privacy id offers Save contact disabled, with the reason, and sends nothing', async () => {
const { screen, fireEvent } = rtl;
listExtra = true;