Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): report a failed session start instead of a stuck QR modal

Yudhi Armyndharis38a2bfcb6625
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 96cb11bab..da0aba876 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Session leases on PostgreSQL compare as instants across nodes in different time zones and across a daylight-saving change.
- Live WebSocket sockets are re-validated against the API-key table once a minute, so a key deleted, revoked, expired or narrowed on another node or by a direct database write drops its sockets there too, and a socket that connected while its key was being revoked no longer keeps that authorization for the life of the connection ([#1625](https://github.com/rmyndharis/OpenWA/issues/1625)).
- A WebSocket subscribe whose socket is evicted while it is in flight no longer registers its rooms after the disconnect.
+- The dashboard no longer opens a QR modal after a start that left the session without an engine.
+- A failed start in the dashboard that left no engine shows the gateway's error in a toast.
+- The dashboard closes a session's QR modal when the session fails, or disconnects with no engine left, instead of leaving it spinning.
+- The dashboard disables a session's Start and Reconnect buttons while its start request is in flight.
### Upgrade notes (behavior changes)
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 1a57514e9..a18d65c99 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -404,7 +404,8 @@
},
"start": {
"teardownPendingTitle": "بدء الجلسة",
- "teardownPending": "لا يزال تفكيك بيانات الاعتماد لهذه الجلسة قيد التسوية. انتظر لحظة وحاول مرة أخرى."
+ "teardownPending": "لا يزال تفكيك بيانات الاعتماد لهذه الجلسة قيد التسوية. انتظر لحظة وحاول مرة أخرى.",
+ "errorTitle": "فشل البدء"
},
"restriction": {
"reachout_timelock": "المحادثات الجديدة محظورة",
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 36a154b8d..c0ba2410e 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "Sitzung wird gestartet",
- "teardownPending": "Ein Anmeldedatenabbau für diese Sitzung läuft noch. Warten Sie einen Moment und versuchen Sie es erneut."
+ "teardownPending": "Ein Anmeldedatenabbau für diese Sitzung läuft noch. Warten Sie einen Moment und versuchen Sie es erneut.",
+ "errorTitle": "Start fehlgeschlagen"
},
"restriction": {
"reachout_timelock": "Neue Chats blockiert",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 7b7e55bbc..80013a190 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -285,7 +285,8 @@
},
"start": {
"teardownPendingTitle": "Session Starting",
- "teardownPending": "A credential teardown for this session is still settling. Wait a moment and try again."
+ "teardownPending": "A credential teardown for this session is still settling. Wait a moment and try again.",
+ "errorTitle": "Start Failed"
},
"qr": {
"title": "Scan QR Code",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 2dde5473d..07e21c071 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "Iniciando sesión",
- "teardownPending": "El borrado de credenciales de esta sesión aún está en curso. Espere un momento e inténtelo de nuevo."
+ "teardownPending": "El borrado de credenciales de esta sesión aún está en curso. Espere un momento e inténtelo de nuevo.",
+ "errorTitle": "Error al iniciar"
},
"restriction": {
"reachout_timelock": "Chats nuevos bloqueados",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 71979b553..f47104f8a 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "Démarrage de la session",
- "teardownPending": "Un nettoyage d'identifiants pour cette session est encore en cours. Patientez un instant et réessayez."
+ "teardownPending": "Un nettoyage d'identifiants pour cette session est encore en cours. Patientez un instant et réessayez.",
+ "errorTitle": "Échec du démarrage"
},
"restriction": {
"reachout_timelock": "Nouvelles discussions bloquées",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 4a5fdae7c..1d1d1d0f9 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -400,7 +400,8 @@
},
"start": {
"teardownPendingTitle": "הפעלת סשן",
- "teardownPending": "פירוק אישורים לסשן זה עדיין מתבצע. המתן רגע ונסה שוב."
+ "teardownPending": "פירוק אישורים לסשן זה עדיין מתבצע. המתן רגע ונסה שוב.",
+ "errorTitle": "ההפעלה נכשלה"
},
"restriction": {
"reachout_timelock": "צ׳אטים חדשים חסומים",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index fcf56622b..adac5ff6c 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "Avvio sessione",
- "teardownPending": "Uno smontaggio delle credenziali per questa sessione è ancora in corso. Attendi un momento e riprova."
+ "teardownPending": "Uno smontaggio delle credenziali per questa sessione è ancora in corso. Attendi un momento e riprova.",
+ "errorTitle": "Avvio Fallito"
},
"restriction": {
"reachout_timelock": "Nuove chat bloccate",
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 90f3d7220..a469ed26d 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "세션 시작 중",
- "teardownPending": "이 세션의 자격 증명 해체가 아직 진행 중입니다. 잠시 기다린 후 다시 시도하세요."
+ "teardownPending": "이 세션의 자격 증명 해체가 아직 진행 중입니다. 잠시 기다린 후 다시 시도하세요.",
+ "errorTitle": "시작 실패"
},
"restriction": {
"reachout_timelock": "새 대화 차단됨",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 4c670f5f0..80e68b53f 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "Iniciando sessão",
- "teardownPending": "A remoção de credenciais desta sessão ainda está em andamento. Aguarde um momento e tente novamente."
+ "teardownPending": "A remoção de credenciais desta sessão ainda está em andamento. Aguarde um momento e tente novamente.",
+ "errorTitle": "Erro ao iniciar"
},
"restriction": {
"reachout_timelock": "Novas conversas bloqueadas",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index d3130e230..ea7a86b03 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "సెషన్ ప్రారంభం",
- "teardownPending": "ఈ సెషన్ యొక్క ఆధారాల విచ్ఛిన్నం ఇంకా స్థిరపడుతోంది. కొద్దిసేపు ఆగి మళ్లీ ప్రయత్నించండి."
+ "teardownPending": "ఈ సెషన్ యొక్క ఆధారాల విచ్ఛిన్నం ఇంకా స్థిరపడుతోంది. కొద్దిసేపు ఆగి మళ్లీ ప్రయత్నించండి.",
+ "errorTitle": "ప్రారంభం విఫలమైంది"
},
"restriction": {
"reachout_timelock": "కొత్త చాట్‌లు నిరోధించబడ్డాయి",
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index a53d3bd24..4a716c966 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -285,7 +285,8 @@
},
"start": {
"teardownPendingTitle": "Oturum Başlatılıyor",
- "teardownPending": "Bu oturum için bir kimlik bilgisi sıfırlama işlemi devam ediyor. Lütfen biraz bekleyip tekrar deneyin."
+ "teardownPending": "Bu oturum için bir kimlik bilgisi sıfırlama işlemi devam ediyor. Lütfen biraz bekleyip tekrar deneyin.",
+ "errorTitle": "Başlatma Başarısız"
},
"qr": {
"title": "QR Kodunu Tara",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 4d719efb6..6e3e379c8 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "会话启动中",
- "teardownPending": "此会话的凭据拆除仍在处理中。请稍候再试。"
+ "teardownPending": "此会话的凭据拆除仍在处理中。请稍候再试。",
+ "errorTitle": "启动失败"
},
"restriction": {
"reachout_timelock": "新会话被阻止",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 65cbca474..f0714eb40 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -393,7 +393,8 @@
},
"start": {
"teardownPendingTitle": "工作階段啟動中",
- "teardownPending": "此工作階段的憑證拆除仍在進行中。請稍候再試。"
+ "teardownPending": "此工作階段的憑證拆除仍在進行中。請稍候再試。",
+ "errorTitle": "啟動失敗"
},
"restriction": {
"reachout_timelock": "新對話被封鎖",
diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.css
index ace39b55b..21822f19a 100644
--- a/dashboard/src/pages/Sessions.css
+++ b/dashboard/src/pages/Sessions.css
@@ -194,11 +194,16 @@
color: var(--text-secondary);
}
-.sessions-page .btn-action:hover {
+.sessions-page .btn-action:hover:not(:disabled) {
background: var(--bg-white);
color: var(--text-primary);
}
+.sessions-page .btn-action:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
.sessions-page .btn-action.danger {
color: var(--error-text);
}
@@ -206,6 +211,8 @@
.sessions-page .btn-action.danger:hover {
background: rgba(239, 68, 68, 0.12);
border-color: rgba(239, 68, 68, 0.3);
+ /* Restated: the generic :hover:not(:disabled) rule above is more specific than .danger alone. */
+ color: var(--error-text);
}
@media (max-width: 1400px) {
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.ts
index a1d190030..31d844542 100644
--- a/dashboard/src/pages/Sessions.test.ts
+++ b/dashboard/src/pages/Sessions.test.ts
@@ -97,6 +97,9 @@ function resetFetchCalls(): void {
proxyGetFails = false;
sessionListFailures = 0;
distinctFailureMessages = false;
+ startFailure = null;
+ startGate = null;
+ startResult = null;
}
function findFetchCall(method: string, path: string): FetchCall | undefined {
@@ -104,9 +107,9 @@ function findFetchCall(method: string, path: string): FetchCall | undefined {
}
// URL router for every endpoint the page can reach. Anything else 404s loudly instead of resolving
-// 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.
+// into a confusing downstream failure. Lifecycle actions (start/stop/logout/force-kill) share one stub
+// that answers with a stopped row; `startFailure`, `startResult` and `startGate` below change how a start
+// answers.
// 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;
@@ -115,6 +118,14 @@ let proxyGetFails = false;
let sessionListFailures = 0;
// Whether each failed read carries its own message, as a 502, a 504 and a dropped connection do.
let distinctFailureMessages = false;
+// When set, POST .../start answers with this error, first applying `leaves` to the session's row: the
+// state the gateway was left in, which is what the page reads back after the failure.
+let startFailure: { status: number; message: string; leaves?: Partial<Session> } | null = null;
+// When set, a successful POST .../start answers with the session's row merged with `answer`, and applies
+// `leaves` (by default `answer` itself) to the row the page reads back, instead of answering a stopped row.
+let startResult: { answer: Partial<Session>; leaves?: Partial<Session> } | null = null;
+// When set, POST .../start answers, whichever way it answers, only once this settles.
+let startGate: Promise<void> | null = null;
let sessionProxy = {
enabled: false,
proxyType: null as string | null,
@@ -224,7 +235,21 @@ function installFetchStub(): void {
if (method === 'POST' && lifecycleMatch) {
const found = SESSIONS.find(s => s.id === lifecycleMatch[1]);
const base = found ?? SESSION_STALE_ENGINE;
- return Promise.resolve(jsonResponse({ ...base, status: 'disconnected', engineLoaded: false }));
+ const isStart = lifecycleMatch[2] === 'start';
+ const answer = (): Response => {
+ if (isStart && startFailure) {
+ if (found) Object.assign(found, startFailure.leaves);
+ return jsonResponse({ message: startFailure.message }, startFailure.status);
+ }
+ if (isStart && startResult) {
+ const answered = { ...base, ...startResult.answer };
+ if (found) Object.assign(found, startResult.leaves ?? startResult.answer);
+ return jsonResponse(answered);
+ }
+ return jsonResponse({ ...base, status: 'disconnected', engineLoaded: false });
+ };
+ if (isStart && startGate) return startGate.then(answer);
+ return Promise.resolve(answer());
}
return Promise.resolve(jsonResponse({ message: `unstubbed ${method} ${path}` }, 404));
@@ -484,6 +509,298 @@ test('Reconnect on a qr_ready card with no engine loaded starts the session', as
}
});
+test('a start that answers with its engine up opens the QR modal', async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ startResult = { answer: { status: 'initializing', engineLoaded: true } };
+ SESSIONS.push({ ...SESSION_QR, id: 'sess-started-1', name: 'started', status: 'created', engineLoaded: false });
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('started')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Start' }));
+
+ await screen.findByRole('dialog');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+// A start can answer 200 with an engine that is gone by the time the list is read back: a stop that landed
+// while it ran retires it, and an engine can fail right after answering. The re-read decides, not the
+// answer, since a QR modal over that session could only spin.
+test('a start whose re-read shows no engine opens no QR modal', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ startResult = {
+ answer: { status: 'initializing', engineLoaded: true },
+ leaves: { status: 'created', engineLoaded: false },
+ };
+ SESSIONS.push({ ...SESSION_QR, id: 'sess-retired-1', name: 'retired', status: 'created', engineLoaded: false });
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('retired')).closest('.session-card') as HTMLElement;
+ const startButton = (): HTMLButtonElement => within(card).getByRole('button', { name: 'Start' });
+ fireEvent.click(startButton());
+ // The button is released in the same update that would open the modal, so once it is enabled again
+ // the handler has finished and the modal's state is settled.
+ await waitFor(() => assert.ok(findFetchCall('POST', '/api/sessions/sess-retired-1/start')));
+ await waitFor(() => assert.ok(!startButton().disabled));
+ assert.ok(!screen.queryByRole('dialog'), 'a QR modal opened for a start that left no engine');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+// A failed re-read says nothing about the engine, so a start the gateway accepted still opens the modal.
+test('a start whose re-read fails still opens the QR modal', async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ startResult = {
+ answer: { status: 'initializing', engineLoaded: true },
+ leaves: { status: 'created', engineLoaded: false },
+ };
+ SESSIONS.push({ ...SESSION_QR, id: 'sess-unread-1', name: 'unread', status: 'created', engineLoaded: false });
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('unread')).closest('.session-card') as HTMLElement;
+ sessionListFailures = 1;
+ fireEvent.click(within(card).getByRole('button', { name: 'Start' }));
+
+ await screen.findByRole('dialog');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+// A start refused before any engine exists (the concurrency cap) leaves no engine behind. A QR modal
+// opened over that session can only spin, since its poll waits for a qr_ready that never comes, and the
+// refusal itself is recorded nowhere the operator could find it.
+test('a start refused without an engine shows the error instead of a QR modal', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ startFailure = { status: 400, message: 'Maximum concurrent sessions reached (1)' };
+ SESSIONS.push({ ...SESSION_QR, id: 'sess-capped-1', name: 'capped', status: 'created', engineLoaded: false });
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('capped')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Start' }));
+
+ const alert = await screen.findByRole('alert');
+ assert.ok(alert.classList.contains('toast-error'), 'the start failure was not shown as an error toast');
+ within(alert).getByText('Start Failed');
+ within(alert).getByText('Maximum concurrent sessions reached (1)');
+ await waitFor(() => {
+ assert.ok(findFetchCall('POST', '/api/sessions/sess-capped-1/start'));
+ });
+ assert.ok(!screen.queryByRole('dialog'), 'a QR modal opened for a session with no engine');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+// A reverse proxy can time out a start the gateway is still carrying out. The engine is registered, so
+// the QR modal is still where the operator should wait.
+test('a start that errors while its engine is coming up still opens the QR modal', async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ startFailure = {
+ status: 504,
+ message: 'Gateway Timeout',
+ leaves: { status: 'initializing', engineLoaded: true },
+ };
+ SESSIONS.push({ ...SESSION_QR, id: 'sess-slow-1', name: 'slow-start', status: 'created', engineLoaded: false });
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('slow-start')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Start' }));
+
+ await screen.findByRole('dialog');
+ assert.ok(!screen.queryByRole('alert'), 'a start still in flight was reported as failed');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+// The toast carries what the gateway answered for THIS start. The row's lastError is left to the card:
+// it can be the terse cause behind a diagnostic 504, or a reason left from an earlier attempt.
+test('a failed start reports the gateway answer, not the row lastError', async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ startFailure = {
+ status: 504,
+ message: 'WhatsApp Web authentication timed out.',
+ leaves: { status: 'failed', engineLoaded: false, lastError: 'auth timeout' },
+ };
+ SESSIONS.push({ ...SESSION_QR, id: 'sess-nolaunch-1', name: 'no-launch', status: 'created', engineLoaded: false });
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('no-launch')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Start' }));
+
+ const alert = await screen.findByRole('alert');
+ within(alert).getByText('WhatsApp Web authentication timed out.');
+ assert.ok(!within(alert).queryByText('auth timeout'), 'the toast showed the row lastError');
+ assert.ok(!screen.queryByRole('dialog'), 'a QR modal opened for a session with no engine');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+// A start can wait seconds before its engine exists (a logout teardown still settling), with nothing on
+// the card to show it. A second click would be refused as "already starting" while the first succeeds.
+test('Start and Reconnect stay disabled while that session start is in flight', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ let release: () => void = () => undefined;
+ startGate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ SESSIONS.push(
+ { ...SESSION_QR, id: 'sess-pending-1', name: 'pending-start', status: 'created', engineLoaded: false },
+ { ...SESSION_QR, id: 'sess-pending-2', name: 'pending-reconnect', status: 'failed', engineLoaded: false },
+ );
+ const starts = (id: string): number =>
+ fetchCalls.filter(c => c.method === 'POST' && c.path === `/api/sessions/${id}/start`).length;
+ try {
+ renderSessions();
+
+ const startCard = (await screen.findByText('pending-start')).closest('.session-card') as HTMLElement;
+ const reconnectCard = screen.getByText('pending-reconnect').closest('.session-card') as HTMLElement;
+ const startButton = (): HTMLButtonElement => within(startCard).getByRole('button', { name: 'Start' });
+ const reconnectButton = (): HTMLButtonElement => within(reconnectCard).getByRole('button', { name: 'Reconnect' });
+
+ fireEvent.click(startButton());
+ await waitFor(() => assert.ok(startButton().disabled, 'Start stayed clickable during its start'));
+ assert.ok(!reconnectButton().disabled, 'a start disabled another session');
+ fireEvent.click(startButton());
+ assert.equal(starts('sess-pending-1'), 1);
+
+ fireEvent.click(reconnectButton());
+ await waitFor(() => assert.ok(reconnectButton().disabled, 'Reconnect stayed clickable during its start'));
+
+ release();
+ await waitFor(() =>
+ assert.ok(!startButton().disabled && !reconnectButton().disabled, 'a button stayed disabled after its start'),
+ );
+ } finally {
+ SESSIONS.pop();
+ SESSIONS.pop();
+ }
+});
+
+function pushSessionStatus(sessionId: string, status: string): void {
+ const socket = lastSocket();
+ assert.ok(socket, 'expected the page to have opened a socket');
+ rtl.act(() => {
+ socket.receive('message', {
+ type: 'event',
+ timestamp: '2026-01-01T00:00:00.000Z',
+ payload: { event: 'session.status', sessionId, data: { status } },
+ });
+ });
+}
+
+// Every FAILED write evicts the engine, so the modal can never show a code again. Covers a start that
+// returned 200 and failed afterwards, which is the only way a QR-stage failure surfaces on Baileys.
+test('a failed status push closes that session QR modal', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ window.sessionStorage.setItem('openwa_api_key', 'test-key');
+ renderSessions();
+
+ const card = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Show QR' }));
+ await screen.findByAltText('QR');
+
+ pushSessionStatus(SESSION_STALE_ENGINE.id, 'failed');
+ assert.ok(screen.queryByRole('dialog'), "another session's failure closed this QR modal");
+
+ pushSessionStatus(SESSION_QR.id, 'failed');
+
+ await waitFor(() => assert.ok(!screen.queryByRole('dialog'), 'the QR modal stayed open after its session failed'));
+});
+
+// `disconnected` covers both an engine inside its reconnect backoff and one that is gone, so the modal
+// closes only once the re-read says there is no engine.
+test('a disconnected push closes the QR modal once the re-read shows no engine', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ window.sessionStorage.setItem('openwa_api_key', 'test-key');
+ const row: Session = { ...SESSION_QR, id: 'sess-dropped-1', name: 'dropped', status: 'qr_ready', engineLoaded: true };
+ SESSIONS.push(row);
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('dropped')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Show QR' }));
+ await screen.findByAltText('QR');
+
+ Object.assign(row, { status: 'disconnected', engineLoaded: false });
+ pushSessionStatus(row.id, 'disconnected');
+
+ await waitFor(() => assert.ok(!screen.queryByRole('dialog'), 'the QR modal stayed open with no engine left'));
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+test('a disconnected push keeps the QR modal while the engine is still registered', async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ window.sessionStorage.setItem('openwa_api_key', 'test-key');
+ const row: Session = { ...SESSION_QR, id: 'sess-backoff-1', name: 'backoff', status: 'qr_ready', engineLoaded: true };
+ SESSIONS.push(row);
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('backoff')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Show QR' }));
+ await screen.findByAltText('QR');
+
+ row.status = 'disconnected';
+ pushSessionStatus(row.id, 'disconnected');
+
+ // The push drops engineLoaded, so the card offers Start until the re-read restores it and brings Stop
+ // back: once Stop is there, the re-read has been applied.
+ await within(card).findByRole('button', { name: 'Stop' });
+ assert.ok(screen.queryByRole('dialog'), 'the QR modal closed while the engine was still registered');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
+// A re-read that fails says nothing about the engine, so the modal stays.
+test('a disconnected push keeps the QR modal when the re-read fails', async () => {
+ const { screen, fireEvent, within, act } = rtl;
+ resetFetchCalls();
+ window.sessionStorage.setItem('openwa_api_key', 'test-key');
+ const row: Session = { ...SESSION_QR, id: 'sess-unknown-1', name: 'unknown', status: 'qr_ready', engineLoaded: true };
+ SESSIONS.push(row);
+ try {
+ renderSessions();
+
+ const card = (await screen.findByText('unknown')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Show QR' }));
+ await screen.findByAltText('QR');
+
+ sessionListFailures = 1;
+ pushSessionStatus(row.id, 'disconnected');
+
+ await screen.findByText('gateway unavailable');
+ // Let the re-read's continuation run and any state it sets render before looking.
+ await act(() => new Promise<void>(resolve => setTimeout(resolve, 0)));
+ assert.ok(screen.queryByRole('dialog'), 'the QR modal closed on a re-read that failed');
+ } finally {
+ SESSIONS.pop();
+ }
+});
+
test('a restricted session shows the restriction on its card, even while it is ready', async () => {
const { screen, within } = rtl;
resetFetchCalls();
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index e97a6badf..6d604f3aa 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -84,6 +84,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);
+ // Sessions whose Start or Reconnect click is still being handled. A start can wait seconds before its
+ // engine exists, and a second click in that window is refused as "already starting" while the first
+ // one proceeds.
+ const [startingIds, setStartingIds] = useState<ReadonlySet<string>>(new Set());
// 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);
@@ -246,19 +250,26 @@ export function Sessions() {
// that means two different things — an engine still registered through its automatic
// reconnect backoff, or a session stopped with no engine at all — and only the server can
// say which, so the offered actions must not be guessed from the status here.
- void fetchSessions();
+ // The same answer decides whether an open QR modal for it can still show a code.
+ void fetchSessions().then(rows => {
+ if (rows.find(s => s.id === event.sessionId)?.engineLoaded === false) {
+ dismissQrForSession(event.sessionId);
+ }
+ });
toast.warning(t('sessions.toasts.disconnectedTitle'), t('sessions.toasts.disconnectedDesc'));
} else if (event.status === 'action_required') {
// Refresh so the card picks up the lastError reason (what the operator must do) from the API.
void fetchSessions();
toast.warning(t('sessions.toasts.actionRequiredTitle'), t('sessions.toasts.actionRequiredDesc'));
} else if (event.status === 'failed') {
- // Refresh so the card picks up the lastError reason from the API.
+ // Refresh so the card picks up the lastError reason from the API. Every FAILED write evicts the
+ // engine, so an open QR modal for this session can never show a code: close it, uncovering the card.
void fetchSessions();
+ dismissQrForSession(event.sessionId);
toast.error(t('sessions.toasts.failedTitle'), t('sessions.toasts.failedDesc'));
}
},
- [toast, t, fetchSessions, queryClient],
+ [toast, t, fetchSessions, queryClient, dismissQrForSession],
),
});
@@ -312,6 +323,7 @@ export function Sessions() {
// gateway. A leftover `initializing` or `qr_ready` status (a node that died mid-pairing) is no reason
// to open the QR modal instead: GET /qr answers 400 until something starts the session.
const handleStart = async (id: string) => {
+ setStartingIds(current => new Set(current).add(id));
try {
// Use the authoritative response instead of fabricating a status. The old code wrote a local
// `status: 'connecting'` — a value the gateway never emits — while keeping every other field
@@ -319,14 +331,20 @@ export function Sessions() {
// Start for a session that just acquired an engine.
const started = await sessionApi.start(id);
setSessions(current => replaceSession(current, started));
- await fetchSessions();
- handleShowQR(id);
+ // A 200 does not promise the engine is still there when the list is read back: a concurrent stop
+ // retires the start, and an engine can fail right after answering. Skip the modal when the re-read
+ // shows the session without one. A failed re-read gives no answer, so the start's success decides.
+ const row = (await fetchSessions()).find(s => s.id === id);
+ if (!row || isSessionStarted(row)) handleShowQR(id);
} catch (err) {
console.error('Failed to start:', err);
// A credential teardown for this name is still settling — the backend fails closed with 409 +
// SESSION_NAME_TEARDOWN_PENDING. It is retryable, so warn with the server message and do NOT
- // open a QR modal (there is no engine to scan yet). Any other start error keeps the existing
- // authoritative reload + QR fallback behavior.
+ // open a QR modal (there is no engine to scan yet). Any other start error re-reads the list. An
+ // engine that is still coming up (a reverse proxy timing out a slow start) gets the QR modal. A
+ // start that left no engine gets the gateway's answer instead: the modal's poll waits for a qr_ready
+ // that cannot arrive, so it would spin until closed, over the card's error row or, for a refusal that
+ // records nothing (the concurrency cap), with the reason only in the console.
const code = (err as { code?: string } | null | undefined)?.code;
if (code === 'SESSION_NAME_TEARDOWN_PENDING') {
const msg = err instanceof Error && err.message ? err.message : t('sessions.start.teardownPending');
@@ -336,7 +354,22 @@ export function Sessions() {
}
const fresh = await fetchSessions();
const current = fresh.find(s => s.id === id);
- if (current?.status !== 'ready') handleShowQR(id);
+ if (current && isSessionStarted(current)) {
+ if (current.status !== 'ready') handleShowQR(id);
+ return;
+ }
+ // The answer to this request, not the row's lastError: that is shown on the card, and it can be the
+ // terse cause behind a diagnostic 504 or a reason left from an earlier attempt.
+ toast.error(
+ t('sessions.start.errorTitle'),
+ err instanceof Error && err.message ? err.message : t('common.unknownError'),
+ );
+ } finally {
+ setStartingIds(current => {
+ const next = new Set(current);
+ next.delete(id);
+ return next;
+ });
}
};
@@ -1155,12 +1188,20 @@ export function Sessions() {
{t('sessions.actions.stop')}
</button>
) : canWrite && (session.status === 'created' || session.status === 'disconnected') ? (
- <button className="btn-action" onClick={() => handleStart(session.id)}>
+ <button
+ className="btn-action"
+ onClick={() => handleStart(session.id)}
+ disabled={startingIds.has(session.id)}
+ >
<Play size={16} />
{t('sessions.actions.start')}
</button>
) : canWrite ? (
- <button className="btn-action" onClick={() => handleStart(session.id)}>
+ <button
+ className="btn-action"
+ onClick={() => handleStart(session.id)}
+ disabled={startingIds.has(session.id)}
+ >
<RefreshCw size={16} />
{t('sessions.actions.reconnect')}
</button>