]> git.giacomolli.uk - onechat/blobdiff - whatsapp_test.go
Prove direct cancellation during a pending sync
[onechat] / whatsapp_test.go
index 96ec2df0031cb169310fb99324046ce8e9698bf4..d200a91fbed394873356f46fb9b863e85b85f104 100644 (file)
@@ -1,7 +1,6 @@
 package main
 
 import (
 package main
 
 import (
-       "context"
        "errors"
        "os"
        "path/filepath"
        "errors"
        "os"
        "path/filepath"
@@ -91,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, "<4>first connect failed, retrying: network unavailable\n<6>connected again after="+durationText(outage)+"\n", test.logs.String())
+               require.Equal(t, "<4>first connect failed, retrying: network unavailable\n<6>connected again after="+daemonLogDuration(outage)+"\n", test.logs.String())
        })
 }
 
        })
 }
 
@@ -124,6 +123,7 @@ func TestWhatsAppLinkedPairRequestKeepsFirstConnectionRetries(t *testing.T) {
                test.whatsapp.Command("pair 15550001111", func(text string) {
                        answers <- text
                })
                test.whatsapp.Command("pair 15550001111", func(text string) {
                        answers <- text
                })
+
                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()
@@ -149,20 +149,20 @@ func TestWhatsAppFirstConnectionRetriesStopForLinkChanges(t *testing.T) {
                stop func(test *WhatsAppRetryTest)
        }{
                {
                stop func(test *WhatsAppRetryTest)
        }{
                {
-                       name: "unlink",
+                       name: "stops retrying after unlink",
                        stop: func(test *WhatsAppRetryTest) {
                                test.whatsapp.Command("unlink", func(_ string) {
                                })
                        },
                },
                {
                        stop: func(test *WhatsAppRetryTest) {
                                test.whatsapp.Command("unlink", func(_ string) {
                                })
                        },
                },
                {
-                       name: "logout",
+                       name: "stops retrying after logout",
                        stop: func(test *WhatsAppRetryTest) {
                                test.fake.Emit(&events.LoggedOut{})
                        },
                },
                {
                        stop: func(test *WhatsAppRetryTest) {
                                test.fake.Emit(&events.LoggedOut{})
                        },
                },
                {
-                       name: "permanent disconnect",
+                       name: "stops retrying after a permanent disconnect",
                        stop: func(test *WhatsAppRetryTest) {
                                test.fake.Emit(&events.StreamReplaced{})
                        },
                        stop: func(test *WhatsAppRetryTest) {
                                test.fake.Emit(&events.StreamReplaced{})
                        },
@@ -194,6 +194,7 @@ func TestWhatsAppPairsAfterFirstConnectionRetriesStop(t *testing.T) {
                synctest.Wait()
                test.whatsapp.Command("unlink", func(_ string) {
                })
                synctest.Wait()
                test.whatsapp.Command("unlink", func(_ string) {
                })
+
                synctest.Wait()
                require.False(t, test.whatsapp.isLinked())
 
                synctest.Wait()
                require.False(t, test.whatsapp.isLinked())
 
@@ -250,12 +251,12 @@ func TestWhatsAppLongFirstConnectionOutageGivesOneNotice(t *testing.T) {
 
                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()
@@ -316,6 +317,7 @@ func TestWhatsAppLogsEachChangeOfTheConnectionOnce(t *testing.T) {
                "<4>disconnected, retrying",
                "<6>connected again after=1m25s",
        }, strings.Split(strings.TrimSuffix(logs.String(), "\n"), "\n"))
                "<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)
 }
        require.NotContains(t, logs.String(), whatsappTestNumber)
        require.NotContains(t, logs.String(), whatsappTestLID)
 }
@@ -326,12 +328,12 @@ func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) {
                session func(t *testing.T, dir string)
        }{
                {
                session func(t *testing.T, dir string)
        }{
                {
-                       name: "no session file",
+                       name: "stays unlinked without a session file",
                        session: func(_ *testing.T, _ string) {
                        },
                },
                {
                        session: func(_ *testing.T, _ string) {
                        },
                },
                {
-                       name: "a session of a pairing that did not end",
+                       name: "stays unlinked after incomplete pairing",
                        session: func(t *testing.T, dir string) {
                                whatsappTestSession(t, dir, false)
                        },
                        session: func(t *testing.T, dir string) {
                                whatsappTestSession(t, dir, false)
                        },
@@ -354,7 +356,7 @@ func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) {
        whatsappTestSession(t, dir, true)
        require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
 
        whatsappTestSession(t, dir, true)
        require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644))
 
-       _, err := openWhatsApp(t.Context(), dir, time.Now, whatsappDiscardLog(), whatsappNewClient)
+       _, err := openWhatsApp(t.Context(), dir, time.Now, discardLog(), whatsappNewClient)
        require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600")
 }
 
        require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600")
 }
 
@@ -463,21 +465,21 @@ func TestWhatsAppPairingEnds(t *testing.T) {
                answer string
        }{
                {
                answer string
        }{
                {
-                       name: "the code expires",
+                       name: "ends pairing when the code expires",
                        end: func(items chan whatsmeow.QRChannelItem) {
                                items <- whatsmeow.QRChannelTimeout
                        },
                        answer: whatsappPairExpired,
                },
                {
                        end: func(items chan whatsmeow.QRChannelItem) {
                                items <- whatsmeow.QRChannelTimeout
                        },
                        answer: whatsappPairExpired,
                },
                {
-                       name: "the library closes the pairing",
+                       name: "ends pairing when the library closes it",
                        end: func(items chan whatsmeow.QRChannelItem) {
                                close(items)
                        },
                        answer: whatsappPairExpired,
                },
                {
                        end: func(items chan whatsmeow.QRChannelItem) {
                                close(items)
                        },
                        answer: whatsappPairExpired,
                },
                {
-                       name: "the pairing fails",
+                       name: "ends pairing when the library reports failure",
                        end: func(items chan whatsmeow.QRChannelItem) {
                                items <- whatsmeow.QRChannelItem{
                                        Event: whatsmeow.QRChannelEventError,
                        end: func(items chan whatsmeow.QRChannelItem) {
                                items <- whatsmeow.QRChannelItem{
                                        Event: whatsmeow.QRChannelEventError,
@@ -546,11 +548,11 @@ func TestWhatsAppUnlink(t *testing.T) {
                answer    string
        }{
                {
                answer    string
        }{
                {
-                       name:   "with a logout",
+                       name:   "logs out before removing the session",
                        answer: "WhatsApp is unlinked.",
                },
                {
                        answer: "WhatsApp is unlinked.",
                },
                {
-                       name:      "with no logout",
+                       name:      "removes an offline session without logout",
                        logoutErr: errors.New("not connected"),
                        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.",
                },
                        logoutErr: errors.New("not connected"),
                        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.",
                },
@@ -599,41 +601,40 @@ func TestWhatsAppLogoutFromThePhone(t *testing.T) {
        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.Equal(t, "<3>logged out by the 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
-
-       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())
+       synctest.Test(t, func(t *testing.T) {
+               test := whatsappRetryTest(t)
+               test.start(t)
+               synctest.Wait()
 
 
-       clock.now = clock.now.Add(time.Hour)
+               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"))
 
 
-       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) {
 }
 
 func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) {
@@ -664,6 +665,7 @@ func TestWhatsAppLogsNoOwnNumber(t *testing.T) {
        require.Eventually(t, func() bool {
                return logs.String() != ""
        }, 10*time.Second, time.Millisecond)
        require.Eventually(t, func() bool {
                return logs.String() != ""
        }, 10*time.Second, time.Millisecond)
+
        require.Equal(t, "<4>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())
 }
 
@@ -674,27 +676,27 @@ func TestWhatsAppPhone(t *testing.T) {
                valid bool
        }{
                {
                valid bool
        }{
                {
-                       name:  "a number with a plus and dashes",
+                       name:  "accepts a number with a plus and dashes",
                        phone: "+1-555-000-1111",
                        valid: true,
                },
                {
                        phone: "+1-555-000-1111",
                        valid: true,
                },
                {
-                       name:  "a number with no country code",
+                       name:  "refuses a number without a country code",
                        phone: "0115550001111",
                        valid: false,
                },
                {
                        phone: "0115550001111",
                        valid: false,
                },
                {
-                       name:  "a short number",
+                       name:  "refuses a number shorter than the minimum",
                        phone: "123456",
                        valid: false,
                },
                {
                        phone: "123456",
                        valid: false,
                },
                {
-                       name:  "a long number",
+                       name:  "refuses a number longer than the maximum",
                        phone: "1234567890123456",
                        valid: false,
                },
                {
                        phone: "1234567890123456",
                        valid: false,
                },
                {
-                       name:  "a number with letters",
+                       name:  "refuses a number with letters",
                        phone: "1555ABC1111",
                        valid: false,
                },
                        phone: "1555ABC1111",
                        valid: false,
                },
@@ -716,25 +718,25 @@ func TestWhatsAppCommandArgs(t *testing.T) {
                found bool
        }{
                {
                found bool
        }{
                {
-                       name:  "a command with its arguments",
+                       name:  "reads and trims the command arguments",
                        line:  " /whatsapp  pair +1 555 ",
                        args:  "pair +1 555",
                        found: true,
                },
                {
                        line:  " /whatsapp  pair +1 555 ",
                        args:  "pair +1 555",
                        found: true,
                },
                {
-                       name:  "the command alone",
+                       name:  "accepts the command without arguments",
                        line:  "/whatsapp",
                        args:  "",
                        found: true,
                },
                {
                        line:  "/whatsapp",
                        args:  "",
                        found: true,
                },
                {
-                       name:  "a word that starts with the command",
+                       name:  "leaves a joined command word as text",
                        line:  "/whatsappstatus",
                        args:  "",
                        found: false,
                },
                {
                        line:  "/whatsappstatus",
                        args:  "",
                        found: false,
                },
                {
-                       name:  "a message that names the command",
+                       name:  "leaves a mention of the command as text",
                        line:  "what does /whatsapp status do?",
                        args:  "",
                        found: false,
                        line:  "what does /whatsapp status do?",
                        args:  "",
                        found: false,
@@ -755,62 +757,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,
-       }
-}