Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): reconcile authoritative session lifecycle state

Yudhi Armyndharis8c1759f67e31
diff --git a/dashboard/src/i18n/locales.test.ts b/dashboard/src/i18n/locales.test.ts
index e53f0e67c..c0ff17cda 100644
--- a/dashboard/src/i18n/locales.test.ts
+++ b/dashboard/src/i18n/locales.test.ts
@@ -5,6 +5,13 @@ import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import i18next from 'i18next';
+// Source files that reference session-lifecycle locale keys — the old `unconfirmed*` keys were
+// renamed to `incomplete*`, so a stale reference would render a raw key string to the operator.
+const SESSIONS_PAGE_SOURCE = readFileSync(
+ join(dirname(fileURLToPath(import.meta.url)), '..', 'pages', 'Sessions.tsx'),
+ 'utf8',
+);
+
// Catalog-level assertions over the real locale files through a real i18next instance — catches
// missing keys (a component would render the raw key), missing plural forms (a count renders the
// wrong number form), and interpolation drift that a JSON diff can't see.
@@ -106,3 +113,65 @@ test('sessionStatus.failed and sessionStatus.authenticating resolve in every loc
assert.equal(i18n.t('sessionStatus.failed'), 'Failed');
assert.equal(i18n.t('sessionStatus.authenticating'), 'Authenticating...');
});
+
+// ── Session lifecycle reconciliation keys (renamed unconfirmed* → incomplete* + new start keys) ──
+// A missing key would render the raw key to the operator; these are driven directly by Sessions.tsx.
+
+const LIFECYCLE_KEYS = [
+ 'sessions.unlink.success',
+ 'sessions.unlink.successTitle',
+ 'sessions.unlink.incomplete',
+ 'sessions.unlink.incompleteTitle',
+ 'sessions.unlink.failed',
+ 'sessions.unlink.failedTitle',
+ 'sessions.start.teardownPending',
+ 'sessions.start.teardownPendingTitle',
+];
+
+test('every session lifecycle key resolves in every locale', () => {
+ for (const lng of LOCALE_IDS) {
+ for (const key of LIFECYCLE_KEYS) {
+ const value = i18n.t(key, { lng });
+ assert.ok(value && value !== key, `${lng}: ${key} missing (component would render a raw key)`);
+ }
+ }
+});
+
+test('the old unconfirmed* locale keys are gone from every locale', () => {
+ for (const lng of LOCALE_IDS) {
+ for (const key of ['sessions.unlink.unconfirmed', 'sessions.unlink.unconfirmedTitle']) {
+ // With fallbackLng disabled, a present key resolves to its value while a removed key renders
+ // the raw key string back out — which is what a stale locale file would surface too.
+ const value = i18n.t(key, { lng });
+ assert.equal(value, key, `${lng}: stale ${key} still present`);
+ }
+ }
+});
+
+test('the page source no longer references any old unconfirmed* locale key', () => {
+ for (const key of ['sessions.unlink.unconfirmedTitle', 'sessions.unlink.unconfirmed']) {
+ assert.ok(
+ !SESSIONS_PAGE_SOURCE.includes(`t('${key}')`) && !SESSIONS_PAGE_SOURCE.includes(`t("${key}")`),
+ `Sessions.tsx still references renamed key ${key}`,
+ );
+ }
+});
+
+// The success copy must NOT claim the dashboard observes the handset's Linked Devices — Task 7's 200
+// contract is "unlink operation + local cleanup completed", not an independent handset observation.
+test('English unlink success/incomplete copy does not claim handset Linked-Devices observation', () => {
+ const success = i18n.t('sessions.unlink.success', { lng: 'en' });
+ assert.ok(!/Linked Devices/i.test(success), `success copy claims handset observation: "${success}"`);
+ assert.ok(!/removed the device from/i.test(success), `success copy claims handset removal: "${success}"`);
+ // The incomplete copy may still mention "linked" as a *possibility* (the device may still be linked),
+ // which is accurate — only the SUCCESS copy must not assert it as observed.
+ const incomplete = i18n.t('sessions.unlink.incomplete', { lng: 'en' });
+ assert.ok(/incomplete/i.test(incomplete), `incomplete copy lost the "incomplete" framing: "${incomplete}"`);
+});
+
+test('English start teardown-pending copy is a retryable warning, not an error', () => {
+ const title = i18n.t('sessions.start.teardownPendingTitle', { lng: 'en' });
+ const body = i18n.t('sessions.start.teardownPending', { lng: 'en' });
+ assert.ok(/try again/i.test(body), `teardown-pending copy lost the retry guidance: "${body}"`);
+ assert.ok(title && title !== 'sessions.start.teardownPendingTitle');
+});
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index cbfb8efb9..696bdbb9e 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -344,11 +344,11 @@
"warning": "سيُزيل واتساب هذا الجهاز من الأجهزة المرتبطة بالحساب وستتوقف الجلسة. تتطلب إعادة الاتصال مسح رمز QR جديدًا أو رمز اقتران. لحذف جميع البيانات المحلية أيضًا، احذف الجلسة بعد ذلك.",
"confirm": "إلغاء الربط",
"successTitle": "تم إلغاء ربط الجهاز",
- "success": "أزال واتساب الجهاز من الأجهزة المرتبطة بالحساب. تتطلب إعادة الاتصال مسح رمز QR جديدًا أو رمز اقتران.",
- "unconfirmedTitle": "لم يتم تأكيد إلغاء الربط",
- "unconfirmed": "توقفت الجلسة محليًا، لكن واتساب لم يؤكد إلغاء الربط — قد يظل الجهاز مدرجًا ضمن الأجهزة المرتبطة. ابدأ الجلسة وحاول مرة أخرى.",
+ "success": "اكتمل إلغاء الربط: تم تسجيل خروج الجهاز وتم مسح بيانات اعتماد الجلسة المحلية. تتطلب إعادة الاتصال مسح QR جديدًا أو رمز اقتران.",
"failedTitle": "فشل إلغاء الربط",
- "failed": "تعذر إلغاء ربط الجلسة."
+ "failed": "تعذر إلغاء ربط الجلسة.",
+ "incompleteTitle": "إلغاء الربط غير مكتمل",
+ "incomplete": "توقفت الجلسة محليًا، لكن عملية تسجيل الخروج غير مكتملة — قد يظل الجهاز مرتبطًا. ابدأ الجلسة وأعد محاولة تسجيل الخروج."
},
"pairing": {
"tabQr": "رمز QR",
@@ -367,6 +367,10 @@
"step3": "<strong>3.</strong> اضغط على <strong>ربط جهاز</strong>، ثم اضغط على <strong>الربط عبر رقم الهاتف بدلاً من ذلك</strong>",
"step4": "<strong>4.</strong> أدخل الرمز المكوّن من 8 أحرف المعروض أعلاه في هاتفك",
"waitingConnection": "في انتظار ربط هاتفك…"
+ },
+ "start": {
+ "teardownPendingTitle": "بدء الجلسة",
+ "teardownPending": "لا يزال تفكيك بيانات الاعتماد لهذه الجلسة قيد التسوية. انتظر لحظة وحاول مرة أخرى."
}
},
"webhooks": {
@@ -953,4 +957,4 @@
},
"loading": "جارٍ البحث…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 8a5d9afde..0ec340835 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp entfernt dieses Gerät aus den verknüpften Geräten des Kontos und die Sitzung wird beendet. Für eine erneute Verbindung ist ein neuer QR-Code oder Kopplungscode erforderlich. Um auch alle lokalen Daten zu löschen, löschen Sie die Sitzung anschließend.",
"confirm": "Trennen",
"successTitle": "Gerät getrennt",
- "success": "WhatsApp hat das Gerät aus den verknüpften Geräten des Kontos entfernt. Für eine erneute Verbindung ist ein neuer QR-Code oder Kopplungscode erforderlich.",
- "unconfirmedTitle": "Trennung nicht bestätigt",
- "unconfirmed": "Die Sitzung wurde lokal beendet, aber WhatsApp hat die Trennung nicht bestätigt — das Gerät könnte noch unter den verknüpften Geräten aufgeführt sein. Starten Sie die Sitzung und versuchen Sie es erneut.",
+ "success": "Trennung abgeschlossen: Das Gerät wurde abgemeldet und die lokalen Sitzungsdaten wurden gelöscht. Zum erneuten Verbinden ist ein neuer QR-Scan oder Kopplungscode erforderlich.",
"failedTitle": "Trennen fehlgeschlagen",
- "failed": "Die Sitzung konnte nicht getrennt werden."
+ "failed": "Die Sitzung konnte nicht getrennt werden.",
+ "incompleteTitle": "Trennung unvollständig",
+ "incomplete": "Die Sitzung wurde lokal beendet, aber der Abmeldevorgang ist unvollständig — das Gerät ist möglicherweise noch verknüpft. Starten Sie die Sitzung und wiederholen Sie die Trennung."
},
"pairing": {
"tabQr": "QR-Code",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> Tippe auf <strong>Gerät verknüpfen</strong> und anschließend auf <strong>Stattdessen mit Telefonnummer verknüpfen</strong>",
"step4": "<strong>4.</strong> Gib den oben angezeigten 8-stelligen Code auf deinem Telefon ein",
"waitingConnection": "Es wird darauf gewartet, dass dein Telefon die Verbindung herstellt…"
+ },
+ "start": {
+ "teardownPendingTitle": "Sitzung wird gestartet",
+ "teardownPending": "Ein Anmeldedatenabbau für diese Sitzung läuft noch. Warten Sie einen Moment und versuchen Sie es erneut."
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "Suche läuft…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 75594d4bb..b96b2c808 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -270,6 +270,10 @@
"errorTitle": "Delete Failed",
"errorDefault": "Failed to delete session"
},
+ "start": {
+ "teardownPendingTitle": "Session Starting",
+ "teardownPending": "A credential teardown for this session is still settling. Wait a moment and try again."
+ },
"qr": {
"title": "Scan QR Code",
"step1": "<strong>1.</strong> Open WhatsApp on your phone",
@@ -333,9 +337,9 @@
"warning": "WhatsApp removes this device from the account's Linked Devices and the session stops. Reconnecting requires a fresh QR scan or pairing code. To also erase all local data, delete the session afterwards.",
"confirm": "Unlink",
"successTitle": "Device Unlinked",
- "success": "WhatsApp removed the device from the account's Linked Devices. A fresh QR scan or pairing code is required to reconnect.",
- "unconfirmedTitle": "Unlink Not Confirmed",
- "unconfirmed": "The session stopped locally, but WhatsApp did not confirm the unlink — the device may still be listed under Linked Devices. Start the session and try again.",
+ "success": "Unlink completed: the device was logged out and the local session credentials were cleared. Reconnecting requires a fresh QR scan or pairing code.",
+ "incompleteTitle": "Unlink Incomplete",
+ "incomplete": "The session stopped locally, but the logout operation is incomplete — the device may still be linked. Start the session and retry the logout.",
"failedTitle": "Unlink Failed",
"failed": "Failed to unlink the session."
},
@@ -938,4 +942,4 @@
},
"loading": "Searching…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 7358bde07..188f82964 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp elimina este dispositivo de los Dispositivos vinculados de la cuenta y la sesión se detiene. Para reconectar se requiere un nuevo código QR o código de emparejamiento. Para borrar también todos los datos locales, elimine la sesión después.",
"confirm": "Desvincular",
"successTitle": "Dispositivo desvinculado",
- "success": "WhatsApp eliminó el dispositivo de los Dispositivos vinculados de la cuenta. Se requiere un nuevo código QR o código de emparejamiento para reconectar.",
- "unconfirmedTitle": "Desvinculación no confirmada",
- "unconfirmed": "La sesión se detuvo localmente, pero WhatsApp no confirmó la desvinculación — es posible que el dispositivo siga apareciendo en Dispositivos vinculados. Inicie la sesión e inténtelo de nuevo.",
+ "success": "Desvinculación completada: se cerró la sesión del dispositivo y se borraron las credenciales locales. Para reconectar se requiere un nuevo código QR o código de emparejamiento.",
"failedTitle": "Error al desvincular",
- "failed": "No se pudo desvincular la sesión."
+ "failed": "No se pudo desvincular la sesión.",
+ "incompleteTitle": "Desvinculación incompleta",
+ "incomplete": "La sesión se detuvo localmente, pero la operación de cierre de sesión está incompleta — es posible que el dispositivo siga vinculado. Inicie la sesión y vuelva a intentar la desvinculación."
},
"pairing": {
"tabQr": "Código QR",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> Toca <strong>Vincular dispositivo</strong> y luego toca <strong>Vincular con número de teléfono</strong>",
"step4": "<strong>4.</strong> Introduce en tu teléfono el código de 8 caracteres que se muestra arriba",
"waitingConnection": "Esperando a que tu teléfono se vincule…"
+ },
+ "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."
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "Buscando…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index bec434b5e..1e7037268 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp retire cet appareil des Appareils associés du compte et la session s'arrête. La reconnexion nécessite un nouveau scan QR ou un code d'appairage. Pour effacer aussi toutes les données locales, supprimez ensuite la session.",
"confirm": "Dissocier",
"successTitle": "Appareil dissocié",
- "success": "WhatsApp a retiré l'appareil des Appareils associés du compte. Un nouveau scan QR ou un code d'appairage est nécessaire pour se reconnecter.",
- "unconfirmedTitle": "Dissociation non confirmée",
- "unconfirmed": "La session s'est arrêtée localement, mais WhatsApp n'a pas confirmé la dissociation — l'appareil peut encore figurer dans les Appareils associés. Démarrez la session et réessayez.",
+ "success": "Dissociation terminée : l'appareil a été déconnecté et les identifiants de session locaux ont été effacés. Reconnecter nécessite un nouveau QR code ou code d'association.",
"failedTitle": "Échec de la dissociation",
- "failed": "Impossible de dissocier la session."
+ "failed": "Impossible de dissocier la session.",
+ "incompleteTitle": "Dissociation incomplète",
+ "incomplete": "La session s'est arrêtée localement, mais l'opération de déconnexion est incomplète — l'appareil peut encore être associé. Démarrez la session et relancez la dissociation."
},
"pairing": {
"tabQr": "Code QR",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> Appuyez sur <strong>Connecter un appareil</strong>, puis sur <strong>Lier avec un numéro de téléphone</strong>",
"step4": "<strong>4.</strong> Saisissez sur votre téléphone le code à 8 caractères affiché ci-dessus",
"waitingConnection": "En attente de la liaison de votre téléphone…"
+ },
+ "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."
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "Recherche…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 8ee5be022..05c1e5209 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -340,11 +340,11 @@
"warning": "וואטסאפ תסיר מכשיר זה מרשימת המכשירים המקושרים של החשבון והסשן ייעצר. ההתחברות מחדש דורשת סריקת QR חדשה או קוד התאמה. כדי למחוק גם את כל הנתונים המקומיים, מחק את הסשן לאחר מכן.",
"confirm": "ביטול קישור",
"successTitle": "המכשיר נותק",
- "success": "וואטסאפ הסירה את המכשיר מרשימת המכשירים המקושרים של החשבון. ההתחברות מחדש דורשת סריקת QR חדשה או קוד התאמה.",
- "unconfirmedTitle": "ביטול הקישור לא אושר",
- "unconfirmed": "הסשן נעצר מקומית, אך וואטסאפ לא אישרה את ביטול הקישור — ייתכן שהמכשיר עדיין מופיע ברשימת המכשירים המקושרים. הפעל את הסשן ונסה שוב.",
+ "success": "ביטול הקישור הושלם: המכשיר נותק ואישורי הסשן המקומיים נמחקו. חיבור מחדש דורש סריקת QR חדשה או קוד הוראה.",
"failedTitle": "ביטול הקישור נכשל",
- "failed": "לא ניתן לבטל את קישור הסשן."
+ "failed": "לא ניתן לבטל את קישור הסשן.",
+ "incompleteTitle": "ביטול קישור חלקי",
+ "incomplete": "הסשן נעצר מקומית, אך פעולת ההתנתקות אינה מושלמת — ייתכן שהמכשיר עדיין מקושר. הפעל את הסשן ונסה שוב את ביטול הקישור."
},
"pairing": {
"tabQr": "קוד QR",
@@ -363,6 +363,10 @@
"step3": "<strong>3.</strong> יש להקיש על <strong>קישור מכשיר</strong>, ולאחר מכן על <strong>קישור עם מספר טלפון במקום זאת</strong>",
"step4": "<strong>4.</strong> יש להזין במכשיר את הקוד בן 8 התווים המוצג למעלה",
"waitingConnection": "ממתין לקישור המכשיר שלך…"
+ },
+ "start": {
+ "teardownPendingTitle": "הפעלת סשן",
+ "teardownPending": "פירוק אישורים לסשן זה עדיין מתבצע. המתן רגע ונסה שוב."
}
},
"webhooks": {
@@ -947,4 +951,4 @@
},
"loading": "מחפש…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 528a14312..0939b8450 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp rimuove questo dispositivo dai Dispositivi collegati dell'account e la sessione si interrompe. Per riconnettersi è necessaria una nuova scansione del QR o un codice di abbinamento. Per cancellare anche tutti i dati locali, elimina la sessione in seguito.",
"confirm": "Scollega",
"successTitle": "Dispositivo scollegato",
- "success": "WhatsApp ha rimosso il dispositivo dai Dispositivi collegati dell'account. Per riconnettersi è necessaria una nuova scansione del QR o un codice di abbinamento.",
- "unconfirmedTitle": "Scollegamento non confermato",
- "unconfirmed": "La sessione si è interrotta localmente, ma WhatsApp non ha confermato lo scollegamento — il dispositivo potrebbe essere ancora elencato tra i Dispositivi collegati. Avvia la sessione e riprova.",
+ "success": "Scollegamento completato: il dispositivo è stato disconnesso e le credenziali di sessione locali sono state cancellate. La riconnessione richiede una nuova scansione QR o un codice di abbinamento.",
"failedTitle": "Scollegamento non riuscito",
- "failed": "Impossibile scollegare la sessione."
+ "failed": "Impossibile scollegare la sessione.",
+ "incompleteTitle": "Scollegamento incompleto",
+ "incomplete": "La sessione si è interrotta localmente, ma l'operazione di disconnessione è incompleta — il dispositivo potrebbe essere ancora collegato. Avvia la sessione e riprova lo scollegamento."
},
"pairing": {
"tabQr": "Codice QR",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> Tocca <strong>Collega un dispositivo</strong>, poi tocca <strong>Collega con numero di telefono</strong>",
"step4": "<strong>4.</strong> Inserisci sul tuo telefono il codice di 8 caratteri mostrato sopra",
"waitingConnection": "In attesa del collegamento del tuo telefono…"
+ },
+ "start": {
+ "teardownPendingTitle": "Avvio sessione",
+ "teardownPending": "Uno smontaggio delle credenziali per questa sessione è ancora in corso. Attendi un momento e riprova."
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "Ricerca…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index f77511cb7..ec25bdc0e 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp이 이 기기를 계정의 연결된 기기 목록에서 제거하고 세션이 중지됩니다. 다시 연결하려면 새 QR 스캔 또는 페어링 코드가 필요합니다. 로컬 데이터까지 모두 지우려면 이후 세션을 삭제하세요.",
"confirm": "연결 해제",
"successTitle": "기기 연결 해제됨",
- "success": "WhatsApp이 계정의 연결된 기기 목록에서 기기를 제거했습니다. 다시 연결하려면 새 QR 스캔 또는 페어링 코드가 필요합니다.",
- "unconfirmedTitle": "연결 해제 미확인",
- "unconfirmed": "세션이 로컬에서 중지되었지만 WhatsApp이 연결 해제를 확인하지 않았습니다. 기기가 연결된 기기 목록에 남아 있을 수 있습니다. 세션을 시작하고 다시 시도하세요.",
+ "success": "연결 해제 완료: 기기가 로그아웃되고 로컬 세션 자격 증명이 삭제되었습니다. 다시 연결하려면 새로운 QR 스캔 또는 페어링 코드가 필요합니다.",
"failedTitle": "연결 해제 실패",
- "failed": "세션 연결 해제에 실패했습니다."
+ "failed": "세션 연결 해제에 실패했습니다.",
+ "incompleteTitle": "연결 해제 미완료",
+ "incomplete": "세션이 로컬에서 중지되었지만 로그아웃 작업이 완료되지 않았습니다. 기기가 여전히 연결되어 있을 수 있습니다. 세션을 시작하고 연결 해제를 다시 시도하세요."
},
"pairing": {
"tabQr": "QR 코드",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> <strong>기기 연결</strong>을 누른 다음 <strong>전화번호로 연결하기</strong>를 누르세요",
"step4": "<strong>4.</strong> 위에 표시된 8자리 코드를 휴대폰에 입력하세요",
"waitingConnection": "휴대폰이 연결되기를 기다리는 중…"
+ },
+ "start": {
+ "teardownPendingTitle": "세션 시작 중",
+ "teardownPending": "이 세션의 자격 증명 해체가 아직 진행 중입니다. 잠시 기다린 후 다시 시도하세요."
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "검색하는 중…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index c07aa78e5..e9e900f66 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -333,11 +333,11 @@
"warning": "O WhatsApp remove este dispositivo dos Aparelhos conectados da conta e a sessão é encerrada. Para reconectar, é preciso um novo escaneamento de QR ou código de pareamento. Para apagar também todos os dados locais, exclua a sessão depois.",
"confirm": "Desvincular",
"successTitle": "Dispositivo desvinculado",
- "success": "O WhatsApp removeu o dispositivo dos Aparelhos conectados da conta. É preciso um novo escaneamento de QR ou código de pareamento para reconectar.",
- "unconfirmedTitle": "Desvinculação não confirmada",
- "unconfirmed": "A sessão foi encerrada localmente, mas o WhatsApp não confirmou a desvinculação — o dispositivo pode ainda constar nos Aparelhos conectados. Inicie a sessão e tente novamente.",
+ "success": "Desvinculação concluída: o dispositivo foi desconectado e as credenciais locais da sessão foram apagadas. Reconectar exige um novo QR code ou código de pareamento.",
"failedTitle": "Falha ao desvincular",
- "failed": "Não foi possível desvincular a sessão."
+ "failed": "Não foi possível desvincular a sessão.",
+ "incompleteTitle": "Desvinculação incompleta",
+ "incomplete": "A sessão foi encerrada localmente, mas a operação de logout está incompleta — o dispositivo pode ainda estar vinculado. Inicie a sessão e tente a desvinculação novamente."
},
"pairing": {
"tabQr": "Código QR",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> Toque em <strong>Conectar dispositivo</strong> e depois em <strong>Vincular com número de telefone</strong>",
"step4": "<strong>4.</strong> Digite no seu celular o código de 8 caracteres mostrado acima",
"waitingConnection": "Aguardando a conexão do seu celular…"
+ },
+ "start": {
+ "teardownPendingTitle": "Iniciando sessão",
+ "teardownPending": "A remoção de credenciais desta sessão ainda está em andamento. Aguarde um momento e tente novamente."
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "Pesquisando…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index fe3e82490..3be14660e 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp ఈ పరికరాన్ని ఖాతా యొక్క లింక్ చేసిన పరికరాల నుండి తొలగిస్తుంది మరియు సెషన్ ఆగిపోతుంది. మళ్లీ కనెక్ట్ చేయడానికి కొత్త QR స్కాన్ లేదా పెయిరింగ్ కోడ్ అవసరం. స్థానిక డేటాను కూడా తొలగించాలంటే, తర్వాత సెషన్‌ను తొలగించండి.",
"confirm": "అన్‌లింక్",
"successTitle": "పరికరం అన్‌లింక్ చేయబడింది",
- "success": "WhatsApp ఖాతా యొక్క లింక్ చేసిన పరికరాల నుండి పరికరాన్ని తొలగించింది. మళ్లీ కనెక్ట్ చేయడానికి కొత్త QR స్కాన్ లేదా పెయిరింగ్ కోడ్ అవసరం.",
- "unconfirmedTitle": "అన్‌లింక్ నిర్ధారించబడలేదు",
- "unconfirmed": "సెషన్ స్థానికంగా ఆగిపోయింది, కానీ WhatsApp అన్‌లింక్‌ను నిర్ధారించలేదు — పరికరం ఇంకా లింక్ చేసిన పరికరాల్లో జాబితా చేయబడి ఉండవచ్చు. సెషన్‌ను ప్రారంభించి మళ్లీ ప్రయత్నించండి.",
+ "success": "అన్‌లింక్ పూర్తయింది: పరికరం లాగ్ అవుట్ చేయబడింది మరియు స్థానిక సెషన్ ఆధారాలు క్లియర్ చేయబడ్డాయి. మళ్లీ కనెక్ట్ అవ్వడానికి కొత్త QR స్కాన్ లేదా జతచేసే కోడ్ అవసరం.",
"failedTitle": "అన్‌లింక్ విఫలమైంది",
- "failed": "సెషన్‌ను అన్‌లింక్ చేయడం విఫలమైంది."
+ "failed": "సెషన్‌ను అన్‌లింక్ చేయడం విఫలమైంది.",
+ "incompleteTitle": "అన్‌లింక్ అసంపూర్ణం",
+ "incomplete": "సెషన్ స్థానికంగా ఆగిపోయింది, కానీ లాగ్అవుట్ ఆపరేషన్ పూర్తి కాలేదు — పరికరం ఇంకా లింక్ అయి ఉండవచ్చు. సెషన్‌ను ప్రారంభించి అన్‌లింక్‌ను మళ్లీ ప్రయత్నించండి."
},
"pairing": {
"tabQr": "QR కోడ్",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> <strong>Link a Device</strong> పై నొక్కి, ఆపై <strong>Link with phone number instead</strong> పై నొక్కండి",
"step4": "<strong>4.</strong> పైన చూపిన 8-అక్షరాల కోడ్‌ను మీ ఫోన్‌లో నమోదు చేయండి",
"waitingConnection": "మీ ఫోన్ లింక్ అయ్యే వరకు వేచి ఉంది…"
+ },
+ "start": {
+ "teardownPendingTitle": "సెషన్ ప్రారంభం",
+ "teardownPending": "ఈ సెషన్ యొక్క ఆధారాల విచ్ఛిన్నం ఇంకా స్థిరపడుతోంది. కొద్దిసేపు ఆగి మళ్లీ ప్రయత్నించండి."
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "శోధిస్తోంది…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 2d8931f0a..4ecd7a583 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp 会将此设备从账号的已关联设备列表中移除,会话将停止。重新连接需要重新扫描二维码或使用配对码。如需同时清除所有本地数据,请随后删除该会话。",
"confirm": "取消关联",
"successTitle": "设备已取消关联",
- "success": "WhatsApp 已将设备从账号的已关联设备列表中移除。重新连接需要重新扫描二维码或使用配对码。",
- "unconfirmedTitle": "取消关联未确认",
- "unconfirmed": "会话已在本地停止,但 WhatsApp 未确认取消关联——设备可能仍列在已关联设备中。请启动会话后重试。",
+ "success": "取消关联已完成:设备已登出,本地会话凭据已清除。重新连接需要新的二维码扫描或配对码。",
"failedTitle": "取消关联失败",
- "failed": "无法取消关联该会话。"
+ "failed": "无法取消关联该会话。",
+ "incompleteTitle": "取消关联未完成",
+ "incomplete": "会话已在本地停止,但登出操作未完成——设备可能仍处于关联状态。请启动会话后重新尝试取消关联。"
},
"pairing": {
"tabQr": "QR 码",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> 点击<strong>关联设备</strong>,然后点击<strong>改用电话号码关联</strong>",
"step4": "<strong>4.</strong> 在手机上输入上方显示的 8 位字符配对码",
"waitingConnection": "正在等待您的手机完成关联…"
+ },
+ "start": {
+ "teardownPendingTitle": "会话启动中",
+ "teardownPending": "此会话的凭据拆除仍在处理中。请稍候再试。"
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "搜索中…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 35e5035e3..16525c083 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -333,11 +333,11 @@
"warning": "WhatsApp 會將此裝置從帳戶的已連結裝置列表中移除,工作階段將停止。重新連接需要重新掃描 QR 碼或使用配對碼。如需同時清除所有本地資料,請隨後刪除該工作階段。",
"confirm": "解除連結",
"successTitle": "裝置已解除連結",
- "success": "WhatsApp 已將裝置從帳戶的已連結裝置列表中移除。重新連接需要重新掃描 QR 碼或使用配對碼。",
- "unconfirmedTitle": "解除連結未確認",
- "unconfirmed": "工作階段已在本地停止,但 WhatsApp 未確認解除連結——裝置可能仍列於已連結裝置中。請啟動工作階段後重試。",
+ "success": "解除連結已完成:裝置已登出,本機工作階段憑證已清除。重新連線需要新的 QR 掃描或配對碼。",
"failedTitle": "解除連結失敗",
- "failed": "無法解除該工作階段的連結。"
+ "failed": "無法解除該工作階段的連結。",
+ "incompleteTitle": "解除連結未完成",
+ "incomplete": "工作階段已在本地停止,但登出操作未完成——裝置可能仍處於連結狀態。請啟動工作階段後重新嘗試解除連結。"
},
"pairing": {
"tabQr": "QR 碼",
@@ -356,6 +356,10 @@
"step3": "<strong>3.</strong> 點按<strong>連結裝置</strong>,然後點按<strong>改用電話號碼連結</strong>",
"step4": "<strong>4.</strong> 在手機上輸入上方顯示的 8 位字元配對碼",
"waitingConnection": "正在等待你的手機完成連結…"
+ },
+ "start": {
+ "teardownPendingTitle": "工作階段啟動中",
+ "teardownPending": "此工作階段的憑證拆除仍在進行中。請稍候再試。"
}
},
"webhooks": {
@@ -938,4 +942,4 @@
},
"loading": "搜尋中…"
}
-}
\ No newline at end of file
+}
diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsx
index 36b670f9f..fb6929b3a 100644
--- a/dashboard/src/pages/Dashboard.tsx
+++ b/dashboard/src/pages/Dashboard.tsx
@@ -59,7 +59,7 @@ export function Dashboard() {
{ label: t('dashboard.stats.totalMessages'), value: totalMessages, icon: Activity },
];
- const formatLastActive = (date?: string) => {
+ const formatLastActive = (date?: string | null) => {
if (!date) return t('common.never');
const diff = Date.now() - new Date(date).getTime();
if (diff < 60000) return t('common.justNow');
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index b48c80ad9..0ae9ca909 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -18,7 +18,14 @@ import {
import { sessionApi, type Session } from '../services/api';
import { queryKeys } from '../hooks/queries';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
-import { canUnlinkSession, classifyUnlinkError, isSessionStarted } from '../utils/sessionActions';
+import {
+ canForceKillSession,
+ canUnlinkSession,
+ classifyUnlinkError,
+ isSessionStarted,
+ replaceSession,
+} from '../utils/sessionActions';
+import { invalidateSessionQueries, reconcileSessionCache } from '../utils/sessionMutation';
import { useToast } from '../components/Toast';
import { useWebSocket } from '../hooks/useWebSocket';
import { useRole } from '../hooks/useRole';
@@ -70,7 +77,7 @@ export function Sessions() {
// query, so invalidation only marks the shared cache stale (no refetch here, no loop) and the
// Dashboard/other views refetch lazily on next mount. Prefix-matches every session-scoped key
// (sessions, sessionStats, per-session groups/chats/templates).
- void queryClient.invalidateQueries({ queryKey: queryKeys.sessions });
+ void invalidateSessionQueries(queryClient, queryKeys.sessions);
return data;
} catch (err) {
setError(err instanceof Error ? err.message : t('sessions.create.errorDefault'));
@@ -88,6 +95,23 @@ export function Sessions() {
sessionsRef.current = sessions;
}, [sessions]);
+ // Reconcile the LOCAL view with an authoritative Session response. The previous handlers discarded
+ // the response and fabricated `{ status: 'disconnected' }`, losing phone:null, timestamps, and other
+ // server-owned fields; this keeps the card and the selected-session modal byte-for-byte with the
+ // server. Functional updates (no captured stale `sessions`) feed both the list and the selected row,
+ // and the shared cache is reconciled + invalidated so sibling views refetch. The QR modal is cleared
+ // when the session that owned it stops, so it never hangs on a disconnected session's stale code.
+ const applySessionResponse = useCallback(
+ async (updated: Session) => {
+ sessionsRef.current = replaceSession(sessionsRef.current, updated);
+ setSessions(sessionsRef.current);
+ setSelectedSession(current => (current?.id === updated.id ? updated : current));
+ if (qrData?.sessionId === updated.id) setQrData(null);
+ await reconcileSessionCache(queryClient, queryKeys.sessions, updated);
+ },
+ [queryClient, qrData?.sessionId],
+ );
+
// Live session-feed subscription state: wildcard first, per-session fallback for scoped keys.
const feedStateRef = useRef(createSessionFeedState());
// Most recent server error frame; folded into feedStateRef by the effect below (kept as state
@@ -111,6 +135,10 @@ export function Sessions() {
s.id === event.sessionId ? { ...s, status: event.status as Session['status'] } : s,
);
setSessions(sessionsRef.current);
+ // Mark the shared session queries stale so sibling views refetch — but ONLY on a real
+ // transition (the dedup guard above already swallows the redundant double-signals, so this
+ // does not re-invalidate on duplicate envelopes).
+ void invalidateSessionQueries(queryClient, queryKeys.sessions);
if (event.status === 'ready') {
toast.success(t('sessions.toasts.readyTitle'), t('sessions.toasts.readyDesc'));
} else if (event.status === 'disconnected') {
@@ -125,7 +153,7 @@ export function Sessions() {
toast.error(t('sessions.toasts.failedTitle'), t('sessions.toasts.failedDesc'));
}
},
- [toast, t, fetchSessions],
+ [toast, t, fetchSessions, queryClient],
),
onServerError: useCallback((frame: { code: string }) => {
setFeedErrorFrame(frame);
@@ -257,7 +285,10 @@ export function Sessions() {
try {
setCreating(true);
const newSession = await sessionApi.create(newSessionName);
- setSessions([...sessions, newSession]);
+ // Functional append: never capture a stale `sessions` (a WS or fetch between the await and the
+ // setState would otherwise drop a row). Then invalidate the prefix so stats/groups/chats refresh.
+ setSessions(current => [...current, newSession]);
+ await invalidateSessionQueries(queryClient, queryKeys.sessions);
setNewSessionName('');
setShowCreateModal(false);
toast.success(t('sessions.create.successTitle'), t('sessions.create.successDesc', { name: newSession.name }));
@@ -274,7 +305,9 @@ export function Sessions() {
const session = sessions.find(s => s.id === id);
try {
await sessionApi.delete(id);
- setSessions(sessions.filter(s => s.id !== id));
+ // Functional removal (no stale `sessions` capture), then invalidate the prefix.
+ setSessions(current => current.filter(s => s.id !== id));
+ await invalidateSessionQueries(queryClient, queryKeys.sessions);
toast.success(
t('sessions.delete.successTitle'),
session
@@ -299,11 +332,22 @@ export function Sessions() {
try {
await sessionApi.start(id);
- setSessions(sessions.map(s => (s.id === id ? { ...s, status: 'connecting' } : s)));
+ setSessions(current => current.map(s => (s.id === id ? { ...s, status: 'connecting' } : s)));
await fetchSessions();
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.
+ 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');
+ toast.warning(t('sessions.start.teardownPendingTitle'), msg);
+ await fetchSessions();
+ return;
+ }
const fresh = await fetchSessions();
const current = fresh.find(s => s.id === id);
if (current?.status !== 'ready') handleShowQR(id);
@@ -342,24 +386,25 @@ export function Sessions() {
const handleStop = async (id: string) => {
try {
- await sessionApi.stop(id);
- setSessions(sessions.map(s => (s.id === id ? { ...s, status: 'disconnected' } : s)));
- if (qrData?.sessionId === id) setQrData(null);
+ const updated = await sessionApi.stop(id);
+ await applySessionResponse(updated);
} catch (err) {
console.error('Failed to stop:', err);
- fetchSessions();
+ // 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();
}
};
const handleForceKill = async (id: string) => {
try {
- await sessionApi.forceKill(id);
- setSessions(sessions.map(s => (s.id === id ? { ...s, status: 'disconnected' } : s)));
+ const updated = await sessionApi.forceKill(id);
+ await applySessionResponse(updated);
toast.success(t('sessions.forceKill.successTitle'), t('sessions.forceKill.success'));
} catch (err) {
console.error('Failed to force-kill:', err);
toast.error(t('sessions.forceKill.failedTitle'), t('sessions.forceKill.failed'));
- fetchSessions();
+ await fetchSessions();
} finally {
setKillConfirmId(null);
}
@@ -371,27 +416,31 @@ export function Sessions() {
if (unlinkingId) return;
setUnlinkingId(id);
try {
- await sessionApi.logout(id);
- setSessions(sessions.map(s => (s.id === id ? { ...s, status: 'disconnected' } : s)));
- if (qrData?.sessionId === id) setQrData(null);
+ const updated = await sessionApi.logout(id);
+ await applySessionResponse(updated);
toast.success(t('sessions.unlink.successTitle'), t('sessions.unlink.success'));
} catch (err) {
console.error('Failed to unlink:', err);
- if (classifyUnlinkError(err) === 'unconfirmed') {
- // 502 — the session DID stop locally, but WhatsApp has not confirmed the unlink. Not a
- // plain failure, so warn with retry guidance instead of raising an error toast.
- toast.warning(t('sessions.unlink.unconfirmedTitle'), t('sessions.unlink.unconfirmed'));
+ // The error response carries no Session body, so re-fetch authoritative state regardless of
+ // how we classify the toast — phone:null/status come from the list endpoint.
+ await fetchSessions();
+ if (classifyUnlinkError(err) === 'incomplete') {
+ // 502 + SESSION_LOGOUT_INCOMPLETE — the session stopped locally but the unlink operation is
+ // incomplete. Surface the server's specific message/retry guidance as a warning, not an error.
+ const msg = err instanceof Error && err.message ? err.message : t('sessions.unlink.incomplete');
+ toast.warning(t('sessions.unlink.incompleteTitle'), msg);
} else {
+ // A reverse-proxy 502 (bare or JSON without the exact code) may never have reached the
+ // gateway, so nothing was stopped — generic failure, not retry guidance.
toast.error(t('sessions.unlink.failedTitle'), t('sessions.unlink.failed'));
}
- fetchSessions();
} finally {
setUnlinkConfirmId(null);
setUnlinkingId(null);
}
};
- const formatLastActive = (date?: string) => {
+ const formatLastActive = (date?: string | null) => {
if (!date) return t('common.never');
const diff = Date.now() - new Date(date).getTime();
if (diff < 60000) return t('common.justNow');
@@ -913,7 +962,7 @@ export function Sessions() {
{t('sessions.actions.delete')}
</button>
)}
- {canWrite && session.status === 'failed' && (
+ {canForceKillSession(session.status, canWrite) && (
<button className="btn-action danger" onClick={() => setKillConfirmId(session.id)}>
<Skull size={16} />
{t('sessions.actions.killStuck')}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 6d051d1e1..cf97d1f69 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -36,9 +36,9 @@ export interface Session {
| 'disconnected'
| 'action_required'
| 'failed';
- phone?: string;
- pushName?: string;
- lastActive?: string;
+ phone?: string | null;
+ pushName?: string | null;
+ lastActive?: string | null;
createdAt: string;
updatedAt: string;
/** Human-readable reason carried while the status is 'failed' (terminal failure) or
@@ -567,8 +567,16 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<
const error = await response.json().catch(() => ({}));
// Carry the HTTP status on the Error (message unchanged, so the toast de-dup still matches) so
// callers can tell apart a permission 403 from a real server 5xx instead of guessing from text.
- const err = new Error(error.message || `HTTP ${response.status}`) as Error & { status?: number };
+ // Carry the machine `code` too: the gateway's stable codes (SESSION_LOGOUT_INCOMPLETE,
+ // SESSION_NAME_TEARDOWN_PENDING, …) drive specific recovery UI, and a reverse-proxy 502 that
+ // never reached the gateway carries no code at all — that distinction is exactly what the unlink
+ // classifier keys on instead of fragile message heuristics.
+ const err = new Error(error.message || `HTTP ${response.status}`) as Error & {
+ status?: number;
+ code?: string;
+ };
err.status = response.status;
+ if (typeof error.code === 'string') err.code = error.code;
throw err;
}
diff --git a/dashboard/src/utils/sessionActions.test.ts b/dashboard/src/utils/sessionActions.test.ts
index ae70d1193..8d3b8ba77 100644
--- a/dashboard/src/utils/sessionActions.test.ts
+++ b/dashboard/src/utils/sessionActions.test.ts
@@ -1,6 +1,29 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { canUnlinkSession, classifyUnlinkError, isSessionStarted } from './sessionActions.ts';
+import {
+ canForceKillSession,
+ canUnlinkSession,
+ classifyUnlinkError,
+ isSessionStarted,
+ replaceSession,
+} from './sessionActions.ts';
+import type { Session } from '../services/api.ts';
+
+// A minimal-but-complete Session factory for the pure-state assertions. Only id/name/status vary
+// in the tests; the rest mirrors the dashboard Session type so the typed helper accepts it.
+function makeSession(overrides: Partial<Session> = {}): Session {
+ return {
+ id: 's1',
+ name: 'session-1',
+ status: 'ready',
+ phone: '+155512345',
+ pushName: 'Alice',
+ lastActive: '2025-01-01T00:00:00.000Z',
+ createdAt: '2025-01-01T00:00:00.000Z',
+ updatedAt: '2025-01-01T00:00:00.000Z',
+ ...overrides,
+ };
+}
// Every status with a live engine must be "started": the card picks Stop vs Start from this, and
// offering Start to a started session gets a 400 and then a QR modal that can never resolve.
@@ -27,25 +50,111 @@ test('canUnlinkSession: a read-only role never sees the action, even for a start
assert.equal(canUnlinkSession('ready', false), false);
});
-test('classifyUnlinkError: the gateway 502 means the unlink was unconfirmed, not a plain failure', () => {
- const err = new Error('Session was stopped locally, but WhatsApp did not confirm') as Error & {
+// Force-kill is the emergency hatch for a WEDGED engine, so it must be offered exactly when a live
+// engine exists — never for FAILED (the engine is already gone, so there is nothing to kill).
+test('canForceKillSession: offered for every engine-backed status, hidden for terminal FAILED', () => {
+ for (const status of [
+ 'initializing',
+ 'connecting',
+ 'qr_ready',
+ 'authenticating',
+ 'ready',
+ 'action_required',
+ ]) {
+ assert.equal(canForceKillSession(status, true), true, `${status} is engine-backed and should offer kill`);
+ }
+ for (const status of ['created', 'idle', 'disconnected', 'failed']) {
+ assert.equal(canForceKillSession(status, true), false, `${status} has no live engine to kill`);
+ }
+});
+
+test('canForceKillSession: a read-only role never sees the action, even for a started session', () => {
+ assert.equal(canForceKillSession('ready', false), false);
+});
+
+// ── replaceSession ────────────────────────────────────────────────────────────
+
+// The authoritative API response replaces the matching row verbatim — losing phone:null was the
+// original bug, so the test pins that the exact response object is stored, not a merge.
+test('replaceSession: the exact authoritative response replaces the matching row, including phone:null', () => {
+ const before = [makeSession({ id: 'a' }), makeSession({ id: 'b' })];
+ const updated = makeSession({ id: 'b', status: 'disconnected', phone: null, pushName: null, lastActive: null });
+ const result = replaceSession(before, updated);
+
+ assert.equal(result.length, 2);
+ assert.deepEqual(result[1], updated);
+ assert.equal(result[1].phone, null);
+ assert.equal(result[1].pushName, null);
+ assert.equal(result[1].lastActive, null);
+});
+
+test('replaceSession: unrelated rows keep their identity and order', () => {
+ const a = makeSession({ id: 'a', name: 'alpha' });
+ const b = makeSession({ id: 'b', name: 'bravo' });
+ const c = makeSession({ id: 'c', name: 'charlie' });
+ const updated = makeSession({ id: 'b', status: 'disconnected' });
+ const result = replaceSession([a, b, c], updated);
+
+ assert.deepEqual(result.map(s => s.id), ['a', 'b', 'c']);
+ assert.equal(result[0], a, 'unrelated row keeps identity');
+ assert.equal(result[2], c, 'unrelated row keeps identity');
+ assert.equal(result[1], updated, 'matching row is the exact response object');
+});
+
+test('replaceSession: nullable pushName / lastActive are accepted and preserved', () => {
+ const before = [makeSession({ id: 'a', pushName: 'Alice', lastActive: '2025-01-01T00:00:00.000Z' })];
+ const updated = makeSession({ id: 'a', pushName: null, lastActive: null });
+ const result = replaceSession(before, updated);
+ assert.equal(result[0].pushName, null);
+ assert.equal(result[0].lastActive, null);
+});
+
+test('replaceSession: a response whose id is absent does not drop other rows (no match → no change)', () => {
+ const a = makeSession({ id: 'a' });
+ const b = makeSession({ id: 'b' });
+ const orphan = makeSession({ id: 'zzz', status: 'disconnected' });
+ const result = replaceSession([a, b], orphan);
+ assert.deepEqual(result.map(s => s.id), ['a', 'b']);
+ assert.equal(result[0], a);
+ assert.equal(result[1], b);
+});
+
+test('replaceSession: an empty list stays empty', () => {
+ assert.deepEqual(replaceSession([], makeSession({ id: 'a' })), []);
+});
+
+// ── classifyUnlinkError ───────────────────────────────────────────────────────
+//
+// Only the gateway's own stable code SESSION_LOGOUT_INCOMPLETE means "stopped locally but the
+// unlink operation is incomplete". A bare OR JSON reverse-proxy 502 without that exact code stays
+// generic — the request may never have reached the gateway, so nothing was stopped.
+
+test('classifyUnlinkError: the SESSION_LOGOUT_INCOMPLETE code yields incomplete', () => {
+ const err = new Error('Session was stopped locally, but the logout operation is incomplete') as Error & {
status?: number;
+ code?: string;
};
err.status = 502;
- assert.equal(classifyUnlinkError(err), 'unconfirmed');
+ err.code = 'SESSION_LOGOUT_INCOMPLETE';
+ assert.equal(classifyUnlinkError(err), 'incomplete');
+});
+
+test('classifyUnlinkError: a bare reverse-proxy 502 (no code) stays generic', () => {
+ const err = new Error('HTTP 502') as Error & { status?: number; code?: string };
+ err.status = 502;
+ assert.equal(classifyUnlinkError(err), 'generic');
});
-// A reverse proxy answers 502 too, and then nothing was stopped — telling the operator to retry the
-// unlink would be wrong. The API client's non-JSON fallback message is what distinguishes them.
-test('classifyUnlinkError: a reverse-proxy 502 is generic, not unconfirmed', () => {
- const err = new Error('HTTP 502') as Error & { status?: number };
+test('classifyUnlinkError: a JSON 502 WITHOUT the exact code stays generic', () => {
+ const err = new Error('some upstream proxy error') as Error & { status?: number; code?: string };
err.status = 502;
+ err.code = 'UPSTREAM_TIMEOUT'; // a foreign code, even on a 502, is not our gateway signal
assert.equal(classifyUnlinkError(err), 'generic');
});
test('classifyUnlinkError: everything else is generic', () => {
for (const status of [400, 401, 403, 404, 500, 503]) {
- const err = new Error('x') as Error & { status?: number };
+ const err = new Error('x') as Error & { status?: number; code?: string };
err.status = status;
assert.equal(classifyUnlinkError(err), 'generic', String(status));
}
diff --git a/dashboard/src/utils/sessionActions.ts b/dashboard/src/utils/sessionActions.ts
index c74164528..1e88bc474 100644
--- a/dashboard/src/utils/sessionActions.ts
+++ b/dashboard/src/utils/sessionActions.ts
@@ -1,10 +1,12 @@
// Which lifecycle actions a session card offers, extracted for direct unit testing (dashboard tests
// cover pure utils only).
+import type { Session } from '../services/api.ts';
+
// Statuses in which the API has an engine loaded for the session. This is the single source of truth
-// for the engine-backed actions — Stop and Unlink — because they share one precondition: something
-// live to act on. Keeping them on one set is what stops a card from offering an action the API
-// rejects, and, just as importantly, from offering Start to a session that is already started (the
+// for the engine-backed actions — Stop, Unlink, and Force-Kill — because they share one precondition:
+// something live to act on. Keeping them on one set is what stops a card from offering an action the
+// API rejects, and, just as importantly, from offering Start to a session that is already started (the
// API answers 400 and the page then opens a QR modal that can never resolve).
//
// `authenticating` and `action_required` belong here: both hold a live engine — the whatsapp-web.js
@@ -29,15 +31,27 @@ export function canUnlinkSession(status: string, canWrite: boolean): boolean {
return canWrite && isSessionStarted(status);
}
-// A 502 from the gateway is not a plain failure: the session DID stop locally, only WhatsApp's
-// confirmation is missing — the device may still be listed under Linked Devices, and the operator
-// should start the session and retry. Everything else (400/404/other 5xx) is a generic failure.
-export function classifyUnlinkError(err: unknown): 'unconfirmed' | 'generic' {
- const e = err as { status?: number; message?: string } | null | undefined;
- if (e?.status !== 502) return 'generic';
- // A reverse proxy in front of the API answers 502 as well, and then the request never reached the
- // gateway at all — nothing was stopped, so the "we stopped it, now retry the unlink" guidance would
- // be actively wrong. The API client falls back to a literal `HTTP <status>` message when the body is
- // not JSON, which is precisely the proxy case; the gateway's own 502 carries a real message.
- return e.message && !/^HTTP \d+$/.test(e.message) ? 'unconfirmed' : 'generic';
+// Force-kill is the emergency hatch for a WEDGED engine, so it is offered exactly when a live engine
+// exists. It must NOT be offered for FAILED: a terminal failure already evicted the engine, so there
+// is nothing left to kill — the card offers reconnect/manual start instead.
+export function canForceKillSession(status: string, canWrite: boolean): boolean {
+ return canWrite && isSessionStarted(status);
+}
+
+// Replace the row matching `updated.id` with the EXACT authoritative response object. The original
+// defect was that the page discarded the API response and fabricated `{ status: 'disconnected' }`,
+// losing server-owned fields (phone:null, timestamps). Returning the exact object — never a merge —
+// is what keeps the local view byte-for-byte with the server's authoritative state.
+export function replaceSession(sessions: Session[], updated: Session): Session[] {
+ return sessions.map(s => (s.id === updated.id ? updated : s));
+}
+
+// The gateway's own stable code SESSION_LOGOUT_INCOMPLETE is the only signal that the session stopped
+// locally while the unlink operation stayed incomplete. A reverse-proxy 502 — bare or a JSON body
+// without that exact code — must stay generic: the request may never have reached the gateway, so
+// nothing was stopped and the "start and retry the logout" guidance would be actively wrong. The code
+// is carried on the thrown API error (see services/api.ts), not inferred from a message heuristic.
+export function classifyUnlinkError(err: unknown): 'incomplete' | 'generic' {
+ const e = err as { code?: string } | null | undefined;
+ return e?.code === 'SESSION_LOGOUT_INCOMPLETE' ? 'incomplete' : 'generic';
}
diff --git a/dashboard/src/utils/sessionMutation.test.ts b/dashboard/src/utils/sessionMutation.test.ts
new file mode 100644
index 000000000..1557a98b3
--- /dev/null
+++ b/dashboard/src/utils/sessionMutation.test.ts
@@ -0,0 +1,110 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { QueryClient, keepPreviousData } from '@tanstack/react-query';
+import { invalidateSessionQueries, reconcileSessionCache } from './sessionMutation.ts';
+import type { Session } from '../services/api.ts';
+
+// A minimal-but-complete Session factory for the cache assertions.
+function makeSession(overrides: Partial<Session> = {}): Session {
+ return {
+ id: 's1',
+ name: 'session-1',
+ status: 'ready',
+ phone: '+155512345',
+ pushName: 'Alice',
+ lastActive: '2025-01-01T00:00:00.000Z',
+ createdAt: '2025-01-01T00:00:00.000Z',
+ updatedAt: '2025-01-01T00:00:00.000Z',
+ ...overrides,
+ };
+}
+
+function freshClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: { queries: { retry: false, placeholderData: keepPreviousData } },
+ });
+}
+
+// Reconciling a Session response into a seeded sessions cache must replace the matching row with the
+// EXACT authoritative object — losing phone:null was the original defect.
+test('reconcileSessionCache: replaces the matching row in the seeded sessions cache with the exact response', async () => {
+ const queryClient = freshClient();
+ const seeded = [makeSession({ id: 'a' }), makeSession({ id: 'b', phone: '+1' })];
+ queryClient.setQueryData<Session[]>(['sessions'], seeded);
+
+ const updated = makeSession({ id: 'b', status: 'disconnected', phone: null });
+ await reconcileSessionCache(queryClient, ['sessions'], updated);
+
+ const cached = queryClient.getQueryData<Session[]>(['sessions']);
+ assert.equal(cached?.length, 2);
+ assert.deepEqual(cached?.[1], updated);
+ assert.equal(cached?.[1].phone, null);
+});
+
+// The whole point of the helper: a Session response also marks the shared session queries stale so
+// the Dashboard (stats/groups/chats/templates) does not keep showing the pre-mutation counts.
+test('reconcileSessionCache: invalidates the sessions prefix (list + stats) but not unrelated keys', async () => {
+ const queryClient = freshClient();
+ const invalidated: string[] = [];
+ const original = queryClient.invalidateQueries.bind(queryClient);
+ queryClient.invalidateQueries = ((filters: { queryKey?: readonly unknown[] }) => {
+ invalidated.push(JSON.stringify(filters.queryKey ?? []));
+ return original(filters);
+ }) as typeof queryClient.invalidateQueries;
+
+ queryClient.setQueryData<Session[]>(['sessions'], [makeSession({ id: 'a' })]);
+ const updated = makeSession({ id: 'a', status: 'disconnected', phone: null });
+ await reconcileSessionCache(queryClient, ['sessions'], updated);
+
+ // The invalidate call targets the sessions prefix (matches list AND stats/groups/chats/templates).
+ assert.ok(
+ invalidated.some(k => k === '["sessions"]'),
+ `sessions prefix not invalidated; got ${JSON.stringify(invalidated)}`,
+ );
+});
+
+// The sessions list cache is shared with the Dashboard, so an update must NOT seed a row list into a
+// cache slot the page never populated — that would shadow the real list query with a one-row stub.
+test('reconcileSessionCache: an absent cache stays absent (no seeding with a one-row list)', async () => {
+ const queryClient = freshClient();
+ const updated = makeSession({ id: 'b', status: 'disconnected' });
+ await reconcileSessionCache(queryClient, ['sessions'], updated);
+ assert.equal(queryClient.getQueryData<Session[]>(['sessions']), undefined);
+});
+
+// create/delete use the same invalidate helper; it must mark the prefix stale so siblings refetch.
+test('invalidateSessionQueries: invalidates the sessions prefix', async () => {
+ const queryClient = freshClient();
+ const invalidated: unknown[] = [];
+ const original = queryClient.invalidateQueries.bind(queryClient);
+ queryClient.invalidateQueries = ((filters: { queryKey?: readonly unknown[] }) => {
+ invalidated.push(filters.queryKey);
+ return original(filters);
+ }) as typeof queryClient.invalidateQueries;
+
+ await invalidateSessionQueries(queryClient, ['sessions']);
+
+ assert.ok(
+ invalidated.some(k => JSON.stringify(k) === '["sessions"]'),
+ `sessions prefix not invalidated; got ${JSON.stringify(invalidated)}`,
+ );
+});
+
+// The helper receives the EXACT query key the caller built; passing the stats key invalidates only
+// the stats entry, and the ['sessions'] prefix is what callers use for the broad invalidate.
+test('invalidateSessionQueries: with the stats key only the stats cache family is touched', async () => {
+ const queryClient = freshClient();
+ const invalidated: unknown[] = [];
+ const original = queryClient.invalidateQueries.bind(queryClient);
+ queryClient.invalidateQueries = ((filters: { queryKey?: readonly unknown[] }) => {
+ invalidated.push(filters.queryKey);
+ return original(filters);
+ }) as typeof queryClient.invalidateQueries;
+
+ await invalidateSessionQueries(queryClient, ['sessions', 'stats']);
+
+ assert.ok(
+ invalidated.some(k => JSON.stringify(k) === '["sessions","stats"]'),
+ `stats key not invalidated; got ${JSON.stringify(invalidated)}`,
+ );
+});
diff --git a/dashboard/src/utils/sessionMutation.ts b/dashboard/src/utils/sessionMutation.ts
new file mode 100644
index 000000000..e7fb5425d
--- /dev/null
+++ b/dashboard/src/utils/sessionMutation.ts
@@ -0,0 +1,32 @@
+// Pure cache helpers that reconcile a page-local Session mutation with the shared TanStack Query
+// cache. Kept dependency-light on purpose: only type-only imports of Session/QueryClient/QueryKey so
+// the Node test runner (no browser `import.meta.env`) can load this module without pulling api.ts.
+
+import type { QueryClient, QueryKey } from '@tanstack/react-query';
+import type { Session } from '../services/api.ts';
+import { replaceSession } from './sessionActions.ts';
+
+/**
+ * Write the authoritative `updated` Session into the seeded `queryKey` cache and mark the whole
+ * `['sessions']` prefix stale so sibling views (Dashboard stats, groups, chats, templates) refetch.
+ *
+ * Does NOT seed an absent cache: if nothing has populated `queryKey` yet, the page holds no observer
+ * on it and seeding a one-row stub would shadow the real list query. The update is a verbatim
+ * replace (see {@link replaceSession}) so server-owned fields like `phone:null` survive.
+ */
+export async function reconcileSessionCache(
+ queryClient: QueryClient,
+ queryKey: QueryKey,
+ updated: Session,
+): Promise<void> {
+ queryClient.setQueryData<Session[]>(queryKey, cached => (cached ? replaceSession(cached, updated) : cached));
+ await invalidateSessionQueries(queryClient, queryKey);
+}
+
+/**
+ * Mark the `['sessions']` prefix stale so create/delete/status transitions don't leave the shared
+ * session queries (list, stats, per-session groups/chats/templates) showing pre-mutation data.
+ */
+export async function invalidateSessionQueries(queryClient: QueryClient, queryKey: QueryKey): Promise<void> {
+ await queryClient.invalidateQueries({ queryKey });
+}