package web
import (
"context"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"net/url"
"slices"
"strings"
"sync"
"testing"
"craftdesign.group/quarry/internal/ops"
)
type dashFeedIn struct {
Kind string `json:"kind"`
Find string `json:"find"`
Repo string `json:"repo"`
Offset int `json:"offset"`
}
type dashReposIn struct {
Find string `json:"find"`
}
type dashAcrossIn struct {
Awaiting bool `json:"awaiting"`
Mine bool `json:"mine"`
Yours bool `json:"yours"`
Brief bool `json:"brief"`
State string `json:"state"`
Limit int `json:"limit"`
}
type dashTeamsIn struct {
Mine bool `json:"mine"`
}
type dashPinIn struct {
Repo string `json:"repo"`
Pinned bool `json:"pinned"`
}
type dashPinOut struct {
Repo string `json:"repo"`
Pinned bool `json:"pinned"`
}
type dashListIn struct {
Q string `json:"q"`
Sort string `json:"sort"`
Kind string `json:"kind"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type dashListOut struct {
Repos []map[string]any `json:"repos"`
Total int `json:"total"`
Served int `json:"served"`
}
type dashPeopleOut struct {
Total int `json:"total"`
}
// homeHarness is the home page over test doubles that count what the
// page asks for. yours is how many tickets ticket.across answers for the
// reader's own; every other ticket question answers one open ticket.
type homeHarness struct {
h http.Handler
mu sync.Mutex
feeds int
across []dashAcrossIn
// repos is what me.repos answers; nil is one repository, alpha.
repos []map[string]any
// teams is what team.list answers.
teams []map[string]any
// pins is the order the account pinned in, and what me.pin changes:
// me.repos marks the rows named here with their place.
pins []string
// pinCalls is every me.pin the page made.
pinCalls []dashPinIn
// pinErr, when set, is what me.pin refuses with.
pinErr error
}
func newHomeHarness(t *testing.T, yours int) *homeHarness {
t.Helper()
hh := &homeHarness{}
r := ops.NewRegistry()
type empty struct{}
type tickets struct {
Tickets []map[string]any `json:"tickets"`
}
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(ops.Register(r, ops.Op[dashFeedIn, struct {
Total int `json:"total"`
}]{Name: "me.feed", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/me/feed",
Run: func(context.Context, dashFeedIn) (struct {
Total int `json:"total"`
}, error) {
hh.mu.Lock()
hh.feeds++
hh.mu.Unlock()
return struct {
Total int `json:"total"`
}{}, nil
}}))
must(ops.Register(r, ops.Op[dashReposIn, struct {
Repos []map[string]any `json:"repos"`
}]{Name: "me.repos", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/me/repos",
Run: func(context.Context, dashReposIn) (struct {
Repos []map[string]any `json:"repos"`
}, error) {
return struct {
Repos []map[string]any `json:"repos"`
}{hh.rows()}, nil
}}))
must(ops.Register(r, ops.Op[dashAcrossIn, tickets]{Name: "ticket.across", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/me/tickets",
Run: func(_ context.Context, in dashAcrossIn) (tickets, error) {
hh.mu.Lock()
hh.across = append(hh.across, in)
hh.mu.Unlock()
n := 1
if in.Yours {
n = yours
}
var out tickets
for i := 0; i < n; i++ {
out.Tickets = append(out.Tickets, map[string]any{"repo": "alpha", "id": "abcdef0123456789",
"title": "a ticket", "status": "Open", "number": i + 1})
}
return out, nil
}}))
must(ops.Register(r, ops.Op[dashTeamsIn, struct {
Teams []map[string]any `json:"teams"`
}]{Name: "team.list", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/teams",
Run: func(context.Context, dashTeamsIn) (struct {
Teams []map[string]any `json:"teams"`
}, error) {
return struct {
Teams []map[string]any `json:"teams"`
}{hh.teams}, nil
}}))
must(ops.Register(r, ops.Op[dashPinIn, dashPinOut]{Name: "me.pin", Doc: "test double", Kind: ops.Command, Auth: ops.Token, Route: "POST /api/v1/me/pins",
Run: func(_ context.Context, in dashPinIn) (dashPinOut, error) {
hh.mu.Lock()
defer hh.mu.Unlock()
hh.pinCalls = append(hh.pinCalls, in)
if hh.pinErr != nil {
return dashPinOut{}, hh.pinErr
}
have := slices.Contains(hh.pins, in.Repo)
if in.Pinned && !have {
hh.pins = append(hh.pins, in.Repo)
} else if !in.Pinned && have {
hh.pins = slices.DeleteFunc(hh.pins, func(r string) bool { return r == in.Repo })
}
return dashPinOut{Repo: in.Repo, Pinned: in.Pinned}, nil
}}))
must(ops.Register(r, ops.Op[dashListIn, dashListOut]{Name: "repo.list", Doc: "test double", Kind: ops.Query, Auth: ops.Anonymous, Route: "GET /api/v1/repos",
Run: func(context.Context, dashListIn) (dashListOut, error) {
return dashListOut{Repos: []map[string]any{{"name": "alpha"}}, Total: 1, Served: 1}, nil
}}))
must(ops.Register(r, ops.Op[dashListIn, dashPeopleOut]{Name: "people.list", Doc: "test double", Kind: ops.Query, Auth: ops.Anonymous, Route: "GET /api/v1/people",
Run: func(context.Context, dashListIn) (dashPeopleOut, error) {
return dashPeopleOut{Total: 1}, nil
}}))
must(ops.Register(r, ops.Op[empty, struct {
Version string `json:"version"`
}]{Name: "meta.version", Doc: "test double", Kind: ops.Query, Auth: ops.Anonymous, Route: "GET /api/v1/version",
Run: func(context.Context, empty) (struct {
Version string `json:"version"`
}, error) {
return struct {
Version string `json:"version"`
}{"t"}, nil
}}))
hh.h = HandlerWith(r, nil, nil, []Option{WithSessions(fakeSessions{user: "jan", roles: map[string]ops.Auth{"": ops.Token}})})
return hh
}
// get answers path as the signed-in reader, with what it asked for
// since the last call.
func (hh *homeHarness) get(t *testing.T, path string) (int, string, int, []dashAcrossIn) {
t.Helper()
hh.mu.Lock()
hh.feeds, hh.across = 0, nil
hh.mu.Unlock()
req := httptest.NewRequest("GET", path, nil)
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
hh.mu.Lock()
defer hh.mu.Unlock()
return w.Code, w.Body.String(), hh.feeds, hh.across
}
// The home page is where the reader works, and none of it waits on the
// activity feed, which reads every event of every tracker the reader
// reaches. The feed is a tab with its own page: /home never asks for it,
// and /activity is the one that does.
func TestTheHomePageDoesNotAskForTheFeed(t *testing.T) {
hh := newHomeHarness(t, 0)
code, body, feeds, across := hh.get(t, "/home")
if code != http.StatusOK {
t.Fatalf("FAIL: /home answered %d", code)
}
if feeds != 0 {
t.Errorf("FAIL: the home page asked for the feed %d times", feeds)
}
if !strings.Contains(body, `data-hook="board"`) {
t.Error("FAIL: the home page has no board")
}
for _, gone := range []string{`data-init="@get('/activity?frag=recent')"`, `data-hook="dash-skeleton"`, `id="dash-activity"`} {
if strings.Contains(body, gone) {
t.Errorf("FAIL: the home page still carries %s", gone)
}
}
if len(across) != 0 {
t.Errorf("FAIL: the home page asked ticket.across: %+v", across)
}
// The activity page asks for the feed, wears the strip, and the band of
// tickets waiting on you leads its ticket changes only.
code, body, feeds, _ = hh.get(t, "/activity")
if code != http.StatusOK || feeds != 1 || !strings.Contains(body, `data-hook="home-tab-activity"`) {
t.Errorf("FAIL: /activity: %d, %d feeds, no strip", code, feeds)
}
if _, _, _, across = hh.get(t, "/activity?kind=t"); len(across) != 1 || !across[0].Awaiting {
t.Errorf("FAIL: ticket changes did not ask for the waiting band: %+v", across)
}
if _, _, _, across = hh.get(t, "/activity?kind=c"); len(across) != 0 {
t.Errorf("FAIL: check-ins asked for the waiting band")
}
}
// The feed as it was addressed on the home page arrives at the activity
// page, its filters kept.
func TestTheOldFeedAddressesArriveAtTheActivityPage(t *testing.T) {
hh := newHomeHarness(t, 0)
for path, want := range map[string]string{
"/?kind=t": "/activity?kind=t",
"/?offset=10&repo=x": "/activity?offset=10&repo=x",
"/?frag=1&kind=w": "/activity?kind=w",
} {
req := httptest.NewRequest("GET", path, nil)
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
if w.Code != http.StatusSeeOther || w.Header().Get("Location") != want {
t.Errorf("FAIL: %s answered %d to %q, want %s", path, w.Code, w.Header().Get("Location"), want)
}
}
}
// The home lists no tickets: the reader's own are the bar's ticket
// button away, and what moved on them is in activity.
func TestTheHomeListsNoTickets(t *testing.T) {
_, body, _, across := newHomeHarness(t, 2).get(t, "/home")
if strings.Contains(body, `data-hook="dash-ticket"`) || len(across) != 0 {
t.Errorf("FAIL: the home page still lists tickets (%d asks)", len(across))
}
if !strings.Contains(body, `href="/tickets"`) {
t.Error("FAIL: no way to the reader's tickets")
}
}
func (hh *homeHarness) rows() []map[string]any {
rows := hh.repos
if rows == nil {
rows = []map[string]any{{"name": "alpha", "role": "admin"}}
}
out := make([]map[string]any, len(rows))
for i, row := range rows {
out[i] = maps.Clone(row)
if at := slices.Index(hh.pins, row["name"].(string)); at >= 0 {
out[i]["pin"] = at + 1
}
}
return out
}
// A repository that is down and still the reader's is marked on their
// dashboard, by its strength, and one that is up carries no mark.
func TestTheDashboardMarksARepositoryThatIsDown(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = []map[string]any{
{"name": "alpha", "role": "admin"},
{"name": "beta", "role": "admin", "takenDown": "disabled"},
{"name": "gamma", "role": "admin", "takenDown": "hold"},
}
_, body, _, _ := hh.get(t, "/home")
if n := strings.Count(body, `data-hook="taken-down"`); n != 2 {
t.Errorf("FAIL: %d takedown marks on the dashboard, want 2", n)
}
if !t.Failed() {
t.Log("ok")
}
}
func (hh *homeHarness) redirect(t *testing.T, path string, signedIn bool) (int, string) {
t.Helper()
req := httptest.NewRequest("GET", path, nil)
if signedIn {
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
}
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
return w.Code, w.Header().Get("Location")
}
// The front page is one page for everyone. A signed-in reader's "/" is
// the forge's listing, and the filters the dashboard used to own go to
// /home with find and vis kept; repos=all is dropped, since the list is
// always whole.
func TestTheRootIsTheFrontPageForEveryone(t *testing.T) {
hh := newHomeHarness(t, 0)
for _, signedIn := range []bool{false, true} {
code, body, _ := fragGet(hh, "/", signedIn)
if code != http.StatusOK || !strings.Contains(body, `id="explore"`) || strings.Contains(body, `data-hook="board"`) {
t.Errorf("FAIL: / (signed in %v) answered %d and is not the listing", signedIn, code)
}
}
for path, want := range map[string]string{
"/?find=pi": "/home?find=pi",
"/?vis=private": "/home?vis=private",
"/?find=pi&vis=public&x=1": "/home?find=pi&vis=public",
"/?repos=all": "/home",
"/?repos=all&find=a%20b": "/home?find=a+b",
"/?find=pi&kind=mirror": "/home?find=pi",
"/?find=pi&repo=quarry": "/activity?find=pi&repo=quarry",
"/?kind=t": "/activity?kind=t",
"/?offset=10": "/activity?offset=10",
} {
if code, loc := hh.redirect(t, path, true); code != http.StatusSeeOther || loc != want {
t.Errorf("FAIL: signed in, %s answered %d to %q, want %s", path, code, loc, want)
}
}
// The front page's own parameters, and the alias, stay put.
for _, path := range []string{"/?view=explore", "/?q=pi", "/?sort=size", "/?kind=mirror", "/?kind=native", "/?kind=all", "/?find=x&view=explore"} {
if code, loc := hh.redirect(t, path, true); code != http.StatusOK {
t.Errorf("FAIL: signed in, %s answered %d to %q, want the listing", path, code, loc)
}
}
// A visitor is never sent anywhere by them.
if code, loc := hh.redirect(t, "/?find=pi", false); code != http.StatusOK {
t.Errorf("FAIL: signed out, /?find=pi answered %d to %q", code, loc)
}
if !t.Failed() {
t.Log("ok")
}
}
// /home is the reader's own page: a visitor is sent to sign in and back,
// the way /activity and /tickets send them, never shown the forge's list
// as if it were theirs.
func TestHomeSendsAVisitorToSignIn(t *testing.T) {
hh := newHomeHarness(t, 0)
if code, loc := hh.redirect(t, "/home", false); code != http.StatusSeeOther || loc != "/login?next=/home" {
t.Errorf("FAIL: /home signed out answered %d to %q", code, loc)
}
code, body, _ := fragGet(hh, "/home", true)
if code != http.StatusOK || !strings.Contains(body, `data-hook="board"`) {
t.Errorf("FAIL: /home signed in answered %d without the board", code)
}
}
// The house button: third in the bar after search and create, signed in
// only, and marked current on /home and on Activity, its tab.
func TestHouseButtonIsThirdAndLit(t *testing.T) {
hh := newHomeHarness(t, 0)
for path, lit := range map[string]bool{"/home": true, "/activity": true, "/": false, "/tickets": false} {
_, body, _ := fragGet(hh, path, true)
home := strings.Index(body, `data-hook="home-btn"`)
create, tickets := strings.Index(body, `popovertarget="create"`), strings.Index(body, `href="/tickets"`)
if home < 0 || !(strings.Index(body, `popovertarget="find"`) < create && create < home && home < tickets) {
t.Errorf("FAIL: %s: bar order is create %d, home %d, tickets %d", path, create, home, tickets)
continue
}
tag := body[strings.LastIndex(body[:home], "<a "):]
tag = tag[:strings.Index(tag, ">")]
if got := strings.Contains(tag, `aria-current="page"`); got != lit {
t.Errorf("FAIL: %s: house marked current = %v, want %v", path, got, lit)
}
}
if _, body, _ := fragGet(hh, "/", false); strings.Contains(body, `data-hook="home-btn"`) {
t.Error("FAIL: a visitor is shown the house button")
}
if !strings.Contains(styleSource, "@media (max-width: 30rem) { .topbar .site .wordmark { display: none; } }") {
t.Error("FAIL: the wordmark does not give way at 30rem")
}
}
func (hh *homeHarness) post(path string, form url.Values, signedIn, script bool) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", path, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if signedIn {
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
}
if script {
req.Header.Set("Datastar-Request", "true")
}
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
return w
}
// Pinning posts a form. Without script the answer is a redirect back to
// the board in the view the reader was in; the pin is the op's doing, and
// the next load of /home shows it.
func TestPinPostsAndTheBoardShowsIt(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
w := hh.post("/home/pin", url.Values{"repo": {"repo05"}, "pinned": {"true"}, "find": {"repo"}, "vis": {"public"}, "kind": {"all"}}, true, false)
if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/home?find=repo&kind=all&vis=public" {
t.Errorf("FAIL: pin answered %d to %q", w.Code, w.Header().Get("Location"))
}
hh.post("/home/pin", url.Values{"repo": {"repo02"}, "pinned": {"true"}}, true, false)
if w := hh.post("/home/pin", url.Values{"repo": {"repo05"}, "pinned": {"true"}}, true, false); w.Header().Get("Location") != "/home" {
t.Errorf("FAIL: a pin from the plain view redirected to %q", w.Header().Get("Location"))
}
if want := []dashPinIn{{"repo05", true}, {"repo02", true}, {"repo05", true}}; !slices.Equal(hh.pinCalls, want) {
t.Errorf("FAIL: me.pin was asked %+v, want %+v", hh.pinCalls, want)
}
_, body, _, _ := hh.get(t, "/home")
pinned, rest := strings.Index(body, `data-hook="board-pinned"`), strings.Index(body, `data-hook="board-rest"`)
if pinned < 0 || rest < pinned || !sameNames(boardOrder(body[pinned:rest]), "repo05", "repo02") {
t.Errorf("FAIL: the pinned group is %v, want repo05 then repo02", boardOrder(body[max(pinned, 0):max(rest, 0)]))
}
if n := len(boardOrder(body[rest:])); n != 8 {
t.Errorf("FAIL: %d rows below the pins, want the other 8", n)
}
// And unpinning takes it back.
hh.post("/home/pin", url.Values{"repo": {"repo05"}, "pinned": {"false"}}, true, false)
if _, body, _, _ = hh.get(t, "/home"); strings.Contains(body, `data-repo="repo05"`) && !strings.Contains(body[strings.Index(body, `data-hook="board-rest"`):], `data-repo="repo05"`) {
t.Error("FAIL: an unpinned repository is still in the pinned group")
}
if !t.Failed() {
t.Log("ok")
}
}
// With script the same form asks for the board alone, and the answer is
// a patch of the board in the view the form carried: no page, no
// redirect.
func TestPinPatchesTheBoardInPlace(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
w := hh.post("/home/pin", url.Values{"repo": {"repo05"}, "pinned": {"true"}, "find": {"repo0"}}, true, true)
if w.Code != http.StatusOK || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/event-stream") {
t.Fatalf("FAIL: the scripted pin answered %d as %q", w.Code, w.Header().Get("Content-Type"))
}
body := strings.ReplaceAll(w.Body.String(), "data: elements ", "")
if !strings.Contains(body, "event: datastar-patch-elements") || !strings.Contains(body, `id="dash-repolist"`) {
t.Fatalf("FAIL: the answer is not a patch of the board:\n%s", body)
}
if strings.Contains(body, `data-hook="dash-find"`) || strings.Contains(body, "<html") {
t.Error("FAIL: the patch carries more than the board (it would reset the box being typed in)")
}
pinned, rest := strings.Index(body, `data-hook="board-pinned"`), strings.Index(body, `data-hook="board-rest"`)
if pinned < 0 || !sameNames(boardOrder(body[pinned:rest]), "repo05") {
t.Errorf("FAIL: the patched pinned group is %v", boardOrder(body))
}
// The find the form carried narrowed the rest: repo0x only.
if got := boardOrder(body[rest:]); len(got) != 9 || listHas(got, "repo05") || listHas(got, "repo10") {
t.Errorf("FAIL: the rest is %v, want the other nine matching repo0", got)
}
if !strings.Contains(body, `data-hook="pin-toggle" data-pinned="true"`) {
t.Error("FAIL: the patched row's pin is not marked pinned")
}
}
// A refusal is a status, never a page: a signed-out caller is 401, and a
// repository the op will not pin is the op's own not-found, whether the
// form posted or script did.
func TestPinRefusals(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
if w := hh.post("/home/pin", url.Values{"repo": {"repo05"}, "pinned": {"true"}}, false, false); w.Code != http.StatusUnauthorized {
t.Errorf("FAIL: signed out, pinning answered %d", w.Code)
}
if len(hh.pinCalls) != 0 {
t.Errorf("FAIL: a signed-out pin reached the op: %+v", hh.pinCalls)
}
hh.pinErr = fmt.Errorf("no repository %q: %w", "secret", ops.ErrNotFound)
w := hh.post("/home/pin", url.Values{"repo": {"secret"}, "pinned": {"true"}}, true, true)
if w.Code != http.StatusNotFound || strings.Contains(w.Body.String(), `id="dash-repolist"`) || strings.Contains(w.Body.String(), "<html") {
t.Errorf("FAIL: a scripted refusal answered %d with %q", w.Code, w.Body.String())
}
if w := hh.post("/home/pin", url.Values{"repo": {"secret"}, "pinned": {"true"}}, true, false); w.Code != http.StatusNotFound {
t.Errorf("FAIL: a posted refusal answered %d", w.Code)
}
}
// Teams are a tab of the home, reached by ?tab=teams and only while the
// account is in one: without a team the address shows the board.
func TestTheTeamsTabServesTeamsOnlyForAMember(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
_, body, _, _ := hh.get(t, "/home?tab=teams")
if strings.Contains(body, `data-hook="dash-teams"`) || !strings.Contains(body, `data-hook="board"`) || strings.Contains(body, `data-hook="home-tab-teams"`) {
t.Error("FAIL: an account in no team is shown a Teams tab")
}
hh.teams = []map[string]any{{"name": "grove", "created": "2026-01-01"}, {"name": "orchard", "created": "2026-02-01"}}
_, body, _, _ = hh.get(t, "/home?tab=teams")
if !strings.Contains(body, `data-hook="dash-teams"`) || strings.Contains(body, `data-hook="board"`) {
t.Error("FAIL: ?tab=teams does not show the teams")
}
if strings.Index(body, `href="/t/orchard"`) > strings.Index(body, `href="/t/grove"`) {
t.Error("FAIL: the newest team is not first")
}
_, body, _, _ = hh.get(t, "/home")
if !strings.Contains(body, `data-hook="home-tab-teams"`) || strings.Contains(body, `data-hook="dash-teams"`) {
t.Error("FAIL: the repositories tab does not offer the teams tab, or draws the teams")
}
// The activity page knows whether to draw the tab too.
if _, body, _, _ = hh.get(t, "/activity"); !strings.Contains(body, `data-hook="home-tab-teams"`) {
t.Error("FAIL: the activity page's strip has no Teams tab for a member")
}
hh.teams = nil
if _, body, _, _ = hh.get(t, "/activity"); strings.Contains(body, `data-hook="home-tab-teams"`) {
t.Error("FAIL: the activity page's strip has a Teams tab for a non-member")
}
}