oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package webtest
2
3import (
4 "bufio"
5 "context"
6 "crypto/tls"
7 "encoding/json"
8 "io"
9 "net/http"
10 "net/url"
11 "reflect"
12 "sort"
13 "strconv"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/base/internal/config"
20 "amadan.net/oficina/base/internal/equipo"
21 "amadan.net/oficina/base/internal/equipo/equipotest"
22)
23
24// Ask's JSON contract (docs/api/base-native-v1.md), as the native app uses
25// it: every call carries the native session cookie, Origin and
26// Accept: application/json, and no Sec-Fetch-Site. These are the routes and
27// shapes ask.js relies on; a change to one breaks a test here.
28
29// newNativeAskApp is Base with Oficina ID and Ask on, the owner linked
30// (and signed in locally in the returned browser), and the owner's native
31// app signed in.
32func newNativeAskApp(t *testing.T) (web, app *testApp, f *equipotest.Fake) {
33 t.Helper()
34 f = equipotest.New(t)
35 web = newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = f.URL })
36 web.link(ownerAddress, "subject-owner")
37 return web, web.nativeSignIn("subject-owner"), f
38}
39
40// nativeForm is a form POST as the native app makes one to Ask.
41func (a *testApp) nativeForm(target string, form url.Values) Resp {
42 a.t.Helper()
43 req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode()))
44 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
45 req.Header.Set("Origin", homeOrigin)
46 req.Header.Set("Accept", "application/json")
47 return a.do(req)
48}
49
50// keysOf is the sorted keys of a JSON object.
51func keysOf(t *testing.T, raw string) []string {
52 t.Helper()
53 var m map[string]json.RawMessage
54 if err := json.Unmarshal([]byte(raw), &m); err != nil {
55 t.Fatalf("not an object: %q: %v", raw, err)
56 }
57 var out []string
58 for k := range m {
59 out = append(out, k)
60 }
61 sort.Strings(out)
62 return out
63}
64
65func wantKeys(t *testing.T, where, raw string, want ...string) {
66 t.Helper()
67 sort.Strings(want)
68 if got := keysOf(t, raw); !reflect.DeepEqual(got, want) {
69 t.Errorf("%s keys %v, want %v\n%s", where, got, want, raw)
70 }
71}
72
73func wantBody(t *testing.T, where string, r Resp, code int, body string) {
74 t.Helper()
75 if r.Code != code || strings.TrimSpace(r.Body) != body {
76 t.Errorf("%s: %d %s, want %d %s", where, r.Code, strings.TrimSpace(r.Body), code, body)
77 }
78}
79
80// askState is /ask/state's answer, its parts kept raw for their shapes.
81type askState struct {
82 State string `json:"state"`
83 Messages []json.RawMessage `json:"messages"`
84 Jobs []json.RawMessage `json:"jobs"`
85 Cards []json.RawMessage `json:"cards"`
86 Turn json.RawMessage `json:"turn"`
87 Status string `json:"status"`
88 Cursor int64 `json:"cursor"`
89}
90
91func (a *testApp) askState() (askState, Resp) {
92 a.t.Helper()
93 r := a.nativeGet("/ask/state")
94 if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Content-Type") != "application/json" {
95 a.t.Fatalf("/ask/state: %d %q %q %s", r.Code, r.Header.Get("Cache-Control"), r.Header.Get("Content-Type"), r.Body)
96 }
97 var s askState
98 if err := json.Unmarshal([]byte(r.Body), &s); err != nil {
99 a.t.Fatal(err)
100 }
101 return s, r
102}
103
104var stateKeys = []string{"state", "messages", "jobs", "cards", "turn", "status", "cursor", "renew_after", "equipo_origin", "disconnected", "can_attach"}
105
106func TestAskContractBeforeConnecting(t *testing.T) {
107 _, app, f := newNativeAskApp(t)
108 s, r := app.askState()
109 wantKeys(t, "state", r.Body, stateKeys...)
110 if strings.TrimSpace(r.Body) != `{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"renew_after":"","equipo_origin":"`+f.URL+`","disconnected":false,"can_attach":false}` || s.State != "connect" {
111 t.Errorf("not connected: %s", r.Body)
112 }
113 wantBody(t, "send", app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"k1"}}), 409, `{"state":"connect"}`)
114 wantBody(t, "cancel", app.nativeForm("/ask/turns/t_1/cancel", url.Values{"key": {"k2"}}), 409, `{"state":"connect"}`)
115 wantBody(t, "answer", app.nativeForm("/ask/cards/c_1/answer", url.Values{"choice": {"x"}, "revision": {"1"}, "key": {"k3"}}), 409, `{"state":"connect"}`)
116 frames := app.events(t, "0", func([]sseFrame) bool { return false })
117 if len(frames) != 1 || frames[0].Event != "state" || frames[0].Data != `{"state":"connect"}` || frames[0].ID != "" {
118 t.Errorf("events while not connected: %+v", frames)
119 }
120}
121
122func TestAskContractConversation(t *testing.T) {
123 web, app, f := newNativeAskApp(t)
124 web.approveEquipo(f)
125 s, r := app.askState()
126 wantKeys(t, "state", r.Body, stateKeys...)
127 if s.State != "ready" || s.Messages == nil || s.Jobs == nil || s.Cards == nil || string(s.Turn) != "null" || s.Status != "" {
128 t.Fatalf("connected state: %s", r.Body)
129 }
130
131 // Send: the message and its turn; the same key again is the same message.
132 form := url.Values{"text": {"What can I do?"}, "key": {"native-1"}}
133 sent := app.nativeForm("/ask/messages", form)
134 if sent.Code != 200 || sent.Header.Get("Cache-Control") != "no-store" {
135 t.Fatalf("send: %d %s", sent.Code, sent.Body)
136 }
137 wantKeys(t, "send", sent.Body, "message", "turn")
138 var out struct {
139 Message, Turn json.RawMessage
140 }
141 _ = json.Unmarshal([]byte(sent.Body), &out)
142 wantKeys(t, "message", string(out.Message), "id", "role", "text", "turn_id", "created_at")
143 wantKeys(t, "turn", string(out.Turn), "id", "kind", "state", "reason")
144 var m struct{ ID, Role, Text string }
145 _ = json.Unmarshal(out.Message, &m)
146 if m.Role != "person" || m.Text != "What can I do?" {
147 t.Errorf("message: %s", out.Message)
148 }
149 again := app.nativeForm("/ask/messages", form)
150 var m2 struct{ Message struct{ ID string } }
151 if again.Code != 200 || json.Unmarshal([]byte(again.Body), &m2) != nil || m2.Message.ID != m.ID {
152 t.Errorf("resend with the same key: %d %s", again.Code, again.Body)
153 }
154 wantBody(t, "empty", app.nativeForm("/ask/messages", url.Values{"text": {" "}, "key": {"native-2"}}), 422, `{"state":"ready"}`)
155
156 // The reply is in the next read.
157 var after askState
158 for i := 0; i < 200; i++ {
159 if after, _ = app.askState(); len(after.Messages) == 2 && string(after.Turn) == "null" {
160 break
161 }
162 time.Sleep(10 * time.Millisecond)
163 }
164 if len(after.Messages) != 2 || after.Cursor <= s.Cursor {
165 t.Fatalf("after the reply: %d messages, cursor %d (was %d)", len(after.Messages), after.Cursor, s.Cursor)
166 }
167 wantKeys(t, "state message", string(after.Messages[1]), "id", "role", "text", "turn_id", "created_at")
168}
169
170func TestAskContractEvents(t *testing.T) {
171 web, app, f := newNativeAskApp(t)
172 web.approveEquipo(f)
173 s, _ := app.askState()
174 f.Hold = true
175 frames := app.events(t, strconv.FormatInt(s.Cursor, 10), func(got []sseFrame) bool {
176 if len(got) == 1 {
177 // The stream is open: send, glance, then answer.
178 go func() {
179 r := app.nativeForm("/ask/messages", url.Values{"text": {"Make a form"}, "key": {"ev-1"}})
180 var out struct{ Turn struct{ ID string } }
181 _ = json.Unmarshal([]byte(r.Body), &out)
182 for f.Turn(out.Turn.ID) != "running" {
183 time.Sleep(5 * time.Millisecond)
184 }
185 f.Glance(out.Turn.ID, "Looking at your **forms**")
186 time.Sleep(20 * time.Millisecond)
187 f.Answer(out.Turn.ID, "Here it is.", true)
188 }()
189 }
190 last := got[len(got)-1]
191 return last.Event == "turn" && strings.Contains(last.Data, `"state":"replied"`)
192 })
193 if frames[0].Retry != "3000" {
194 t.Errorf("first frame %+v, want retry: 3000", frames[0])
195 }
196 seen := map[string]bool{}
197 for _, fr := range frames[1:] {
198 if fr.Comment {
199 continue
200 }
201 seen[fr.Event] = true
202 var env struct {
203 Type string `json:"type"`
204 Data json.RawMessage `json:"data"`
205 }
206 if err := json.Unmarshal([]byte(fr.Data), &env); err != nil || env.Type != fr.Event {
207 t.Fatalf("frame %+v: %v", fr, err)
208 }
209 wantKeys(t, fr.Event+" frame", fr.Data, "type", "data")
210 switch fr.Event {
211 case "glance":
212 if fr.ID != "" {
213 t.Errorf("a glance carried an id: %+v", fr)
214 }
215 wantKeys(t, "glance event", string(env.Data), "turn_id", "text")
216 if !strings.Contains(string(env.Data), `"text":"Looking at your forms"`) {
217 t.Errorf("glance: %s", env.Data)
218 }
219 default:
220 if _, err := strconv.ParseUint(fr.ID, 10, 63); err != nil {
221 t.Errorf("%s frame without a numeric id: %+v", fr.Event, fr)
222 }
223 }
224 switch fr.Event {
225 case "message":
226 wantKeys(t, "message event", string(env.Data), "id", "role", "text", "turn_id", "created_at")
227 case "turn":
228 wantKeys(t, "turn event", string(env.Data), "id", "kind", "state", "reason")
229 case "delta":
230 wantKeys(t, "delta event", string(env.Data), "turn_id", "offset", "text")
231 }
232 }
233 for _, want := range []string{"message", "turn", "delta", "glance"} {
234 if !seen[want] {
235 t.Errorf("no %s event in %+v", want, frames)
236 }
237 }
238}
239
240func TestAskContractCancel(t *testing.T) {
241 web, app, f := newNativeAskApp(t)
242 web.approveEquipo(f)
243 f.Hold = true
244 r := app.nativeForm("/ask/messages", url.Values{"text": {"Something long"}, "key": {"c-1"}})
245 var out struct{ Turn struct{ ID string } }
246 if json.Unmarshal([]byte(r.Body), &out) != nil || out.Turn.ID == "" {
247 t.Fatalf("send: %d %s", r.Code, r.Body)
248 }
249 for f.Turn(out.Turn.ID) != "running" {
250 time.Sleep(5 * time.Millisecond)
251 }
252 s, _ := app.askState()
253 if !strings.Contains(string(s.Turn), out.Turn.ID) || s.Status != "Thinking…" {
254 t.Errorf("running: turn %s status %q", s.Turn, s.Status)
255 }
256 wantBody(t, "cancel", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-2"}}), 200, `{"state":"ready"}`)
257 wantBody(t, "cancel again", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-3"}}), 409, `{"state":"ready"}`)
258}
259
260func TestAskContractCards(t *testing.T) {
261 web, app, f := newNativeAskApp(t)
262 web.approveEquipo(f)
263 job := f.AskJob("Christmas order form")
264 f.AskKindFor("confirm", job, "Go ahead?", goOptions, nil)
265 q := f.AskQuestion("Which colour?", "red", "blue")
266 s, r := app.askState()
267 if len(s.Jobs) != 1 || len(s.Cards) != 1 {
268 t.Fatalf("jobs and cards: %s", r.Body)
269 }
270 wantKeys(t, "card", string(s.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result")
271 wantKeys(t, "job", string(s.Jobs[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "detail", "started_at", "cards")
272 var j struct {
273 Kind, State, Question string
274 Cards []json.RawMessage
275 }
276 if json.Unmarshal(s.Jobs[0], &j) != nil || j.Kind != "job" || j.Question != "Christmas order form" || len(j.Cards) != 1 {
277 t.Fatalf("job: %s", s.Jobs[0])
278 }
279 wantKeys(t, "job's card", string(j.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "job")
280
281 // Answer at the revision seen: the card, the message and turn it started.
282 a := app.nativeForm("/ask/cards/"+q+"/answer", url.Values{"choice": {"red"}, "revision": {"1"}, "key": {"a-1"}})
283 if a.Code != 200 {
284 t.Fatalf("answer: %d %s", a.Code, a.Body)
285 }
286 wantKeys(t, "answer", a.Body, "card", "message", "turn")
287 var ans struct {
288 Card struct{ ID, State, Result string }
289 Message *struct{ Text string }
290 Turn *struct{ ID string }
291 }
292 if json.Unmarshal([]byte(a.Body), &ans) != nil || ans.Card.ID != q || ans.Card.State != "answered" || ans.Message == nil || ans.Message.Text != "red" || ans.Turn == nil {
293 t.Errorf("answer: %s", a.Body)
294 }
295 // An outcome card's answer starts nothing.
296 o := f.AskOutcome("Publish it?", goOptions, nil)
297 wantBody(t, "outcome", app.nativeForm("/ask/cards/"+o+"/answer", url.Values{"choice": {"go"}, "revision": {"1"}, "key": {"a-2"}}), 200,
298 `{"card":{"id":"`+o+`","revision":2,"kind":"outcome","state":"answered","question":"Publish it?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[],"result":"Go ahead"},"message":null,"turn":null}`)
299 // Stale: the card moved on.
300 q2 := f.AskQuestion("Which size?", "S", "M")
301 f.SetCard(q2, "open", "")
302 wantBody(t, "stale", app.nativeForm("/ask/cards/"+q2+"/answer", url.Values{"choice": {"S"}, "revision": {"1"}, "key": {"a-3"}}), 409, `{"state":"ready"}`)
303}
304
305// Equipo refusing the key is Ask's 409 {"state":"reconnect"}, never a 401:
306// a 401 is always Base's own session ending ({"code":"unauthenticated"}),
307// and the kit signs in again on one.
308func TestAskContractLostKey(t *testing.T) {
309 web, app, f := newNativeAskApp(t)
310 web.approveEquipo(f)
311 for i, call := range []func() Resp{
312 func() Resp { return app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"l-1"}}) },
313 func() Resp { return app.nativeForm("/ask/turns/t_0001/cancel", url.Values{"key": {"l-2"}}) },
314 func() Resp {
315 return app.nativeForm("/ask/cards/c_0001/answer", url.Values{"choice": {"go"}, "revision": {"1"}, "key": {"l-3"}})
316 },
317 } {
318 // Each time the key is refused afresh: reconnect, and Base's
319 // stored link is lost.
320 web.approveEquipo(f)
321 f.RevokeAll()
322 wantBody(t, "write "+strconv.Itoa(i), call(), 409, `{"state":"reconnect"}`)
323 }
324 if s, _ := app.askState(); s.State != "reconnect" {
325 t.Errorf("state after a refused key: %s", s.State)
326 }
327 if r := app.nativeGet("/api/v1/me"); r.Code != 200 {
328 t.Errorf("the session ended with the key: %d", r.Code)
329 }
330}
331
332// While Base's session is good, no Ask route answers 401, whatever Equipo
333// says of the key: connected, refused as it is used, or already lost.
334func TestAskNeverAnswers401WithASession(t *testing.T) {
335 web, app, f := newNativeAskApp(t)
336 f.LinkOficinaID("subject-owner", ownerAddress)
337 calls := map[string]func() Resp{
338 "state": func() Resp { return app.nativeGet("/ask/state") },
339 "send": func() Resp { return app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {equipoKey()}}) },
340 "cancel": func() Resp { return app.nativeForm("/ask/turns/t_9999/cancel", url.Values{"key": {equipoKey()}}) },
341 "answer": func() Resp {
342 return app.nativeForm("/ask/cards/c_9999/answer", url.Values{"choice": {"x"}, "revision": {"1"}, "key": {equipoKey()}})
343 },
344 "check": func() Resp { return app.nativeForm("/ask/connect/check", url.Values{"next": {"ask"}}) },
345 "dock": func() Resp { return app.nativeForm("/ask/dock", url.Values{"open": {"1"}}) },
346 "page": func() Resp { return app.get("/ask") },
347 "oficina": func() Resp { return app.get("/ask/oficina/connect") },
348 "set-up": func() Resp { return app.connectWithOficina(f, "subject-owner") },
349 "replayed": func() Resp { return app.nativePost("/api/v1/ask/oficina", `{"assertion":"x","verifier":"y"}`) },
350 }
351 try := func(when string) {
352 t.Helper()
353 for name, call := range calls {
354 if name == "set-up" {
355 continue
356 }
357 if r := call(); r.Code == http.StatusUnauthorized {
358 t.Errorf("%s, %s: 401 %s", when, name, r.Body)
359 }
360 }
361 app.events(t, "0", func([]sseFrame) bool { return true })
362 }
363 try("not connected")
364 web.approveEquipo(f)
365 try("connected")
366 f.RevokeAll()
367 try("refused as used")
368 try("lost")
369 if r := calls["set-up"](); r.Code != 200 {
370 t.Fatalf("set-up: %d %s", r.Code, r.Body)
371 }
372 f.EndNativeSession(f.DeviceSession(liveDevice(t, f)))
373 try("Equipo's session ended")
374 if r := app.post("/ask/disconnect", nil); r.Code == http.StatusUnauthorized {
375 t.Errorf("disconnect: 401")
376 }
377}
378
379var keySeq int
380
381func equipoKey() string { keySeq++; return "never-401-" + strconv.Itoa(keySeq) }
382
383// After the member disconnects Ask, /ask/state says so and an automatic
384// set-up is refused with 409 disconnected.
385func TestAskContractDisconnected(t *testing.T) {
386 web, app, f := newNativeAskApp(t)
387 f.LinkOficinaID("subject-owner", ownerAddress)
388 web.approveEquipo(f)
389 web.post("/ask/disconnect", nil)
390 _, r := app.askState()
391 wantKeys(t, "state", r.Body, stateKeys...)
392 if !strings.Contains(r.Body, `"state":"connect"`) || !strings.Contains(r.Body, `"disconnected":true`) {
393 t.Fatalf("state after Disconnect: %s", r.Body)
394 }
395 wantBody(t, "automatic set-up", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`)
396}
397
398// sseFrame is one frame of an event stream, as the native client parses it.
399type sseFrame struct {
400 ID, Event, Data, Retry string
401 Comment bool
402}
403
404// events opens /ask/events?after= as the native app does and reads frames
405// until done says so or the stream ends. The first frame is the retry.
406func (a *testApp) events(t *testing.T, after string, done func([]sseFrame) bool) []sseFrame {
407 t.Helper()
408 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
409 defer cancel()
410 req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+after, nil)
411 req.Header.Set("Origin", homeOrigin)
412 req.Header.Set("Accept", "text/event-stream")
413 a.addHeader(req)
414 for _, c := range a.client.Jar.Cookies(req.URL) {
415 req.AddCookie(c)
416 }
417 res := serveStreaming(a.client.Transport.(handlerTransport).h, req)
418 defer res.Body.Close()
419 if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" || res.Header.Get("Cache-Control") != "no-store" {
420 t.Fatalf("events: %d %v", res.StatusCode, res.Header)
421 }
422 var frames []sseFrame
423 var cur sseFrame
424 sc := bufio.NewScanner(res.Body)
425 for sc.Scan() {
426 line := sc.Text()
427 switch {
428 case line == "":
429 frames = append(frames, cur)
430 cur = sseFrame{}
431 if done(frames) {
432 return frames
433 }
434 case strings.HasPrefix(line, ":"):
435 cur.Comment = true
436 default:
437 name, value, _ := strings.Cut(line, ": ")
438 switch name {
439 case "id":
440 cur.ID = value
441 case "event":
442 cur.Event = value
443 case "data":
444 cur.Data = value
445 case "retry":
446 cur.Retry = value
447 }
448 }
449 }
450 if ctx.Err() != nil {
451 t.Fatalf("the stream timed out after %+v", frames)
452 }
453 // Drop the retry frame for a stream that ends at once (a state event).
454 if len(frames) > 0 && frames[0].Retry != "" && frames[0].Event == "" {
455 return frames[1:]
456 }
457 return frames
458}
459
460// serveStreaming serves req with h in the background and answers as soon
461// as the headers are written, with a body that streams what h writes. The
462// in-process transport waits for the whole response, which a stream never
463// ends.
464func serveStreaming(h http.Handler, req *http.Request) *http.Response {
465 in := req.Clone(req.Context())
466 in.RequestURI, in.Host, in.RemoteAddr, in.TLS = req.URL.RequestURI(), req.URL.Host, "192.0.2.10:4321", &tls.ConnectionState{}
467 pr, pw := io.Pipe()
468 w := &pipeWriter{header: http.Header{}, pw: pw, ready: make(chan struct{})}
469 go func() {
470 h.ServeHTTP(w, in)
471 w.WriteHeader(http.StatusOK)
472 pw.Close()
473 }()
474 <-w.ready
475 return &http.Response{StatusCode: w.status, Header: w.sent, Body: pr, Request: req}
476}
477
478type pipeWriter struct {
479 header, sent http.Header
480 pw *io.PipeWriter
481 status int
482 once sync.Once
483 ready chan struct{}
484}
485
486func (p *pipeWriter) Header() http.Header { return p.header }
487
488func (p *pipeWriter) WriteHeader(code int) {
489 p.once.Do(func() {
490 p.status, p.sent = code, p.header.Clone()
491 close(p.ready)
492 })
493}
494
495func (p *pipeWriter) Write(b []byte) (int, error) {
496 p.WriteHeader(http.StatusOK)
497 return p.pw.Write(b)
498}
499
500func (p *pipeWriter) Flush() {}
501
502// Carry on now (docs/api/base-native-v1.md): a paused job's card says
503// carry_on; the route answers {"card": the job as it is now}; a 409 from
504// Equipo (card_stale, not_paused, carry_on_unavailable) is Ask's stale
505// 409 {"state":"ready"}; before connecting it is the state's 409.
506func TestAskContractCarryOn(t *testing.T) {
507 web, app, f := newNativeAskApp(t)
508 wantBody(t, "not connected", app.nativeForm("/ask/cards/c_1/carry_on", url.Values{"revision": {"1"}, "key": {"k1"}}), 409, `{"state":"connect"}`)
509 web.approveEquipo(f)
510 job := f.AskJob("Bakery website")
511 f.PauseJob(job, "Paused until 21:00", "It has reached the limit on its plan for now. It will carry on by itself at 21:00 (in 9 hours).", true)
512 s, r := app.askState()
513 if len(s.Jobs) != 1 {
514 t.Fatalf("jobs: %s", r.Body)
515 }
516 wantKeys(t, "paused job", string(s.Jobs[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "detail", "started_at", "carry_on", "cards")
517 var j struct {
518 State, Result string
519 Revision int64
520 CarryOn bool `json:"carry_on"`
521 }
522 if json.Unmarshal(s.Jobs[0], &j) != nil || j.State != "paused" || j.Result != "Paused until 21:00" || !j.CarryOn {
523 t.Fatalf("paused job: %s", s.Jobs[0])
524 }
525 rev := strconv.FormatInt(j.Revision, 10)
526 wantBody(t, "stale", app.nativeForm("/ask/cards/"+job+"/carry_on", url.Values{"revision": {"1"}, "key": {"s-1"}}), 409, `{"state":"ready"}`)
527 ok := app.nativeForm("/ask/cards/"+job+"/carry_on", url.Values{"revision": {rev}, "key": {"s-2"}})
528 wantKeys(t, "carry on", ok.Body, "card")
529 var out struct{ Card struct{ ID, State string } }
530 if ok.Code != 200 || json.Unmarshal([]byte(ok.Body), &out) != nil || out.Card.ID != job || out.Card.State != "working" {
531 t.Errorf("carry on: %d %s", ok.Code, ok.Body)
532 }
533 // Sent again with its key (its answer was lost): the same answer.
534 if again := app.nativeForm("/ask/cards/"+job+"/carry_on", url.Values{"revision": {rev}, "key": {"s-2"}}); again.Code != 200 || again.Body != ok.Body {
535 t.Errorf("resent: %d %s, want %s", again.Code, again.Body, ok.Body)
536 }
537 // No longer paused.
538 s, _ = app.askState()
539 _ = json.Unmarshal(s.Jobs[0], &j)
540 wantBody(t, "not paused", app.nativeForm("/ask/cards/"+job+"/carry_on", url.Values{"revision": {strconv.FormatInt(j.Revision, 10)}, "key": {"s-3"}}), 409, `{"state":"ready"}`)
541}
542
543// Files (docs/api/base-native-v1.md, "Files"): a message with files carries them as
544// attachments; a message without has no such key; the state says
545// can_attach; Remove and a read are Base's own routes.
546func TestAskContractFiles(t *testing.T) {
547 web, app, f := newNativeAskApp(t)
548 web.approveEquipo(f)
549 f.FilesReady(true)
550 f.Hold = true
551 // This harness serves Base in-process, where no read deadline can be
552 // set, so the upload is made straight to Equipo with the member's
553 // bearer; TestAskUploadRelays pins POST /ask/attachments's answer.
554 tokens := f.Tokens()
555 if len(tokens) != 1 {
556 t.Fatalf("tokens: %v", tokens)
557 }
558 at, err := equipo.New(f.URL).Upload(context.Background(), tokens[0], "notes.md", "text/markdown", []byte("# Notes"))
559 if err != nil {
560 t.Fatal(err)
561 }
562 attachmentKeys := []string{"id", "kind", "name", "media_type", "size", "width", "height"}
563 sent := app.nativeForm("/ask/messages", url.Values{"attachments": {at.ID}, "key": {"native-files"}})
564 if sent.Code != 200 {
565 t.Fatalf("send: %d %s", sent.Code, sent.Body)
566 }
567 var out struct{ Message json.RawMessage }
568 _ = json.Unmarshal([]byte(sent.Body), &out)
569 wantKeys(t, "message with files", string(out.Message), "id", "role", "text", "turn_id", "created_at", "attachments")
570 var m struct{ Attachments []json.RawMessage }
571 _ = json.Unmarshal(out.Message, &m)
572 if len(m.Attachments) != 1 {
573 t.Fatalf("message: %s", out.Message)
574 }
575 wantKeys(t, "attachment", string(m.Attachments[0]), attachmentKeys...)
576 s, r := app.askState()
577 if !strings.Contains(r.Body, `"can_attach":true`) || len(s.Messages) == 0 {
578 t.Fatalf("state: %s", r.Body)
579 }
580 if got := app.nativeGet("/ask/attachments/" + at.ID); got.Code != 200 || got.Body != "# Notes" {
581 t.Fatalf("read: %d %s", got.Code, got.Body)
582 }
583 another := app.nativeForm("/ask/messages", url.Values{"text": {"no files"}, "key": {"native-words"}})
584 _ = json.Unmarshal([]byte(another.Body), &out)
585 wantKeys(t, "message without files", string(out.Message), "id", "role", "text", "turn_id", "created_at")
586}
587