diff --git a/changelog.d/fixed-tracker-close-issue.md b/changelog.d/fixed-tracker-close-issue.md new file mode 100644 index 0000000000..4033ea1d8c --- /dev/null +++ b/changelog.d/fixed-tracker-close-issue.md @@ -0,0 +1 @@ +- Every open issue in the Activity Monitor now offers a permission-checked Close issue action with an in-app confirmation; only the selected issue closes, leaving linked pull requests and other issues unchanged. diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 4a0e08437d..1140ac1386 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -17,7 +17,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_repo_hold.go` | | `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. Rows also carry `rebase_merge: {state: approved|rebasing|ci-pending|merged|failed, actor, base, text, fail_reason, conflict_files[], armed_at}` while a *Rebase, then merge as maintainer* follow-through is live or just settled (persisted in `/data/rebase-merge-followups.json`; `fail_reason: foreign-head` when the head moved after the approval by someone other than the hive, so nothing merged), and `rebase: {attempt, max, exhausted, head, text}` on a conflicting PR the fixer is rebasing under the two-attempt loop guard (`/data/rebase-attempts.json`). | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:342`, `pkg/dashboard/api_repo_hold.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:343`, `pkg/dashboard/api_repo_item_decision.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"close-read"|"close-issue"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants first post a required comment naming the operator (and the superseding PR when `superseded_by` is given); a failed comment prevents closure. `close-superseded` and `close-wontfix` close as **not planned**; `close-read` acknowledges an advisory issue and closes it **as completed**. `close-issue` (`type: "issue"` only) closes the single named open issue **as completed**, at any stage, leaving linked PRs and other issues untouched; it returns 400 for a PR (including one sent as an issue), 404 when the issue is not found, and 409 when already closed. It retains the existing permission and mutation gates, including the paused-repo `status: "refused"` result without writes. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `queue-merge` (*Approve and let hive merge*, the lead action) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` (on the hive's own PR, which the App cannot review, the queue note is a comment and the operator's approval is recorded as `approve` records it — `released` lists `approval-recorded`, `admitted`); hive's merge sweep merges on its next tick once CI is green and the head has soaked, and that recorded operator approval is the one thing that lets the sweep merge an untrusted-author PR (the merge comment names the operator). `merge-now` (*Merge now as maintainer*, secondary) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:343`, `pkg/dashboard/api_repo_item_decision.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park, ladder?: {decision, reason, ruled_out[]}}, notes, error}`; `ladder` is set on contributor-PR decisions and names the rung that decided — `already-fixed` → `mergeable-as-is` → `rebase-then-merge` → `return-to-contributor` → `contributor-offline` — and why each rung above it did not apply); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:346`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:347` | diff --git a/src/docs/dashboard-sections/activity-monitor.md b/src/docs/dashboard-sections/activity-monitor.md index 74c6931d6c..6af87d38a1 100644 --- a/src/docs/dashboard-sections/activity-monitor.md +++ b/src/docs/dashboard-sections/activity-monitor.md @@ -356,7 +356,7 @@ Every issue and PR row (never a column or repo-group header) carries a left gutt #### Did I act on this? (the decision badge) -Every row action submitted from the dashboard — Approve, Give direction, Close as superseded, Close as won't-fix, Let hive decide, Hold / Release hold, Accept triage, Mark needs-human — is written to a server-side ledger (`/data/operator-actions.json`, `operator_actions.go`; newest 20 per item) as `{action, actor, at, note, target, outcome, detail, head_sha, stage}`, so the record survives reloads and shows in every browser. +Every row action submitted from the dashboard — Approve, Give direction, Close as superseded, Close as won't-fix, Close issue, Let hive decide, Hold / Release hold, Accept triage, Mark needs-human — is written to a server-side ledger (`/data/operator-actions.json`, `operator_actions.go`; newest 20 per item) as `{action, actor, at, note, target, outcome, detail, head_sha, stage}`, so the record survives reloads and shows in every browser. The tracker row carries the newest one as `last_operator_action` (+ `operator_action_count`) and `GET /api/repos/{owner}/{repo}/items/{number}` returns the full list. The row then wears a small **history badge** in the cap cell, before the state pills (`.ham-acted`): the clock-with-counter-clockwise-arrow mark the right-most column header also carries (hover: "History — decisions and actions on this item"), with the count of recorded actions beside it — never a ✓, which read as "done/passed" (owner, 2026-10-28). @@ -394,7 +394,7 @@ On a Prow repo where the hive bot is not an approver, Prow has already answered The delegated *Let hive decide* path still posts the comments only — it recommends and never clears a sentinel alert — *Close as superseded by…* (a picker listing the other open PRs in the repo, or type `#458` / `owner/repo#458` / a URL; then an optional comment, then the sweep's labelled close), *Won't fix…* (a comment naming you, then a not-planned close) and *Give direction…* (your text is recorded as `/hive decision ` against the head, so the author agent pushes a new head; only on PRs the hive opened). -For an issue: *Approve direction* (records the same `/hive approve` a maintainer would comment: the parking labels come off, `approved-direction` goes on, the stage engine logs the un-park and a reply comment names you; nothing is merged), *Send back to the hive…* (`/hive decision `), *Close as superseded by…* and *Close as won't-fix…*. A selection mixing parked issues and parked PRs has Decide… greyed; **Hold** or **Release hold** depending on the `hold` chip (the same `…/items/{number}/hold` toggle as the repository cards, and the same permission — owner, or a signed-in user with write access to the repo); **Re-evaluate now** (the hive-wide read-only rescan behind the Overview's refresh — a rescan already running is reported, not duplicated); **Accept triage** (only on an issue the chevron calls *Triage needed* — stage 015, or the `needs-triage` chip on another stage — never on a PR; the one-click form of a maintainer accepting triage on GitHub: adds the reporter-trust triage label, `triage/accepted` by default or the first of `issue_filter.reporter_trust.untrusted_require_labels`, removes the awaiting label `needs-triage` / `reporter_trust.awaiting_label` and a Hive-written `stage/015-triage-needed`; the row re-reads *Actionable* with the 👤 gone at once, the reporter-trust gate admits the issue on its next poll and the stage engine records 015 → 010; same permission as Hold, audited as `repo_item_accept_triage`, a no-op when already accepted); **Mark needs-human…** (hidden once the chip is on; merger or owner role, applies `needs-human` and a marker comment through the review pipeline's send-to-human endpoint); **Open on GitHub**; **Copy link**. +For a parked issue, *Decide…* offers *Approve direction* (records the same `/hive approve` a maintainer would comment: the parking labels come off, `approved-direction` goes on, the stage engine logs the un-park and a reply comment names you; nothing is merged), *Send back to the hive…* (`/hive decision `), *Close as superseded by…* and *Close as won't-fix…*. Separately, **Close issue…** appears on every open issue, whatever its stage, author, claim or hold, including a linked issue reached from a PR-only row's issue menu. Its in-app confirmation names the repository, number and title and accepts an optional comment; an attributed closing note is required. It closes only that exact issue **as completed**, never its covering PR or sibling issues, and cannot fan out over a selection. The same signed-in GitHub user / repository-write permission and mutation gates apply; denied actions are greyed with a reason, and server refusals or errors are surfaced without hiding the issue or reporting it closed. A selection mixing parked issues and parked PRs has Decide… greyed; **Hold** or **Release hold** depending on the `hold` chip (the same `…/items/{number}/hold` toggle as the repository cards, and the same permission — owner, or a signed-in user with write access to the repo); **Re-evaluate now** (the hive-wide read-only rescan behind the Overview's refresh — a rescan already running is reported, not duplicated); **Accept triage** (only on an issue the chevron calls *Triage needed* — stage 015, or the `needs-triage` chip on another stage — never on a PR; the one-click form of a maintainer accepting triage on GitHub: adds the reporter-trust triage label, `triage/accepted` by default or the first of `issue_filter.reporter_trust.untrusted_require_labels`, removes the awaiting label `needs-triage` / `reporter_trust.awaiting_label` and a Hive-written `stage/015-triage-needed`; the row re-reads *Actionable* with the 👤 gone at once, the reporter-trust gate admits the issue on its next poll and the stage engine records 015 → 010; same permission as Hold, audited as `repo_item_accept_triage`, a no-op when already accepted); **Mark needs-human…** (hidden once the chip is on; merger or owner role, applies `needs-human` and a marker comment through the review pipeline's send-to-human endpoint); **Open on GitHub**; **Copy link**. Entries you may not use are greyed with the reason in their tooltip, never hidden. Confirmation and free-text input use the dashboard's own dialogs — no browser prompts. Every action is an existing audited dashboard endpoint (the decision endpoint is `POST /api/repos/{owner}/{repo}/items/{number}/decision` and triage acceptance is `POST /api/repos/{owner}/{repo}/items/{number}/accept-triage`, see [api-reference.md](../api-reference.md)); none of them bypasses the hive's governance or merges anything. @@ -414,7 +414,7 @@ Legend, in the operator's words: **working** (icon turns), **waiting on X** (sti #### Result toasts (`runRowAction`) -Every row action — *Let hive decide*, *Approve*, *Give direction*, *Close as superseded*, *Won't fix*, *Approve direction*, *Send back to the hive*, *Accept triage*, *Hold* / *Release hold*, *Re-evaluate now*, *Mark needs-human* — goes through one SPA helper, `runRowAction(action, row)`, which marks the row acting, sends the request, and renders a toast from the server's shared `result` object (additive on every endpoint's existing response: `{action, target: {repo, kind, number, url}, outcome, next, rule?, applied_at?}`, `action` one of `adopted | approved | recommended | closed | directed | refused | held | released | rescanned | triage-accepted | needs-human | noop-already-applied`). +Every row action — *Let hive decide*, *Approve*, *Give direction*, *Close as superseded*, *Won't fix*, *Close issue*, *Approve direction*, *Send back to the hive*, *Accept triage*, *Hold* / *Release hold*, *Re-evaluate now*, *Mark needs-human* — goes through one SPA helper, `runRowAction(action, row)`, which marks the row acting, sends the request, and renders a toast from the server's shared `result` object (additive on every endpoint's existing response: `{action, target: {repo, kind, number, url}, outcome, next, rule?, applied_at?}`, `action` one of `adopted | approved | recommended | closed | directed | refused | held | released | rescanned | triage-accepted | needs-human | noop-already-applied`). The toast reads, in order, *what happened → on what → what happens next*: a headline naming the clicked row and, when it differs, the target (*Hive decided on acme/console#14938 → PR #14947: adopted (contributor offline)*), the outcome sentence, the ⚠ sentinel line when the head carries one, the *next* line (*The hive rebases and merges it unattended.*), an explicit ✕ and an *Open PR #14947 ↗* link. @@ -426,7 +426,7 @@ Older hives that answer without `result` still get a toast built from the legacy #### Confirmations and "Don't ask again" -Each confirm dialog a row action raises — Approve (including a sentinel-flagged head: *⚠ Sentinel flagged security-relevant changes at 40a959b …*), Let hive decide, Close as superseded / won't-fix, Mark needs-human and the rest — carries a **Don't ask again for this action** box. Ticking it and confirming stores `hive.tracker.confirm.=skip` in this browser's `localStorage` (one key per action id, e.g. `hive.tracker.confirm.decide:delegate`); later clicks on that action run at once. +The skippable confirm dialogs — Approve (including a sentinel-flagged head: *⚠ Sentinel flagged security-relevant changes at 40a959b …*), Let hive decide, Close as superseded / won't-fix, Mark needs-human and the rest — carry a **Don't ask again for this action** box. Ticking it and confirming stores `hive.tracker.confirm.=skip` in this browser's `localStorage` (one key per action id, e.g. `hive.tracker.confirm.decide:delegate`); later clicks on that action run at once. **Close issue** is deliberately not skippable: every attempt confirms the exact repository, issue number and title before posting the optional comment and closing it. Nothing the dialog would have said is lost: the result toast carries the same ⚠ sentinel line (it is per head, so skipping the confirm never skips the warning) and the one-line item summary. Actions that need your text (*Give direction…*, *Send back…*, the superseder picker) always ask. The ⚙ settings dialog's **Confirmations** section lists which actions are skipped and has one **Reset confirmations** button that turns them all back on. diff --git a/src/pkg/dashboard/api_repo_item_close_issue_test.go b/src/pkg/dashboard/api_repo_item_close_issue_test.go new file mode 100644 index 0000000000..893b2a5b44 --- /dev/null +++ b/src/pkg/dashboard/api_repo_item_close_issue_test.go @@ -0,0 +1,87 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +func TestCloseIssueDecisionTargetsOnlySelectedIssue(t *testing.T) { + for _, labels := range [][]string{ + nil, {"stage/045-needs-decision"}, {"stage/085-needs-decision", "needs-human"}, + {"hive/hold", "agent/scanner", "claimed"}, {"tracking", "triage/advisory"}, + } { + t.Run(strings.Join(labels, ","), func(t *testing.T) { + m := &repoItemDecisionMock{issueLabels: labels} + s := newRepoItemDecisionServer(t, m) + w := postRepoItemDecision(t, s, 7, "writer", `{"decision":"close-issue","type":"issue","comment":"Finished independently"}`) + if w.Code != http.StatusOK { + t.Fatalf("close: %d %s", w.Code, w.Body.String()) + } + if len(m.edits) != 1 || m.editPaths[0] != "/repos/testorg/testrepo/issues/7" || + m.edits[0]["state"] != "closed" || m.edits[0]["state_reason"] != issueStateReasonCompleted { + t.Fatalf("must close only selected issue: paths=%v edits=%v", m.editPaths, m.edits) + } + if len(m.comments) != 1 || !strings.Contains(m.comments[0], "completed by @writer") || !strings.Contains(m.comments[0], "Finished independently") { + t.Fatalf("closing attribution: %v", m.comments) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Status != "closed" || resp.Result == nil || resp.Result.Action != rowActionClosed || resp.Result.Target.Kind != "issue" || resp.Result.Target.Number != 7 { + t.Fatalf("result: %+v", resp) + } + if len(m.added) != 0 || len(m.merges) != 0 || len(m.reviews) != 0 { + t.Fatal("issue close must not resolve a PR or move other items") + } + }) + } +} + +func TestCloseIssueDecisionGuardsAndFailures(t *testing.T) { + for _, tc := range []struct { + name, user, body, state string + + number, commentError, editError, want int + + paused bool + }{ + {name: "anonymous", number: 7, want: http.StatusUnauthorized}, + {name: "read-only", user: "reader", number: 7, want: http.StatusForbidden}, + {name: "PR type", user: "writer", number: 8, body: `{"decision":"close-issue","type":"pr"}`, want: http.StatusBadRequest}, + {name: "PR disguised as issue", user: "writer", number: 8, want: http.StatusBadRequest}, + {name: "already closed", user: "writer", number: 7, state: "closed", want: http.StatusConflict}, + {name: "missing issue", user: "writer", number: 404, want: http.StatusNotFound}, + {name: "required attribution refused", user: "writer", number: 7, commentError: http.StatusForbidden, want: http.StatusBadGateway}, + {name: "remote close refused", user: "writer", number: 7, editError: http.StatusForbidden, want: http.StatusBadGateway}, + {name: "remote close unavailable", user: "writer", number: 7, editError: http.StatusServiceUnavailable, want: http.StatusBadGateway}, + {name: "repo paused", user: "writer", number: 7, paused: true, want: http.StatusOK}, + } { + t.Run(tc.name, func(t *testing.T) { + m := &repoItemDecisionMock{issueState: tc.state, commentError: tc.commentError, editError: tc.editError} + s := newRepoItemDecisionServer(t, m) + if tc.paused { + s.deps.Config.Project.PausedRepos = []config.RepoPause{{Repo: "testrepo", Reason: "read only"}} + } + body := tc.body + if body == "" { + body = `{"decision":"close-issue","type":"issue"}` + } + w := postRepoItemDecision(t, s, tc.number, tc.user, body) + if w.Code != tc.want { + t.Fatalf("got %d want %d: %s", w.Code, tc.want, w.Body.String()) + } + if len(m.edits) != 0 || strings.Contains(w.Body.String(), `"status":"closed"`) { + t.Fatalf("failure must not close or report closed: %v %s", m.edits, w.Body.String()) + } + if tc.editError == 0 && len(m.comments) != 0 { + t.Fatalf("guard failure posted a comment: %v", m.comments) + } + if tc.paused && !strings.Contains(w.Body.String(), `"action":"refused"`) { + t.Fatalf("pause must explain refusal: %s", w.Body.String()) + } + }) + } +} diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index be749629da..7729b6cf8d 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -66,6 +66,7 @@ const ( repoItemDecisionDirection = "direction" repoItemDecisionCloseSuperseded = "close-superseded" repoItemDecisionCloseWontFix = "close-wontfix" + repoItemDecisionCloseIssue = "close-issue" // close-read closes an advisory issue (triage/advisory, a dedupe // checklist) as completed once a maintainer has read it // (hivecommons/hive#15381): the row's "Close (read)" action. @@ -284,6 +285,10 @@ func repoItemDecisionResultWith(repoFull string, number int, itemType, decision, out.Action = rowActionClosed out.Outcome = "Closed as read (advisory acknowledged)." out.Next = "Nothing further to do; the row leaves the tracker on its next refresh." + case repoItemDecisionCloseIssue: + out.Action = rowActionClosed + out.Outcome = "Issue closed as completed." + out.Next = "Only this issue was closed; linked pull requests and other issues are unchanged." case repoItemDecisionAdopt: out.Action = rowActionAdopted out.Outcome = "Adoption queued: `" + label + "` applied." @@ -422,10 +427,34 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "decision", event.Decision), "", repoFull, number) jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: "unparked", Label: ghpkg.HumanAckLabel, Result: repoItemDecisionResult(repoFull, number, itemType, decision, comment, "", ghpkg.HumanAckLabel, nil)}) - case repoItemDecisionCloseSuperseded, repoItemDecisionCloseWontFix, repoItemDecisionCloseRead: + case repoItemDecisionCloseSuperseded, repoItemDecisionCloseWontFix, repoItemDecisionCloseRead, repoItemDecisionCloseIssue: verb := "won't fix" stateReason := issueStateReasonNotPlanned supersededBy := "" + if decision == repoItemDecisionCloseIssue { + if itemType != "issue" { + jsonError(w, "close-issue applies to issues only", http.StatusBadRequest) + return + } + issue, resp, err := gh.GoGitHub().Issues.Get(ctx, owner, repoName, number) + if err != nil { + if resp != nil && resp.StatusCode == http.StatusNotFound { + jsonError(w, "issue not found", http.StatusNotFound) + return + } + jsonError(w, err.Error(), http.StatusBadGateway) + return + } + if issue.IsPullRequest() { + jsonError(w, "close-issue applies to issues only", http.StatusBadRequest) + return + } + if issue.GetState() != "open" { + jsonError(w, "issue is already closed", http.StatusConflict) + return + } + verb, stateReason = "completed", issueStateReasonCompleted + } if decision == repoItemDecisionCloseRead { if itemType != "issue" { jsonError(w, "close-read applies to issues", http.StatusBadRequest) @@ -531,7 +560,7 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request) } s.handlePullRequestMergeDecision(ctx, w, repoFull, number, user, decision, comment) default: - jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix, close-read, adopt, reroute, re-author, merge-now or queue-merge", http.StatusBadRequest) + jsonError(w, "unknown decision; want approve, direction, close-superseded, close-wontfix, close-read, close-issue, adopt, reroute, re-author, merge-now or queue-merge", http.StatusBadRequest) } } diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index ee4c6c26a8..13aa600438 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -70,6 +70,12 @@ type repoItemDecisionMock struct { fixedIssueClosedBy int // issueTitle / issueBody shape issue #7 (empty = untitled, no body). issueTitle, issueBody string + // issueState shapes GET /issues/7 (empty means open). + issueState string + // commentError / editError refuse POST /comments or PATCH /issues/N. + commentError, editError int + // editPaths records each PATCH path alongside edits. + editPaths []string } func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { @@ -91,7 +97,11 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { for _, label := range m.issueLabels { labels = append(labels, map[string]string{"name": label}) } - _ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": "open", "title": m.issueTitle, "body": m.issueBody, "labels": labels, "user": map[string]any{"login": "hive[bot]", "type": "Bot"}}) + state := m.issueState + if state == "" { + state = "open" + } + _ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": state, "title": m.issueTitle, "body": m.issueBody, "labels": labels, "user": map[string]any{"login": "hive[bot]", "type": "Bot"}}) case r.Method == http.MethodGet && (strings.HasSuffix(path, "/issues/8") || strings.HasSuffix(path, "/issues/9")): n := 8 if strings.HasSuffix(path, "/issues/9") { @@ -206,6 +216,10 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { } _ = json.NewEncoder(w).Encode(prior) case r.Method == http.MethodPost && strings.HasSuffix(path, "/comments"): + if m.commentError != 0 { + http.Error(w, `{"message":"comment denied"}`, m.commentError) + return + } var c map[string]string _ = json.NewDecoder(r.Body).Decode(&c) m.comments = append(m.comments, c["body"]) @@ -223,9 +237,14 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { m.removed = append(m.removed, path[strings.LastIndex(path, "/")+1:]) _, _ = io.WriteString(w, `{}`) case r.Method == http.MethodPatch && strings.Contains(path, "/issues/"): + if m.editError != 0 { + http.Error(w, `{"message":"close denied"}`, m.editError) + return + } var body map[string]any _ = json.NewDecoder(r.Body).Decode(&body) m.edits = append(m.edits, body) + m.editPaths = append(m.editPaths, path) _, _ = io.WriteString(w, `{}`) default: t.Logf("unexpected GitHub API request: %s %s", r.Method, path) diff --git a/src/pkg/dashboard/operator_actions.go b/src/pkg/dashboard/operator_actions.go index 63211b0d64..f2760da846 100644 --- a/src/pkg/dashboard/operator_actions.go +++ b/src/pkg/dashboard/operator_actions.go @@ -37,6 +37,7 @@ const ( operatorActionCloseSuperseded = "close-superseded" operatorActionWontFix = "wontfix" operatorActionCloseRead = "close-read" + operatorActionCloseIssue = "close-issue" operatorActionLetHiveDecide = "let-hive-decide" operatorActionHold = "hold" operatorActionRelease = "release" @@ -338,6 +339,8 @@ func operatorActionFromBody(endpoint string, body []byte) (operatorActionRequest out.Action = operatorActionWontFix case repoItemDecisionCloseRead: out.Action = operatorActionCloseRead + case repoItemDecisionCloseIssue: + out.Action = operatorActionCloseIssue case repoItemDecisionMergeNow: out.Action = operatorActionMergeNow case repoItemDecisionQueueMerge: @@ -908,7 +911,7 @@ func operatorActionClosedGrace() time.Duration { // operatorClosedActions are the row actions whose applied outcome is a // closed issue or PR. -var operatorClosedActions = []string{operatorActionCloseSuperseded, operatorActionWontFix, operatorActionCloseRead} +var operatorClosedActions = []string{operatorActionCloseSuperseded, operatorActionWontFix, operatorActionCloseRead, operatorActionCloseIssue} // operatorActionClosedItem reports whether the item's newest recorded // action closed it from the dashboard within grace of now: GitHub's list diff --git a/src/pkg/dashboard/operator_actions_test.go b/src/pkg/dashboard/operator_actions_test.go index 486ac3d91b..3dc7c6b5f9 100644 --- a/src/pkg/dashboard/operator_actions_test.go +++ b/src/pkg/dashboard/operator_actions_test.go @@ -480,13 +480,16 @@ func TestStageTrackerDropOperatorClosed(t *testing.T) { {Repo: "o/r", Number: 4, Kind: "issue", LastOperatorAction: act(operatorActionWontFix, operatorActionOutcomeApplied, operatorActionClosedDetail, grace+time.Second)}, {Repo: "o/r", Number: 5, Kind: "issue", LastOperatorAction: act(operatorActionCloseRead, operatorActionOutcomeFailed, "Close refused: repo paused", time.Minute)}, {Repo: "o/r", Number: 6, Kind: "issue", LastOperatorAction: act(operatorActionApprove, operatorActionOutcomeApplied, "unparked", time.Minute)}, + {Repo: "o/r", Number: 7, Kind: "issue", LastOperatorAction: act(operatorActionCloseIssue, operatorActionOutcomeApplied, operatorActionClosedDetail, time.Minute)}, + {Repo: "o/r", Number: 8, Kind: "issue", LastOperatorAction: act(operatorActionCloseIssue, operatorActionOutcomeFailed, "permission denied", time.Minute)}, + {Repo: "o/r", Number: 9, Kind: "pr", LinkedIssues: []StageTrackerLinkedIssue{{Number: 7, State: "open"}}}, } got := stageTrackerDropOperatorClosed(items, now, grace) var nums []int for _, it := range got { nums = append(nums, it.Number) } - want := []int{1, 4, 5, 6} + want := []int{1, 4, 5, 6, 8, 9} if !slices.Equal(nums, want) { t.Fatalf("kept %v, want %v (just-closed rows 2 and 3 must leave; a refused close, an old close and a non-close stay)", nums, want) } diff --git a/src/pkg/dashboard/stage_tracker_accept_triage_test.go b/src/pkg/dashboard/stage_tracker_accept_triage_test.go index 1b3a2b90c4..d4c6fa48d6 100644 --- a/src/pkg/dashboard/stage_tracker_accept_triage_test.go +++ b/src/pkg/dashboard/stage_tracker_accept_triage_test.go @@ -35,7 +35,7 @@ const ctx = { user: true, canHold: true, canHuman: true, login: 'octo', nowMs: N // The primary case: an issue at 015 "Triage needed". const triage = { repo: 'o/r', kind: 'issue', number: 1, title: 'From an untrusted reporter', url: 'https://github.com/o/r/issues/1', stage: 15, modifiers: [] }; let as = stageTrackerRowActions(triage, ctx); -assert.deepStrictEqual(ids(as), ['accept-triage', 'hold', 'retry', 'needs-human', 'open', 'copy'], 'Accept triage heads the menu'); +assert.deepStrictEqual(ids(as), ['accept-triage', 'hold', 'retry', 'needs-human', 'decide:close-issue', 'open', 'copy'], 'Accept triage heads the menu'); const accept = as.find(a => a.id === 'accept-triage'); assert.strictEqual(accept.label, 'Accept triage'); assert.strictEqual(accept.enabled, true); diff --git a/src/pkg/dashboard/stage_tracker_advisory_test.go b/src/pkg/dashboard/stage_tracker_advisory_test.go index b535dbf0c9..9829d7cc12 100644 --- a/src/pkg/dashboard/stage_tracker_advisory_test.go +++ b/src/pkg/dashboard/stage_tracker_advisory_test.go @@ -293,7 +293,7 @@ const ordinary = { repo: 'o/r', number: 2, kind: 'issue', stage: 0, caption: 'No const ids = as => as.map(a => a.id); const ctx = { user: true, canHold: true, canHuman: true }; const as = stageTrackerRowActions(empty, ctx); -assert.deepStrictEqual(ids(as), ['decide:close-read', 'hold', 'retry', 'needs-human', 'open', 'copy'], ids(as).join(',')); +assert.deepStrictEqual(ids(as), ['decide:close-read', 'hold', 'retry', 'needs-human', 'decide:close-issue', 'open', 'copy'], ids(as).join(',')); assert.strictEqual(as[0].label, 'Close now'); assert.ok(as[0].lead && as[0].enabled, JSON.stringify(as[0])); assert.ok(as[0].hint.startsWith('nothing found'), as[0].hint); diff --git a/src/pkg/dashboard/stage_tracker_close_issue_test.go b/src/pkg/dashboard/stage_tracker_close_issue_test.go new file mode 100644 index 0000000000..9710ae7242 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_close_issue_test.go @@ -0,0 +1,127 @@ +package dashboard + +import "testing" + +func TestStageTrackerCloseIssueEveryStageAndExactTarget(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+"\n"+jsFunc(t, html, "stageTrackerLinkedIssueToolsHtml")+` +const ctx = { user: true, canHold: true }; +const issue = { repo: 'hivecommons/dibs', kind: 'issue', number: 527, title: 'Selected issue', url: 'u527' }; +for (let stage = 0; stage <= 100; stage++) { + for (const author_kind of ['human', 'hive', 'clanker']) { + const it = { ...issue, stage, author_kind, mirrored: true, claimant: { login: 'agent' }, modifiers: ['hold', 'needs-human'], + linked_prs: [{ number: 528, stage: 85, modifiers: ['needs-decision'] }, { number: 529, stage: 60 }] }; + const close = stageTrackerRowActions(it, ctx).find(a => a.id === 'decide:close-issue'); + assert.ok(close && close.enabled, 'every open issue stage/author/hold has Close: ' + stage); + assert.deepStrictEqual(stageTrackerActionRequest(it, close.id, { comment: 'done' }), { + url: '/api/repos/hivecommons/dibs/items/527/decision', + body: { decision: 'close-issue', type: 'issue', comment: 'done' }, + }, 'never chooses covering PR or another issue'); + for (const ro of [{ user: false, canHold: false }, { user: true, canHold: false }]) { + const denied = stageTrackerRowActions(it, ro).find(a => a.id === close.id); + assert.ok(denied && !denied.enabled && denied.why, 'permission denial stays visible'); + } + } +} +for (const it of [{ ...issue, state: 'closed' }, { ...issue, kind: 'pr' }]) { + assert.ok(!stageTrackerRowActions(it, ctx).some(a => a.id === 'decide:close-issue')); + assert.strictEqual(stageTrackerActionRequest(it, 'decide:close-issue'), null); +} +const pr = { repo: 'other/repository', kind: 'pr', number: 900, linked_issues: [ + { number: 901, title: 'First issue', state: 'open', url: 'u901' }, + { number: 902, title: 'Selected nested issue', state: 'open', url: 'u902' }, + { number: 903, title: 'Closed issue', state: 'closed', url: 'u903' }, +] }; +const tools = stageTrackerLinkedIssueToolsHtml(pr); +assert.ok(tools.includes('other/repository/issue#901') && tools.includes('other/repository/issue#902')); +assert.ok(!tools.includes('issue#903'), 'no close menu for a closed linked issue'); +const nested = stageTrackerItemByKey({ items: [pr] }, 'other/repository/issue#902'); +assert.strictEqual(nested.title, 'Selected nested issue'); +assert.strictEqual(stageTrackerActionRequest(nested, 'decide:close-issue').url, '/api/repos/other/repository/items/902/decision'); +assert.strictEqual(stageTrackerItemByKey({ items: [issue, pr] }, 'hivecommons/dibs/issue#527'), issue, 'canonical root DTO wins'); +const pend = { keys: ['other/repository/issue#902'], key: 'other/repository/issue#902', state: stageTrackerItemState(nested), at: Date.now() }; +const refreshed = { ...pr, linked_issues: pr.linked_issues.map(li => li.number === 902 ? { ...li, state: 'closed' } : li) }; +assert.strictEqual(stageTrackerPendingLive([pend], { items: [refreshed] }, Date.now()).length, 0, 'canonical closed linked issue settles pending without hiding its PR'); +assert.strictEqual(refreshed.number, 900); +`) +} + +func TestStageTrackerCloseIssueConfirmationPendingAndFailures(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+stageTrackerConfirmOptOutJS(t, html)+` +const issue = { repo: 'hivecommons/dibs', kind: 'issue', number: 527, title: 'Selected issue', url: 'u527', stage: 85, mirrored: true, + linked_prs: [{ number: 528, stage: 85, modifiers: ['needs-decision'] }] }; +_stageTracker = { items: [issue] }; +const messages = [], results = [], calls = []; +global.showToast = (msg, type) => { messages.push({ msg, type }); return null; }; +global.dismissToast = () => {}; +function stageTrackerProgressToast() { return { update() {}, done() {} }; } +let refreshes = 0; +function stageTrackerAfterActions() { refreshes++; } +function stageTrackerResultToast(result) { results.push(result); return { result }; } +function stageTrackerDecidePending(pend) { pend.decided = true; } +let releasePrompt, releaseFetch; +global.hivePrompt = cfg => { dialogs.push({ cfg }); return new Promise(resolve => { releasePrompt = resolve; }); }; +global.fetch = (url, init) => { calls.push({ url, body: JSON.parse(init.body) }); return new Promise(resolve => { releaseFetch = resolve; }); }; +const tick = async () => { for (let i = 0; i < 10; i++) await Promise.resolve(); }; +(async () => { + const first = runRowAction('decide:close-issue', issue); + assert.strictEqual(dialogs.length, 1); + assert.ok(dialogs[0].cfg.label.includes('hivecommons/dibs#527') && dialogs[0].cfg.label.includes('Selected issue')); + assert.ok(dialogs[0].cfg.label.includes('linked pull requests and other issues stay unchanged')); + assert.strictEqual(dialogs[0].cfg.danger, true); + assert.strictEqual(calls.length, 0, 'confirmation before any mutation'); + await runRowAction('decide:close-issue', issue); + assert.strictEqual(dialogs.length, 1, 'double click cannot open another confirmation'); + releasePrompt('Finished separately'); + await tick(); + assert.strictEqual(calls.length, 1); + assert.strictEqual(calls[0].url, '/api/repos/hivecommons/dibs/items/527/decision'); + assert.strictEqual(calls[0].body.comment, 'Finished separately'); + assert.strictEqual(_stageTrackerPending[0].caption, 'Closing…'); + assert.strictEqual(issue.state, undefined, 'no optimistic false close'); + assert.strictEqual(results.length, 0, 'no success before remote response'); + await runRowAction('decide:close-issue', issue); + assert.strictEqual(calls.length, 1, 'pending prevents double submit'); + releaseFetch({ ok: true, json: async () => ({ status: 'closed', result: { action: 'closed', target: { repo: issue.repo, number: 527, kind: 'issue' }, outcome: 'Issue closed as completed.' } }) }); + const done = await first; + assert.strictEqual(done.results[0].ok, true); + assert.strictEqual(results[0].target.number, 527); + assert.strictEqual(_stageTrackerPending[0].caption, 'Closed · leaving list'); + assert.strictEqual(refreshes, 1, 'canonical tracker refresh requested'); + assert.strictEqual(_stageTracker.items[0], issue, 'existing closed-row policy owns removal; no local hide'); + await runRowAction('decide:close-issue', issue); + assert.strictEqual(dialogs.length, 1, 'waiting for canonical DTO still prevents duplicate close'); + _stageTrackerPending = []; + for (const error of ['write permission required', 'read-only', 'CSRF validation failed', 'forge service unavailable', 'API write denied']) { + const attempt = runRowAction('decide:close-issue', issue); + releasePrompt(''); + await tick(); + releaseFetch({ ok: false, status: 403, json: async () => ({ error }) }); + const failed = await attempt; + assert.strictEqual(failed.results[0].ok, false); + assert.strictEqual(_stageTrackerPending.length, 0, 'error clears pending'); + assert.ok(results.at(-1).outcome.includes(error), 'standard error notification includes server reason'); + assert.strictEqual(_stageTracker.items[0], issue, 'failed close does not hide issue'); + } + for (const data of [{}, { status: 'refused', result: { action: 'refused', target: { repo: issue.repo, number: 527, kind: 'issue' }, outcome: 'Close refused: repo paused' } }]) { + const attempt = runRowAction('decide:close-issue', issue); + releasePrompt(''); + await tick(); + releaseFetch({ ok: true, json: async () => data }); + await attempt; + assert.ok(results.at(-1).action === 'error' || results.at(-1).action === 'refused', 'no fake success'); + assert.strictEqual(_stageTrackerPending.length, 0); + assert.strictEqual(_stageTracker.items[0], issue); + } + const cancelled = runRowAction('decide:close-issue', issue); + const before = calls.length; + releasePrompt(null); + assert.strictEqual((await cancelled).cancelled, true); + assert.strictEqual(calls.length, before, 'cancel writes nothing'); + const n = dialogs.length; + await runRowAction('decide:close-issue', [issue, { ...issue, number: 999 }]); + assert.strictEqual(dialogs.length, n, 'single exact selected issue only; no bulk fan-out'); +})().catch(e => { console.error(e); process.exit(1); }); +`) +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 7f74fb0c52..05f209d4c1 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -38,6 +38,7 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsConstLine(t, html, "STAGE_TRACKER_DELEGATE_ALL_MIN"), jsConstLine(t, html, "STAGE_TRACKER_MERGE_ACTIONS"), jsConstLine(t, html, "STAGE_TRACKER_GENERIC_ACTIONS"), + jsConstLine(t, html, "_stageTrackerCloseIssueBusy"), jsConstLine(t, html, "STAGE_TRACKER_TERMINAL"), "var _stageTrackerSel = new Set(); var _stageTrackerSelAnchor = ''; var _stageTrackerMenu = null; var _stageTracker = null; var _statusSeqFloor = 0; var _stageTrackerEtag = 'e'; var _stageTrackerSig = 's';", jsFunc(t, html, "esc"), @@ -288,12 +289,12 @@ const ids = as => as.map(a => a.id); const ctx = { user: true, canHold: true, canHuman: true }; const parked = { repo: 'o/r', kind: 'issue', number: 1, title: 'Parked', url: 'https://github.com/o/r/issues/1', stage: 45, modifiers: ['needs-decision'] }; let as = stageTrackerRowActions(parked, ctx); -assert.deepStrictEqual(ids(as), ['decide', 'hold', 'retry', 'needs-human', 'open', 'copy']); +assert.deepStrictEqual(ids(as), ['decide', 'hold', 'retry', 'needs-human', 'decide:close-issue', 'open', 'copy']); assert.deepStrictEqual(ids(as[0].submenu), ['decide:delegate', 'decide:approve', 'decide:direction', 'decide:close-superseded', 'decide:close-wontfix'], 'an issue gets let-hive-decide first, then approve / direction / close'); assert.ok(as.every(a => a.enabled), 'everything is enabled for a writer'); const plain = { repo: 'o/r', kind: 'issue', number: 2, url: 'u', stage: 20, modifiers: [] }; -assert.deepStrictEqual(ids(stageTrackerRowActions(plain, ctx)), ['hold', 'retry', 'needs-human', 'open', 'copy'], 'no Decide off 045/085'); +assert.deepStrictEqual(ids(stageTrackerRowActions(plain, ctx)), ['hold', 'retry', 'needs-human', 'decide:close-issue', 'open', 'copy'], 'no Decide off 045/085'); const held = { repo: 'o/r', kind: 'pr', number: 3, url: 'u', stage: 60, modifiers: ['hold', 'needs-human'] }; as = stageTrackerRowActions(held, ctx); @@ -371,7 +372,7 @@ assert.strictEqual(by.open.enabled, true); const menu = stageTrackerMenuHtml(as, 'o/r#1 · Parked'); assert.ok(menu.startsWith('')); -assert.strictEqual((menu.match(/role="menuitem"/g) || []).length, 11, 'six top-level items + five decide options'); +assert.strictEqual((menu.match(/role="menuitem"/g) || []).length, 12, 'seven top-level items including Close issue + five decide options'); assert.ok(menu.includes('data-ham-act="hold" tabindex="-1" aria-disabled="true" title="' + STAGE_TRACKER_WHY_WRITE + '"'), 'disabled items carry the reason'); assert.ok(menu.includes('aria-haspopup="menu" aria-expanded="false"'), 'Decide is a collapsed submenu'); assert.ok(menu.includes('`; + if (typeof stageTrackerLinkedIssueToolsHtml === 'function') leadHtml += stageTrackerLinkedIssueToolsHtml(item); } const prs = typeof stageTrackerRowPRKeys === 'function' ? stageTrackerRowPRKeys(item) : ''; const trainKey = typeof stageTrackerTrainKey === 'function' ? stageTrackerTrainKey(item) : ''; 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 e9d5400707..93f62b91eb 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -370,7 +370,7 @@ request still on the wire) is a different thing drawn on the chevron; this badge appears once the server has recorded the action. */ const STAGE_TRACKER_ACTED_LABELS = { - approve: 'Approve', 'give-direction': 'Give direction', 'close-superseded': 'Close as superseded', wontfix: "Close as won't-fix", 'close-read': 'Closed', + approve: 'Approve', 'give-direction': 'Give direction', 'close-superseded': 'Close as superseded', wontfix: "Close as won't-fix", 'close-read': 'Closed', 'close-issue': 'Close issue', 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', 'queue-merge': 'Approve and let hive merge', 'merge-now': 'Merge now as maintainer', adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 51a950591b..9b8758d576 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -17402,7 +17402,7 @@

