15 "github.com/stretchr/testify/require"
17 "go.mau.fi/whatsmeow/types"
18 "go.mau.fi/whatsmeow/types/events"
21 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
23 whatsappTestSession(t, dir, true)
24 clock := newTestClock()
25 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
26 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
29 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
31 require.True(t, fake.Emit(&events.Connected{}))
32 require.Equal(t, "WhatsApp is linked and connected since 2026-01-01 12:00.", whatsapp.Status())
34 clock.now = clock.now.Add(20 * time.Minute)
35 require.True(t, fake.Emit(&events.Disconnected{}))
36 clock.now = clock.now.Add(time.Minute)
37 require.True(t, fake.Emit(&events.Disconnected{}))
38 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 func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
43 whatsappTestSession(t, dir, true)
44 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
45 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
48 require.True(t, fake.Emit(&events.Disconnected{}))
49 require.Equal(t, "WhatsApp is linked and disconnected since 2026-01-01 12:00.", whatsapp.Status())
52 func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
53 testCases := []struct {
55 session func(t *testing.T, dir string)
58 name: "no session file",
59 session: func(t *testing.T, dir string) {
63 name: "a session of a pairing that did not end",
64 session: func(t *testing.T, dir string) {
65 whatsappTestSession(t, dir, false)
70 for _, tc := range testCases {
71 t.Run(tc.name, func(t *testing.T) {
74 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
75 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
80 func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
82 whatsappTestSession(t, dir, true)
83 require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
85 _, err := openWhatsApp(t.Context(), dir, time.Now, whatsappDiscardLog(), whatsappNewClient)
86 require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600")
89 func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) {
90 server := newModelFake(t)
91 telegram := newTelegramFake(t)
92 bot, _ := telegramStartTestBot(t, telegram)
93 socket := daemonStartTestWithBot(t, server, bot)
94 asking := terminalStartTestClient(t, socket)
95 other := terminalStartTestClient(t, socket)
96 asking.WaitFor(t, "[connected to OneChat]")
97 other.WaitFor(t, "[connected to OneChat]")
99 asking.Type("/whatsapp status")
100 asking.WaitFor(t, "WhatsApp is not linked.")
101 asking.Type(" /whatsapp unknown ")
102 asking.WaitFor(t, whatsappUsage)
103 asking.Type("/whatsapp pair 0123")
104 asking.WaitFor(t, "PHONE must be the number of your WhatsApp account")
106 telegram.Add(TelegramUpdate{
108 Message: telegramOwnerMessage("/whatsapp status"),
111 telegramWaitForSent(t, telegram, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.")
112 require.Len(t, telegram.Sent(), 1)
113 require.Equal(t, "[connected to OneChat]\n", other.Output())
114 require.Zero(t, server.Calls())
117 func TestWhatsAppPairsWithACode(t *testing.T) {
119 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
120 server := newModelFake(t)
121 socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
122 asking := terminalStartTestClient(t, socket)
123 other := terminalStartTestClient(t, socket)
124 asking.WaitFor(t, "[connected to OneChat]")
125 other.WaitFor(t, "[connected to OneChat]")
127 asking.Type("/whatsapp pair +1 555-000-1111")
128 items := <-fake.pairings
129 items <- whatsmeow.QRChannelItem{
130 Event: whatsmeow.QRChannelEventCode,
133 asking.WaitFor(t, whatsappPairSteps+"\n"+whatsappTestCode+"\n")
134 require.True(t, fake.Emit(&events.PairSuccess{
135 ID: types.NewADJID(whatsappTestNumber, 0, 1),
136 LID: types.NewADJID(whatsappTestLID, 0, 1),
138 items <- whatsmeow.QRChannelSuccess
139 asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
141 // The library connects again after the link with the context of the
142 // connection, so the end of the pairing must not end it.
143 connections := fake.Connections()
144 require.Len(t, connections, 1)
145 require.Never(t, func() bool {
146 return connections[0].Err() != nil
147 }, 200*time.Millisecond, time.Millisecond)
149 require.Equal(t, []string{whatsappTestNumber}, fake.Phones())
150 require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
151 require.Equal(t, "[connected to OneChat]\n", other.Output())
152 require.Zero(t, server.Calls())
153 require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory))
155 info, err := os.Stat(filepath.Join(dir, whatsappDirName))
156 require.NoError(t, err)
157 require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
159 info, err = os.Stat(filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
160 require.NoError(t, err)
161 require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
164 func TestWhatsAppPairingCodeIsATelegramMessageAlone(t *testing.T) {
165 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
166 telegram := newTelegramFake(t)
167 bot, _ := telegramStartTestBot(t, telegram)
168 daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
170 telegram.Add(TelegramUpdate{
172 Message: telegramOwnerMessage("/whatsapp pair 15550001111"),
175 items := <-fake.pairings
176 items <- whatsmeow.QRChannelItem{
177 Event: whatsmeow.QRChannelEventCode,
180 telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode)
183 func TestWhatsAppPairingEnds(t *testing.T) {
184 testCases := []struct {
186 end func(items chan whatsmeow.QRChannelItem)
190 name: "the code expires",
191 end: func(items chan whatsmeow.QRChannelItem) {
192 items <- whatsmeow.QRChannelTimeout
194 answer: whatsappPairExpired,
197 name: "the library closes the pairing",
198 end: func(items chan whatsmeow.QRChannelItem) {
201 answer: whatsappPairExpired,
204 name: "the pairing fails",
205 end: func(items chan whatsmeow.QRChannelItem) {
206 items <- whatsmeow.QRChannelItem{
207 Event: whatsmeow.QRChannelEventError,
208 Error: errors.New("bad handshake"),
211 answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.",
215 for _, tc := range testCases {
216 t.Run(tc.name, func(t *testing.T) {
217 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
218 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
219 client := terminalStartTestClient(t, socket)
220 client.Type("/whatsapp pair 15550001111")
222 items := <-fake.pairings
223 items <- whatsmeow.QRChannelItem{
224 Event: whatsmeow.QRChannelEventCode,
227 client.WaitFor(t, whatsappTestCode)
229 client.WaitFor(t, tc.answer)
230 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
235 func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) {
236 whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
237 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
238 client := terminalStartTestClient(t, socket)
240 client.Type("/whatsapp pair 15550001111")
242 client.Type("/whatsapp pair 15550002222")
243 items := <-fake.pairings
244 items <- whatsmeow.QRChannelItem{
245 Event: whatsmeow.QRChannelEventCode,
248 client.WaitFor(t, whatsappTestCode)
249 require.Equal(t, []string{"15550002222"}, fake.Phones())
250 require.NotContains(t, client.Output(), "did not start the pairing")
253 func TestWhatsAppPairWhenLinked(t *testing.T) {
255 whatsappTestSession(t, dir, true)
256 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
257 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
258 client := terminalStartTestClient(t, socket)
260 client.Type("/whatsapp pair 15550001111")
261 client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.")
264 func TestWhatsAppUnlink(t *testing.T) {
265 testCases := []struct {
271 name: "with a logout",
272 answer: "WhatsApp is unlinked.",
275 name: "with no logout",
276 logoutErr: errors.New("not connected"),
277 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.",
281 for _, tc := range testCases {
282 t.Run(tc.name, func(t *testing.T) {
284 whatsappTestSession(t, dir, true)
285 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
286 fake.logoutErr = tc.logoutErr
287 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
288 client := terminalStartTestClient(t, socket)
291 client.Type("/whatsapp unlink")
292 client.WaitFor(t, tc.answer)
293 require.Equal(t, 1, fake.Logouts())
294 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
295 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
296 require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory))
298 client.Type("/whatsapp unlink")
299 client.WaitFor(t, "WhatsApp is not linked.\n")
304 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
306 whatsappTestSession(t, dir, true)
307 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
308 telegram := newTelegramFake(t)
309 bot, _ := telegramStartTestBot(t, telegram)
310 socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
311 client := terminalStartTestClient(t, socket)
312 client.WaitFor(t, "[connected to OneChat]")
315 require.True(t, fake.Emit(&events.LoggedOut{}))
316 notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again."
317 client.WaitFor(t, notice)
318 telegramWaitForSent(t, telegram, notice)
319 require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
320 require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
321 require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory))
324 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
326 whatsappTestSession(t, dir, true)
327 clock := newTestClock()
328 whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
329 whatsapp.noticeDelay = 300 * time.Millisecond
330 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
331 client := terminalStartTestClient(t, socket)
332 client.WaitFor(t, "[connected to OneChat]")
335 require.True(t, fake.Emit(&events.Connected{}))
336 require.True(t, fake.Emit(&events.Disconnected{}))
337 require.True(t, fake.Emit(&events.Connected{}))
338 time.Sleep(400 * time.Millisecond)
339 require.Equal(t, "[connected to OneChat]\n", client.Output())
341 clock.now = clock.now.Add(time.Hour)
342 require.True(t, fake.Emit(&events.Disconnected{}))
343 require.True(t, fake.Emit(&events.Disconnected{}))
344 client.WaitFor(t, "WhatsApp is disconnected since 2026-01-01 13:00. OneChat tries again.\n")
345 require.True(t, fake.Emit(&events.Disconnected{}))
346 time.Sleep(400 * time.Millisecond)
348 require.True(t, fake.Emit(&events.Connected{}))
349 client.WaitFor(t, "WhatsApp is connected again.\n")
350 require.Equal(t, 1, strings.Count(client.Output(), "WhatsApp is disconnected since"))
353 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
355 whatsappTestSession(t, dir, true)
356 whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
357 socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
358 client := terminalStartTestClient(t, socket)
359 client.WaitFor(t, "[connected to OneChat]")
362 require.True(t, fake.Emit(&events.StreamReplaced{}))
363 client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.")
366 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
368 whatsappTestSession(t, dir, true)
369 whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
370 fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid")
371 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
374 require.Eventually(t, func() bool {
375 return logs.String() != ""
376 }, 10*time.Second, time.Millisecond)
377 require.Equal(t, "connect: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String())
380 func TestWhatsAppPhone(t *testing.T) {
381 testCases := []struct {
387 name: "a number with a plus and dashes",
388 phone: "+1-555-000-1111",
392 name: "a number with no country code",
393 phone: "0115550001111",
397 name: "a short number",
402 name: "a long number",
403 phone: "1234567890123456",
407 name: "a number with letters",
408 phone: "1555ABC1111",
413 for _, tc := range testCases {
414 t.Run(tc.name, func(t *testing.T) {
415 _, valid := whatsappPhone(tc.phone)
416 require.Equal(t, tc.valid, valid)
421 func TestWhatsAppCommandArgs(t *testing.T) {
422 testCases := []struct {
429 name: "a command with its arguments",
430 line: " /whatsapp pair +1 555 ",
435 name: "the command alone",
441 name: "a word that starts with the command",
442 line: "/whatsappstatus",
447 name: "a message that names the command",
448 line: "what does /whatsapp status do?",
454 for _, tc := range testCases {
455 t.Run(tc.name, func(t *testing.T) {
456 args, found := whatsappCommandArgs(tc.line)
457 require.Equal(t, tc.args, args)
458 require.Equal(t, tc.found, found)
463 func TestWhatsAppFindMatchesNamesWithNoRegardToCaseAndAccents(t *testing.T) {
464 whatsapp, fake := whatsappStartTestLinked(t)
465 fake.groups = []*types.GroupInfo{
467 JID: whatsappTestFamily,
468 GroupName: types.GroupName{
469 Name: "Família Souza",
474 whatsappTestContacts(t, whatsapp)
475 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
476 whatsappTestConnect(t, fake)
478 testCases := []struct {
484 name: "no accent finds an accent",
486 answer: "15550004444@s.whatsapp.net | João Silva | contact",
489 name: "a part of a name finds contacts and groups",
491 answer: "15550002222@s.whatsapp.net | Ana Souza | contact\n120363000000000001@g.us | Família Souza | group",
494 name: "a business name",
496 answer: "15550005555@s.whatsapp.net | Corner Bakery | contact",
501 answer: "No contact or group has a name with \"Zed\".",
505 for _, tc := range testCases {
506 t.Run(tc.name, func(t *testing.T) {
507 answer, err := whatsapp.Find(t.Context(), tc.query)
508 require.NoError(t, err)
509 require.Equal(t, tc.answer, answer)
514 func TestWhatsAppFindGivesAtMostTwentyMatches(t *testing.T) {
515 whatsapp, _ := whatsappStartTestLinked(t)
516 for index := range 25 {
517 jid := types.NewJID(fmt.Sprintf("1555001%04d", index), types.DefaultUserServer)
518 require.NoError(t, whatsapp.device.Contacts.PutContactName(t.Context(), jid, "", fmt.Sprintf("Member %02d", index)))
521 answer, err := whatsapp.Find(t.Context(), "member")
522 require.NoError(t, err)
524 lines := strings.Split(answer, "\n")
525 require.Len(t, lines, 22)
526 require.Equal(t, "15550010000@s.whatsapp.net | Member 00 | contact", lines[0])
527 require.Equal(t, "5 more: give a longer part of the name.", lines[20])
528 require.Equal(t, "The groups are not in this answer, because WhatsApp is disconnected.", lines[21])
531 func TestWhatsAppFindBeforeTheNamesArrive(t *testing.T) {
532 whatsapp, fake := whatsappStartTestLinked(t)
533 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
534 whatsappTestConnect(t, fake)
536 answer, err := whatsapp.Find(t.Context(), "ana")
537 require.NoError(t, err)
538 require.Equal(t, whatsappNamesNotReady, answer)
541 func TestWhatsAppFindWithoutALink(t *testing.T) {
542 whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
544 answer, err := whatsapp.Find(t.Context(), "ana")
545 require.NoError(t, err)
546 require.Equal(t, whatsappNotLinked, answer)
549 func TestAgentFindsAWhatsAppContact(t *testing.T) {
550 whatsapp, fake := whatsappStartTestLinked(t)
551 whatsappTestContacts(t, whatsapp)
552 server := newModelFake(t)
553 server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
554 if call.number == 0 {
555 modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "whatsapp_find", `{"name":"ana"}`)}, 100, 0, 5))
559 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Found Ana.")}, 100, 0, 5))
562 socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
563 client := terminalStartTestClient(t, socket)
564 whatsappTestConnect(t, fake)
566 client.Type("Find Ana on WhatsApp.")
567 client.WaitFor(t, "[result] 15550002222@s.whatsapp.net | Ana Souza | contact\nFound Ana.\n[done]")
570 func TestSubagentHasNoWhatsAppTools(t *testing.T) {
572 require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`))
573 require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`))
576 // whatsappTestContacts puts the contacts of the tests into the session of
577 // whatsapp: Ana Souza, Joao Silva with an accent, a business, and the user.
578 func whatsappTestContacts(t *testing.T, whatsapp *WhatsApp) {
581 contacts := whatsapp.device.Contacts
582 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestAna, "Ana", "Ana Souza"))
583 require.NoError(t, contacts.PutContactName(t.Context(), types.NewJID("15550004444", types.DefaultUserServer), "João", "João Silva"))
584 _, _, err := contacts.PutBusinessName(t.Context(), types.NewJID("15550005555", types.DefaultUserServer), "Corner Bakery")
585 require.NoError(t, err)
586 require.NoError(t, contacts.PutContactName(t.Context(), whatsappTestOwn, "Me", "Me Souza"))
589 func TestWhatsAppSendSendsOnceForEachID(t *testing.T) {
590 whatsapp, fake := whatsappStartTestLinked(t)
591 whatsappTestContacts(t, whatsapp)
592 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
593 whatsappTestConnect(t, fake)
595 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.")
596 require.NoError(t, err)
597 require.Equal(t, "Sent to Ana Souza at 12:05.", answer)
599 answer, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.")
600 require.NoError(t, err)
601 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)
603 _, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "Another text.")
604 require.EqualError(t, err, "the id keys belongs to another message: give a new id for each message")
606 require.Equal(t, []WhatsAppFakeSend{
608 to: whatsappTestAna.String(),
609 text: "The keys are under the mat.",
614 again, err := openWhatsAppState(filepath.Join(whatsapp.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
615 require.NoError(t, err)
617 record, found := again.Send("keys")
618 require.True(t, found)
619 require.Equal(t, whatsappSent, record.State)
620 require.Equal(t, "MSG1", record.MessageID)
623 func TestWhatsAppSendToAGroup(t *testing.T) {
624 whatsapp, fake := whatsappStartTestLinked(t)
625 fake.groups = []*types.GroupInfo{
627 JID: whatsappTestFamily,
628 GroupName: types.GroupName{
634 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
635 whatsappTestConnect(t, fake)
637 answer, err := whatsapp.Send(t.Context(), "cake", whatsappTestFamily.String(), "I bring the cake.")
638 require.NoError(t, err)
639 require.Equal(t, "Sent to Family at 12:05.", answer)
642 func TestWhatsAppSendThatFails(t *testing.T) {
643 whatsapp, fake := whatsappStartTestLinked(t)
644 fake.sendErr = errors.New("server error for " + whatsappTestNumber)
645 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
646 whatsappTestConnect(t, fake)
649 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
650 require.NoError(t, err)
651 require.True(t, strings.HasPrefix(answer, "The send failed: server error for OWN."), answer)
654 require.Len(t, fake.Sent(), 1)
657 func TestWhatsAppSendCutByAStop(t *testing.T) {
658 whatsapp, fake := whatsappStartTestLinked(t)
659 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
660 whatsappTestConnect(t, fake)
662 digest := sha256.Sum256([]byte("hi"))
663 require.NoError(t, whatsapp.state.PutSend(WhatsAppSend{
665 Chat: whatsappTestAna.String(),
666 Digest: hex.EncodeToString(digest[:]),
667 State: whatsappSending,
670 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
671 require.NoError(t, err)
672 require.Contains(t, answer, "its result is unknown")
673 require.Empty(t, fake.Sent())
676 func TestWhatsAppSendRefuses(t *testing.T) {
677 testCases := []struct {
687 chat: whatsappTestAna.String(),
689 err: "the id must have 1 to 100 bytes",
694 chat: whatsappTestAna.String(),
696 err: "the text must have 1 to 65536 bytes",
699 name: "a name for a chat",
703 err: `"Ana Souza" is not the ID of a WhatsApp chat: find the ID with whatsapp_find`,
706 name: "a status broadcast",
708 chat: types.StatusBroadcastJID.String(),
710 err: `"status@broadcast" is not a private chat or a group`,
713 name: "the chat of the user",
715 chat: whatsappTestOwn.String(),
717 err: "this is the chat of the user with itself: send to another chat",
721 whatsapp, fake := whatsappStartTestLinked(t)
722 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
723 whatsappTestConnect(t, fake)
725 for _, tc := range testCases {
726 t.Run(tc.name, func(t *testing.T) {
727 _, err := whatsapp.Send(t.Context(), tc.id, tc.chat, tc.text)
728 require.EqualError(t, err, tc.err)
732 require.Empty(t, fake.Sent())
735 func TestWhatsAppSendWhileDisconnected(t *testing.T) {
736 whatsapp, fake := whatsappStartTestLinked(t)
737 daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
738 whatsappTestConnect(t, fake)
739 require.True(t, fake.Emit(&events.Disconnected{}))
741 _, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
742 require.EqualError(t, err, "WhatsApp is disconnected, so nothing was sent: try again later")
744 require.True(t, fake.Emit(&events.Connected{}))
745 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
746 require.NoError(t, err)
747 require.Equal(t, "Sent to +15550002222 at 12:05.", answer)
750 func TestWhatsAppSendWithoutALink(t *testing.T) {
751 whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
753 answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
754 require.NoError(t, err)
755 require.Equal(t, whatsappNotLinked, answer)
758 func TestAgentSendsAWhatsAppMessage(t *testing.T) {
759 whatsapp, fake := whatsappStartTestLinked(t)
760 whatsappTestContacts(t, whatsapp)
761 server := newModelFake(t)
762 server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
763 if call.number == 0 {
764 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))
768 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Sent.")}, 100, 0, 5))
771 socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
772 client := terminalStartTestClient(t, socket)
773 whatsappTestConnect(t, fake)
775 client.Type("Tell Ana that the keys are under the mat.")
776 client.WaitFor(t, "[result] Sent to Ana Souza at 12:05.\nSent.\n[done]")
777 require.Len(t, fake.Sent(), 1)