oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "crypto/rand"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "strconv"
10 "strings"
11 "sync"
12 "time"
13 "unicode/utf8"
14
15 "amadan.net/oficina/base/internal/equipo"
16)
17
18// assistant is the prefix of the Assistant's routes, the only chat routes
19// the fake serves.
20const assistant = "/api/v1/assistant"
21
22// The chat's resources in wire's JSON shapes (Message, Turn,
23// AssistantCard, Event).
24type message struct {
25 ID string `json:"id"`
26 Revision int64 `json:"revision"`
27 Role string `json:"role"`
28 Text string `json:"text"`
29 TurnID string `json:"turn_id"`
30 CreatedAt time.Time `json:"created_at"`
31 Switched *struct{} `json:"switched"`
32 // Attachments are the files sent with a person's message, in order;
33 // omitted when there are none (wire.Message).
34 Attachments []file `json:"attachments,omitempty"`
35 // Lookups are what the Assistant looked up for a reply, sent only to
36 // a Base that draws them (asRead).
37 Lookups []equipo.Lookup `json:"lookups,omitempty"`
38}
39
40// drawsLookups reports whether r says Base draws lookup answers
41// (Base-Capabilities), as Equipo reads it.
42func (f *Fake) drawsLookups(r *http.Request) bool {
43 if f.LookupsRegardless {
44 return true
45 }
46 for _, v := range r.Header.Values(equipo.CapabilitiesHeader) {
47 for _, c := range strings.Split(v, ",") {
48 if strings.TrimSpace(c) == equipo.CapLookupAnswers {
49 return true
50 }
51 }
52 }
53 return false
54}
55
56// asRead is m as a read with draws gets it: its lookups as they are, or,
57// for a Base that can't draw them, folded into its text, as Equipo's
58// plain-text fallback does (computed at read time, never stored).
59func asRead(m message, draws bool) message {
60 if draws || len(m.Lookups) == 0 {
61 return m
62 }
63 m.Text = equipo.Message{Text: m.Text, Lookups: m.Lookups}.PlainLookups().Text
64 m.Lookups = nil
65 return m
66}
67
68// read is msgs as a read with draws gets them (asRead).
69func read(msgs []message, draws bool) []message {
70 out := make([]message, len(msgs))
71 for i, m := range msgs {
72 out[i] = asRead(m, draws)
73 }
74 return out
75}
76
77type turn struct {
78 ID string `json:"id"`
79 Revision int64 `json:"revision"`
80 Kind string `json:"kind"`
81 State string `json:"state"`
82 Reason string `json:"reason"`
83 Attempt int64 `json:"attempt"`
84 MessageIDs []string `json:"message_ids"`
85 ReplyID string `json:"reply_id"`
86 Connection string `json:"connection"`
87 CreatedAt time.Time `json:"created_at"`
88 UpdatedAt time.Time `json:"updated_at"`
89 Timing *struct{} `json:"timing"`
90}
91
92// card is wire.AssistantCard: options and links are never null.
93type card struct {
94 ID string `json:"id"`
95 Revision int64 `json:"revision"`
96 Kind string `json:"kind"`
97 State string `json:"state"`
98 Question string `json:"question"`
99 Options []equipo.Option `json:"options"`
100 Links []equipo.Link `json:"links"`
101 Result string `json:"result"`
102 Job string `json:"job,omitempty"`
103 Detail string `json:"detail,omitempty"`
104 StartedAt *time.Time `json:"started_at,omitempty"`
105 CarryOn bool `json:"carry_on,omitempty"`
106}
107
108type event struct {
109 Cursor int64 `json:"cursor"`
110 Type string `json:"type"`
111 Resource string `json:"resource"`
112 ID string `json:"id"`
113 Revision int64 `json:"revision"`
114 TurnID string `json:"turn_id,omitempty"`
115 MessageID string `json:"message_id,omitempty"`
116 Attempt int64 `json:"attempt,omitempty"`
117 Data any `json:"data"`
118}
119
120// chat is one person's conversation with the Assistant.
121type chat struct {
122 cmu sync.Mutex
123 seq int
124 messages []message
125 turns map[string]*turn
126 cards []*card
127 events []event // in order; a live event (a glance) has cursor 0
128 cursor int64 // the newest event's cursor, from 40
129 sent map[string]string // idempotency key to message id
130 carried map[string]bool // carry_on's card id and idempotency key, once carried on
131 wake chan struct{} // closed at each new event
132 // runner is why the person's runner cannot answer: "no_runner",
133 // "runner_too_old", or "" when it can.
134 runner string
135 // address is who the bearer speaks for (the snapshot's me.address).
136 address string
137 // zone is the person's time zone; zoneOwn says their own browser or
138 // device set it (SetTimeZone), not Base (PUT assistant/time-zone).
139 zone string
140 zoneOwn bool
141 // zoneStatus and zoneCode, when set, are what every PUT time-zone
142 // gets; zoneHold, when set, holds each one until it closes.
143 zoneStatus int
144 zoneCode string
145 zoneHold chan struct{}
146 // carryStatus, when set, is what every carry_on gets (a 5xx).
147 carryStatus int
148 // hostStatus and hostCode, when set, are what every PUT host gets.
149 hostStatus int
150 hostCode string
151 // consent is the URL connect gives; finish is the status finish gives
152 // (default connected); oficinaStatus and oficinaCode, when set, are what
153 // both answer instead.
154 consent, finish string
155 oficinaStatus int
156 oficinaCode string
157}
158
159func (c *chat) init() {
160 c.turns, c.sent, c.carried, c.wake = map[string]*turn{}, map[string]string{}, map[string]bool{}, make(chan struct{})
161 c.cursor = 40
162 c.address = "paul@tito.io"
163}
164
165func (c *chat) next(prefix string) string { c.seq++; return fmt.Sprintf("%s_%04d", prefix, c.seq) }
166
167// emit records an event at the next cursor; the caller holds cmu.
168func (c *chat) emit(typ, resource, id string, rev int64, turnID string, data any) {
169 c.cursor++
170 c.add(event{Cursor: c.cursor, Type: typ, Resource: resource, ID: id, Revision: rev, TurnID: turnID, Attempt: 1, Data: data})
171}
172
173// emitLive records a live event, as Equipo sends a glance: cursor 0, sent
174// only to the streams open now, never again; the caller holds cmu.
175func (c *chat) emitLive(typ, resource, id string, rev int64, turnID string, data any) {
176 c.add(event{Type: typ, Resource: resource, ID: id, Revision: rev, TurnID: turnID, Attempt: 1, Data: data})
177}
178
179func (c *chat) add(e event) {
180 c.events = append(c.events, e)
181 close(c.wake)
182 c.wake = make(chan struct{})
183}
184
185// Emit adds an event of any type, such as one Base must not pass on.
186func (f *Fake) Emit(typ string, data any) {
187 f.cmu.Lock()
188 defer f.cmu.Unlock()
189 f.emit(typ, typ, "x", 1, "", data)
190}
191
192// AskQuestion puts an open question card in the conversation, as the
193// Assistant's ask_person does: each option's value is its label.
194func (f *Fake) AskQuestion(question string, options ...string) string {
195 opts := make([]equipo.Option, len(options))
196 for i, o := range options {
197 opts[i] = equipo.Option{Value: o, Label: o}
198 }
199 return f.AskKind("question", question, opts, nil)
200}
201
202// AskOutcome puts an open outcome card in the conversation, as Equipo
203// does when the team's work needs the person.
204func (f *Fake) AskOutcome(question string, options []equipo.Option, links []equipo.Link) string {
205 return f.AskKind("outcome", question, options, links)
206}
207
208// AskKind puts an open card of any kind in the conversation, such as one
209// Base must not show.
210func (f *Fake) AskKind(kind, question string, options []equipo.Option, links []equipo.Link) string {
211 f.cmu.Lock()
212 defer f.cmu.Unlock()
213 c := &card{ID: f.next("c"), Revision: 1, Kind: kind, State: "open", Question: question,
214 Options: append([]equipo.Option{}, options...), Links: append([]equipo.Link{}, links...)}
215 f.cards = append(f.cards, c)
216 f.emit("card", "card", c.ID, c.Revision, "", *c)
217 return c.ID
218}
219
220// RaiseConnect puts an open connect card in the conversation, raised in
221// turn (its event carries the turn's id, as Equipo's does), with one link,
222// labelled Connect, to link. It returns the card's id.
223func (f *Fake) RaiseConnect(turn, link string) string {
224 f.cmu.Lock()
225 defer f.cmu.Unlock()
226 c := &card{ID: f.next("c"), Revision: 1, Kind: equipo.CardConnect, State: "open", Question: "Connect your Oficina apps",
227 Options: []equipo.Option{}, Links: []equipo.Link{{Label: "Connect", URL: link, Rel: equipo.LinkOficinaConnect}}}
228 f.cards = append(f.cards, c)
229 f.emit("card", "card", c.ID, c.Revision, turn, *c)
230 return c.ID
231}
232
233// AskJob puts a job card in the conversation, as Equipo does when the
234// Assistant hands work on: working, getting started, linked to the job's
235// page in Equipo. It returns the card's id.
236func (f *Fake) AskJob(title string) string {
237 f.cmu.Lock()
238 defer f.cmu.Unlock()
239 now := time.Now().UTC()
240 c := &card{ID: f.next("c"), Revision: 1, Kind: equipo.CardJob, State: equipo.JobWorking, Question: title,
241 Options: []equipo.Option{}, Result: "Getting started", Detail: "Working out what's needed.", StartedAt: &now,
242 Links: []equipo.Link{{Label: "Open in Equipo", URL: f.URL + "/jobs/" + f.next("h"), Rel: equipo.LinkEquipo}}}
243 f.cards = append(f.cards, c)
244 f.emit("card", "card", c.ID, c.Revision, "", *c)
245 return c.ID
246}
247
248// AskLegacyJob puts a job card in the conversation as Equipo draws a job
249// handed on before job threads (plan decision J7): it has no thread, so no
250// link to a page in Equipo. It returns the card's id.
251func (f *Fake) AskLegacyJob(title string) string {
252 f.cmu.Lock()
253 defer f.cmu.Unlock()
254 now := time.Now().UTC()
255 c := &card{ID: f.next("c"), Revision: 1, Kind: equipo.CardJob, State: equipo.JobWorking, Question: title,
256 Options: []equipo.Option{}, Links: []equipo.Link{}, Result: "Getting started", Detail: "Working out what's needed.", StartedAt: &now}
257 f.cards = append(f.cards, c)
258 f.emit("card", "card", c.ID, c.Revision, "", *c)
259 return c.ID
260}
261
262// SetJob moves job card id to state with result and detail, and links
263// before its Equipo link, which stays last: a new revision, announced.
264func (f *Fake) SetJob(id, state, result, detail string, links ...equipo.Link) {
265 f.cmu.Lock()
266 defer f.cmu.Unlock()
267 for _, c := range f.cards {
268 if c.ID != id {
269 continue
270 }
271 next := append([]equipo.Link{}, links...)
272 for _, l := range c.Links {
273 if l.Rel == equipo.LinkEquipo {
274 next = append(next, l)
275 }
276 }
277 c.State, c.Result, c.Detail, c.Links, c.Revision = state, result, detail, next, c.Revision+1
278 f.emit("card", "card", c.ID, c.Revision, "", *c)
279 }
280}
281
282// PauseJob moves job card id to paused, with result and detail as Equipo
283// writes them in the person's time zone, and carryOn saying whether the
284// person may carry on now: a new revision, announced.
285func (f *Fake) PauseJob(id, result, detail string, carryOn bool) {
286 f.SetJob(id, equipo.JobPaused, result, detail)
287 f.cmu.Lock()
288 defer f.cmu.Unlock()
289 for _, c := range f.cards {
290 if c.ID == id && c.CarryOn != carryOn {
291 c.CarryOn, c.Revision = carryOn, c.Revision+1
292 f.emit("card", "card", c.ID, c.Revision, "", *c)
293 }
294 }
295}
296
297// StopJob moves job card id to stopped, with result and detail, and
298// carryOn saying whether the person may carry it on now (a job held
299// because building was turned off, once it is on again): a new revision,
300// announced.
301func (f *Fake) StopJob(id, result, detail string, carryOn bool) {
302 f.SetJob(id, equipo.JobStopped, result, detail)
303 f.cmu.Lock()
304 defer f.cmu.Unlock()
305 for _, c := range f.cards {
306 if c.ID == id && c.CarryOn != carryOn {
307 c.CarryOn, c.Revision = carryOn, c.Revision+1
308 f.emit("card", "card", c.ID, c.Revision, "", *c)
309 }
310 }
311}
312
313// SetJobStarted moves when job card id started to at: a new revision,
314// announced.
315func (f *Fake) SetJobStarted(id string, at time.Time) {
316 f.cmu.Lock()
317 defer f.cmu.Unlock()
318 for _, c := range f.cards {
319 if c.ID == id {
320 at := at.UTC()
321 c.StartedAt, c.Revision = &at, c.Revision+1
322 f.emit("card", "card", c.ID, c.Revision, "", *c)
323 }
324 }
325}
326
327// AskOutcomeFor puts an open outcome card in the conversation that
328// belongs to job card job, as Equipo mirrors a job's go-ahead or Publish.
329func (f *Fake) AskOutcomeFor(job, question string, options []equipo.Option, links []equipo.Link) string {
330 return f.AskKindFor(equipo.CardOutcome, job, question, options, links)
331}
332
333// AskKindFor puts an open card of kind in the conversation that belongs
334// to job card job, such as a question mirrored before job threads.
335func (f *Fake) AskKindFor(kind, job, question string, options []equipo.Option, links []equipo.Link) string {
336 f.cmu.Lock()
337 defer f.cmu.Unlock()
338 c := &card{ID: f.next("c"), Revision: 1, Kind: kind, State: "open", Question: question, Job: job,
339 Options: append([]equipo.Option{}, options...), Links: append([]equipo.Link{}, links...)}
340 f.cards = append(f.cards, c)
341 f.emit("card", "card", c.ID, c.Revision, "", *c)
342 return c.ID
343}
344
345// EmitTurn adds a turn of kind in state that no message of the person's
346// started, such as a team_update turn, announcing it. It returns its id.
347func (f *Fake) EmitTurn(kind, state string) string {
348 f.cmu.Lock()
349 defer f.cmu.Unlock()
350 now := time.Now().UTC()
351 t := &turn{ID: f.next("t"), Revision: 1, Kind: kind, State: state, Attempt: 1, MessageIDs: []string{},
352 CreatedAt: now, UpdatedAt: now}
353 f.turns[t.ID] = t
354 f.emit("turn", "turn", t.ID, t.Revision, t.ID, *t)
355 return t.ID
356}
357
358// SetCard moves card id to state with result, a new revision, announcing
359// it.
360func (f *Fake) SetCard(id, state, result string) {
361 f.cmu.Lock()
362 defer f.cmu.Unlock()
363 for _, c := range f.cards {
364 if c.ID == id {
365 c.State, c.Result, c.Revision = state, result, c.Revision+1
366 f.emit("card", "card", c.ID, c.Revision, "", *c)
367 }
368 }
369}
370
371// NoRunner makes the person runnerless: the snapshot says the Assistant
372// is not available, and a message or a question's answer gets 409
373// no_runner.
374func (f *Fake) NoRunner() {
375 f.cmu.Lock()
376 defer f.cmu.Unlock()
377 f.runner = "no_runner"
378}
379
380// RunnerTooOld makes the person's runner too old for the Assistant: the
381// snapshot says it is not available, and a message or a question's
382// answer gets 409 runner_too_old.
383func (f *Fake) RunnerTooOld() {
384 f.cmu.Lock()
385 defer f.cmu.Unlock()
386 f.runner = "runner_too_old"
387}
388
389// SetAddress makes address the Equipo person the bearer speaks for.
390func (f *Fake) SetAddress(address string) {
391 f.cmu.Lock()
392 defer f.cmu.Unlock()
393 f.address = address
394}
395
396// RefuseHost makes every PUT host answer status with code, as Equipo does
397// when Base's origin is not on its EQUIPO_ASSISTANT_HOSTS (403
398// host_not_allowed); a zero status accepts them again.
399func (f *Fake) RefuseHost(status int, code string) {
400 f.cmu.Lock()
401 defer f.cmu.Unlock()
402 f.hostStatus, f.hostCode = status, code
403}
404
405// Hosts are the PUT host requests the fake received, oldest first.
406func (f *Fake) Hosts() []Call { return f.Calls(assistant + "/host") }
407
408// Say adds an Assistant line to the conversation.
409func (f *Fake) Say(text string) {
410 f.cmu.Lock()
411 defer f.cmu.Unlock()
412 m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: text, CreatedAt: time.Now().UTC()}
413 f.messages = append(f.messages, m)
414 f.emit("message", "message", m.ID, 1, "", m)
415}
416
417// SayWithLookups adds an Assistant line with lookups on it, as a reply
418// that looked things up has (ReplyWithLookups, without a turn).
419func (f *Fake) SayWithLookups(text string, lookups ...equipo.Lookup) {
420 f.cmu.Lock()
421 defer f.cmu.Unlock()
422 m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: text, CreatedAt: time.Now().UTC(),
423 Lookups: append([]equipo.Lookup(nil), lookups...)}
424 f.messages = append(f.messages, m)
425 f.emit("message", "message", m.ID, 1, "", m)
426}
427
428// Turn is the state of the turn with id ("" when there is none).
429func (f *Fake) Turn(id string) string {
430 f.cmu.Lock()
431 defer f.cmu.Unlock()
432 if t, ok := f.turns[id]; ok {
433 return t.State
434 }
435 return ""
436}
437
438func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) {
439 d, ok := f.bearer(r)
440 if !ok {
441 writeError(w, r, 401, "unauthenticated")
442 return
443 }
444 if f.serveFiles(w, r, d.id) {
445 return
446 }
447 // Only the Assistant's routes: a call to the Coordinator's is a 404.
448 p, ok := strings.CutPrefix(r.URL.Path, assistant)
449 switch {
450 case !ok:
451 writeError(w, r, 404, "not_found")
452 case r.Method == http.MethodPut && p == "/host":
453 f.host(w, r)
454 case r.Method == http.MethodPut && p == "/time-zone":
455 f.timeZone(w, r)
456 case r.Method == http.MethodGet && p == "/snapshot":
457 f.snapshot(w, r)
458 case r.Method == http.MethodGet && p == "/messages":
459 f.cmu.Lock()
460 writeJSON(w, 200, map[string]any{"items": read(f.tail(), f.drawsLookups(r)), "before": ""})
461 f.cmu.Unlock()
462 case r.Method == http.MethodPost && p == "/messages":
463 f.send(w, r, d.id)
464 case r.Method == http.MethodPost && strings.HasPrefix(p, "/turns/") && strings.HasSuffix(p, "/cancel"):
465 f.cancel(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/turns/"), "/cancel"))
466 case r.Method == http.MethodPost && strings.HasPrefix(p, "/cards/") && strings.HasSuffix(p, "/answer"):
467 f.answer(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/cards/"), "/answer"))
468 case r.Method == http.MethodPost && strings.HasPrefix(p, "/cards/") && strings.HasSuffix(p, "/carry_on"):
469 f.carryOn(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/cards/"), "/carry_on"))
470 case r.Method == http.MethodPost && p == "/oficina/connect":
471 f.oficinaConnect(w, r)
472 case r.Method == http.MethodPost && p == "/oficina/connect/finish":
473 f.oficinaFinish(w, r)
474 case r.Method == http.MethodGet && p == "/events":
475 f.stream(w, r)
476 default:
477 writeError(w, r, 404, "not_found")
478 }
479}
480
481func (f *Fake) tail() []message {
482 out := append([]message{}, f.messages...)
483 if len(out) > 50 {
484 out = out[len(out)-50:]
485 }
486 return out
487}
488
489func (f *Fake) snapshot(w http.ResponseWriter, r *http.Request) {
490 f.mu.Lock()
491 hold, entered, fail := f.snapHold, f.snapEntered, f.failSnapshot
492 f.snapHold, f.snapEntered = nil, nil
493 f.mu.Unlock()
494 if fail {
495 writeError(w, r, 503, "unavailable")
496 return
497 }
498 if hold != nil {
499 close(entered)
500 <-hold
501 }
502 f.cmu.Lock()
503 defer f.cmu.Unlock()
504 turns := []turn{}
505 for _, t := range f.turns {
506 turns = append(turns, *t)
507 }
508 cards := []card{}
509 for _, c := range f.cards {
510 cards = append(cards, asSeen(*c, pausedOK(r)))
511 }
512 writeJSON(w, 200, map[string]any{
513 "me": map[string]any{"id": f.address, "address": f.address, "role": "owner",
514 "person": map[string]any{"name": "Paul"}, "team_id": f.Instance, "team_name": "Tito"},
515 "messages": read(f.tail(), f.drawsLookups(r)), "turns": turns, "cards": cards, "cursor": f.cursor,
516 "available": f.runner == "", "can_attach": f.canAttach(),
517 })
518}
519
520// host is PUT host {origin, token}: 200 {origin, revision}, the token
521// never given back.
522func (f *Fake) host(w http.ResponseWriter, r *http.Request) {
523 var in struct {
524 Origin string `json:"origin"`
525 Token string `json:"token"`
526 }
527 if strict(r, &in) != nil || !strings.HasPrefix(in.Origin, "https://") && !strings.HasPrefix(in.Origin, "http://127.0.0.1") ||
528 len(in.Token) < 20 || len(in.Token) > 512 {
529 writeError(w, r, 422, "invalid_input")
530 return
531 }
532 f.cmu.Lock()
533 status, code := f.hostStatus, f.hostCode
534 f.cmu.Unlock()
535 if status != 0 {
536 writeError(w, r, status, code)
537 return
538 }
539 writeJSON(w, 200, map[string]any{"origin": in.Origin, "revision": len(f.Hosts())})
540}
541
542// send is POST messages, as Equipo's LaneStore.Send with files (the
543// assistant-attachments spec, A1): text may be empty when files come; at
544// most five, each the person's own and unsent; files need a runner that
545// can take them (409 attachments_unavailable, nothing stored). A replayed
546// key with other text or files is 409 idempotency_conflict.
547func (f *Fake) send(w http.ResponseWriter, r *http.Request, owner string) {
548 f.fmu.Lock()
549 hold, entered := f.sendHold, f.sendEntered
550 f.sendHold, f.sendEntered = nil, nil
551 f.fmu.Unlock()
552 f.waitHeld(hold, entered)
553 var in struct {
554 Text string `json:"text"`
555 IdempotencyKey string `json:"idempotency_key"`
556 Attachments []string `json:"attachments,omitempty"`
557 }
558 if strict(r, &in) != nil {
559 writeError(w, r, 422, "invalid_input")
560 return
561 }
562 in.Text = strings.TrimSpace(in.Text)
563 if (in.Text == "" && len(in.Attachments) == 0) || len(in.Text) > 16<<10 || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) ||
564 len(in.IdempotencyKey) < 1 || len(in.IdempotencyKey) > 128 || len(in.Attachments) > maxFiles ||
565 strings.HasPrefix(in.IdempotencyKey, "reply:") || strings.HasPrefix(in.IdempotencyKey, "card:") || strings.HasPrefix(in.IdempotencyKey, "handoff:") {
566 writeError(w, r, 422, "invalid_input")
567 return
568 }
569 f.cmu.Lock()
570 // A replayed key answers first, as Equipo's LaneStore.Send does; the
571 // runner is checked only for a new message.
572 if id, ok := f.sent[in.IdempotencyKey]; ok {
573 for _, m := range f.messages {
574 if m.ID != id {
575 continue
576 }
577 if m.Text != in.Text || !sameFiles(m.Attachments, in.Attachments) {
578 writeError(w, r, 409, "idempotency_conflict")
579 } else {
580 writeJSON(w, 200, map[string]any{"message": m, "turn": *f.turns[m.TurnID]})
581 }
582 }
583 f.cmu.Unlock()
584 return
585 }
586 if f.runner != "" {
587 code := f.runner
588 f.cmu.Unlock()
589 writeError(w, r, 409, code)
590 return
591 }
592 if len(in.Attachments) > 0 && !f.canAttach() {
593 f.cmu.Unlock()
594 writeError(w, r, 409, "attachments_unavailable")
595 return
596 }
597 if !f.checkFiles(owner, in.Attachments) {
598 f.cmu.Unlock()
599 writeError(w, r, 422, "invalid_input")
600 return
601 }
602 m, t := f.askWith(in.Text, func(id string) []file { return f.linkFiles(in.Attachments, id) })
603 f.sent[in.IdempotencyKey] = m.ID
604 f.cmu.Unlock()
605 f.mu.Lock()
606 lost := f.failSend
607 f.failSend = false
608 f.mu.Unlock()
609 if lost {
610 writeError(w, r, 503, "unavailable")
611 } else {
612 writeJSON(w, 201, map[string]any{"message": m, "turn": t})
613 }
614 go f.answerTurn(t.ID, in.Text)
615}
616
617// canAttach is the snapshot's can_attach: a runner that can answer and
618// can take files.
619func (f *Fake) canAttach() bool {
620 f.fmu.Lock()
621 defer f.fmu.Unlock()
622 return f.filesReady && f.runner == ""
623}
624
625func sameFiles(have []file, ids []string) bool {
626 if len(have) != len(ids) {
627 return false
628 }
629 for i := range have {
630 if have[i].ID != ids[i] {
631 return false
632 }
633 }
634 return true
635}
636
637// ask records the person's message and a queued turn; the caller holds cmu.
638func (f *Fake) ask(text string) (message, turn) { return f.askWith(text, nil) }
639
640// askWith is ask for a message with files: link, when set, links them to
641// the message's id and answers them.
642func (f *Fake) askWith(text string, link func(id string) []file) (message, turn) {
643 now := time.Now().UTC()
644 t := &turn{ID: f.next("t"), Revision: 1, State: "queued", Attempt: 1, CreatedAt: now, UpdatedAt: now}
645 m := message{ID: f.next("m"), Revision: 1, Role: "person", Text: text, TurnID: t.ID, CreatedAt: now}
646 if link != nil {
647 m.Attachments = link(m.ID)
648 }
649 t.MessageIDs = []string{m.ID}
650 f.turns[t.ID] = t
651 f.messages = append(f.messages, m)
652 f.emit("message", "message", m.ID, 1, t.ID, m)
653 f.emit("turn", "turn", t.ID, t.Revision, t.ID, *t)
654 return m, *t
655}
656
657// answerTurn runs the turn: running, the reply streamed in deltas, the
658// reply message, replied. With Hold it stops at running.
659func (f *Fake) answerTurn(id, text string) {
660 f.setTurn(id, "running", "")
661 if f.Hold {
662 return
663 }
664 f.Answer(id, f.Reply(text), true)
665}
666
667// Answer answers the running turn with id (one Hold kept running): with
668// deltas, the reply streamed in word by word first (Stream); then the
669// reply message, and the turn replied.
670func (f *Fake) Answer(id, reply string, deltas bool) { f.answerWith(id, reply, deltas, nil) }
671
672// ReplyWithLookups answers the running turn with id as Answer does (its
673// words streamed first), with lookups on the reply, as Equipo attaches
674// what the Assistant looked up for it. A read that doesn't say Base draws
675// them gets them folded into the text.
676func (f *Fake) ReplyWithLookups(id, reply string, lookups ...equipo.Lookup) {
677 f.answerWith(id, reply, true, lookups)
678}
679
680func (f *Fake) answerWith(id, reply string, deltas bool, lookups []equipo.Lookup) {
681 if deltas {
682 f.Stream(id, reply)
683 }
684 f.cmu.Lock()
685 defer f.cmu.Unlock()
686 if f.turns[id].State != "running" {
687 return
688 }
689 m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: reply, TurnID: id, CreatedAt: time.Now().UTC(),
690 Lookups: append([]equipo.Lookup(nil), lookups...)}
691 f.messages = append(f.messages, m)
692 f.emit("message", "message", m.ID, 1, id, m)
693 t := f.turns[id]
694 t.State, t.ReplyID, t.Revision, t.UpdatedAt = "replied", m.ID, t.Revision+1, time.Now().UTC()
695 f.emit("turn", "turn", id, t.Revision, id, *t)
696}
697
698// Stream streams reply into the running turn with id, word by word, as
699// Equipo's deltas: each at its offset in UTF-8 bytes. It sends no reply.
700func (f *Fake) Stream(id, reply string) { f.StreamParts(id, strings.SplitAfter(reply, " ")) }
701
702// StreamParts is Stream in the pieces given, wherever they split the text.
703func (f *Fake) StreamParts(id string, parts []string) {
704 offset := 0
705 for _, part := range parts {
706 select {
707 case <-f.closing:
708 return
709 case <-time.After(15 * time.Millisecond):
710 }
711 f.cmu.Lock()
712 if f.turns[id].State != "running" {
713 f.cmu.Unlock()
714 return
715 }
716 f.emit("delta", "turn", id, 0, id, map[string]any{"turn_id": id, "offset": offset, "text": part})
717 f.cmu.Unlock()
718 offset += len(part)
719 }
720}
721
722// Glance sends Equipo's glance for the turn with id: one line on what the
723// Assistant is about to do, before the turn's first words. Like a delta it
724// is an event only, never a message and never in a snapshot.
725func (f *Fake) Glance(id, text string) {
726 f.cmu.Lock()
727 defer f.cmu.Unlock()
728 f.emitLive("glance", "turn", id, 0, id, map[string]string{"turn_id": id, "text": text})
729}
730
731// RunTurn moves the turn with id to running, as a runner taking it does.
732func (f *Fake) RunTurn(id string) { f.setTurn(id, "running", "") }
733
734// FailTurn ends the turn with id unanswered: failed.
735func (f *Fake) FailTurn(id string) { f.setTurn(id, "failed", "") }
736
737// FailTurnFor ends the turn with id unanswered for reason, such as
738// attachment_unavailable.
739func (f *Fake) FailTurnFor(id, reason string) { f.setTurn(id, "failed", reason) }
740
741// WaitTurn puts the turn with id in the waiting state: saved, with nothing
742// yet able to answer it.
743func (f *Fake) WaitTurn(id string) { f.setTurn(id, "waiting", "") }
744
745func (f *Fake) setTurn(id, state, reason string) {
746 f.cmu.Lock()
747 defer f.cmu.Unlock()
748 t := f.turns[id]
749 t.State, t.Reason, t.Revision, t.UpdatedAt = state, reason, t.Revision+1, time.Now().UTC()
750 f.emit("turn", "turn", id, t.Revision, id, *t)
751}
752
753func (f *Fake) cancel(w http.ResponseWriter, r *http.Request, id string) {
754 f.cmu.Lock()
755 t, ok := f.turns[id]
756 if !ok {
757 f.cmu.Unlock()
758 writeError(w, r, 404, "not_found")
759 return
760 }
761 if t.State != "queued" && t.State != "running" && t.State != "waiting" {
762 f.cmu.Unlock()
763 writeError(w, r, 409, "turn_ended")
764 return
765 }
766 f.cmu.Unlock()
767 f.setTurn(id, "cancelled", "")
768 writeJSON(w, http.StatusAccepted, map[string]any{"attempt": 1})
769}
770
771func (f *Fake) answer(w http.ResponseWriter, r *http.Request, id string) {
772 var in struct {
773 Choice string `json:"choice"`
774 Revision int64 `json:"revision"`
775 }
776 if strict(r, &in) != nil {
777 writeError(w, r, 422, "invalid_input")
778 return
779 }
780 f.cmu.Lock()
781 var c *card
782 for _, x := range f.cards {
783 if x.ID == id {
784 c = x
785 }
786 }
787 if c == nil {
788 f.cmu.Unlock()
789 writeError(w, r, 404, "not_found")
790 return
791 }
792 if c.State != "open" || c.Revision != in.Revision {
793 code := "card_answered"
794 if c.State == "open" {
795 code = "card_stale"
796 }
797 writeJSON(w, 409, map[string]any{"code": code, "copy_key": "api." + code, "request_id": r.Header.Get("Idempotency-Key"), "card": *c})
798 f.cmu.Unlock()
799 return
800 }
801 label, ok := "", false
802 for _, o := range c.Options {
803 if o.Value == in.Choice {
804 label, ok = o.Label, true
805 }
806 }
807 if !ok {
808 f.cmu.Unlock()
809 writeError(w, r, 422, "invalid_input")
810 return
811 }
812 if c.Kind == "question" && f.runner != "" {
813 code := f.runner
814 f.cmu.Unlock()
815 writeError(w, r, 409, code)
816 return
817 }
818 c.State, c.Revision = "answered", c.Revision+1
819 if c.Kind != "question" {
820 // As Equipo does for an outcome card: the card says how it ended,
821 // and the answer starts no turn, so its message and turn are
822 // empty (a zero time included).
823 c.Result = label
824 f.emit("card", "card", c.ID, c.Revision, "", *c)
825 f.cmu.Unlock()
826 writeJSON(w, 200, map[string]any{"card": *c, "message": message{}, "turn": turn{}})
827 return
828 }
829 c.Result = in.Choice
830 f.emit("card", "card", c.ID, c.Revision, "", *c)
831 m, t := f.ask(in.Choice)
832 f.cmu.Unlock()
833 writeJSON(w, 200, map[string]any{"card": *c, "message": m, "turn": t})
834 go f.answerTurn(t.ID, in.Choice)
835}
836
837// carryOn is POST cards/{id}/carry_on {revision, idempotency_key}, as
838// Equipo's docs/api/equipo-v1.md says: a paused job that offers it
839// (carry_on) starts again now, working, and the answer is 200 {"card"}.
840// A key that already carried this card on gets 200 with the card as it is
841// now, as Equipo's job_paused.go does. 409 card_stale at another
842// revision, not_paused when it is not paused, carry_on_unavailable when it
843// does not offer it, each {code, copy_key, request_id, card}; 404 for
844// anything but a job card.
845func (f *Fake) carryOn(w http.ResponseWriter, r *http.Request, id string) {
846 var in struct {
847 Revision int64 `json:"revision"`
848 IdempotencyKey string `json:"idempotency_key"`
849 }
850 if strict(r, &in) != nil || len(in.IdempotencyKey) < 1 || len(in.IdempotencyKey) > 128 {
851 writeError(w, r, 422, "invalid_input")
852 return
853 }
854 f.cmu.Lock()
855 defer f.cmu.Unlock()
856 if f.carryStatus != 0 {
857 writeError(w, r, f.carryStatus, "unavailable")
858 return
859 }
860 var c *card
861 for _, x := range f.cards {
862 if x.ID == id && x.Kind == equipo.CardJob {
863 c = x
864 }
865 }
866 conflict := func(code string) {
867 request := r.Header.Get("Idempotency-Key")
868 if request == "" || len(request) > 256 {
869 request = rand.Text()
870 }
871 writeJSON(w, 409, map[string]any{"code": code, "copy_key": "api." + code, "request_id": request, "card": *c})
872 }
873 switch {
874 case c == nil:
875 writeError(w, r, 404, "not_found")
876 case f.carried[c.ID+"\x00"+in.IdempotencyKey]:
877 writeJSON(w, 200, map[string]any{"card": *c})
878 case c.Revision != in.Revision:
879 conflict("card_stale")
880 case c.State != equipo.JobPaused && c.State != equipo.JobStopped:
881 conflict("not_paused")
882 case !c.CarryOn:
883 conflict("carry_on_unavailable")
884 default:
885 c.State, c.Result, c.Detail, c.CarryOn, c.Revision = equipo.JobWorking, "Carrying on", "Picking up where it left off.", false, c.Revision+1
886 f.emit("card", "card", c.ID, c.Revision, "", *c)
887 f.carried[c.ID+"\x00"+in.IdempotencyKey] = true
888 writeJSON(w, 200, map[string]any{"card": *c})
889 }
890}
891
892// pausedOK reports whether r opted in to the paused job state
893// (job_states=paused, a comma-separated list).
894func pausedOK(r *http.Request) bool {
895 for _, v := range r.URL.Query()["job_states"] {
896 for _, s := range strings.Split(v, ",") {
897 if s == equipo.JobPaused {
898 return true
899 }
900 }
901 }
902 return false
903}
904
905// asSeen is c as a client sees it: without the paused opt-in, a paused
906// job comes as working with the same result and detail and no carry_on.
907func asSeen(c card, paused bool) card {
908 if !paused && c.Kind == equipo.CardJob && c.State == equipo.JobPaused {
909 c.State, c.CarryOn = equipo.JobWorking, false
910 }
911 return c
912}
913
914// timeZone is PUT assistant/time-zone {time_zone, only_if_unset}, as
915// Equipo's zone.go (31cdb35d): 200 {time_zone: the zone in effect} for a
916// zone Go knows (an IANA name), else 422 invalid_input. With only_if_unset
917// a zone the person's own browser or device set stays; one Base set
918// before is replaced.
919func (f *Fake) timeZone(w http.ResponseWriter, r *http.Request) {
920 var in struct {
921 TimeZone string `json:"time_zone"`
922 OnlyIfUnset bool `json:"only_if_unset"`
923 }
924 f.cmu.Lock()
925 status, code, hold := f.zoneStatus, f.zoneCode, f.zoneHold
926 f.cmu.Unlock()
927 if hold != nil {
928 select {
929 case <-hold:
930 case <-r.Context().Done():
931 return
932 case <-f.closing:
933 return
934 }
935 }
936 if status != 0 {
937 writeError(w, r, status, code)
938 return
939 }
940 if strict(r, &in) != nil || in.TimeZone == "" || in.TimeZone == "Local" {
941 writeError(w, r, 422, "invalid_input")
942 return
943 }
944 if _, err := time.LoadLocation(in.TimeZone); err != nil {
945 writeError(w, r, 422, "invalid_input")
946 return
947 }
948 f.cmu.Lock()
949 if !in.OnlyIfUnset || !f.zoneOwn {
950 f.zone, f.zoneOwn = in.TimeZone, false
951 }
952 zone := f.zone
953 f.cmu.Unlock()
954 writeJSON(w, 200, map[string]string{"time_zone": zone})
955}
956
957// FailCarryOn makes every carry_on answer status (a 5xx; 0 stops).
958func (f *Fake) FailCarryOn(status int) { f.cmu.Lock(); f.carryStatus = status; f.cmu.Unlock() }
959
960// SetTimeZone sets the person's zone, as one of their own devices does.
961func (f *Fake) SetTimeZone(zone string) { f.cmu.Lock(); f.zone, f.zoneOwn = zone, true; f.cmu.Unlock() }
962
963// RefuseTimeZone makes every PUT time-zone answer status with code (0
964// accepts them again).
965func (f *Fake) RefuseTimeZone(status int, code string) {
966 f.cmu.Lock()
967 f.zoneStatus, f.zoneCode = status, code
968 f.cmu.Unlock()
969}
970
971// HoldTimeZone holds every PUT time-zone (until the request gives up)
972// until release is called; calls after that answer at once.
973func (f *Fake) HoldTimeZone() (release func()) {
974 hold := make(chan struct{})
975 f.cmu.Lock()
976 f.zoneHold = hold
977 f.cmu.Unlock()
978 return sync.OnceFunc(func() {
979 f.cmu.Lock()
980 if f.zoneHold == hold {
981 f.zoneHold = nil
982 }
983 f.cmu.Unlock()
984 close(hold)
985 })
986}
987
988// TimeZone is the zone the person set (PUT time-zone), "" before any.
989func (f *Fake) TimeZone() string {
990 f.cmu.Lock()
991 defer f.cmu.Unlock()
992 return f.zone
993}
994
995// stream is GET events: Server-Sent Events after ?after= (or
996// Last-Event-ID), as Equipo writes them: then, live events (cursor 0, no
997// id line) that come while the stream is open.
998func (f *Fake) stream(w http.ResponseWriter, r *http.Request) {
999 raw := r.URL.Query().Get("after")
1000 if raw == "" {
1001 raw = r.Header.Get("Last-Event-ID")
1002 }
1003 f.cmu.Lock()
1004 after, next := f.cursor, 0
1005 live := len(f.events)
1006 f.cmu.Unlock()
1007 if raw != "" {
1008 n, err := strconv.ParseInt(raw, 10, 64)
1009 if err != nil || n < 0 {
1010 writeError(w, r, 422, "invalid_input")
1011 return
1012 }
1013 after = n
1014 }
1015 paused, draws := pausedOK(r), f.drawsLookups(r)
1016 rc := http.NewResponseController(w)
1017 w.Header().Set("Content-Type", "text/event-stream")
1018 w.WriteHeader(200)
1019 if _, err := io.WriteString(w, "retry: 2000\n: ok\n\n"); err != nil || rc.Flush() != nil {
1020 return
1021 }
1022 for {
1023 f.cmu.Lock()
1024 var batch []event
1025 for i, e := range f.events[next:] {
1026 if e.Cursor > after || (e.Cursor == 0 && next+i >= live) {
1027 batch = append(batch, e)
1028 }
1029 }
1030 next = len(f.events)
1031 wake := f.wake
1032 f.cmu.Unlock()
1033 for _, e := range batch {
1034 if c, ok := e.Data.(card); ok {
1035 e.Data = asSeen(c, paused)
1036 }
1037 if m, ok := e.Data.(message); ok {
1038 e.Data = asRead(m, draws)
1039 }
1040 raw, _ := json.Marshal(e)
1041 id := ""
1042 if e.Cursor != 0 {
1043 id = fmt.Sprintf("id: %d\n", e.Cursor)
1044 after = e.Cursor
1045 }
1046 if _, err := fmt.Fprintf(w, "%sevent: %s\ndata: %s\n\n", id, e.Type, raw); err != nil {
1047 return
1048 }
1049 }
1050 if rc.Flush() != nil {
1051 return
1052 }
1053 select {
1054 case <-r.Context().Done():
1055 return
1056 case <-f.closing:
1057 return
1058 case <-wake:
1059 }
1060 }
1061}
1062
1063// OficinaConsent sets the consent URL connect answers with; FinishWith the
1064// status finish answers with. FailOficina makes both answer status with code
1065// (0 stops).
1066func (f *Fake) OficinaConsent(url string) { f.cmu.Lock(); f.consent = url; f.cmu.Unlock() }
1067func (f *Fake) FinishWith(status string) { f.cmu.Lock(); f.finish = status; f.cmu.Unlock() }
1068func (f *Fake) FailOficina(status int, code string) {
1069 f.cmu.Lock()
1070 f.oficinaStatus, f.oficinaCode = status, code
1071 f.cmu.Unlock()
1072}
1073
1074// OtherPersonsState is a state finish refuses with 403, as Equipo does for
1075// a state that belongs to someone else.
1076const OtherPersonsState = "someone-else"
1077
1078func (f *Fake) oficinaConnect(w http.ResponseWriter, r *http.Request) {
1079 var in struct {
1080 ReturnTo string `json:"return_to"`
1081 }
1082 f.cmu.Lock()
1083 status, code, consent := f.oficinaStatus, f.oficinaCode, f.consent
1084 f.cmu.Unlock()
1085 if strict(r, &in) != nil || in.ReturnTo == "" {
1086 writeError(w, r, 422, "invalid_input")
1087 return
1088 }
1089 if status != 0 {
1090 writeError(w, r, status, code)
1091 return
1092 }
1093 if consent == "" {
1094 consent = "https://oficina.example/consent?x=1"
1095 }
1096 writeJSON(w, 200, map[string]string{"url": consent})
1097}
1098
1099func (f *Fake) oficinaFinish(w http.ResponseWriter, r *http.Request) {
1100 var in struct {
1101 State string `json:"state"`
1102 Code string `json:"code"`
1103 }
1104 f.cmu.Lock()
1105 status, code, finish := f.oficinaStatus, f.oficinaCode, f.finish
1106 f.cmu.Unlock()
1107 if strict(r, &in) != nil || in.State == "" || in.Code == "" {
1108 writeError(w, r, 422, "invalid_input")
1109 return
1110 }
1111 switch {
1112 case in.State == OtherPersonsState:
1113 writeError(w, r, 403, "forbidden")
1114 case status != 0:
1115 writeError(w, r, status, code)
1116 default:
1117 if finish == "" {
1118 finish = "connected"
1119 }
1120 if finish == "connected" {
1121 f.settleConnect()
1122 }
1123 writeJSON(w, 200, map[string]string{"status": finish})
1124 }
1125}
1126
1127// settleConnect resolves the open connect cards, as Equipo does once the
1128// person has connected.
1129func (f *Fake) settleConnect() {
1130 f.cmu.Lock()
1131 defer f.cmu.Unlock()
1132 for _, c := range f.cards {
1133 if c.Kind == equipo.CardConnect && c.State == "open" {
1134 c.State, c.Revision = "resolved", c.Revision+1
1135 f.emit("card", "card", c.ID, c.Revision, "", *c)
1136 }
1137 }
1138}
1139