Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(contacts): batch-resolve sidebar avatars in one request (no more 429 burst) (#818)
Yudhi Armyndharis1f71f555f33a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a457e036..c19ac2fc8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -77,6 +77,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Chat-list avatars no longer burst into HTTP 429s: profile pictures for the whole sidebar are+ batch-resolved in ONE request (`GET .../contacts/profile-pictures?ids=…`, up to 50 ids, 3 engine+ lookups at a time) instead of one parallel fetch per row, which exhausted the per-IP throttle.++- The chat header no longer formats a LID privacy id as a fake phone number (e.g. "+26 281 346125 0071"): digit-only LIDs and group ids are rejected by the phone formatter, and personal @lidchats now resolve and display the real number through the engine (cached a day). Chat list rowsdiff --git a/dashboard/src/hooks/useProfilePictures.ts b/dashboard/src/hooks/useProfilePictures.tsnew file mode 100644index 000000000..7ed66995c--- /dev/null+++ b/dashboard/src/hooks/useProfilePictures.ts@@ -0,0 +1,23 @@+import { useQuery } from '@tanstack/react-query';+import { contactApi } from '../services/api';++/**+ * Batch-fetch profile picture URLs for a list of chat ids in ONE request (the chat-list sidebar).+ * Firing one useProfilePicture per row bursts N parallel calls and exhausts the per-IP throttle+ * (429s); the batch endpoint resolves up to 50 ids server-side, 3 at a time.+ *+ * Caching mirrors useProfilePicture: 1h stale (signed CDN URLs rotate), 30min gc, no retry — an+ * id that comes back null just keeps the icon fallback. The query key uses the sorted id list so+ * reordering the sidebar doesn't refetch.+ */+export function useProfilePictures(sessionId: string | undefined, contactIds: string[]) {+ const sortedKey = [...contactIds].sort().join(',');+ return useQuery<Record<string, string | null>, Error>({+ queryKey: ['profilePictures', sessionId, sortedKey] as const,+ queryFn: () => contactApi.profilePictures(sessionId!, sortedKey.split(',')).then(r => r.pictures),+ enabled: Boolean(sessionId && contactIds.length > 0),+ staleTime: 60 * 60 * 1000, // 1 hour+ gcTime: 30 * 60 * 1000,+ retry: false,+ });+}diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 6e22cbc33..034b31a3d 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -19,6 +19,7 @@ import {ChevronDown,} from 'lucide-react';import { useProfilePicture } from '../hooks/useProfilePicture';+import { useProfilePictures } from '../hooks/useProfilePictures';import { useResolvedPhone } from '../hooks/useResolvedPhone';import { formatPhoneForDisplay } from '../utils/formatPhone';import {@@ -88,19 +89,18 @@ const getMediaSrc = (media?: MessageMedia): string => {return `data:${media.mimetype};base64,${media.data}`;};-// Chat list avatar: the same 1h-cached profile picture as the room header (shared TanStack Query-// cache keyed by (sessionId, contactId), so the row and the header never fetch twice), falling-// back to the generic person/group icon while it loads or when the picture is hidden/unavailable.-function ChatAvatar({ sessionId, chat }: { sessionId: string; chat: Chat }) {- const pp = useProfilePicture(sessionId, chat.id);- if (pp.data) {+// Chat list avatar. Renders from the sidebar's ONE batch request (useProfilePictures) — firing a+// query per row burst the per-IP throttle into 429s. The generic icon stays while the batch loads+// or when the contact hides their picture.+function ChatAvatar({ pictureUrl, isGroup }: { pictureUrl?: string | null; isGroup: boolean }) {+ if (pictureUrl) {return (<div className="chat-avatar">- <img src={pp.data} alt="" onError={() => pp.refetch()} />+ <img src={pictureUrl} alt="" /></div>);}- return <div className="chat-avatar">{chat.isGroup ? <Users size={20} /> : <User size={20} />}</div>;+ return <div className="chat-avatar">{isGroup ? <Users size={20} /> : <User size={20} />}</div>;}export function Chats() {@@ -159,6 +159,12 @@ export function Chats() {onMediaLoad,} = useChatScrollPosition(activeChat?.id ?? null, messages.length > 0);+ // Batch profile-picture fetch for the visible chat list — ONE request for the whole sidebar+ // (per-row queries burst the per-IP throttle into 429s). Sorted-key cached 1h; rows fall back+ // to the generic icon for ids that resolve null.+ const chatIds = useMemo(() => chats.map(c => c.id), [chats]);+ const listPics = useProfilePictures(selectedSessionId || undefined, chatIds);+// Profile-picture fetch for the active room (cached 1h by useProfilePicture; TanStack Query// dedupes, so other components querying the same key share this slice).const activePp = useProfilePicture(selectedSessionId || undefined, activeChat?.id);@@ -940,7 +946,7 @@ export function Chats() {className={`chat-item-card ${isActive ? 'active' : ''}`}onClick={() => setActiveChat(chat)}>- <ChatAvatar sessionId={selectedSessionId} chat={chat} />+ <ChatAvatar pictureUrl={listPics.data?.[chat.id]} isGroup={chat.isGroup} /><div className="chat-item-info"><div className="chat-item-top">diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex d5de427fb..19d5fad7c 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -662,6 +662,16 @@ export const contactApi = {request<{ contactId: string; phone: string | null }>(`/sessions/${sessionId}/contacts/${encodeURIComponent(contactId)}/phone`,),+ // Batch-resolve profile picture URLs for a whole sidebar in ONE request — the per-chat burst of+ // parallel single fetches exhausts the per-IP throttle (429s). Engine lookups run 3 at a time+ // server-side; ids beyond the backend's 50-id cap are dropped client-side too.+ profilePictures: (sessionId: string, contactIds: string[]) =>+ request<{ pictures: Record<string, string | null> }>(+ `/sessions/${sessionId}/contacts/profile-pictures?ids=${contactIds+ .slice(0, 50)+ .map(encodeURIComponent)+ .join(',')}`,+ ),};// =============================================================================diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex e3f4dad63..0f16d8bd6 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -31,6 +31,25 @@ export class ContactController {});}+ @Get('profile-pictures')+ @ApiOperation({+ summary: 'Batch-resolve profile picture URLs for up to 50 contacts',+ description:+ 'One request for a whole chat sidebar — avoids the burst of parallel single fetches that ' ++ 'would exhaust the per-IP throttle. Engine lookups run 3 at a time; per-id failures return null.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiQuery({ name: 'ids', required: true, description: 'Comma-separated contact ids (max 50 used)' })+ // NOTE: declared BEFORE @Get(':contactId') so the literal segment wins over the param route.+ async getProfilePictures(@Param('sessionId') sessionId: string, @Query('ids') ids?: string) {+ const list = (ids ?? '')+ .split(',')+ .map(s => s.trim())+ .filter(Boolean);+ const pictures = await this.contactService.getProfilePictures(sessionId, list);+ return { pictures };+ }+@Get(':contactId')@ApiOperation({ summary: 'Get a specific contact by ID' })@ApiParam({ name: 'sessionId', description: 'Session ID' })diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex 549555180..674fd67cd 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -51,4 +51,37 @@ describe('ContactService', () => {);expect(resolveContactPhone).toHaveBeenCalledWith('123@lid');});++ it('batch-resolves profile pictures, nulling per-id failures without aborting', async () => {+ const getProfilePicture = jest+ .fn()+ .mockResolvedValueOnce('https://pps/1.jpg')+ .mockRejectedValueOnce(new Error('no picture'))+ .mockResolvedValueOnce('https://pps/3.jpg');+ const out = await makeService({ getProfilePicture }).getProfilePictures('s1', ['[email protected]', '[email protected]', '[email protected]']);+ expect(out).toEqual({ '[email protected]': 'https://pps/1.jpg', '[email protected]': null, '[email protected]': 'https://pps/3.jpg' });+ });++ it('ignores ids beyond the 50-id batch cap', async () => {+ const getProfilePicture = jest.fn().mockResolvedValue(null);+ const ids = Array.from({ length: 60 }, (_, i) => `${i}@c.us`);+ const out = await makeService({ getProfilePicture }).getProfilePictures('s1', ids);+ expect(Object.keys(out)).toHaveLength(50);+ expect(getProfilePicture).toHaveBeenCalledTimes(50);+ });++ it('runs batch lookups at most 3 concurrently', async () => {+ let active = 0;+ let maxActive = 0;+ const getProfilePicture = jest.fn().mockImplementation(async () => {+ active += 1;+ maxActive = Math.max(maxActive, active);+ await new Promise(r => setImmediate(r));+ active -= 1;+ return null;+ });+ const ids = Array.from({ length: 9 }, (_, i) => `${i}@c.us`);+ await makeService({ getProfilePicture }).getProfilePictures('s1', ids);+ expect(maxActive).toBeLessThanOrEqual(3);+ });});diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex a45323b97..2e8774e69 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -51,6 +51,38 @@ export class ContactService {return this.getEngine(sessionId).getProfilePicture(contactId);}+ /** Upper bound for one batch call — keeps a huge `ids` list from pinning the engine for minutes. */+ private static readonly PROFILE_PICTURES_MAX_IDS = 50;++ /**+ * Batch-resolve profile picture URLs for a list of contact ids (the dashboard's chat-list avatars+ * — one HTTP call instead of N, so the per-IP throttle isn't exhausted by a sidebar full of+ * parallel fetches). Engine lookups run 3 at a time; a per-id failure yields null for that id+ * (hidden/no picture), never aborts the batch. Ids beyond PROFILE_PICTURES_MAX_IDS are ignored.+ */+ async getProfilePictures(sessionId: string, ids: string[]): Promise<Record<string, string | null>> {+ const engine = this.getEngine(sessionId);+ const capped = ids.slice(0, ContactService.PROFILE_PICTURES_MAX_IDS);+ const pictures: Record<string, string | null> = {};+ const CHUNK = 3;+ for (let i = 0; i < capped.length; i += CHUNK) {+ const chunk = capped.slice(i, i + CHUNK);+ const results = await Promise.all(+ chunk.map(async (id): Promise<readonly [string, string | null]> => {+ try {+ return [id, await engine.getProfilePicture(id)] as const;+ } catch {+ return [id, null] as const;+ }+ }),+ );+ for (const [id, url] of results) {+ pictures[id] = url;+ }+ }+ return pictures;+ }+blockContact(sessionId: string, contactId: string) {return this.getEngine(sessionId).blockContact(contactId);}