Skip to content
quarry Artifact [93dc1ecf09]
Login

Artifact [93dc1ecf09]

Artifact 93dc1ecf09adac66a71134e9da70f871aa4e9a0ea0b019d48d5855e39f5831a7:


package web

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"regexp"
	"strings"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/api"
	"craftdesign.group/quarry/internal/artifact"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/ops"
)

// carriers is the forge's record of who pushed which post, which is all a
// settlement is judged by (api.blockingProvenance).
type carriers map[string]string

func (c carriers) RecordCarriers(_, login string, hs []string) error {
	for _, h := range hs {
		c[h] = login
	}
	return nil
}
func (c carriers) CarrierOf(_, h string) (string, time.Time) {
	return c[h], time.Date(2026, 8, 21, 0, 0, 0, 0, time.UTC)
}

const (
	blkOpen1   = "e1"
	blkOpen2   = "e2"
	blkDone    = "e3"
	blkResolve = "e4"
	blkRoot    = "a1a1a1a1a1a1"
)

func blkHash(p string) string { return strings.Repeat(p, 20) }

// blockingIndex is the landing fixture plus eve's two open blockers, a
// third dan resolved with a word, and one plain remark.
func blockingIndex(t *testing.T) (*index.Index, carriers) {
	t.Helper()
	ix := landingIndex(t, false)
	root := strings.Repeat("a1", 20)
	post := func(p, user, date, parent, body string) index.Parsed {
		return index.Parsed{Hash: blkHash(p), Art: &artifact.Artifact{Type: artifact.Forum,
			ThreadRoot: root, InReplyTo: parent, Date: date, User: user,
			Mimetype: "text/x-markdown", Body: []byte(body)}}
	}
	if err := ix.FoldNow([]index.Parsed{
		post(blkOpen1, "eve", "2026-08-20T12:00:00", root, "blocking: handle the nil case\n"),
		post(blkOpen2, "eve", "2026-08-20T12:05:00", root, "blocking: and the empty one\n"),
		post(blkDone, "eve", "2026-08-20T12:10:00", root, "blocking: rename the flag\n"),
		post(blkResolve, "dan", "2026-08-20T13:00:00", blkHash(blkDone),
			index.FormatMarker(index.MarkResolved, strings.Repeat(blkDone, 6), "renamed in the next push")),
		post("f1", "eve", "2026-08-20T13:30:00", root, "just a remark\n"),
	}); err != nil {
		t.Fatal(err)
	}
	return ix, carriers{blkHash(blkOpen1): "eve", blkHash(blkOpen2): "eve", blkHash(blkDone): "eve",
		blkHash(blkResolve): "dan", blkHash("f1"): "eve"}
}

func blockingServer(t *testing.T, ix *index.Index, c carriers, user, caps string) *httptest.Server {
	t.Helper()
	r := ops.NewRegistry()
	if err := api.RegisterAll(r, api.Deps{Version: "v", Carriers: c,
		Repos: api.NewRepos(map[string]*api.Repo{"alpha": {Chat: "alpha", Index: ix}})}); err != nil {
		t.Fatal(err)
	}
	opts := []Option{WithSessions(fakeSessions{user: user})}
	if caps != "" {
		opts = append(opts, WithCaps(&memCaps{stored: map[string]string{user: caps}}))
	}
	srv := httptest.NewServer(HandlerWith(r, nil, nil, opts))
	t.Cleanup(srv.Close)
	return srv
}

func blockingPage(t *testing.T, user, caps string) string {
	ix, c := blockingIndex(t)
	return landingGet(t, blockingServer(t, ix, c, user, caps), "/r/alpha/landing/"+blkRoot)
}

// formAround is the form element holding needle, or "" when none does.
func formAround(html, needle string) string {
	at := strings.Index(html, needle)
	if at < 0 {
		return ""
	}
	from := strings.LastIndex(html[:at], "<form")
	end := strings.Index(html[at:], "</form>")
	if from < 0 || end < 0 {
		return ""
	}
	return html[from : at+end+len("</form>")]
}

func blkHooks(html, hook string) int {
	return strings.Count(html, `data-hook="`+hook+`"`)
}

