]> git.giacomolli.uk - onechat/blobdiff - whatsapp_test.go
Name timeouts for the operations they limit
[onechat] / whatsapp_test.go
index db04dc7424737406782dbb439f365b3db0279e39..c1471e98e8f3c3aa2ad97daa69cd13795be3bd59 100644 (file)
@@ -1,7 +1,6 @@
 package main
 
 import (
 package main
 
 import (
-       "context"
        "errors"
        "os"
        "path/filepath"
        "errors"
        "os"
        "path/filepath"
@@ -19,6 +18,7 @@ import (
 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
 func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
+
        clock := newTestClock()
        whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
        daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
        clock := newTestClock()
        whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
        daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
@@ -30,8 +30,11 @@ func TestWhatsAppStatusFollowsTheConnection(t *testing.T) {
        require.Equal(t, "WhatsApp is linked and connected since 2026-01-01 12:00.", whatsapp.Status())
 
        clock.now = clock.now.Add(20 * time.Minute)
        require.Equal(t, "WhatsApp is linked and connected since 2026-01-01 12:00.", whatsapp.Status())
 
        clock.now = clock.now.Add(20 * time.Minute)
+
        require.True(t, fake.Emit(&events.Disconnected{}))
        require.True(t, fake.Emit(&events.Disconnected{}))
+
        clock.now = clock.now.Add(time.Minute)
        clock.now = clock.now.Add(time.Minute)
+
        require.True(t, fake.Emit(&events.Disconnected{}))
        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())
 }
        require.True(t, fake.Emit(&events.Disconnected{}))
        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())
 }
@@ -44,7 +47,7 @@ func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) {
                synctest.Wait()
 
                require.Equal(t, "WhatsApp is linked and disconnected since "+time.Now().Format(whatsappTimeLayout)+".", test.whatsapp.Status())
                synctest.Wait()
 
                require.Equal(t, "WhatsApp is linked and disconnected since "+time.Now().Format(whatsappTimeLayout)+".", test.whatsapp.Status())
-               require.Equal(t, "first connect failed, retrying: network unavailable\n", test.logs.String())
+               require.Equal(t, "<4>first connect failed, retrying: network unavailable\n", test.logs.String())
        })
 }
 
        })
 }
 
@@ -62,7 +65,9 @@ func TestWhatsAppRetriesTheFirstConnectionWithCappedBackoff(t *testing.T) {
                require.True(t, test.fake.Emit(&events.Disconnected{}))
 
                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}
                require.True(t, test.fake.Emit(&events.Disconnected{}))
 
                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}
+
                var outage time.Duration
                var outage time.Duration
+
                for index, delay := range delays {
                        time.Sleep(delay - time.Nanosecond)
                        synctest.Wait()
                for index, delay := range delays {
                        time.Sleep(delay - time.Nanosecond)
                        synctest.Wait()
@@ -70,6 +75,7 @@ func TestWhatsAppRetriesTheFirstConnectionWithCappedBackoff(t *testing.T) {
                        time.Sleep(time.Nanosecond)
                        synctest.Wait()
                        require.Len(t, test.fake.Connections(), index+2)
                        time.Sleep(time.Nanosecond)
                        synctest.Wait()
                        require.Len(t, test.fake.Connections(), index+2)
+
                        outage += delay
                }
 
                        outage += delay
                }
 
@@ -84,7 +90,7 @@ func TestWhatsAppRetriesTheFirstConnectionWithCappedBackoff(t *testing.T) {
                time.Sleep(10 * time.Minute)
                synctest.Wait()
                require.Len(t, test.fake.Connections(), 11)
                time.Sleep(10 * time.Minute)
                synctest.Wait()
                require.Len(t, test.fake.Connections(), 11)
-               require.Equal(t, "first connect failed, retrying: network unavailable\nconnected again after "+durationText(outage)+"\n", test.logs.String())
+               require.Equal(t, "<4>first connect failed, retrying: network unavailable\n<6>connected again after="+durationText(outage)+"\n", test.logs.String())
        })
 }
 
        })
 }
 
