| 1 | package equipo_test |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "crypto/ed25519" |
| 7 | "crypto/rand" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "os" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/rastrillo/rastrillo/budget" |
| 18 | |
| 19 | "amadan.net/oficina/base/internal/equipo" |
| 20 | "amadan.net/oficina/base/internal/equipo/equipotest" |
| 21 | ) |
| 22 | |
| 23 | func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| 24 | |
| 25 | // signIn runs the device flow against f, approving the code at once. |
| 26 | func signIn(t *testing.T, f *equipotest.Fake, c *equipo.Client) equipo.Credential { |
| 27 | t.Helper() |
| 28 | ctx := context.Background() |
| 29 | pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| 30 | ch, err := c.BeginDevice(ctx, pub, "Base (Acme)") |
| 31 | if err != nil { |
| 32 | t.Fatal(err) |
| 33 | } |
| 34 | proof, err := equipo.Prove(key, ch, rand.Text()) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | if _, err := c.Exchange(ctx, proof); !errors.Is(err, equipo.ErrPending) { |
| 39 | t.Fatalf("before approval: %v, want ErrPending", err) |
| 40 | } |
| 41 | if err := f.Approve(ch.UserCode); err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | cred, err := c.Exchange(ctx, proof) |
| 45 | if err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | return cred |
| 49 | } |
| 50 | |
| 51 | func TestDeviceFlowAndRevoke(t *testing.T) { |
| 52 | f := equipotest.New(t) |
| 53 | c := equipo.New(f.URL) |
| 54 | cred := signIn(t, f, c) |
| 55 | if !strings.HasPrefix(cred.Token, "equipo.person.v1.") || cred.Revision != 3 || cred.ExpiresAt.IsZero() { |
| 56 | t.Fatalf("credential: %+v", cred) |
| 57 | } |
| 58 | for _, call := range f.Calls("") { |
| 59 | if call.Header.Get("Idempotency-Key") == "" || call.Header.Get("Cookie") != "" || call.Header.Get("Origin") != "" { |
| 60 | t.Errorf("%s %s headers: %v", call.Method, call.Path, call.Header) |
| 61 | } |
| 62 | } |
| 63 | ctx := context.Background() |
| 64 | if _, err := c.Snapshot(ctx, cred.Token); err != nil { |
| 65 | t.Fatal(err) |
| 66 | } |
| 67 | if err := c.RevokeDevice(ctx, cred.Token, cred.ID, cred.Revision); err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | if _, err := c.Snapshot(ctx, cred.Token); !errors.Is(err, equipo.ErrUnauthenticated) { |
| 71 | t.Fatalf("after revoke: %v, want ErrUnauthenticated", err) |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | func TestExpiredCode(t *testing.T) { |
| 76 | f := equipotest.New(t) |
| 77 | c := equipo.New(f.URL) |
| 78 | ctx := context.Background() |
| 79 | pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| 80 | ch, err := c.BeginDevice(ctx, pub, "Base") |
| 81 | if err != nil { |
| 82 | t.Fatal(err) |
| 83 | } |
| 84 | f.Expire() |
| 85 | proof, _ := equipo.Prove(key, ch, rand.Text()) |
| 86 | if _, err := c.Exchange(ctx, proof); !errors.Is(err, equipo.ErrExpired) { |
| 87 | t.Fatalf("expired: %v", err) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | func TestSendCarriesBearerAndKey(t *testing.T) { |
| 92 | f := equipotest.New(t) |
| 93 | c := equipo.New(f.URL) |
| 94 | cred := signIn(t, f, c) |
| 95 | sent, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1", nil) |
| 96 | if err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | if sent.Message.Text != "What can I do" || sent.Turn.ID == "" || sent.Turn.State != "queued" { |
| 100 | t.Fatalf("sent: %+v", sent) |
| 101 | } |
| 102 | calls := f.Calls("/api/v1/assistant/messages") |
| 103 | if len(calls) != 1 { |
| 104 | t.Fatalf("calls: %+v", calls) |
| 105 | } |
| 106 | h := calls[0].Header |
| 107 | if h.Get("Authorization") != "Bearer "+cred.Token || h.Get("Idempotency-Key") != "k-1" { |
| 108 | t.Errorf("headers: %v", h) |
| 109 | } |
| 110 | var body map[string]string |
| 111 | if err := json.Unmarshal([]byte(calls[0].Body), &body); err != nil || body["idempotency_key"] != "k-1" { |
| 112 | t.Errorf("body: %s", calls[0].Body) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | func TestSealIsPerMember(t *testing.T) { |
| 117 | s := equipo.NewSealer("instance-key") |
| 118 | blob, err := s.Seal("member-a", []byte("equipo.person.v1.secret")) |
| 119 | if err != nil { |
| 120 | t.Fatal(err) |
| 121 | } |
| 122 | if strings.Contains(string(blob), "secret") { |
| 123 | t.Fatal("sealed blob holds the plaintext") |
| 124 | } |
| 125 | if got, err := s.Open("member-a", blob); err != nil || string(got) != "equipo.person.v1.secret" { |
| 126 | t.Fatalf("open: %q %v", got, err) |
| 127 | } |
| 128 | if _, err := s.Open("member-b", blob); err == nil { |
| 129 | t.Fatal("another member's key opened it") |
| 130 | } |
| 131 | if _, err := equipo.NewSealer("other-key").Open("member-a", blob); err == nil { |
| 132 | t.Fatal("another instance key opened it") |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // An Equipo that never answers the stream's headers does not hold Base. |
| 137 | func TestEventsHeaderTimeout(t *testing.T) { |
| 138 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })) |
| 139 | defer srv.Close() |
| 140 | c := equipo.New(srv.URL) |
| 141 | c.StreamHeaderTimeout = 100 * time.Millisecond |
| 142 | start := time.Now() |
| 143 | if _, err := c.Events(context.Background(), "token", ""); err == nil || time.Since(start) > 2*time.Second { |
| 144 | t.Fatalf("Events: %v after %s", err, time.Since(start)) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Every chat call goes to the Assistant's routes with the member's bearer; |
| 149 | // the Coordinator's routes are never called. |
| 150 | func TestClientUsesAssistantRoutes(t *testing.T) { |
| 151 | f := equipotest.New(t) |
| 152 | c := equipo.New(f.URL) |
| 153 | cred := signIn(t, f, c) |
| 154 | ctx := context.Background() |
| 155 | q := f.AskQuestion("Which one?", "a", "b") |
| 156 | f.Hold = true |
| 157 | snap, err := c.Snapshot(ctx, cred.Token) |
| 158 | if err != nil || len(snap.Cards) != 1 || !snap.Available || snap.Me.Address != "paul@tito.io" { |
| 159 | t.Fatalf("snapshot: %+v %v", snap, err) |
| 160 | } |
| 161 | sent, err := c.Send(ctx, cred.Token, "What can I do", "k-1", nil) |
| 162 | if err != nil { |
| 163 | t.Fatal(err) |
| 164 | } |
| 165 | if err := c.Cancel(ctx, cred.Token, sent.Turn.ID, "k-2"); err != nil { |
| 166 | t.Fatal(err) |
| 167 | } |
| 168 | if _, err := c.Answer(ctx, cred.Token, q, "a", 1, "k-3"); err != nil { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | res, err := c.Events(ctx, cred.Token, "41") |
| 172 | if err != nil { |
| 173 | t.Fatal(err) |
| 174 | } |
| 175 | res.Body.Close() |
| 176 | // A fake host token, built here so no token-shaped literal lands in |
| 177 | // the repository. |
| 178 | hostToken := "bh_" + strings.Repeat("A", 43) |
| 179 | if err := c.RegisterHost(ctx, cred.Token, "https://base.example.test", hostToken); err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | want := map[string]string{ |
| 183 | "GET /api/v1/assistant/snapshot": "", |
| 184 | "POST /api/v1/assistant/messages": "", |
| 185 | "POST /api/v1/assistant/turns/" + sent.Turn.ID + "/cancel": "", |
| 186 | "POST /api/v1/assistant/cards/" + q + "/answer": "", |
| 187 | "GET /api/v1/assistant/events": "", |
| 188 | "PUT /api/v1/assistant/host": "", |
| 189 | } |
| 190 | for _, call := range f.Calls("") { |
| 191 | if strings.HasPrefix(call.Path, "/api/v1/auth/") { |
| 192 | continue |
| 193 | } |
| 194 | key := call.Method + " " + call.Path |
| 195 | if _, ok := want[key]; !ok { |
| 196 | t.Errorf("called %s", key) |
| 197 | continue |
| 198 | } |
| 199 | if call.Header.Get("Authorization") != "Bearer "+cred.Token { |
| 200 | t.Errorf("%s without the bearer: %v", key, call.Header) |
| 201 | } |
| 202 | delete(want, key) |
| 203 | } |
| 204 | for key := range want { |
| 205 | t.Errorf("never called %s", key) |
| 206 | } |
| 207 | for _, old := range []string{"/api/v1/snapshot", "/api/v1/messages", "/api/v1/events"} { |
| 208 | if n := len(f.Calls(old)); n != 0 { |
| 209 | t.Errorf("%d calls to %s", n, old) |
| 210 | } |
| 211 | } |
| 212 | hosts := f.Hosts() |
| 213 | if len(hosts) != 1 || strings.TrimSpace(hosts[0].Body) != `{"origin":"https://base.example.test","token":"`+hostToken+`"}` { |
| 214 | t.Fatalf("hosts: %+v", hosts) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | // Without a runner Equipo refuses a message: 409 no_runner, which Base |
| 219 | // can tell from runner_too_old. |
| 220 | func TestSendWithoutRunner(t *testing.T) { |
| 221 | f := equipotest.New(t) |
| 222 | c := equipo.New(f.URL) |
| 223 | cred := signIn(t, f, c) |
| 224 | f.NoRunner() |
| 225 | _, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1", nil) |
| 226 | if !errors.Is(err, equipo.ErrNoRunner) || errors.Is(err, equipo.ErrRunnerTooOld) { |
| 227 | t.Fatalf("send: %v, want ErrNoRunner", err) |
| 228 | } |
| 229 | if snap, err := c.Snapshot(context.Background(), cred.Token); err != nil || snap.Available || len(snap.Messages) != 0 { |
| 230 | t.Fatalf("snapshot: %+v %v", snap, err) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // Base keeps the four card kinds the Assistant draws, with their own |
| 235 | // fields and only web links; any other kind stays in Equipo. |
| 236 | func TestCardClean(t *testing.T) { |
| 237 | opts := []equipo.Option{{Value: "go", Label: "Go ahead"}, {Value: "later", Label: "Not yet"}} |
| 238 | for name, c := range map[string]struct { |
| 239 | in equipo.Card |
| 240 | want string |
| 241 | }{ |
| 242 | "confirm": {equipo.Card{ID: "c1", Revision: 2, Kind: "confirm", State: "open", Question: "Send it?", Options: opts, |
| 243 | Links: []equipo.Link{{Label: "See it", URL: "https://x.test/a"}}}, |
| 244 | `{"id":"c1","revision":2,"kind":"confirm","state":"open","question":"Send it?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[{"label":"See it","url":"https://x.test/a"}],"result":""}`}, |
| 245 | "connect": {equipo.Card{ID: "c2", Revision: 1, Kind: "connect", State: "resolved", Question: "Connect Calendar", Result: "Connected", |
| 246 | Links: []equipo.Link{{Label: "Connect", URL: "https://connect.test/consent?x=1"}}}, |
| 247 | `{"id":"c2","revision":1,"kind":"connect","state":"resolved","question":"Connect Calendar","options":[],"links":[{"label":"Connect","url":"https://connect.test/consent?x=1"}],"result":"Connected"}`}, |
| 248 | "unsafe links": {equipo.Card{ID: "c3", Kind: "outcome", State: "open", Links: []equipo.Link{ |
| 249 | {Label: "a", URL: "javascript:alert(1)"}, {Label: "b", URL: "/tasks/tk1"}, {Label: "c", URL: "https://user:pw@x.test/"}, |
| 250 | {Label: "d", URL: "https://ok.test/"}}}, |
| 251 | `{"id":"c3","revision":0,"kind":"outcome","state":"open","question":"","options":[],"links":[{"label":"d","url":"https://ok.test/"}],"result":""}`}, |
| 252 | } { |
| 253 | got, ok := c.in.Clean() |
| 254 | raw, _ := json.Marshal(got) |
| 255 | if !ok || string(raw) != c.want { |
| 256 | t.Errorf("%s: %v\n got %s\nwant %s", name, ok, raw, c.want) |
| 257 | } |
| 258 | } |
| 259 | for _, kind := range []string{"task", "merge", "publish", "project", ""} { |
| 260 | if _, ok := (equipo.Card{ID: "c6", Kind: kind, State: "open"}).Clean(); ok { |
| 261 | t.Errorf("a %q card was kept", kind) |
| 262 | } |
| 263 | } |
| 264 | var in equipo.Card |
| 265 | raw := `{"id":"c7","revision":1,"kind":"question","state":"open","question":"Which?","options":[{"value":"a","label":"A"}],"links":[],"result":"","task_id":"tk1","site":{"app":"x"}}` |
| 266 | if err := json.Unmarshal([]byte(raw), &in); err != nil { |
| 267 | t.Fatal(err) |
| 268 | } |
| 269 | const want = `{"id":"c7","revision":1,"kind":"question","state":"open","question":"Which?","options":[{"value":"a","label":"A"}],"links":[],"result":""}` |
| 270 | if out, _ := json.Marshal(in); string(out) != want { |
| 271 | t.Errorf("decoded with extra fields: %s", out) |
| 272 | } |
| 273 | got, ok := in.Clean() |
| 274 | if out, _ := json.Marshal(got); !ok || string(out) != want { |
| 275 | t.Errorf("extra fields: %v %s", ok, out) |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | // A card shows while it is open, and afterwards only if it says how it |
| 280 | // ended. |
| 281 | func TestCardShown(t *testing.T) { |
| 282 | for _, c := range []struct { |
| 283 | state, result string |
| 284 | want bool |
| 285 | }{{"open", "", true}, {"answered", "", false}, {"answered", "Done", true}, {"resolved", "Published", true}, {"resolved", "", false}} { |
| 286 | if got := (equipo.Card{Kind: "outcome", State: c.state, Result: c.result}).Shown(); got != c.want { |
| 287 | t.Errorf("%s %q: shown %v", c.state, c.result, got) |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | // A job card keeps what Base draws of it: no options, the Equipo link's |
| 293 | // rel and no other, its detail and start time. A job in a state it does |
| 294 | // not know stays in Equipo; detail is a job's only, and an attached |
| 295 | // card's job id must look like one. |
| 296 | func TestCardCleanJob(t *testing.T) { |
| 297 | start := time.Date(2026, 11, 13, 9, 30, 0, 0, time.UTC) |
| 298 | in := equipo.Card{ID: "c_1", Revision: 3, Kind: equipo.CardJob, State: equipo.JobReady, Question: "Add a booking page", |
| 299 | Options: []equipo.Option{{Value: "go", Label: "Go"}}, Result: "Ready to look at", Detail: "Have a look before it goes live.", StartedAt: &start, |
| 300 | Links: []equipo.Link{{Label: "See it", URL: "https://preview.test/"}, {Label: "Odd", URL: "https://odd.test/", Rel: "other"}, |
| 301 | {Label: "Open in Equipo", URL: "https://equipo.test/jobs/h_1", Rel: equipo.LinkEquipo}}} |
| 302 | got, ok := in.Clean() |
| 303 | raw, _ := json.Marshal(got) |
| 304 | const want = `{"id":"c_1","revision":3,"kind":"job","state":"ready","question":"Add a booking page","options":[],"links":[{"label":"See it","url":"https://preview.test/"},{"label":"Odd","url":"https://odd.test/"},{"label":"Open in Equipo","url":"https://equipo.test/jobs/h_1","rel":"equipo"}],"result":"Ready to look at","detail":"Have a look before it goes live.","started_at":"2026-11-13T09:30:00Z"}` |
| 305 | if !ok || string(raw) != want { |
| 306 | t.Errorf("job: %v\n got %s\nwant %s", ok, raw, want) |
| 307 | } |
| 308 | if l, ok := got.Go(); !ok || l.URL != "https://preview.test/" { |
| 309 | t.Errorf("Go: %v %+v", ok, l) |
| 310 | } |
| 311 | if l, ok := got.Equipo(); !ok || l.URL != "https://equipo.test/jobs/h_1" { |
| 312 | t.Errorf("Equipo: %v %+v", ok, l) |
| 313 | } |
| 314 | only := equipo.Card{Kind: equipo.CardJob, State: equipo.JobWorking, Links: in.Links[2:]} |
| 315 | if l, ok := only.Go(); ok { |
| 316 | t.Errorf("a job with only its Equipo link has a Go link: %+v", l) |
| 317 | } |
| 318 | for _, state := range []string{equipo.JobWorking, equipo.JobAsking, equipo.JobDone, equipo.JobStopped} { |
| 319 | if _, ok := (equipo.Card{ID: "c_2", Kind: equipo.CardJob, State: state}).Clean(); !ok { |
| 320 | t.Errorf("a %s job was dropped", state) |
| 321 | } |
| 322 | } |
| 323 | for _, state := range []string{"pending", "open", ""} { |
| 324 | if _, ok := (equipo.Card{ID: "c_2", Kind: equipo.CardJob, State: state}).Clean(); ok { |
| 325 | t.Errorf("a %q job was kept", state) |
| 326 | } |
| 327 | } |
| 328 | outcome, ok := equipo.Card{ID: "c_3", Kind: equipo.CardOutcome, State: "open", Detail: "More", StartedAt: &start, Job: "c_1", |
| 329 | Links: []equipo.Link{{Label: "See it", URL: "https://preview.test/"}}}.Clean() |
| 330 | raw, _ = json.Marshal(outcome) |
| 331 | const wantOutcome = `{"id":"c_3","revision":0,"kind":"outcome","state":"open","question":"","options":[],"links":[{"label":"See it","url":"https://preview.test/"}],"result":"","job":"c_1"}` |
| 332 | if !ok || string(raw) != wantOutcome { |
| 333 | t.Errorf("outcome: %v\n got %s\nwant %s", ok, raw, wantOutcome) |
| 334 | } |
| 335 | if l, ok := outcome.Go(); ok { |
| 336 | t.Errorf("an outcome card has a job's Go link: %+v", l) |
| 337 | } |
| 338 | if l, ok := (equipo.Card{Kind: equipo.CardOutcome, Links: in.Links[2:]}).Equipo(); ok { |
| 339 | t.Errorf("an outcome card has a job's Equipo link: %+v", l) |
| 340 | } |
| 341 | for job, keep := range map[string]bool{"c_1": true, "C-9_x": true, strings.Repeat("a", 128): true, |
| 342 | "../x": false, "c 1": false, "c/1": false, strings.Repeat("a", 129): false, "": false} { |
| 343 | got, _ := (equipo.Card{ID: "c_4", Kind: equipo.CardOutcome, State: "open", Job: job}).Clean() |
| 344 | if (got.Job == job && job != "") != keep || !keep && got.Job != "" { |
| 345 | t.Errorf("job %q: kept %q", job, got.Job) |
| 346 | } |
| 347 | } |
| 348 | if !(equipo.Card{Kind: equipo.CardJob, State: equipo.JobWorking}).Shown() { |
| 349 | t.Error("a working job is not shown") |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // The fake raises and moves job cards as Equipo does: the Equipo link |
| 354 | // stays last, each change is a new revision and an event; a go-ahead can |
| 355 | // belong to a job, and a turn of any kind can appear. |
| 356 | func TestFakeJobCards(t *testing.T) { |
| 357 | f := equipotest.New(t) |
| 358 | c := equipo.New(f.URL) |
| 359 | cred := signIn(t, f, c) |
| 360 | ctx := context.Background() |
| 361 | id := f.AskJob("Add a booking page") |
| 362 | f.SetJob(id, equipo.JobReady, "Ready to look at", "Have a look.", equipo.Link{Label: "See it", URL: "https://preview.test/"}) |
| 363 | go1 := f.AskOutcomeFor(id, "This is ready. Go ahead?", []equipo.Option{{Value: "go", Label: "Go ahead"}}, nil) |
| 364 | tid := f.EmitTurn("team_update", equipo.TurnRunning) |
| 365 | snap, err := c.Snapshot(ctx, cred.Token) |
| 366 | if err != nil || len(snap.Cards) != 2 || len(snap.Turns) != 1 { |
| 367 | t.Fatalf("snapshot: %+v %v", snap, err) |
| 368 | } |
| 369 | job, ok := snap.Cards[0].Clean() |
| 370 | if !ok || job.ID != id || job.Revision != 2 || job.State != equipo.JobReady || job.Question != "Add a booking page" || |
| 371 | job.Result != "Ready to look at" || job.Detail != "Have a look." || job.StartedAt == nil || time.Since(*job.StartedAt) > time.Minute { |
| 372 | t.Errorf("job: %v %+v", ok, job) |
| 373 | } |
| 374 | if l, ok := job.Go(); !ok || l.URL != "https://preview.test/" { |
| 375 | t.Errorf("Go: %v %+v", ok, l) |
| 376 | } |
| 377 | if l, ok := job.Equipo(); !ok || len(job.Links) != 2 || job.Links[1] != l || l.Label != "Open in Equipo" || |
| 378 | !strings.HasPrefix(l.URL, f.URL+"/jobs/h_") { |
| 379 | t.Errorf("Equipo link: %v %+v", ok, job.Links) |
| 380 | } |
| 381 | if o := snap.Cards[1]; o.ID != go1 || o.Kind != equipo.CardOutcome || o.Job != id || o.State != "open" { |
| 382 | t.Errorf("attached card: %+v", o) |
| 383 | } |
| 384 | if tr := snap.Turns[0]; tr.ID != tid || tr.Kind != "team_update" || tr.State != equipo.TurnRunning { |
| 385 | t.Errorf("turn: %+v", tr) |
| 386 | } |
| 387 | sctx, cancel := context.WithTimeout(ctx, 2*time.Second) |
| 388 | defer cancel() |
| 389 | res, err := c.Events(sctx, cred.Token, "40") |
| 390 | if err != nil { |
| 391 | t.Fatal(err) |
| 392 | } |
| 393 | defer res.Body.Close() |
| 394 | var seen []string |
| 395 | sc := bufio.NewScanner(res.Body) |
| 396 | for len(seen) < 4 && sc.Scan() { |
| 397 | if line, ok := strings.CutPrefix(sc.Text(), "event: "); ok { |
| 398 | seen = append(seen, line) |
| 399 | } |
| 400 | } |
| 401 | if strings.Join(seen, " ") != "card card card turn" { |
| 402 | t.Errorf("events: %v", seen) |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | // readFrames reads the stream's frames (each its lines) until one holds |
| 407 | // until, or the stream ends. |
| 408 | func readFrames(t *testing.T, sc *bufio.Scanner, until string) []string { |
| 409 | t.Helper() |
| 410 | var frames []string |
| 411 | var cur []string |
| 412 | for sc.Scan() { |
| 413 | if sc.Text() != "" { |
| 414 | cur = append(cur, sc.Text()) |
| 415 | continue |
| 416 | } |
| 417 | if len(cur) == 0 { |
| 418 | continue |
| 419 | } |
| 420 | f := strings.Join(cur, "\n") |
| 421 | cur = nil |
| 422 | frames = append(frames, f) |
| 423 | if strings.Contains(f, until) { |
| 424 | return frames |
| 425 | } |
| 426 | } |
| 427 | t.Fatalf("the stream ended before %q: %q", until, frames) |
| 428 | return nil |
| 429 | } |
| 430 | |
| 431 | // The fake sends a glance as Equipo does: live only, without an id line |
| 432 | // and with cursor 0, so the cursor runs on unbroken past it; a stream |
| 433 | // that reconnects with its cursor never gets it again. |
| 434 | func TestFakeGlanceIsLiveOnly(t *testing.T) { |
| 435 | f := equipotest.New(t) |
| 436 | f.Hold = true |
| 437 | c := equipo.New(f.URL) |
| 438 | cred := signIn(t, f, c) |
| 439 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 440 | defer cancel() |
| 441 | sent, err := c.Send(ctx, cred.Token, "What's on today?", "k-1", nil) |
| 442 | if err != nil { |
| 443 | t.Fatal(err) |
| 444 | } |
| 445 | res, err := c.Events(ctx, cred.Token, "40") |
| 446 | if err != nil { |
| 447 | t.Fatal(err) |
| 448 | } |
| 449 | defer res.Body.Close() |
| 450 | sc := bufio.NewScanner(res.Body) |
| 451 | readFrames(t, sc, `"state":"running"`) |
| 452 | f.Glance(sent.Turn.ID, "Checking your diary") |
| 453 | f.Say("Two meetings.") |
| 454 | frames := readFrames(t, sc, "Two meetings.") |
| 455 | if len(frames) != 2 { |
| 456 | t.Fatalf("frames after the glance: %q", frames) |
| 457 | } |
| 458 | if want := "event: glance\ndata: "; !strings.HasPrefix(frames[0], want) || !strings.Contains(frames[0], `"cursor":0,`) || |
| 459 | !strings.Contains(frames[0], `"data":{"text":"Checking your diary","turn_id":"`+sent.Turn.ID+`"}`) { |
| 460 | t.Errorf("the glance: %q", frames[0]) |
| 461 | } |
| 462 | if !strings.HasPrefix(frames[1], "id: 44\nevent: message\n") { |
| 463 | t.Errorf("after the glance: %q", frames[1]) |
| 464 | } |
| 465 | |
| 466 | again, err := c.Events(ctx, cred.Token, "40") |
| 467 | if err != nil { |
| 468 | t.Fatal(err) |
| 469 | } |
| 470 | defer again.Body.Close() |
| 471 | frames = readFrames(t, bufio.NewScanner(again.Body), "Two meetings.") |
| 472 | for _, fr := range frames { |
| 473 | if strings.Contains(fr, "glance") { |
| 474 | t.Errorf("replayed the glance: %q", frames) |
| 475 | } |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | // A paused job is kept, with carry_on when Equipo offers it; carry_on on a |
| 480 | // job in any other state, or on another kind of card, is dropped. A job |
| 481 | // card from an Equipo that never sends carry_on cleans to the same JSON |
| 482 | // as before (no carry_on key at all). |
| 483 | func TestCardCleanPausedJob(t *testing.T) { |
| 484 | got, ok := equipo.Card{ID: "c_1", Revision: 4, Kind: equipo.CardJob, State: equipo.JobPaused, Question: "Bakery website", |
| 485 | Result: "Paused until 21:00", Detail: "It will carry on by itself at 21:00 (in 9 hours).", CarryOn: true}.Clean() |
| 486 | raw, _ := json.Marshal(got) |
| 487 | const want = `{"id":"c_1","revision":4,"kind":"job","state":"paused","question":"Bakery website","options":[],"links":[],"result":"Paused until 21:00","detail":"It will carry on by itself at 21:00 (in 9 hours).","carry_on":true}` |
| 488 | if !ok || string(raw) != want { |
| 489 | t.Errorf("paused: %v\n got %s\nwant %s", ok, raw, want) |
| 490 | } |
| 491 | for _, c := range []equipo.Card{ |
| 492 | {ID: "c_2", Kind: equipo.CardJob, State: equipo.JobWorking, CarryOn: true}, |
| 493 | {ID: "c_4", Kind: equipo.CardOutcome, State: "open", CarryOn: true}, |
| 494 | } { |
| 495 | got, _ := c.Clean() |
| 496 | if raw, _ := json.Marshal(got); got.CarryOn || strings.Contains(string(raw), "carry_on") { |
| 497 | t.Errorf("%s %s kept carry_on: %s", c.Kind, c.State, raw) |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | // A stopped job keeps carry_on: a job held because building was turned |
| 503 | // off, once it is on again, carries on when the person says so (plan |
| 504 | // AD4). Any card that isn't a job never has it. |
| 505 | func TestCardCleanStoppedCarryOn(t *testing.T) { |
| 506 | got, ok := equipo.Card{ID: "c_1", Revision: 2, Kind: equipo.CardJob, State: equipo.JobStopped, Question: "Bakery website", |
| 507 | Result: "Stopped", Detail: "Building is on again. You can carry on with this, or drop it.", CarryOn: true}.Clean() |
| 508 | if !ok || !got.CarryOn { |
| 509 | t.Errorf("stopped job: %v %+v", ok, got) |
| 510 | } |
| 511 | for _, c := range []equipo.Card{ |
| 512 | {ID: "c_2", Kind: equipo.CardOutcome, State: "open", CarryOn: true}, |
| 513 | {ID: "c_3", Kind: equipo.CardQuestion, State: equipo.JobStopped, CarryOn: true}, |
| 514 | {ID: "c_4", Kind: equipo.CardJob, State: equipo.JobReady, CarryOn: true}, |
| 515 | } { |
| 516 | if got, _ := c.Clean(); got.CarryOn { |
| 517 | t.Errorf("%s %s kept carry_on", c.Kind, c.State) |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | // CarryOnNow posts {revision, idempotency_key} with the key as the |
| 523 | // Idempotency-Key and reads the card back from {"card"}; the same key |
| 524 | // replays the answer; Equipo's 409s come back as errors with their codes. |
| 525 | func TestCarryOnNow(t *testing.T) { |
| 526 | f := equipotest.New(t) |
| 527 | c := equipo.New(f.URL) |
| 528 | cred := signIn(t, f, c) |
| 529 | ctx := context.Background() |
| 530 | job := f.AskJob("Bakery website") |
| 531 | f.PauseJob(job, "Paused until 21:00", "It will carry on by itself at 21:00.", true) |
| 532 | var e *equipo.Error |
| 533 | if _, err := c.CarryOnNow(ctx, cred.Token, job, 1, "k-1"); !errors.As(err, &e) || e.Status != 409 || e.Code != "card_stale" { |
| 534 | t.Errorf("stale: %v", err) |
| 535 | } |
| 536 | card, err := c.CarryOnNow(ctx, cred.Token, job, 3, "k-2") |
| 537 | if err != nil || card.ID != job || card.State != equipo.JobWorking || card.Revision != 4 { |
| 538 | t.Fatalf("carry on: %+v %v", card, err) |
| 539 | } |
| 540 | calls := f.Calls("/api/v1/assistant/cards/" + job + "/carry_on") |
| 541 | if last := calls[len(calls)-1]; strings.TrimSpace(last.Body) != `{"idempotency_key":"k-2","revision":3}` || |
| 542 | last.Header.Get("Idempotency-Key") != "k-2" { |
| 543 | t.Errorf("sent: %+v", last) |
| 544 | } |
| 545 | if again, err := c.CarryOnNow(ctx, cred.Token, job, 3, "k-2"); err != nil || again.Revision != 4 || again.State != equipo.JobWorking { |
| 546 | t.Errorf("replayed: %+v %v", again, err) |
| 547 | } |
| 548 | // Equipo replays a key with the card as it is now, not as it was. |
| 549 | f.SetJob(job, equipo.JobReady, "Ready to try", "Have a look.") |
| 550 | if again, err := c.CarryOnNow(ctx, cred.Token, job, 3, "k-2"); err != nil || again.Revision != 5 || again.State != equipo.JobReady { |
| 551 | t.Errorf("replayed after a move: %+v %v", again, err) |
| 552 | } |
| 553 | if _, err := c.CarryOnNow(ctx, cred.Token, "c_nothing", 1, "k-2"); !errors.As(err, &e) || e.Status != 404 { |
| 554 | t.Errorf("no such card, with a key seen before: %v", err) |
| 555 | } |
| 556 | if _, err := c.CarryOnNow(ctx, cred.Token, job, 5, "k-3"); !errors.As(err, &e) || e.Code != "not_paused" { |
| 557 | t.Errorf("not paused: %v", err) |
| 558 | } |
| 559 | f.PauseJob(job, "Paused until 22:00", "", false) |
| 560 | if _, err := c.CarryOnNow(ctx, cred.Token, job, 6, "k-4"); !errors.As(err, &e) || e.Code != "carry_on_unavailable" { |
| 561 | t.Errorf("unavailable: %v", err) |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | // Base opts in to the paused state on the snapshot and the event stream |
| 566 | // (job_states=paused). Without it, as for an older Base, Equipo sends a |
| 567 | // paused job as working, with its result and detail and no carry_on. |
| 568 | func TestPausedIsOptIn(t *testing.T) { |
| 569 | f := equipotest.New(t) |
| 570 | c := equipo.New(f.URL) |
| 571 | cred := signIn(t, f, c) |
| 572 | ctx := context.Background() |
| 573 | job := f.AskJob("Bakery website") |
| 574 | f.PauseJob(job, "Paused until 21:00", "It will carry on by itself at 21:00.", true) |
| 575 | snap, err := c.Snapshot(ctx, cred.Token) |
| 576 | if err != nil || len(snap.Cards) != 1 || snap.Cards[0].State != equipo.JobPaused || !snap.Cards[0].CarryOn { |
| 577 | t.Fatalf("opted in: %+v %v", snap.Cards, err) |
| 578 | } |
| 579 | if calls := f.Calls("/api/v1/assistant/snapshot"); calls[len(calls)-1].Query != "job_states=paused" { |
| 580 | t.Errorf("snapshot's query %q", calls[len(calls)-1].Query) |
| 581 | } |
| 582 | res, err := c.Events(ctx, cred.Token, "40") |
| 583 | if err != nil { |
| 584 | t.Fatal(err) |
| 585 | } |
| 586 | res.Body.Close() |
| 587 | if calls := f.Calls("/api/v1/assistant/events"); calls[len(calls)-1].Query != "job_states=paused&after=40" { |
| 588 | t.Errorf("events' query %q", calls[len(calls)-1].Query) |
| 589 | } |
| 590 | |
| 591 | // An older Base, asking without it. |
| 592 | req, _ := http.NewRequest(http.MethodGet, f.URL+"/api/v1/assistant/snapshot", nil) |
| 593 | req.Header.Set("Authorization", "Bearer "+cred.Token) |
| 594 | raw, err := http.DefaultClient.Do(req) |
| 595 | if err != nil { |
| 596 | t.Fatal(err) |
| 597 | } |
| 598 | defer raw.Body.Close() |
| 599 | var old equipo.Snapshot |
| 600 | if json.NewDecoder(raw.Body).Decode(&old) != nil || len(old.Cards) != 1 || old.Cards[0].State != equipo.JobWorking || |
| 601 | old.Cards[0].CarryOn || old.Cards[0].Result != "Paused until 21:00" { |
| 602 | t.Errorf("without the opt-in: %+v", old.Cards) |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | // SetTimeZone is PUT time-zone {time_zone}; a zone Equipo does not know is |
| 607 | // 422 invalid_input. |
| 608 | func TestSetTimeZone(t *testing.T) { |
| 609 | f := equipotest.New(t) |
| 610 | c := equipo.New(f.URL) |
| 611 | cred := signIn(t, f, c) |
| 612 | ctx := context.Background() |
| 613 | const dublin = "Europe/Dublin" |
| 614 | if err := c.SetTimeZone(ctx, cred.Token, dublin); err != nil || f.TimeZone() != dublin { |
| 615 | t.Fatalf("set: %v, zone %q", err, f.TimeZone()) |
| 616 | } |
| 617 | if calls := f.Calls("/api/v1/assistant/time-zone"); len(calls) != 1 || calls[0].Method != http.MethodPut || |
| 618 | strings.TrimSpace(calls[0].Body) != `{"only_if_unset":true,"time_zone":"Europe/Dublin"}` || calls[0].Header.Get("Idempotency-Key") == "" { |
| 619 | t.Errorf("sent: %+v", calls) |
| 620 | } |
| 621 | // Base's zone replaces the one Base set before (BASE_TIMEZONE changed), |
| 622 | // never one the person's own device set. |
| 623 | if err := c.SetTimeZone(ctx, cred.Token, "Europe/Madrid"); err != nil || f.TimeZone() != "Europe/Madrid" { |
| 624 | t.Errorf("Base's new zone: %v, zone %q", err, f.TimeZone()) |
| 625 | } |
| 626 | f.SetTimeZone("Europe/Berlin") |
| 627 | if err := c.SetTimeZone(ctx, cred.Token, dublin); err != nil || f.TimeZone() != "Europe/Berlin" { |
| 628 | t.Errorf("over the person's own: %v, zone %q", err, f.TimeZone()) |
| 629 | } |
| 630 | var e *equipo.Error |
| 631 | if err := c.SetTimeZone(ctx, cred.Token, "Mars/Olympus"); !errors.As(err, &e) || e.Status != 422 || e.Code != "invalid_input" { |
| 632 | t.Errorf("unknown zone: %v", err) |
| 633 | } |
| 634 | } |
| 635 | |