func TestTheHeaderChipCountsTheOpenBlockingComments(t *testing.T) {
	html := blockingPage(t, "dan", "3i")
	m := regexp.MustCompile(`data-hook="blocking-open" data-count="(\d+)"`).FindStringSubmatch(html)
	if m == nil || m[1] != "2" {
		t.Fatalf("FAIL: header chip = %v, want a count of 2 (two open, one resolved)", m)
	}
	ix := landingIndex(t, false)
	plain := landingGet(t, landingServer(t, ix, "3i"), "/r/alpha/landing/"+blkRoot)
	if blkHooks(plain, "blocking-open") != 0 || blkHooks(plain, "blocking-gate") != 0 {
		t.Errorf("FAIL: a landing with no blocking comments draws the chip or the gate")
	}
}

func TestTheGateListsEachOpenCommentAndDisablesAccept(t *testing.T) {
	html := blockingPage(t, "dan", "3i")
	if !regexp.MustCompile(`data-hook="blocking-gate" data-count="2"`).MatchString(html) {
		t.Fatalf("FAIL: no gate row counting two open comments")
	}
	for _, p := range []string{blkOpen1, blkOpen2} {
		want := `data-hook="blocking-link" data-hash="` + strings.Repeat(p, 6) + `" href="#p-` + strings.Repeat(p, 6) + `"`
		if !strings.Contains(html, want) {
			t.Errorf("FAIL: the gate has no link to the post %s", p)
		}
		if !strings.Contains(html, `id="p-`+strings.Repeat(p, 6)+`"`) {
			t.Errorf("FAIL: the link's target post %s has no anchor", p)
		}
	}
	if strings.Contains(html, `data-hash="`+strings.Repeat(blkDone, 6)+`" href`) {
		t.Errorf("FAIL: the gate lists a resolved comment")
	}
	btn := regexp.MustCompile(`<button[^>]*data-accept="go"[^>]*>`).FindString(html)
	if btn == "" {
		t.Fatalf("FAIL: the accept button is not drawn at all")
	}
	if !strings.Contains(btn, " disabled") || !strings.Contains(btn, "data-blocked") {
		t.Errorf("FAIL: the accept button is live over open blocking comments: %s", btn)
	}
}

func TestOnlyAnOverriderSeesTheOverrideControl(t *testing.T) {
	admin := blockingPage(t, "dan", "3ia")
	form := regexp.MustCompile(`(?s)<form[^>]*data-hook="blocking-override".*?</form>`).FindString(admin)
	if form == "" {
		t.Fatalf("FAIL: an admin gets no override control")
	}
	for _, want := range []string{`type="checkbox"`, `name="overrideBlocking"`, `name="override"`, ` required`, `/landing/` + blkRoot + `/accept`} {
		if !strings.Contains(form, want) {
			t.Errorf("FAIL: the override form lacks %q: %s", want, form)
		}
	}
	if blkHooks(blockingPage(t, "dan", "3i"), "blocking-override") != 0 {
		t.Errorf("FAIL: a plain accepter, who the API refuses, is offered the override")
	}
}

func TestResolveIsOfferedToASettlerAndNotToAStranger(t *testing.T) {
	settler := blockingPage(t, "dan", "3i") // the landing's author
	if n := blkHooks(settler, "blocking-resolve"); n != 2 {
		t.Errorf("FAIL: the landing's author sees %d Resolve buttons, want one per open comment", n)
	}
	form := formAround(settler, `name="resolves" value="`+blkHash(blkOpen1)+`"`)
	if form == "" || !strings.Contains(form, `/landing/`+blkRoot+`/comment`) || strings.Contains(form, `name="message"`) {
		t.Errorf("FAIL: the Resolve form is not a single button posting resolves=<hash> to the comment route: %q", form)
	}
	if n := blkHooks(blockingPage(t, "mallory", "3"), "blocking-resolve"); n != 0 {
		t.Errorf("FAIL: a stranger who may only comment is offered Resolve %d times", n)
	}
	if n := blkHooks(blockingPage(t, "eve", "3"), "blocking-resolve"); n != 2 {
		t.Errorf("FAIL: the comments' own author sees %d Resolve buttons, want 2", n)
	}
}