Where to get help

request still on the wire) is a different thing drawn on the chevron; this badge appears once the server has recorded the action. */ const STAGE_TRACKER_ACTED_LABELS = { - approve: 'Approve', 'give-direction': 'Give direction', 'close-superseded': 'Close as superseded', wontfix: "Close as won't-fix", 'close-read': 'Closed', + approve: 'Approve', 'give-direction': 'Give direction', 'close-superseded': 'Close as superseded', wontfix: "Close as won't-fix", 'close-read': 'Closed', 'close-issue': 'Close issue', 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', 'queue-merge': 'Approve and let hive merge', 'merge-now': 'Merge now as maintainer', adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', @@ -17520,7 +17520,7 @@

Where to get help

} // Row-menu action id each ledger action was submitted under, so the // option the owner just took is not offered back to them. - const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; // Pure: what the owner can still do when their action changed nothing // (no-op) or the item has not moved (stuck): the enabled options from // the row's decision_needed payload, minus the one just taken. @@ -18142,6 +18142,7 @@

Where to get help

${stageTrackerIcon('issue', 'ham-kind-ico')}${chip} ${esc(li.text)} `; + if (typeof stageTrackerLinkedIssueToolsHtml === 'function') leadHtml += stageTrackerLinkedIssueToolsHtml(item); } const prs = typeof stageTrackerRowPRKeys === 'function' ? stageTrackerRowPRKeys(item) : ''; const trainKey = typeof stageTrackerTrainKey === 'function' ? stageTrackerTrainKey(item) : ''; @@ -20478,6 +20479,7 @@

All labels

'decide:delegate': 'Let hive decide', 'decide:delegate-all': 'Let hive decide — all PRs', 'decide:delegate:rerun': 'Re-run decision', 'decide:approve': 'Approve', 'decide:direction': 'Give direction', 'decide:close-superseded': 'Close as superseded by', 'decide:close-wontfix': "Close as won't-fix", 'decide:close-read': 'Close now', + 'decide:close-issue': 'Close issue', 'decide:adopt': 'Adopt (hive takes over)', 'decide:queue-merge': 'Approve and let hive merge', 'decide:merge-now': 'Merge now as maintainer', 'decide:re-author': 'Re-author as hive PR', @@ -20494,7 +20496,8 @@

All labels

const STAGE_TRACKER_MERGE_ACTIONS = ['decide:queue-merge', 'decide:merge-now']; // Generic items every row has; a server-named decision option with one // of these ids is not repeated at the top of the menu. - const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:adopt']; + const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:adopt', 'decide:close-issue']; + const _stageTrackerCloseIssueBusy = new Set(); // Accept triage shows on an issue the chevron calls "Triage needed": // stage 015, or the needs-triage pill on a pre-claim stage (010 / 017 / // 045). A needs-triage left on a claimed or covered issue is reported @@ -20603,6 +20606,10 @@

All labels

if (!d || !Array.isArray(d.items)) return null; for (const it of d.items) if (stageTrackerItemKey(it) === key) return it; for (const it of d.items) { + for (const li of (Array.isArray(it.linked_issues) ? it.linked_issues : [])) { + const issue = { repo: it.repo, number: li.number, kind: 'issue', title: li.title || '', url: li.url || '', state: li.state || '' }; + if (stageTrackerItemKey(issue) === key) return issue; + } for (const lp of (Array.isArray(it.linked_prs) ? it.linked_prs : [])) { const pr = stageTrackerLinkedPRItem(it, lp); if (stageTrackerItemKey(pr) === key) return pr; @@ -20610,6 +20617,14 @@

All labels

} return null; } + // Linked issues in a PR-only view still have their own exact target. + function stageTrackerLinkedIssueToolsHtml(item) { + return (Array.isArray(item.linked_issues) ? item.linked_issues : []).filter(li => li && Number(li.number) > 0 && li.state === 'open').map(li => { + const issue = { repo: item.repo, number: li.number, kind: 'issue' }; + const ref = stageTrackerRefOf(issue); + return `Issue #${Number(li.number)} `; + }).join(''); + } function stageTrackerItemsForKeys(keys) { return keys.map(k => stageTrackerItemByKey(_stageTracker, k)).filter(Boolean); } @@ -20886,6 +20901,7 @@

