oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "io"
8 "log/slog"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14 "unicode/utf8"
15
16 "amadan.net/oficina/equipo/internal/equipo/assist"
17 "amadan.net/oficina/equipo/internal/wire"
18 "amadan.net/rastrillo/rastrillo/db"
19 "gorm.io/gorm"
20)
21
22// TestTeamRequestOnceByKey: the team provider is called again with the
23// key it was called with (a process that stopped before it stored the
24// result calls again): the first request answers, whatever the input,
25// and nothing more is handed over.
26func TestTeamRequestOnceByKey(t *testing.T) {
27 const person = "owner@example.com"
28 src, err := hkTemplatePath()
29 if err != nil {
30 t.Fatal(err)
31 }
32 raw, err := os.ReadFile(src)
33 if err != nil {
34 t.Fatal(err)
35 }
36 path := filepath.Join(t.TempDir(), "handoff.db")
37 if err := os.WriteFile(path, raw, 0o600); err != nil {
38 t.Fatal(err)
39 }
40 d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
41 if err != nil {
42 t.Fatal(err)
43 }
44 t.Cleanup(func() { _ = d.Close() })
45 s := NewStore(d, Authority{
46 PrimaryRunner: func(*gorm.DB, string) (string, error) { return "RUNNER1", nil },
47 Audit: func(*gorm.DB, string, string, string) error { return nil },
48 }, nil)
49 now := time.Now().UTC()
50 if err := d.G.Create(&turnRecord{ID: "t_1", Person: person, State: wire.TurnRunning, Attempt: 1, Dispatched: true, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: wire.LaneAssistant}).Error; err != nil {
51 t.Fatal(err)
52 }
53 if err := d.G.Create(&messageRecord{ID: "m_1", Person: person, IdempotencyKey: "a-1", Role: wire.RolePerson, Text: "Can we fix a bug in Tito? Login is broken", TurnID: "t_1", Revision: 1, CreatedAt: now, Lane: wire.LaneAssistant}).Error; err != nil {
54 t.Fatal(err)
55 }
56 call := toolCallRecord{CallID: "t_1/1/u1", Person: person, TurnID: "t_1", Attempt: 1, Name: wire.ToolUse, Lane: wire.LaneAssistant, Operation: opTeamRequest}
57 ctx := withCall(context.Background(), call)
58 p := s.TeamProvider()
59 first, err := p.Invoke(ctx, person, opTeamRequest, json.RawMessage(`{"words":"Login is broken"}`), "5f0c2d3e-0000-5000-8000-000000000001")
60 if err != nil {
61 t.Fatal(err)
62 }
63 again, err := p.Invoke(ctx, person, opTeamRequest, json.RawMessage(`{"words":"a bug in Tito"}`), "5f0c2d3e-0000-5000-8000-000000000001")
64 if err != nil || string(again) != string(first) {
65 t.Fatalf("again %s %v, first %s", again, err, first)
66 }
67 var handoffs, messages int64
68 d.G.Model(&handoffRecord{}).Count(&handoffs)
69 d.G.Model(&messageRecord{}).Where("lane LIKE 'job:%'").Count(&messages)
70 if handoffs != 1 || messages != 1 {
71 t.Fatalf("%d hand-offs, %d thread messages", handoffs, messages)
72 }
73}
74
75// TestFallbackTitle (D10): a hand-off with no title of the model's is
76// named by the person's words on one line: whole up to 60 characters,
77// otherwise their first 59 cut at the last space, plus "…".
78func TestFallbackTitle(t *testing.T) {
79 sixty := strings.Repeat("word ", 11) + "abcde"
80 for words, want := range map[string]string{
81 sixty: sixty,
82 strings.Repeat("é", 60): strings.Repeat("é", 60),
83 strings.Repeat("abcd ", 15): strings.Repeat("abcd ", 10) + "abcd…",
84 strings.Repeat("a", 75): strings.Repeat("a", 59) + "…",
85 " Fix the\n login \t page ": "Fix the login page",
86 } {
87 got := fallbackTitle(words)
88 if got != want || utf8.RuneCountInString(got) > 60 {
89 t.Fatalf("fallbackTitle(%q) = %q, want %q", words, got, want)
90 }
91 }
92 long := strings.Repeat("abcd ", 15)
93 got := fallbackTitle(long)
94 cut := strings.TrimSuffix(got, "…")
95 if cut == got || !strings.HasPrefix(long, cut) || long[len(cut)] != ' ' {
96 t.Fatalf("not cut at a space: %q", got)
97 }
98}
99
100// TestJobNoteBlockedLines: every cause that stops a job for its person
101// has a plain line for the Assistant (noteBlocked): each team card that
102// waits on them, each need of a task's but the go-ahead and a retryable
103// step, and going live that failed. Unknown, it is no line.
104func TestJobNoteBlockedLines(t *testing.T) {
105 causes := []string{wire.CardAccess, wire.CardHome, wire.CardDirection, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardMergeShips, wire.CardMergePolicy, wire.CardMakerRemoved,
106 wire.NeedsHeld, wire.NeedsBranchMoved, wire.NeedsReviewBlocked, wire.NeedsFixRounds, wire.NeedsMergeConflict, wire.NeedsMachineRemoved, wire.NeedsRunnerOffline, wire.NeedsMacSandbox, wire.NeedsDirection, causeGoingLive, causeNoAccess}
107 for _, c := range causes {
108 if line := blockedLine(c); line == "" || strings.HasSuffix(line, ".") || strings.ContainsAny(line, "\n[]") {
109 t.Errorf("%s: %q", c, line)
110 }
111 }
112 if blockedLine(wire.NeedsRunnerOffline) != blockedLine(wire.NeedsMachineRemoved) || blockedLine(wire.CardMergeShips) != blockedLine(wire.CardMergePolicy) {
113 t.Error("causes that ask the same thing say it differently")
114 }
115 for _, c := range []string{"", wire.NeedsMerge, wire.NeedsRetry, "something_new"} {
116 if line := blockedLine(c); line != "" {
117 t.Errorf("%q: %q", c, line)
118 }
119 }
120 // Going live refused for want of access: what is missing, and never
121 // an invitation to try the same again.
122 if line := blockedLine(causeNoAccess); !strings.Contains(line, "no access") || strings.Contains(strings.ToLower(line), "equipo") || strings.Contains(line, "need to try it again") || line == blockedLine(causeGoingLive) {
123 t.Errorf("no access: %q", line)
124 }
125}
126
127// TestGoingLiveCause: a failed merge refused for want of access (the
128// runner's own refusal, or the hub's forbidden) stops its job on access;
129// any other failed merge or publish on going live.
130func TestGoingLiveCause(t *testing.T) {
131 for _, c := range []struct {
132 s *stepRecord
133 want string
134 }{
135 {&stepRecord{Specialist: wire.SpecialistMerge, Reason: wire.ReasonMergeCredential}, causeNoAccess},
136 {&stepRecord{Specialist: wire.SpecialistMerge, Reason: "merge_forbidden"}, causeNoAccess},
137 {&stepRecord{Specialist: wire.SpecialistMerge, Reason: "merge_failed"}, causeGoingLive},
138 {&stepRecord{Specialist: wire.SpecialistPublish, Reason: wire.ReasonMergeCredential}, causeGoingLive},
139 {nil, causeGoingLive},
140 } {
141 if got := goingLiveCause(c.s); got != c.want {
142 t.Errorf("%+v: %q, want %q", c.s, got, c.want)
143 }
144 }
145}
146
147// TestTeamRequestLeavesFilesBehind (A5): a hand-off from an Assistant turn
148// whose message carries files goes ahead without them. The result says
149// how many stayed behind, the job thread's message has none, and the
150// job's context ends with the instance's line about them, also on a
151// repeated call. Without files there is no field and no line; a message
152// of files alone has no words to hand over, so nothing is made.
153func TestTeamRequestLeavesFilesBehind(t *testing.T) {
154 request := func(t *testing.T, text string, files ...string) (*hkRig, json.RawMessage, error) {
155 r := filesRig(t, wire.ProtocolAssistantFiles)
156 turn := turnRecord{ID: "t_1", Person: hkOwner, State: wire.TurnRunning, Kind: wire.TurnPerson, Attempt: 1, Dispatched: true, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: wire.LaneAssistant}
157 r.must(r.s.db.G.Create(&turn).Error)
158 r.must(r.s.db.G.Create(&messageRecord{ID: "m_1", Person: hkOwner, IdempotencyKey: "a-1", Role: wire.RolePerson, Text: text, TurnID: "t_1", Revision: 1, CreatedAt: r.now, Lane: wire.LaneAssistant, Origin: originComposer}).Error)
159 for i, name := range files {
160 id := r.upload(hkOwner, name, "# "+name)
161 r.must(r.s.db.G.Model(&fileRecord{}).Where("id = ?", id).Updates(map[string]any{"message_id": "m_1", "position": i + 1}).Error)
162 }
163 call := toolCallRecord{CallID: "t_1/1/u1", Person: hkOwner, TurnID: "t_1", Attempt: 1, Name: wire.ToolUse, Lane: wire.LaneAssistant, Operation: opTeamRequest}
164 out, err := r.s.TeamProvider().Invoke(withCall(r.ctx, call), hkOwner, opTeamRequest, json.RawMessage(`{"words":"Fix the login page","context":"Tito's web app."}`), "5f0c2d3e-0000-5000-8000-000000000001")
165 return r, out, err
166 }
167 result := func(t *testing.T, raw json.RawMessage) map[string]any {
168 var m map[string]any
169 if err := json.Unmarshal(raw, &m); err != nil {
170 t.Fatal(err)
171 }
172 return m
173 }
174
175 r, out, err := request(t, "Please fix the login page", "shot.md", "notes.md")
176 if err != nil {
177 t.Fatal(err)
178 }
179 if got := result(t, out); got["files_left_behind"] != float64(2) {
180 t.Fatalf("result %s", out)
181 }
182 var h handoffRecord
183 r.must(r.s.db.G.First(&h).Error)
184 if want := "Tito's web app. " + filesLeftBehind(2); h.Context != want {
185 t.Fatalf("context %q, want %q", h.Context, want)
186 }
187 if n := r.count("SELECT count(*) FROM chat_attachments WHERE message_id = ?", h.MessageID); n != 0 {
188 t.Fatalf("the job's message has %d files", n)
189 }
190 call := toolCallRecord{CallID: "t_1/1/u1", Person: hkOwner, TurnID: "t_1", Attempt: 1, Name: wire.ToolUse, Lane: wire.LaneAssistant, Operation: opTeamRequest}
191 again, err := r.s.TeamProvider().Invoke(withCall(r.ctx, call), hkOwner, opTeamRequest, json.RawMessage(`{"words":"Fix the login page"}`), "5f0c2d3e-0000-5000-8000-000000000001")
192 if err != nil || string(again) != string(out) {
193 t.Fatalf("again %s %v", again, err)
194 }
195
196 _, out, err = request(t, "Please fix the login page")
197 if err != nil || strings.Contains(string(out), "files_left_behind") {
198 t.Fatalf("without files %s %v", out, err)
199 }
200 r, _, err = request(t, "", "shot.md")
201 var f assist.Failure
202 if !errors.As(err, &f) || f.Code != "invalid_input" || r.count("SELECT count(*) FROM chat_handoffs") != 0 {
203 t.Fatalf("files alone: %v", err)
204 }
205 if filesLeftBehind(1) != "The person attached 1 file to this request in their conversation. This job cannot see it." {
206 t.Fatalf("one file: %q", filesLeftBehind(1))
207 }
208 if !strings.Contains(teamOps[0].Description, "files_left_behind") || !strings.Contains(string(teamOps[0].Output), "files_left_behind") {
209 t.Fatal("the operation does not say the job can't see the files")
210 }
211}
212