Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): open the chat a typed number already has
Yudhi Armyndharis4f7fa3e466ce
diff --git a/dashboard/src/components/chats/NewChatPanel.tsx b/dashboard/src/components/chats/NewChatPanel.tsxindex b74a98a77..b34c74654 100644--- a/dashboard/src/components/chats/NewChatPanel.tsx+++ b/dashboard/src/components/chats/NewChatPanel.tsx@@ -22,6 +22,11 @@ interface NewChatPanelProps {* the chat was found through, for the page to check it is still the one selected.*/onOpenChat: (chat: Chat, sessionId: string) => void;+ /**+ * The id the chat list holds a phone-based id's conversation under when that is another id of the same contact+ * (one that moved to privacy-id addressing keeps its chat under its @lid), or null when the list has none.+ */+ findListedChat?: (phoneId: string) => Promise<string | null>;onClose: () => void;}@@ -64,7 +69,7 @@ const draftChat = (id: string, name: string, kind: Chat['kind'], timestamp = 0):* Sidebar sub-view for starting a 1:1 chat or creating a group. The page mounts it only for a key that* can write; group creation is offered on Baileys only, since whatsapp-web.js answers it with 501.*/-function NewChatPanel({ sessionId, onOpenChat, onClose }: NewChatPanelProps) {+function NewChatPanel({ sessionId, onOpenChat, findListedChat, onClose }: NewChatPanelProps) {const { t } = useTranslation();const { error: showErrorToast, success: showSuccessToast } = useToast();const { engineType } = useRole();@@ -127,7 +132,11 @@ function NewChatPanel({ sessionId, onOpenChat, onClose }: NewChatPanelProps) {// Resolve a typed number to its canonical WhatsApp id. The send routes accept an unregistered number// without an error, so this check is the only thing that keeps a chat from going nowhere. An answer// that arrives after the panel was closed is dropped, toasts included: nothing on screen asked for it.- const resolveNumber = async (digits: string, label: string): Promise<string | null> => {+ const resolveNumber = async (+ digits: string,+ label: string,+ listedAs?: (phoneId: string) => Promise<string | null>,+ ): Promise<string | null> => {setChecking(true);try {const res = await contactApi.checkNumber(sessionId, digits);@@ -136,7 +145,10 @@ function NewChatPanel({ sessionId, onOpenChat, onClose }: NewChatPanelProps) {showErrorToast(t('chats.newChat.notOnWhatsApp', { number: label }));return null;}- return res.whatsappId;+ // A conversation the list keeps under another id of the same contact is the one to open. Failing to+ // find it is no reason to fail the number, which opens a new chat as it would for any other.+ const listed = listedAs ? await listedAs(res.whatsappId).catch(() => null) : null;+ return listed ?? res.whatsappId;} catch (err) {if (openRef.current) {showErrorToast(t('chats.newChat.checkFailed'), err instanceof Error ? err.message : undefined);@@ -149,7 +161,7 @@ function NewChatPanel({ sessionId, onOpenChat, onClose }: NewChatPanelProps) {const handleStartWithNumber = async () => {if (!typedNumber) return;- const id = await resolveNumber(typedNumber, typedNumberLabel);+ const id = await resolveNumber(typedNumber, typedNumberLabel, findListedChat);if (id && openRef.current) onOpenChat(draftChat(id, '', 'individual'), sessionId);};diff --git a/dashboard/src/hooks/useResolvedPhone.ts b/dashboard/src/hooks/useResolvedPhone.tsindex 2cc12e02f..abd76b63c 100644--- a/dashboard/src/hooks/useResolvedPhone.ts+++ b/dashboard/src/hooks/useResolvedPhone.ts@@ -12,11 +12,18 @@ import { contactApi } from '../services/api';*/export function useResolvedPhone(sessionId: string | undefined, contactId: string | undefined) {return useQuery<string | null, Error>({- queryKey: ['resolvedPhone', sessionId, contactId] as const,- queryFn: () => contactApi.resolvePhone(sessionId!, contactId!).then(r => r.phone),+ ...resolvedPhoneQuery(sessionId!, contactId!),enabled: Boolean(sessionId && contactId),- staleTime: 24 * 60 * 60 * 1000, // 1 day — lid→phone mappings don't churngcTime: 60 * 60 * 1000,retry: false,});}++/** The query behind {@link useResolvedPhone}, for a caller that asks about several ids at once (fetchQuery). */+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+ };+}diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.tsindex f038552bc..6be994ed1 100644--- a/dashboard/src/pages/Chats.features.test.ts+++ b/dashboard/src/pages/Chats.features.test.ts@@ -107,6 +107,19 @@ const NUMBER_NAMED_CONTACT = {isBlocked: false,};let listExtra = false;+// The phone the gateway resolves a privacy id to, by id; an id it knows nothing about answers null.+const lidPhones: Record<string, string> = {};+// When true, resolving a privacy id fails as it does while the engine is busy.+let failLidPhones = false;+// How many more privacy-id chats the list holds, none of which resolves to a phone.+let extraLidChats = 0;+const extraLidChat = (n: number): Chat => ({+ ...CHAT,+ id: `9000000000${String(n).padStart(3, '0')}@lid`,+ name: `Lid ${n}`,+ timestamp: 1_600_000_000 - n,+ lastMessage: `from lid ${n}`,+});// Served when a test turns `listDuplicateContact` on: Bob listed twice under one id, as whatsapp-web.js lists a// contact it holds as both a LID and a phone record. The first copy carries another number than the id's.const DUPLICATE_CONTACT = { ...CONTACT, number: '262813461250071' };@@ -168,6 +181,7 @@ function installFetchStub(): void {{ ...CHAT, ...aliceNow },...(listGroup ? [GROUP] : []),...(listExtra ? [PUSH_ONLY_CHAT, LID_CHAT, NUMBER_NAMED_CHAT] : []),+ ...Array.from({ length: extraLidChats }, (_, n) => extraLidChat(n)),]),);}@@ -269,6 +283,11 @@ function installFetchStub(): void {const id = decodeURIComponent(path.split('/contacts/')[1].split('/profile-picture')[0]);return Promise.resolve(jsonResponse({ url: pictureFor[id] ?? null }));}+ if (method === 'GET' && /\/contacts\/[^/]+\/phone$/.test(path)) {+ const id = decodeURIComponent(path.split('/contacts/')[1].split('/phone')[0]);+ if (failLidPhones) return Promise.resolve(jsonResponse({ message: 'busy' }, 503));+ return Promise.resolve(jsonResponse({ contactId: id, phone: lidPhones[id] ?? null }));+ }if (method === 'GET' && path.startsWith(`${base}/contacts/check/`)) {return gated('check', () => jsonResponse({ exists: true, whatsappId: RESOLVED_ID }));}@@ -334,6 +353,9 @@ afterEach(async () => {listExtra = false;listDuplicateContact = false;failContacts = false;+ failLidPhones = false;+ extraLidChats = 0;+ for (const id of Object.keys(lidPhones)) delete lidPhones[id];for (const key of Object.keys(aliceNow)) delete aliceNow[key as keyof Chat];aliceThread = [];declineWrites = false;@@ -420,6 +442,82 @@ for (const reactStrictMode of [false, true]) {});}+// ── The number check answers a phone id, while a contact that moved to privacy-id addressing keeps its conversation+// under its @lid: starting a chat with that number has to find it. ──++const phoneRequests = () =>+ fetchCalls.filter(c => c.method === 'GET' && /\/contacts\/[^/]+\/phone$/.test(c.path)).map(c => c.path);++/** Type the number the new chat tests use into the panel and press Start chat. */+async function startChatWithTypedNumber(): Promise<void> {+ const { screen, fireEvent } = rtl;+ fireEvent.click(screen.getByRole('button', { name: 'New chat' }));+ fireEvent.change(screen.getByLabelText('Search name or number with country code'), {+ target: { value: TYPED_NUMBER },+ });+ fireEvent.click(await screen.findByRole('button', { name: /^Start chat with/ }));+}++const listedChatCards = (container: HTMLElement) => container.querySelectorAll('.chats-list .chat-item-card').length;++test('a typed number whose chat the list holds under a privacy id opens that chat, not a new one', async () => {+ const { screen, waitFor, within } = rtl;+ listExtra = true;+ lidPhones[LID_CHAT.id] = '15550009999';+ const { container } = renderPage();+ await screen.findByText('Lia');+ const before = listedChatCards(container);+ await startChatWithTypedNumber();++ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the chat did not open'));+ await within(container.querySelector('.room-header') as HTMLElement).findByText('Lia');+ assert.equal(listedChatCards(container), before, 'a second chat was added beside the one the list holds');+ assert.equal(+ phoneRequests().filter(path => path.includes(encodeURIComponent(LID_CHAT.id))).length,+ 1,+ 'the engine was asked about the privacy id more than once',+ );+});++test('a privacy-id chat of another phone is not mistaken for the number, which opens a new chat', async () => {+ const { screen, waitFor, within } = rtl;+ listExtra = true;+ lidPhones[LID_CHAT.id] = '15550007777';+ const { container } = renderPage();+ await screen.findByText('Lia');+ const before = listedChatCards(container);+ await startChatWithTypedNumber();++ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the chat did not open'));+ await within(container.querySelector('.room-header') as HTMLElement).findByText('15550009999');+ assert.equal(listedChatCards(container), before + 1, 'the new chat was not added to the list');+});++test('a privacy id the engine cannot resolve right now does not stop a chat from opening', async () => {+ const { screen, waitFor, within } = rtl;+ listExtra = true;+ failLidPhones = true;+ const { container } = renderPage();+ await screen.findByText('Lia');+ await startChatWithTypedNumber();++ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the chat did not open'));+ await within(container.querySelector('.room-header') as HTMLElement).findByText('15550009999');+ assert.ok(!screen.queryByText('Could not check the number'), 'a failed lookup was shown as a failed number check');+});++test('only the newest privacy-id chats are asked about, not every one the list holds', async () => {+ const { screen, waitFor } = rtl;+ extraLidChats = 60;+ const { container } = renderPage();+ await screen.findByText('Lid 0');+ await startChatWithTypedNumber();++ await waitFor(() => assert.ok(container.querySelector('.room-header'), 'the chat did not open'));+ assert.ok(phoneRequests().length > 0, 'no privacy id was asked about');+ assert.ok(phoneRequests().length < extraLidChats, `all ${extraLidChats} privacy ids were asked about`);+});+for (const reactStrictMode of [false, true]) {test(`a group is created with the picked contacts on Baileys, and whatsapp-web.js is not offered one${reactStrictMode ? ' (StrictMode)' : ''}`, async () => {const { screen, fireEvent, waitFor, within } = rtl;diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 21d88bc61..4c05d2cd5 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -26,7 +26,7 @@ import {} from 'lucide-react';import { useProfilePicture } from '../hooks/useProfilePicture';import { useProfilePictures } from '../hooks/useProfilePictures';-import { useResolvedPhone } from '../hooks/useResolvedPhone';+import { useResolvedPhone, resolvedPhoneQuery } from '../hooks/useResolvedPhone';import { formatPhoneForDisplay } from '../utils/formatPhone';import {sessionApi,@@ -97,6 +97,13 @@ const MARK_READ_DEBOUNCE_MS = 750;const MARK_READ_MESSAGE_IDS_MAX = 100;const readKey = (sessionId: string, chatId: string) => `${sessionId}\u0000${chatId}`;+// How many privacy-id chats a typed number is looked for among, and how many are asked about at once. The engine+// answers one id per request, so searching the whole list would cost a request for every chat in it. Only the+// newest chats are searched: an older conversation opens as a new chat, as it does for a number the list has no+// row for. Raise the cap, or have the gateway name the privacy id of a phone, if that proves too few.+const LID_CHATS_SEARCHED = 30;+const LID_LOOKUPS_AT_ONCE = 5;+// Longest one background chat-list walk may take before it is abandoned. A walk is a dozen small requests, and// the gateway answers a stalled engine at 180 s, so this is far above a healthy walk and below that.const BACKGROUND_RELOAD_DEADLINE_MS = 120_000;@@ -1237,6 +1244,29 @@ export function Chats() {? shownChats: [...shownChats.filter(c => c.pinned), ...shownChats.filter(c => !c.pinned)];+ // The number check answers a phone id, while a contact that moved to privacy-id addressing keeps its conversation+ // under its @lid. Finds the id the list holds that conversation under: the same phone spelled another way, else+ // the @lid chat the engine resolves to that phone. The engine's answers share the room header's cache.+ const findListedChat = async (phoneId: string): Promise<string | null> => {+ const sessionId = selectedSessionRef.current;+ const spelled = chatsRef.current.find(c => contactKey(c.id) === contactKey(phoneId));+ if (spelled) return spelled.id;+ const phone = phoneId.split('@')[0].replace(/\D/g, '');+ const privacyChats = chatsRef.current+ .filter(c => c.kind === 'individual' && c.id.endsWith('@lid'))+ .slice(0, LID_CHATS_SEARCHED);+ for (let i = 0; i < privacyChats.length; i += LID_LOOKUPS_AT_ONCE) {+ const batch = privacyChats.slice(i, i + LID_LOOKUPS_AT_ONCE);+ const phones = await Promise.all(+ batch.map(c => queryClient.fetchQuery(resolvedPhoneQuery(sessionId, c.id)).catch(() => null)),+ );+ if (selectedSessionRef.current !== sessionId) return null;+ const hit = batch.find((_, j) => phones[j]?.replace(/\D/g, '') === phone);+ if (hit) return hit.id;+ }+ return null;+ };+// Open a chat picked in the new-chat panel. A chat with no history is not in the engine's list, so// it is added to the sidebar locally until the first message, or the next list load, settles it.// The filter and search are cleared so the opened chat is visible in the list. A chat the panel found@@ -1624,6 +1654,7 @@ export function Chats() {<NewChatPanelsessionId={selectedSessionId}onOpenChat={handleOpenNewChat}+ findListedChat={findListedChat}onClose={() => setShowNewChat(false)}/>) : null