]> git.giacomolli.uk - onechat/blob - whatsapp_test.go
Rebuild agent memory in date order
[onechat] / whatsapp_test.go
1 package main
2
3 import (
4         "context"
5         "errors"
6         "os"
7         "path/filepath"
8         "strings"
9         "testing"
10         "testing/synctest"
11         "time"
12
13         "github.com/stretchr/testify/require"
14         "go.mau.fi/whatsmeow"
15         "go.mau.fi/whatsmeow/types"
16         "go.mau.fi/whatsmeow/types/events"
17 )
18
19 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
20         dir := t.TempDir()
21         whatsappTestSession(t, dir, true)
22         clock := newTestClock()
23         whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
24         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
25
26         <-fake.connects
27         require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
28
29         require.True(t, fake.Emit(&events.Connected{}))
30         require.Equal(t, "WhatsApp is linked and connected since 2026-01-01 12:00.", whatsapp.Status())
31
32         clock.now = clock.now.Add(20 * time.Minute)
33         require.True(t, fake.Emit(&events.Disconnected{}))
34         clock.now = clock.now.Add(time.Minute)
35         require.True(t, fake.Emit(&events.Disconnected{}))
36         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())
37 }
38
39 func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
40         synctest.Test(t, func(t *testing.T) {
41                 test := whatsappRetryTest(t)
42                 test.fake.connectErr = errors.New("network unavailable")
43                 test.start(t)
44                 synctest.Wait()
45
46                 require.Equal(t, "WhatsApp is linked and disconnected since "+time.Now().Format(whatsappTimeLayout)+".", test.whatsapp.Status())
47                 require.Equal(t, "first connect failed, retrying: network unavailable\n", test.logs.String())
48         })
49 }
50
51 func TestWhatsAppRetriesTheFirstConnectionWithCappedBackoff(t *testing.T) {
52         synctest.Test(t, func(t *testing.T) {
53                 test := whatsappRetryTest(t)
54                 for range 10 {
55                         test.fake.connectErrors = append(test.fake.connectErrors, errors.New("network unavailable"))
56                 }
57
58                 test.start(t)
59                 synctest.Wait()
60                 require.Len(t, test.fake.Connections(), 1)
61                 require.True(t, test.fake.Emit(&events.Disconnected{}))
62                 require.True(t, test.fake.Emit(&events.Disconnected{}))
63
64                 delays := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 32 * time.Second, 64 * time.Second, 128 * time.Second, 256 * time.Second, 5 * time.Minute, 5 * time.Minute}
65                 var outage time.Duration
66                 for index, delay := range delays {
67                         time.Sleep(delay - time.Nanosecond)
68                         synctest.Wait()
69                         require.Len(t, test.fake.Connections(), index+1)
70                         time.Sleep(time.Nanosecond)
71                         synctest.Wait()
72                         require.Len(t, test.fake.Connections(), index+2)
73                         outage += delay
74                 }
75
76                 times := test.fake.ConnectionTimes()
77                 for index, delay := range delays {
78                         require.Equal(t, delay, times[index+1].Sub(times[index]))
79                 }
80
81                 require.True(t, test.fake.Emit(&events.Connected{}))
82                 require.True(t, test.fake.Emit(&events.OfflineSyncCompleted{}))
83                 synctest.Wait()
84                 time.Sleep(10 * time.Minute)
85                 synctest.Wait()
86                 require.Len(t, test.fake.Connections(), 11)
87                 require.Equal(t, "first connect failed, retrying: network unavailable\nconnected again after "+durationText(outage)+"\n", test.logs.String())
88         })
89 }
90
91 func TestWhatsAppFirstConnectionRetriesStopWhenContextEnds(t *testing.T) {
92         synctest.Test(t, func(t *testing.T) {
93                 test := whatsappRetryTest(t)
94                 test.fake.connectErr = errors.New("network unavailable")
95                 test.start(t)
96                 synctest.Wait()
97                 time.Sleep(2 * time.Second)
98                 synctest.Wait()
99                 require.Len(t, test.fake.Connections(), 2)
100
101                 test.cancel()
102                 require.NoError(t, <-test.done)
103                 time.Sleep(10 * time.Minute)
104                 synctest.Wait()
105                 require.Len(t, test.fake.Connections(), 2)
106         })
107 }
108
109 func TestWhatsAppLinkedPairRequestKeepsFirstConnectionRetries(t *testing.T) {
110         synctest.Test(t, func(t *testing.T) {
111                 test := whatsappRetryTest(t)
112                 test.fake.connectErr = errors.New("network unavailable")
113                 test.start(t)
114                 synctest.Wait()
115
116                 answers := make(chan string, 1)
117                 test.whatsapp.Command("pair 15550001111", func(text string) {
118                         answers <- text
119                 })
120                 require.Equal(t, "WhatsApp is linked already. Run /whatsapp unlink first.", <-answers)
121                 synctest.Wait()
122                 test.fake.mutex.Lock()
123                 test.fake.connectErr = nil
124                 test.fake.mutex.Unlock()
125                 time.Sleep(whatsappRetryDelay)
126                 synctest.Wait()
127                 require.Len(t, test.fake.Connections(), 2)
128                 require.True(t, test.fake.Emit(&events.Connected{}))
129                 require.True(t, test.fake.Emit(&events.OfflineSyncCompleted{}))
130                 require.Contains(t, test.whatsapp.Status(), "linked and connected since")
131                 time.Sleep(whatsappRetryLimit)
132                 synctest.Wait()
133                 require.Len(t, test.fake.Connections(), 2)
134                 require.Equal(t, "first connect failed, retrying: network unavailable\nconnected again after 2s\n", test.logs.String())
135         })
136 }
137
138 func TestWhatsAppFirstConnectionRetriesStopForLinkChanges(t *testing.T) {
139         testCases := []struct {
140                 name string
141                 stop func(test *WhatsAppRetryTest)
142         }{
143                 {
144                         name: "unlink",
145                         stop: func(test *WhatsAppRetryTest) {
146                                 test.whatsapp.Command("unlink", func(text string) {})
147                         },
148                 },
149                 {
150                         name: "logout",
151                         stop: func(test *WhatsAppRetryTest) {
152                                 test.fake.Emit(&events.LoggedOut{})
153                         },
154                 },
155                 {
156                         name: "permanent disconnect",
157                         stop: func(test *WhatsAppRetryTest) {
158                                 test.fake.Emit(&events.StreamReplaced{})
159                         },
160                 },
161         }
162
163         for _, tc := range testCases {
164                 t.Run(tc.name, func(t *testing.T) {
165                         synctest.Test(t, func(t *testing.T) {
166                                 test := whatsappRetryTest(t)
167                                 test.fake.connectErr = errors.New("network unavailable")
168                                 test.start(t)
169                                 synctest.Wait()
170                                 tc.stop(test)
171                                 synctest.Wait()
172                                 time.Sleep(10 * time.Minute)
173                                 synctest.Wait()
174                                 require.Len(t, test.fake.Connections(), 1)
175                         })
176                 })
177         }
178 }
179
180 func TestWhatsAppPairsAfterFirstConnectionRetriesStop(t *testing.T) {
181         synctest.Test(t, func(t *testing.T) {
182                 test := whatsappRetryTest(t)
183                 test.fake.connectErr = errors.New("network unavailable")
184                 test.start(t)
185                 synctest.Wait()
186                 test.whatsapp.Command("unlink", func(text string) {})
187                 synctest.Wait()
188                 require.False(t, test.whatsapp.isLinked())
189
190                 test.fake.mutex.Lock()
191                 test.fake.connectErr = nil
192                 test.fake.mutex.Unlock()
193                 test.whatsapp.Command("pair 15550001111", func(text string) {})
194                 items := <-test.fake.pairings
195                 items <- whatsmeow.QRChannelItem{Event: whatsmeow.QRChannelEventCode}
196                 synctest.Wait()
197                 require.True(t, test.fake.Emit(&events.PairSuccess{
198                         ID:  types.NewADJID(whatsappTestNumber, 0, 1),
199                         LID: types.NewADJID(whatsappTestLID, 0, 1),
200                 }))
201                 items <- whatsmeow.QRChannelSuccess
202                 synctest.Wait()
203                 require.True(t, test.whatsapp.isLinked())
204                 time.Sleep(10 * time.Minute)
205                 synctest.Wait()
206                 require.Len(t, test.fake.Connections(), 2)
207                 require.Equal(t, []string{whatsappTestNumber}, test.fake.Phones())
208         })
209 }
210
211 func TestWhatsAppInboxFailureStopsFirstConnectionRetries(t *testing.T) {
212         synctest.Test(t, func(t *testing.T) {
213                 test := whatsappRetryTest(t)
214                 test.fake.connectErr = errors.New("network unavailable")
215                 test.start(t)
216                 synctest.Wait()
217                 failure := errors.New("state write failed")
218                 test.whatsapp.inbox.failures <- failure
219                 require.ErrorIs(t, <-test.done, failure)
220                 time.Sleep(10 * time.Minute)
221                 synctest.Wait()
222                 require.Len(t, test.fake.Connections(), 1)
223         })
224 }
225
226 func TestWhatsAppLongFirstConnectionOutageGivesOneNotice(t *testing.T) {
227         synctest.Test(t, func(t *testing.T) {
228                 test := whatsappRetryTest(t)
229                 test.fake.connectErr = errors.New("network unavailable")
230                 test.start(t)
231                 synctest.Wait()
232                 since := time.Now().Format(whatsappTimeLayout)
233                 time.Sleep(whatsappNoticeDelay)
234                 synctest.Wait()
235                 require.Equal(t, 1, test.events.Count("notice"))
236                 require.Equal(t, "WhatsApp is disconnected since "+since+". OneChat tries again.", test.events.Last("notice"))
237
238                 time.Sleep(whatsappNoticeDelay)
239                 synctest.Wait()
240                 require.Equal(t, 1, test.events.Count("notice"))
241                 test.fake.mutex.Lock()
242                 test.fake.connectErr = nil
243                 test.fake.mutex.Unlock()
244                 time.Sleep(whatsappRetryLimit)
245                 synctest.Wait()
246                 require.True(t, test.fake.Emit(&events.Connected{}))
247                 require.True(t, test.fake.Emit(&events.OfflineSyncCompleted{}))
248                 synctest.Wait()
249                 require.Equal(t, 2, test.events.Count("notice"))
250                 require.Equal(t, "WhatsApp is connected again.", test.events.Last("notice"))
251         })
252 }
253
254 func TestWhatsAppStartingRetriesDoNotDuplicateLibraryRetries(t *testing.T) {
255         dir := t.TempDir()
256         whatsappTestSession(t, dir, true)
257         whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
258         client, ok := whatsappNewClient(whatsapp.device, whatsapp.handle).(*whatsmeow.Client)
259         require.True(t, ok)
260         require.False(t, client.InitialAutoReconnect)
261         require.True(t, client.EnableAutoReconnect)
262
263         device := whatsapp.container.NewDevice()
264         client, ok = whatsappNewClient(device, whatsapp.handle).(*whatsmeow.Client)
265         require.True(t, ok)
266         require.True(t, client.InitialAutoReconnect)
267 }
268
269 func TestWhatsAppLogsEachChangeOfTheConnectionOnce(t *testing.T) {
270         dir := t.TempDir()
271         whatsappTestSession(t, dir, true)
272         clock := newTestClock()
273         whatsapp, fake, logs := whatsappStartTest(t, dir, clock)
274         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
275
276         <-fake.connects
277         require.True(t, fake.Emit(&events.Connected{}))
278         clock.now = clock.now.Add(time.Minute)
279         require.True(t, fake.Emit(&events.Disconnected{}))
280         clock.now = clock.now.Add(time.Minute)
281         require.True(t, fake.Emit(&events.Disconnected{}))
282         clock.now = clock.now.Add(25 * time.Second)
283         require.True(t, fake.Emit(&events.Connected{}))
284
285         require.Equal(t, []string{
286                 "connected",
287                 "disconnected, retrying",
288                 "connected again after 1m25s",
289         }, strings.Split(strings.TrimSuffix(logs.String(), "\n"), "\n"))
290         require.NotContains(t, logs.String(), whatsappTestNumber)
291         require.NotContains(t, logs.String(), whatsappTestLID)
292 }
293
294 func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
295         testCases := []struct {
296                 name    string
297                 session func(t *testing.T, dir string)
298         }{
299                 {
300                         name: "no session file",
301                         session: func(t *testing.T, dir string) {
302                         },
303                 },
304                 {
305                         name: "a session of a pairing that did not end",
306                         session: func(t *testing.T, dir string) {
307                                 whatsappTestSession(t, dir, false)
308                         },
309                 },
310         }
311
312         for _, tc := range testCases {
313                 t.Run(tc.name, func(t *testing.T) {
314                         dir := t.TempDir()
315                         tc.session(t, dir)
316                         whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
317                         require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
318                 })
319         }
320 }
321
322 func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
323         dir := t.TempDir()
324         whatsappTestSession(t, dir, true)
325         require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
326
327         _, err := openWhatsApp(t.Context(), dir, time.Now, whatsappDiscardLog(), whatsappNewClient)
328         require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600")
329 }
330
331 func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) {
332         server := newModelFake(t)
333         telegram := newTelegramFake(t)
334         bot, _ := telegramStartTestBot(t, telegram)
335         socket := daemonStartTestWithBot(t, server, bot)
336         asking := terminalStartTestClient(t, socket)
337         other := terminalStartTestClient(t, socket)
338         asking.WaitFor(t, "[connected to OneChat]")
339         other.WaitFor(t, "[connected to OneChat]")
340
341         asking.Type("/whatsapp status")
342         asking.WaitFor(t, "WhatsApp is not linked.")
343         asking.Type(" /whatsapp  unknown ")
344         asking.WaitFor(t, whatsappUsage)
345         asking.Type("/whatsapp pair 0123")
346         asking.WaitFor(t, "PHONE must be the number of your WhatsApp account")
347
348         telegram.Add(TelegramUpdate{
349                 UpdateID: 1,
350                 Message:  telegramOwnerMessage("/whatsapp status"),
351         })
352
353         telegramWaitForSent(t, telegram, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.")
354         require.Len(t, telegram.Sent(), 1)
355         require.Equal(t, "[connected to OneChat]\n", other.Output())
356         require.Zero(t, server.Calls())
357 }
358
359 func TestWhatsAppPairsWithACode(t *testing.T) {
360         dir := t.TempDir()
361         whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
362         server := newModelFake(t)
363         socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
364         asking := terminalStartTestClient(t, socket)
365         other := terminalStartTestClient(t, socket)
366         asking.WaitFor(t, "[connected to OneChat]")
367         other.WaitFor(t, "[connected to OneChat]")
368
369         asking.Type("/whatsapp pair +1 555-000-1111")
370         items := <-fake.pairings
371         items <- whatsmeow.QRChannelItem{
372                 Event: whatsmeow.QRChannelEventCode,
373         }
374
375         asking.WaitFor(t, whatsappPairSteps+"\n"+whatsappTestCode+"\n")
376         require.True(t, fake.Emit(&events.PairSuccess{
377                 ID:  types.NewADJID(whatsappTestNumber, 0, 1),
378                 LID: types.NewADJID(whatsappTestLID, 0, 1),
379         }))
380         items <- whatsmeow.QRChannelSuccess
381         asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
382
383         // The library connects again after the link with the context of the
384         // connection, so the end of the pairing must not end it.
385         connections := fake.Connections()
386         require.Len(t, connections, 1)
387         require.Never(t, func() bool {
388                 return connections[0].Err() != nil
389         }, 200*time.Millisecond, time.Millisecond)
390
391         require.Equal(t, []string{whatsappTestNumber}, fake.Phones())
392         require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status())
393         require.Equal(t, "[connected to OneChat]\n", other.Output())
394         require.Zero(t, server.Calls())
395         require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory))
396
397         info, err := os.Stat(filepath.Join(dir, whatsappDirName))
398         require.NoError(t, err)
399         require.Equal(t, os.FileMode(0o700), info.Mode().Perm())
400
401         info, err = os.Stat(filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
402         require.NoError(t, err)
403         require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
404 }
405
406 func TestWhatsAppPairingCodeIsATelegramMessageAlone(t *testing.T) {
407         whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
408         telegram := newTelegramFake(t)
409         bot, _ := telegramStartTestBot(t, telegram)
410         daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
411
412         telegram.Add(TelegramUpdate{
413                 UpdateID: 1,
414                 Message:  telegramOwnerMessage("/whatsapp pair 15550001111"),
415         })
416
417         items := <-fake.pairings
418         items <- whatsmeow.QRChannelItem{
419                 Event: whatsmeow.QRChannelEventCode,
420         }
421
422         telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode)
423 }
424
425 func TestWhatsAppPairingEnds(t *testing.T) {
426         testCases := []struct {
427                 name   string
428                 end    func(items chan whatsmeow.QRChannelItem)
429                 answer string
430         }{
431                 {
432                         name: "the code expires",
433                         end: func(items chan whatsmeow.QRChannelItem) {
434                                 items <- whatsmeow.QRChannelTimeout
435                         },
436                         answer: whatsappPairExpired,
437                 },
438                 {
439                         name: "the library closes the pairing",
440                         end: func(items chan whatsmeow.QRChannelItem) {
441                                 close(items)
442                         },
443                         answer: whatsappPairExpired,
444                 },
445                 {
446                         name: "the pairing fails",
447                         end: func(items chan whatsmeow.QRChannelItem) {
448                                 items <- whatsmeow.QRChannelItem{
449                                         Event: whatsmeow.QRChannelEventError,
450                                         Error: errors.New("bad handshake"),
451                                 }
452                         },
453                         answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.",
454                 },
455         }
456
457         for _, tc := range testCases {
458                 t.Run(tc.name, func(t *testing.T) {
459                         whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
460                         socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
461                         client := terminalStartTestClient(t, socket)
462                         client.Type("/whatsapp pair 15550001111")
463
464                         items := <-fake.pairings
465                         items <- whatsmeow.QRChannelItem{
466                                 Event: whatsmeow.QRChannelEventCode,
467                         }
468
469                         client.WaitFor(t, whatsappTestCode)
470                         tc.end(items)
471                         client.WaitFor(t, tc.answer)
472                         require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
473                 })
474         }
475 }
476
477 func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) {
478         whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
479         socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
480         client := terminalStartTestClient(t, socket)
481
482         client.Type("/whatsapp pair 15550001111")
483         <-fake.pairings
484         client.Type("/whatsapp pair 15550002222")
485         items := <-fake.pairings
486         items <- whatsmeow.QRChannelItem{
487                 Event: whatsmeow.QRChannelEventCode,
488         }
489
490         client.WaitFor(t, whatsappTestCode)
491         require.Equal(t, []string{"15550002222"}, fake.Phones())
492         require.NotContains(t, client.Output(), "did not start the pairing")
493 }
494
495 func TestWhatsAppPairWhenLinked(t *testing.T) {
496         dir := t.TempDir()
497         whatsappTestSession(t, dir, true)
498         whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
499         socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
500         client := terminalStartTestClient(t, socket)
501
502         client.Type("/whatsapp pair 15550001111")
503         client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.")
504 }
505
506 func TestWhatsAppUnlink(t *testing.T) {
507         testCases := []struct {
508                 name      string
509                 logoutErr error
510                 answer    string
511         }{
512                 {
513                         name:   "with a logout",
514                         answer: "WhatsApp is unlinked.",
515                 },
516                 {
517                         name:      "with no logout",
518                         logoutErr: errors.New("not connected"),
519                         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.",
520                 },
521         }
522
523         for _, tc := range testCases {
524                 t.Run(tc.name, func(t *testing.T) {
525                         dir := t.TempDir()
526                         whatsappTestSession(t, dir, true)
527                         whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
528                         fake.logoutErr = tc.logoutErr
529                         socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
530                         client := terminalStartTestClient(t, socket)
531                         <-fake.connects
532
533                         client.Type("/whatsapp unlink")
534                         client.WaitFor(t, tc.answer)
535                         require.Equal(t, 1, fake.Logouts())
536                         require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
537                         require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
538                         require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory))
539
540                         client.Type("/whatsapp unlink")
541                         client.WaitFor(t, "WhatsApp is not linked.\n")
542                 })
543         }
544 }
545
546 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
547         dir := t.TempDir()
548         whatsappTestSession(t, dir, true)
549         whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
550         telegram := newTelegramFake(t)
551         bot, _ := telegramStartTestBot(t, telegram)
552         socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
553         client := terminalStartTestClient(t, socket)
554         client.WaitFor(t, "[connected to OneChat]")
555         <-fake.connects
556
557         require.True(t, fake.Emit(&events.LoggedOut{}))
558         notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again."
559         client.WaitFor(t, notice)
560         telegramWaitForSent(t, telegram, notice)
561         require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
562         require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
563         require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory))
564 }
565
566 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
567         dir := t.TempDir()
568         whatsappTestSession(t, dir, true)
569         clock := newTestClock()
570         whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
571         whatsapp.noticeDelay = 300 * time.Millisecond
572         socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
573         client := terminalStartTestClient(t, socket)
574         client.WaitFor(t, "[connected to OneChat]")
575         <-fake.connects
576
577         require.True(t, fake.Emit(&events.Connected{}))
578         require.True(t, fake.Emit(&events.Disconnected{}))
579         require.True(t, fake.Emit(&events.Connected{}))
580         time.Sleep(400 * time.Millisecond)
581         require.Equal(t, "[connected to OneChat]\n", client.Output())
582
583         clock.now = clock.now.Add(time.Hour)
584         require.True(t, fake.Emit(&events.Disconnected{}))
585         require.True(t, fake.Emit(&events.Disconnected{}))
586         client.WaitFor(t, "WhatsApp is disconnected since 2026-01-01 13:00. OneChat tries again.\n")
587         require.True(t, fake.Emit(&events.Disconnected{}))
588         time.Sleep(400 * time.Millisecond)
589
590         require.True(t, fake.Emit(&events.Connected{}))
591         client.WaitFor(t, "WhatsApp is connected again.\n")
592         require.Equal(t, 1, strings.Count(client.Output(), "WhatsApp is disconnected since"))
593 }
594
595 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
596         dir := t.TempDir()
597         whatsappTestSession(t, dir, true)
598         whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
599         socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
600         client := terminalStartTestClient(t, socket)
601         client.WaitFor(t, "[connected to OneChat]")
602         <-fake.connects
603
604         require.True(t, fake.Emit(&events.StreamReplaced{}))
605         client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.")
606 }
607
608 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
609         dir := t.TempDir()
610         whatsappTestSession(t, dir, true)
611         whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
612         fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid")
613         daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
614         <-fake.connects
615
616         require.Eventually(t, func() bool {
617                 return logs.String() != ""
618         }, 10*time.Second, time.Millisecond)
619         require.Equal(t, "first connect failed, retrying: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String())
620 }
621
622 func TestWhatsAppPhone(t *testing.T) {
623         testCases := []struct {
624                 name  string
625                 phone string
626                 valid bool
627         }{
628                 {
629                         name:  "a number with a plus and dashes",
630                         phone: "+1-555-000-1111",
631                         valid: true,
632                 },
633                 {
634                         name:  "a number with no country code",
635                         phone: "0115550001111",
636                         valid: false,
637                 },
638                 {
639                         name:  "a short number",
640                         phone: "123456",
641                         valid: false,
642                 },
643                 {
644                         name:  "a long number",
645                         phone: "1234567890123456",
646                         valid: false,
647                 },
648                 {
649                         name:  "a number with letters",
650                         phone: "1555ABC1111",
651                         valid: false,
652                 },
653         }
654
655         for _, tc := range testCases {
656                 t.Run(tc.name, func(t *testing.T) {
657                         _, valid := whatsappPhone(tc.phone)
658                         require.Equal(t, tc.valid, valid)
659                 })
660         }
661 }
662
663 func TestWhatsAppCommandArgs(t *testing.T) {
664         testCases := []struct {
665                 name  string
666                 line  string
667                 args  string
668                 found bool
669         }{
670                 {
671                         name:  "a command with its arguments",
672                         line:  " /whatsapp  pair +1 555 ",
673                         args:  "pair +1 555",
674                         found: true,
675                 },
676                 {
677                         name:  "the command alone",
678                         line:  "/whatsapp",
679                         args:  "",
680                         found: true,
681                 },
682                 {
683                         name:  "a word that starts with the command",
684                         line:  "/whatsappstatus",
685                         args:  "",
686                         found: false,
687                 },
688                 {
689                         name:  "a message that names the command",
690                         line:  "what does /whatsapp status do?",
691                         args:  "",
692                         found: false,
693                 },
694         }
695
696         for _, tc := range testCases {
697                 t.Run(tc.name, func(t *testing.T) {
698                         args, found := whatsappCommandArgs(tc.line)
699                         require.Equal(t, tc.args, args)
700                         require.Equal(t, tc.found, found)
701                 })
702         }
703 }
704
705 func TestSubagentHasNoWhatsAppTools(t *testing.T) {
706         box := &Toolbox{}
707         require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`))
708         require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`))
709 }
710
711 // WhatsAppRetryTest runs WhatsApp without a model or network client call. All
712 // timers and channels belong to its synctest bubble, so backoff uses fake time.
713 type WhatsAppRetryTest struct {
714         whatsapp *WhatsApp
715         fake     *WhatsAppFake
716         logs     *SyncBuffer
717         loop     *TurnLoop
718         events   *TurnEventRecorder
719         cancel   context.CancelFunc
720         done     chan error
721 }
722
723 func (r *WhatsAppRetryTest) start(t *testing.T) {
724         t.Helper()
725
726         ctx, cancel := context.WithCancel(t.Context())
727         r.cancel = cancel
728         r.done = make(chan error, 1)
729         go func() {
730                 r.done <- r.whatsapp.Run(ctx, r.loop, r.events.Add)
731         }()
732
733         t.Cleanup(func() {
734                 cancel()
735                 synctest.Wait()
736         })
737 }
738
739 func whatsappRetryTest(t *testing.T) *WhatsAppRetryTest {
740         t.Helper()
741
742         dir := t.TempDir()
743         whatsappTestSession(t, dir, true)
744         whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
745         whatsapp.clock = time.Now
746         agent, err := openAgent(t.TempDir())
747         require.NoError(t, err)
748         memory, err := openMemory(t.Context(), agent.dir, time.Now, newFakeSummarizer(), discardLog())
749         require.NoError(t, err)
750         t.Cleanup(func() {
751                 require.NoError(t, memory.Close())
752         })
753
754         events := &TurnEventRecorder{}
755         client := newModelClient("https://example.com", ModelAPIKey(modelTestKey), agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
756         loop, err := newTurnLoop(agent, memory, newTestSubagents(t), whatsapp, newTestSchedules(t, time.Now), client, time.Now, discardLog(), events.Add)
757         require.NoError(t, err)
758
759         return &WhatsAppRetryTest{
760                 whatsapp: whatsapp,
761                 fake:     fake,
762                 logs:     logs,
763                 loop:     loop,
764                 events:   events,
765         }
766 }