@peopl-health/nexus 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,767 @@
1
+ const axios = require('axios');
2
+
3
+ // Configuration
4
+ const SERVER_URL = 'http://localhost:3000';
5
+ const TEST_PHONE = 'whatsapp:+51976302758'; // Change this to your test number
6
+
7
+ // Test messages to send
8
+ const testMessages = [
9
+ { From: TEST_PHONE, Body: 'hola este mensaje' },
10
+ { From: TEST_PHONE, Body: 'es para hacer una prueba' },
11
+ { From: TEST_PHONE, Body: 'y que te diga que' },
12
+ { From: TEST_PHONE, Body: 'es mi cumpleaños :D' }
13
+ ];
14
+
15
+ // Test messages with documents
16
+ const testMessagesWithDocs = [
17
+ {
18
+ From: TEST_PHONE,
19
+ Body: 'Hola, aquí tienes un documento',
20
+ MediaUrl0: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
21
+ NumMedia: '1',
22
+ MediaContentType0: 'application/pdf'
23
+ },
24
+ {
25
+ From: TEST_PHONE,
26
+ Body: 'Y aquí otro documento',
27
+ MediaUrl0: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
28
+ NumMedia: '1',
29
+ MediaContentType0: 'application/pdf'
30
+ },
31
+ { From: TEST_PHONE, Body: '¿Puedes procesar estos documentos?' },
32
+ { From: TEST_PHONE, Body: 'Espero tu respuesta' }
33
+ ];
34
+
35
+ // Mixed test messages (text + documents)
36
+ const mixedTestMessages = [
37
+ { From: TEST_PHONE, Body: 'Mensaje de texto 1' },
38
+ {
39
+ From: TEST_PHONE,
40
+ Body: 'Documento adjunto',
41
+ MediaUrl0: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
42
+ NumMedia: '1',
43
+ MediaContentType0: 'application/pdf'
44
+ },
45
+ { From: TEST_PHONE, Body: 'Mensaje de texto 2' },
46
+ {
47
+ From: TEST_PHONE,
48
+ Body: 'Otro documento',
49
+ MediaUrl0: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
50
+ NumMedia: '1',
51
+ MediaContentType0: 'application/pdf'
52
+ },
53
+ { From: TEST_PHONE, Body: 'Mensaje final' }
54
+ ];
55
+
56
+ // Test for media-first conflict scenario (the specific issue we're fixing)
57
+ const mediaFirstTestMessages = [
58
+ {
59
+ From: TEST_PHONE,
60
+ Body: 'Documento primero',
61
+ MediaUrl0: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
62
+ NumMedia: '1',
63
+ MediaContentType0: 'application/pdf'
64
+ },
65
+ { From: TEST_PHONE, Body: 'Mensaje después del documento' },
66
+ { From: TEST_PHONE, Body: '¿Qué es lo que puedes ver en el documento que te acabo de enviar?' }
67
+ ];
68
+
69
+ // Test messages with images
70
+ const testMessagesWithImages = [
71
+ {
72
+ From: TEST_PHONE,
73
+ Body: 'Aquí tienes una imagen',
74
+ MediaUrl0: 'https://picsum.photos/800/600?random=1',
75
+ NumMedia: '1',
76
+ MediaContentType0: 'image/jpeg'
77
+ },
78
+ {
79
+ From: TEST_PHONE,
80
+ Body: 'Y aquí otra imagen',
81
+ MediaUrl0: 'https://picsum.photos/800/600?random=2',
82
+ NumMedia: '1',
83
+ MediaContentType0: 'image/jpeg'
84
+ },
85
+ { From: TEST_PHONE, Body: '¿Puedes analizar estas imágenes?' },
86
+ { From: TEST_PHONE, Body: 'Espero tu respuesta sobre lo que ves' }
87
+ ];
88
+
89
+ // Mixed test messages (text + images)
90
+ const mixedImageTestMessages = [
91
+ { From: TEST_PHONE, Body: 'Mensaje de texto 1' },
92
+ {
93
+ From: TEST_PHONE,
94
+ Body: 'Imagen adjunta',
95
+ MediaUrl0: 'https://picsum.photos/800/600?random=3',
96
+ NumMedia: '1',
97
+ MediaContentType0: 'image/jpeg'
98
+ },
99
+ { From: TEST_PHONE, Body: 'Mensaje de texto 2' },
100
+ {
101
+ From: TEST_PHONE,
102
+ Body: 'Otra imagen',
103
+ MediaUrl0: 'https://picsum.photos/800/600?random=4',
104
+ NumMedia: '1',
105
+ MediaContentType0: 'image/jpeg'
106
+ },
107
+ { From: TEST_PHONE, Body: 'Mensaje final' }
108
+ ];
109
+
110
+ // Test for image-first batching scenario
111
+ const imageFirstTestMessages = [
112
+ {
113
+ From: TEST_PHONE,
114
+ Body: 'Imagen primero',
115
+ MediaUrl0: 'https://picsum.photos/800/600?random=5',
116
+ NumMedia: '1',
117
+ MediaContentType0: 'image/jpeg'
118
+ },
119
+ { From: TEST_PHONE, Body: 'Mensaje después de la imagen' },
120
+ { From: TEST_PHONE, Body: '¿Puedes procesar la imagen y responder?' }
121
+ ];
122
+
123
+ // Delay between messages (in milliseconds)
124
+ const MESSAGE_DELAY = 2000; // 2 seconds between messages
125
+
126
+ async function sendMessage(message, index) {
127
+ try {
128
+ let messageType = '💬 Text';
129
+ if (message.MediaUrl0) {
130
+ if (message.MediaContentType0?.startsWith('image/')) {
131
+ messageType = '🖼️ Image';
132
+ } else if (message.MediaContentType0?.startsWith('application/')) {
133
+ messageType = '📄 Document';
134
+ } else {
135
+ messageType = '📎 Media';
136
+ }
137
+ }
138
+
139
+ console.log(`📤 Sending message ${index + 1} (${messageType}): "${message.Body}"`);
140
+
141
+ if (message.MediaUrl0) {
142
+ console.log(` 📎 Media: ${message.MediaUrl0}`);
143
+ console.log(` 📎 Type: ${message.MediaContentType0}`);
144
+ }
145
+
146
+ const response = await axios.post(`${SERVER_URL}/webhook`, message, {
147
+ headers: {
148
+ 'Content-Type': 'application/json'
149
+ }
150
+ });
151
+
152
+ console.log(`✅ Message ${index + 1} sent successfully (Status: ${response.status})`);
153
+ return response.data;
154
+ } catch (error) {
155
+ console.error(`❌ Error sending message ${index + 1}:`, error.message);
156
+ return null;
157
+ }
158
+ }
159
+
160
+ async function testBatching() {
161
+ console.log('🧪 Starting Message Batching Test (Text Only)');
162
+ console.log('=====================================');
163
+ console.log(`Server URL: ${SERVER_URL}`);
164
+ console.log(`Test Phone: ${TEST_PHONE}`);
165
+ console.log(`Message Delay: ${MESSAGE_DELAY}ms`);
166
+ console.log('=====================================\n');
167
+
168
+ // Check if server is running
169
+ try {
170
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
171
+ console.log('✅ Server is running');
172
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
173
+ console.log('');
174
+ } catch (error) {
175
+ console.error('❌ Server is not running or not accessible');
176
+ console.error('Please start the server with: node examples/basic-usage.js');
177
+ process.exit(1);
178
+ }
179
+
180
+ // Send messages with delays
181
+ console.log('📨 Sending test messages...\n');
182
+
183
+ for (let i = 0; i < testMessages.length; i++) {
184
+ const message = testMessages[i];
185
+
186
+ // Send the message
187
+ await sendMessage(message, i);
188
+
189
+ // Wait before sending next message (except for the last one)
190
+ if (i < testMessages.length - 1) {
191
+ console.log(`⏳ Waiting ${MESSAGE_DELAY}ms before next message...\n`);
192
+ await new Promise(resolve => setTimeout(resolve, MESSAGE_DELAY));
193
+ }
194
+ }
195
+
196
+ console.log('\n🎯 Test completed!');
197
+ console.log('=====================================');
198
+ console.log('Expected behavior:');
199
+ console.log('- Messages should be batched together');
200
+ console.log('- You should see "Waiting X seconds for more messages" in server logs');
201
+ console.log('- After the wait time, you should see "Processing batched messages"');
202
+ console.log('- Only ONE assistant response should be generated for all messages');
203
+ console.log('=====================================\n');
204
+
205
+ console.log('📋 To verify the test worked:');
206
+ console.log('1. Check server logs for batching messages');
207
+ console.log('2. Look for "Waiting X seconds for more messages"');
208
+ console.log('3. Look for "Processing batched messages"');
209
+ console.log('4. Verify only one assistant response was sent');
210
+ }
211
+
212
+ async function testBatchingWithDocuments() {
213
+ console.log('🧪 Starting Message Batching Test (With Documents)');
214
+ console.log('==================================================');
215
+ console.log(`Server URL: ${SERVER_URL}`);
216
+ console.log(`Test Phone: ${TEST_PHONE}`);
217
+ console.log(`Message Delay: ${MESSAGE_DELAY}ms`);
218
+ console.log('==================================================\n');
219
+
220
+ // Check if server is running
221
+ try {
222
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
223
+ console.log('✅ Server is running');
224
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
225
+ console.log('');
226
+ } catch (error) {
227
+ console.error('❌ Server is not running or not accessible');
228
+ console.error('Please start the server with: node examples/basic-usage.js');
229
+ process.exit(1);
230
+ }
231
+
232
+ // Send messages with documents
233
+ console.log('📨 Sending test messages with documents...\n');
234
+
235
+ for (let i = 0; i < testMessagesWithDocs.length; i++) {
236
+ const message = testMessagesWithDocs[i];
237
+
238
+ // Send the message
239
+ await sendMessage(message, i);
240
+
241
+ // Wait before sending next message (except for the last one)
242
+ if (i < testMessagesWithDocs.length - 1) {
243
+ console.log(`⏳ Waiting ${MESSAGE_DELAY}ms before next message...\n`);
244
+ await new Promise(resolve => setTimeout(resolve, MESSAGE_DELAY));
245
+ }
246
+ }
247
+
248
+ console.log('\n🎯 Document batching test completed!');
249
+ console.log('==================================================');
250
+ console.log('Expected behavior:');
251
+ console.log('- Messages with documents should be batched together');
252
+ console.log('- Documents should be processed and stored');
253
+ console.log('- You should see "Waiting X seconds for more messages" in server logs');
254
+ console.log('- After the wait time, you should see "Processing batched messages"');
255
+ console.log('- Only ONE assistant response should be generated for all messages');
256
+ console.log('==================================================\n');
257
+ }
258
+
259
+ async function testMixedBatching() {
260
+ console.log('🧪 Starting Mixed Message Batching Test (Text + Documents)');
261
+ console.log('==========================================================');
262
+ console.log(`Server URL: ${SERVER_URL}`);
263
+ console.log(`Test Phone: ${TEST_PHONE}`);
264
+ console.log(`Message Delay: ${MESSAGE_DELAY}ms`);
265
+ console.log('==========================================================\n');
266
+
267
+ // Check if server is running
268
+ try {
269
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
270
+ console.log('✅ Server is running');
271
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
272
+ console.log('');
273
+ } catch (error) {
274
+ console.error('❌ Server is not running or not accessible');
275
+ console.error('Please start the server with: node examples/basic-usage.js');
276
+ process.exit(1);
277
+ }
278
+
279
+ // Send mixed messages
280
+ console.log('📨 Sending mixed test messages (text + documents)...\n');
281
+ console.log('🔍 Watch the server logs for batching messages!');
282
+ console.log('Expected server logs:');
283
+ console.log(' - "Batching config: { enabled: true, ... }"');
284
+ console.log(' - "Received additional message from whatsapp:+51976302758, resetting wait timer"');
285
+ console.log(' - "Waiting X seconds for more messages from whatsapp:+51976302758"');
286
+ console.log(' - "Processing batched messages from whatsapp:+51976302758"');
287
+ console.log('');
288
+
289
+ for (let i = 0; i < mixedTestMessages.length; i++) {
290
+ const message = mixedTestMessages[i];
291
+
292
+ // Send the message
293
+ await sendMessage(message, i);
294
+
295
+ // Wait before sending next message (except for the last one)
296
+ if (i < mixedTestMessages.length - 1) {
297
+ console.log(`⏳ Waiting ${MESSAGE_DELAY}ms before next message...\n`);
298
+ await new Promise(resolve => setTimeout(resolve, MESSAGE_DELAY));
299
+ }
300
+ }
301
+
302
+ console.log('\n🎯 Mixed batching test completed!');
303
+ console.log('==========================================================');
304
+ console.log('Expected behavior:');
305
+ console.log('- Text and document messages should be batched together');
306
+ console.log('- Documents should be processed and stored');
307
+ console.log('- You should see "Waiting X seconds for more messages" in server logs');
308
+ console.log('- After the wait time, you should see "Processing batched messages"');
309
+ console.log('- Only ONE assistant response should be generated for all messages');
310
+ console.log('==========================================================\n');
311
+
312
+ console.log('🔍 If you received 2 separate responses instead of 1:');
313
+ console.log('1. Check server logs for batching messages');
314
+ console.log('2. Verify batching is enabled: "Batching config: { enabled: true }"');
315
+ console.log('3. Look for "Waiting X seconds" messages');
316
+ console.log('4. Check if messages are being processed too quickly/slowly');
317
+ console.log('5. Look for "Processing batched messages from [chatId] (including media if any)"');
318
+ console.log('6. Verify no "Error handling batched messages" or run conflicts');
319
+ }
320
+
321
+ async function testMediaFirstBatching() {
322
+ console.log('🧪 Starting Media-First Batching Test (Document + Text)');
323
+ console.log('==========================================================');
324
+ console.log('This test specifically addresses the media-first conflict issue');
325
+ console.log('==========================================================\n');
326
+
327
+ // Check if server is running
328
+ try {
329
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
330
+ console.log('✅ Server is running');
331
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
332
+ console.log('');
333
+ } catch (error) {
334
+ console.error('❌ Server is not running or not accessible');
335
+ console.error('Please start the server with: node examples/basic-usage.js');
336
+ process.exit(1);
337
+ }
338
+
339
+ // Send media-first messages
340
+ console.log('📨 Sending media-first test messages (document + text)...\n');
341
+ console.log('🔍 Watch the server logs for batching messages!');
342
+ console.log('Expected server logs:');
343
+ console.log(' - "Batching config: { enabled: true, ... }"');
344
+ console.log(' - "Received additional message from whatsapp:+51976302758, resetting wait timer"');
345
+ console.log(' - "Waiting X seconds for more messages from whatsapp:+51976302758"');
346
+ console.log(' - "Processing batched messages from whatsapp:+51976302758 (including media if any)"');
347
+ console.log('');
348
+
349
+ for (let i = 0; i < mediaFirstTestMessages.length; i++) {
350
+ const message = mediaFirstTestMessages[i];
351
+
352
+ // Send the message
353
+ await sendMessage(message, i);
354
+
355
+ // Wait before sending next message (except for the last one)
356
+ if (i < mediaFirstTestMessages.length - 1) {
357
+ console.log(`⏳ Waiting ${MESSAGE_DELAY}ms before next message...\n`);
358
+ await new Promise(resolve => setTimeout(resolve, MESSAGE_DELAY));
359
+ }
360
+ }
361
+
362
+ console.log('\n🎯 Media-first batching test completed!');
363
+ console.log('==========================================================');
364
+ console.log('Expected behavior:');
365
+ console.log('- Document and text messages should be batched together');
366
+ console.log('- No "Error handling batched messages" or run conflicts');
367
+ console.log('- Only ONE assistant response should be generated');
368
+ console.log('- You should see "Processing batched messages from [chatId] (including media if any)"');
369
+ console.log('==========================================================\n');
370
+
371
+ console.log('🔍 If you see errors or multiple responses:');
372
+ console.log('1. Check for "Error handling batched messages" in server logs');
373
+ console.log('2. Look for OpenAI run conflicts');
374
+ console.log('3. Verify media messages are being included in batching');
375
+ console.log('4. Check that messages are marked as processed correctly');
376
+ }
377
+
378
+ async function testBatchingDiagnostic() {
379
+ console.log('🔍 Batching Diagnostic Test');
380
+ console.log('============================');
381
+ console.log('This test will help diagnose why batching might not be working\n');
382
+
383
+ // Check server status
384
+ try {
385
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
386
+ console.log('✅ Server is running');
387
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
388
+ console.log('');
389
+ } catch (error) {
390
+ console.error('❌ Server is not running or not accessible');
391
+ process.exit(1);
392
+ }
393
+
394
+ // Send a single message first to check immediate processing
395
+ console.log('📤 Step 1: Sending single message to test immediate processing...');
396
+ const singleMessage = { From: TEST_PHONE, Body: 'Single test message' };
397
+ await sendMessage(singleMessage, 0);
398
+
399
+ console.log('\n⏳ Waiting 5 seconds...\n');
400
+ await new Promise(resolve => setTimeout(resolve, 5000));
401
+
402
+ // Send two messages quickly
403
+ console.log('📤 Step 2: Sending two messages quickly (should batch)...');
404
+ const quickMessages = [
405
+ { From: TEST_PHONE, Body: 'Quick message 1' },
406
+ { From: TEST_PHONE, Body: 'Quick message 2' }
407
+ ];
408
+
409
+ for (let i = 0; i < quickMessages.length; i++) {
410
+ await sendMessage(quickMessages[i], i);
411
+ if (i < quickMessages.length - 1) {
412
+ console.log('⏳ Waiting 1 second before next message...\n');
413
+ await new Promise(resolve => setTimeout(resolve, 1000));
414
+ }
415
+ }
416
+
417
+ console.log('\n🎯 Diagnostic test completed!');
418
+ console.log('============================');
419
+ console.log('Check server logs for:');
420
+ console.log('1. "Batching config: { enabled: true, ... }"');
421
+ console.log('2. "Received additional message from whatsapp:+51976302758, resetting wait timer"');
422
+ console.log('3. "Waiting X seconds for more messages from whatsapp:+51976302758"');
423
+ console.log('4. "Processing batched messages from whatsapp:+51976302758"');
424
+ console.log('');
425
+ console.log('If you see these logs but still get 2 responses, there might be an issue with:');
426
+ console.log('- Assistant processing logic');
427
+ console.log('- Message deduplication');
428
+ console.log('- Batching timeout handling');
429
+ }
430
+
431
+ async function testBatchingCorrectly() {
432
+ console.log('🧪 Correct Batching Test');
433
+ console.log('=========================');
434
+ console.log('This test shows batching working correctly\n');
435
+
436
+ // Check server status
437
+ try {
438
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
439
+ console.log('✅ Server is running');
440
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
441
+ console.log('');
442
+ } catch (error) {
443
+ console.error('❌ Server is not running or not accessible');
444
+ process.exit(1);
445
+ }
446
+
447
+ // Send multiple messages quickly (all should be batched)
448
+ console.log('📤 Sending 3 messages quickly (all should be batched together)...');
449
+ const batchMessages = [
450
+ { From: TEST_PHONE, Body: 'Batch message 1' },
451
+ { From: TEST_PHONE, Body: 'Batch message 2' },
452
+ { From: TEST_PHONE, Body: 'Batch message 3' }
453
+ ];
454
+
455
+ for (let i = 0; i < batchMessages.length; i++) {
456
+ await sendMessage(batchMessages[i], i);
457
+ if (i < batchMessages.length - 1) {
458
+ console.log('⏳ Waiting 1 second before next message...\n');
459
+ await new Promise(resolve => setTimeout(resolve, 1000));
460
+ }
461
+ }
462
+
463
+ console.log('\n🎯 Correct batching test completed!');
464
+ console.log('===================================');
465
+ console.log('Expected behavior:');
466
+ console.log('- All 3 messages should be batched together');
467
+ console.log('- You should see "Waiting X seconds for more messages" in server logs');
468
+ console.log('- After the wait time, you should see "Processing batched messages"');
469
+ console.log('- Only ONE assistant response should be generated for all 3 messages');
470
+ console.log('===================================\n');
471
+
472
+ console.log('🔍 Check server logs for:');
473
+ console.log('1. "Batching config: { enabled: true, ... }"');
474
+ console.log('2. "Received additional message from whatsapp:+51976302758, resetting wait timer"');
475
+ console.log('3. "Waiting X seconds for more messages from whatsapp:+51976302758"');
476
+ console.log('4. "Processing batched messages from whatsapp:+51976302758"');
477
+ console.log('5. Only ONE "Assistant initialized" message');
478
+ console.log('6. Only ONE response sent to WhatsApp');
479
+ }
480
+
481
+ async function testWithoutBatching() {
482
+ console.log('🧪 Testing WITHOUT Batching (Control Test)');
483
+ console.log('==========================================');
484
+ console.log('This test sends messages with longer delays to avoid batching');
485
+ console.log('Each message should be processed immediately\n');
486
+
487
+ const controlMessages = [
488
+ { From: TEST_PHONE, Body: 'Control message 1' },
489
+ { From: TEST_PHONE, Body: 'Control message 2' }
490
+ ];
491
+
492
+ for (let i = 0; i < controlMessages.length; i++) {
493
+ const message = controlMessages[i];
494
+ await sendMessage(message, i);
495
+
496
+ if (i < controlMessages.length - 1) {
497
+ console.log('⏳ Waiting 20 seconds (longer than batch timeout)...\n');
498
+ await new Promise(resolve => setTimeout(resolve, 20000));
499
+ }
500
+ }
501
+
502
+ console.log('\n🎯 Control test completed!');
503
+ console.log('Expected: Each message should be processed immediately');
504
+ }
505
+
506
+ async function testSingleMessage() {
507
+ console.log('🧪 Testing Single Message (No Batching)');
508
+ console.log('======================================');
509
+
510
+ const singleMessage = { From: TEST_PHONE, Body: 'Single message test' };
511
+ await sendMessage(singleMessage, 0);
512
+
513
+ console.log('\n🎯 Single message test completed!');
514
+ console.log('Expected: Message should be processed immediately (no batching)');
515
+ }
516
+
517
+ async function testBatchingWithImages() {
518
+ console.log('🧪 Starting Message Batching Test (With Images)');
519
+ console.log('================================================');
520
+ console.log(`Server URL: ${SERVER_URL}`);
521
+ console.log(`Test Phone: ${TEST_PHONE}`);
522
+ console.log(`Message Delay: ${MESSAGE_DELAY}ms`);
523
+ console.log('================================================\n');
524
+
525
+ // Check if server is running
526
+ try {
527
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
528
+ console.log('✅ Server is running');
529
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
530
+ console.log('');
531
+ } catch (error) {
532
+ console.error('❌ Server is not running or not accessible');
533
+ console.error('Please start the server with: node examples/basic-usage.js');
534
+ process.exit(1);
535
+ }
536
+
537
+ // Send messages with images
538
+ console.log('📨 Sending test messages with images...\n');
539
+
540
+ for (let i = 0; i < testMessagesWithImages.length; i++) {
541
+ const message = testMessagesWithImages[i];
542
+
543
+ // Send the message
544
+ await sendMessage(message, i);
545
+
546
+ // Wait before sending next message (except for the last one)
547
+ if (i < testMessagesWithImages.length - 1) {
548
+ console.log(`⏳ Waiting ${MESSAGE_DELAY}ms before next message...\n`);
549
+ await new Promise(resolve => setTimeout(resolve, MESSAGE_DELAY));
550
+ }
551
+ }
552
+
553
+ console.log('\n🎯 Image batching test completed!');
554
+ console.log('================================================');
555
+ console.log('Expected behavior:');
556
+ console.log('- Messages with images should be batched together');
557
+ console.log('- Images should be processed and stored');
558
+ console.log('- You should see "Waiting X seconds for more messages" in server logs');
559
+ console.log('- After the wait time, you should see "Processing batched messages"');
560
+ console.log('- Only ONE assistant response should be generated for all messages');
561
+ console.log('================================================\n');
562
+ }
563
+
564
+ async function testMixedImageBatching() {
565
+ console.log('🧪 Starting Mixed Image Batching Test (Text + Images)');
566
+ console.log('====================================================');
567
+ console.log(`Server URL: ${SERVER_URL}`);
568
+ console.log(`Test Phone: ${TEST_PHONE}`);
569
+ console.log(`Message Delay: ${MESSAGE_DELAY}ms`);
570
+ console.log('====================================================\n');
571
+
572
+ // Check if server is running
573
+ try {
574
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
575
+ console.log('✅ Server is running');
576
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
577
+ console.log('');
578
+ } catch (error) {
579
+ console.error('❌ Server is not running or not accessible');
580
+ console.error('Please start the server with: node examples/basic-usage.js');
581
+ process.exit(1);
582
+ }
583
+
584
+ // Send mixed messages
585
+ console.log('📨 Sending mixed test messages (text + images)...\n');
586
+ console.log('🔍 Watch the server logs for batching messages!');
587
+ console.log('Expected server logs:');
588
+ console.log(' - "Batching config: { enabled: true, ... }"');
589
+ console.log(' - "Received additional message from whatsapp:+51976302758, resetting wait timer"');
590
+ console.log(' - "Waiting X seconds for more messages from whatsapp:+51976302758"');
591
+ console.log(' - "Processing batched messages from whatsapp:+51976302758"');
592
+ console.log('');
593
+
594
+ for (let i = 0; i < mixedImageTestMessages.length; i++) {
595
+ const message = mixedImageTestMessages[i];
596
+
597
+ // Send the message
598
+ await sendMessage(message, i);
599
+
600
+ // Wait before sending next message (except for the last one)
601
+ if (i < mixedImageTestMessages.length - 1) {
602
+ console.log(`⏳ Waiting ${MESSAGE_DELAY}ms before next message...\n`);
603
+ await new Promise(resolve => setTimeout(resolve, MESSAGE_DELAY));
604
+ }
605
+ }
606
+
607
+ console.log('\n🎯 Mixed image batching test completed!');
608
+ console.log('====================================================');
609
+ console.log('Expected behavior:');
610
+ console.log('- Text and image messages should be batched together');
611
+ console.log('- Images should be processed and stored');
612
+ console.log('- You should see "Waiting X seconds for more messages" in server logs');
613
+ console.log('- After the wait time, you should see "Processing batched messages"');
614
+ console.log('- Only ONE assistant response should be generated for all messages');
615
+ console.log('====================================================\n');
616
+
617
+ console.log('🔍 If you received 2 separate responses instead of 1:');
618
+ console.log('1. Check server logs for batching messages');
619
+ console.log('2. Verify batching is enabled: "Batching config: { enabled: true }"');
620
+ console.log('3. Look for "Waiting X seconds" messages');
621
+ console.log('4. Check if messages are being processed too quickly/slowly');
622
+ console.log('5. Look for "Processing batched messages from [chatId] (including media if any)"');
623
+ console.log('6. Verify no "Error handling batched messages" or run conflicts');
624
+ }
625
+
626
+ async function testImageFirstBatching() {
627
+ console.log('🧪 Starting Image-First Batching Test (Image + Text)');
628
+ console.log('====================================================');
629
+ console.log('This test specifically addresses the image-first conflict issue');
630
+ console.log('====================================================\n');
631
+
632
+ // Check if server is running
633
+ try {
634
+ const statusResponse = await axios.get(`${SERVER_URL}/status`);
635
+ console.log('✅ Server is running');
636
+ console.log('Server Status:', JSON.stringify(statusResponse.data, null, 2));
637
+ console.log('');
638
+ } catch (error) {
639
+ console.error('❌ Server is not running or not accessible');
640
+ console.error('Please start the server with: node examples/basic-usage.js');
641
+ process.exit(1);
642
+ }
643
+
644
+ // Send image-first messages
645
+ console.log('📨 Sending image-first test messages (image + text)...\n');
646
+ console.log('🔍 Watch the server logs for batching messages!');
647
+ console.log('Expected server logs:');
648
+ console.log(' - "Batching config: { enabled: true, ... }"');
649
+ console.log(' - "Received additional message from whatsapp:+51976302758, resetting wait timer"');
650
+ console.log(' - "Waiting X seconds for more messages from whatsapp:+51976302758"');
651
+ console.log(' - "Processing batched messages from whatsapp:+51976302758 (including media if any)"');
652
+ console.log('');
653
+
654
+ for (let i = 0; i < imageFirstTestMessages.length; i++) {
655
+ const message = imageFirstTestMessages[i];
656
+
657
+ // Send the message
658
+ await sendMessage(message, i);
659
+
660
+ // Wait before sending next message (except for the last one)
661
+ if (i < imageFirstTestMessages.length - 1) {
662
+ console.log(`⏳ Waiting ${MESSAGE_DELAY}ms before next message...\n`);
663
+ await new Promise(resolve => setTimeout(resolve, MESSAGE_DELAY));
664
+ }
665
+ }
666
+
667
+ console.log('\n🎯 Image-first batching test completed!');
668
+ console.log('====================================================');
669
+ console.log('Expected behavior:');
670
+ console.log('- Image and text messages should be batched together');
671
+ console.log('- No "Error handling batched messages" or run conflicts');
672
+ console.log('- Only ONE assistant response should be generated');
673
+ console.log('- You should see "Processing batched messages from [chatId] (including media if any)"');
674
+ console.log('====================================================\n');
675
+
676
+ console.log('🔍 If you see errors or multiple responses:');
677
+ console.log('1. Check for "Error handling batched messages" in server logs');
678
+ console.log('2. Look for OpenAI run conflicts');
679
+ console.log('3. Verify image messages are being included in batching');
680
+ console.log('4. Check that messages are marked as processed correctly');
681
+ }
682
+
683
+ // Main execution
684
+ async function main() {
685
+ const testType = process.argv[2] || 'batching';
686
+
687
+ switch (testType) {
688
+ case 'batching':
689
+ await testBatching();
690
+ break;
691
+ case 'documents':
692
+ await testBatchingWithDocuments();
693
+ break;
694
+ case 'images':
695
+ await testBatchingWithImages();
696
+ break;
697
+ case 'mixed':
698
+ await testMixedBatching();
699
+ break;
700
+ case 'mixed-images':
701
+ await testMixedImageBatching();
702
+ break;
703
+ case 'media-first':
704
+ await testMediaFirstBatching();
705
+ break;
706
+ case 'image-first':
707
+ await testImageFirstBatching();
708
+ break;
709
+ case 'diagnostic':
710
+ await testBatchingDiagnostic();
711
+ break;
712
+ case 'correct':
713
+ await testBatchingCorrectly();
714
+ break;
715
+ case 'control':
716
+ await testWithoutBatching();
717
+ break;
718
+ case 'single':
719
+ await testSingleMessage();
720
+ break;
721
+ case 'all':
722
+ console.log('🧪 Running ALL Tests\n');
723
+ await testSingleMessage();
724
+ console.log('\n' + '='.repeat(50) + '\n');
725
+ await testBatching();
726
+ console.log('\n' + '='.repeat(50) + '\n');
727
+ await testBatchingWithDocuments();
728
+ console.log('\n' + '='.repeat(50) + '\n');
729
+ await testBatchingWithImages();
730
+ console.log('\n' + '='.repeat(50) + '\n');
731
+ await testMixedBatching();
732
+ console.log('\n' + '='.repeat(50) + '\n');
733
+ await testMixedImageBatching();
734
+ console.log('\n' + '='.repeat(50) + '\n');
735
+ await testMediaFirstBatching();
736
+ console.log('\n' + '='.repeat(50) + '\n');
737
+ await testImageFirstBatching();
738
+ console.log('\n' + '='.repeat(50) + '\n');
739
+ await testWithoutBatching();
740
+ break;
741
+ default:
742
+ console.log('Usage: node test-batching.js [batching|documents|images|mixed|mixed-images|media-first|image-first|diagnostic|correct|control|single|all]');
743
+ console.log('');
744
+ console.log('Tests:');
745
+ console.log(' batching - Test message batching with text only (default)');
746
+ console.log(' documents - Test message batching with documents only');
747
+ console.log(' images - Test message batching with images only');
748
+ console.log(' mixed - Test message batching with text + documents');
749
+ console.log(' mixed-images - Test message batching with text + images');
750
+ console.log(' media-first - Test media-first batching (fixes run conflicts)');
751
+ console.log(' image-first - Test image-first batching (fixes run conflicts)');
752
+ console.log(' diagnostic - Diagnostic test to debug batching issues');
753
+ console.log(' correct - Correct batching test (3 messages, all batched)');
754
+ console.log(' control - Test without batching (long delays)');
755
+ console.log(' single - Test single message (no batching)');
756
+ console.log(' all - Run all tests');
757
+ process.exit(1);
758
+ }
759
+ }
760
+
761
+ // Handle graceful shutdown
762
+ process.on('SIGINT', () => {
763
+ console.log('\n👋 Test interrupted by user');
764
+ process.exit(0);
765
+ });
766
+
767
+ main().catch(console.error);
@@ -338,8 +338,6 @@ class NexusMessaging {
338
338
  // Handle immediate response messages (interactive, flows, etc.)
339
339
  if (messageData.interactive) {
340
340
  return await this.handleInteractive(messageData);
341
- } else if (messageData.media) {
342
- return await this.handleMedia(messageData);
343
341
  } else if (messageData.command) {
344
342
  return await this.handleCommand(messageData);
345
343
  } else if (messageData.keyword) {
@@ -347,12 +345,17 @@ class NexusMessaging {
347
345
  } else if (messageData.flow) {
348
346
  return await this.handleFlow(messageData);
349
347
  } else {
350
- // For regular messages, use batching if enabled
348
+ // For regular messages and media, use batching if enabled
351
349
  console.log('Batching config:', this.batchingConfig);
352
350
  if (this.batchingConfig.enabled && chatId) {
353
351
  return await this._handleWithBatching(messageData, chatId);
354
352
  } else {
355
- return await this.handleMessage(messageData);
353
+ // Handle media and regular messages without batching
354
+ if (messageData.media) {
355
+ return await this.handleMedia(messageData);
356
+ } else {
357
+ return await this.handleMessage(messageData);
358
+ }
356
359
  }
357
360
  }
358
361
  }
@@ -631,7 +634,7 @@ class NexusMessaging {
631
634
  */
632
635
  async _handleBatchedMessages(chatId) {
633
636
  try {
634
- console.log(`Processing batched messages from ${chatId}`);
637
+ console.log(`Processing batched messages from ${chatId} (including media if any)`);
635
638
 
636
639
  // Get assistant response
637
640
  const botResponse = await replyAssistant(chatId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",