Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): offer Disconnect to writer keys and report a failed stop

Yudhi Armyndharis98f27cd81ade
diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.ts
index d75b6d8e0..1afdb6e2c 100644
--- a/dashboard/src/hooks/queries.ts
+++ b/dashboard/src/hooks/queries.ts
@@ -77,7 +77,8 @@ export function useStopSessionMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => sessionApi.stop(id),
- onSuccess: () => {
+ // A failed stop can still have changed the session, so the list is re-read either way.
+ onSettled: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.sessions });
},
});
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index c11955924..efc469821 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -227,6 +227,7 @@
"noSessions": "لم يتم العثور على جلسات. أنشئ جلسة للبدء.",
"view": "عرض",
"disconnect": "قطع الاتصال",
+ "disconnectFailed": "تعذر قطع اتصال الجلسة",
"errorPrefix": "خطأ: {{message}}",
"loadError": "فشل تحميل البيانات",
"charts": {
@@ -356,7 +357,8 @@
"actionRequiredTitle": "إجراء مطلوب",
"actionRequiredDesc": "تتطلب هذه الجلسة انتباهك. افتح الجلسة لمعرفة ما يجب فعله.",
"failedTitle": "فشلت الجلسة",
- "failedDesc": "فشل بدء جلسة واتساب. افتح الجلسة لمعرفة السبب."
+ "failedDesc": "فشل بدء جلسة واتساب. افتح الجلسة لمعرفة السبب.",
+ "stopFailedTitle": "فشل الإيقاف"
},
"card": {
"phone": "الهاتف",
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 39c90e647..0d9e69b40 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -216,6 +216,7 @@
"noSessions": "Keine Sitzungen gefunden. Erstelle eine, um zu beginnen.",
"view": "Ansehen",
"disconnect": "Trennen",
+ "disconnectFailed": "Sitzung konnte nicht getrennt werden",
"errorPrefix": "Fehler: {{message}}",
"loadError": "Daten konnten nicht geladen werden",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "Handlung erforderlich",
"actionRequiredDesc": "Diese Sitzung braucht deine Aufmerksamkeit. Öffne die Sitzung, um zu sehen, was zu tun ist.",
"failedTitle": "Sitzung fehlgeschlagen",
- "failedDesc": "Die WhatsApp-Sitzung konnte nicht gestartet werden. Öffne die Sitzung, um den Grund anzuzeigen."
+ "failedDesc": "Die WhatsApp-Sitzung konnte nicht gestartet werden. Öffne die Sitzung, um den Grund anzuzeigen.",
+ "stopFailedTitle": "Stoppen fehlgeschlagen"
},
"card": {
"phone": "Telefon",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index ca832d26e..91df9d29d 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -216,6 +216,7 @@
"noSessions": "No sessions found. Create one to get started.",
"view": "View",
"disconnect": "Disconnect",
+ "disconnectFailed": "Could not disconnect the session",
"errorPrefix": "Error: {{message}}",
"loadError": "Failed to load data",
"charts": {
@@ -350,7 +351,8 @@
"actionRequiredTitle": "Action required",
"actionRequiredDesc": "This session needs your attention. Open the session to see what to do.",
"failedTitle": "Session Failed",
- "failedDesc": "The WhatsApp session failed to start. Open the session to see the reason."
+ "failedDesc": "The WhatsApp session failed to start. Open the session to see the reason.",
+ "stopFailedTitle": "Stop Failed"
},
"card": {
"phone": "Phone",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index bf7e67f78..ae7208da1 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -216,6 +216,7 @@
"noSessions": "No se encontraron sesiones. Crea una para empezar.",
"view": "Ver",
"disconnect": "Desconectar",
+ "disconnectFailed": "No se pudo desconectar la sesión",
"errorPrefix": "Error: {{message}}",
"loadError": "Error al cargar los datos",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "Acción requerida",
"actionRequiredDesc": "Esta sesión necesita tu atención. Abre la sesión para ver qué hacer.",
"failedTitle": "Sesión fallida",
- "failedDesc": "La sesión de WhatsApp no pudo iniciarse. Abre la sesión para ver el motivo."
+ "failedDesc": "La sesión de WhatsApp no pudo iniciarse. Abre la sesión para ver el motivo.",
+ "stopFailedTitle": "Error al detener"
},
"card": {
"phone": "Teléfono",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 8c9ab84ce..5764c83d4 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -216,6 +216,7 @@
"noSessions": "Aucune session trouvée. Créez-en une pour commencer.",
"view": "Voir",
"disconnect": "Déconnecter",
+ "disconnectFailed": "Impossible de déconnecter la session",
"errorPrefix": "Erreur : {{message}}",
"loadError": "Échec du chargement des données",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "Action requise",
"actionRequiredDesc": "Cette session nécessite votre attention. Ouvrez la session pour voir quoi faire.",
"failedTitle": "Échec de la session",
- "failedDesc": "Le démarrage de la session WhatsApp a échoué. Ouvrez la session pour en voir la raison."
+ "failedDesc": "Le démarrage de la session WhatsApp a échoué. Ouvrez la session pour en voir la raison.",
+ "stopFailedTitle": "Échec de l'arrêt"
},
"card": {
"phone": "Téléphone",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index b39ccb4d3..4c1886788 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -223,6 +223,7 @@
"noSessions": "לא נמצאו Sessions. יש ליצור אחד כדי להתחיל.",
"view": "צפייה",
"disconnect": "ניתוק",
+ "disconnectFailed": "לא ניתן לנתק את ה-Session",
"errorPrefix": "שגיאה: {{message}}",
"loadError": "טעינת הנתונים נכשלה",
"charts": {
@@ -352,7 +353,8 @@
"actionRequiredTitle": "נדרשת פעולה",
"actionRequiredDesc": "ה-Session הזה דורש את תשומת לבך. פתחו את ה-Session כדי לראות מה לעשות.",
"failedTitle": "ה-Session נכשל",
- "failedDesc": "ה-Session של WhatsApp נכשל באתחול. פתחו את ה-Session כדי לראות את הסיבה."
+ "failedDesc": "ה-Session של WhatsApp נכשל באתחול. פתחו את ה-Session כדי לראות את הסיבה.",
+ "stopFailedTitle": "העצירה נכשלה"
},
"card": {
"phone": "טלפון",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 914dadb08..1c913b5d2 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -216,6 +216,7 @@
"noSessions": "Nessuna sessione trovata. Creane una per iniziare.",
"view": "Visualizza",
"disconnect": "Disconnetti",
+ "disconnectFailed": "Impossibile disconnettere la sessione",
"errorPrefix": "Errore: {{message}}",
"loadError": "Impossibile caricare i dati",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "Azione richiesta",
"actionRequiredDesc": "Questa sessione richiede la tua attenzione. Apri la sessione per vedere cosa fare.",
"failedTitle": "Sessione Fallita",
- "failedDesc": "Avvio della sessione WhatsApp non riuscito. Apri la sessione per vedere il motivo."
+ "failedDesc": "Avvio della sessione WhatsApp non riuscito. Apri la sessione per vedere il motivo.",
+ "stopFailedTitle": "Arresto non riuscito"
},
"card": {
"phone": "Telefono",
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 7cf0b6899..b33974b54 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -216,6 +216,7 @@
"noSessions": "세션이 없습니다. 세션을 생성해 시작하세요.",
"view": "보기",
"disconnect": "연결 해제",
+ "disconnectFailed": "세션 연결을 해제할 수 없습니다",
"errorPrefix": "오류: {{message}}",
"loadError": "데이터를 불러오지 못했습니다",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "조치 필요",
"actionRequiredDesc": "이 세션에 주의가 필요합니다. 할 일을 확인하려면 세션을 여세요.",
"failedTitle": "세션 실패",
- "failedDesc": "WhatsApp 세션을 시작하지 못했습니다. 세션을 열어 원인을 확인하세요."
+ "failedDesc": "WhatsApp 세션을 시작하지 못했습니다. 세션을 열어 원인을 확인하세요.",
+ "stopFailedTitle": "중지 실패"
},
"card": {
"phone": "전화번호",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 27a6dab9b..2deec1b0b 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -216,6 +216,7 @@
"noSessions": "Nenhuma sessão encontrada. Crie uma para começar.",
"view": "Ver",
"disconnect": "Desconectar",
+ "disconnectFailed": "Não foi possível desconectar a sessão",
"errorPrefix": "Erro: {{message}}",
"loadError": "Erro ao carregar os dados",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "Ação necessária",
"actionRequiredDesc": "Esta sessão precisa de sua atenção. Abra a sessão para ver o que fazer.",
"failedTitle": "Sessão falhou",
- "failedDesc": "A sessão do WhatsApp não pôde ser iniciada. Abra a sessão para ver o motivo."
+ "failedDesc": "A sessão do WhatsApp não pôde ser iniciada. Abra a sessão para ver o motivo.",
+ "stopFailedTitle": "Falha ao parar"
},
"card": {
"phone": "Telefone",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 1aab3ec4f..61133447e 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -216,6 +216,7 @@
"noSessions": "ఎలాంటి సెషన్లు కనుగొనబడలేదు. ప్రారంభించడానికి ఒకదాన్ని సృష్టించండి.",
"view": "చూడు",
"disconnect": "డిస్‌కనెక్ట్ చేయి",
+ "disconnectFailed": "సెషన్‌ను డిస్‌కనెక్ట్ చేయడం సాధ్యం కాలేదు",
"errorPrefix": "లోపం: {{message}}",
"loadError": "డేటాను లోడ్ చేయడం విఫలమైంది",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "చర్య అవసరం",
"actionRequiredDesc": "ఈ సెషన్‌కు మీ శ్రద్ధ అవసరం. ఏమి చేయాలో చూడటానికి సెషన్‌ను తెరవండి.",
"failedTitle": "సెషన్ విఫలమైంది",
- "failedDesc": "వాట్సాప్ సెషన్ ప్రారంభం కావడం విఫలమైంది. కారణాన్ని చూడటానికి సెషన్‌ను తెరవండి."
+ "failedDesc": "వాట్సాప్ సెషన్ ప్రారంభం కావడం విఫలమైంది. కారణాన్ని చూడటానికి సెషన్‌ను తెరవండి.",
+ "stopFailedTitle": "ఆపడం విఫలమైంది"
},
"card": {
"phone": "ఫోన్",
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index 50347086a..75ab25b2c 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -216,6 +216,7 @@
"noSessions": "Oturum bulunamadı. Başlamak için bir tane oluşturun.",
"view": "Görüntüle",
"disconnect": "Bağlantıyı Kes",
+ "disconnectFailed": "Oturumun bağlantısı kesilemedi",
"errorPrefix": "Hata: {{message}}",
"loadError": "Veriler yüklenemedi",
"charts": {
@@ -350,7 +351,8 @@
"actionRequiredTitle": "İşlem gerekiyor",
"actionRequiredDesc": "Bu oturumun ilgilenilmesi gerekiyor. Ne yapılması gerektiğini görmek için oturumu açın.",
"failedTitle": "Oturum Başarısız",
- "failedDesc": "WhatsApp oturumu başlatılamadı. Nedenini görmek için oturumu açın."
+ "failedDesc": "WhatsApp oturumu başlatılamadı. Nedenini görmek için oturumu açın.",
+ "stopFailedTitle": "Durdurma başarısız"
},
"card": {
"phone": "Telefon",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 5fc7efdca..fd1fecff7 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -216,6 +216,7 @@
"noSessions": "未找到会话。创建一个即可开始。",
"view": "查看",
"disconnect": "断开连接",
+ "disconnectFailed": "无法断开会话连接",
"errorPrefix": "错误:{{message}}",
"loadError": "加载数据失败",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "需要操作",
"actionRequiredDesc": "此会话需要您的关注。打开会话以查看需要做什么。",
"failedTitle": "会话失败",
- "failedDesc": "WhatsApp 会话启动失败。打开该会话以查看原因。"
+ "failedDesc": "WhatsApp 会话启动失败。打开该会话以查看原因。",
+ "stopFailedTitle": "停止失败"
},
"card": {
"phone": "电话",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 1ff8c23a4..16a8a6ee1 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -216,6 +216,7 @@
"noSessions": "找不到工作階段。建立一個即可開始。",
"view": "查看",
"disconnect": "中斷連線",
+ "disconnectFailed": "無法中斷工作階段連線",
"errorPrefix": "錯誤:{{message}}",
"loadError": "載入資料失敗",
"charts": {
@@ -345,7 +346,8 @@
"actionRequiredTitle": "需要操作",
"actionRequiredDesc": "此工作階段需要您的關注。開啟工作階段以查看需要做什麼。",
"failedTitle": "工作階段失敗",
- "failedDesc": "WhatsApp 工作階段啟動失敗。開啟該工作階段以查看原因。"
+ "failedDesc": "WhatsApp 工作階段啟動失敗。開啟該工作階段以查看原因。",
+ "stopFailedTitle": "停止失敗"
},
"card": {
"phone": "電話",
diff --git a/dashboard/src/pages/Dashboard.test.ts b/dashboard/src/pages/Dashboard.test.ts
index 390c2df14..b95e81c78 100644
--- a/dashboard/src/pages/Dashboard.test.ts
+++ b/dashboard/src/pages/Dashboard.test.ts
@@ -1,6 +1,7 @@
// Render test for the Dashboard stat cards under the bare `node --test` runner, on the Sessions.test.ts
// harness. GET /webhooks and GET /stats/overview both reject a viewer key; each card must then show
-// the unavailable placeholder rather than a count the gateway never returned.
+// the unavailable placeholder rather than a count the gateway never returned. POST /sessions/:id/stop
+// is OPERATOR-only: a viewer is offered no Disconnect, and a failed stop is reported, not swallowed.
import '../test-helpers/register-hooks.ts';
import { test, before, afterEach } from 'node:test';
import assert from 'node:assert/strict';
@@ -10,16 +11,34 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
let webhooksStatus = 403;
let webhookList: unknown[] = [];
+let sessionList: unknown[] = [];
+let stopStatus = 200;
function jsonResponse(data: unknown, status = 200): Response {
return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });
}
+const READY_SESSION = {
+ id: 'sess-ready-1',
+ name: 'Main',
+ status: 'ready',
+ phone: '15551234567',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+};
+
function installFetchStub(): void {
globalThis.fetch = ((input: RequestInfo | URL): Promise<Response> => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
const path = url.replace(/^https?:\/\/[^/]+/, '');
- if (path === '/api/sessions') return Promise.resolve(jsonResponse([]));
+ if (path === '/api/sessions') return Promise.resolve(jsonResponse(sessionList));
+ if (path === `/api/sessions/${READY_SESSION.id}/stop`) {
+ return Promise.resolve(
+ stopStatus === 200
+ ? jsonResponse({ ...READY_SESSION, status: 'disconnected' })
+ : jsonResponse({ message: 'Engine not loaded' }, stopStatus),
+ );
+ }
if (path === '/api/webhooks') {
return webhooksStatus === 200
? Promise.resolve(jsonResponse(webhookList))
@@ -32,6 +51,8 @@ function installFetchStub(): void {
let rtl: typeof import('@testing-library/react');
let Dashboard: (typeof import('./Dashboard.tsx'))['Dashboard'];
+let RoleProvider: (typeof import('../components/RoleProvider.tsx'))['RoleProvider'];
+let ToastProvider: (typeof import('../components/Toast.tsx'))['ToastProvider'];
let queryClient: QueryClient | undefined;
before(async () => {
@@ -44,9 +65,12 @@ before(async () => {
disconnect(): void {}
};
installFetchStub();
+ window.localStorage.setItem('openwa_user_role', 'viewer');
const { i18nReady } = await import('../i18n/index.ts');
await i18nReady;
rtl = await import('@testing-library/react');
+ ({ RoleProvider } = await import('../components/RoleProvider.tsx'));
+ ({ ToastProvider } = await import('../components/Toast.tsx'));
({ Dashboard } = await import('./Dashboard.tsx'));
});
@@ -55,6 +79,9 @@ afterEach(() => {
queryClient?.clear();
queryClient = undefined;
webhookList = [];
+ sessionList = [];
+ stopStatus = 200;
+ window.localStorage.setItem('openwa_user_role', 'viewer');
});
function renderDashboard(): void {
@@ -63,7 +90,11 @@ function renderDashboard(): void {
createElement(
QueryClientProvider,
{ client: queryClient },
- createElement(MemoryRouter, null, createElement(Dashboard)),
+ createElement(
+ MemoryRouter,
+ null,
+ createElement(RoleProvider, null, createElement(ToastProvider, null, createElement(Dashboard))),
+ ),
),
);
}
@@ -101,3 +132,30 @@ test('a successful empty webhook read still counts zero', async () => {
await rtl.screen.findByText('Webhooks Configured');
await rtl.waitFor(() => assert.equal(statValue('Webhooks Configured'), '0'));
});
+
+test('a read-only key is offered no Disconnect', async () => {
+ webhooksStatus = 403;
+ sessionList = [READY_SESSION];
+ renderDashboard();
+ await rtl.screen.findByText('Main');
+ assert.ok(rtl.screen.getByRole('button', { name: 'View' }), 'the row rendered without its actions');
+ assert.ok(!rtl.screen.queryByRole('button', { name: 'Disconnect' }), 'a viewer key was offered Disconnect');
+});
+
+test('a failed stop is reported, not swallowed', async () => {
+ webhooksStatus = 200;
+ sessionList = [READY_SESSION];
+ stopStatus = 400;
+ window.localStorage.setItem('openwa_user_role', 'operator');
+ renderDashboard();
+ const disconnect = await rtl.screen.findByRole('button', { name: 'Disconnect' });
+ // The session changed on the server even though the stop answered an error: the list is re-read.
+ sessionList = [{ ...READY_SESSION, status: 'disconnected' }];
+ rtl.fireEvent.click(disconnect);
+ const alert = await rtl.screen.findByRole('alert');
+ assert.match(alert.textContent ?? '', /Could not disconnect the session/);
+ assert.match(alert.textContent ?? '', /Engine not loaded/);
+ await rtl.waitFor(() =>
+ assert.ok(!rtl.screen.queryByRole('button', { name: 'Disconnect' }), 'the session list was not re-read'),
+ );
+});
diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsx
index c248e2809..283c1ceb2 100644
--- a/dashboard/src/pages/Dashboard.tsx
+++ b/dashboard/src/pages/Dashboard.tsx
@@ -4,6 +4,8 @@ import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { MessageSquare, Send, Webhook, Activity, Loader2 } from 'lucide-react';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
+import { useRole } from '../hooks/useRole';
+import { useToast } from '../hooks/useToast';
import {
useSessionsQuery,
useSessionStatsQuery,
@@ -22,6 +24,8 @@ export function Dashboard() {
const { t } = useTranslation();
useDocumentTitle(t('dashboard.title'));
const navigate = useNavigate();
+ const { canWrite } = useRole();
+ const toast = useToast();
const { data: sessions = [], isLoading: loadingSessions, error: sessionsError } = useSessionsQuery();
const { data: stats } = useSessionStatsQuery();
const { data: webhooks, isError: webhooksFailed } = useWebhooksQuery();
@@ -43,7 +47,7 @@ export function Dashboard() {
try {
await stopMutation.mutateAsync(id);
} catch (err) {
- console.error('Failed to disconnect:', err);
+ toast.error(t('dashboard.disconnectFailed'), err instanceof Error ? err.message : undefined);
}
};
@@ -162,7 +166,8 @@ export function Dashboard() {
<button className="btn-sm" onClick={() => navigate('/sessions')}>
{t('dashboard.view')}
</button>
- {['ready', 'initializing', 'qr_ready'].includes(session.status) && (
+ {/* Stopping a session is an operator write; a read-only key would only collect a 403. */}
+ {canWrite && ['ready', 'initializing', 'qr_ready'].includes(session.status) && (
<button className="btn-sm danger" onClick={() => handleDisconnect(session.id)}>
{t('dashboard.disconnect')}
</button>
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.ts
index 419f910f2..698a7e804 100644
--- a/dashboard/src/pages/Sessions.test.ts
+++ b/dashboard/src/pages/Sessions.test.ts
@@ -100,6 +100,7 @@ function resetFetchCalls(): void {
startFailure = null;
startGate = null;
startResult = null;
+ stopFailure = null;
}
function findFetchCall(method: string, path: string): FetchCall | undefined {
@@ -124,6 +125,8 @@ let startFailure: { status: number; message: string; leaves?: Partial<Session> }
// 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 .../stop answers with this error.
+let stopFailure: { status: number; message: string } | null = null;
// When set, POST .../start answers, whichever way it answers, only once this settles.
let startGate: Promise<void> | null = null;
let sessionProxy = {
@@ -241,6 +244,9 @@ function installFetchStub(): void {
if (found) Object.assign(found, startFailure.leaves);
return jsonResponse({ message: startFailure.message }, startFailure.status);
}
+ if (lifecycleMatch[2] === 'stop' && stopFailure) {
+ return jsonResponse({ message: stopFailure.message }, stopFailure.status);
+ }
if (isStart && startResult) {
const answered = { ...base, ...startResult.answer };
if (found) Object.assign(found, startResult.leaves ?? startResult.answer);
@@ -1193,3 +1199,18 @@ test('saving without retyping the URL leaves the stored proxy and its credential
'an untouched form must not write, or it would replace a credentialed URL with nothing',
);
});
+
+test('a failed stop is reported instead of only logged', async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ stopFailure = { status: 409, message: 'Session is busy' };
+ renderSessions();
+
+ const card = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Stop' }));
+
+ const alert = await screen.findByRole('alert');
+ assert.ok(alert.classList.contains('toast-error'), 'the stop failure was not shown as an error toast');
+ within(alert).getByText('Stop Failed');
+ within(alert).getByText('Session is busy');
+});
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index 1c135a3d0..b70212053 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -500,6 +500,7 @@ export function Sessions() {
await applySessionResponse(updated);
} catch (err) {
console.error('Failed to stop:', err);
+ toast.error(t('sessions.toasts.stopFailedTitle'), err instanceof Error ? err.message : t('common.unknownError'));
// The error response carries no Session body, so re-fetch the authoritative state — phone:null
// and the real status come from the list endpoint, not the error envelope.
await fetchSessions();