13 "github.com/stretchr/testify/require"
16 func TestOwnerTalksToTheAgentThroughTelegram(t *testing.T) {
17 server := newFakeResponses(t)
18 server.reply = func(w http.ResponseWriter, call fakeCall) {
19 writeEvents(w, completedEvent([]any{messageItem("Hello from the agent.")}, 100, 0, 5))
22 telegram := newFakeBot(t)
23 bot, _ := startTestBot(t, telegram)
24 socket := startTestDaemonWithBot(t, server, bot)
25 terminal := startTestClient(t, socket)
26 terminal.WaitFor(t, "[connected to OneChat]")
28 telegram.Add(botUpdate{
30 Message: ownerMessage("hi from the phone"),
33 terminal.WaitFor(t, "[telegram] hi from the phone\n[working]\nHello from the agent.\n[done]")
34 waitForSent(t, telegram, "Hello from the agent.")
35 require.True(t, slices.ContainsFunc(telegram.Calls(), func(call fakeBotCall) bool {
36 return call.method == "sendChatAction" && call.params["action"] == "typing"
39 terminal.Type("hi from the desk")
40 require.Equal(t, []string{"Hello from the agent.", "[terminal] hi from the desk", "Hello from the agent."}, waitForSent(t, telegram, "Hello from the agent.", "[terminal] hi from the desk", "Hello from the agent."))
43 func TestBotIgnoresEveryoneButTheOwner(t *testing.T) {
44 telegram := newFakeBot(t)
45 bot, logs := startTestBot(t, telegram)
46 socket := startTestDaemonWithBot(t, newFakeResponses(t), bot)
47 terminal := startTestClient(t, socket)
48 terminal.WaitFor(t, "[connected to OneChat]")
50 group := ownerMessage("secret in a group")
56 stranger := ownerMessage("secret of a stranger")
60 unsigned := ownerMessage("secret with no sender")
63 for id, message := range []*botMessage{group, stranger, unsigned, nil} {
64 telegram.Add(botUpdate{
65 UpdateID: int64(10 + id),
70 require.Eventually(t, func() bool {
71 offset, err := loadOffset(bot.offsetPath)
72 return err == nil && offset == 14
73 }, 10*time.Second, time.Millisecond)
75 require.Empty(t, telegram.Sent())
76 require.NotContains(t, terminal.Output(), "secret")
77 require.NotContains(t, logs.String(), "secret")
78 require.Contains(t, logs.String(), "update ignored")
81 func TestBotAnswersThatOnlyTextIsSupported(t *testing.T) {
82 telegram := newFakeBot(t)
83 bot, _ := startTestBot(t, telegram)
84 startTestDaemonWithBot(t, newFakeResponses(t), bot)
86 telegram.Add(botUpdate{
88 Message: ownerMessage(""),
91 waitForSent(t, telegram, textOnly)
94 func TestStopFromTelegramInterruptsTheTurn(t *testing.T) {
95 server := newFakeResponses(t)
96 arrived := make(chan struct{})
97 release := make(chan struct{})
102 server.reply = func(w http.ResponseWriter, call fakeCall) {
107 telegram := newFakeBot(t)
108 bot, _ := startTestBot(t, telegram)
109 startTestDaemonWithBot(t, server, bot)
111 telegram.Add(botUpdate{
113 Message: ownerMessage("a long task"),
117 telegram.Add(botUpdate{
119 Message: ownerMessage(stopCommand),
122 waitForSent(t, telegram, "Error: interrupted")
124 telegram.Add(botUpdate{
126 Message: ownerMessage(stopCommand),
129 waitForSent(t, telegram, "Error: interrupted", "No turn runs.")
132 func TestBotStartsAtTheStoredOffset(t *testing.T) {
133 server := newFakeResponses(t)
134 server.reply = func(w http.ResponseWriter, call fakeCall) {
135 writeEvents(w, completedEvent([]any{messageItem("ok")}, 100, 0, 5))
138 telegram := newFakeBot(t)
139 bot, _ := startTestBot(t, telegram)
140 require.NoError(t, saveOffset(bot.offsetPath, 10))
142 telegram.Add(botUpdate{
144 Message: ownerMessage("handled before the restart"),
147 telegram.Add(botUpdate{
149 Message: ownerMessage("new after the restart"),
152 socket := startTestDaemonWithBot(t, server, bot)
153 terminal := startTestClient(t, socket)
154 terminal.WaitFor(t, "[connected to OneChat]")
155 waitForSent(t, telegram, "ok")
157 require.Equal(t, float64(10), telegram.Calls()[0].params["offset"])
158 require.NotContains(t, terminal.Output(), "handled before the restart")
160 require.Eventually(t, func() bool {
161 offset, err := loadOffset(bot.offsetPath)
162 return err == nil && offset == 11
163 }, 10*time.Second, time.Millisecond)
166 func TestBotTriesAgainAfterFailures(t *testing.T) {
167 server := newFakeResponses(t)
168 server.reply = func(w http.ResponseWriter, call fakeCall) {
169 writeEvents(w, completedEvent([]any{messageItem("ok")}, 100, 0, 5))
172 telegram := newFakeBot(t)
173 failures := map[string]int{
178 telegram.fail = func(call fakeBotCall) (int, string) {
179 if failures[call.method] == 0 {
183 failures[call.method]--
184 if call.method == "sendMessage" {
185 return http.StatusTooManyRequests, "Too Many Requests: retry after 1"
188 return http.StatusBadGateway, "Bad Gateway"
191 bot, logs := startTestBot(t, telegram)
192 startTestDaemonWithBot(t, server, bot)
194 telegram.Add(botUpdate{
196 Message: ownerMessage("hello"),
199 waitForSent(t, telegram, "ok")
200 require.Contains(t, logs.String(), "answered 502")
201 require.Contains(t, logs.String(), "answered 429")
202 require.NotContains(t, logs.String(), testBotToken)
205 func TestDeliverTriesAgainAfterATimeout(t *testing.T) {
206 telegram := newFakeBot(t)
208 telegram.stall = func(call fakeBotCall) bool {
209 if call.method != "sendMessage" || stalls == 0 {
218 bot, logs := startTestBot(t, telegram)
219 bot.api.sendTimeout = 50 * time.Millisecond
220 bot.deliver(t.Context(), botPart{
224 require.Equal(t, []string{"hello"}, telegram.Sent())
225 require.Len(t, telegram.Calls(), 2)
226 require.Contains(t, logs.String(), "no valid answer")
227 require.NotContains(t, logs.String(), testBotToken)
230 func TestOnlyRepliesGetEntities(t *testing.T) {
231 server := newFakeResponses(t)
232 server.reply = func(w http.ResponseWriter, call fakeCall) {
233 writeEvents(w, completedEvent([]any{messageItem("**Done** with `x`.")}, 100, 0, 5))
236 telegram := newFakeBot(t)
237 bot, _ := startTestBot(t, telegram)
238 socket := startTestDaemonWithBot(t, server, bot)
239 terminal := startTestClient(t, socket)
240 terminal.WaitFor(t, "[connected to OneChat]")
242 terminal.Type("make **it** so")
243 waitForSent(t, telegram, "[terminal] make **it** so", "Done with x.")
245 telegram.Add(botUpdate{
247 Message: ownerMessage(""),
250 waitForSent(t, telegram, textOnly)
252 entities := map[string]any{}
253 for _, call := range telegram.Calls() {
254 if call.method == "sendMessage" {
255 entities[call.params["text"].(string)] = call.params["entities"]
259 require.Equal(t, map[string]any{
260 "[terminal] make **it** so": nil,
261 "Done with x.": []any{
264 "offset": float64(0),
265 "length": float64(4),
269 "offset": float64(10),
270 "length": float64(1),
277 func TestRefusedEntitiesGoAgainAsPlainText(t *testing.T) {
278 telegram := newFakeBot(t)
279 telegram.fail = func(call fakeBotCall) (int, string) {
280 if call.params["entities"] == nil {
284 return http.StatusBadRequest, "Bad Request: can't parse entities of bot" + testBotToken
287 bot, logs := startTestBot(t, telegram)
288 text, entities := markdownEntities("a **secret** word")
289 bot.deliver(t.Context(), botPart{
294 calls := telegram.Calls()
295 require.Len(t, calls, 2)
296 require.NotNil(t, calls[0].params["entities"])
297 require.Nil(t, calls[1].params["entities"])
298 require.Equal(t, []string{"a secret word"}, telegram.Sent())
299 require.Equal(t, 1, strings.Count(logs.String(), "\n"))
300 require.Contains(t, logs.String(), "entities refused")
301 require.NotContains(t, logs.String(), testBotToken)
302 require.NotContains(t, logs.String(), "secret word")
305 func TestBotLogsNoTokenWhenTheNetworkFails(t *testing.T) {
306 telegram := newFakeBot(t)
309 bot, logs := startTestBot(t, telegram)
310 startTestDaemonWithBot(t, newFakeResponses(t), bot)
312 require.Eventually(t, func() bool {
313 return strings.Count(logs.String(), "no valid answer") >= 2
314 }, 10*time.Second, time.Millisecond)
315 require.NotContains(t, logs.String(), testBotToken)
318 func TestSplitMessage(t *testing.T) {
319 testCases := []struct {
326 name: "short text stays whole",
329 parts: []string{"one two"},
332 name: "cut after the last line break",
333 text: "first line\nsecond line",
335 parts: []string{"first line\n", "second line"},
338 name: "cut after the last space without a line break",
339 text: "aaaa bbbb cccc",
341 parts: []string{"aaaa bbbb ", "cccc"},
344 name: "hard cut of one long word",
347 parts: []string{"abcd", "efgh", "ij"},
350 name: "a character outside the BMP counts two units and is not cut",
351 text: "ab\U0001F600cd",
353 parts: []string{"ab", "\U0001F600c", "d"},
357 for _, tc := range testCases {
358 t.Run(tc.name, func(t *testing.T) {
359 require.Equal(t, tc.parts, splitMessage(tc.text, tc.limit))
363 long := strings.Repeat("word ", 2000)
364 parts := splitMessage(long, messageUnits)
365 require.Len(t, parts, 3)
366 require.Equal(t, long, strings.Join(parts, ""))
369 func TestSplitEntitiesCutsAnEntityAcrossASplit(t *testing.T) {
370 parts := splitEntities("aabbbbcc", []botEntity{
383 require.Equal(t, []botPart{
386 entities: []botEntity{
396 entities: []botEntity{
412 func TestSplitRich(t *testing.T) {
413 testCases := []struct {
420 name: "short reply stays whole",
421 markdown: "| a | b |",
423 parts: []string{"| a | b |"},
426 name: "cut after a blank line keeps a table whole",
427 markdown: "Intro.\n\n| a | b |\n|---|---|\n| 1 | 2 |\n",
429 parts: []string{"Intro.\n\n", "| a | b |\n|---|---|\n| 1 | 2 |\n"},
432 name: "blank line in a code block is not a cut",
433 markdown: "Text.\n\n```go\nx\n\ny\n```\n\nEnd.\n",
435 parts: []string{"Text.\n\n", "```go\nx\n\ny\n```\n\n", "End.\n"},
438 name: "paragraph with no blank line is cut after a line",
439 markdown: "aaa\nbbb\nccc\n",
441 parts: []string{"aaa\nbbb\n", "ccc\n"},
444 name: "long code block is closed and opened again",
445 markdown: "```sh\none\ntwo\nthree\n```\n",
447 parts: []string{"```sh\none\n```\n", "```sh\ntwo\n```\n", "```sh\nthree\n```\n"},
450 name: "long line is cut at the limit and not inside a character",
451 markdown: "ab\u00e9cd",
453 parts: []string{"ab", "\u00e9c", "d"},
457 for _, tc := range testCases {
458 t.Run(tc.name, func(t *testing.T) {
459 require.Equal(t, tc.parts, splitRich(tc.markdown, tc.limit))
463 long := strings.Repeat("A paragraph of the reply.\n\n", 2000)
464 parts := splitRich(long, richMessageBytes)
465 require.Len(t, parts, 2)
466 require.Len(t, parts[0], richMessageBytes-richMessageBytes%len("A paragraph of the reply.\n\n"))
467 require.Equal(t, long, strings.Join(parts, ""))
470 func TestLoadBotConfig(t *testing.T) {
471 testCases := []struct {
478 name: "owner file is read",
479 content: `{"token": "` + testBotToken + `", "owner": 4242}`,
483 name: "file that others can read is refused",
484 content: `{"token": "` + testBotToken + `", "owner": 4242}`,
486 errorText: "mode must be 0600",
489 name: "token with a path character is refused",
490 content: `{"token": "123:abc/../x", "owner": 4242}`,
492 errorText: "form of a bot token",
495 name: "missing owner is refused",
496 content: `{"token": "` + testBotToken + `"}`,
498 errorText: "numeric Telegram user ID",
501 name: "unknown field is refused",
502 content: `{"token": "` + testBotToken + `", "owner": 4242, "chat": 1}`,
504 errorText: "not valid JSON",
508 for _, tc := range testCases {
509 t.Run(tc.name, func(t *testing.T) {
511 path := filepath.Join(dir, botConfigFileName)
512 require.NoError(t, os.WriteFile(path, []byte(tc.content), tc.mode))
513 require.NoError(t, os.Chmod(path, tc.mode))
515 config, found, err := loadBotConfig(dir)
516 if tc.errorText != "" {
517 require.ErrorContains(t, err, tc.errorText)
518 require.NotContains(t, err.Error(), testBotToken)
523 require.NoError(t, err)
524 require.True(t, found)
525 require.Equal(t, botConfig{
532 _, found, err := loadBotConfig(t.TempDir())
533 require.NoError(t, err)
534 require.False(t, found)
537 // startTestBot returns a bot of testOwner on server, with its offset file in a
538 // temporary directory and short waits, and the buffer of its log.
539 func startTestBot(t *testing.T, server *fakeBot) (*telegramBot, *syncBuffer) {
542 logs := &syncBuffer{}
543 bot := newTelegramBot(newBotAPI(server.URL, testBotToken), testOwner, filepath.Join(t.TempDir(), offsetFileName), log.New(logs, "", 0))
544 bot.minWait = time.Millisecond
545 bot.maxWait = 10 * time.Millisecond
550 // waitForSent waits until the bot sent the texts in order, and returns them.
551 func waitForSent(t *testing.T, server *fakeBot, texts ...string) []string {
554 require.Eventually(t, func() bool {
555 sent := server.Sent()
556 return len(sent) >= len(texts) && slices.Equal(sent[len(sent)-len(texts):], texts)
557 }, 10*time.Second, time.Millisecond, "sent so far: %q", server.Sent())