@@ -120,6 +126,7 @@ func TestWhatsAppLinkedPairRequestKeepsFirstConnectionRetries(t *testing.T) {
                require.Equal(t, "WhatsApp is linked already. Run /whatsapp unlink first.", <-answers)
                synctest.Wait()
                test.fake.mutex.Lock()
                require.Equal(t, "WhatsApp is linked already. Run /whatsapp unlink first.", <-answers)
                synctest.Wait()
                test.fake.mutex.Lock()
+
                test.fake.connectErr = nil
                test.fake.mutex.Unlock()
                time.Sleep(whatsappRetryDelay)
                test.fake.connectErr = nil
                test.fake.mutex.Unlock()
                time.Sleep(whatsappRetryDelay)
@@ -131,7 +138,7 @@ func TestWhatsAppLinkedPairRequestKeepsFirstConnectionRetries(t *testing.T) {
                time.Sleep(whatsappRetryLimit)
                synctest.Wait()
                require.Len(t, test.fake.Connections(), 2)
                time.Sleep(whatsappRetryLimit)
                synctest.Wait()
                require.Len(t, test.fake.Connections(), 2)
-               require.Equal(t, "first connect failed, retrying: network unavailable\nconnected again after 2s\n", test.logs.String())
+               require.Equal(t, "<4>first connect failed, retrying: network unavailable\n<6>connected again after=2s\n", test.logs.String())
        })
 }
 
        })
 }
 
