]> git.giacomolli.uk - onechat/blob - schedule_test.go
f83c2e44d7004ab12c036dc6caa6c993122cecc2
[onechat] / schedule_test.go
1 package main
2
3 import (
4 "context"
5 "os"
6 "path/filepath"
7 "strings"
8 "sync"
9 "testing"
10 "time"
11
12 "github.com/stretchr/testify/require"
13 )
14
15 func TestSchedulesSet(t *testing.T) {
16 testCases := []struct {
17 name string
18 text string
19 at *string
20 cron *string
21 answer string
22 listed string
23 }{
24 {
25 name: "a one-time schedule at a local time",
26 text: "Remind the user to drink water.",
27 at: new("2026-11-09 09:00"),
28 answer: "Schedule 1 set. Next: Monday 2026-11-09 09:00 -03:00.",
29 listed: "1 | Monday 2026-11-09 09:00 -03:00 | once | Remind the user to drink water.",
30 },
31 {
32 name: "a repeating schedule at the next match",
33 text: "Tell the user\nthe time.",
34 cron: new("*/5 * * * *"),
35 answer: "Schedule 1 set. Next: Sunday 2026-11-08 20:05 -03:00.",
36 listed: "1 | Sunday 2026-11-08 20:05 -03:00 | */5 * * * * | Tell the user the time.",
37 },
38 }
39
40 for _, tc := range testCases {
41 t.Run(tc.name, func(t *testing.T) {
42 schedules, _ := scheduleTestOpen(t)
43
44 answer, err := schedules.Set(tc.text, tc.at, tc.cron)
45 require.NoError(t, err)
46 require.Equal(t, tc.answer, answer)
47 require.Equal(t, tc.listed, schedules.List())
48 })
49 }
50 }
51
52 func TestSchedulesSetRefuses(t *testing.T) {
53 testCases := []struct {
54 name string
55 text string
56 at *string
57 cron *string
58 message string
59 }{
60 {
61 name: "an empty text",
62 text: " \n",
63 at: new("2026-11-09 09:00"),
64 message: "the text must have 1 to 4096 bytes",
65 },
66 {
67 name: "a text that is too long",
68 text: strings.Repeat("x", scheduleTextBytes+1),
69 at: new("2026-11-09 09:00"),
70 message: "the text must have 1 to 4096 bytes",
71 },
72 {
73 name: "neither at nor cron",
74 text: "Tell the user the time.",
75 message: "give either at or cron, and null for the other",
76 },
77 {
78 name: "both at and cron",
79 text: "Tell the user the time.",
80 at: new("2026-11-09 09:00"),
81 cron: new("0 9 * * *"),
82 message: "give either at or cron, and null for the other",
83 },
84 {
85 name: "a time in another layout",
86 text: "Tell the user the time.",
87 at: new("2026-11-09T09:00:00-03:00"),
88 message: "at must be a local time such as 2026-11-08 20:00",
89 },
90 {
91 name: "a time that is past",
92 text: "Tell the user the time.",
93 at: new("2026-11-08 20:00"),
94 message: "the time Sunday 2026-11-08 20:00 -03:00 is not after now, Sunday 2026-11-08 20:00 -03:00",
95 },
96 {
97 name: "runs less than 5 minutes apart",
98 text: "Tell the user the time.",
99 cron: new("* * * * *"),
100 message: "at least 5 minutes apart",
101 },
102 }
103
104 for _, tc := range testCases {
105 t.Run(tc.name, func(t *testing.T) {
106 schedules, path := scheduleTestOpen(t)
107
108 _, err := schedules.Set(tc.text, tc.at, tc.cron)
109 require.ErrorContains(t, err, tc.message)
110 require.NoFileExists(t, path)
111 })
112 }
113 }
114
115 func TestSchedulesSurviveARestart(t *testing.T) {
116 schedules, path := scheduleTestOpen(t)
117
118 _, err := schedules.Set("Remind the user to drink water.", new("2026-11-09 09:00"), nil)
119 require.NoError(t, err)
120
121 _, err = schedules.Set("Tell the user the news.", nil, new("0 8 * * 1-5"))
122 require.NoError(t, err)
123
124 _, err = schedules.Remove(1)
125 require.NoError(t, err)
126
127 info, err := os.Stat(path)
128 require.NoError(t, err)
129 require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
130
131 reopened, err := openSchedules(path, schedules.clock)
132 require.NoError(t, err)
133 require.Equal(t, "2 | Monday 2026-11-09 08:00 -03:00 | 0 8 * * 1-5 | Tell the user the news.", reopened.List())
134
135 answer, err := reopened.Set("Remind the user to call.", new("2026-11-08 21:00"), nil)
136 require.NoError(t, err)
137 require.Equal(t, "Schedule 3 set. Next: Sunday 2026-11-08 21:00 -03:00.", answer)
138 }
139
140 func TestSchedulesRemove(t *testing.T) {
141 schedules, _ := scheduleTestOpen(t)
142
143 _, err := schedules.Set("Remind the user to drink water.", new("2026-11-09 09:00"), nil)
144 require.NoError(t, err)
145
146 answer, err := schedules.Remove(1)
147 require.NoError(t, err)
148 require.Equal(t, "Schedule 1 removed.", answer)
149 require.Equal(t, "No schedules.", schedules.List())
150
151 _, err = schedules.Remove(1)
152 require.EqualError(t, err, "no schedule 1")
153 }
154
155 func TestSchedulesDone(t *testing.T) {
156 schedules, _ := scheduleTestOpen(t)
157 start := schedules.clock()
158
159 _, err := schedules.Set("Remind the user to drink water.", new("2026-11-08 21:00"), nil)
160 require.NoError(t, err)
161
162 _, err = schedules.Set("Tell the user the time.", nil, new("0 * * * *"))
163 require.NoError(t, err)
164
165 wait, found := schedules.Wait(start)
166 require.True(t, found)
167 require.Equal(t, time.Hour, wait)
168
169 // The daemon was stopped for three hours, so each schedule missed its
170 // times and runs once.
171 now := start.Add(3*time.Hour + 30*time.Minute)
172 due := schedules.Due(now)
173 require.Len(t, due, 2)
174 for _, schedule := range due {
175 require.NoError(t, schedules.Done(schedule, now))
176 }
177
178 require.Empty(t, schedules.Due(now))
179 require.Equal(t, "2 | Monday 2026-11-09 00:00 -03:00 | 0 * * * * | Tell the user the time.", schedules.List())
180
181 _, err = schedules.Remove(2)
182 require.NoError(t, err)
183 require.NoError(t, schedules.Done(due[1], now))
184 require.Equal(t, "No schedules.", schedules.List())
185
186 _, found = schedules.Wait(now)
187 require.False(t, found)
188 }
189
190 func TestScheduleMessage(t *testing.T) {
191 zone := time.FixedZone("", -3*60*60)
192 due := time.Date(2026, time.November, 9, 9, 0, 0, 0, zone)
193 testCases := []struct {
194 name string
195 schedule Schedule
196 now time.Time
197 message string
198 }{
199 {
200 name: "a one-time run on time",
201 schedule: Schedule{
202 ID: 3,
203 Text: "Remind the user to drink water.",
204 Due: due,
205 },
206 now: due.Add(time.Second),
207 message: "[Schedule 3] Monday 2026-11-09 09:00 -03:00, once\nRemind the user to drink water.\n" + scheduleEmptyReply,
208 },
209 {
210 name: "a late repeating run",
211 schedule: Schedule{
212 ID: 4,
213 Text: "Tell the user the news.",
214 Cron: "0 9 * * 1-5",
215 Due: due,
216 },
217 now: due.Add(2 * time.Hour),
218 message: "[Schedule 4] Monday 2026-11-09 09:00 -03:00, repeats 0 9 * * 1-5\nTell the user the news.\n" + scheduleLateLine + "\n" + scheduleEmptyReply,
219 },
220 }
221
222 for _, tc := range testCases {
223 t.Run(tc.name, func(t *testing.T) {
224 require.Equal(t, tc.message, tc.schedule.Message(tc.now))
225 })
226 }
227 }
228
229 func TestOpenSchedulesRefusesABadCron(t *testing.T) {
230 path := filepath.Join(t.TempDir(), scheduleFileName)
231 require.NoError(t, os.WriteFile(path, []byte(`{"next":1,"schedules":[{"id":1,"text":"x","cron":"* * * * *","due":"2026-11-09T09:00:00-03:00"}]}`), 0o600))
232
233 _, err := openSchedules(path, time.Now)
234 require.ErrorContains(t, err, "schedule 1: the runs of")
235 }
236
237 func TestSchedulesRunStartsATurnWhenDue(t *testing.T) {
238 clock := &ScheduleTestClock{
239 now: time.Date(2026, time.November, 8, 20, 0, 0, 0, time.FixedZone("", -3*60*60)),
240 }
241
242 schedules, err := openSchedules(filepath.Join(t.TempDir(), scheduleFileName), clock.Now)
243 require.NoError(t, err)
244
245 server := newModelFake(t)
246 test := scheduleTestRun(t, schedules, server)
247
248 _, err = schedules.Set("Remind the user to drink water.", new("2026-11-08 20:05"), nil)
249 require.NoError(t, err)
250
251 clock.Set(clock.Now().Add(5 * time.Minute))
252 test.events.WaitFor(t, "idle", 1)
253 require.Equal(t, 1, server.Calls())
254
255 texts := turnInputTexts(t, server.Call(0))
256 require.Equal(t, "[Schedule 1] Sunday 2026-11-08 20:05 -03:00, once\nRemind the user to drink water.\n"+scheduleEmptyReply, texts[len(texts)-1])
257 require.Equal(t, scheduleSource, test.events.LastEvent("work").Source)
258 require.Equal(t, "No schedules.", schedules.List())
259 }
260
261 func TestSchedulesRunMissedSchedulesOnceAtTheStart(t *testing.T) {
262 path := filepath.Join(t.TempDir(), scheduleFileName)
263 require.NoError(t, os.WriteFile(path, []byte(`{"next":2,"schedules":[{"id":1,"text":"Remind the user to call.","cron":"","due":"2026-11-08T09:00:00-03:00"},{"id":2,"text":"Tell the user the time.","cron":"0 * * * *","due":"2026-11-08T10:00:00-03:00"}]}`), 0o600))
264
265 clock := &ScheduleTestClock{
266 now: time.Date(2026, time.November, 8, 20, 30, 0, 0, time.FixedZone("", -3*60*60)),
267 }
268
269 schedules, err := openSchedules(path, clock.Now)
270 require.NoError(t, err)
271
272 server := newModelFake(t)
273 test := scheduleTestRun(t, schedules, server)
274 test.events.WaitFor(t, "idle", 1)
275 require.Equal(t, 1, server.Calls())
276
277 texts := turnInputTexts(t, server.Call(0))
278 require.Equal(t, []string{
279 "[Schedule 1] Sunday 2026-11-08 09:00 -03:00, once\nRemind the user to call.\n" + scheduleLateLine + "\n" + scheduleEmptyReply,
280 "[Schedule 2] Sunday 2026-11-08 10:00 -03:00, repeats 0 * * * *\nTell the user the time.\n" + scheduleLateLine + "\n" + scheduleEmptyReply,
281 }, texts[len(texts)-2:])
282 require.Equal(t, "2 | Sunday 2026-11-08 21:00 -03:00 | 0 * * * * | Tell the user the time.", schedules.List())
283 }
284
285 func TestDaemonRunsADueSchedule(t *testing.T) {
286 clock := &ScheduleTestClock{
287 now: time.Date(2026, time.November, 8, 20, 0, 0, 0, time.FixedZone("", -3*60*60)),
288 }
289
290 schedules, err := openSchedules(filepath.Join(t.TempDir(), scheduleFileName), clock.Now)
291 require.NoError(t, err)
292
293 schedules.check = time.Millisecond
294 whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock())
295 socket, _ := daemonStartTestWithSchedules(t, newModelFake(t), nil, whatsapp, schedules, clock.Now)
296 client := terminalStartTestClient(t, socket)
297 client.WaitFor(t, "[connected to")
298
299 _, err = schedules.Set("Remind the user to drink water.", new("2026-11-08 20:05"), nil)
300 require.NoError(t, err)
301
302 clock.Set(clock.Now().Add(5 * time.Minute))
303 client.WaitFor(t, "[Schedule 1] Sunday 2026-11-08 20:05 -03:00, once\nRemind the user to drink water.\n"+scheduleEmptyReply+"\n[working]\na line\n[done]")
304 }
305
306 func TestToolboxRunsTheScheduleTools(t *testing.T) {
307 schedules, _ := scheduleTestOpen(t)
308 box := &Toolbox{
309 schedules: schedules,
310 }
311
312 require.Equal(t, "Schedule 1 set. Next: Monday 2026-11-09 08:00 -03:00.", box.run(t.Context(), "schedule_set", `{"text":"Tell the user the news.","at":null,"cron":"0 8 * * 1-5"}`))
313 require.Equal(t, "Schedule 2 set. Next: Sunday 2026-11-08 20:02 -03:00.", box.run(t.Context(), "schedule_set", `{"text":"Remind the user to drink water.","at":"2026-11-08 20:02","cron":null}`))
314 require.Equal(t, "2 | Sunday 2026-11-08 20:02 -03:00 | once | Remind the user to drink water.\n1 | Monday 2026-11-09 08:00 -03:00 | 0 8 * * 1-5 | Tell the user the news.", box.run(t.Context(), "schedule_list", `{}`))
315 require.Equal(t, "Schedule 1 removed.", box.run(t.Context(), "schedule_remove", `{"id":1}`))
316 require.Equal(t, "error: no schedule 1", box.run(t.Context(), "schedule_remove", `{"id":1}`))
317 require.Equal(t, "error: give either at or cron, and null for the other", box.run(t.Context(), "schedule_set", `{"text":"x","at":null,"cron":null}`))
318 }
319
320 func TestSubagentHasNoScheduleTools(t *testing.T) {
321 box := &Toolbox{}
322 require.Equal(t, `error: unknown tool "schedule_set"`, box.run(t.Context(), "schedule_set", `{"text":"x","at":"2026-11-09 09:00","cron":null}`))
323 require.Equal(t, `error: unknown tool "schedule_list"`, box.run(t.Context(), "schedule_list", `{}`))
324 require.Equal(t, `error: unknown tool "schedule_remove"`, box.run(t.Context(), "schedule_remove", `{"id":1}`))
325 }
326
327 // ScheduleTestClock is a clock that a test sets while Run reads it.
328 type ScheduleTestClock struct {
329 mutex sync.Mutex
330 now time.Time
331 }
332
333 // Now returns the time of the clock.
334 func (c *ScheduleTestClock) Now() time.Time {
335 c.mutex.Lock()
336 defer c.mutex.Unlock()
337
338 return c.now
339 }
340
341 // Set sets the time of the clock.
342 func (c *ScheduleTestClock) Set(now time.Time) {
343 c.mutex.Lock()
344 defer c.mutex.Unlock()
345
346 c.now = now
347 }
348
349 // scheduleTestOpen opens the schedules of a new file, with a clock at Sunday
350 // 2026-11-08 20:00 -03:00, and returns them and the path of the file.
351 func scheduleTestOpen(t *testing.T) (*Schedules, string) {
352 path := filepath.Join(t.TempDir(), scheduleFileName)
353 clock := &TestClock{
354 now: time.Date(2026, time.November, 8, 20, 0, 0, 0, time.FixedZone("", -3*60*60)),
355 }
356
357 schedules, err := openSchedules(path, clock.Now)
358 require.NoError(t, err)
359
360 return schedules, path
361 }
362
363 // scheduleTestRun runs schedules in a new turn loop that calls server, until
364 // the test ends. Run looks at the times every millisecond.
365 func scheduleTestRun(t *testing.T, schedules *Schedules, server *ModelFake) *TurnTestLoop {
366 t.Helper()
367
368 schedules.check = time.Millisecond
369 test := newTestTurnLoop(t, server)
370 ctx, cancel := context.WithCancel(t.Context())
371 done := make(chan error)
372 go func() {
373 done <- schedules.Run(ctx, test.loop)
374 }()
375
376 t.Cleanup(func() {
377 cancel()
378 require.NoError(t, <-done)
379 })
380
381 return test
382 }