Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): fetch the media a message list did not inline

Yudhi Armyndharisc7a20b181845
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98ca50bc7..c5e1b7e9b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,7 +52,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The three group-picture routes now refuse an id that does not name a group. They reuse the account's own profile-picture primitives, and Baileys omits the `target` attribute whenever the jid is the account's own — so `PUT` or `DELETE /sessions/:id/groups/<own-jid>/picture` replaced or permanently deleted the WhatsApp account's own avatar and answered `{success: true}`, while whatsapp-web.js refused the same input with a 404. Both engines now reject it with a 400 before the id reaches either adapter. The published responses were corrected to match: the 404 no longer claims the 1:1-chat case the 400 now owns, and `PUT` documents the new 400 alongside its existing ones.
-- `GET /sessions/:sessionId/messages` and the MCP `MessageList` tool now bound the inline media they return, via `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default). The row count was clamped to 1..100, but a row is not a bounded object: each carries its base64 in `metadata.media.data`, so a hundred media rows serialised to well over a hundred megabytes, and a large enough page pushed `JSON.stringify` past its ceiling and failed the read outright — permanently for the dashboard, which requests the maximum page size with no way to ask for less. The budget is spent newest-first; past it a payload is replaced with the `{ omitted: true, sizeBytes }` marker the engine already emits for skipped inbound media, and remains fetchable from the per-message media route. In the dashboard a trimmed message shows the same 📎 Media placeholder it already uses for media the engine skipped on the way in, and `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` raises the budget for a deployment that would rather pay the bytes. The knob is checked at boot like its export-side sibling — `8MiB` would otherwise parse to 8 bytes and omit everything — and is forwarded by both compose files. The newest payload is always let through even when it alone exceeds the budget: omitting it left a single large photo or video permanently unreadable through this route, since the dashboard thread has no other media source and caches with `staleTime: Infinity`. A budget of 0 still means "do not inline" and grants no allowance.
+- `GET /sessions/:sessionId/messages` and the MCP `MessageList` tool now bound the inline media they return, via `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default). The row count was clamped to 1..100, but a row is not a bounded object: each carries its base64 in `metadata.media.data`, so a hundred media rows serialised to well over a hundred megabytes, and a large enough page pushed `JSON.stringify` past its ceiling and failed the read outright — permanently for the dashboard, which requests the maximum page size with no way to ask for less. The budget is spent newest-first; past it a payload is replaced with the `{ omitted: true, sizeBytes }` marker the engine already emits for skipped inbound media, and remains fetchable from the per-message media route. In the dashboard a trimmed message shows the same 📎 Media placeholder it already uses for media the engine skipped on the way in, and that placeholder now downloads the media when clicked — the thread requests the largest page size and caches it with `staleTime: Infinity`, so without a fetch of its own the marker was terminal and an older attachment in a media-heavy chat had no route to it at all. `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` raises the budget for a deployment that would rather pay the bytes. The knob is checked at boot like its export-side sibling — `8MiB` would otherwise parse to 8 bytes and omit everything — and is forwarded by both compose files. The newest payload is always let through even when it alone exceeds the budget: omitting it left a single large photo or video permanently unreadable through this route, since the dashboard thread has no other media source and caches with `staleTime: Infinity`. A budget of 0 still means "do not inline" and grants no allowance.
- Bulk send now caps its rendered result at `TEMPLATE_RENDER_MAX_CHARS` (default 64 KiB), the same limit the single-send template path already enforced. `content.text` is length-validated before substitution, so caller-supplied variables inflated each item without bound while the request body stayed far below the in-flight body budget — a few hundred KiB of variables became hundreds of megabytes of heap per item, then went to the engine and the `messages.body` column. An over-cap render now fails that item with a message naming the limit, exactly as a pacing refusal does, rather than being truncated silently or sent.
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsx
index 0391bec00..1e6cff0b6 100644
--- a/dashboard/src/components/chats/ChatThread.tsx
+++ b/dashboard/src/components/chats/ChatThread.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useState, type RefObject } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, CornerUpLeft, Loader2, MessageSquare, Smile, Trash2 } from 'lucide-react';
-import type { Chat } from '../../services/api';
+import { sessionApi, type Chat } from '../../services/api';
import { getMediaSrc, senderKey, type ChatMessageView } from '../../utils/chatMessages';
import MessageBody from './MessageBody';
@@ -16,6 +16,8 @@ const senderColor = (name: string): string => {
};
interface ChatThreadProps {
+ /** Needed to fetch a message's media on demand; null before a session is chosen. */
+ sessionId: string | null;
activeChat: Chat;
messages: ChatMessageView[];
loadingMessages: boolean;
@@ -33,6 +35,7 @@ interface ChatThreadProps {
// scroll-position hook (its containerRef is handed down); reply/react/delete/lightbox intents go
// back up as callbacks.
function ChatThread({
+ sessionId,
activeChat,
messages,
loadingMessages,
@@ -46,6 +49,39 @@ function ChatThread({
}: ChatThreadProps) {
const { t } = useTranslation();
+ // Media the message list did not inline. The route serves the bytes as an attachment
+ // (Content-Disposition), and the list only carries payloads up to
+ // MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES — past that a row arrives as `{ omitted: true }`. Without
+ // this fetch the placeholder is terminal: this thread requests the largest page size and caches it
+ // with staleTime Infinity, so an older attachment in a media-heavy chat has no other route to it.
+ const [mediaFetch, setMediaFetch] = useState<{ id: string; state: 'loading' | 'failed' } | null>(null);
+ const downloadMedia = useCallback(
+ async (message: ChatMessageView) => {
+ const messageId = message.waMessageId;
+ if (!sessionId || !messageId) return;
+ setMediaFetch({ id: messageId, state: 'loading' });
+ let objectUrl: string | null = null;
+ try {
+ const blob = await sessionApi.getMessageMediaBlob(sessionId, activeChat.id, messageId);
+ objectUrl = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = objectUrl;
+ // The stored filename when there is one; the message id is a unique fallback that keeps two
+ // downloads from the same thread apart.
+ link.download = message.metadata?.media?.filename || messageId;
+ link.click();
+ setMediaFetch(null);
+ } catch {
+ // 404 covers every "there are no bytes" case the route documents (URL-based send, media
+ // download disabled, over the inbound cap). Say so on the bubble rather than failing mutely.
+ setMediaFetch({ id: messageId, state: 'failed' });
+ } finally {
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ }
+ },
+ [sessionId, activeChat.id],
+ );
+
// Scroll-to-bottom button visibility. The main scroll-position memory is owned by
// useChatScrollPosition, which doesn't expose its pin state (intentionally — that would re-render
// the whole room on every scroll). This small listener tracks only the boolean "user is far from
@@ -171,7 +207,23 @@ function ChatThread({
}
if (!mediaInfo) return null;
if (mediaInfo.omitted) {
- return <div className="message-media-omitted">📎 {t('chats.media.omitted')}</div>;
+ // Not a plain label: the bytes exist behind the per-message media route, so this is the
+ // only handle the viewer has on them.
+ const fetchState = mediaFetch && mediaFetch.id === msg.waMessageId ? mediaFetch.state : null;
+ return (
+ <button
+ type="button"
+ className="message-media-omitted"
+ onClick={() => void downloadMedia(msg)}
+ disabled={!sessionId || !msg.waMessageId || fetchState === 'loading'}
+ >
+ {fetchState === 'loading' ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ <>📎 {t(fetchState === 'failed' ? 'chats.status.mediaUnavailable' : 'chats.media.omitted')}</>
+ )}
+ </button>
+ );
}
const mediaSrc = getMediaSrc(mediaInfo);
if (!mediaSrc) return null;
diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.css
index 039c53d2e..d6aaf0735 100644
--- a/dashboard/src/pages/Chats.css
+++ b/dashboard/src/pages/Chats.css
@@ -895,11 +895,28 @@
object-fit: cover;
}
+/* A button, not a label: the bytes are fetchable from the per-message media route, so this is the
+ viewer's handle on media the list did not inline. Styled to keep the previous inert appearance
+ apart from the affordance. */
.chats-page .message-media-omitted {
+ display: flex;
+ align-items: center;
+ gap: 0.3rem;
+ padding: 0;
+ border: none;
+ background: none;
color: var(--text-muted);
font-style: italic;
font-size: 0.9em;
+ font-family: inherit;
margin-bottom: 0.25rem;
+ cursor: pointer;
+ text-decoration: underline dotted;
+}
+
+.chats-page .message-media-omitted:disabled {
+ cursor: default;
+ text-decoration: none;
}
.chats-page .chat-video-media {
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 2b3b4df24..1f34822d5 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -66,6 +66,29 @@ const DB_MESSAGE: ChatMessage = {
createdAt: new Date(1_700_000_000_000).toISOString(),
};
+// A row whose media the server did not inline: past MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES the
+// message list replaces the payload with this marker, so the bubble has no bytes to render and the
+// per-message media route is the only way to reach them.
+const OMITTED_MEDIA_MESSAGE: ChatMessage = {
+ id: 'db-2',
+ waMessageId: 'wamid.2',
+ chatId: CHAT.id,
+ from: CHAT.id,
+ to: 'me',
+ body: '',
+ type: 'image',
+ direction: 'incoming',
+ status: 'delivered',
+ timestamp: 1_700_000_001,
+ createdAt: new Date(1_700_000_001_000).toISOString(),
+ metadata: { media: { mimetype: 'image/jpeg', filename: 'photo.jpg', omitted: true, sizeBytes: 9_000_000 } },
+};
+
+/** The per-message media route the omitted marker sends the viewer to. */
+const MEDIA_PATH = `/api/sessions/${SESSION.id}/messages/${encodeURIComponent(CHAT.id)}/${encodeURIComponent(
+ OMITTED_MEDIA_MESSAGE.waMessageId as string,
+)}/media`;
+
// Contact for the status-compose recipient picker (Baileys requires an explicit allow-list).
const CONTACT = { id: '[email protected]', name: 'Bob', number: '15550002222' };
const STATUS_TEXT = 'status text here';
@@ -136,7 +159,11 @@ function installFetchStub(): void {
return Promise.resolve(jsonResponse([CONTACT]));
}
if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/messages?`)) {
- return Promise.resolve(jsonResponse({ messages: [DB_MESSAGE], total: 1 }));
+ return Promise.resolve(jsonResponse({ messages: [DB_MESSAGE, OMITTED_MEDIA_MESSAGE], total: 2 }));
+ }
+ // The media route answers bytes, not JSON — Content-Disposition: attachment.
+ if (method === 'GET' && path === MEDIA_PATH) {
+ return Promise.resolve(new Response(new Blob(['jpeg-bytes']), { status: 200 }));
}
if (method === 'GET' && /\/messages\/[^/]+\/history/.test(path)) {
return Promise.resolve(jsonResponse([]));
@@ -370,3 +397,43 @@ test('a staged attachment is dropped when a different chat is opened', async ()
"Alice's attachment followed the user into Carol's room",
);
});
+
+/**
+ * The server-side inline-media budget replaces an over-budget payload with `{ omitted: true }`. This
+ * thread requests the largest page size and caches it with staleTime Infinity, so without a fetch of
+ * its own the marker is terminal — the bytes exist on the server and the viewer cannot reach them.
+ * Asserting the WIRE call, not the label: a placeholder that merely looks clickable would pass a
+ * DOM-only check.
+ */
+test('an omitted media bubble fetches the bytes from the per-message media route', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+
+ // jsdom implements neither, and the component uses both to hand the blob to a download link.
+ const createdUrls: string[] = [];
+ const revokedUrls: string[] = [];
+ URL.createObjectURL = (): string => {
+ const url = `blob:mock-${createdUrls.length}`;
+ createdUrls.push(url);
+ return url;
+ };
+ URL.revokeObjectURL = (url: string): void => void revokedUrls.push(url);
+
+ const { container } = renderChats();
+ fireEvent.click(await screen.findByText('Alice'));
+ const thread = container.querySelector('.room-messages') as HTMLElement;
+
+ const placeholder = (await within(thread).findByRole('button', { name: /Media/ })) as HTMLButtonElement;
+ assert.equal(countFetchCalls('GET', MEDIA_PATH), 0, 'the media route must not be hit until asked');
+
+ fireEvent.click(placeholder);
+
+ await waitFor(() => {
+ assert.equal(countFetchCalls('GET', MEDIA_PATH), 1, 'expected one GET to the per-message media route');
+ });
+ // The object URL is released once the download is handed off, so browsing a media-heavy thread
+ // does not accumulate blobs.
+ await waitFor(() => {
+ assert.deepEqual(revokedUrls, createdUrls, 'every object URL created must be revoked');
+ });
+});
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 0d0c75782..fd93e689a 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -900,6 +900,7 @@ export function Chats() {
{/* Messages body (list, media, reactions, scroll-to-bottom) — components/chats/ChatThread. */}
<ChatThread
+ sessionId={selectedSessionId}
activeChat={activeChat}
messages={messages}
loadingMessages={loadingMessages}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index ababf8575..b7cce8b3d 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -767,6 +767,12 @@ export const sessionApi = {
includeMedia ? '&includeMedia=true' : ''
}`,
),
+ // A message's stored media, fetched on demand. The message list carries its media inline only up to
+ // 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`),
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}`),