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