Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): auto-dismiss the new-account onboarding modal, else surface action_required (#982) (#998)

Yudhi Armyndharis9a542d68d381
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11490814b..d06c21dc7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **The whatsapp-web.js engine auto-dismisses a new account's "What's new on WhatsApp Web" onboarding
+ modal** (#982). A freshly-linked account shows this modal after `ready`, and left unacknowledged it
+ gets the companion unlinked roughly five minutes later — surfacing as `disconnected: LOGOUT`.
+ whatsapp-web.js exposes no API for the modal (its own #3550 is still open), so the adapter reaches
+ the underlying page directly and clicks Continue best-effort, matching by the visible button/modal
+ text (stable across WhatsApp Web builds, unlike class selectors). The watcher starts on `ready` and
+ self-terminates after a lifetime cap since the modal is one-shot per account. When the dismissal
+ cannot be performed — the selector has moved, the page is unreachable, or no Continue button was
+ found — the session moves to a new **`action_required`** status instead of being silently logged
+ out. That status carries a human-readable reason via `lastError` (relaxed from FAILED-only to also
+ cover ACTION_REQUIRED) and flows through the existing `session.status` webhook and WebSocket
+ channels, the dashboard status pill, and all five SDKs. The watcher's interval, lifetime cap, and
+ probe timeout are bounded and `.unref()`'d, and it is cleared on every teardown path.
+
- **`POST /sessions/:id/logout` unlinks the device from the WhatsApp account** (#984). Both engines
already implemented a real protocol-level unlink — whatsapp-web.js calls `WAWebSocketModel.Socket.logout()`
and Baileys sends `<remove-companion-device reason="user_initiated"/>` — but the method had no caller,
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 814f95468..70acb43ee 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -239,6 +239,7 @@
"qr_ready": "امسح رمز QR",
"ready": "متصل",
"disconnected": "غير متصل",
+ "action_required": "إجراء مطلوب",
"failed": "فشل",
"authenticating": "جارٍ المصادقة..."
},
@@ -315,6 +316,8 @@
"readyDesc": "جلسة واتساب متصلة الآن",
"disconnectedTitle": "انقطع اتصال الجلسة",
"disconnectedDesc": "انقطع اتصال جلسة واتساب",
+ "actionRequiredTitle": "إجراء مطلوب",
+ "actionRequiredDesc": "تتطلب هذه الجلسة انتباهك. افتح الجلسة لمعرفة ما يجب فعله.",
"failedTitle": "فشلت الجلسة",
"failedDesc": "فشل بدء جلسة واتساب. افتح الجلسة لمعرفة السبب."
},
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index f28265a92..e688b16a6 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -228,6 +228,7 @@
"qr_ready": "QR-Code scannen",
"ready": "Verbunden",
"disconnected": "Getrennt",
+ "action_required": "Handlung erforderlich",
"failed": "Fehlgeschlagen",
"authenticating": "Wird authentifiziert..."
},
@@ -304,6 +305,8 @@
"readyDesc": "Die WhatsApp-Sitzung ist jetzt verbunden",
"disconnectedTitle": "Sitzung getrennt",
"disconnectedDesc": "Die WhatsApp-Sitzung wurde getrennt",
+ "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."
},
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 7195deae8..705956e1f 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -228,6 +228,7 @@
"qr_ready": "Scan QR",
"ready": "Connected",
"disconnected": "Disconnected",
+ "action_required": "Action required",
"failed": "Failed",
"authenticating": "Authenticating..."
},
@@ -304,6 +305,8 @@
"readyDesc": "WhatsApp session is now connected",
"disconnectedTitle": "Session Disconnected",
"disconnectedDesc": "WhatsApp session was disconnected",
+ "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."
},
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index c65c7b407..714b14144 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -228,6 +228,7 @@
"qr_ready": "Escanear QR",
"ready": "Conectada",
"disconnected": "Desconectada",
+ "action_required": "Acción requerida",
"failed": "Fallida",
"authenticating": "Autenticando..."
},
@@ -304,6 +305,8 @@
"readyDesc": "La sesión de WhatsApp está conectada",
"disconnectedTitle": "Sesión desconectada",
"disconnectedDesc": "La sesión de WhatsApp se ha desconectado",
+ "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."
},
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index c46a053b0..21dacdd9e 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -228,6 +228,7 @@
"qr_ready": "Scanner le QR",
"ready": "Connecté",
"disconnected": "Déconnecté",
+ "action_required": "Action requise",
"failed": "Échec",
"authenticating": "Authentification..."
},
@@ -304,6 +305,8 @@
"readyDesc": "La session WhatsApp est maintenant connectée",
"disconnectedTitle": "Session déconnectée",
"disconnectedDesc": "La session WhatsApp a été déconnectée",
+ "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."
},
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index cf3004f47..9a40d4a9d 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -235,6 +235,7 @@
"qr_ready": "סריקת QR",
"ready": "מחובר",
"disconnected": "מנותק",
+ "action_required": "נדרשת פעולה",
"failed": "נכשל",
"authenticating": "מאמת..."
},
@@ -311,6 +312,8 @@
"readyDesc": "ה-Session של WhatsApp מחובר",
"disconnectedTitle": "ה-Session נותק",
"disconnectedDesc": "ה-Session של WhatsApp נותק",
+ "actionRequiredTitle": "נדרשת פעולה",
+ "actionRequiredDesc": "תקנת זו דורשת את תשומת לבך. פתח את התקנה כדי לראות מה לעשות.",
"failedTitle": "ה-Session נכשל",
"failedDesc": "ה-Session של WhatsApp נכשל באתחול. פתחו את ה-Session כדי לראות את הסיבה."
},
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 99219e6b0..7768ff8a9 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -228,6 +228,7 @@
"qr_ready": "Scansiona QR",
"ready": "Connesso",
"disconnected": "Disconnesso",
+ "action_required": "Azione richiesta",
"failed": "Non riuscita",
"authenticating": "Autenticazione in corso..."
},
@@ -304,6 +305,8 @@
"readyDesc": "La sessione WhatsApp è ora connessa",
"disconnectedTitle": "Sessione Disconnessa",
"disconnectedDesc": "La sessione WhatsApp è stata disconnessa",
+ "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."
},
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 6f9891490..4b12e607b 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -228,6 +228,7 @@
"qr_ready": "QR 스캔",
"ready": "연결됨",
"disconnected": "연결 끊김",
+ "action_required": "조치 필요",
"failed": "실패",
"authenticating": "인증하는 중..."
},
@@ -304,6 +305,8 @@
"readyDesc": "WhatsApp 세션이 연결되었습니다",
"disconnectedTitle": "세션 연결 끊김",
"disconnectedDesc": "WhatsApp 세션 연결이 끊어졌습니다",
+ "actionRequiredTitle": "조치 필요",
+ "actionRequiredDesc": "이 세션에 주의가 필요합니다. 할 일을 확인하려면 세션을 여세요.",
"failedTitle": "세션 실패",
"failedDesc": "WhatsApp 세션을 시작하지 못했습니다. 세션을 열어 원인을 확인하세요."
},
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index f27f88918..20721a141 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -228,6 +228,7 @@
"qr_ready": "Escanear QR",
"ready": "Conectada",
"disconnected": "Desconectada",
+ "action_required": "Ação necessária",
"failed": "Falha",
"authenticating": "Autenticando..."
},
@@ -304,6 +305,8 @@
"readyDesc": "A sessão do WhatsApp está conectada",
"disconnectedTitle": "Sessão desconectada",
"disconnectedDesc": "A sessão do WhatsApp foi desconectada",
+ "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."
},
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index eeb3d699f..73606cb9f 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -228,6 +228,7 @@
"qr_ready": "QR స్కాన్ చేయండి",
"ready": "కనెక్ట్ అయింది",
"disconnected": "డిస్‌కనెక్ట్ అయింది",
+ "action_required": "చర్య అవసరం",
"failed": "విఫలమైంది",
"authenticating": "ప్రామాణీకరిస్తోంది..."
},
@@ -304,6 +305,8 @@
"readyDesc": "వాట్సాప్ సెషన్ ఇప్పుడు కనెక్ట్ అయింది",
"disconnectedTitle": "సెషన్ డిస్‌కనెక్ట్ అయింది",
"disconnectedDesc": "వాట్సాప్ సెషన్ డిస్‌కనెక్ట్ చేయబడింది",
+ "actionRequiredTitle": "చర్య అవసరం",
+ "actionRequiredDesc": "ఈ సెషన్‌కు మీ శ్రద్ధ అవసరం. ఏమి చేయాలో చూడటానికి సెషన్‌ను తెరవండి.",
"failedTitle": "సెషన్ విఫలమైంది",
"failedDesc": "వాట్సాప్ సెషన్ ప్రారంభం కావడం విఫలమైంది. కారణాన్ని చూడటానికి సెషన్‌ను తెరవండి."
},
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 12a3a1e46..e576af2fa 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -228,6 +228,7 @@
"qr_ready": "扫描 QR",
"ready": "已连接",
"disconnected": "已断开",
+ "action_required": "需要操作",
"failed": "失败",
"authenticating": "正在验证..."
},
@@ -304,6 +305,8 @@
"readyDesc": "WhatsApp 会话现已连接",
"disconnectedTitle": "会话已断开",
"disconnectedDesc": "WhatsApp 会话已断开连接",
+ "actionRequiredTitle": "需要操作",
+ "actionRequiredDesc": "此会话需要您的关注。打开会话以查看需要做什么。",
"failedTitle": "会话失败",
"failedDesc": "WhatsApp 会话启动失败。打开该会话以查看原因。"
},
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 6ebbbbd56..004bc8293 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -228,6 +228,7 @@
"qr_ready": "掃描 QR",
"ready": "已連線",
"disconnected": "已中斷連線",
+ "action_required": "需要操作",
"failed": "失敗",
"authenticating": "正在驗證..."
},
@@ -304,6 +305,8 @@
"readyDesc": "WhatsApp 工作階段現已連線",
"disconnectedTitle": "工作階段已中斷連線",
"disconnectedDesc": "WhatsApp 工作階段已中斷連線",
+ "actionRequiredTitle": "需要操作",
+ "actionRequiredDesc": "此工作階段需要您的關注。開啟工作階段以查看需要做什麼。",
"failedTitle": "工作階段失敗",
"failedDesc": "WhatsApp 工作階段啟動失敗。開啟該工作階段以查看原因。"
},
diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.css
index 3323237d2..a40854eaf 100644
--- a/dashboard/src/pages/Sessions.css
+++ b/dashboard/src/pages/Sessions.css
@@ -645,6 +645,11 @@
color: var(--info);
}
+.sessions-page .status-pill.action_required {
+ background: rgba(245, 158, 11, 0.1);
+ color: #d97706;
+}
+
.sessions-page .status-pill.ready {
background: rgba(34, 197, 94, 0.1);
color: var(--success);
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index 9faa83bfa..d6d299fbb 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -99,6 +99,10 @@ export function Sessions() {
toast.success(t('sessions.toasts.readyTitle'), t('sessions.toasts.readyDesc'));
} else if (event.status === 'disconnected') {
toast.warning(t('sessions.toasts.disconnectedTitle'), t('sessions.toasts.disconnectedDesc'));
+ } else if (event.status === 'action_required') {
+ // Refresh so the card picks up the lastError reason (what the operator must do) from the API.
+ void fetchSessions();
+ toast.warning(t('sessions.toasts.actionRequiredTitle'), t('sessions.toasts.actionRequiredDesc'));
} else if (event.status === 'failed') {
// Refresh so the card picks up the lastError reason from the API.
void fetchSessions();
@@ -362,7 +366,8 @@ export function Sessions() {
const matchesStatus =
statusFilter === 'all' ||
(statusFilter === 'active' && s.status === 'ready') ||
- (statusFilter === 'inactive' && ['created', 'idle', 'disconnected', 'failed'].includes(s.status)) ||
+ (statusFilter === 'inactive' &&
+ ['created', 'idle', 'disconnected', 'action_required', 'failed'].includes(s.status)) ||
(statusFilter === 'connecting' &&
['initializing', 'connecting', 'authenticating', 'qr_ready'].includes(s.status));
return matchesSearch && matchesStatus;
@@ -788,7 +793,7 @@ export function Sessions() {
<span className="info-label">{t('sessions.card.lastActive')}</span>
<span className="info-value">{formatLastActive(session.lastActive)}</span>
</div>
- {session.status === 'failed' && session.lastError ? (
+ {(session.status === 'failed' || session.status === 'action_required') && session.lastError ? (
<div className="info-row session-error">
<span className="info-label">{t('sessions.card.error')}</span>
<span className="info-value error-text" title={session.lastError}>
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index de5dae2d9..6d051d1e1 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -34,13 +34,15 @@ export interface Session {
| 'qr_ready'
| 'ready'
| 'disconnected'
+ | 'action_required'
| 'failed';
phone?: string;
pushName?: string;
lastActive?: string;
createdAt: string;
updatedAt: string;
- /** Human-readable reason for the most recent terminal engine failure (set only when status is 'failed'). */
+ /** Human-readable reason carried while the status is 'failed' (terminal failure) or
+ * 'action_required' (operator must intervene, e.g. acknowledge an onboarding modal). */
lastError?: string | null;
}
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index b5bc06c0d..d04192bc9 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -76,7 +76,7 @@ List endpoints return a bare array (some paginated list routes instead return a
]
```
-Session `status` wire values are **lowercase**: `created | initializing | qr_ready | authenticating | ready | disconnected | failed`.
+Session `status` wire values are **lowercase**: `created | initializing | qr_ready | authenticating | ready | disconnected | action_required | failed`.
### Error Response
@@ -184,7 +184,7 @@ Every path below is prefixed with `/api`. Unless marked **public**, send `X-API-
### 6.4.1 Sessions
-Base path `/api/sessions`. All routes that return a session return data shaped by `SessionResponseDto.fromEntity` (via `transformSession`), which **strips** `config`, `proxyUrl`, and `proxyType` and renames the entity field `lastActiveAt` to `lastActive`. Session `status` wire values are lowercase: `created | initializing | qr_ready | authenticating | ready | disconnected | failed`.
+Base path `/api/sessions`. All routes that return a session return data shaped by `SessionResponseDto.fromEntity` (via `transformSession`), which **strips** `config`, `proxyUrl`, and `proxyType` and renames the entity field `lastActiveAt` to `lastActive`. Session `status` wire values are lowercase: `created | initializing | qr_ready | authenticating | ready | disconnected | action_required | failed`.
#### GET /api/sessions
@@ -5133,7 +5133,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
| `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
| `session.disconnected` | The session disconnects | `{ sessionId, reason }` |
| `session.reconnect_loop` | Every 5th consecutive reconnect attempt is scheduled (attempt 5, 10, 15, …) — the session is failing to come back up | `{ sessionId, attempts, nextDelayMs }` |
-| `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `failed` |
+| `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `action_required` / `failed` |
| `group.join` | Participant(s) are added to or join a group this session is in | `{ groupId, actorId?, participantIds, timestamp }` — `actorId` is the admin/inviter when known |
| `group.leave` | Participant(s) leave or are removed from a group | `{ groupId, actorId?, participantIds, timestamp }` |
| `group.update` | Group metadata changes (subject, description, announce/locked settings) | `{ groupId, actorId?, participantIds, changes?, timestamp }` — `changes` carries only the fields that changed: `subject?`, `description?`, `announce?`, `locked?` |
diff --git a/openapi.json b/openapi.json
index ad9265714..d8a2ecc0c 100644
--- a/openapi.json
+++ b/openapi.json
@@ -6248,6 +6248,7 @@
"authenticating",
"ready",
"disconnected",
+ "action_required",
"failed"
],
"example": "ready"
@@ -6316,6 +6317,7 @@
"authenticating",
"ready",
"disconnected",
+ "action_required",
"failed"
],
"example": "qr_ready"
diff --git a/sdk/go/types_session.go b/sdk/go/types_session.go
index 14fd0b5c8..cdc94d183 100644
--- a/sdk/go/types_session.go
+++ b/sdk/go/types_session.go
@@ -16,7 +16,8 @@ func (q *ListSessionsQuery) values() url.Values {
}
// SessionResponse describes a WhatsApp session. Status is one of: created,
-// initializing, qr_ready, authenticating, ready, disconnected, failed.
+// initializing, qr_ready, authenticating, ready, disconnected, action_required,
+// failed.
type SessionResponse struct {
ID string `json:"id"`
Name string `json:"name"`
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionStatus.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionStatus.java
index 94f6ba28f..6fa2cf8d8 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionStatus.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionStatus.java
@@ -19,6 +19,8 @@ public enum SessionStatus {
READY,
@SerializedName("disconnected")
DISCONNECTED,
+ @SerializedName("action_required")
+ ACTION_REQUIRED,
@SerializedName("failed")
FAILED
}
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 6524ae682..16d6c03c8 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -21,7 +21,14 @@ export type ChatKind = 'individual' | 'group' | 'channel' | 'status' | 'broadcas
/** Session lifecycle status. */
export type SessionStatus =
- 'created' | 'initializing' | 'qr_ready' | 'authenticating' | 'ready' | 'disconnected' | 'failed';
+ | 'created'
+ | 'initializing'
+ | 'qr_ready'
+ | 'authenticating'
+ | 'ready'
+ | 'disconnected'
+ | 'action_required'
+ | 'failed';
/** Minimal success envelope returned by some state-changing endpoints. */
export interface SuccessResult {
@@ -41,7 +48,7 @@ export interface SessionResponse {
lastActive?: string | null;
createdAt: string;
updatedAt: string;
- /** Only present when `status === 'failed'`. */
+ /** Only present when `status === 'failed'` (terminal failure) or `status === 'action_required'` (operator must intervene). */
lastError?: string | null;
}
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 1812f8fdd..f281ff07c 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -14,7 +14,14 @@ from typing import Any, Literal, Optional, TypedDict
Jid = str
SessionStatus = Literal[
- "created", "initializing", "qr_ready", "authenticating", "ready", "disconnected", "failed"
+ "created",
+ "initializing",
+ "qr_ready",
+ "authenticating",
+ "ready",
+ "disconnected",
+ "action_required",
+ "failed",
]
ChatState = Literal["typing", "recording", "paused"]
MessageDirection = Literal["incoming", "outgoing"]
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index b2d33e9d1..87452706e 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1066,7 +1066,9 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
client.emit('authenticated');
expect(adapter.getStatus()).toBe(EngineStatus.READY);
- expect(jest.getTimerCount()).toBe(0);
+ // Ready reconciliation is done (0 reconcile timers), but reaching READY arms the onboarding-modal
+ // watcher (#982), so one timer remains until it self-terminates or teardown clears it.
+ expect(jest.getTimerCount()).toBe(1);
expect(onReady).toHaveBeenCalledTimes(1);
});
@@ -4239,4 +4241,203 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
await expect(adapter.getProfilePicture('[email protected]')).resolves.toBeNull();
});
});
+
+ describe('WhatsAppWebJsAdapter onboarding modal watcher (#982)', () => {
+ type ModalProbe = { modalPresent: boolean; dismissed: boolean };
+
+ const newAdapter = (): WhatsAppWebJsAdapter =>
+ new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });
+
+ // Promote the adapter to READY the same way production does (authenticate then let the reconcile
+ // probe flip it), with a controllable pupPage.evaluate shared by both the reconcile probe and the
+ // watcher. Default `evaluate` returns true so the reconcile probe sees window.WWebJS and promotes
+ // to READY; individual tests override the return (mockResolvedValueOnce) for the next watcher tick.
+ const promoteToReady = (): {
+ adapter: WhatsAppWebJsAdapter;
+ client: EventEmitter & {
+ info?: { wid?: { user?: string }; pushname?: string };
+ getState: jest.Mock;
+ pupPage: { evaluate: jest.Mock };
+ };
+ evaluate: jest.Mock;
+ onActionRequired: jest.Mock;
+ onStateChanged: jest.Mock;
+ } => {
+ const adapter = newAdapter();
+ const evaluate = jest.fn();
+ const client = Object.assign(new EventEmitter(), {
+ info: { wid: { user: '628123' }, pushname: 'Tester' },
+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),
+ pupPage: { evaluate },
+ });
+ const onActionRequired = jest.fn();
+ const onStateChanged = jest.fn();
+ (adapter as unknown as { client: unknown }).client = client;
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onActionRequired, onStateChanged };
+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();
+ // Default: window.WWebJS present (reconcile probe) AND no modal (watcher ticks that aren't
+ // overridden). mockResolvedValueOnce in a test takes precedence for exactly the next call.
+ evaluate.mockResolvedValue(true);
+ return { adapter, client, evaluate, onActionRequired, onStateChanged };
+ };
+
+ it('dismisses the modal when the Continue button is present and keeps the session ready (no fallback)', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, evaluate, onActionRequired, client } = promoteToReady();
+
+ (client as EventEmitter).emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100); // reconcile → READY → watcher armed
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+
+ // Next watcher tick sees the modal and clicks Continue.
+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);
+ await jest.advanceTimersByTimeAsync(5100); // ONBOARDING_MODAL_INTERVAL_MS
+
+ expect(onActionRequired).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('falls back to ACTION_REQUIRED when the modal is present but Continue cannot be clicked', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, evaluate, onActionRequired } = promoteToReady();
+
+ (adapter as unknown as { client: EventEmitter }).client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+
+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: false } satisfies ModalProbe);
+ await jest.advanceTimersByTimeAsync(5100);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.ACTION_REQUIRED);
+ expect(onActionRequired).toHaveBeenCalledTimes(1);
+ expect(onActionRequired).toHaveBeenCalledWith(expect.stringMatching(/onboarding modal/i));
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('falls back to ACTION_REQUIRED when the page evaluate rejects (selector moved / page closed)', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, evaluate, onActionRequired } = promoteToReady();
+
+ (adapter as unknown as { client: EventEmitter }).client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+
+ evaluate.mockRejectedValueOnce(new Error('Execution context was destroyed'));
+ await jest.advanceTimersByTimeAsync(5100);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.ACTION_REQUIRED);
+ expect(onActionRequired).toHaveBeenCalledTimes(1);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('does not fire the fallback when no modal is present (over-suppression guard)', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, onActionRequired } = promoteToReady();
+
+ (adapter as unknown as { client: EventEmitter }).client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+
+ // Several ticks, all reporting no modal — must stay READY and never call onActionRequired.
+ await jest.advanceTimersByTimeAsync(5100);
+ await jest.advanceTimersByTimeAsync(5100);
+ await jest.advanceTimersByTimeAsync(5100);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(onActionRequired).not.toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('self-terminates after the lifetime cap with no dangling timer', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, onActionRequired } = promoteToReady();
+
+ (adapter as unknown as { client: EventEmitter }).client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+
+ // Walk just past the 5-minute lifetime cap; every tick sees no modal.
+ await jest.advanceTimersByTimeAsync(5 * 60_000 + 5100);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.READY); // never fell back — the modal never appeared
+ expect(onActionRequired).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0); // watcher self-terminated
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('is idempotent: a single watcher regardless of ready event vs reconcile path', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, client } = promoteToReady();
+
+ (client as EventEmitter).emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100); // reconcile promotes → watcher #1 armed
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(jest.getTimerCount()).toBe(1);
+
+ // A late 'ready' event runs markReadyFromClientInfo again — it must not arm a second watcher.
+ (client as EventEmitter).emit('ready');
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(jest.getTimerCount()).toBe(1);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('clears the watcher on teardown (no dangling timer across all teardown paths)', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, client } = promoteToReady();
+ (client as EventEmitter & { destroy?: jest.Mock }).destroy = jest.fn().mockResolvedValue(undefined);
+
+ (client as EventEmitter).emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(jest.getTimerCount()).toBe(1); // watcher armed
+
+ await adapter.destroy();
+
+ expect(jest.getTimerCount()).toBe(0); // watcher cleared on teardown
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('does not re-promote from ACTION_REQUIRED back to READY', async () => {
+ jest.useFakeTimers();
+ try {
+ const { adapter, evaluate, client, onActionRequired } = promoteToReady();
+
+ (client as EventEmitter).emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+
+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: false } satisfies ModalProbe);
+ await jest.advanceTimersByTimeAsync(5100);
+ expect(adapter.getStatus()).toBe(EngineStatus.ACTION_REQUIRED);
+
+ // A stray ready event must not resurrect READY from the action-required state.
+ (client as EventEmitter).emit('ready');
+ expect(adapter.getStatus()).toBe(EngineStatus.ACTION_REQUIRED);
+ expect(onActionRequired).toHaveBeenCalledTimes(1);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+ });
});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index d52939274..4b69d9d7b 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -293,6 +293,16 @@ export interface WhatsAppWebJsConfig {
const READY_RECONCILE_INTERVAL_MS = 2000;
const READY_RECONCILE_TIMEOUT_MS = 90_000;
+// Onboarding-modal watcher (#982). A freshly-linked account shows a "What's new on WhatsApp Web"
+// modal with a Continue button that must be acknowledged, or WhatsApp unlinks the companion ~5m
+// later (surfacing as disconnected: LOGOUT). whatsapp-web.js exposes no API for this (#3550 open),
+// so the watcher reaches the page directly, dismisses it best-effort, and falls back to
+// ACTION_REQUIRED if that fails. The modal is one-shot per account, so the watcher self-terminates
+// after the lifetime cap rather than polling forever.
+const ONBOARDING_MODAL_INTERVAL_MS = 5_000;
+const ONBOARDING_MODAL_MAX_LIFETIME_MS = 5 * 60_000;
+const ONBOARDING_MODAL_PROBE_TIMEOUT_MS = 5_000;
+
// WhatsApp Web version resolution (the #488 auto-resolve) lives in a dependency-free module so infra
// status can import it without loading whatsapp-web.js (engine lazy-loading). The adapter imports
// resolveWebVersionPin above for use in initialize().
@@ -354,6 +364,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
private readyReconcileTimer: ReturnType<typeof setTimeout> | null = null;
private readyReconcileStartedAt = 0;
private readyReconcileProbeInFlight = false;
+ // Onboarding-modal watcher handle (#982). Self-rescheduling setTimeout so a hung probe can't stall
+ // the loop; cleared on teardown exactly like readyReconcileTimer.
+ private onboardingWatcherTimer: ReturnType<typeof setTimeout> | null = null;
+ private onboardingWatcherStartedAt = 0;
+ private onboardingWatcherStarted = false;
/** How long a received call's handle stays rejectable. Calls ring for roughly a minute, so
* two minutes covers the ringing window with margin without pinning dead calls for long. */
private static readonly LIVE_CALL_TTL_MS = 2 * 60_000;
@@ -1074,7 +1089,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
private markReadyFromClientInfo(): void {
- if ([EngineStatus.READY, EngineStatus.DISCONNECTED, EngineStatus.FAILED].includes(this.status)) return;
+ if (
+ [EngineStatus.READY, EngineStatus.DISCONNECTED, EngineStatus.FAILED, EngineStatus.ACTION_REQUIRED].includes(
+ this.status,
+ )
+ )
+ return;
this.clearReadyReconcile();
try {
const info = this.client?.info;
@@ -1087,6 +1107,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.setStatus(EngineStatus.READY);
this.callbacks.onReady?.('', '');
}
+ // A freshly-linked account may show a "What's new" onboarding modal that, left unacknowledged,
+ // gets the companion unlinked (~5m later → disconnected: LOGOUT, #982). Dismiss it best-effort
+ // and fall back to ACTION_REQUIRED. Started after READY so a non-ready session never arms it.
+ this.startOnboardingWatcher();
}
private scheduleReadyReconcile(): void {
@@ -1152,6 +1176,120 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.readyReconcileProbeInFlight = false;
}
+ /**
+ * Dismiss a freshly-linked account's "What's new on WhatsApp Web" onboarding modal (#982). The modal
+ * has a Continue button that must be acknowledged or WhatsApp unlinks the companion ~5m later
+ * (surfacing as disconnected: LOGOUT). whatsapp-web.js exposes no API for this (#3550 open), so the
+ * watcher reaches the page directly. Idempotent and one-shot per engine: the modal appears once per
+ * account, so the loop self-terminates at the lifetime cap instead of polling forever. On any probe
+ * failure the session moves to ACTION_REQUIRED and surfaces the reason — never silently.
+ */
+ private startOnboardingWatcher(): void {
+ if (this.onboardingWatcherStarted) return; // idempotent: ready event + reconcile path share one funnel
+ this.onboardingWatcherStarted = true;
+ this.onboardingWatcherStartedAt = Date.now();
+
+ const tick = (): void => {
+ if (!this.client || this.status !== EngineStatus.READY || this.tearingDown || this.disconnectReported) {
+ this.clearOnboardingWatcher();
+ return;
+ }
+ // The modal is one-shot per account: stop after the lifetime cap rather than polling forever.
+ if (Date.now() - this.onboardingWatcherStartedAt >= ONBOARDING_MODAL_MAX_LIFETIME_MS) {
+ this.clearOnboardingWatcher();
+ return;
+ }
+ // Schedule the next tick up front so a hung page.evaluate can't stall the loop.
+ this.onboardingWatcherTimer = setTimeout(tick, ONBOARDING_MODAL_INTERVAL_MS);
+ this.onboardingWatcherTimer.unref?.();
+ // Fire-and-forget: a rejection is the fallback signal, not a crash.
+ void this.dismissOnboardingModalIfNeeded();
+ };
+
+ this.onboardingWatcherTimer = setTimeout(tick, ONBOARDING_MODAL_INTERVAL_MS);
+ this.onboardingWatcherTimer.unref?.();
+ }
+
+ private clearOnboardingWatcher(): void {
+ if (this.onboardingWatcherTimer) {
+ clearTimeout(this.onboardingWatcherTimer);
+ this.onboardingWatcherTimer = null;
+ }
+ this.onboardingWatcherStartedAt = 0;
+ }
+
+ /**
+ * One watcher tick: detect the onboarding modal and click Continue. Returns/throws rather than
+ * mutating state directly so the loop stays the single owner of the ACTION_REQUIRED transition.
+ * `undefined` = no modal (nothing to do); the page evaluating to a click is the success path; any
+ * thrown/rejected evaluate (selector moved, page closed, timeout) is treated as "needs attention".
+ */
+ private async dismissOnboardingModalIfNeeded(): Promise<void> {
+ if (!this.client) return;
+ const page = (this.client as unknown as { pupPage?: { evaluate: <T>(fn: () => T) => Promise<T> } }).pupPage;
+
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const result = await Promise.race([
+ page?.evaluate(() => {
+ // Match by visible text rather than class selectors — WhatsApp Web rebuilds its DOM across
+ // builds, but the button label ("Continue") and modal heading ("What's new") are stable.
+ const isVisible = (el: Element): boolean => {
+ const rect = (el as HTMLElement).getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0 && (el as HTMLElement).offsetParent !== null;
+ };
+ const candidates = Array.from(document.querySelectorAll('button, [role="button"], div'));
+ const heading = candidates.some(
+ el => isVisible(el) && /what'?s new/i.test((el.textContent || '').trim().slice(0, 64)),
+ );
+ if (!heading) return { modalPresent: false, dismissed: false };
+ const button = candidates
+ .filter(el => isVisible(el) && (el.textContent || '').trim() === 'Continue')
+ .slice(-1)[0];
+ if (!button) return { modalPresent: true, dismissed: false };
+ (button as HTMLElement).click();
+ return { modalPresent: true, dismissed: true };
+ }),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(
+ () => reject(new Error('onboarding modal probe timed out')),
+ ONBOARDING_MODAL_PROBE_TIMEOUT_MS,
+ );
+ timeout.unref?.();
+ }),
+ ]);
+
+ if (result?.modalPresent && !result.dismissed) {
+ // The modal is there but no clickable Continue was found — the account needs a human.
+ this.reportActionRequired(
+ 'WhatsApp is showing an onboarding modal ("What\'s new") that could not be dismissed ' +
+ "automatically. Acknowledge it (e.g. link a normal WhatsApp Web session on the phone's " +
+ 'number and click through) or the companion will be unlinked.',
+ );
+ }
+ } catch (error) {
+ // A page.evaluate failure after READY usually means the page navigated/closed mid-probe, but it
+ // also covers the modal having moved beyond recognition — surface ACTION_REQUIRED rather than
+ // letting the session be silently logged out at the five-minute mark.
+ this.reportActionRequired(
+ `Could not reach the WhatsApp Web page to dismiss the onboarding modal: ${
+ error instanceof Error ? error.message : String(error)
+ }. The session may be logged out shortly; acknowledge the onboarding on a normal WhatsApp Web ` +
+ 'session if the companion gets unlinked.',
+ );
+ } finally {
+ if (timeout) clearTimeout(timeout);
+ }
+ }
+
+ private reportActionRequired(reason: string): void {
+ this.clearOnboardingWatcher();
+ if (this.status !== EngineStatus.READY) return; // already leaving READY; don't override a teardown/failure
+ this.setStatus(EngineStatus.ACTION_REQUIRED);
+ this.callbacks.onActionRequired?.(reason);
+ this.logger.warn(reason, { sessionId: this.config.sessionId, action: 'onboarding_modal_fallback' });
+ }
+
/**
* Recover a session that authenticated but never reached runtime readiness (stale/incompatible auth
* or a wedged page). Clear the broken LocalAuth and disconnect so the session lifecycle re-pairs (a
@@ -1317,6 +1455,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
if (!client) return null;
this.clearReadyReconcile();
+ this.clearOnboardingWatcher();
if (this.status !== EngineStatus.DISCONNECTED) {
this.setStatus(EngineStatus.DISCONNECTED);
}
@@ -1329,6 +1468,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.client = null;
}
this.clearReadyReconcile();
+ this.clearOnboardingWatcher();
}
async disconnect(): Promise<void> {
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 4f825a647..327180c43 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -22,6 +22,7 @@ export enum EngineStatus {
QR_READY = 'qr_ready',
AUTHENTICATING = 'authenticating',
READY = 'ready',
+ ACTION_REQUIRED = 'action_required',
FAILED = 'failed',
}
@@ -528,6 +529,15 @@ export interface EngineEventCallbacks {
onHistoryMessages?: (messages: IncomingMessage[]) => void;
onDisconnected?: (reason: string) => void;
onStateChanged?: (state: EngineStatus) => void;
+ /**
+ * Fired when the engine needs an operator action to keep the session healthy — currently only the
+ * whatsapp-web.js onboarding-modal fallback (#982): a new account shows a "What's new" modal after
+ * linking that must be acknowledged, and the adapter dismisses it automatically; this fires only if
+ * that dismissal fails, so a headless deployment is told (rather than left to be logged out ~5m
+ * later). The engine has already moved to ACTION_REQUIRED; `reason` carries a human-readable cause.
+ * Distinct from `onError` (terminal) and `onDisconnected` (recoverable): intervention clears it.
+ */
+ onActionRequired?: (reason: string) => void;
/**
* Fired on a terminal initialization/authentication failure (e.g. Chromium
* could not launch, or WhatsApp rejected the stored credentials). The engine
diff --git a/src/modules/session/entities/session.entity.ts b/src/modules/session/entities/session.entity.ts
index fe4dc3b7a..2a09eb58b 100644
--- a/src/modules/session/entities/session.entity.ts
+++ b/src/modules/session/entities/session.entity.ts
@@ -9,6 +9,7 @@ export enum SessionStatus {
AUTHENTICATING = 'authenticating',
READY = 'ready',
DISCONNECTED = 'disconnected',
+ ACTION_REQUIRED = 'action_required',
FAILED = 'failed',
}
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 33b460e13..d9aaa87fc 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -274,6 +274,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
SessionStatus.INITIALIZING,
SessionStatus.QR_READY,
SessionStatus.AUTHENTICATING,
+ SessionStatus.ACTION_REQUIRED,
];
const result = await this.sessionRepository.update(
@@ -522,12 +523,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
/**
- * Populate the transient `lastError` field from the in-memory error map. Only a
- * FAILED session carries an error; any other status clears it so a recovered
- * session never shows a stale failure reason.
+ * Populate the transient `lastError` field from the in-memory error map. A FAILED session always
+ * carries its failure reason, and an ACTION_REQUIRED session carries what the operator must do
+ * (e.g. the whatsapp-web.js onboarding-modal fallback, #982); any other status clears it so a
+ * recovered session never shows a stale reason.
*/
private attachLastError(session: Session): Session {
- session.lastError = session.status === SessionStatus.FAILED ? this.sessionErrors.get(session.id) : undefined;
+ session.lastError =
+ session.status === SessionStatus.FAILED || session.status === SessionStatus.ACTION_REQUIRED
+ ? this.sessionErrors.get(session.id)
+ : undefined;
return session;
}
@@ -1533,6 +1538,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
[EngineStatus.QR_READY]: SessionStatus.QR_READY,
[EngineStatus.AUTHENTICATING]: SessionStatus.AUTHENTICATING,
[EngineStatus.READY]: SessionStatus.READY,
+ [EngineStatus.ACTION_REQUIRED]: SessionStatus.ACTION_REQUIRED,
[EngineStatus.FAILED]: SessionStatus.FAILED,
};
const newStatus = statusMap[engineState];
@@ -1540,6 +1546,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
void this.updateStatus(id, newStatus);
}
},
+ onActionRequired: (reason: string): void => {
+ if (!this.isLiveEngine(id, engine)) return;
+ this.logger.warn(`Session requires operator action: ${reason}`, {
+ sessionId: id,
+ reason,
+ action: 'action_required',
+ });
+ // Record the reason so attachLastError surfaces it while the session is ACTION_REQUIRED,
+ // then updateStatus (via onStateChanged above) has already written the status. Set here too
+ // to be defensive: the callback order is onActionRequired then onStateChanged, but persisting
+ // the reason here means it is available regardless.
+ this.sessionErrors.set(id, reason);
+ void this.hookManager.execute('session:error', { reason }, { sessionId: id, source: 'Engine' });
+ },
onError: (reason: string): void => {
if (!this.isLiveEngine(id, engine)) return;
this.logger.error(`Session engine failed: ${reason}`, undefined, {