Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): refresh the sidebar picture after a group picture change
Yudhi Armyndharisce52836c8d77
diff --git a/dashboard/src/hooks/useProfilePictures.test.ts b/dashboard/src/hooks/useProfilePictures.test.tsindex be0773cf0..e5b8cae93 100644--- a/dashboard/src/hooks/useProfilePictures.test.ts+++ b/dashboard/src/hooks/useProfilePictures.test.ts@@ -311,6 +311,20 @@ test('a first batch that fails reports the error', async () => {assert.equal(result.current.data, undefined);});+test('an invalidated batch asks again for every id it holds, so a changed picture shows', async () => {+ const { result } = renderPictures('s1', ['a', 'b']);+ await rtl.waitFor(() => assert.equal(Object.keys(result.current.data ?? {}).length, 2));++ answer = (sessionId, ids) =>+ Promise.resolve(json({ pictures: Object.fromEntries(ids.map(id => [id, `${urlFor(sessionId, id)}?v=2`])) }));+ await rtl.act(() => clients[clients.length - 1].invalidateQueries({ queryKey: ['profilePictures', 's1'] }));+ await rtl.waitFor(() => assert.equal(result.current.data?.b, `${urlFor('s1', 'b')}?v=2`));+ assert.deepEqual(asked(), [+ ['a', 'b'],+ ['a', 'b'],+ ]);+});+test('asks for nothing without a session or without ids', async () => {const none = renderPictures(undefined, ['a']);const empty = renderPictures('s1', []);diff --git a/dashboard/src/hooks/useProfilePictures.ts b/dashboard/src/hooks/useProfilePictures.tsindex 1a753cbc0..d7cb5b7b5 100644--- a/dashboard/src/hooks/useProfilePictures.ts+++ b/dashboard/src/hooks/useProfilePictures.ts@@ -23,7 +23,8 @@ interface ResolvedPicture {* only the ids not held yet are asked for: every answer is kept per session with the time it arrived,* ids that came back null (hidden or no picture) included, and reused for an hour. The data returned* covers the requested ids, and the previous data of the same session stays while a smaller batch is- * out, so the rows keep their pictures instead of dropping to the generic icon.+ * out, so the rows keep their pictures instead of dropping to the generic icon. An invalidated batch (a+ * picture was changed) asks for every id again, held or not.** Caching mirrors useProfilePicture: 1h stale (signed CDN URLs rotate), 30min gc, no retry — an* id that comes back null just keeps the icon fallback.@@ -36,7 +37,7 @@ export function useProfilePictures(sessionId: string | undefined, contactIds: stconst sortedKey = [...requestIds].sort().join(',');return useQuery<Record<string, string | null>, Error>({queryKey: ['profilePictures', sessionId, sortedKey] as const,- queryFn: async () => {+ queryFn: async ({ client, queryKey }) => {const held = resolvedRef.current.get(sessionId!) ?? new Map<string, ResolvedPicture>();resolvedRef.current.set(sessionId!, held);const view = () => {@@ -48,9 +49,10 @@ export function useProfilePictures(sessionId: string | undefined, contactIds: streturn pictures;};const now = Date.now();+ const invalidated = client.getQueryState(queryKey)?.isInvalidated ?? false;const missing = requestIds.filter(id => {const entry = held.get(id);- return !entry || now - entry.at >= PICTURE_TTL_MS;+ return invalidated || !entry || now - entry.at >= PICTURE_TTL_MS;});if (missing.length > 0) {try {diff --git a/dashboard/src/pages/Chats.features.test.ts b/dashboard/src/pages/Chats.features.test.tsindex 3c8db51b4..334a463b4 100644--- a/dashboard/src/pages/Chats.features.test.ts+++ b/dashboard/src/pages/Chats.features.test.ts@@ -33,6 +33,8 @@ function hold(name: string): () => void {// When true, the chat and contact writes answer HTTP 200 with `{ success: false }`, as an engine that// declined to act does.let declineWrites = false;+// The profile pictures the batch route serves, by chat id; an id with none answers null.+const pictureFor: Record<string, string> = {};const CHAT: Chat = {id: '[email protected]',@@ -174,7 +176,12 @@ function installFetchStub(): void {return Promise.resolve(jsonResponse({ success: true, message: 'ok' }));}if (method === 'GET' && path.startsWith(`${base}/contacts/profile-pictures`)) {- return Promise.resolve(jsonResponse({ pictures: {} }));+ const ids = decodeURIComponent(path.split('ids=')[1] ?? '')+ .split(',')+ .filter(Boolean);+ return Promise.resolve(+ jsonResponse({ pictures: Object.fromEntries(ids.map(id => [id, pictureFor[id] ?? null])) }),+ );}if (method === 'GET' && /\/contacts\/[^/]+\/profile-picture$/.test(path)) {return Promise.resolve(jsonResponse({ url: null }));@@ -241,6 +248,7 @@ afterEach(async () => {listExtra = false;listDuplicateContact = false;declineWrites = false;+ for (const id of Object.keys(pictureFor)) delete pictureFor[id];gates.clear();listGroup = false;groupAdmin = true;@@ -425,6 +433,42 @@ test('the group dialog saves a new name through the subject route and renames thassert.ok(within(dialog).getByRole('button', { name: 'Remove: Bob' }), 'an admin was offered no member actions');});+test('a group picture saved in the group dialog replaces the one on the sidebar row', async () => {+ const { screen, fireEvent, waitFor, within } = rtl;+ const objectUrls = { create: URL.createObjectURL, revoke: URL.revokeObjectURL };+ URL.createObjectURL = () => 'blob:picked';+ URL.revokeObjectURL = () => undefined;+ try {+ listGroup = true;+ pictureFor[GROUP.id] = 'https://cdn.example/old.jpg';+ const { container } = renderPage();+ await screen.findByText('Team');+ const rowPicture = () =>+ within(container.querySelector('.chats-list') as HTMLElement)+ .getByText('Team')+ .closest('.chat-item-card')+ ?.querySelector('img')+ ?.getAttribute('src');+ await waitFor(() => assert.equal(rowPicture(), 'https://cdn.example/old.jpg'));++ pickRowAction('Team', 'Group info');+ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByText(`Managed via ${SESSION.name}`);+ const file = new (window as unknown as { File: typeof File }).File(['x'], 'team.png', { type: 'image/png' });+ fireEvent.change(dialog.querySelector('input[type="file"]') as HTMLInputElement, { target: { files: [file] } });+ const save = within(dialog).getByRole('button', { name: 'Save changes' }) as HTMLButtonElement;+ await waitFor(() => assert.equal(save.disabled, false, 'the picked picture was not taken'));++ pictureFor[GROUP.id] = 'https://cdn.example/new.jpg';+ fireEvent.click(save);+ await waitFor(() => assert.ok(fetchCalls.some(c => c.method === 'PUT' && c.path.endsWith('/picture'))));+ await waitFor(() => assert.equal(rowPicture(), 'https://cdn.example/new.jpg', 'the row kept the old picture'));+ } finally {+ URL.createObjectURL = objectUrls.create;+ URL.revokeObjectURL = objectUrls.revoke;+ }+});+test('a participant the gateway refuses is reported although the write answered 200', async () => {const { screen, fireEvent, waitFor, within } = rtl;listGroup = true;