]> git.giacomolli.uk - onechat/blob - whatsapp_test.go
Give the WhatsApp batches their own type
[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/types"
18         "go.mau.fi/whatsmeow/types/events"
19 )
20
21 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
22         dir := t.TempDir()
23         whatsappTestSession(t, dir, true)
24         clock := newTestClock()
25         whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
26         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
27
28         <-fake.connects
29         require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
30
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())
33
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())
39 }
40
41 func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
42         dir := t.TempDir()
43         whatsappTestSession(t, dir, true)
44         whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
45         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
46
47         <-fake.connects
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())
50 }
51
52 func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
53         testCases := []struct {
54                 name    string
55                 session func(t *testing.T, dir string)
56         }{
57                 {
58                         name: "no session file",
59                         session: func(t *testing.T, dir string) {
60                         },
61                 },
62                 {
63                         name: "a session of a pairing that did not end",
64                         session: func(t *testing.T, dir string) {
65                                 whatsappTestSession(t, dir, false)
66                         },
67                 },
68         }
69
70         for _, tc := range testCases {
71                 t.Run(tc.name, func(t *testing.T) {
72                         dir := t.TempDir()
73                         tc.session(t, dir)
74                         whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
75                         require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
76                 })
77         }
78 }
79
80 func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
81         dir := t.TempDir()
82         whatsappTestSession(t, dir, true)
83         require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
84
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")
87 }
88
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]")
98
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")
105
106         telegram.Add(TelegramUpdate{
107                 UpdateID: 1,
108                 Message:  telegramOwnerMessage("/whatsapp status"),
109         })
110
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())
115 }
116
117 func TestWhatsAppPairsWithACode(t *testing.T) {
118         dir := t.TempDir()
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]")
126
127         asking.Type("/whatsapp pair +1 555-000-1111")
128         items := <-fake.pairings
129         items <- whatsmeow.QRChannelItem{
130                 Event: whatsmeow.QRChannelEventCode,
131         }
132
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),
137         }))
138         items <- whatsmeow.QRChannelSuccess
139         asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
140
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)
148
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))
154
155         info, err := os.Stat(filepath.Join(dir, whatsappDirName))
156         require.NoError(t, err)
157         require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
158
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())
162 }
163
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)
169
170         telegram.Add(TelegramUpdate{
171                 UpdateID: 1,
172                 Message:  telegramOwnerMessage("/whatsapp pair 15550001111"),
173         })
174
175         items := <-fake.pairings
176         items <- whatsmeow.QRChannelItem{
177                 Event: whatsmeow.QRChannelEventCode,
178         }
179
180         telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode)
181 }
182
183 func TestWhatsAppPairingEnds(t *testing.T) {
184         testCases := []struct {
185                 name   string
186                 end    func(items chan whatsmeow.QRChannelItem)
187                 answer string
188         }{
189                 {
190                         name: "the code expires",
191                         end: func(items chan whatsmeow.QRChannelItem) {
192                                 items <- whatsmeow.QRChannelTimeout
193                         },
194                         answer: whatsappPairExpired,
195                 },
196                 {
197                         name: "the library closes the pairing",
198                         end: func(items chan whatsmeow.QRChannelItem) {
199                                 close(items)
200                         },
201                         answer: whatsappPairExpired,
202                 },
203                 {
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"),
209                                 }
210                         },
211                         answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.",
212                 },
213         }
214
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")
221
222                         items := <-fake.pairings
223                         items <- whatsmeow.QRChannelItem{
224                                 Event: whatsmeow.QRChannelEventCode,
225                         }
226
227                         client.WaitFor(t, whatsappTestCode)
228                         tc.end(items)
229                         client.WaitFor(t, tc.answer)
230                         require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
231                 })
232         }
233 }
234
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)
239
240         client.Type("/whatsapp pair 15550001111")
241         <-fake.pairings
242         client.Type("/whatsapp pair 15550002222")
243         items := <-fake.pairings
244         items <- whatsmeow.QRChannelItem{
245                 Event: whatsmeow.QRChannelEventCode,
246         }
247
248         client.WaitFor(t, whatsappTestCode)
249         require.Equal(t, []string{"15550002222"}, fake.Phones())
250         require.NotContains(t, client.Output(), "did not start the pairing")
251 }
252
253 func TestWhatsAppPairWhenLinked(t *testing.T) {
254         dir := t.TempDir()
255         whatsappTestSession(t, dir, true)
256         whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
257         socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
258         client := terminalStartTestClient(t, socket)
259
260         client.Type("/whatsapp pair 15550001111")
261         client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.")
262 }
263
264 func TestWhatsAppUnlink(t *testing.T) {
265         testCases := []struct {
266                 name      string
267                 logoutErr error
268                 answer    string
269         }{
270                 {
271                         name:   "with a logout",
272                         answer: "WhatsApp is unlinked.",
273                 },
274                 {
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.",
278                 },
279         }
280
281         for _, tc := range testCases {
282                 t.Run(tc.name, func(t *testing.T) {
283                         dir := t.TempDir()
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)
289                         <-fake.connects
290
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))
297
298                         client.Type("/whatsapp unlink")
299                         client.WaitFor(t, "WhatsApp is not linked.\n")
300                 })
301         }
302 }
303
304 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
305         dir := t.TempDir()
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]")
313         <-fake.connects
314
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))
322 }
323
324 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
325         dir := t.TempDir()
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]")
333         <-fake.connects
334
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())
340
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)
347
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"))
351 }
352
353 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
354         dir := t.TempDir()
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]")
360         <-fake.connects
361
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.")
364 }
365
366 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
367         dir := t.TempDir()
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)
372         <-fake.connects
373
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())
378 }
379
380 func TestWhatsAppPhone(t *testing.T) {
381         testCases := []struct {
382                 name  string
383                 phone string
384                 valid bool
385         }{
386                 {
387                         name:  "a number with a plus and dashes",
388                         phone: "+1-555-000-1111",
389                         valid: true,
390                 },
391                 {
392                         name:  "a number with no country code",
393                         phone: "0115550001111",
394                         valid: false,
395                 },
396                 {
397                         name:  "a short number",
398                         phone: "123456",
399                         valid: false,
400                 },
401                 {
402                         name:  "a long number",
403                         phone: "1234567890123456",
404                         valid: false,
405                 },
406                 {
407                         name:  "a number with letters",
408                         phone: "1555ABC1111",
409                         valid: false,
410                 },
411         }
412
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)
417                 })
418         }
419 }
420
421 func TestWhatsAppCommandArgs(t *testing.T) {
422         testCases := []struct {
423                 name  string
424                 line  string
425                 args  string
426                 found bool
427         }{
428                 {
429                         name:  "a command with its arguments",
430                         line:  " /whatsapp  pair +1 555 ",
431                         args:  "pair +1 555",
432                         found: true,
433                 },
434                 {
435                         name:  "the command alone",
436                         line:  "/whatsapp",
437                         args:  "",
438                         found: true,
439                 },
440                 {
441                         name:  "a word that starts with the command",
442                         line:  "/whatsappstatus",
443                         args:  "",
444                         found: false,
445                 },
446                 {
447                         name:  "a message that names the command",
448                         line:  "what does /whatsapp status do?",
449                         args:  "",
450                         found: false,
451                 },
452         }
453
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)
459                 })
460         }
461 }
462
463 func TestWhatsAppFindMatchesNamesWithNoRegardToCaseAndAccents(t *testing.T) {
464         whatsapp, fake := whatsappStartTestLinked(t)
465         fake.groups = []*types.GroupInfo{
466                 {
467                         JID: whatsappTestFamily,
468                         GroupName: types.GroupName{
469                                 Name: "Família Souza",
470                         },
471                 },
472         }
473
474         whatsappTestContacts(t, whatsapp)
475         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
476         whatsappTestConnect(t, fake)
477
478         testCases := []struct {
479                 name   string
480                 query  string
481                 answer string
482         }{
483                 {
484                         name:   "no accent finds an accent",
485                         query:  "joao",
486                         answer: "15550004444@s.whatsapp.net | João Silva | contact",
487                 },
488                 {
489                         name:   "a part of a name finds contacts and groups",
490                         query:  "SOUZA",
491                         answer: "15550002222@s.whatsapp.net | Ana Souza | contact\n120363000000000001@g.us | Família Souza | group",
492                 },
493                 {
494                         name:   "a business name",
495                         query:  "bakery",
496                         answer: "15550005555@s.whatsapp.net | Corner Bakery | contact",
497                 },
498                 {
499                         name:   "no match",
500                         query:  "Zed",
501                         answer: "No contact or group has a name with \"Zed\".",
502                 },
503         }
504
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)
510                 })
511         }
512 }
513
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)))
519         }
520
521         answer, err := whatsapp.Find(t.Context(), "member")
522         require.NoError(t, err)
523
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])
529 }
530
531 func TestWhatsAppFindBeforeTheNamesArrive(t *testing.T) {
532         whatsapp, fake := whatsappStartTestLinked(t)
533         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
534         whatsappTestConnect(t, fake)
535
536         answer, err := whatsapp.Find(t.Context(), "ana")
537         require.NoError(t, err)
538         require.Equal(t, whatsappNamesNotReady, answer)
539 }
540
541 func TestWhatsAppFindWithoutALink(t *testing.T) {
542         whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
543
544         answer, err := whatsapp.Find(t.Context(), "ana")
545         require.NoError(t, err)
546         require.Equal(t, whatsappNotLinked, answer)
547 }
548
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))
556                         return
557                 }
558
559                 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Found Ana.")}, 100, 0, 5))
560         }
561
562         socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
563         client := terminalStartTestClient(t, socket)
564         whatsappTestConnect(t, fake)
565
566         client.Type("Find Ana on WhatsApp.")
567         client.WaitFor(t, "[result] 15550002222@s.whatsapp.net | Ana Souza | contact\nFound Ana.\n[done]")
568 }
569
570 func TestSubagentHasNoWhatsAppTools(t *testing.T) {
571         box := &Toolbox{}
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"}`))
574 }
575
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) {
579         t.Helper()
580
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"))
587 }
588
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)
594
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)
598
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)
602
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")
605
606         require.Equal(t, []WhatsAppFakeSend{
607                 {
608                         to:   whatsappTestAna.String(),
609                         text: "The keys are under the mat.",
610                         id:   "MSG1",
611                 },
612         }, fake.Sent())
613
614         again, err := openWhatsAppState(filepath.Join(whatsapp.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow)
615         require.NoError(t, err)
616
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)
621 }
622
623 func TestWhatsAppSendToAGroup(t *testing.T) {
624         whatsapp, fake := whatsappStartTestLinked(t)
625         fake.groups = []*types.GroupInfo{
626                 {
627                         JID: whatsappTestFamily,
628                         GroupName: types.GroupName{
629                                 Name: "Family",
630                         },
631                 },
632         }
633
634         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
635         whatsappTestConnect(t, fake)
636
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)
640 }
641
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)
647
648         for range 2 {
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)
652         }
653
654         require.Len(t, fake.Sent(), 1)
655 }
656
657 func TestWhatsAppSendCutByAStop(t *testing.T) {
658         whatsapp, fake := whatsappStartTestLinked(t)
659         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
660         whatsappTestConnect(t, fake)
661
662         digest := sha256.Sum256([]byte("hi"))
663         require.NoError(t, whatsapp.state.PutSend(WhatsAppSend{
664                 ID:     "keys",
665                 Chat:   whatsappTestAna.String(),
666                 Digest: hex.EncodeToString(digest[:]),
667                 State:  whatsappSending,
668         }))
669
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())
674 }
675
676 func TestWhatsAppSendRefuses(t *testing.T) {
677         testCases := []struct {
678                 name string
679                 id   string
680                 chat string
681                 text string
682                 err  string
683         }{
684                 {
685                         name: "no id",
686                         id:   " ",
687                         chat: whatsappTestAna.String(),
688                         text: "hi",
689                         err:  "the id must have 1 to 100 bytes",
690                 },
691                 {
692                         name: "no text",
693                         id:   "a",
694                         chat: whatsappTestAna.String(),
695                         text: "",
696                         err:  "the text must have 1 to 65536 bytes",
697                 },
698                 {
699                         name: "a name for a chat",
700                         id:   "a",
701                         chat: "Ana Souza",
702                         text: "hi",
703                         err:  `"Ana Souza" is not the ID of a WhatsApp chat: find the ID with whatsapp_find`,
704                 },
705                 {
706                         name: "a status broadcast",
707                         id:   "a",
708                         chat: types.StatusBroadcastJID.String(),
709                         text: "hi",
710                         err:  `"status@broadcast" is not a private chat or a group`,
711                 },
712                 {
713                         name: "the chat of the user",
714                         id:   "a",
715                         chat: whatsappTestOwn.String(),
716                         text: "hi",
717                         err:  "this is the chat of the user with itself: send to another chat",
718                 },
719         }
720
721         whatsapp, fake := whatsappStartTestLinked(t)
722         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
723         whatsappTestConnect(t, fake)
724
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)
729                 })
730         }
731
732         require.Empty(t, fake.Sent())
733 }
734
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{}))
740
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")
743
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)
748 }
749
750 func TestWhatsAppSendWithoutALink(t *testing.T) {
751         whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
752
753         answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi")
754         require.NoError(t, err)
755         require.Equal(t, whatsappNotLinked, answer)
756 }
757
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))
765                         return
766                 }
767
768                 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Sent.")}, 100, 0, 5))
769         }
770
771         socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
772         client := terminalStartTestClient(t, socket)
773         whatsappTestConnect(t, fake)
774
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)
778 }