@@ -143,7 +150,8 @@ func TestWhatsAppFirstConnectionRetriesStopForLinkChanges(t *testing.T) {
                {
                        name: "unlink",
                        stop: func(test *WhatsAppRetryTest) {
                {
                        name: "unlink",
                        stop: func(test *WhatsAppRetryTest) {
-                               test.whatsapp.Command("unlink", func(text string) {})
+                               test.whatsapp.Command("unlink", func(_ string) {
+                               })
                        },
                },
                {
                        },
                },
                {
@@ -183,22 +191,29 @@ func TestWhatsAppPairsAfterFirstConnectionRetriesStop(t *testing.T) {
                test.fake.connectErr = errors.New("network unavailable")
                test.start(t)
                synctest.Wait()
                test.fake.connectErr = errors.New("network unavailable")
                test.start(t)
                synctest.Wait()
-               test.whatsapp.Command("unlink", func(text string) {})
+               test.whatsapp.Command("unlink", func(_ string) {
+               })
                synctest.Wait()
                require.False(t, test.whatsapp.isLinked())
 
                test.fake.mutex.Lock()
                synctest.Wait()
                require.False(t, test.whatsapp.isLinked())
 
                test.fake.mutex.Lock()
+
                test.fake.connectErr = nil
                test.fake.mutex.Unlock()
                test.fake.connectErr = nil
                test.fake.mutex.Unlock()
-               test.whatsapp.Command("pair 15550001111", func(text string) {})
+               test.whatsapp.Command("pair 15550001111", func(_ string) {
+               })
+
                items := <-test.fake.pairings
                items <- whatsmeow.QRChannelItem{Event: whatsmeow.QRChannelEventCode}
                items := <-test.fake.pairings
                items <- whatsmeow.QRChannelItem{Event: whatsmeow.QRChannelEventCode}
+
                synctest.Wait()
                require.True(t, test.fake.Emit(&events.PairSuccess{
                        ID:  types.NewADJID(whatsappTestNumber, 0, 1),
                        LID: types.NewADJID(whatsappTestLID, 0, 1),
                }))
                synctest.Wait()
                require.True(t, test.fake.Emit(&events.PairSuccess{
                        ID:  types.NewADJID(whatsappTestNumber, 0, 1),
                        LID: types.NewADJID(whatsappTestLID, 0, 1),
                }))
+
                items <- whatsmeow.QRChannelSuccess
                items <- whatsmeow.QRChannelSuccess
+
                synctest.Wait()
                require.True(t, test.whatsapp.isLinked())
                time.Sleep(10 * time.Minute)
                synctest.Wait()
                require.True(t, test.whatsapp.isLinked())
                time.Sleep(10 * time.Minute)
@@ -214,8 +229,10 @@ func TestWhatsAppInboxFailureStopsFirstConnectionRetries(t *testing.T) {
                test.fake.connectErr = errors.New("network unavailable")
                test.start(t)
                synctest.Wait()
                test.fake.connectErr = errors.New("network unavailable")
                test.start(t)
                synctest.Wait()
+
                failure := errors.New("state write failed")
                test.whatsapp.inbox.failures <- failure
                failure := errors.New("state write failed")
                test.whatsapp.inbox.failures <- failure
+
                require.ErrorIs(t, <-test.done, failure)
                time.Sleep(10 * time.Minute)
                synctest.Wait()
                require.ErrorIs(t, <-test.done, failure)
                time.Sleep(10 * time.Minute)
                synctest.Wait()
@@ -229,16 +246,19 @@ func TestWhatsAppLongFirstConnectionOutageGivesOneNotice(t *testing.T) {
                test.fake.connectErr = errors.New("network unavailable")
                test.start(t)
                synctest.Wait()
                test.fake.connectErr = errors.New("network unavailable")
                test.start(t)
                synctest.Wait()
+
                since := time.Now().Format(whatsappTimeLayout)
                since := time.Now().Format(whatsappTimeLayout)
-               time.Sleep(whatsappNoticeDelay)
+
+               time.Sleep(whatsappOutageNoticeDelay)
                synctest.Wait()
                require.Equal(t, 1, test.events.Count("notice"))
                require.Equal(t, "WhatsApp is disconnected since "+since+". OneChat tries again.", test.events.Last("notice"))
 
                synctest.Wait()
                require.Equal(t, 1, test.events.Count("notice"))
                require.Equal(t, "WhatsApp is disconnected since "+since+". OneChat tries again.", test.events.Last("notice"))
 
-               time.Sleep(whatsappNoticeDelay)
+               time.Sleep(whatsappOutageNoticeDelay)
                synctest.Wait()
                require.Equal(t, 1, test.events.Count("notice"))
                test.fake.mutex.Lock()
                synctest.Wait()
                require.Equal(t, 1, test.events.Count("notice"))
                test.fake.mutex.Lock()
+
                test.fake.connectErr = nil
                test.fake.mutex.Unlock()
                time.Sleep(whatsappRetryLimit)
                test.fake.connectErr = nil
                test.fake.mutex.Unlock()
                time.Sleep(whatsappRetryLimit)
@@ -254,6 +274,7 @@ func TestWhatsAppLongFirstConnectionOutageGivesOneNotice(t *testing.T) {
 func TestWhatsAppStartingRetriesDoNotDuplicateLibraryRetries(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
 func TestWhatsAppStartingRetriesDoNotDuplicateLibraryRetries(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
+
        whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
        client, ok := whatsappNewClient(whatsapp.device, whatsapp.handle).(*whatsmeow.Client)
        require.True(t, ok)
        whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
        client, ok := whatsappNewClient(whatsapp.device, whatsapp.handle).(*whatsmeow.Client)
        require.True(t, ok)
@@ -269,23 +290,30 @@ func TestWhatsAppStartingRetriesDoNotDuplicateLibraryRetries(t *testing.T) {
 func TestWhatsAppLogsEachChangeOfTheConnectionOnce(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
 func TestWhatsAppLogsEachChangeOfTheConnectionOnce(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
+
        clock := newTestClock()
        whatsapp, fake, logs := whatsappStartTest(t, dir, clock)
        daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
 
        <-fake.connects
        require.True(t, fake.Emit(&events.Connected{}))
        clock := newTestClock()
        whatsapp, fake, logs := whatsappStartTest(t, dir, clock)
        daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
 
        <-fake.connects
        require.True(t, fake.Emit(&events.Connected{}))
+
        clock.now = clock.now.Add(time.Minute)
        clock.now = clock.now.Add(time.Minute)
+
        require.True(t, fake.Emit(&events.Disconnected{}))
        require.True(t, fake.Emit(&events.Disconnected{}))
+
        clock.now = clock.now.Add(time.Minute)
        clock.now = clock.now.Add(time.Minute)
+
        require.True(t, fake.Emit(&events.Disconnected{}))
        require.True(t, fake.Emit(&events.Disconnected{}))
+
        clock.now = clock.now.Add(25 * time.Second)
        clock.now = clock.now.Add(25 * time.Second)
+
        require.True(t, fake.Emit(&events.Connected{}))
 
        require.Equal(t, []string{
        require.True(t, fake.Emit(&events.Connected{}))
 
        require.Equal(t, []string{
-               "connected",
-               "disconnected, retrying",
-               "connected again after 1m25s",
+               "<6>connected",
+               "<4>disconnected, retrying",
+               "<6>connected again after=1m25s",
        }, strings.Split(strings.TrimSuffix(logs.String(), "\n"), "\n"))
        require.NotContains(t, logs.String(), whatsappTestNumber)
        require.NotContains(t, logs.String(), whatsappTestLID)
        }, strings.Split(strings.TrimSuffix(logs.String(), "\n"), "\n"))
        require.NotContains(t, logs.String(), whatsappTestNumber)
        require.NotContains(t, logs.String(), whatsappTestLID)
@@ -298,7 +326,7 @@ func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
        }{
                {
                        name: "no session file",
        }{
                {
                        name: "no session file",
-                       session: func(t *testing.T, dir string) {
+                       session: func(_ *testing.T, _ string) {
                        },
                },
                {
                        },
                },
                {
@@ -313,6 +341,7 @@ func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
                t.Run(tc.name, func(t *testing.T) {
                        dir := t.TempDir()
                        tc.session(t, dir)
                t.Run(tc.name, func(t *testing.T) {
                        dir := t.TempDir()
                        tc.session(t, dir)
+
                        whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
                        require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
                })
                        whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
                        require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
                })
@@ -358,7 +387,7 @@ func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) {
 
 func TestWhatsAppPairsWithACode(t *testing.T) {
        dir := t.TempDir()
 
 func TestWhatsAppPairsWithACode(t *testing.T) {
        dir := t.TempDir()
-       whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
+       whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
        server := newModelFake(t)
        socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
        asking := terminalStartTestClient(t, socket)
        server := newModelFake(t)
        socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp)
        asking := terminalStartTestClient(t, socket)
@@ -367,6 +396,7 @@ func TestWhatsAppPairsWithACode(t *testing.T) {
        other.WaitFor(t, "[connected to OneChat]")
 
        asking.Type("/whatsapp pair +1 555-000-1111")
        other.WaitFor(t, "[connected to OneChat]")
 
        asking.Type("/whatsapp pair +1 555-000-1111")
+
        items := <-fake.pairings
        items <- whatsmeow.QRChannelItem{
                Event: whatsmeow.QRChannelEventCode,
        items := <-fake.pairings
        items <- whatsmeow.QRChannelItem{
                Event: whatsmeow.QRChannelEventCode,
@@ -377,7 +407,9 @@ func TestWhatsAppPairsWithACode(t *testing.T) {
                ID:  types.NewADJID(whatsappTestNumber, 0, 1),
                LID: types.NewADJID(whatsappTestLID, 0, 1),
        }))
                ID:  types.NewADJID(whatsappTestNumber, 0, 1),
                LID: types.NewADJID(whatsappTestLID, 0, 1),
        }))
+
        items <- whatsmeow.QRChannelSuccess
        items <- whatsmeow.QRChannelSuccess
+
        asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
 
        // The library connects again after the link with the context of the
        asking.WaitFor(t, "WhatsApp is linked to +15550001111.")
 
        // The library connects again after the link with the context of the
@@ -393,6 +425,7 @@ func TestWhatsAppPairsWithACode(t *testing.T) {
        require.Equal(t, "[connected to OneChat]\n", other.Output())
        require.Zero(t, server.Calls())
        require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory))
        require.Equal(t, "[connected to OneChat]\n", other.Output())
        require.Zero(t, server.Calls())
        require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory))
+       require.Equal(t, "<6>linked\n", logs.String())
 
        info, err := os.Stat(filepath.Join(dir, whatsappDirName))
        require.NoError(t, err)
 
        info, err := os.Stat(filepath.Join(dir, whatsappDirName))
        require.NoError(t, err)
@@ -482,6 +515,7 @@ func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) {
        client.Type("/whatsapp pair 15550001111")
        <-fake.pairings
        client.Type("/whatsapp pair 15550002222")
        client.Type("/whatsapp pair 15550001111")
        <-fake.pairings
        client.Type("/whatsapp pair 15550002222")
+
        items := <-fake.pairings
        items <- whatsmeow.QRChannelItem{
                Event: whatsmeow.QRChannelEventCode,
        items := <-fake.pairings
        items <- whatsmeow.QRChannelItem{
                Event: whatsmeow.QRChannelEventCode,
@@ -495,6 +529,7 @@ func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) {
 func TestWhatsAppPairWhenLinked(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
 func TestWhatsAppPairWhenLinked(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
+
        whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
        socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
        client := terminalStartTestClient(t, socket)
        whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
        socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
        client := terminalStartTestClient(t, socket)
@@ -524,15 +559,18 @@ func TestWhatsAppUnlink(t *testing.T) {
                t.Run(tc.name, func(t *testing.T) {
                        dir := t.TempDir()
                        whatsappTestSession(t, dir, true)
                t.Run(tc.name, func(t *testing.T) {
                        dir := t.TempDir()
                        whatsappTestSession(t, dir, true)
-                       whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
+
+                       whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
                        fake.logoutErr = tc.logoutErr
                        socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
                        client := terminalStartTestClient(t, socket)
                        fake.logoutErr = tc.logoutErr
                        socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
                        client := terminalStartTestClient(t, socket)
+
                        <-fake.connects
 
                        client.Type("/whatsapp unlink")
                        client.WaitFor(t, tc.answer)
                        require.Equal(t, 1, fake.Logouts())
                        <-fake.connects
 
                        client.Type("/whatsapp unlink")
                        client.WaitFor(t, tc.answer)
                        require.Equal(t, 1, fake.Logouts())
+                       require.Equal(t, "<6>unlinked\n", logs.String())
                        require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
                        require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
                        require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory))
                        require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
                        require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
                        require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory))
@@ -546,7 +584,8 @@ func TestWhatsAppUnlink(t *testing.T) {
 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
 func TestWhatsAppLogoutFromThePhone(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
-       whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
+
+       whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
        telegram := newTelegramFake(t)
        bot, _ := telegramStartTestBot(t, telegram)
        socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
        telegram := newTelegramFake(t)
        bot, _ := telegramStartTestBot(t, telegram)
        socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp)
@@ -555,47 +594,51 @@ func TestWhatsAppLogoutFromThePhone(t *testing.T) {
        <-fake.connects
 
        require.True(t, fake.Emit(&events.LoggedOut{}))
        <-fake.connects
 
        require.True(t, fake.Emit(&events.LoggedOut{}))
+
        notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again."
        client.WaitFor(t, notice)
        telegramWaitForSent(t, telegram, notice)
        notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again."
        client.WaitFor(t, notice)
        telegramWaitForSent(t, telegram, notice)
+       require.Equal(t, "<3>logged out by the phone, run /whatsapp pair PHONE\n", logs.String())
        require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
        require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
        require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory))
 }
 
 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
        require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName))
        require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status())
        require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory))
 }
 
 func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) {
-       dir := t.TempDir()
-       whatsappTestSession(t, dir, true)
-       clock := newTestClock()
-       whatsapp, fake, _ := whatsappStartTest(t, dir, clock)
-       whatsapp.noticeDelay = 300 * time.Millisecond
-       socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
-       client := terminalStartTestClient(t, socket)
-       client.WaitFor(t, "[connected to OneChat]")
-       <-fake.connects
+       synctest.Test(t, func(t *testing.T) {
+               test := whatsappRetryTest(t)
+               test.start(t)
+               synctest.Wait()
 
 
-       require.True(t, fake.Emit(&events.Connected{}))
-       require.True(t, fake.Emit(&events.Disconnected{}))
-       require.True(t, fake.Emit(&events.Connected{}))
-       time.Sleep(400 * time.Millisecond)
-       require.Equal(t, "[connected to OneChat]\n", client.Output())
+               require.True(t, test.fake.Emit(&events.Connected{}))
+               require.True(t, test.fake.Emit(&events.Disconnected{}))
+               require.True(t, test.fake.Emit(&events.Connected{}))
+               time.Sleep(whatsappOutageNoticeDelay + time.Second)
+               synctest.Wait()
+               require.Zero(t, test.events.Count("notice"))
 
 
-       clock.now = clock.now.Add(time.Hour)
-       require.True(t, fake.Emit(&events.Disconnected{}))
-       require.True(t, fake.Emit(&events.Disconnected{}))
-       client.WaitFor(t, "WhatsApp is disconnected since 2026-01-01 13:00. OneChat tries again.\n")
-       require.True(t, fake.Emit(&events.Disconnected{}))
-       time.Sleep(400 * time.Millisecond)
+               require.True(t, test.fake.Emit(&events.Disconnected{}))
+               require.True(t, test.fake.Emit(&events.Disconnected{}))
+               time.Sleep(whatsappOutageNoticeDelay)
+               synctest.Wait()
+               require.Equal(t, 1, test.events.Count("notice"))
+               require.Contains(t, test.events.Last("notice"), "OneChat tries again.")
+               require.True(t, test.fake.Emit(&events.Disconnected{}))
+               time.Sleep(whatsappOutageNoticeDelay)
+               synctest.Wait()
+               require.Equal(t, 1, test.events.Count("notice"))
 
 
-       require.True(t, fake.Emit(&events.Connected{}))
-       client.WaitFor(t, "WhatsApp is connected again.\n")
-       require.Equal(t, 1, strings.Count(client.Output(), "WhatsApp is disconnected since"))
+               require.True(t, test.fake.Emit(&events.Connected{}))
+               require.Equal(t, 2, test.events.Count("notice"))
+               require.Equal(t, "WhatsApp is connected again.", test.events.Last("notice"))
+       })
 }
 
 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
 }
 
 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
-       whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock())
+
+       whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
        socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
        client := terminalStartTestClient(t, socket)
        client.WaitFor(t, "[connected to OneChat]")
        socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
        client := terminalStartTestClient(t, socket)
        client.WaitFor(t, "[connected to OneChat]")
@@ -603,20 +646,23 @@ func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
 
        require.True(t, fake.Emit(&events.StreamReplaced{}))
        client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.")
 
        require.True(t, fake.Emit(&events.StreamReplaced{}))
        client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.")
+       require.Equal(t, "<3>disconnected for good, restart to retry: stream replaced\n", logs.String())
 }
 
 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
 }
 
 func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
        dir := t.TempDir()
        whatsappTestSession(t, dir, true)
+
        whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
        fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid")
        whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
        fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid")
+
        daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
        <-fake.connects
 
        require.Eventually(t, func() bool {
                return logs.String() != ""
        }, 10*time.Second, time.Millisecond)
        daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp)
        <-fake.connects
 
        require.Eventually(t, func() bool {
                return logs.String() != ""
        }, 10*time.Second, time.Millisecond)
-       require.Equal(t, "first connect failed, retrying: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String())
+       require.Equal(t, "<4>first connect failed, retrying: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String())
 }
 
 func TestWhatsAppPhone(t *testing.T) {
 }
 
 func TestWhatsAppPhone(t *testing.T) {
@@ -707,60 +753,3 @@ func TestSubagentHasNoWhatsAppTools(t *testing.T) {
        require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`))
        require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`))
 }
        require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`))
        require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`))
 }
