package equipotest import ( "crypto/rand" "encoding/json" "fmt" "io" "net/http" "strconv" "strings" "sync" "time" "unicode/utf8" "amadan.net/oficina/base/internal/equipo" ) // assistant is the prefix of the Assistant's routes, the only chat routes // the fake serves. const assistant = "/api/v1/assistant" // The chat's resources in wire's JSON shapes (Message, Turn, // AssistantCard, Event). type message struct { ID string `json:"id"` Revision int64 `json:"revision"` Role string `json:"role"` Text string `json:"text"` TurnID string `json:"turn_id"` CreatedAt time.Time `json:"created_at"` Switched *struct{} `json:"switched"` // Attachments are the files sent with a person's message, in order; // omitted when there are none (wire.Message). Attachments []file `json:"attachments,omitempty"` // Lookups are what the Assistant looked up for a reply, sent only to // a Base that draws them (asRead). Lookups []equipo.Lookup `json:"lookups,omitempty"` } // drawsLookups reports whether r says Base draws lookup answers // (Base-Capabilities), as Equipo reads it. func (f *Fake) drawsLookups(r *http.Request) bool { if f.LookupsRegardless { return true } for _, v := range r.Header.Values(equipo.CapabilitiesHeader) { for _, c := range strings.Split(v, ",") { if strings.TrimSpace(c) == equipo.CapLookupAnswers { return true } } } return false } // asRead is m as a read with draws gets it: its lookups as they are, or, // for a Base that can't draw them, folded into its text, as Equipo's // plain-text fallback does (computed at read time, never stored). func asRead(m message, draws bool) message { if draws || len(m.Lookups) == 0 { return m } m.Text = equipo.Message{Text: m.Text, Lookups: m.Lookups}.PlainLookups().Text m.Lookups = nil return m } // read is msgs as a read with draws gets them (asRead). func read(msgs []message, draws bool) []message { out := make([]message, len(msgs)) for i, m := range msgs { out[i] = asRead(m, draws) } return out } type turn struct { ID string `json:"id"` Revision int64 `json:"revision"` Kind string `json:"kind"` State string `json:"state"` Reason string `json:"reason"` Attempt int64 `json:"attempt"` MessageIDs []string `json:"message_ids"` ReplyID string `json:"reply_id"` Connection string `json:"connection"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` Timing *struct{} `json:"timing"` } // card is wire.AssistantCard: options and links are never null. type card struct { ID string `json:"id"` Revision int64 `json:"revision"` Kind string `json:"kind"` State string `json:"state"` Question string `json:"question"` Options []equipo.Option `json:"options"` Links []equipo.Link `json:"links"` Result string `json:"result"` Job string `json:"job,omitempty"` Detail string `json:"detail,omitempty"` StartedAt *time.Time `json:"started_at,omitempty"` CarryOn bool `json:"carry_on,omitempty"` } type event struct { Cursor int64 `json:"cursor"` Type string `json:"type"` Resource string `json:"resource"` ID string `json:"id"` Revision int64 `json:"revision"` TurnID string `json:"turn_id,omitempty"` MessageID string `json:"message_id,omitempty"` Attempt int64 `json:"attempt,omitempty"` Data any `json:"data"` } // chat is one person's conversation with the Assistant. type chat struct { cmu sync.Mutex seq int messages []message turns map[string]*turn cards []*card events []event // in order; a live event (a glance) has cursor 0 cursor int64 // the newest event's cursor, from 40 sent map[string]string // idempotency key to message id carried map[string]bool // carry_on's card id and idempotency key, once carried on wake chan struct{} // closed at each new event // runner is why the person's runner cannot answer: "no_runner", // "runner_too_old", or "" when it can. runner string // address is who the bearer speaks for (the snapshot's me.address). address string // zone is the person's time zone; zoneOwn says their own browser or // device set it (SetTimeZone), not Base (PUT assistant/time-zone). zone string zoneOwn bool // zoneStatus and zoneCode, when set, are what every PUT time-zone // gets; zoneHold, when set, holds each one until it closes. zoneStatus int zoneCode string zoneHold chan struct{} // carryStatus, when set, is what every carry_on gets (a 5xx). carryStatus int // hostStatus and hostCode, when set, are what every PUT host gets. hostStatus int hostCode string // consent is the URL connect gives; finish is the status finish gives // (default connected); oficinaStatus and oficinaCode, when set, are what // both answer instead. consent, finish string oficinaStatus int oficinaCode string } func (c *chat) init() { c.turns, c.sent, c.carried, c.wake = map[string]*turn{}, map[string]string{}, map[string]bool{}, make(chan struct{}) c.cursor = 40 c.address = "paul@tito.io" } func (c *chat) next(prefix string) string { c.seq++; return fmt.Sprintf("%s_%04d", prefix, c.seq) } // emit records an event at the next cursor; the caller holds cmu. func (c *chat) emit(typ, resource, id string, rev int64, turnID string, data any) { c.cursor++ c.add(event{Cursor: c.cursor, Type: typ, Resource: resource, ID: id, Revision: rev, TurnID: turnID, Attempt: 1, Data: data}) } // emitLive records a live event, as Equipo sends a glance: cursor 0, sent // only to the streams open now, never again; the caller holds cmu. func (c *chat) emitLive(typ, resource, id string, rev int64, turnID string, data any) { c.add(event{Type: typ, Resource: resource, ID: id, Revision: rev, TurnID: turnID, Attempt: 1, Data: data}) } func (c *chat) add(e event) { c.events = append(c.events, e) close(c.wake) c.wake = make(chan struct{}) } // Emit adds an event of any type, such as one Base must not pass on. func (f *Fake) Emit(typ string, data any) { f.cmu.Lock() defer f.cmu.Unlock() f.emit(typ, typ, "x", 1, "", data) } // AskQuestion puts an open question card in the conversation, as the // Assistant's ask_person does: each option's value is its label. func (f *Fake) AskQuestion(question string, options ...string) string { opts := make([]equipo.Option, len(options)) for i, o := range options { opts[i] = equipo.Option{Value: o, Label: o} } return f.AskKind("question", question, opts, nil) } // AskOutcome puts an open outcome card in the conversation, as Equipo // does when the team's work needs the person. func (f *Fake) AskOutcome(question string, options []equipo.Option, links []equipo.Link) string { return f.AskKind("outcome", question, options, links) } // AskKind puts an open card of any kind in the conversation, such as one // Base must not show. func (f *Fake) AskKind(kind, question string, options []equipo.Option, links []equipo.Link) string { f.cmu.Lock() defer f.cmu.Unlock() c := &card{ID: f.next("c"), Revision: 1, Kind: kind, State: "open", Question: question, Options: append([]equipo.Option{}, options...), Links: append([]equipo.Link{}, links...)} f.cards = append(f.cards, c) f.emit("card", "card", c.ID, c.Revision, "", *c) return c.ID } // RaiseConnect puts an open connect card in the conversation, raised in // turn (its event carries the turn's id, as Equipo's does), with one link, // labelled Connect, to link. It returns the card's id. func (f *Fake) RaiseConnect(turn, link string) string { f.cmu.Lock() defer f.cmu.Unlock() c := &card{ID: f.next("c"), Revision: 1, Kind: equipo.CardConnect, State: "open", Question: "Connect your Oficina apps", Options: []equipo.Option{}, Links: []equipo.Link{{Label: "Connect", URL: link, Rel: equipo.LinkOficinaConnect}}} f.cards = append(f.cards, c) f.emit("card", "card", c.ID, c.Revision, turn, *c) return c.ID } // AskJob puts a job card in the conversation, as Equipo does when the // Assistant hands work on: working, getting started, linked to the job's // page in Equipo. It returns the card's id. func (f *Fake) AskJob(title string) string { f.cmu.Lock() defer f.cmu.Unlock() now := time.Now().UTC() c := &card{ID: f.next("c"), Revision: 1, Kind: equipo.CardJob, State: equipo.JobWorking, Question: title, Options: []equipo.Option{}, Result: "Getting started", Detail: "Working out what's needed.", StartedAt: &now, Links: []equipo.Link{{Label: "Open in Equipo", URL: f.URL + "/jobs/" + f.next("h"), Rel: equipo.LinkEquipo}}} f.cards = append(f.cards, c) f.emit("card", "card", c.ID, c.Revision, "", *c) return c.ID } // AskLegacyJob puts a job card in the conversation as Equipo draws a job // handed on before job threads (plan decision J7): it has no thread, so no // link to a page in Equipo. It returns the card's id. func (f *Fake) AskLegacyJob(title string) string { f.cmu.Lock() defer f.cmu.Unlock() now := time.Now().UTC() c := &card{ID: f.next("c"), Revision: 1, Kind: equipo.CardJob, State: equipo.JobWorking, Question: title, Options: []equipo.Option{}, Links: []equipo.Link{}, Result: "Getting started", Detail: "Working out what's needed.", StartedAt: &now} f.cards = append(f.cards, c) f.emit("card", "card", c.ID, c.Revision, "", *c) return c.ID } // SetJob moves job card id to state with result and detail, and links // before its Equipo link, which stays last: a new revision, announced. func (f *Fake) SetJob(id, state, result, detail string, links ...equipo.Link) { f.cmu.Lock() defer f.cmu.Unlock() for _, c := range f.cards { if c.ID != id { continue } next := append([]equipo.Link{}, links...) for _, l := range c.Links { if l.Rel == equipo.LinkEquipo { next = append(next, l) } } c.State, c.Result, c.Detail, c.Links, c.Revision = state, result, detail, next, c.Revision+1 f.emit("card", "card", c.ID, c.Revision, "", *c) } } // PauseJob moves job card id to paused, with result and detail as Equipo // writes them in the person's time zone, and carryOn saying whether the // person may carry on now: a new revision, announced. func (f *Fake) PauseJob(id, result, detail string, carryOn bool) { f.SetJob(id, equipo.JobPaused, result, detail) f.cmu.Lock() defer f.cmu.Unlock() for _, c := range f.cards { if c.ID == id && c.CarryOn != carryOn { c.CarryOn, c.Revision = carryOn, c.Revision+1 f.emit("card", "card", c.ID, c.Revision, "", *c) } } } // StopJob moves job card id to stopped, with result and detail, and // carryOn saying whether the person may carry it on now (a job held // because building was turned off, once it is on again): a new revision, // announced. func (f *Fake) StopJob(id, result, detail string, carryOn bool) { f.SetJob(id, equipo.JobStopped, result, detail) f.cmu.Lock() defer f.cmu.Unlock() for _, c := range f.cards { if c.ID == id && c.CarryOn != carryOn { c.CarryOn, c.Revision = carryOn, c.Revision+1 f.emit("card", "card", c.ID, c.Revision, "", *c) } } } // SetJobStarted moves when job card id started to at: a new revision, // announced. func (f *Fake) SetJobStarted(id string, at time.Time) { f.cmu.Lock() defer f.cmu.Unlock() for _, c := range f.cards { if c.ID == id { at := at.UTC() c.StartedAt, c.Revision = &at, c.Revision+1 f.emit("card", "card", c.ID, c.Revision, "", *c) } } } // AskOutcomeFor puts an open outcome card in the conversation that // belongs to job card job, as Equipo mirrors a job's go-ahead or Publish. func (f *Fake) AskOutcomeFor(job, question string, options []equipo.Option, links []equipo.Link) string { return f.AskKindFor(equipo.CardOutcome, job, question, options, links) } // AskKindFor puts an open card of kind in the conversation that belongs // to job card job, such as a question mirrored before job threads. func (f *Fake) AskKindFor(kind, job, question string, options []equipo.Option, links []equipo.Link) string { f.cmu.Lock() defer f.cmu.Unlock() c := &card{ID: f.next("c"), Revision: 1, Kind: kind, State: "open", Question: question, Job: job, Options: append([]equipo.Option{}, options...), Links: append([]equipo.Link{}, links...)} f.cards = append(f.cards, c) f.emit("card", "card", c.ID, c.Revision, "", *c) return c.ID } // EmitTurn adds a turn of kind in state that no message of the person's // started, such as a team_update turn, announcing it. It returns its id. func (f *Fake) EmitTurn(kind, state string) string { f.cmu.Lock() defer f.cmu.Unlock() now := time.Now().UTC() t := &turn{ID: f.next("t"), Revision: 1, Kind: kind, State: state, Attempt: 1, MessageIDs: []string{}, CreatedAt: now, UpdatedAt: now} f.turns[t.ID] = t f.emit("turn", "turn", t.ID, t.Revision, t.ID, *t) return t.ID } // SetCard moves card id to state with result, a new revision, announcing // it. func (f *Fake) SetCard(id, state, result string) { f.cmu.Lock() defer f.cmu.Unlock() for _, c := range f.cards { if c.ID == id { c.State, c.Result, c.Revision = state, result, c.Revision+1 f.emit("card", "card", c.ID, c.Revision, "", *c) } } } // NoRunner makes the person runnerless: the snapshot says the Assistant // is not available, and a message or a question's answer gets 409 // no_runner. func (f *Fake) NoRunner() { f.cmu.Lock() defer f.cmu.Unlock() f.runner = "no_runner" } // RunnerTooOld makes the person's runner too old for the Assistant: the // snapshot says it is not available, and a message or a question's // answer gets 409 runner_too_old. func (f *Fake) RunnerTooOld() { f.cmu.Lock() defer f.cmu.Unlock() f.runner = "runner_too_old" } // SetAddress makes address the Equipo person the bearer speaks for. func (f *Fake) SetAddress(address string) { f.cmu.Lock() defer f.cmu.Unlock() f.address = address } // RefuseHost makes every PUT host answer status with code, as Equipo does // when Base's origin is not on its EQUIPO_ASSISTANT_HOSTS (403 // host_not_allowed); a zero status accepts them again. func (f *Fake) RefuseHost(status int, code string) { f.cmu.Lock() defer f.cmu.Unlock() f.hostStatus, f.hostCode = status, code } // Hosts are the PUT host requests the fake received, oldest first. func (f *Fake) Hosts() []Call { return f.Calls(assistant + "/host") } // Say adds an Assistant line to the conversation. func (f *Fake) Say(text string) { f.cmu.Lock() defer f.cmu.Unlock() m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: text, CreatedAt: time.Now().UTC()} f.messages = append(f.messages, m) f.emit("message", "message", m.ID, 1, "", m) } // SayWithLookups adds an Assistant line with lookups on it, as a reply // that looked things up has (ReplyWithLookups, without a turn). func (f *Fake) SayWithLookups(text string, lookups ...equipo.Lookup) { f.cmu.Lock() defer f.cmu.Unlock() m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: text, CreatedAt: time.Now().UTC(), Lookups: append([]equipo.Lookup(nil), lookups...)} f.messages = append(f.messages, m) f.emit("message", "message", m.ID, 1, "", m) } // Turn is the state of the turn with id ("" when there is none). func (f *Fake) Turn(id string) string { f.cmu.Lock() defer f.cmu.Unlock() if t, ok := f.turns[id]; ok { return t.State } return "" } func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) { d, ok := f.bearer(r) if !ok { writeError(w, r, 401, "unauthenticated") return } if f.serveFiles(w, r, d.id) { return } // Only the Assistant's routes: a call to the Coordinator's is a 404. p, ok := strings.CutPrefix(r.URL.Path, assistant) switch { case !ok: writeError(w, r, 404, "not_found") case r.Method == http.MethodPut && p == "/host": f.host(w, r) case r.Method == http.MethodPut && p == "/time-zone": f.timeZone(w, r) case r.Method == http.MethodGet && p == "/snapshot": f.snapshot(w, r) case r.Method == http.MethodGet && p == "/messages": f.cmu.Lock() writeJSON(w, 200, map[string]any{"items": read(f.tail(), f.drawsLookups(r)), "before": ""}) f.cmu.Unlock() case r.Method == http.MethodPost && p == "/messages": f.send(w, r, d.id) case r.Method == http.MethodPost && strings.HasPrefix(p, "/turns/") && strings.HasSuffix(p, "/cancel"): f.cancel(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/turns/"), "/cancel")) case r.Method == http.MethodPost && strings.HasPrefix(p, "/cards/") && strings.HasSuffix(p, "/answer"): f.answer(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/cards/"), "/answer")) case r.Method == http.MethodPost && strings.HasPrefix(p, "/cards/") && strings.HasSuffix(p, "/carry_on"): f.carryOn(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/cards/"), "/carry_on")) case r.Method == http.MethodPost && p == "/oficina/connect": f.oficinaConnect(w, r) case r.Method == http.MethodPost && p == "/oficina/connect/finish": f.oficinaFinish(w, r) case r.Method == http.MethodGet && p == "/events": f.stream(w, r) default: writeError(w, r, 404, "not_found") } } func (f *Fake) tail() []message { out := append([]message{}, f.messages...) if len(out) > 50 { out = out[len(out)-50:] } return out } func (f *Fake) snapshot(w http.ResponseWriter, r *http.Request) { f.mu.Lock() hold, entered, fail := f.snapHold, f.snapEntered, f.failSnapshot f.snapHold, f.snapEntered = nil, nil f.mu.Unlock() if fail { writeError(w, r, 503, "unavailable") return } if hold != nil { close(entered) <-hold } f.cmu.Lock() defer f.cmu.Unlock() turns := []turn{} for _, t := range f.turns { turns = append(turns, *t) } cards := []card{} for _, c := range f.cards { cards = append(cards, asSeen(*c, pausedOK(r))) } writeJSON(w, 200, map[string]any{ "me": map[string]any{"id": f.address, "address": f.address, "role": "owner", "person": map[string]any{"name": "Paul"}, "team_id": f.Instance, "team_name": "Tito"}, "messages": read(f.tail(), f.drawsLookups(r)), "turns": turns, "cards": cards, "cursor": f.cursor, "available": f.runner == "", "can_attach": f.canAttach(), }) } // host is PUT host {origin, token}: 200 {origin, revision}, the token // never given back. func (f *Fake) host(w http.ResponseWriter, r *http.Request) { var in struct { Origin string `json:"origin"` Token string `json:"token"` } if strict(r, &in) != nil || !strings.HasPrefix(in.Origin, "https://") && !strings.HasPrefix(in.Origin, "http://127.0.0.1") || len(in.Token) < 20 || len(in.Token) > 512 { writeError(w, r, 422, "invalid_input") return } f.cmu.Lock() status, code := f.hostStatus, f.hostCode f.cmu.Unlock() if status != 0 { writeError(w, r, status, code) return } writeJSON(w, 200, map[string]any{"origin": in.Origin, "revision": len(f.Hosts())}) } // send is POST messages, as Equipo's LaneStore.Send with files (the // assistant-attachments spec, A1): text may be empty when files come; at // most five, each the person's own and unsent; files need a runner that // can take them (409 attachments_unavailable, nothing stored). A replayed // key with other text or files is 409 idempotency_conflict. func (f *Fake) send(w http.ResponseWriter, r *http.Request, owner string) { f.fmu.Lock() hold, entered := f.sendHold, f.sendEntered f.sendHold, f.sendEntered = nil, nil f.fmu.Unlock() f.waitHeld(hold, entered) var in struct { Text string `json:"text"` IdempotencyKey string `json:"idempotency_key"` Attachments []string `json:"attachments,omitempty"` } if strict(r, &in) != nil { writeError(w, r, 422, "invalid_input") return } in.Text = strings.TrimSpace(in.Text) if (in.Text == "" && len(in.Attachments) == 0) || len(in.Text) > 16<<10 || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) || len(in.IdempotencyKey) < 1 || len(in.IdempotencyKey) > 128 || len(in.Attachments) > maxFiles || strings.HasPrefix(in.IdempotencyKey, "reply:") || strings.HasPrefix(in.IdempotencyKey, "card:") || strings.HasPrefix(in.IdempotencyKey, "handoff:") { writeError(w, r, 422, "invalid_input") return } f.cmu.Lock() // A replayed key answers first, as Equipo's LaneStore.Send does; the // runner is checked only for a new message. if id, ok := f.sent[in.IdempotencyKey]; ok { for _, m := range f.messages { if m.ID != id { continue } if m.Text != in.Text || !sameFiles(m.Attachments, in.Attachments) { writeError(w, r, 409, "idempotency_conflict") } else { writeJSON(w, 200, map[string]any{"message": m, "turn": *f.turns[m.TurnID]}) } } f.cmu.Unlock() return } if f.runner != "" { code := f.runner f.cmu.Unlock() writeError(w, r, 409, code) return } if len(in.Attachments) > 0 && !f.canAttach() { f.cmu.Unlock() writeError(w, r, 409, "attachments_unavailable") return } if !f.checkFiles(owner, in.Attachments) { f.cmu.Unlock() writeError(w, r, 422, "invalid_input") return } m, t := f.askWith(in.Text, func(id string) []file { return f.linkFiles(in.Attachments, id) }) f.sent[in.IdempotencyKey] = m.ID f.cmu.Unlock() f.mu.Lock() lost := f.failSend f.failSend = false f.mu.Unlock() if lost { writeError(w, r, 503, "unavailable") } else { writeJSON(w, 201, map[string]any{"message": m, "turn": t}) } go f.answerTurn(t.ID, in.Text) } // canAttach is the snapshot's can_attach: a runner that can answer and // can take files. func (f *Fake) canAttach() bool { f.fmu.Lock() defer f.fmu.Unlock() return f.filesReady && f.runner == "" } func sameFiles(have []file, ids []string) bool { if len(have) != len(ids) { return false } for i := range have { if have[i].ID != ids[i] { return false } } return true } // ask records the person's message and a queued turn; the caller holds cmu. func (f *Fake) ask(text string) (message, turn) { return f.askWith(text, nil) } // askWith is ask for a message with files: link, when set, links them to // the message's id and answers them. func (f *Fake) askWith(text string, link func(id string) []file) (message, turn) { now := time.Now().UTC() t := &turn{ID: f.next("t"), Revision: 1, State: "queued", Attempt: 1, CreatedAt: now, UpdatedAt: now} m := message{ID: f.next("m"), Revision: 1, Role: "person", Text: text, TurnID: t.ID, CreatedAt: now} if link != nil { m.Attachments = link(m.ID) } t.MessageIDs = []string{m.ID} f.turns[t.ID] = t f.messages = append(f.messages, m) f.emit("message", "message", m.ID, 1, t.ID, m) f.emit("turn", "turn", t.ID, t.Revision, t.ID, *t) return m, *t } // answerTurn runs the turn: running, the reply streamed in deltas, the // reply message, replied. With Hold it stops at running. func (f *Fake) answerTurn(id, text string) { f.setTurn(id, "running", "") if f.Hold { return } f.Answer(id, f.Reply(text), true) } // Answer answers the running turn with id (one Hold kept running): with // deltas, the reply streamed in word by word first (Stream); then the // reply message, and the turn replied. func (f *Fake) Answer(id, reply string, deltas bool) { f.answerWith(id, reply, deltas, nil) } // ReplyWithLookups answers the running turn with id as Answer does (its // words streamed first), with lookups on the reply, as Equipo attaches // what the Assistant looked up for it. A read that doesn't say Base draws // them gets them folded into the text. func (f *Fake) ReplyWithLookups(id, reply string, lookups ...equipo.Lookup) { f.answerWith(id, reply, true, lookups) } func (f *Fake) answerWith(id, reply string, deltas bool, lookups []equipo.Lookup) { if deltas { f.Stream(id, reply) } f.cmu.Lock() defer f.cmu.Unlock() if f.turns[id].State != "running" { return } m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: reply, TurnID: id, CreatedAt: time.Now().UTC(), Lookups: append([]equipo.Lookup(nil), lookups...)} f.messages = append(f.messages, m) f.emit("message", "message", m.ID, 1, id, m) t := f.turns[id] t.State, t.ReplyID, t.Revision, t.UpdatedAt = "replied", m.ID, t.Revision+1, time.Now().UTC() f.emit("turn", "turn", id, t.Revision, id, *t) } // Stream streams reply into the running turn with id, word by word, as // Equipo's deltas: each at its offset in UTF-8 bytes. It sends no reply. func (f *Fake) Stream(id, reply string) { f.StreamParts(id, strings.SplitAfter(reply, " ")) } // StreamParts is Stream in the pieces given, wherever they split the text. func (f *Fake) StreamParts(id string, parts []string) { offset := 0 for _, part := range parts { select { case <-f.closing: return case <-time.After(15 * time.Millisecond): } f.cmu.Lock() if f.turns[id].State != "running" { f.cmu.Unlock() return } f.emit("delta", "turn", id, 0, id, map[string]any{"turn_id": id, "offset": offset, "text": part}) f.cmu.Unlock() offset += len(part) } } // Glance sends Equipo's glance for the turn with id: one line on what the // Assistant is about to do, before the turn's first words. Like a delta it // is an event only, never a message and never in a snapshot. func (f *Fake) Glance(id, text string) { f.cmu.Lock() defer f.cmu.Unlock() f.emitLive("glance", "turn", id, 0, id, map[string]string{"turn_id": id, "text": text}) } // RunTurn moves the turn with id to running, as a runner taking it does. func (f *Fake) RunTurn(id string) { f.setTurn(id, "running", "") } // FailTurn ends the turn with id unanswered: failed. func (f *Fake) FailTurn(id string) { f.setTurn(id, "failed", "") } // FailTurnFor ends the turn with id unanswered for reason, such as // attachment_unavailable. func (f *Fake) FailTurnFor(id, reason string) { f.setTurn(id, "failed", reason) } // WaitTurn puts the turn with id in the waiting state: saved, with nothing // yet able to answer it. func (f *Fake) WaitTurn(id string) { f.setTurn(id, "waiting", "") } func (f *Fake) setTurn(id, state, reason string) { f.cmu.Lock() defer f.cmu.Unlock() t := f.turns[id] t.State, t.Reason, t.Revision, t.UpdatedAt = state, reason, t.Revision+1, time.Now().UTC() f.emit("turn", "turn", id, t.Revision, id, *t) } func (f *Fake) cancel(w http.ResponseWriter, r *http.Request, id string) { f.cmu.Lock() t, ok := f.turns[id] if !ok { f.cmu.Unlock() writeError(w, r, 404, "not_found") return } if t.State != "queued" && t.State != "running" && t.State != "waiting" { f.cmu.Unlock() writeError(w, r, 409, "turn_ended") return } f.cmu.Unlock() f.setTurn(id, "cancelled", "") writeJSON(w, http.StatusAccepted, map[string]any{"attempt": 1}) } func (f *Fake) answer(w http.ResponseWriter, r *http.Request, id string) { var in struct { Choice string `json:"choice"` Revision int64 `json:"revision"` } if strict(r, &in) != nil { writeError(w, r, 422, "invalid_input") return } f.cmu.Lock() var c *card for _, x := range f.cards { if x.ID == id { c = x } } if c == nil { f.cmu.Unlock() writeError(w, r, 404, "not_found") return } if c.State != "open" || c.Revision != in.Revision { code := "card_answered" if c.State == "open" { code = "card_stale" } writeJSON(w, 409, map[string]any{"code": code, "copy_key": "api." + code, "request_id": r.Header.Get("Idempotency-Key"), "card": *c}) f.cmu.Unlock() return } label, ok := "", false for _, o := range c.Options { if o.Value == in.Choice { label, ok = o.Label, true } } if !ok { f.cmu.Unlock() writeError(w, r, 422, "invalid_input") return } if c.Kind == "question" && f.runner != "" { code := f.runner f.cmu.Unlock() writeError(w, r, 409, code) return } c.State, c.Revision = "answered", c.Revision+1 if c.Kind != "question" { // As Equipo does for an outcome card: the card says how it ended, // and the answer starts no turn, so its message and turn are // empty (a zero time included). c.Result = label f.emit("card", "card", c.ID, c.Revision, "", *c) f.cmu.Unlock() writeJSON(w, 200, map[string]any{"card": *c, "message": message{}, "turn": turn{}}) return } c.Result = in.Choice f.emit("card", "card", c.ID, c.Revision, "", *c) m, t := f.ask(in.Choice) f.cmu.Unlock() writeJSON(w, 200, map[string]any{"card": *c, "message": m, "turn": t}) go f.answerTurn(t.ID, in.Choice) } // carryOn is POST cards/{id}/carry_on {revision, idempotency_key}, as // Equipo's docs/api/equipo-v1.md says: a paused job that offers it // (carry_on) starts again now, working, and the answer is 200 {"card"}. // A key that already carried this card on gets 200 with the card as it is // now, as Equipo's job_paused.go does. 409 card_stale at another // revision, not_paused when it is not paused, carry_on_unavailable when it // does not offer it, each {code, copy_key, request_id, card}; 404 for // anything but a job card. func (f *Fake) carryOn(w http.ResponseWriter, r *http.Request, id string) { var in struct { Revision int64 `json:"revision"` IdempotencyKey string `json:"idempotency_key"` } if strict(r, &in) != nil || len(in.IdempotencyKey) < 1 || len(in.IdempotencyKey) > 128 { writeError(w, r, 422, "invalid_input") return } f.cmu.Lock() defer f.cmu.Unlock() if f.carryStatus != 0 { writeError(w, r, f.carryStatus, "unavailable") return } var c *card for _, x := range f.cards { if x.ID == id && x.Kind == equipo.CardJob { c = x } } conflict := func(code string) { request := r.Header.Get("Idempotency-Key") if request == "" || len(request) > 256 { request = rand.Text() } writeJSON(w, 409, map[string]any{"code": code, "copy_key": "api." + code, "request_id": request, "card": *c}) } switch { case c == nil: writeError(w, r, 404, "not_found") case f.carried[c.ID+"\x00"+in.IdempotencyKey]: writeJSON(w, 200, map[string]any{"card": *c}) case c.Revision != in.Revision: conflict("card_stale") case c.State != equipo.JobPaused && c.State != equipo.JobStopped: conflict("not_paused") case !c.CarryOn: conflict("carry_on_unavailable") default: c.State, c.Result, c.Detail, c.CarryOn, c.Revision = equipo.JobWorking, "Carrying on", "Picking up where it left off.", false, c.Revision+1 f.emit("card", "card", c.ID, c.Revision, "", *c) f.carried[c.ID+"\x00"+in.IdempotencyKey] = true writeJSON(w, 200, map[string]any{"card": *c}) } } // pausedOK reports whether r opted in to the paused job state // (job_states=paused, a comma-separated list). func pausedOK(r *http.Request) bool { for _, v := range r.URL.Query()["job_states"] { for _, s := range strings.Split(v, ",") { if s == equipo.JobPaused { return true } } } return false } // asSeen is c as a client sees it: without the paused opt-in, a paused // job comes as working with the same result and detail and no carry_on. func asSeen(c card, paused bool) card { if !paused && c.Kind == equipo.CardJob && c.State == equipo.JobPaused { c.State, c.CarryOn = equipo.JobWorking, false } return c } // timeZone is PUT assistant/time-zone {time_zone, only_if_unset}, as // Equipo's zone.go (31cdb35d): 200 {time_zone: the zone in effect} for a // zone Go knows (an IANA name), else 422 invalid_input. With only_if_unset // a zone the person's own browser or device set stays; one Base set // before is replaced. func (f *Fake) timeZone(w http.ResponseWriter, r *http.Request) { var in struct { TimeZone string `json:"time_zone"` OnlyIfUnset bool `json:"only_if_unset"` } f.cmu.Lock() status, code, hold := f.zoneStatus, f.zoneCode, f.zoneHold f.cmu.Unlock() if hold != nil { select { case <-hold: case <-r.Context().Done(): return case <-f.closing: return } } if status != 0 { writeError(w, r, status, code) return } if strict(r, &in) != nil || in.TimeZone == "" || in.TimeZone == "Local" { writeError(w, r, 422, "invalid_input") return } if _, err := time.LoadLocation(in.TimeZone); err != nil { writeError(w, r, 422, "invalid_input") return } f.cmu.Lock() if !in.OnlyIfUnset || !f.zoneOwn { f.zone, f.zoneOwn = in.TimeZone, false } zone := f.zone f.cmu.Unlock() writeJSON(w, 200, map[string]string{"time_zone": zone}) } // FailCarryOn makes every carry_on answer status (a 5xx; 0 stops). func (f *Fake) FailCarryOn(status int) { f.cmu.Lock(); f.carryStatus = status; f.cmu.Unlock() } // SetTimeZone sets the person's zone, as one of their own devices does. func (f *Fake) SetTimeZone(zone string) { f.cmu.Lock(); f.zone, f.zoneOwn = zone, true; f.cmu.Unlock() } // RefuseTimeZone makes every PUT time-zone answer status with code (0 // accepts them again). func (f *Fake) RefuseTimeZone(status int, code string) { f.cmu.Lock() f.zoneStatus, f.zoneCode = status, code f.cmu.Unlock() } // HoldTimeZone holds every PUT time-zone (until the request gives up) // until release is called; calls after that answer at once. func (f *Fake) HoldTimeZone() (release func()) { hold := make(chan struct{}) f.cmu.Lock() f.zoneHold = hold f.cmu.Unlock() return sync.OnceFunc(func() { f.cmu.Lock() if f.zoneHold == hold { f.zoneHold = nil } f.cmu.Unlock() close(hold) }) } // TimeZone is the zone the person set (PUT time-zone), "" before any. func (f *Fake) TimeZone() string { f.cmu.Lock() defer f.cmu.Unlock() return f.zone } // stream is GET events: Server-Sent Events after ?after= (or // Last-Event-ID), as Equipo writes them: then, live events (cursor 0, no // id line) that come while the stream is open. func (f *Fake) stream(w http.ResponseWriter, r *http.Request) { raw := r.URL.Query().Get("after") if raw == "" { raw = r.Header.Get("Last-Event-ID") } f.cmu.Lock() after, next := f.cursor, 0 live := len(f.events) f.cmu.Unlock() if raw != "" { n, err := strconv.ParseInt(raw, 10, 64) if err != nil || n < 0 { writeError(w, r, 422, "invalid_input") return } after = n } paused, draws := pausedOK(r), f.drawsLookups(r) rc := http.NewResponseController(w) w.Header().Set("Content-Type", "text/event-stream") w.WriteHeader(200) if _, err := io.WriteString(w, "retry: 2000\n: ok\n\n"); err != nil || rc.Flush() != nil { return } for { f.cmu.Lock() var batch []event for i, e := range f.events[next:] { if e.Cursor > after || (e.Cursor == 0 && next+i >= live) { batch = append(batch, e) } } next = len(f.events) wake := f.wake f.cmu.Unlock() for _, e := range batch { if c, ok := e.Data.(card); ok { e.Data = asSeen(c, paused) } if m, ok := e.Data.(message); ok { e.Data = asRead(m, draws) } raw, _ := json.Marshal(e) id := "" if e.Cursor != 0 { id = fmt.Sprintf("id: %d\n", e.Cursor) after = e.Cursor } if _, err := fmt.Fprintf(w, "%sevent: %s\ndata: %s\n\n", id, e.Type, raw); err != nil { return } } if rc.Flush() != nil { return } select { case <-r.Context().Done(): return case <-f.closing: return case <-wake: } } } // OficinaConsent sets the consent URL connect answers with; FinishWith the // status finish answers with. FailOficina makes both answer status with code // (0 stops). func (f *Fake) OficinaConsent(url string) { f.cmu.Lock(); f.consent = url; f.cmu.Unlock() } func (f *Fake) FinishWith(status string) { f.cmu.Lock(); f.finish = status; f.cmu.Unlock() } func (f *Fake) FailOficina(status int, code string) { f.cmu.Lock() f.oficinaStatus, f.oficinaCode = status, code f.cmu.Unlock() } // OtherPersonsState is a state finish refuses with 403, as Equipo does for // a state that belongs to someone else. const OtherPersonsState = "someone-else" func (f *Fake) oficinaConnect(w http.ResponseWriter, r *http.Request) { var in struct { ReturnTo string `json:"return_to"` } f.cmu.Lock() status, code, consent := f.oficinaStatus, f.oficinaCode, f.consent f.cmu.Unlock() if strict(r, &in) != nil || in.ReturnTo == "" { writeError(w, r, 422, "invalid_input") return } if status != 0 { writeError(w, r, status, code) return } if consent == "" { consent = "https://oficina.example/consent?x=1" } writeJSON(w, 200, map[string]string{"url": consent}) } func (f *Fake) oficinaFinish(w http.ResponseWriter, r *http.Request) { var in struct { State string `json:"state"` Code string `json:"code"` } f.cmu.Lock() status, code, finish := f.oficinaStatus, f.oficinaCode, f.finish f.cmu.Unlock() if strict(r, &in) != nil || in.State == "" || in.Code == "" { writeError(w, r, 422, "invalid_input") return } switch { case in.State == OtherPersonsState: writeError(w, r, 403, "forbidden") case status != 0: writeError(w, r, status, code) default: if finish == "" { finish = "connected" } if finish == "connected" { f.settleConnect() } writeJSON(w, 200, map[string]string{"status": finish}) } } // settleConnect resolves the open connect cards, as Equipo does once the // person has connected. func (f *Fake) settleConnect() { f.cmu.Lock() defer f.cmu.Unlock() for _, c := range f.cards { if c.Kind == equipo.CardConnect && c.State == "open" { c.State, c.Revision = "resolved", c.Revision+1 f.emit("card", "card", c.ID, c.Revision, "", *c) } } }