Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(dashboard): add an Unlink action to session cards (#1002)
Yudhi Armyndharisf8d1d937939b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d06c21dc7..308533aec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,6 +48,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the audit-action enumeration in `docs/05`, the method tables in `docs/18` and `sdk/README.md`) nowinclude the route.+- **The dashboard's Sessions page gains an Unlink action** (#984). Wired to the logout endpoint, it+ is the only lifecycle button that tells WhatsApp anything: the device disappears from the account+ holder's Linked Devices list, and reconnecting requires a fresh QR scan or pairing code. It is+ labelled "Unlink" rather than "Logout" so it cannot be confused with the sidebar's own+ (authentication) logout, and it appears for exactly the states that have a live engine — the same+ visibility as Stop. The confirmation dialog spells out both consequences (fresh QR to reconnect;+ delete the session separately if local data should go too), and the 502 case — session stopped+ locally but the unlink unconfirmed by WhatsApp — surfaces as a warning toast with retry guidance+ instead of a plain error. Localized across all twelve dashboard locales.+### Fixed- **A wedged logout can no longer delete a freshly re-paired profile** (#994). `teardownEngineSafely`diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 70acb43ee..cbfb8efb9 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -308,6 +308,7 @@"start": "بدء","stop": "إيقاف","reconnect": "إعادة الاتصال",+ "unlink": "إلغاء الربط","delete": "حذف","killStuck": "إنهاء العالقة"},@@ -337,6 +338,18 @@"failedTitle": "فشل الإنهاء القسري","failed": "فشل إنهاء الجلسة قسريًا."},+ "unlink": {+ "title": "إلغاء ربط الجهاز",+ "message": "هل تريد إلغاء ربط الجلسة <strong>\"{{name}}\"</strong> بحساب واتساب؟",+ "warning": "سيُزيل واتساب هذا الجهاز من الأجهزة المرتبطة بالحساب وستتوقف الجلسة. تتطلب إعادة الاتصال مسح رمز QR جديدًا أو رمز اقتران. لحذف جميع البيانات المحلية أيضًا، احذف الجلسة بعد ذلك.",+ "confirm": "إلغاء الربط",+ "successTitle": "تم إلغاء ربط الجهاز",+ "success": "أزال واتساب الجهاز من الأجهزة المرتبطة بالحساب. تتطلب إعادة الاتصال مسح رمز QR جديدًا أو رمز اقتران.",+ "unconfirmedTitle": "لم يتم تأكيد إلغاء الربط",+ "unconfirmed": "توقفت الجلسة محليًا، لكن واتساب لم يؤكد إلغاء الربط — قد يظل الجهاز مدرجًا ضمن الأجهزة المرتبطة. ابدأ الجلسة وحاول مرة أخرى.",+ "failedTitle": "فشل إلغاء الربط",+ "failed": "تعذر إلغاء ربط الجلسة."+ },"pairing": {"tabQr": "رمز QR","tabPhone": "الربط عبر رقم الهاتف",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex e688b16a6..8a5d9afde 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -297,6 +297,7 @@"start": "Starten","stop": "Stoppen","reconnect": "Erneut verbinden",+ "unlink": "Trennen","delete": "Löschen","killStuck": "Hängende Sitzung beenden"},@@ -326,6 +327,18 @@"failedTitle": "Zwangsbeendigung fehlgeschlagen","failed": "Die Sitzung konnte nicht zwangsweise beendet werden."},+ "unlink": {+ "title": "Gerät trennen",+ "message": "Sitzung <strong>\"{{name}}\"</strong> vom WhatsApp-Konto trennen?",+ "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.",+ "failedTitle": "Trennen fehlgeschlagen",+ "failed": "Die Sitzung konnte nicht getrennt werden."+ },"pairing": {"tabQr": "QR-Code","tabPhone": "Mit Telefonnummer verknüpfen",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 705956e1f..75594d4bb 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -297,6 +297,7 @@"start": "Start","stop": "Stop","reconnect": "Reconnect",+ "unlink": "Unlink","delete": "Delete","killStuck": "Kill Stuck"},@@ -326,6 +327,18 @@"failedTitle": "Force-Kill Failed","failed": "Failed to force-kill the session."},+ "unlink": {+ "title": "Unlink Device",+ "message": "Unlink session <strong>\"{{name}}\"</strong> from the WhatsApp account?",+ "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.",+ "failedTitle": "Unlink Failed",+ "failed": "Failed to unlink the session."+ },"pairing": {"tabQr": "QR Code","tabPhone": "Link with Phone Number",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 714b14144..7358bde07 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -297,6 +297,7 @@"start": "Iniciar","stop": "Detener","reconnect": "Reconectar",+ "unlink": "Desvincular","delete": "Eliminar","killStuck": "Cerrar bloqueada"},@@ -326,6 +327,18 @@"failedTitle": "Error al forzar el cierre","failed": "No se pudo forzar el cierre de la sesión."},+ "unlink": {+ "title": "Desvincular dispositivo",+ "message": "¿Desvincular la sesión <strong>\"{{name}}\"</strong> de la cuenta de WhatsApp?",+ "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.",+ "failedTitle": "Error al desvincular",+ "failed": "No se pudo desvincular la sesión."+ },"pairing": {"tabQr": "Código QR","tabPhone": "Vincular con número de teléfono",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 21dacdd9e..bec434b5e 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -297,6 +297,7 @@"start": "Démarrer","stop": "Arrêter","reconnect": "Reconnecter",+ "unlink": "Dissocier","delete": "Supprimer","killStuck": "Arrêter (bloquée)"},@@ -326,6 +327,18 @@"failedTitle": "Échec de l'arrêt forcé","failed": "Échec de l'arrêt forcé de la session."},+ "unlink": {+ "title": "Dissocier l'appareil",+ "message": "Dissocier la session <strong>\"{{name}}\"</strong> du compte WhatsApp ?",+ "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.",+ "failedTitle": "Échec de la dissociation",+ "failed": "Impossible de dissocier la session."+ },"pairing": {"tabQr": "Code QR","tabPhone": "Lier avec un numéro de téléphone",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 9a40d4a9d..ba802de24 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -304,6 +304,7 @@"start": "הפעלה","stop": "עצירה","reconnect": "התחברות מחדש",+ "unlink": "ביטול קישור","delete": "מחיקה","killStuck": "סגור תקוע"},@@ -333,6 +334,18 @@"failedTitle": "הסגירה בכוח נכשלה","failed": "סגירת הסשן בכוח נכשלה."},+ "unlink": {+ "title": "ביטול קישור המכשיר",+ "message": "לבטל את קישור הסשן <strong>\"{{name}}\"</strong> מחשבון הוואטסאפ?",+ "warning": "וואטסאפ תסיר מכשיר זה מרשימת המכשירים המקושרים של החשבון והסשן ייעצר. ההתחברות מחדש דורשת סריקת QR חדשה או קוד התאמה. כדי למחוק גם את כל הנתונים המקומיים, מחק את הסשן לאחר מכן.",+ "confirm": "ביטול קישור",+ "successTitle": "המכשיר נותק",+ "success": "וואטסאפ הסירה את המכשיר מרשימת המכשירים המקושרים של החשבון. ההתחברות מחדש דורשת סריקת QR חדשה או קוד התאמה.",+ "unconfirmedTitle": "ביטול הקישור לא אושר",+ "unconfirmed": "הסשן נעצר מקומית, אך וואטסאפ לא אישרה את ביטול הקישור — ייתכן שהמכשיר עדיין מופיע ברשימת המכשירים המקושרים. הפעל את הסשן ונסה שוב.",+ "failedTitle": "ביטול הקישור נכשל",+ "failed": "לא ניתן לבטל את קישור הסשן."+ },"pairing": {"tabQr": "קוד QR","tabPhone": "קישור עם מספר טלפון",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 7768ff8a9..528a14312 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -297,6 +297,7 @@"start": "Avvia","stop": "Ferma","reconnect": "Riconnetti",+ "unlink": "Scollega","delete": "Elimina","killStuck": "Termina sessione bloccata"},@@ -326,6 +327,18 @@"failedTitle": "Terminazione forzata non riuscita","failed": "Impossibile terminare forzatamente la sessione."},+ "unlink": {+ "title": "Scollega dispositivo",+ "message": "Scollegare la sessione <strong>\"{{name}}\"</strong> dall'account WhatsApp?",+ "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.",+ "failedTitle": "Scollegamento non riuscito",+ "failed": "Impossibile scollegare la sessione."+ },"pairing": {"tabQr": "Codice QR","tabPhone": "Collega con numero di telefono",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 4b12e607b..f77511cb7 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -297,6 +297,7 @@"start": "시작","stop": "중지","reconnect": "재연결",+ "unlink": "연결 해제","delete": "삭제","killStuck": "강제 종료"},@@ -326,6 +327,18 @@"failedTitle": "강제 종료 실패","failed": "세션을 강제로 종료하지 못했습니다."},+ "unlink": {+ "title": "기기 연결 해제",+ "message": "세션 <strong>\"{{name}}\"</strong>을(를) WhatsApp 계정에서 연결 해제할까요?",+ "warning": "WhatsApp이 이 기기를 계정의 연결된 기기 목록에서 제거하고 세션이 중지됩니다. 다시 연결하려면 새 QR 스캔 또는 페어링 코드가 필요합니다. 로컬 데이터까지 모두 지우려면 이후 세션을 삭제하세요.",+ "confirm": "연결 해제",+ "successTitle": "기기 연결 해제됨",+ "success": "WhatsApp이 계정의 연결된 기기 목록에서 기기를 제거했습니다. 다시 연결하려면 새 QR 스캔 또는 페어링 코드가 필요합니다.",+ "unconfirmedTitle": "연결 해제 미확인",+ "unconfirmed": "세션이 로컬에서 중지되었지만 WhatsApp이 연결 해제를 확인하지 않았습니다. 기기가 연결된 기기 목록에 남아 있을 수 있습니다. 세션을 시작하고 다시 시도하세요.",+ "failedTitle": "연결 해제 실패",+ "failed": "세션 연결 해제에 실패했습니다."+ },"pairing": {"tabQr": "QR 코드","tabPhone": "전화번호로 연결",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 20721a141..c07aa78e5 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -297,6 +297,7 @@"start": "Iniciar","stop": "Parar","reconnect": "Reconectar",+ "unlink": "Desvincular","delete": "Excluir","killStuck": "Forçar encerramento"},@@ -326,6 +327,18 @@"failedTitle": "Falha no encerramento forçado","failed": "Não foi possível forçar o encerramento da sessão."},+ "unlink": {+ "title": "Desvincular dispositivo",+ "message": "Desvincular a sessão <strong>\"{{name}}\"</strong> da conta do WhatsApp?",+ "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.",+ "failedTitle": "Falha ao desvincular",+ "failed": "Não foi possível desvincular a sessão."+ },"pairing": {"tabQr": "Código QR","tabPhone": "Vincular com número de telefone",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 73606cb9f..fe3e82490 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -297,6 +297,7 @@"start": "ప్రారంభించు","stop": "ఆపివేయి","reconnect": "మళ్లీ కనెక్ట్ చేయి",+ "unlink": "అన్లింక్","delete": "తొలగించు","killStuck": "నిలిచిపోయినదాన్ని ఆపండి"},@@ -326,6 +327,18 @@"failedTitle": "బలవంతంగా ఆపడం విఫలమైంది","failed": "సెషన్ను బలవంతంగా ఆపడం విఫలమైంది."},+ "unlink": {+ "title": "పరికరాన్ని అన్లింక్ చేయండి",+ "message": "సెషన్ <strong>\"{{name}}\"</strong>ని WhatsApp ఖాతా నుండి అన్లింక్ చేయాలా?",+ "warning": "WhatsApp ఈ పరికరాన్ని ఖాతా యొక్క లింక్ చేసిన పరికరాల నుండి తొలగిస్తుంది మరియు సెషన్ ఆగిపోతుంది. మళ్లీ కనెక్ట్ చేయడానికి కొత్త QR స్కాన్ లేదా పెయిరింగ్ కోడ్ అవసరం. స్థానిక డేటాను కూడా తొలగించాలంటే, తర్వాత సెషన్ను తొలగించండి.",+ "confirm": "అన్లింక్",+ "successTitle": "పరికరం అన్లింక్ చేయబడింది",+ "success": "WhatsApp ఖాతా యొక్క లింక్ చేసిన పరికరాల నుండి పరికరాన్ని తొలగించింది. మళ్లీ కనెక్ట్ చేయడానికి కొత్త QR స్కాన్ లేదా పెయిరింగ్ కోడ్ అవసరం.",+ "unconfirmedTitle": "అన్లింక్ నిర్ధారించబడలేదు",+ "unconfirmed": "సెషన్ స్థానికంగా ఆగిపోయింది, కానీ WhatsApp అన్లింక్ను నిర్ధారించలేదు — పరికరం ఇంకా లింక్ చేసిన పరికరాల్లో జాబితా చేయబడి ఉండవచ్చు. సెషన్ను ప్రారంభించి మళ్లీ ప్రయత్నించండి.",+ "failedTitle": "అన్లింక్ విఫలమైంది",+ "failed": "సెషన్ను అన్లింక్ చేయడం విఫలమైంది."+ },"pairing": {"tabQr": "QR కోడ్","tabPhone": "ఫోన్ నంబర్తో లింక్ చేయండి",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex e576af2fa..2d8931f0a 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -297,6 +297,7 @@"start": "启动","stop": "停止","reconnect": "重新连接",+ "unlink": "取消关联","delete": "删除","killStuck": "终止卡死会话"},@@ -326,6 +327,18 @@"failedTitle": "强制终止失败","failed": "强制终止会话失败。"},+ "unlink": {+ "title": "取消关联设备",+ "message": "要将会话 <strong>\"{{name}}\"</strong> 从 WhatsApp 账号取消关联吗?",+ "warning": "WhatsApp 会将此设备从账号的已关联设备列表中移除,会话将停止。重新连接需要重新扫描二维码或使用配对码。如需同时清除所有本地数据,请随后删除该会话。",+ "confirm": "取消关联",+ "successTitle": "设备已取消关联",+ "success": "WhatsApp 已将设备从账号的已关联设备列表中移除。重新连接需要重新扫描二维码或使用配对码。",+ "unconfirmedTitle": "取消关联未确认",+ "unconfirmed": "会话已在本地停止,但 WhatsApp 未确认取消关联——设备可能仍列在已关联设备中。请启动会话后重试。",+ "failedTitle": "取消关联失败",+ "failed": "无法取消关联该会话。"+ },"pairing": {"tabQr": "QR 码","tabPhone": "使用电话号码关联",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 004bc8293..35e5035e3 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -297,6 +297,7 @@"start": "啟動","stop": "停止","reconnect": "重新連線",+ "unlink": "解除連結","delete": "刪除","killStuck": "強制終止"},@@ -326,6 +327,18 @@"failedTitle": "強制終止失敗","failed": "無法強制終止工作階段。"},+ "unlink": {+ "title": "解除裝置連結",+ "message": "要將工作階段 <strong>\"{{name}}\"</strong> 從 WhatsApp 帳戶解除連結嗎?",+ "warning": "WhatsApp 會將此裝置從帳戶的已連結裝置列表中移除,工作階段將停止。重新連接需要重新掃描 QR 碼或使用配對碼。如需同時清除所有本地資料,請隨後刪除該工作階段。",+ "confirm": "解除連結",+ "successTitle": "裝置已解除連結",+ "success": "WhatsApp 已將裝置從帳戶的已連結裝置列表中移除。重新連接需要重新掃描 QR 碼或使用配對碼。",+ "unconfirmedTitle": "解除連結未確認",+ "unconfirmed": "工作階段已在本地停止,但 WhatsApp 未確認解除連結——裝置可能仍列於已連結裝置中。請啟動工作階段後重試。",+ "failedTitle": "解除連結失敗",+ "failed": "無法解除該工作階段的連結。"+ },"pairing": {"tabQr": "QR 碼","tabPhone": "以電話號碼連結",diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex d6d299fbb..be11e4b45 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -1,10 +1,24 @@import { useState, useEffect, useCallback, useRef } from 'react';import { useQueryClient } from '@tanstack/react-query';import { Trans, useTranslation } from 'react-i18next';-import { Plus, QrCode, RefreshCw, Trash2, Eye, Loader2, Play, Square, Search, Filter, Skull } from 'lucide-react';+import {+ Plus,+ QrCode,+ RefreshCw,+ Trash2,+ Eye,+ Loader2,+ Play,+ Square,+ Search,+ Filter,+ Skull,+ Unlink,+} from 'lucide-react';import { sessionApi, type Session } from '../services/api';import { queryKeys } from '../hooks/queries';import { useDocumentTitle } from '../hooks/useDocumentTitle';+import { canUnlinkSession, classifyUnlinkError } from '../utils/sessionUnlink';import { useToast } from '../components/Toast';import { useWebSocket } from '../hooks/useWebSocket';import { useRole } from '../hooks/useRole';@@ -41,6 +55,7 @@ export function Sessions() {const [selectedSession, setSelectedSession] = useState<Session | null>(null);const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);const [killConfirmId, setKillConfirmId] = useState<string | null>(null);+ const [unlinkConfirmId, setUnlinkConfirmId] = useState<string | null>(null);const fetchSessions = useCallback(async (): Promise<Session[]> => {try {@@ -349,6 +364,27 @@ export function Sessions() {}};+ const handleUnlink = async (id: string) => {+ try {+ await sessionApi.logout(id);+ setSessions(sessions.map(s => (s.id === id ? { ...s, status: 'disconnected' } : s)));+ if (qrData?.sessionId === id) setQrData(null);+ 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'));+ } else {+ toast.error(t('sessions.unlink.failedTitle'), t('sessions.unlink.failed'));+ }+ fetchSessions();+ } finally {+ setUnlinkConfirmId(null);+ }+ };+const formatLastActive = (date?: string) => {if (!date) return t('common.never');const diff = Date.now() - new Date(date).getTime();@@ -752,6 +788,35 @@ export function Sessions() {</Modal>)}+ {unlinkConfirmId && (+ <Modal+ open+ onClose={() => setUnlinkConfirmId(null)}+ title={t('sessions.unlink.title')}+ className="confirm-modal"+ closeLabel={t('common.close')}+ footer={+ <>+ <button className="btn-secondary" onClick={() => setUnlinkConfirmId(null)}>+ {t('common.cancel')}+ </button>+ <button className="btn-danger" onClick={() => handleUnlink(unlinkConfirmId)}>+ {t('sessions.unlink.confirm')}+ </button>+ </>+ }+ >+ <p>+ <Trans+ i18nKey="sessions.unlink.message"+ values={{ name: sessions.find(s => s.id === unlinkConfirmId)?.name }}+ components={{ strong: <strong /> }}+ />+ </p>+ <p className="text-muted">{t('sessions.unlink.warning')}</p>+ </Modal>+ )}+<div className="sessions-grid">{filteredSessions.length === 0 ? (<div className="empty-state">@@ -826,6 +891,12 @@ export function Sessions() {{t('sessions.actions.reconnect')}</button>) : null}+ {canUnlinkSession(session.status, canWrite) && (+ <button className="btn-action danger" onClick={() => setUnlinkConfirmId(session.id)}>+ <Unlink size={16} />+ {t('sessions.actions.unlink')}+ </button>+ )}{canWrite && (<button className="btn-action danger" onClick={() => setDeleteConfirmId(session.id)}><Trash2 size={16} />diff --git a/dashboard/src/utils/sessionUnlink.test.ts b/dashboard/src/utils/sessionUnlink.test.tsnew file mode 100644index 000000000..2b5fe4328--- /dev/null+++ b/dashboard/src/utils/sessionUnlink.test.ts@@ -0,0 +1,34 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { canUnlinkSession, classifyUnlinkError } from './sessionUnlink.ts';++test('canUnlinkSession: only started states are unlinkable (they have a live engine)', () => {+ for (const status of ['ready', 'initializing', 'connecting', 'qr_ready']) {+ assert.equal(canUnlinkSession(status, true), true, status);+ }+ for (const status of ['created', 'idle', 'disconnected', 'failed', 'action_required']) {+ assert.equal(canUnlinkSession(status, true), false, status);+ }+});++test('canUnlinkSession: a read-only role never sees the action, even for a started session', () => {+ assert.equal(canUnlinkSession('ready', false), false);+});++test('classifyUnlinkError: 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 & {+ status?: number;+ };+ err.status = 502;+ assert.equal(classifyUnlinkError(err), 'unconfirmed');+});++test('classifyUnlinkError: everything else is generic', () => {+ for (const status of [400, 401, 403, 404, 500]) {+ const err = new Error('x') as Error & { status?: number };+ err.status = status;+ assert.equal(classifyUnlinkError(err), 'generic', String(status));+ }+ assert.equal(classifyUnlinkError(new Error('network down')), 'generic'); // no status at all+ assert.equal(classifyUnlinkError(undefined), 'generic');+});diff --git a/dashboard/src/utils/sessionUnlink.ts b/dashboard/src/utils/sessionUnlink.tsnew file mode 100644index 000000000..dec319f2e--- /dev/null+++ b/dashboard/src/utils/sessionUnlink.ts@@ -0,0 +1,22 @@+// Decision logic for the Sessions page Unlink action, extracted for direct unit testing+// (dashboard tests cover pure utils only). The action calls POST /sessions/:id/logout, which:+// - 400s when the session is not started — the unlink is a network round-trip that needs a+// live engine, so a stopped session is rejected rather than reported as a success, and+// - 502s when the session was stopped locally but WhatsApp did not confirm the unlink.++// Visibility mirrors Stop: only started states have a live engine to send the unlink through.+// A failed session is Kill Stuck's domain; a stopped session must be started before it can be+// unlinked (which is also what the API's 400 message tells the operator).+const UNLINKABLE_STATUSES = new Set(['ready', 'initializing', 'connecting', 'qr_ready']);++export function canUnlinkSession(status: string, canWrite: boolean): boolean {+ return canWrite && UNLINKABLE_STATUSES.has(status);+}++// The 502 case is not a plain failure: the session DID stop locally, only the confirmation from+// WhatsApp is missing — the device may still be listed under Linked Devices, and the operator+// should start the session and retry. Everything else (400/404/5xx) is a generic failure.+export function classifyUnlinkError(err: unknown): 'unconfirmed' | 'generic' {+ const status = (err as { status?: number } | null | undefined)?.status;+ return status === 502 ? 'unconfirmed' : 'generic';+}diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.mdindex 3b1416e37..23cbc8478 100644--- a/docs/17-dashboard-design.md+++ b/docs/17-dashboard-design.md@@ -195,9 +195,15 @@ a non-admin hitting the path falls through to the `*` redirect.│ │ │ │ Status: 🟢 Connected │ ││ │ └─────────┘ Platform: Android │ ││ │ │ │-│ │ [Restart Session] [Logout] [Delete] │ │+│ │ [Restart Session] [Unlink Device] [Delete] │ ││ └─────────────────────────────────────────────────────────────┘ ││ │+│ Unlink Device asks WhatsApp to remove this companion device from │+│ the account's Linked Devices (POST /sessions/:id/logout), then │+│ stops the session — reconnecting requires a fresh QR scan or │+│ pairing code. Delete only clears the local data; it does NOT │+│ unlink. │+│ ││ ┌─────────────────────┬─────────────────────┐ ││ │ 📊 Statistics │ ⚙️ Configuration │ ││ ├─────────────────────┼─────────────────────┤ │