package thintest import ( "bytes" "context" "encoding/json" "io" "net/http" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // dialAt connects the owner's runner as a Linux primary speaking protocol. func (r *rig) dialAt(protocol int) *FakeRunner { r.t.Helper() 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)) if err != nil { r.t.Fatal(err) } r.t.Cleanup(f.Close) r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online && c.Runner.Revision > 0 }) return f } // newAssistRig is a rig whose owner's primary speaks the Assistant's // protocol. func newAssistRig(t *testing.T) (*rig, *FakeRunner) { r := newRig(t) return r, r.dialAt(wire.ProtocolAssistant) } // assistEvents reads the Assistant stream until cond holds of the events // so far, or fails. func assistEvents(t *testing.T, s *Stream, what string, seen *[]wire.Event, cond func([]wire.Event) bool) { t.Helper() deadline := time.After(10 * time.Second) for !cond(*seen) { select { case e, ok := <-s.Events: if !ok { t.Fatalf("assistant stream ended waiting for %s", what) } *seen = append(*seen, e) case <-deadline: t.Fatalf("timed out waiting for %s; saw %d events", what, len(*seen)) } } } // eventFor finds the index of the first event of kind about id (-1). func eventFor(events []wire.Event, kind, id string, match func(json.RawMessage) bool) int { return slices.IndexFunc(events, func(e wire.Event) bool { return e.Type == kind && e.ID == id && (match == nil || match(e.Data)) }) } // raw sends a request with optional bearer and cookie and returns the // status, headers and body. func raw(t *testing.T, method, url, token string, cookie *http.Cookie, body string) (int, http.Header, []byte) { t.Helper() var reader io.Reader if body != "" { reader = strings.NewReader(body) } req, _ := http.NewRequest(method, url, reader) if body != "" { req.Header.Set("Content-Type", "application/json") } if token != "" { req.Header.Set("Authorization", "Bearer "+token) } if cookie != nil { req.AddCookie(cookie) req.Header.Set("Sec-Fetch-Site", "same-origin") req.Header.Set("Origin", strings.TrimSuffix(url[:strings.Index(url, "/api/")], "/")) } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() res, err := http.DefaultClient.Do(req.WithContext(ctx)) if err != nil { t.Fatal(err) } defer res.Body.Close() out, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16)) return res.StatusCode, res.Header, out } // TestContractAssistantConversation: an Assistant message reaches the // runner in its lane, its reply comes back on the Assistant stream as an // assistant message, and nothing of it reaches the Coordinator's routes. func TestContractAssistantConversation(t *testing.T) { r, runner := newAssistRig(t) a := r.client.Assistant() snap, err := a.Snapshot(r.ctx) if err != nil || !snap.Available || len(snap.Messages) != 0 || len(snap.Turns) != 0 || snap.Cards == nil || snap.Me.Address != Owner { t.Fatalf("first snapshot %+v %v", snap, err) } s, err := a.Open(r.ctx, snap.Cursor) if err != nil { t.Fatal(err) } defer s.Close() status, header, body := raw(t, "POST", r.inst.URL+"/api/v1/assistant/messages", r.client.Token, nil, `{"text":"hello assistant","idempotency_key":"a-1"}`) if status != http.StatusCreated || header.Get("Cache-Control") != "no-store" { t.Fatalf("send %d %q %s", status, header.Get("Cache-Control"), body) } var sent wire.Sent if err := json.Unmarshal(body, &sent); err != nil || sent.Message.Role != wire.RolePerson || sent.Turn.Kind != "" || sent.Turn.ID == "" { t.Fatalf("sent %+v %v", sent, err) } // The same key and text answer 200 with the same message; other text // is a conflict. 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)) { t.Fatalf("replay %d %s", status, body) } if _, err = a.Send(r.ctx, "something else", "a-1"); Status(err) != http.StatusConflict { t.Fatalf("conflict %v", err) } // Files need a runner on protocol 33 (assistant attachments spec A1); // this one speaks 19, so nothing is stored. 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"`)) { t.Fatalf("attachments %d %s", status, body) } f, frame, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } cmd := frame.(*wire.MessageCommand) if cmd.Lane != wire.LaneAssistant || cmd.TurnID != sent.Turn.ID || cmd.Text != "hello assistant" || cmd.Person != Owner || !slices.Equal(cmd.PersonText, []string{"hello assistant"}) { t.Fatalf("command %+v", cmd) } if err = runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { t.Fatal(err) } if err = runner.Send(r.ctx, "a-delta", wire.FrameDelta, wire.DeltaReport{TurnID: cmd.TurnID, Attempt: 1, Offset: 0, Text: "Hi"}); err != nil { t.Fatal(err) } if err = runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Hi there."}); err != nil { t.Fatal(err) } var seen []wire.Event replied := func(d json.RawMessage) bool { var v wire.Turn return json.Unmarshal(d, &v) == nil && v.State == wire.TurnReplied } assistEvents(t, s, "the reply", &seen, func(es []wire.Event) bool { return eventFor(es, wire.EventTurn, cmd.TurnID, replied) >= 0 }) delta := slices.IndexFunc(seen, func(e wire.Event) bool { return e.Type == wire.EventDelta && e.TurnID == cmd.TurnID }) reply := slices.IndexFunc(seen, func(e wire.Event) bool { var m wire.Message return e.Type == wire.EventMessage && json.Unmarshal(e.Data, &m) == nil && m.Role == wire.RoleAssistant && m.Text == "Hi there." && m.TurnID == cmd.TurnID }) if delta < 0 || reply < delta { t.Fatalf("delta %d then reply %d: %+v", delta, reply, seen) } snap, err = a.Snapshot(r.ctx) 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 { t.Fatalf("assistant snapshot %+v %v", snap, err) } page, err := a.Messages(r.ctx, "", 50) if err != nil || len(page.Items) != 2 { t.Fatalf("assistant messages %+v %v", page, err) } if _, err = a.Messages(r.ctx, "", 201); Status(err) != 422 { t.Fatalf("limit 201 %v", err) } // The Coordinator's routes never show it. A Coordinator message after // it shows the stream has passed every Assistant event. coord, err := r.client.Send(r.ctx, "to the coordinator", "c-1") if err != nil { t.Fatal(err) } cs, err := r.client.Open(r.ctx, 0) if err != nil { t.Fatal(err) } defer cs.Close() var coordSeen []wire.Event assistEvents(t, cs, "the coordinator message", &coordSeen, func(es []wire.Event) bool { return eventFor(es, wire.EventMessage, coord.Message.ID, nil) >= 0 }) for _, e := range coordSeen { 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.")) { t.Fatalf("an Assistant event on /api/v1/events: %+v", e) } } csnap, err := r.client.Snapshot(r.ctx) 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 }) { t.Fatalf("coordinator snapshot %+v %v", csnap, err) } cpage, err := r.client.Messages(r.ctx, "", 50) if err != nil || len(cpage.Items) != 1 { t.Fatalf("coordinator messages %+v %v", cpage, err) } if _, err = r.client.Turn(r.ctx, cmd.TurnID); Status(err) != 404 { t.Fatalf("an Assistant turn on /api/v1/turns: %v", err) } // The Coordinator's own message never reaches the Assistant's routes. if page, _ = a.Messages(r.ctx, "", 50); len(page.Items) != 2 { t.Fatalf("assistant messages after a coordinator one %+v", page) } // A Coordinator cursor on the Assistant's route is the other lane's id // (404). On the Coordinator's route an Assistant cursor is, as before // lanes, an id it does not have (422); so is one nobody has. if _, err = a.Messages(r.ctx, coord.Message.ID, 50); Status(err) != 404 { t.Fatalf("a coordinator message as the Assistant's cursor: %v", err) } if _, err = r.client.Messages(r.ctx, sent.Message.ID, 50); Status(err) != 422 { t.Fatalf("an Assistant message as the Coordinator's cursor: %v", err) } for _, c := range []*AssistantClient{a, nil} { var err error if c != nil { _, err = c.Messages(r.ctx, "m_nothing", 50) } else { _, err = r.client.Messages(r.ctx, "m_nothing", 50) } if Status(err) != 422 { t.Fatalf("an unknown cursor (assistant %v): %v", c != nil, err) } } // The Coordinator's command carries no lane and none of the Assistant's // conversation in its tail. _, frame, err = runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } if c := frame.(*wire.MessageCommand); c.Lane != "" || len(c.Tail) != 0 { t.Fatalf("coordinator command %+v", c) } } // TestContractLanesRunAtOnce: an Assistant message goes to the runner at // once while a Coordinator turn runs, and each lane queues its own. func TestContractLanesRunAtOnce(t *testing.T) { r, runner := newAssistRig(t) a := r.client.Assistant() busy, err := r.client.Send(r.ctx, "a long job", "c-1") if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "c-ack", wire.FrameAck, wire.Ack{ID: f.ID}) r.wait("coordinator running", func(c *Conversation) bool { return c.Turns[busy.Turn.ID].State == wire.TurnRunning }) waiting, err := r.client.Send(r.ctx, "and another", "c-2") if err != nil || waiting.Turn.ID == busy.Turn.ID { t.Fatalf("second coordinator message %+v %v", waiting, err) } sent, err := a.Send(r.ctx, "quick question", "a-1") if err != nil { t.Fatal(err) } _, frame, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } if cmd := frame.(*wire.MessageCommand); cmd.Lane != wire.LaneAssistant || cmd.TurnID != sent.Turn.ID { t.Fatalf("the Assistant waited for the coordinator: %+v", cmd) } // A second Assistant message waits behind the first, in its own lane. next, err := a.Send(r.ctx, "one more", "a-2") if err != nil || next.Turn.ID == sent.Turn.ID || next.Turn.State != wire.TurnQueued { t.Fatalf("second assistant message %+v %v", next, err) } if err = runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: sent.Turn.ID, Attempt: 1, Text: "Sure."}); err != nil { t.Fatal(err) } // Its reply starts the Assistant's next turn, not the Coordinator's. _, frame, err = runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } if cmd := frame.(*wire.MessageCommand); cmd.Lane != wire.LaneAssistant || cmd.TurnID != next.Turn.ID || len(cmd.Tail) != 2 || cmd.Tail[1].Role != wire.RoleAssistant { t.Fatalf("after the Assistant's reply %+v", cmd) } if err = runner.Send(r.ctx, "c-reply", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "Done."}); err != nil { t.Fatal(err) } _, frame, err = runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } 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 }) { t.Fatalf("after the coordinator's reply %+v", cmd) } } // TestContractAssistantNeedsRunner: the Assistant answers only people // whose primary runner speaks its protocol, and stores nothing otherwise. func TestContractAssistantNeedsRunner(t *testing.T) { r := newRig(t) const member = "member@example.com" if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil { t.Fatal(err) } refused := func(c *Client, code string) { t.Helper() a := c.Assistant() _, err := a.Send(r.ctx, "hello", "a-"+code) var e wire.Error 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 == "" { t.Fatalf("send without a runner: %v", err) } snap, err := a.Snapshot(r.ctx) if err != nil || snap.Available || len(snap.Messages) != 0 || len(snap.Turns) != 0 { t.Fatalf("%s snapshot %+v %v", code, snap, err) } var n int64 if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages").Scan(&n); err != nil || n != 0 { t.Fatalf("%s stored %d messages %v", code, n, err) } } refused(NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member)), "no_runner") old := r.dialAt(wire.ProtocolModels) refused(r.client, "runner_too_old") old.Close() r.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) current := r.dialAt(wire.ProtocolAssistant) a := r.client.Assistant() if snap, err := a.Snapshot(r.ctx); err != nil || !snap.Available { t.Fatalf("available at 19 %+v %v", snap, err) } sent, err := a.Send(r.ctx, "hello", "a-1") if err != nil { t.Fatal(err) } if _, frame, err := current.Expect(r.ctx, wire.FrameMessage); err != nil || frame.(*wire.MessageCommand).Lane != wire.LaneAssistant { t.Fatalf("dispatched at 19 %v", err) } current.Close() r.wait("offline again", func(c *Conversation) bool { return !c.Runner.Online }) // The same primary comes back older: the turn ends, never sent. again := r.dialAt(wire.ProtocolModels) snap, err := a.Snapshot(r.ctx) 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" { t.Fatalf("turn after an older runner %+v %v", snap, err) } var unacked int64 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 { t.Fatalf("%d Assistant commands still waiting %v", unacked, err) } // The Coordinator still works at 18, and its frame is the first. coord, err := r.client.Send(r.ctx, "hello coordinator", "c-1") if err != nil { t.Fatal(err) } if _, frame, err := again.Expect(r.ctx, wire.FrameMessage); err != nil || frame.(*wire.MessageCommand).TurnID != coord.Turn.ID { t.Fatalf("coordinator at 18 %v %+v", err, frame) } } // TestContractAssistantQuestion: ask_person in an Assistant turn raises a // generic question card in its lane; the answer is the person's next // Assistant message. func TestContractAssistantQuestion(t *testing.T) { r, runner := newAssistRig(t) a := r.client.Assistant() snap, _ := a.Snapshot(r.ctx) s, err := a.Open(r.ctx, snap.Cursor) if err != nil { t.Fatal(err) } defer s.Close() sent, err := a.Send(r.ctx, "book me in", "a-1") if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) tools := &toolRig{rig: r, runner: runner, turn: sent.Turn.ID} if res := tools.call("q1", wire.ToolAskPerson, map[string]any{"question": "Which day?", "options": []string{"Monday", "Tuesday"}}); res.Code != "asked" { t.Fatalf("ask_person %+v", res) } var seen []wire.Event assistEvents(t, s, "the card", &seen, func(es []wire.Event) bool { return slices.ContainsFunc(es, func(e wire.Event) bool { return e.Type == wire.EventCard }) }) i := slices.IndexFunc(seen, func(e wire.Event) bool { return e.Type == wire.EventCard }) var card wire.AssistantCard if err := wire.Strict(seen[i].Data, &card); err != nil { t.Fatalf("card event %s: %v", seen[i].Data, err) } 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 { t.Fatalf("card %+v", card) } // The Coordinator's page never shows it, open or answered. if body := r.inst.Get(t, "/conversation"); strings.Contains(body, "Which day") { t.Fatal("the conversation page shows the Assistant's open card") } runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: sent.Turn.ID, Attempt: 1, Text: "Which day suits?"}) if snap, err = a.Snapshot(r.ctx); err != nil || len(snap.Cards) != 1 || snap.Cards[0].ID != card.ID { t.Fatalf("snapshot cards %+v %v", snap, err) } // Not the Coordinator's card. if csnap, _ := r.client.Snapshot(r.ctx); len(csnap.Cards) != 0 { t.Fatalf("coordinator snapshot cards %+v", csnap.Cards) } if _, err = r.client.Answer(r.ctx, card.ID, "Tuesday", card.Revision); Status(err) != 404 { t.Fatalf("answered through /api/v1/cards: %v", err) } _, err = a.Answer(r.ctx, card.ID, "Tuesday", card.Revision+1) var conflict wire.AssistantConflict 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 { t.Fatalf("stale answer %v", err) } if _, err = a.Answer(r.ctx, card.ID, "Friday", card.Revision); Status(err) != 422 { t.Fatalf("an answer that is no option: %v", err) } answered, err := a.Answer(r.ctx, card.ID, "Tuesday", card.Revision) 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 { t.Fatalf("answer %+v %v", answered, err) } _, frame, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } if cmd := frame.(*wire.MessageCommand); cmd.Lane != wire.LaneAssistant || cmd.TurnID != answered.Turn.ID || len(cmd.PersonText) != 0 || !strings.Contains(cmd.Text, "Which day?") { t.Fatalf("answer command %+v", cmd) } _, err = a.Answer(r.ctx, card.ID, "Tuesday", answered.Card.Revision) 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 { t.Fatalf("second answer %v", err) } if _, err = a.Answer(r.ctx, "c_nothing", "Tuesday", 1); Status(err) != 404 { t.Fatalf("unknown card %v", err) } if body := r.inst.Get(t, "/conversation"); strings.Contains(body, "book me in") || strings.Contains(body, "Which day") || strings.Contains(body, "Tuesday") { t.Fatal("the conversation page shows the Assistant's lane") } // A Coordinator question is not the Assistant's to answer. coord, err := r.client.Send(r.ctx, "hello", "c-1") if err != nil { t.Fatal(err) } f, _, err = runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "c-ack", wire.FrameAck, wire.Ack{ID: f.ID}) team := &toolRig{rig: r, runner: runner, turn: coord.Turn.ID} if res := team.call("q2", wire.ToolAskPerson, map[string]any{"question": "Which repo?", "options": []string{"Woodstar"}}); res.Code != "asked" { t.Fatalf("coordinator ask_person %+v", res) } csnap, err := r.client.Snapshot(r.ctx) if err != nil || len(csnap.Cards) != 1 { t.Fatalf("coordinator card %+v %v", csnap.Cards, err) } if _, err = a.Answer(r.ctx, csnap.Cards[0].ID, "Woodstar", csnap.Cards[0].Revision); Status(err) != 404 { t.Fatalf("a Coordinator card answered as the Assistant's: %v", err) } if snap, _ = a.Snapshot(r.ctx); len(snap.Cards) != 1 || snap.Cards[0].ID != card.ID { t.Fatalf("assistant snapshot cards %+v", snap.Cards) } } // TestContractAssistantRefusesTeamTools: each lane's tools only, and // each lane's activity names only its own tools. func TestContractAssistantRefusesTeamTools(t *testing.T) { r, runner := newAssistRig(t) snap, _ := r.client.Assistant().Snapshot(r.ctx) s, err := r.client.Assistant().Open(r.ctx, snap.Cursor) if err != nil { t.Fatal(err) } defer s.Close() sent, err := r.client.Assistant().Send(r.ctx, "fix my app", "a-1") if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) assist := &toolRig{rig: r, runner: runner, turn: sent.Turn.ID} 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" { t.Fatalf("record_task in an Assistant turn %+v", res) } if res := assist.call("st", wire.ToolStatus, map[string]any{}); !res.IsError || res.Code != "unknown_tool" { t.Fatalf("status in an Assistant turn %+v", res) } if res := assist.call("rn", wire.ToolReadNotes, map[string]any{}); res.IsError || res.Code != "notes" { t.Fatalf("read_notes in an Assistant turn %+v", res) } activity := func(s *Stream, turn string, tools ...string) []string { t.Helper() for i, tool := range tools { runner.Send(r.ctx, "act-"+turn+"-"+itoa(i), wire.FrameActivity, wire.ActivityReport{TurnID: turn, Attempt: 1, Kind: wire.ActivityTool, Tool: tool}) } var seen []wire.Event var got []string assistEvents(t, s, "activity", &seen, func(es []wire.Event) bool { got = nil for _, e := range es { var a wire.Activity if e.Type == wire.EventActivity && e.TurnID == turn && json.Unmarshal(e.Data, &a) == nil { got = append(got, a.Tool) } } return len(got) == len(tools) }) return got } if got := activity(s, sent.Turn.ID, wire.ToolLook, wire.ToolRecordTask); !slices.Equal(got, []string{wire.ToolLook, "other"}) { t.Fatalf("Assistant activity %v", got) } coord, err := r.client.Send(r.ctx, "hello", "c-1") if err != nil { t.Fatal(err) } f, _, err = runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "c-ack", wire.FrameAck, wire.Ack{ID: f.ID}) cs, err := r.client.Open(r.ctx, snap.Cursor) if err != nil { t.Fatal(err) } defer cs.Close() if got := activity(cs, coord.Turn.ID, wire.ToolLook, wire.ToolFind); !slices.Equal(got, []string{"other", wire.ToolFind}) { t.Fatalf("Coordinator activity %v", got) } team := &toolRig{rig: r, runner: runner, turn: coord.Turn.ID} for _, name := range []string{wire.ToolLook, wire.ToolDescribe, wire.ToolUse} { if res := team.call(name, name, map[string]any{}); !res.IsError || res.Code != "unknown_tool" { t.Fatalf("%s in a Coordinator turn %+v", name, res) } } } // TestContractAssistantCancelAndAuth: cancel in the lane, ids from the // other lane unknown, and the bearer alone admits. func TestContractAssistantCancelAndAuth(t *testing.T) { r, runner := newAssistRig(t) a := r.client.Assistant() sent, err := a.Send(r.ctx, "a long errand", "a-1") if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) coord, err := r.client.Send(r.ctx, "hello", "c-1") if err != nil { t.Fatal(err) } if _, err = a.Cancel(r.ctx, coord.Turn.ID); Status(err) != 404 { t.Fatalf("a Coordinator turn cancelled as the Assistant's: %v", err) } if _, err = r.client.Cancel(r.ctx, sent.Turn.ID); Status(err) != 404 { t.Fatalf("an Assistant turn cancelled as the Coordinator's: %v", err) } accepted, err := a.Cancel(r.ctx, sent.Turn.ID) if err != nil || accepted.Attempt != 1 { t.Fatalf("cancel %+v %v", accepted, err) } for { _, frame, err := runner.Next(r.ctx) if err != nil { t.Fatal(err) } if c, ok := frame.(*wire.CancelCommand); ok { if c.TurnID != sent.Turn.ID { t.Fatalf("cancel frame %+v", c) } break } } runner.Send(r.ctx, "a-cancelled", wire.FrameTurn, wire.TurnReport{TurnID: sent.Turn.ID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}) deadline := time.Now().Add(10 * time.Second) for { _, err = a.Cancel(r.ctx, sent.Turn.ID) var e wire.Error if s, ok := err.(*ErrStatus); ok && s.Status == http.StatusConflict && json.Unmarshal(s.Body, &e) == nil && e.Code == "turn_ended" { break } if time.Now().After(deadline) { t.Fatalf("second cancel %v", err) } time.Sleep(50 * time.Millisecond) } if _, err = a.Cancel(r.ctx, "t_nothing"); Status(err) != 404 { t.Fatalf("unknown turn %v", err) } // Every route takes the bearer and nothing else: no bearer is 401, // with the browser's session cookie too. 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", ""}} for _, route := range routes { for _, cookie := range []*http.Cookie{nil, r.inst.Cookie()} { status, header, body := raw(t, route[0], r.inst.URL+"/api/v1/assistant"+route[1], "", cookie, route[2]) var e wire.Error if status != http.StatusUnauthorized || json.Unmarshal(body, &e) != nil || e.Code != "unauthenticated" || header.Get("Cache-Control") != "no-store" { t.Fatalf("%s %s cookie %v: %d %s", route[0], route[1], cookie != nil, status, body) } } } 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" { t.Fatalf("snapshot with the bearer %d", status) } } // TestContractAssistantKeysPerLane: an idempotency key is the person's // per lane. Every key the Coordinator took before lanes still works, // retries included, and the Assistant may use the same keys. func TestContractAssistantKeysPerLane(t *testing.T) { r, _ := newAssistRig(t) a := r.client.Assistant() old, err := r.client.Send(r.ctx, "from before", "assistant:x") if err != nil { t.Fatalf("a Coordinator key that was always valid: %v", err) } // As a row from before lanes: no lane at all. if _, err = r.inst.DB.Writer().Exec("UPDATE chat_messages SET lane = NULL WHERE id = ?", old.Message.ID); err != nil { t.Fatal(err) } if again, err := r.client.Send(r.ctx, "from before", "assistant:x"); err != nil || again.Message.ID != old.Message.ID { t.Fatalf("historical retry %+v %v", again, err) } mine := map[string]string{} for _, key := range []string{"x", "assistant:x"} { sent, err := a.Send(r.ctx, "hello", key) if err != nil || sent.Message.ID == old.Message.ID { t.Fatalf("Assistant key %q: %+v %v", key, sent, err) } mine[key] = sent.Message.ID } coord, err := r.client.Send(r.ctx, "hello", "x") if err != nil || coord.Message.ID == mine["x"] { t.Fatalf("Coordinator key x beside the Assistant's: %+v %v", coord, err) } for key, id := range mine { if again, err := a.Send(r.ctx, "hello", key); err != nil || again.Message.ID != id { t.Fatalf("Assistant retry %q %+v %v", key, again, err) } } if again, err := r.client.Send(r.ctx, "hello", "x"); err != nil || again.Message.ID != coord.Message.ID { t.Fatalf("Coordinator retry %+v %v", again, err) } } // TestContractAssistantAnswerNeedsRunner: an answer is a new Assistant // message, so it too needs a primary that can carry it. Refused, it // changes nothing: the card stays open and nothing is queued. func TestContractAssistantAnswerNeedsRunner(t *testing.T) { r, runner := newAssistRig(t) a := r.client.Assistant() sent, err := a.Send(r.ctx, "book me in", "a-1") if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-ack", wire.FrameAck, wire.Ack{ID: f.ID}) tools := &toolRig{rig: r, runner: runner, turn: sent.Turn.ID} if res := tools.call("q1", wire.ToolAskPerson, map[string]any{"question": "Which day?", "options": []string{"Monday", "Tuesday"}}); res.Code != "asked" { t.Fatalf("ask_person %+v", res) } runner.Send(r.ctx, "a-reply", wire.FrameReply, wire.Reply{TurnID: sent.Turn.ID, Attempt: 1, Text: "Which day suits?"}) var card wire.AssistantCard deadline := time.Now().Add(10 * time.Second) for { snap, err := a.Snapshot(r.ctx) if err == nil && len(snap.Cards) == 1 && len(snap.Turns) == 1 && snap.Turns[0].State == wire.TurnReplied { card = snap.Cards[0] break } if time.Now().After(deadline) { t.Fatalf("no card %+v %v", snap, err) } time.Sleep(50 * time.Millisecond) } runner.Close() r.wait("offline", func(c *Conversation) bool { return !c.Runner.Online }) unchanged := func(code string) { t.Helper() snap, err := a.Snapshot(r.ctx) 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 { t.Fatalf("%s changed the lane %+v %v", code, snap, err) } var waiting int64 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 { t.Fatalf("%s queued %d messages %v", code, waiting, err) } } refused := func(code string) { t.Helper() _, err := a.Answer(r.ctx, card.ID, "Tuesday", card.Revision) var e wire.Error if s, ok := err.(*ErrStatus); !ok || s.Status != http.StatusConflict || json.Unmarshal(s.Body, &e) != nil || e.Code != code { t.Fatalf("answer with %s: %v", code, err) } unchanged(code) } // The same primary back on protocol 18, after the fence ran. older := r.dialAt(wire.ProtocolModels) refused("runner_too_old") older.Close() r.wait("offline again", func(c *Conversation) bool { return !c.Runner.Online }) // The primary removed: nobody runs for the person. var id string var revision int64 if err := r.inst.DB.Writer().QueryRow("SELECT id, revision FROM runners").Scan(&id, &revision); err != nil { t.Fatal(err) } if err := r.inst.Store.RevokeRunner(r.ctx, equipo.Actor{Address: Owner}, id, revision); err != nil { t.Fatal(err) } refused("no_runner") }