oficina / equipo Public

chat: a refused scriptless taste answer shows the card again

Final review M6 (Fable 10). Without script, a taste card answered
with a third ticked feel (or a box past 300 characters) was refused
as invalid and the person got a page of its own (422), losing the
card.

A scriptless answer that carries taste answers and is refused as
invalid now returns to its page with card_failed=<card>; the
conversation (and a job thread) renders that card again, still open,
with the card error inline: roster.failed, the words chat-stream.js
already shows for a refused answer (no new copy). With script the
answer keeps its error status, which the script shows inline.

Test (RED first):
  go test ./internal/equipo/ -run TestTasteFormTooManyFeelsInline
    RED: "scriptless: 422 \"\" <!doctype html>..."
    GREEN: ok; also -run 'TestTaste|Card'

Mutations (each restored):
  no markCardFailed on the conversation -> "the card is not shown
                                           again with its error" FAIL
  no redirect for an invalid answer     -> the RED above
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 15104812193f9c787033de09d419ad1f53d80727 parent 46213a0
3 files changed, +152 −11
  • internal/equipo/chat_page.go +77 −10
  • internal/equipo/taste_form_test.go +74 −0
  • internal/equipo/templates/chat.html +1 −1
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index bd512be8..da7e325f 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"slices"
"strconv"
"strings"
@@ -82,6 +83,9 @@ type chatLine struct {
// chatCard is one card under the message that ends its turn. Line is the
// card's sentence; the forms post to the page routes below.
type chatCard struct {
+ // Failed is the card error shown inline when the page was asked to
+ // show this card's answer as refused (card_failed); "" hides it.
+ Failed string
ReportAction *reportAction
ProjectMono monoLine
ThreadActivity string
@@ -486,6 +490,7 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
return
}
view.Messages = feedLines(win.Messages, win.Cards, choices, tasks, loc)
+ markCardFailed(view.Messages, r.URL.Query().Get("card_failed"))
// Nothing can answer: no turn shows the thinking line or a timer
// until an attempt starts on a connection. A turn waiting for one, and
// any queued behind it, get a quiet status under the person's message;
@@ -660,6 +665,7 @@ func (a *application) jobPage(w http.ResponseWriter, r *http.Request) {
}
view := chatView{Offline: !snap.Runner.Online, Cursor: snap.Cursor, Job: head}
view.Messages = feedLines(snap.Messages, snap.Cards, choices, tasks, chats.Zone(address))
+ markCardFailed(view.Messages, r.URL.Query().Get("card_failed"))
for i := range view.Messages {
for _, cards := range [][]chatCard{view.Messages[i].Cards, view.Messages[i].Receipts} {
for k := range cards {
@@ -807,19 +813,69 @@ func (a *application) chatCardAnswer(w http.ResponseWriter, r *http.Request) {
if back == "/conversation" || strings.HasPrefix(back, "/jobs/") {
back += "#conversation-end"
}
+ taste := formTaste(r)
+ if taste != nil && !strings.Contains(r.Header.Get("Accept"), "application/json") {
+ // A scriptless taste answer the instance refuses (a third feel,
+ // a box too long) shows the card again with the card error
+ // inline, not a page of its own; with script, chat-stream.js
+ // does that from the error status.
+ failed := cardFailedBack(back, chi.URLParam(r, "id"))
+ a.chatActionFailTo(w, r, back, failed, func(ctx context.Context, address string) error {
+ return a.answerCardForm(ctx, address, r, taste)
+ })
+ return
+ }
a.chatActionTo(w, r, back, func(ctx context.Context, address string) error {
- revision, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
- var remember *string
- if r.PostFormValue("remember_present") == "1" {
- name := ""
- if r.PostFormValue("remember") == "1" {
- name = r.PostFormValue("remember_name")
+ return a.answerCardForm(ctx, address, r, taste)
+ })
+}
+
+// answerCardForm answers the card a page form names, as the session's
+// person.
+func (a *application) answerCardForm(ctx context.Context, address string, r *http.Request, taste *wire.TasteAnswer) error {
+ revision, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
+ var remember *string
+ if r.PostFormValue("remember_present") == "1" {
+ name := ""
+ if r.PostFormValue("remember") == "1" {
+ name = r.PostFormValue("remember_name")
+ }
+ remember = &name
+ }
+ _, _, err := a.store.Chat().Answer(ctx, address, chi.URLParam(r, "id"), wire.AnswerCard{Choice: r.PostFormValue("choice"), Revision: revision, Note: r.PostFormValue("note"), Option: formOption(r), RememberName: remember, Taste: taste})
+ return err
+}
+
+// cardFailedBack is back with the card marked as refused (card_failed),
+// ahead of back's fragment: the page it returns to renders that card
+// again with the card error inline (markCardFailed).
+func cardFailedBack(back, card string) string {
+ path, fragment, cut := strings.Cut(back, "#")
+ sep := "?"
+ if strings.Contains(path, "?") {
+ sep = "&"
+ }
+ out := path + sep + "card_failed=" + url.QueryEscape(card)
+ if cut {
+ out += "#" + fragment
+ }
+ return out
+}
+
+// markCardFailed sets the card error on the card id among lines, for a
+// page whose request names it (card_failed): reused words, the card
+// error chat-stream.js shows for a refused answer.
+func markCardFailed(lines []chatLine, id string) {
+ if id == "" {
+ return
+ }
+ for i := range lines {
+ for j := range lines[i].Cards {
+ if lines[i].Cards[j].ID == id {
+ lines[i].Cards[j].Failed = copyText("roster.failed")
}
- remember = &name
}
- _, _, err := a.store.Chat().Answer(ctx, address, chi.URLParam(r, "id"), wire.AnswerCard{Choice: r.PostFormValue("choice"), Revision: revision, Note: r.PostFormValue("note"), Option: formOption(r), RememberName: remember, Taste: formTaste(r)})
- return err
- })
+ }
}
func (a *application) chatProjectRemove(w http.ResponseWriter, r *http.Request) {
@@ -836,6 +892,13 @@ func (a *application) chatAction(w http.ResponseWriter, r *http.Request, act fun
// chatActionTo runs a page action as the session's person and returns to
// back (a fixed path the handler chose, never one from the form).
func (a *application) chatActionTo(w http.ResponseWriter, r *http.Request, back string, act func(context.Context, string) error) {
+ a.chatActionFailTo(w, r, back, "", act)
+}
+
+// chatActionFailTo is chatActionTo that returns to failed (a fixed path
+// the handler chose) instead of a page of its own when act is refused as
+// invalid; "" keeps that page.
+func (a *application) chatActionFailTo(w http.ResponseWriter, r *http.Request, back, failed string, act func(context.Context, string) error) {
w.Header().Set("Cache-Control", "no-store")
ctx, address, ok := sessionContext(r)
if !ok {
@@ -862,6 +925,10 @@ func (a *application) chatActionTo(w http.ResponseWriter, r *http.Request, back
http.Redirect(w, r, back, http.StatusSeeOther)
return
}
+ if failed != "" && errors.Is(err, chat.ErrInvalid) {
+ http.Redirect(w, r, failed, http.StatusSeeOther)
+ return
+ }
a.failure(w, r, chatError(err))
return
}
diff --git a/internal/equipo/taste_form_test.go b/internal/equipo/taste_form_test.go
new file mode 100644
index 00000000..2bc914b6
--- /dev/null
+++ b/internal/equipo/taste_form_test.go
@@ -0,0 +1,74 @@
+package equipo
+
+import (
+ "html"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo/identity"
+ "amadan.net/rastrillo/rastrillo/auth"
+ "github.com/go-chi/chi/v5"
+)
+
+// TestTasteFormTooManyFeelsInline (final review, M6 / Fable 10): a
+// scriptless taste card answer with a third ticked feel is refused, but
+// not with a full-page error (422): the page returns to the conversation and
+// renders the card again, still open, with the generic card error
+// inline (roster.failed, no new words). A scripted answer keeps its 422,
+// which chat-stream.js shows inline itself.
+func TestTasteFormTooManyFeelsInline(t *testing.T) {
+ r := newPreviewPassRig(t)
+ exec := func(q string, args ...any) {
+ t.Helper()
+ if _, e := r.s.db.Writer().Exec(q, args...); e != nil {
+ t.Fatal(e)
+ }
+ }
+ now := r.s.Chat().Now()
+ exec("INSERT INTO chat_cards(id,person,kind,state,turn_id,question,options,revision,created_at,updated_at,lane) VALUES('c_taste',?,'design_taste','open','','A few questions','[\"use\",\"skip\"]',1,?,?,'')", r.principal.Address, now, now)
+ exec("INSERT INTO chat_taste_asks(card_id,person,project_id,turn_id,state,feels,words,answer,created_at,updated_at) VALUES('c_taste',?,'p_preview','','asked','[\"Calm\",\"Bold\",\"Warm\"]','','',?,?)", r.principal.Address, now, now)
+ app := &application{store: r.s, origin: r.s.personOrigin}
+ route := chi.NewRouter()
+ route.Post("/conversation/cards/{id}/answer", app.chatCardAnswer)
+ route.Get("/conversation", app.chatPage)
+ do := func(method, path string, form url.Values, accept string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(method, "https://equipo.example"+path, strings.NewReader(form.Encode()))
+ if form != nil {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ if accept != "" {
+ req.Header.Set("Accept", accept)
+ }
+ req = identity.With(req, auth.Identity{Address: r.principal.Address, At: r.clock.Now()})
+ w := httptest.NewRecorder()
+ route.ServeHTTP(w, req)
+ return w
+ }
+ three := url.Values{"revision": {"1"}, "choice": {"use"}, "feel": {"Calm", "Bold", "Warm"}, "taste_avoid": {"Gradients"}}
+ if w := do("POST", "/conversation/cards/c_taste/answer", three, "application/json"); w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("scripted: %d %s", w.Code, w.Body)
+ }
+ w := do("POST", "/conversation/cards/c_taste/answer", three, "")
+ if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/conversation?card_failed=c_taste#conversation-end" {
+ t.Fatalf("scriptless: %d %q %s", w.Code, w.Header().Get("Location"), w.Body)
+ }
+ page := do("GET", "/conversation?card_failed=c_taste", nil, "")
+ if page.Code != 200 {
+ t.Fatalf("conversation: %d %s", page.Code, page.Body)
+ }
+ body := page.Body.String()
+ want := `<p equipo-card-error role="alert">` + html.EscapeString(copyText("roster.failed")) + `</p>`
+ if !strings.Contains(body, want) || !strings.Contains(body, `action="/conversation/cards/c_taste/answer"`) {
+ t.Fatalf("the card is not shown again with its error %q:\n%s", want, body)
+ }
+ if strings.Count(body, `<p equipo-card-error role="alert">`) != 1 {
+ t.Fatalf("other cards show the error:\n%s", body)
+ }
+ if plain := do("GET", "/conversation", nil, ""); strings.Contains(plain.Body.String(), `<p equipo-card-error role="alert">`) {
+ t.Fatal("the error shows without the query")
+ }
+}
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index 26fbad3d..25deb73c 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -22,7 +22,7 @@
{{else if or (eq .Kind "merge_ships") (eq .Kind "merge_policy") (eq .Kind "merge_receipt")}}{{if eq .Kind "merge_receipt"}}<div equipo-card-line equipo-markdown data-merge-receipt>{{chatMarkdown .Line}}</div>{{else}}<p equipo-card-line>{{.Line}}</p>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{template "project-name-confirm" .}}{{range .Options}}<button rst-btn="{{if or (eq . "save") (eq . "not_ships")}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-merge-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if .Access}}{{template "access-card" .}}
{{else if eq .Kind "access"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<details equipo-grant><summary rst-btn>{{copy "chat.card.grant"}}</summary><p>{{.GrantHow}}</p><code>amadan agent grant {{.Agent}} {{.Namespace}}</code><form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}<button rst-btn name="choice" value="check" type="submit" data-grant-check>{{copy "chat.card.grant_check"}}</button></form></details>{{end}}
-{{end}}<p equipo-card-error role="alert" hidden></p></section>{{end}}{{if .Presentation.Coverage.Skipped}}<section equipo-roster-card data-flat>{{template "work-task-receipt" .}}</section>{{end}}{{if not .SetAside}}{{range .ResearchReports}}<div equipo-roster-byline><span equipo-roster-avatar>{{icon "search"}}</span><b>{{copy "work.specialist.research"}}</b><span>{{copy "roster.reports"}}</span>{{template "roster-project" $}}{{with .At}}<time datetime="{{.Format "2006-01-02T15:04:05Z07:00"}}">{{.Format "15:04"}}</time>{{end}}</div><section equipo-roster-card data-research-report><header equipo-roster-research-head><h3>{{copy "roster.research"}}</h3>{{with $.Presentation.Context.TaskTitle}}<span equipo-roster-task>{{.}}</span>{{end}}</header><p>{{.Summary}}</p><ol equipo-roster-findings>{{range .Facts}}<li><div><strong>{{.Label}}</strong> {{.Value}}</div>{{range .Sources}}{{if .URL}}<a href="{{.URL}}" title="{{.URL}}" target="_blank" rel="noopener"><span>{{.Domain}}</span></a>{{else}}<span>{{.ID}}</span>{{end}}{{end}}</li>{{end}}{{range .Gaps}}<li data-gap>{{.}}</li>{{end}}</ol><div equipo-roster-links><button type="button" rst-btn data-report-talk aria-controls="report-thread-{{$.ID}}" aria-expanded="{{if $.Presentation.Thread}}true{{else}}false{{end}}">{{copy "roster.talk"}}</button><a href="/tasks/{{$.TaskID}}#research-{{.StepID}}">{{copy "roster.research_log"}} ({{len .Fetches}})</a></div></section>{{end}}{{end}}
+{{end}}<p equipo-card-error role="alert"{{if not .Failed}} hidden{{end}}>{{.Failed}}</p></section>{{end}}{{if .Presentation.Coverage.Skipped}}<section equipo-roster-card data-flat>{{template "work-task-receipt" .}}</section>{{end}}{{if not .SetAside}}{{range .ResearchReports}}<div equipo-roster-byline><span equipo-roster-avatar>{{icon "search"}}</span><b>{{copy "work.specialist.research"}}</b><span>{{copy "roster.reports"}}</span>{{template "roster-project" $}}{{with .At}}<time datetime="{{.Format "2006-01-02T15:04:05Z07:00"}}">{{.Format "15:04"}}</time>{{end}}</div><section equipo-roster-card data-research-report><header equipo-roster-research-head><h3>{{copy "roster.research"}}</h3>{{with $.Presentation.Context.TaskTitle}}<span equipo-roster-task>{{.}}</span>{{end}}</header><p>{{.Summary}}</p><ol equipo-roster-findings>{{range .Facts}}<li><div><strong>{{.Label}}</strong> {{.Value}}</div>{{range .Sources}}{{if .URL}}<a href="{{.URL}}" title="{{.URL}}" target="_blank" rel="noopener"><span>{{.Domain}}</span></a>{{else}}<span>{{.ID}}</span>{{end}}{{end}}</li>{{end}}{{range .Gaps}}<li data-gap>{{.}}</li>{{end}}</ol><div equipo-roster-links><button type="button" rst-btn data-report-talk aria-controls="report-thread-{{$.ID}}" aria-expanded="{{if $.Presentation.Thread}}true{{else}}false{{end}}">{{copy "roster.talk"}}</button><a href="/tasks/{{$.TaskID}}#research-{{.StepID}}">{{copy "roster.research_log"}} ({{len .Fetches}})</a></div></section>{{end}}{{end}}
</li>{{end}}
{{define "taste-questions"}}<fieldset equipo-taste-feels><legend>{{copy "chat.card.taste_feel"}}</legend>{{with .Taste}}{{range .Feels}}<label equipo-taste-feel><input type="checkbox" name="feel" value="{{.}}"><span>{{.}}</span></label>{{end}}{{end}}<label equipo-taste-box><span>{{copy "chat.card.taste_other"}}</span><textarea name="taste_other" maxlength="300" rows="1"></textarea></label></fieldset><label equipo-taste-box><span>{{copy "chat.card.taste_like"}}</span><textarea name="taste_like" maxlength="300" rows="2"></textarea></label><label equipo-taste-box><span>{{copy "chat.card.taste_avoid"}}</span><textarea name="taste_avoid" maxlength="300" rows="2"></textarea></label><label equipo-taste-box><span>{{copy "chat.card.taste_keep"}}</span><textarea name="taste_keep" maxlength="300" rows="2"></textarea></label>{{end}}
{{define "roster-copy-hold"}}<div equipo-copy-hold><span equipo-roster-stage>{{copy "roster.copy_waiting"}}</span><h3>{{.Line}}</h3><p>{{.HoldReason}}</p>{{with .Presentation.Coverage}}<div equipo-copy-meter>{{if .Known}}{{if .Total}}<meter min="0" max="{{.Total}}" value="{{.Reviewed}}" aria-label="{{printf (copy "roster.copy_count") .Reviewed .Total}}"></meter>{{end}}<span>{{printf (copy "roster.copy_count") .Reviewed .Total}}</span>{{else}}<span>{{copy "roster.copy_coverage"}}</span>{{end}}{{with .Since}}<small>{{printf (copy "roster.copy_since") (.Format "15:04")}}</small>{{end}}</div>{{end}}<div equipo-actions><a rst-btn="primary" href="/conversation?about={{.TaskID}}">{{copy "work.decide.ask_coordinator"}}</a>{{if .Task.CopyCanSkip}}<form method="post" action="/conversation/tasks/{{.TaskID}}/continue-without-copy" data-card-form><button rst-btn type="submit" data-copy-continue>{{copy "copy.continue"}}</button></form>{{end}}</div></div>{{end}}