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