-
-// WhatsAppRetryTest runs WhatsApp without a model or network client call. All
-// timers and channels belong to its synctest bubble, so backoff uses fake time.
-type WhatsAppRetryTest struct {
-       whatsapp *WhatsApp
-       fake     *WhatsAppFake
-       logs     *SyncBuffer
-       loop     *TurnLoop
-       events   *TurnEventRecorder
-       cancel   context.CancelFunc
-       done     chan error
-}
-
-func (r *WhatsAppRetryTest) start(t *testing.T) {
-       t.Helper()
-
-       ctx, cancel := context.WithCancel(t.Context())
-       r.cancel = cancel
-       r.done = make(chan error, 1)
-       go func() {
-               r.done <- r.whatsapp.Run(ctx, r.loop, r.events.Add)
-       }()
-
-       t.Cleanup(func() {
-               cancel()
-               synctest.Wait()
-       })
-}
-
-func whatsappRetryTest(t *testing.T) *WhatsAppRetryTest {
-       t.Helper()
-
-       dir := t.TempDir()
-       whatsappTestSession(t, dir, true)
-       whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock())
-       whatsapp.clock = time.Now
-       agent, err := openAgent(t.TempDir())
-       require.NoError(t, err)
-       memory, err := openMemory(t.Context(), agent.dir, time.Now, newFakeSummarizer(), discardLog())
-       require.NoError(t, err)
-       t.Cleanup(func() {
-               require.NoError(t, memory.Close())
-       })
-
-       events := &TurnEventRecorder{}
-       client := newModelClient("https://example.com", ModelAPIKey(modelTestKey), agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
-       loop, err := newTurnLoop(agent, memory, newTestSubagents(t), whatsapp, newTestSchedules(t, time.Now), client, time.Now, discardLog(), events.Add)
-       require.NoError(t, err)
-
-       return &WhatsAppRetryTest{
-               whatsapp: whatsapp,
-               fake:     fake,
-               logs:     logs,
-               loop:     loop,
-               events:   events,
-       }
-}