Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): restore the chat draft lifetime and harden the smoke test
Yudhi Armyndharisf948eb63f9d9
diff --git a/dashboard/src/components/chats/ChatComposer.tsx b/dashboard/src/components/chats/ChatComposer.tsxindex b75c259b6..8e388c543 100644--- a/dashboard/src/components/chats/ChatComposer.tsx+++ b/dashboard/src/components/chats/ChatComposer.tsx@@ -26,11 +26,14 @@ interface ChatComposerProps {setReplyingTo: Dispatch<SetStateAction<ChatMessageView | null>>;onMessageAppended: (direction: ScrollDirection) => void;setChats: Dispatch<SetStateAction<Chat[]>>;+ messageInput: string;+ setMessageInput: Dispatch<SetStateAction<string>>;}// 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), so it lives in the page and is handed down; everything else is local.+// sets it), and `messageInput` lives in the page so a typed draft survives closing the room;+// everything else is local.function ChatComposer({selectedSessionId,activeChat,@@ -38,6 +41,8 @@ function ChatComposer({setReplyingTo,onMessageAppended,setChats,+ messageInput,+ setMessageInput,}: ChatComposerProps) {const { t } = useTranslation();const { canWrite } = useRole();@@ -45,7 +50,6 @@ function ChatComposer({const { appendMessage, updateMessage } = useChatMessagesActions();const queryClient = useQueryClient();- const [messageInput, setMessageInput] = useState<string>('');const [sending, setSending] = useState<boolean>(false);// File attachmentsdiff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex ebd3e83da..616668816 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -4,7 +4,8 @@// same providers App.tsx uses (QueryClientProvider → RoleProvider → ToastProvider; i18n via the// side-effect import; Chats uses no router hooks, so no Router is needed) and the backend is// stubbed at the fetch layer with canned JSON for every endpoint the page hits on mount,-// on chat open, and on send.+// on chat open, on send, and on status-compose. Every stubbed request is recorded so tests can+// assert the wire effect (POST body) of a UI action, not just its optimistic DOM echo.//// Runner constraints honored here: plain .ts with React.createElement (the runner cannot parse// JSX), loader hooks registered before any app-module import (see test-helpers/register-hooks),@@ -52,6 +53,10 @@ const DB_MESSAGE: ChatMessage = {createdAt: new Date(1_700_000_000_000).toISOString(),};+// 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';+function jsonResponse(data: unknown, status = 200): Response {return new Response(JSON.stringify(data), {status,@@ -59,8 +64,30 @@ function jsonResponse(data: unknown, status = 200): Response {});}+// Every request the stub serves is recorded (method, path, parsed JSON body) so tests can assert+// the WIRE effect of a UI action — an optimistic bubble alone would pass even if the POST broke.+interface FetchCall {+ method: string;+ path: string;+ body?: unknown;+}++const fetchCalls: FetchCall[] = [];++function resetFetchCalls(): void {+ fetchCalls.length = 0;+}++function findFetchCall(method: string, path: string): FetchCall | undefined {+ return fetchCalls.find(c => c.method === method && c.path === path);+}++function countFetchCalls(method: string, path: string): number {+ return fetchCalls.filter(c => c.method === method && c.path === path).length;+}+// URL router for every endpoint the page (and the hooks/components under it) can hit during the-// smoke flow below. Anything else gets a 404 so an unexpected request fails loudly in the test+// 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);@@ -69,6 +96,16 @@ function installFetchStub(): void {const method = init?.method ?? 'GET';const path = url.replace(/^https?:\/\/[^/]+/, '');+ let body: unknown;+ if (typeof init?.body === 'string') {+ try {+ body = JSON.parse(init.body);+ } catch {+ body = init.body;+ }+ }+ fetchCalls.push({ method, path, body });+if (method === 'GET' && path === '/api/sessions') return Promise.resolve(jsonResponse([SESSION]));if (method === 'GET' && path === '/api/infra/engines/current') {return Promise.resolve(jsonResponse({ engineType: 'baileys' }));@@ -82,18 +119,27 @@ function installFetchStub(): void {if (method === 'GET' && path === `/api/sessions/${SESSION.id}/contacts/${chatId}/profile-picture`) {return Promise.resolve(jsonResponse({ url: null }));}+ if (method === 'GET' && path === `/api/sessions/${SESSION.id}/contacts`) {+ return Promise.resolve(jsonResponse([CONTACT]));+ }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`)) {return Promise.resolve(jsonResponse([]));}+ if (method === 'GET' && path === `/api/sessions/${SESSION.id}/status`) {+ return Promise.resolve(jsonResponse({ statuses: [] }));+ }if (method === 'POST' && path === `/api/sessions/${SESSION.id}/chats/read`) {return Promise.resolve(jsonResponse({ success: true }));}if (method === 'POST' && path === `/api/sessions/${SESSION.id}/messages/send-text`) {return Promise.resolve(jsonResponse({ messageId: 'wamid.out.1', timestamp: 1_700_000_100 }));}+ if (method === 'POST' && path === `/api/sessions/${SESSION.id}/status/send-text`) {+ return Promise.resolve(jsonResponse({ success: true }));+ }return Promise.resolve(jsonResponse({ message: `unstubbed ${method} ${path}` }, 404));};}@@ -150,10 +196,11 @@ function renderChats(): { container: HTMLElement } {);}-// ── Smoke test ───────────────────────────────────────────────────────────────+// ── Smoke tests ──────────────────────────────────────────────────────────────test('Chats renders: session/chat list loads, a chat opens, and a message sends', async () => {- const { screen, fireEvent, within } = rtl;+ const { screen, fireEvent, within, waitFor } = rtl;+ resetFetchCalls();const { container } = renderChats();// Sidebar: the session selector shows the stubbed ready session, and the chat list row@@ -179,4 +226,75 @@ test('Chats renders: session/chat list loads, a chat opens, and a message sends'assert.equal(sendButton.disabled, false);fireEvent.click(sendButton);await within(thread).findByText('hello back');++ // The optimistic bubble alone would pass even if the POST never fired — assert the wire call.+ await waitFor(() => {+ const call = findFetchCall('POST', `/api/sessions/${SESSION.id}/messages/send-text`);+ assert.ok(call, 'expected a POST to the send-text endpoint');+ assert.deepEqual(call.body, { chatId: CHAT.id, text: 'hello back' });+ });+});++test('status compose modal posts a text status with the baileys recipient allow-list', async () => {+ const { screen, fireEvent, within, waitFor } = rtl;+ resetFetchCalls();+ renderChats();++ // The compose trigger lives in the sidebar's Status tab. The engine stub answers 'baileys',+ // so the modal enables its contacts query and requires an explicit recipient allow-list.+ await screen.findByText('Main (15551234567)');+ fireEvent.click(screen.getByRole('tab', { name: 'Status' }));+ fireEvent.click(screen.getByRole('button', { name: 'Post a status' }));++ const dialog = await screen.findByRole('dialog');+ // Text status body (the textarea's placeholder is chats.status.composeText).+ fireEvent.change(within(dialog).getByPlaceholderText('Text'), { target: { value: STATUS_TEXT } });+ // Pick the stubbed contact once the contacts query resolves.+ await within(dialog).findByText('Bob');+ fireEvent.click(within(dialog).getByRole('checkbox'));++ const postButton = within(dialog).getByRole('button', { name: 'Post' }) as HTMLButtonElement;+ assert.equal(postButton.disabled, false); // text + recipient + known engine → submittable+ fireEvent.click(postButton);++ // The wire call: POST status/send-text with the text and the selected allow-list+ // (backgroundColor/font are dropped from the body while unset).+ await waitFor(() => {+ const call = findFetchCall('POST', `/api/sessions/${SESSION.id}/status/send-text`);+ assert.ok(call, 'expected a POST to the status send-text endpoint');+ assert.deepEqual(call.body, { text: STATUS_TEXT, recipients: [CONTACT.id] });+ });++ // Success path: the modal closes and onPosted refetches the status list (one GET from the+ // tab switch, one from the refetch).+ await waitFor(() => assert.equal(screen.queryByRole('dialog'), null));+ await waitFor(() => {+ assert.ok(+ countFetchCalls('GET', `/api/sessions/${SESSION.id}/status`) >= 2,+ 'expected the status list to refetch after posting',+ );+ });+});++test('a typed draft survives closing and reopening the room', async () => {+ const { screen, fireEvent, within } = rtl;+ resetFetchCalls();+ const { container } = renderChats();++ // Open the chat and type (but do NOT send) a draft.+ await screen.findByText('Main (15551234567)');+ fireEvent.click(await screen.findByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');+ fireEvent.change(screen.getByPlaceholderText('Type a message...'), { target: { value: 'draft survives' } });++ // Close the room with the back button (aria-label = common.back); the composer unmounts.+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));+ assert.equal(screen.queryByRole('button', { name: 'Back' }), null);++ // Reopen the same chat (room closed → 'Alice' matches only the sidebar row): the draft must+ // still be in the input — the page owns messageInput precisely so it survives this round trip.+ fireEvent.click(screen.getByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');+ const input = screen.getByPlaceholderText('Type a message...') as HTMLInputElement;+ assert.equal(input.value, 'draft survives');});diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 4d6b88dac..72fd191b3 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -187,6 +187,8 @@ export function Chats() {const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);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>('');// Per-chat scroll-position memory + auto-scroll heuristic.// Pass `messages.length > 0` as the loaded signal: it stays stable once the@@ -886,6 +888,8 @@ export function Chats() {setReplyingTo={setReplyingTo}onMessageAppended={onMessageAppended}setChats={setChats}+ messageInput={messageInput}+ setMessageInput={setMessageInput}/></div>) : activeChannel ? (diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex cac4cecca..030f64031 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -144,13 +144,7 @@ export { extractLinkedParentJID } from './wwebjs-groups';// Messaging helpers moved to ./wwebjs-messaging with the messaging operations; re-exported because// existing callers (the adapter spec) still import them from here.-export {- isHttpUrl,- loadRemoteMedia,- extractWwebjsCall,- isNoLidForUserError,- wwebjsAckToDeliveryStatus,-} from './wwebjs-messaging';+export { isHttpUrl, loadRemoteMedia, extractWwebjsCall, wwebjsAckToDeliveryStatus } from './wwebjs-messaging';// Proxy launch helpers moved to ./wwebjs-proxy; re-exported because existing callers (the adapter// spec) still import them from here.diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex a3e7c56b8..e39b843da 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -89,7 +89,7 @@ export async function loadRemoteMedia(url: string): Promise<MessageMedia> {/*** True when a send error is whatsapp-web.js's "recipient needs a LID we don't have" failure, raised* when sending to a `@c.us` for a contact WhatsApp has migrated to `@lid`.- * ponytail: matched on the wwjs error text — there is no structured code; revisit if wwjs changes it.+ * Matched on the wwjs error text — there is no structured code; revisit if wwjs changes it.*/export function isNoLidForUserError(err: unknown): boolean {return err instanceof Error && err.message.includes('No LID for user');@@ -190,8 +190,8 @@ export class WwebjsMessaging {// confirmed resolution keeps ordinary sends from re-probing on each message (#580). A `@lid` is// stable; a stale entry (a contact that migrates mid-session) self-heals via the retry in// `sendResolved`.- // ponytail: unbounded Map, bounded in practice by distinct recipients per session; add an LRU only- // if a session ever addresses a truly unbounded set of fresh numbers.+ // Unbounded Map, bounded in practice by distinct recipients per session; add an LRU only if a+ // session ever addresses a truly unbounded set of fresh numbers.private readonly resolvedSendIds = new Map<string, string>();/**diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex 52ad7df80..e4d1f739f 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -213,7 +213,7 @@ export class DockerService implements OnModuleInit {* - Credentials: the compose services are the MANUAL operator path and deliberately ship no* default secret (empty POSTGRES_PASSWORD / MINIO_ROOT_* fail fast on boot). The specs below* are the dashboard built-in path: they provision the fixed built-in credentials- * (openwa/openwa, minioadmin/minioadmin) that infra.controller writes to data/.env.generated+ * (openwa/openwa, minioadmin/minioadmin) that infra-config.controller writes to data/.env.generated* and that the production boot guard (bootstrap-security.ts) exempts only while the* *_BUILTIN flag is set AND the datastore host resolves to the internal-only container.* - Postgres init script: compose bind-mounts scripts/postgres-init-schema.sh from the host@@ -259,7 +259,7 @@ export class DockerService implements OnModuleInit {name: 'openwa-postgres',alias: 'postgres',// Fixed built-in credentials — the dashboard saves these same values to- // data/.env.generated (infra.controller) and the production boot guard exempts them only+ // data/.env.generated (infra-config.controller) and the production boot guard exempts them only// for the built-in, internal-host deployment (see the getContainerSpec docblock).env: ['POSTGRES_USER=openwa', 'POSTGRES_PASSWORD=openwa', 'POSTGRES_DB=openwa'],volumes: [{ name: 'openwa_postgres-data', path: '/var/lib/postgresql/data' }],diff --git a/src/modules/plugins/plugins.controller.spec.ts b/src/modules/plugins/plugins.controller.spec.tsindex 2bb5d6111..ebe943d92 100644--- a/src/modules/plugins/plugins.controller.spec.ts+++ b/src/modules/plugins/plugins.controller.spec.ts@@ -22,7 +22,7 @@ describe('PluginsController authorization', () => {] as const;it.each(adminOnly)('%s requires the ADMIN role', method => {- // Metadata lookup key, never invoked — see the same note in infra.controller.spec.ts.+ // Metadata lookup key, never invoked.// eslint-disable-next-line @typescript-eslint/unbound-methodconst handler = PluginsController.prototype[method];const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 282d38274..827c621fb 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -48,9 +48,9 @@ import { HookManager } from '../../core/hooks';// history sync) get the omitted marker synthesized at the persistence chokepoints.// How many recent status-broadcast messages the connect-time seed pulls (each with its media).-// ponytail: fixed ceiling — the most-recent 50 cover a normal account's 24h of stories; anything-// posted after connect still lands live via onMessage. Make it configurable only if a flood account-// proves 50 too few.+// Fixed ceiling: the most-recent 50 cover a normal account's 24h of stories; anything posted after+// connect still lands live via onMessage. Make it configurable only if a flood account proves 50+// too few.const STATUS_SEED_LIMIT = 50;interface ReconnectState extends ReconnectAttemptState {