Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): abort unmounted media previews

Yudhi Armyndharisbd21df798cdd
diff --git a/dashboard/src/components/chats/ArchivedMediaPreview.test.ts b/dashboard/src/components/chats/ArchivedMediaPreview.test.ts
index 9e1474f79..5823771c4 100644
--- a/dashboard/src/components/chats/ArchivedMediaPreview.test.ts
+++ b/dashboard/src/components/chats/ArchivedMediaPreview.test.ts
@@ -114,3 +114,22 @@ test('a response landing after unmount makes no object URL', async () => {
await new Promise(r => setTimeout(r, 0));
assert.deepEqual(created, [], 'a late response must not leak a URL nothing will revoke');
});
+
+test('unmount aborts an archived media request still waiting for its bytes', async () => {
+ let signal: AbortSignal | undefined;
+ const { unmount } = rtl.render(
+ createElement(ArchivedMediaPreview, {
+ kind: 'image',
+ fallback,
+ load: received => {
+ signal = received;
+ return new Promise<Blob>(() => undefined);
+ },
+ }),
+ );
+ await rtl.waitFor(() => assert.ok(signal, 'the loader did not receive an abort signal'));
+ assert.equal(signal!.aborted, false);
+ unmount();
+ assert.equal(signal!.aborted, true);
+ assert.deepEqual(created, []);
+});
diff --git a/dashboard/src/components/chats/ArchivedMediaPreview.tsx b/dashboard/src/components/chats/ArchivedMediaPreview.tsx
index ec735d1a3..a58410cbd 100644
--- a/dashboard/src/components/chats/ArchivedMediaPreview.tsx
+++ b/dashboard/src/components/chats/ArchivedMediaPreview.tsx
@@ -7,7 +7,7 @@ export type ArchivedMediaKind = 'image' | 'video' | 'audio';
interface ArchivedMediaPreviewProps {
kind: ArchivedMediaKind;
/** Fetches the archived bytes (the per-message media route). Called at most once per mount. */
- load: () => Promise<Blob>;
+ load: (signal: AbortSignal) => Promise<Blob>;
alt?: string;
/** Rendered instead of the preview when the fetch fails, the download button, so the bytes stay reachable. */
fallback: ReactNode;
@@ -76,8 +76,9 @@ function ArchivedMediaPreview({ kind, load, alt, fallback, measureMedia, onMedia
useEffect(() => {
if (state.phase !== 'loading') return undefined;
let cancelled = false;
+ const controller = new AbortController();
loadRef
- .current()
+ .current(controller.signal)
.then(blob => {
if (cancelled) return;
const url = URL.createObjectURL(blob);
@@ -89,6 +90,7 @@ function ArchivedMediaPreview({ kind, load, alt, fallback, measureMedia, onMedia
});
return () => {
cancelled = true;
+ controller.abort();
};
}, [state.phase]);
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsx
index 01300639c..87bfab15e 100644
--- a/dashboard/src/components/chats/ChatThread.tsx
+++ b/dashboard/src/components/chats/ChatThread.tsx
@@ -352,7 +352,7 @@ function ChatThread({
<ArchivedMediaPreview
key={`${sessionId}:${activeChat.id}:${waMessageId}`}
kind={previewKind}
- load={() => sessionApi.getMessageMediaBlob(sessionId, activeChat.id, waMessageId)}
+ load={signal => sessionApi.getMessageMediaBlob(sessionId, activeChat.id, waMessageId, signal)}
alt={mediaInfo.filename || t('chats.media.image')}
fallback={downloadButton}
measureMedia={measureMedia}
diff --git a/dashboard/src/services/api.test.ts b/dashboard/src/services/api.test.ts
index 33a859bbe..55a1842a9 100644
--- a/dashboard/src/services/api.test.ts
+++ b/dashboard/src/services/api.test.ts
@@ -69,6 +69,36 @@ test('a role 403 keeps the key and rejects with the status', async () => {
assert.deepEqual(navigations, []);
});
+test('archived media forwards cancellation through fetch and the response body', async () => {
+ const controller = new AbortController();
+ let requested: string | undefined;
+ let options: RequestInit | undefined;
+ let reading = false;
+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
+ requested = String(input);
+ options = init;
+ return Promise.resolve({
+ ok: true,
+ blob: () => {
+ reading = true;
+ return new Promise<Blob>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), {
+ once: true,
+ });
+ });
+ },
+ } as Response);
+ }) as typeof fetch;
+ const bytes = sessionApi.getMessageMediaBlob('s1', '[email protected]', 'WA1', controller.signal);
+ await new Promise(resolve => setImmediate(resolve));
+ assert.ok(reading);
+ assert.ok(requested?.endsWith('/sessions/s1/messages/100%40c.us/WA1/media'));
+ assert.equal((options?.headers as Record<string, string>)['X-API-Key'], 'stored-key');
+ assert.equal(options?.signal, controller.signal);
+ controller.abort();
+ await assert.rejects(bytes, { name: 'AbortError' });
+});
+
test('the contact list walks past the 1000 contacts one response carries', async () => {
const { contactApi } = await import('./api.ts');
const requested: string[] = [];
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 5cd8af24b..d00b2a3e4 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -809,7 +809,7 @@ async function requestText(endpoint: string): Promise<string> {
}
/** Like {@link request} but returns a Blob — e.g. for status media downloads. */
-async function requestBlob(endpoint: string): Promise<Blob> {
+async function requestBlob(endpoint: string, signal?: AbortSignal): Promise<Blob> {
const url = `${API_BASE_URL}${endpoint}`;
// Get API key from sessionStorage for authentication
@@ -819,7 +819,7 @@ async function requestBlob(endpoint: string): Promise<Blob> {
...(apiKey ? { 'X-API-Key': apiKey } : {}),
};
- const response = await fetch(url, { headers });
+ const response = await fetch(url, { headers, signal });
if (!response.ok) {
return handleErrorResponse<Blob>(response);
@@ -898,8 +898,11 @@ export const sessionApi = {
// MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES; past that budget the payload arrives as the
// `{ omitted: true, sizeBytes }` marker and the bytes are only reachable here. Served as an
// attachment (Content-Disposition), so callers download it rather than rendering it inline.
- getMessageMediaBlob: (id: string, chatId: string, messageId: string) =>
- requestBlob(`/sessions/${id}/messages/${encodeURIComponent(chatId)}/${encodeURIComponent(messageId)}/media`),
+ getMessageMediaBlob: (id: string, chatId: string, messageId: string, signal?: AbortSignal) =>
+ requestBlob(
+ `/sessions/${id}/messages/${encodeURIComponent(chatId)}/${encodeURIComponent(messageId)}/media`,
+ signal,
+ ),
getSubscribedChannels: (id: string) => request<Channel[]>(`/sessions/${id}/channels`),
getChannelMessages: (id: string, channelId: string, limit = 50) =>
request<ChannelMessage[]>(`/sessions/${id}/channels/${encodeURIComponent(channelId)}/messages?limit=${limit}`),