]> git.giacomolli.uk - onechat/blob - whatsapp_test.go
Send WhatsApp messages with an ID
[onechat] / whatsapp_test.go
1 package main
2
3 import (
4 "crypto/sha256"
5 "encoding/hex"
6 "errors"
7 "fmt"
8 "net/http"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "github.com/stretchr/testify/require"
16 "go.mau.fi/whatsmeow"
17 "go.mau.fi/whatsmeow/proto/waE2E"
18 "go.mau.fi/whatsmeow/proto/waWeb"
19 "go.mau.fi/whatsmeow/types"
20 "go.mau.fi/whatsmeow/types/events"
21 )
22
23 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
24 dir := t.TempDir()
25 whatsappTestSession(t, dir, true)
26 clock := newTestClock()
27 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
28 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
29
30 <-fake.connects
31 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
32
33 require.True(t, fake.Emit(&events.Connected{}))
34 require.Equal(t, "WhatsApp is linked and connected since 2026-01-01 12:00.", whatsapp.Status())
35
36 clock.now = clock.now.Add(20 * time.Minute)
37 require.True(t, fake.Emit(&events.Disconnected{}))
38 clock.now = clock.now.Add(time.Minute)
39 require.True(t, fake.Emit(&events.Disconnected{}))
40 require.Equal(t, "WhatsApp is linked and disconnected since 2026-01-01 12:20. The last connection started at 2026-01-01 12:00.", whatsapp.Status())
41 }
42
43 func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
44 dir := t.TempDir()
45 whatsappTestSession(t, dir, true)
46 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
47 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
48
49 <-fake.connects
50 require.True(t, fake.Emit(&events.Disconnected{}))
51 require.Equal(t, "WhatsApp is linked and disconnected since 2026-01-01 12:00.", whatsapp.Status())
52 }
53
54 func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
55 testCases := []struct {
56 name string
57 session func(t *testing.T, dir string)
58 }{
59 {
60 name: "no session file",
61 session: func(t *testing.T, dir string) {
62 },
63 },
64 {
65 name: "a session of a pairing that did not end",
66 session: func(t *testing.T, dir string) {
67 whatsappTestSession(t, dir, false)
68 },
69 },
70 }
71
72 for _, tc := range testCases {
73 t.Run(tc.name, func(t *testing.T) {
74 dir := t.TempDir()
75 tc.session(t, dir)
76 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
77 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
78 })
79 }
80 }
81
82 func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
83 dir := t.TempDir()
84 whatsappTestSession(t, dir, true)
85 require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
86
87 _, err := openWhatsApp(t.Context(), dir, time.Now, whatsappDiscardLog(), whatsappNewClient)
88 require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600")
89 }
90
91 func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) {
92 server := newModelFake(t)
93 telegram := newTelegramFake(t)
94 bot, _ := telegramStartTestBot(t, telegram)
95 socket := daemonStartTestWithBot(t, server, bot)
96 asking := terminalStartTestClient(t, socket)
97 other := terminalStartTestClient(t, socket)
98 asking.WaitFor(t, "[connected to OneChat]")
99 other.WaitFor(t, "[connected to OneChat]")
100
101 asking.Type("/whatsapp status")
102 asking.WaitFor(t, "WhatsApp is not linked.")
103 asking.Type(" /whatsapp unknown ")
104 asking.WaitFor(t, whatsappUsage)
105 asking.Type("/whatsapp pair 0123")
106 asking.WaitFor(t, "PHONE must be the number of your WhatsApp account")
107
108 telegram.Add(TelegramUpdate{
109 UpdateID: 1,
110 Message: telegramOwnerMessage("/whatsapp status"),
111 })
112
113 telegramWaitForSent(t, telegram, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.")
114 require.Len(t, telegram.Sent(), 1)
115 require.Equal(t, "[connected to OneChat]\n", other.Output())
116 require.Zero(t, server.Calls())
117 }
118
119 func TestWhatsAppPairsWithACode(t *testing.T) {
120 dir := t.TempDir()
121 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
122 server := newModelFake(t)
123 socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
124 asking := terminalStartTestClient(t, socket)
125 other := terminalStartTestClient(t, socket)
126 asking.WaitFor(t, "[connected to OneChat]")
127 other.WaitFor(t, "[connected to OneChat]")
128
129 asking.Type("/whatsapp pair +1 555-000-1111")
130 items := <-fake.pairings
131 items <- whatsmeow.QRChannelItem{
132 Event: whatsmeow.QRChannelEventCode,
133 }
134
135 asking.WaitFor(t, whatsappPairSteps+"\n"+whatsappTestCode+"\n")
136 require.True(t, fake.Emit(&events.PairSuccess{
137 ID: types.NewADJID(whatsappTestNumber, 0, 1),
138 LID: types.NewADJID(whatsappTestLID, 0, 1),
139 }))
140 items <- whatsmeow.QRChannelSuccess
141 asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
142
143 require.Equal(t, []string{whatsappTestNumber}, fake.Phones())
144 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
145 require.Equal(t, "[connected to OneChat]\n", other.Output())
146 require.Zero(t, server.Calls())
147 require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory))
148
149 info, err := os.Stat(filepath.Join(dir, whatsappDirName))
150 require.NoError(t, err)
151 require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
152
153 info, err = os.Stat(filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
154 require.NoError(t, err)
155 require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
156 }
157
158 func TestWhatsAppPairingCodeIsATelegramMessageAlone(t *testing.T) {
159 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
160 telegram := newTelegramFake(t)
161 bot, _ := telegramStartTestBot(t, telegram)
162 daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
163
164 telegram.Add(TelegramUpdate{
165 UpdateID: 1,
166 Message: telegramOwnerMessage("/whatsapp pair 15550001111"),
167 })
168
169 items := <-fake.pairings
170 items <- whatsmeow.QRChannelItem{
171 Event: whatsmeow.QRChannelEventCode,
172 }
173
174 telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode)
175 }
176
177 func TestWhatsAppPairingEnds(t *testing.T) {
178 testCases := []struct {
179 name string
180 end func(items chan whatsmeow.QRChannelItem)
181 answer string
182 }{
183 {
184 name: "the code expires",
185 end: func(items chan whatsmeow.QRChannelItem) {
186 items <- whatsmeow.QRChannelTimeout
187 },
188 answer: whatsappPairExpired,
189 },
190 {
191 name: "the library closes the pairing",
192 end: func(items chan whatsmeow.QRChannelItem) {
193 close(items)
194 },
195 answer: whatsappPairExpired,
196 },
197 {
198 name: "the pairing fails",
199 end: func(items chan whatsmeow.QRChannelItem) {
200 items <- whatsmeow.QRChannelItem{
201 Event: whatsmeow.QRChannelEventError,
202 Error: errors.New("bad handshake"),
203 }
204 },
205 answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.",
206 },
207 }
208
209 for _, tc := range testCases {
210 t.Run(tc.name, func(t *testing.T) {
211 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
212 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
213 client := terminalStartTestClient(t, socket)
214 client.Type("/whatsapp pair 15550001111")
215
216 items := <-fake.pairings
217 items <- whatsmeow.QRChannelItem{
218 Event: whatsmeow.QRChannelEventCode,
219 }
220
221 client.WaitFor(t, whatsappTestCode)
222 tc.end(items)
223 client.WaitFor(t, tc.answer)
224 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
225 })
226 }
227 }
228
229 func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) {
230 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
231 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
232 client := terminalStartTestClient(t, socket)
233
234 client.Type("/whatsapp pair 15550001111")
235 <-fake.pairings
236 client.Type("/whatsapp pair 15550002222")
237 items := <-fake.pairings
238 items <- whatsmeow.QRChannelItem{
239 Event: whatsmeow.QRChannelEventCode,
240 }
241
242 client.WaitFor(t, whatsappTestCode)
243 require.Equal(t, []string{"15550002222"}, fake.Phones())
244 require.NotContains(t, client.Output(), "did not start the pairing")
245 }
246
247 func TestWhatsAppPairWhenLinked(t *testing.T) {
248 dir := t.TempDir()
249 whatsappTestSession(t, dir, true)
250 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
251 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
252 client := terminalStartTestClient(t, socket)
253
254 client.Type("/whatsapp pair 15550001111")
255 client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.")
256 }
257
258 func TestWhatsAppUnlink(t *testing.T) {
259 testCases := []struct {
260 name string
261 logoutErr error
262 answer string
263 }{
264 {
265 name: "with a logout",
266 answer: "WhatsApp is unlinked.",
267 },
268 {
269 name: "with no logout",
270 logoutErr: errors.New("not connected"),
271 answer: "WhatsApp is unlinked here, but the phone did not get the logout. In WhatsApp on your phone, open Linked devices and remove the device.",
272 },
273 }
274
275 for _, tc := range testCases {
276 t.Run(tc.name, func(t *testing.T) {
277 dir := t.TempDir()
278 whatsappTestSession(t, dir, true)
279 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
280 fake.logoutErr = tc.logoutErr
281 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
282 client := terminalStartTestClient(t, socket)
283 <-fake.connects
284
285 client.Type("/whatsapp unlink")
286 client.WaitFor(t, tc.answer)
287 require.Equal(t, 1, fake.Logouts())
288 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
289 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
290 require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory))
291
292 client.Type("/whatsapp unlink")
293 client.WaitFor(t, "WhatsApp is not linked.\n")
294 })
295 }
296 }
297
298 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
299 dir := t.TempDir()
300 whatsappTestSession(t, dir, true)
301 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
302 telegram := newTelegramFake(t)
303 bot, _ := telegramStartTestBot(t, telegram)
304 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
305 client := terminalStartTestClient(t, socket)
306 client.WaitFor(t, "[connected to OneChat]")
307 <-fake.connects
308
309 require.True(t, fake.Emit(&events.LoggedOut{}))
310 notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again."
311 client.WaitFor(t, notice)
312 telegramWaitForSent(t, telegram, notice)
313 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
314 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
315 require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory))
316 }
317
318 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
319 dir := t.TempDir()
320 whatsappTestSession(t, dir, true)
321 clock := newTestClock()
322 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
323 whatsapp.noticeDelay = 300 * time.Millisecond
324 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
325 client := terminalStartTestClient(t, socket)
326 client.WaitFor(t, "[connected to OneChat]")
327 <-fake.connects
328
329 require.True(t, fake.Emit(&events.Connected{}))
330 require.True(t, fake.Emit(&events.Disconnected{}))
331 require.True(t, fake.Emit(&events.Connected{}))
332 time.Sleep(400 * time.Millisecond)
333 require.Equal(t, "[connected to OneChat]\n", client.Output())
334
335 clock.now = clock.now.Add(time.Hour)
336 require.True(t, fake.Emit(&events.Disconnected{}))
337 require.True(t, fake.Emit(&events.Disconnected{}))
338 client.WaitFor(t, "WhatsApp is disconnected since 2026-01-01 13:00. OneChat tries again.\n")
339 require.True(t, fake.Emit(&events.Disconnected{}))
340 time.Sleep(400 * time.Millisecond)
341
342 require.True(t, fake.Emit(&events.Connected{}))
343 client.WaitFor(t, "WhatsApp is connected again.\n")
344 require.Equal(t, 1, strings.Count(client.Output(), "WhatsApp is disconnected since"))
345 }
346
347 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
348 dir := t.TempDir()
349 whatsappTestSession(t, dir, true)
350 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
351 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
352 client := terminalStartTestClient(t, socket)
353 client.WaitFor(t, "[connected to OneChat]")
354 <-fake.connects
355
356 require.True(t, fake.Emit(&events.StreamReplaced{}))
357 client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.")
358 }
359
360 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
361 dir := t.TempDir()
362 whatsappTestSession(t, dir, true)
363 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
364 fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid")
365 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
366 <-fake.connects
367
368 require.Eventually(t, func() bool {
369 return logs.String() != ""
370 }, 10*time.Second, time.Millisecond)
371 require.Equal(t, "connect: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String())
372 }
373
374 func TestWhatsAppPhone(t *testing.T) {
375 testCases := []struct {
376 name string
377 phone string
378 valid bool
379 }{
380 {
381 name: "a number with a plus and dashes",
382 phone: "+1-555-000-1111",
383 valid: true,
384 },
385 {
386 name: "a number with no country code",
387 phone: "0115550001111",
388 valid: false,
389 },
390 {
391 name: "a short number",
392 phone: "123456",
393 valid: false,
394 },
395 {
396 name: "a long number",
397 phone: "1234567890123456",
398 valid: false,
399 },
400 {
401 name: "a number with letters",
402 phone: "1555ABC1111",
403 valid: false,
404 },
405 }
406
407 for _, tc := range testCases {
408 t.Run(tc.name, func(t *testing.T) {
409 _, valid := whatsappPhone(tc.phone)
410 require.Equal(t, tc.valid, valid)
411 })
412 }
413 }
414
415 func TestWhatsAppCommandArgs(t *testing.T) {
416 testCases := []struct {
417 name string
418 line string
419 args string
420 found bool
421 }{
422 {
423 name: "a command with its arguments",
424 line: " /whatsapp pair +1 555 ",
425 args: "pair +1 555",
426 found: true,
427 },
428 {
429 name: "the command alone",
430 line: "/whatsapp",
431 args: "",
432 found: true,
433 },
434 {
435 name: "a word that starts with the command",
436 line: "/whatsappstatus",
437 args: "",
438 found: false,
439 },
440 {
441 name: "a message that names the command",
442 line: "what does /whatsapp status do?",
443 args: "",
444 found: false,
445 },
446 }
447
448 for _, tc := range testCases {
449 t.Run(tc.name, func(t *testing.T) {
450 args, found := whatsappCommandArgs(tc.line)
451 require.Equal(t, tc.args, args)
452 require.Equal(t, tc.found, found)
453 })
454 }
455 }
456
457 // whatsappTestLogTexts returns the texts of the messages in the log of memory,
458 // after the log holds at least one message.
459 func whatsappTestLogTexts(t *testing.T, memory *Memory) []string {
460 t.Helper()
461
462 require.Eventually(t, func() bool {
463 return memory.Len() > 0
464 }, 10*time.Second, time.Millisecond)
465
466 var texts []string
467 for id := range memory.Len() {
468 message, err := memory.Message(id)
469 require.NoError(t, err)
470
471 texts = append(texts, message.Text)
472 }
473
474 return texts
475 }
476
477 func TestWhatsAppPrivateBatchStartsATurnWithAnEmptyReply(t *testing.T) {
478 whatsapp, fake := whatsappStartTestLinked(t)
479 require.NoError(t, whatsapp.device.Contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
480
481 server := newModelFake(t)
482 server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
483 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("")}, 100, 0, 5))
484 }
485
486 telegram := newTelegramFake(t)
487 bot, _ := telegramStartTestBot(t, telegram)
488 socket, memory := daemonStartTestWithWhatsApp(t, server, bot, whatsapp)
489 client := terminalStartTestClient(t, socket)
490 client.WaitFor(t, "[connected to OneChat]")
491 <-fake.connects
492
493 // The catch-up holds the batch open until its end, so the two messages
494 // form one batch also on a slow machine.
495 require.True(t, fake.Emit(&events.Connected{}))
496 at := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
497 require.True(t, fake.Emit(whatsappTestMessage(whatsappTestAna, whatsappTestAna, "m1", "Are you at home?", at)))
498 require.True(t, fake.Emit(whatsappTestMessage(whatsappTestAna, whatsappTestOwn, "m2", "Yes", at)))
499 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
500
501 text := "[WhatsApp] Ana Souza, private chat 15550002222@s.whatsapp.net, Thursday 2026-01-01\n12:00 Ana Souza: Are you at home?\n12:00 You: Yes\n" + whatsappBatchEmptyReply
502 client.WaitFor(t, text+"\n[working]\n[done]\n")
503 require.Equal(t, 1, server.Calls())
504 require.Contains(t, string(server.Call(0).raw), "Are you at home?")
505 require.Equal(t, []string{text}, whatsappTestLogTexts(t, memory))
506 require.Empty(t, telegram.Sent())
507 require.Eventually(t, func() bool {
508 return len(whatsapp.state.Closed()) == 0
509 }, 10*time.Second, time.Millisecond)
510 }
511
512 func TestWhatsAppGroupTurns(t *testing.T) {
513 testCases := []struct {
514 name string
515 message func(event *events.Message)
516 line string
517 turn bool
518 }{
519 {
520 name: "plain",
521 message: func(event *events.Message) {
522 },
523 line: "12:00 Bruno Lima: Who brings the cake?",
524 },
525 {
526 name: "mention",
527 message: func(event *events.Message) {
528 event.Message = &waE2E.Message{
529 ExtendedTextMessage: &waE2E.ExtendedTextMessage{
530 Text: new("@" + whatsappTestLID + " can you bring the cake? Call " + whatsappTestNumber + "."),
531 ContextInfo: &waE2E.ContextInfo{
532 MentionedJID: []string{whatsappTestLID + "@lid"},
533 },
534 },
535 }
536 },
537 line: "12:00 Bruno Lima (mentions you): @you can you bring the cake? Call OWN.",
538 turn: true,
539 },
540 {
541 name: "reply",
542 message: func(event *events.Message) {
543 event.Message = &waE2E.Message{
544 ExtendedTextMessage: &waE2E.ExtendedTextMessage{
545 Text: new("Who brings the cake?"),
546 ContextInfo: &waE2E.ContextInfo{
547 Participant: new(whatsappTestOwn.String()),
548 },
549 },
550 }
551 },
552 line: "12:00 Bruno Lima (replies to you): Who brings the cake?",
553 turn: true,
554 },
555 }
556
557 for _, tc := range testCases {
558 t.Run(tc.name, func(t *testing.T) {
559 whatsapp, fake := whatsappStartTestLinked(t)
560 fake.groups = []*types.GroupInfo{
561 {
562 JID: whatsappTestFamily,
563 GroupName: types.GroupName{
564 Name: "Family",
565 },
566 },
567 }
568
569 server := newModelFake(t)
570 socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
571 client := terminalStartTestClient(t, socket)
572 client.WaitFor(t, "[connected to OneChat]")
573 whatsappTestConnect(t, fake)
574
575 event := whatsappTestMessage(whatsappTestFamily, whatsappTestBruno, "m1", "Who brings the cake?", time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC))
576 event.Info.PushName = "Bruno Lima"
577 tc.message(event)
578 require.True(t, fake.Emit(event))
579
580 text := "[WhatsApp] Family, group 120363000000000001@g.us, Thursday 2026-01-01\n" + tc.line
581 if tc.turn {
582 text += "\n" + whatsappBatchEmptyReply
583 client.WaitFor(t, "[done]")
584 require.Equal(t, 1, server.Calls())
585 } else {
586 client.WaitFor(t, text)
587 time.Sleep(100 * time.Millisecond)
588 require.Zero(t, server.Calls())
589 }
590
591 require.Equal(t, text, whatsappTestLogTexts(t, memory)[0])
592 })
593 }
594 }
595
596 func TestWhatsAppTakesOnlyText(t *testing.T) {
597 at := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
598 testCases := []struct {
599 name string
600 change func(event *events.Message)
601 }{
602 {
603 name: "an edit",
604 change: func(event *events.Message) {
605 event.IsEdit = true
606 },
607 },
608 {
609 name: "old history",
610 change: func(event *events.Message) {
611 event.SourceWebMsg = &waWeb.WebMessageInfo{}
612 },
613 },
614 {
615 name: "a view-once message",
616 change: func(event *events.Message) {
617 event.IsViewOnce = true
618 },
619 },
620 {
621 name: "a disappearing message",
622 change: func(event *events.Message) {
623 event.IsEphemeral = true
624 },
625 },
626 {
627 name: "the chat of the user with itself",
628 change: func(event *events.Message) {
629 event.Info.Chat = whatsappTestOwn
630 },
631 },
632 {
633 name: "a status broadcast",
634 change: func(event *events.Message) {
635 event.Info.Chat = types.StatusBroadcastJID
636 },
637 },
638 {
639 name: "a photo with a caption",
640 change: func(event *events.Message) {
641 event.Message = &waE2E.Message{
642 ImageMessage: &waE2E.ImageMessage{
643 Caption: new("look"),
644 },
645 }
646 },
647 },
648 {
649 name: "a text of spaces",
650 change: func(event *events.Message) {
651 event.Message.Conversation = new(" ")
652 },
653 },
654 }
655
656 for _, tc := range testCases {
657 t.Run(tc.name, func(t *testing.T) {
658 whatsapp, _ := whatsappStartTestLinked(t)
659 event := whatsappTestMessage(whatsappTestAna, whatsappTestAna, "m1", "hi", at)
660 tc.change(event)
661 require.True(t, whatsapp.handle(event))
662 require.NoError(t, whatsapp.state.CloseAll())
663 require.Empty(t, whatsapp.state.Closed())
664 })
665 }
666 }
667
668 // whatsappStartTestLinked opens a WhatsApp with a linked device in a temporary
669 // directory, with a quiet time of 50 ms for its batches.
670 func whatsappStartTestLinked(t *testing.T) (*WhatsApp, *WhatsAppFake) {
671 t.Helper()
672
673 dir := t.TempDir()
674 whatsappTestSession(t, dir, true)
675 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
676 whatsapp.state.quiet = 50 * time.Millisecond
677
678 return whatsapp, fake
679 }
680
681 func TestWhatsAppCatchupGivesOneTurn(t *testing.T) {
682 whatsapp, fake := whatsappStartTestLinked(t)
683 server := newModelFake(t)
684 socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
685 client := terminalStartTestClient(t, socket)
686 client.WaitFor(t, "[connected to OneChat]")
687 <-fake.connects
688
689 require.True(t, fake.Emit(&events.Connected{}))
690 at := time.Date(2026, 1, 1, 8, 0, 0, 0, time.UTC)
691 for index, event := range []*events.Message{
692 whatsappTestMessage(whatsappTestAna, whatsappTestAna, "m1", "Good morning", at),
693 whatsappTestMessage(whatsappTestBruno, whatsappTestBruno, "m2", "Call me", at.Add(time.Hour)),
694 whatsappTestMessage(whatsappTestAna, whatsappTestAna, "m3", "Are you there?", at.Add(2*time.Hour)),
695 } {
696 event.Info.PushName = []string{"Ana", "Bruno", "Ana"}[index]
697 require.True(t, fake.Emit(event))
698 }
699
700 time.Sleep(100 * time.Millisecond)
701 require.Zero(t, memory.Len())
702
703 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
704 client.WaitFor(t, "[done]")
705 require.Equal(t, []string{
706 "[WhatsApp] Ana, private chat 15550002222@s.whatsapp.net, Thursday 2026-01-01\n08:00 Ana: Good morning\n" + whatsappBatchEmptyReply,
707 "[WhatsApp] Bruno, private chat 15550003333@s.whatsapp.net, Thursday 2026-01-01\n09:00 Bruno: Call me\n" + whatsappBatchEmptyReply,
708 "[WhatsApp] Ana, private chat 15550002222@s.whatsapp.net, Thursday 2026-01-01\n10:00 Ana: Are you there?\n" + whatsappBatchEmptyReply,
709 }, whatsappTestLogTexts(t, memory)[:3])
710
711 time.Sleep(100 * time.Millisecond)
712 require.Equal(t, 1, server.Calls())
713 for _, text := range []string{"Good morning", "Call me", "Are you there?"} {
714 require.Contains(t, string(server.Call(0).raw), text)
715 }
716 }
717
718 func TestWhatsAppCatchupEndsAfterItsLimit(t *testing.T) {
719 whatsapp, fake := whatsappStartTestLinked(t)
720 whatsapp.catchupLimit = 100 * time.Millisecond
721 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
722 client := terminalStartTestClient(t, socket)
723 client.WaitFor(t, "[connected to OneChat]")
724 <-fake.connects
725
726 require.True(t, fake.Emit(&events.Connected{}))
727 require.True(t, fake.Emit(whatsappTestMessage(whatsappTestAna, whatsappTestOwn, "m1", "On my way.", time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC))))
728 client.WaitFor(t, "12:00 You: On my way.")
729 require.Len(t, whatsappTestLogTexts(t, memory), 1)
730 }
731
732 func TestWhatsAppStateOfTheStateFileWaitForTheCatchup(t *testing.T) {
733 dir := t.TempDir()
734 whatsappTestSession(t, dir, true)
735 before, _, _ := whatsappStartTest(t, dir, newTestClock())
736 _, err := before.state.Add(whatsappTestChat, WhatsAppMessage{
737 ID: "m1",
738 Sender: "Ana Souza",
739 Time: time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC),
740 Text: "Did you see my message?",
741 }, time.Now().Add(-time.Hour))
742 require.NoError(t, err)
743
744 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
745 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
746 client := terminalStartTestClient(t, socket)
747 client.WaitFor(t, "[connected to OneChat]")
748 <-fake.connects
749
750 time.Sleep(100 * time.Millisecond)
751 require.Zero(t, memory.Len())
752
753 require.True(t, fake.Emit(&events.Connected{}))
754 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
755 client.WaitFor(t, "12:00 Ana Souza: Did you see my message?")
756 client.WaitFor(t, "[done]")
757 }
758
759 // whatsappTestConnect waits for the connection of the daemon and gives it the
760 // events of a connection with an empty catch-up.
761 func whatsappTestConnect(t *testing.T, fake *WhatsAppFake) {
762 t.Helper()
763
764 <-fake.connects
765 require.True(t, fake.Emit(&events.Connected{}))
766 require.True(t, fake.Emit(&events.OfflineSyncCompleted{}))
767 }
768
769 func TestWhatsAppFindMatchesNamesWithNoRegardToCaseAndAccents(t *testing.T) {
770 whatsapp, fake := whatsappStartTestLinked(t)
771 fake.groups = []*types.GroupInfo{
772 {
773 JID: whatsappTestFamily,
774 GroupName: types.GroupName{
775 Name: "Família Souza",
776 },
777 },
778 }
779
780 whatsappTestContacts(t, whatsapp)
781 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
782 whatsappTestConnect(t, fake)
783
784 testCases := []struct {
785 name string
786 query string
787 answer string
788 }{
789 {
790 name: "no accent finds an accent",
791 query: "joao",
792 answer: "15550004444@s.whatsapp.net | João Silva | contact",
793 },
794 {
795 name: "a part of a name finds contacts and groups",
796 query: "SOUZA",
797 answer: "15550002222@s.whatsapp.net | Ana Souza | contact\n120363000000000001@g.us | Família Souza | group",
798 },
799 {
800 name: "a business name",
801 query: "bakery",
802 answer: "15550005555@s.whatsapp.net | Corner Bakery | contact",
803 },
804 {
805 name: "no match",
806 query: "Zed",
807 answer: "No contact or group has a name with \"Zed\".",
808 },
809 }
810
811 for _, tc := range testCases {
812 t.Run(tc.name, func(t *testing.T) {
813 answer, err := whatsapp.Find(t.Context(), tc.query)
814 require.NoError(t, err)
815 require.Equal(t, tc.answer, answer)
816 })
817 }
818 }
819
820 func TestWhatsAppFindGivesAtMostTwentyMatches(t *testing.T) {
821 whatsapp, _ := whatsappStartTestLinked(t)
822 for index := range 25 {
823 jid := types.NewJID(fmt.Sprintf("1555001%04d", index), types.DefaultUserServer)
824 require.NoError(t, whatsapp.device.Contacts.PutContactName(t.Context(), jid, "", fmt.Sprintf("Member %02d", index)))
825 }
826
827 answer, err := whatsapp.Find(t.Context(), "member")
828 require.NoError(t, err)
829
830 lines := strings.Split(answer, "\n")
831 require.Len(t, lines, 22)
832 require.Equal(t, "15550010000@s.whatsapp.net | Member 00 | contact", lines[0])
833 require.Equal(t, "5 more: give a longer part of the name.", lines[20])
834 require.Equal(t, "The groups are not in this answer, because WhatsApp is disconnected.", lines[21])
835 }
836
837 func TestWhatsAppFindBeforeTheNamesArrive(t *testing.T) {
838 whatsapp, fake := whatsappStartTestLinked(t)
839 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
840 whatsappTestConnect(t, fake)
841
842 answer, err := whatsapp.Find(t.Context(), "ana")
843 require.NoError(t, err)
844 require.Equal(t, whatsappNamesNotReady, answer)
845 }
846
847 func TestWhatsAppFindWithoutALink(t *testing.T) {
848 whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
849
850 answer, err := whatsapp.Find(t.Context(), "ana")
851 require.NoError(t, err)
852 require.Equal(t, whatsappNotLinked, answer)
853 }
854
855 func TestAgentFindsAWhatsAppContact(t *testing.T) {
856 whatsapp, fake := whatsappStartTestLinked(t)
857 whatsappTestContacts(t, whatsapp)
858 server := newModelFake(t)
859 server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
860 if call.number == 0 {
861 modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "whatsapp_find", `{"name":"ana"}`)}, 100, 0, 5))
862 return
863 }
864
865 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Found Ana.")}, 100, 0, 5))
866 }
867
868 socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
869 client := terminalStartTestClient(t, socket)
870 whatsappTestConnect(t, fake)
871
872 client.Type("Find Ana on WhatsApp.")
873 client.WaitFor(t, "[result] 15550002222@s.whatsapp.net | Ana Souza | contact\nFound Ana.\n[done]")
874 }
875
876 func TestSubagentHasNoWhatsAppTools(t *testing.T) {
877 box := &Toolbox{}
878 require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`))
879 require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`))
880 }
881
882 // whatsappTestContacts puts the contacts of the tests into the session of
883 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
884 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
885 t.Helper()
886
887 contacts := whatsapp.device.Contacts
888 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
889 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
890 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
891 require.NoError(t, err)
892 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))
893 }
894
895 func TestWhatsAppSendSendsOnceForEachID(t *testing.T) {
896 whatsapp, fake := whatsappStartTestLinked(t)
897 whatsappTestContacts(t, whatsapp)
898 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
899 whatsappTestConnect(t, fake)
900
901 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.")
902 require.NoError(t, err)
903 require.Equal(t, "Sent to Ana Souza at 12:05.", answer)
904
905 answer, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.")
906 require.NoError(t, err)
907 require.Equal(t, "Sent to Ana Souza at 12:05. This is the answer of the first call with this id: nothing was sent again.", answer)
908
909 _, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "Another text.")
910 require.EqualError(t, err, "the id keys belongs to another message: give a new id for each message")
911
912 require.Equal(t, []WhatsAppFakeSend{
913 {
914 to: whatsappTestAna.String(),
915 text: "The keys are under the mat.",
916 id: "MSG1",
917 },
918 }, fake.Sent())
919
920 again, err := openWhatsAppState(filepath.Join(whatsapp.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
921 require.NoError(t, err)
922
923 record, found := again.Send("keys")
924 require.True(t, found)
925 require.Equal(t, whatsappSent, record.State)
926 require.Equal(t, "MSG1", record.MessageID)
927 }
928
929 func TestWhatsAppSendToAGroup(t *testing.T) {
930 whatsapp, fake := whatsappStartTestLinked(t)
931 fake.groups = []*types.GroupInfo{
932 {
933 JID: whatsappTestFamily,
934 GroupName: types.GroupName{
935 Name: "Family",
936 },
937 },
938 }
939
940 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
941 whatsappTestConnect(t, fake)
942
943 answer, err := whatsapp.Send(t.Context(), "cake", whatsappTestFamily.String(), "I bring the cake.")
944 require.NoError(t, err)
945 require.Equal(t, "Sent to Family at 12:05.", answer)
946 }
947
948 func TestWhatsAppSendThatFails(t *testing.T) {
949 whatsapp, fake := whatsappStartTestLinked(t)
950 fake.sendErr = errors.New("server error for " + whatsappTestNumber)
951 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
952 whatsappTestConnect(t, fake)
953
954 for range 2 {
955 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
956 require.NoError(t, err)
957 require.True(t, strings.HasPrefix(answer, "The send failed: server error for OWN."), answer)
958 }
959
960 require.Len(t, fake.Sent(), 1)
961 }
962
963 func TestWhatsAppSendCutByAStop(t *testing.T) {
964 whatsapp, fake := whatsappStartTestLinked(t)
965 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
966 whatsappTestConnect(t, fake)
967
968 digest := sha256.Sum256([]byte("hi"))
969 require.NoError(t, whatsapp.state.PutSend(WhatsAppSend{
970 ID: "keys",
971 Chat: whatsappTestAna.String(),
972 Digest: hex.EncodeToString(digest[:]),
973 State: whatsappSending,
974 }))
975
976 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
977 require.NoError(t, err)
978 require.Contains(t, answer, "its result is unknown")
979 require.Empty(t, fake.Sent())
980 }
981
982 func TestWhatsAppSendRefuses(t *testing.T) {
983 testCases := []struct {
984 name string
985 id string
986 chat string
987 text string
988 err string
989 }{
990 {
991 name: "no id",
992 id: " ",
993 chat: whatsappTestAna.String(),
994 text: "hi",
995 err: "the id must have 1 to 100 bytes",
996 },
997 {
998 name: "no text",
999 id: "a",
1000 chat: whatsappTestAna.String(),
1001 text: "",
1002 err: "the text must have 1 to 65536 bytes",
1003 },
1004 {
1005 name: "a name for a chat",
1006 id: "a",
1007 chat: "Ana Souza",
1008 text: "hi",
1009 err: `"Ana Souza" is not the ID of a WhatsApp chat: find the ID with whatsapp_find`,
1010 },
1011 {
1012 name: "a status broadcast",
1013 id: "a",
1014 chat: types.StatusBroadcastJID.String(),
1015 text: "hi",
1016 err: `"status@broadcast" is not a private chat or a group`,
1017 },
1018 {
1019 name: "the chat of the user",
1020 id: "a",
1021 chat: whatsappTestOwn.String(),
1022 text: "hi",
1023 err: "this is the chat of the user with itself: send to another chat",
1024 },
1025 }
1026
1027 whatsapp, fake := whatsappStartTestLinked(t)
1028 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
1029 whatsappTestConnect(t, fake)
1030
1031 for _, tc := range testCases {
1032 t.Run(tc.name, func(t *testing.T) {
1033 _, err := whatsapp.Send(t.Context(), tc.id, tc.chat, tc.text)
1034 require.EqualError(t, err, tc.err)
1035 })
1036 }
1037
1038 require.Empty(t, fake.Sent())
1039 }
1040
1041 func TestWhatsAppSendWhileDisconnected(t *testing.T) {
1042 whatsapp, fake := whatsappStartTestLinked(t)
1043 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
1044 whatsappTestConnect(t, fake)
1045 require.True(t, fake.Emit(&events.Disconnected{}))
1046
1047 _, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
1048 require.EqualError(t, err, "WhatsApp is disconnected, so nothing was sent: try again later")
1049
1050 require.True(t, fake.Emit(&events.Connected{}))
1051 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
1052 require.NoError(t, err)
1053 require.Equal(t, "Sent to +15550002222 at 12:05.", answer)
1054 }
1055
1056 func TestWhatsAppSendWithoutALink(t *testing.T) {
1057 whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
1058
1059 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
1060 require.NoError(t, err)
1061 require.Equal(t, whatsappNotLinked, answer)
1062 }
1063
1064 func TestAgentSendsAWhatsAppMessage(t *testing.T) {
1065 whatsapp, fake := whatsappStartTestLinked(t)
1066 whatsappTestContacts(t, whatsapp)
1067 server := newModelFake(t)
1068 server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
1069 if call.number == 0 {
1070 modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "whatsapp_send", `{"id":"keys","chat":"15550002222@s.whatsapp.net","text":"The keys are under the mat."}`)}, 100, 0, 5))
1071 return
1072 }
1073
1074 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Sent.")}, 100, 0, 5))
1075 }
1076
1077 socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
1078 client := terminalStartTestClient(t, socket)
1079 whatsappTestConnect(t, fake)
1080
1081 client.Type("Tell Ana that the keys are under the mat.")
1082 client.WaitFor(t, "[result] Sent to Ana Souza at 12:05.\nSent.\n[done]")
1083 require.Len(t, fake.Sent(), 1)
1084 }