func TestAResolvedCommentFoldsAndOffersReopen(t *testing.T) {
	html := blockingPage(t, "mallory", "3") // anyone who may comment may reopen
	chip := regexp.MustCompile(`data-hook="post-resolved" data-by="([^"]*)"`).FindStringSubmatch(html)
	if chip == nil || chip[1] != "dan" {
		t.Fatalf("FAIL: the resolved chip names %v, want the account that resolved it", chip)
	}
	if !regexp.MustCompile(`<details[^>]*data-hook="blocking-folded"`).MatchString(html) {
		t.Errorf("FAIL: the resolved comment is not folded")
	}
	if blkHooks(html, "blocking-reopen") != 1 {
		t.Errorf("FAIL: want one Reopen, on the resolved comment, got %d", blkHooks(html, "blocking-reopen"))
	}
	if !strings.Contains(html, `name="reopens" value="`+blkHash(blkDone)+`"`) {
		t.Errorf("FAIL: Reopen does not name the resolved comment")
	}
	// The resolve is drawn once, inside the fold of the comment it settled,
	// below that comment's body, and not again in the flat list.
	fold := html[strings.Index(html, `data-hook="blocking-folded"`):]
	fold = fold[:strings.Index(fold, "</details>")]
	if blkHooks(html, "post-settle") != 1 || blkHooks(fold, "post-settle") != 1 {
		t.Fatalf("FAIL: the resolve is drawn %d times, %d inside the fold; want once, inside", blkHooks(html, "post-settle"), blkHooks(fold, "post-settle"))
	}
	if !strings.Contains(fold, `data-settle="resolved" data-target="`+strings.Repeat(blkDone, 6)+`"`) ||
		strings.Index(fold, "rename the flag") > strings.Index(fold, `data-hook="post-settle"`) ||
		!strings.Contains(fold, "renamed in the next push") {
		t.Errorf("FAIL: the settle is not under the folded comment's body with its words")
	}
	// Author, then the chip, then the time, as an open post's header reads.
	// The summary IS the post's header row, so opening the fold reveals
	// the body and not a second header.
	if !strings.Contains(fold, `<summary class="f-post-h">`) || strings.Contains(fold, `<div class="f-post-h">`) {
		t.Errorf("FAIL: the fold repeats the header instead of using its summary as it")
	}
	sum := fold[strings.Index(fold, "<summary"):strings.Index(fold, "</summary>")]
	if a, c := strings.Index(sum, "<strong>"), strings.Index(sum, `data-hook="post-resolved"`); a < 0 || c < a {
		t.Errorf("FAIL: the summary puts the chip before the author")
	}
	if !strings.Contains(sum, "<code>"+strings.Repeat(blkDone, 6)) {
		t.Errorf("FAIL: the summary row carries no hash")
	}
	if chip := regexp.MustCompile(`data-hook="post-resolved"[^>]*>([^<]*)<`).FindStringSubmatch(sum); chip == nil || chip[1] != "resolved" {
		t.Errorf("FAIL: the chip holds more than the state: %v", chip)
	}
	if !strings.Contains(fold, `<div class="f-settle-note">`) {
		t.Errorf("FAIL: the settle's note is not on its own block")
	}
	if blkHooks(html, "post-blocking") != 2 {
		t.Errorf("FAIL: want the two open comments labelled blocking, got %d", blkHooks(html, "post-blocking"))
	}
	if blkHooks(html, "blocking-gate") != 1 {
		t.Errorf("FAIL: the resolved comment still counts at the gate")
	}
}

func TestTheMarkerLineIsNotShownAsText(t *testing.T) {
	html := blockingPage(t, "dan", "3i")
	body := html[strings.Index(html, `id="discussion"`):]
	for _, bad := range []string{"blocking: handle", "blocking: and the", "resolved: "} {
		if strings.Contains(body, bad) {
			t.Errorf("FAIL: the marker %q reached the page as text", bad)
		}
	}
	for _, want := range []string{"handle the nil case", "renamed in the next push"} {
		if !strings.Contains(body, want) {
			t.Errorf("FAIL: the comment's own words %q are missing", want)
		}
	}
}

