oficina / base Public

Register Base with Equipo's Assistant and show who is connected

When a member's Equipo connection becomes ready, Base mints them a host
token and gives it to Equipo (PUT /api/v1/assistant/host) with Base's
origin; a member connected earlier is registered on their next read of
the chat, once. A failed registration is logged without any token and
tried again on the next read; it never breaks the chat or disconnects
anyone. Reconnecting rotates the token; Disconnect, a new Connect and a
bearer Equipo refuses all forget it.

Without a runner that can answer (snapshot not available, or 409
no_runner / runner_too_old on a send or a question's answer) the chat
keeps the conversation and the person's text, shows no message, and
says so with a link to Equipo; JSON clients get state norunner or
oldrunner. Settings shows the Equipo address the connection speaks for
(migration 0010 adds equipo_links.person). New and changed strings are
listed in docs/copy-pending.md, Review 7, pending.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev d6abbd4c8e0f9ca95a7e188432b0b4d5ab6b1a14 parent 35754ba
18 files changed, +630 −54
  • README.md +8 −1
  • docs/copy-pending.md +7 −0
  • docs/roadmap.md +3 −3
  • internal/browsertest/ask_test.go +37 −0
  • internal/equipo/equipotest/chat.go +50 −8
  • internal/look/static/ask.js +27 −8
  • internal/store/equipo.go +17 −6
  • internal/store/migrations/0010_equipo_person.sql +3 −0
  • internal/web/ask.go +70 −12
  • internal/web/ask_connect.go +55 −0
  • internal/web/ask_relay.go +11 −1
  • internal/web/settings.go +7 −3
  • internal/web/templates/ask_connect.html +1 −1
  • internal/web/templates/partials/chat.html +5 −3
  • internal/web/templates/settings.html +1 −1
  • internal/webtest/ask_test.go +281 −5
  • internal/webtest/harness_test.go +24 −2
  • internal/webtest/settings_test.go +23 −0
diff --git a/README.md b/README.md
index 16e5bb4..876de92 100644
--- a/README.md
+++ b/README.md
@@ -46,11 +46,18 @@ Everything is an environment variable. `BASE_ORIGIN`, `BASE_OWNER` and
across restarts: apps check sign-ins against its public half.
- `BASE_ALLOW_LOGGED_MAIL=1` prints sign-in links instead of sending them.
Local only; Base refuses it on a non-loopback origin.
-- `BASE_EQUIPO_ORIGIN` is the Equipo whose coordinator answers "Ask Base
+- `BASE_EQUIPO_ORIGIN` is the Equipo whose Assistant answers "Ask Base
anything", such as `https://equipo.example.com`. Without it the Ask field
stays off. Each person connects Equipo once, from Settings or the Ask
panel; Base keeps their Equipo key sealed with `BASE_INSTANCE_KEY`, so
changing that key disconnects everyone from Equipo.
+ When a person connects, Base tells Equipo its own address (`BASE_ORIGIN`)
+ and gives it a token for that person alone. Equipo's Assistant uses the
+ token to read Base's apps, people and settings as that person. Connecting
+ again replaces the token, and disconnecting withdraws it. Equipo takes the
+ address only if its operator lists it in `EQUIPO_ASSISTANT_HOSTS`. Until
+ then the chat still works, but the Assistant can't see Base: Base logs
+ `host_not_allowed` and tries again the next time the person opens the chat.
- `BASE_OFICINA_APPS` lists your team's Oficina apps, which Home shows first
in its grid of apps, each opening in a new tab. Write each as
`id=address`, separated by commas, in the order you want them, such as
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index 47a0b8f..4c843f3 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -324,3 +324,10 @@ Review 7 (pending): Base's operations for Equipo's Assistant. The Assistant read
| internal/operations/operations.go | Error message: Base's database failed (503 unavailable) | Base could not answer. Try again. |
| internal/web/ask_cards.go, ask.js | REMOVED (Ask Base now draws every card from Equipo's fields: an option's label, a link's label, the card's result): a publish card whose site failed | ~~Publishing failed.~~ |
| partials/chat.html, ask_cards.go, ask.js | REMOVED (as above): Equipo's card words Base kept its own copies of (Review 6) | ~~Open the preview~~ / ~~Open the site~~ / ~~Merge~~ / ~~Wait for checks~~ / ~~Wait for a Mac~~ / ~~Not now~~ / ~~Publish~~ / ~~Merging without checks.~~ / ~~Waiting for checks.~~ / ~~Waiting for a Mac.~~ / ~~Not now.~~ / ~~Nothing to decide any more.~~ / ~~Publishing.~~ / ~~Published~~ / ~~Publish could not be confirmed~~ / ~~Not published.~~ |
+| internal/web/templates/partials/chat.html | Ask panel and /ask, under the conversation: the person has no runner that can answer (Equipo's snapshot says not available, or a send or a question's answer gets 409 no_runner). The link opens Equipo in a new tab. The person's text stays in the field | Ask Base needs a runner of your own to answer. [Add one in Equipo], then try again. |
+| internal/web/templates/partials/chat.html | Ask panel and /ask, under the conversation: a send or a question's answer gets 409 runner_too_old. The link opens Equipo in a new tab. The person's text stays in the field | Your runner needs an update for this. [Update it in Equipo], then try again. |
+| internal/web/templates/settings.html | Settings, the Equipo row's value once Base has read which Equipo person the connection speaks for (before that it stays "Connected") | Connected as {address} |
+| internal/web/templates/partials/chat.html | CHANGED (Base talks to Equipo's Assistant now): the Ask panel and /ask before connecting | ~~Connect Equipo, and its coordinator answers you here.~~ → Connect Equipo, and its Assistant answers you here. |
+| internal/web/templates/ask_connect.html | CHANGED (as above): the connect page before connecting | ~~Connect Equipo, and its coordinator answers you in Base.~~ → Connect Equipo, and its Assistant answers you in Base. |
+| README.md | Settings: the BASE_EQUIPO_ORIGIN bullet, its first sentence (changed) and the new lines after it | `BASE_EQUIPO_ORIGIN` is the Equipo whose Assistant answers "Ask Base anything" (was: whose coordinator answers). New: When a person connects, Base tells Equipo its own address (`BASE_ORIGIN`) and gives it a token for that person alone. Equipo's Assistant uses the token to read Base's apps, people and settings as that person. Connecting again replaces the token, and disconnecting withdraws it. Equipo takes the address only if its operator lists it in `EQUIPO_ASSISTANT_HOSTS`. Until then the chat still works, but the Assistant can't see Base: Base logs `host_not_allowed` and tries again the next time the person opens the chat. |
+| docs/roadmap.md | Working notes, steps 4 to 6 (lines 8 to 10), each changed to point at the Assistant's spec and slice 1 plan | 4: "What can I do": Equipo's Assistant learns what's in Base. Slice 1 of the Assistant, with step 6: spec … (§8, steps 1 to 4), plan …. Built (branch assistant, in Base and Equipo); Equipo's release to staging and the live check pending. / 5: the Assistant's `oficina` provider, the spec's §8 step 5, after slice 1. Needs oficina-connect deployed. / 6: "Build me a quick website": the Assistant hands it to the team, then asks "Publish it?". In slice 1 with step 4 (same spec and plan). |
diff --git a/docs/roadmap.md b/docs/roadmap.md
index a764c8c..aaf53aa 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -5,9 +5,9 @@ The "Base + Equipo" slice, in order. Each step makes one join between the pieces
1. Sign in to Base with Oficina ID. Done (branch oficina-id, deployed 2026-11-11).
2. Ask Base: Equipo's coordinator chat in a glass panel, via Equipo's device sign-in. Built (branch ask-base); copy review 5 and deploy pending.
3. Oficina apps on Home: a rail on a wide screen, tiles on a phone (BASE_OFICINA_APPS). Built (branch ask-base); copy review 5 and deploy pending.
-4. "What can I do": the coordinator learns what's in Base. oficina/equipo discussion 9.
-5. "Put a meeting in my calendar…": oficina/equipo 10, oficina/agent-access 2, oficina/calendar 37.
-6. "Build me a quick website": oficina/equipo 11, carlos/platform 934.
+4. "What can I do": Equipo's Assistant learns what's in Base. Slice 1 of the Assistant, with step 6: spec docs/superpowers/specs/2026-11-12-equipo-assistant-design.md (§8, steps 1 to 4), plan docs/superpowers/plans/2026-11-12-equipo-assistant-slice1.md. Built (branch assistant, in Base and Equipo); Equipo's release to staging and the live check pending. oficina/equipo discussion 9.
+5. "Put a meeting in my calendar…": the Assistant's `oficina` provider, the spec's §8 step 5, after slice 1. Needs oficina-connect deployed. oficina/equipo 10, oficina/agent-access 2, oficina/calendar 37.
+6. "Build me a quick website": the Assistant hands it to the team, then asks "Publish it?". In slice 1 with step 4 (same spec and plan). oficina/equipo 11, carlos/platform 934.
7. Contra: expiring, one-time secret grants for Equipo agents. carlos/contra 27.
8. Widgets on Home (Paul, 2026-11-12): any app registers Base widgets; people arrange them; Equipo can create them. Leaning declarative (list, number, timeline, chart, links) drawn by Base from an app's data address, signed in as the person; no app HTML in Base. Builds on agent-access operations.
9. Fresh installs: Oficina apps pre-enrolled to Oficina ID (Alta in Base's installer, team mode). oficina/home 105.
diff --git a/internal/browsertest/ask_test.go b/internal/browsertest/ask_test.go
index fae45c9..5a1bdaf 100644
--- a/internal/browsertest/ask_test.go
+++ b/internal/browsertest/ask_test.go
@@ -134,6 +134,43 @@ func TestAskPanelSendsOnce(t *testing.T) {
}
}
+// Without a runner that can answer, the panel says so with a link to
+// Equipo; a send keeps what the person wrote in the field and shows no
+// message; a runner too old has its own note.
+func TestAskPanelNoRunner(t *testing.T) {
+ rig, f := askBase(t)
+ f.NoRunner()
+ openPanel(t, rig)
+ note := `#ask-panel .ask-runner[data-when="norunner"]`
+ old := `#ask-panel .ask-runner[data-when="oldrunner"]`
+ drive(t, rig, chromedp.WaitVisible(chromedp.CSS(note)))
+ if !harness.Evaluate[bool](rig, `!!document.querySelector(`+strconv.Quote(note+` a[href="`+f.URL+`/"][target="_blank"]`)+`)`) {
+ t.Fatal("the no-runner note has no link to Equipo")
+ }
+ rig.Screen("#ask-panel", "the panel without a runner")
+ // Each send moves the panel from one note to the other.
+ const text = "Build me a quick website"
+ f.RunnerTooOld()
+ drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), text),
+ chromedp.Click(chromedp.CSS(`#ask-panel form.composer button`)),
+ chromedp.WaitVisible(chromedp.CSS(old)), chromedp.WaitNotVisible(chromedp.CSS(note)))
+ f.NoRunner()
+ drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel form.composer button`)),
+ chromedp.WaitVisible(chromedp.CSS(note)), chromedp.WaitNotVisible(chromedp.CSS(old)))
+ if n := len(f.Calls("/api/v1/assistant/messages")); n != 2 {
+ t.Fatalf("sends relayed: %d, want 2", n)
+ }
+ if got := harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`); got != text {
+ t.Errorf("the field holds %q, want %q", got, text)
+ }
+ if n := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); n != 0 {
+ t.Errorf("person messages shown: %d", n)
+ }
+ if got := harness.Evaluate[string](rig, `document.querySelector("#ask-panel .ask-status").textContent`); got != "" {
+ t.Errorf("status line %q", got)
+ }
+}
+
func keys(calls []equipotest.Call) []string {
var out []string
for _, c := range calls {
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go
index 1e78fd0..a6efeff 100644
--- a/internal/equipo/equipotest/chat.go
+++ b/internal/equipo/equipotest/chat.go
@@ -79,11 +79,19 @@ type chat struct {
events []event
sent map[string]string // idempotency key to message id
wake chan struct{} // closed at each new event
- noRunner bool
+ // 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
+ // hostStatus and hostCode, when set, are what every PUT host gets.
+ hostStatus int
+ hostCode string
}
func (c *chat) init() {
c.turns, c.sent, c.wake = map[string]*turn{}, map[string]string{}, make(chan struct{})
+ c.address = "paul@tito.io"
}
func (c *chat) next(prefix string) string { c.seq++; return fmt.Sprintf("%s_%04d", prefix, c.seq) }
@@ -150,7 +158,32 @@ func (f *Fake) SetCard(id, state, result string) {
func (f *Fake) NoRunner() {
f.cmu.Lock()
defer f.cmu.Unlock()
- f.noRunner = true
+ 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.
@@ -226,10 +259,10 @@ func (f *Fake) snapshot(w http.ResponseWriter) {
cards = append(cards, *c)
}
writeJSON(w, 200, map[string]any{
- "me": map[string]any{"id": "paul@tito.io", "address": "paul@tito.io", "role": "owner",
+ "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": f.tail(), "turns": turns, "cards": cards, "cursor": int64(len(f.events) + 40),
- "available": !f.noRunner,
+ "available": f.runner == "",
})
}
@@ -245,6 +278,13 @@ func (f *Fake) host(w http.ResponseWriter, r *http.Request) {
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())})
}
@@ -266,9 +306,10 @@ func (f *Fake) send(w http.ResponseWriter, r *http.Request) {
return
}
f.cmu.Lock()
- if f.noRunner {
+ if f.runner != "" {
+ code := f.runner
f.cmu.Unlock()
- writeError(w, r, 409, "no_runner")
+ writeError(w, r, 409, code)
return
}
if id, ok := f.sent[in.IdempotencyKey]; ok {
@@ -413,9 +454,10 @@ func (f *Fake) answer(w http.ResponseWriter, r *http.Request, id string) {
writeError(w, r, 422, "invalid_input")
return
}
- if c.Kind == "question" && f.noRunner {
+ if c.Kind == "question" && f.runner != "" {
+ code := f.runner
f.cmu.Unlock()
- writeError(w, r, 409, "no_runner")
+ writeError(w, r, 409, code)
return
}
c.State, c.Revision = "answered", c.Revision+1
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 9f21a72..fb10bd4 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -25,6 +25,11 @@ function start(root) {
const json = { Accept: "application/json" };
+ // The states that show the conversation: ready, and ready without a
+ // runner that can answer (none, or one too old), which adds a note.
+ const runnerless = ["norunner", "oldrunner"];
+ const chatting = (state) => state === "ready" || runnerless.includes(state);
+
function show(state) {
root.dataset.state = state;
for (const el of root.querySelectorAll("[data-when]")) {
@@ -276,7 +281,7 @@ function start(root) {
return;
}
show(s.state);
- if (s.state !== "ready" || !live()) return;
+ if (!chatting(s.state) || !live()) return;
thread.replaceChildren();
pinned = true;
s.messages.forEach(addMessage);
@@ -294,10 +299,13 @@ function start(root) {
// post sends a form by fetch and returns its JSON, or null when it was
// already on its way or failed (and the panel says so).
- // lastStatus is the HTTP status of the latest post that got an answer.
+ // lastStatus is the HTTP status of the latest post that got an answer,
+ // lastState the state it answered with.
let lastStatus = 0;
+ let lastState = "";
async function post(form, extra) {
lastStatus = 0;
+ lastState = "";
const body = new URLSearchParams(new FormData(form));
body.delete("key");
for (const [k, v] of Object.entries(extra || {})) body.set(k, v);
@@ -313,12 +321,18 @@ function start(root) {
const res = await fetch(form.action, { method: "POST", headers: json, body });
const out = await res.json();
lastStatus = res.status;
+ lastState = out.state || "";
known = res.status !== 502;
- if (res.ok) return out;
- // Lost the connection: the panel says what to do. Otherwise the
- // conversation stays, with a line to try again (a 409 is stale: the
- // next events show how things are).
- if (["connect", "pending", "reconnect"].includes(out.state)) show(out.state);
+ if (res.ok) {
+ // It went through: a runner answers again, so its note goes.
+ if (root.dataset.state !== "ready") show("ready");
+ return out;
+ }
+ // Lost the connection: the panel says what to do. No runner that
+ // can answer: the conversation stays, with a note saying so.
+ // Otherwise the conversation stays, with a line to try again (a 409
+ // is stale: the next events show how things are).
+ if (["connect", "pending", "reconnect", ...runnerless].includes(out.state)) show(out.state);
else if (res.status !== 409) status.textContent = "Equipo didn't get that. Try again.";
} catch {
status.textContent = "Equipo didn't get that. Try again.";
@@ -358,6 +372,11 @@ function start(root) {
if (!choice) return;
for (const b of form.querySelectorAll("button")) b.disabled = true;
const out = await post(form, { choice });
+ if (!out && runnerless.includes(lastState)) {
+ // Nothing was answered: the card stays open for when a runner can.
+ for (const b of form.querySelectorAll("button")) b.disabled = false;
+ return;
+ }
if (!out && lastStatus === 409) {
// The card moved on (a new revision, or answered elsewhere): read the
// conversation afresh and let the person choose again. Never resend.
@@ -439,7 +458,7 @@ function start(root) {
place();
dialog.showModal();
load().then(() => {
- const first = root.dataset.state === "ready" ? field : dialog.querySelector("[data-when]:not([hidden]) .btn");
+ const first = chatting(root.dataset.state) ? field : dialog.querySelector("[data-when]:not([hidden]) .btn");
if (first) first.focus();
});
field.focus();
diff --git a/internal/store/equipo.go b/internal/store/equipo.go
index deef816..2d445f6 100644
--- a/internal/store/equipo.go
+++ b/internal/store/equipo.go
@@ -18,7 +18,8 @@ const (
// EquipoLink is a member's connection to the Equipo at Origin. Sealed is
// opaque here: the web package seals and opens it. Revision is the
-// device's revision in Equipo, which revoking it names.
+// device's revision in Equipo, which revoking it names. Person is the
+// Equipo address the bearer speaks for, empty until Base has read it.
type EquipoLink struct {
MemberID, Origin, State string
DeviceID string
@@ -27,17 +28,18 @@ type EquipoLink struct {
ExpiresAt time.Time
Revision int64
PolledAt *time.Time
+ Person string
}
const equipoCols = `member_id, origin, state, device_id, user_code,
- verification_uri, sealed, expires_at, revision, polled_at`
+ verification_uri, sealed, expires_at, revision, polled_at, person`
// EquipoLinkFor is the member's link; ok is false when there is none.
func EquipoLinkFor(ctx context.Context, db *sql.DB, memberID string) (l EquipoLink, ok bool, err error) {
var polled sql.NullTime
err = db.QueryRowContext(ctx, `SELECT `+equipoCols+` FROM equipo_links WHERE member_id = ?`, memberID).
Scan(&l.MemberID, &l.Origin, &l.State, &l.DeviceID, &l.UserCode,
- &l.VerificationURI, &l.Sealed, &l.ExpiresAt, &l.Revision, &polled)
+ &l.VerificationURI, &l.Sealed, &l.ExpiresAt, &l.Revision, &polled, &l.Person)
if errors.Is(err, sql.ErrNoRows) {
return EquipoLink{}, false, nil
}
@@ -58,14 +60,15 @@ func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error {
polled = l.PolledAt.UTC()
}
_, err := db.ExecContext(ctx, `INSERT INTO equipo_links (`+equipoCols+`, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (member_id) DO UPDATE SET origin = excluded.origin, state = excluded.state,
device_id = excluded.device_id, user_code = excluded.user_code,
verification_uri = excluded.verification_uri, sealed = excluded.sealed,
expires_at = excluded.expires_at, revision = excluded.revision,
- polled_at = excluded.polled_at, exchanging_until = NULL, updated_at = excluded.updated_at`,
+ polled_at = excluded.polled_at, person = excluded.person,
+ exchanging_until = NULL, updated_at = excluded.updated_at`,
l.MemberID, l.Origin, l.State, l.DeviceID, l.UserCode, l.VerificationURI,
- l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, time.Now().UTC())
+ l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, l.Person, time.Now().UTC())
return err
}
@@ -118,6 +121,14 @@ func SetEquipoLinkState(ctx context.Context, db *sql.DB, memberID, dev, state st
return err
}
+// SetEquipoPerson records the Equipo address the member's device dev
+// speaks for, if the link is still that device.
+func SetEquipoPerson(ctx context.Context, db *sql.DB, memberID, dev, person string) error {
+ _, err := db.ExecContext(ctx, `UPDATE equipo_links SET person = ?, updated_at = ? WHERE member_id = ? AND device_id = ?`,
+ person, time.Now().UTC(), memberID, dev)
+ return err
+}
+
// DeleteEquipoLink forgets the member's link, if it is still device dev.
func DeleteEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error {
_, err := db.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ? AND device_id = ?`, memberID, dev)
diff --git a/internal/store/migrations/0010_equipo_person.sql b/internal/store/migrations/0010_equipo_person.sql
new file mode 100644
index 0000000..38c88b5
--- /dev/null
+++ b/internal/store/migrations/0010_equipo_person.sql
@@ -0,0 +1,3 @@
+-- person is the Equipo address the member's bearer speaks for, as Equipo
+-- last said (its snapshot's me.address); empty until Base has read it.
+ALTER TABLE equipo_links ADD COLUMN person text NOT NULL DEFAULT '';
diff --git a/internal/web/ask.go b/internal/web/ask.go
index 738efec..a03eddd 100644
--- a/internal/web/ask.go
+++ b/internal/web/ask.go
@@ -6,6 +6,7 @@ import (
"errors"
"net/http"
"strings"
+ "sync"
"time"
"github.com/go-chi/chi/v5"
@@ -22,6 +23,9 @@ type asker struct {
seal equipo.Sealer
// label is the device name a member sees when approving Base in Equipo.
label string
+ // hosts holds a *sync.Mutex per member id, held while their host is
+ // registered with Equipo (hostFor).
+ hosts sync.Map
}
// askRoutes mounts the chat, behind the member gate and Base's CSRF check.
@@ -46,17 +50,27 @@ func newAsker(origin, instanceKey, name string) *asker {
// sign-in code waits for approval in Equipo; expired and refused: that code
// can no longer be approved; failed: Base could not keep the bearer it got; ready: a live bearer; reconnect: Equipo
// refused the bearer or it expired; unavailable: Equipo did not answer.
+// Norunner and oldrunner are ready, but the person has no runner that can
+// answer the Assistant (none, or one too old): the conversation shows,
+// with a note saying so.
const (
- askConnect = "connect"
- askPending = "pending"
- askExpired = "expired"
- askRefused = "refused"
- askFailed = "failed"
- askReady = "ready"
- askReconnect = "reconnect"
- askUnavailable = "unavailable"
+ askConnect = "connect"
+ askPending = "pending"
+ askExpired = "expired"
+ askRefused = "refused"
+ askFailed = "failed"
+ askReady = "ready"
+ askReconnect = "reconnect"
+ askUnavailable = "unavailable"
+ askNoRunner = "norunner"
+ askRunnerTooOld = "oldrunner"
)
+// chatting reports whether state shows the conversation.
+func chatting(state string) bool {
+ return state == askReady || state == askNoRunner || state == askRunnerTooOld
+}
+
// deviceSecrets is what Base keeps sealed for a member's Equipo device:
// the Ed25519 seed, the device secret, the challenge and the nonce it
// proves with (kept, so a lost exchange answer can be asked for again),
@@ -106,10 +120,15 @@ func (a *app) askLink(ctx context.Context, me store.Member) (store.EquipoLink, d
}
// askLost records that Equipo refused the bearer of the member's device
-// dev, unless the link has moved on to another device since.
+// dev, unless the link has moved on to another device since, and forgets
+// the member's host token: Equipo no longer speaks for them.
func (a *app) askLost(ctx context.Context, me store.Member, dev string) {
if err := store.SetEquipoLinkState(ctx, a.db, me.ID, dev, store.EquipoLost); err != nil {
a.logger.Error("ask: mark lost", "err", err)
+ return
+ }
+ if l, ok, err := store.EquipoLinkFor(ctx, a.db, me.ID); err == nil && ok && l.DeviceID == dev {
+ a.dropHost(ctx, me)
}
}
@@ -126,6 +145,9 @@ type askView struct {
Status string
Key string
Problem string
+ // Text is what the person wrote and Equipo did not take, kept in the
+ // field.
+ Text string
}
// Shows reports whether the block for states (space-separated) shows now.
@@ -182,19 +204,32 @@ func (v *askView) fill(s equipo.Snapshot) {
}
// askSnapshot reads the member's conversation into v, moving v.State to
-// reconnect or unavailable when Equipo refuses or does not answer.
+// reconnect or unavailable when Equipo refuses or does not answer, and to
+// norunner when the person has no runner that can answer. Once Equipo
+// has answered, it records who the bearer speaks for, and registers the
+// member's host if Equipo does not hold it yet.
func (a *app) askSnapshot(r *http.Request, me store.Member, l store.EquipoLink, token string, v *askView) int64 {
s, err := a.ask.client.Snapshot(r.Context(), token)
switch {
case errors.Is(err, equipo.ErrUnauthenticated):
a.askLost(r.Context(), me, l.DeviceID)
v.State = askReconnect
+ return 0
case err != nil:
a.logger.Warn("ask: snapshot", "err", err)
v.State = askUnavailable
- default:
- v.fill(s)
+ return 0
+ }
+ v.fill(s)
+ if !s.Available {
+ v.State = askNoRunner
}
+ if s.Me.Address != "" && s.Me.Address != l.Person {
+ if err := store.SetEquipoPerson(r.Context(), a.db, me.ID, l.DeviceID, s.Me.Address); err != nil {
+ a.logger.Error("ask: equipo person", "err", err)
+ }
+ }
+ a.hostFor(r.Context(), me, token, false)
return s.Cursor
}
@@ -224,6 +259,29 @@ func (a *app) askPageView(w http.ResponseWriter, r *http.Request) {
a.render(w, r, "ask", askPage{Name: a.cfg.Name, Ask: v})
}
+// askRunnerPage answers a form Equipo refused for want of a runner (state
+// norunner or oldrunner): /ask as it is now, with that note, and the
+// person's text and its key kept in the field, so sending it again is
+// the same message.
+func (a *app) askRunnerPage(w http.ResponseWriter, r *http.Request, c askConn, state string) {
+ l, _, _, err := a.askLink(r.Context(), c.me)
+ if err != nil {
+ a.logger.Error("ask: link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ v := a.newAskView(askReady, "ask")
+ a.askSnapshot(r, c.me, l, c.token, &v)
+ if chatting(v.State) {
+ v.State = state
+ }
+ v.Text, v.Key = r.PostFormValue("text"), askKey(r.PostFormValue("key"))
+ w.Header().Set("Cache-Control", "no-store")
+ if err := a.pages.PageTheme(w, http.StatusConflict, "ask", askPage{Name: a.cfg.Name, Ask: v}, themeOf(r)); err != nil {
+ a.logger.Error("render", "page", "ask", "err", err)
+ }
+}
+
// askStateJSON is GET /ask/state: what the panel draws, and the cursor its
// event stream starts after.
func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
index 6221915..a49c888 100644
--- a/internal/web/ask_connect.go
+++ b/internal/web/ask_connect.go
@@ -7,6 +7,7 @@ import (
"errors"
"net/http"
"strings"
+ "sync"
"time"
"amadan.net/carlos/base/internal/equipo"
@@ -47,6 +48,9 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
if old, sec, state, err := a.askLink(ctx, me); err == nil && state == askReady {
a.revoke(ctx, old, sec)
}
+ // A new connection may be another Equipo person: until it is ready,
+ // no one holds a host token for this member.
+ a.dropHost(ctx, me)
pub, key, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
a.fail(w, err)
@@ -203,6 +207,7 @@ func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec
if err == nil {
var stored bool
if stored, err = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision); stored {
+ a.hostFor(ctx, me, cred.Token, true)
return askReady
}
}
@@ -250,9 +255,59 @@ func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) {
a.fail(w, err)
return
}
+ a.dropHost(r.Context(), me)
http.Redirect(w, r, "/settings", http.StatusSeeOther)
}
+// registerHost gives Equipo a new host token for the member, with their
+// bearer token: where Base's operations live (Base's own origin) and what
+// the Assistant presents to call them for this member. The new token
+// replaces the member's last one, which names nobody from then on.
+func (a *app) registerHost(ctx context.Context, me store.Member, token string) error {
+ host, err := store.MintHostToken(ctx, a.db, me.ID)
+ if err != nil {
+ return err
+ }
+ if err := a.ask.client.RegisterHost(ctx, token, a.cfg.Origin, host); err != nil {
+ return err
+ }
+ return store.MarkHostRegistered(ctx, a.db, me.ID)
+}
+
+// hostFor registers the member's host with Equipo: always when fresh (a
+// connection that just became ready), else only if Equipo does not hold
+// their current token yet. One registration runs per member at a time,
+// so two reads cannot leave Equipo holding a token Base has replaced. A
+// failure is logged (never a token) and tried again on the next read: it
+// neither breaks the chat nor disconnects anyone.
+func (a *app) hostFor(ctx context.Context, me store.Member, token string, fresh bool) {
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout)
+ defer cancel()
+ mu, _ := a.ask.hosts.LoadOrStore(me.ID, &sync.Mutex{})
+ mu.(*sync.Mutex).Lock()
+ defer mu.(*sync.Mutex).Unlock()
+ if !fresh {
+ done, err := store.HostRegistered(ctx, a.db, me.ID)
+ if err != nil {
+ a.logger.Error("ask: host registered", "err", err)
+ return
+ }
+ if done {
+ return
+ }
+ }
+ if err := a.registerHost(ctx, me, token); err != nil {
+ a.logger.Warn("ask: register host", "err", err)
+ }
+}
+
+// dropHost forgets the member's host token, so it names nobody.
+func (a *app) dropHost(ctx context.Context, me store.Member) {
+ if err := store.DeleteHostToken(context.WithoutCancel(ctx), a.db, me.ID); err != nil {
+ a.logger.Error("ask: forget host token", "err", err)
+ }
+}
+
func (a *app) renderConnect(w http.ResponseWriter, r *http.Request, status int, v connectView) {
v.Name, v.Label, v.Back = a.cfg.Name, a.ask.label, askNext[v.Next]
w.Header().Set("Cache-Control", "no-store")
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
index f9655a9..ce31604 100644
--- a/internal/web/ask_relay.go
+++ b/internal/web/ask_relay.go
@@ -60,7 +60,9 @@ type askConn struct {
}
// askDone finishes a relayed write. A 401 from Equipo means the member must
-// reconnect; a 409 (a card already answered, a turn already ended) is
+// reconnect; a 409 no_runner or runner_too_old means the person has no
+// runner that can answer (norunner, oldrunner), and what they wrote stays
+// unsent; any other 409 (a card already answered, a turn already ended) is
// stale, and the conversation as it is now says so; anything else is a
// problem to try again.
func (a *app) askDone(w http.ResponseWriter, r *http.Request, c askConn, err error, out any) {
@@ -70,12 +72,20 @@ func (a *app) askDone(w http.ResponseWriter, r *http.Request, c askConn, err err
case errors.Is(err, equipo.ErrUnauthenticated):
a.askLost(r.Context(), c.me, c.device)
status, state = http.StatusUnauthorized, askReconnect
+ case errors.Is(err, equipo.ErrNoRunner):
+ status, state = http.StatusConflict, askNoRunner
+ case errors.Is(err, equipo.ErrRunnerTooOld):
+ status, state = http.StatusConflict, askRunnerTooOld
case errors.As(err, &e) && e.Status == http.StatusConflict:
status = http.StatusConflict
case err != nil:
a.logger.Warn("ask: relay", "err", err)
status, state = http.StatusBadGateway, askUnavailable
}
+ if !wantsJSON(r) && (state == askNoRunner || state == askRunnerTooOld) {
+ a.askRunnerPage(w, r, c, state)
+ return
+ }
if !wantsJSON(r) {
target := "/ask"
if status == http.StatusBadGateway {
diff --git a/internal/web/settings.go b/internal/web/settings.go
index c88c0b5..46771f7 100644
--- a/internal/web/settings.go
+++ b/internal/web/settings.go
@@ -28,8 +28,9 @@ type settingsPage struct {
Oficina, Connect bool
ConnectLabel string
// Equipo is the member's Equipo connection (connect, pending, ready or
- // reconnect), empty with the chat off.
- Equipo string
+ // reconnect), empty with the chat off. EquipoPerson is the Equipo
+ // address it speaks for, once Base has read it.
+ Equipo, EquipoPerson string
// Themes are the Appearance choices, the member's pressed.
Themes []themeChoice
}
@@ -74,13 +75,16 @@ func (a *app) settings(w http.ResponseWriter, r *http.Request) {
page.Themes = append(page.Themes, themeChoice{Value: c.value, Label: c.label, On: c.stored == me.Theme})
}
if a.ask != nil {
- _, _, state, err := a.askLink(r.Context(), me)
+ l, _, state, err := a.askLink(r.Context(), me)
if err != nil {
a.logger.Error("settings: equipo link", "err", err)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
page.Equipo = homeState(state)
+ if state == askReady {
+ page.EquipoPerson = l.Person
+ }
}
if a.oficina != nil {
page.Oficina = true
diff --git a/internal/web/templates/ask_connect.html b/internal/web/templates/ask_connect.html
index 2d06b5e..3204dc9 100644
--- a/internal/web/templates/ask_connect.html
+++ b/internal/web/templates/ask_connect.html
@@ -9,7 +9,7 @@
<p class="alt">Once you've approved it, come back and press Check again.</p>
<form method="post" action="/ask/connect/check" data-connect-check><input type="hidden" name="next" value="{{.Next}}"><button class="btn ghost full" type="submit">Check again</button></form>
<script type="module" src="{{asset "static/ask-connect.js"}}"></script>
-{{else}}<p>{{if eq .State "expired"}}That code expired. Start again to get a new one.{{else if eq .State "refused"}}Equipo didn't accept that request. Start again.{{else if eq .State "failed"}}That didn't work. Start again.{{else if eq .State "reconnect"}}Base's connection to Equipo expired or was removed.{{else}}Connect Equipo, and its coordinator answers you in Base.{{end}}</p>
+{{else}}<p>{{if eq .State "expired"}}That code expired. Start again to get a new one.{{else if eq .State "refused"}}Equipo didn't accept that request. Start again.{{else if eq .State "failed"}}That didn't work. Start again.{{else if eq .State "reconnect"}}Base's connection to Equipo expired or was removed.{{else}}Connect Equipo, and its Assistant answers you in Base.{{end}}</p>
<form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn full" type="submit">{{if eq .State "connect"}}Connect Equipo{{else if eq .State "reconnect"}}Reconnect Equipo{{else}}Start again{{end}}</button></form>
<a class="btn ghost full" href="{{.Back}}">Back</a>
{{end}}{{with .Problem}}<p class="status" role="alert">{{.}}</p>{{end}}
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html
index 363b1f7..08debe4 100644
--- a/internal/web/templates/partials/chat.html
+++ b/internal/web/templates/partials/chat.html
@@ -11,7 +11,7 @@
{{- if and .Open .Options}}<form class="choices" method="post" action="/ask/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="key" value="{{newKey}}">{{range .Options}}<button class="btn ghost" type="submit" name="choice" value="{{.Value}}">{{.Label}}</button>{{end}}</form>{{end}}
{{- with .Result}}<p class="card-state">{{.}}</p>{{end}}</li>{{end}}
{{define "ask-body"}}<div class="ask-note" data-when="connect"{{if not (.Shows "connect")}} hidden{{end}}>
-<p>Connect Equipo, and its coordinator answers you here.</p>
+<p>Connect Equipo, and its Assistant answers you here.</p>
<form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn" type="submit">Connect Equipo</button></form>
</div>
<div class="ask-note" data-when="pending"{{if not (.Shows "pending")}} hidden{{end}}>
@@ -25,7 +25,7 @@
<div class="ask-note" data-when="unavailable"{{if not (.Shows "unavailable")}} hidden{{end}}>
<p>Equipo isn't answering. Try again in a minute.</p>
</div>
-<div class="ask-chat" data-when="ready"{{if not (.Shows "ready")}} hidden{{end}}>
+<div class="ask-chat" data-when="ready norunner oldrunner"{{if not (.Shows "ready norunner oldrunner")}} hidden{{end}}>
<div class="log"><ol class="thread" role="log" aria-label="Conversation">
{{range .Messages}}{{if eq .Role "person"}}<li class="msg person" data-id="{{.ID}}">{{.Text}}</li>{{else}}<li class="msg coordinator" data-id="{{.ID}}">{{$.Rich .Text}}</li>{{end}}
{{end}}{{range .Cards}}{{template "ask-card" .}}
@@ -33,9 +33,11 @@
<button class="jump" type="button" hidden>Jump to latest</button></div>
<p class="ask-empty" data-empty{{if or .Messages .Cards}} hidden{{end}}>Ask about your work, or ask Base to get something done.</p>
{{with .Problem}}<p class="ask-problem" role="alert">{{.}}</p>{{end}}
+{{/* Without a runner that can answer, the conversation shows and says so; what the person wrote stays in the field. */}}<p class="ask-problem ask-runner" data-when="norunner"{{if not (.Shows "norunner")}} hidden{{end}} role="alert">Ask Base needs a runner of your own to answer. <a href="{{.Equipo}}" target="_blank" rel="noopener">Add one in Equipo</a>, then try again.</p>
+<p class="ask-problem ask-runner" data-when="oldrunner"{{if not (.Shows "oldrunner")}} hidden{{end}} role="alert">Your runner needs an update for this. <a href="{{.Equipo}}" target="_blank" rel="noopener">Update it in Equipo</a>, then try again.</p>
<div class="ask-foot">
<p class="ask-status" role="status">{{.Status}}</p>
<form class="stop" method="post" action="{{with .Turn}}/ask/turns/{{.ID}}/cancel{{else}}/ask{{end}}"{{if not .Turn}} hidden{{end}}><input type="hidden" name="key" value="{{newKey}}"><button class="btn ghost" type="submit">Stop</button></form>
</div>
-<form class="composer" method="post" action="/ask/messages"><input type="hidden" name="key" value="{{.Key}}"><label class="sr-only" for="ask-text">Message</label><textarea class="input" id="ask-text" name="text" rows="1" required maxlength="16000" placeholder="Ask Base anything"></textarea><button class="btn" type="submit">Send</button></form>
+<form class="composer" method="post" action="/ask/messages"><input type="hidden" name="key" value="{{.Key}}"><label class="sr-only" for="ask-text">Message</label><textarea class="input" id="ask-text" name="text" rows="1" required maxlength="16000" placeholder="Ask Base anything">{{.Text}}</textarea><button class="btn" type="submit">Send</button></form>
</div>{{end}}
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html
index cfc36b5..626ae4b 100644
--- a/internal/web/templates/settings.html
+++ b/internal/web/templates/settings.html
@@ -8,7 +8,7 @@
<li><div class="who">Signed in as<small>{{.Address}}</small></div></li>
<li><div class="who" id="appearance">Appearance</div><form class="segmented" method="post" action="/settings/appearance" role="group" aria-labelledby="appearance">{{range .Themes}}<button type="submit" name="theme" value="{{.Value}}" aria-pressed="{{.On}}">{{.Label}}</button>{{end}}</form></li>
<li><div class="who">Passkeys<small id="passkeys">{{if .Passkeys}}{{.Passkeys}} added{{else}}None yet{{end}}</small></div>{{if .CanAddPasskey}}{{/* Hidden until the script finds the browser can make a passkey, so with scripts off there is no dead button. */}}<button class="btn ghost" type="button" hidden data-passkey-add data-module="{{.ModuleURL}}" data-begin="{{.RegisterBegin}}" data-finish="{{.RegisterEnd}}" data-rp-name="{{.Name}}" data-user-id="{{.UserID}}" data-user-name="{{.Address}}" data-done="/settings?passkey=added" data-cancelled="No passkey was added." data-failed="That didn't work. Try again." aria-describedby="passkey-msg">Add a passkey</button>{{end}}</li>
-{{with .Equipo}}<li><div class="who">Equipo<small>{{if eq . "ready"}}Connected{{else if eq . "pending"}}Waiting for your approval in Equipo{{else if eq . "reconnect"}}Connection expired or removed{{else}}Not connected{{end}}</small></div>{{if eq . "ready"}}<form method="post" action="/ask/disconnect"><button class="btn ghost" type="submit">Disconnect</button></form>{{else if eq . "pending"}}<a class="btn ghost" href="/ask/connect?next=settings">Finish connecting</a>{{else}}<form method="post" action="/ask/connect"><input type="hidden" name="next" value="settings"><button class="btn ghost" type="submit">{{if eq . "reconnect"}}Reconnect Equipo{{else}}Connect Equipo{{end}}</button></form>{{end}}</li>
+{{with .Equipo}}<li><div class="who">Equipo<small>{{if eq . "ready"}}{{with $.EquipoPerson}}Connected as {{.}}{{else}}Connected{{end}}{{else if eq . "pending"}}Waiting for your approval in Equipo{{else if eq . "reconnect"}}Connection expired or removed{{else}}Not connected{{end}}</small></div>{{if eq . "ready"}}<form method="post" action="/ask/disconnect"><button class="btn ghost" type="submit">Disconnect</button></form>{{else if eq . "pending"}}<a class="btn ghost" href="/ask/connect?next=settings">Finish connecting</a>{{else}}<form method="post" action="/ask/connect"><input type="hidden" name="next" value="settings"><button class="btn ghost" type="submit">{{if eq . "reconnect"}}Reconnect Equipo{{else}}Connect Equipo{{end}}</button></form>{{end}}</li>
{{end}}{{if .Connect}}<li><div class="who">Oficina account<small>Not connected</small></div><a class="btn ghost" href="/account/home">{{.ConnectLabel}}</a></li>
{{end}}</ul>
{{if .PasskeyAdded}}<p class="status" role="status" id="passkey-added">Passkey added. Next time, sign in with it.</p>
diff --git a/internal/webtest/ask_test.go b/internal/webtest/ask_test.go
index 9766bfc..764a545 100644
--- a/internal/webtest/ask_test.go
+++ b/internal/webtest/ask_test.go
@@ -59,6 +59,18 @@ func (a *testApp) pollable() {
// Connect Equipo, approve the code in Equipo, come back. It returns the
// bearer Equipo issued.
func (a *testApp) connectEquipo(f *equipotest.Fake) string {
+ a.t.Helper()
+ a.approveEquipo(f)
+ tokens := f.Tokens()
+ if len(tokens) != 1 {
+ a.t.Fatalf("tokens: %v", tokens)
+ }
+ return tokens[0]
+}
+
+// approveEquipo is connectEquipo without asking which bearer Equipo
+// issued: it connects again just as well.
+func (a *testApp) approveEquipo(f *equipotest.Fake) {
a.t.Helper()
r := a.post("/ask/connect", url.Values{"next": {"settings"}})
if r.Code != 303 || r.Location() != "/ask/connect?next=settings" {
@@ -76,11 +88,6 @@ func (a *testApp) connectEquipo(f *equipotest.Fake) string {
if r := a.check("settings"); r.Code != 303 || r.Location() != "/settings" {
a.t.Fatalf("after approval: %d %q\n%s", r.Code, r.Location(), r.Body)
}
- tokens := f.Tokens()
- if len(tokens) != 1 {
- a.t.Fatalf("tokens: %v", tokens)
- }
- return tokens[0]
}
// check presses "Check again" on the connect page.
@@ -572,6 +579,9 @@ func TestDuplicateExchangeKeepsConnection(t *testing.T) {
if f.Revoked(l.DeviceID) {
t.Fatal("a duplicate success revoked the live connection")
}
+ if n := len(f.Hosts()); n != 0 {
+ t.Fatalf("a duplicate success registered the host again: %d PUTs", n)
+ }
if got, found, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); !found || got.State != store.EquipoConnected {
t.Fatalf("link: %+v %v", got, found)
}
@@ -751,3 +761,269 @@ func TestAskAnswerRelaysValue(t *testing.T) {
t.Fatalf("after the 409 the card is at revision %q, want 2", fresh.Get("revision"))
}
}
+
+// hostOf is the host token in Equipo's PUT host call i (the last when
+// i is -1), with the bearer and origin it came with.
+func hostOf(t *testing.T, f *equipotest.Fake, i int) (token, bearer, origin string) {
+ t.Helper()
+ hosts := f.Hosts()
+ if i < 0 {
+ i = len(hosts) + i
+ }
+ if i < 0 || i >= len(hosts) {
+ t.Fatalf("PUT host %d of %d", i, len(hosts))
+ }
+ var in struct{ Origin, Token string }
+ if hosts[i].Method != http.MethodPut || json.Unmarshal([]byte(hosts[i].Body), &in) != nil {
+ t.Fatalf("PUT host: %+v", hosts[i])
+ }
+ return in.Token, strings.TrimPrefix(hosts[i].Header.Get("Authorization"), "Bearer "), in.Origin
+}
+
+// hostMember is the member host token names, "" for nobody.
+func (a *testApp) hostMember(token string) string {
+ a.t.Helper()
+ m, ok, err := store.MemberByHostToken(context.Background(), a.DB, token)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ if !ok {
+ return ""
+ }
+ return m.ID
+}
+
+func (a *testApp) hostRegistered() bool {
+ a.t.Helper()
+ ok, err := store.HostRegistered(context.Background(), a.DB, a.ownerID())
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ return ok
+}
+
+// quiet fails if the app logged any of secrets.
+func (a *testApp) quiet(secrets ...string) {
+ a.t.Helper()
+ logs := a.logs.String()
+ for _, s := range secrets {
+ if s != "" && strings.Contains(logs, s) {
+ a.t.Fatalf("the log carried a secret:\n%s", logs)
+ }
+ }
+}
+
+// Once the member's connection is ready, Base mints them a host token and
+// gives it to Equipo, with their bearer and Base's own origin: once.
+// Reconnecting gives Equipo a new one, and the old one names nobody.
+func TestConnectRegistersHost(t *testing.T) {
+ a, f := newAskApp(t)
+ bearer := a.connectEquipo(f)
+ if n := len(f.Hosts()); n != 1 {
+ t.Fatalf("PUT host after connecting: %d, want 1", n)
+ }
+ first, sentWith, origin := hostOf(t, f, 0)
+ if sentWith != bearer || origin != testOrigin || !strings.HasPrefix(first, "bh_") {
+ t.Fatalf("PUT host: bearer ok %v, origin %q, token %q", sentWith == bearer, origin, first)
+ }
+ if a.hostMember(first) != a.ownerID() || !a.hostRegistered() {
+ t.Fatalf("host token names %q, registered %v", a.hostMember(first), a.hostRegistered())
+ }
+ a.get("/ask")
+ a.get("/ask/state")
+ if n := len(f.Hosts()); n != 1 {
+ t.Fatalf("reading the chat registered again: %d PUTs", n)
+ }
+
+ a.approveEquipo(f)
+ if n := len(f.Hosts()); n != 2 {
+ t.Fatalf("PUT host after reconnecting: %d, want 2", n)
+ }
+ second, sentWith, _ := hostOf(t, f, 1)
+ if second == first || sentWith == bearer {
+ t.Fatal("reconnecting registered the old token or with the old bearer")
+ }
+ if a.hostMember(first) != "" || a.hostMember(second) != a.ownerID() {
+ t.Fatalf("old token names %q, new names %q", a.hostMember(first), a.hostMember(second))
+ }
+ a.noLeak(first)
+ a.noLeak(second)
+ a.quiet(first, second, bearer, sentWith)
+}
+
+// A member who connected before Base registered hosts has no host token:
+// their next read of the chat registers one, once.
+func TestHostRegisteredLazily(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ if err := store.DeleteHostToken(context.Background(), a.DB, a.ownerID()); err != nil {
+ t.Fatal(err)
+ }
+ if page := a.get("/ask"); page.Code != 200 || len(f.Hosts()) != 2 {
+ t.Fatalf("/ask: %d, PUTs %d, want 2", page.Code, len(f.Hosts()))
+ }
+ token, _, _ := hostOf(t, f, -1)
+ if a.hostMember(token) != a.ownerID() || !a.hostRegistered() {
+ t.Fatal("the lazy registration did not take")
+ }
+ a.get("/ask/state")
+ a.get("/ask")
+ if n := len(f.Hosts()); n != 2 {
+ t.Fatalf("registered again: %d PUTs", n)
+ }
+}
+
+// A refused registration does not break the chat or disconnect anyone: it
+// is logged (no token in it), and the next read tries again.
+func TestHostRegistrationFailureIsRetried(t *testing.T) {
+ a, f := newAskApp(t)
+ f.RefuseHost(http.StatusForbidden, "host_not_allowed")
+ bearer := a.connectEquipo(f)
+ if n := len(f.Hosts()); n != 1 || a.hostRegistered() {
+ t.Fatalf("PUTs %d, registered %v", n, a.hostRegistered())
+ }
+ if n := strings.Count(a.logs.String(), "host_not_allowed"); n != 1 {
+ t.Fatalf("logged host_not_allowed %d times, want 1:\n%s", n, a.logs.String())
+ }
+ if s := a.get("/settings").Body; !strings.Contains(s, `action="/ask/disconnect"`) {
+ t.Fatalf("a refused registration disconnected the member:\n%s", s)
+ }
+ page := a.get("/ask")
+ if page.Code != 200 || !strings.Contains(page.Body, `data-state="ready"`) || len(f.Hosts()) != 2 {
+ t.Fatalf("/ask: %d, PUTs %d\n%s", page.Code, len(f.Hosts()), page.Body)
+ }
+ if n := strings.Count(a.logs.String(), "host_not_allowed"); n != 2 {
+ t.Fatalf("logged host_not_allowed %d times after two tries", n)
+ }
+ if r := a.post("/ask/messages", url.Values{"text": {"What can I do"}}); r.Code != 303 || len(f.Calls("/api/v1/assistant/messages")) != 1 {
+ t.Fatalf("send: %d", r.Code)
+ }
+ if l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); l.State != store.EquipoConnected {
+ t.Fatalf("link %q", l.State)
+ }
+
+ f.RefuseHost(http.StatusServiceUnavailable, "unavailable")
+ a.get("/ask/state")
+ if len(f.Hosts()) != 3 || a.hostRegistered() {
+ t.Fatalf("PUTs %d, registered %v", len(f.Hosts()), a.hostRegistered())
+ }
+ f.RefuseHost(0, "")
+ a.get("/ask")
+ token, _, _ := hostOf(t, f, -1)
+ if len(f.Hosts()) != 4 || !a.hostRegistered() || a.hostMember(token) != a.ownerID() {
+ t.Fatalf("PUTs %d, registered %v", len(f.Hosts()), a.hostRegistered())
+ }
+ a.get("/ask")
+ if n := len(f.Hosts()); n != 4 {
+ t.Fatalf("registered again once it took: %d PUTs", n)
+ }
+ var tried []string
+ for i := range f.Hosts() {
+ tok, _, _ := hostOf(t, f, i)
+ tried = append(tried, tok)
+ }
+ a.quiet(append(tried, bearer)...)
+}
+
+// Disconnecting, and Equipo refusing the bearer, both forget the member's
+// host token.
+func TestDisconnectDropsHostToken(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ token, _, _ := hostOf(t, f, -1)
+ if r := a.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ if a.hostMember(token) != "" {
+ t.Fatal("the host token outlived Disconnect")
+ }
+
+ a.approveEquipo(f)
+ token, _, _ = hostOf(t, f, -1)
+ if a.hostMember(token) != a.ownerID() {
+ t.Fatal("connecting again registered nothing")
+ }
+ f.RevokeAll()
+ if page := a.get("/ask").Body; !strings.Contains(page, ">Reconnect Equipo</button>") {
+ t.Fatalf("no reconnect:\n%s", page)
+ }
+ if a.hostMember(token) != "" {
+ t.Fatal("the host token outlived a refused bearer")
+ }
+}
+
+// noteFor is the runner note shown for state, with its attributes.
+func noteFor(t *testing.T, page, state string) string {
+ t.Helper()
+ m := regexp.MustCompile(`(?s)<p class="ask-problem ask-runner" data-when="` + state + `"[^>]*>.*?</p>`).FindString(page)
+ if m == "" {
+ t.Fatalf("no %s note in:\n%s", state, page)
+ }
+ return m
+}
+
+// postJSON posts form as the panel's script does.
+func (a *testApp) postJSON(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", a.origin)
+ req.Header.Set("Accept", "application/json")
+ return a.do(req)
+}
+
+// Without a runner the chat says so, links to Equipo, keeps what the
+// person wrote and shows no message; a runner too old has its own note.
+// The panel's script hears the state.
+func TestAskNoRunner(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ f.Say("Hello.")
+ f.NoRunner()
+ page := a.get("/ask").Body
+ note := noteFor(t, page, "norunner")
+ if strings.Contains(note, " hidden") || !strings.Contains(note, `href="`+f.URL+`/"`) ||
+ !strings.Contains(page, `data-state="norunner"`) || !strings.Contains(page, "Hello.") {
+ t.Fatalf("no-runner note:\n%s", page)
+ }
+ if !strings.Contains(noteFor(t, page, "oldrunner"), " hidden") {
+ t.Fatal("the runner-too-old note shows")
+ }
+ var st struct{ State string }
+ if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "norunner" {
+ t.Fatalf("state: %s", r.Body)
+ }
+
+ // Scripts off: the page comes back with the text in the field, the
+ // same key, and no message.
+ r := a.post("/ask/messages", url.Values{"text": {"Build me a quick website"}, "key": {"k-norunner"}})
+ if r.Code != http.StatusConflict || strings.Contains(noteFor(t, r.Body, "norunner"), " hidden") ||
+ !strings.Contains(r.Body, `>Build me a quick website</textarea>`) || strings.Contains(r.Body, `<li class="msg person"`) ||
+ formFields(t, r.Body, "/ask/messages").Get("key") != "k-norunner" {
+ t.Fatalf("send without a runner: %d\n%s", r.Code, r.Body)
+ }
+ // Scripts on: the state.
+ if r := a.postJSON("/ask/messages", url.Values{"text": {"Build me a quick website"}, "key": {"k-json"}}); r.Code != http.StatusConflict ||
+ strings.TrimSpace(r.Body) != `{"state":"norunner"}` {
+ t.Fatalf("JSON send: %d %s", r.Code, r.Body)
+ }
+ q := f.AskQuestion("Which one?", "red", "blue")
+ if r := a.postJSON("/ask/cards/"+q+"/answer", url.Values{"choice": {"red"}, "revision": {"1"}, "key": {"k-card"}}); r.Code != http.StatusConflict ||
+ strings.TrimSpace(r.Body) != `{"state":"norunner"}` {
+ t.Fatalf("JSON answer: %d %s", r.Code, r.Body)
+ }
+
+ f.RunnerTooOld()
+ r = a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {"k-old"}})
+ if r.Code != http.StatusConflict || strings.Contains(noteFor(t, r.Body, "oldrunner"), " hidden") ||
+ !strings.Contains(noteFor(t, r.Body, "norunner"), " hidden") || !strings.Contains(r.Body, `>What can I do</textarea>`) {
+ t.Fatalf("send with a runner too old: %d\n%s", r.Code, r.Body)
+ }
+ if r := a.postJSON("/ask/messages", url.Values{"text": {"What can I do"}, "key": {"k-old-json"}}); r.Code != http.StatusConflict ||
+ strings.TrimSpace(r.Body) != `{"state":"oldrunner"}` {
+ t.Fatalf("JSON send: %d %s", r.Code, r.Body)
+ }
+ if strings.Contains(a.get("/ask").Body, `<li class="msg person"`) {
+ t.Fatal("a refused message shows")
+ }
+}
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go
index a300c77..4a065a8 100644
--- a/internal/webtest/harness_test.go
+++ b/internal/webtest/harness_test.go
@@ -3,6 +3,7 @@
package webtest
import (
+ "bytes"
"context"
"database/sql"
"errors"
@@ -94,6 +95,26 @@ type testApp struct {
seen []Resp
// seenMu guards seen; a pointer, so newBrowser's copy shares it.
seenMu *sync.Mutex
+ // logs is everything the app logged.
+ logs *logBuffer
+}
+
+// logBuffer is the app's log, written by its handlers and read by a test.
+type logBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (l *logBuffer) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.Write(p)
+}
+
+func (l *logBuffer) String() string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.String()
}
// newApp builds the whole app per test over its own copy of the migrated
@@ -116,7 +137,8 @@ func newAppBuilt(t *testing.T, build func(*sql.DB, config.Config) web.Installer,
// newAppConfigured is newAppBuilt with a last say over the configuration.
func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location, tweak func(*config.Config)) *testApp {
t.Helper()
- logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ logs := &logBuffer{}
+ logger := slog.New(slog.NewTextHandler(logs, nil))
d, err := db.Open(schema.Path(t), logger)
if err != nil {
t.Fatalf("db.Open: %v", err)
@@ -139,7 +161,7 @@ func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Insta
t.Cleanup(srv.Close)
jar, _ := cookiejar.New(nil)
client := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
- return &testApp{seenMu: &sync.Mutex{}, t: t, srv: srv, client: client, mail: mailer, DB: d.Writer(), base: srv.URL, origin: testOrigin, localSignin: "/signin"}
+ return &testApp{seenMu: &sync.Mutex{}, logs: logs, t: t, srv: srv, client: client, mail: mailer, DB: d.Writer(), base: srv.URL, origin: testOrigin, localSignin: "/signin"}
}
func (a *testApp) do(req *http.Request) Resp {
diff --git a/internal/webtest/settings_test.go b/internal/webtest/settings_test.go
index 95d467e..1f055a5 100644
--- a/internal/webtest/settings_test.go
+++ b/internal/webtest/settings_test.go
@@ -117,3 +117,26 @@ func TestSettingsAppearance(t *testing.T) {
t.Error("the sign-in page forces a theme")
}
}
+
+// Settings says which Equipo person the member is connected as, once Base
+// has read it from Equipo, and keeps up when it changes.
+func TestSettingsShowsEquipoPerson(t *testing.T) {
+ a, f := newAskApp(t)
+ f.SetAddress("ana@equipo.example")
+ a.connectEquipo(f)
+ a.get("/ask")
+ if s := a.get("/settings").Body; !strings.Contains(s, "Equipo<small>Connected as ana@equipo.example</small>") {
+ t.Fatalf("Settings:\n%s", s)
+ }
+ f.SetAddress("bea@equipo.example")
+ a.get("/ask/state")
+ if s := a.get("/settings").Body; !strings.Contains(s, "Equipo<small>Connected as bea@equipo.example</small>") {
+ t.Fatalf("Settings after a change:\n%s", s)
+ }
+ // Connecting again may be someone else: until Base reads who, it says
+ // only that it is connected.
+ a.approveEquipo(f)
+ if s := a.get("/settings").Body; !strings.Contains(s, "Equipo<small>Connected</small>") {
+ t.Fatalf("Settings after reconnecting:\n%s", s)
+ }
+}