Phase 11, part 3: approvals for what agents send out

Agents can now ask to publish or schedule a post, send an email, add
someone to a mailing list, or apply an SEO change. Each waits on the
Approvals page (with a count in the sidebar) for an admin or a member with
edit on its module, who can edit it first, approve or refuse it, and let
the agent take that class of action on its own with a cap per day. A
rotation after a leak revokes the old keys and withdraws everything
allowed. All of it is in the audit log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 10:54:53 -07:00
co-authored by Claude Opus 5.5
parent bfb74e7700
commit 311d2e815b
17 changed files with 1396 additions and 13 deletions
+254
View File
@@ -0,0 +1,254 @@
// Package approvals holds what agents ask to send out of Supermarket (a
// post, an email, a mailing-list add, a change to a site) until a person
// says yes or no, and the kinds of action a person has let an agent take
// on its own, each with a cap per day.
package approvals
import (
"database/sql"
"encoding/json"
"errors"
"time"
"supermarket/internal/db"
)
// Statuses.
const (
Waiting = "waiting"
Done = "done" // approved and carried out (or done on its own)
Refused = "refused"
Failed = "failed" // approved, but carrying it out failed
)
// Request is something an agent asked to do.
type Request struct {
ID int64
Agent int64
Class string
Module string
Target int64
Params map[string]string
Summary string
Status string
Created time.Time
Decided time.Time
DecidedBy int64 // 0 with Done: on its own
Result string
}
// OnItsOwn says whether the agent did it without asking.
func (r *Request) OnItsOwn() bool {
return r.Status != Waiting && r.Status != Refused && r.DecidedBy == 0
}
// Grant lets an agent take a class of action on its own.
type Grant struct {
Agent int64
Class string
Label string
Module string
DailyCap int // 0: none
GrantedBy int64
Granted time.Time
}
const timeFormat = "2006-01-02T15:04:05.000Z"
func ts(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(timeFormat)
}
func parseTS(s string) time.Time {
t, _ := time.Parse(timeFormat, s)
return t
}
var ErrNotFound = errors.New("no such request")
// ErrDecided is a request someone has already decided.
var ErrDecided = errors.New("this request was already decided")
// Add records a request, waiting (or, done on its own, with its result).
func Add(d *db.DB, r *Request, now time.Time) error {
params, _ := json.Marshal(r.Params)
if r.Status == "" {
r.Status = Waiting
}
r.Created = now
decided := ""
if r.Status != Waiting {
r.Decided = now
decided = ts(now)
}
var err error
r.ID, err = d.Insert(`INSERT INTO approvals (agent_id, class, module, target_id, params, summary, status, created_at, decided_at, decided_by, result)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, r.Agent, r.Class, r.Module, r.Target, string(params), r.Summary, r.Status, ts(now), decided, r.DecidedBy, r.Result)
return err
}
const cols = `id, agent_id, class, module, target_id, params, summary, status, created_at, decided_at, decided_by, result`
func scan(row interface{ Scan(...any) error }) (*Request, error) {
var r Request
var params, created, decided string
if err := row.Scan(&r.ID, &r.Agent, &r.Class, &r.Module, &r.Target, &params, &r.Summary, &r.Status, &created, &decided, &r.DecidedBy, &r.Result); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
_ = json.Unmarshal([]byte(params), &r.Params)
if r.Params == nil {
r.Params = map[string]string{}
}
r.Created, r.Decided = parseTS(created), parseTS(decided)
return &r, nil
}
// Get finds a request.
func Get(d *db.DB, id int64) (*Request, error) {
return scan(d.QueryRow(`SELECT `+cols+` FROM approvals WHERE id = ?`, id))
}
// List are requests with a status (all, if ""), newest first; agent 0 for
// every agent's.
func List(d *db.DB, status string, agent int64, limit int) ([]Request, error) {
q := `SELECT ` + cols + ` FROM approvals WHERE 1 = 1`
var args []any
if status != "" {
q += ` AND status = ?`
args = append(args, status)
}
if agent != 0 {
q += ` AND agent_id = ?`
args = append(args, agent)
}
q += ` ORDER BY id DESC LIMIT ?`
args = append(args, limit)
rows, err := d.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Request
for rows.Next() {
r, err := scan(rows)
if err != nil {
return nil, err
}
out = append(out, *r)
}
return out, rows.Err()
}
// Claim takes a waiting request for a decision, once: of two people
// deciding together, one gets ErrDecided.
func Claim(d *db.DB, id, by int64, status string, now time.Time) error {
res, err := d.Exec(`UPDATE approvals SET status = ?, decided_at = ?, decided_by = ? WHERE id = ? AND status = ?`,
status, ts(now), by, id, Waiting)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n != 1 {
return ErrDecided
}
return nil
}
// Finish records how carrying out an approved request went.
func Finish(d *db.DB, id int64, failed error) error {
status, result := Done, ""
if failed != nil {
status, result = Failed, failed.Error()
}
_, err := d.Exec(`UPDATE approvals SET status = ?, result = ? WHERE id = ?`, status, result, id)
return err
}
// SetResult notes what a done request led to (a post's address).
func SetResult(d *db.DB, id int64, result string) error {
_, err := d.Exec(`UPDATE approvals SET result = ? WHERE id = ?`, result, id)
return err
}
// Pending says whether there's already a waiting request for the same
// class and target: asking twice doesn't make two.
func Pending(d *db.DB, class string, target int64) (*Request, error) {
r, err := scan(d.QueryRow(`SELECT `+cols+` FROM approvals WHERE class = ? AND target_id = ? AND status = ? ORDER BY id LIMIT 1`, class, target, Waiting))
if errors.Is(err, ErrNotFound) {
return nil, nil
}
return r, err
}
// Grants.
// Allow lets an agent take a class of action on its own (or changes its cap).
func Allow(d *db.DB, g Grant, now time.Time) error {
_, err := d.Exec(`INSERT INTO agent_autonomy (agent_id, class, label, module, daily_cap, granted_by, granted_at) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (agent_id, class) DO UPDATE SET daily_cap = excluded.daily_cap, label = excluded.label, granted_by = excluded.granted_by, granted_at = excluded.granted_at`,
g.Agent, g.Class, g.Label, g.Module, g.DailyCap, g.GrantedBy, ts(now))
return err
}
// Withdraw takes a class back.
func Withdraw(d *db.DB, agent int64, class string) error {
_, err := d.Exec(`DELETE FROM agent_autonomy WHERE agent_id = ? AND class = ?`, agent, class)
return err
}
// WithdrawAll takes everything back from an agent (its key leaked).
func WithdrawAll(d *db.DB, agent int64) error {
_, err := d.Exec(`DELETE FROM agent_autonomy WHERE agent_id = ?`, agent)
return err
}
// Grants are what agents may do on their own: agent 0 for all.
func Grants(d *db.DB, agent int64) ([]Grant, error) {
q := `SELECT agent_id, class, label, module, daily_cap, granted_by, granted_at FROM agent_autonomy`
var args []any
if agent != 0 {
q += ` WHERE agent_id = ?`
args = append(args, agent)
}
rows, err := d.Query(q+` ORDER BY agent_id, class`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Grant
for rows.Next() {
var g Grant
var at string
if err := rows.Scan(&g.Agent, &g.Class, &g.Label, &g.Module, &g.DailyCap, &g.GrantedBy, &at); err != nil {
return nil, err
}
g.Granted = parseTS(at)
out = append(out, g)
}
return out, rows.Err()
}
// Allowed says whether an agent may take a class of action on its own
// now: it was granted, and today's count is under the cap.
func Allowed(d *db.DB, agent int64, class string, now time.Time) (bool, error) {
var cap int
err := d.QueryRow(`SELECT daily_cap FROM agent_autonomy WHERE agent_id = ? AND class = ?`, agent, class).Scan(&cap)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
if cap == 0 {
return true, nil
}
var n int
err = d.QueryRow(`SELECT count(*) FROM approvals WHERE agent_id = ? AND class = ? AND decided_by = 0 AND status IN (?, ?) AND decided_at >= ?`,
agent, class, Done, Failed, ts(now.Add(-24*time.Hour))).Scan(&n)
return n < cap, err
}
+65
View File
@@ -0,0 +1,65 @@
package approvals
import (
"errors"
"path/filepath"
"testing"
"time"
"supermarket/internal/db"
)
func TestRequestsAndGrants(t *testing.T) {
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
now := time.Now()
r := &Request{Agent: 5, Class: "post:2", Module: "content", Target: 11, Params: map[string]string{"at": "x"}, Summary: "Publish draft 11"}
if err := Add(d, r, now); err != nil {
t.Fatal(err)
}
if p, _ := Pending(d, "post:2", 11); p == nil || p.ID != r.ID {
t.Error("not pending")
}
if err := Claim(d, r.ID, 1, Done, now); err != nil {
t.Fatal(err)
}
if err := Claim(d, r.ID, 2, Refused, now); !errors.Is(err, ErrDecided) {
t.Errorf("decided twice: %v", err)
}
Finish(d, r.ID, errors.New("X said no"))
got, _ := Get(d, r.ID)
if got.Status != Failed || got.Result != "X said no" || got.DecidedBy != 1 || got.Params["at"] != "x" || got.OnItsOwn() {
t.Errorf("%+v", got)
}
if list, _ := List(d, Waiting, 0, 10); len(list) != 0 {
t.Error("still waiting")
}
// On its own, with a cap of 2 a day.
if ok, _ := Allowed(d, 5, "email-first", now); ok {
t.Error("allowed without a grant")
}
Allow(d, Grant{Agent: 5, Class: "email-first", Label: "send a first email", Module: "prospects", DailyCap: 2, GrantedBy: 1}, now)
for i := 0; i < 2; i++ {
if ok, _ := Allowed(d, 5, "email-first", now); !ok {
t.Fatalf("call %d refused", i)
}
Add(d, &Request{Agent: 5, Class: "email-first", Module: "prospects", Target: int64(i), Summary: "x", Status: Done}, now)
}
if ok, _ := Allowed(d, 5, "email-first", now); ok {
t.Error("over the cap")
}
if ok, _ := Allowed(d, 5, "email-first", now.Add(25*time.Hour)); !ok {
t.Error("the cap is per day")
}
if gs, _ := Grants(d, 5); len(gs) != 1 || gs[0].DailyCap != 2 {
t.Errorf("grants %+v", gs)
}
WithdrawAll(d, 5)
if ok, _ := Allowed(d, 5, "email-first", now.Add(25*time.Hour)); ok {
t.Error("withdrawn")
}
}
+32
View File
@@ -185,6 +185,38 @@ CREATE TABLE agent_keys (
);
CREATE INDEX agent_keys_user ON agent_keys(user_id);
ALTER TABLE users ADD COLUMN description TEXT NOT NULL DEFAULT '';
`,
},
// 38
{
Note: "approvals: what agents ask to send out, and what they may do on their own",
SQLite: `
CREATE TABLE approvals (
id INTEGER PRIMARY KEY,
agent_id INTEGER NOT NULL,
class TEXT NOT NULL, -- post:<account>, email-first, email-reply, list:<id>, seo-change:<site>
module TEXT NOT NULL, -- whose members decide: content, prospects, seo
target_id INTEGER NOT NULL, -- the draft, message, contact or change
params TEXT NOT NULL DEFAULT '{}', -- what else it needs: when, which list…
summary TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'waiting', -- waiting, done, refused, failed
created_at TEXT NOT NULL,
decided_at TEXT NOT NULL DEFAULT '',
decided_by INTEGER NOT NULL DEFAULT 0, -- 0 with done: the agent did it on its own
result TEXT NOT NULL DEFAULT ''
);
CREATE INDEX approvals_status ON approvals(status, created_at);
CREATE INDEX approvals_agent ON approvals(agent_id, class, decided_at);
CREATE TABLE agent_autonomy (
agent_id INTEGER NOT NULL,
class TEXT NOT NULL,
label TEXT NOT NULL, -- what it is, in words
module TEXT NOT NULL,
daily_cap INTEGER NOT NULL DEFAULT 0, -- 0: no cap
granted_by INTEGER NOT NULL,
granted_at TEXT NOT NULL,
PRIMARY KEY (agent_id, class)
);
`,
},
}
+2
View File
@@ -31,6 +31,8 @@ var routeAreas = map[string]string{
"=/": areaSignedIn, "=/search": areaSignedIn, "/settings/account": areaSignedIn,
"/users": areaSignedIn, "=/settings": areaSignedIn,
// Each request is checked against its module (approvals.go).
"/approvals": areaSignedIn,
// Old addresses that only redirect.
"=/profile": areaSignedIn, "=/core": areaSignedIn,
+3
View File
@@ -178,6 +178,9 @@ var actionLabels = map[string]string{
"synced-mailing-lists": "synced the mailing lists", "changed-profile": "changed the company profile",
"agent-created": "made the agent", "agent-changed": "changed what this agent may do:", "key-rotated": "rotated the key of",
"key-made": "made a new key for", "key-revoked": "revoked a key of",
"asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused",
"allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:",
"wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market",
}
func actionLabel(a string) string {
+21 -1
View File
@@ -7,6 +7,7 @@ import (
"strings"
"time"
"supermarket/internal/approvals"
"supermarket/internal/audit"
"supermarket/internal/fileutil"
"supermarket/internal/mcpserver"
@@ -273,6 +274,8 @@ func (s *Server) showKey(w http.ResponseWriter, r *http.Request, u *users.User,
type agentData struct {
Row agentRow
Grants []grant
Allowed []approvals.Grant // what it may do on its own
Asked []approvals.Request
Problem string
Now time.Time
}
@@ -314,7 +317,10 @@ func (s *Server) renderAgent(w http.ResponseWriter, r *http.Request, u *users.Us
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "agent", page{Title: u.Name, Nav: "settings/agents", Data: agentData{Row: row, Grants: agentGrants(), Problem: problem, Now: now}})
d := agentData{Row: row, Grants: agentGrants(), Problem: problem, Now: now}
d.Allowed, _ = approvals.Grants(s.DB, u.ID)
d.Asked, _ = approvals.List(s.DB, "", u.ID, 20)
s.render(w, r, "agent", page{Title: u.Name, Nav: "settings/agents", Data: d})
return
}
}
@@ -348,7 +354,21 @@ func (s *Server) agentAction(w http.ResponseWriter, r *http.Request) {
}
case "rotate":
var key string
leaked := r.PostFormValue("leaked") == "on"
if leaked {
// A leaked key: its replacement starts with nothing allowed on
// its own, and the old key stops now.
if err = approvals.WithdrawAll(s.DB, u.ID); err == nil {
err = users.RevokeAll(s.DB, u.ID, now)
}
if err != nil {
break
}
}
if key, _, err = users.Rotate(s.DB, u.ID, now); err == nil {
if leaked {
s.audit(r, "key-revoked", u.Name, "it leaked: every key revoked, and what it may do on its own withdrawn")
}
if s.isHermes(u.ID) {
err = s.newHermesToken(key)
}
+1
View File
@@ -62,6 +62,7 @@ func (s *Server) AgentTools(srv *mcp.Server, c *mcpserver.Caller) {
if may("market", true) {
s.marketActTools(srv, c)
}
s.approvalTools(srv, c)
}
// toolJSON is a tool's answer, as JSON text.
+681
View File
@@ -0,0 +1,681 @@
package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"supermarket/internal/approvals"
"supermarket/internal/content"
"supermarket/internal/mcpserver"
"supermarket/internal/outreach"
"supermarket/internal/posting"
"supermarket/internal/prospects"
"supermarket/internal/seo"
"supermarket/internal/users"
)
// Approvals. Anything an agent asks to send out of Supermarket waits here
// for a person: members with edit on its module, or admins. They can edit
// it first, approve or refuse it, and let the agent take that class of
// action on its own from then on, with a cap per day. Agents read untrusted
// text (signals, replies, search results), so nothing goes out on an
// agent's word alone until a person has said this kind may.
// The classes of action.
const (
classEmailFirst = "email-first" // a first email to a prospect
classEmailReply = "email-reply" // a reply in an existing conversation
)
func classPost(account int64) string { return "post:" + strconv.FormatInt(account, 10) }
func classList(list string) string { return "list:" + list }
func classSEO(site string) string { return "seo-change:" + site }
func classKind(class string) string { k, _, _ := strings.Cut(class, ":"); return k }
func classParam(class string) string { _, p, _ := strings.Cut(class, ":"); return p }
func classModule(class string) string {
switch classKind(class) {
case "post":
return "content"
case "seo-change":
return "seo"
}
return "prospects"
}
// classLabel says what a class lets an agent do.
func (s *Server) classLabel(class string) string {
switch classKind(class) {
case "post":
id, _ := strconv.ParseInt(classParam(class), 10, 64)
if a, err := posting.Get(s.DB, id); err == nil {
return "publish posts to " + a.Label()
}
return "publish posts to an account since signed out"
case classEmailFirst:
return "send a first email to a prospect"
case classEmailReply:
return "send a reply in an existing conversation"
case "list":
return "add people to the mailing list " + classParam(class)
case "seo-change":
return "apply SEO changes to " + classParam(class)
}
return class
}
// agentViewer is an agent as a viewer: for the checks people get too
// (posting to an account).
func (s *Server) agentViewer(id int64) *viewer {
u, err := users.ByID(s.DB, id)
if err != nil || u.Status != users.Active {
return &viewer{}
}
m, err := users.MembershipOf(s.DB, users.Team, id)
if err != nil {
return &viewer{}
}
return &viewer{User: u, Member: m}
}
// ask is how an agent's request to send something out starts: done at
// once if the agent may do this on its own (within its cap), else waiting
// for a person. It returns what to tell the agent.
func (s *Server) ask(ctx context.Context, c *mcpserver.Caller, r *approvals.Request) (string, error) {
r.Agent, r.Module = callerID(c), classModule(r.Class)
if p, err := approvals.Pending(s.DB, r.Class, r.Target); err != nil {
return "", err
} else if p != nil {
return fmt.Sprintf("Already waiting for approval (request %d): nothing more to do; approvals_status says when it's decided.", p.ID), nil
}
now := time.Now()
ok, err := approvals.Allowed(s.DB, r.Agent, r.Class, now)
if err != nil {
return "", err
}
if !ok {
if err := approvals.Add(s.DB, r, now); err != nil {
return "", err
}
s.auditAgent(c, "asked-approval", r.Summary, fmt.Sprintf("request %d", r.ID))
return fmt.Sprintf("Waiting for approval (request %d): a person approves or refuses it in Supermarket's Approvals. approvals_status says when it's decided.", r.ID), nil
}
// On its own: carried out now, and recorded.
result, runErr := s.carryOut(ctx, r, s.agentViewer(r.Agent))
r.Status, r.Result = approvals.Done, result
if runErr != nil {
r.Status, r.Result = approvals.Failed, runErr.Error()
}
if err := approvals.Add(s.DB, r, now); err != nil {
return "", err
}
s.auditAgent(c, "did-on-its-own", r.Summary, r.Result)
if runErr != nil {
return "", runErr
}
return "Done (allowed on its own): " + result, nil
}
// carryOut does what a request asked, as as (the person approving it, or
// the agent on its own).
func (s *Server) carryOut(ctx context.Context, r *approvals.Request, as *viewer) (string, error) {
now := time.Now()
switch classKind(r.Class) {
case "post":
account, _ := strconv.ParseInt(classParam(r.Class), 10, 64)
a, err := posting.Get(s.DB, account)
if err != nil {
return "", errors.New("that posting account was signed out")
}
if !s.mayPostAs(as, a) {
return "", fmt.Errorf("%s may not post as %s (Settings → Posting accounts)", whoName(as), a.Label())
}
if err := content.SetAccount(s.DB, r.Target, account); err != nil {
return "", err
}
if as.User != nil {
_ = content.SetPostedBy(s.DB, r.Target, as.User.ID)
}
if at := r.Params["at"]; at != "" {
when, err := time.Parse(time.RFC3339, at)
if err != nil {
return "", err
}
if !when.After(now) {
when = now // its time passed while it waited: now
}
if err := content.Schedule(s.DB, r.Target, when); err != nil {
return "", err
}
return "scheduled for " + when.Local().Format("2 Jan 2006 15:04"), nil
}
pctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
d, err := content.Publish(pctx, s.DB, s.publishers(), s.tagger(), r.Target)
if err != nil {
return "", err
}
return "published as " + d.PostedAs + ": " + d.PostURL, nil
case classEmailFirst, classEmailReply:
if err := outreach.Queue(s.DB, r.Target, now); err != nil {
return "", err
}
return "queued: it goes out in turn, within the sending hours", nil
case "list":
lctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
if err := s.addToListID(lctx, r.Target, classParam(r.Class), false); err != nil {
return "", err
}
return "added to the mailing list", nil
case "seo-change":
if s.gitea() == nil {
return "", errors.New("Gitea isn't connected (Settings → Search engines)")
}
ch, err := seo.GetChange(s.DB, r.Target)
if err != nil {
return "", err
}
var site *seoSite
for _, st := range s.seoSites() {
if auditKey(st) == ch.Site {
site = &st
}
}
if site == nil {
return "", errors.New("that change's website isn't in the profile any more")
}
if err := seo.Decide(s.DB, r.Target, true, now); err != nil {
return "", err
}
ap := s.applier(*site)
go func() {
actx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
if err := ap.Apply(actx, s.DB, r.Target); err != nil {
s.Log.Warn("seo: making the pull request", "change", r.Target, "err", err)
}
}()
return "approved: the pull request is being made", nil
}
return "", fmt.Errorf("no class %q", r.Class)
}
func whoName(v *viewer) string {
if v.User != nil {
return displayName(v.User)
}
return "you"
}
// The Approvals page.
// approvalView is a waiting request, with what's needed to edit it.
type approvalView struct {
approvals.Request
Agent string
ClassLabel string
Draft *content.Draft
Accounts []*posting.Account // for a post: where the viewer may send it
Message *outreach.Message
Change *seo.Change
At time.Time
}
type approvalsData struct {
Waiting []approvalView
Recent []approvalView
Allowed []grantView
}
type grantView struct {
approvals.Grant
Agent string
Mine bool // the viewer may withdraw it
}
// decides says whether a viewer may decide a request in a module.
func decides(v *viewer, module string) bool { return v.can(module, true) }
// waitingFor counts what waits for the viewer: the sidebar's number.
func (s *Server) waitingFor(v *viewer) int {
if v == nil {
return 0
}
list, err := approvals.List(s.DB, approvals.Waiting, 0, 500)
if err != nil {
return 0
}
n := 0
for _, r := range list {
if decides(v, r.Module) {
n++
}
}
return n
}
func (s *Server) agentName(id int64) string {
if u, err := users.ByID(s.DB, id); err == nil {
return u.Name
}
return "an agent since removed"
}
func (s *Server) viewApproval(r approvals.Request, v *viewer) approvalView {
av := approvalView{Request: r, Agent: s.agentName(r.Agent), ClassLabel: s.classLabel(r.Class)}
switch classKind(r.Class) {
case "post":
av.Draft, _ = content.GetDraft(s.DB, r.Target)
if av.Draft != nil {
av.Accounts = s.usableAccounts(v)[av.Draft.Channel]
}
if at := r.Params["at"]; at != "" {
av.At, _ = time.Parse(time.RFC3339, at)
}
case classEmailFirst, classEmailReply:
av.Message, _ = outreach.Get(s.DB, r.Target)
case "seo-change":
av.Change, _ = seo.GetChange(s.DB, r.Target)
}
return av
}
func (s *Server) approvalsPage(w http.ResponseWriter, r *http.Request) {
s.renderApprovals(w, r, "")
}
func (s *Server) renderApprovals(w http.ResponseWriter, r *http.Request, errMsg string) {
v := viewerOf(r)
waiting, err := approvals.List(s.DB, approvals.Waiting, 0, 200)
if err != nil {
s.serverError(w, err)
return
}
recent, err := approvals.List(s.DB, "", 0, 60)
if err != nil {
s.serverError(w, err)
return
}
var d approvalsData
for _, req := range waiting {
if decides(v, req.Module) {
d.Waiting = append(d.Waiting, s.viewApproval(req, v))
}
}
for _, req := range recent {
if req.Status != approvals.Waiting && v.can(req.Module, false) && len(d.Recent) < 30 {
d.Recent = append(d.Recent, approvalView{Request: req, Agent: s.agentName(req.Agent), ClassLabel: s.classLabel(req.Class)})
}
}
grants, err := approvals.Grants(s.DB, 0)
if err != nil {
s.serverError(w, err)
return
}
for _, g := range grants {
if v.can(g.Module, false) {
d.Allowed = append(d.Allowed, grantView{Grant: g, Agent: s.agentName(g.Agent), Mine: decides(v, g.Module)})
}
}
s.render(w, r, "approvals", page{Title: "Approvals", Nav: "approvals", Error: errMsg, Data: d})
}
// approvalAction approves or refuses a request: POST /approvals/{id}/{action}.
func (s *Server) approvalAction(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
v := viewerOf(r)
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
req, err := approvals.Get(s.DB, id)
if errors.Is(err, approvals.ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.serverError(w, err)
return
}
if !decides(v, req.Module) {
s.forbidden(w, r)
return
}
by := int64(0)
if v.User != nil {
by = v.User.ID
}
now := time.Now()
switch r.PathValue("action") {
case "refuse":
if err := approvals.Claim(s.DB, id, by, approvals.Refused, now); err != nil {
s.renderApprovals(w, r, sentence(err.Error())+".")
return
}
s.audit(r, "refused", req.Summary, "asked by "+s.agentName(req.Agent))
redirect(w, r, "/approvals", "refused")
case "approve":
// Edits first, as on the module's own page.
if err := s.editApproval(r, req); err != nil {
s.renderApprovals(w, r, sentence(err.Error())+".")
return
}
if err := approvals.Claim(s.DB, id, by, approvals.Done, now); err != nil {
s.renderApprovals(w, r, sentence(err.Error())+".")
return
}
req, _ = approvals.Get(s.DB, id)
result, runErr := s.carryOut(r.Context(), req, v)
_ = approvals.Finish(s.DB, id, runErr)
if runErr == nil {
_ = approvals.SetResult(s.DB, id, result)
}
s.audit(r, "approved", req.Summary, "asked by "+s.agentName(req.Agent)+": "+result)
if r.PostFormValue("trust") == "on" {
cap, _ := strconv.Atoi(r.PostFormValue("cap"))
g := approvals.Grant{Agent: req.Agent, Class: req.Class, Label: s.classLabel(req.Class), Module: req.Module, DailyCap: max(cap, 0), GrantedBy: by}
if err := approvals.Allow(s.DB, g, now); err != nil {
s.serverError(w, err)
return
}
s.audit(r, "allowed-on-its-own", s.agentName(req.Agent), g.Label+capText(g.DailyCap))
}
if runErr != nil {
s.renderApprovals(w, r, "Approved, but it didn't work: "+runErr.Error())
return
}
redirect(w, r, "/approvals", "approved-request")
default:
http.NotFound(w, r)
}
}
func capText(cap int) string {
if cap <= 0 {
return ", no cap"
}
return fmt.Sprintf(", up to %d a day", cap)
}
// editApproval saves what the person changed before approving: a post's
// text and account, an email's subject and text, a change's wording.
func (s *Server) editApproval(r *http.Request, req *approvals.Request) error {
f := r.PostForm
switch classKind(req.Class) {
case "post":
if text, ok := f["content"]; ok {
if err := content.UpdateDraft(s.DB, req.Target, text[0]); err != nil {
return err
}
}
if title, ok := f["title"]; ok && strings.TrimSpace(title[0]) != "" {
if err := content.UpdateTitle(s.DB, req.Target, title[0]); err != nil {
return err
}
}
if acc := f.Get("account"); acc != "" && acc != classParam(req.Class) {
// Another account: the request becomes that class.
id, _ := strconv.ParseInt(acc, 10, 64)
if _, err := posting.Get(s.DB, id); err != nil {
return errors.New("choose an account")
}
req.Class = classPost(id)
if _, err := s.DB.Exec(`UPDATE approvals SET class = ? WHERE id = ?`, req.Class, req.ID); err != nil {
return err
}
}
case classEmailFirst, classEmailReply:
if body, ok := f["body"]; ok {
if err := outreach.Edit(s.DB, req.Target, f.Get("subject"), body[0]); err != nil {
return err
}
}
case "seo-change":
if t, ok := f["title"]; ok {
if err := seo.EditChange(s.DB, req.Target, t[0], f.Get("description")); err != nil {
return err
}
}
}
return nil
}
// approvalWithdraw takes back what an agent may do on its own.
func (s *Server) approvalWithdraw(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
agent, _ := strconv.ParseInt(r.PostFormValue("agent"), 10, 64)
class := r.PostFormValue("class")
if !decides(viewerOf(r), classModule(class)) {
s.forbidden(w, r)
return
}
if err := approvals.Withdraw(s.DB, agent, class); err != nil {
s.serverError(w, err)
return
}
s.audit(r, "withdrew-on-its-own", s.agentName(agent), s.classLabel(class))
back := "/approvals"
if strings.HasPrefix(r.Referer(), s.PublicURL+"/settings/agents/") {
back = strings.TrimPrefix(r.Referer(), s.PublicURL)
}
redirect(w, r, back, "withdrawn-class")
}
// The tools that ask.
type publishArgs struct {
DraftID int64 `json:"draft_id" jsonschema:"the draft, from content_drafts or content_create_draft"`
AccountID int64 `json:"account_id,omitempty" jsonschema:"the posting account (posting_accounts); empty: the draft's own, or the company's for its channel"`
At string `json:"at,omitempty" jsonschema:"when to publish, as 2026-11-27T09:00 (Supermarket's time zone) or RFC 3339; empty: as soon as it's approved"`
}
type sendArgs struct {
MessageID int64 `json:"message_id" jsonschema:"the outreach draft, from outreach_list or outreach_draft"`
}
type listAddArgs struct {
ContactID int64 `json:"contact_id" jsonschema:"the person, from prospects_review"`
ListID string `json:"list_id" jsonschema:"the Listmonk list's id; only double opt-in lists, which ask the person first"`
}
type changeArgs struct {
ChangeID int64 `json:"change_id" jsonschema:"the proposed change, from seo_changes"`
}
type statusArgs struct {
ID int64 `json:"id,omitempty" jsonschema:"one request; empty for the agent's last 30"`
}
func (s *Server) approvalTools(srv *mcp.Server, c *mcpserver.Caller) {
may := func(module string) bool { return c == nil || c.Can(module, true) }
mcp.AddTool(srv, &mcp.Tool{
Name: "approvals_status",
Description: "Your requests to send things out, and whether a person approved (and what happened), refused, or hasn't decided yet; and what you may do on your own.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a statusArgs) (*mcp.CallToolResult, any, error) {
if a.ID != 0 {
r, err := approvals.Get(s.DB, a.ID)
if err != nil || r.Agent != callerID(c) {
return nil, nil, approvals.ErrNotFound
}
return toolJSON(r)
}
list, err := approvals.List(s.DB, "", callerID(c), 30)
if err != nil {
return nil, nil, err
}
grants, err := approvals.Grants(s.DB, callerID(c))
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]any{"requests": nonNilList(list), "allowed_on_your_own": nonNilList(grants)})
})
if may("content") {
mcp.AddTool(srv, &mcp.Tool{
Name: "posting_accounts",
Description: "The social accounts posts can go out from, with their ids, and whether you may post to each.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
av := s.agentViewer(callerID(c))
type acct struct {
ID int64 `json:"id"`
Account string `json:"account"`
Channel string `json:"channel"`
Working bool `json:"working"`
MayPost bool `json:"you_may_post"`
}
out := []acct{}
for _, a := range s.postingAccounts() {
out = append(out, acct{a.ID, a.Label(), posting.Channel(a.Network), s.working(a), s.mayPostAs(av, a)})
}
return toolJSON(out)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "content_publish",
Description: "Ask to publish a draft, now or at a time, from a posting account. It waits for a person's approval unless you may publish " +
"to that account on your own; the answer says which.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a publishArgs) (*mcp.CallToolResult, any, error) {
d, err := content.GetDraft(s.DB, a.DraftID)
if err != nil {
return nil, nil, err
}
if !d.Editable() {
return nil, nil, errors.New("this draft was published, discarded, or is being published")
}
if p := d.Problem(); p != "" {
return nil, nil, errors.New(p + ": fix it first (content_edit_draft)")
}
acct := a.AccountID
if acct == 0 {
ac, err := s.draftAccount(d)
if err != nil {
return nil, nil, err
}
if ac == nil {
return nil, nil, fmt.Errorf("%s has no posting account: one must be connected first", d.ChannelName())
}
acct = ac.ID
}
ac, err := posting.Get(s.DB, acct)
if err != nil || posting.Channel(ac.Network) != d.Channel {
return nil, nil, errors.New("that isn't an account for this draft's channel (posting_accounts)")
}
if !s.mayPostAs(s.agentViewer(callerID(c)), ac) {
return nil, nil, fmt.Errorf("you may not post as %s: an admin can allow it on Settings → Posting accounts", ac.Label())
}
params := map[string]string{}
what := "Publish"
if strings.TrimSpace(a.At) != "" {
at, err := parseAgentTime(a.At)
if err != nil {
return nil, nil, err
}
params["at"] = at.UTC().Format(time.RFC3339)
what = "Schedule, for " + at.Local().Format("2 Jan 15:04") + ","
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: classPost(acct), Target: d.ID, Params: params,
Summary: fmt.Sprintf("%s a post to %s", what, ac.Label())})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
}
if may("prospects") {
mcp.AddTool(srv, &mcp.Tool{
Name: "outreach_send",
Description: "Ask to send an outreach email draft (it's queued, and goes out within the sending hours). It waits for a person's approval " +
"unless you may send that kind on your own (a first email, or a reply in a conversation).",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a sendArgs) (*mcp.CallToolResult, any, error) {
m, err := outreach.Get(s.DB, a.MessageID)
if err != nil {
return nil, nil, err
}
if m.Channel != outreach.ChannelEmail {
return nil, nil, errors.New("LinkedIn messages are sent by hand, by a person")
}
if m.Status != outreach.StatusDraft && m.Status != outreach.StatusFailed {
return nil, nil, fmt.Errorf("this message is %s, not a draft", m.Status)
}
class := classEmailFirst
if prev, err := outreach.ForContacts(s.DB, []int64{m.ContactID}); err == nil {
for _, o := range prev[m.ContactID] {
if o.ID != m.ID && !o.SentAt.IsZero() {
class = classEmailReply
}
}
}
kind := "a first email"
if class == classEmailReply {
kind = "a reply"
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: class, Target: m.ID, Summary: "Send " + kind + " to " + m.To})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
mcp.AddTool(srv, &mcp.Tool{
Name: "mailing_list_add",
Description: "Ask to add a person to a double opt-in mailing list (Listmonk asks them first). It waits for a person's approval unless you may add to that list on your own.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a listAddArgs) (*mcp.CallToolResult, any, error) {
p, err := prospects.GetContact(s.DB, a.ContactID)
if err != nil {
return nil, nil, err
}
if strings.TrimSpace(a.ListID) == "" {
return nil, nil, errors.New("give the list's id")
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: classList(strings.TrimSpace(a.ListID)), Target: p.ID,
Summary: "Add " + p.Name() + " (" + p.Email + ") to mailing list " + a.ListID})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
}
if may("seo") {
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_apply_change",
Description: "Ask to apply a proposed title and description change (a pull request on the site). It waits for a person's approval unless you may apply changes to that site on your own.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a changeArgs) (*mcp.CallToolResult, any, error) {
ch, err := seo.GetChange(s.DB, a.ChangeID)
if err != nil {
return nil, nil, err
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: classSEO(ch.Site), Target: ch.ID, Summary: "Change the title and description of " + ch.Page})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
}
}
// parseAgentTime reads a time an agent gives: RFC 3339, or local
// 2006-01-02T15:04. It must be ahead, within a year.
func parseAgentTime(v string) (time.Time, error) {
v = strings.TrimSpace(v)
t, err := time.Parse(time.RFC3339, v)
if err != nil {
if t, err = time.ParseInLocation(dateTimeLocal, v, time.Local); err != nil {
return time.Time{}, fmt.Errorf("%q isn't a time: give 2026-11-27T09:00, or RFC 3339", v)
}
}
now := time.Now()
if t.Before(now.Add(-time.Minute)) {
return time.Time{}, errors.New("that time has passed")
}
if t.After(now.AddDate(1, 0, 0)) {
return time.Time{}, errors.New("that's more than a year away")
}
return t, nil
}
+188
View File
@@ -0,0 +1,188 @@
package web
import (
"encoding/json"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/approvals"
"supermarket/internal/content"
"supermarket/internal/posting"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/users"
)
var requestRe = regexp.MustCompile(`request (\d+)`)
func TestAgentDayThroughApprovals(t *testing.T) {
s, h := newServerEdition(t)
sent := &fakePosts{}
s.testPublisher = func(a *posting.Account) content.Publisher { return fakePub{sent, a} }
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
viewerOnly := addUser(t, s, "vi@example.com", users.Member, map[string]users.Access{"content": users.View})
seoOnly := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit})
company := &posting.Account{Network: posting.X, Name: "@acme", External: "acme"}
posting.Save(s.DB, s.Secrets, company, "t", "", time.Now())
agent, key := newAgent(t, s, "Morning writer", map[string]users.Access{"content": users.Edit, "seo": users.View})
// A day's work: read the morning check and What to write next…
_, tools := mcpTools(h, key)
got := " " + strings.Join(tools, " ") + " "
for _, not := range []string{"seo_edit_change", "seo_apply_change"} {
if strings.Contains(got, " "+not+" ") {
t.Errorf("an SEO tool that changes things is offered: %s", not)
}
}
mcpCall(t, h, key, "seo_morning_check", map[string]any{})
mcpCall(t, h, key, "seo_next", map[string]any{})
// …write a draft, and schedule it.
text, _ := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Widgets, faster."})
var d draftView
json.Unmarshal([]byte(text), &d)
// It may not post to the company's account until it's on the grid.
at := time.Now().Add(3 * time.Hour).Format(dateTimeLocal)
if text, isErr := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at}); !isErr || !strings.Contains(text, "may not post as X @acme") {
t.Errorf("not on the grid: %v %s", isErr, text)
}
posting.SetGrants(s.DB, map[int64][]int64{company.ID: {agent.ID}})
text, isErr := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at})
if isErr || !strings.Contains(text, "Waiting for approval") {
t.Fatalf("publish: %s", text)
}
reqID, _ := strconv.ParseInt(requestRe.FindStringSubmatch(text)[1], 10, 64)
// Asking again doesn't make a second request.
if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at}); !strings.Contains(text, "Already waiting") {
t.Errorf("asked twice: %s", text)
}
if dr, _ := content.GetDraft(s.DB, d.ID); dr.Status != content.StatusDraft || len(sent.sent) != 0 {
t.Errorf("went out without approval: %+v", dr)
}
// Who sees it: the owner, not a Content viewer, not an SEO member.
if body := as(h, oc, http.MethodGet, "/", nil).Body.String(); !strings.Contains(body, `title="1 waiting for you"`) {
t.Error("no count in the sidebar")
}
page := as(h, oc, http.MethodGet, "/approvals", nil).Body.String()
if !strings.Contains(page, "Morning writer") || !strings.Contains(page, "Widgets, faster.") {
t.Errorf("approvals page: %s", page)
}
for _, u := range []*users.User{viewerOnly, seoOnly} {
c := sessionFor(t, s, u)
if body := as(h, c, http.MethodGet, "/approvals", nil).Body.String(); strings.Contains(body, "Widgets, faster.") {
t.Errorf("%s sees it", u.Email)
}
if rec := as(h, c, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("%s approves: %d", u.Email, rec.Code)
}
}
// The owner edits it, approves it, and lets it schedule to @acme on its
// own, once a day.
rec := as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{
"content": {"Widgets, much faster."}, "account": {strconv.FormatInt(company.ID, 10)}, "trust": {"on"}, "cap": {"1"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("approve: %d %s", rec.Code, rec.Body.String())
}
dr, _ := content.GetDraft(s.DB, d.ID)
if dr.Status != content.StatusScheduled || dr.Content != "Widgets, much faster." || dr.AccountID != company.ID || dr.PostedBy != owner.ID {
t.Errorf("scheduled: %+v", dr)
}
if text, _ := mcpCall(t, h, key, "approvals_status", map[string]any{"id": reqID}); !strings.Contains(text, `"Status": "done"`) {
t.Errorf("status: %s", text)
}
if rec := as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{}); rec.Code == http.StatusSeeOther {
t.Error("approved twice")
}
// Now on its own, once; the next waits again.
text, _ = mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Second."})
json.Unmarshal([]byte(text), &d)
if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID}); !strings.Contains(text, "Done (allowed on its own): published as X @acme") {
t.Errorf("on its own: %s", text)
}
if len(sent.sent) != 1 || sent.sent[0] != "X @acme: Second." {
t.Errorf("sent %v", sent.sent)
}
text, _ = mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Third."})
json.Unmarshal([]byte(text), &d)
text, _ = mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID})
if !strings.Contains(text, "Waiting for approval") {
t.Errorf("over the cap: %s", text)
}
third, _ := strconv.ParseInt(requestRe.FindStringSubmatch(text)[1], 10, 64)
// Refused: nothing goes, and the agent can read why.
as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(third, 10)+"/refuse", url.Values{})
if r, _ := approvals.Get(s.DB, third); r.Status != approvals.Refused || len(sent.sent) != 1 {
t.Errorf("refused: %+v", r)
}
// The agent's page lists what it may do on its own; the log has it all.
body := as(h, oc, http.MethodGet, "/settings/agents/"+strconv.FormatInt(agent.ID, 10), nil).Body.String()
if !strings.Contains(body, "publish posts to X @acme") || !strings.Contains(body, "up to 1 a day") {
t.Errorf("agent page: %s", body)
}
act := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String()
for _, want := range []string{"asked for approval to", "approved", "let an agent act on its own:", "did on its own:", "refused"} {
if !strings.Contains(act, want) {
t.Errorf("activity lacks %q", want)
}
}
// The key leaked: rotated with "it leaked", the old key stops at once and
// nothing is allowed on its own.
rec = as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/rotate", url.Values{"leaked": {"on"}})
newKey := keyRe.FindStringSubmatch(rec.Body.String())[1]
if code, _ := mcpTools(h, key); code != http.StatusUnauthorized {
t.Errorf("leaked key still works: %d", code)
}
if gs, _ := approvals.Grants(s.DB, agent.ID); len(gs) != 0 {
t.Errorf("grants kept: %+v", gs)
}
if code, _ := mcpTools(h, newKey); code != http.StatusOK {
t.Errorf("new key: %d", code)
}
// Revoking the key stops it at once.
keys, _ := users.Keys(s.DB, agent.ID)
for _, k := range keys {
users.Revoke(s.DB, agent.ID, k.ID, time.Now())
}
if code, _ := mcpTools(h, newKey); code != http.StatusUnauthorized {
t.Errorf("revoked: %d", code)
}
}
func TestApprovalThatFails(t *testing.T) {
s, h := newTestServer(t, nil)
_, key := newAgent(t, s, "Lister", map[string]users.Access{"prospects": users.Edit})
id, _, err := prospectsAdd(s)
if err != nil {
t.Fatal(err)
}
text, _ := mcpCall(t, h, key, "mailing_list_add", map[string]any{"contact_id": id, "list_id": "3"})
m := requestRe.FindStringSubmatch(text)
if m == nil {
t.Fatalf("add: %s", text)
}
// Listmonk isn't set up: approving says so, and the request is failed.
rec := postForm(h, "/approvals/"+m[1]+"/approve", url.Values{})
if !strings.Contains(rec.Body.String(), "set up Listmonk") {
t.Errorf("approve: %s", rec.Body.String())
}
rid, _ := strconv.ParseInt(m[1], 10, 64)
if r, _ := approvals.Get(s.DB, rid); r.Status != approvals.Failed {
t.Errorf("status %s", r.Status)
}
}
func prospectsAdd(s *Server) (int64, bool, error) {
return prospects.AddContact(s.DB, prospects.Contact{FirstName: "Kim", LastName: "Lee", Email: "kim@example.org", Source: "manual"}, time.Now())
}
+10 -4
View File
@@ -118,6 +118,15 @@ func (s *Server) listmonkTest(w http.ResponseWriter, r *http.Request) {
// addToList adds a person to a mailing list.
func (s *Server) addToList(r *http.Request, id int64) error {
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
return s.addToListID(ctx, id, r.PostFormValue("list"), r.PostFormValue("agreed") == "on")
}
// addToListID adds a person to a mailing list, by the list's ID. confirmed
// says they agreed to receive it; without that, only a double opt-in list
// takes them (it asks them first).
func (s *Server) addToListID(ctx context.Context, id int64, listID string, confirmed bool) error {
c := s.listmonk()
if c == nil {
return errors.New("set up Listmonk under Settings → Email first")
@@ -138,22 +147,19 @@ func (s *Server) addToList(r *http.Request, id int64) error {
} else if sup {
return errors.New(p.Email + " is on your suppression list, so it can't go on a mailing list")
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
lists, err := s.mailingLists(ctx, false)
if err != nil && len(lists) == 0 {
return err
}
var list *listmonk.List
for i := range lists {
if fmt.Sprint(lists[i].ID) == r.PostFormValue("list") {
if fmt.Sprint(lists[i].ID) == listID {
list = &lists[i]
}
}
if list == nil {
return errors.New("choose a mailing list")
}
confirmed := r.PostFormValue("agreed") == "on"
if !confirmed && !list.Double() {
return errors.New(list.Name + " sends its mail without asking first: add someone there only once they've agreed to receive it, or choose a double opt-in list")
}
+1 -1
View File
@@ -340,7 +340,7 @@ func (s *Server) postingPage(w http.ResponseWriter, r *http.Request) {
return
}
for _, m := range members {
if m.Kind == users.Person && m.Status != users.Disabled {
if m.Status != users.Disabled { // people and agents: an agent posts only where it's allowed
g.People = append(g.People, m)
}
g.Owners[m.ID] = m.Name
+13 -3
View File
@@ -344,6 +344,9 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /settings/about", s.aboutPage)
mux.HandleFunc("GET /settings/connections", s.connectionsPage)
mux.HandleFunc("GET /settings/activity", s.activityPage)
mux.HandleFunc("GET /approvals", s.approvalsPage)
mux.HandleFunc("POST /approvals/allowed/withdraw", s.approvalWithdraw)
mux.HandleFunc("POST /approvals/{id}/{action}", s.approvalAction)
mux.HandleFunc("GET /settings/agents", s.agentsPage)
mux.HandleFunc("POST /settings/agents", s.agentCreate)
mux.HandleFunc("GET /settings/agents/{id}", s.agentPage)
@@ -577,9 +580,10 @@ type page struct {
NewProspects int // companies and people waiting for review, shown in the menu
Drafts int // outreach drafts waiting, shown in the menu
Bare bool // no sidebar: pages before signing in
CSRF string // the form token, for htmx (app.js)
Viewer *viewer // who's looking
Bare bool // no sidebar: pages before signing in
CSRF string // the form token, for htmx (app.js)
Approvals int // agents' requests waiting for this viewer
Viewer *viewer // who's looking
}
// Section is the top bar's first breadcrumb, from Nav.
@@ -655,6 +659,9 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p
p.Error = sentence(p.Error)
p.CSRF = csrfToken(r)
p.Viewer = viewerOf(r)
if !p.Bare {
p.Approvals = s.waitingFor(p.Viewer)
}
out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, "layout.html", p) })
if err != nil {
s.Log.Error("render", "page", name, "err", err)
@@ -704,6 +711,9 @@ var flashes = map[string]string{
"joined": "Welcome to Supermarket.",
"key-revoked": "Revoked: that key no longer works.",
"agent-off": "Turned off: none of its keys work.",
"refused": "Refused: the agent is told.",
"approved-request": "Approved, and done.",
"withdrawn-class": "Withdrawn: it asks again from now on.",
"account-removed": "Signed out: posts scheduled to it are back in Posts.",
"own-account-connected": "Connected: you can post as it, and an admin can let others.",
"deleted": "Deleted.",
+15 -1
View File
@@ -29,12 +29,26 @@
</tbody>
</table>
<div class="actions">
<form class="inline" method="post" action="/settings/agents/{{$a.ID}}/rotate"><button type="submit" class="secondary">Rotate the key</button></form>
<form class="inline row" method="post" action="/settings/agents/{{$a.ID}}/rotate"><button type="submit" class="secondary">Rotate the key</button>
<label class="check small"><input type="checkbox" name="leaked"> It leaked: stop the old keys now, and withdraw what it may do on its own</label></form>
<form class="inline row" method="post" action="/settings/agents/{{$a.ID}}/new-key"><label class="small">Expires <input type="date" name="expires"></label><button type="submit" class="secondary">Add a key</button></form>
</div>
<p class="help"><strong>Rotate</strong> makes a new key; the old one keeps working for a day, so whatever uses it can be switched over. After a leak, <strong>revoke</strong> it instead: it stops at once.</p>
</section>
<section class="card" id="allowed">
<h2>On its own</h2>
{{if .Allowed}}
<p class="help">What {{$a.Name}} may do without asking, approved on the Approvals page. Everything else it asks for waits there for a person.</p>
<table class="list"><tbody>{{range .Allowed}}<tr>
<td>{{.Label}}</td><td>{{if .DailyCap}}up to {{.DailyCap}} a day{{else}}no cap{{end}}</td><td>{{ago .Granted}}{{with by .GrantedBy}} {{.}}{{end}}</td>
<td><form class="inline" method="post" action="/approvals/allowed/withdraw"><input type="hidden" name="agent" value="{{.Agent}}"><input type="hidden" name="class" value="{{.Class}}"><button type="submit" class="secondary small">Withdraw</button></form></td>
</tr>{{end}}</tbody></table>
{{else}}<p class="help">Nothing: everything it asks to send out (posts, emails, mailing-list adds, changes to the sites) waits on <a href="/approvals">Approvals</a> for a person.</p>{{end}}
{{if .Asked}}<h3>Lately</h3>
<ul class="small">{{range .Asked}}<li>{{.Summary}}: {{if eq .Status "waiting"}}waiting{{else if eq .Status "refused"}}refused{{else if eq .Status "failed"}}failed{{else if .OnItsOwn}}done on its own{{else}}approved{{end}}, {{ago .Created}}</li>{{end}}</ul>{{end}}
</section>
<section class="card">
<div class="actions">
{{if eq $a.Status "disabled"}}
+67
View File
@@ -0,0 +1,67 @@
{{define "content"}}{{with .Data}}
<div class="page-head">
<h1>Approvals</h1>
<p class="lede">What agents ask to send out of Supermarket: posts, emails, mailing-list adds, changes to the sites. Nothing goes until a person approves it, unless that kind of action has been allowed on its own. Edit it first if you like.</p>
</div>
{{if .Waiting}}
{{range .Waiting}}{{$req := .}}
<form class="card approval" method="post" action="/approvals/{{.ID}}/approve" id="r-{{.ID}}">
<p class="meta"><strong>{{.Agent}}</strong> <span class="pill">agent</span> asks to: <strong>{{.Summary}}</strong> · {{ago .Created}}</p>
{{with .Draft}}
{{if eq .Channel "reddit"}}<label class="small">Title <input name="title" value="{{.Title}}" maxlength="300"></label>
<p class="small muted">r/{{.Target}}</p>{{end}}
<textarea name="content" rows="{{if eq .Channel "x"}}5{{else}}10{{end}}" data-count="{{.Channel}}" data-limit="{{.Limit}}" data-reserve="{{if eq .Channel "x"}}{{xreserve .SourceURL}}{{else}}0{{end}}">{{.Content}}</textarea>
{{with .SourceURL}}<p class="small">Source: <a href="{{.}}" target="_blank" rel="noopener noreferrer">{{.}}</a></p>{{end}}
{{if $req.Accounts}}<label class="small inline-label">From
<select name="account">{{range $req.Accounts}}<option value="{{.ID}}" {{if eq (printf "post:%d" .ID) $req.Class}}selected{{end}}>{{.Label}}</option>{{end}}</select></label>
{{else}}<p class="warn-text small">You can't post to any account for this channel: an admin can let you (Settings → Posting accounts).</p>{{end}}
{{if not $req.At.IsZero}}<p class="small">To go out {{$req.At.Local.Format "Mon 2 Jan 2006, 15:04"}} (or at once, if that's passed).</p>{{end}}
{{end}}
{{with .Message}}
<p class="small">To <strong>{{.Contact.Name}}</strong> &lt;{{.To}}&gt;{{with .Company}} at {{.}}{{end}}</p>
<label class="small">Subject <input name="subject" value="{{.Subject}}"></label>
<textarea name="body" rows="10">{{.Body}}</textarea>
{{end}}
{{with .Change}}
<p class="small">{{.Page}}</p>
<label class="small">Title <input name="title" value="{{.NewTitle}}"></label>
<label class="small">Description <textarea name="description" rows="3">{{.NewDescription}}</textarea></label>
{{end}}
<div class="actions">
<button type="submit">Approve</button>
<button type="submit" class="secondary danger" formaction="/approvals/{{.ID}}/refuse">Refuse</button>
</div>
<label class="check small"><input type="checkbox" name="trust"> <span>And let {{.Agent}} {{.ClassLabel}} on its own from now on, up to <input name="cap" type="number" min="0" value="5" size="3" class="tiny"> a day (0: no cap)</span></label>
</form>
{{end}}
{{else}}
<section class="card empty"><p>Nothing waiting for you.</p></section>
{{end}}
{{if .Allowed}}
<section class="card">
<h2>What agents may do on their own</h2>
<table class="list">
<thead><tr><th>Agent</th><th>May</th><th>Cap</th><th>Since</th><th></th></tr></thead>
<tbody>{{range .Allowed}}<tr>
<td>{{.Agent}}</td><td>{{.Label}}</td><td>{{if .DailyCap}}{{.DailyCap}} a day{{else}}none{{end}}</td><td>{{ago .Granted}}{{with by .GrantedBy}} {{.}}{{end}}</td>
<td>{{if .Mine}}<form class="inline" method="post" action="/approvals/allowed/withdraw"><input type="hidden" name="agent" value="{{.Grant.Agent}}"><input type="hidden" name="class" value="{{.Class}}"><button type="submit" class="secondary small">Withdraw</button></form>{{end}}</td>
</tr>{{end}}</tbody>
</table>
</section>
{{end}}
{{if .Recent}}
<section class="card">
<h2>Decided</h2>
<table class="list">
<thead><tr><th>When</th><th>Agent</th><th>Asked to</th><th>Outcome</th></tr></thead>
<tbody>{{range .Recent}}<tr>
<td>{{ago .Decided}}</td><td>{{.Agent}}</td><td>{{.Summary}}</td>
<td>{{if eq .Status "refused"}}Refused{{with by .DecidedBy}} {{.}}{{end}}{{else if eq .Status "failed"}}<span class="error-text">Failed</span>: {{truncate 120 .Result}}{{else if .OnItsOwn}}Done on its own{{with .Result}}: {{truncate 120 .}}{{end}}{{else}}Approved{{with by .DecidedBy}} {{.}}{{end}}{{with .Result}}: {{truncate 120 .}}{{end}}{{end}}</td>
</tr>{{end}}</tbody>
</table>
</section>
{{end}}
{{end}}{{end}}
+1
View File
@@ -35,6 +35,7 @@
</form>
<nav class="nav" aria-label="Main">
<a href="/" {{if eq .Nav "home"}}aria-current="page"{{end}}>{{template "icon" "overview"}}<span>Overview</span></a>
<a href="/approvals" {{if eq .Nav "approvals"}}aria-current="page"{{end}}>{{template "icon" "ai"}}<span>Approvals</span>{{with .Approvals}} <span class="count-badge" title="{{.}} waiting for you">{{.}}</span>{{end}}</a>
{{if .Can "market"}}<a href="/market" {{if eq .Nav "inventory"}}aria-current="page"{{end}}>{{template "icon" "inventory"}}<span>Market</span></a>{{end}}
{{if .Modules}}<div class="nav-label">Modules</div>{{end}}
+1 -1
View File
@@ -10,7 +10,7 @@
<thead><tr><th>Person</th>{{range .Accounts}}<th>{{.Label}}<br><span class="muted small">{{if eq .Owner 0}}the company's{{else}}{{index $d.Owners .Owner}}'s own{{end}}{{if not (index $d.Working .ID)}} · not working{{end}}</span></th>{{end}}</tr></thead>
<tbody>
{{range $p := .People}}<tr>
<td>{{if .Name}}{{.Name}}{{else}}{{.Email}}{{end}}<br><span class="muted small">{{if .Admin}}admin{{else if .Can "content" true}}member{{else}}no Content: can't post{{end}}</span></td>
<td>{{if .Name}}{{.Name}}{{else}}{{.Email}}{{end}}<br><span class="muted small">{{if eq .Kind "agent"}}agent{{if not (.Can "content" true)}}, without Content: can't post{{end}}{{else if .Admin}}admin{{else if .Can "content" true}}member{{else}}no Content: can't post{{end}}</span></td>
{{range $a := $d.Accounts}}<td>
{{if $p.Admin}}<input type="checkbox" checked disabled title="Admins may post to every account">
{{else if eq $a.Owner $p.ID}}<input type="checkbox" checked disabled title="Their own account">