// A line note is drawn from its row alone under its line, with the same
// label, fold and actions as in the discussion.
func TestInlineLineNotesCarryTheBlockingLabelAndFold(t *testing.T) {
	det := &landingDetail{CanSpeak: true, Diff: noteDiff()}
	det.State, det.ID = "open", "abcdef123456"
	det.Comments = []forumPostRow{
		{Hash: "n1aaaaaaaaaa", User: "ada", HTML: "check this", Blocking: "open", MayResolve: true, CommentURL: "/r/r/landing/abcdef123456/comment",
			Line: &index.LineNote{File: "a.go", Side: "new", Line: 2, At: "cafe12"}},
		{Hash: "n2bbbbbbbbbb", User: "bob", HTML: "done now", Blocking: "resolved", ResolvedBy: "ada", ResolvedAt: "2026-08-20T10:00:00", MayReopen: true,
			CommentURL: "/r/r/landing/abcdef123456/comment", Line: &index.LineNote{File: "a.go", Side: "old", Line: 2, At: "cafe12"}},
	}
	data := pageData{Repo: "r", Diff: *det.Diff, Landing: det}
	lineNotesFor(&data, det, "cafe12deadbeef", "")
	var buf strings.Builder
	if err := noHooks.template(diffPage).ExecuteTemplate(&buf, "diff-more", data); err != nil {
		t.Fatal(err)
	}
	page := buf.String()
	for _, hook := range []string{"post-blocking", "blocking-resolve", "post-resolved", "blocking-reopen"} {
		if blkHooks(page, hook) != 1 {
			t.Errorf("FAIL: a line note should carry %s once, got %d", hook, blkHooks(page, hook))
		}
	}
	if !regexp.MustCompile(`<details class="d-note blk-fold"`).MatchString(page) {
		t.Errorf("FAIL: the resolved line note is not folded")
	}
}

// What the handler hands the op is the whole feature on the write side:
// the checkbox, the resolve and the reopen travel as typed fields, and the
// page never writes a marker itself.
type sayStubIn struct {
	Repo             string `json:"repo" path:"repo"`
	ID               string `json:"id" path:"id"`
	Message          string `json:"message"`
	To               string `json:"to"`
	Override         string `json:"override"`
	File             string `json:"file"`
	Line             int    `json:"line"`
	Blocking         bool   `json:"blocking"`
	Resolves         string `json:"resolves"`
	Reopens          string `json:"reopens"`
	OverrideBlocking bool   `json:"overrideBlocking"`
}

type sayStubOut struct {
	Hash string `json:"hash"`
}

func sayStub(t *testing.T, verb string, got *sayStubIn, fail error) *httptest.Server {
	t.Helper()
	r := viewRegistry(t, nil)
	if err := ops.Register(r, ops.Op[sayStubIn, sayStubOut]{
		Name: "landing." + verb, Caps: "3", Doc: "test stub", Kind: ops.Command, Auth: ops.Token,
		Route: "POST /api/v1/r/{repo}/landing/{id}/" + verb,
		Run: func(_ context.Context, in sayStubIn) (sayStubOut, error) {
			*got = in
			return sayStubOut{}, fail
		},
	}); err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewServer(HandlerWith(r, nil, nil, nil))
	t.Cleanup(srv.Close)
	return srv
}

func blkPost(t *testing.T, srv *httptest.Server, path string, v url.Values) (*http.Response, string) {
	t.Helper()
	c := srv.Client()
	c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
	resp, err := c.PostForm(srv.URL+path, v)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := io.ReadAll(resp.Body)
	return resp, string(b)
}

func TestTheBlockingCheckboxReachesTheOpAsBlocking(t *testing.T) {
	var got sayStubIn
	srv := sayStub(t, "comment", &got, nil)
	resp, _ := blkPost(t, srv, "/r/alpha/landing/"+blkRoot+"/comment",
		url.Values{"message": {"guard it"}, "blocking": {"true"}})
	if resp.StatusCode != http.StatusSeeOther || !got.Blocking || got.Message != "guard it" {
		t.Fatalf("FAIL: status %d, op saw %+v", resp.StatusCode, got)
	}
	got = sayStubIn{}
	blkPost(t, srv, "/r/alpha/landing/"+blkRoot+"/comment", url.Values{"message": {"fine"}})
	if got.Blocking || got.Resolves != "" || got.Reopens != "" {
		t.Errorf("FAIL: an unticked box made a blocking, resolve or reopen: %+v", got)
	}
	// A line note carries it too: the inline composer posts the same fields.
	got = sayStubIn{}
	blkPost(t, srv, "/r/alpha/landing/"+blkRoot+"/comment",
		url.Values{"message": {"here"}, "blocking": {"true"}, "file": {"a.go"}, "side": {"new"}, "line": {"2"}})
	if !got.Blocking || got.File != "a.go" || got.Line != 2 {
		t.Errorf("FAIL: a blocking line note reached the op as %+v", got)
	}
	got = sayStubIn{}
	blkPost(t, srv, "/r/alpha/landing/"+blkRoot+"/comment", url.Values{"resolves": {blkHash(blkOpen1)}, "message": {"done"}})
	if got.Resolves != blkHash(blkOpen1) || got.Blocking {
		t.Errorf("FAIL: a resolve reached the op as %+v", got)
	}
	got = sayStubIn{}
	blkPost(t, srv, "/r/alpha/landing/"+blkRoot+"/comment", url.Values{"reopens": {blkHash(blkDone)}})
	if got.Reopens != blkHash(blkDone) {
		t.Errorf("FAIL: a reopen reached the op as %+v", got)
	}
}

