From d740ad1204af505dc670b74d6ebb1e88a278cda4 Mon Sep 17 00:00:00 2001 From: Daniel Netzer Date: Thu, 12 Nov 2026 14:55:35 +0200 Subject: [PATCH] Findings tab: fixes from the first walkthrough (#386) --- lab/internal/ui/findings.go | 44 ++++++ lab/internal/ui/findings_inbox.go | 5 +- lab/internal/ui/findings_sync.go | 13 +- lab/internal/ui/findings_sync_test.go | 59 +++++-- lab/internal/ui/findings_test.go | 89 +++++++++++ lab/internal/ui/findings_view.go | 49 ++++-- lab/internal/ui/inbox_findings_test.go | 88 +++++++++++ lab/internal/ui/molecule_findings_ui_test.go | 156 +++++++++++++++++++ lab/internal/ui/sync.go | 10 +- lab/internal/ui/web/css/molecule.css | 4 + lab/internal/ui/web/js/molecule-decision.js | 7 +- lab/internal/ui/web/js/molecule-findings.js | 57 +++++-- lab/internal/ui/web/js/molecule.js | 7 +- 13 files changed, 540 insertions(+), 48 deletions(-) diff --git a/lab/internal/ui/findings.go b/lab/internal/ui/findings.go index 2f45107..eb3c474 100644 --- a/lab/internal/ui/findings.go +++ b/lab/internal/ui/findings.go @@ -12,6 +12,7 @@ import ( "regexp" "strings" "time" + "unicode/utf8" "github.com/DanielNetzer/forgecell/lab/internal/delivery" "github.com/DanielNetzer/forgecell/lab/internal/fixround" @@ -45,6 +46,8 @@ const ( findingsMaxOpen = 500 // findingsMaxRuneText bounds a served finding title or error. findingsMaxRuneText = 300 + // findingsMaxBodyRunes bounds a served finding body. + findingsMaxBodyRunes = 4000 // findingsMaxPathBytes bounds a served finding path. findingsMaxPathBytes = 1024 // findingsWriteTimeout bounds a synchronous findings write and the @@ -89,6 +92,10 @@ var findingsReasons = map[string]string{ "fix-rounds-stop": "This change request has reached its fix-round bound; continue it by hand", "too-many": "Raise the reviewers' autoFix level in the Formula or include fewer findings", "no-formula": "This Lab has no approved active Formula; approve one with forgecell init first", + // The tab follows this Molecule's Formula snapshot; a proposal follows the + // Lab's active approved Formula, so the two can differ. + "no-active-reviewers": "This Molecule's Formula snapshot declares reviewers, but the Lab's active approved Formula does not; approve a Formula that declares them, then propose again", + "not-live": "The change request is merged or closed, so there is nothing left to fix on it", } // findingsRefuse answers a findings refusal with its fixed message and the @@ -194,6 +201,35 @@ func findingsText(x redactor, s string, limit int) string { return harness.ReviewDisplayText(x.text(redactSecrets(s)), limit) } +// findingsBody is an untrusted finding body as bounded display text: secrets +// and local paths replaced, each line control-free with its whitespace +// collapsed, blank runs kept to one empty line, at most findingsMaxBodyRunes +// in all. cut reports a body the record or this bound shortened. +func findingsBody(x redactor, body string, recordedCut bool) (string, bool) { + var lines []string + left, cut := findingsMaxBodyRunes, recordedCut + for _, line := range strings.Split(x.text(redactSecrets(body)), "\n") { + line = harness.ReviewDisplayText(line, findingsMaxBodyRunes) + if line == "" && (len(lines) == 0 || lines[len(lines)-1] == "") { + continue + } + n := utf8.RuneCountInString(line) + 1 + if n > left { + if left > 1 { + lines = append(lines, harness.ReviewDisplayText(line, left-1)) + } + cut = true + break + } + left -= n + lines = append(lines, line) + } + for len(lines) > 0 && lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + return strings.Join(lines, "\n"), cut +} + // findingsPath is a finding's recorded path when it serves unchanged, or "". func findingsPath(x redactor, p string) string { if p == "" || len(p) > findingsMaxPathBytes || findingsText(x, p, findingsMaxPathBytes) != p { @@ -356,6 +392,10 @@ func (h *handler) findingsPost(w http.ResponseWriter, r *http.Request, id, actio case "findings/collect": h.findingsCollectPost(w, id, f) case "findings/propose": + if !findingsLive(receipt) { + h.findingsRefuse(w, http.StatusConflict, "not-live", "the change request is merged or closed; nothing was proposed") + return + } h.findingsProposePost(w, id, propose.Include) case "findings/dismiss": h.findingsDismissPost(w, id, dismiss.Fingerprint, func() error { @@ -476,6 +516,10 @@ func (h *handler) findingsEngineRefusal(w http.ResponseWriter, err error) { h.refuseGate(w, http.StatusServiceUnavailable, "interrupted", "the request was interrupted before the engine finished") return } + if errors.Is(err, delivery.ErrNoReviewers) { + h.findingsRefuse(w, http.StatusConflict, "no-active-reviewers", "this Lab's Formula declares no reviewers; nothing was proposed") + return + } text := err.Error() for _, m := range []struct { part, category, message string diff --git a/lab/internal/ui/findings_inbox.go b/lab/internal/ui/findings_inbox.go index 9bfa4c9..7e423fb 100644 --- a/lab/internal/ui/findings_inbox.go +++ b/lab/internal/ui/findings_inbox.go @@ -99,9 +99,10 @@ func findingsLive(receipt delivery.Receipt) bool { // confirmation, else open reviewer findings to triage when none of them is // pending in a fix round. It replaces only an In-progress, Recently recorded // or empty entry, never a scope, publish or blocked card, and reads no -// workspace and starts no process. +// workspace and starts no process. A merged or closed change request has no +// findings decision: its entry stays as it is. func inboxFindingsOverlay(lab string, r molecule.Record, v *InboxView) { - if v == nil || r.Status == molecule.StatusRetired || (v.Kind != "" && v.Kind != InboxProgress && v.Kind != InboxRecorded) { + if v == nil || v.Merged || r.Status == molecule.StatusRetired || (v.Kind != "" && v.Kind != InboxProgress && v.Kind != InboxRecorded) { return } f, ok := findingsSnapshot(r) diff --git a/lab/internal/ui/findings_sync.go b/lab/internal/ui/findings_sync.go index 9dd4da5..8d48b20 100644 --- a/lab/internal/ui/findings_sync.go +++ b/lab/internal/ui/findings_sync.go @@ -20,8 +20,10 @@ import ( // holds a pending or errored reviewer. Each Molecule is collected at most once // per max(60s, the largest needs.minPollSeconds of its reviewer plugins); a // failed collection, or one whose newest round is incomplete or holds an -// errored reviewer, doubles that wait for each further consecutive failure, up -// to one hour, as the keyed Issues view does. A Lab UI started without a source checkout runs nothing. +// errored reviewer, waits twice that, and doubles the wait for each further +// consecutive failure, up to one hour, as the keyed Issues view does. So a +// failing reviewer is not collected again a minute after the Lab opens. A Lab +// UI started without a source checkout runs nothing. // The pass never proposes, dismisses or pushes. const ( @@ -229,11 +231,18 @@ func (h *handler) findingsSyncPass(ctx context.Context, ids []string) { s.entries[d.id] = e } e.ttl = issuesKeyedBackoff(d.interval, e.ttl, e.failed, failed) + if failed { + e.ttl = min(max(e.ttl, findingsSyncFailedWait(d.interval)), issuesKeyedMaxPoll) + } e.finished, e.failed = h.findingsNow(), failed s.mu.Unlock() } } +// findingsSyncFailedWait is the shortest wait after a failed collection: +// twice the Molecule's interval. +func findingsSyncFailedWait(interval time.Duration) time.Duration { return 2 * interval } + // findingsSyncFailedRound reports a collection whose newest round is cut by a // bound or holds a reviewer that errored: it backs off as a failure does. func findingsSyncFailedRound(record delivery.FindingsRecord) bool { diff --git a/lab/internal/ui/findings_sync_test.go b/lab/internal/ui/findings_sync_test.go index c122699..e603539 100644 --- a/lab/internal/ui/findings_sync_test.go +++ b/lab/internal/ui/findings_sync_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net/http" "os" "path/filepath" "sort" @@ -216,14 +217,16 @@ func TestFindingsSyncBacksOffOnFailure(t *testing.T) { t.Fatalf("at %v: %d collections, want %d", clock.get().Format(time.TimeOnly), got, want) } } - at(1) // fails: the next waits a minute + at(1) // fails: the next waits twice the minute clock.advance(time.Minute) - at(2) // fails again: the wait doubles to 2 minutes + at(1) clock.advance(time.Minute) + at(2) // fails again: the wait doubles to 4 minutes + clock.advance(3 * time.Minute) at(2) clock.advance(time.Minute) - at(3) // 4 minutes next - clock.advance(3 * time.Minute) + at(3) // 8 minutes next + clock.advance(7 * time.Minute) at(3) clock.advance(time.Minute) at(4) @@ -262,14 +265,16 @@ func TestFindingsSyncRetriesAnErroredReviewerWithBackoff(t *testing.T) { findingsTestWrite(t, lab, id, nil, errored) c.returns(delivery.FindingsRecord{Rounds: []delivery.FindingsRound{errored}}) at := func(want int) { t.Helper(); findingsSyncAt(t, h, list, clock, c, want) } - at(1) // collected without error, but the reviewer errored: a minute next + at(1) // collected without error, but the reviewer errored: 2 minutes next clock.advance(time.Minute) - at(2) // errored again: the wait doubles to 2 minutes + at(1) clock.advance(time.Minute) + at(2) // errored again: the wait doubles to 4 minutes + clock.advance(3 * time.Minute) at(2) clock.advance(time.Minute) - at(3) // 4 minutes next - clock.advance(3 * time.Minute) + at(3) // 8 minutes next + clock.advance(7 * time.Minute) at(3) // The reviewer answers: a good round resets the wait, and a complete // round on the head without errors is not collected again. @@ -297,10 +302,12 @@ func TestFindingsSyncBacksOffATruncatedRound(t *testing.T) { at := func(want int) { t.Helper(); findingsSyncAt(t, h, list, clock, c, want) } at(1) clock.advance(time.Minute) - at(2) + at(1) // not a minute later: a failure waits twice the minute clock.advance(time.Minute) - at(2) // not every minute: the wait doubled + at(2) clock.advance(time.Minute) + at(2) // the wait doubled + clock.advance(3 * time.Minute) at(3) // A persistently truncated reviewer settles at one collection an hour. for i := 0; i < 10; i++ { @@ -323,6 +330,38 @@ func TestFindingsSyncBacksOffATruncatedRound(t *testing.T) { } } +// Opening the Lab while a reviewer fails collects once, not again a minute +// later: a failed round waits twice the interval. Collect now still runs. +func TestFindingsSyncDoesNotRecollectAFailedRoundWithinTheWindow(t *testing.T) { + h, list, clock, c := findingsSyncFixture(t, 1, "/src") + h.findingsPoll = func(string, formula.Formula) time.Duration { return 0 } + errored := findingsTestRound(findingsTestCommit, delivery.FindingsError, true) + errored.Reviewers[0].Error = "the reviewer failed" + c.returns(delivery.FindingsRecord{Rounds: []delivery.FindingsRound{errored}}) + at := func(want int) { t.Helper(); findingsSyncAt(t, h, list, clock, c, want) } + at(1) + clock.advance(findingsSyncMinPoll) + at(1) + clock.advance(findingsSyncMinPoll - time.Second) + at(1) + clock.advance(time.Second) + at(2) + h.findingsSync.mu.Lock() + ttl := h.findingsSync.entries[list[0].ID].ttl + h.findingsSync.mu.Unlock() + if ttl < findingsSyncFailedWait(findingsSyncMinPoll) { + t.Fatalf("wait %v after two failures", ttl) + } + // The throttle is the background pass's alone: Collect now is not held back. + if w := do(t, h, gatePost("/api/molecules/"+list[0].ID+"/findings/collect", `{}`)); w.Code != http.StatusAccepted { + t.Fatalf("collect now: %d %s", w.Code, w.Body) + } + waitJob(t, h, findingsJobKey(list[0].ID)) + if got := len(c.collected()); got != 3 { + t.Fatalf("%d collections after Collect now, want 3", got) + } +} + func TestFindingsSyncStopsOnCancel(t *testing.T) { h, list, _, c := findingsSyncFixture(t, 3, "/src") c.during = func(ctx context.Context, id string) error { diff --git a/lab/internal/ui/findings_test.go b/lab/internal/ui/findings_test.go index 8fd5266..e837fdf 100644 --- a/lab/internal/ui/findings_test.go +++ b/lab/internal/ui/findings_test.go @@ -656,6 +656,95 @@ func TestFindingsProposeServesALineOnlyWithItsPath(t *testing.T) { } } +// findingsTestLifecycle records the change request's observed state on the +// Molecule's receipt. +func findingsTestLifecycle(t *testing.T, lab, id, state string) { + t.Helper() + path := filepath.Join(lab, "deliveries", id+".json") + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + observed := strings.Replace(string(raw), `"state":"published"`, `"state":"published","lifecycle":{"state":"`+state+`","observedAt":"2026-11-02T10:00:00Z"}`, 1) + if err := os.WriteFile(path, []byte(observed), 0600); err != nil { + t.Fatal(err) + } +} + +// Item 3 of #386: each open finding serves its body, redacted, control-free +// with its lines kept, and bounded; the snapshot's reviewer plugins are named. +func TestFindingsViewServesFindingBodies(t *testing.T) { + lab := t.TempDir() + r := findingsTestRecord(lab, findingsTestID, true) + findingsTestReceipt(t, lab, r.ID) + explained := findingsTestFinding("a", "high", "src/a.go", "Nil deref") + explained.Body = "The pointer is nil with " + findingsTestSecret + ".\r\n\n\n\x1b[31mSee " + r.Workspace.Path + "/src/a.go\x07 too.\nLast line." + long := findingsTestFinding("b", "medium", "src/b.go", "Long") + long.Body = strings.Repeat("word ", 2000) + bare := findingsTestFinding("c", "low", "src/c.go", "No body") + findingsTestWrite(t, lab, r.ID, nil, findingsTestRound(findingsTestCommit, delivery.FindingsComplete, true, explained, long, bare)) + h, _ := findingsTestHandler(t, lab, "/src", r) + v, body := findingsGetView(t, h, r.ID) + if len(v.Open) != 3 || len(v.Plugins) != 1 || v.Plugins[0] != "critic" || v.Lifecycle != "" { + t.Fatalf("view %+v", v) + } + got := v.Open[0] + if got.BodyTruncated || !strings.HasPrefix(got.Body, "The pointer is nil with ") || !strings.HasSuffix(got.Body, "\nLast line.") || strings.Count(got.Body, "\n") != 3 || strings.Contains(got.Body, "\n\n\n") { + t.Fatalf("body %q", got.Body) + } + if strings.ContainsAny(got.Body, "\r\x1b\x07") || strings.Contains(got.Body, findingsTestSecret) || strings.Contains(body, r.Workspace.Path) { + t.Fatalf("body served unredacted: %q", got.Body) + } + if n := len([]rune(v.Open[1].Body)); !v.Open[1].BodyTruncated || n == 0 || n > findingsMaxBodyRunes { + t.Fatalf("long body: %d runes, truncated %v", n, v.Open[1].BodyTruncated) + } + if v.Open[2].Body != "" || v.Open[2].BodyTruncated || strings.Count(body, `"body":`) != 2 { + t.Fatalf("an empty body was served: %+v", v.Open[2]) + } +} + +// Item 5 of #386: the engine's "this Lab's Formula declares no reviewers" is +// its own refusal, whose next step names the Formula mismatch. +func TestFindingsProposeNoActiveReviewersReason(t *testing.T) { + _, r, h, fake := findingsTestLab(t, "/src") + fake.proposeErr = delivery.ErrNoReviewers + got := findingsRefusalOf(t, do(t, h, gatePost("/api/molecules/"+r.ID+"/findings/propose", `{"include":[]}`)), http.StatusConflict, "no-active-reviewers") + if got.Error != "this Lab's Formula declares no reviewers; nothing was proposed" || got.Reason != findingsReasons["no-active-reviewers"] { + t.Fatalf("refusal %+v", got) + } + if !strings.Contains(got.Reason, "This Molecule's Formula snapshot declares reviewers, but the Lab's active approved Formula does not") { + t.Fatalf("reason %q", got.Reason) + } +} + +// Item 4 of #386: once the change request is merged or closed, the view says +// so and a proposal is refused without calling the engine. +func TestFindingsProposeRefusedAfterMergeOrClose(t *testing.T) { + for state, want := range map[string]string{"MERGED": "merged", "CLOSED": "closed"} { + t.Run(state, func(t *testing.T) { + lab, r, h, fake := findingsTestLab(t, "/src") + findingsTestLifecycle(t, lab, r.ID, state) + if v, _ := findingsGetView(t, h, r.ID); v.Lifecycle != want || !v.Published { + t.Fatalf("view lifecycle %q, want %q", v.Lifecycle, want) + } + got := findingsRefusalOf(t, do(t, h, gatePost("/api/molecules/"+r.ID+"/findings/propose", `{"include":[]}`)), http.StatusConflict, "not-live") + if got.Reason != findingsReasons["not-live"] { + t.Fatalf("refusal %+v", got) + } + if _, proposes, _, pushes := fake.counts(); proposes != 0 || pushes != 0 { + t.Fatalf("a refused proposal called the engine: %d proposals, %d pushes", proposes, pushes) + } + }) + } + // An open change request still proposes. + lab, r, h, fake := findingsTestLab(t, "/src") + findingsTestLifecycle(t, lab, r.ID, "OPEN") + fake.proposal = fixround.Proposal{Round: 1, None: true} + if w := do(t, h, gatePost("/api/molecules/"+r.ID+"/findings/propose", `{"include":[]}`)); w.Code != http.StatusOK { + t.Fatalf("open change request: %d %s", w.Code, w.Body) + } +} + func TestFindingsSampleDataServesNoFindings(t *testing.T) { h := testHandler(t, Options{Demo: true}) if w := do(t, h, authed("/api/molecules/"+findingsTestID+"/findings")); w.Code != http.StatusNotFound { diff --git a/lab/internal/ui/findings_view.go b/lab/internal/ui/findings_view.go index 1b94dc1..18e4c9a 100644 --- a/lab/internal/ui/findings_view.go +++ b/lab/internal/ui/findings_view.go @@ -16,10 +16,15 @@ import ( // declares no reviewers serves {"reviewers": false} alone. type ReviewerFindingsView struct { Reviewers bool `json:"reviewers"` + // Plugins names the snapshot's reviewer plugins in declaration order, for + // display; the reviewer fields below keep the reviewer keys. + Plugins []string `json:"plugins,omitempty"` // Published is set when the receipt is a published delivery; Head is then - // its change request's current head. + // its change request's current head. Lifecycle is "merged" or "closed" once + // the receipt observed its change request so; a proposal is then refused. Published bool `json:"published,omitempty"` Head string `json:"head,omitempty"` + Lifecycle string `json:"lifecycle,omitempty"` // Unreadable is set, with a fixed Error, when the findings record could not // be read; nothing else of it is served. Unreadable bool `json:"unreadable,omitempty"` @@ -55,17 +60,32 @@ type FindingsRoundView struct { } // FindingsOpenView is one open finding of the latest complete round. Repeated -// is set when an earlier fix round addressed it and it came back. +// is set when an earlier fix round addressed it and it came back. Body is the +// reviewer's explanation, served on the view only (findingsBody). type FindingsOpenView struct { - Reviewer string `json:"reviewer"` - Plugin string `json:"plugin"` - Severity string `json:"severity"` - Path string `json:"path,omitempty"` - Line int64 `json:"line,omitempty"` - Title string `json:"title"` - Fingerprint string `json:"fingerprint"` - AutoFix bool `json:"autoFix"` - Repeated bool `json:"repeated"` + Reviewer string `json:"reviewer"` + Plugin string `json:"plugin"` + Severity string `json:"severity"` + Path string `json:"path,omitempty"` + Line int64 `json:"line,omitempty"` + Title string `json:"title"` + Body string `json:"body,omitempty"` + BodyTruncated bool `json:"bodyTruncated,omitempty"` + Fingerprint string `json:"fingerprint"` + AutoFix bool `json:"autoFix"` + Repeated bool `json:"repeated"` +} + +// findingsLifecycle is "merged" or "closed" for a receipt whose change request +// is no longer live, or "". +func findingsLifecycle(receipt delivery.Receipt) string { + switch { + case findingsLive(receipt): + return "" + case receipt.Lifecycle.State == "MERGED": + return "merged" + } + return "closed" } // FindingsDismissal is one dismissed finding and the operator's reason. @@ -142,6 +162,9 @@ func (h *handler) findingsView(ctx context.Context, r molecule.Record) ReviewerF lab := h.opts.LabDir x := newRedactor(lab, r) v := ReviewerFindingsView{Reviewers: true, Collecting: h.findingsBusy(r.ID)} + for _, ref := range f.Reviewers() { + v.Plugins = append(v.Plugins, findingsText(x, ref.Plugin, findingsMaxRuneText)) + } if j, ok := h.jobs.get(findingsJobKey(r.ID)); ok { v.Collect = findingsJobOf(j) } @@ -153,6 +176,7 @@ func (h *handler) findingsView(ctx context.Context, r molecule.Record) ReviewerF if rerr == nil { v.Published = true v.Head, _ = delivery.ReceiptHead(receipt) + v.Lifecycle = findingsLifecycle(receipt) for _, fr := range receipt.FixRounds { v.FixRounds = append(v.FixRounds, FindingsFixRound{Round: fr.Round, Commit: fr.Commit, PushedAt: stepSince(fr.PushedAt)}) for _, fp := range fr.Findings { @@ -208,7 +232,8 @@ func findingsRecordView(x redactor, f formula.Formula, record delivery.FindingsR title = "(untitled)" } path := findingsPath(x, sf.Path) - v.Open = append(v.Open, FindingsOpenView{Reviewer: findingsText(x, sf.Reviewer, findingsMaxRuneText), Plugin: findingsText(x, sf.Plugin, findingsMaxRuneText), Severity: sf.Severity, Path: path, Line: findingsLine(path, sf.Line), Title: title, Fingerprint: sf.Fingerprint, AutoFix: sf.AutoFix, Repeated: addressed[sf.Fingerprint]}) + body, cut := findingsBody(x, sf.Body, sf.BodyTruncated) + v.Open = append(v.Open, FindingsOpenView{Reviewer: findingsText(x, sf.Reviewer, findingsMaxRuneText), Plugin: findingsText(x, sf.Plugin, findingsMaxRuneText), Severity: sf.Severity, Path: path, Line: findingsLine(path, sf.Line), Title: title, Body: body, BodyTruncated: cut && body != "", Fingerprint: sf.Fingerprint, AutoFix: sf.AutoFix, Repeated: addressed[sf.Fingerprint]}) } } v.OpenCount = count(v.OpenCount) diff --git a/lab/internal/ui/inbox_findings_test.go b/lab/internal/ui/inbox_findings_test.go index a25708a..711b012 100644 --- a/lab/internal/ui/inbox_findings_test.go +++ b/lab/internal/ui/inbox_findings_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/DanielNetzer/forgecell/lab/internal/delivery" + "github.com/DanielNetzer/forgecell/lab/internal/forgesync" "github.com/DanielNetzer/forgecell/lab/internal/molecule" ) @@ -130,6 +131,93 @@ func TestInboxFindingsKindsAndTheirPrecedence(t *testing.T) { } } +// Item 4 of #386: a merged or closed change request has no findings or +// fix-round entry, whether its receipt observed it or the entry already +// carries the merge; a live one keeps its entry. +func TestInboxFindingsMergedOrClosedDropsTheEntry(t *testing.T) { + a := findingsTestFinding("a", "high", "src/a.go", "Nil deref") + b := findingsTestFinding("b", "low", "docs/x.md", "Typo") + for _, state := range []string{"MERGED", "CLOSED"} { + for name, pending := range map[string]bool{"findings": false, "fix round": true} { + t.Run(state+" "+name, func(t *testing.T) { + lab := t.TempDir() + r := findingsTestRecord(lab, findingsTestID, true) + findingsTestReceipt(t, lab, r.ID) + findingsTestWrite(t, lab, r.ID, nil, findingsTestRound(findingsTestCommit, delivery.FindingsComplete, true, a, b)) + if pending { + findingsTestPending(&r, 1, findingsTestCommit, findingsTestTree, true, true, b.Fingerprint) + } + findingsTestLifecycle(t, lab, r.ID, state) + got := summarize(lab, r, delivery.ReadReceiptStatus).Inbox + if got.Kind == InboxFindings || got.Kind == InboxFixRound || inboxFindingsJSON(t, got) != inboxFindingsJSON(t, inboxFindingsBase(lab, r)) { + t.Fatalf("entry %+v", got) + } + }) + } + } + // An entry that already carries the merge is left as it is, even over a + // receipt still observed open. + lab := t.TempDir() + r := findingsTestRecord(lab, findingsTestID, true) + findingsTestReceipt(t, lab, r.ID) + findingsTestWrite(t, lab, r.ID, nil, findingsTestRound(findingsTestCommit, delivery.FindingsComplete, true, a, b)) + v := InboxView{Kind: InboxRecorded, Title: "Merged", Action: "Open", Merged: true} + inboxFindingsOverlay(lab, r, &v) + if v.Kind != InboxRecorded || v.Title != "Merged" || !v.Merged { + t.Fatalf("merged entry %+v", v) + } + live := InboxView{Kind: InboxRecorded, Title: "Draft published", Action: "Open"} + inboxFindingsOverlay(lab, r, &live) + if live.Kind != InboxFindings { + t.Fatalf("live entry %+v", live) + } + // /api/sync counts a findings entry under Needs you only while GitHub has + // not seen its pull request merged or closed. The pull request decides, + // whatever bucket the Issue or the ledger lane files the state under. + issue := func(state, reason, reopenedAt string) *forgesync.Issue { + return &forgesync.Issue{Number: 351, Found: true, State: state, StateReason: reason, ReopenedAt: reopenedAt} + } + pr := func(state string) map[int64]forgesync.PR { + p := forgesync.PR{Number: 374, Found: true, State: state} + if state == forgesync.PRMerged { + p.MergedAt, p.MergeCommit = "2026-11-01T10:00:00Z", findingsTestCommit + } + return map[int64]forgesync.PR{374: p} + } + mol := func(lane string) forgesync.Molecule { + return forgesync.Molecule{ID: findingsTestID, Lane: lane, StartedAt: "2026-11-01T09:00:00Z", PRNumber: 374, PublishedCommit: findingsTestCommit} + } + open, closed := forgesync.IssueOpen, forgesync.IssueClosed + for name, c := range map[string]struct { + issue *forgesync.Issue + pr string + lane string + live bool + }{ + "merged": {issue(closed, forgesync.ReasonCompleted, ""), forgesync.PRMerged, forgesync.LaneFinished, false}, + "merged, Issue open": {issue(open, "", ""), forgesync.PRMerged, forgesync.LaneFinished, false}, + "PR closed": {issue(open, "", ""), forgesync.PRClosed, forgesync.LaneFinished, false}, + "not planned, PR merged": {issue(closed, forgesync.ReasonNotPlanned, ""), forgesync.PRMerged, forgesync.LaneFinished, false}, + "closed elsewhere, PR closed": {issue(closed, forgesync.ReasonCompleted, ""), forgesync.PRClosed, forgesync.LaneFinished, false}, + "reopened after merge": {issue(open, forgesync.ReasonReopened, "2026-11-02T10:00:00Z"), forgesync.PRMerged, forgesync.LaneFinished, false}, + "live ledger lane, PR merged": {issue(open, "", ""), forgesync.PRMerged, forgesync.LaneDecision, false}, + "draft PR open": {issue(open, "", ""), forgesync.PROpen, forgesync.LaneFinished, true}, + "open PR, Issue closed": {issue(closed, forgesync.ReasonCompleted, ""), forgesync.PROpen, forgesync.LaneFinished, true}, + "PR not checked": {issue(open, "", ""), "", forgesync.LaneFinished, true}, + "GitHub not checked": {nil, "", forgesync.LaneFinished, true}, + "live ledger lane, PR open": {issue(open, "", ""), forgesync.PROpen, forgesync.LaneDecision, true}, + } { + prs := map[int64]forgesync.PR{} + if c.pr != "" { + prs = pr(c.pr) + } + d := forgesync.ForMolecule(c.issue, prs, mol(c.lane)) + if got := syncFindingsLive(d); got != c.live { + t.Errorf("%s (%s, bucket %s): findings entry live %v, want %v", name, d.Kind, d.Bucket, got, c.live) + } + } +} + // Without reviewers, every existing kind is exactly inboxView's. func TestInboxFindingsLeavesEveryExistingKindByteIdentical(t *testing.T) { cases := map[string]func(t *testing.T) (string, molecule.Record){ diff --git a/lab/internal/ui/molecule_findings_ui_test.go b/lab/internal/ui/molecule_findings_ui_test.go index bd3f5e2..31e2653 100644 --- a/lab/internal/ui/molecule_findings_ui_test.go +++ b/lab/internal/ui/molecule_findings_ui_test.go @@ -253,6 +253,162 @@ func TestMoleculeFindingsTabMarkup(t *testing.T) { } } +// moleculeFindingsWants checks that each named function of js holds its wants. +func moleculeFindingsWants(t *testing.T, js string, wants map[string][]string) { + t.Helper() + for name, list := range wants { + body := moduleFunction(t, js, name) + for _, want := range list { + if !strings.Contains(body, want) { + t.Errorf("%s lacks %q", name, want) + } + } + } +} + +// Item 2 of #386: a failed reviewer's round shows the failure and its reason +// only, never "round complete" next to it. Item 1: every reviewer is shown by +// its plugin name, never by its key ("0:forgecomments"). +func TestMoleculeFindingsFailedRoundShowsFailureOnly(t *testing.T) { + js := moleculeFindingsModule(t) + round := moduleFunction(t, js, "findingsRoundItem") + failure := "const line = status === 'failed' ? 'Failed: ' + (error || 'no reason was recorded') + '.' : " + at := strings.Index(round, failure) + if at < 0 { + t.Fatalf("findingsRoundItem lacks the failure-only line: %s", round) + } + // The round's completeness is only on the branch of a reviewer that did not fail. + for _, text := range []string{"'round complete'", "'round incomplete'"} { + if i := strings.Index(round, text); i < at+len(failure) { + t.Errorf("findingsRoundItem shows %s outside the not-failed branch", text) + } + } + if !strings.Contains(round, "status !== 'failed' && error ? el('p', { class: 'file-reason' }, error) : null") { + t.Error("findingsRoundItem repeats a failed reviewer's error") + } + moleculeFindingsWants(t, js, map[string][]string{ + "findingsName": {"plainText(r.plugin, '')", ".replace(/^\\d+:/, '')"}, + "findingsRoundItem": {"el('code', null, findingsName(r))"}, + "findingsOpenItem": {"el('p', { class: 'file-reason' }, findingsName(f))"}, + "findingsRenderDismissed": {"[findingsName(d), when ? 'dismissed ' + when : '']"}, + }) + for _, bad := range []string{"plainText(r.reviewer, 'Reviewer'))", "plainText(f.reviewer, '')", "plainText(d.reviewer, 'Reviewer')"} { + if strings.Contains(js, bad) { + t.Errorf("molecule-findings.js still shows a reviewer key: %q", bad) + } + } +} + +// Item 4 of #386: once the change request is merged or closed, on its receipt +// or as the GitHub sync observed it, Propose is disabled with its reason. +// Item 10: without open findings Propose is hidden, not only disabled. +func TestMoleculeFindingsProposeDisabledAfterMerge(t *testing.T) { + js := moleculeFindingsModule(t) + moleculeFindingsWants(t, js, map[string][]string{ + "findingsEnsure": { + "c.proposeHelp = el('p', { class: 'drive-help', id: uid('mv-propose-help'), hidden: true });", + "'aria-describedby': c.proposeHelp.id, dataset: { gate: 'findings-propose' }", + "c.propose, c.proposeHelp, c.proposal", + }, + "findingsRenderOpen": { + "const s = syncOf(fx.id), pr = s && s.pr, ended = v.lifecycle === 'merged' || (pr && pr.state === 'MERGED') ? 'merged' : v.lifecycle === 'closed' || (pr && pr.state !== 'OPEN') ? 'closed' : '';", + "c.propose.hidden = open.length === 0;", + "c.propose.disabled = busy || v.published !== true || open.length === 0 || Boolean(ended);", + "setText(c.proposeHelp, ended ? 'The change request is ' + ended + ', so there is nothing left to propose a fix round for.' : '');", + "c.proposeHelp.hidden = !ended || open.length === 0;", + }, + }) + if !regexp.MustCompile(`(?m)^import \{[^}]*\bsyncOf\b[^}]*\} from './core\.js';$`).MatchString(js) { + t.Error("molecule-findings.js does not read the sync state from core.js") + } +} + +// Item 5 of #386: a refused proposal shows the served category, message and +// reason through refusalText, never a bare "Refused (refused)". +func TestMoleculeFindingsShowsRefusalReason(t *testing.T) { + js := moleculeFindingsModule(t) + moleculeFindingsWants(t, js, map[string][]string{ + "findingsPost": {"if (!res.ok) { findingsSay(refusalText(data)); return null; }"}, + "findingsSay": {"fx.message = text;", "fx.announce = true;"}, + "findingsPropose": {"const proposal = await findingsPost('findings/propose', { include: include });"}, + }) + gates := do(t, testHandler(t, Options{LabDir: t.TempDir()}), authed("/js/core-gates.js")).Body.String() + moleculeFindingsWants(t, gates, map[string][]string{ + "refusalText": {"body.category", "notRecorded(body && body.error)", "reasonText(body)"}, + "reasonText": {"body.reason"}, + }) + // The server side: the engine's no-reviewers refusal has its own category + // and a next step that names the Formula mismatch. + for _, category := range []string{"no-active-reviewers", "not-live"} { + if reason := findingsReasons[category]; !boundedReason(reason) { + t.Errorf("category %s has reason %q", category, reason) + } + } + if !strings.Contains(findingsReasons["no-active-reviewers"], "Formula snapshot declares reviewers, but the Lab's active approved Formula does not") { + t.Errorf("no-active-reviewers reason %q", findingsReasons["no-active-reviewers"]) + } +} + +// Item 6 of #386: a refused or lost proposal keeps every ticked include box; +// only a proposal, or another Molecule, clears them. +func TestMoleculeFindingsKeepsSelectionAfterRefusal(t *testing.T) { + js := moleculeFindingsModule(t) + propose := moduleFunction(t, js, "findingsPropose") + for _, want := range []string{ + "const id = fx.id, kept = new Set(fx.checked);", + "if (!proposal) { fx.checked = kept; findingsRender(); return; }", + } { + if !strings.Contains(propose, want) { + t.Errorf("findingsPropose lacks %q", want) + } + } + refused, cleared := strings.Index(propose, "if (!proposal) {"), strings.Index(propose, "fx.checked = new Set();") + if refused < 0 || cleared < refused || strings.Count(propose, "fx.checked = new Set();") != 1 { + t.Errorf("findingsPropose clears the ticks before a proposal: %s", propose) + } + // Every render restores the boxes from fx.checked; only the success path, + // a dismissal of that finding and a new selection change it. + moleculeFindingsWants(t, js, map[string][]string{ + "findingsRenderOpen": {"for (const box of c.open.querySelectorAll('input[type=checkbox]')) box.checked = fx.checked.has(box.dataset.fingerprint);"}, + "findingsSelect": {"fx.checked = new Set();"}, + }) + for _, name := range []string{"findingsPost", "findingsSay", "findingsLoad", "findingsRender"} { + if strings.Contains(moduleFunction(t, js, name), "fx.checked") { + t.Errorf("%s changes the ticked findings", name) + } + } +} + +// Item 3 of #386: a finding's body is shown as text under its title, collapsed +// when long or multi-line. Item 7: the roles row names the declared reviewers. +func TestMoleculeFindingsShowsBodiesAndDeclaredReviewers(t *testing.T) { + js := moleculeFindingsModule(t) + moleculeFindingsWants(t, js, map[string][]string{ + "findingsBodyBlock": { + "el('p', { class: 'mv-finding-body' }, body + (f.bodyTruncated === true ? ' …' : ''))", + "body.length <= FINDINGS_BODY_SHORT && !body.includes('\\n')", + "el('details', { class: 'mv-details' }, el('summary', null, 'The reviewer’s explanation')", + }, + "findingsOpenItem": {"el('p', { class: 'file-reason' }, plainText(f.title, '(untitled)')),\n findingsBodyBlock(f),"}, + "findingsReviewers": {"fx.id === id", "fx.view.plugins"}, + "findingsShowTab": {"if (fx.onView) fx.onView();"}, + }) + h := testHandler(t, Options{LabDir: t.TempDir()}) + moleculeFindingsWants(t, do(t, h, authed("/js/molecule.js")).Body.String(), map[string][]string{ + "renderDetail": {"renderRoles(d, findingsReviewers(d.id));"}, + "mount": {"mountFindings(chooseTab, () => { const d = state.detail; if (d && d.view) renderRoles(d, findingsReviewers(d.id)); });"}, + }) + moleculeFindingsWants(t, do(t, h, authed("/js/molecule-decision.js")).Body.String(), map[string][]string{ + "renderRoles": {"Array.isArray(reviewers) ? reviewers.filter(", "outside.join(', ')", "|| 'No review step'"}, + }) + css := servedCSS(t) + for _, want := range []string{".confirm-form .drive-field { flex: 0 0 auto; align-content: start; }", ".mv-finding-body { white-space: pre-wrap;"} { + if !strings.Contains(css, want) { + t.Errorf("molecule.css lacks %q", want) + } + } +} + // moleculeFindingsDocText is a document as one lower-case line: quote markers // and line breaks do not hide a phrase. func moleculeFindingsDocText(raw string) string { diff --git a/lab/internal/ui/sync.go b/lab/internal/ui/sync.go index ab56c70..b349c35 100644 --- a/lab/internal/ui/sync.go +++ b/lab/internal/ui/sync.go @@ -29,6 +29,14 @@ func needsYou(d forgesync.DisplayState) bool { return d.Bucket == forgesync.BucketDecision || d.Bucket == forgesync.BucketBlocked } +// syncFindingsLive reports a state whose pull request GitHub has not seen +// merged or closed: only then is a findings or fix-round entry a decision. It +// reads the pull request itself, never the bucket, which the Issue and the +// ledger lane decide first. No pull request read leaves the receipt to decide. +func syncFindingsLive(d forgesync.DisplayState) bool { + return d.PR == nil || d.PR.State == forgesync.PROpen +} + func (h *handler) syncStates(w http.ResponseWriter, r *http.Request) { if h.opts.Demo { h.json(w, http.StatusOK, demoSync()) @@ -68,7 +76,7 @@ func (h *handler) syncStates(w http.ResponseWriter, r *http.Request) { if d.Bucket != forgesync.BucketRetired { out.Counts[d.Bucket]++ } - if needsYou(d) || s.Inbox.Kind == InboxFixRound || s.Inbox.Kind == InboxFindings { + if needsYou(d) || (syncFindingsLive(d) && (s.Inbox.Kind == InboxFixRound || s.Inbox.Kind == InboxFindings)) { out.NeedsYou[s.ID] = true } } diff --git a/lab/internal/ui/web/css/molecule.css b/lab/internal/ui/web/css/molecule.css index 7ec6f36..8b9696b 100644 --- a/lab/internal/ui/web/css/molecule.css +++ b/lab/internal/ui/web/css/molecule.css @@ -112,6 +112,10 @@ .confirm-question { font-size: 14px; font-weight: 600; color: var(--ink); overflow-wrap: anywhere; } .confirm-actions { display: flex; flex-wrap: wrap; gap: 10px; } .confirm-actions .btn { flex: 1 1 auto; } +/* In the column form a field's 150px flex basis is a height: keep the label on its input. */ +.confirm-form .drive-field { flex: 0 0 auto; align-content: start; } +/* A finding's body is the reviewer's own lines, wrapped. */ +.mv-finding-body { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; color: #3e5448; } /* The Timeline tab: origin, totals, the Formula snapshot and the Atoms. */ .run-panel { padding: 22px; } diff --git a/lab/internal/ui/web/js/molecule-decision.js b/lab/internal/ui/web/js/molecule-decision.js index df0ed0e..4b226e0 100644 --- a/lab/internal/ui/web/js/molecule-decision.js +++ b/lab/internal/ui/web/js/molecule-decision.js @@ -391,14 +391,17 @@ function rangeText(low, high) { return a + '–' + b; } -export function renderRoles(d) { +// renderRoles patches the roles row. reviewers are the outside reviewer +// plugins the Molecule's Formula declares: a review step too. +export function renderRoles(d, reviewers) { const c = ensureMoleculeView(); const v = d.view; $('#mv-roles').hidden = !v; if (!v) return; const r = v.roles || {}; setText(c.roles.coding, [plainText(r.coding, ''), plainText(r.model, '')].filter(Boolean).join(' · ') || 'Not recorded'); - setText(c.roles.reviewer, typeof r.reviewer === 'string' && r.reviewer ? r.reviewer + ', read-only' : 'No review step'); + const outside = Array.isArray(reviewers) ? reviewers.filter((n) => typeof n === 'string' && n) : []; + setText(c.roles.reviewer, [typeof r.reviewer === 'string' && r.reviewer ? r.reviewer + ', read-only' : '', outside.join(', ')].filter(Boolean).join(' · ') || 'No review step'); const p = v.planningCost, total = p && money(p.usd); setText(c.roles.cost, !total ? 'Not recorded' : p.partial ? total + ' · reported for ' + count(p.reported) + ' of ' + counted(count(p.attempts), 'attempt', 'attempts') : total); } diff --git a/lab/internal/ui/web/js/molecule-findings.js b/lab/internal/ui/web/js/molecule-findings.js index 840da58..467823b 100644 --- a/lab/internal/ui/web/js/molecule-findings.js +++ b/lab/internal/ui/web/js/molecule-findings.js @@ -8,7 +8,7 @@ // round runs a git preview, so it is never read in a tight loop or while the // page is hidden. A collection or a push started here is followed by the // bounded poll below, since /job does not report these jobs. -import { $, el, uid, fill, state, ctx, PULL_URL, externalLink, api, failed, keepFocus, setText, plainText, count, counted, whenText, dateTitle, SessionError } from './core.js'; +import { $, el, uid, fill, state, ctx, PULL_URL, externalLink, api, failed, keepFocus, setText, plainText, count, counted, whenText, dateTitle, SessionError, syncOf } from './core.js'; import { postJSON, refusalText, reasonText } from './core-gates.js'; import { submitButton, field, fillKeyed } from './molecule-actions.js'; @@ -26,6 +26,7 @@ const FINDINGS_MAX_LIST = 50; const FINDINGS_MAX_FILES = 200; const FINDINGS_MAX_INCLUDES = 50; const FINDINGS_MAX_REASON = 500; +const FINDINGS_BODY_SHORT = 280; // a longer or multi-line body starts collapsed const FINDINGS_SEVERITIES = [['high', 'High'], ['medium', 'Medium'], ['low', 'Low'], ['info', 'Info']]; const FINDINGS_ROUND_STATUS = { complete: 'complete', pending: 'pending', error: 'failed' }; const FINDINGS_PENDING_TEXT = { @@ -37,12 +38,15 @@ const FINDINGS_PENDING_TEXT = { }; // fx is the panel's state, for the one open Molecule. -const fx = { id: null, token: 0, loading: false, view: null, readFailed: false, fetchedAt: 0, want: false, follow: null, pending: false, message: '', announce: false, note: '', proposal: null, checked: new Set(), dismissing: '', reasonError: '', confirming: '', ids: new Map(), chooseTab: null, c: null }; +const fx = { id: null, token: 0, loading: false, view: null, readFailed: false, fetchedAt: 0, want: false, follow: null, pending: false, message: '', announce: false, note: '', proposal: null, checked: new Set(), dismissing: '', reasonError: '', confirming: '', ids: new Map(), chooseTab: null, onView: null, c: null }; const FINDINGS_READ_FAILED = 'could not read the findings; showing the last read'; // mountFindings takes the Molecule view's tab switch, so the panel can select -// the Findings or the Plan tab without importing the view. -export function mountFindings(chooseTab) { fx.chooseTab = chooseTab; } +// the Findings or the Plan tab without importing the view, and a call run +// whenever the tab shows or hides (the roles row names the reviewers). +export function mountFindings(chooseTab, onView) { fx.chooseTab = chooseTab; fx.onView = onView || null; } +// findingsReviewers is Molecule id's declared reviewer plugins, or []. +export function findingsReviewers(id) { return (id && fx.id === id && fx.view && Array.isArray(fx.view.plugins) ? fx.view.plugins : []).filter((n) => typeof n === 'string' && n).slice(0, FINDINGS_MAX_LIST); } // findingsSelect starts the panel for Molecule id, or closes it for null. // want selects the Findings tab once the view says it shows, as for an Inbox @@ -130,6 +134,7 @@ function findingsShowTab(on) { if (tab.hidden !== !on) tab.hidden = !on; if (!on && tab.getAttribute('aria-selected') === 'true' && fx.chooseTab) fx.chooseTab('plan', false); if (on && fx.want && fx.chooseTab) { fx.want = false; fx.chooseTab('findings', false); } + if (fx.onView) fx.onView(); } // ---- Following a job --------------------------------------------------------------- @@ -234,9 +239,11 @@ async function findingsPropose() { const open = findingsOpenRows(fx.view); const include = [...fx.checked].filter((fp) => open.some((f) => f.fingerprint === fp && !f.autoFix)); if (include.length > FINDINGS_MAX_INCLUDES) { findingsSay('Include at most ' + FINDINGS_MAX_INCLUDES + ' findings below the threshold in one fix round.'); return; } - const id = fx.id; + const id = fx.id, kept = new Set(fx.checked); const proposal = await findingsPost('findings/propose', { include: include }); - if (!proposal || fx.id !== id) return; + if (fx.id !== id) return; + // A refused or lost proposal keeps every tick; only a proposal clears them. + if (!proposal) { fx.checked = kept; findingsRender(); return; } fx.proposal = { body: proposal, open: open }; fx.checked = new Set(); await findingsLoad(); @@ -338,7 +345,8 @@ function findingsEnsure(panel) { c.collect = el('button', { type: 'button', class: 'btn btn-secondary', 'aria-describedby': c.collectHelp.id, dataset: { gate: 'findings-collect' }, onclick: findingsCollect }, 'Collect now'); c.openCount = el('p', { class: 'drive-help' }); c.open = el('div'); - c.propose = el('button', { type: 'button', class: 'btn btn-secondary', dataset: { gate: 'findings-propose' }, onclick: findingsPropose }, 'Propose a fix round'); + c.proposeHelp = el('p', { class: 'drive-help', id: uid('mv-propose-help'), hidden: true }); + c.propose = el('button', { type: 'button', class: 'btn btn-secondary', 'aria-describedby': c.proposeHelp.id, dataset: { gate: 'findings-propose' }, onclick: findingsPropose }, 'Propose a fix round'); c.proposal = el('div', { class: 'gate-status' }); const reasonId = uid('mv-dismiss-reason'); // The reason's validation error sits next to it and stays until fixed. @@ -369,7 +377,7 @@ function findingsEnsure(panel) { c.root = el('div', { class: 'mv-sections' }, c.message, c.note, c.stale, c.unreadable, findingsSection('Latest collection', c.rounds, c.collect, c.collectHelp), - findingsSection('Open findings', c.openCount, c.open, c.propose, c.proposal), + findingsSection('Open findings', c.openCount, c.open, c.propose, c.proposeHelp, c.proposal), c.pendingSection, c.pushedSection, c.dismissedBlock); fill(panel, c.root); fx.c = c; @@ -427,15 +435,18 @@ function findingsRenderCollect(c, v) { setText(c.collect, collecting ? 'Collecting…' : 'Collect now'); } +// findingsName is a reviewer's plugin name, never its key ("0:forgecomments"). +function findingsName(r) { return plainText(r.plugin, '') || plainText(r.reviewer, 'Reviewer').replace(/^\d+:/, ''); } +// findingsRoundItem is a reviewer's latest round; a failure shows only itself and its reason. function findingsRoundItem(r) { - const status = FINDINGS_ROUND_STATUS[r.status] || 'pending'; - const when = whenText(r.collectedAt); + const status = FINDINGS_ROUND_STATUS[r.status] || 'pending', when = whenText(r.collectedAt), error = plainText(r.error, ''); + const line = status === 'failed' ? 'Failed: ' + (error || 'no reason was recorded') + '.' : [when ? 'collected ' + when : 'not collected', r.complete === true ? 'round complete' : 'round incomplete'].join(' · '); return el('li', { class: 'file' }, el('span', { class: 'file-badge' + (status === 'complete' ? ' is-new' : '') }, status), el('div', { class: 'file-text' }, - el('code', null, plainText(r.reviewer, 'Reviewer')), - el('p', { class: 'file-reason', title: dateTitle(r.collectedAt) }, [plainText(r.plugin, ''), when ? 'collected ' + when : 'not collected', r.complete === true ? 'round complete' : 'round incomplete'].filter(Boolean).join(' · ')), - r.error ? el('p', { class: 'file-reason' }, plainText(r.error, '')) : null)); + el('code', null, findingsName(r)), + el('p', { class: 'file-reason', title: dateTitle(r.collectedAt) }, line), + status !== 'failed' && error ? el('p', { class: 'file-reason' }, error) : null)); } function findingsRenderOpen(c, v) { @@ -456,7 +467,20 @@ function findingsRenderOpen(c, v) { }); if (typing && c.reason.isConnected && document.activeElement !== c.reason) c.reason.focus({ preventScroll: true }); for (const box of c.open.querySelectorAll('input[type=checkbox]')) box.checked = fx.checked.has(box.dataset.fingerprint); - c.propose.disabled = busy || v.published !== true || open.length === 0; + // Propose shows only with open findings; a merged or closed change request + // (on its receipt or the pull request GitHub sync read) disables it and says why. + const s = syncOf(fx.id), pr = s && s.pr, ended = v.lifecycle === 'merged' || (pr && pr.state === 'MERGED') ? 'merged' : v.lifecycle === 'closed' || (pr && pr.state !== 'OPEN') ? 'closed' : ''; + c.propose.hidden = open.length === 0; + c.propose.disabled = busy || v.published !== true || open.length === 0 || Boolean(ended); + setText(c.proposeHelp, ended ? 'The change request is ' + ended + ', so there is nothing left to propose a fix round for.' : ''); + c.proposeHelp.hidden = !ended || open.length === 0; +} + +// findingsBodyBlock is a finding's body as text, collapsed when long or multi-line. +function findingsBodyBlock(f) { + const body = typeof f.body === 'string' ? f.body.trim() : '', text = body && el('p', { class: 'mv-finding-body' }, body + (f.bodyTruncated === true ? ' …' : '')); + if (!body || (body.length <= FINDINGS_BODY_SHORT && !body.includes('\n'))) return text || null; + return el('details', { class: 'mv-details' }, el('summary', null, 'The reviewer’s explanation'), el('div', { class: 'mv-details-body' }, text)); } function findingsOpenItem(f, locked) { @@ -477,7 +501,8 @@ function findingsOpenItem(f, locked) { el('div', { class: 'file-text' }, el('code', null, where), el('p', { class: 'file-reason' }, plainText(f.title, '(untitled)')), - el('p', { class: 'file-reason' }, plainText(f.reviewer, '')), + findingsBodyBlock(f), + el('p', { class: 'file-reason' }, findingsName(f)), marks.length ? el('p', null, marks) : null, include, dismiss, open ? fx.c.dismissForm : null)); } @@ -567,7 +592,7 @@ function findingsRenderDismissed(c, v) { return el('li', { class: 'file' }, el('span', { class: 'file-badge is-unknown' }, 'dismissed'), el('div', { class: 'file-text' }, - el('p', { title: dateTitle(d.at) }, [plainText(d.reviewer, 'Reviewer'), when ? 'dismissed ' + when : ''].filter(Boolean).join(' · ')), + el('p', { title: dateTitle(d.at) }, [findingsName(d), when ? 'dismissed ' + when : ''].filter(Boolean).join(' · ')), el('p', { class: 'file-reason' }, 'Reason: ' + plainText(d.reason, 'Not recorded')), el('button', { type: 'button', class: 'btn btn-secondary btn-small', disabled: busy, dataset: { gate: 'findings-undismiss-' + d.fingerprint }, onclick: () => findingsUndismiss(d.fingerprint) }, 'Undismiss'))); })); diff --git a/lab/internal/ui/web/js/molecule.js b/lab/internal/ui/web/js/molecule.js index 8837cce..4cce084 100644 --- a/lab/internal/ui/web/js/molecule.js +++ b/lab/internal/ui/web/js/molecule.js @@ -8,7 +8,7 @@ import { $, add, el, fill, state, ctx, newGate, issueLabel, issueURL, laneLabel, import { mv, ensureMoleculeView, renderDecision, renderRoles, loadStats, mergedOf, mergeText } from './molecule-decision.js'; import { renderPlan, copyDigest } from './molecule-plan.js'; import { renderTimeline, mountTimeline } from './molecule-timeline.js'; -import { mountFindings, findingsSelect, findingsOpened, findingsTick } from './molecule-findings.js'; +import { mountFindings, findingsSelect, findingsOpened, findingsTick, findingsReviewers } from './molecule-findings.js'; const TONES = ['needs', 'running', 'blocked', 'merged', 'neutral']; const STEP_STATES = ['done', 'current', 'blocked', 'todo']; @@ -121,7 +121,7 @@ function renderDetail() { renderHeader(d); renderPlan(d); renderDecision(d); - renderRoles(d); + renderRoles(d, findingsReviewers(d.id)); loadStats(d); renderTimeline(d); } @@ -295,7 +295,8 @@ export function mount(root, ctx) { e.preventDefault(); chooseTab(nextTab(e.key, b.dataset.tab), true); }); - mountFindings(chooseTab); + // The roles row names the reviewers the findings view declares once it is read. + mountFindings(chooseTab, () => { const d = state.detail; if (d && d.view) renderRoles(d, findingsReviewers(d.id)); }); $('#mv-timeline').addEventListener('focusout', (e) => { if (mv.timelineDirty && state.detail && !$('#mv-timeline').contains(e.relatedTarget)) renderTimeline(state.detail); });