Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
Merge main into feat/chats-redesign
Yudhi Armyndharis877b5b90b1bd
diff --cc CHANGELOG.mdindex 0933bd4d6,991e89208..1fe4619a7--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -9,13 -9,11 +9,16 @@@ and this project adheres to [Semantic V### Added- - Add Number Checker page in dashboard for single and bulk WhatsApp recipient pre-validation.+ - Add Number Checker page in dashboard for single and bulk WhatsApp recipient pre-validation, in every dashboard language.- Add the opt-in `message.receipt` event for per-recipient group and status receipts on Baileys (#1748).- - Add All, Unread, 1:1, Groups and Unknown quick filters to the dashboard chat list, where Unread includes chats marked unread and Unknown lists 1:1 chats whose contact is not saved.- - Add a New chat panel to the dashboard Chats page for operator keys that opens a chat with a saved contact or a typed international number once the gateway confirms the number is on WhatsApp, and on Baileys creates a group from a name and picked contacts or numbers.- - Add a menu to every dashboard chat row and to the open chat's header that pins, mutes, archives, marks unread, clears or deletes a chat (on whatsapp-web.js only for now, see #1891), saves, renames or blocks its contact, and leaves a group, asking first before an action that cannot be undone; the header's menu also copies the chat id and closes the chat.- - Add an Archived view to the dashboard chat list; archived chats leave the main list, and pinned chats lead it.- - Add a group info dialog to the dashboard Chats page that edits a group's name, picture and description and adds, removes, promotes and demotes its participants when the account administers the group.+ - Record plugin install, update, uninstall, enable, disable and configuration changes in the audit log.+ - Add `QUEUE_PREFIX` to set the Redis key prefix of the BullMQ queues, so deployments that share a Redis stop taking each other's webhook jobs.+ - `QUEUE_PREFIX` does not separate the rate-limit store or the WebSocket fan-out.++- Add All, Unread, 1:1, Groups and Unknown quick filters to the dashboard chat list. Thanks @rjsebening.++- Add a New chat panel to the dashboard Chats page that opens a chat with a saved contact or a number WhatsApp confirms, and on Baileys creates a group. Thanks @rjsebening.++- Add chat and contact menus to the dashboard Chats page: pin, mute, archive, mark unread, save, rename and block a contact, leave a group, and clear or delete a chat on whatsapp-web.js only until #1891 is fixed. Thanks @rjsebening.++- Add an Archived view to the dashboard chat list. Thanks @rjsebening.++- Add a group info dialog to the dashboard Chats page that edits a group and manages its participants. Thanks @rjsebening.### Changeddiff --cc dashboard/src/components/chats/GroupInfoDialog.tsxindex 40861b1d6,000000000..ea7769d4dmode 100644,000000..100644--- a/dashboard/src/components/chats/GroupInfoDialog.tsx+++ b/dashboard/src/components/chats/GroupInfoDialog.tsx@@@ -1,382 -1,0 +1,382 @@@+import { useEffect, useRef, useState } from 'react';+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useTranslation } from 'react-i18next';+import { Crown, Info, Loader2, RefreshCw, ShieldCheck, ShieldOff, UserMinus, UserPlus, Users } from 'lucide-react';+import { Modal } from '../Modal';+import { contactApi, sessionApi, type Chat, type GroupInfo, type Session } from '../../services/api';+import { useProfilePicture } from '../../hooks/useProfilePicture';+import { useRole } from '../../hooks/useRole';+import { useToast } from '../../hooks/useToast';+import { formatPhoneForDisplay } from '../../utils/formatPhone';- import { MEDIA_UPLOAD_MAX_BYTES } from './ChatComposer';++import { MEDIA_UPLOAD_MAX_BYTES } from '../../utils/mediaUpload';+import ChatAvatar from './ChatAvatar';++// The gateway's caps (CreateGroupDto / GroupDescriptionDto).+const GROUP_NAME_MAX_LENGTH = 100;+const GROUP_DESCRIPTION_MAX_LENGTH = 1024;++type Tab = 'info' | 'participants';++interface GroupInfoDialogProps {+ session: Session;+ group: Chat;+ onClose: () => void;+ /** The group's name changed through `sessionId`: the page renames its row and room if still on it. */+ onRenamed: (sessionId: string, groupId: string, name: string) => void;+}++const errorText = (err: unknown) => (err instanceof Error ? err.message : undefined);++/** Whether a participant is this session's own account. */+const isOwnAccount = (participant: GroupInfo['participants'][number], session: Session) => {+ const own = session.phone?.replace(/\D/g, '');+ return Boolean(own) && (participant.number === own || participant.id.split('@')[0].split(':')[0] === own);+};++/**+ * Edit a group's name, picture and description, and its participants, through the session that is open.+ * What this account may change is WhatsApp's call: an admin may change everything, a member only the info+ * of a group whose info is not locked to admins. The dialog reads that from the group and offers no edit the+ * gateway would refuse.+ */+function GroupInfoDialog({ session, group, onClose, onRenamed }: GroupInfoDialogProps) {+ const { t } = useTranslation();+ const { canWrite } = useRole();+ const { success: showSuccess, error: showError } = useToast();+ const queryClient = useQueryClient();++ const [tab, setTab] = useState<Tab>('info');+ const infoQuery = useQuery({+ queryKey: ['group-info', session.id, group.id],+ queryFn: () => sessionApi.getGroup(session.id, group.id),+ });+ const picture = useProfilePicture(session.id, group.id);+ const info = infoQuery.data;++ const me = info?.participants.find(p => isOwnAccount(p, session));+ const isAdmin = Boolean(me?.isAdmin || me?.isSuperAdmin);+ const canEditInfo = canWrite && Boolean(info) && (isAdmin || info?.locked === false);+ const canManageMembers = canWrite && isAdmin;++ // The form starts from the group as loaded, and again after a refresh.+ const [name, setName] = useState('');+ const [description, setDescription] = useState('');+ const [newPicture, setNewPicture] = useState<{ base64: string; mimetype: string; preview: string } | null>(null);+ const [saving, setSaving] = useState(false);+ useEffect(() => {+ if (!info) return;+ setName(info.name);+ setDescription(info.description ?? '');+ setNewPicture(null);+ }, [info]);+ // The preview is an object URL: released when replaced and when the dialog closes.+ useEffect(() => {+ if (!newPicture) return;+ return () => URL.revokeObjectURL(newPicture.preview);+ }, [newPicture]);++ const fileInputRef = useRef<HTMLInputElement | null>(null);+ const pickPicture = (file: File | undefined) => {+ if (!file) return;+ if (!file.type.startsWith('image/')) return;+ if (file.size > MEDIA_UPLOAD_MAX_BYTES) {+ showError(t('chats.errors.fileTooLarge'));+ return;+ }+ const reader = new FileReader();+ reader.onload = event => {+ const base64 = String(event.target?.result ?? '').split(',')[1] ?? '';+ setNewPicture({ base64, mimetype: file.type, preview: URL.createObjectURL(file) });+ };+ reader.readAsDataURL(file);+ };++ const trimmedName = name.trim();+ const nameChanged = Boolean(info) && trimmedName !== info?.name;+ const descriptionChanged = Boolean(info) && description !== (info?.description ?? '');+ const dirty = nameChanged || descriptionChanged || Boolean(newPicture);++ // Each field is its own route, so each is saved on its own: a picture the engine refuses does not take+ // a saved name down with it, and the toast names the step that failed.+ const save = async () => {+ if (!info || !dirty || !trimmedName || saving) return;+ setSaving(true);+ try {+ if (nameChanged) {+ await sessionApi.setGroupSubject(session.id, group.id, trimmedName);+ onRenamed(session.id, group.id, trimmedName);+ }+ if (descriptionChanged) await sessionApi.setGroupDescription(session.id, group.id, description);+ if (newPicture) {+ await sessionApi.setGroupPicture(session.id, group.id, newPicture.base64, newPicture.mimetype);+ await queryClient.invalidateQueries({ queryKey: ['profilePicture', session.id, group.id] });+ await queryClient.invalidateQueries({ queryKey: ['profilePictures', session.id] });+ }+ showSuccess(t('chats.group.saved'));+ await infoQuery.refetch();+ } catch (err) {+ showError(t('chats.group.saveFailed'), errorText(err));+ } finally {+ setSaving(false);+ }+ };++ // --- Participants ---+ const [pending, setPending] = useState<string | null>(null);+ const [newMember, setNewMember] = useState('');+ const runMemberAction = async (key: string, action: () => Promise<unknown>) => {+ setPending(key);+ try {+ await action();+ await infoQuery.refetch();+ } catch (err) {+ showError(t('chats.group.memberActionFailed'), errorText(err));+ } finally {+ setPending(null);+ }+ };+ // A number is checked first, as in the new-chat panel: the gateway resolves it to the id WhatsApp uses.+ const addMember = () =>+ runMemberAction('add', async () => {+ const digits = newMember.replace(/\D/g, '').replace(/^00/, '');+ const check = await contactApi.checkNumber(session.id, digits);+ if (!check.exists || !check.whatsappId) {+ throw new Error(t('chats.newChat.notOnWhatsApp', { number: formatPhoneForDisplay(digits) ?? `+${digits}` }));+ }+ await sessionApi.addGroupParticipants(session.id, group.id, [check.whatsappId]);+ setNewMember('');+ });++ const sessionName = session.name;+ const subheader = (+ <div className="group-info-toolbar">+ <div className="chats-tabs" role="tablist">+ {(['info', 'participants'] as const).map(id => (+ <button+ key={id}+ type="button"+ role="tab"+ aria-selected={tab === id}+ className={`chats-tab ${tab === id ? 'active' : ''}`}+ onClick={() => setTab(id)}+ >+ {id === 'info' ? <Info size={16} /> : <Users size={16} />}+ {id === 'info' ? t('chats.group.tabInfo') : t('chats.group.tabParticipants')}+ </button>+ ))}+ </div>+ {info && (+ <span className={`group-info-badge ${isAdmin ? 'admin' : ''}`}>+ {isAdmin ? <ShieldCheck size={16} /> : <ShieldOff size={16} />}+ {isAdmin+ ? t('chats.group.managedBy', { session: sessionName })+ : t('chats.group.notAdmin', { session: sessionName })}+ </span>+ )}+ <button+ type="button"+ className="icon-btn"+ onClick={() => void infoQuery.refetch()}+ disabled={infoQuery.isFetching}+ title={t('common.refresh')}+ aria-label={t('common.refresh')}+ >+ <RefreshCw size={18} className={infoQuery.isFetching ? 'animate-spin' : undefined} />+ </button>+ </div>+ );++ return (+ <Modal+ open+ onClose={onClose}+ className="group-info-modal"+ closeLabel={t('common.close')}+ title={+ <span className="group-info-title">+ <span className="group-info-tile" aria-hidden="true">+ <Users size={24} />+ </span>+ <span className="group-info-heading">+ <span>{t('chats.group.editTitle')}</span>+ <span className="group-info-subtitle">{info?.name ?? group.name}</span>+ </span>+ </span>+ }+ subheader={subheader}+ footer={+ tab === 'info' ? (+ <>+ <button type="button" className="btn-secondary" onClick={onClose} disabled={saving}>+ {t('common.cancel')}+ </button>+ <button+ type="button"+ className="btn-primary"+ onClick={() => void save()}+ disabled={!canEditInfo || !dirty || !trimmedName || saving}+ >+ {saving ? <Loader2 className="animate-spin" size={16} /> : t('chats.group.save')}+ </button>+ </>+ ) : undefined+ }+ >+ {infoQuery.isLoading ? (+ <div className="group-info-state">+ <Loader2 className="animate-spin" size={24} />+ </div>+ ) : infoQuery.isError || !info ? (+ <div className="group-info-state">{t('chats.group.loadFailed')}</div>+ ) : tab === 'info' ? (+ <div className="group-info-form">+ <label className="group-info-field">+ <span>+ {t('chats.group.name')} <span className="required">*</span>+ </span>+ <input+ type="text"+ value={name}+ maxLength={GROUP_NAME_MAX_LENGTH}+ onChange={e => setName(e.target.value)}+ disabled={!canEditInfo}+ />+ </label>++ <div className="group-info-field">+ <span>{t('chats.group.picture')}</span>+ <button+ type="button"+ className="group-info-picture"+ onClick={() => fileInputRef.current?.click()}+ disabled={!canEditInfo}+ >+ {newPicture ? (+ <span className="chat-avatar avatar-lg">+ <img src={newPicture.preview} alt="" />+ </span>+ ) : (+ <ChatAvatar pictureUrl={picture.data} kind="group" size="lg" onImageError={() => picture.refetch()} />+ )}+ <span>{canEditInfo ? t('chats.group.pictureHint') : t('chats.group.readOnlyHint')}</span>+ </button>+ <input+ ref={fileInputRef}+ type="file"+ accept="image/jpeg,image/png,image/webp"+ aria-label={t('chats.group.picture')}+ hidden+ onChange={e => {+ pickPicture(e.target.files?.[0]);+ e.target.value = '';+ }}+ />+ </div>++ <label className="group-info-field">+ <span>{t('chats.group.description')}</span>+ <textarea+ value={description}+ maxLength={GROUP_DESCRIPTION_MAX_LENGTH}+ placeholder={t('chats.group.descriptionPlaceholder')}+ onChange={e => setDescription(e.target.value)}+ disabled={!canEditInfo}+ rows={5}+ />+ </label>+ </div>+ ) : (+ <div className="group-info-members">+ {canManageMembers && (+ <form+ className="group-info-add"+ onSubmit={e => {+ e.preventDefault();+ if (newMember.replace(/\D/g, '').length >= 7) void addMember();+ }}+ >+ <input+ type="tel"+ value={newMember}+ onChange={e => setNewMember(e.target.value)}+ placeholder={t('chats.group.addPlaceholder')}+ aria-label={t('chats.group.addPlaceholder')}+ />+ <button+ type="submit"+ className="btn-primary"+ disabled={newMember.replace(/\D/g, '').length < 7 || pending !== null}+ >+ {pending === 'add' ? <Loader2 className="animate-spin" size={16} /> : <UserPlus size={16} />}+ {t('chats.group.add')}+ </button>+ </form>+ )}+ <div className="group-info-count">+ {t('chats.group.participantCount', { count: info.participants.length })}+ </div>+ <ul className="group-info-list">+ {info.participants.map(p => {+ const own = isOwnAccount(p, session);+ const label = own ? t('chats.you') : p.name || formatPhoneForDisplay(p.number) || p.number;+ return (+ <li key={p.id}>+ <ChatAvatar kind="individual" />+ <span className="group-info-member">+ <bdi className="name">{label}</bdi>+ {p.name && (+ <bdi className="number" dir="ltr">+ {formatPhoneForDisplay(p.number) ?? p.number}+ </bdi>+ )}+ </span>+ {(p.isSuperAdmin || p.isAdmin) && (+ <span className="group-info-role">+ {p.isSuperAdmin && <Crown size={12} />}+ {p.isSuperAdmin ? t('chats.group.owner') : t('chats.group.admin')}+ </span>+ )}+ {canManageMembers && !own && !p.isSuperAdmin && (+ <span className="group-info-actions">+ <button+ type="button"+ className="icon-btn small"+ disabled={pending !== null}+ onClick={() =>+ void runMemberAction(p.id, () =>+ sessionApi.setGroupAdmins(session.id, group.id, [p.id], !p.isAdmin),+ )+ }+ title={p.isAdmin ? t('chats.group.removeAdmin') : t('chats.group.makeAdmin')}+ aria-label={`${p.isAdmin ? t('chats.group.removeAdmin') : t('chats.group.makeAdmin')}: ${label}`}+ >+ {p.isAdmin ? <ShieldOff size={16} /> : <ShieldCheck size={16} />}+ </button>+ <button+ type="button"+ className="icon-btn small danger"+ disabled={pending !== null}+ onClick={() => {+ if (!window.confirm(t('chats.group.removeConfirm', { name: label }))) return;+ void runMemberAction(p.id, () =>+ sessionApi.removeGroupParticipants(session.id, group.id, [p.id]),+ );+ }}+ title={t('chats.group.remove')}+ aria-label={`${t('chats.group.remove')}: ${label}`}+ >+ {pending === p.id ? <Loader2 className="animate-spin" size={16} /> : <UserMinus size={16} />}+ </button>+ </span>+ )}+ </li>+ );+ })}+ </ul>+ </div>+ )}+ </Modal>+ );+}++export default GroupInfoDialog;diff --cc dashboard/src/pages/Chats.tsxindex b592707a5,83e5688f3..47b0ac900--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@@ -88,8 -63,11 +89,12 @@@ import './Chats.css'// Quiet window for coalescing mark-as-read RPCs (see markReadCoalescer below).const MARK_READ_DEBOUNCE_MS = 750;+const readKey = (sessionId: string, chatId: string) => `${sessionId}\u0000${chatId}`;+ // Longest one background chat-list walk may take before it is abandoned. A walk is a dozen small requests, and+ // the gateway answers a stalled engine at 180 s, so this is far above a healthy walk and below that.+ const BACKGROUND_RELOAD_DEADLINE_MS = 120_000;+// mergeDeliveryStatus (forward-only delivery-tick merge) is shared with mergeOrAppend in utils/chatMessages// so the WS append path and the ack path apply the exact same rule.