oficina / base Public

Write down and pin Ask's JSON contract for the native app

docs/api/base-native-v1.md documents what the native app may rely on:
the native exchange and session, /signout, the 401 refusal, /api/v1/me
and /api/v1/home, and Ask's routes as ask.js already uses them
(/ask/state, /ask/events and its frames, /ask/messages, cancel and
answer), with every status and body they answer. Nothing in Ask changed.

ask_native_contract_test.go makes each call as the native app will, with
the native session cookie, Origin and Accept: application/json, against
equipotest's fake, and checks the documented keys and bodies. The event
stream is read in-process through a small streaming writer. Worth
knowing for the client: Ask's writes are form-encoded, and Equipo
refusing the key is 401 {"state":"reconnect"}, which is not Base's
session ending ({"code":"unauthenticated"}).

make ci: 16 packages ran, 0 failed; test step 16.2s of 60s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 890c309f547ef85298b783bd6358b88350cb944d parent df22a81
2 files changed, +621 −0
  • docs/api/base-native-v1.md +201 −0
  • internal/webtest/ask_native_contract_test.go +420 −0
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
new file mode 100644
index 0000000..0716ded
--- /dev/null
+++ b/docs/api/base-native-v1.md
@@ -0,0 +1,201 @@
+# Base's API for its native app, v1
+
+What Base's Mac and iPhone app may rely on. Everything here is pinned by
+tests in `internal/webtest` (`native_test.go`, `api_test.go`,
+`ask_native_contract_test.go`, `ask_oficina_native_test.go`). The Ask
+routes are the same ones the web's `ask.js` uses, so a change that breaks
+this document breaks the web too.
+
+## Signing in
+
+- **`POST /native/oficina-id`** is connect's native exchange
+ (`connect.NativeExchange`; Home spec 2026-11-14-oficina-id-native.md §7).
+ The kit sends `{assertion, verifier}` as JSON, with no `Origin`, no
+ `Sec-Fetch-Site` and no cookie.
+ - `200 {"state":"ok","name":"__Host-rastrillo_session","value":…,"expires_at":<unix>}`:
+ the session, seven days from now, absolute.
+ - `403 {"state":"unknown"}`: no member here is linked to this Oficina ID.
+ Base admits only people who have signed in to Base on the web with
+ Oficina ID once (slice 1).
+ - `400 invalid`, `401 failed` (get a fresh assertion), `503 unavailable`,
+ as connect documents. Base never answers `409 choose`.
+- **The session** is the cookie `name=value`. Every other request sends it
+ with `Origin: <Base's origin>`; a POST without that `Origin` is refused
+ (403, Base's CSRF check).
+- **`POST /signout`** ends the session it carries, and nothing else:
+ `204` to a JSON request (`Content-Type` or `Accept` of
+ `application/json`), `303 /signed-out` to a form.
+- **Refusals.** Anything under `/api/`, and any request whose `Accept`
+ names `application/json` or `text/event-stream`, hears
+ `401 {"code":"unauthenticated"}` (no-store, never a redirect) when it has
+ no session, or a session that names nobody who is a member now: unlinked,
+ removed, or a native session more than seven days old. Mint a new session
+ and try once more.
+
+## Reads
+
+### `GET /api/v1/me`
+
+```json
+{
+ "member": {"id": "…", "name": "Ana Ruiz", "email": "ana@acme.test", "initials": "AR", "owner": false},
+ "base": {"name": "Acme", "slug": "acme", "origin": "https://base.acme.example", "timezone": "Europe/Dublin"},
+ "appearance": "system",
+ "equipo_origin": "https://equipo.acme.example"
+}
+```
+
+- `member.name` is the member's name, or their address's local part,
+ capitalised. `member.id` is Base's member id, never the address.
+- `base.timezone` is an IANA name.
+- `appearance` is `system`, `light` or `dark`. Change it with the web's
+ `POST /settings/appearance`, form field `theme` (`system`, `light` or
+ `dark`), which answers `303 /settings`.
+- `equipo_origin` is `null` when Ask Base is off.
+
+### `GET /api/v1/home`
+
+```json
+{
+ "greeting": "Good morning, Ana.",
+ "lede": "One step until Acme's Base is ready.",
+ "steps": [{"label": "Signed in", "done": true}, {"label": "Invite your team", "done": false}, {"label": "Install your first app", "done": true}],
+ "apps": [
+ {"id": "calls", "kind": "oficina", "name": "Calls", "url": "https://calls.oficina.works/", "icon_url": "/static/oficina/calls.<hash>.svg", "bundle_id": "works.oficina.calls", "scheme": "oficina-calls"},
+ {"id": "docs", "kind": "oficina", "name": "Docs", "url": "https://docs.oficina.works/", "icon_url": "/static/oficina/docs.<hash>.svg", "bundle_id": "works.oficina.docs"},
+ {"id": "scratchpad", "kind": "installed", "name": "Scratchpad", "url": "https://acme-scratchpad.example/", "tint": "rose", "icon_svg": "<svg …>"},
+ {"id": "store", "kind": "own", "name": "Store", "url": "https://base.acme.example/store", "tint": "teal", "icon_svg": "<svg …>"}
+ ]
+}
+```
+
+- `apps` are in Home's order: the team's Oficina apps, the installed apps,
+ then Base's own pages (`store`, `people`, `settings`).
+- An Oficina app has `icon_url`, a path on Base's origin (content-hashed,
+ immutable), its `bundle_id` (`works.oficina.<id>`), and a `scheme` only
+ where its native app opens by one today (Calls, Equipo). The others open
+ on the web until their apps take the kit's `…://open`.
+- An installed app or own page has `tint` (a catalogue tint name: `amber`,
+ `teal`, `violet`, `rose`, `mist`, …) and `icon_svg`, line art drawn in
+ `currentColor`. Own pages' `url`s are Base's web pages.
+- Optional keys are absent, never `null` or `""`.
+
+## Ask Base
+
+The web's own routes. Writes are **form-encoded**
+(`application/x-www-form-urlencoded`), not JSON, and must send
+`Accept: application/json` to get JSON back (without it they redirect, as
+for a form). Every answer is `no-store`.
+
+### The states
+
+`state` is one of:
+
+| state | meaning |
+|---|---|
+| `connect` | Ask isn't connected for this person (or a code ran out). |
+| `pending` | A sign-in code waits for approval in Equipo (web code flow). |
+| `ready` | Connected; the conversation shows. |
+| `norunner`, `oldrunner` | Connected, but the person has no runner that can answer (none, or too old). The conversation shows, with a note. |
+| `reconnect` | Equipo refused the key, or it expired. |
+| `unavailable` | Equipo didn't answer. |
+
+### `GET /ask/state`
+
+```json
+{"state": "ready", "messages": [Message…], "jobs": [Job…], "cards": [Card…], "turn": Turn|null,
+ "status": "Thinking…", "cursor": 42}
+```
+
+- `messages`, `jobs` and `cards` are never `null`. Outside `ready`,
+ `norunner` and `oldrunner` they are empty and `cursor` is `0`.
+- `turn` is the newest turn the person sees running (never a quiet
+ `team_update` one), or `null`. `status` is the line under the
+ conversation while it runs: `"Thinking…"`, `"Ask Base can't answer right
+ now. It will as soon as it can."` (turn `waiting`), or `""`.
+- `cursor` is where `/ask/events` starts.
+
+**Message** `{"id", "role": "person"|"assistant", "text", "turn_id", "created_at"}`.
+An assistant's `text` may carry the little Markdown `ask.js` draws (lists,
+links to http(s) only, bold and italics).
+
+**Turn** `{"id", "kind", "state": "queued"|"running"|"waiting"|"replied"|"failed"|"cancelled", "reason"}`.
+
+**Card** `{"id", "revision", "kind", "state", "question", "options": [{"value","label"}], "links": [{"label","url","rel"?}], "result", "job"?, "detail"?, "started_at"?, "turn_id"?}`.
+- `kind` is `question`, `confirm`, `outcome`, `connect` or `job`; a card is
+ `open` while it waits for an answer. Every link is absolute http(s).
+- `rel` is `equipo` (a job's page in Equipo) or `oficina_connect` (Base's
+ own `/ask/oficina/connect`, a browser flow).
+- A job card has no options; its `state` is `working`, `asking`, `ready`,
+ `done` or `stopped`; `result` is its short status, `detail` one sentence
+ more and `started_at` when it began.
+- `job` names the job card a card belongs to; `turn_id`, on a connect card
+ from the stream, the turn that raised it.
+
+**Job** is a job Card plus `"cards": [Card…]`, the cards that belong to it,
+open and ended.
+
+### `GET /ask/events?after=<cursor>`
+
+Server-Sent Events, `text/event-stream`. On a reconnect, `Last-Event-ID`
+wins over `after`. The stream opens with `retry: 3000`, then:
+
+```
+id: 43
+event: message
+data: {"type":"message","data":Message}
+```
+
+| event | data |
+|---|---|
+| `message` | Message |
+| `turn` | Turn |
+| `card` | Card (a job card included: `kind` `job`) |
+| `delta` | `{"turn_id","offset","text"}`: a few of the reply's words; `offset` counts UTF-8 bytes |
+| `activity` | `{"turn_id","label"}`: what the Assistant is doing |
+| `glance` | `{"turn_id","text"}`: one line before the first words. **No `id` line**: it doesn't move the cursor. |
+| `state` | `{"state"}`: the stream can't start (not `ready`); it ends after this one event. |
+
+- `: ping` comments keep it alive. A stream lasts at most ten minutes;
+ reconnect with the last id.
+- Equipo not answering is `502`, and a bad `after` `400` (plain text):
+ reload `/ask/state` and start again from its cursor.
+
+### `POST /ask/messages`
+
+Form: `text` (1 to 16 KiB after trimming) and `key`, a fresh idempotency key
+per message (at most 128 bytes, not starting `reply:` or `card:`). A resend
+after a network error reuses the key: Equipo keeps one message per key.
+
+- `200 {"message": Message, "turn": Turn}`.
+- `422 {"state":"ready"}`: empty or too long.
+
+### `POST /ask/turns/{id}/cancel`
+
+Form: `key`. `200 {"state":"ready"}`; `409 {"state":"ready"}` when the turn
+has already ended.
+
+### `POST /ask/cards/{id}/answer`
+
+Form: `choice` (an option's `value`), `revision` (the card's, as seen) and
+`key`.
+
+- `200 {"card": Card, "message": Message|null, "turn": Turn|null}`. An
+ outcome card's answer starts no turn: both are `null`.
+- `409 {"state":"ready"}`: the card moved on (answered, or a newer
+ revision). Reload `/ask/state` to redraw it.
+
+### Every write's other answers
+
+| status | body | meaning |
+|---|---|---|
+| `409` | `{"state":"connect"\|"pending"\|"reconnect"\|"unavailable"}` | Not connected: nothing was sent. |
+| `401` | `{"state":"reconnect"}` | **Equipo** refused the key. This is not Base's session ending (that's `{"code":"unauthenticated"}`): don't sign in again; connect Ask again. |
+| `409` | `{"state":"norunner"\|"oldrunner"}` | No runner can answer; nothing was sent. |
+| `502` | `{"state":"unavailable"}` | Equipo didn't answer. Try again with the same key. |
+| `400` | plain text | The form couldn't be read. |
+
+### `POST /ask/disconnect`
+
+Ends the person's Ask connection, revoking the key in Equipo, whichever
+way it was made. It answers `303 /settings`.
diff --git a/internal/webtest/ask_native_contract_test.go b/internal/webtest/ask_native_contract_test.go
new file mode 100644
index 0000000..ca7e517
--- /dev/null
+++ b/internal/webtest/ask_native_contract_test.go
@@ -0,0 +1,420 @@
+package webtest
+
+import (
+ "bufio"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+)
+
+// Ask's JSON contract (docs/api/base-native-v1.md), as the native app uses
+// it: every call carries the native session cookie, Origin and
+// Accept: application/json, and no Sec-Fetch-Site. These are the routes and
+// shapes ask.js relies on; a change to one breaks a test here.
+
+// newNativeAskApp is Base with Oficina ID and Ask on, the owner linked
+// (and signed in locally in the returned browser), and the owner's native
+// app signed in.
+func newNativeAskApp(t *testing.T) (web, app *testApp, f *equipotest.Fake) {
+ t.Helper()
+ f = equipotest.New(t)
+ web = newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = f.URL })
+ web.link(ownerAddress, "subject-owner")
+ return web, web.nativeSignIn("subject-owner"), f
+}
+
+// nativeForm is a form POST as the native app makes one to Ask.
+func (a *testApp) nativeForm(target string, form url.Values) Resp {
+ a.t.Helper()
+ req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", homeOrigin)
+ req.Header.Set("Accept", "application/json")
+ return a.do(req)
+}
+
+// keysOf is the sorted keys of a JSON object.
+func keysOf(t *testing.T, raw string) []string {
+ t.Helper()
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(raw), &m); err != nil {
+ t.Fatalf("not an object: %q: %v", raw, err)
+ }
+ var out []string
+ for k := range m {
+ out = append(out, k)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func wantKeys(t *testing.T, where, raw string, want ...string) {
+ t.Helper()
+ sort.Strings(want)
+ if got := keysOf(t, raw); !reflect.DeepEqual(got, want) {
+ t.Errorf("%s keys %v, want %v\n%s", where, got, want, raw)
+ }
+}
+
+func wantBody(t *testing.T, where string, r Resp, code int, body string) {
+ t.Helper()
+ if r.Code != code || strings.TrimSpace(r.Body) != body {
+ t.Errorf("%s: %d %s, want %d %s", where, r.Code, strings.TrimSpace(r.Body), code, body)
+ }
+}
+
+// askState is /ask/state's answer, its parts kept raw for their shapes.
+type askState struct {
+ State string `json:"state"`
+ Messages []json.RawMessage `json:"messages"`
+ Jobs []json.RawMessage `json:"jobs"`
+ Cards []json.RawMessage `json:"cards"`
+ Turn json.RawMessage `json:"turn"`
+ Status string `json:"status"`
+ Cursor int64 `json:"cursor"`
+}
+
+func (a *testApp) askState() (askState, Resp) {
+ a.t.Helper()
+ r := a.nativeGet("/ask/state")
+ if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Content-Type") != "application/json" {
+ a.t.Fatalf("/ask/state: %d %q %q %s", r.Code, r.Header.Get("Cache-Control"), r.Header.Get("Content-Type"), r.Body)
+ }
+ var s askState
+ if err := json.Unmarshal([]byte(r.Body), &s); err != nil {
+ a.t.Fatal(err)
+ }
+ return s, r
+}
+
+var stateKeys = []string{"state", "messages", "jobs", "cards", "turn", "status", "cursor"}
+
+func TestAskContractBeforeConnecting(t *testing.T) {
+ _, app, _ := newNativeAskApp(t)
+ s, r := app.askState()
+ wantKeys(t, "state", r.Body, stateKeys...)
+ if strings.TrimSpace(r.Body) != `{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0}` || s.State != "connect" {
+ t.Errorf("not connected: %s", r.Body)
+ }
+ wantBody(t, "send", app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"k1"}}), 409, `{"state":"connect"}`)
+ wantBody(t, "cancel", app.nativeForm("/ask/turns/t_1/cancel", url.Values{"key": {"k2"}}), 409, `{"state":"connect"}`)
+ wantBody(t, "answer", app.nativeForm("/ask/cards/c_1/answer", url.Values{"choice": {"x"}, "revision": {"1"}, "key": {"k3"}}), 409, `{"state":"connect"}`)
+ frames := app.events(t, "0", func([]sseFrame) bool { return false })
+ if len(frames) != 1 || frames[0].Event != "state" || frames[0].Data != `{"state":"connect"}` || frames[0].ID != "" {
+ t.Errorf("events while not connected: %+v", frames)
+ }
+}
+
+func TestAskContractConversation(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ s, r := app.askState()
+ wantKeys(t, "state", r.Body, stateKeys...)
+ if s.State != "ready" || s.Messages == nil || s.Jobs == nil || s.Cards == nil || string(s.Turn) != "null" || s.Status != "" {
+ t.Fatalf("connected state: %s", r.Body)
+ }
+
+ // Send: the message and its turn; the same key again is the same message.
+ form := url.Values{"text": {"What can I do?"}, "key": {"native-1"}}
+ sent := app.nativeForm("/ask/messages", form)
+ if sent.Code != 200 || sent.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("send: %d %s", sent.Code, sent.Body)
+ }
+ wantKeys(t, "send", sent.Body, "message", "turn")
+ var out struct {
+ Message, Turn json.RawMessage
+ }
+ _ = json.Unmarshal([]byte(sent.Body), &out)
+ wantKeys(t, "message", string(out.Message), "id", "role", "text", "turn_id", "created_at")
+ wantKeys(t, "turn", string(out.Turn), "id", "kind", "state", "reason")
+ var m struct{ ID, Role, Text string }
+ _ = json.Unmarshal(out.Message, &m)
+ if m.Role != "person" || m.Text != "What can I do?" {
+ t.Errorf("message: %s", out.Message)
+ }
+ again := app.nativeForm("/ask/messages", form)
+ var m2 struct{ Message struct{ ID string } }
+ if again.Code != 200 || json.Unmarshal([]byte(again.Body), &m2) != nil || m2.Message.ID != m.ID {
+ t.Errorf("resend with the same key: %d %s", again.Code, again.Body)
+ }
+ wantBody(t, "empty", app.nativeForm("/ask/messages", url.Values{"text": {" "}, "key": {"native-2"}}), 422, `{"state":"ready"}`)
+
+ // The reply is in the next read.
+ var after askState
+ for i := 0; i < 200; i++ {
+ if after, _ = app.askState(); len(after.Messages) == 2 && string(after.Turn) == "null" {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if len(after.Messages) != 2 || after.Cursor <= s.Cursor {
+ t.Fatalf("after the reply: %d messages, cursor %d (was %d)", len(after.Messages), after.Cursor, s.Cursor)
+ }
+ wantKeys(t, "state message", string(after.Messages[1]), "id", "role", "text", "turn_id", "created_at")
+}
+
+func TestAskContractEvents(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ s, _ := app.askState()
+ f.Hold = true
+ frames := app.events(t, strconv.FormatInt(s.Cursor, 10), func(got []sseFrame) bool {
+ if len(got) == 1 {
+ // The stream is open: send, glance, then answer.
+ go func() {
+ r := app.nativeForm("/ask/messages", url.Values{"text": {"Make a form"}, "key": {"ev-1"}})
+ var out struct{ Turn struct{ ID string } }
+ _ = json.Unmarshal([]byte(r.Body), &out)
+ for f.Turn(out.Turn.ID) != "running" {
+ time.Sleep(5 * time.Millisecond)
+ }
+ f.Glance(out.Turn.ID, "Looking at your **forms**")
+ time.Sleep(20 * time.Millisecond)
+ f.Answer(out.Turn.ID, "Here it is.", true)
+ }()
+ }
+ last := got[len(got)-1]
+ return last.Event == "turn" && strings.Contains(last.Data, `"state":"replied"`)
+ })
+ if frames[0].Retry != "3000" {
+ t.Errorf("first frame %+v, want retry: 3000", frames[0])
+ }
+ seen := map[string]bool{}
+ for _, fr := range frames[1:] {
+ if fr.Comment {
+ continue
+ }
+ seen[fr.Event] = true
+ var env struct {
+ Type string `json:"type"`
+ Data json.RawMessage `json:"data"`
+ }
+ if err := json.Unmarshal([]byte(fr.Data), &env); err != nil || env.Type != fr.Event {
+ t.Fatalf("frame %+v: %v", fr, err)
+ }
+ wantKeys(t, fr.Event+" frame", fr.Data, "type", "data")
+ switch fr.Event {
+ case "glance":
+ if fr.ID != "" {
+ t.Errorf("a glance carried an id: %+v", fr)
+ }
+ wantKeys(t, "glance event", string(env.Data), "turn_id", "text")
+ if !strings.Contains(string(env.Data), `"text":"Looking at your forms"`) {
+ t.Errorf("glance: %s", env.Data)
+ }
+ default:
+ if _, err := strconv.ParseUint(fr.ID, 10, 63); err != nil {
+ t.Errorf("%s frame without a numeric id: %+v", fr.Event, fr)
+ }
+ }
+ switch fr.Event {
+ case "message":
+ wantKeys(t, "message event", string(env.Data), "id", "role", "text", "turn_id", "created_at")
+ case "turn":
+ wantKeys(t, "turn event", string(env.Data), "id", "kind", "state", "reason")
+ case "delta":
+ wantKeys(t, "delta event", string(env.Data), "turn_id", "offset", "text")
+ }
+ }
+ for _, want := range []string{"message", "turn", "delta", "glance"} {
+ if !seen[want] {
+ t.Errorf("no %s event in %+v", want, frames)
+ }
+ }
+}
+
+func TestAskContractCancel(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ f.Hold = true
+ r := app.nativeForm("/ask/messages", url.Values{"text": {"Something long"}, "key": {"c-1"}})
+ var out struct{ Turn struct{ ID string } }
+ if json.Unmarshal([]byte(r.Body), &out) != nil || out.Turn.ID == "" {
+ t.Fatalf("send: %d %s", r.Code, r.Body)
+ }
+ for f.Turn(out.Turn.ID) != "running" {
+ time.Sleep(5 * time.Millisecond)
+ }
+ s, _ := app.askState()
+ if !strings.Contains(string(s.Turn), out.Turn.ID) || s.Status != "Thinking…" {
+ t.Errorf("running: turn %s status %q", s.Turn, s.Status)
+ }
+ wantBody(t, "cancel", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-2"}}), 200, `{"state":"ready"}`)
+ wantBody(t, "cancel again", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-3"}}), 409, `{"state":"ready"}`)
+}
+
+func TestAskContractCards(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ job := f.AskJob("Christmas order form")
+ f.AskKindFor("confirm", job, "Go ahead?", goOptions, nil)
+ q := f.AskQuestion("Which colour?", "red", "blue")
+ s, r := app.askState()
+ if len(s.Jobs) != 1 || len(s.Cards) != 1 {
+ t.Fatalf("jobs and cards: %s", r.Body)
+ }
+ wantKeys(t, "card", string(s.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result")
+ wantKeys(t, "job", string(s.Jobs[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "detail", "started_at", "cards")
+ var j struct {
+ Kind, State, Question string
+ Cards []json.RawMessage
+ }
+ if json.Unmarshal(s.Jobs[0], &j) != nil || j.Kind != "job" || j.Question != "Christmas order form" || len(j.Cards) != 1 {
+ t.Fatalf("job: %s", s.Jobs[0])
+ }
+ wantKeys(t, "job's card", string(j.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "job")
+
+ // Answer at the revision seen: the card, the message and turn it started.
+ a := app.nativeForm("/ask/cards/"+q+"/answer", url.Values{"choice": {"red"}, "revision": {"1"}, "key": {"a-1"}})
+ if a.Code != 200 {
+ t.Fatalf("answer: %d %s", a.Code, a.Body)
+ }
+ wantKeys(t, "answer", a.Body, "card", "message", "turn")
+ var ans struct {
+ Card struct{ ID, State, Result string }
+ Message *struct{ Text string }
+ Turn *struct{ ID string }
+ }
+ 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 {
+ t.Errorf("answer: %s", a.Body)
+ }
+ // An outcome card's answer starts nothing.
+ o := f.AskOutcome("Publish it?", goOptions, nil)
+ wantBody(t, "outcome", app.nativeForm("/ask/cards/"+o+"/answer", url.Values{"choice": {"go"}, "revision": {"1"}, "key": {"a-2"}}), 200,
+ `{"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}`)
+ // Stale: the card moved on.
+ q2 := f.AskQuestion("Which size?", "S", "M")
+ f.SetCard(q2, "open", "")
+ wantBody(t, "stale", app.nativeForm("/ask/cards/"+q2+"/answer", url.Values{"choice": {"S"}, "revision": {"1"}, "key": {"a-3"}}), 409, `{"state":"ready"}`)
+}
+
+// Equipo refusing the key is Ask's 401 {"state":"reconnect"}, not Base's
+// own {"code":"unauthenticated"}: the session is fine.
+func TestAskContractLostKey(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ f.RevokeAll()
+ wantBody(t, "send", app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"l-1"}}), 401, `{"state":"reconnect"}`)
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Errorf("state after a refused key: %s", s.State)
+ }
+ if r := app.nativeGet("/api/v1/me"); r.Code != 200 {
+ t.Errorf("the session ended with the key: %d", r.Code)
+ }
+}
+
+// sseFrame is one frame of an event stream, as the native client parses it.
+type sseFrame struct {
+ ID, Event, Data, Retry string
+ Comment bool
+}
+
+// events opens /ask/events?after= as the native app does and reads frames
+// until done says so or the stream ends. The first frame is the retry.
+func (a *testApp) events(t *testing.T, after string, done func([]sseFrame) bool) []sseFrame {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+after, nil)
+ req.Header.Set("Origin", homeOrigin)
+ req.Header.Set("Accept", "text/event-stream")
+ for _, c := range a.client.Jar.Cookies(req.URL) {
+ req.AddCookie(c)
+ }
+ res := serveStreaming(a.client.Transport.(handlerTransport).h, req)
+ defer res.Body.Close()
+ if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" || res.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("events: %d %v", res.StatusCode, res.Header)
+ }
+ var frames []sseFrame
+ var cur sseFrame
+ sc := bufio.NewScanner(res.Body)
+ for sc.Scan() {
+ line := sc.Text()
+ switch {
+ case line == "":
+ frames = append(frames, cur)
+ cur = sseFrame{}
+ if done(frames) {
+ return frames
+ }
+ case strings.HasPrefix(line, ":"):
+ cur.Comment = true
+ default:
+ name, value, _ := strings.Cut(line, ": ")
+ switch name {
+ case "id":
+ cur.ID = value
+ case "event":
+ cur.Event = value
+ case "data":
+ cur.Data = value
+ case "retry":
+ cur.Retry = value
+ }
+ }
+ }
+ if ctx.Err() != nil {
+ t.Fatalf("the stream timed out after %+v", frames)
+ }
+ // Drop the retry frame for a stream that ends at once (a state event).
+ if len(frames) > 0 && frames[0].Retry != "" && frames[0].Event == "" {
+ return frames[1:]
+ }
+ return frames
+}
+
+// serveStreaming serves req with h in the background and answers as soon
+// as the headers are written, with a body that streams what h writes. The
+// in-process transport waits for the whole response, which a stream never
+// ends.
+func serveStreaming(h http.Handler, req *http.Request) *http.Response {
+ in := req.Clone(req.Context())
+ in.RequestURI, in.Host, in.RemoteAddr, in.TLS = req.URL.RequestURI(), req.URL.Host, "192.0.2.10:4321", &tls.ConnectionState{}
+ pr, pw := io.Pipe()
+ w := &pipeWriter{header: http.Header{}, pw: pw, ready: make(chan struct{})}
+ go func() {
+ h.ServeHTTP(w, in)
+ w.WriteHeader(http.StatusOK)
+ pw.Close()
+ }()
+ <-w.ready
+ return &http.Response{StatusCode: w.status, Header: w.sent, Body: pr, Request: req}
+}
+
+type pipeWriter struct {
+ header, sent http.Header
+ pw *io.PipeWriter
+ status int
+ once sync.Once
+ ready chan struct{}
+}
+
+func (p *pipeWriter) Header() http.Header { return p.header }
+
+func (p *pipeWriter) WriteHeader(code int) {
+ p.once.Do(func() {
+ p.status, p.sent = code, p.header.Clone()
+ close(p.ready)
+ })
+}
+
+func (p *pipeWriter) Write(b []byte) (int, error) {
+ p.WriteHeader(http.StatusOK)
+ return p.pw.Write(b)
+}
+
+func (p *pipeWriter) Flush() {}