oficina / base Public

Point Ask Base at Equipo's Assistant and draw its cards generically

Every chat call (snapshot, messages, cancel, card answers, events) now
goes under /api/v1/assistant, and RegisterHost puts the member's Base
host with PUT /api/v1/assistant/host (Task 13 decides when). The
snapshot carries me.address and available; no_runner and
runner_too_old are new 409 sentinels.

Cards are Equipo's generic Assistant cards: question, confirm, outcome
and connect, with options as {value, label}, links and a result line.
Card.Clean keeps only those kinds and only web links; Shown is open, or
ended with a result. The template and ask.js draw a button per option
(its label, posting its value), a link per link and the result, with no
words of Base's own, and no /tasks/ links in the Assistant's lines.

An outcome card's answer starts no turn: Equipo sends an empty message
and a zero turn, which Base passes on as null so the panel adds no
bubble and waits for nothing. The fake Equipo serves only the
Assistant's routes, so a call to an old path fails the tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 35754bab1193d97a3482d61c31a1920322b8a82b parent 20c419e
19 files changed, +615 −572
  • docs/copy-pending.md +2 −0
  • internal/browsertest/ask_test.go +3 −3
  • internal/browsertest/cards_test.go +49 −76
  • internal/equipo/chat.go +90 −74
  • internal/equipo/equipo.go +9 −3
  • internal/equipo/equipo_test.go +129 −18
  • internal/equipo/equipotest/chat.go +106 −117
  • internal/equipo/equipotest/fake.go +5 −4
  • internal/look/static/app.css +1 −0
  • internal/look/static/ask.js +29 −52
  • internal/web/app.go +1 −2
  • internal/web/ask.go +4 −4
  • internal/web/ask_cards.go +9 −79
  • internal/web/ask_relay.go +20 −6
  • internal/web/relay_internal_test.go +13 −16
  • internal/web/rich_internal_test.go +25 −14
  • internal/web/templates/ask.html +1 −1
  • internal/web/templates/partials/chat.html +7 −8
  • internal/webtest/ask_test.go +112 −95
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index 0dcc79e..47a0b8f 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -322,3 +322,5 @@ Review 7 (pending): Base's operations for Equipo's Assistant. The Assistant read
| internal/operations/operations.go | Error message: input over 64 KiB (413 too_large) | The input is too large. |
| internal/operations/operations.go | Error message: input other than {} (422 invalid) | This operation takes no input. |
| 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.~~ |
diff --git a/internal/browsertest/ask_test.go b/internal/browsertest/ask_test.go
index 83c04b8..fae45c9 100644
--- a/internal/browsertest/ask_test.go
+++ b/internal/browsertest/ask_test.go
@@ -113,7 +113,7 @@ func TestAskPanelSendsOnce(t *testing.T) {
drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Build me a quick website"),
chromedp.Evaluate[chromedp.Void](`(() => { const b = document.querySelector("`+send+`"); b.click(); b.click(); })()`),
chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.person").length === 1`, chromedp.WithPollingTimeout(5*time.Second)))
- if n := len(f.Calls("/api/v1/messages")); n != 1 {
+ if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
t.Fatalf("a double press sent %d requests", n)
}
@@ -127,7 +127,7 @@ func TestAskPanelSendsOnce(t *testing.T) {
if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 2 {
t.Errorf("person messages shown: %d, want 2", got)
}
- calls := f.Calls("/api/v1/messages")
+ calls := f.Calls("/api/v1/assistant/messages")
if len(calls) != 3 || calls[1].Header.Get("Idempotency-Key") != calls[2].Header.Get("Idempotency-Key") ||
calls[0].Header.Get("Idempotency-Key") == calls[1].Header.Get("Idempotency-Key") {
t.Fatalf("keys: %v", keys(calls))
@@ -162,7 +162,7 @@ func TestAskPanel(t *testing.T) {
if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 1 {
t.Errorf("person messages shown: %d", got)
}
- if n := len(f.Calls("/api/v1/messages")); n != 1 {
+ if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
t.Errorf("messages sent to Equipo: %d", n)
}
if dir := os.Getenv("BASE_BROWSER_ARTIFACTS"); dir != "" {
diff --git a/internal/browsertest/cards_test.go b/internal/browsertest/cards_test.go
index 582a26e..0a1b1ed 100644
--- a/internal/browsertest/cards_test.go
+++ b/internal/browsertest/cards_test.go
@@ -3,103 +3,76 @@
package browsertest
import (
- "net/http"
"strconv"
+ "strings"
"testing"
"time"
"github.com/chromedp/chromedp"
"amadan.net/rastrillo/rastrillo/harness"
+
+ "amadan.net/carlos/base/internal/equipo"
)
-// The website demo in the panel: a merge card whose preview arrives, an
-// answer that turns out stale (re-read, not resent), and a publish card
-// through to published with its site.
-func TestAskWebsiteCards(t *testing.T) {
+// The Assistant's cards in the panel, drawn from their fields alone: an
+// open outcome card with its buttons and link keeps the conversation at
+// its newest line; answering it posts the option's value and brings no
+// bubble and no turn; a card that has ended shows its result and link;
+// a card of a kind Base does not draw never shows.
+func TestAskCardsInPanel(t *testing.T) {
rig, f := askBase(t)
openPanel(t, rig)
wait := func(js string) {
t.Helper()
drive(t, rig, chromedp.Poll[chromedp.Void](js, chromedp.WithPollingTimeout(10*time.Second)))
}
- merge := f.AskMerge("Quick website")
- card := `#ask-panel [data-card="` + merge + `"]`
- wait(`(() => { const c = document.querySelector(` + strconv.Quote(card) + `);
- return c && c.textContent.includes("Merge Quick website without checks?") &&
- [...c.querySelectorAll("button")].map(b => b.textContent).join("|") === "Merge|Wait for checks" })()`)
- f.SetPreview(merge, "https://eq-tk0001.devbox.test/", true)
- wait(`!!document.querySelector(` + strconv.Quote(card+` a.card-link[href="https://eq-tk0001.devbox.test/"][target="_blank"][rel="noopener"]`) + `)`)
- mobileShot(t, rig, "1-merge-preview")
-
- // The preview moved on without the panel seeing it: Merge gets a 409,
- // and the panel re-reads the conversation instead of resending.
- f.SetPreview(merge, "https://eq-tk0001.devbox.test/v2/", false)
- rig.Allow(http.MethodPost, "/ask/cards/"+merge+"/answer", http.StatusConflict)
- drive(t, rig, chromedp.Click(chromedp.CSS(card+` button[value="merge"]`)))
- wait(`!!document.querySelector(` + strconv.Quote(card+` input[name="revision"][value="3"]`) + `)`)
- if calls := f.Calls("/api/v1/cards/" + merge + "/answer"); len(calls) != 1 {
- t.Fatalf("a stale answer was sent %d times", len(calls))
- }
- drive(t, rig, chromedp.Click(chromedp.CSS(card+` button[value="merge"]`)))
- wait(`document.querySelector(` + strconv.Quote(card) + `).textContent.includes("Merging without checks.")`)
- if calls := f.Calls("/api/v1/cards/" + merge + "/answer"); len(calls) != 2 {
- t.Fatalf("answers: %d", len(calls))
+ for i := 1; i <= 20; i++ {
+ f.Say("Earlier line " + strconv.Itoa(i) + " of a long conversation.")
}
+ wait(`document.querySelectorAll("#ask-panel .thread > li").length >= 20`)
- publish := f.AskPublish("Quick website", "site-sample")
- pcard := `#ask-panel [data-card="` + publish + `"]`
- wait(`(() => { const c = document.querySelector(` + strconv.Quote(pcard) + `);
- return c && [...c.querySelectorAll("button")].map(b => b.textContent).join("|") === "Publish|Not now" })()`)
- mobileShot(t, rig, "2-publish-asked")
- drive(t, rig, chromedp.Click(chromedp.CSS(pcard+` button[value="publish"]`)))
- wait(`(() => { const c = document.querySelector(` + strconv.Quote(pcard) + `);
- return c && c.querySelector(".card-state")?.textContent === "Published" &&
- !!c.querySelector('a.card-link[href="https://site-sample.example.test/"][rel="noopener"]') })()`)
- // Equipo's line about it links the task (on Equipo) and the site.
- wait(`!!document.querySelector('#ask-panel .msg.coordinator a[href="` + f.URL + `/tasks/tk0001"]')`)
- f.Say("Try [this](javascript:alert(1)) or <img src=x onerror=alert(1)>.")
- wait(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent.includes("<img src=x"))`)
- if n := harness.Evaluate[int](rig, `document.querySelectorAll('#ask-panel a[href^="javascript"], #ask-panel .msg img').length`); n != 0 {
- t.Fatalf("unsafe markup rendered: %d", n)
+ options := []equipo.Option{{Value: "go", Label: "Go ahead"}, {Value: "later", Label: "Not yet"}}
+ preview := []equipo.Link{{Label: "See it", URL: "https://preview.example.test/"}}
+ open := f.AskOutcome("This is ready. Go ahead?", options, preview)
+ card := `#ask-panel [data-card="` + open + `"]`
+ wait(`(() => { const c = document.querySelector(` + strconv.Quote(card) + `);
+ return c && c.textContent.includes("This is ready. Go ahead?") &&
+ [...c.querySelectorAll("button")].map(b => b.textContent + "=" + b.value).join("|") === "Go ahead=go|Not yet=later" &&
+ !!c.querySelector('a.card-link[href="https://preview.example.test/"][target="_blank"][rel="noopener"]') })()`)
+ drive(t, rig, chromedp.Sleep(200*time.Millisecond))
+ if got := harness.Evaluate[string](rig, lastVisible); got != "" {
+ t.Errorf("with an open card: %s", got)
}
- rig.Screen("#ask-panel", "the panel after publishing")
- mobileShot(t, rig, "3-published")
-}
+ mobileShot(t, rig, "1-outcome-open")
-// Polish: an answered merge or publish card adds no bubble (Equipo sends
-// none), option and state words come only from Base's own tables, and a
-// preview on Equipo's own origin is a link like any other.
-func TestAskCardsPolish(t *testing.T) {
- rig, f := askBase(t)
- openPanel(t, rig)
- wait := func(js string) {
- t.Helper()
- drive(t, rig, chromedp.Poll[chromedp.Void](js, chromedp.WithPollingTimeout(10*time.Second)))
- }
- merge := f.AskMerge("Quick website")
- preview := f.URL + "/tasks/tk0001/preview"
- f.SetPreview(merge, preview, true)
- card := `#ask-panel [data-card="` + merge + `"]`
- wait(`!!document.querySelector(` + strconv.Quote(card+` a.card-link[href="`+preview+`"]`) + `)`)
- drive(t, rig, chromedp.Click(chromedp.CSS(card+` button[value="merge"]`)))
- wait(`document.querySelector(` + strconv.Quote(card) + `).textContent.includes("Merging without checks.")`)
+ // Answering posts the value; Equipo starts no turn for it, so there is
+ // no bubble, no status and no Stop.
+ drive(t, rig, chromedp.Click(chromedp.CSS(card+` button[value="go"]`)))
+ wait(`document.querySelector(` + strconv.Quote(card+` .card-state`) + `)?.textContent === "Go ahead"`)
drive(t, rig, chromedp.Sleep(300*time.Millisecond))
- if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .msg.person")].map(m => "[" + m.textContent + "]").join("") + "|" + document.querySelector("#ask-panel .ask-status").textContent`); got != "|" {
- t.Errorf("after answering a merge card: bubbles and status %q, want none", got)
+ if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .msg.person")].map(m => "[" + m.textContent + "]").join("") + "|" +
+ document.querySelector("#ask-panel .ask-status").textContent + "|" + document.querySelector("#ask-panel form.stop").hidden`); got != "||true" {
+ t.Errorf("after answering an outcome card: bubbles, status and Stop hidden %q", got)
}
-
- q := f.AskQuestion("Pick one", "constructor", "toString")
- qcard := `#ask-panel [data-card="` + q + `"]`
- wait(`!!document.querySelector(` + strconv.Quote(qcard+` button`) + `)`)
- if got := harness.Evaluate[string](rig, `[...document.querySelectorAll(`+strconv.Quote(qcard+` button`)+`)].map(b => b.textContent).join("|")`); got != "constructor|toString" {
- t.Errorf("option buttons read %q", got)
+ if c := f.Calls("/api/v1/assistant/cards/" + open + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"go","revision":1}` {
+ t.Fatalf("answers: %+v", c)
}
- publish := f.AskPublish("Quick website", "site-sample")
- f.SetCard(publish, "answered", "constructor", "toString")
- pcard := `#ask-panel [data-card="` + publish + `"]`
- wait(`!!document.querySelector(` + strconv.Quote(pcard+` .card-state`) + `)`)
- if got := harness.Evaluate[string](rig, `document.querySelector(`+strconv.Quote(pcard+` .card-state`)+`).textContent`); got != "Nothing to decide any more." {
- t.Errorf("a card with unknown choice and site state reads %q", got)
+
+ // An ended card says how it ended, with its link, and has no buttons.
+ site := f.AskOutcome("Your site is ready. Publish it?", nil, []equipo.Link{{Label: "Open it", URL: "https://site.example.test/"}})
+ f.SetCard(site, "resolved", "Published")
+ scard := `#ask-panel [data-card="` + site + `"]`
+ wait(`(() => { const c = document.querySelector(` + strconv.Quote(scard) + `);
+ return c && c.querySelector(".card-state")?.textContent === "Published" && !c.querySelector("form") &&
+ !!c.querySelector('a.card-link[href="https://site.example.test/"][rel="noopener"]') })()`)
+ mobileShot(t, rig, "2-outcome-result")
+
+ task := f.AskKind("task", "Merge tk0001?", options, nil)
+ f.Say("Try [this](javascript:alert(1)), [that](/tasks/tk1) or <img src=x onerror=alert(1)>.")
+ wait(`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent.includes("<img src=x"))`)
+ if n := harness.Evaluate[int](rig, `document.querySelectorAll('#ask-panel a[href^="javascript"], #ask-panel a[href*="/tasks/"], #ask-panel .msg img, #ask-panel [data-card="`+task+`"]').length`); n != 0 {
+ t.Fatalf("unsafe markup, a task link or a task card rendered: %d", n)
}
+ rig.Screen("#ask-panel", "the panel with the Assistant's cards")
}
diff --git a/internal/equipo/chat.go b/internal/equipo/chat.go
index 4939d74..190b49d 100644
--- a/internal/equipo/chat.go
+++ b/internal/equipo/chat.go
@@ -23,7 +23,7 @@ func InFlight(state string) bool {
return state == TurnQueued || state == TurnRunning || state == TurnWaiting
}
-// Message is one line of the conversation; Role is person or coordinator.
+// Message is one line of the conversation; Role is person or assistant.
type Message struct {
ID string `json:"id"`
Role string `json:"role"`
@@ -32,7 +32,7 @@ type Message struct {
CreatedAt time.Time `json:"created_at"`
}
-// Turn is the coordinator's answer to the person's messages.
+// Turn is the Assistant's answer to the person's messages.
type Turn struct {
ID string `json:"id"`
Kind string `json:"kind"`
@@ -40,75 +40,69 @@ type Turn struct {
Reason string `json:"reason"`
}
-// Card is something in the conversation to act on. Base shows three
-// kinds (see Projected): a question, a merge card (Equipo asks whether to
-// merge a task without checks, with its preview once it is up) and a
-// publish card (whether to publish a merged website; Site says how that
-// went). Each Option is a button.
+// Card is something in the conversation to act on, drawn from its fields
+// alone: the question, a button per option (its label, answering with its
+// value), a link per link, and once it has one, a line saying how it
+// ended (Result). Base knows no kind's words of its own.
type Card struct {
- ID string `json:"id"`
- Revision int64 `json:"revision"`
- Kind string `json:"kind"`
- State string `json:"state"`
- Name string `json:"name,omitempty"`
- TaskID string `json:"task_id,omitempty"`
- Question string `json:"question"`
- Options []string `json:"options"`
- Choice string `json:"choice"`
- PreviewURL string `json:"preview_url,omitempty"`
- Site *CardSite `json:"site,omitempty"`
-}
-
-// CardSite is a publish card's website: its app, the merged commit, how
-// publishing it stands (asked, publishing, published, unconfirmed, failed
-// or declined) and, once known, its public URL.
-type CardSite struct {
- App string `json:"app"`
- SHA string `json:"sha"`
- State string `json:"state"`
- URL string `json:"url,omitempty"`
-}
-
-// Card kinds Base shows.
+ ID string `json:"id"`
+ Revision int64 `json:"revision"`
+ Kind string `json:"kind"`
+ State string `json:"state"`
+ Question string `json:"question"`
+ Options []Option `json:"options"`
+ Links []Link `json:"links"`
+ Result string `json:"result"`
+}
+
+// Option is one answer a card offers: Label on the button, Value sent.
+type Option struct {
+ Value string `json:"value"`
+ Label string `json:"label"`
+}
+
+// Link is a link a card shows.
+type Link struct {
+ Label string `json:"label"`
+ URL string `json:"url"`
+}
+
+// The kinds of card the Assistant raises.
const (
CardQuestion = "question"
- CardMerge = "merge"
- CardPublish = "publish"
+ CardConfirm = "confirm"
+ CardOutcome = "outcome"
+ CardConnect = "connect"
)
-// Projected is the card as Base passes it on: only the fields its kind
-// uses, and a link only if it is an http(s) URL. ok is false for every
-// other kind of card (projects, tasks and the rest stay in Equipo).
-func (c Card) Projected() (Card, bool) {
- out := Card{ID: c.ID, Revision: c.Revision, Kind: c.Kind, State: c.State, Question: c.Question,
- Options: c.Options, Choice: c.Choice}
+// Clean is the card as Base passes it on: its own fields only, never-null
+// options and links, and a link only if it is an http(s) URL (WebURL).
+// ok is false for every other kind of card.
+func (c Card) Clean() (Card, bool) {
switch c.Kind {
- case CardQuestion:
- case CardMerge:
- out.Name, out.TaskID, out.PreviewURL = c.Name, c.TaskID, WebURL(c.PreviewURL)
- case CardPublish:
- out.Name, out.TaskID = c.Name, c.TaskID
- if c.Site != nil {
- out.Site = &CardSite{App: c.Site.App, SHA: c.Site.SHA, State: c.Site.State, URL: WebURL(c.Site.URL)}
- }
+ case CardQuestion, CardConfirm, CardOutcome, CardConnect:
default:
return Card{}, false
}
+ out := Card{ID: c.ID, Revision: c.Revision, Kind: c.Kind, State: c.State, Question: c.Question,
+ Options: []Option{}, Links: []Link{}, Result: c.Result}
+ for _, o := range c.Options {
+ out.Options = append(out.Options, Option{Value: o.Value, Label: o.Label})
+ }
+ for _, l := range c.Links {
+ if u := WebURL(l.URL); u != "" {
+ out.Links = append(out.Links, Link{Label: l.Label, URL: u})
+ }
+ }
return out, true
}
// Open reports whether the card waits for an answer.
func (c Card) Open() bool { return c.State == "open" }
-// Shown reports whether a conversation read afresh shows the card: a
-// question or merge card while it is open, a publish card always (it goes
-// on to say whether the site was published).
-func (c Card) Shown() bool {
- if c.Kind == CardPublish {
- return true
- }
- return (c.Kind == CardQuestion || c.Kind == CardMerge) && c.Open()
-}
+// Shown reports whether a conversation read afresh shows the card: while
+// it is open, and afterwards if it says how it ended.
+func (c Card) Shown() bool { return c.Open() || c.Result != "" }
// WebURL is raw if it is an absolute http or https URL with a host and no
// user info, else "".
@@ -120,23 +114,33 @@ func WebURL(raw string) string {
return u.String()
}
-// Snapshot is the part of GET /api/v1/snapshot Base shows: the
-// conversation's tail, its turns, its cards and the event cursor they
-// were read at, so the stream picks up exactly after them.
+// assistant is the prefix of the Assistant's routes: every chat call goes
+// there, never to the Coordinator's.
+const assistant = "/api/v1/assistant"
+
+// Snapshot is the part of GET /api/v1/assistant/snapshot Base shows: who
+// the bearer speaks for, the conversation's tail, its turns, its cards,
+// the event cursor they were read at (so the stream picks up exactly
+// after them), and whether the person has a runner that can answer.
type Snapshot struct {
- Messages []Message `json:"messages"`
- Turns []Turn `json:"turns"`
- Cards []Card `json:"cards"`
- Cursor int64 `json:"cursor"`
+ Me struct {
+ Address string `json:"address"`
+ } `json:"me"`
+ Messages []Message `json:"messages"`
+ Turns []Turn `json:"turns"`
+ Cards []Card `json:"cards"`
+ Cursor int64 `json:"cursor"`
+ Available bool `json:"available"`
}
-// Sent is POST /api/v1/messages's answer.
+// Sent is POST messages's answer.
type Sent struct {
Message Message `json:"message"`
Turn Turn `json:"turn"`
}
-// Answered is POST /api/v1/cards/{id}/answer's answer.
+// Answered is POST cards/{id}/answer's answer. An answer that starts no
+// turn (an outcome card's) has an empty Message and a zero Turn.
type Answered struct {
Card Card `json:"card"`
Message Message `json:"message"`
@@ -146,39 +150,51 @@ type Answered struct {
// Snapshot reads the person's conversation in one go.
func (c *Client) Snapshot(ctx context.Context, token string) (Snapshot, error) {
var out Snapshot
- _, err := c.call(ctx, http.MethodGet, "/api/v1/snapshot", token, "", nil, nil, &out)
+ _, err := c.call(ctx, http.MethodGet, assistant+"/snapshot", token, "", nil, nil, &out)
return out, err
}
-// Send sends the person's message. key makes a retry safe: Equipo keeps
-// one message per key. It goes as the body's idempotency_key, and as the
-// Idempotency-Key header every mutation carries.
+// Send sends the person's message: ErrNoRunner or ErrRunnerTooOld when
+// the person has no runner that can answer. key makes a retry safe:
+// Equipo keeps one message per key. It goes as the body's
+// idempotency_key, and as the Idempotency-Key header every mutation
+// carries.
func (c *Client) Send(ctx context.Context, token, text, key string) (Sent, error) {
var out Sent
in := map[string]string{"text": text, "idempotency_key": key}
- _, err := c.call(ctx, http.MethodPost, "/api/v1/messages", token, key, nil, in, &out)
+ _, err := c.call(ctx, http.MethodPost, assistant+"/messages", token, key, nil, in, &out)
return out, err
}
// Cancel stops a turn that has not ended.
func (c *Client) Cancel(ctx context.Context, token, turnID, key string) error {
- _, err := c.call(ctx, http.MethodPost, "/api/v1/turns/"+url.PathEscape(turnID)+"/cancel", token, key, nil, struct{}{}, nil)
+ _, err := c.call(ctx, http.MethodPost, assistant+"/turns/"+url.PathEscape(turnID)+"/cancel", token, key, nil, struct{}{}, nil)
return err
}
-// Answer answers question card id with choice, at the card's revision.
+// Answer answers card id with an option's value, at the card's revision.
func (c *Client) Answer(ctx context.Context, token, id, choice string, revision int64, key string) (Answered, error) {
var out Answered
in := map[string]any{"choice": choice, "revision": revision}
- _, err := c.call(ctx, http.MethodPost, "/api/v1/cards/"+url.PathEscape(id)+"/answer", token, key, nil, in, &out)
+ _, err := c.call(ctx, http.MethodPost, assistant+"/cards/"+url.PathEscape(id)+"/answer", token, key, nil, in, &out)
return out, err
}
+// RegisterHost tells Equipo where the person's Base operations live
+// (origin) and the token Base minted for them (hostToken), which the
+// Assistant presents when it calls them. A second call replaces the
+// first.
+func (c *Client) RegisterHost(ctx context.Context, token, origin, hostToken string) error {
+ in := map[string]string{"origin": origin, "token": hostToken}
+ _, err := c.call(ctx, http.MethodPut, assistant+"/host", token, NewKey(), nil, in, nil)
+ return err
+}
+
// Events opens the person's event stream after cursor after ("" for from
// now). It gives up when the headers take longer than StreamHeaderTimeout.
// The caller reads and closes the body; cancelling ctx ends the stream.
func (c *Client) Events(ctx context.Context, token, after string) (*http.Response, error) {
- u := c.origin + "/api/v1/events"
+ u := c.origin + assistant + "/events"
if after != "" {
u += "?after=" + url.QueryEscape(after)
}
diff --git a/internal/equipo/equipo.go b/internal/equipo/equipo.go
index fb7a04d..f79c82b 100644
--- a/internal/equipo/equipo.go
+++ b/internal/equipo/equipo.go
@@ -1,10 +1,11 @@
// Package equipo is Base's client for Equipo's person API (v1): signing a
-// device in for a member, and the coordinator chat behind "Ask Base
+// device in for a member, and the Assistant's chat behind "Ask Base
// anything". Base calls Equipo server to server with the member's bearer;
// the bearer never reaches a browser.
//
-// The shapes mirror Equipo's handlers on main (internal/wire/api.go,
-// internal/equipo/personapi/devices.go), reading only the fields Base uses.
+// The shapes mirror Equipo's handlers (internal/wire/api.go and
+// assistant.go, internal/equipo/personapi/devices.go and
+// chat/assistant_http.go), reading only the fields Base uses.
package equipo
import (
@@ -48,6 +49,11 @@ var (
ErrSlowDown = &Error{Status: 429}
// ErrExpired: the sign-in code expired; start again.
ErrExpired = &Error{Status: 410}
+ // ErrNoRunner: the person has no runner, so the Assistant cannot
+ // answer a message or a question.
+ ErrNoRunner = &Error{Status: 409, Code: "no_runner"}
+ // ErrRunnerTooOld: the person's runner is too old for the Assistant.
+ ErrRunnerTooOld = &Error{Status: 409, Code: "runner_too_old"}
)
// Challenge is POST /api/v1/auth/devices's answer.
diff --git a/internal/equipo/equipo_test.go b/internal/equipo/equipo_test.go
index 69d31ce..b65cf6d 100644
--- a/internal/equipo/equipo_test.go
+++ b/internal/equipo/equipo_test.go
@@ -98,7 +98,7 @@ func TestSendCarriesBearerAndKey(t *testing.T) {
if sent.Message.Text != "What can I do" || sent.Turn.ID == "" || sent.Turn.State != "queued" {
t.Fatalf("sent: %+v", sent)
}
- calls := f.Calls("/api/v1/messages")
+ calls := f.Calls("/api/v1/assistant/messages")
if len(calls) != 1 {
t.Fatalf("calls: %+v", calls)
}
@@ -144,32 +144,143 @@ func TestEventsHeaderTimeout(t *testing.T) {
}
}
-// Base shows question, merge and publish cards, each with only its own
-// fields, and only web links.
-func TestCardProjected(t *testing.T) {
- site := &equipo.CardSite{App: "site-sample", SHA: "eee", State: "published", URL: "https://site-sample.example.test/"}
+// Every chat call goes to the Assistant's routes with the member's bearer;
+// the Coordinator's routes are never called.
+func TestClientUsesAssistantRoutes(t *testing.T) {
+ f := equipotest.New(t)
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ ctx := context.Background()
+ q := f.AskQuestion("Which one?", "a", "b")
+ f.Hold = true
+ snap, err := c.Snapshot(ctx, cred.Token)
+ if err != nil || len(snap.Cards) != 1 || !snap.Available || snap.Me.Address != "paul@tito.io" {
+ t.Fatalf("snapshot: %+v %v", snap, err)
+ }
+ sent, err := c.Send(ctx, cred.Token, "What can I do", "k-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := c.Cancel(ctx, cred.Token, sent.Turn.ID, "k-2"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := c.Answer(ctx, cred.Token, q, "a", 1, "k-3"); err != nil {
+ t.Fatal(err)
+ }
+ res, err := c.Events(ctx, cred.Token, "41")
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if err := c.RegisterHost(ctx, cred.Token, "https://base.example.test", "bh_0123456789abcdefghij"); err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]string{
+ "GET /api/v1/assistant/snapshot": "",
+ "POST /api/v1/assistant/messages": "",
+ "POST /api/v1/assistant/turns/" + sent.Turn.ID + "/cancel": "",
+ "POST /api/v1/assistant/cards/" + q + "/answer": "",
+ "GET /api/v1/assistant/events": "",
+ "PUT /api/v1/assistant/host": "",
+ }
+ for _, call := range f.Calls("") {
+ if strings.HasPrefix(call.Path, "/api/v1/auth/") {
+ continue
+ }
+ key := call.Method + " " + call.Path
+ if _, ok := want[key]; !ok {
+ t.Errorf("called %s", key)
+ continue
+ }
+ if call.Header.Get("Authorization") != "Bearer "+cred.Token {
+ t.Errorf("%s without the bearer: %v", key, call.Header)
+ }
+ delete(want, key)
+ }
+ for key := range want {
+ t.Errorf("never called %s", key)
+ }
+ for _, old := range []string{"/api/v1/snapshot", "/api/v1/messages", "/api/v1/events"} {
+ if n := len(f.Calls(old)); n != 0 {
+ t.Errorf("%d calls to %s", n, old)
+ }
+ }
+ hosts := f.Hosts()
+ if len(hosts) != 1 || strings.TrimSpace(hosts[0].Body) != `{"origin":"https://base.example.test","token":"bh_0123456789abcdefghij"}` {
+ t.Fatalf("hosts: %+v", hosts)
+ }
+}
+
+// Without a runner Equipo refuses a message: 409 no_runner, which Base
+// can tell from runner_too_old.
+func TestSendWithoutRunner(t *testing.T) {
+ f := equipotest.New(t)
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ f.NoRunner()
+ _, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1")
+ if !errors.Is(err, equipo.ErrNoRunner) || errors.Is(err, equipo.ErrRunnerTooOld) {
+ t.Fatalf("send: %v, want ErrNoRunner", err)
+ }
+ if snap, err := c.Snapshot(context.Background(), cred.Token); err != nil || snap.Available || len(snap.Messages) != 0 {
+ t.Fatalf("snapshot: %+v %v", snap, err)
+ }
+}
+
+// Base keeps the four card kinds the Assistant draws, with their own
+// fields and only web links; any other kind stays in Equipo.
+func TestCardClean(t *testing.T) {
+ opts := []equipo.Option{{Value: "go", Label: "Go ahead"}, {Value: "later", Label: "Not yet"}}
for name, c := range map[string]struct {
in equipo.Card
want string
}{
- "question": {equipo.Card{ID: "c1", Revision: 1, Kind: "question", State: "open", Name: "n", TaskID: "tk1", Question: "Which?", Options: []string{"a"}, PreviewURL: "https://x.test/", Site: site},
- `{"id":"c1","revision":1,"kind":"question","state":"open","question":"Which?","options":["a"],"choice":""}`},
- "merge": {equipo.Card{ID: "c2", Revision: 2, Kind: "merge", State: "open", Name: "Quick website", TaskID: "tk1", Question: "Merge Quick website without checks?", Options: []string{"merge", "wait"}, PreviewURL: "https://eq-tk1.devbox.test/", Site: site},
- `{"id":"c2","revision":2,"kind":"merge","state":"open","name":"Quick website","task_id":"tk1","question":"Merge Quick website without checks?","options":["merge","wait"],"choice":"","preview_url":"https://eq-tk1.devbox.test/"}`},
- "merge, bad preview": {equipo.Card{ID: "c3", Kind: "merge", State: "open", PreviewURL: "javascript:alert(1)"},
- `{"id":"c3","revision":0,"kind":"merge","state":"open","question":"","options":null,"choice":""}`},
- "publish": {equipo.Card{ID: "c4", Revision: 3, Kind: "publish", State: "answered", Name: "Quick website", TaskID: "tk1", Question: "Publish?", Options: []string{"publish", "not_now"}, Choice: "publish", PreviewURL: "https://x.test/", Site: site},
- `{"id":"c4","revision":3,"kind":"publish","state":"answered","name":"Quick website","task_id":"tk1","question":"Publish?","options":["publish","not_now"],"choice":"publish","site":{"app":"site-sample","sha":"eee","state":"published","url":"https://site-sample.example.test/"}}`},
- "publish, bad site url": {equipo.Card{ID: "c5", Kind: "publish", State: "open", Site: &equipo.CardSite{App: "a", State: "asked", URL: "data:text/html,hi"}},
- `{"id":"c5","revision":0,"kind":"publish","state":"open","question":"","options":null,"choice":"","site":{"app":"a","sha":"","state":"asked"}}`},
+ "confirm": {equipo.Card{ID: "c1", Revision: 2, Kind: "confirm", State: "open", Question: "Send it?", Options: opts,
+ Links: []equipo.Link{{Label: "See it", URL: "https://x.test/a"}}},
+ `{"id":"c1","revision":2,"kind":"confirm","state":"open","question":"Send it?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[{"label":"See it","url":"https://x.test/a"}],"result":""}`},
+ "connect": {equipo.Card{ID: "c2", Revision: 1, Kind: "connect", State: "resolved", Question: "Connect Calendar", Result: "Connected",
+ Links: []equipo.Link{{Label: "Connect", URL: "https://connect.test/consent?x=1"}}},
+ `{"id":"c2","revision":1,"kind":"connect","state":"resolved","question":"Connect Calendar","options":[],"links":[{"label":"Connect","url":"https://connect.test/consent?x=1"}],"result":"Connected"}`},
+ "unsafe links": {equipo.Card{ID: "c3", Kind: "outcome", State: "open", Links: []equipo.Link{
+ {Label: "a", URL: "javascript:alert(1)"}, {Label: "b", URL: "/tasks/tk1"}, {Label: "c", URL: "https://user:pw@x.test/"},
+ {Label: "d", URL: "https://ok.test/"}}},
+ `{"id":"c3","revision":0,"kind":"outcome","state":"open","question":"","options":[],"links":[{"label":"d","url":"https://ok.test/"}],"result":""}`},
} {
- got, ok := c.in.Projected()
+ got, ok := c.in.Clean()
raw, _ := json.Marshal(got)
if !ok || string(raw) != c.want {
t.Errorf("%s: %v\n got %s\nwant %s", name, ok, raw, c.want)
}
}
- if _, ok := (equipo.Card{ID: "c6", Kind: "project", State: "added"}).Projected(); ok {
- t.Error("a project card was shown")
+ for _, kind := range []string{"task", "merge", "publish", "project", ""} {
+ if _, ok := (equipo.Card{ID: "c6", Kind: kind, State: "open"}).Clean(); ok {
+ t.Errorf("a %q card was kept", kind)
+ }
+ }
+ var in equipo.Card
+ raw := `{"id":"c7","revision":1,"kind":"question","state":"open","question":"Which?","options":[{"value":"a","label":"A"}],"links":[],"result":"","task_id":"tk1","site":{"app":"x"}}`
+ if err := json.Unmarshal([]byte(raw), &in); err != nil {
+ t.Fatal(err)
+ }
+ const want = `{"id":"c7","revision":1,"kind":"question","state":"open","question":"Which?","options":[{"value":"a","label":"A"}],"links":[],"result":""}`
+ if out, _ := json.Marshal(in); string(out) != want {
+ t.Errorf("decoded with extra fields: %s", out)
+ }
+ got, ok := in.Clean()
+ if out, _ := json.Marshal(got); !ok || string(out) != want {
+ t.Errorf("extra fields: %v %s", ok, out)
+ }
+}
+
+// A card shows while it is open, and afterwards only if it says how it
+// ended.
+func TestCardShown(t *testing.T) {
+ for _, c := range []struct {
+ state, result string
+ want bool
+ }{{"open", "", true}, {"answered", "", false}, {"answered", "Done", true}, {"resolved", "Published", true}, {"resolved", "", false}} {
+ if got := (equipo.Card{Kind: "outcome", State: c.state, Result: c.result}).Shown(); got != c.want {
+ t.Errorf("%s %q: shown %v", c.state, c.result, got)
+ }
}
}
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go
index 5c949a4..1e78fd0 100644
--- a/internal/equipo/equipotest/chat.go
+++ b/internal/equipo/equipotest/chat.go
@@ -10,9 +10,16 @@ import (
"sync"
"time"
"unicode/utf8"
+
+ "amadan.net/carlos/base/internal/equipo"
)
-// The chat's resources in wire's JSON shapes (Message, Turn, Card, Event).
+// assistant is the prefix of the Assistant's routes, the only chat routes
+// the fake serves.
+const assistant = "/api/v1/assistant"
+
+// The chat's resources in wire's JSON shapes (Message, Turn,
+// AssistantCard, Event).
type message struct {
ID string `json:"id"`
Revision int64 `json:"revision"`
@@ -38,32 +45,16 @@ type turn struct {
Timing *struct{} `json:"timing"`
}
+// card is wire.AssistantCard: options and links are never null.
type card struct {
- ID string `json:"id"`
- Revision int64 `json:"revision"`
- Kind string `json:"kind"`
- State string `json:"state"`
- TurnID string `json:"turn_id"`
- ProjectID string `json:"project_id"`
- Name string `json:"name"`
- Question string `json:"question"`
- Options []string `json:"options"`
- Choice string `json:"choice"`
- TaskID string `json:"task_id"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
- // PreviewURL is a merge card's preview once it is up; Site a publish
- // card's site (Equipo's base-publish branch).
- PreviewURL string `json:"preview_url,omitempty"`
- Site *site `json:"site,omitempty"`
-}
-
-type site struct {
- App string `json:"app"`
- SHA string `json:"sha"`
- State string `json:"state"`
- URL string `json:"url,omitempty"`
- At *time.Time `json:"at,omitempty"`
+ ID string `json:"id"`
+ Revision int64 `json:"revision"`
+ Kind string `json:"kind"`
+ State string `json:"state"`
+ Question string `json:"question"`
+ Options []equipo.Option `json:"options"`
+ Links []equipo.Link `json:"links"`
+ Result string `json:"result"`
}
type event struct {
@@ -78,7 +69,7 @@ type event struct {
Data any `json:"data"`
}
-// chat is one person's conversation with the coordinator.
+// chat is one person's conversation with the Assistant.
type chat struct {
cmu sync.Mutex
seq int
@@ -88,6 +79,7 @@ type chat struct {
events []event
sent map[string]string // idempotency key to message id
wake chan struct{} // closed at each new event
+ noRunner bool
}
func (c *chat) init() {
@@ -111,103 +103,64 @@ func (f *Fake) Emit(typ string, data any) {
f.emit(typ, typ, "x", 1, "", data)
}
-// AskQuestion puts an open question card in the conversation.
+// AskQuestion puts an open question card in the conversation, as the
+// Assistant's ask_person does: each option's value is its label.
func (f *Fake) AskQuestion(question string, options ...string) string {
- f.cmu.Lock()
- defer f.cmu.Unlock()
- now := time.Now().UTC()
- c := &card{ID: f.next("c"), Revision: 1, Kind: "question", State: "open", Question: question,
- Options: options, CreatedAt: now, UpdatedAt: now}
- f.cards = append(f.cards, c)
- f.emit("card", "card", c.ID, c.Revision, "", *c)
- return c.ID
+ opts := make([]equipo.Option, len(options))
+ for i, o := range options {
+ opts[i] = equipo.Option{Value: o, Label: o}
+ }
+ return f.AskKind("question", question, opts, nil)
+}
+
+// AskOutcome puts an open outcome card in the conversation, as Equipo
+// does when the team's work needs the person.
+func (f *Fake) AskOutcome(question string, options []equipo.Option, links []equipo.Link) string {
+ return f.AskKind("outcome", question, options, links)
}
-// AskMerge puts an open merge card in the conversation, as Equipo does
-// for a task whose checks could not run: Merge or Wait for checks.
-func (f *Fake) AskMerge(title string) string {
+// AskKind puts an open card of any kind in the conversation, such as one
+// Base must not show.
+func (f *Fake) AskKind(kind, question string, options []equipo.Option, links []equipo.Link) string {
f.cmu.Lock()
defer f.cmu.Unlock()
- now := time.Now().UTC()
- c := &card{ID: f.next("c"), Revision: 1, Kind: "merge", State: "open", ProjectID: "p_0001", Name: title,
- Question: "Merge " + title + " without checks?", Options: []string{"merge", "wait"}, TaskID: "tk0001",
- CreatedAt: now, UpdatedAt: now}
+ c := &card{ID: f.next("c"), Revision: 1, Kind: kind, State: "open", Question: question,
+ Options: append([]equipo.Option{}, options...), Links: append([]equipo.Link{}, links...)}
f.cards = append(f.cards, c)
f.emit("card", "card", c.ID, c.Revision, "", *c)
return c.ID
}
-// SetPreview puts a preview link on merge card id, a new revision. With
-// announce false no event says so, as if it were missed: an answer at the
-// old revision then gets 409.
-func (f *Fake) SetPreview(id, url string, announce bool) {
+// SetCard moves card id to state with result, a new revision, announcing
+// it.
+func (f *Fake) SetCard(id, state, result string) {
f.cmu.Lock()
defer f.cmu.Unlock()
for _, c := range f.cards {
if c.ID == id {
- c.PreviewURL, c.Revision, c.UpdatedAt = url, c.Revision+1, time.Now().UTC()
- if announce {
- f.emit("card", "card", c.ID, c.Revision, "", *c)
- }
+ c.State, c.Result, c.Revision = state, result, c.Revision+1
+ f.emit("card", "card", c.ID, c.Revision, "", *c)
}
}
}
-// AskPublish puts an open publish card in the conversation: Publish or Not
-// now. Publish runs to published, with the site's URL and a line saying so.
-func (f *Fake) AskPublish(title, app string) string {
+// NoRunner makes the person runnerless: the snapshot says the Assistant
+// is not available, and a message or a question's answer gets 409
+// no_runner.
+func (f *Fake) NoRunner() {
f.cmu.Lock()
defer f.cmu.Unlock()
- now := time.Now().UTC()
- c := &card{ID: f.next("c"), Revision: 1, Kind: "publish", State: "open", ProjectID: "p_0001", Name: title,
- Question: "Publish " + title + " on the web as " + app + "?", Options: []string{"publish", "not_now"},
- TaskID: "tk0001", CreatedAt: now, UpdatedAt: now,
- Site: &site{App: app, SHA: strings.Repeat("e", 40), State: "asked"}}
- f.cards = append(f.cards, c)
- f.emit("card", "card", c.ID, c.Revision, "", *c)
- return c.ID
+ f.noRunner = true
}
-// publish runs a publish card answered Publish: publishing, then published.
-func (f *Fake) publish(c *card) {
- select {
- case <-f.closing:
- return
- case <-time.After(40 * time.Millisecond):
- }
- f.cmu.Lock()
- defer f.cmu.Unlock()
- now := time.Now().UTC()
- url := "https://" + c.Site.App + ".example.test/"
- c.Site.State, c.Site.URL, c.Site.At, c.Revision, c.UpdatedAt = "published", url, &now, c.Revision+1, now
- f.emit("card", "card", c.ID, c.Revision, "", *c)
- m := message{ID: f.next("m"), Revision: 1, Role: "coordinator", CreatedAt: now,
- Text: "Published [" + c.Name + "](/tasks/" + c.TaskID + ") at " + url + "."}
- f.messages = append(f.messages, m)
- f.emit("message", "message", m.ID, 1, "", m)
-}
-
-// SetCard moves card id to state with choice, and its site (if it has
-// one) to site, announcing it.
-func (f *Fake) SetCard(id, state, choice, siteState string) {
- f.cmu.Lock()
- defer f.cmu.Unlock()
- for _, c := range f.cards {
- if c.ID == id {
- c.State, c.Choice, c.Revision = state, choice, c.Revision+1
- if c.Site != nil {
- c.Site.State = siteState
- }
- f.emit("card", "card", c.ID, c.Revision, "", *c)
- }
- }
-}
+// Hosts are the PUT host requests the fake received, oldest first.
+func (f *Fake) Hosts() []Call { return f.Calls(assistant + "/host") }
-// Say adds a coordinator line to the conversation.
+// Say adds an Assistant line to the conversation.
func (f *Fake) Say(text string) {
f.cmu.Lock()
defer f.cmu.Unlock()
- m := message{ID: f.next("m"), Revision: 1, Role: "coordinator", Text: text, CreatedAt: time.Now().UTC()}
+ m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: text, CreatedAt: time.Now().UTC()}
f.messages = append(f.messages, m)
f.emit("message", "message", m.ID, 1, "", m)
}
@@ -227,8 +180,13 @@ func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) {
writeError(w, r, 401, "unauthenticated")
return
}
- p := strings.TrimPrefix(r.URL.Path, "/api/v1")
+ // Only the Assistant's routes: a call to the Coordinator's is a 404.
+ p, ok := strings.CutPrefix(r.URL.Path, assistant)
switch {
+ case !ok:
+ writeError(w, r, 404, "not_found")
+ case r.Method == http.MethodPut && p == "/host":
+ f.host(w, r)
case r.Method == http.MethodGet && p == "/snapshot":
f.snapshot(w)
case r.Method == http.MethodGet && p == "/messages":
@@ -268,15 +226,28 @@ 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", "team_id": f.Instance},
- "messages": f.tail(), "turns": turns, "runner": map[string]any{"id": "R1", "online": true},
- "projects": []any{}, "cards": cards, "tasks": []any{},
- "coordinator": map[string]any{"id": "paul@tito.io", "revision": 2, "state": "ready"},
- "connections": nil, "housekeeping_summary": map[string]any{}, "cursor": int64(len(f.events) + 40),
- "runners": []any{},
+ "me": map[string]any{"id": "paul@tito.io", "address": "paul@tito.io", "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,
})
}
+// host is PUT host {origin, token}: 200 {origin, revision}, the token
+// never given back.
+func (f *Fake) host(w http.ResponseWriter, r *http.Request) {
+ var in struct {
+ Origin string `json:"origin"`
+ Token string `json:"token"`
+ }
+ if strict(r, &in) != nil || !strings.HasPrefix(in.Origin, "https://") && !strings.HasPrefix(in.Origin, "http://127.0.0.1") ||
+ len(in.Token) < 20 || len(in.Token) > 512 {
+ writeError(w, r, 422, "invalid_input")
+ return
+ }
+ writeJSON(w, 200, map[string]any{"origin": in.Origin, "revision": len(f.Hosts())})
+}
+
func (f *Fake) send(w http.ResponseWriter, r *http.Request) {
var in struct {
Text string `json:"text"`
@@ -295,6 +266,11 @@ func (f *Fake) send(w http.ResponseWriter, r *http.Request) {
return
}
f.cmu.Lock()
+ if f.noRunner {
+ f.cmu.Unlock()
+ writeError(w, r, 409, "no_runner")
+ return
+ }
if id, ok := f.sent[in.IdempotencyKey]; ok {
for _, m := range f.messages {
if m.ID == id {
@@ -362,7 +338,7 @@ func (f *Fake) answerTurn(id, text string) {
if f.turns[id].State != "running" {
return
}
- m := message{ID: f.next("m"), Revision: 1, Role: "coordinator", Text: reply, TurnID: id, CreatedAt: time.Now().UTC()}
+ m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: reply, TurnID: id, CreatedAt: time.Now().UTC()}
f.messages = append(f.messages, m)
f.emit("message", "message", m.ID, 1, id, m)
t := f.turns[id]
@@ -426,29 +402,42 @@ func (f *Fake) answer(w http.ResponseWriter, r *http.Request, id string) {
f.cmu.Unlock()
return
}
- c.State, c.Choice, c.Revision, c.UpdatedAt = "answered", in.Choice, c.Revision+1, time.Now().UTC()
- if c.Site != nil {
- c.Site.State = "declined"
- if in.Choice == "publish" {
- c.Site.State = "publishing"
- go f.publish(c)
+ label, ok := "", false
+ for _, o := range c.Options {
+ if o.Value == in.Choice {
+ label, ok = o.Label, true
}
}
- f.emit("card", "card", c.ID, c.Revision, c.TurnID, *c)
- if c.Kind == "merge" || c.Kind == "publish" {
- // As Equipo does (answerMerge, answerPublish): the card alone
- // answers; no message, no turn.
+ if !ok {
+ f.cmu.Unlock()
+ writeError(w, r, 422, "invalid_input")
+ return
+ }
+ if c.Kind == "question" && f.noRunner {
+ f.cmu.Unlock()
+ writeError(w, r, 409, "no_runner")
+ return
+ }
+ c.State, c.Revision = "answered", c.Revision+1
+ if c.Kind != "question" {
+ // As Equipo does for an outcome card: the card says how it ended,
+ // and the answer starts no turn, so its message and turn are
+ // empty (a zero time included).
+ c.Result = label
+ f.emit("card", "card", c.ID, c.Revision, "", *c)
f.cmu.Unlock()
writeJSON(w, 200, map[string]any{"card": *c, "message": message{}, "turn": turn{}})
return
}
+ c.Result = in.Choice
+ f.emit("card", "card", c.ID, c.Revision, "", *c)
m, t := f.ask(in.Choice)
f.cmu.Unlock()
writeJSON(w, 200, map[string]any{"card": *c, "message": m, "turn": t})
go f.answerTurn(t.ID, in.Choice)
}
-// stream is GET /api/v1/events: Server-Sent Events after ?after= (or
+// stream is GET events: Server-Sent Events after ?after= (or
// Last-Event-ID), as Equipo writes them.
func (f *Fake) stream(w http.ResponseWriter, r *http.Request) {
raw := r.URL.Query().Get("after")
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go
index 2481c49..fd80046 100644
--- a/internal/equipo/equipotest/fake.go
+++ b/internal/equipo/equipotest/fake.go
@@ -1,7 +1,8 @@
// Package equipotest is a fake Equipo for Base's tests: the person API's
-// device sign-in and coordinator chat routes, in the shapes Equipo's
-// handlers write (amadan.net/oficina/equipo, internal/wire and
-// internal/equipo/personapi on main). It runs on 127.0.0.1 only.
+// device sign-in and the Assistant's chat routes (/api/v1/assistant), in
+// the shapes Equipo's handlers write (amadan.net/oficina/equipo,
+// internal/wire, internal/equipo/personapi and
+// internal/equipo/chat/assistant_http.go). It runs on 127.0.0.1 only.
package equipotest
import (
@@ -44,7 +45,7 @@ type device struct {
type Fake struct {
URL string
Instance string
- // Reply is what the coordinator answers to a message. Hold keeps every
+ // Reply is what the Assistant answers to a message. Hold keeps every
// new turn running until Finish, so a test can cancel one.
Reply func(text string) string
Hold bool
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 32abf0a..52601f1 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -490,6 +490,7 @@ dialog.ask-panel::backdrop { background: transparent; }
.card-link, .msg.coordinator a { color: var(--focus); text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; }
.card-link { display: inline-flex; align-items: center; min-height: 44px; font-weight: 500; }
.msg.card .card-state { margin: 0; color: var(--haze); font-size: 14px; }
+.msg.card .choices + .card-state { margin-top: 10px; }
.ask-empty, .ask-problem { margin: 0; padding: 0 20px 12px; color: var(--haze); font-size: 14px; }
.ask-foot { display: flex; align-items: center; gap: 10px; padding: 0 16px; }
.ask-status { flex: 1; margin: 0; min-height: 1.5em; color: var(--haze); font-size: 14px; }
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 5cd9dfe..9f21a72 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -19,8 +19,6 @@ function start(root) {
const stop = root.querySelector("form.stop");
const composer = root.querySelector("form.composer");
const field = composer.querySelector("textarea");
- // Equipo's origin, which its /tasks/ links point at.
- const equipo = (root.dataset.equipo || "").replace(/\/+$/, "");
let source = null;
let turn = null;
let retry = 0;
@@ -76,10 +74,8 @@ function start(root) {
return id ? thread.querySelector(`[${attr}="${CSS.escape(id)}"]`) : null;
}
- // A message, once: a coordinator's reply takes its streamed draft's place.
+ // A message, once: the Assistant's reply takes its streamed draft's place.
function addMessage(m) {
- // An answered merge or publish card brings no message (Equipo sends
- // none: the card says what was chosen), so an empty one is skipped.
if (!m || !m.id || item("data-id", m.id)) return;
const li = document.createElement("li");
li.className = "msg " + (m.role === "person" ? "person" : "coordinator");
@@ -105,10 +101,10 @@ function start(root) {
scroll();
}
- // Equipo's lines may carry Markdown links. Only http(s) addresses and
- // Equipo's own /tasks/ pages become links (opening in a new tab); the
- // rest, raw HTML included, is text. Base's server does the same
- // (richText in ask_cards.go).
+ // Equipo's lines may carry Markdown links. Only http(s) addresses become
+ // links (opening in a new tab); the rest, raw HTML and relative paths
+ // included, is text. Base's server does the same (richText in
+ // ask_cards.go).
const linkRE = /\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?:\/\/[^\s<>()\[\]"']+/g;
// webURL is target if it is an absolute http(s) URL with a host and no
// user info, else "" (equipo.WebURL on the server).
@@ -120,12 +116,6 @@ function start(root) {
return "";
}
}
- function safeHref(target) {
- if (target.startsWith("/tasks/")) {
- return /^[A-Za-z0-9_-]{1,64}$/.test(target.slice(7)) && equipo ? equipo + target : "";
- }
- return webURL(target);
- }
function link(href, text) {
const a = document.createElement("a");
a.href = href;
@@ -144,7 +134,7 @@ function start(root) {
end = m.index + target.length;
label = target;
}
- const href = safeHref(target);
+ const href = webURL(target);
if (!href) continue;
el.append(text.slice(last, m.index), link(href, label));
last = end;
@@ -152,33 +142,16 @@ function start(root) {
el.append(text.slice(last));
}
- // The words for a card's options and, once it is answered, its state:
- // Equipo's own wording (its chat.card copy). Base's server has the same
- // (cardOption and cardStatus in ask_cards.go).
- // Tables without a prototype, read only for their own keys: an option
- // or state named "constructor" is just an unknown word.
- const table = (o) => Object.assign(Object.create(null), o);
- const word = (t, k) => (typeof k === "string" && Object.hasOwn(t, k) ? t[k] : undefined);
- const options = table({ merge: "Merge", wait: "Wait for checks", wait_mac: "Wait for a Mac", not_now: "Not now", publish: "Publish" });
- const sites = table({ publishing: "Publishing.", published: "Published", unconfirmed: "Publish could not be confirmed",
- failed: "Publishing failed.", declined: "Not published." });
- const chosen = table({ merge: "Merging without checks.", wait: "Waiting for checks.", wait_mac: "Waiting for a Mac.",
- not_now: "Not now.", publish: "Publishing." });
- function cardStatus(c) {
- const site = c.kind === "publish" && c.site && word(sites, c.site.state);
- if (site) return site;
- if (c.state === "open") return "";
- return word(chosen, c.choice) || "Nothing to decide any more.";
- }
-
- // A card: a question, a merge card (with its preview) or a publish card
- // (with its site), drawn as the server draws it (the ask-card template).
- // A newer revision redraws it; an answered question goes.
+ // A card, drawn from its fields alone as the server draws it (the
+ // ask-card template): the question, a link per link, a button per option
+ // (its label, posting its value) while it is open, and the line saying
+ // how it ended. A newer revision redraws it; a card that has ended with
+ // nothing to say goes, and so does one of a kind Base does not draw.
+ const kinds = ["question", "confirm", "outcome", "connect"];
function addCard(c) {
if (!c || !c.id) return;
const old = item("data-card", c.id);
- const known = c.kind === "question" || c.kind === "merge" || c.kind === "publish";
- if (!known || (c.kind === "question" && c.state !== "open")) {
+ if (!kinds.includes(c.kind) || (c.state !== "open" && !c.result)) {
if (old) old.remove();
scroll();
return;
@@ -189,18 +162,19 @@ function start(root) {
li.dataset.card = c.id;
li.dataset.revision = String(c.revision);
const q = document.createElement("p");
- q.textContent = c.question || c.name || "";
+ q.textContent = c.question || "";
li.append(q);
- for (const [href, text] of [[c.preview_url, "Open the preview"], [c.site && c.site.url, "Open the site"]]) {
- const safe = href && webURL(href);
+ for (const l of c.links || []) {
+ const safe = l && typeof l.url === "string" && webURL(l.url);
if (!safe) continue;
const p = document.createElement("p");
- const a = link(safe, text);
+ const a = link(safe, l.label || safe);
a.className = "card-link";
p.append(a);
li.append(p);
}
- if (c.state === "open") {
+ const options = (c.options || []).filter((o) => o && typeof o.value === "string" && o.value);
+ if (c.state === "open" && options.length) {
const form = document.createElement("form");
form.className = "choices";
form.method = "post";
@@ -210,20 +184,21 @@ function start(root) {
rev.name = "revision";
rev.value = String(c.revision);
form.append(rev);
- for (const o of c.options || []) {
+ for (const o of options) {
const b = document.createElement("button");
b.className = "btn ghost";
b.type = "submit";
b.name = "choice";
- b.value = o;
- b.textContent = word(options, o) || o;
+ b.value = o.value;
+ b.textContent = o.label || o.value;
form.append(b);
}
li.append(form);
- } else {
+ }
+ if (c.result) {
const p = document.createElement("p");
p.className = "card-state";
- p.textContent = cardStatus(c);
+ p.textContent = c.result;
li.append(p);
}
if (old) old.replaceWith(li);
@@ -394,8 +369,10 @@ function start(root) {
return;
}
addCard(out.card);
- addMessage(out.message);
- setTurn(out.turn);
+ // An outcome card's answer starts no turn: no message, nothing to wait
+ // for (both are null).
+ if (out.message) addMessage(out.message);
+ if (out.turn) setTurn(out.turn);
});
// The ⋯ menu: Escape and a click elsewhere close it. Escape gives focus
diff --git a/internal/web/app.go b/internal/web/app.go
index dd284f3..c2f3a21 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -83,8 +83,7 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
return nil, err
}
// newKey gives each chat form its own request key when the page is drawn.
- pages, err := look.NewRenderer(sub, template.FuncMap{"newKey": equipo.NewKey,
- "cardOption": cardOption, "cardStatus": cardStatus})
+ pages, err := look.NewRenderer(sub, template.FuncMap{"newKey": equipo.NewKey})
if err != nil {
return nil, err
}
diff --git a/internal/web/ask.go b/internal/web/ask.go
index b29aad7..738efec 100644
--- a/internal/web/ask.go
+++ b/internal/web/ask.go
@@ -14,8 +14,8 @@ import (
"amadan.net/carlos/base/internal/store"
)
-// asker is "Ask Base anything": Equipo's coordinator chat, relayed server
-// to server with each member's own device bearer. Nil when
+// asker is "Ask Base anything": the chat with Equipo's Assistant, relayed
+// server to server with each member's own device bearer. Nil when
// BASE_EQUIPO_ORIGIN is unset.
type asker struct {
client *equipo.Client
@@ -162,12 +162,12 @@ func turnStatus(t *equipo.Turn) string {
return "Equipo is answering…"
}
-// fill puts a snapshot in the view: the messages, the open questions and
+// fill puts a snapshot in the view: the messages, the cards to show and
// the newest turn that has not ended.
func (v *askView) fill(s equipo.Snapshot) {
v.Messages = s.Messages
for _, c := range s.Cards {
- if p, ok := c.Projected(); ok && p.Shown() {
+ if p, ok := c.Clean(); ok && p.Shown() {
v.Cards = append(v.Cards, p)
}
}
diff --git a/internal/web/ask_cards.go b/internal/web/ask_cards.go
index eba1f88..459f603 100644
--- a/internal/web/ask_cards.go
+++ b/internal/web/ask_cards.go
@@ -9,73 +9,14 @@ import (
"amadan.net/carlos/base/internal/equipo"
)
-// cardOptions are the buttons' words for the options Equipo's cards offer,
-// in Equipo's own wording (its chat.card.* copy). An option Base does not
-// know shows as Equipo sent it.
-var cardOptions = map[string]string{
- "merge": "Merge",
- "wait": "Wait for checks",
- "wait_mac": "Wait for a Mac",
- "not_now": "Not now",
- "publish": "Publish",
-}
-
-// cardOption is the label of a card's option.
-func cardOption(opt string) string {
- if l, ok := cardOptions[opt]; ok {
- return l
- }
- return opt
-}
-
-// cardStatus is the line a card shows once it no longer waits for an
-// answer: for a publish card, where publishing its site stands; for a
-// merge card, what was chosen. Equipo's words where it has them.
-func cardStatus(c equipo.Card) string {
- if c.Kind == equipo.CardPublish && c.Site != nil {
- switch c.Site.State {
- case "publishing":
- return "Publishing."
- case "published":
- return "Published"
- case "unconfirmed":
- return "Publish could not be confirmed"
- case "failed":
- return "Publishing failed."
- case "declined":
- return "Not published."
- }
- }
- if c.Open() {
- return ""
- }
- switch c.Choice {
- case "merge":
- return "Merging without checks."
- case "wait":
- return "Waiting for checks."
- case "wait_mac":
- return "Waiting for a Mac."
- case "not_now":
- return "Not now."
- case "publish":
- return "Publishing."
- }
- return "Nothing to decide any more."
-}
-
// linkRE finds a Markdown link [label](target), or a bare http(s) URL.
-var (
- linkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+`)
- taskRE = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
-)
+var linkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+`)
-// richText is a coordinator's line as HTML: every character escaped, and
-// a Markdown link or bare URL made a link only when it goes to an http(s)
-// address, or to one of Equipo's own /tasks/ pages (on Equipo's origin).
-// Anything else, raw HTML included, stays as text. The panel's script
-// does the same (ask.js, rich).
-func richText(text, origin string) template.HTML {
+// richText is an Assistant's line as HTML: every character escaped, and a
+// Markdown link or bare URL made a link only when it goes to an http(s)
+// address. Anything else, raw HTML and relative paths included, stays as
+// text. The panel's script does the same (ask.js, rich).
+func richText(text string) template.HTML {
var b strings.Builder
last := 0
for _, m := range linkRE.FindAllStringSubmatchIndex(text, -1) {
@@ -89,7 +30,7 @@ func richText(text, origin string) template.HTML {
target = strings.TrimRight(text[m[0]:m[1]], ".,;:!?")
end, label = m[0]+len(target), target
}
- href := safeHref(target, origin)
+ href := equipo.WebURL(target)
if href == "" {
continue
}
@@ -101,16 +42,5 @@ func richText(text, origin string) template.HTML {
return template.HTML(b.String())
}
-// safeHref is where a link in Equipo's text may go, or "".
-func safeHref(target, origin string) string {
- if task, ok := strings.CutPrefix(target, "/tasks/"); ok {
- if !taskRE.MatchString(task) {
- return ""
- }
- return strings.TrimRight(origin, "/") + "/tasks/" + task
- }
- return equipo.WebURL(target)
-}
-
-// Rich is a coordinator's line with its links (richText), for templates.
-func (v askView) Rich(text string) template.HTML { return richText(text, v.Equipo) }
+// Rich is an Assistant's line with its links (richText), for templates.
+func (v askView) Rich(text string) template.HTML { return richText(text) }
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
index 4498c2f..f9655a9 100644
--- a/internal/web/ask_relay.go
+++ b/internal/web/ask_relay.go
@@ -131,15 +131,30 @@ func (a *app) askCancel(w http.ResponseWriter, r *http.Request) {
a.askDone(w, r, c, err, map[string]string{"state": askReady})
}
-// askAnswer is POST /ask/cards/{id}/answer: one of a question's buttons.
+// askAnswer is POST /ask/cards/{id}/answer: one of a card's buttons,
+// relayed as its option's value. The answer is the card, and the message
+// and turn the answer started, if any: an outcome card's answer starts
+// none (Equipo sends an empty message and a zero turn), so both are null
+// and the panel waits for nothing.
func (a *app) askAnswer(w http.ResponseWriter, r *http.Request) {
c, ok := a.askBearer(w, r)
if !ok {
return
}
rev, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
- out, err := a.ask.client.Answer(r.Context(), c.token, chi.URLParam(r, "id"), r.PostFormValue("choice"), rev, askKey(r.PostFormValue("key")))
- out.Card, _ = out.Card.Projected()
+ in, err := a.ask.client.Answer(r.Context(), c.token, chi.URLParam(r, "id"), r.PostFormValue("choice"), rev, askKey(r.PostFormValue("key")))
+ var out struct {
+ Card equipo.Card `json:"card"`
+ Message *equipo.Message `json:"message"`
+ Turn *equipo.Turn `json:"turn"`
+ }
+ out.Card, _ = in.Card.Clean()
+ if in.Message.ID != "" {
+ out.Message = &in.Message
+ }
+ if in.Turn.ID != "" {
+ out.Turn = &in.Turn
+ }
a.askDone(w, r, c, err, out)
}
@@ -343,8 +358,7 @@ func (e sseEvent) frame() string {
// project reduces an event's data to the conversation's shape, the one
// /ask/state uses; ok is false for every other kind of event, and for
-// cards Base does not show (equipo.Card.Projected: projects, tasks and
-// the rest stay in Equipo).
+// cards of a kind Base does not draw (equipo.Card.Clean).
func project(typ string, raw json.RawMessage) (any, bool) {
switch typ {
case "message":
@@ -358,7 +372,7 @@ func project(typ string, raw json.RawMessage) (any, bool) {
if json.Unmarshal(raw, &c) != nil || c.ID == "" {
return nil, false
}
- return c.Projected()
+ return c.Clean()
case "delta":
var d struct {
TurnID string `json:"turn_id"`
diff --git a/internal/web/relay_internal_test.go b/internal/web/relay_internal_test.go
index bea935e..2e8a4ae 100644
--- a/internal/web/relay_internal_test.go
+++ b/internal/web/relay_internal_test.go
@@ -78,7 +78,7 @@ func TestRelayParsesBareCR(t *testing.T) {
// conversation's shape, bad JSON and bad ids dropped.
func TestRelayWritesItsOwnFrames(t *testing.T) {
project := `{"cursor":45,"type":"card","data":{"id":"c_1","revision":1,"kind":"project","state":"added","project_id":"p_1","name":"oficina/sample"}}`
- question := `{"cursor":46,"type":"card","data":{"id":"c_2","revision":1,"kind":"question","state":"open","turn_id":"t_1","project_id":"p_9","question":"Which branch?","options":["main"],"task_id":"tk_9"}}`
+ question := `{"cursor":46,"type":"card","data":{"id":"c_2","revision":1,"kind":"question","state":"open","turn_id":"t_1","project_id":"p_9","question":"Which branch?","options":[{"value":"main","label":"main"}],"links":[],"result":"","task_id":"tk_9"}}`
upstream := frame("41", "turn", turnEvent) + frame("44", "message", `{"cursor":44,"data":{oops`) +
frame("x1", "message", msgEvent) + frame("45", "card", project) + frame("46", "card", question) +
"event: ping\ndata: {\"type\":\"ping\"}\n\n" + ": comment\nretry: 1\n\n"
@@ -90,7 +90,7 @@ func TestRelayWritesItsOwnFrames(t *testing.T) {
}
for _, want := range []string{
"id: 41\nevent: turn\ndata: {\"type\":\"turn\",\"data\":{\"id\":\"t_1\",\"kind\":\"\",\"state\":\"running\",\"reason\":\"\"}}\n\n",
- "id: 46\nevent: card\ndata: {\"type\":\"card\",\"data\":{\"id\":\"c_2\",\"revision\":1,\"kind\":\"question\",\"state\":\"open\",\"question\":\"Which branch?\",\"options\":[\"main\"],\"choice\":\"\"}}\n\n",
+ "id: 46\nevent: card\ndata: {\"type\":\"card\",\"data\":{\"id\":\"c_2\",\"revision\":1,\"kind\":\"question\",\"state\":\"open\",\"question\":\"Which branch?\",\"options\":[{\"value\":\"main\",\"label\":\"main\"}],\"links\":[],\"result\":\"\"}}\n\n",
": ping\n\n",
} {
if !strings.Contains(out, want) {
@@ -99,23 +99,20 @@ func TestRelayWritesItsOwnFrames(t *testing.T) {
}
}
-// Merge and publish cards pass with only their own fields; anything else
-// Equipo puts on them stays behind.
-func TestRelayMergeAndPublishCards(t *testing.T) {
- merge := `{"cursor":47,"type":"card","data":{"id":"c_3","revision":2,"kind":"merge","state":"open","turn_id":"t_9","project_id":"p_9","name":"Quick website","question":"Merge Quick website without checks?","options":["merge","wait"],"choice":"","task_id":"tk0001","created_at":"2026-11-12T10:00:00Z","specialist":{"x":1},"secret_field":"s3cr3t","preview_url":"https://eq-tk0001.devbox.test/"}}`
- publish := `{"cursor":48,"type":"card","data":{"id":"c_4","revision":1,"kind":"publish","state":"open","project_id":"p_9","name":"Quick website","question":"Publish Quick website on the web as site-sample?","options":["publish","not_now"],"choice":"","task_id":"tk0001","site":{"app":"site-sample","sha":"eee","state":"asked","at":"2026-11-12T10:00:00Z","token":"s3cr3t"}}}`
- out := relayTo(t, strings.NewReader(frame("47", "card", merge)+frame("48", "card", publish)), time.Second, func() {})
- for _, banned := range []string{"p_9", "t_9", "specialist", "s3cr3t", "created_at", "\"at\""} {
+// The Assistant's cards pass as they are drawn: options as value and
+// label, web links only, and nothing else Equipo puts on them. A card of a
+// kind Base does not draw (a task card) is not passed on.
+func TestRelayGenericCards(t *testing.T) {
+ outcome := `{"cursor":47,"type":"card","data":{"id":"c_3","revision":2,"kind":"outcome","state":"open","turn_id":"t_9","project_id":"p_9","question":"This is ready. Go ahead?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[{"label":"See it","url":"https://preview.example.test/"},{"label":"Bad","url":"javascript:alert(1)"}],"result":"","task_id":"tk0001","secret_field":"s3cr3t"}}`
+ task := `{"cursor":48,"type":"card","data":{"id":"c_4","revision":1,"kind":"task","state":"open","question":"Merge tk0001?","options":[],"links":[],"result":""}}`
+ out := relayTo(t, strings.NewReader(frame("47", "card", outcome)+frame("48", "card", task)), time.Second, func() {})
+ for _, banned := range []string{"p_9", "t_9", "tk0001", "s3cr3t", "javascript", "c_4", "id: 48"} {
if strings.Contains(out, banned) {
t.Errorf("relayed %q:\n%s", banned, out)
}
}
- for _, want := range []string{
- `data: {"type":"card","data":{"id":"c_3","revision":2,"kind":"merge","state":"open","name":"Quick website","task_id":"tk0001","question":"Merge Quick website without checks?","options":["merge","wait"],"choice":"","preview_url":"https://eq-tk0001.devbox.test/"}}`,
- `data: {"type":"card","data":{"id":"c_4","revision":1,"kind":"publish","state":"open","name":"Quick website","task_id":"tk0001","question":"Publish Quick website on the web as site-sample?","options":["publish","not_now"],"choice":"","site":{"app":"site-sample","sha":"eee","state":"asked"}}}`,
- } {
- if !strings.Contains(out, want) {
- t.Errorf("relay lacks %s:\n%s", want, out)
- }
+ want := `data: {"type":"card","data":{"id":"c_3","revision":2,"kind":"outcome","state":"open","question":"This is ready. Go ahead?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[{"label":"See it","url":"https://preview.example.test/"}],"result":""}}`
+ if !strings.Contains(out, want) {
+ t.Errorf("relay lacks %s:\n%s", want, out)
}
}
diff --git a/internal/web/rich_internal_test.go b/internal/web/rich_internal_test.go
index 501ac4b..43ef364 100644
--- a/internal/web/rich_internal_test.go
+++ b/internal/web/rich_internal_test.go
@@ -2,23 +2,34 @@ package web
import "testing"
-// Equipo's lines may carry Markdown links. Base links only web addresses
-// and Equipo's own /tasks/ pages (on Equipo's origin); everything else,
-// raw HTML included, stays text.
+// Equipo's lines may carry Markdown links. Base links only web addresses;
+// everything else, raw HTML included, stays text.
func TestRichText(t *testing.T) {
- const origin = "https://equipo.test/"
for in, want := range map[string]string{
- "Published [Quick website](/tasks/tk0001) at https://site-sample.example.test/.": `Published <a href="https://equipo.test/tasks/tk0001" target="_blank" rel="noopener">Quick website</a> at <a href="https://site-sample.example.test/" target="_blank" rel="noopener">https://site-sample.example.test/</a>.`,
- "See [docs](https://docs.test/a?b=1&c=2)": `See <a href="https://docs.test/a?b=1&amp;c=2" target="_blank" rel="noopener">docs</a>`,
- "[x](javascript:alert(1))": `[x](javascript:alert(1))`,
- "[x](data:text/html,<b>hi</b>)": `[x](data:text/html,&lt;b&gt;hi&lt;/b&gt;)`,
- "<script>alert(1)</script> <b>bold</b>": `&lt;script&gt;alert(1)&lt;/script&gt; &lt;b&gt;bold&lt;/b&gt;`,
- "[<img src=x onerror=alert(1)>](https://a.test/)": `<a href="https://a.test/" target="_blank" rel="noopener">&lt;img src=x onerror=alert(1)&gt;</a>`,
- "[x](/tasks/../admin)": `[x](/tasks/../admin)`,
- "[x](//evil.test/)": `[x](//evil.test/)`,
- "plain & simple": `plain &amp; simple`,
+ "Published at https://site-sample.example.test/.": `Published at <a href="https://site-sample.example.test/" target="_blank" rel="noopener">https://site-sample.example.test/</a>.`,
+ "See [docs](https://docs.test/a?b=1&c=2)": `See <a href="https://docs.test/a?b=1&amp;c=2" target="_blank" rel="noopener">docs</a>`,
+ "[x](javascript:alert(1))": `[x](javascript:alert(1))`,
+ "[x](data:text/html,<b>hi</b>)": `[x](data:text/html,&lt;b&gt;hi&lt;/b&gt;)`,
+ "<script>alert(1)</script> <b>bold</b>": `&lt;script&gt;alert(1)&lt;/script&gt; &lt;b&gt;bold&lt;/b&gt;`,
+ "[<img src=x onerror=alert(1)>](https://a.test/)": `<a href="https://a.test/" target="_blank" rel="noopener">&lt;img src=x onerror=alert(1)&gt;</a>`,
+ "[x](/tasks/../admin)": `[x](/tasks/../admin)`,
+ "[x](//evil.test/)": `[x](//evil.test/)`,
+ "plain & simple": `plain &amp; simple`,
} {
- if got := string(richText(in, origin)); got != want {
+ if got := string(richText(in)); got != want {
+ t.Errorf("richText(%q)\n got %s\nwant %s", in, got, want)
+ }
+ }
+}
+
+// The Assistant never points at the team's pages: a /tasks/ link is
+// text, while a web address still links.
+func TestRichTextHasNoTaskLinks(t *testing.T) {
+ for in, want := range map[string]string{
+ "[x](/tasks/tk1)": `[x](/tasks/tk1)`,
+ "See [it](https://site.example.test/)": `See <a href="https://site.example.test/" target="_blank" rel="noopener">it</a>`,
+ } {
+ if got := string(richText(in)); got != want {
t.Errorf("richText(%q)\n got %s\nwant %s", in, got, want)
}
}
diff --git a/internal/web/templates/ask.html b/internal/web/templates/ask.html
index e48f1ee..a2ce106 100644
--- a/internal/web/templates/ask.html
+++ b/internal/web/templates/ask.html
@@ -1,7 +1,7 @@
{{define "title"}}Ask Base · {{.Name}}{{end}}
{{define "head"}}{{if .Ask.Turn}}<noscript><meta http-equiv="refresh" content="5"></noscript>{{end}}{{end}}
{{define "main"}}<main class="inner">
-<section class="sheet glass ask-page" data-ask data-state="{{.Ask.State}}" data-equipo="{{.Ask.Equipo}}">
+<section class="sheet glass ask-page" data-ask data-state="{{.Ask.State}}">
<div class="crumb"><a class="wordmark" href="/">base</a><span>Ask Base</span></div>
{{template "ask-head" .Ask}}
{{template "ask-body" .Ask}}
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html
index 8c4112c..363b1f7 100644
--- a/internal/web/templates/partials/chat.html
+++ b/internal/web/templates/partials/chat.html
@@ -2,15 +2,14 @@
{{define "ask-head"}}<div class="ask-head"><h2 id="ask-title">Ask Base</h2>{{template "ask-more" .}}</div>{{end}}
{{/* Open Equipo, behind a ⋯ menu: a <details>, so it opens without scripts. */}}
{{define "ask-more"}}<details class="ask-more"><summary class="round" aria-label="More"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 12h.01M12 12h.01M18 12h.01"/></svg></summary><div class="ask-menu glass"><a href="{{.Equipo}}" target="_blank" rel="noopener">Open Equipo</a></div></details>{{end}}
-{{define "ask-panel"}}<dialog id="ask-panel" class="ask-panel glass" aria-labelledby="ask-title" data-ask data-state="{{.State}}" data-equipo="{{.Equipo}}">
+{{define "ask-panel"}}<dialog id="ask-panel" class="ask-panel glass" aria-labelledby="ask-title" data-ask data-state="{{.State}}">
<div class="ask-head"><h2 id="ask-title">Ask Base</h2>{{template "ask-more" .}}<button class="round close" type="button" data-ask-close aria-label="Close"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></div>
{{template "ask-body" .}}</dialog>{{end}}
-{{/* A card: a question, a merge card (with its preview) or a publish card (with its site). The panel's script draws the same (ask.js, cardItem). */}}
-{{define "ask-card"}}<li class="msg card card-{{.Kind}}" data-card="{{.ID}}" data-revision="{{.Revision}}"><p>{{with .Question}}{{.}}{{else}}{{.Name}}{{end}}</p>
-{{- with .PreviewURL}}<p><a class="card-link" href="{{.}}" target="_blank" rel="noopener">Open the preview</a></p>{{end}}
-{{- with .Site}}{{with .URL}}<p><a class="card-link" href="{{.}}" target="_blank" rel="noopener">Open the site</a></p>{{end}}{{end}}
-{{- if .Open}}<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="{{.}}">{{cardOption .}}</button>{{end}}</form>
-{{- else}}<p class="card-state">{{cardStatus .}}</p>{{end}}</li>{{end}}
+{{/* A card, drawn from its fields alone: the question, a link per link, a button per option (its label, posting its value) while it is open, and the line saying how it ended. The panel's script draws the same (ask.js, addCard). */}}
+{{define "ask-card"}}<li class="msg card card-{{.Kind}}" data-card="{{.ID}}" data-revision="{{.Revision}}"><p>{{.Question}}</p>
+{{- range .Links}}<p><a class="card-link" href="{{.URL}}" target="_blank" rel="noopener">{{.Label}}</a></p>{{end}}
+{{- 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>
<form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn" type="submit">Connect Equipo</button></form>
@@ -28,7 +27,7 @@
</div>
<div class="ask-chat" data-when="ready"{{if not (.Shows "ready")}} hidden{{end}}>
<div class="log"><ol class="thread" role="log" aria-label="Conversation">
-{{range .Messages}}<li class="msg {{.Role}}" data-id="{{.ID}}">{{if eq .Role "coordinator"}}{{$.Rich .Text}}{{else}}{{.Text}}{{end}}</li>
+{{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" .}}
{{end}}</ol>
<button class="jump" type="button" hidden>Jump to latest</button></div>
diff --git a/internal/webtest/ask_test.go b/internal/webtest/ask_test.go
index ce380c6..9766bfc 100644
--- a/internal/webtest/ask_test.go
+++ b/internal/webtest/ask_test.go
@@ -8,6 +8,7 @@ import (
"html"
"net/http"
"net/url"
+ "os"
"regexp"
"strconv"
"strings"
@@ -15,6 +16,7 @@ import (
"time"
"amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/equipo"
"amadan.net/carlos/base/internal/equipo/equipotest"
"amadan.net/carlos/base/internal/store"
"amadan.net/carlos/base/internal/web"
@@ -310,7 +312,7 @@ func TestAskFormsCarryKeys(t *testing.T) {
answer.Set("choice", "main")
a.post("/ask/cards/"+id+"/answer", answer)
a.post(cancel[1], stop)
- for path, key := range map[string]string{"/api/v1/cards/" + id + "/answer": answer.Get("key"), "/api/v1" + strings.TrimPrefix(cancel[1], "/ask"): stop.Get("key")} {
+ for path, key := range map[string]string{"/api/v1/assistant/cards/" + id + "/answer": answer.Get("key"), "/api/v1/assistant" + strings.TrimPrefix(cancel[1], "/ask"): stop.Get("key")} {
if c := f.Calls(path); len(c) != 1 || c[0].Header.Get("Idempotency-Key") != key {
t.Errorf("%s: %+v, want key %q", path, c, key)
}
@@ -329,7 +331,7 @@ func TestAskSendRelaysWithBearer(t *testing.T) {
if r.Code != 303 || r.Location() != "/ask" {
t.Fatalf("send: %d %q", r.Code, r.Location())
}
- calls := f.Calls("/api/v1/messages")
+ calls := f.Calls("/api/v1/assistant/messages")
if len(calls) != 1 {
t.Fatalf("sends: %d", len(calls))
}
@@ -374,7 +376,7 @@ func TestAskRefusesCrossSitePost(t *testing.T) {
if r := a.postFrom("https://evil.example", "/ask/messages", url.Values{"text": {"hi"}}); r.Code != 403 {
t.Fatalf("cross-site send: %d", r.Code)
}
- if n := len(f.Calls("/api/v1/messages")); n != 0 {
+ if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 {
t.Fatalf("relayed a cross-site send")
}
}
@@ -393,7 +395,7 @@ func TestAskScriptsOffCardAndCancel(t *testing.T) {
if r := a.post(action, fields); r.Code != 303 || r.Location() != "/ask" {
t.Fatalf("answer: %d", r.Code)
}
- ans := f.Calls("/api/v1/cards/" + id + "/answer")
+ ans := f.Calls("/api/v1/assistant/cards/" + id + "/answer")
if len(ans) != 1 || ans[0].Body != `{"choice":"main","revision":1}`+"\n" && ans[0].Body != `{"choice":"main","revision":1}` {
t.Fatalf("answer relayed: %+v", ans)
}
@@ -512,7 +514,7 @@ func TestAskEventsRelay(t *testing.T) {
if strings.Contains(stream.String(), token) {
t.Fatal("the stream carried the bearer")
}
- up := f.Calls("/api/v1/events")
+ up := f.Calls("/api/v1/assistant/events")
if len(up) == 0 || up[0].Header.Get("Authorization") != "Bearer "+token || up[0].Query != "after="+strconv64(st.Cursor) {
t.Fatalf("upstream: %+v", up)
}
@@ -619,118 +621,133 @@ func TestAskMoreMenu(t *testing.T) {
}
}
-// Scripts off: a merge card with its preview, a publish card through to
-// published with its site, and Equipo's Markdown links, all on /ask.
-func TestAskMergeAndPublishCards(t *testing.T) {
+// cardItem is the card with id as /ask draws it.
+func cardItem(t *testing.T, page, id string) string {
+ t.Helper()
+ m := regexp.MustCompile(`(?s)<li class="msg card card-[a-z]+" data-card="` + regexp.QuoteMeta(id) + `"[^>]*>.*?</li>`).FindString(page)
+ if m == "" {
+ t.Fatalf("no card %s in:\n%s", id, page)
+ }
+ return m
+}
+
+var goOptions = []equipo.Option{{Value: "go", Label: "Go ahead"}, {Value: "later", Label: "Not yet"}}
+
+// Cards are drawn from their fields alone: a button is an option's label
+// posting its value, a link is one of the card's links, opening in a new
+// tab. An outcome and a confirm card draw the same way; Base has no words
+// of its own for any kind.
+func TestAskCardsAreDrawnFromFields(t *testing.T) {
a, f := newAskApp(t)
a.connectEquipo(f)
- merge := f.AskMerge("Quick website")
- f.SetPreview(merge, "https://eq-tk0001.devbox.test/", true)
- publish := f.AskPublish("Quick website", "site-sample")
- f.Say("Try [this](javascript:alert(1)) or <b>that</b>.")
+ links := []equipo.Link{{Label: "See it", URL: "https://preview.example.test/"}}
+ outcome := f.AskOutcome("This is ready. Go ahead?", goOptions, links)
+ confirm := f.AskKind("confirm", "Send the invitation?", goOptions, links)
+ task := f.AskKind("task", "Merge tk0001?", goOptions, nil)
+ f.Say("Try [this](javascript:alert(1)), [that](/tasks/tk1) or <b>bold</b>.")
page := a.get("/ask").Body
- for _, want := range []string{
- "Merge Quick website without checks?",
- `<a class="card-link" href="https://eq-tk0001.devbox.test/" target="_blank" rel="noopener">Open the preview</a>`,
- `name="choice" value="merge">Merge</button>`, `name="choice" value="wait">Wait for checks</button>`,
- "Publish Quick website on the web as site-sample?",
- `name="choice" value="publish">Publish</button>`, `name="choice" value="not_now">Not now</button>`,
- "Try [this](javascript:alert(1)) or &lt;b&gt;that&lt;/b&gt;.",
- } {
- if !strings.Contains(page, want) {
- t.Errorf("/ask lacks %s:\n%s", want, page)
+ if !strings.Contains(page, `<li class="msg coordinator" data-id="`) ||
+ !strings.Contains(page, "Try [this](javascript:alert(1)), [that](/tasks/tk1) or &lt;b&gt;bold&lt;/b&gt;.</li>") {
+ t.Errorf("the Assistant's line is not plain text:\n%s", page)
+ }
+ for _, id := range []string{outcome, confirm} {
+ card := cardItem(t, page, id)
+ for _, want := range []string{
+ `<button class="btn ghost" type="submit" name="choice" value="go">Go ahead</button>`,
+ `<button class="btn ghost" type="submit" name="choice" value="later">Not yet</button>`,
+ `<a class="card-link" href="https://preview.example.test/" target="_blank" rel="noopener">See it</a>`,
+ } {
+ if !strings.Contains(card, want) {
+ t.Errorf("card %s lacks %s:\n%s", id, want, card)
+ }
+ }
+ if fields := formFields(t, page, "/ask/cards/"+id+"/answer"); fields.Get("revision") != "1" {
+ t.Errorf("card %s answers at revision %q", id, fields.Get("revision"))
}
}
- if strings.Contains(page, `href="javascript`) {
- t.Fatal("a javascript: link was rendered")
- }
-
- // A stale merge answer (the preview arrived unseen) is not resent: Base
- // goes back to /ask, which shows the card at its new revision.
- f.SetPreview(merge, "https://eq-tk0001.devbox.test/v2/", false)
- stale := formFields(t, page, "/ask/cards/"+merge+"/answer")
- stale.Set("choice", "merge")
- if r := a.post("/ask/cards/"+merge+"/answer", stale); r.Code != 303 || r.Location() != "/ask" {
- t.Fatalf("stale answer: %d %q", r.Code, r.Location())
- }
- if calls := f.Calls("/api/v1/cards/" + merge + "/answer"); len(calls) != 1 || !strings.Contains(calls[0].Body, `"revision":2`) {
- t.Fatalf("answers: %+v", calls)
- }
- if fresh := formFields(t, a.get("/ask").Body, "/ask/cards/"+merge+"/answer"); fresh.Get("revision") != "3" {
- t.Fatalf("after the 409 the card is at revision %q, want 3", fresh.Get("revision"))
+ if strings.Contains(page, task) || strings.Contains(page, "Merge tk0001?") {
+ t.Errorf("a task card was drawn:\n%s", page)
}
-
- answer := formFields(t, page, "/ask/cards/"+publish+"/answer")
- answer.Set("choice", "publish")
- a.post("/ask/cards/"+publish+"/answer", answer)
- if c := f.Calls("/api/v1/cards/" + publish + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"publish","revision":1}` {
- t.Fatalf("publish answer: %+v", c)
- }
- var body string
- for i := 0; i < 100; i++ {
- if body = a.get("/ask").Body; strings.Contains(body, "Open the site") {
- break
+ var st struct {
+ Cards []struct {
+ ID string
+ Options []struct{ Value, Label string }
+ Links []struct{ Label, URL string }
}
- time.Sleep(20 * time.Millisecond)
}
- if strings.Contains(body, `<li class="msg person"`) {
- t.Errorf("an answered card left a bubble (Equipo sends no message for it):\n%s", body)
+ if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 2 ||
+ st.Cards[0].ID != outcome || len(st.Cards[0].Options) != 2 || st.Cards[0].Options[0].Label != "Go ahead" ||
+ len(st.Cards[0].Links) != 1 || st.Cards[0].Links[0].URL != "https://preview.example.test/" {
+ t.Fatalf("state: %s", r.Body)
}
- for _, want := range []string{
- `<a class="card-link" href="https://site-sample.example.test/" target="_blank" rel="noopener">Open the site</a>`,
- `<p class="card-state">Published</p>`,
- `Published <a href="` + f.URL + `/tasks/tk0001" target="_blank" rel="noopener">Quick website</a> at <a href="https://site-sample.example.test/"`,
- } {
- if !strings.Contains(body, want) {
- t.Errorf("after publishing /ask lacks %s:\n%s", want, body)
+ for _, file := range []string{"../web/ask_cards.go", "../look/static/ask.js", "../web/templates/partials/chat.html"} {
+ raw, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, word := range []string{"Merge", "Wait for checks", "Publishing"} {
+ if strings.Contains(string(raw), word) {
+ t.Errorf("%s says %q", file, word)
+ }
}
}
}
-// A merge card answered from the panel, in Equipo's real shapes (options
-// merge and wait; the 200 answer carries the answered card and an empty
-// message and turn): Base relays the click, answers with the card as
-// answered, and its stream passes the answered card on.
-func TestAskMergeAnswerRoundTrip(t *testing.T) {
+// Answering posts the option's value, at the card's revision. An answered
+// outcome card says how it ended and brings no message and no turn (Equipo
+// answers with empty ones). An answer at a stale revision is not resent:
+// /ask shows the card as it is now.
+func TestAskAnswerRelaysValue(t *testing.T) {
a, f := newAskApp(t)
a.connectEquipo(f)
- var st struct{ Cursor int64 }
- merge := f.AskMerge("Swipe from the edge to go back doesn't work")
- if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil {
- t.Fatalf("state: %s", r.Body)
+ id := f.AskOutcome("This is ready. Go ahead?", goOptions, nil)
+ answer := formFields(t, a.get("/ask").Body, "/ask/cards/"+id+"/answer")
+ answer.Set("choice", "go")
+ if r := a.post("/ask/cards/"+id+"/answer", answer); r.Code != 303 || r.Location() != "/ask" {
+ t.Fatalf("answer: %d %q", r.Code, r.Location())
+ }
+ if c := f.Calls("/api/v1/assistant/cards/" + id + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"go","revision":1}` {
+ t.Fatalf("relayed: %+v", c)
+ }
+ page := a.get("/ask").Body
+ if card := cardItem(t, page, id); !strings.Contains(card, `<p class="card-state">Go ahead</p>`) || strings.Contains(card, "<form") {
+ t.Errorf("answered card:\n%s", card)
}
- req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/cards/"+merge+"/answer",
- strings.NewReader(url.Values{"choice": {"merge"}, "revision": {"1"}, "key": {"k-merge"}}.Encode()))
+ if strings.Contains(page, `<li class="msg person"`) || strings.Contains(page, `class="stop" method="post" action="/ask/turns/`) {
+ t.Errorf("an answered outcome card left a bubble or a turn:\n%s", page)
+ }
+
+ // Scripts on: the answer is the card, and no message or turn at all.
+ other := f.AskOutcome("Publish it?", goOptions, nil)
+ req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/cards/"+other+"/answer",
+ strings.NewReader(url.Values{"choice": {"later"}, "revision": {"1"}, "key": {"k-out"}}.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Origin", a.origin)
req.Header.Set("Accept", "application/json")
res := a.do(req)
var out struct {
- Card struct{ ID, Kind, State, Choice string }
- Message struct{ ID string }
- Turn struct{ ID string }
- }
- if res.Code != 200 || json.Unmarshal([]byte(res.Body), &out) != nil || out.Card.ID != merge || out.Card.State != "answered" ||
- out.Card.Choice != "merge" || out.Message.ID != "" || out.Turn.ID != "" {
- t.Fatalf("answer: %d %s", res.Code, res.Body)
+ Card struct{ ID, State, Result string }
+ Message *struct{}
+ Turn *struct{}
+ }
+ if res.Code != 200 || json.Unmarshal([]byte(res.Body), &out) != nil || out.Card.ID != other || out.Card.State != "answered" ||
+ out.Card.Result != "Not yet" || out.Message != nil || out.Turn != nil {
+ t.Fatalf("JSON answer: %d %s", res.Code, res.Body)
+ }
+
+ // Stale: the card moved on unseen. One call, a 409, and /ask shows the
+ // card at its new revision.
+ q := f.AskQuestion("Which one?", "red", "blue")
+ stale := formFields(t, a.get("/ask").Body, "/ask/cards/"+q+"/answer")
+ f.SetCard(q, "open", "")
+ stale.Set("choice", "red")
+ if r := a.post("/ask/cards/"+q+"/answer", stale); r.Code != 303 || r.Location() != "/ask" {
+ t.Fatalf("stale answer: %d %q", r.Code, r.Location())
}
- if c := f.Calls("/api/v1/cards/" + merge + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"merge","revision":1}` ||
- c[0].Header.Get("Idempotency-Key") != "k-merge" {
- t.Fatalf("relayed: %+v", c)
+ if c := f.Calls("/api/v1/assistant/cards/" + q + "/answer"); len(c) != 1 || strings.TrimSpace(c[0].Body) != `{"choice":"red","revision":1}` {
+ t.Fatalf("stale answers: %+v", c)
}
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
- defer cancel()
- sreq, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+strconv64(st.Cursor), nil)
- sres, err := a.client.Do(sreq)
- if err != nil {
- t.Fatal(err)
- }
- defer sres.Body.Close()
- sc := bufio.NewScanner(sres.Body)
- for sc.Scan() {
- if line := sc.Text(); strings.HasPrefix(line, "data: ") && strings.Contains(line, `"state":"answered"`) && strings.Contains(line, `"choice":"merge"`) {
- return
- }
+ if fresh := formFields(t, a.get("/ask").Body, "/ask/cards/"+q+"/answer"); fresh.Get("revision") != "2" {
+ t.Fatalf("after the 409 the card is at revision %q, want 2", fresh.Get("revision"))
}
- t.Fatal("the stream never passed the answered merge card on")
}