Fixes 4 issues identified in PR #35 code review:
## 1. Self-Primary Identity Check (Copilot #1)
- BEFORE: `ctx.meId && (areJidsSameUser(...) || (ctx.meLid && ...))`
- AFTER: Check meId and meLid independently with OR
- FIX: Now correctly detects when only meLid exists
## 2. Debounce Cache Placement (Copilot #3, #4)
- BEFORE: Cache set immediately after debounce check
- AFTER: Cache set only before actual assertSessions call
- FIX: Prevents incorrect debouncing when exiting early (offline, etc.)
## 3. Session Regression (ChatGPT Codex P2)
- BEFORE: Returned 'skipped_no_session' when no session exists
- AFTER: Always call assertSessions - identity change IS the signal to rebuild
- FIX: Critical for key reset and device restore scenarios
## 4. Result Type Enhancement
- Added `hadExistingSession: boolean` to 'session_refreshed' result
- Removed 'skipped_no_session' action (no longer applicable)
- Enables better monitoring of session creation vs refresh
## Test Updates
- Added test for meLid-only self-primary detection
- Updated session creation test (no longer skips)
- Added test verifying debounce not set on offline skip
- Added Result Types test suite for type safety
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>
Add extractPnFromMessages() function to extract phone numbers from
userReceipt fields when pnJid is missing in LID conversations.
This is a cherry-pick of the functionality from upstream PR #2282
(commit f829b6d7a) integrated with our existing LID-PN extraction logic.
Closes: WhiskeySockets/Baileys#2282
Metrics with labels only appear in Prometheus output after being
incremented at least once. This fix pre-initializes all labeled metrics
with zero values so they appear in Grafana dashboards immediately,
including buffer_destroyed_total which was showing "No data".
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 metrics tracking for:
- circuit_breaker_trips_total: Incremented when circuit opens
- adaptive_health_status: 1 if healthy (not in aggressive mode), 0 otherwise
- adaptive_event_rate: Current events per second
Added methods to AdaptiveTimeoutCalculator:
- getEventRate(): Returns current event rate in events/second
- isHealthy(): Returns true if not in aggressive mode
Metrics are updated on each buffer flush when adaptive timeout is enabled.
Added recordBufferDestroyed() and recordBufferFinalFlush() functions
and integrated into destroy() function in event-buffer.ts.
Tracks:
- Buffer destruction with reason and whether there was pending flush
- Final flushes that occur during buffer destruction
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
The metric was defined but never incremented when buffer overflow occurred.
Added recordBufferOverflow() function and call it from checkBufferOverflow()
when buffer exceeds maxBufferSize (default 5000 events).
The metric was defined but never incremented when LRU cleanup happened.
Added recordCacheCleanup() function and call it from cleanupHistoryCache()
when cache entries are removed due to exceeding maxHistoryCacheSize.
The buffer_cache_size metric was defined but never updated, always showing 0.
Fix:
- Add historyCacheSize parameter to recordBufferFlush function
- Pass historyCache.size from event-buffer.ts when recording flush metrics
- Update both bufferCacheSize and bufferHistoryCacheSize metrics
The buffer_flushes_total metric was registered twice with different labels:
- In main metrics object: ['type', 'reason']
- In getEventBufferMetrics(): ['forced']
This caused recordBufferFlush() to silently fail because it tried to
increment with { forced } labels but the registered metric expected
{ type, reason } labels.
Fix:
- Remove duplicate bufferFlushes from getEventBufferMetrics()
- Update recordBufferFlush() to use metrics.bufferFlushes with correct labels
- Update recordEventBuffered() to use main metrics.eventsBuffered
- Rename local variable to avoid shadowing global metrics object
Previously, buffer metrics required a separate BAILEYS_BUFFER_METRICS=true
env variable even when BAILEYS_PROMETHEUS_ENABLED=true was set. This caused
the buffer_flushes_total metric to have no data even though flushes were
occurring.
Now buffer metrics are enabled automatically when either BAILEYS_BUFFER_METRICS
or BAILEYS_PROMETHEUS_ENABLED is set to true.
Added new metrics:
- active_connections: Number of active WhatsApp connections
- connection_errors_total: Total connection errors by type
- buffer_destroyed_total: Total buffers destroyed
- buffer_final_flush_total: Final flushes during destruction
- buffer_cache_cleanup_total: Cache cleanup operations
- buffer_cache_size: Current buffer cache size
- adaptive_health_status: System health (0=unhealthy, 1=healthy)
- adaptive_event_rate: Current event rate per second
These metrics are required for the Grafana dashboard to display all panels correctly.
Check if nodejs_eventloop_lag_seconds metric already exists before creating
it in SystemMetricsCollector. This prevents conflicts when collectDefaultMetrics
from prom-client has already registered metrics with the same name.
Added helper functions metricExists() and getExistingMetric() to safely
check and retrieve existing metrics from the custom registry.
The Prometheus metrics server was implemented but never started because
initializeMetrics() was never called. This fix adds automatic initialization
when the module is loaded and BAILEYS_PROMETHEUS_ENABLED=true.
This ensures the /metrics endpoint is available without requiring manual
initialization in the application code.
When hkdf became async, mutationKeys also became async but the call
site wasn't updated. This caused Promise<Promise<Key>> instead of
Promise<Key>, breaking contact sync events (contacts.upsert).
Ref: WhiskeySockets/Baileys#2288
- 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