Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): scope the staged chat attachment to its conversation
Yudhi Armyndharisbd81916dc15f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dbb3b88f0..1a64d6cc1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed++- **12 `operationId` values in `openapi.json` were renamed.** `InfraController` was split into four+ controllers by resource — `InfraStatusController`, `InfraConfigController`, `InfraDataController`+ and `InfraStorageController` — and NestJS derives an operation's id from its controller class name,+ so every `/api/infra` operation is now `Infra<Resource>Controller_<method>` instead of+ `InfraController_<method>` (for example `InfraController_getStatus` →+ `InfraStatusController_getStatus`). 12 of the specification's 158 operations are affected, all of+ them under `/api/infra`.++ Nothing on the wire moved. The 129 paths, their HTTP methods, parameters, request bodies, response+ schemas, security requirements and the 68 component schemas are byte-identical to 0.12.3 — a client+ that calls the REST API by URL needs no change at all. The rename matters only if you generate a+ client from the specification and its generator names methods after `operationId`: those method+ names change, and the generated client has to be regenerated.++- **A file attached but not yet sent in Dashboard > Chats is now dropped when you open a different+ conversation.** Previously the staged file outlived the room it was picked in: attaching in one+ chat, going back, and opening another left the attachment sitting in the second chat's composer,+ where the next send would deliver it to the wrong recipient. It is now cleared as soon as another+ chat is opened, and cleared when the session is switched.++ Closing and reopening the *same* room still keeps it, so the round trip is lossless — the same+ guarantee the typed message draft already had. Both lifetimes are pinned by regression tests.+## [0.12.3] - 2026-08-01### Fixeddiff --git a/dashboard/src/components/chats/ChatComposer.tsx b/dashboard/src/components/chats/ChatComposer.tsxindex 8e388c543..a60245ef6 100644--- a/dashboard/src/components/chats/ChatComposer.tsx+++ b/dashboard/src/components/chats/ChatComposer.tsx@@ -19,6 +19,14 @@ const messageTypeFromMime = (mimetype: string): MessageType => {return 'document';};+/** A picked-but-unsent file, staged until send, removal, or a move to another chat. */+export interface StagedAttachment {+ file: File;+ base64: string;+ mimetype: string;+ filename: string;+}+interface ChatComposerProps {selectedSessionId: string;activeChat: Chat;@@ -28,12 +36,16 @@ interface ChatComposerProps {setChats: Dispatch<SetStateAction<Chat[]>>;messageInput: string;setMessageInput: Dispatch<SetStateAction<string>>;+ attachment: StagedAttachment | null;+ setAttachment: Dispatch<SetStateAction<StagedAttachment | null>>;+ previewUrl: string | null;+ setPreviewUrl: Dispatch<SetStateAction<string | null>>;}// The composer half of the chat room: attachment preview, emoji panel, reply banner, and the input// bar with the whole optimistic-send flow. `replyingTo` is shared with the thread (its reply action-// sets it), and `messageInput` lives in the page so a typed draft survives closing the room;-// everything else is local.+// sets it), and `messageInput` plus the staged attachment live in the page so a draft survives+// closing the room; everything else is local.function ChatComposer({selectedSessionId,activeChat,@@ -43,6 +55,10 @@ function ChatComposer({setChats,messageInput,setMessageInput,+ attachment,+ setAttachment,+ previewUrl,+ setPreviewUrl,}: ChatComposerProps) {const { t } = useTranslation();const { canWrite } = useRole();@@ -52,27 +68,20 @@ function ChatComposer({const [sending, setSending] = useState<boolean>(false);- // File attachments- const [attachment, setAttachment] = useState<{- file: File;- base64: string;- mimetype: string;- filename: string;- } | null>(null);- const [previewUrl, setPreviewUrl] = useState<string | null>(null);const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);// Monotonic token invalidating an in-flight attachment FileReader: picking a second file (or// removing the attachment) before `onload` fires must win over the late-arriving bytes —// otherwise the slower read overwrites the newer pick. Same pattern as composeImageReadSeq.const attachmentReadSeq = useRef(0);- // Unmounting with a read still in flight: invalidate the reader so its late- // onload handler drops the bytes instead of setting state on a dead component.+ // Leaving this conversation — switching to another chat, or unmounting when the room closes —+ // invalidates an in-flight read, so its late `onload` drops the bytes instead of staging them+ // against whichever chat is open by then. The attachment state itself lives in the page.useEffect(() => {return () => {attachmentReadSeq.current += 1;};- }, []);+ }, [activeChat.id]);// Referencesconst fileInputRef = useRef<HTMLInputElement | null>(null);@@ -99,15 +108,6 @@ function ChatComposer({'✨',];- // Revoke the object URL created for an image-attachment preview once it is replaced, cleared, or- // the component unmounts. The cleanup runs with the previous value on every change, so this single- // effect covers all paths (new file, remove, session switch) — otherwise each preview leaks a- // blob held for the lifetime of the document.- useEffect(() => {- if (!previewUrl) return;- return () => URL.revokeObjectURL(previewUrl);- }, [previewUrl]);-// 5. Handle file selection & base64 conversionconst handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0];diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 616668816..a1c76d890 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -39,6 +39,19 @@ const CHAT: Chat = {lastMessage: 'hello from alice',};+// A second conversation, so the attachment tests can distinguish "closed and reopened the SAME+// room" (staged file survives) from "moved to ANOTHER chat" (staged file is dropped). Named to+// avoid colliding with CONTACT below, which the status-compose test matches by name.+const CHAT_2: Chat = {+ id: '[email protected]',+ name: 'Carol',+ isGroup: false,+ kind: 'individual',+ unreadCount: 0,+ timestamp: 1_700_000_050,+ lastMessage: 'hello from carol',+};+const DB_MESSAGE: ChatMessage = {id: 'db-1',waMessageId: 'wamid.1',@@ -90,7 +103,6 @@ function countFetchCalls(method: string, path: string): number {// smoke flows below. Anything else gets a 404 so an unexpected request fails loudly in the test// output instead of resolving into a confusing downstream crash.function installFetchStub(): void {- const chatId = encodeURIComponent(CHAT.id);globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;const method = init?.method ?? 'GET';@@ -111,12 +123,13 @@ function installFetchStub(): void {return Promise.resolve(jsonResponse({ engineType: 'baileys' }));}if (method === 'GET' && path === `/api/sessions/${SESSION.id}/chats`) {- return Promise.resolve(jsonResponse([CHAT]));+ return Promise.resolve(jsonResponse([CHAT, CHAT_2]));}if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/contacts/profile-pictures`)) {return Promise.resolve(jsonResponse({ pictures: {} }));}- if (method === 'GET' && path === `/api/sessions/${SESSION.id}/contacts/${chatId}/profile-picture`) {+ // Matched for any chat id (both CHAT and CHAT_2 open in these tests), not just the first.+ if (method === 'GET' && /\/contacts\/[^/]+\/profile-picture$/.test(path)) {return Promise.resolve(jsonResponse({ url: null }));}if (method === 'GET' && path === `/api/sessions/${SESSION.id}/contacts`) {@@ -125,7 +138,7 @@ function installFetchStub(): void {if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/messages?`)) {return Promise.resolve(jsonResponse({ messages: [DB_MESSAGE], total: 1 }));}- if (method === 'GET' && path.startsWith(`/api/sessions/${SESSION.id}/messages/${chatId}/history`)) {+ if (method === 'GET' && /\/messages\/[^/]+\/history/.test(path)) {return Promise.resolve(jsonResponse([]));}if (method === 'GET' && path === `/api/sessions/${SESSION.id}/status`) {@@ -298,3 +311,62 @@ test('a typed draft survives closing and reopening the room', async () => {const input = screen.getByPlaceholderText('Type a message...') as HTMLInputElement;assert.equal(input.value, 'draft survives');});++// Stage a file in the open room and wait for the preview banner. A non-image type is used on+// purpose: the image branch calls URL.createObjectURL, which JSDOM does not implement.+//+// The File MUST come from the JSDOM window, not the bare `File` global: installJsdomGlobals only+// copies window properties that Node does not already define, so `Blob`/`File` stay Node's while+// `FileReader` is JSDOM's — and JSDOM's readAsDataURL brand-checks its argument against JSDOM's+// own Blob ("parameter 1 is not of type 'Blob'").+async function stageAttachment(container: HTMLElement, filename: string): Promise<void> {+ const { fireEvent, waitFor } = rtl;+ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;+ const file = new window.File(['%PDF-1.4 stub'], filename, { type: 'application/pdf' });+ fireEvent.change(fileInput, { target: { files: [file] } });+ // The bytes arrive through FileReader.onload, so the banner is asynchronous.+ await waitFor(() => {+ assert.ok(container.querySelector('.attachment-preview-banner'), 'attachment banner did not appear');+ });+}++test('a staged attachment survives closing and reopening the same room', async () => {+ const { screen, fireEvent, within } = rtl;+ resetFetchCalls();+ const { container } = renderChats();++ await screen.findByText('Main (15551234567)');+ fireEvent.click(await screen.findByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');+ await stageAttachment(container, 'contract.pdf');++ // Close the room: ChatComposer unmounts, so the file only survives because the page owns it.+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));+ assert.equal(container.querySelector('.attachment-preview-banner'), null);++ fireEvent.click(screen.getByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');+ assert.ok(container.querySelector('.attachment-preview-banner'), 'attachment was lost on reopen');+ assert.equal(container.querySelector('.preview-filename')?.textContent, 'contract.pdf');+});++test('a staged attachment is dropped when a different chat is opened', async () => {+ const { screen, fireEvent, within } = rtl;+ resetFetchCalls();+ const { container } = renderChats();++ await screen.findByText('Main (15551234567)');+ fireEvent.click(await screen.findByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');+ await stageAttachment(container, 'for-alice.pdf');++ // Move to another conversation without closing the room first. Carrying the file over would let+ // the next send deliver it to the wrong recipient, so it must be dropped.+ fireEvent.click(screen.getByText('Carol'));+ await within(container.querySelector('.room-header') as HTMLElement).findByText('Carol');+ assert.equal(+ container.querySelector('.attachment-preview-banner'),+ null,+ "Alice's attachment followed the user into Carol's room",+ );+});diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 72fd191b3..4bbdda347 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -51,7 +51,7 @@ import MediaLightbox, { type LightboxItem } from '../components/chats/MediaLightimport KindIcon from '../components/chats/KindIcon';import ChatSidebar from '../components/chats/ChatSidebar';import ChatThread from '../components/chats/ChatThread';-import ChatComposer from '../components/chats/ChatComposer';+import ChatComposer, { type StagedAttachment } from '../components/chats/ChatComposer';import StatusMedia from '../components/chats/StatusMedia';import StatusComposeModal from '../components/chats/StatusComposeModal';import './Chats.css';@@ -189,6 +189,37 @@ export function Chats() {const [replyingTo, setReplyingTo] = useState<ChatMessageView | null>(null);// Draft text lives here (not in ChatComposer) so it survives closing/switching the room.const [messageInput, setMessageInput] = useState<string>('');+ // The staged attachment lives here for the same reason the draft text does — ChatComposer+ // unmounts when the room closes, which would silently discard a picked file. Unlike the text+ // draft it is dropped when a DIFFERENT chat is opened (see the effect below): a file that+ // follows the user into another conversation can be sent to the wrong recipient.+ const [attachment, setAttachment] = useState<StagedAttachment | null>(null);+ const [previewUrl, setPreviewUrl] = useState<string | null>(null);++ // Revoke the object URL created for an image-attachment preview once it is replaced or cleared.+ // The cleanup runs with the previous value on every change, so this single effect covers all+ // paths (new file, remove, send, chat switch) — otherwise each preview leaks a blob held for the+ // lifetime of the document. It lives here, not in ChatComposer: revoking on the composer's+ // unmount would hand a reopened room a dead blob URL for an attachment that is still staged.+ useEffect(() => {+ if (!previewUrl) return;+ return () => URL.revokeObjectURL(previewUrl);+ }, [previewUrl]);++ // Drop a staged attachment when the user moves to a DIFFERENT chat. Closing the room+ // (`activeChat` → null) deliberately keeps it, so close/reopen is a lossless round trip; only an+ // actual change of conversation clears. The composer invalidates its in-flight FileReader on the+ // same transition, so a late read cannot re-stage the file against the new chat.+ const lastRoomIdRef = useRef<string | null>(null);+ useEffect(() => {+ const current = activeChat?.id ?? null;+ if (current === null) return;+ const previous = lastRoomIdRef.current;+ lastRoomIdRef.current = current;+ if (previous === null || previous === current) return;+ setAttachment(null);+ setPreviewUrl(null);+ }, [activeChat]);// Per-chat scroll-position memory + auto-scroll heuristic.// Pass `messages.length > 0` as the loaded signal: it stays stable once the@@ -268,8 +299,13 @@ export function Chats() {setActiveChat(null);setActiveChannel(null);setActiveStatusContactId(null);- // The composer unmounts with the closed room, dropping its attachment/preview state and- // running its own cleanups (object-URL revoke, FileReader invalidation).+ // A staged attachment belongs to a chat in the session being left, so it is dropped here+ // rather than carried across — the close/reopen round trip that preserves it is scoped to a+ // single session. Clearing previewUrl runs the revoke effect's cleanup; the composer+ // unmounts with the closed room and invalidates its own in-flight FileReader.+ setAttachment(null);+ setPreviewUrl(null);+ lastRoomIdRef.current = null;}}, [selectedSessionId, loadChats]);@@ -890,6 +926,10 @@ export function Chats() {setChats={setChats}messageInput={messageInput}setMessageInput={setMessageInput}+ attachment={attachment}+ setAttachment={setAttachment}+ previewUrl={previewUrl}+ setPreviewUrl={setPreviewUrl}/></div>) : activeChannel ? (diff --git a/dashboard/src/utils/restartPoll.test.ts b/dashboard/src/utils/restartPoll.test.tsindex f6d45e872..283b808aa 100644--- a/dashboard/src/utils/restartPoll.test.ts+++ b/dashboard/src/utils/restartPoll.test.ts@@ -18,7 +18,7 @@ test('an estimate the floor already covers does not shorten the deadline', () =>});test('a full-profile restart gets more room than the server estimated', () => {- // 15 base + 20 postgres + 13 redis + 15 minio — the worst case infra.controller computes.+ // 15 base + 20 postgres + 13 redis + 15 minio — the worst case infra-config.controller computes.assert.equal(restartPollAttempts(63), 126);});diff --git a/src/modules/plugins/plugins.controller.spec.ts b/src/modules/plugins/plugins.controller.spec.tsindex ebe943d92..ba5bb97ea 100644--- a/src/modules/plugins/plugins.controller.spec.ts+++ b/src/modules/plugins/plugins.controller.spec.ts@@ -7,7 +7,7 @@ describe('PluginsController authorization', () => {const reflector = new Reflector();// Plugin reads expose installed versions, non-secret config, and health/error text — privileged- // inventory on par with the ADMIN-gated write routes and the InfraController convention. A+ // inventory on par with the ADMIN-gated write routes and the infra controllers' convention. A// VIEWER/OPERATOR key (or a session-scoped key) must not be able to enumerate it via the raw API.const adminOnly = ['findAll',