func TestBothComposersOfferTheBlockingCheckbox(t *testing.T) {
	html := blockingPage(t, "dan", "3i")
	if !regexp.MustCompile(`<input type="checkbox" name="blocking" value="true" data-hook="compose-blocking">`).MatchString(html) {
		t.Errorf("FAIL: the landing comment form has no Blocking checkbox")
	}
	det := &landingDetail{CanSpeak: true, Diff: noteDiff()}
	det.State, det.ID = "open", "abcdef123456"
	data := pageData{Repo: "r", Diff: *det.Diff, Landing: det}
	lineNotesFor(&data, det, "cafe12deadbeef", "a.go:new:2")
	var buf strings.Builder
	if err := noHooks.template(diffPage).ExecuteTemplate(&buf, "diff-more", data); err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(buf.String(), `name="blocking" value="true" data-hook="compose-blocking"`) {
		t.Errorf("FAIL: the inline composer has no Blocking checkbox")
	}
}

func TestTheOverrideCarriesItsFlagAndReasonToAccept(t *testing.T) {
	var got sayStubIn
	srv := sayStub(t, "accept", &got, nil)
	blkPost(t, srv, "/r/alpha/landing/"+blkRoot+"/accept",
		url.Values{"overrideBlocking": {"true"}, "override": {"reviewed offline"}})
	if !got.OverrideBlocking || got.Override != "reviewed offline" {
		t.Errorf("FAIL: the accept reached the op as %+v", got)
	}
}

func TestABlockingRefusalIsARefusalPageWithTheOpenListNotA500(t *testing.T) {
	var got sayStubIn
	h1, h2 := blkHash(blkOpen1), blkHash(blkOpen2)
	srv := sayStub(t, "accept", &got, &ops.Refusal{Code: api.RefusalBlockingOpen, Class: ops.ErrForbidden,
		Message: "2 open blocking comment(s) on this landing",
		Fields: map[string]string{"count": "2",
			"open": `[{"hash":"` + h1 + `","file":"","line":0},{"hash":"` + h2 + `","file":"a.go","line":7}]`}})
	resp, html := blkPost(t, srv, "/r/alpha/landing/"+blkRoot+"/accept", url.Values{})
	if resp.StatusCode != http.StatusForbidden {
		t.Fatalf("FAIL: status %d, want 403:\n%.600s", resp.StatusCode, html)
	}
	if !strings.Contains(html, `data-refusal="blocking_open"`) {
		t.Errorf("FAIL: no data-refusal hook")
	}
	if n := blkHooks(html, "blocking-link"); n != 2 {
		t.Errorf("FAIL: %d links to the open comments, want 2", n)
	}
	if !strings.Contains(html, `href="/r/alpha/landing/`+blkRoot+`#p-`+strings.Repeat(blkOpen1, 6)+`"`) {
		t.Errorf("FAIL: a link does not lead to its post on the landing")
	}
	if !strings.Contains(html, `data-hook="refusal-back" href="/r/alpha/landing/`+blkRoot+`"`) {
		t.Errorf("FAIL: no way back to the landing")
	}
}

