diff --git a/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md b/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md new file mode 100644 index 0000000000..8282daf6aa --- /dev/null +++ b/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md @@ -0,0 +1 @@ +- Activity Monitor chevrons follow the canonical spec ([#16599](https://github.com/hivecommons/hive/issues/16599)): a row always has 1–2 **active** chevrons (amber fill + counted caption) — the item's stage column, plus a CI/Review track only while it genuinely runs on the current head; every other chevron is an **icon only** (neutral not-yet-run, red failed/changes requested, green passed/approved) with its counts and the backend sentence in the tooltip. CI and Review icons are a tiny ring segmented into `checks_total` / `perspectives_total` steps that fills clockwise (pass green, fail red, newest step pulsing while running). When nothing moves the blocker column is filled in a still stalled style, e.g. `CI 1/11 · waiting on workflow approval` for heads whose workflow runs are `action_required` on GitHub (new `PRCIActivity.WorkflowApproval`, blocker `workflow-approval-required:N`). Review-pending rows never read `Review unknown` / a default `5/5`: with no verdict bundle on the head they are `Review N/5 · in progress` (N = verdicts actually posted) or `· adjudicating`. diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 7c240be68b..da1e0b420a 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:5122-5134`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5133-5145`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 94e5cf04be..e85ee45610 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -202,6 +202,21 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA out.Caption = "CI queued · " + check + " waiting for a runner" out.Detail = "Required check " + check + " has been requested for the PR's current commit but has not started executing yet." case "missing": + if wa := a.WorkflowApproval; wa != nil && wa.Pending > 0 { + // Unreported because GitHub holds the runs behind its + // approve-workflows gate: a person's click, not a push, + // moves it (hivecommons/hive#16599). + out.Blocker = stageTrackerWorkflowApprovalBlocker(wa.Pending) + out.Caption = fmt.Sprintf("CI waiting · %s %s approval on GitHub", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "needs", "need")) + out.Detail = fmt.Sprintf("%s for the PR's current commit %s waiting for a maintainer to approve workflows on GitHub (the gate GitHub applies to dependabot and first-time or fork contributors), so required check %s cannot report until someone approves them.", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "is", "are"), check) + if wa.Actor != "" { + out.Actor = wa.Actor + } + if wa.ObservedAt != nil { + out.Since = wa.ObservedAt + } + break + } out.Caption = "CI waiting · required check " + check + " hasn't reported for this head yet" out.Detail = "Branch protection requires a check named " + check + ", but no check run or commit status with that name exists for the PR's current commit. Usually the workflow that produces it has not been triggered; a push, re-run, or label can start it." case "unknown": @@ -223,6 +238,22 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA return out } +// stageTrackerWorkflowApprovalBlockerPrefix leads the CI blocker when the +// unreported checks are workflow runs waiting on GitHub's approve-workflows +// gate; the strip reads the count after the colon. +const stageTrackerWorkflowApprovalBlockerPrefix = "workflow-approval-required:" + +func stageTrackerWorkflowApprovalBlocker(n int) string { + return fmt.Sprintf("%s%d", stageTrackerWorkflowApprovalBlockerPrefix, n) +} + +func pluralVerb(n int, one, many string) string { + if n == 1 { + return one + } + return many +} + // stageTrackerCountHeadChecks fills the check counts from every check run // observed on the head when the required set is not known: one entry per // check name, red if any run of that name is red, green only if its latest @@ -339,6 +370,50 @@ func stageTrackerCountPerspectives(out *StageTrackerActivity, pr github.PullRequ } } +// stageTrackerReviewPendingState resolves the Review track for a PR the +// stage itself says is under review (050) when no verdict settled it: the +// swarm is in progress, so the track is "reviewing" (active) with the +// count of perspectives that posted for the current head — never +// "unknown", which left review-pending rows with no lit chevron +// (hivecommons/hive#16599). Without a head bundle or aggregate no +// perspective has posted: done is 0, whatever earlier rounds left behind. +func stageTrackerReviewPendingState(out *StageTrackerActivity, stage int, stageSince *time.Time) { + if out == nil || out.State != "unknown" || stage != trackerNumberReviewPending { + return + } + bundleSeen := strings.Contains(out.Source, "verified-review-bundle") + if !bundleSeen { + out.PerspectivesDone = 0 + } + total := out.PerspectivesTotal + done := out.PerspectivesDone + if total > 0 && done >= total && bundleSeen { + out.State = "adjudicating" + out.Caption = fmt.Sprintf("Review %d/%d · verdicts in · aggregating", done, total) + out.Detail = "Every perspective has posted a verdict for the PR's current commit; hive is combining them into the review decision." + } else { + out.State = "reviewing" + out.Caption = fmt.Sprintf("Review %d/%d · in progress", done, total) + out.Detail = fmt.Sprintf("The PR is at review pending: %d of %s have posted a verdict for the PR's current commit; the rest are still reviewing or waiting for a reviewer.", done, plural(total, "perspective")) + } + out.Active = true + // The stage label is the observation; its time is when the label + // landed (stable across rebuilds, so the payload ETag does not move). + if out.ObservedAt == nil && stageSince != nil { + at := *stageSince + out.ObservedAt = &at + } + if out.Since == nil && stageSince != nil { + at := *stageSince + out.Since = &at + } + if out.Source == "" || out.Source == "unavailable" { + out.Source = "stage-review-pending" + } else { + out.Source += "+stage-review-pending" + } +} + func trackerHeadMatches(repo string, number int, head, observedRepo string, observedNumber int, observedHead string) bool { return number == observedNumber && head != "" && strings.EqualFold(head, observedHead) && strings.EqualFold(repo, observedRepo) } diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index a2ee508b03..41ca00b281 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -22,7 +22,14 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => ``); +function constLine(source, name) { + const match = source.match(new RegExp('const ' + name + ' = [^\\n]*;')); + assert.ok(match, name); + return match[0]; +} +const trackConsts = ['STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER', 'STAGE_TRACKER_WORKFLOW_APPROVAL_TIP', 'STAGE_TRACKER_RING_SEGMENT_GAP_MAX', 'STAGE_TRACKER_RING_RADIUS', 'STAGE_TRACKER_RING_GAP_DEG'].map(name => constLine(strip, name)).join('\n'); +const trackFns = ['stageTrackerTrackLead', 'stageTrackerWaitingOnPerson', 'stageTrackerTrackRunning', 'stageTrackerWorkflowApprovalPending', 'stageTrackerRingSvg', 'stageTrackerStalledTrack', 'stageTrackerQueueAheadWord', 'stageTrackerStageTrack', 'stageTrackerHiveOwnsRepair', 'stageTrackerTrackWord', 'stageTrackerActivityTrackHtml'].map(name => fn(strip, name)).join('\n'); +const track = new Function('esc', 'stageTrackerIcon', trackConsts + '\n' + trackFns + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => ``); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -116,7 +123,7 @@ function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } function stageTrackerIcon(n) { return ''; } -` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStageTrack') + fn(strip, 'stageTrackerStalledTrack') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); const renderStrip = makeStripRenderer(); function physicalTracks(item) { @@ -475,12 +482,17 @@ test('Hive #16434 shape: missing current-head CI and review stay unknown but vis review_activity: { head: 'head', state: 'unknown', caption: 'Review unknown · current-head evidence unavailable', source: 'unavailable' }, })); for (const cell of [cells.ci, cells.review]) { - assert.match(cell, /ham-activity-track pending ham-current/, 'absent evidence in the current phase is pending: words, no amber (#16540)'); assert.match(cell, /data-activity-state="unknown"/); assert.match(cell, /data-display-state="unknown"/); assert.doesNotMatch(cell, /data-motion=|ham-activity-track done/); } - assert.match(cells.ci, /CI \?\/\? · no checks reported yet]*><\/svg><\/span>/); @@ -510,12 +526,13 @@ test('current phase, running activity, failure and successful completion are ind ['failing', 'CI failing · "build" red', false, 'failing'], ['running', 'CI running · 1/2 checks done', true, 'active'], ['passing', 'CI green · all 2 required checks passed', false, 'done'], - ['skipped', 'CI skipped · check "build" skipped', false, 'pending'], + ['skipped', 'CI skipped · check "build" skipped', false, 'todo'], ]) { const cells = physicalTracks(livePR({ ci_activity: activity(state, caption, running) })); - assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current'), state + ' → ' + cls); + assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current'), state + ' → ' + cls + ': ' + cells.ci); assert.equal(cells.ci.includes('data-motion="active"'), running); - assert.match(cells.review, /pending ham-current[^]*data-activity-state="unknown"/); + // The stage's own track (review, 050) is active with words (#16599). + assert.match(cells.review, /active ham-current[^]*data-activity-state="unknown"/); } const admitted = physicalTracks(livePR({ stage: 80, ci_activity: activity('passing', 'CI green · all 2 required checks passed'), review_activity: activity('approved', 'Review approved') })); assert.doesNotMatch(admitted.ci + admitted.review, /ham-current|aria-current/); @@ -538,7 +555,8 @@ test('old-head or stale observations cannot fabricate running/completion, but do } if (mode === 'old-head') { assert.match(cells.review, /data-activity-state="unknown"/); - assert.match(cells.ci, /pending ham-current[^]*CI \?\/\? · no checks reported yet([^]*?)]*>/g, ''), kind === 'ci' ? 'CI ?/? · no checks reported yet' : 'Review · swarm requested', 'the count words ride beside the glyph, never a bare icon (#16484)'); + // #16599: at 050 the Review column is the stage's own track and carries + // its words; the inactive CI column is its glyph alone, words in the tooltip. + assert.equal(content.replace(/<[^>]*>/g, ''), kind === 'ci' ? '' : 'Review · queued', 'words ride only on the active chevron (#16599)'); + if (kind === 'ci') assert.match(rendered, /aria-label="[^"]*CI: CI \?\/\? · no checks reported yet · /, 'the inactive count words move to the tooltip'); assert.match(rendered, /role="tooltip">[^]*full precise reason/, 'the precise backend caption stays in the tooltip'); assert.match(content, /aria-label="Open current-head/); assert.match(rendered, /class="ham-chevron-info config-info" tabindex="0"/); @@ -653,7 +674,7 @@ const STAGE_TRACKER_MOTION_ACTIVE = 'active', STAGE_TRACKER_MOTION_STATIC = 'sta function stageTrackerSentinelInLane() { return false; } function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } -` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + ` +` + trackConsts + '\n' + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerWorkflowApprovalPending') + fn(strip, 'stageTrackerRingSvg') + fn(strip, 'stageTrackerStageTrack') + fn(strip, 'stageTrackerStalledTrack') + fn(strip, 'stageTrackerQueueAheadWord') + ` function stageTrackerMotion() { return 'active'; } function stageTrackerIcon(n, cls) { return ''; } ` + anchor + fn(row, 'stageTrackerSegments') + fn(strip, 'stageTrackerActivityTrackHtml') + fn(strip, 'stageTrackerStripItems'); @@ -690,9 +711,9 @@ test('stale activity is visibly unknown in the tooltip, never pulses, and still assert.match(html, /activity unknown · last observed reviewing/); assert.doesNotMatch(html, /data-motion/); assert.match(html, /data-display-state="unknown"/); - assert.match(html, /ham-activity-track active"[^]*ham-chevron-copy ham-track-state">]*><\/svg>Review 1\/5 · reviewer reviewingReview 1\/5 · reviewer reviewing]*><\/svg><\/span>/, 'an approval of this head stays done when stale: glyph alone, count words in the tooltip'); + assert.match(track(item, 'review', {}, false, now + 300000), /ham-activity-track done"[^]*Review: Review 5\/5 approved · [^]*ham-track-verdict"><\/span>/, 'an approval of this head stays done when stale: glyph alone, count words in the tooltip'); }); test('current-head evidence links are accessible and never retained across a new head', () => { @@ -745,7 +766,7 @@ test('the backend detail sentence rides in the track tooltip, not on the chevron }); test('#16484: count grammar — CI passed/total and Review done/total across every state', () => { - const word = new Function(fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + ';return stageTrackerTrackWord;')(); + const word = new Function(trackConsts + '\n' + fn(strip, 'stageTrackerWorkflowApprovalPending') + fn(strip, 'stageTrackerQueueAheadWord') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + ';return stageTrackerTrackWord;')(); const ci = (state, extra = {}) => word({ head: 'h', ci_activity: { head: 'h', state, ...extra } }, 'ci', true); assert.equal(ci('passing', { checks_passed: 14, checks_total: 14 }), 'CI 14/14 passed'); assert.equal(ci('failing', { checks_passed: 11, checks_total: 14, checks_failed: 1, checks_failing: ['lint'] }), 'CI 11/14 · 1 failing (lint)'); @@ -775,11 +796,12 @@ test('#16484: count grammar — CI passed/total and Review done/total across eve for (const q of ['@clubanderson', 'ping @clubanderson, please decide.', 'ok @ClubAnderson?']) assert.equal(review('human_decision', {}, { decision_needed: { question: q } }), 'Review 3/5 · needs your sign-off', 'the viewer handle ends at punctuation or the end: ' + q); } finally { delete globalThis.window; } assert.equal(review('reviewing', { actor: 'reviewer-2' }), 'Review 3/5 · reviewer-2 reviewing'); - assert.equal(review('adjudicating', { actor: 'adjudicator' }), 'Review 3/5 · adjudicator reviewing'); + assert.equal(review('adjudicating', { actor: 'adjudicator' }), 'Review 3/5 · adjudicator adjudicating'); assert.equal(review('assigned', { actor: 'reviewer' }), 'Review 3/5 · reviewer queued'); assert.equal(review('assigned'), 'Review 3/5 · queued'); - assert.equal(review('unassigned', { perspectives_done: 0 }), 'Review 0/5 · swarm requested'); - assert.equal(review('unknown', { perspectives_done: 0 }), 'Review 0/5 · swarm requested'); + assert.equal(review('unassigned', { perspectives_done: 0 }), 'Review 0/5 · queued'); + assert.equal(review('unassigned', { perspectives_done: 0, queue_ahead: 3 }), 'Review 0/5 · queued, 3 ahead'); + assert.equal(review('unknown', { perspectives_done: 0 }), 'Review 0/5 · queued'); assert.equal(review('unknown', { perspectives_done: 0 }, { push: { state: 'pushed', sha: 'h', next: 're-review' } }), 'Review 0/5 · re-review pending (new head)'); assert.equal(review('unknown'), 'Review 3/5 · perspectives', 'partial verdicts with no aggregate verdict yet'); assert.equal(word({ head: 'h', review_activity: { head: 'h', state: 'approved' } }, 'review', true), 'Review approved', 'older servers without counts'); @@ -797,21 +819,30 @@ test('#16484: the three screenshot rows — both tracks lit with counts, swarm r ci_activity: fresh('running', { checks_passed: 9, checks_total: 14, active: true }), review_activity: fresh('unknown', { perspectives_done: 0, perspectives_total: 5 }) })); assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 9/14 · running'); assert.match(cells.ci, /data-motion="active"/); - assert.equal(cls(cells.review), 'pending', 'a pending re-review is words without motion (#16540)'); assert.equal(text(cells.review), 'Review 0/5 · re-review pending (new head)'); + // #16599: the pending re-review is not in motion and not the stage's own + // track (070) → glyph alone, its words in the tooltip. + assert.equal(cls(cells.review), 'todo', 'a pending re-review is an inactive glyph (#16599)'); assert.equal(text(cells.review), ''); + assert.match(cells.review, /aria-label="[^"]*Review: Review 0\/5 · re-review pending \(new head\) · /); assert.doesNotMatch(cells.review, /data-motion/); assert.match(cells.review, /hive is waiting on CI for new head d3c0824/, 'the tooltip still says which track leads'); // #16491: review swarm requested, no bundle yet; CI shows its count. cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, ci_activity: fresh('running', { checks_passed: 2, checks_total: 14 }), review_activity: fresh('unassigned', { perspectives_done: 0, perspectives_total: 5, blocker: 'no reviewer free' }) })); - assert.equal(cls(cells.review), 'pending'); assert.equal(text(cells.review), 'Review 0/5 · swarm requested'); + // #16599: at 050 the Review column is the stage's own track → active with + // words even while only queued; CI runs beside it (two lit). + assert.equal(cls(cells.review), 'active'); assert.equal(text(cells.review), 'Review 0/5 · queued'); + assert.doesNotMatch(cells.review, /data-motion/, 'queued is lit but still'); assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 2/14 · running'); // #16268: CI failed native-queue-policy, review approved, held. cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, modifiers: ['hold'], hold: { by: 'hanthor', pill: 'Held by @hanthor' }, ci_activity: fresh('failing', { checks_passed: 13, checks_total: 14, checks_failed: 1, checks_failing: ['native-queue-policy'], blocker: 'native-queue-policy' }), review_activity: fresh('approved', { perspectives_done: 5, perspectives_total: 5 }) })); - // Settled verdicts are the glyph alone; the count words ride in the tooltip. + // Nothing runs and the row sits in the CI/Review column, so the failing + // CI is the stalled blocker: lit still (amber-muted), words on (#16599); + // the settled approval is the glyph alone, its count words in the tooltip. const tip = cell => cell.match(/ aria-label="([^"]*)"/)[1]; - assert.equal(cls(cells.ci), 'failing'); assert.equal(text(cells.ci), ''); assert.match(cells.ci, /data-verdict="fail"/); + assert.equal(cls(cells.ci), 'active'); assert.match(cells.ci, /ham-activity-track active ham-stalled/); assert.doesNotMatch(cells.ci, /data-motion/); + assert.equal(text(cells.ci), 'CI 13/14 · 1 failing (native-queue-policy)'); assert.match(cells.ci, /data-verdict="fail"/); assert.match(tip(cells.ci), /^(?:Current pipeline phase · )?CI: CI 13\/14 · 1 failing \(native-queue-policy\) · /); assert.equal(cls(cells.review), 'done'); assert.equal(text(cells.review), ''); assert.match(cells.review, /data-verdict="pass"/); assert.match(tip(cells.review), /^(?:Current pipeline phase · )?Review: Review 5\/5 approved · /); diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index efe9cbee22..192e0a0146 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -474,6 +474,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } it.ReviewActivity = stageTrackerReviewActivity(activityPR, bundle, currentAggregate, dispatchState, status, now) stageTrackerCountPerspectives(it.ReviewActivity, activityPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) + stageTrackerReviewPendingState(it.ReviewActivity, it.Stage, it.StageSince) stageTrackerLeadApproveForSignOff(&it) if stageTrackerClaimantStage(it.Kind, it.Stage) { var worker *stageTrackerWorker @@ -549,6 +550,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } it.ReviewActivity = stageTrackerReviewActivity(currentPR, bundle, currentAggregate, dispatchState, status, now) stageTrackerCountPerspectives(it.ReviewActivity, currentPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) + stageTrackerReviewPendingState(it.ReviewActivity, it.Stage, it.StageSince) } activityItem.CIActivity, activityItem.ReviewActivity = it.CIActivity, it.ReviewActivity stageTrackerApplyCodeActivity(&activityItem, dispatchState, status, now) diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index ebcc249adc..4303ddbc9a 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -1,7 +1,9 @@ package dashboard import ( + "os" "os/exec" + "path/filepath" "strings" "testing" ) @@ -695,7 +697,13 @@ assert.deepStrictEqual(animated, [[claimed, review, 'wash'], [review, claimed, ' // a re-render after clicks picks up where the preview left off assert.strictEqual(activeShort(stageTrackerMotionSectionHtml('wash', stages)), 'CI + Review'); ` - cmd := exec.Command(node, "-e", script) + // The lifted strip exceeds Linux's single-argument limit, so the script + // goes through a file rather than -e. + path := filepath.Join(t.TempDir(), "motion_preview_sample.js") + if err := os.WriteFile(path, []byte(script), 0o600); err != nil { + t.Fatal(err) + } + cmd := exec.Command(node, path) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("node motion preview sample fixture failed: %v\n%s", err, out) } diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js index 1a914781e8..9775682398 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -27,7 +27,14 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => ``); +function constLine(source, name) { + const match = source.match(new RegExp('const ' + name + ' = [^\\n]*;')); + assert.ok(match, name); + return match[0]; +} +const trackConsts = ['STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER', 'STAGE_TRACKER_WORKFLOW_APPROVAL_TIP', 'STAGE_TRACKER_RING_SEGMENT_GAP_MAX', 'STAGE_TRACKER_RING_RADIUS', 'STAGE_TRACKER_RING_GAP_DEG'].map(name => constLine(strip, name)).join('\n'); +const trackFns = ['stageTrackerTrackLead', 'stageTrackerWaitingOnPerson', 'stageTrackerTrackRunning', 'stageTrackerWorkflowApprovalPending', 'stageTrackerRingSvg', 'stageTrackerStalledTrack', 'stageTrackerQueueAheadWord', 'stageTrackerStageTrack', 'stageTrackerHiveOwnsRepair', 'stageTrackerTrackWord', 'stageTrackerActivityTrackHtml'].map(name => fn(strip, name)).join('\n'); +const track = new Function('esc', 'stageTrackerIcon', trackConsts + '\n' + trackFns + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => ``); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const segments = new Function('stageTrackerAnchor', globals + ` const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; @@ -44,7 +51,7 @@ function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } function stageTrackerIcon(n) { return ''; } -` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track); +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStageTrack') + fn(strip, 'stageTrackerStalledTrack') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track); const stages = [{ number: 70, branch_from: 50 }, { number: 71, branch_from: 50 }, { number: 72, branch_from: 50 }]; const now = Date.parse('2026-11-04T02:45:00Z'); @@ -111,23 +118,24 @@ test('adopted row: a complete review verdict is done-style, and a human-decision const review = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: decision }))[5]; assert.match(review, /class="ham-seg ham-activity-track done decided"/, 'done-style, muted: not the active fill'); assert.doesNotMatch(review, /ham-activity-track active|data-motion="active"/); - assert.match(review, /Review 5\/5 · changes requested]*data-verdict="fail"/); assert.match(changes, /Review: Review 5\/5 · changes requested · /); - assert.match(changes, /ham-track-verdict">]*><\/svg><\/span>/); + assert.match(changes, /ham-track-verdict"><\/span>/); const approved = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'approved' } }))[5]; assert.match(approved, /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"/); assert.match(approved, /Review: Review 5\/5 approved · /); - assert.match(approved, /ham-track-verdict">]*><\/svg><\/span>/); + assert.match(approved, /ham-track-verdict"><\/span>/); const ci = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: decision }))[4]; assert.match(ci, /class="ham-seg ham-activity-track done"/, '11/11 passed is done-style'); }); @@ -157,8 +165,11 @@ test('#16509 row: adopted, CI 7/11 unreported, review 5/5 decided → one amber review_activity: { head: 'abc1234def', state: 'human_decision', caption: 'Review findings · human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }); const c = cells(item); assert.match(c[3], /class="ham-seg active detoured"/, 'the stage chevron is the one lit chevron'); - assert.match(c[4], /class="ham-seg ham-activity-track pending"/, 'unreported checks are not motion'); - assert.match(c[4], /CI 7\/11 · test not reported]*><\/svg><\/span>/); + assert.match(c[4], /class="ham-seg ham-activity-track todo"[^>]*title="CI: CI 7\/11 · test not reported · /); + assert.doesNotMatch(c[4], /test not reported<\/span>/); assert.equal(litCount(c.join('')), 1); // Even a queued check does not light CI while the row waits on a person. const queued = cells(redPR({ stage: 71, display_column: 30, author: 'hanthor', author_kind: 'human', code_activity: owner, ci_activity: { ...ci, state: 'queued' }, review_activity: approved })); - assert.match(queued[4], /class="ham-seg ham-activity-track pending"/); + assert.match(queued[4], /class="ham-seg ham-activity-track todo"/); assert.equal(litCount(queued.join('')), 1); }); @@ -203,14 +215,17 @@ test('#16456 row: PR in progress with changes requested → the stage chevron is ci_activity: { head: 'abc1234def', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, review_activity: { head: 'abc1234def', state: 'changes_requested', caption: 'Review findings', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: red } })); assert.match(c[3], /class="ham-seg active ham-remediation-unassigned detoured"/); - assert.match(c[4], /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"[^]*CI: CI 11\/11 passed · [^]*ham-track-verdict">]*><\/svg><\/span>/); - assert.match(c[5], /class="ham-seg ham-activity-track failing"[^>]*data-verdict="fail"[^]*Review: Review 5\/5 · changes requested · [^]*ham-track-verdict">]*><\/svg><\/span>/); + assert.match(c[4], /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"[^]*CI: CI 11\/11 passed · [^]*ham-track-verdict"><\/span>/); + assert.match(c[4], /ham-ring ham-ring-pass[^>]*data-ring-done="11"/, 'the pass ring is the icon'); + assert.match(c[5], /class="ham-seg ham-activity-track failing"[^>]*data-verdict="fail"[^]*Review: Review 5\/5 · changes requested · [^]*ham-track-verdict"><\/span>/); + assert.match(c[5], /ham-ring ham-ring-fail/, 'the finding ring is red'); assert.equal(litCount(c.join('')), 1, 'done / failing tracks are text-colour variants, not fills'); }); -test('#16539 shape: a queued swarm reads 0/5, pending, not filled', () => { +test('#16539 shape: a queued swarm reads 0/5 and, as the stage\'s own track, is lit still (#16599)', () => { const c = cells(redPR({ display_column: 50, stage: 50, review_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Review queued · unassigned', blocker: 'no-free-reviewer', perspectives_done: 0, perspectives_total: 5, source: 'review-dispatch-wait', observed_at: seen } })); - assert.match(c[5], /class="ham-seg ham-activity-track pending ham-current"[^]*Review 0\/5 · swarm requested (s.match(re) || []).length; +const noColour = (s) => assert.ok(!/#[0-9a-f]{3,8}\b|rgb\(|stroke="(?!none)|fill="(?!none)/i.test(s), 'raw colour in ring: ' + s); +// queued: 0/5 done, nothing pulses, five muted steps +let r = stageTrackerRingSvg(0, 5, 0, 'unassigned'); +noColour(r); +assert.ok(r.startsWith(' { if ((it.modifiers || []).includes('needs-rebase // the stage chevron's active fill (a settled-current one is not amber) or a // CI / Review track in the active class. Checked on every fixture rendered. const litChevrons = (html) => (html.match(/class="ham-seg active(?! [^"]*ham-settled-current)|class="ham-seg ham-activity-track active\b/g) || []).length; -const atMostTwoLit = (item, row) => row.split('aria-label="Pipeline progress"').slice(1).forEach((s, i) => assert.ok(litChevrons(s) <= 2, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' lights ' + litChevrons(s) + ' chevrons: ' + s)); +// hivecommons/hive#16599 (canonical): 1 ≤ active ≤ 2 — the stage column is +// always active (a settled-current one counts as filled), a track only while +// it runs or is the stage's own / stalled track; and words ride ONLY active +// chevrons — an inactive CI / Review track is its icon alone. +const filledChevrons = (html) => litChevrons(html) + (html.match(/class="ham-seg active [^"]*ham-settled-current/g) || []).length; +const trackCopyText = (li) => ((/([\s\S]*?)<\/span>(?:/g, '').replace(/<[^>]+>/g, '').trim(); +const wordsOnlyWhenActive = (item, s) => Array.from(s.matchAll(/
  • /g)).forEach(m => { + const words = trackCopyText(m[0]); + if (/\bactive\b/.test(m[1])) assert.ok(words, 'fixture #' + item.number + ' active track without words: ' + m[0]); + else assert.strictEqual(words, '', 'fixture #' + item.number + ' inactive track carries words: ' + m[0]); +}); +const atMostTwoLit = (item, row) => row.split('aria-label="Pipeline progress"').slice(1).forEach((s, i) => { + assert.ok(litChevrons(s) <= 2, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' lights ' + litChevrons(s) + ' chevrons: ' + s); + if (s.includes('aria-current="step"')) assert.ok(filledChevrons(s) >= 1, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' has no filled chevron: ' + s); + wordsOnlyWhenActive(item, s); +}); const rawRowHtml = stageTrackerRowHtml; stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); const row = rawRowHtml(item, stages, ctx); atMostTwoLit(item, row); return row; }; // A row is a title line, its strip, then zero or more nested PR sub-rows. diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index efee6c4dc9..6797a4091d 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -683,12 +683,12 @@ assert.ok(/[^<]*<\/span>/.test(row) && !/ const review = /
  • ]*>[\s\S]*?<\/li>/.exec(adoptedRow); assert.ok(review, 'review track present: ' + adoptedRow); assert.strictEqual(review[1], 'done decided', 'a finished review back in PR in progress is settled, not amber: ' + review[0]); - assert.ok(review[0].includes('Review 5/5 · changes requested') && !review[0].includes('awaiting human') && !review[0].includes('data-motion='), review[0]); + assert.ok(review[0].includes('Review: Review 5/5 · changes requested · ') && !review[0].includes('awaiting human') && !review[0].includes('data-motion=') && review[0].includes('ham-ring-decided'), 'the verdict rides the tooltip; the inactive track is its ring alone: ' + review[0]); const ci = /
  • ]*>[\s\S]*?Review 5\/5 · needs owner sign-off<\/span>/.test(parkedRow), 'genuinely parked on a person names the sign-off, still not amber: ' + parkedRow); + assert.ok(/
  • ]*title="Review: Review 5\/5 · needs owner sign-off · /.test(parkedRow), 'genuinely parked on a person names the sign-off in the tooltip, still not amber: ' + parkedRow); } // hivecommons/hive#16540 rows. #16509: adopted, CI 7/11 unreported, review // decided → one lit chevron. #16268: waiting for the contributor, CI 7/11 @@ -703,13 +703,13 @@ assert.ok(/[^<]*<\/span>/.test(row) && !/ code_activity: { head: 'f269349', state: 'adopted', caption: 'Adopted by hive · activity', source: 'adoption', observed_at: seen }, ci_activity: unreported, review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings · human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); assert.strictEqual(lit(three), 1, 'adopted + unreported CI + decided review lights one chevron: ' + strip(three)); - assert.ok(/
  • ]*>[\s\S]*?CI 7\/11 · test not reported<\/span>/.test(three), 'unreported checks are pending, not amber: ' + three); + assert.ok(/
  • ]*title="CI: CI 7\/11 · test not reported · /.test(three), 'unreported checks are the neutral icon, words in the tooltip: ' + three); const owner = stageTrackerRowHtml({ repo: 'acme/console', number: 16268, kind: 'pr', stage: 71, display_column: 30, head: 'f269349', author: 'hanthor', author_kind: 'human', code_activity: { head: 'f269349', state: 'waiting_owner', caption: 'Waiting for @hanthor · not observed coding', actor: 'hanthor', source: 'native-author-wait', observed_at: seen }, ci_activity: unreported, review_activity: { head: 'f269349', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); assert.strictEqual(lit(owner), 1, 'with the contributor: only the stage chevron is lit: ' + strip(owner)); assert.ok(/
  • ]*aria-current="step"/.test(owner) && owner.includes('Waiting for @hanthor'), owner); - assert.ok(/data-track="ci"[^>]*>[\s\S]*?CI 7\/11 · test not reported<\/span>/.test(owner) && /
  • ]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict">]*>[\s\S]*?<\/svg><\/span>[\s\S]*?Review: Review 5\/5 approved · /.test(owner), 'an approved review is the glyph alone, its count words in the tooltip: ' + owner); + assert.ok(/
  • ]*title="CI: CI 7\/11 · test not reported · /.test(owner) && /
  • ]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict">]*>[\s\S]*?<\/svg><\/span>[\s\S]*?Review: Review 5\/5 approved · /.test(owner), 'with the contributor both tracks are icons alone, words in the tooltips: ' + owner); const busy = stageTrackerRowHtml({ repo: 'acme/console', number: 16456, kind: 'pr', stage: 70, display_column: 30, head: 'f269349', author: 'hive[bot]', author_kind: 'hive', code_activity: { head: 'f269349', state: 'remediating', caption: 'Remediating · scanner · 4m', actor: 'scanner', active: true, source: 'fix-dispatch', observed_at: seen }, ci_activity: { head: 'f269349', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, @@ -763,6 +763,48 @@ assert.ok(/[^<]*<\/span>/.test(row) && !/ const nested = stageTrackerRowHtml({ repo: 'hivecommons/hive', number: 16500, kind: 'issue', stage: 40, linked_prs: [shape()] }, stages, ctx); assert.ok(nested.includes('Waiting for @clubanderson · rerun shared ci on GitHub'), 'nested PR carries the word: ' + nested); } +// hivecommons/hive#16599 rows (canonical: active = amber + words, inactive = +// icon only). #16567 (dependabot, 050, review approved, 10 workflow runs +// behind GitHub's approve-workflows gate): nothing moves, so the CI column +// is the stalled active track with the person icon and the words "1/11 · +// waiting on workflow approval"; Review is the green ring alone. #427 (050, +// swarm queued, CI passed): Review is the stage's own track, active even +// while queued; CI is the green icon only. CI running + swarm adjudicating +// lights both tracks with words, never a third. +{ + const seen = new Date(now - 60000).toISOString(); + const lit = (html) => litChevrons(strip(html)); + const gated = stageTrackerRowHtml({ repo: 'acme/console', number: 16567, kind: 'pr', stage: 50, display_column: 50, head: 'b9cd4ba', author: 'dependabot[bot]', author_kind: 'bot', + ci_activity: { head: 'b9cd4ba', state: 'missing', caption: 'CI waiting · 10 workflow runs need approval on GitHub', checks_passed: 1, checks_total: 11, blocker: 'workflow-approval-required:10', actor: 'dependabot[bot]', source: 'github-check-runs', observed_at: seen, workflow_approval: { pending: 10 } }, + review_activity: { head: 'b9cd4ba', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(gated), 1, 'the stalled CI column is the one active chevron: ' + strip(gated)); + assert.ok(/
  • ]*data-motion)[^>]*>[\s\S]*?CI 1\/11 · waiting on workflow approval<\/span>]*aria-label="Needs a maintainer to approve the workflow runs on GitHub[^"]*"/.test(gated), 'stalled CI is amber-muted, still, names the wait and wears the person icon: ' + gated); + assert.ok(/]*aria-label="CI: CI 1\/11 · waiting on workflow approval" data-ring-total="11" data-ring-done="1" data-ring-failed="0">/.test(gated), 'the CI glyph is the 11-step ring with one step done: ' + gated); + assert.ok(/
  • ]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict">]*data-ring-done="5"[\s\S]*?<\/svg><\/span>]*data-motion)[^>]*>[\s\S]*?Review 0\/5 · queued<\/span>/.test(queued), 'Review 0/5 · queued is amber and steady: ' + queued); + assert.ok(/
  • ]*data-verdict="pass"[^>]*>[\s\S]*?]*data-ring-done="11"[\s\S]*?<\/svg><\/span>'), ahead); + const progress = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'missing', caption: 'CI waiting', checks_passed: 7, checks_total: 11, blocker: 'test', source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'reviewing', active: true, caption: 'Review 2/5 · in progress', perspectives_done: 2, perspectives_total: 5, source: 'verified-review-bundle+stage-review-pending', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(progress), 1, 'review in progress lights the Review column only: ' + strip(progress)); + assert.ok(/
  • ]*data-motion="active"[^>]*>[\s\S]*?Review 2\/5 · in progress<\/span>/.test(progress), progress); + assert.ok(/
  • ]*>[\s\S]*?]*data-ring-done="7"[\s\S]*?<\/svg><\/span>]*data-ring-total="5" data-ring-done="2"/.test(progress) && (progress.match(/ham-ring-pulse/g) || []).length === 1, 'the review ring pulses its next step: ' + progress); + const both = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'adjudicating', active: true, caption: 'Review 5/5 · verdicts in · aggregating', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(both), 2, 'CI running + adjudicating: both tracks, no third: ' + strip(both)); + assert.ok(both.includes('CI 4/11 · running') && both.includes('Review 5/5 · adjudicating'), both); +} // Merged: the lit cap is the only chevron with hover text. row = stageTrackerRowHtml({ repo: 'acme/console', number: 106, kind: 'pr', stage: 110 }, stages, ctx); assert.ok(/
  • /.test(row) && titled(strip(row)).length === 1, row); diff --git a/src/pkg/dashboard/stage_tracker_workflow_approval_test.go b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go new file mode 100644 index 0000000000..0fbad0e85c --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go @@ -0,0 +1,98 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// A dependabot head whose 10 unreported required checks are workflow runs +// GitHub holds behind its approve-workflows gate reads as waiting on a +// person, not as "hasn't reported" (hivecommons/hive#16599). +func TestStageTrackerCIActivityWorkflowApproval(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + seen := now.Add(-2 * time.Hour) + required := []string{"verify", "build", "lint"} + activity := func(wa *github.PRWorkflowApproval) github.PullRequest { + return github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{ + Head: "head", Source: "github-check-runs", ObservedAt: &now, RequiredKnown: true, Required: required, StatusesKnown: true, + RequiredSource: "protection", + RequiredChecks: []github.PRRequiredCheck{{Name: "verify", AppKnown: true}, {Name: "build", AppKnown: true}, {Name: "lint", AppKnown: true}}, + Checks: []github.PRActivityCheck{{Name: "verify", State: "completed", Conclusion: "success"}}, + WorkflowApproval: wa, + }} + } + for _, tc := range []struct { + name string + wa *github.PRWorkflowApproval + wantBlocker string + wantCaption string + wantActor string + }{ + {"gated", &github.PRWorkflowApproval{Pending: 10, RunIDs: []int64{1}, Actor: "dependabot[bot]", ObservedAt: &seen}, + "workflow-approval-required:10", "CI waiting · 10 workflow runs need approval on GitHub", "dependabot[bot]"}, + {"single gated run", &github.PRWorkflowApproval{Pending: 1}, "workflow-approval-required:1", "CI waiting · 1 workflow run needs approval on GitHub", ""}, + {"no gate", nil, "build", "hasn't reported for this head yet", ""}, + {"empty record", &github.PRWorkflowApproval{}, "build", "hasn't reported for this head yet", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + got := stageTrackerCIActivity(activity(tc.wa), now) + if got.State != "missing" || got.Active { + t.Fatalf("state=%q active=%v", got.State, got.Active) + } + if !strings.HasPrefix(got.Blocker, strings.TrimSuffix(tc.wantBlocker, "build")) || !strings.Contains(got.Caption, tc.wantCaption) { + t.Fatalf("blocker=%q caption=%q", got.Blocker, got.Caption) + } + if got.Actor != tc.wantActor { + t.Fatalf("actor=%q want %q", got.Actor, tc.wantActor) + } + if got.ChecksPassed != 1 || got.ChecksTotal != 3 { + t.Fatalf("counts %d/%d", got.ChecksPassed, got.ChecksTotal) + } + if tc.wa != nil && tc.wa.Pending > 0 { + if !strings.Contains(got.Detail, "approve workflows") { + t.Fatalf("detail=%q", got.Detail) + } + if tc.wa.ObservedAt != nil && (got.Since == nil || !got.Since.Equal(seen)) { + t.Fatalf("since=%v", got.Since) + } + } + }) + } +} + +// A PR at review pending (050) with no settled verdict is under review: +// "reviewing" with the posted-perspective count, never "unknown"; without +// a head bundle nothing has posted (hivecommons/hive#16599). +func TestStageTrackerReviewPendingState(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + in StageTrackerActivity + stage int + wantState, wantCap string + wantDone, wantActive int + }{ + {"no evidence at 050", StageTrackerActivity{State: "unknown", Source: "unavailable", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "reviewing", "Review 0/5 · in progress", 0, 1}, + {"partial bundle at 050", StageTrackerActivity{State: "unknown", Source: "verified-review-bundle", PerspectivesDone: 1, PerspectivesTotal: 5}, 50, "reviewing", "Review 1/5 · in progress", 1, 1}, + {"all posted, no aggregate", StageTrackerActivity{State: "unknown", Source: "verified-review-bundle", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "adjudicating", "Review 5/5 · verdicts in · aggregating", 5, 1}, + {"not at 050", StageTrackerActivity{State: "unknown", Source: "unavailable", PerspectivesDone: 2, PerspectivesTotal: 5}, 30, "unknown", "", 2, 0}, + {"settled verdict untouched", StageTrackerActivity{State: "approved", Caption: "Review approved", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "approved", "Review approved", 5, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + out := tc.in + stageTrackerReviewPendingState(&out, tc.stage, &now) + if out.State != tc.wantState || out.PerspectivesDone != tc.wantDone || out.Active != (tc.wantActive == 1) { + t.Fatalf("got %+v", out) + } + if tc.wantCap != "" && out.Caption != tc.wantCap { + t.Fatalf("caption=%q want %q", out.Caption, tc.wantCap) + } + if tc.wantActive == 1 && (out.ObservedAt == nil || !out.ObservedAt.Equal(now) && tc.in.ObservedAt == nil || !strings.Contains(out.Source, "stage-review-pending")) { + t.Fatalf("observed=%v source=%q", out.ObservedAt, out.Source) + } + }) + } +} diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index b68f720ef5..35f3b1bb75 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -355,7 +355,6 @@ done-style step that keeps its word (stage_tracker_remediation.go). */ .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } .ham-seg.done.ham-fix-pushed { color: var(--green); } - .ham-seg.done.ham-fix-pushed .ham-seg-t::before { content: '✓'; margin-right: var(--sp-1); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } @@ -390,6 +389,31 @@ .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } .ham-seg.active.ham-settled-current::before { display: none; } .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* A row always has one filled chevron (hivecommons/hive#16599). When + nothing moves on a review-pending row and the stage track has + settled, the blocker's track is filled stalled: a still, muted amber + (muted red on a finding), words kept, person icon when a human + action moves it (workflow approval, a sign-off). */ + .ham-seg.ham-activity-track.active.ham-stalled { background: color-mix(in srgb, var(--amber) 55%, var(--panel-strong)); color: var(--text); animation: none; } + .ham-seg.ham-activity-track.active.ham-stalled::before { display: none; } + .ham-seg.ham-activity-track.ham-stalled .ham-actor-ico { margin-left: var(--sp-1); flex: 0 0 auto; } + /* The CI / Review glyph is a ring of steps (checks / perspectives, + hivecommons/hive#16599): filled clockwise from twelve — done in the + track's colour, failed red, the rest the muted track. While the + track runs the next step pulses. Tokens only; the SVG has no colour. */ + .ham-ring { width: 14px; height: 14px; } + .ham-ring .ham-ring-seg, .ham-ring .ham-ring-track { stroke: var(--line-strong); } + .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, currentColor 28%, transparent); } + .ham-ring .ham-ring-done { stroke: var(--green); } + .ham-ring-fail .ham-ring-done { stroke: var(--status-error); } + .ham-ring-live .ham-ring-done { stroke: var(--amber); } + .ham-ring-decided .ham-ring-done { stroke: var(--muted); } + .ham-ring .ham-ring-failed { stroke: var(--status-error); } + .ham-seg.active .ham-ring .ham-ring-done, .ham-seg.active .ham-ring .ham-ring-failed { stroke: var(--surface-0); } + .ham-seg.active .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, var(--surface-0) 35%, transparent); } + .ham-ring .ham-ring-pulse { stroke: currentColor; animation: ham-ring-step 1.2s ease-in-out infinite; } + @keyframes ham-ring-step { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } } + @media (prefers-reduced-motion: reduce) { .ham-ring .ham-ring-pulse { animation: none; opacity: 0.7; } } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } /* A settled verdict is the glyph alone (green passed / approved, red diff --git a/src/pkg/dashboard/static-src/js/tracker-row-strip.js b/src/pkg/dashboard/static-src/js/tracker-row-strip.js index bd577488fd..a57190b1bb 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -64,7 +64,10 @@ case 'running': return count + ' · running' + (failing ? ' · ' + failing : ''); case 'queued': return count + ' · queued' + (failing ? ' · ' + failing : ''); case 'skipped': return count + ' · ' + (blocker ? blocker + ' skipped' : 'skipped'); - case 'missing': return count + ' · ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + case 'missing': { + if (stageTrackerWorkflowApprovalPending(a) > 0) return count + ' · waiting on workflow approval' + (failing ? ' · ' + failing : ''); + return count + ' · ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + } default: return count + ' · ' + (total ? 'no verdict yet' : 'no checks reported yet'); } } @@ -91,11 +94,101 @@ const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); return count + (mine ? ' · needs your sign-off' : ' · needs owner sign-off'); } - case 'reviewing': case 'adjudicating': return count + ' · ' + (actor ? actor + ' reviewing' : 'reviewing'); - case 'assigned': return count + ' · ' + (actor ? actor + ' queued' : 'queued'); - case 'unassigned': return count + ' · swarm requested'; - default: return count + ' · ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'swarm requested'); + case 'reviewing': return count + ' · ' + (actor ? actor + ' reviewing' : 'in progress'); + case 'adjudicating': return count + ' · ' + (actor ? actor + ' adjudicating' : 'adjudicating'); + case 'assigned': return count + ' · ' + (actor ? actor + ' queued' : 'queued') + stageTrackerQueueAheadWord(a); + case 'unassigned': return count + ' · queued' + stageTrackerQueueAheadWord(a); + default: return count + ' · ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'queued'); + } + } + + // Unreported checks whose workflow runs sit behind GitHub's + // approve-workflows gate (dependabot, forks): the CI blocker reads + // "workflow-approval-required:" (stage_tracker_activity.go). A + // person's click moves them, so the chevron names the wait and wears + // the person icon (hivecommons/hive#16599). + const STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER = 'workflow-approval-required:'; + const STAGE_TRACKER_WORKFLOW_APPROVAL_TIP = 'Needs a maintainer to approve the workflow runs on GitHub before the checks can start'; + function stageTrackerWorkflowApprovalPending(a) { + if (!a) return 0; + const b = String(a.blocker || ''); + if (b.indexOf(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER) === 0) return Math.max(1, Number(b.slice(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER.length)) || 0); + return a.workflow_approval && Number(a.workflow_approval.pending) > 0 ? Number(a.workflow_approval.pending) : 0; + } + + // The tiny ring in a CI / Review chevron: total steps around the + // circle, filled clockwise from twelve — done (green or the state's + // colour) first, then failed (red), the rest the muted track. Steps are + // separated by a gap up to 16 of them, a continuous arc beyond. While + // the track runs the next step pulses. Colours are CSS classes only + // (tracker.css tokens); the SVG carries no raw colour. + const STAGE_TRACKER_RING_SEGMENT_GAP_MAX = 16; + const STAGE_TRACKER_RING_RADIUS = 6; + const STAGE_TRACKER_RING_GAP_DEG = 14; + function stageTrackerRingSvg(done, total, failed, state, label) { + const t = Math.max(0, Math.floor(Number(total) || 0)); + const d = Math.min(t, Math.max(0, Math.floor(Number(done) || 0))); + const f = Math.min(t - d, Math.max(0, Math.floor(Number(failed) || 0))); + const st = String(state || ''); + const running = ['running', 'queued', 'reviewing', 'adjudicating', 'assigned'].includes(st); + const tone = st === 'changes_requested' || st === 'failing' ? 'fail' : st === 'approved' || st === 'passing' ? 'pass' : st === 'human_decision' ? 'decided' : running ? 'live' : 'pass'; + const a11y = label || (t ? `${d} of ${t} done` + (f ? `, ${f} failed` : '') : 'no steps'); + const r = STAGE_TRACKER_RING_RADIUS, c = 8; + const pt = (deg) => { const rad = (deg - 90) * Math.PI / 180; return (c + r * Math.cos(rad)).toFixed(2) + ' ' + (c + r * Math.sin(rad)).toFixed(2); }; + const arc = (from, to, cls) => { + if (to - from >= 360) return ``; + if (to <= from) return ''; + const large = to - from > 180 ? 1 : 0; + return ``; + }; + const open = ``; + if (!t) return open + ``; + const next = Math.min(t - 1, d + f); + const segs = []; + if (t <= STAGE_TRACKER_RING_SEGMENT_GAP_MAX) { + const step = 360 / t; + const gap = t === 1 ? 0 : Math.min(STAGE_TRACKER_RING_GAP_DEG, step / 3); + for (let i = 0; i < t; i++) { + const cls = 'ham-ring-seg ' + (i < d ? 'ham-ring-done' : i < d + f ? 'ham-ring-failed' : 'ham-ring-rest') + (running && i === next ? ' ham-ring-pulse' : ''); + segs.push(arc(i * step + gap / 2, (i + 1) * step - gap / 2, cls)); + } + } else { + const unit = 360 / t; + segs.push(arc(0, 360, 'ham-ring-seg ham-ring-rest ham-ring-track')); + segs.push(arc(0, d * unit, 'ham-ring-seg ham-ring-done')); + segs.push(arc(d * unit, (d + f) * unit, 'ham-ring-seg ham-ring-failed')); + if (running && d + f < t) segs.push(arc(next * unit, (next + 1) * unit, 'ham-ring-seg ham-ring-rest ham-ring-pulse')); } + return open + segs.join('') + ''; + } + + // Which chevron carries a row stuck at column 50 with no track in + // motion: the track that has not settled — CI unless it passed, else + // Review (a pending verdict or a sign-off). A row never shows no + // filled chevron (hivecommons/hive#16599). + function stageTrackerStalledTrack(item) { + const on = kind => { const a = item && item[kind + '_activity']; return a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; }; + if (typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item)) return ''; + if (on('ci') !== 'passing') return 'ci'; + return 'review'; + } + + // ", 3 ahead" when the backend knows the swarm queue position. + function stageTrackerQueueAheadWord(a) { + const n = a && Number(a.queue_ahead); + return Number.isFinite(n) && n > 0 ? ', ' + n + ' ahead' : ''; + } + + // The track that IS the item's current stage: at review pending (050) + // the Review column. It is lit whenever its verdict has not settled — + // queued, in progress, adjudicating alike — because the chevron that + // corresponds to the stage is the lit one (hivecommons/hive#16599, + // reversing #16545's "queued = pending" for the stage column only). + function stageTrackerStageTrack(item) { + if (!item || Number(item.stage) !== 50) return ''; + const a = item.review_activity; + const st = a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; + return ['approved', 'changes_requested', 'human_decision'].includes(st) ? '' : 'review'; } function stageTrackerHiveOwnsRepair(item) { @@ -142,7 +235,7 @@ // field — only a running track is filled (hivecommons/hive#16540); not // started = the empty chevron with the glyph alone. Freshness gates only // the pulse. - function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs, opts) { if (blank) return `
  • `; const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; @@ -161,13 +254,23 @@ const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); const finished = matches && (state === 'passing' || state === 'approved'); const finding = matches && (state === 'failing' || state === 'changes_requested'); - // A complete verdict parked on a person is settled, not in progress: - // done-style, muted, never the amber fill (hivecommons/hive#16509 row). + // A complete verdict parked on a person is settled (muted icon). const settled = matches && state === 'human_decision' && (!known || !a.active); - // At most two chevrons on a row are ever amber: a track is active - // only while it is running; words without motion are pending. + // ACTIVE = filled amber with its words; 1 ≤ active ≤ 2 on a row. A + // track is active while it genuinely runs on the current head, when + // it is the stage's own track (stageTrackerStageTrack), or when it is + // the stalled blocker of a row with nothing in motion (opts.stalled, + // still amber-muted). Everything else is the icon alone — green for + // a pass, red for a finding, neutral when not run or decided — with + // its count words in the tooltip (hivecommons/hive#16599). const running = stageTrackerTrackRunning(item, kind); - const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : running ? 'active' : text ? 'pending' : 'todo'; + const stageTrack = current && typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item) === kind; + const stalled = !!(opts && opts.stalled) && current && !running; + const lit = running || stageTrack || stalled; + const cls = lit ? 'active' + (stalled ? ' ham-stalled' : '') : finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : 'todo'; + const approvalPending = kind === 'ci' && matches ? stageTrackerWorkflowApprovalPending(a) : 0; + const humanAction = approvalPending > 0 ? STAGE_TRACKER_WORKFLOW_APPROVAL_TIP : kind === 'review' && state === 'human_decision' ? 'Needs a person\'s decision' : ''; + const personIco = stalled && humanAction ? stageTrackerIcon('human', 'ham-ico ham-actor-ico', humanAction) : ''; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; @@ -192,15 +295,18 @@ if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - // A settled verdict (CI passed / failed, review approved / changes - // requested) collapses to its glyph alone in the pass / fail colour; - // the count words move into the tooltip. A glance then says whether - // the track went on to the merge queue or to remediation. Pending, - // running, not-reported and sign-off states keep their words. + // Only an active track carries words; an inactive one is its icon + // (ring) in the pass / fail / neutral colour, words in the tooltip. const verdict = finished ? 'pass' : finding ? 'fail' : ''; - const word = verdict ? '' : esc(text); + const word = lit ? esc(text) : ''; const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + // The glyph is the ring of steps (checks / perspectives) once a + // count exists; the flask / eye only while no total is known. + const ringTotal = matches ? Number(a[kind === 'ci' ? 'checks_total' : 'perspectives_total']) || 0 : 0; + const ringDone = matches ? Number(a[kind === 'ci' ? 'checks_passed' : 'perspectives_done']) || 0 : 0; + const ringFailed = kind === 'ci' && matches ? Number(a.checks_failed) || 0 : 0; + const ringLabel = name + ': ' + (text || (ringTotal ? ringDone + '/' + ringTotal : 'no count')); + const icon = ringTotal && typeof stageTrackerRingSvg === 'function' ? stageTrackerRingSvg(ringDone, ringTotal, ringFailed, running ? (kind === 'ci' ? 'running' : 'reviewing') : state, ringLabel) : stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `${icon}${word}` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; @@ -210,8 +316,8 @@ (hold ? ' · ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' · ' + hold.reason : '') : '') + (lead ? ' · hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const copy = `${evidenceLink}`; - return `
  • ${copy}${esc(fullTip)}${decided ? `${decided}` : ''}
  • `; + const copy = `${evidenceLink}${personIco}`; + return `
  • ${copy}${esc(fullTip)}${decided ? `${decided}` : ''}
  • `; } // Chevrons for one item. range bounds the columns the item owns (an @@ -275,8 +381,11 @@ const waitingOnTracks = tracksRunning === 2; if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; + // Column 50 is the row's phase and no track moves: one track is + // filled stalled so the row always shows where it is (#16599). + const stalledTrack = tracksRunning === 0 && segs.some(sg => sg.number === 50 && sg.state === 'active') && typeof stageTrackerStalledTrack === 'function' ? stageTrackerStalledTrack(item) : ''; return segs.map(sg => { - if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs, { stalled: stalledTrack === kind })).join(''); if (sg.number < from || sg.number > to) return ``; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); @@ -366,7 +475,9 @@ } else if (fixPushed) { const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' · '); const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); - inner = `${stageTrackerIcon(sg.number, 'ham-ico')}${esc(code.caption)}${esc(pushedTip)}`; + // Inactive = icon only (hivecommons/hive#16599): the pushed fix is + // the green glyph; its caption rides the tooltip. + inner = `${stageTrackerIcon(sg.number, 'ham-ico')}${esc(pushedTip)}`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `
  • ${inner}
  • `; }).join(''); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index aa350a10b5..066e2b5035 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1692,7 +1692,6 @@ done-style step that keeps its word (stage_tracker_remediation.go). */ .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } .ham-seg.done.ham-fix-pushed { color: var(--green); } - .ham-seg.done.ham-fix-pushed .ham-seg-t::before { content: '✓'; margin-right: var(--sp-1); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } @@ -1727,6 +1726,31 @@ .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } .ham-seg.active.ham-settled-current::before { display: none; } .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* A row always has one filled chevron (hivecommons/hive#16599). When + nothing moves on a review-pending row and the stage track has + settled, the blocker's track is filled stalled: a still, muted amber + (muted red on a finding), words kept, person icon when a human + action moves it (workflow approval, a sign-off). */ + .ham-seg.ham-activity-track.active.ham-stalled { background: color-mix(in srgb, var(--amber) 55%, var(--panel-strong)); color: var(--text); animation: none; } + .ham-seg.ham-activity-track.active.ham-stalled::before { display: none; } + .ham-seg.ham-activity-track.ham-stalled .ham-actor-ico { margin-left: var(--sp-1); flex: 0 0 auto; } + /* The CI / Review glyph is a ring of steps (checks / perspectives, + hivecommons/hive#16599): filled clockwise from twelve — done in the + track's colour, failed red, the rest the muted track. While the + track runs the next step pulses. Tokens only; the SVG has no colour. */ + .ham-ring { width: 14px; height: 14px; } + .ham-ring .ham-ring-seg, .ham-ring .ham-ring-track { stroke: var(--line-strong); } + .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, currentColor 28%, transparent); } + .ham-ring .ham-ring-done { stroke: var(--green); } + .ham-ring-fail .ham-ring-done { stroke: var(--status-error); } + .ham-ring-live .ham-ring-done { stroke: var(--amber); } + .ham-ring-decided .ham-ring-done { stroke: var(--muted); } + .ham-ring .ham-ring-failed { stroke: var(--status-error); } + .ham-seg.active .ham-ring .ham-ring-done, .ham-seg.active .ham-ring .ham-ring-failed { stroke: var(--surface-0); } + .ham-seg.active .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, var(--surface-0) 35%, transparent); } + .ham-ring .ham-ring-pulse { stroke: currentColor; animation: ham-ring-step 1.2s ease-in-out infinite; } + @keyframes ham-ring-step { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } } + @media (prefers-reduced-motion: reduce) { .ham-ring .ham-ring-pulse { animation: none; opacity: 0.7; } } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } /* A settled verdict is the glyph alone (green passed / approved, red @@ -18207,7 +18231,10 @@

    Where to get help

    case 'running': return count + ' · running' + (failing ? ' · ' + failing : ''); case 'queued': return count + ' · queued' + (failing ? ' · ' + failing : ''); case 'skipped': return count + ' · ' + (blocker ? blocker + ' skipped' : 'skipped'); - case 'missing': return count + ' · ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + case 'missing': { + if (stageTrackerWorkflowApprovalPending(a) > 0) return count + ' · waiting on workflow approval' + (failing ? ' · ' + failing : ''); + return count + ' · ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' · ' + failing : ''); + } default: return count + ' · ' + (total ? 'no verdict yet' : 'no checks reported yet'); } } @@ -18234,11 +18261,101 @@

    Where to get help

    const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); return count + (mine ? ' · needs your sign-off' : ' · needs owner sign-off'); } - case 'reviewing': case 'adjudicating': return count + ' · ' + (actor ? actor + ' reviewing' : 'reviewing'); - case 'assigned': return count + ' · ' + (actor ? actor + ' queued' : 'queued'); - case 'unassigned': return count + ' · swarm requested'; - default: return count + ' · ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'swarm requested'); + case 'reviewing': return count + ' · ' + (actor ? actor + ' reviewing' : 'in progress'); + case 'adjudicating': return count + ' · ' + (actor ? actor + ' adjudicating' : 'adjudicating'); + case 'assigned': return count + ' · ' + (actor ? actor + ' queued' : 'queued') + stageTrackerQueueAheadWord(a); + case 'unassigned': return count + ' · queued' + stageTrackerQueueAheadWord(a); + default: return count + ' · ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'queued'); + } + } + + // Unreported checks whose workflow runs sit behind GitHub's + // approve-workflows gate (dependabot, forks): the CI blocker reads + // "workflow-approval-required:" (stage_tracker_activity.go). A + // person's click moves them, so the chevron names the wait and wears + // the person icon (hivecommons/hive#16599). + const STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER = 'workflow-approval-required:'; + const STAGE_TRACKER_WORKFLOW_APPROVAL_TIP = 'Needs a maintainer to approve the workflow runs on GitHub before the checks can start'; + function stageTrackerWorkflowApprovalPending(a) { + if (!a) return 0; + const b = String(a.blocker || ''); + if (b.indexOf(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER) === 0) return Math.max(1, Number(b.slice(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER.length)) || 0); + return a.workflow_approval && Number(a.workflow_approval.pending) > 0 ? Number(a.workflow_approval.pending) : 0; + } + + // The tiny ring in a CI / Review chevron: total steps around the + // circle, filled clockwise from twelve — done (green or the state's + // colour) first, then failed (red), the rest the muted track. Steps are + // separated by a gap up to 16 of them, a continuous arc beyond. While + // the track runs the next step pulses. Colours are CSS classes only + // (tracker.css tokens); the SVG carries no raw colour. + const STAGE_TRACKER_RING_SEGMENT_GAP_MAX = 16; + const STAGE_TRACKER_RING_RADIUS = 6; + const STAGE_TRACKER_RING_GAP_DEG = 14; + function stageTrackerRingSvg(done, total, failed, state, label) { + const t = Math.max(0, Math.floor(Number(total) || 0)); + const d = Math.min(t, Math.max(0, Math.floor(Number(done) || 0))); + const f = Math.min(t - d, Math.max(0, Math.floor(Number(failed) || 0))); + const st = String(state || ''); + const running = ['running', 'queued', 'reviewing', 'adjudicating', 'assigned'].includes(st); + const tone = st === 'changes_requested' || st === 'failing' ? 'fail' : st === 'approved' || st === 'passing' ? 'pass' : st === 'human_decision' ? 'decided' : running ? 'live' : 'pass'; + const a11y = label || (t ? `${d} of ${t} done` + (f ? `, ${f} failed` : '') : 'no steps'); + const r = STAGE_TRACKER_RING_RADIUS, c = 8; + const pt = (deg) => { const rad = (deg - 90) * Math.PI / 180; return (c + r * Math.cos(rad)).toFixed(2) + ' ' + (c + r * Math.sin(rad)).toFixed(2); }; + const arc = (from, to, cls) => { + if (to - from >= 360) return ``; + if (to <= from) return ''; + const large = to - from > 180 ? 1 : 0; + return ``; + }; + const open = ``; + if (!t) return open + ``; + const next = Math.min(t - 1, d + f); + const segs = []; + if (t <= STAGE_TRACKER_RING_SEGMENT_GAP_MAX) { + const step = 360 / t; + const gap = t === 1 ? 0 : Math.min(STAGE_TRACKER_RING_GAP_DEG, step / 3); + for (let i = 0; i < t; i++) { + const cls = 'ham-ring-seg ' + (i < d ? 'ham-ring-done' : i < d + f ? 'ham-ring-failed' : 'ham-ring-rest') + (running && i === next ? ' ham-ring-pulse' : ''); + segs.push(arc(i * step + gap / 2, (i + 1) * step - gap / 2, cls)); + } + } else { + const unit = 360 / t; + segs.push(arc(0, 360, 'ham-ring-seg ham-ring-rest ham-ring-track')); + segs.push(arc(0, d * unit, 'ham-ring-seg ham-ring-done')); + segs.push(arc(d * unit, (d + f) * unit, 'ham-ring-seg ham-ring-failed')); + if (running && d + f < t) segs.push(arc(next * unit, (next + 1) * unit, 'ham-ring-seg ham-ring-rest ham-ring-pulse')); } + return open + segs.join('') + ''; + } + + // Which chevron carries a row stuck at column 50 with no track in + // motion: the track that has not settled — CI unless it passed, else + // Review (a pending verdict or a sign-off). A row never shows no + // filled chevron (hivecommons/hive#16599). + function stageTrackerStalledTrack(item) { + const on = kind => { const a = item && item[kind + '_activity']; return a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; }; + if (typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item)) return ''; + if (on('ci') !== 'passing') return 'ci'; + return 'review'; + } + + // ", 3 ahead" when the backend knows the swarm queue position. + function stageTrackerQueueAheadWord(a) { + const n = a && Number(a.queue_ahead); + return Number.isFinite(n) && n > 0 ? ', ' + n + ' ahead' : ''; + } + + // The track that IS the item's current stage: at review pending (050) + // the Review column. It is lit whenever its verdict has not settled — + // queued, in progress, adjudicating alike — because the chevron that + // corresponds to the stage is the lit one (hivecommons/hive#16599, + // reversing #16545's "queued = pending" for the stage column only). + function stageTrackerStageTrack(item) { + if (!item || Number(item.stage) !== 50) return ''; + const a = item.review_activity; + const st = a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; + return ['approved', 'changes_requested', 'human_decision'].includes(st) ? '' : 'review'; } function stageTrackerHiveOwnsRepair(item) { @@ -18285,7 +18402,7 @@

    Where to get help

    // field — only a running track is filled (hivecommons/hive#16540); not // started = the empty chevron with the glyph alone. Freshness gates only // the pulse. - function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs, opts) { if (blank) return ``; const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; @@ -18304,13 +18421,23 @@

    Where to get help

    const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); const finished = matches && (state === 'passing' || state === 'approved'); const finding = matches && (state === 'failing' || state === 'changes_requested'); - // A complete verdict parked on a person is settled, not in progress: - // done-style, muted, never the amber fill (hivecommons/hive#16509 row). + // A complete verdict parked on a person is settled (muted icon). const settled = matches && state === 'human_decision' && (!known || !a.active); - // At most two chevrons on a row are ever amber: a track is active - // only while it is running; words without motion are pending. + // ACTIVE = filled amber with its words; 1 ≤ active ≤ 2 on a row. A + // track is active while it genuinely runs on the current head, when + // it is the stage's own track (stageTrackerStageTrack), or when it is + // the stalled blocker of a row with nothing in motion (opts.stalled, + // still amber-muted). Everything else is the icon alone — green for + // a pass, red for a finding, neutral when not run or decided — with + // its count words in the tooltip (hivecommons/hive#16599). const running = stageTrackerTrackRunning(item, kind); - const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : running ? 'active' : text ? 'pending' : 'todo'; + const stageTrack = current && typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item) === kind; + const stalled = !!(opts && opts.stalled) && current && !running; + const lit = running || stageTrack || stalled; + const cls = lit ? 'active' + (stalled ? ' ham-stalled' : '') : finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : 'todo'; + const approvalPending = kind === 'ci' && matches ? stageTrackerWorkflowApprovalPending(a) : 0; + const humanAction = approvalPending > 0 ? STAGE_TRACKER_WORKFLOW_APPROVAL_TIP : kind === 'review' && state === 'human_decision' ? 'Needs a person\'s decision' : ''; + const personIco = stalled && humanAction ? stageTrackerIcon('human', 'ham-ico ham-actor-ico', humanAction) : ''; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; @@ -18335,15 +18462,18 @@

    Where to get help

    if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - // A settled verdict (CI passed / failed, review approved / changes - // requested) collapses to its glyph alone in the pass / fail colour; - // the count words move into the tooltip. A glance then says whether - // the track went on to the merge queue or to remediation. Pending, - // running, not-reported and sign-off states keep their words. + // Only an active track carries words; an inactive one is its icon + // (ring) in the pass / fail / neutral colour, words in the tooltip. const verdict = finished ? 'pass' : finding ? 'fail' : ''; - const word = verdict ? '' : esc(text); + const word = lit ? esc(text) : ''; const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + // The glyph is the ring of steps (checks / perspectives) once a + // count exists; the flask / eye only while no total is known. + const ringTotal = matches ? Number(a[kind === 'ci' ? 'checks_total' : 'perspectives_total']) || 0 : 0; + const ringDone = matches ? Number(a[kind === 'ci' ? 'checks_passed' : 'perspectives_done']) || 0 : 0; + const ringFailed = kind === 'ci' && matches ? Number(a.checks_failed) || 0 : 0; + const ringLabel = name + ': ' + (text || (ringTotal ? ringDone + '/' + ringTotal : 'no count')); + const icon = ringTotal && typeof stageTrackerRingSvg === 'function' ? stageTrackerRingSvg(ringDone, ringTotal, ringFailed, running ? (kind === 'ci' ? 'running' : 'reviewing') : state, ringLabel) : stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `${icon}${word}` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; @@ -18353,8 +18483,8 @@

    Where to get help

    (hold ? ' · ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' · ' + hold.reason : '') : '') + (lead ? ' · hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const copy = `${evidenceLink}`; - return `
  • ${copy}${esc(fullTip)}${decided ? `${decided}` : ''}
  • `; + const copy = `${evidenceLink}${personIco}`; + return `
  • ${copy}${esc(fullTip)}${decided ? `${decided}` : ''}
  • `; } // Chevrons for one item. range bounds the columns the item owns (an @@ -18418,8 +18548,11 @@

    Where to get help

    const waitingOnTracks = tracksRunning === 2; if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; + // Column 50 is the row's phase and no track moves: one track is + // filled stalled so the row always shows where it is (#16599). + const stalledTrack = tracksRunning === 0 && segs.some(sg => sg.number === 50 && sg.state === 'active') && typeof stageTrackerStalledTrack === 'function' ? stageTrackerStalledTrack(item) : ''; return segs.map(sg => { - if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs, { stalled: stalledTrack === kind })).join(''); if (sg.number < from || sg.number > to) return ``; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); @@ -18509,7 +18642,9 @@

    Where to get help

    } else if (fixPushed) { const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' · '); const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); - inner = `${stageTrackerIcon(sg.number, 'ham-ico')}${esc(code.caption)}${esc(pushedTip)}`; + // Inactive = icon only (hivecommons/hive#16599): the pushed fix is + // the green glyph; its caption rides the tooltip. + inner = `${stageTrackerIcon(sg.number, 'ham-ico')}${esc(pushedTip)}`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `
  • ${inner}
  • `; }).join(''); diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 8469b51124..333f1cdeaa 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -2560,6 +2560,12 @@ func (c *Client) EnrichCIStatus(ctx context.Context, prs []PullRequest) { incidents := map[string]bool{} for i := range prs { reported := c.enrichPRCI(ctx, &prs[i]) + // Unreported checks may be workflow runs waiting on GitHub's + // approve-workflows gate (dependabot, forks); only a pending head + // pays for the extra listing (hivecommons/hive#16599). + if prs[i].CIStatus == "pending" && prs[i].CIActivity != nil { + prs[i].CIActivity.WorkflowApproval = c.workflowRunsAwaitingApproval(ctx, prs[i].Repo, prs[i].HeadSHA) + } if prs[i].CIStatus == "failure" { prs[i].SharedCIIncident = c.openSharedCIIncident(ctx, &prs[i], incidents) } diff --git a/src/pkg/github/pr_ci_activity.go b/src/pkg/github/pr_ci_activity.go index 9ca1ba6200..52ee5be70b 100644 --- a/src/pkg/github/pr_ci_activity.go +++ b/src/pkg/github/pr_ci_activity.go @@ -21,6 +21,9 @@ type PRCIActivity struct { Checks []PRActivityCheck `json:"checks,omitempty"` StatusesKnown bool `json:"statuses_known"` StatusesObservedAt *time.Time `json:"statuses_observed_at,omitempty"` + // WorkflowApproval names workflow runs on this head that GitHub holds + // behind its approve-workflows gate; nil when none were observed. + WorkflowApproval *PRWorkflowApproval `json:"workflow_approval,omitempty"` } type PRActivityCheck struct { diff --git a/src/pkg/github/webhook_ci_evidence.go b/src/pkg/github/webhook_ci_evidence.go index 57913dbb64..576d51c812 100644 --- a/src/pkg/github/webhook_ci_evidence.go +++ b/src/pkg/github/webhook_ci_evidence.go @@ -373,6 +373,11 @@ func cloneCIActivity(a *PRCIActivity) *PRCIActivity { out.Required = append([]string(nil), a.Required...) out.RequiredChecks = append([]PRRequiredCheck(nil), a.RequiredChecks...) out.Checks = append([]PRActivityCheck(nil), a.Checks...) + if a.WorkflowApproval != nil { + wa := *a.WorkflowApproval + wa.RunIDs = append([]int64(nil), a.WorkflowApproval.RunIDs...) + out.WorkflowApproval = &wa + } return &out } @@ -480,6 +485,10 @@ func (c *Client) applyWebhookCIEvidence(event string, p webhookEventPayload, con } repo := p.Repository.FullName sharedWebhookTracker().recordCIEvent() + // Any CI delivery for the head — a workflow_run leaving action_required + // once someone clicked Approve, a check run starting — means the cached + // approval probe may be stale; re-list on the next cycle. + forgetWorkflowApproval(repo, head) out := &WebhookCIEvidence{HeadSHA: head, PRs: append([]int(nil), numbers...)} store := sharedCIEvidence() checks := webhookCIChecks(event, p) diff --git a/src/pkg/github/workflow_approval.go b/src/pkg/github/workflow_approval.go new file mode 100644 index 0000000000..dc23eacf1c --- /dev/null +++ b/src/pkg/github/workflow_approval.go @@ -0,0 +1,130 @@ +package github + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// PRWorkflowApproval records workflow runs on a PR head that GitHub holds +// behind its "approve and run workflows" gate (status action_required). Such +// runs create no check runs, so from the check-run listing alone the required +// checks simply look unreported; this is the evidence that they are in fact +// waiting on a person clicking Approve (hivecommons/hive#16599). +type PRWorkflowApproval struct { + Pending int `json:"pending"` + RunIDs []int64 `json:"run_ids,omitempty"` + Actor string `json:"actor,omitempty"` + ObservedAt *time.Time `json:"observed_at,omitempty"` +} + +// WorkflowApprovalStatus is the workflow-run status GitHub reports while a +// run waits for a maintainer to approve it. +const WorkflowApprovalStatus = "action_required" + +// workflowApprovalCacheTTL bounds the extra workflow-run listing to one call +// per head per window; the cycle calls EnrichCIStatus far more often than a +// human approves workflows. +const workflowApprovalCacheTTL = 90 * time.Second + +type workflowApprovalEntry struct { + at time.Time + val *PRWorkflowApproval +} + +var workflowApprovalCache sync.Map // repo@sha → workflowApprovalEntry + +// workflowApprovalEvictAfter is how long a head's probe stays cached once +// it is no longer refreshed: heads that got pushed over or merged stop +// being probed, and their entries go with the next sweep of the map. +const workflowApprovalEvictAfter = 30 * time.Minute + +var workflowApprovalLastEvict atomic.Int64 // unix seconds + +// evictStaleWorkflowApprovals drops entries older than +// workflowApprovalEvictAfter, at most once per eviction window, so the +// package-global map stays bounded by the heads probed in the last half hour. +func evictStaleWorkflowApprovals(now time.Time) { + last := workflowApprovalLastEvict.Load() + if now.Unix()-last < int64(workflowApprovalEvictAfter/time.Second) { + return + } + if !workflowApprovalLastEvict.CompareAndSwap(last, now.Unix()) { + return + } + workflowApprovalCache.Range(func(key, value any) bool { + if e, ok := value.(workflowApprovalEntry); !ok || now.Sub(e.at) > workflowApprovalEvictAfter { + workflowApprovalCache.Delete(key) + } + return true + }) +} + +// workflowRunsAwaitingApproval lists the head's workflow runs and keeps the +// ones gated on approval. It returns nil when none are, or when the listing +// failed: absence of evidence is not evidence. +func (c *Client) workflowRunsAwaitingApproval(ctx context.Context, repo, sha string) *PRWorkflowApproval { + if c == nil || c.client == nil || strings.TrimSpace(sha) == "" { + return nil + } + key := repo + "@" + sha + evictStaleWorkflowApprovals(time.Now()) + if cached, ok := workflowApprovalCache.Load(key); ok { + if e, ok := cached.(workflowApprovalEntry); ok && time.Since(e.at) < workflowApprovalCacheTTL { + return e.val + } + } + owner, name := c.splitRepo(repo) + runs, _, err := c.client.Actions.ListRepositoryWorkflowRuns(WithRESTCaller(ctx, "hive:workflow_approval"), owner, name, &gh.ListWorkflowRunsOptions{ + HeadSHA: sha, + ListOptions: gh.ListOptions{PerPage: 100}, + }) + if err != nil || runs == nil { + c.logger.Debug("failed to list workflow runs for head", "repo", repo, "sha", sha, "error", err) + return nil + } + val := workflowApprovalFromRuns(runs.WorkflowRuns, time.Now().UTC()) + workflowApprovalCache.Store(key, workflowApprovalEntry{at: time.Now(), val: val}) + return val +} + +// workflowApprovalFromRuns is the pure half: the approval-gated subset of a +// head's workflow runs, or nil when the head has none. +func workflowApprovalFromRuns(runs []*gh.WorkflowRun, now time.Time) *PRWorkflowApproval { + var out *PRWorkflowApproval + for _, run := range runs { + if run == nil { + continue + } + if run.GetStatus() != WorkflowApprovalStatus && run.GetConclusion() != WorkflowApprovalStatus { + continue + } + if out == nil { + at := now.UTC() + out = &PRWorkflowApproval{ObservedAt: &at} + } + out.Pending++ + if id := run.GetID(); id != 0 { + out.RunIDs = append(out.RunIDs, id) + } + if out.Actor == "" { + if actor := run.GetActor().GetLogin(); actor != "" { + out.Actor = actor + } else if actor := run.GetTriggeringActor().GetLogin(); actor != "" { + out.Actor = actor + } + } + } + return out +} + +// forgetWorkflowApproval drops the cached probe for a head so the next +// cycle re-lists: called when a CI webhook for the head arrives (someone +// approved, a run started) and after the hive approves runs itself. +func forgetWorkflowApproval(repo, sha string) { + workflowApprovalCache.Delete(repo + "@" + sha) +} diff --git a/src/pkg/github/workflow_approval_test.go b/src/pkg/github/workflow_approval_test.go new file mode 100644 index 0000000000..a9cacfc97a --- /dev/null +++ b/src/pkg/github/workflow_approval_test.go @@ -0,0 +1,69 @@ +package github + +import ( + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +func TestWorkflowApprovalFromRuns(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + runs := []*gh.WorkflowRun{ + nil, + {ID: gh.Ptr(int64(1)), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("success")}, + {ID: gh.Ptr(int64(2)), Status: gh.Ptr(WorkflowApprovalStatus), Actor: &gh.User{Login: gh.Ptr("dependabot[bot]")}}, + {ID: gh.Ptr(int64(3)), Status: gh.Ptr("completed"), Conclusion: gh.Ptr(WorkflowApprovalStatus)}, + {ID: gh.Ptr(int64(4)), Status: gh.Ptr("in_progress")}, + } + got := workflowApprovalFromRuns(runs, now) + if got == nil { + t.Fatal("expected approval evidence") + } + if got.Pending != 2 || len(got.RunIDs) != 2 || got.RunIDs[0] != 2 || got.RunIDs[1] != 3 { + t.Fatalf("pending=%d ids=%v", got.Pending, got.RunIDs) + } + if got.Actor != "dependabot[bot]" { + t.Fatalf("actor=%q", got.Actor) + } + if got.ObservedAt == nil || !got.ObservedAt.Equal(now) { + t.Fatalf("observed_at=%v", got.ObservedAt) + } + if workflowApprovalFromRuns(runs[:2], now) != nil { + t.Fatal("no gated runs must yield nil, not an empty record") + } +} + +func TestCloneCIActivityCopiesWorkflowApproval(t *testing.T) { + src := &PRCIActivity{Head: "abc", WorkflowApproval: &PRWorkflowApproval{Pending: 1, RunIDs: []int64{7}}} + out := cloneCIActivity(src) + out.WorkflowApproval.RunIDs[0] = 9 + out.WorkflowApproval.Pending = 5 + if src.WorkflowApproval.RunIDs[0] != 7 || src.WorkflowApproval.Pending != 1 { + t.Fatal("clone shares workflow approval with its source") + } +} + +func TestWorkflowApprovalCacheEvictsAndForgets(t *testing.T) { + workflowApprovalCache.Store("org/repo@old", workflowApprovalEntry{at: time.Now().Add(-2 * workflowApprovalEvictAfter)}) + workflowApprovalCache.Store("org/repo@fresh", workflowApprovalEntry{at: time.Now()}) + workflowApprovalLastEvict.Store(0) + evictStaleWorkflowApprovals(time.Now()) + if _, ok := workflowApprovalCache.Load("org/repo@old"); ok { + t.Fatal("stale entry survived eviction") + } + if _, ok := workflowApprovalCache.Load("org/repo@fresh"); !ok { + t.Fatal("fresh entry evicted") + } + // Within the window the sweep is a no-op even for stale entries. + workflowApprovalCache.Store("org/repo@old2", workflowApprovalEntry{at: time.Now().Add(-2 * workflowApprovalEvictAfter)}) + evictStaleWorkflowApprovals(time.Now()) + if _, ok := workflowApprovalCache.Load("org/repo@old2"); !ok { + t.Fatal("eviction ran again inside its window") + } + forgetWorkflowApproval("org/repo", "fresh") + if _, ok := workflowApprovalCache.Load("org/repo@fresh"); ok { + t.Fatal("forget left the entry") + } + workflowApprovalCache.Delete("org/repo@old2") +}