| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | // dialAt connects the owner's runner as a Linux primary speaking protocol. |
| 19 | func (r *rig) dialAt(protocol int) *FakeRunner { |
| 20 | r.t.Helper() |
| 21 | f, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, primaryAt(wire.Hello{Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, protocol)) |
| 22 | if err != nil { |
| 23 | r.t.Fatal(err) |
| 24 | } |
| 25 | r.t.Cleanup(f.Close) |
| 26 | r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online && c.Runner.Revision > 0 }) |
| 27 | return f |
| 28 | } |
| 29 | |
| 30 | // newAssistRig is a rig whose owner's primary speaks the Assistant's |
| 31 | // protocol. |
| 32 | func newAssistRig(t *testing.T) (*rig, *FakeRunner) { |
| 33 | r := newRig(t) |
| 34 | return r, r.dialAt(wire.ProtocolAssistant) |
| 35 | } |
| 36 | |
| 37 | // assistEvents reads the Assistant stream until cond holds of the events |
| 38 | // so far, or fails. |
| 39 | func assistEvents(t *testing.T, s *Stream, what string, seen *[]wire.Event, cond func([]wire.Event) bool) { |
| 40 | t.Helper() |
| 41 | deadline := time.After(10 * time.Second) |
| 42 | for !cond(*seen) { |
| 43 | select { |
| 44 | case e, ok := <-s.Events: |
| 45 | if !ok { |
| 46 | t.Fatalf("assistant stream ended waiting for %s", what) |
| 47 | } |
| 48 | *seen = append(*seen, e) |
| 49 | case <-deadline: |
| 50 | t.Fatalf("timed out waiting for %s; saw %d events", what, len(*seen)) |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // eventFor finds the index of the first event of kind about id (-1). |
| 56 | func eventFor(events []wire.Event, kind, id string, match func(json.RawMessage) bool) int { |
| 57 | return slices.IndexFunc(events, func(e wire.Event) bool { |
| 58 | return e.Type == kind && e.ID == id && (match == nil || match(e.Data)) |
| 59 | }) |
| 60 | } |
| 61 | |
| 62 | // raw sends a request with optional bearer and cookie and returns the |
| 63 | // status, headers and body. |
| 64 | func raw(t *testing.T, method, url, token string, cookie *http.Cookie, body string) (int, http.Header, []byte) { |
| 65 | t.Helper() |
| 66 | var reader io.Reader |
| 67 | if body != "" { |
| 68 | reader = strings.NewReader(body) |
| 69 | } |
| 70 | req, _ := http.NewRequest(method, url, reader) |
| 71 | if body != "" { |
| 72 | req.Header.Set("Content-Type", "application/json") |
| 73 | } |
| 74 | if token != "" { |
| 75 | req.Header.Set("Authorization", "Bearer "+token) |
| 76 | } |
| 77 | if cookie != nil { |
| 78 | req.AddCookie(cookie) |
| 79 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 80 | req.Header.Set("Origin", strings.TrimSuffix(url[:strings.Index(url, "/api/")], "/")) |
| 81 | } |
| 82 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 83 | defer cancel() |
| 84 | res, err := http.DefaultClient.Do(req.WithContext(ctx)) |
| 85 | if err != nil { |
| 86 | t.Fatal(err) |
| 87 | } |
| 88 | defer res.Body.Close() |
| 89 | out, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16)) |
| 90 | return res.StatusCode, res.Header, out |
| 91 | } |
| 92 | |
| 93 | // TestContractAssistantConversation: an Assistant message reaches the |
| 94 | // runner in its lane, its reply comes back on the Assistant stream as an |
| 95 | // assistant message, and nothing of it reaches the Coordinator's routes. |
| 96 | func TestContractAssistantConversation(t *testing.T) { |
| 97 | r, runner := newAssistRig(t) |
| 98 | a := r.client.Assistant() |
| 99 | snap, err := a.Snapshot(r.ctx) |
| 100 | if err != nil || !snap.Available || len(snap.Messages) != 0 || len(snap.Turns) != 0 || snap.Cards == nil || snap.Me.Address != Owner { |
| 101 | t.Fatalf("first snapshot %+v %v", snap, err) |
| 102 | } |
| 103 | s, err := a.Open(r.ctx, snap.Cursor) |
| 104 | if err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | defer s.Close() |
| 108 | |
| 109 | status, header, body := raw(t, "POST", r.inst.URL+"/api/v1/assistant/messages", r.client.Token, nil, `{"text":"hello assistant","idempotency_key":"a-1"}`) |
| 110 | if status != http.StatusCreated || header.Get("Cache-Control") != "no-store" { |
| 111 | t.Fatalf("send %d %q %s", status, header.Get("Cache-Control"), body) |
| 112 | } |
| 113 | var sent wire.Sent |
| 114 | if err := json.Unmarshal(body, &sent); err != nil || sent.Message.Role != wire.RolePerson || sent.Turn.Kind != "" || sent.Turn.ID == "" { |
| 115 | t.Fatalf("sent %+v %v", sent, err) |
| 116 | } |
| 117 | // The same key and text answer 200 with the same message; other text |
| 118 | // is a conflict. |
| 119 | if status, _, body = raw(t, "POST", r.inst.URL+"/api/v1/assistant/messages", r.client.Token, nil, `{"text":"hello assistant","idempotency_key":"a-1"}`); status != http.StatusOK || !bytes.Contains(body, []byte(sent.Message.ID)) { |
| 120 | t.Fatalf("replay %d %s", status, body) |
| 121 | } |
| 122 | if _, err = a.Send(r.ctx, "something else", "a-1"); Status(err) != http.StatusConflict { |
| 123 | t.Fatalf("conflict %v", err) |
| 124 | } |
| 125 | // Files need a runner on protocol 33 (assistant attachments spec A1); |
| 126 | // this one speaks 19, so nothing is stored. |
| 127 | if status, _, body = raw(t, "POST", r.inst.URL+"/api/v1/assistant/messages", r.client.Token, nil, `{"text":"with a file","idempotency_key":"a-2","attachments":["at_x"]}`); status != http.StatusConflict || !bytes.Contains(body, []byte(`"attachments_unavailable"`)) { |
| 128 | t.Fatalf("attachments %d %s", status, body) |
| 129 | } |
| 130 | |
| 131 | f, frame, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 132 | if err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | cmd := frame.(*wire.MessageCommand) |
| 136 | if cmd.Lane != wire.LaneAssistant || cmd.TurnID != sent.Turn.ID || cmd.Text != "hello assistant" || cmd.Person != Owner || !slices.Equal(cmd.PersonText, []string{"hello assistant"}) { |
| 137 | t.Fatalf("command %+v", cmd) |
| 138 | } |
| 139 | if err = runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | if err = runner.Send(r.ctx, "a-delta", wire.FrameDelta, wire.DeltaReport{TurnID: cmd.TurnID, Attempt: 1, Offset: 0, Text: "Hi"}); err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | if err = runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Hi there."}); err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | var seen []wire.Event |
| 149 | replied := func(d json.RawMessage) bool { |
| 150 | var v wire.Turn |
| 151 | return json.Unmarshal(d, &v) == nil && v.State == wire.TurnReplied |
| 152 | } |
| 153 | assistEvents(t, s, "the reply", &seen, func(es []wire.Event) bool { return eventFor(es, wire.EventTurn, cmd.TurnID, replied) >= 0 }) |
| 154 | delta := slices.IndexFunc(seen, func(e wire.Event) bool { return e.Type == wire.EventDelta && e.TurnID == cmd.TurnID }) |
| 155 | reply := slices.IndexFunc(seen, func(e wire.Event) bool { |
| 156 | var m wire.Message |
| 157 | return e.Type == wire.EventMessage && json.Unmarshal(e.Data, &m) == nil && m.Role == wire.RoleAssistant && m.Text == "Hi there." && m.TurnID == cmd.TurnID |
| 158 | }) |
| 159 | if delta < 0 || reply < delta { |
| 160 | t.Fatalf("delta %d then reply %d: %+v", delta, reply, seen) |
| 161 | } |
| 162 | |
| 163 | snap, err = a.Snapshot(r.ctx) |
| 164 | if err != nil || len(snap.Messages) != 2 || snap.Messages[0].Role != wire.RolePerson || snap.Messages[1].Role != wire.RoleAssistant || len(snap.Turns) != 1 || snap.Turns[0].State != wire.TurnReplied { |
| 165 | t.Fatalf("assistant snapshot %+v %v", snap, err) |
| 166 | } |
| 167 | page, err := a.Messages(r.ctx, "", 50) |
| 168 | if err != nil || len(page.Items) != 2 { |
| 169 | t.Fatalf("assistant messages %+v %v", page, err) |
| 170 | } |
| 171 | if _, err = a.Messages(r.ctx, "", 201); Status(err) != 422 { |
| 172 | t.Fatalf("limit 201 %v", err) |
| 173 | } |
| 174 | |
| 175 | // The Coordinator's routes never show it. A Coordinator message after |
| 176 | // it shows the stream has passed every Assistant event. |
| 177 | coord, err := r.client.Send(r.ctx, "to the coordinator", "c-1") |
| 178 | if err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | cs, err := r.client.Open(r.ctx, 0) |
| 182 | if err != nil { |
| 183 | t.Fatal(err) |
| 184 | } |
| 185 | defer cs.Close() |
| 186 | var coordSeen []wire.Event |
| 187 | assistEvents(t, cs, "the coordinator message", &coordSeen, func(es []wire.Event) bool { return eventFor(es, wire.EventMessage, coord.Message.ID, nil) >= 0 }) |
| 188 | for _, e := range coordSeen { |
| 189 | if e.TurnID == cmd.TurnID || e.ID == sent.Message.ID || e.ID == cmd.TurnID || bytes.Contains(e.Data, []byte("hello assistant")) || bytes.Contains(e.Data, []byte("Hi there.")) { |
| 190 | t.Fatalf("an Assistant event on /api/v1/events: %+v", e) |
| 191 | } |
| 192 | } |
| 193 | csnap, err := r.client.Snapshot(r.ctx) |
| 194 | if err != nil || len(csnap.Messages) != 1 || csnap.Messages[0].ID != coord.Message.ID || slices.ContainsFunc(csnap.Turns, func(v wire.Turn) bool { return v.ID == cmd.TurnID }) { |
| 195 | t.Fatalf("coordinator snapshot %+v %v", csnap, err) |
| 196 | } |
| 197 | cpage, err := r.client.Messages(r.ctx, "", 50) |
| 198 | if err != nil || len(cpage.Items) != 1 { |
| 199 | t.Fatalf("coordinator messages %+v %v", cpage, err) |
| 200 | } |
| 201 | if _, err = r.client.Turn(r.ctx, cmd.TurnID); Status(err) != 404 { |
| 202 | t.Fatalf("an Assistant turn on /api/v1/turns: %v", err) |
| 203 | } |
| 204 | // The Coordinator's own message never reaches the Assistant's routes. |
| 205 | if page, _ = a.Messages(r.ctx, "", 50); len(page.Items) != 2 { |
| 206 | t.Fatalf("assistant messages after a coordinator one %+v", page) |
| 207 | } |
| 208 | // A Coordinator cursor on the Assistant's route is the other lane's id |
| 209 | // (404). On the Coordinator's route an Assistant cursor is, as before |
| 210 | // lanes, an id it does not have (422); so is one nobody has. |
| 211 | if _, err = a.Messages(r.ctx, coord.Message.ID, 50); Status(err) != 404 { |
| 212 | t.Fatalf("a coordinator message as the Assistant's cursor: %v", err) |
| 213 | } |
| 214 | if _, err = r.client.Messages(r.ctx, sent.Message.ID, 50); Status(err) != 422 { |
| 215 | t.Fatalf("an Assistant message as the Coordinator's cursor: %v", err) |
| 216 | } |
| 217 | for _, c := range []*AssistantClient{a, nil} { |
| 218 | var err error |
| 219 | if c != nil { |
| 220 | _, err = c.Messages(r.ctx, "m_nothing", 50) |
| 221 | } else { |
| 222 | _, err = r.client.Messages(r.ctx, "m_nothing", 50) |
| 223 | } |
| 224 | if Status(err) != 422 { |
| 225 | t.Fatalf("an unknown cursor (assistant %v): %v", c != nil, err) |
| 226 | } |
| 227 | } |
| 228 | // The Coordinator's command carries no lane and none of the Assistant's |
| 229 | // conversation in its tail. |
| 230 | _, frame, err = runner.Expect(r.ctx, wire.FrameMessage) |
| 231 | if err != nil { |
| 232 | t.Fatal(err) |
| 233 | } |
| 234 | if c := frame.(*wire.MessageCommand); c.Lane != "" || len(c.Tail) != 0 { |
| 235 | t.Fatalf("coordinator command %+v", c) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | // TestContractLanesRunAtOnce: an Assistant message goes to the runner at |
| 240 | // once while a Coordinator turn runs, and each lane queues its own. |
| 241 | func TestContractLanesRunAtOnce(t *testing.T) { |
| 242 | r, runner := newAssistRig(t) |
| 243 | a := r.client.Assistant() |
| 244 | busy, err := r.client.Send(r.ctx, "a long job", "c-1") |
| 245 | if err != nil { |
| 246 | t.Fatal(err) |
| 247 | } |
| 248 | f, _, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 249 | if err != nil { |
| 250 | t.Fatal(err) |
| 251 | } |
| 252 | runner.Send(r.ctx, "c-ack", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 253 | r.wait("coordinator running", func(c *Conversation) bool { return c.Turns[busy.Turn.ID].State == wire.TurnRunning }) |
| 254 | waiting, err := r.client.Send(r.ctx, "and another", "c-2") |
| 255 | if err != nil || waiting.Turn.ID == busy.Turn.ID { |
| 256 | t.Fatalf("second coordinator message %+v %v", waiting, err) |
| 257 | } |
| 258 | |
| 259 | sent, err := a.Send(r.ctx, "quick question", "a-1") |
| 260 | if err != nil { |
| 261 | t.Fatal(err) |
| 262 | } |
| 263 | _, frame, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 264 | if err != nil { |
| 265 | t.Fatal(err) |
| 266 | } |
| 267 | if cmd := frame.(*wire.MessageCommand); cmd.Lane != wire.LaneAssistant || cmd.TurnID != sent.Turn.ID { |
| 268 | t.Fatalf("the Assistant waited for the coordinator: %+v", cmd) |
| 269 | } |
| 270 | // A second Assistant message waits behind the first, in its own lane. |
| 271 | next, err := a.Send(r.ctx, "one more", "a-2") |
| 272 | if err != nil || next.Turn.ID == sent.Turn.ID || next.Turn.State != wire.TurnQueued { |
| 273 | t.Fatalf("second assistant message %+v %v", next, err) |
| 274 | } |
| 275 | if err = runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: sent.Turn.ID, Attempt: 1, Text: "Sure."}); err != nil { |
| 276 | t.Fatal(err) |
| 277 | } |
| 278 | // Its reply starts the Assistant's next turn, not the Coordinator's. |
| 279 | _, frame, err = runner.Expect(r.ctx, wire.FrameMessage) |
| 280 | if err != nil { |
| 281 | t.Fatal(err) |
| 282 | } |
| 283 | if cmd := frame.(*wire.MessageCommand); cmd.Lane != wire.LaneAssistant || cmd.TurnID != next.Turn.ID || len(cmd.Tail) != 2 || cmd.Tail[1].Role != wire.RoleAssistant { |
| 284 | t.Fatalf("after the Assistant's reply %+v", cmd) |
| 285 | } |
| 286 | if err = runner.Send(r.ctx, "c-reply", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "Done."}); err != nil { |
| 287 | t.Fatal(err) |
| 288 | } |
| 289 | _, frame, err = runner.Expect(r.ctx, wire.FrameMessage) |
| 290 | if err != nil { |
| 291 | t.Fatal(err) |
| 292 | } |
| 293 | if cmd := frame.(*wire.MessageCommand); cmd.Lane != "" || cmd.TurnID != waiting.Turn.ID || slices.ContainsFunc(cmd.Tail, func(m wire.TailMessage) bool { return m.Role == wire.RoleAssistant }) { |
| 294 | t.Fatalf("after the coordinator's reply %+v", cmd) |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // TestContractAssistantNeedsRunner: the Assistant answers only people |
| 299 | // whose primary runner speaks its protocol, and stores nothing otherwise. |
| 300 | func TestContractAssistantNeedsRunner(t *testing.T) { |
| 301 | r := newRig(t) |
| 302 | const member = "member@example.com" |
| 303 | if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil { |
| 304 | t.Fatal(err) |
| 305 | } |
| 306 | refused := func(c *Client, code string) { |
| 307 | t.Helper() |
| 308 | a := c.Assistant() |
| 309 | _, err := a.Send(r.ctx, "hello", "a-"+code) |
| 310 | var e wire.Error |
| 311 | if s, ok := err.(*ErrStatus); !ok || s.Status != http.StatusConflict || json.Unmarshal(s.Body, &e) != nil || e.Code != code || e.CopyKey != "api."+code || e.RequestID == "" { |
| 312 | t.Fatalf("send without a runner: %v", err) |
| 313 | } |
| 314 | snap, err := a.Snapshot(r.ctx) |
| 315 | if err != nil || snap.Available || len(snap.Messages) != 0 || len(snap.Turns) != 0 { |
| 316 | t.Fatalf("%s snapshot %+v %v", code, snap, err) |
| 317 | } |
| 318 | var n int64 |
| 319 | if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages").Scan(&n); err != nil || n != 0 { |
| 320 | t.Fatalf("%s stored %d messages %v", code, n, err) |
| 321 | } |
| 322 | } |
| 323 | refused(NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member)), "no_runner") |
| 324 | |
| 325 | old := r.dialAt(wire.ProtocolModels) |
| 326 | refused(r.client, "runner_too_old") |
| 327 | old.Close() |
| 328 | r.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) |
| 329 | |
| 330 | current := r.dialAt(wire.ProtocolAssistant) |
| 331 | a := r.client.Assistant() |
| 332 | if snap, err := a.Snapshot(r.ctx); err != nil || !snap.Available { |
| 333 | t.Fatalf("available at 19 %+v %v", snap, err) |
| 334 | } |
| 335 | sent, err := a.Send(r.ctx, "hello", "a-1") |
| 336 | if err != nil { |
| 337 | t.Fatal(err) |
| 338 | } |
| 339 | if _, frame, err := current.Expect(r.ctx, wire.FrameMessage); err != nil || frame.(*wire.MessageCommand).Lane != wire.LaneAssistant { |
| 340 | t.Fatalf("dispatched at 19 %v", err) |
| 341 | } |
| 342 | current.Close() |
| 343 | r.wait("offline again", func(c *Conversation) bool { return !c.Runner.Online }) |
| 344 | |
| 345 | // The same primary comes back older: the turn ends, never sent. |
| 346 | again := r.dialAt(wire.ProtocolModels) |
| 347 | snap, err := a.Snapshot(r.ctx) |
| 348 | if err != nil || snap.Available || len(snap.Turns) != 1 || snap.Turns[0].ID != sent.Turn.ID || snap.Turns[0].State != wire.TurnFailed || snap.Turns[0].Reason != "runner_too_old" { |
| 349 | t.Fatalf("turn after an older runner %+v %v", snap, err) |
| 350 | } |
| 351 | var unacked int64 |
| 352 | if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND acked_at IS NULL", wire.FrameMessage).Scan(&unacked); err != nil || unacked != 0 { |
| 353 | t.Fatalf("%d Assistant commands still waiting %v", unacked, err) |
| 354 | } |
| 355 | // The Coordinator still works at 18, and its frame is the first. |
| 356 | coord, err := r.client.Send(r.ctx, "hello coordinator", "c-1") |
| 357 | if err != nil { |
| 358 | t.Fatal(err) |
| 359 | } |
| 360 | if _, frame, err := again.Expect(r.ctx, wire.FrameMessage); err != nil || frame.(*wire.MessageCommand).TurnID != coord.Turn.ID { |
| 361 | t.Fatalf("coordinator at 18 %v %+v", err, frame) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | // TestContractAssistantQuestion: ask_person in an Assistant turn raises a |
| 366 | // generic question card in its lane; the answer is the person's next |
| 367 | // Assistant message. |
| 368 | func TestContractAssistantQuestion(t *testing.T) { |
| 369 | r, runner := newAssistRig(t) |
| 370 | a := r.client.Assistant() |
| 371 | snap, _ := a.Snapshot(r.ctx) |
| 372 | s, err := a.Open(r.ctx, snap.Cursor) |
| 373 | if err != nil { |
| 374 | t.Fatal(err) |
| 375 | } |
| 376 | defer s.Close() |
| 377 | sent, err := a.Send(r.ctx, "book me in", "a-1") |
| 378 | if err != nil { |
| 379 | t.Fatal(err) |
| 380 | } |
| 381 | f, _, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 382 | if err != nil { |
| 383 | t.Fatal(err) |
| 384 | } |
| 385 | runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 386 | tools := &toolRig{rig: r, runner: runner, turn: sent.Turn.ID} |
| 387 | if res := tools.call("q1", wire.ToolAskPerson, map[string]any{"question": "Which day?", "options": []string{"Monday", "Tuesday"}}); res.Code != "asked" { |
| 388 | t.Fatalf("ask_person %+v", res) |
| 389 | } |
| 390 | var seen []wire.Event |
| 391 | assistEvents(t, s, "the card", &seen, func(es []wire.Event) bool { |
| 392 | return slices.ContainsFunc(es, func(e wire.Event) bool { return e.Type == wire.EventCard }) |
| 393 | }) |
| 394 | i := slices.IndexFunc(seen, func(e wire.Event) bool { return e.Type == wire.EventCard }) |
| 395 | var card wire.AssistantCard |
| 396 | if err := wire.Strict(seen[i].Data, &card); err != nil { |
| 397 | t.Fatalf("card event %s: %v", seen[i].Data, err) |
| 398 | } |
| 399 | if card.Kind != wire.CardQuestion || card.State != wire.CardOpen || card.Question != "Which day?" || !slices.Equal(card.Options, []wire.CardOption{{Value: "Monday", Label: "Monday"}, {Value: "Tuesday", Label: "Tuesday"}}) || card.Links == nil { |
| 400 | t.Fatalf("card %+v", card) |
| 401 | } |
| 402 | // The Coordinator's page never shows it, open or answered. |
| 403 | if body := r.inst.Get(t, "/conversation"); strings.Contains(body, "Which day") { |
| 404 | t.Fatal("the conversation page shows the Assistant's open card") |
| 405 | } |
| 406 | runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: sent.Turn.ID, Attempt: 1, Text: "Which day suits?"}) |
| 407 | if snap, err = a.Snapshot(r.ctx); err != nil || len(snap.Cards) != 1 || snap.Cards[0].ID != card.ID { |
| 408 | t.Fatalf("snapshot cards %+v %v", snap, err) |
| 409 | } |
| 410 | // Not the Coordinator's card. |
| 411 | if csnap, _ := r.client.Snapshot(r.ctx); len(csnap.Cards) != 0 { |
| 412 | t.Fatalf("coordinator snapshot cards %+v", csnap.Cards) |
| 413 | } |
| 414 | if _, err = r.client.Answer(r.ctx, card.ID, "Tuesday", card.Revision); Status(err) != 404 { |
| 415 | t.Fatalf("answered through /api/v1/cards: %v", err) |
| 416 | } |
| 417 | |
| 418 | _, err = a.Answer(r.ctx, card.ID, "Tuesday", card.Revision+1) |
| 419 | var conflict wire.AssistantConflict |
| 420 | if s, ok := err.(*ErrStatus); !ok || s.Status != http.StatusConflict || wire.Strict(s.Body, &conflict) != nil || conflict.Code != "card_stale" || conflict.CopyKey != "api.card_stale" || conflict.Card.ID != card.ID || conflict.Card.Revision != card.Revision || conflict.Card.Options == nil { |
| 421 | t.Fatalf("stale answer %v", err) |
| 422 | } |
| 423 | if _, err = a.Answer(r.ctx, card.ID, "Friday", card.Revision); Status(err) != 422 { |
| 424 | t.Fatalf("an answer that is no option: %v", err) |
| 425 | } |
| 426 | answered, err := a.Answer(r.ctx, card.ID, "Tuesday", card.Revision) |
| 427 | if err != nil || answered.Card.State != wire.CardAnswered || answered.Card.Result != "Tuesday" || answered.Message.Text != "Tuesday" || answered.Message.Role != wire.RolePerson || answered.Turn.ID == "" || answered.Turn.ID == sent.Turn.ID { |
| 428 | t.Fatalf("answer %+v %v", answered, err) |
| 429 | } |
| 430 | _, frame, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 431 | if err != nil { |
| 432 | t.Fatal(err) |
| 433 | } |
| 434 | if cmd := frame.(*wire.MessageCommand); cmd.Lane != wire.LaneAssistant || cmd.TurnID != answered.Turn.ID || len(cmd.PersonText) != 0 || !strings.Contains(cmd.Text, "Which day?") { |
| 435 | t.Fatalf("answer command %+v", cmd) |
| 436 | } |
| 437 | _, err = a.Answer(r.ctx, card.ID, "Tuesday", answered.Card.Revision) |
| 438 | if s, ok := err.(*ErrStatus); !ok || s.Status != http.StatusConflict || wire.Strict(s.Body, &conflict) != nil || conflict.Code != "card_answered" || conflict.Card.State != wire.CardAnswered { |
| 439 | t.Fatalf("second answer %v", err) |
| 440 | } |
| 441 | if _, err = a.Answer(r.ctx, "c_nothing", "Tuesday", 1); Status(err) != 404 { |
| 442 | t.Fatalf("unknown card %v", err) |
| 443 | } |
| 444 | if body := r.inst.Get(t, "/conversation"); strings.Contains(body, "book me in") || strings.Contains(body, "Which day") || strings.Contains(body, "Tuesday") { |
| 445 | t.Fatal("the conversation page shows the Assistant's lane") |
| 446 | } |
| 447 | // A Coordinator question is not the Assistant's to answer. |
| 448 | coord, err := r.client.Send(r.ctx, "hello", "c-1") |
| 449 | if err != nil { |
| 450 | t.Fatal(err) |
| 451 | } |
| 452 | f, _, err = runner.Expect(r.ctx, wire.FrameMessage) |
| 453 | if err != nil { |
| 454 | t.Fatal(err) |
| 455 | } |
| 456 | runner.Send(r.ctx, "c-ack", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 457 | team := &toolRig{rig: r, runner: runner, turn: coord.Turn.ID} |
| 458 | if res := team.call("q2", wire.ToolAskPerson, map[string]any{"question": "Which repo?", "options": []string{"Woodstar"}}); res.Code != "asked" { |
| 459 | t.Fatalf("coordinator ask_person %+v", res) |
| 460 | } |
| 461 | csnap, err := r.client.Snapshot(r.ctx) |
| 462 | if err != nil || len(csnap.Cards) != 1 { |
| 463 | t.Fatalf("coordinator card %+v %v", csnap.Cards, err) |
| 464 | } |
| 465 | if _, err = a.Answer(r.ctx, csnap.Cards[0].ID, "Woodstar", csnap.Cards[0].Revision); Status(err) != 404 { |
| 466 | t.Fatalf("a Coordinator card answered as the Assistant's: %v", err) |
| 467 | } |
| 468 | if snap, _ = a.Snapshot(r.ctx); len(snap.Cards) != 1 || snap.Cards[0].ID != card.ID { |
| 469 | t.Fatalf("assistant snapshot cards %+v", snap.Cards) |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | // TestContractAssistantRefusesTeamTools: each lane's tools only, and |
| 474 | // each lane's activity names only its own tools. |
| 475 | func TestContractAssistantRefusesTeamTools(t *testing.T) { |
| 476 | r, runner := newAssistRig(t) |
| 477 | snap, _ := r.client.Assistant().Snapshot(r.ctx) |
| 478 | s, err := r.client.Assistant().Open(r.ctx, snap.Cursor) |
| 479 | if err != nil { |
| 480 | t.Fatal(err) |
| 481 | } |
| 482 | defer s.Close() |
| 483 | sent, err := r.client.Assistant().Send(r.ctx, "fix my app", "a-1") |
| 484 | if err != nil { |
| 485 | t.Fatal(err) |
| 486 | } |
| 487 | f, _, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 488 | if err != nil { |
| 489 | t.Fatal(err) |
| 490 | } |
| 491 | runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 492 | assist := &toolRig{rig: r, runner: runner, turn: sent.Turn.ID} |
| 493 | if res := assist.call("rt", wire.ToolRecordTask, map[string]any{"repo": "amadan.net/oficina/sample", "title": "Fix it", "brief": "Fix the app."}); !res.IsError || res.Code != "unknown_tool" { |
| 494 | t.Fatalf("record_task in an Assistant turn %+v", res) |
| 495 | } |
| 496 | if res := assist.call("st", wire.ToolStatus, map[string]any{}); !res.IsError || res.Code != "unknown_tool" { |
| 497 | t.Fatalf("status in an Assistant turn %+v", res) |
| 498 | } |
| 499 | if res := assist.call("rn", wire.ToolReadNotes, map[string]any{}); res.IsError || res.Code != "notes" { |
| 500 | t.Fatalf("read_notes in an Assistant turn %+v", res) |
| 501 | } |
| 502 | activity := func(s *Stream, turn string, tools ...string) []string { |
| 503 | t.Helper() |
| 504 | for i, tool := range tools { |
| 505 | runner.Send(r.ctx, "act-"+turn+"-"+itoa(i), wire.FrameActivity, wire.ActivityReport{TurnID: turn, Attempt: 1, Kind: wire.ActivityTool, Tool: tool}) |
| 506 | } |
| 507 | var seen []wire.Event |
| 508 | var got []string |
| 509 | assistEvents(t, s, "activity", &seen, func(es []wire.Event) bool { |
| 510 | got = nil |
| 511 | for _, e := range es { |
| 512 | var a wire.Activity |
| 513 | if e.Type == wire.EventActivity && e.TurnID == turn && json.Unmarshal(e.Data, &a) == nil { |
| 514 | got = append(got, a.Tool) |
| 515 | } |
| 516 | } |
| 517 | return len(got) == len(tools) |
| 518 | }) |
| 519 | return got |
| 520 | } |
| 521 | if got := activity(s, sent.Turn.ID, wire.ToolLook, wire.ToolRecordTask); !slices.Equal(got, []string{wire.ToolLook, "other"}) { |
| 522 | t.Fatalf("Assistant activity %v", got) |
| 523 | } |
| 524 | |
| 525 | coord, err := r.client.Send(r.ctx, "hello", "c-1") |
| 526 | if err != nil { |
| 527 | t.Fatal(err) |
| 528 | } |
| 529 | f, _, err = runner.Expect(r.ctx, wire.FrameMessage) |
| 530 | if err != nil { |
| 531 | t.Fatal(err) |
| 532 | } |
| 533 | runner.Send(r.ctx, "c-ack", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 534 | cs, err := r.client.Open(r.ctx, snap.Cursor) |
| 535 | if err != nil { |
| 536 | t.Fatal(err) |
| 537 | } |
| 538 | defer cs.Close() |
| 539 | if got := activity(cs, coord.Turn.ID, wire.ToolLook, wire.ToolFind); !slices.Equal(got, []string{"other", wire.ToolFind}) { |
| 540 | t.Fatalf("Coordinator activity %v", got) |
| 541 | } |
| 542 | team := &toolRig{rig: r, runner: runner, turn: coord.Turn.ID} |
| 543 | for _, name := range []string{wire.ToolLook, wire.ToolDescribe, wire.ToolUse} { |
| 544 | if res := team.call(name, name, map[string]any{}); !res.IsError || res.Code != "unknown_tool" { |
| 545 | t.Fatalf("%s in a Coordinator turn %+v", name, res) |
| 546 | } |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | // TestContractAssistantCancelAndAuth: cancel in the lane, ids from the |
| 551 | // other lane unknown, and the bearer alone admits. |
| 552 | func TestContractAssistantCancelAndAuth(t *testing.T) { |
| 553 | r, runner := newAssistRig(t) |
| 554 | a := r.client.Assistant() |
| 555 | sent, err := a.Send(r.ctx, "a long errand", "a-1") |
| 556 | if err != nil { |
| 557 | t.Fatal(err) |
| 558 | } |
| 559 | f, _, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 560 | if err != nil { |
| 561 | t.Fatal(err) |
| 562 | } |
| 563 | runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 564 | coord, err := r.client.Send(r.ctx, "hello", "c-1") |
| 565 | if err != nil { |
| 566 | t.Fatal(err) |
| 567 | } |
| 568 | if _, err = a.Cancel(r.ctx, coord.Turn.ID); Status(err) != 404 { |
| 569 | t.Fatalf("a Coordinator turn cancelled as the Assistant's: %v", err) |
| 570 | } |
| 571 | if _, err = r.client.Cancel(r.ctx, sent.Turn.ID); Status(err) != 404 { |
| 572 | t.Fatalf("an Assistant turn cancelled as the Coordinator's: %v", err) |
| 573 | } |
| 574 | accepted, err := a.Cancel(r.ctx, sent.Turn.ID) |
| 575 | if err != nil || accepted.Attempt != 1 { |
| 576 | t.Fatalf("cancel %+v %v", accepted, err) |
| 577 | } |
| 578 | for { |
| 579 | _, frame, err := runner.Next(r.ctx) |
| 580 | if err != nil { |
| 581 | t.Fatal(err) |
| 582 | } |
| 583 | if c, ok := frame.(*wire.CancelCommand); ok { |
| 584 | if c.TurnID != sent.Turn.ID { |
| 585 | t.Fatalf("cancel frame %+v", c) |
| 586 | } |
| 587 | break |
| 588 | } |
| 589 | } |
| 590 | runner.Send(r.ctx, "a-cancelled", wire.FrameTurn, wire.TurnReport{TurnID: sent.Turn.ID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}) |
| 591 | deadline := time.Now().Add(10 * time.Second) |
| 592 | for { |
| 593 | _, err = a.Cancel(r.ctx, sent.Turn.ID) |
| 594 | var e wire.Error |
| 595 | if s, ok := err.(*ErrStatus); ok && s.Status == http.StatusConflict && json.Unmarshal(s.Body, &e) == nil && e.Code == "turn_ended" { |
| 596 | break |
| 597 | } |
| 598 | if time.Now().After(deadline) { |
| 599 | t.Fatalf("second cancel %v", err) |
| 600 | } |
| 601 | time.Sleep(50 * time.Millisecond) |
| 602 | } |
| 603 | if _, err = a.Cancel(r.ctx, "t_nothing"); Status(err) != 404 { |
| 604 | t.Fatalf("unknown turn %v", err) |
| 605 | } |
| 606 | |
| 607 | // Every route takes the bearer and nothing else: no bearer is 401, |
| 608 | // with the browser's session cookie too. |
| 609 | routes := [][3]string{{"GET", "/snapshot", ""}, {"GET", "/messages", ""}, {"POST", "/messages", `{"text":"x","idempotency_key":"k"}`}, {"POST", "/turns/" + sent.Turn.ID + "/cancel", `{}`}, {"POST", "/cards/c_x/answer", `{"choice":"x","revision":1}`}, {"GET", "/events", ""}} |
| 610 | for _, route := range routes { |
| 611 | for _, cookie := range []*http.Cookie{nil, r.inst.Cookie()} { |
| 612 | status, header, body := raw(t, route[0], r.inst.URL+"/api/v1/assistant"+route[1], "", cookie, route[2]) |
| 613 | var e wire.Error |
| 614 | if status != http.StatusUnauthorized || json.Unmarshal(body, &e) != nil || e.Code != "unauthenticated" || header.Get("Cache-Control") != "no-store" { |
| 615 | t.Fatalf("%s %s cookie %v: %d %s", route[0], route[1], cookie != nil, status, body) |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | if status, header, _ := raw(t, "GET", r.inst.URL+"/api/v1/assistant/snapshot", r.client.Token, nil, ""); status != 200 || header.Get("Cache-Control") != "no-store" { |
| 620 | t.Fatalf("snapshot with the bearer %d", status) |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | // TestContractAssistantKeysPerLane: an idempotency key is the person's |
| 625 | // per lane. Every key the Coordinator took before lanes still works, |
| 626 | // retries included, and the Assistant may use the same keys. |
| 627 | func TestContractAssistantKeysPerLane(t *testing.T) { |
| 628 | r, _ := newAssistRig(t) |
| 629 | a := r.client.Assistant() |
| 630 | old, err := r.client.Send(r.ctx, "from before", "assistant:x") |
| 631 | if err != nil { |
| 632 | t.Fatalf("a Coordinator key that was always valid: %v", err) |
| 633 | } |
| 634 | // As a row from before lanes: no lane at all. |
| 635 | if _, err = r.inst.DB.Writer().Exec("UPDATE chat_messages SET lane = NULL WHERE id = ?", old.Message.ID); err != nil { |
| 636 | t.Fatal(err) |
| 637 | } |
| 638 | if again, err := r.client.Send(r.ctx, "from before", "assistant:x"); err != nil || again.Message.ID != old.Message.ID { |
| 639 | t.Fatalf("historical retry %+v %v", again, err) |
| 640 | } |
| 641 | mine := map[string]string{} |
| 642 | for _, key := range []string{"x", "assistant:x"} { |
| 643 | sent, err := a.Send(r.ctx, "hello", key) |
| 644 | if err != nil || sent.Message.ID == old.Message.ID { |
| 645 | t.Fatalf("Assistant key %q: %+v %v", key, sent, err) |
| 646 | } |
| 647 | mine[key] = sent.Message.ID |
| 648 | } |
| 649 | coord, err := r.client.Send(r.ctx, "hello", "x") |
| 650 | if err != nil || coord.Message.ID == mine["x"] { |
| 651 | t.Fatalf("Coordinator key x beside the Assistant's: %+v %v", coord, err) |
| 652 | } |
| 653 | for key, id := range mine { |
| 654 | if again, err := a.Send(r.ctx, "hello", key); err != nil || again.Message.ID != id { |
| 655 | t.Fatalf("Assistant retry %q %+v %v", key, again, err) |
| 656 | } |
| 657 | } |
| 658 | if again, err := r.client.Send(r.ctx, "hello", "x"); err != nil || again.Message.ID != coord.Message.ID { |
| 659 | t.Fatalf("Coordinator retry %+v %v", again, err) |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | // TestContractAssistantAnswerNeedsRunner: an answer is a new Assistant |
| 664 | // message, so it too needs a primary that can carry it. Refused, it |
| 665 | // changes nothing: the card stays open and nothing is queued. |
| 666 | func TestContractAssistantAnswerNeedsRunner(t *testing.T) { |
| 667 | r, runner := newAssistRig(t) |
| 668 | a := r.client.Assistant() |
| 669 | sent, err := a.Send(r.ctx, "book me in", "a-1") |
| 670 | if err != nil { |
| 671 | t.Fatal(err) |
| 672 | } |
| 673 | f, _, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 674 | if err != nil { |
| 675 | t.Fatal(err) |
| 676 | } |
| 677 | runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 678 | tools := &toolRig{rig: r, runner: runner, turn: sent.Turn.ID} |
| 679 | if res := tools.call("q1", wire.ToolAskPerson, map[string]any{"question": "Which day?", "options": []string{"Monday", "Tuesday"}}); res.Code != "asked" { |
| 680 | t.Fatalf("ask_person %+v", res) |
| 681 | } |
| 682 | runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: sent.Turn.ID, Attempt: 1, Text: "Which day suits?"}) |
| 683 | var card wire.AssistantCard |
| 684 | deadline := time.Now().Add(10 * time.Second) |
| 685 | for { |
| 686 | snap, err := a.Snapshot(r.ctx) |
| 687 | if err == nil && len(snap.Cards) == 1 && len(snap.Turns) == 1 && snap.Turns[0].State == wire.TurnReplied { |
| 688 | card = snap.Cards[0] |
| 689 | break |
| 690 | } |
| 691 | if time.Now().After(deadline) { |
| 692 | t.Fatalf("no card %+v %v", snap, err) |
| 693 | } |
| 694 | time.Sleep(50 * time.Millisecond) |
| 695 | } |
| 696 | runner.Close() |
| 697 | r.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) |
| 698 | unchanged := func(code string) { |
| 699 | t.Helper() |
| 700 | snap, err := a.Snapshot(r.ctx) |
| 701 | if err != nil || len(snap.Cards) != 1 || snap.Cards[0].State != wire.CardOpen || snap.Cards[0].Revision != card.Revision || len(snap.Messages) != 2 || len(snap.Turns) != 1 { |
| 702 | t.Fatalf("%s changed the lane %+v %v", code, snap, err) |
| 703 | } |
| 704 | var waiting int64 |
| 705 | if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND acked_at IS NULL", wire.FrameMessage).Scan(&waiting); err != nil || waiting != 0 { |
| 706 | t.Fatalf("%s queued %d messages %v", code, waiting, err) |
| 707 | } |
| 708 | } |
| 709 | refused := func(code string) { |
| 710 | t.Helper() |
| 711 | _, err := a.Answer(r.ctx, card.ID, "Tuesday", card.Revision) |
| 712 | var e wire.Error |
| 713 | if s, ok := err.(*ErrStatus); !ok || s.Status != http.StatusConflict || json.Unmarshal(s.Body, &e) != nil || e.Code != code { |
| 714 | t.Fatalf("answer with %s: %v", code, err) |
| 715 | } |
| 716 | unchanged(code) |
| 717 | } |
| 718 | // The same primary back on protocol 18, after the fence ran. |
| 719 | older := r.dialAt(wire.ProtocolModels) |
| 720 | refused("runner_too_old") |
| 721 | older.Close() |
| 722 | r.wait("offline again", func(c *Conversation) bool { return !c.Runner.Online }) |
| 723 | // The primary removed: nobody runs for the person. |
| 724 | var id string |
| 725 | var revision int64 |
| 726 | if err := r.inst.DB.Writer().QueryRow("SELECT id, revision FROM runners").Scan(&id, &revision); err != nil { |
| 727 | t.Fatal(err) |
| 728 | } |
| 729 | if err := r.inst.Store.RevokeRunner(r.ctx, equipo.Actor{Address: Owner}, id, revision); err != nil { |
| 730 | t.Fatal(err) |
| 731 | } |
| 732 | refused("no_runner") |
| 733 | } |
| 734 | |