For list messages, use type='list' instead of 'native_flow' in the
biz node structure. This allows the list button to open properly.
- native_flow messages: biz > interactive(type=native_flow) > native_flow
- list messages: biz > interactive(type=list) > list
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Changes the biz node from flat structure (biz > native_flow) to nested
structure (biz > interactive > native_flow) as used by Pastorini/Astra-Api.
Structure:
- biz: {}
- interactive: { type: 'native_flow', v: '1' }
- native_flow: { v: '9', name: 'mixed' }
This fixes error 479 that was breaking all interactive messages.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix carousel detection in getButtonType to return native_flow
- Add isCarouselMessage helper function
- Skip bot node injection for carousel messages (fixes error 479)
- Restore ProductCarouselCard and ProductCarouselMessageOptions types
- Restore generateProductCarouselMessage function
- Add productCarousel handler in generateWAMessageContent
The bot node with biz_bot='1' was causing error 479 for media carousels
because carousels are regular interactive messages, not bot messages.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The previous condition `!isJidGroup()` was too broad and would incorrectly
inject bot nodes for status broadcasts, newsletters, and Meta AI bots.
Now uses explicit checks for private 1:1 user conversations:
- isPnUser() for @s.whatsapp.net JIDs
- isLidUser() for @lid JIDs
- @c.us suffix for legacy format
- Excludes bot JIDs with isJidBot()
This prevents potential issues with message delivery to non-user destinations.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Update getButtonType() to return 'native_flow' for modern nativeFlowMessage format
- Add product list detection (PRODUCT_LIST type returns native_flow)
- Implement getButtonArgs() with proper v:4 attributes for native_flow
- Add special attribute handling for payment flows (review_and_pay, mpm, review_order)
- Add bot node injection for private chats (required for interactive messages to render)
- Based on Itsukichan/Baileys and baileys_helpers implementation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Address PR review comment: the viewOnceMessage detection now checks
all 7 message types for consistency with direct message detection:
- buttonsMessage
- templateMessage
- listMessage
- buttonsResponseMessage
- listResponseMessage
- templateButtonReplyMessage
- interactiveMessage
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The getButtonType function was not detecting interactive messages
when wrapped inside viewOnceMessage (the modern nativeFlowMessage format).
This fix adds detection for:
- viewOnceMessage > interactiveMessage
- viewOnceMessage > listMessage
- viewOnceMessage > buttonsMessage
When enableInteractiveMessages is true, the 'biz' node will now be
correctly injected for messages using the viewOnceMessage wrapper.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1. Add logger to writeCacheFile (version-cache.ts)
- Now logs warnings when file write fails
- Helps debugging in production environments
2. Sanitize logging in parseGroupResult (communities.ts)
- Changed from info to debug level
- Removed full node/groupNode dumps (sensitive data)
- Now only logs nodeTag and groupId
3. Add input validation in parseNewsletterCreateResponse (newsletter.ts)
- Validates response structure before destructuring
- Adds fallback values for parseInt (prevents NaN)
- Adds null checks for optional fields
4. Add health-status.ts module
- getHealthStatus(): Full health check with circuit breakers, cache, memory
- isHealthy(): Simple boolean for liveness probes
- getSimpleHealthStatus(): Returns 'ok', 'degraded', or 'error'
- Useful for k8s probes and monitoring dashboards
Fixes 3 issues identified in code review:
1. ENV VAR PRECEDENCE: Changed DEFAULT_CONNECTION_CONFIG to use
undefined for enableUnifiedSession, allowing env var
BAILEYS_UNIFIED_SESSION_ENABLED to take precedence.
Priority is now: explicit config > env var > default (true)
2. SINGLE INITIALIZATION: UnifiedSessionManager is now created
only once, after sendNode is defined. This avoids:
- Duplicate circuit breaker instances
- State reinitialization
- Unnecessary overhead and logs
3. CONTINUOUS TIME SYNC: serverTimeOffset is now updated on
every received frame that contains a 't' attribute, not just
on CB:success. This keeps the offset accurate even during
long-running connections.
Implements WhatsApp's unified_session telemetry feature to reduce
detection of unofficial clients. This is an enterprise-grade implementation
inspired by whatsmeow PR #1057 and Baileys PR #2294.
Features:
- UnifiedSessionManager class with circuit breaker protection
- Server time synchronization for accurate session IDs
- Rate limiting to prevent spam (1 minute between sends)
- Prometheus metrics integration (unified_session_sent, errors)
- Structured logging for debugging
- Configurable via SocketConfig.enableUnifiedSession
- Environment variable support (BAILEYS_UNIFIED_SESSION_ENABLED)
Trigger points (matching official WhatsApp Web):
- After successful login (CB:success)
- After successful pairing (CB:iq,,pair-success)
- When sending 'available' presence
Implementation details:
- Session ID algorithm: (now + serverOffset + 3days) % 7days
- Time constants exported from Defaults/index.ts
- Full test coverage (31 tests)
References:
- https://github.com/tulir/whatsmeow/pull/1057
- https://github.com/WhiskeySockets/Baileys/pull/2294
- https://github.com/tulir/whatsmeow/issues/810
Fix TS2345 errors where array element access (medias[i]) was inferred as
`AlbumMediaItem | undefined` instead of `AlbumMediaItem`.
Changes:
- Add non-null assertion (!) after array access in for loops
- Add explicit cast to AnyMessageContent for hasNonNullishProperty calls
The non-null assertion is safe here because we iterate with `i < medias.length`,
guaranteeing the index is valid.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Addresses additional PR review suggestions:
1. **Consistent media type validation**
- Changed from `'image' in m` to `hasNonNullishProperty(m, 'image')`
- Aligns with validation in generateWAMessageContent
- Prevents counting items with undefined image/video properties
2. **Explicit interrupted send indication**
- Added `attemptedItems: number` - how many items were actually tried
- Added `stoppedEarly: boolean` - true if interrupted by continueOnFailure=false
- Updated `success` to be false if stoppedEarly (even if no failures in attempted items)
- Helps automated integrations understand partial sends
Example result when interrupted:
```json
{
"totalItems": 5,
"attemptedItems": 3,
"successCount": 2,
"failedCount": 1,
"stoppedEarly": true,
"success": false
}
```
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fixes all issues identified in PR #44 review:
1. **Album root message now relayed to server** (Critical)
- Before: Only generated root message, never sent it
- After: Calls relayMessage() on albumRootMsg before sending media items
- Also emits own event if emitOwnEvents is enabled
2. **Fixed messageId collision**
- Before: Spread ...options could pass same messageId to all items
- After: Explicitly pass only safe options (timestamp, quoted, etc.)
- Each media item now gets a fresh ID from generateWAMessage
3. **Fixed proto structure for album association**
- Before: Used non-existent messageContextInfo.messageAddOnType
- After: Uses correct messageContextInfo.messageAssociation with:
- associationType: proto.MessageAssociation.AssociationType.MEDIA_ALBUM
- parentMessageKey: albumKey
4. **Added runtime error for sendMessage misuse**
- sendMessage() now throws clear error if called with { album: ... }
- Forces users to use sendAlbumMessage() for proper behavior
5. **Fixed documentation**
- delay: Changed "based on media size" to "based on media type"
- retryAttempts: Clarified it's "total attempts" not just retries
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implements WhatsApp album messages (grouped media) with the following features:
- Send 2-10 images/videos grouped as a single album message
- Adaptive delay between sends based on media type (videos get 2x delay)
- Intelligent retry with exponential backoff for failed items
- parentMessageKey reference to album root (as suggested by maintainer)
- Complete result structure with success/failure tracking per item
- Validation for min (2) and max (10) media items
Types added:
- AlbumMediaItem: Single image/video with caption, mentions, dimensions
- AlbumMessageOptions: Configuration for delay, retry, continueOnFailure
- AlbumMediaResult: Per-item result with latency and retry attempts
- AlbumSendResult: Complete result with albumKey and statistics
Based on PR #2058 from WhiskeySockets/Baileys with improvements.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Update outdated file reference in comment (process-message.ts:399-421
-> PDO response handler in src/Utils/process-message.ts)
- Add missing else branch in fallback path for duplicate request logging
to maintain observability parity with scheduled path
- Clarify log message in fallback path to reflect direct request flow
('Message received before direct resend request completed')
https://claude.ai/code/session_011WM4Nb6tE1S5nLjHen8Xsi
Aligns CTWA recovery with upstream philosophy by using messageRetryManager
instead of direct requestPlaceholderResend calls.
Benefits:
- Uses 3-second delay from manager (avoids request spam)
- Enables automatic cancellation if message arrives before request
- Centralizes phone request logic in messageRetryManager
- Adds fallback for when manager is not available
Changes:
- Wrap requestPlaceholderResend in messageRetryManager.schedulePhoneRequest()
- Add new metric status 'scheduled' for tracking scheduled requests
- Add metric status 'sent' when request is actually sent after delay
- Keep direct call as fallback when messageRetryManager is null
https://claude.ai/code/session_011WM4Nb6tE1S5nLjHen8Xsi
⚠️ EXPERIMENTAL FEATURE - Use only for testing with disposable accounts
Implements full support for WhatsApp interactive messages including:
- Simple text buttons (up to 3 buttons)
- Buttons with images/videos
- List messages (up to 10 items in sections)
- Template buttons (quick reply, URL, call actions)
- Carousel messages (up to 10 scrollable cards)
Features:
- Feature flag 'enableInteractiveMessages' (default: true for dev/testing)
- Prometheus metrics for tracking sends, successes, failures, and latency
- Comprehensive TypeScript types for all interactive message formats
- Extensive logging with warnings about potential account bans
- Automatic 'biz' node injection when feature is enabled
CRITICAL WARNINGS:
- These features may NOT work on non-business WhatsApp accounts
- Can cause temporary or permanent account BANS
- WhatsApp actively blocks this functionality since April 2022
- Messages may be rejected or fail silently
- Use ONLY in dev environment with test accounts
Architecture:
- Added ButtonInfo, Templatable, Listable, Carouselable types to Message.ts
- Extended AnyMediaMessageContent and AnyRegularMessageContent
- Implemented message generation in messages.ts
- Added getButtonType() and getButtonArgs() helpers in messages-send.ts
- Injected 'biz' node in stanza construction with metrics tracking
- Added 4 new Prometheus metrics: interactiveMessagesSent, Success, Failures, Latency
Documentation:
- Complete usage guide in INTERACTIVE_MESSAGES.md
- Examples for all interactive message types
- Metrics monitoring queries
- Troubleshooting guide
- Migration path to WhatsApp Business API
Related issues:
- https://github.com/WhiskeySockets/Baileys/issues/56
- https://github.com/WhiskeySockets/Baileys/issues/25
- https://github.com/WhiskeySockets/Baileys/pull/2291
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Prevents unnecessary placeholder resend requests for messages older than 7 days,
improving resource efficiency and aligning with upstream best practices. Adds
metrics tracking for rejected old messages and includes message age in logs.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Remove the override that was forcing full history sync when
syncFullHistory was true. Now uses the default from Defaults/index.ts
which skips FULL sync type for better performance and stability.
Benefits:
- Faster connection time (2-10s vs 30s-5min)
- Lower bandwidth usage (1-10MB vs 50-500MB+)
- More stable connections (no timeouts)
- INITIAL_BOOTSTRAP + RECENT provide sufficient data
Users can still customize via shouldSyncHistoryMessage if needed.
- Add fallback chain for contact name: displayName || name || username
- Add fallback for LID: lidJid || accountLid
- Add TODO marker for WAJIDHASH support in picture updates
These fallbacks improve robustness when WhatsApp returns contact
data in different fields depending on account type (business, personal).
Cherry-pick from upstream PR #2280 (commit 92d4198)
- Add STATUS_EXPIRY_SECONDS constant (24h = 86400s)
- Skip retry attempts for status broadcast messages older than 24h
- Saves resources by not retrying messages that are already expired
Co-authored-by: João Lucas de Oliveira Lopes <55464917+jlucaso1@users.noreply.github.com>
Added metrics tracking for:
- message_retries_total: Incremented when message retry is attempted
- message_failures_total: Incremented when max retries reached or encryption fails
Note: messages_queued metric is not applicable as this implementation
sends messages directly without an explicit queue system.
Added recordConnectionError() function and integrated it into socket.ts
to track connection errors by type:
- connection_closed
- connection_lost
- connection_replaced
- timed_out
- logged_out
- bad_session
- restart_required
- multidevice_mismatch
- error_{code} for other status codes
- Replace Function type with proper VersionCacheLogger interface
- Add documentation for cacheFilePath about container/serverless limitations
- Handle fetchInProgress in clearVersionCache to prevent cache restoration
- Add deduplication check in refreshVersionCache
- Remove unused fetchLatestWaWebVersion import
- Return success status from refreshVersionCache to detect fallback
- Fix inefficient getCachedVersion call - use cacheStatus.version directly
- Remove as any casts by using logger adapter pattern
- Don't downgrade version on transient network errors
Fixes from code review:
1. Fix #1,6: Use connection.update event instead of overriding sock.end()
- Listens for 'close' event to cleanup interval
- Handles both explicit close and internal disconnections
2. Fix#3: Exit code 2 when fetch fails (not 0)
- Allows CI to distinguish success/error/fetch-failed
- Properly signals fetch failures to workflows
3. Fix#4: Document revision bounds + add env vars
- Added detailed comments explaining min/max revision values
- Made configurable via WA_MIN_REVISION/WA_MAX_REVISION env vars
4. Fix #5,9: Remove unused fetchLatestVersion option
- Removed from SocketConfig and defaults
- Updated versionCheckIntervalMs docs to clarify it's only for makeWASocketAutoVersion
5. Fix#7: Use separate variable for version tracking
- trackedVersion instead of mutating mergedConfig
- Prevents unexpected side effects
6. Fix#8: Check socket state before emitting events
- isSocketClosed flag to prevent race conditions
- Double-check after async operations
7. Fix#10: Implement force parameter in workflow
- Creates PR even without version changes when force=true
- Useful for re-triggering updates manually
Note: Test coverage (Fix#2) deferred to separate PR due to
ESM mocking complexity with Jest.
Implements automatic version updates that are transparent to users:
- Checks for new WhatsApp Web version every 6 hours (configurable)
- When new version detected, saves it for next natural reconnection
- Emits 'version.update' event so users can track updates
- No disconnection required - WhatsApp naturally reconnects every 30min-2h
- Cleans up interval when socket closes
Configuration:
```typescript
const sock = await makeWASocketAutoVersion({
auth: state,
versionCheckIntervalMs: 6 * 60 * 60 * 1000 // 6 hours (default)
})
sock.ev.on('version.update', ({ currentVersion, newVersion, isCritical }) => {
console.log(`New version: ${newVersion.join('.')}`)
})
```
Adds a new async function that automatically fetches the latest
WhatsApp Web version from web.whatsapp.com before connecting.
Usage:
```typescript
// Option 1: Auto-fetch version (recommended)
const sock = await makeWASocketAutoVersion({ auth: state })
// Option 2: Manual version (existing behavior)
const sock = makeWASocket({ auth: state })
```
Benefits:
- No need to update library for version changes
- Automatic fallback to bundled version if fetch fails
- Logged warnings when using fallback
Messages from Facebook/Instagram ads (Click-to-WhatsApp) don't arrive on
linked devices because Meta's ads endpoint doesn't encrypt for multi-device.
They arrive as "Message absent from node" placeholders.
This change automatically requests the message from the primary phone via
PDO (Peer Data Operation) when a CTWA placeholder is detected.
Changes:
- Add enableCTWARecovery config option (default: true)
- Trigger requestPlaceholderResend() for "Message absent from node" errors
- Add Prometheus metrics for CTWA recovery tracking
- Add comprehensive unit tests for CTWA recovery functionality
Resolves: https://github.com/WhiskeySockets/Baileys/issues/1723
Resolves: https://github.com/WhiskeySockets/Baileys/issues/1034
Based on RSocket's battle-tested configuration:
- Add maxWebSocketListeners config option (default: 20)
- 8 base WS events + 10 dynamic listeners + 2 buffer slots
- Add maxSocketClientListeners config option (default: 50)
- Replace dangerous setMaxListeners(0) with configurable limits
- Add warning log if user explicitly sets limit to 0
BREAKING: Previous behavior used setMaxListeners(0) which removed
all limits. Now defaults to safe limits but can be overridden via config.
* fix: ensure proper socket closure and await connection termination in tests
* feat(tests): enhance E2E tests for image and video message handling, including downloads and group interactions