Ask: record each app's capabilities; send Base-Capabilities per member
Native /ask/* requests say what the app draws in Base-Client-Capabilities; Base keeps the newest value per app session (ask_clients, migration 0013) and sends Base-Capabilities: lookup_answers on every Equipo call for a member only while every native client seen in the last 30 days said so. Web sessions are not recorded. A failed record withholds the capability.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+433
−9
docs/api/base-native-v1.md+12 −0internal/equipo/abilities.go+40 −0internal/equipo/chat.go+1 −0internal/equipo/equipo.go+1 −0internal/equipo/files.go+1 −0internal/store/askclients.go+44 −0internal/store/askclients_test.go+47 −0internal/store/migrations/0013_ask_clients.sql+6 −0internal/web/app.go+3 −0internal/web/ask_caps.go+106 −0internal/web/ask_connect.go+4 −3internal/web/ask_internal_test.go+6 −6internal/webtest/ask_caps_test.go+148 −0internal/webtest/ask_native_contract_test.go+1 −0internal/webtest/harness_test.go+13 −0
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md| index ddc1135..279c03a 100644 |
| --- a/docs/api/base-native-v1.md |
| +++ b/docs/api/base-native-v1.md |
| @@ -92,6 +92,18 @@ The web's own routes. Writes are **form-encoded** |
| `Accept: application/json` to get JSON back (without it they redirect, as |
| for a form). Every answer is `no-store`. |
| +### What the app can draw |
| + |
| +Every `/ask/*` request may send `Base-Client-Capabilities`, a |
| +comma-separated list of what this build of the app draws. Base keeps the |
| +newest list per app session, and tells the Assistant a feature is drawn |
| +only while every app the member used in the last 30 days last said so. |
| +An app that doesn't send a value keeps what it gets today. |
| + |
| +| value | what the app draws | |
| +|---|---| |
| +| `lookup_answers` | A message's `lookups` (below) | |
| + |
| ### The states |
| `state` is one of: |
diff --git a/internal/equipo/abilities.go b/internal/equipo/abilities.go| new file mode 100644 |
| index 0000000..0ec51ad |
| --- /dev/null |
| +++ b/internal/equipo/abilities.go |
| @@ -0,0 +1,40 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strings" |
| +) |
| + |
| +// The values of Base-Capabilities: what Base, and every client the |
| +// member uses, can draw. CapLookupAnswers: a reply's lookup answers and |
| +// their sources (Message.Lookups). |
| +const CapLookupAnswers = "lookup_answers" |
| + |
| +// KnownCapabilities are the values Base may send, in order. A value is |
| +// sent for a member only while each of their clients can draw it. |
| +var KnownCapabilities = []string{CapLookupAnswers} |
| + |
| +// CapabilitiesHeader is the header that carries them on every call. |
| +const CapabilitiesHeader = "Base-Capabilities" |
| + |
| +type capsKey struct{} |
| + |
| +// WithCapabilities is ctx with caps to send as Base-Capabilities on every |
| +// call made with it (none: the header is left out). |
| +func WithCapabilities(ctx context.Context, caps []string) context.Context { |
| + return context.WithValue(ctx, capsKey{}, append([]string(nil), caps...)) |
| +} |
| + |
| +// CapabilitiesOf are the capabilities ctx carries. |
| +func CapabilitiesOf(ctx context.Context) []string { |
| + caps, _ := ctx.Value(capsKey{}).([]string) |
| + return caps |
| +} |
| + |
| +// setCapabilities puts ctx's capabilities on req. |
| +func setCapabilities(ctx context.Context, req *http.Request) { |
| + if caps := CapabilitiesOf(ctx); len(caps) > 0 { |
| + req.Header.Set(CapabilitiesHeader, strings.Join(caps, ",")) |
| + } |
| +} |
diff --git a/internal/equipo/chat.go b/internal/equipo/chat.go| index d18d676..f8e4aaa 100644 |
| --- a/internal/equipo/chat.go |
| +++ b/internal/equipo/chat.go |
| @@ -368,6 +368,7 @@ func (c *Client) Events(ctx context.Context, token, after string) (*http.Respons |
| } |
| req.Header.Set("Accept", "text/event-stream") |
| req.Header.Set("Authorization", "Bearer "+token) |
| + setCapabilities(ctx, req) |
| late := time.AfterFunc(c.StreamHeaderTimeout, cancel) |
| res, err := c.http.Do(req) |
| if !late.Stop() && err == nil { |
diff --git a/internal/equipo/equipo.go b/internal/equipo/equipo.go| index b800739..2f4de14 100644 |
| --- a/internal/equipo/equipo.go |
| +++ b/internal/equipo/equipo.go |
| @@ -135,6 +135,7 @@ func (c *Client) call(ctx context.Context, method, path, token, key string, head |
| req.Header.Set("Content-Type", "application/json") |
| } |
| req.Header.Set("Accept", "application/json") |
| + setCapabilities(ctx, req) |
| if token != "" { |
| req.Header.Set("Authorization", "Bearer "+token) |
| } |
diff --git a/internal/equipo/files.go b/internal/equipo/files.go| index 634cb7f..50637f4 100644 |
| --- a/internal/equipo/files.go |
| +++ b/internal/equipo/files.go |
| @@ -121,6 +121,7 @@ func (c *Client) do(ctx context.Context, method, path, token string, header http |
| req.Header[k] = v |
| } |
| req.Header.Set("Authorization", "Bearer "+token) |
| + setCapabilities(ctx, req) |
| late := time.AfterFunc(c.fileTimeout(), cancel) |
| res, err := c.http.Do(req) |
| if !late.Stop() && err == nil { |
diff --git a/internal/store/askclients.go b/internal/store/askclients.go| new file mode 100644 |
| index 0000000..2c61d92 |
| --- /dev/null |
| +++ b/internal/store/askclients.go |
| @@ -0,0 +1,44 @@ |
| +package store |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "time" |
| +) |
| + |
| +// AskClient is one native app of a member's: what it last said it can |
| +// draw (a comma-separated list, Base-Client-Capabilities) and when. |
| +type AskClient struct { |
| + Client string |
| + Caps string |
| + SeenAt time.Time |
| +} |
| + |
| +// SeeAskClient records that the member numbered member's native client |
| +// called with caps, replacing what it said before. |
| +func SeeAskClient(ctx context.Context, db *sql.DB, member int64, client, caps string) error { |
| + _, err := db.ExecContext(ctx, `INSERT INTO ask_clients (member_id, client, caps, seen_at) VALUES (?, ?, ?, ?) |
| + ON CONFLICT (member_id, client) DO UPDATE SET caps = excluded.caps, seen_at = excluded.seen_at`, |
| + member, client, caps, time.Now().UTC()) |
| + return err |
| +} |
| + |
| +// AskClients are the member numbered member's native clients seen since |
| +// since. |
| +func AskClients(ctx context.Context, db *sql.DB, member int64, since time.Time) ([]AskClient, error) { |
| + rows, err := db.QueryContext(ctx, `SELECT client, caps, seen_at FROM ask_clients WHERE member_id = ? AND seen_at >= ? |
| + ORDER BY client`, member, since.UTC()) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []AskClient |
| + for rows.Next() { |
| + var c AskClient |
| + if err := rows.Scan(&c.Client, &c.Caps, &c.SeenAt); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, c) |
| + } |
| + return out, rows.Err() |
| +} |
diff --git a/internal/store/askclients_test.go b/internal/store/askclients_test.go| new file mode 100644 |
| index 0000000..f2ffde1 |
| --- /dev/null |
| +++ b/internal/store/askclients_test.go |
| @@ -0,0 +1,47 @@ |
| +package store |
| + |
| +import ( |
| + "context" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// Each native client keeps only the newest capabilities it called with, |
| +// and AskClients lists only those seen since the time asked for. |
| +func TestSeeAskClientNewest(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + if err := SeeAskClient(ctx, db, 7, "phone", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := SeeAskClient(ctx, db, 7, "phone", "lookup_answers"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := SeeAskClient(ctx, db, 7, "mac", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := SeeAskClient(ctx, db, 8, "phone", "other"); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := AskClients(ctx, db, 7, time.Now().Add(-time.Hour)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + caps := map[string]string{} |
| + for _, c := range got { |
| + caps[c.Client] = c.Caps |
| + } |
| + if len(got) != 2 || caps["phone"] != "lookup_answers" || caps["mac"] != "" { |
| + t.Fatalf("member 7's clients = %+v", got) |
| + } |
| + // Nothing was seen after now. |
| + if got, err := AskClients(ctx, db, 7, time.Now().Add(time.Minute)); err != nil || len(got) != 0 { |
| + t.Fatalf("clients seen in the future = %+v, %v", got, err) |
| + } |
| + // A row seen long ago is left out. |
| + if _, err := db.Exec(`UPDATE ask_clients SET seen_at = ? WHERE member_id = 7 AND client = 'mac'`, time.Now().Add(-31*24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, err := AskClients(ctx, db, 7, time.Now().Add(-30*24*time.Hour)); err != nil || len(got) != 1 || got[0].Client != "phone" { |
| + t.Fatalf("clients seen in the last 30 days = %+v, %v", got, err) |
| + } |
| +} |
diff --git a/internal/store/migrations/0013_ask_clients.sql b/internal/store/migrations/0013_ask_clients.sql| new file mode 100644 |
| index 0000000..0ea1966 |
| --- /dev/null |
| +++ b/internal/store/migrations/0013_ask_clients.sql |
| @@ -0,0 +1,6 @@ |
| +-- ask_clients: what each of a member's native apps last said it can draw |
| +-- (Base-Client-Capabilities), so Base tells Equipo only what every client |
| +-- the member uses can show. member_id is the member's number; client is |
| +-- the app's native session (its token's hash, never the token). Web |
| +-- sessions are not recorded: the web is Base's own and always can. |
| +CREATE TABLE ask_clients (member_id integer NOT NULL, client text NOT NULL, caps text NOT NULL DEFAULT '', seen_at datetime NOT NULL, PRIMARY KEY (member_id, client)); |
diff --git a/internal/web/app.go b/internal/web/app.go| index b37a994..998977d 100644 |
| --- a/internal/web/app.go |
| +++ b/internal/web/app.go |
| @@ -197,6 +197,9 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| r.Post(passkeyDoor.FinishPath, a.pk.DiscoverFinish) |
| r.Group(func(r chi.Router) { |
| r.Use(a.requireMember) |
| + if a.ask != nil { |
| + r.Use(a.withAskCaps) |
| + } |
| r.Get("/", a.home) |
| r.Get("/people", a.people) |
| r.Post("/people", a.invite) |
diff --git a/internal/web/ask_caps.go b/internal/web/ask_caps.go| new file mode 100644 |
| index 0000000..ecc3480 |
| --- /dev/null |
| +++ b/internal/web/ask_caps.go |
| @@ -0,0 +1,106 @@ |
| +package web |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/oficina/base/internal/equipo" |
| + "amadan.net/oficina/base/internal/store" |
| +) |
| + |
| +// clientCapsHeader is what Base's native app says it can draw, on each of |
| +// its /ask/* requests (docs/api/base-native-v1.md). |
| +const clientCapsHeader = "Base-Client-Capabilities" |
| + |
| +// clientWindow is how long a native client's last word counts: one not |
| +// seen for longer no longer holds a capability back. |
| +const clientWindow = 30 * 24 * time.Hour |
| + |
| +// clientCaps reads a request's Base-Client-Capabilities: native is true |
| +// for the native app's session, caps are the known values it named, in |
| +// KnownCapabilities' order. A web session is never native. |
| +func clientCaps(r *http.Request) (native bool, caps []string) { |
| + s, ok := sessions.Current(r) |
| + if !ok || s.Method != connect.NativeMethod { |
| + return false, nil |
| + } |
| + said := map[string]bool{} |
| + for _, v := range r.Header.Values(clientCapsHeader) { |
| + for _, c := range strings.Split(v, ",") { |
| + said[strings.TrimSpace(c)] = true |
| + } |
| + } |
| + for _, c := range equipo.KnownCapabilities { |
| + if said[c] { |
| + caps = append(caps, c) |
| + } |
| + } |
| + return true, caps |
| +} |
| + |
| +// askCaps are the capabilities Base tells Equipo for the member numbered |
| +// member: every known one, but those a native client of theirs seen in |
| +// the last 30 days last called without. A read error withholds them all. |
| +func (a *app) askCaps(ctx context.Context, member int64) []string { |
| + clients, err := store.AskClients(ctx, a.db, member, time.Now().Add(-clientWindow)) |
| + if err != nil { |
| + a.logger.Error("ask: clients", "err", err) |
| + return nil |
| + } |
| + var out []string |
| + for _, c := range equipo.KnownCapabilities { |
| + ok := true |
| + for _, cl := range clients { |
| + ok = ok && slices.Contains(strings.Split(cl.Caps, ","), c) |
| + } |
| + if ok { |
| + out = append(out, c) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// withAskCaps records what a native /ask/* request says its app can draw |
| +// (web sessions are not recorded), then puts the member's capabilities |
| +// (askCaps) on the request's context, so every Equipo call made for it |
| +// carries Base-Capabilities. It runs behind the member gate. |
| +func (a *app) withAskCaps(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + me, ok := CurrentMember(r) |
| + if !ok { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + ctx := r.Context() |
| + n, err := store.MemberNumber(ctx, a.db, me.ID) |
| + if err != nil { |
| + a.logger.Error("ask: member number", "err", err) |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + recorded := true |
| + if native, said := clientCaps(r); native && strings.HasPrefix(r.URL.Path, "/ask/") { |
| + c, err := r.Cookie(a.sess.CookieName()) |
| + if err == nil { |
| + err = store.SeeAskClient(ctx, a.db, n, sessions.HashToken(c.Value), strings.Join(said, ",")) |
| + } |
| + if err != nil { |
| + // Unrecorded, this app could be one that can't draw |
| + // them: withhold every capability for this request. |
| + a.logger.Error("ask: see client", "err", err) |
| + recorded = false |
| + } |
| + } |
| + var caps []string |
| + if recorded { |
| + caps = a.askCaps(ctx, n) |
| + } |
| + next.ServeHTTP(w, r.WithContext(equipo.WithCapabilities(ctx, caps))) |
| + }) |
| +} |
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go| index daa6512..4c31602 100644 |
| --- a/internal/web/ask_connect.go |
| +++ b/internal/web/ask_connect.go |
| @@ -333,7 +333,7 @@ func (a *app) registerHost(ctx context.Context, me store.Member, dev, token stri |
| func (a *app) hostFor(ctx context.Context, me store.Member, dev, token string, fresh bool) { |
| ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout) |
| defer cancel() |
| - a.zoneFor(me, token, fresh) |
| + a.zoneFor(ctx, me, token, fresh) |
| defer a.lockMember(me.ID)() |
| if !fresh { |
| done, err := store.HostRegistered(ctx, a.db, me.ID) |
| @@ -375,7 +375,7 @@ type zoneTold struct { |
| // connection (fresh). It never holds up the page or the member's lock: |
| // the call runs on its own, bounded by zoneWait. After a failure (5xx, |
| // 429, 404, no answer in time) it is tried again no sooner than zoneRetry. |
| -func (a *app) zoneFor(me store.Member, token string, fresh bool) { |
| +func (a *app) zoneFor(parent context.Context, me store.Member, token string, fresh bool) { |
| if a.ask.zone == "" { |
| return |
| } |
| @@ -397,8 +397,9 @@ func (a *app) zoneFor(me store.Member, token string, fresh bool) { |
| } |
| z.busy = true |
| a.ask.zoneMu.Unlock() |
| + caps := equipo.CapabilitiesOf(parent) |
| go func() { |
| - ctx, cancel := context.WithTimeout(context.Background(), zoneWait) |
| + ctx, cancel := context.WithTimeout(equipo.WithCapabilities(context.Background(), caps), zoneWait) |
| defer cancel() |
| err := a.ask.client.SetTimeZone(ctx, token, a.ask.zone) |
| var e *equipo.Error |
diff --git a/internal/web/ask_internal_test.go b/internal/web/ask_internal_test.go| index 97d3bf0..2ce7f02 100644 |
| --- a/internal/web/ask_internal_test.go |
| +++ b/internal/web/ask_internal_test.go |
| @@ -110,12 +110,12 @@ func TestZoneBacksOffOn404(t *testing.T) { |
| } |
| me := store.Member{ID: "m1"} |
| start := time.Now() |
| - a.zoneFor(me, token, false) |
| + a.zoneFor(context.Background(), me, token, false) |
| z := told(t, a, me.ID) |
| if z.settled != tc.settled || !tc.settled && z.retryAt.Before(start.Add(zoneRetry)) || tc.settled && !z.retryAt.IsZero() { |
| t.Errorf("%d: settled %v, retry at %v (want settled %v)", tc.status, z.settled, z.retryAt, tc.settled) |
| } |
| - a.zoneFor(me, token, false) |
| + a.zoneFor(context.Background(), me, token, false) |
| if n := len(f.Calls("/api/v1/assistant/time-zone")); n != 1 { |
| t.Errorf("%d: %d calls before the wait is up", tc.status, n) |
| } |
| @@ -129,11 +129,11 @@ func TestZoneAgainForAConnectionMidCall(t *testing.T) { |
| a, f, token := newZoneApp(t) |
| release := f.HoldTimeZone() |
| me := store.Member{ID: "m1"} |
| - a.zoneFor(me, token, true) |
| + a.zoneFor(context.Background(), me, token, true) |
| for len(f.Calls("/api/v1/assistant/time-zone")) == 0 { |
| time.Sleep(5 * time.Millisecond) |
| } |
| - a.zoneFor(me, token, true) // the new connection, mid-call: no second call yet |
| + a.zoneFor(context.Background(), me, token, true) // the new connection, mid-call: no second call yet |
| if n := len(f.Calls("/api/v1/assistant/time-zone")); n != 1 { |
| t.Fatalf("%d calls while one is in flight", n) |
| } |
| @@ -141,9 +141,9 @@ func TestZoneAgainForAConnectionMidCall(t *testing.T) { |
| if z := told(t, a, me.ID); z.settled { |
| t.Fatal("the call before the new connection settled it") |
| } |
| - a.zoneFor(me, token, false) |
| + a.zoneFor(context.Background(), me, token, false) |
| told(t, a, me.ID) |
| - a.zoneFor(me, token, false) |
| + a.zoneFor(context.Background(), me, token, false) |
| told(t, a, me.ID) |
| if n := len(f.Calls("/api/v1/assistant/time-zone")); n != 2 { |
| t.Errorf("%d calls, want the held one and one for the new connection", n) |
diff --git a/internal/webtest/ask_caps_test.go b/internal/webtest/ask_caps_test.go| new file mode 100644 |
| index 0000000..427193b |
| --- /dev/null |
| +++ b/internal/webtest/ask_caps_test.go |
| @@ -0,0 +1,148 @@ |
| +package webtest |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/base/internal/equipo" |
| + "amadan.net/oficina/base/internal/equipo/equipotest" |
| + "amadan.net/oficina/base/internal/store" |
| +) |
| + |
| +// capsOfLast is the Base-Capabilities header of the newest call to path, |
| +// and whether the header was there at all. |
| +func capsOfLast(t *testing.T, f *equipotest.Fake, path string) (string, bool) { |
| + t.Helper() |
| + calls := f.Calls(path) |
| + if len(calls) == 0 { |
| + t.Fatalf("no call to %s", path) |
| + } |
| + v, ok := calls[len(calls)-1].Header["Base-Capabilities"] |
| + if !ok { |
| + return "", false |
| + } |
| + return strings.Join(v, ","), true |
| +} |
| + |
| +const snapshotPath = "/api/v1/assistant/snapshot" |
| + |
| +// A member who uses only the web is told, on Equipo's every call, that |
| +// Base draws lookup answers. |
| +func TestAskCapsWebOnly(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.approveEquipo(f) |
| + if r := a.get("/ask"); r.Code != 200 { |
| + t.Fatalf("/ask: %d", r.Code) |
| + } |
| + if caps, ok := capsOfLast(t, f, snapshotPath); !ok || caps != equipo.CapLookupAnswers { |
| + t.Errorf("Base-Capabilities %q (%v), want %q", caps, ok, equipo.CapLookupAnswers) |
| + } |
| +} |
| + |
| +// One native app that called without saying it draws lookups withholds |
| +// the capability for the member, on the web too, until it calls with it, |
| +// or until it was last seen more than 30 days ago. |
| +func TestAskCapsWithheldForOldNative(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + want := func(where string, have bool) { |
| + t.Helper() |
| + caps, ok := capsOfLast(t, f, snapshotPath) |
| + if have && (!ok || caps != equipo.CapLookupAnswers) || !have && ok { |
| + t.Errorf("%s: Base-Capabilities %q (%v), want it %v", where, caps, ok, have) |
| + } |
| + } |
| + app.askState() |
| + want("an old app's own read", false) |
| + if r := web.get("/ask"); r.Code != 200 { |
| + t.Fatalf("/ask: %d", r.Code) |
| + } |
| + want("the web, while the old app is in use", false) |
| + |
| + app.header = http.Header{"Base-Client-Capabilities": {"job_actions, " + equipo.CapLookupAnswers}} |
| + app.askState() |
| + want("the app, upgraded", true) |
| + web.get("/ask") |
| + want("the web, once the app is upgraded", true) |
| + |
| + app.header = nil |
| + app.askState() |
| + want("the app, downgraded", false) |
| + if _, err := web.DB.Exec(`UPDATE ask_clients SET seen_at = ?`, time.Now().Add(-31*24*time.Hour).UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + web.get("/ask") |
| + want("the web, the old app unseen for 31 days", true) |
| +} |
| + |
| +// Every relayed call carries the header: the snapshot, the event stream, |
| +// a message, a card's answer, Carry on now and the time zone. The host's |
| +// registration carries it too, with its body as it always was. |
| +func TestCapabilityHeaderOnEveryCall(t *testing.T) { |
| + web, _, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + web.get("/ask") |
| + for i := 0; i < 200 && len(f.Calls("/api/v1/assistant/time-zone")) == 0; i++ { |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + card := f.AskQuestion("Which colour?", "Blue", "Green") |
| + job := f.AskJob("A form") |
| + f.PauseJob(job, "Paused until 21:00", "It has reached the limit on its plan for now.", true) |
| + if r := web.post("/ask/messages", url.Values{"text": {"Hello"}, "key": {"caps-1"}}); r.Code != 303 { |
| + t.Fatalf("send: %d %s", r.Code, r.Body) |
| + } |
| + if r := web.post("/ask/cards/"+card+"/answer", url.Values{"choice": {"Blue"}, "revision": {"1"}, "key": {"caps-2"}}); r.Code != 303 { |
| + t.Fatalf("answer: %d %s", r.Code, r.Body) |
| + } |
| + var rev int64 |
| + for _, raw := range jobsOf(t, web) { |
| + var c equipo.Card |
| + _ = json.Unmarshal(raw, &c) |
| + if c.ID == job { |
| + rev = c.Revision |
| + } |
| + } |
| + if r := web.post("/ask/cards/"+job+"/carry_on", url.Values{"revision": {strconv.FormatInt(rev, 10)}, "key": {"caps-3"}}); r.Code != 303 { |
| + t.Fatalf("carry on: %d %s", r.Code, r.Body) |
| + } |
| + web.events(t, "0", func(got []sseFrame) bool { return len(got) >= 2 }) |
| + for _, p := range []string{snapshotPath, "/api/v1/assistant/events", "/api/v1/assistant/messages", |
| + "/api/v1/assistant/cards/" + card + "/answer", "/api/v1/assistant/cards/" + job + "/carry_on", |
| + "/api/v1/assistant/time-zone", "/api/v1/assistant/host"} { |
| + if caps, ok := capsOfLast(t, f, p); !ok || caps != equipo.CapLookupAnswers { |
| + t.Errorf("%s: Base-Capabilities %q (%v)", p, caps, ok) |
| + } |
| + } |
| + hosts := f.Hosts() |
| + var body map[string]string |
| + if err := json.Unmarshal([]byte(hosts[len(hosts)-1].Body), &body); err != nil || len(body) != 2 || body["origin"] == "" || body["token"] == "" { |
| + t.Errorf("host body %q: %v", hosts[len(hosts)-1].Body, err) |
| + } |
| + n, err := store.MemberNumber(context.Background(), web.DB, web.ownerID()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The web is never recorded as a client. |
| + if got, err := store.AskClients(context.Background(), web.DB, n, time.Time{}); err != nil || len(got) != 0 { |
| + t.Errorf("web clients recorded: %+v %v", got, err) |
| + } |
| +} |
| + |
| +// jobsOf is /ask/state's jobs, read by browser a. |
| +func jobsOf(t *testing.T, a *testApp) []json.RawMessage { |
| + t.Helper() |
| + req, _ := http.NewRequest(http.MethodGet, a.base+"/ask/state", nil) |
| + req.Header.Set("Accept", "application/json") |
| + r := a.do(req) |
| + var s askState |
| + if err := json.Unmarshal([]byte(r.Body), &s); err != nil { |
| + t.Fatalf("/ask/state: %d %s", r.Code, r.Body) |
| + } |
| + return s.Jobs |
| +} |
diff --git a/internal/webtest/ask_native_contract_test.go b/internal/webtest/ask_native_contract_test.go| index 2ad304f..df9d2de 100644 |
| --- a/internal/webtest/ask_native_contract_test.go |
| +++ b/internal/webtest/ask_native_contract_test.go |
| @@ -410,6 +410,7 @@ func (a *testApp) events(t *testing.T, after string, done func([]sseFrame) bool) |
| 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") |
| + a.addHeader(req) |
| for _, c := range a.client.Jar.Cookies(req.URL) { |
| req.AddCookie(c) |
| } |
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go| index eeb6b74..bea93ee 100644 |
| --- a/internal/webtest/harness_test.go |
| +++ b/internal/webtest/harness_test.go |
| @@ -97,6 +97,9 @@ type testApp struct { |
| seenMu *sync.Mutex |
| // logs is everything the app logged. |
| logs *logBuffer |
| + // header is sent with every request this browser makes (the native |
| + // app's Base-Client-Capabilities), unless the request sets it itself. |
| + header http.Header |
| } |
| // logBuffer is the app's log, written by its handlers and read by a test. |
| @@ -166,6 +169,7 @@ func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Insta |
| func (a *testApp) do(req *http.Request) Resp { |
| a.t.Helper() |
| + a.addHeader(req) |
| res, err := a.client.Do(req) |
| if err != nil { |
| a.t.Fatal(err) |
| @@ -179,6 +183,15 @@ func (a *testApp) do(req *http.Request) Resp { |
| return out |
| } |
| +// addHeader sets a.header's fields on req where req has none of its own. |
| +func (a *testApp) addHeader(req *http.Request) { |
| + for k, v := range a.header { |
| + if _, ok := req.Header[k]; !ok { |
| + req.Header[k] = v |
| + } |
| + } |
| +} |
| + |
| func (a *testApp) get(target string) Resp { |
| a.t.Helper() |
| req, _ := http.NewRequest(http.MethodGet, a.base+target, nil) |