// With no capability plane nobody holds letters, and the landing's author
// still settles (maySettleBlock): the Resolve is offered to a signed-in
// author, and to nobody who is not signed in, since a page read with no
// session has no account to be the author.
func TestWithNoCapsPlaneTheLandingAuthorSeesResolve(t *testing.T) {
	signedIn := blockingPage(t, "dan", "")
	if n := blkHooks(signedIn, "blocking-resolve"); n != 2 {
		t.Errorf("FAIL: the landing's author, with no caps plane, sees %d Resolve buttons, want 2", n)
	}
	ix, c := blockingIndex(t)
	srv := blockingServer(t, ix, c, "dan", "")
	resp, err := srv.Client().Get(srv.URL + "/r/alpha/landing/" + blkRoot)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := io.ReadAll(resp.Body)
	if n := blkHooks(string(b), "blocking-resolve"); n != 0 {
		t.Errorf("FAIL: a reader with no session is offered Resolve %d times", n)
	}
}

// A resolve or reopen shows inside the comment it names, whichever way it
// went; one aimed at nothing on the page stays a row of its own.
func TestFoldSettlesPutsEachEventInsideItsCommentAndKeepsOrphans(t *testing.T) {
	rows := []forumPostRow{
		{Hash: "b1", Blocking: "open", User: "eve"},
		{Hash: "s1", Settle: "reopened", Settles: "b1", SettleBy: "dan", SettleUnverified: true, HTML: "still broken"},
		{Hash: "s2", Settle: "resolved", Settles: "gone", User: "dan"},
		{Hash: "p1", User: "eve"},
		{Hash: "p2", User: "bob", Parent: "s1", ParentUser: "dan"},
	}
	got := foldSettles(rows)
	if len(got) != 4 || got[0].Hash != "b1" || got[1].Hash != "s2" || got[2].Hash != "p1" {
		t.Fatalf("FAIL: the flat list is %+v, want the blocker, the orphan settle and the remark", got)
	}
	if ev := got[0].Events; len(ev) != 1 || ev[0].Kind != "reopened" || ev[0].User != "dan" || !ev[0].Unverified || ev[0].HTML != "still broken" {
		t.Errorf("FAIL: the reopen is not inside the blocker it reopened: %+v", ev)
	}
}

// A reply to a settle that now lives inside its comment points at that
// comment's anchor, which exists, rather than at the settle's own, which
// is no longer drawn.
func TestAReplyToAFoldedSettleLinksToItsComment(t *testing.T) {
	got := foldSettles([]forumPostRow{
		{Hash: "b1", Blocking: "resolved", User: "eve"},
		{Hash: "s1", Settle: "resolved", Settles: "b1", SettleBy: "dan"},
		{Hash: "p2", User: "bob", Parent: "s1", ParentUser: "dan"},
	})
	if len(got) != 2 || got[1].Parent != "b1" || got[1].ParentUser != "eve" {
		t.Errorf("FAIL: the reply still points at the folded settle: %+v", got)
	}
}

// A hidden settle folded into its comment keeps the withheld treatment
// and the words it holds stay out; one nobody vouches for says so.
func TestAFoldedSettleKeepsWithheldAndUnverifiedMarks(t *testing.T) {
	row := forumPostRow{Hash: "b1b1b1b1b1b1b1", Events: []settleEvent{
		{Kind: "resolved", User: "dan", Date: "2026-08-20T13:00:00", Hidden: true, HiddenReason: "off topic"},
		{Kind: "reopened", User: "ghost", Date: "2026-08-20T14:00:00", Unverified: true, HTML: "again"},
		{Kind: "reopened", User: "eve", Date: "2026-08-20T15:00:00", Deleted: true, Removed: "abuse"},
	}}
	var buf strings.Builder
	if err := noHooks.template(landingPage).ExecuteTemplate(&buf, "blk-events", row); err != nil {
		t.Fatal(err)
	}
	out := buf.String()
	if strings.Count(out, `data-hook="post-settle"`) != 3 || strings.Count(out, `data-hook="post-deleted"`) != 1 || strings.Count(out, "data-unverified") != 1 {
		t.Errorf("FAIL: want three events, one removal notice and one unverified mark:\n%s", out)
	}
	if !strings.Contains(out, `class="f-settle-note t-none"`) || strings.Contains(out, `class="f-settle-note">`+"</div>") {
		t.Errorf("FAIL: the hidden settle is not drawn withheld:\n%s", out)
	}
}