All labels

: { id: 'hold', label: 'Hold', enabled: write, why: write ? '' : STAGE_TRACKER_WHY_WRITE, sep: triage && !target }); out.push({ id: 'retry', label: 'Re-evaluate now', hint: 'rescan', enabled: true, why: '' }); if (!has('needs-human')) out.push({ id: 'needs-human', label: 'Mark needs-human…', enabled: !!ctx.canHuman, why: ctx.canHuman ? '' : STAGE_TRACKER_WHY_ROLE }); + if (item.kind === 'issue' && String(item.state || '').toLowerCase() !== 'closed') out.push(Object.assign({ id: 'decide:close-issue', label: 'Close issue…', danger: true, hint: 'only this issue · completed' }, stageTrackerActionAllowed('decide:close-issue', ctx))); out.push({ id: 'open', label: 'Open on GitHub', enabled: !!item.url, why: item.url ? '' : 'No GitHub link', sep: true }); out.push({ id: 'copy', label: 'Copy link', enabled: !!item.url, why: item.url ? '' : 'No GitHub link' }); return out; @@ -21620,6 +21636,7 @@

All labels

case 'accept-triage': return item.kind === 'pr' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/accept-triage', body: {} }; case 'blocker:recheck': return item.kind === 'pr' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/blocker/recheck', body: {} }; case 'blocker:close-partial': return item.kind === 'pr' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/blocker/close-partial', body: { comment: payload.comment || '' } }; + case 'decide:close-issue': return item.kind !== 'issue' || String(item.state || '').toLowerCase() === 'closed' ? null : { url: '/api/repos/' + seg + '/items/' + n + '/decision', body: { decision: 'close-issue', comment: payload.comment || '', type: 'issue' } }; } if (id === 'decide:delegate' || id === 'decide:delegate:rerun') { const body = { type, reason: item.reason || '', caption: item.caption || '', sentinel_reason: item.sentinel_reason || '' }; @@ -21776,6 +21793,7 @@

