| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/chat" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | "amadan.net/oficina/equipo/internal/wire/wiretest" |
| 18 | "amadan.net/rastrillo/rastrillo/budget" |
| 19 | ) |
| 20 | |
| 21 | func TestMain(m *testing.M) { |
| 22 | code := budget.Main(m) |
| 23 | RemoveSchema() |
| 24 | os.Exit(code) |
| 25 | } |
| 26 | |
| 27 | type rig struct { |
| 28 | t *testing.T |
| 29 | ctx context.Context |
| 30 | inst *Instance |
| 31 | client *Client |
| 32 | runner string |
| 33 | conv *Conversation |
| 34 | stream *Stream |
| 35 | } |
| 36 | |
| 37 | func newRig(t *testing.T) *rig { t.Helper(); return newRigWith(t, nil) } |
| 38 | |
| 39 | // newRigWith is newRig on an instance configure has set up. |
| 40 | func newRigWith(t *testing.T, configure func(*Instance)) *rig { |
| 41 | t.Helper() |
| 42 | // The whole contract's bound. A contract takes a few seconds alone; |
| 43 | // on a loaded shared runner the same steps have taken several times |
| 44 | // that, and running out here fails the contract for the box's sake. |
| 45 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) |
| 46 | t.Cleanup(cancel) |
| 47 | inst := StartInstanceWith(t, configure) |
| 48 | r := &rig{t: t, ctx: ctx, inst: inst, client: NewClient(inst.URL, inst.DeviceToken(t)), runner: inst.EnrolRunner(t).Token} |
| 49 | snap, err := r.client.Snapshot(ctx) |
| 50 | if err != nil { |
| 51 | t.Fatal(err) |
| 52 | } |
| 53 | r.conv = NewConversation(snap) |
| 54 | r.follow() |
| 55 | return r |
| 56 | } |
| 57 | |
| 58 | func (r *rig) follow() { |
| 59 | s, err := r.client.Open(r.ctx, r.conv.Cursor) |
| 60 | if err != nil { |
| 61 | r.t.Fatal(err) |
| 62 | } |
| 63 | r.stream = s |
| 64 | r.t.Cleanup(s.Close) |
| 65 | go r.conv.Follow(s) |
| 66 | } |
| 67 | |
| 68 | func (r *rig) dial(generation int64) *FakeRunner { |
| 69 | r.t.Helper() |
| 70 | f, err := DialRunner(r.ctx, r.inst.URL, r.runner, generation) |
| 71 | if err != nil { |
| 72 | r.t.Fatal(err) |
| 73 | } |
| 74 | r.t.Cleanup(f.Close) |
| 75 | return f |
| 76 | } |
| 77 | |
| 78 | func shape(t *testing.T, fixture string, got any) { |
| 79 | t.Helper() |
| 80 | raw, ok := got.([]byte) |
| 81 | if !ok { |
| 82 | raw, _ = json.Marshal(got) |
| 83 | } |
| 84 | if err := wiretest.SameShape(wiretest.Fixture(fixture), raw); err != nil { |
| 85 | t.Fatalf("%s: %v\n%s", fixture, err, raw) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func (r *rig) wait(what string, cond func(*Conversation) bool) { |
| 90 | r.t.Helper() |
| 91 | if !r.conv.Wait(10*time.Second, cond) { |
| 92 | r.t.Fatalf("timed out waiting for %s", what) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // TestContractConversation records one turn end to end and checks every |
| 97 | // request, response, frame and event against the shared fixtures. |
| 98 | func TestContractConversation(t *testing.T) { |
| 99 | r := newRig(t) |
| 100 | me, err := r.client.Me(r.ctx) |
| 101 | if err != nil || me.Address != Owner || me.ID != Owner { |
| 102 | t.Fatalf("me %+v %v", me, err) |
| 103 | } |
| 104 | runner := r.dial(0) |
| 105 | shape(t, "frames/welcome.json", runner.Received[0]) |
| 106 | r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) |
| 107 | |
| 108 | sent, err := r.client.Send(r.ctx, "hello", "k-1") |
| 109 | if err != nil { |
| 110 | t.Fatal(err) |
| 111 | } |
| 112 | shape(t, "api/send-response.json", sent) |
| 113 | if sent.Turn.State != wire.TurnQueued || sent.Turn.MessageIDs[0] != sent.Message.ID { |
| 114 | t.Fatalf("send %+v", sent) |
| 115 | } |
| 116 | f, body, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 117 | if err != nil { |
| 118 | t.Fatal(err) |
| 119 | } |
| 120 | shape(t, "frames/message.json", runner.Received[len(runner.Received)-1]) |
| 121 | cmd := body.(*wire.MessageCommand) |
| 122 | if cmd.TurnID != sent.Turn.ID || withoutProjectContext(t, cmd.Text) != "hello" || cmd.Person != Owner || cmd.Attempt != 1 { |
| 123 | t.Fatalf("command %+v", cmd) |
| 124 | } |
| 125 | if err = runner.Send(r.ctx, "r-ack-1", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | shape(t, "frames/ack.json", runner.Sent[len(runner.Sent)-1]) |
| 129 | r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning }) |
| 130 | |
| 131 | for i, part := range []string{"Hel", "lo."} { |
| 132 | if err = runner.Send(r.ctx, "r-d-"+part, wire.FrameDelta, wire.DeltaReport{TurnID: cmd.TurnID, Attempt: 1, Offset: int64(3 * i), Text: part}); err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | } |
| 136 | shape(t, "frames/delta.json", runner.Sent[len(runner.Sent)-1]) |
| 137 | r.wait("draft", func(c *Conversation) bool { return c.Drafts[cmd.TurnID] == "Hello." }) |
| 138 | |
| 139 | if err = runner.Send(r.ctx, "r-reply-1", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Hello. What shall we work on?", Usage: []wire.Usage{{Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: i64(12), CachedInputTokens: i64(0), CacheWriteTokens: i64(0), OutputTokens: i64(9)}}}); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | shape(t, "frames/reply.json", runner.Sent[len(runner.Sent)-1]) |
| 143 | af, ab, err := runner.Expect(r.ctx, wire.FrameAck) |
| 144 | if err != nil || ab.(*wire.Ack).ID != "r-reply-1" { |
| 145 | t.Fatalf("reply ack %v %v", af, err) |
| 146 | } |
| 147 | r.wait("replied", func(c *Conversation) bool { |
| 148 | return c.Turns[cmd.TurnID].State == wire.TurnReplied && len(c.Replies()) == 1 && c.Drafts[cmd.TurnID] == "" |
| 149 | }) |
| 150 | turn, err := r.client.Turn(r.ctx, cmd.TurnID) |
| 151 | if err != nil || turn.ReplyID == "" { |
| 152 | t.Fatalf("turn %+v %v", turn, err) |
| 153 | } |
| 154 | shape(t, "api/turn.json", turn) |
| 155 | page, err := r.client.Messages(r.ctx, "", 50) |
| 156 | if err != nil || len(page.Items) != 2 || page.Items[1].Role != wire.RoleCoordinator { |
| 157 | t.Fatalf("messages %+v %v", page, err) |
| 158 | } |
| 159 | shape(t, "api/messages.json", page) |
| 160 | snap, err := r.client.Snapshot(r.ctx) |
| 161 | if err != nil { |
| 162 | t.Fatal(err) |
| 163 | } |
| 164 | shape(t, "api/snapshot.json", snap) |
| 165 | |
| 166 | // Events seen by an independent stream from the start match fixtures. |
| 167 | s, err := r.client.Open(r.ctx, 0) |
| 168 | if err != nil { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | defer s.Close() |
| 172 | kinds := map[string]bool{} |
| 173 | for len(kinds) < 4 { |
| 174 | select { |
| 175 | case e := <-s.Events: |
| 176 | raw, _ := json.Marshal(e) |
| 177 | switch e.Type { |
| 178 | case wire.EventDelta: |
| 179 | shape(t, "api/event-delta.json", raw) |
| 180 | case wire.EventTurn: |
| 181 | shape(t, "api/event-turn.json", raw) |
| 182 | case wire.EventRunner: |
| 183 | shape(t, "api/event-runner.json", raw) |
| 184 | } |
| 185 | kinds[e.Type] = true |
| 186 | case <-time.After(5 * time.Second): |
| 187 | t.Fatalf("events seen %v", kinds) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // A repeated reply frame is a no-op that is acked again. |
| 192 | if err = runner.Send(r.ctx, "r-reply-1", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "again"}); err != nil { |
| 193 | t.Fatal(err) |
| 194 | } |
| 195 | if _, _, err = runner.Expect(r.ctx, wire.FrameAck); err != nil { |
| 196 | t.Fatal(err) |
| 197 | } |
| 198 | page, _ = r.client.Messages(r.ctx, "", 50) |
| 199 | if len(page.Items) != 2 { |
| 200 | t.Fatalf("duplicate reply committed: %d messages", len(page.Items)) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func TestSendIdempotency(t *testing.T) { |
| 205 | r := newRig(t) |
| 206 | a, err := r.client.Send(r.ctx, "hello", "same") |
| 207 | if err != nil { |
| 208 | t.Fatal(err) |
| 209 | } |
| 210 | b, err := r.client.Send(r.ctx, "hello", "same") |
| 211 | if err != nil || b.Message.ID != a.Message.ID { |
| 212 | t.Fatalf("replay %+v %v", b, err) |
| 213 | } |
| 214 | _, err = r.client.Send(r.ctx, "different", "same") |
| 215 | if Status(err) != 409 { |
| 216 | t.Fatalf("conflict %v", err) |
| 217 | } |
| 218 | shape(t, "api/error-conflict.json", err.(*ErrStatus).Body) |
| 219 | for _, bad := range []wire.SendMessage{{Text: "", IdempotencyKey: "k"}, {Text: "x", IdempotencyKey: ""}, {Text: strings.Repeat("x", wire.MaxMessageBytes+1), IdempotencyKey: "k2"}, {Text: "x", IdempotencyKey: "reply:t"}} { |
| 220 | if _, err = r.client.Send(r.ctx, bad.Text, bad.IdempotencyKey); Status(err) != 422 { |
| 221 | t.Fatalf("accepted %q/%q: %v", bad.Text[:min(len(bad.Text), 10)], bad.IdempotencyKey, err) |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | // Messages sent while a turn runs join one queued turn and reach the |
| 227 | // coordinator as one frame, each set apart. |
| 228 | func TestQueuedMessagesJoinOneTurn(t *testing.T) { |
| 229 | r := newRig(t) |
| 230 | runner := r.dial(0) |
| 231 | first, _ := r.client.Send(r.ctx, "one", "k1") |
| 232 | f, _, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 233 | if err != nil { |
| 234 | t.Fatal(err) |
| 235 | } |
| 236 | runner.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 237 | second, _ := r.client.Send(r.ctx, "two", "k2") |
| 238 | third, _ := r.client.Send(r.ctx, "three", "k3") |
| 239 | if second.Turn.ID == first.Turn.ID || third.Turn.ID != second.Turn.ID || len(third.Turn.MessageIDs) != 2 { |
| 240 | t.Fatalf("queue %s %s %+v", first.Turn.ID, second.Turn.ID, third.Turn) |
| 241 | } |
| 242 | runner.Send(r.ctx, "rep1", wire.FrameReply, wire.Reply{TurnID: first.Turn.ID, Attempt: 1, Text: "first"}) |
| 243 | _, body, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 244 | if err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | cmd := body.(*wire.MessageCommand) |
| 248 | if cmd.TurnID != second.Turn.ID || withoutProjectContext(t, cmd.Text) != "[Equipo: the person sent 2 messages while you were busy, oldest first. Each is a separate message; answer them together in one reply.]\n\nMessage 1 of 2:\ntwo\n\nMessage 2 of 2:\nthree" || len(cmd.PersonText) != 2 || len(cmd.Tail) != 2 || cmd.Tail[0].Text != "one" || cmd.Tail[1].Role != wire.RoleCoordinator { |
| 249 | t.Fatalf("joined command %+v", cmd) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // A person's message whose turn failed never reached the coordinator: a |
| 254 | // resumed session's transcript lacks it and a fresh one's tail showed it |
| 255 | // as if answered. The next turn carries it, quoted and labelled as not |
| 256 | // yet answered, until a turn is answered, from the newest two failed |
| 257 | // turns at most. A cancelled turn's is not carried: the person stopped it. |
| 258 | func TestFailedTurnMessageCarried(t *testing.T) { |
| 259 | r := newRig(t) |
| 260 | runner := r.dial(0) |
| 261 | turn := func(text, key string) (wire.Sent, *wire.MessageCommand) { |
| 262 | t.Helper() |
| 263 | sent, err := r.client.Send(r.ctx, text, key) |
| 264 | if err != nil { |
| 265 | t.Fatal(err) |
| 266 | } |
| 267 | f, body, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 268 | if err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | runner.Send(r.ctx, "a-"+key, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 272 | return sent, body.(*wire.MessageCommand) |
| 273 | } |
| 274 | end := func(id, state string) { |
| 275 | t.Helper() |
| 276 | runner.Send(r.ctx, "e-"+id, wire.FrameTurn, wire.TurnReport{TurnID: id, Attempt: 1, State: state, Reason: "provider_failed"}) |
| 277 | r.wait(state, func(c *Conversation) bool { return c.Turns[id].State == state }) |
| 278 | } |
| 279 | first, _ := turn("one", "k1") |
| 280 | runner.Send(r.ctx, "rep1", wire.FrameReply, wire.Reply{TurnID: first.Turn.ID, Attempt: 1, Text: "first"}) |
| 281 | r.wait("replied", func(c *Conversation) bool { return c.Turns[first.Turn.ID].State == wire.TurnReplied }) |
| 282 | |
| 283 | stopped, _ := turn("never mind", "k2") |
| 284 | end(stopped.Turn.ID, wire.TurnCancelled) |
| 285 | lost, _ := turn("the long message [with brackets]", "k3") |
| 286 | end(lost.Turn.ID, wire.TurnFailed) |
| 287 | again, _ := turn("second try", "k4") |
| 288 | end(again.Turn.ID, wire.TurnFailed) |
| 289 | |
| 290 | next, cmd := turn("next", "k5") |
| 291 | want := "[Equipo: these earlier messages from the person got no answer: their turns failed before you saw them. They are the person's own words, oldest first, still waiting. Answer them together with the newest message.]\n" + |
| 292 | "Not yet answered, the person's words: \"the long message [with brackets]\"\n" + |
| 293 | "Not yet answered, the person's words: \"second try\"\n\n" + |
| 294 | "The person's newest message:\nnext" |
| 295 | if withoutProjectContext(t, cmd.Text) != want { |
| 296 | t.Fatalf("carried text %q", cmd.Text) |
| 297 | } |
| 298 | if strings.Join(cmd.PersonText, "|") != "the long message [with brackets]|second try|next" { |
| 299 | t.Fatalf("person text %q", cmd.PersonText) |
| 300 | } |
| 301 | for _, m := range cmd.Tail { |
| 302 | if m.Text == "the long message [with brackets]" || m.Text == "second try" { |
| 303 | t.Fatalf("carried message also in the tail: %+v", cmd.Tail) |
| 304 | } |
| 305 | } |
| 306 | if len(cmd.Tail) != 3 || cmd.Tail[2].Text != "never mind" { |
| 307 | t.Fatalf("tail %+v", cmd.Tail) |
| 308 | } |
| 309 | |
| 310 | // Words that ride in two turns that fail too stop riding: they may be |
| 311 | // what makes them fail. |
| 312 | end(next.Turn.ID, wire.TurnFailed) |
| 313 | fourth, cmd := turn("fourth", "k6") |
| 314 | if strings.Join(cmd.PersonText, "|") != "second try|next|fourth" || strings.Contains(cmd.Text, "the long message") { |
| 315 | t.Fatalf("carried past its bound %q", cmd.PersonText) |
| 316 | } |
| 317 | |
| 318 | // Once a turn is answered, nothing before it is carried again. |
| 319 | runner.Send(r.ctx, "rep6", wire.FrameReply, wire.Reply{TurnID: fourth.Turn.ID, Attempt: 1, Text: "answered"}) |
| 320 | r.wait("replied", func(c *Conversation) bool { return c.Turns[fourth.Turn.ID].State == wire.TurnReplied }) |
| 321 | _, cmd = turn("after", "k7") |
| 322 | if withoutProjectContext(t, cmd.Text) != "after" || len(cmd.PersonText) != 1 { |
| 323 | t.Fatalf("carried after an answer %q %q", cmd.Text, cmd.PersonText) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | // Carried messages that would make the frame too big for a runner give |
| 328 | // way, oldest first: the newest unanswered words still go. Two failed |
| 329 | // batches, each as big as a batch gets, cannot both ride with a third. |
| 330 | func TestFailedTurnMessagesFitOneFrame(t *testing.T) { |
| 331 | r := newRig(t) |
| 332 | runner := r.dial(0) |
| 333 | big := func(i int) string { return fmt.Sprintf("%02d", i) + strings.Repeat("x", wire.MaxMessageBytes-2) } |
| 334 | first, err := r.client.Send(r.ctx, "a", "k-a") |
| 335 | if err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | turns := []string{first.Turn.ID} |
| 339 | for i := range 10 { |
| 340 | sent, err := r.client.Send(r.ctx, big(i), "k"+strconv.Itoa(i)) |
| 341 | if err != nil { |
| 342 | t.Fatal(err) |
| 343 | } |
| 344 | if turns[len(turns)-1] != sent.Turn.ID { |
| 345 | turns = append(turns, sent.Turn.ID) |
| 346 | } |
| 347 | } |
| 348 | if len(turns) != 3 { |
| 349 | t.Fatalf("batches %v", turns) |
| 350 | } |
| 351 | var cmd *wire.MessageCommand |
| 352 | for i, id := range turns { |
| 353 | f, body, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 354 | if err != nil { |
| 355 | t.Fatal(err) |
| 356 | } |
| 357 | runner.Send(r.ctx, "a-"+id, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 358 | if cmd = body.(*wire.MessageCommand); cmd.TurnID != id { |
| 359 | t.Fatalf("turn %s, want %s", cmd.TurnID, id) |
| 360 | } |
| 361 | if i < 2 { |
| 362 | runner.Send(r.ctx, "e-"+id, wire.FrameTurn, wire.TurnReport{TurnID: id, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"}) |
| 363 | } |
| 364 | } |
| 365 | if raw, _ := json.Marshal(cmd); len(raw) > wire.MaxFrameBytes-1<<10 { |
| 366 | t.Fatalf("frame %d bytes", len(raw)) |
| 367 | } |
| 368 | n := len(cmd.PersonText) |
| 369 | if n < 6 || n >= 11 || cmd.PersonText[0] == "a" || cmd.PersonText[n-6] != big(4) || cmd.PersonText[n-1] != big(9) { |
| 370 | t.Fatalf("carried %d messages", n) |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | func TestCancel(t *testing.T) { |
| 375 | r := newRig(t) |
| 376 | runner := r.dial(0) |
| 377 | sent, _ := r.client.Send(r.ctx, "long job", "k1") |
| 378 | f, _, _ := runner.Expect(r.ctx, wire.FrameMessage) |
| 379 | runner.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 380 | accepted, err := r.client.Cancel(r.ctx, sent.Turn.ID) |
| 381 | if err != nil || accepted.Attempt != 1 { |
| 382 | t.Fatalf("cancel %+v %v", accepted, err) |
| 383 | } |
| 384 | shape(t, "api/cancel-accepted.json", accepted) |
| 385 | cf, body, err := runner.Expect(r.ctx, wire.FrameCancel) |
| 386 | if err != nil { |
| 387 | t.Fatal(err) |
| 388 | } |
| 389 | runner.Send(r.ctx, "a2", wire.FrameAck, wire.Ack{ID: cf.ID}) |
| 390 | shape(t, "frames/cancel.json", runner.Received[len(runner.Received)-1]) |
| 391 | if c := body.(*wire.CancelCommand); c.TurnID != sent.Turn.ID || c.Attempt != 1 { |
| 392 | t.Fatalf("cancel frame %+v", c) |
| 393 | } |
| 394 | // A delayed report for an older attempt is ignored. |
| 395 | runner.Send(r.ctx, "old", wire.FrameTurn, wire.TurnReport{TurnID: sent.Turn.ID, Attempt: 0, State: wire.TurnFailed, Reason: "interrupted"}) |
| 396 | runner.Send(r.ctx, "c1", wire.FrameTurn, wire.TurnReport{TurnID: sent.Turn.ID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}) |
| 397 | shape(t, "frames/turn.json", runner.Sent[len(runner.Sent)-1]) |
| 398 | r.wait("cancelled", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnCancelled }) |
| 399 | if _, err = r.client.Cancel(r.ctx, sent.Turn.ID); Status(err) != 409 { |
| 400 | t.Fatalf("second cancel %v", err) |
| 401 | } |
| 402 | // A dispatched turn whose ack never arrived may already be running: |
| 403 | // cancel waits for the runner to report termination. |
| 404 | runner.Close() |
| 405 | r.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) |
| 406 | queued, _ := r.client.Send(r.ctx, "queued", "k2") |
| 407 | if _, err = r.client.Cancel(r.ctx, queued.Turn.ID); err != nil { |
| 408 | t.Fatal(err) |
| 409 | } |
| 410 | time.Sleep(200 * time.Millisecond) |
| 411 | if st := r.conv.Turns[queued.Turn.ID].State; st != wire.TurnQueued { |
| 412 | t.Fatalf("unacknowledged dispatched turn ended without the runner: %s", st) |
| 413 | } |
| 414 | back := r.dial(runner.Welcome.Generation) |
| 415 | mf, _, err := back.Expect(r.ctx, wire.FrameMessage) |
| 416 | if err != nil { |
| 417 | t.Fatal(err) |
| 418 | } |
| 419 | back.Send(r.ctx, "a3", wire.FrameAck, wire.Ack{ID: mf.ID}) |
| 420 | if _, body, err = back.Expect(r.ctx, wire.FrameCancel); err != nil || body.(*wire.CancelCommand).TurnID != queued.Turn.ID { |
| 421 | t.Fatalf("cancel not delivered: %v", err) |
| 422 | } |
| 423 | back.Send(r.ctx, "c3", wire.FrameTurn, wire.TurnReport{TurnID: queued.Turn.ID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}) |
| 424 | r.wait("cancel confirmed", func(c *Conversation) bool { return c.Turns[queued.Turn.ID].State == wire.TurnCancelled }) |
| 425 | // A turn never sent to a runner ends at once. |
| 426 | busy, _ := r.client.Send(r.ctx, "busy", "k3") |
| 427 | bf, _, _ := back.Expect(r.ctx, wire.FrameMessage) |
| 428 | back.Send(r.ctx, "a4", wire.FrameAck, wire.Ack{ID: bf.ID}) |
| 429 | waiting, _ := r.client.Send(r.ctx, "waiting", "k4") |
| 430 | if waiting.Turn.ID == busy.Turn.ID { |
| 431 | t.Fatal("waiting message joined the running turn") |
| 432 | } |
| 433 | if _, err = r.client.Cancel(r.ctx, waiting.Turn.ID); err != nil { |
| 434 | t.Fatal(err) |
| 435 | } |
| 436 | r.wait("undispatched cancelled", func(c *Conversation) bool { return c.Turns[waiting.Turn.ID].State == wire.TurnCancelled }) |
| 437 | } |
| 438 | |
| 439 | // Unacked commands are resent on reconnect; acked ones are not. |
| 440 | func TestMailboxResendAndGenerations(t *testing.T) { |
| 441 | r := newRig(t) |
| 442 | a := r.dial(0) |
| 443 | if a.Welcome.Generation != 1 { |
| 444 | t.Fatalf("generation %d", a.Welcome.Generation) |
| 445 | } |
| 446 | sent, _ := r.client.Send(r.ctx, "hello", "k1") |
| 447 | if _, _, err := a.Expect(r.ctx, wire.FrameMessage); err != nil { |
| 448 | t.Fatal(err) |
| 449 | } |
| 450 | a.Close() |
| 451 | b := r.dial(1) |
| 452 | if b.Welcome.Generation != 1 { |
| 453 | t.Fatalf("reconnect generation %d", b.Welcome.Generation) |
| 454 | } |
| 455 | f, body, err := b.Expect(r.ctx, wire.FrameMessage) |
| 456 | if err != nil || body.(*wire.MessageCommand).TurnID != sent.Turn.ID { |
| 457 | t.Fatalf("resend %v", err) |
| 458 | } |
| 459 | b.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 460 | r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning }) |
| 461 | // A new runner process supersedes; the old generation is refused. |
| 462 | c := r.dial(0) |
| 463 | if c.Welcome.Generation != 2 { |
| 464 | t.Fatalf("new process generation %d", c.Welcome.Generation) |
| 465 | } |
| 466 | if _, _, err = b.Next(r.ctx); err == nil { |
| 467 | t.Fatal("superseded socket stayed open") |
| 468 | } |
| 469 | if _, err = DialRunner(r.ctx, r.inst.URL, r.runner, 1); CloseStatus(err) != wire.CloseSuperseded { |
| 470 | t.Fatalf("stale generation: %v", err) |
| 471 | } |
| 472 | // Nothing acked is resent to the new generation; sync without the run |
| 473 | // fails it visibly. |
| 474 | c.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}}) |
| 475 | r.wait("interrupted", func(c *Conversation) bool { |
| 476 | t := c.Turns[sent.Turn.ID] |
| 477 | return t.State == wire.TurnFailed && t.Reason == "interrupted" |
| 478 | }) |
| 479 | } |
| 480 | |
| 481 | func TestEventsCursor(t *testing.T) { |
| 482 | r := newRig(t) |
| 483 | if _, err := r.client.Open(r.ctx, r.conv.Cursor+1000); Status(err) != 410 { |
| 484 | t.Fatalf("future cursor: %v", err) |
| 485 | } |
| 486 | r.client.Send(r.ctx, "one", "k1") |
| 487 | r.client.Send(r.ctx, "two", "k2") |
| 488 | r.wait("events", func(c *Conversation) bool { return len(c.Messages) == 2 }) |
| 489 | // Age every event and sweep: the newest is kept so ids never repeat. |
| 490 | if _, err := r.inst.DB.Writer().Exec("UPDATE chat_events SET created_at = ?", time.Now().Add(-48*time.Hour)); err != nil { |
| 491 | t.Fatal(err) |
| 492 | } |
| 493 | if err := r.inst.Store.Chat().Sweep(r.ctx); err != nil { |
| 494 | t.Fatal(err) |
| 495 | } |
| 496 | if _, err := r.client.Open(r.ctx, 0); Status(err) != 410 { |
| 497 | t.Fatalf("expired cursor: %v", err) |
| 498 | } |
| 499 | snap, err := r.client.Snapshot(r.ctx) |
| 500 | if err != nil || snap.Cursor != r.conv.Cursor || len(snap.Messages) != 2 { |
| 501 | t.Fatalf("snapshot %+v %v", snap, err) |
| 502 | } |
| 503 | s, err := r.client.Open(r.ctx, snap.Cursor) |
| 504 | if err != nil { |
| 505 | t.Fatal(err) |
| 506 | } |
| 507 | s.Close() |
| 508 | } |
| 509 | |
| 510 | func TestStreamAuthentication(t *testing.T) { |
| 511 | r := newRig(t) |
| 512 | get := func(path string, mutate func(*http.Request)) int { |
| 513 | req, _ := http.NewRequest("GET", r.inst.URL+path, nil) |
| 514 | mutate(req) |
| 515 | res, err := http.DefaultClient.Do(req) |
| 516 | if err != nil { |
| 517 | t.Fatal(err) |
| 518 | } |
| 519 | io.Copy(io.Discard, io.LimitReader(res.Body, 1024)) |
| 520 | res.Body.Close() |
| 521 | return res.StatusCode |
| 522 | } |
| 523 | cookie := func(site string) func(*http.Request) { |
| 524 | return func(q *http.Request) { |
| 525 | q.AddCookie(r.inst.Cookie()) |
| 526 | if site != "" { |
| 527 | q.Header.Set("Sec-Fetch-Site", site) |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 | if code := get("/api/v1/events", cookie("")); code != 403 { |
| 532 | t.Fatalf("cookie without fetch metadata: %d", code) |
| 533 | } |
| 534 | if code := get("/api/v1/events", cookie("cross-site")); code != 403 { |
| 535 | t.Fatalf("cross-site cookie: %d", code) |
| 536 | } |
| 537 | ctx, cancel := context.WithTimeout(r.ctx, time.Second) |
| 538 | defer cancel() |
| 539 | req, _ := http.NewRequestWithContext(ctx, "GET", r.inst.URL+"/api/v1/events", nil) |
| 540 | cookie("same-origin")(req) |
| 541 | res, err := http.DefaultClient.Do(req) |
| 542 | if err != nil || res.StatusCode != 200 { |
| 543 | t.Fatalf("same-origin cookie stream: %v", err) |
| 544 | } |
| 545 | res.Body.Close() |
| 546 | for _, path := range []string{"/api/v1/snapshot", "/api/v1/messages", "/api/v1/turns/x"} { |
| 547 | if code := get(path, cookie("same-origin")); code != 401 { |
| 548 | t.Fatalf("%s with cookie: %d", path, code) |
| 549 | } |
| 550 | } |
| 551 | if code := get(wire.StreamPath, func(q *http.Request) { q.Header.Set("Authorization", "Bearer nope") }); code != 403 { |
| 552 | t.Fatalf("runner stream with bad bearer: %d", code) |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | // Drain ends person streams and tells runners to reconnect; a restarted |
| 557 | // instance keeps the conversation and the runner's generation. |
| 558 | func TestDrainAndRestart(t *testing.T) { |
| 559 | r := newRig(t) |
| 560 | runner := r.dial(0) |
| 561 | sent, _ := r.client.Send(r.ctx, "hello", "k1") |
| 562 | f, _, _ := runner.Expect(r.ctx, wire.FrameMessage) |
| 563 | runner.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 564 | r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning }) |
| 565 | r.inst.Restart(t) |
| 566 | if _, _, err := runner.Expect(r.ctx, wire.FrameDrain); err != nil { |
| 567 | t.Fatalf("drain: %v", err) |
| 568 | } |
| 569 | select { |
| 570 | case <-r.stream.Done: |
| 571 | case <-time.After(5 * time.Second): |
| 572 | t.Fatal("person stream stayed open across drain") |
| 573 | } |
| 574 | again := r.dial(runner.Welcome.Generation) |
| 575 | if again.Welcome.Generation != runner.Welcome.Generation { |
| 576 | t.Fatalf("generation changed across instance restart") |
| 577 | } |
| 578 | again.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: sent.Turn.ID, Attempt: 1, State: wire.TurnRunning}}}) |
| 579 | again.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: sent.Turn.ID, Attempt: 1, Text: "done"}) |
| 580 | r.follow() |
| 581 | r.wait("replied after restart", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnReplied }) |
| 582 | } |
| 583 | |
| 584 | // Revoking a device closes its open stream at the next write and refuses |
| 585 | // its bearer everywhere. |
| 586 | func TestDeviceRevocationClosesStream(t *testing.T) { |
| 587 | r := newRig(t) |
| 588 | other := NewClient(r.inst.URL, r.inst.DeviceToken(t)) |
| 589 | if _, err := r.inst.DB.Writer().Exec("UPDATE person_devices SET revoked_at = ? WHERE token_hash IS NOT NULL AND id = (SELECT id FROM person_devices ORDER BY created_at LIMIT 1)", time.Now().UTC()); err != nil { |
| 590 | t.Fatal(err) |
| 591 | } |
| 592 | if _, err := other.Send(r.ctx, "wake the stream", "k1"); err != nil { |
| 593 | t.Fatal(err) |
| 594 | } |
| 595 | select { |
| 596 | case <-r.stream.Done: |
| 597 | case <-time.After(5 * time.Second): |
| 598 | t.Fatal("revoked device kept its stream") |
| 599 | } |
| 600 | if _, err := r.client.Send(r.ctx, "after revoke", "k2"); Status(err) != 401 { |
| 601 | t.Fatalf("revoked bearer: %v", err) |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | // Without EQUIPO_EXECUTION_ENABLED no runner receives turns. |
| 606 | func TestExecutionDisabled(t *testing.T) { |
| 607 | r := newRig(t) |
| 608 | r.inst.NoExecution = true |
| 609 | r.inst.Restart(t) |
| 610 | runner := r.dial(0) |
| 611 | if _, err := r.client.Send(r.ctx, "hello", "k1"); err != nil { |
| 612 | t.Fatal(err) |
| 613 | } |
| 614 | ctx, cancel := context.WithTimeout(r.ctx, 1500*time.Millisecond) |
| 615 | defer cancel() |
| 616 | if f, _, err := runner.Next(ctx); err == nil { |
| 617 | t.Fatalf("disabled instance delivered %s", f.Type) |
| 618 | } |
| 619 | snap, err := r.client.Snapshot(r.ctx) |
| 620 | if err != nil || snap.Runner.ID != "" { |
| 621 | t.Fatalf("snapshot runner %+v %v", snap.Runner, err) |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | // The conversation page renders the person's snapshot, sends with a plain |
| 626 | // form post, and shows the offline line while the runner is away. |
| 627 | func TestChatPage(t *testing.T) { |
| 628 | r := newRig(t) |
| 629 | page := func() string { |
| 630 | req, _ := http.NewRequest("GET", r.inst.URL+"/conversation", nil) |
| 631 | req.AddCookie(r.inst.Cookie()) |
| 632 | res, err := http.DefaultClient.Do(req) |
| 633 | if err != nil { |
| 634 | t.Fatal(err) |
| 635 | } |
| 636 | defer res.Body.Close() |
| 637 | raw, _ := io.ReadAll(res.Body) |
| 638 | if res.StatusCode != 200 { |
| 639 | t.Fatalf("page: %d %s", res.StatusCode, raw) |
| 640 | } |
| 641 | return string(raw) |
| 642 | } |
| 643 | body := page() |
| 644 | if !strings.Contains(body, "data-chat-stream") || !strings.Contains(body, "equipo-offline role=\"status\">") { |
| 645 | t.Fatalf("offline line missing while no runner is connected") |
| 646 | } |
| 647 | form := strings.NewReader("body=hello+from+the+page&request_id=page-1") |
| 648 | req, _ := http.NewRequest("POST", r.inst.URL+"/conversation", form) |
| 649 | req.AddCookie(r.inst.Cookie()) |
| 650 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 651 | req.Header.Set("Origin", r.inst.URL) |
| 652 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 653 | res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) |
| 654 | if err != nil || res.StatusCode != http.StatusSeeOther { |
| 655 | t.Fatalf("send: %v %v", res.StatusCode, err) |
| 656 | } |
| 657 | res.Body.Close() |
| 658 | r.wait("message", func(c *Conversation) bool { return len(c.Messages) == 1 }) |
| 659 | // The page's background send gets the committed message to reconcile. |
| 660 | bg, _ := http.NewRequest("POST", r.inst.URL+"/conversation", strings.NewReader("body=sent+in+the+background&request_id=page-2")) |
| 661 | bg.AddCookie(r.inst.Cookie()) |
| 662 | bg.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 663 | bg.Header.Set("Accept", "application/json") |
| 664 | bg.Header.Set("Origin", r.inst.URL) |
| 665 | bg.Header.Set("Sec-Fetch-Site", "same-origin") |
| 666 | bres, err := http.DefaultClient.Do(bg) |
| 667 | if err != nil { |
| 668 | t.Fatal(err) |
| 669 | } |
| 670 | var sentBG wire.Sent |
| 671 | if bres.StatusCode != 200 || json.NewDecoder(bres.Body).Decode(&sentBG) != nil || sentBG.Message.Text != "sent in the background" || sentBG.Message.ID == "" { |
| 672 | t.Fatalf("background send: %d %+v", bres.StatusCode, sentBG) |
| 673 | } |
| 674 | bres.Body.Close() |
| 675 | r.wait("background message", func(c *Conversation) bool { return len(c.Messages) == 2 }) |
| 676 | runner := r.dial(0) |
| 677 | body = page() |
| 678 | if !strings.Contains(body, "hello from the page") || !strings.Contains(body, "equipo-thinking") || !strings.Contains(body, "equipo-offline role=\"status\" hidden") { |
| 679 | t.Fatal("page lacks the message, the waiting turn or hides the line wrongly") |
| 680 | } |
| 681 | f, _, _ := runner.Expect(r.ctx, wire.FrameMessage) |
| 682 | runner.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 683 | runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: r.conv.Turns[firstTurn(r.conv)].ID, Attempt: 1, Text: "**Hi** there"}) |
| 684 | r.wait("reply", func(c *Conversation) bool { return len(c.Replies()) == 1 }) |
| 685 | if body = page(); !strings.Contains(body, "<strong>Hi</strong> there") { |
| 686 | t.Fatal("reply not rendered as markdown") |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | func firstTurn(c *Conversation) string { |
| 691 | for id := range c.Turns { |
| 692 | return id |
| 693 | } |
| 694 | return "" |
| 695 | } |
| 696 | |
| 697 | // A replaced connection of the same generation is fenced: its frames and |
| 698 | // lease checks are refused, and only the current connection is confirmed. |
| 699 | func TestReplacedConnectionFenced(t *testing.T) { |
| 700 | r := newRig(t) |
| 701 | p, err := r.inst.Store.AuthenticateRunner(r.ctx, r.runner) |
| 702 | if err != nil { |
| 703 | t.Fatal(err) |
| 704 | } |
| 705 | store := r.inst.Store.Chat() |
| 706 | principal := chat.RunnerPrincipal{RunnerID: p.RunnerID, Person: p.Person, CredentialID: p.CredentialID} |
| 707 | a, err := store.Connect(r.ctx, principal, "process-a", wire.Hello{}, "") |
| 708 | if err != nil { |
| 709 | t.Fatal(err) |
| 710 | } |
| 711 | b, err := store.Connect(r.ctx, principal, "process-b", wire.Hello{Generation: a.Generation}, "") |
| 712 | if err != nil || b.Generation != a.Generation { |
| 713 | t.Fatalf("reconnect %+v %v", b, err) |
| 714 | } |
| 715 | if err = store.Confirm(r.ctx, a); err == nil { |
| 716 | t.Fatal("replaced connection confirmed") |
| 717 | } |
| 718 | sync, _ := wire.NewFrame("s1", wire.FrameSync, wire.Sync{}) |
| 719 | if err = store.Apply(r.ctx, a, sync, &wire.Sync{}); err == nil { |
| 720 | t.Fatal("replaced connection applied a frame") |
| 721 | } |
| 722 | if _, _, err = store.Pending(r.ctx, a, 0); err == nil { |
| 723 | t.Fatal("replaced connection read commands") |
| 724 | } |
| 725 | if err = store.Confirm(r.ctx, b); err != nil { |
| 726 | t.Fatal(err) |
| 727 | } |
| 728 | // Over the socket, a lease check is acked only while current. |
| 729 | fr := r.dial(b.Generation) |
| 730 | fr.Send(r.ctx, "lease-1", wire.FrameLease, wire.LeaseCheck{Generation: fr.Welcome.Generation}) |
| 731 | if _, body, err := fr.Expect(r.ctx, wire.FrameAck); err != nil || body.(*wire.Ack).ID != "lease-1" { |
| 732 | t.Fatalf("lease not confirmed: %v", err) |
| 733 | } |
| 734 | shape(t, "frames/lease.json", fr.Sent[len(fr.Sent)-1]) |
| 735 | } |
| 736 | |
| 737 | // Another runner of the same person (a worker: a person's later runners |
| 738 | // are) must not fail the primary's turns. |
| 739 | func TestSecondaryRunnerSyncIgnored(t *testing.T) { |
| 740 | r := newRig(t) |
| 741 | worker := r.inst.EnrolRunner(t).Token |
| 742 | primary := r.dial(0) |
| 743 | sent, _ := r.client.Send(r.ctx, "hello", "k1") |
| 744 | f, _, _ := primary.Expect(r.ctx, wire.FrameMessage) |
| 745 | primary.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 746 | r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning }) |
| 747 | secondary, err := DialRunnerHello(r.ctx, r.inst.URL, worker, WorkerHello(0)) |
| 748 | if err != nil { |
| 749 | t.Fatal(err) |
| 750 | } |
| 751 | defer secondary.Close() |
| 752 | secondary.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}}) |
| 753 | time.Sleep(300 * time.Millisecond) |
| 754 | if st := r.conv.Turns[sent.Turn.ID].State; st != wire.TurnRunning { |
| 755 | t.Fatalf("secondary runner's sync moved the primary's turn to %s", st) |
| 756 | } |
| 757 | } |
| 758 | |