Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep the held pictures across a page remount

Yudhi Armyndharis85e7eb65aeb0
diff --git a/dashboard/src/hooks/useProfilePictures.test.ts b/dashboard/src/hooks/useProfilePictures.test.ts
index e5b8cae93..6fb56c2e8 100644
--- a/dashboard/src/hooks/useProfilePictures.test.ts
+++ b/dashboard/src/hooks/useProfilePictures.test.ts
@@ -73,9 +73,9 @@ interface Props {
ids: string[];
}
-function renderPictures(sessionId: string | undefined, ids: string[]) {
- const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
- clients.push(client);
+function renderPictures(sessionId: string | undefined, ids: string[], existing?: QueryClient) {
+ const client = existing ?? new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
+ if (!existing) clients.push(client);
const wrapper = ({ children }: { children: ReactNode }) => createElement(QueryClientProvider, { client }, children);
return rtl.renderHook(({ sessionId, ids }: Props) => useProfilePictures(sessionId, ids), {
wrapper,
@@ -325,6 +325,48 @@ test('an invalidated batch asks again for every id it holds, so a changed pictur
]);
});
+test('a page that mounts again with the same ids reads the pictures from the cache and asks for nothing', async () => {
+ const first = renderPictures('s1', ['a', 'b', 'c']);
+ await rtl.waitFor(() => assert.equal(Object.keys(first.result.current.data ?? {}).length, 3));
+ const client = clients[clients.length - 1];
+ first.unmount();
+
+ const second = renderPictures('s1', ['a', 'b', 'c'], client);
+ await rtl.waitFor(() => assert.equal(Object.keys(second.result.current.data ?? {}).length, 3));
+ await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(requests.length, 1, 'a second mount asked for pictures the cache already held');
+ assert.equal(second.result.current.isStale, false);
+ assert.equal(second.result.current.data?.a, urlFor('s1', 'a'));
+});
+
+test('a page that mounts again with one more id asks for that id alone', async () => {
+ const first = renderPictures('s1', ['a', 'b', 'c']);
+ await rtl.waitFor(() => assert.equal(Object.keys(first.result.current.data ?? {}).length, 3));
+ const client = clients[clients.length - 1];
+ first.unmount();
+
+ const second = renderPictures('s1', ['b', 'c', 'd'], client);
+ await rtl.waitFor(() => assert.equal(second.result.current.data?.d, urlFor('s1', 'd')));
+ assert.deepEqual(asked(), [['a', 'b', 'c'], ['d']]);
+});
+
+test('signing out drops the held pictures, so the next actor is shown none of them', async () => {
+ const first = renderPictures('s1', ['a', 'b']);
+ await rtl.waitFor(() => assert.equal(Object.keys(first.result.current.data ?? {}).length, 2));
+ const client = clients[clients.length - 1];
+ first.unmount();
+ // What the dashboard does on logout (clearActorState).
+ client.clear();
+
+ const second = renderPictures('s1', ['a', 'b'], client);
+ await rtl.waitFor(() => assert.equal(requests.length, 2));
+ assert.deepEqual(asked(), [
+ ['a', 'b'],
+ ['a', 'b'],
+ ]);
+ await rtl.waitFor(() => assert.equal(Object.keys(second.result.current.data ?? {}).length, 2));
+});
+
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.ts
index d7cb5b7b5..92f107340 100644
--- a/dashboard/src/hooks/useProfilePictures.ts
+++ b/dashboard/src/hooks/useProfilePictures.ts
@@ -1,5 +1,4 @@
-import { useRef } from 'react';
-import { useQuery } from '@tanstack/react-query';
+import { useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query';
import { contactApi } from '../services/api';
// Signed CDN URLs rotate: a held picture is reused for an hour, then asked for again.
@@ -10,6 +9,24 @@ interface ResolvedPicture {
at: number;
}
+type Held = Map<string, ResolvedPicture>;
+
+// What each session's batches were told, with the time it arrived. It is kept in the query cache, beside the data
+// of the batches it came with, and not with the page: a page that mounts again finds it instead of asking for every
+// picture once more, and signing out, which clears the cache, drops it. Nothing collects it on its own, as it is
+// small and its entries age out by their own clock.
+const HELD_KEY = 'profilePicturesHeld';
+const heldKey = (sessionId: string) => [HELD_KEY, sessionId] as const;
+function heldFor(client: QueryClient, sessionId: string): Held {
+ client.setQueryDefaults([HELD_KEY], { gcTime: Infinity });
+ let held = client.getQueryData<Held>(heldKey(sessionId));
+ if (!held) {
+ held = new Map();
+ client.setQueryData(heldKey(sessionId), held);
+ }
+ return held;
+}
+
/**
* 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
@@ -21,7 +38,8 @@ interface ResolvedPicture {
*
* A change of membership (a message from a chat outside the top 50 pushes one out) is a new key, but
* 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
+ * ids that came back null (hidden or no picture) included, and reused for an hour. What is held lives
+ * in the query cache, so a page that mounts again with the same ids asks for nothing. 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. An invalidated batch (a
* picture was changed) asks for every id again, held or not.
@@ -30,16 +48,13 @@ interface ResolvedPicture {
* id that comes back null just keeps the icon fallback.
*/
export function useProfilePictures(sessionId: string | undefined, contactIds: string[]) {
- // Kept with the page, not in a module: signing out unmounts it and drops every picture, and a session's
- // are never offered to another.
- const resolvedRef = useRef(new Map<string, Map<string, ResolvedPicture>>());
+ const queryClient = useQueryClient();
const requestIds = contactIds.slice(0, 50); // list order: the visible top rows win the cap
const sortedKey = [...requestIds].sort().join(',');
return useQuery<Record<string, string | null>, Error>({
queryKey: ['profilePictures', sessionId, sortedKey] as const,
queryFn: async ({ client, queryKey }) => {
- const held = resolvedRef.current.get(sessionId!) ?? new Map<string, ResolvedPicture>();
- resolvedRef.current.set(sessionId!, held);
+ const held = heldFor(client, sessionId!);
const view = () => {
const pictures: Record<string, string | null> = {};
for (const id of requestIds) {
@@ -74,7 +89,7 @@ export function useProfilePictures(sessionId: string | undefined, contactIds: st
// failed top-up) or an expired one makes the query stale at once, so the next focus or mount asks again
// for just those, instead of a failed attempt counting as a fresh hour.
staleTime: query => {
- const held = sessionId ? resolvedRef.current.get(sessionId) : undefined;
+ const held = sessionId ? queryClient.getQueryData<Held>(heldKey(sessionId)) : undefined;
let expiresAt = Infinity;
for (const id of requestIds) {
const entry = held?.get(id);