Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(dashboard): add an auto-reject-calls toggle to the session detail panel

Yudhi Armyndharis828b5a9d66e0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 55e13121d..4c55b8427 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Auto-reject calls can be turned on from the dashboard** — the session detail panel now carries a toggle wired to the config endpoint, so the setting no longer requires an API call to reach, and it states that `call.received` still fires and that no restart is needed.
- **Session config can now be changed without re-linking the account** — `PATCH /api/sessions/{id}/config` sets `autoRejectCalls`, `maxReconnectAttempts` and `reconnectBaseDelay` on a session that is already running, where all three were previously fixed at creation and turning one on meant creating a new session and scanning the QR again.
### Fixed
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 2edd6bde0..3818b7bfd 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -301,7 +301,9 @@
"phone": "رقم الهاتف",
"phoneNone": "غير متصل",
"created": "تاريخ الإنشاء",
- "lastActive": "آخر نشاط"
+ "lastActive": "آخر نشاط",
+ "autoRejectCalls": "الرفض التلقائي للمكالمات",
+ "autoRejectCallsHint": "يتم رفض المكالمات الواردة فور رنينها. ولا يزال الويب هوك call.received يُرسل قبل ذلك. يسري على المكالمة التالية — دون الحاجة إلى إعادة التشغيل."
},
"actions": {
"view": "عرض",
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 9b96dbb9e..003ebba37 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -290,7 +290,9 @@
"phone": "Telefonnummer",
"phoneNone": "Nicht verbunden",
"created": "Erstellt",
- "lastActive": "Zuletzt aktiv"
+ "lastActive": "Zuletzt aktiv",
+ "autoRejectCalls": "Anrufe automatisch ablehnen",
+ "autoRejectCallsHint": "Eingehende Anrufe werden abgelehnt, sobald sie klingeln. Der Webhook call.received wird trotzdem zuerst ausgelöst. Gilt ab dem nächsten Anruf — kein Neustart nötig."
},
"actions": {
"view": "Ansehen",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 40b004789..4cdd83c6d 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -294,7 +294,9 @@
"phone": "Phone Number",
"phoneNone": "Not connected",
"created": "Created",
- "lastActive": "Last Active"
+ "lastActive": "Last Active",
+ "autoRejectCalls": "Auto-reject calls",
+ "autoRejectCallsHint": "Incoming calls are declined as soon as they ring. The call.received webhook still fires first. Applies to the next call — no restart needed."
},
"actions": {
"view": "View",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index fd0b3d1f4..791a835bc 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -290,7 +290,9 @@
"phone": "Número de teléfono",
"phoneNone": "No conectado",
"created": "Creado",
- "lastActive": "Última actividad"
+ "lastActive": "Última actividad",
+ "autoRejectCalls": "Rechazar llamadas automáticamente",
+ "autoRejectCallsHint": "Las llamadas entrantes se rechazan en cuanto suenan. El webhook call.received se envía igualmente antes. Se aplica a la próxima llamada; no hace falta reiniciar."
},
"actions": {
"view": "Ver",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 390f8d92e..f17b9c279 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -290,7 +290,9 @@
"phone": "Numéro de téléphone",
"phoneNone": "Non connecté",
"created": "Créé le",
- "lastActive": "Dernière activité"
+ "lastActive": "Dernière activité",
+ "autoRejectCalls": "Rejeter automatiquement les appels",
+ "autoRejectCallsHint": "Les appels entrants sont refusés dès qu'ils sonnent. Le webhook call.received est tout de même émis avant. S'applique au prochain appel — aucun redémarrage nécessaire."
},
"actions": {
"view": "Voir",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 23cf7b89a..a25015e15 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -297,7 +297,9 @@
"phone": "מספר טלפון",
"phoneNone": "לא מחובר",
"created": "נוצר בתאריך",
- "lastActive": "פעילות אחרונה"
+ "lastActive": "פעילות אחרונה",
+ "autoRejectCalls": "דחיית שיחות אוטומטית",
+ "autoRejectCallsHint": "שיחות נכנסות נדחות ברגע שהן מצלצלות. ה-webhook call.received עדיין נשלח לפני כן. חל מהשיחה הבאה — ללא צורך בהפעלה מחדש."
},
"actions": {
"view": "צפייה",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 2fc12f8f4..172673c97 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -290,7 +290,9 @@
"phone": "Numero di Telefono",
"phoneNone": "Non connesso",
"created": "Creata",
- "lastActive": "Ultima Attività"
+ "lastActive": "Ultima Attività",
+ "autoRejectCalls": "Rifiuta automaticamente le chiamate",
+ "autoRejectCallsHint": "Le chiamate in arrivo vengono rifiutate appena squillano. Il webhook call.received viene comunque inviato prima. Si applica alla prossima chiamata — nessun riavvio necessario."
},
"actions": {
"view": "Visualizza",
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index da723feba..51ed56b02 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -290,7 +290,9 @@
"phone": "전화번호",
"phoneNone": "연결되지 않음",
"created": "생성일",
- "lastActive": "마지막 활동"
+ "lastActive": "마지막 활동",
+ "autoRejectCalls": "통화 자동 거절",
+ "autoRejectCallsHint": "수신 통화가 울리는 즉시 거절됩니다. call.received 웹훅은 그전에 그대로 전송됩니다. 다음 통화부터 적용되며 재시작이 필요하지 않습니다."
},
"actions": {
"view": "보기",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 06d71d253..65f54886e 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -290,7 +290,9 @@
"phone": "Número de telefone",
"phoneNone": "Não conectado",
"created": "Criado em",
- "lastActive": "Última atividade"
+ "lastActive": "Última atividade",
+ "autoRejectCalls": "Rejeitar chamadas automaticamente",
+ "autoRejectCallsHint": "As chamadas recebidas são recusadas assim que tocam. O webhook call.received continua sendo enviado antes. Vale a partir da próxima chamada — sem reiniciar."
},
"actions": {
"view": "Ver",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index bb354da92..2b88f75e6 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -290,7 +290,9 @@
"phone": "ఫోన్ నంబర్",
"phoneNone": "కనెక్ట్ కాలేదు",
"created": "సృష్టించబడింది",
- "lastActive": "చివరిసారి యాక్టివ్"
+ "lastActive": "చివరిసారి యాక్టివ్",
+ "autoRejectCalls": "కాల్‌లను ఆటోమేటిక్‌గా తిరస్కరించు",
+ "autoRejectCallsHint": "ఇన్‌కమింగ్ కాల్‌లు మోగిన వెంటనే తిరస్కరించబడతాయి. call.received వెబ్‌హుక్ మాత్రం ముందుగా పంపబడుతుంది. తదుపరి కాల్ నుండి వర్తిస్తుంది — పునఃప్రారంభం అవసరం లేదు."
},
"actions": {
"view": "చూడు",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index bc620bcbb..af601f2eb 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -290,7 +290,9 @@
"phone": "电话号码",
"phoneNone": "未连接",
"created": "创建时间",
- "lastActive": "上次活跃"
+ "lastActive": "上次活跃",
+ "autoRejectCalls": "自动拒接来电",
+ "autoRejectCallsHint": "来电响铃后立即拒接。call.received webhook 仍会先行触发。下一通来电起生效,无需重启。"
},
"actions": {
"view": "查看",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 051149e5d..aae1b8390 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -290,7 +290,9 @@
"phone": "電話號碼",
"phoneNone": "未連線",
"created": "建立時間",
- "lastActive": "上次活躍"
+ "lastActive": "上次活躍",
+ "autoRejectCalls": "自動拒接來電",
+ "autoRejectCallsHint": "來電響鈴後即時拒接。call.received webhook 仍會先行觸發。下一通來電起生效,無需重新啟動。"
},
"actions": {
"view": "查看",
diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.css
index 2bc3b667d..8f963c474 100644
--- a/dashboard/src/pages/Sessions.css
+++ b/dashboard/src/pages/Sessions.css
@@ -785,3 +785,80 @@
font-size: 0.9375rem;
color: var(--text-primary);
}
+
+/* Auto-reject toggle in the session detail modal. The toggle-switch rules mirror the per-page copies
+ in Webhooks.css / Plugins.css / Infrastructure.css — this codebase scopes them per page rather
+ than sharing one definition. The visually-hidden input is excluded from the modal's
+ input[type='checkbox'] reset in index.css, so it keeps width:0 here. */
+.sessions-page .detail-toggle-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+}
+
+.sessions-page .detail-hint {
+ font-size: 0.75rem;
+ color: var(--text-muted);
+ line-height: 1.4;
+}
+
+.sessions-page .toggle-switch {
+ position: relative;
+ display: inline-block;
+ width: 48px;
+ height: 26px;
+ flex-shrink: 0;
+}
+
+.sessions-page .toggle-switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+}
+
+.sessions-page .toggle-slider {
+ position: absolute;
+ cursor: pointer;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background-color: var(--border);
+ transition: 0.3s;
+ border-radius: 26px;
+}
+
+.sessions-page .toggle-slider::before {
+ position: absolute;
+ content: '';
+ height: 20px;
+ width: 20px;
+ left: 3px;
+ bottom: 3px;
+ background-color: white;
+ transition: 0.3s;
+ border-radius: 50%;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
+}
+
+.sessions-page .toggle-switch input:checked + .toggle-slider {
+ background-color: var(--primary);
+}
+
+.sessions-page .toggle-switch input:checked + .toggle-slider::before {
+ transform: translateX(22px);
+}
+
+/* A viewer-role key cannot write, and the control is also held during a save. The page copies this
+ rule came from have no disabled state because none of their toggles can be disabled; without it
+ the switch looks live to someone who can never move it. */
+.sessions-page .toggle-switch input:disabled + .toggle-slider {
+ cursor: not-allowed;
+ opacity: 0.55;
+}
+
+.sessions-page .toggle-switch input:focus-visible + .toggle-slider {
+ outline: 2px solid var(--primary);
+ outline-offset: 2px;
+}
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.ts
index 1652332d8..5eb686334 100644
--- a/dashboard/src/pages/Sessions.test.ts
+++ b/dashboard/src/pages/Sessions.test.ts
@@ -88,6 +88,10 @@ function findFetchCall(method: string, path: string): FetchCall | undefined {
// into a confusing downstream failure. Lifecycle actions (start/stop/logout/force-kill/pairing-code)
// are stubbed generically even though none of the three cases below trigger them, per the brief's
// endpoint list — a future case exercising them should not need to touch this stub.
+// Mutable so a test can set the starting value and observe what a PATCH wrote back.
+let sessionConfig = { autoRejectCalls: false, maxReconnectAttempts: null as number | null, reconnectBaseDelay: 5000 };
+let configPatchFails = false;
+
function installFetchStub(): void {
globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
@@ -130,6 +134,18 @@ function installFetchStub(): void {
return Promise.resolve(new Response(null, { status: 204 }));
}
+ const configMatch = path.match(/^\/api\/sessions\/([^/]+)\/config$/);
+ if (configMatch) {
+ if (method === 'GET') return Promise.resolve(jsonResponse({ ...sessionConfig }));
+ if (method === 'PATCH') {
+ // Per-test switch: the revert case needs the write to fail while the initial read succeeds,
+ // which a single stub response cannot express.
+ if (configPatchFails) return Promise.resolve(jsonResponse({ message: 'nope' }, 500));
+ Object.assign(sessionConfig, body as Record<string, unknown>);
+ return Promise.resolve(jsonResponse({ ...sessionConfig }));
+ }
+ }
+
const qrMatch = path.match(/^\/api\/sessions\/([^/]+)\/qr$/);
if (method === 'GET' && qrMatch) {
const found = SESSIONS.find(s => s.id === qrMatch[1]);
@@ -331,3 +347,52 @@ test('an unrestricted session shows no restriction row', async () => {
assert.equal(within(card).queryByText('Restriction'), null);
});
+
+// ── Auto-reject toggle ───────────────────────────────────────────────────────
+
+async function openDetailFor(name: string): Promise<HTMLInputElement> {
+ const { screen, within } = rtl;
+ const card = (await screen.findByText(name)).closest('.session-card') as HTMLElement;
+ rtl.fireEvent.click(within(card).getByRole('button', { name: 'View' }));
+ // The config is fetched when the modal opens, so the toggle only appears once that read lands —
+ // findBy, not getBy.
+ return (await screen.findByRole('checkbox')) as HTMLInputElement;
+}
+
+test('the auto-reject toggle reflects the stored config and patches only the key it owns', async () => {
+ resetFetchCalls();
+ sessionConfig = { autoRejectCalls: false, maxReconnectAttempts: null, reconnectBaseDelay: 5000 };
+ configPatchFails = false;
+ renderSessions();
+
+ const toggle = await openDetailFor('new-device');
+ assert.equal(toggle.checked, false);
+
+ rtl.fireEvent.click(toggle);
+ await rtl.waitFor(() => assert.ok(fetchCalls.some(c => c.method === 'PATCH')));
+
+ const patch = fetchCalls.find(c => c.method === 'PATCH');
+ assert.match(patch?.path ?? '', /\/api\/sessions\/[^/]+\/config$/);
+ // Only autoRejectCalls: sending the whole object would rewrite the two reconnect keys this screen
+ // never showed the operator, and a merge patch exists precisely to avoid that.
+ assert.deepEqual(patch?.body, { autoRejectCalls: true });
+ await rtl.waitFor(() => assert.equal((rtl.screen.getByRole('checkbox') as HTMLInputElement).checked, true));
+});
+
+test('a rejected write reverts the toggle instead of leaving it showing a state the gateway never accepted', async () => {
+ resetFetchCalls();
+ sessionConfig = { autoRejectCalls: false, maxReconnectAttempts: null, reconnectBaseDelay: 5000 };
+ configPatchFails = true;
+ renderSessions();
+
+ const toggle = await openDetailFor('new-device');
+ assert.equal(toggle.checked, false);
+
+ rtl.fireEvent.click(toggle);
+ await rtl.waitFor(() => assert.ok(fetchCalls.some(c => c.method === 'PATCH')));
+
+ // The optimistic flip must not survive the failure: a toggle left on would tell the operator calls
+ // are being auto-rejected when the gateway still has it off.
+ await rtl.waitFor(() => assert.equal((rtl.screen.getByRole('checkbox') as HTMLInputElement).checked, false));
+ configPatchFails = false;
+});
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index e0103b47d..6e3856520 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -15,7 +15,7 @@ import {
Skull,
Unlink,
} from 'lucide-react';
-import { sessionApi, type Session, type AccountRestriction } from '../services/api';
+import { sessionApi, type Session, type SessionConfig, type AccountRestriction } from '../services/api';
import { queryKeys } from '../hooks/queries';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import {
@@ -69,6 +69,10 @@ export function Sessions() {
const [killConfirmId, setKillConfirmId] = useState<string | null>(null);
const [unlinkConfirmId, setUnlinkConfirmId] = useState<string | null>(null);
const [unlinkingId, setUnlinkingId] = useState<string | null>(null);
+ // Session config is not on the list payload — the API never returns the config column, so it is
+ // fetched per session when the detail modal opens rather than N times to render the list.
+ const [sessionConfig, setSessionConfig] = useState<SessionConfig | null>(null);
+ const [savingConfig, setSavingConfig] = useState(false);
const fetchSessions = useCallback(async (): Promise<Session[]> => {
try {
@@ -266,6 +270,47 @@ export function Sessions() {
}
};
+ // Load the config when the detail modal opens and drop it when it closes, so a value fetched for
+ // one session can never render against another.
+ const selectedSessionId = selectedSession?.id ?? null;
+ useEffect(() => {
+ setSessionConfig(null);
+ if (!selectedSessionId) return;
+ let cancelled = false;
+ sessionApi
+ .getConfig(selectedSessionId)
+ .then(cfg => {
+ if (!cancelled) setSessionConfig(cfg);
+ })
+ .catch(() => {
+ // Leave the row absent rather than defaulting the toggle to off: rendering it off would
+ // assert that auto-reject is disabled for a session we failed to ask about.
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [selectedSessionId]);
+
+ const handleAutoRejectToggle = async (next: boolean) => {
+ if (!selectedSessionId || !sessionConfig) return;
+ const previous = sessionConfig;
+ setSessionConfig({ ...sessionConfig, autoRejectCalls: next });
+ setSavingConfig(true);
+ try {
+ setSessionConfig(await sessionApi.updateConfig(selectedSessionId, { autoRejectCalls: next }));
+ } catch (err) {
+ // Revert: an optimistic toggle left flipped would tell the operator calls are being rejected
+ // when the gateway never accepted the change.
+ setSessionConfig(previous);
+ toast.error(
+ t('sessions.details.autoRejectCalls'),
+ err instanceof Error ? err.message : t('common.unknownError'),
+ );
+ } finally {
+ setSavingConfig(false);
+ }
+ };
+
const handleStop = async (id: string) => {
try {
const updated = await sessionApi.stop(id);
@@ -628,6 +673,23 @@ export function Sessions() {
{selectedSession.lastActive ? new Date(selectedSession.lastActive).toLocaleString() : t('common.never')}
</span>
</div>
+ {sessionConfig && (
+ <div className="detail-item detail-item-toggle">
+ <div className="detail-toggle-row">
+ <span className="detail-label">{t('sessions.details.autoRejectCalls')}</span>
+ <label className="toggle-switch">
+ <input
+ type="checkbox"
+ checked={sessionConfig.autoRejectCalls}
+ disabled={!canWrite || savingConfig}
+ onChange={e => void handleAutoRejectToggle(e.target.checked)}
+ />
+ <span className="toggle-slider"></span>
+ </label>
+ </div>
+ <small className="detail-hint">{t('sessions.details.autoRejectCallsHint')}</small>
+ </div>
+ )}
</div>
</Modal>
)}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 9990f88d3..bc6ca6721 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -22,6 +22,17 @@ if (API_ORIGIN) warnIfInsecureHttpUrl(API_ORIGIN, 'VITE_API_URL');
// Types
// =============================================================================
+/**
+ * The three tunable keys, as the gateway resolves them — not the raw stored column, which the API
+ * never returns. `maxReconnectAttempts` is null when reconnects are unlimited, which is the default
+ * and which no number in the accepted 0-20 range can express.
+ */
+export interface SessionConfig {
+ autoRejectCalls: boolean;
+ maxReconnectAttempts: number | null;
+ reconnectBaseDelay: number;
+}
+
export interface Session {
id: string;
name: string;
@@ -709,6 +720,13 @@ export const sessionApi = {
body: JSON.stringify({ name }),
}),
delete: (id: string) => request<void>(`/sessions/${id}`, { method: 'DELETE' }),
+ getConfig: (id: string) => request<SessionConfig>(`/sessions/${id}/config`),
+ // PATCH merges: only the keys sent are touched. Send null to clear one back to its default.
+ updateConfig: (id: string, patch: Partial<Record<keyof SessionConfig, boolean | number | null>>) =>
+ request<SessionConfig>(`/sessions/${id}/config`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ }),
start: (id: string) => request<Session>(`/sessions/${id}/start`, { method: 'POST' }),
stop: (id: string) => request<Session>(`/sessions/${id}/stop`, { method: 'POST' }),
logout: (id: string) => request<Session>(`/sessions/${id}/logout`, { method: 'POST' }),