// Replies stock Fossil can write: a resolve inside a line note, and a
// reopen no account is recorded for. The page draws both in the comment
// they settle, the second under the name it claims, marked unverified.
func TestALineNoteResolveAndAnUnrecordedReopenFoldIntoTheirComment(t *testing.T) {
	ix, c := blockingIndex(t)
	root := strings.Repeat("a1", 20)
	post := func(p, user, date, parent, body string) index.Parsed {
		return index.Parsed{Hash: blkHash(p), Art: &artifact.Artifact{Type: artifact.Forum,
			ThreadRoot: root, InReplyTo: parent, Date: date, User: user,
			Mimetype: "text/x-markdown", Body: []byte(body)}}
	}
	target := strings.Repeat("d1", 6)
	lineResolve := index.FormatLineNote(index.LineNote{File: "a.go", Side: "new", Line: 1},
		index.FormatMarker(index.MarkResolved, target, "settled in a line note"))
	if err := ix.FoldNow([]index.Parsed{
		post("d1", "eve", "2026-08-20T14:00:00", root, "blocking: one more\n"),
		post("d2", "dan", "2026-08-20T14:05:00", blkHash("d1"), lineResolve),
		post("d3", "ghost", "2026-08-20T14:10:00", blkHash("d1"), index.FormatMarker(index.MarkReopened, target, "not so")),
	}); err != nil {
		t.Fatal(err)
	}
	c[blkHash("d1")], c[blkHash("d2")] = "eve", "dan"
	html := landingGet(t, blockingServer(t, ix, c, "dan", ""), "/r/alpha/landing/"+blkRoot)
	at := strings.Index(html, `id="p-`+target+`"`)
	if at < 0 {
		t.Fatal("FAIL: the comment is not on the page")
	}
	post1 := html[at:]
	post1 = post1[:strings.Index(post1, "</article>")]
	if strings.Count(post1, `data-hook="post-settle"`) != 2 || strings.Count(post1, "data-unverified") != 1 {
		t.Errorf("FAIL: want the resolve and the reopen inside the comment, one unverified:\n%s", post1)
	}
	if !strings.Contains(post1, "settled in a line note") || strings.Contains(html, "resolved: "+target) {
		t.Errorf("FAIL: the line-note resolve is not drawn as its words")
	}
	if blkHooks(html, "blocking-open") != 1 || !strings.Contains(html, `data-count="3"`) {
		t.Errorf("FAIL: the reopen should leave the comment counted open (three open)")
	}
}

func TestHelpTextSitsBesideTheDisabledAccept(t *testing.T) {
	if blkHooks(blockingPage(t, "dan", "3i"), "blocking-help") != 1 {
		t.Errorf("FAIL: want one line of help beside the disabled accept")
	}
	plain := landingGet(t, landingServer(t, landingIndex(t, false), "3i"), "/r/alpha/landing/"+blkRoot)
	if blkHooks(plain, "blocking-help") != 0 {
		t.Errorf("FAIL: help drawn with no blocking comment open")
	}
}

// Replying to a blocker the viewer may settle offers to settle it in
// the same post; a note about the resolve is written there.
func TestReplyingToABlockerOffersToSettleItInTheSamePost(t *testing.T) {
	ix, c := blockingIndex(t)
	srv := blockingServer(t, ix, c, "dan", "3i")
	open := landingGet(t, srv, "/r/alpha/landing/"+blkRoot+"?reply-to="+blkHash(blkOpen1)[:12])
	if !strings.Contains(open, `name="resolves" value="`+blkHash(blkOpen1)+`" data-hook="compose-settle" data-as="resolves"`) {
		t.Errorf("FAIL: a reply to an open blocker does not offer to resolve it")
	}
	done := landingGet(t, srv, "/r/alpha/landing/"+blkRoot+"?reply-to="+blkHash(blkDone)[:12])
	if !strings.Contains(done, `data-hook="compose-settle" data-as="reopens"`) {
		t.Errorf("FAIL: a reply to a resolved blocker does not offer to reopen it")
	}
	plain := landingGet(t, srv, "/r/alpha/landing/"+blkRoot+"?reply-to="+blkHash("f1")[:12])
	if strings.Contains(plain, `data-hook="compose-settle"`) {
		t.Errorf("FAIL: a reply to a plain remark offers to settle something")
	}
	if strings.Contains(landingGet(t, blockingServer(t, ix, c, "mallory", "3"), "/r/alpha/landing/"+blkRoot+"?reply-to="+blkHash(blkOpen1)[:12]), `data-as="resolves"`) {
		t.Errorf("FAIL: a stranger replying to a blocker is offered to resolve it")
	}
}