Commit Graph

2381 Commits

Author SHA1 Message Date
Claude 65768bc70c refactor(ctwa): use messageRetryManager for placeholder resend scheduling
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
2026-01-23 13:17:32 +00:00
Renato Alcara 87ed383ba4 fix(messages): reorganize interactive message processing to execute correctly
Critical bug fix: Interactive message blocks were never being executed because
they were placed AFTER the normal text message processing block. Messages with
text+buttons were processed as plain text, ignoring the interactive features.

Changes:
- Move all interactive message processing (buttons, lists, templates, carousel)
  to BEFORE the normal text processing block
- Remove duplicate interactive message blocks that were unreachable
- Ensure correct execution order: check for interactive features first, then
  fallback to normal text processing

This fixes the runtime error where interactive message functions were not
being called properly when sending messages with buttons/lists.

Structure now:
1. Check text + buttons → buttonsMessage
2. Check text + templateButtons → templateMessage
3. Check sections → listMessage
4. Check carousel → interactiveMessage
5. Check text (normal) → extendedTextMessage
6. Other message types...

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-23 01:23:24 -03:00
Renato Alcara b48dbd7038 fix(types): resolve TypeScript compilation errors in interactive messages
Fixes type incompatibility error when processing buttons with media:
- Extract only media properties before passing to prepareWAMessageMedia
- Remove problematic interactiveMessage type from AnyRegularMessageContent
- Move Carouselable to text message type as Partial

This resolves the compilation error:
  error TS2345: Argument of type '...' is not assignable to parameter
  of type 'AnyMediaMessageContent'

Changes:
- src/Utils/messages.ts: Extract media content explicitly for type safety
- src/Types/Message.ts: Simplify type definitions, add Carouselable to text messages

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-23 01:14:58 -03:00
Renato Alcara 90db2512d9 feat(experimental): add interactive messages support (buttons, lists, templates, carousel)
⚠️ 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>
2026-01-23 00:51:33 -03:00
Renato Alcara fe2563d509 fix baileys install
fix baileys install
2026-01-22 20:57:26 -03:00
Claude 1ffaec663d fix(types): remove duplicate enableCTWARecovery declaration in SocketConfig
The property was declared twice in SocketConfig type:
- Line 134 as required boolean
- Line 211 as optional boolean

This caused TypeScript compilation errors:
- TS2300: Duplicate identifier
- TS2687: Mismatched modifiers
- TS2717: Type mismatch between required and optional

Removed the duplicate declaration, keeping the first one which is
already properly documented and has the correct type.
2026-01-22 23:55:59 +00:00
Renato Alcara 7ec7e2c430 fix(messages-recv): add age validation for CTWA placeholder resend requests
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>
2026-01-22 20:07:11 -03:00
Renato Alcara b205a43eab fix: align noise-handler buffer types for TypeScript
fix: align noise-handler buffer types for TypeScript
2026-01-22 17:55:16 -03:00
Claude 7d2a1fc540 fix: align noise-handler buffer types for TypeScript 5.x compatibility
- Add explicit Buffer type annotations to salt, encKey, decKey variables
- Add Promise<[Buffer, Buffer]> return type to localHKDF function
- Add Buffer type casts for subarray return values
- Remove unnecessary non-null assertion operators (!)

Fixes TS2322 type mismatch errors when building with TypeScript 5.9.3+
and Node.js v24+. No runtime behavior changes.

Based on upstream PR #2284.
2026-01-22 20:51:43 +00:00
Renato Alcara 1171db5924 fix(example): correct logger parameter order and fix wrong event
fix(example): correct logger parameter order and fix wrong event
2026-01-22 17:45:51 -03:00
Claude 3d4ba16dc5 fix(example): correct logger parameter order and fix wrong event
Address PR #38 review comments:
- Fix contacts.upsert logging wrong event (was message-receipt.update)
- Fix chats.delete logger params order (object, message)
- Fix group.member-tag.update params order and remove redundant JSON.stringify

Follows pino logger convention: logger.method(object, message)
2026-01-22 20:42:34 +00:00
Renato Alcara 561a9a8e28 merge upstream
merge upstream
2026-01-22 17:31:26 -03:00
Claude 1a1fc9daff chore: mark upstream commits as integrated
Merge upstream/master using 'ours' strategy to mark the following
commits as integrated (already cherry-picked with customizations):