All labels

const r = await fetch(req.url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(req.body) }); let data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + if (id === 'decide:close-issue' && data.status !== 'closed' && data.status !== 'refused') throw new Error(data.error || 'The server did not confirm that the issue closed'); if (data.minStatusSeq != null) _statusSeqFloor = Math.max(_statusSeqFloor || 0, Number(data.minStatusSeq) || 0); if (req.poll && !stageTrackerDelegatedDone(data)) { showToast('Hive is deciding ' + stageTrackerRefOf(it) + '…', 'info'); @@ -22321,6 +22339,12 @@

All labels

} case 'decide:close-read': return (await stageTrackerAsk(id, 'confirm', { title: 'Close advisory', message: stageTrackerAdvisoryCloseMessage(items, refs, who), confirmLabel: 'Close' })) ? {} : null; + case 'decide:close-issue': { + const item = items[0]; + // This destructive exact-issue action always asks; no confirmation opt-out. + const v = await hivePrompt({ title: 'Close issue', label: 'Close ' + refs + ' — ' + (item.title || 'Untitled issue') + ' as completed, as ' + who + '? Only this issue closes; linked pull requests and other issues stay unchanged. An attributed closing note is posted. Additional comment (optional):', placeholder: 'Optional closing comment', confirmLabel: 'Close issue', danger: true }); + return v == null ? null : { comment: v }; + } case 'decide:merge-now': { const base = items.map(it => it.base_ref || '').filter(Boolean)[0] || 'its base branch'; if (items.some(stageTrackerNeedsRebase)) { @@ -22440,7 +22464,7 @@

All labels

const STAGE_TRACKER_ACTING_CAPTIONS = { 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'blocker:recheck': 'Checking App permissions…', 'blocker:close-partial': 'Closing as partial…', - 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', + 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', 'decide:close-issue': 'Closing…', 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:re-author': 'Queuing re-authoring…', 'decide:adopt': 'Adopting…', 'decide:adopt-now': 'Adopting now…', 'decide:reroute': 'Rerouting…', }; @@ -22460,7 +22484,7 @@

All labels

} // The ledger name of a row action id (the inverse of the badge's // STAGE_TRACKER_ACTED_OPTION_ID), for a failure noted on the client. - const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:re-author': 're-author', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; + const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:re-author': 're-author', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; // A failed or refused action is noted on the row at once, so the // history badge turns red and its hover's first line names the reason // — the server's ledger only sees 5xx and refused answers, and a @@ -22490,7 +22514,7 @@

All labels

// Pure: the state signature a toast / acting row waits to see change. function stageTrackerItemState(it) { if (!it) return ''; - return String(Number(it.stage) || 0) + '|' + (it.stage_slug || '') + '|' + (it.caption || '') + '|' + (Array.isArray(it.modifiers) ? it.modifiers.slice().sort().join(',') : '') + (it.rebase_merge && it.rebase_merge.state ? '|rm:' + it.rebase_merge.state : '') + (it.rebase && it.rebase.text ? '|rb:' + it.rebase.text : ''); + return String(Number(it.stage) || 0) + '|' + (it.stage_slug || '') + '|' + (it.caption || '') + '|' + (Array.isArray(it.modifiers) ? it.modifiers.slice().sort().join(',') : '') + (it.state ? '|state:' + it.state : '') + (it.rebase_merge && it.rebase_merge.state ? '|rm:' + it.rebase_merge.state : '') + (it.rebase && it.rebase.text ? '|rb:' + it.rebase.text : ''); } function stageTrackerTargetKey(target) { return target && target.number ? stageTrackerItemKey({ repo: target.repo, kind: target.kind === 'pr' ? 'pr' : 'issue', number: target.number }) : ''; @@ -22755,6 +22779,24 @@

All labels

const id = action; const rows = items.slice(); if (!items.length) return { toasts: [], pending: [] }; + if (id === 'decide:close-issue') { + // Never remap an issue close through its covering PR or fan it out. + if (items.length !== 1 || !stageTrackerActionRequest(items[0], id)) { + stageTrackerNothingToActOn(id, rows); + return { toasts: [], pending: [] }; + } + const key = stageTrackerItemKey(items[0]); + if (_stageTrackerCloseIssueBusy.has(key) || _stageTrackerPending.some(p => p.keys.indexOf(key) >= 0)) return { toasts: [], pending: [] }; + _stageTrackerCloseIssueBusy.add(key); + try { + const payload = await stageTrackerActionPayload(items, id, rows); + if (payload == null) return { toasts: [], pending: [], cancelled: true }; + const results = await stageTrackerRunActions(items, id, payload, rows); + return { toast: results.toasts[0] || null, toasts: results.toasts, pending: results.pending, results }; + } finally { + _stageTrackerCloseIssueBusy.delete(key); + } + } if (id === 'open') { for (const it of items) if (it.url) window.open(it.url, '_blank', 'noopener'); return { toasts: [], pending: [] }; @@ -22956,7 +22998,6 @@

All labels

// kind → { name, bytes (ArrayBuffer), buffer (AudioBuffer|null), failed } var _stageTrackerClips = { open: null, merge: null }; var _stageTrackerSettingsReturnFocus = null; - function stageTrackerPRKey(repo, number) { return (repo || '') + '/pr#' + (Number(number) || 0); } function stageTrackerItemKey(it) { return (it.repo || '') + '/' + (it.kind || '') + '#' + (Number(it.number) || 0); }