- chat-utils,sync-action-utils: provide alternatives for the contact name
- example: revamp logging for example
- defaults, index: change shouldSyncHistoryMessage behavior
- history: fortify contact data
- history: add proper logging support in history
- example: cleanup
- socket: no sync warning!!!!!
- Fix connection showing "Online" but disconnected (#2132)
- fix: skip retry for expired status messages over 24 hours old
- fix: optimize getLIDsForPNs and add getPNsForLIDs (#2274)
- fix: extract LID-PN mappings from conversation objects in history sync

Our customizations are preserved. This zeros the "behind" counter.
2026-01-22 20:28:19 +00:00
Claude b288c41d11 Merge branch 'claude/feat-identity-change-handler-eQVNg' 2026-01-22 20:28:03 +00:00
Claude fe9a3166a8 chat-utils: add fallbacks for contact name extraction
Apply consistent fallback pattern for contact names:
- chat-utils.ts: fullName || firstName || username for lidContactAction
- sync-action-utils.ts: fullName || firstName || username for processContactAction

Ensures contact names are extracted regardless of which field WhatsApp populates.
2026-01-22 20:11:20 +00:00
Claude b69f6c6b6b example: use structured logging instead of console.log
Refactor example.ts to use pino logger with structured data:
- Replace all console.log with logger.debug/fatal
- Use objects for data instead of string concatenation
- Add contacts.upsert event handler
- Improves log filtering and searchability
2026-01-22 20:03:32 +00:00
Claude f2dd5c81c8 config: skip FULL history sync by default (market standard)
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.
2026-01-22 19:59:20 +00:00
Renato Alcara ec22355902 feat(history): fortify contact data extraction with fallbacks
feat(history): fortify contact data extraction with fallbacks
2026-01-22 16:50:33 -03:00
Claude 1dfdd47a12 feat(history): fortify contact data extraction with fallbacks
- 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).
2026-01-22 19:48:20 +00:00
Renato Alcara 5395ecd213 feat(history): add proper logging support for history sync debugging
feat(history): add proper logging support for history sync debugging
2026-01-22 16:29:56 -03:00
Claude 5d97e170d2 feat(history): add proper logging support for history sync debugging
- Add optional ILogger parameter to processHistoryMessage and
  downloadAndProcessHistorySyncNotification functions
- Add trace-level logging with syncType and progress for debugging
- Preserve all existing imports and LID-PN extraction functionality
- Enhanced JSDoc documentation with detailed parameter descriptions

This enables trace-level visibility into history sync processing,
helping debug issues with message synchronization and LID mappings.
2026-01-22 19:24:36 +00:00
Renato Alcara 6257648086 feat: add identity change handler for improved connection stability
feat: add identity change handler for improved connection stability
2026-01-22 16:01:11 -03:00
Claude 4a3d8e9e46 fix: address PR review comments for identity change handler
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
2026-01-22 18:55:01 +00:00
Claude c4da46321f feat: add identity change handler for improved connection stability
Cherry-pick from upstream PR #2264 (commit 5cbad317) with enhancements:

## Changes

### New Files
- `src/Utils/identity-change-handler.ts`: Centralized identity change handling
  - Enterprise-grade JSDoc documentation
  - Clear result types for all 9 possible outcomes
  - Debouncing to prevent duplicate session refreshes
  - Companion device filtering
  - Offline notification handling

- `src/__tests__/Socket/identity-change-handling.test.ts`: Comprehensive tests
  - Core functionality tests
  - Debounce behavior tests
  - Error handling tests
  - Edge case coverage

### Modified Files
- `src/Socket/messages-recv.ts`: Updated error handling
  - MISSING_KEYS_ERROR now returns NACK with ParsingError
  - Maintains CTWA recovery logic intact
  - Preserves all Prometheus metrics integration

- `src/Utils/generics.ts`: Added `isStringNullOrEmpty()` helper
- `src/Utils/index.ts`: Added identity-change-handler export

## Benefits
- Fixes "Online" status shown when actually disconnected (#2132)
- Better session management after contact identity changes
- Clear separation of concerns with dedicated handler module

Co-authored-by: João Lucas de Oliveira Lopes <55464917+jlucaso1@users.noreply.github.com>
2026-01-22 18:34:19 +00:00
Renato Alcara 8141e0dfcc Merge pull request #34
fix merge conflict e qv ng
2026-01-22 15:25:35 -03:00
Claude 9e1e67df6a fix: skip retry for expired status messages over 24 hours old
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>
2026-01-22 18:24:18 +00:00
Renato Alcara 8ddfc4d5a5 Merge pull request #33
feat(history): add userReceipt fallback for LID-PN mapping extraction
2026-01-22 14:19:10 -03:00
Claude 55e86987e9 feat(history): add userReceipt fallback for LID-PN mapping extraction
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
2026-01-22 17:13:07 +00:00
Renato Alcara 83936cfec2 Functionality: Add automatic retrieval of messages from CTWA (Click-to-WhatsApp) ads.
Functionality: Add automatic retrieval of messages from CTWA (Click-to-WhatsApp) ads.
2026-01-22 14:02:48 -03:00
Claude 2b3ab32596 Merge branch 'claude/ctwa-upstream-no-metrics-FdFq2' into claude/fix-merge-conflict-eQVNg 2026-01-22 16:59:27 +00:00
Claude 5d889d67b3 fix: resolve merge conflicts with master branch
Merge origin/master into CTWA recovery feature branch

Resolved conflicts:
- src/Defaults/index.ts: kept detailed comment about enableCTWARecovery
- src/Socket/messages-recv.ts: integrated metrics with CTWA recovery logic
- src/__tests__/Utils/ctwa-recovery.test.ts: added metrics tests
2026-01-22 16:58:59 +00:00
Claude ff16ed53e9 fix: resolve merge conflicts for CTWA recovery feature PR #31
Merge branch 'claude/ctwa-upstream-no-metrics-FdFq2' into master

Resolved conflicts:
- src/Defaults/index.ts: kept detailed comment about enableCTWARecovery
- src/Socket/messages-recv.ts: preserved metrics integration with CTWA recovery
- src/__tests__/Utils/ctwa-recovery.test.ts: kept metrics tests
2026-01-22 16:50:42 +00:00
Renato Alcara 04ecb21210 fix prometheus server
fix prometheus server
2026-01-22 13:43:43 -03:00
Claude bc7fcca45f fix: initialize metrics with labels to show zero values in Prometheus
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".
2026-01-22 15:14:29 +00:00
Claude b3917299cd feat: add message retry and failure metrics tracking
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.
2026-01-22 14:42:22 +00:00
Claude de5988ba8f feat: implement WhatsApp connection and message metrics
Added tracking for all WhatsApp-related metrics:

Connection metrics:
- active_connections: Gauge tracking active connections (inc on open, dec on close)
- connection_attempts_total: Counter for connection attempts (success/failure)

Message metrics:
- messages_sent_total: Counter with type label (text, image, video, audio, etc)
- messages_received_total: Counter with type label
- history_sync_messages_total: Counter for history sync messages

Added helper functions in prometheus-metrics.ts:
- incrementActiveConnections(), decrementActiveConnections(), setActiveConnections()
- recordConnectionAttempt(status)
- recordMessageSent(type), recordMessageReceived(type)
- recordMessageRetry(type), recordMessageFailure(type, reason)
- setMessagesQueued(count, priority)
- recordHistorySyncMessages(count)
2026-01-22 14:20:17 +00:00
Claude f9ed1dc16f feat: add adaptive metrics and circuit breaker trips tracking
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.
2026-01-22 13:57:34 +00:00
Claude 5b8ea3bb2b fix: add buffer_destroyed_total and buffer_final_flush_total metrics
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
2026-01-22 13:47:48 +00:00
Claude 8d0c03cc2a feat: add connection_errors_total metric tracking
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
2026-01-22 13:43:31 +00:00
Claude 6412286c73 fix: add buffer_overflows_total metric increment
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).
2026-01-22 13:40:31 +00:00
Claude 6570a1fc6e fix: add buffer_cache_cleanup_total metric increment
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.
2026-01-22 13:31:32 +00:00
Claude 68f6a2ae88 fix: update buffer_cache_size metric with actual history cache size
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
2026-01-22 13:28:25 +00:00
João Lucas de Oliveira Lopes f829b6d7a8 fix: extract LID-PN mappings from conversation objects in history sync (#2282)
* fix: extract LID-PN mappings from conversation objects in history sync

* fix: extract PN from userReceipt when pnJid is missing for LID chats
2026-01-22 15:00:41 +02:00
Gustavo Quadri 52fcad2b9c fix: optimize getLIDsForPNs and add getPNsForLIDs (#2274)
* fix: optimize lid-mapping and add getpnsforlids

* fix: lint

* fix: reintroduce store and fix partial returns

* fix: lint
2026-01-22 14:58:02 +02:00
Claude b1687389cd fix: resolve buffer_flushes_total metric label mismatch
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
2026-01-22 12:57:44 +00:00
João Lucas de Oliveira Lopes 92d4198ff1 fix: skip retry for expired status messages over 24 hours old (#2280) 2026-01-22 14:55:29 +02:00
João Lucas de Oliveira Lopes 5cbad3170b Fix connection showing "Online" but disconnected (#2132) (#2264)
* fix(messages): handle identity change notifications correctly (#2132)

* fix: tests and linting, add a helper like waweb
2026-01-22 14:54:10 +02:00
Claude e4ffbb4b5c fix: enable buffer metrics automatically when Prometheus is enabled
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.
2026-01-22 12:50:02 +00:00
Rajeh Taher 1ef04d5329 socket: no sync warning!!!!! 2026-01-22 14:43:19 +02:00
Rajeh Taher bfde86bce7 example: cleanup 2026-01-22 14:42:56 +02:00