diff --git a/changelog.d/fixed-let-hive-decide-busy-state.md b/changelog.d/fixed-let-hive-decide-busy-state.md new file mode 100644 index 0000000000..046abd9848 --- /dev/null +++ b/changelog.d/fixed-let-hive-decide-busy-state.md @@ -0,0 +1 @@ +- Stage tracker: *Let hive decide* now shows it is working the instant it is clicked — the button goes busy (**Asking the hive…** with the tracker's working glyph) and the preview opens at once as a skeleton that fills when the plan lands, with an inline error and **Retry** on failure and no double-fire — and answers faster: the plan endpoint is cached for a short TTL (`HIVE_DASHBOARD_DECIDE_PLAN_CACHE_TTL`) and prefetched as a row's decision options come into view, reporting its duration in `Server-Timing`. Issues covered by a PR parked at 085 no longer inherit the PR's actionable chip (they show a passive *decision pending on #N* chip and the caption *Covered by PR #N — waiting for a decision on the PR*), and every chevron with the 👤 marker now names what the person is wanted for (`human_reason`, e.g. *PR in progress · #15759 needs a decision*) ([#15773](https://github.com/hivecommons/hive/issues/15773)). diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index fea330b76a..0789f1561d 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,6 +24,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1626` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1627` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1628` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1630` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1631` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1632` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index e007e73333..64cd490a72 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -63,4 +63,4 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:315` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:316` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:317` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1633` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1637` | diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index f41d563955..0f64fe8245 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -8,17 +8,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)) | `pkg/dashboard/api.go:44` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:45` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:66` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1606` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1607` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1608` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1614` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1619` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1620` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1621` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1622` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1623` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1624` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1625` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1610` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1611` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1612` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1618` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1623` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1624` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1625` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1626` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1627` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1628` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1629` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 4d53bb4955..ade07b3953 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:46` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1686` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1690` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:79` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:80` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:81` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 7b807078b6..5181987ad4 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -209,6 +209,8 @@ Full entry: [Hive activity monitor](dashboard-sections/activity-monitor.md#hive- The monitor's decision feature has its own entry: [Let hive decide](dashboard-sections/activity-monitor.md#let-hive-decide). +Clicking it answers at once: the button reads **Asking the hive…** with the tracker's working glyph and the preview opens as a skeleton that fills when the plan arrives (served from a short server cache and prefetched as the row's options come into view). Every chevron carrying the 👤 marker names its reason after a middot (*PR in progress · #N needs a decision*), and an issue covered by a PR parked at 085 shows a passive *decision pending on #N* chip instead of the PR's button. + ## Agent activity One line per worker showing what it is doing now, how long since it last acted, and which issues it has reserved. diff --git a/src/docs/dashboard-sections/activity-monitor.md b/src/docs/dashboard-sections/activity-monitor.md index 398c45bfa3..3ced3d77f4 100644 --- a/src/docs/dashboard-sections/activity-monitor.md +++ b/src/docs/dashboard-sections/activity-monitor.md @@ -65,6 +65,8 @@ The hive often parks work on a person: a decision asked at **045** / **085**, a - **Topbar.** A **Waiting on you · N** pill sits beside **Health**, hidden at zero. Click it to land on the activity monitor with the **Waiting on you** filter applied; `?filter=waiting-on-you` on the dashboard URL does the same (for links from chat or a notification). - **Toast.** When the count rises between two polls, one in-app toast says **N items need your decision — #15312, #15433 …** with a **Show** action that applies the filter. At most one toast per ten minutes; none in kiosk mode. +**The person marker always says why.** A lit chevron with the 👤 marker names what the person is wanted for after a middot — *PR in progress · #15759 needs a decision*, *Needs decision · security finding*, *Ready for human merge · workflow files*, *Advisory · read & close* — from the payload's `human_reason` (≤40 characters, set on every row and nested PR whose `stage_actor` is a person; the full question stays in the tooltip). An issue riding a PR parked at **085** does not inherit the PR's *Let hive decide* chip: it carries `decision_pending_on` (the PR number), its caption reads *Covered by PR #N — waiting for a decision on the PR*, and the row shows a passive, muted **decision pending on #N** chip that scrolls to the PR's row, which alone offers the decision ([#15773](https://github.com/hivecommons/hive/issues/15773)). + `kind` is one of `needs-decision` (045 / 085 or the `needs-decision` modifier), `ready-for-human-merge` (090), `approve-needed` (`needs-human` / `unauthorized`), `returned-to-contributor-offline` (071 / 072 once the author's grace has elapsed — `who` is then the contributor, the operator being their fallback), `other-human-wait` (015 triage). `who` is `operator` for everything the signed-in operator / maintainers must do themselves. Rows on **hold**, advisories, decided rows and PRs nested under a listed issue are not counted: hold is the operator's own choice, an advisory asks for nothing, and a decided row is the hive's to act on next. Each item also carries `waiting_on_you` / `wait_kind`, which is what the **Waiting on you** toolbar chip filters on. ### Filters, sorting and pagination @@ -585,6 +587,8 @@ The item leaves 085/045 and proceeds without the owner. The action is audited as 1. Read the one-time explanation and confirmation. **Don't ask again for this action** is optional; reset it in ⚙ → **Confirmations**. 2. The row reads **Hive is deciding…** while the job runs. + +**Before the confirmation: the preview.** The click answers at once ([#15773](https://github.com/hivecommons/hive/issues/15773)): the button goes disabled with `aria-busy`, reads **Asking the hive…** behind the tracker's working glyph, the row wears the in-flight caption, and the preview dialog opens immediately as a skeleton (title *What the hive would do*, shimmer placeholder lines, **Cancel** live, the confirm button disabled) that fills when the plan arrives; if the plan fails the dialog shows the error inline with **Retry**, and the button restores. A second click while the preview is open is ignored. The plan itself is served from a short server cache (`HIVE_DASHBOARD_DECIDE_PLAN_CACHE_TTL`, default 90s) keyed by repo, number, head and the request words, and the SPA prefetches it as the row's decision options come into view (lead chip hover/focus, ⋯ menu, decision popover), so the click normally answers from cache; `POST …/decide-delegated/plan` returns `Server-Timing: decide_plan;dur=;desc=` and a debug log line with the same. A decision on the item drops its cached plans. 3. Read the persistent result toast. It says what was decided and what happens next; it stays until the target row changes state. 4. If the result has not happened, use [When the decision doesn't take effect](#when-the-decision-doesnt-take-effect), rather than treating an approval as a completed merge. diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index 8cb2316d0f..f9803fcf03 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -87,6 +87,12 @@ type delegatedDecisionRequest struct { // Chosen names the preview button that sent this request // (hivecommons/hive#15126); the ledger records it as the action's note. Chosen string `json:"chosen,omitempty"` + // Head is the PR head the tracker row showed when the plan was asked + // for; it keys the plan cache so a push invalidates a prefetched + // preview (hivecommons/hive#15773). Prefetch marks a plan asked for + // ahead of a click (logged, otherwise identical). + Head string `json:"head,omitempty"` + Prefetch bool `json:"prefetch,omitempty"` } // delegatedDecisionJob is the wire shape of one job. @@ -254,6 +260,8 @@ func (s *Server) handleRepoItemDecideDelegated(w http.ResponseWriter, r *http.Re } now := time.Now() key := delegatedJobKey(repoFull, number) + // A decision changes what the preview would say: drop its plans. + s.delegatedPlans().invalidate(repoFull, number) job := &delegatedDecisionJob{ ID: key + "@" + strconv.FormatInt(now.UnixNano(), 36), Repo: repoFull, Number: number, Type: itemType, Status: delegatedJobStatusRunning, Requester: user, StartedAt: now, Marker: delegatedecision.Marker(s.delegateHiveID()), @@ -634,21 +642,67 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb in.Author = author in.HiveAuthored = client.IsHiveAuthorLogin(author) in.TrustedAuthor = in.HiveAuthored - if err := s.gatherDelegatedPRContext(ctx, repoFull, pr, &in); err != nil { - return in, err - } - if err := s.gatherDelegatedLadderInput(ctx, repoFull, pr, &in); err != nil { - return in, err - } in.DiffEmpty = ghpkg.PRChangedFilesClaimsEmpty(pr) state := strings.ToLower(pr.GetMergeableState()) in.Conflicting = state == "dirty" || (pr.Mergeable != nil && !pr.GetMergeable()) - green, err := delegatedHeadCIGreen(ctx, api, owner, repoName, pr, in.Conflicting, state) - if err != nil { - return in, fmt.Errorf("reading checks for %s#%d: %w", repoFull, number, err) + // The remaining GitHub reads are independent of one another (the + // PR context, the supersession lookup, the head's checks, the file + // list, the author's permission); in flight together they cost one + // round trip, not five (hivecommons/hive#15773). Each goroutine + // writes its own variables; only the context writes into in. + var ( + wg sync.WaitGroup + ctxErr, supErr, ciErr error + sup *delegatedecision.MergedCloser + green bool + files []*gh.CommitFile + trusted bool + checkPerm = !in.TrustedAuthor && author != "" + gatherCtx, cancelGathers = context.WithCancel(ctx) + ) + defer cancelGathers() + wg.Add(4) + go func() { + defer wg.Done() + ctxErr = s.gatherDelegatedPRContext(gatherCtx, repoFull, pr, &in) + }() + go func() { + defer wg.Done() + sup, supErr = s.delegatedSupersession(gatherCtx, repoFull, pr, in.HiveAuthored) + }() + go func() { + defer wg.Done() + green, ciErr = delegatedHeadCIGreen(gatherCtx, api, owner, repoName, pr, in.Conflicting, state) + }() + go func() { + defer wg.Done() + files, _, _ = api.PullRequests.ListFiles(gatherCtx, owner, repoName, number, &gh.ListOptions{PerPage: delegatedDecisionGatherLimit}) + }() + if checkPerm { + wg.Add(1) + go func() { + defer wg.Done() + if perm, _, err := api.Repositories.GetPermissionLevel(gatherCtx, owner, repoName, author); err == nil { + switch strings.ToLower(perm.GetPermission()) { + case "admin", "write", "maintain": + trusted = true + } + } + }() + } + wg.Wait() + if ctxErr != nil { + return in, ctxErr + } + if supErr != nil { + return in, supErr + } + s.gatherDelegatedLadderLocal(repoFull, pr, &in, sup) + if ciErr != nil { + return in, fmt.Errorf("reading checks for %s#%d: %w", repoFull, number, ciErr) } in.CIGreen = green - if files, _, err := api.PullRequests.ListFiles(ctx, owner, repoName, number, &gh.ListOptions{PerPage: delegatedDecisionGatherLimit}); err == nil && len(files) > 0 { + if len(files) > 0 { in.LowRiskPaths = true for _, f := range files { if !delegatedLowRiskPath(f.GetFilename()) { @@ -659,13 +713,8 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb } } } - if !in.TrustedAuthor && author != "" { - if perm, _, err := api.Repositories.GetPermissionLevel(ctx, owner, repoName, author); err == nil { - switch strings.ToLower(perm.GetPermission()) { - case "admin", "write", "maintain": - in.TrustedAuthor = true - } - } + if trusted { + in.TrustedAuthor = true } } sentinel := s.sentinelLabel() diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go index 63b6af85f5..92a6c07c5c 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go @@ -106,12 +106,18 @@ func (s *Server) handleRepoItemDecideDelegatedPlan(w http.ResponseWriter, r *htt if s.deps.Ctx != nil { ctx = s.deps.Ctx } - plan, err := s.planDelegatedDecision(ctx, repoFull, number, itemType, mergerRole, body) - if err != nil { - jsonError(w, err.Error(), http.StatusBadGateway) + res := s.cachedPlanDelegatedDecision(ctx, repoFull, number, itemType, mergerRole, body) + // Server-Timing says how long the gather took and whether the cache + // answered, so the click's latency can be read off the network panel. + w.Header().Add("Server-Timing", fmt.Sprintf("decide_plan;dur=%.1f;desc=%s", float64(res.dur.Microseconds())/1000, res.source)) + if s.logger != nil { + s.logger.Debug("decide-delegated plan", "repo", repoFull, "number", number, "type", itemType, "source", res.source, "prefetch", body.Prefetch, "dur_ms", res.dur.Milliseconds(), "err", res.err) + } + if res.err != nil { + jsonError(w, res.err.Error(), http.StatusBadGateway) return } - jsonResponse(w, plan) + jsonResponse(w, res.plan) } // planDelegatedDecision runs the same gather + decide as diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go index 988efe75bf..51b328059f 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go @@ -2,11 +2,13 @@ package dashboard import ( "encoding/json" + "errors" "net/http" "net/http/httptest" "strconv" "strings" "testing" + "time" "github.com/hivecommons/hive/pkg/delegatedecision" ) @@ -333,3 +335,105 @@ func TestDelegatedDecisionPlanIssueAndAdvisory(t *testing.T) { }) } } + +// hivecommons/hive#15773: the preview is cached for a short TTL keyed by +// (repo, number, type, head, request, role) so a prefetch as the row's +// options come into view makes the click instant; a gather in flight is +// joined, not repeated; a decision on the item drops its plans; the +// response says where the plan came from. +func TestDelegatedDecisionPlanCacheAnswersRepeatClicks(t *testing.T) { + mock := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/085-needs-decision", "needs-human"}} + srv := newDelegatedServer(t, mock) + srv.deps.Config.Governor.Labels.Stage.Adoption.Enabled = boolPtr(true) + hdr := map[string]string{"X-Hive-Role": "merger"} + body := `{"type":"pr","reason":"adoption-stalled:contributor-offline","caption":"adoption stalled","head":"abc123","prefetch":true}` + + w := postDelegatedPlan(t, srv, 8, "writer", body, hdr) + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + if st := w.Header().Get("Server-Timing"); !strings.Contains(st, "decide_plan;dur=") || !strings.Contains(st, "desc=gather") { + t.Fatalf("Server-Timing = %q, want a gather with its duration", st) + } + mock.mu.Lock() + gets := mock.gets + mock.mu.Unlock() + if gets == 0 { + t.Fatal("the first plan must gather from GitHub") + } + + // The click after the prefetch: same key, no GitHub traffic. + w = postDelegatedPlan(t, srv, 8, "writer", strings.Replace(body, `,"prefetch":true`, "", 1), hdr) + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + if st := w.Header().Get("Server-Timing"); !strings.Contains(st, "desc=cache") { + t.Fatalf("Server-Timing = %q, want the cache", st) + } + mock.mu.Lock() + if mock.gets != gets { + mock.mu.Unlock() + t.Fatalf("cached click hit GitHub: gets %d → %d", gets, mock.gets) + } + mock.mu.Unlock() + var plan delegatedDecisionPlan + if err := json.Unmarshal(w.Body.Bytes(), &plan); err != nil || plan.Would != string(delegatedecision.VerdictAdoptSupersede) { + t.Fatalf("cached plan = %+v err=%v", plan, err) + } + + // A new head is a new plan. + w = postDelegatedPlan(t, srv, 8, "writer", strings.Replace(body, "abc123", "def456", 1), hdr) + if st := w.Header().Get("Server-Timing"); w.Code != http.StatusOK || !strings.Contains(st, "desc=gather") { + t.Fatalf("new head: code=%d Server-Timing=%q", w.Code, st) + } + + // A decision on the item drops its plans. + srv.delegatedPlans().invalidate("testorg/testrepo", 8) + w = postDelegatedPlan(t, srv, 8, "writer", body, hdr) + if st := w.Header().Get("Server-Timing"); w.Code != http.StatusOK || !strings.Contains(st, "desc=gather") { + t.Fatalf("after invalidate: code=%d Server-Timing=%q", w.Code, st) + } +} + +// The cache itself: a TTL lapse (clock injected) drops the entry, a gather +// in flight is shared, a failed gather is not kept, and TTL 0 disables it. +func TestDelegatedPlanCacheTTLAndInflight(t *testing.T) { + c := newDelegatedPlanCache(time.Minute) + t0 := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) + key := delegatedPlanCacheKey("o/r", 1, "pr", true, delegatedDecisionRequest{Head: "h1"}) + if c.lookup(key, t0) != nil { + t.Fatal("empty cache answered") + } + e := c.start(key, t0) + if got := c.lookup(key, t0); got != e { + t.Fatal("a gather in flight must be shared") + } + c.finish(key, e, &delegatedDecisionPlan{Would: "approve"}, nil, t0, 3*time.Second) + if got := c.lookup(key, t0.Add(59*time.Second)); got == nil || got.plan.Would != "approve" || got.dur != 3*time.Second { + t.Fatalf("within TTL: %+v", got) + } + if c.lookup(key, t0.Add(61*time.Second)) != nil { + t.Fatal("past the TTL the plan must be gathered again") + } + failed := c.start(key, t0) + c.finish(key, failed, nil, errors.New("github: 502"), t0, time.Second) + if c.lookup(key, t0) != nil { + t.Fatal("a failed gather must not be cached") + } + if k2 := delegatedPlanCacheKey("o/r", 1, "pr", true, delegatedDecisionRequest{Head: "h2"}); k2 == key { + t.Fatal("the head must be part of the key") + } + if k3 := delegatedPlanCacheKey("o/r", 1, "pr", false, delegatedDecisionRequest{Head: "h1"}); k3 == key { + t.Fatal("the merger role must be part of the key") + } + off := newDelegatedPlanCache(0) + e = off.start(key, t0) + off.finish(key, e, &delegatedDecisionPlan{}, nil, t0, 0) + if off.lookup(key, t0) != nil { + t.Fatal("TTL 0 must disable the cache") + } + t.Setenv(delegatedPlanCacheTTLEnv, "15s") + if got := delegatedPlanCacheTTL(); got != 15*time.Second { + t.Fatalf("env TTL = %v", got) + } +} diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index 5300abb567..9e7a94650b 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -67,6 +67,8 @@ type repoItemDecisionMock struct { fixedIssueClosedBy int // issueTitle / issueBody shape issue #7 (empty = untitled, no body). issueTitle, issueBody string + // gets counts GET requests (the plan cache test reads it). + gets int } func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { @@ -76,6 +78,9 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { defer m.mu.Unlock() w.Header().Set("Content-Type", "application/json") path := r.URL.Path + if r.Method == http.MethodGet { + m.gets++ + } switch { case r.Method == http.MethodGet && (strings.HasSuffix(path, "/collaborators/writer/permission") || strings.HasSuffix(path, "/collaborators/someone/permission")): _, _ = io.WriteString(w, `{"permission":"write"}`) diff --git a/src/pkg/dashboard/delegated_ladder.go b/src/pkg/dashboard/delegated_ladder.go index 758afc15ba..33238cfd53 100644 --- a/src/pkg/dashboard/delegated_ladder.go +++ b/src/pkg/dashboard/delegated_ladder.go @@ -20,28 +20,42 @@ import ( // what the author drives (clanker / hive / person, for the wording), and // whether their relay has picked the rework up. -// gatherDelegatedLadderInput fills Input.SupersededBy, AuthorTooling, -// ReworkPickedUp and RepoPaused for a contributor PR. A supersession +// The ladder input (Input.SupersededBy, AuthorTooling, ReworkPickedUp, +// RepoPaused) for a contributor PR comes in two halves: the GitHub half +// (delegatedSupersession) needs only the PR and runs in flight with the +// PR-context reads; the local half (gatherDelegatedLadderLocal) needs the +// context's OwnerAuthor / HumanAuthor and runs after both. A supersession // lookup failure aborts the decision: the fallback rung is adoption, and // "unknown" must not read as "not superseded". -func (s *Server) gatherDelegatedLadderInput(ctx context.Context, repoFull string, pr *gh.PullRequest, in *delegatedecision.Input) error { - client := s.deps.GHClient - in.RepoPaused = client.RepoIsPaused(repoFull) - in.AuthorTooling = s.delegatedAuthorTooling(in.Labels, in.OwnerAuthor) - if in.HiveAuthored { - return nil + +// delegatedSupersession is the ladder's one GitHub read: the merged PR +// that already carries this one's fix, nil when none (or hive-authored). +func (s *Server) delegatedSupersession(ctx context.Context, repoFull string, pr *gh.PullRequest, hiveAuthored bool) (*delegatedecision.MergedCloser, error) { + if hiveAuthored { + return nil, nil } - sup, ok, err := client.DetectMergedSupersession(ctx, repoFull, pr) + sup, ok, err := s.deps.GHClient.DetectMergedSupersession(ctx, repoFull, pr) if err != nil { - return fmt.Errorf("reading whether %s#%d is already fixed: %w", repoFull, pr.GetNumber(), err) + return nil, fmt.Errorf("reading whether %s#%d is already fixed: %w", repoFull, pr.GetNumber(), err) + } + if !ok { + return nil, nil } - if ok { - in.SupersededBy = &delegatedecision.MergedCloser{PR: sup.Closer, Issue: sup.Issue, SHA: sup.MergeSHA} + return &delegatedecision.MergedCloser{PR: sup.Closer, Issue: sup.Issue, SHA: sup.MergeSHA}, nil +} + +// gatherDelegatedLadderLocal fills the ladder fields that need no GitHub +// call, once the PR context (OwnerAuthor, HumanAuthor) is in. +func (s *Server) gatherDelegatedLadderLocal(repoFull string, pr *gh.PullRequest, in *delegatedecision.Input, sup *delegatedecision.MergedCloser) { + in.RepoPaused = s.deps.GHClient.RepoIsPaused(repoFull) + in.AuthorTooling = s.delegatedAuthorTooling(in.Labels, in.OwnerAuthor) + if in.HiveAuthored { + return } + in.SupersededBy = sup if !in.PersonAuthored() { in.ReworkPickedUp = s.delegatedReworkPickedUp(repoFull, pr, in.Author, time.Now()) } - return nil } // delegatedAuthorTooling reads the author-kind labels (names from diff --git a/src/pkg/dashboard/delegated_plan_cache.go b/src/pkg/dashboard/delegated_plan_cache.go new file mode 100644 index 0000000000..83057eb625 --- /dev/null +++ b/src/pkg/dashboard/delegated_plan_cache.go @@ -0,0 +1,223 @@ +package dashboard + +import ( + "context" + "os" + "strconv" + "strings" + "sync" + "time" +) + +// The "Let hive decide" preview answered in 2–6 s on hive's own spoke +// (hivecommons/hive#15773): planDelegatedDecision gathers the PR live from +// GitHub — the PR, its files, the author's permission level, the head's +// checks, every competing PR, the comments and reviews, the prior +// decisions — and the SPA showed nothing until the plan landed. The cache +// below makes the click instant when the SPA prefetched the plan as the +// row's decision options came into view, and makes a click on a plan still +// being gathered join that gather instead of starting a second one. +// +// A plan is a preview, not a decision: the decide endpoint re-gathers, so +// a cached plan a few seconds stale can only ever mis-preview. The TTL is +// short on purpose; a decision on the item drops its plans at once. + +// delegatedPlanCacheTTLDefault is how long a gathered plan answers clicks. +const delegatedPlanCacheTTLDefault = 90 * time.Second + +// delegatedPlanCacheTTLEnv overrides the TTL (a Go duration; "0" disables +// the cache — every click gathers). +const delegatedPlanCacheTTLEnv = "HIVE_DASHBOARD_DECIDE_PLAN_CACHE_TTL" + +// delegatedPlanCacheMaxEntries bounds the cache; the oldest entry leaves +// when it is full. +const delegatedPlanCacheMaxEntries = 256 + +// delegatedPlanCacheTTL reads the TTL, env override first. +func delegatedPlanCacheTTL() time.Duration { + if raw := strings.TrimSpace(os.Getenv(delegatedPlanCacheTTLEnv)); raw != "" { + if d, err := time.ParseDuration(raw); err == nil && d >= 0 { + return d + } + } + return delegatedPlanCacheTTLDefault +} + +// delegatedPlanEntry is one gathered (or gathering) plan. done closes when +// plan/err are set; at is when the gather finished. +type delegatedPlanEntry struct { + done chan struct{} + plan *delegatedDecisionPlan + err error + at time.Time + dur time.Duration +} + +// delegatedPlanCache keys gathered plans by what shapes them (repo, +// number, type, head, the request's own words and the viewer's merger +// role) and single-flights concurrent gathers of the same key. +type delegatedPlanCache struct { + mu sync.Mutex + entries map[string]*delegatedPlanEntry + ttl time.Duration +} + +func newDelegatedPlanCache(ttl time.Duration) *delegatedPlanCache { + return &delegatedPlanCache{entries: map[string]*delegatedPlanEntry{}, ttl: ttl} +} + +// delegatedPlanCacheKey is the cache key for one plan request. +func delegatedPlanCacheKey(repoFull string, number int, itemType string, mergerRole bool, req delegatedDecisionRequest) string { + parts := []string{repoFull, strconv.Itoa(number), itemType, strconv.FormatBool(mergerRole), + strings.TrimSpace(req.Head), strings.TrimSpace(req.Reason), strings.TrimSpace(req.Caption), strings.TrimSpace(req.SentinelReason)} + return strings.Join(parts, "\x00") +} + +// delegatedPlanCacheItemPrefix is the key prefix every plan of one item shares. +func delegatedPlanCacheItemPrefix(repoFull string, number int) string { + return repoFull + "\x00" + strconv.Itoa(number) + "\x00" +} + +// lookup returns a live entry (finished within the TTL, or still being +// gathered) for key, or nil. +func (c *delegatedPlanCache) lookup(key string, now time.Time) *delegatedPlanEntry { + if c == nil || c.ttl <= 0 { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + e := c.entries[key] + if e == nil { + return nil + } + select { + case <-e.done: + if now.Sub(e.at) > c.ttl { + delete(c.entries, key) + return nil + } + default: + } + return e +} + +// start registers a gather for key and returns the entry to fill with +// finish. With the cache disabled the entry is not retained. +func (c *delegatedPlanCache) start(key string, now time.Time) *delegatedPlanEntry { + e := &delegatedPlanEntry{done: make(chan struct{})} + if c == nil || c.ttl <= 0 { + return e + } + c.mu.Lock() + defer c.mu.Unlock() + c.evictLocked(now) + c.entries[key] = e + return e +} + +// finish publishes the gather's result. +func (c *delegatedPlanCache) finish(key string, e *delegatedPlanEntry, plan *delegatedDecisionPlan, err error, now time.Time, dur time.Duration) { + e.plan, e.err, e.at, e.dur = plan, err, now, dur + close(e.done) + if err == nil || c == nil || c.ttl <= 0 { + return + } + // A failed gather is not worth a TTL: the next click retries. + c.mu.Lock() + if c.entries[key] == e { + delete(c.entries, key) + } + c.mu.Unlock() +} + +// invalidate drops every plan of one item (a decision was just recorded). +func (c *delegatedPlanCache) invalidate(repoFull string, number int) { + if c == nil { + return + } + prefix := delegatedPlanCacheItemPrefix(repoFull, number) + c.mu.Lock() + defer c.mu.Unlock() + for k := range c.entries { + if strings.HasPrefix(k, prefix) { + delete(c.entries, k) + } + } +} + +// evictLocked drops expired entries and, when still full, the oldest one. +func (c *delegatedPlanCache) evictLocked(now time.Time) { + for k, e := range c.entries { + select { + case <-e.done: + if now.Sub(e.at) > c.ttl { + delete(c.entries, k) + } + default: + } + } + for len(c.entries) >= delegatedPlanCacheMaxEntries { + oldestKey, oldest := "", time.Time{} + for k, e := range c.entries { + select { + case <-e.done: + if oldestKey == "" || e.at.Before(oldest) { + oldestKey, oldest = k, e.at + } + default: + } + } + if oldestKey == "" { + return + } + delete(c.entries, oldestKey) + } +} + +// delegatedPlanResult is what the handler reports: the plan, how long the +// gather took and whether the cache (or a gather already in flight) +// answered. +type delegatedPlanResult struct { + plan *delegatedDecisionPlan + err error + dur time.Duration + source string // "gather", "cache" or "inflight" +} + +// cachedPlanDelegatedDecision answers from the cache, joins a gather in +// flight, or gathers and publishes. +func (s *Server) cachedPlanDelegatedDecision(ctx context.Context, repoFull string, number int, itemType string, mergerRole bool, req delegatedDecisionRequest) delegatedPlanResult { + c := s.delegatedPlans() + key := delegatedPlanCacheKey(repoFull, number, itemType, mergerRole, req) + now := time.Now() + if e := c.lookup(key, now); e != nil { + source := "cache" + select { + case <-e.done: + default: + source = "inflight" + } + select { + case <-e.done: + return delegatedPlanResult{plan: e.plan, err: e.err, dur: e.dur, source: source} + case <-ctx.Done(): + return delegatedPlanResult{err: ctx.Err(), source: source} + } + } + e := c.start(key, now) + start := time.Now() + plan, err := s.planDelegatedDecision(ctx, repoFull, number, itemType, mergerRole, req) + dur := time.Since(start) + c.finish(key, e, plan, err, time.Now(), dur) + return delegatedPlanResult{plan: plan, err: err, dur: dur, source: "gather"} +} + +// delegatedPlans is the server's plan cache, created on first use. +func (s *Server) delegatedPlans() *delegatedPlanCache { + s.delegatedPlanOnce.Do(func() { + if s.delegatedPlanCache == nil { + s.delegatedPlanCache = newDelegatedPlanCache(delegatedPlanCacheTTL()) + } + }) + return s.delegatedPlanCache +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 091eac8b87..e846edc88f 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -150,6 +150,10 @@ type Server struct { // the status snapshot, served until its TTL lapses (stage_tracker_build.go). stageTrackerCache stageTrackerCache stageTrackerCacheMu sync.Mutex + // delegatedPlanCache holds the "Let hive decide" previews the SPA + // prefetched or a click gathered (delegated_plan_cache.go). + delegatedPlanCache *delegatedPlanCache + delegatedPlanOnce sync.Once // stageTrackerBuild is the one rebuild in flight, nil when none; it is // guarded by stageTrackerCacheMu, which is never held across the build. stageTrackerBuild *stageTrackerBuild diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 5ce05339a6..dae4a2ec77 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -532,7 +532,16 @@ type StageTrackerItem struct { // draws the stage pill's actor icon from StageActor.Kind only // (stage_tracker_actor.go). StageActor *StageTrackerActor `json:"stage_actor,omitempty"` - LinkedPR int `json:"linked_pr,omitempty"` + // HumanReason, set whenever StageActor is a person, is the ≤40-char + // clause the chevron word carries after a middot ("#15759 needs a + // decision", "workflow files") so the 👤 marker never ships without + // saying what the person is wanted for (hivecommons/hive#15773). + HumanReason string `json:"human_reason,omitempty"` + // DecisionPendingOn is the covering PR an issue rides while that PR + // waits on a decision: the issue draws a passive "decision pending on + // #N" chip instead of the PR's actionable one (hivecommons/hive#15773). + DecisionPendingOn int `json:"decision_pending_on,omitempty"` + LinkedPR int `json:"linked_pr,omitempty"` // LinkedPRs lists the open pull requests covering an issue (the one // named in the stage reason first) with everything the tracker needs // to draw each as a sub-row nested under the issue. @@ -702,6 +711,8 @@ type StageTrackerLinkedPR struct { // StageActor mirrors the nested PR's own row field so the sub-row's // pill wears the same actor icon. StageActor *StageTrackerActor `json:"stage_actor,omitempty"` + // HumanReason mirrors the PR row's (see StageTrackerItem.HumanReason). + HumanReason string `json:"human_reason,omitempty"` // DrawnUnder is the issue whose row draws this PR's full sub-row (the // PR's NestedUnder). A PR that closes several open issues (`Closes // #14910` and `Closes #14911` in one body) is listed by each of them, diff --git a/src/pkg/dashboard/stage_tracker_advisory_test.go b/src/pkg/dashboard/stage_tracker_advisory_test.go index b535dbf0c9..fb390d7791 100644 --- a/src/pkg/dashboard/stage_tracker_advisory_test.go +++ b/src/pkg/dashboard/stage_tracker_advisory_test.go @@ -233,6 +233,8 @@ func TestStageTrackerAdvisoryChipAndAction(t *testing.T) { jsFunc(t, html, "stageTrackerActorTip"), jsFunc(t, html, "stageTrackerHeadline"), jsFunc(t, html, "stageTrackerSegments"), + jsFunc(t, html, "stageTrackerHumanReasonOf"), + jsFunc(t, html, "stageTrackerHumanReasonHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerItemOnHold"), jsFunc(t, html, "stageTrackerItemNeedsHuman"), diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index e35072aa5c..931818a077 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -476,6 +476,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto stageTrackerResolveLinkedPRs(resp.Items, prOpen) stageTrackerMarkClosedBy(resp.Items, s.mergedLedger().ClosedBy) stageTrackerResolveActors(resp.Items) + stageTrackerResolveHumanReasons(resp.Items) sort.SliceStable(resp.Items, stageTrackerLess(resp.Items)) return resp } diff --git a/src/pkg/dashboard/stage_tracker_covered_decision.test.js b/src/pkg/dashboard/stage_tracker_covered_decision.test.js new file mode 100644 index 0000000000..c13ab55507 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_covered_decision.test.js @@ -0,0 +1,110 @@ +// Covered issues and the 👤 marker's reason (hivecommons/hive#15773). +// Owner, on #15503 ("under #15502", covered by PR #15759 parked at 085): +// why does the issue show "Let hive decide" at all? And: "when i see 'pr +// in progress' on the chevron - i have no idea when it needs a human at +// that stage". So: an issue whose covering PR waits on a decision draws a +// passive, muted "decision pending on #N" chip that scrolls to the PR row +// instead of the PR's actionable chip; and every chevron with the human +// marker names what the person is wanted for after a middot, with the +// full question in the tooltip. The functions are lifted out of +// index.html so this runs the shipped source. +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); + +function fn(name) { + const start = html.indexOf('function ' + name + '('); + assert.ok(start >= 0, name + ' not found in index.html'); + let depth = 0; + for (let i = html.indexOf('{', start); i < html.length; i++) { + if (html[i] === '{') depth++; + else if (html[i] === '}' && --depth === 0) return html.slice(start, i + 1); + } + assert.fail('unterminated ' + name); +} + +const stubs = ` +const esc = s => String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +let leadAction = null; +function stageTrackerLeadAction(item, ctx) { return typeof leadAction === 'function' ? leadAction(item, ctx) : leadAction; } +function stageTrackerRefOf(item) { return '#' + item.number; } +function stageTrackerLinkedPROpen() { return true; } +const STAGE_TRACKER_ACTOR_NONE = 'none'; +function stageTrackerStageActor(item) { return item.stage_actor || null; } +`; +const src = [ + fn('stageTrackerItemKey'), + fn('stageTrackerActorKind'), + fn('stageTrackerHumanReasonOf'), + fn('stageTrackerHumanReasonHtml'), + fn('stageTrackerLinkedPRItem'), + fn('stageTrackerDecisionPendingOn'), + fn('stageTrackerDecisionPendingChipHtml'), + fn('stageTrackerLeadDrawnElsewhere'), + fn('stageTrackerLeadActionOnRow'), + fn('stageTrackerLeadActionHtml'), +].join('\n'); +const T = new Function(stubs + src + ` +return { setLead: f => { leadAction = f; }, onRow: stageTrackerLeadActionOnRow, html: stageTrackerLeadActionHtml, chip: stageTrackerDecisionPendingChipHtml, + reasonOf: stageTrackerHumanReasonOf, reasonHtml: stageTrackerHumanReasonHtml, linked: stageTrackerLinkedPRItem };`)(); + +const decide = { id: 'decide:delegate', label: 'Let hive decide', enabled: true, hint: 'hive answers the reviewer', target: { kind: 'pr', repo: 'acme/docs', number: 15759 } }; +const pr = { kind: 'pr', repo: 'acme/docs', number: 15759, stage: 85, stage_actor: { kind: 'human', why: 'a maintainer must decide' }, human_reason: "reviewer's question" }; +const primary = { kind: 'issue', repo: 'acme/docs', number: 15502, stage: 40, decision_pending_on: 15759, stage_actor: { kind: 'human' }, human_reason: '#15759 needs a decision', + linked_prs: [{ number: 15759, drawn_under: 15502, stage: 85, stage_actor: { kind: 'human' }, human_reason: "reviewer's question" }] }; +const secondary = Object.assign({}, primary, { number: 15503 }); + +test('a covered issue draws the passive "decision pending on #N" chip, not the PR\'s actionable one', () => { + T.setLead(() => decide); + const ctx = { user: true }; + for (const issue of [primary, secondary]) { + assert.strictEqual(T.onRow(issue, ctx, issue.linked_prs), null, '#' + issue.number + ' must not lead with the PR\'s decision'); + const out = T.html(issue, ctx, issue.linked_prs); + assert.ok(!out.includes('ham-lead-act') && !out.includes('>Let hive decide<'), out); + assert.ok(out.includes('class="ham-chip ham-chip-passive"'), out); + assert.ok(out.includes('>decision pending on #15759<'), out); + assert.ok(out.includes('data-action="hamBannerShowRow" data-arg0="acme/docs/pr#15759"'), 'the chip scrolls to the PR row: ' + out); + assert.ok(/title="PR #15759 is parked on a decision/.test(out), out); + } + // The PR row itself keeps the button. + const prOut = T.html(pr, ctx); + assert.ok(prOut.includes('ham-lead-act') && prOut.includes('data-ham-act="decide:delegate"') && prOut.includes('>Let hive decide<'), prOut); +}); + +test('without the server flag a secondary issue still never offers the decision of a PR drawn under the primary', () => { + T.setLead(() => decide); + const issue = { kind: 'issue', repo: 'acme/docs', number: 15503, stage: 40, linked_prs: [{ number: 15759, drawn_under: 15502, stage: 85 }] }; + assert.strictEqual(T.onRow(issue, { user: true }, []), null); + assert.strictEqual(T.html(issue, { user: true }, []), '', 'no flag, no chip: the sub-row under the primary issue carries the button'); + // The primary (the PR drawn under it, no sub-rows passed) keeps the existing contract. + const prime = Object.assign({}, issue, { number: 15502 }); + assert.ok(T.onRow(prime, { user: true }), 'the issue the PR is drawn under keeps its lead when no sub-rows are rendered'); + // An issue's own decision (045, target is the issue) still leads. + const own = { kind: 'issue', repo: 'acme/docs', number: 15600, stage: 45 }; + T.setLead(() => Object.assign({}, decide, { target: { kind: 'issue', number: 15600 } })); + assert.ok(T.onRow(own, { user: true }), 'an issue decides its own 045 question'); + // A non-decision lead whose target is a PR (e.g. merge) is untouched. + T.setLead(() => ({ id: 'merge', label: 'Merge', enabled: true, target: { kind: 'pr', number: 15759 } })); + assert.ok(T.onRow(issue, { user: true }, []), 'only decide:* leads are suppressed'); + // No lead at all and no flag → nothing. + T.setLead(() => null); + assert.strictEqual(T.html(issue, { user: true }), ''); +}); + +test('the human marker always carries its reason after a middot; the word is not repeated', () => { + assert.strictEqual(T.reasonOf(primary), '#15759 needs a decision'); + assert.strictEqual(T.reasonOf(pr), "reviewer's question"); + assert.strictEqual(T.reasonOf({ kind: 'pr', stage: 70, stage_actor: { kind: 'hive' }, human_reason: 'stale' }), '', 'a hive actor carries no human reason'); + assert.strictEqual(T.reasonOf({ kind: 'pr', stage: 85, stage_actor: { kind: 'human' } }), '', 'no server reason, no clause'); + assert.strictEqual(T.reasonHtml('#15759 needs a decision', 'PR in progress'), ' · #15759 needs a decision'); + assert.strictEqual(T.reasonHtml('read & close', 'Advisory · read & close'), '', 'a word that already says it adds nothing'); + assert.strictEqual(T.reasonHtml('x', 'w'), ' · <b>x</b>', 'escaped'); + assert.strictEqual(T.reasonHtml('', 'w'), ''); + // The nested PR sub-row carries the PR's own reason. + const sub = T.linked(primary, primary.linked_prs[0]); + assert.strictEqual(sub.human_reason, "reviewer's question"); + assert.strictEqual(T.reasonOf(sub), "reviewer's question"); +}); diff --git a/src/pkg/dashboard/stage_tracker_decide_busy.test.js b/src/pkg/dashboard/stage_tracker_decide_busy.test.js new file mode 100644 index 0000000000..0f26c93a91 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_decide_busy.test.js @@ -0,0 +1,249 @@ +// "Let hive decide" shows it is working (hivecommons/hive#15773). The owner: +// "it takes a few seconds to open the dialog with what hive would do. can +// we have something - that is consistent with the rest of the activity +// tracker, that shows the button is working?" The clicked button goes +// disabled + aria-busy and reads "Asking the hive…" behind the tracker's +// working glyph, the row wears the in-flight caption, and the preview +// opens AT ONCE as a skeleton (Cancel live, the primary disabled) that +// fills when the plan lands; a fetch failure shows inline with Retry; a +// second click while the preview is open is ignored; a plan prefetched as +// the row's options came into view answers the click without a request. +// The functions are lifted out of index.html so this runs the shipped source. +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); + +function fn(name) { + const start = html.indexOf('function ' + name + '('); + assert.ok(start >= 0, name + ' not found in index.html'); + let decl = start; + if (html.slice(start - 6, start) === 'async ') decl -= 6; + let depth = 0; + for (let i = html.indexOf('{', start); i < html.length; i++) { + if (html[i] === '{') depth++; + else if (html[i] === '}' && --depth === 0) return html.slice(decl, i + 1); + } + assert.fail('unterminated ' + name); +} +function constLine(name) { + const m = html.match(new RegExp('const ' + name + ' = [^\\n]*\\n')); + assert.ok(m, name + ' not found in index.html'); + return m[0]; +} + +// The least DOM the preview needs: elements with classList, attributes, +// an innerHTML that materialises the buttons it names, querySelector by +// class, and a document that records appended overlays. +const dom = ` +function el(tag) { + const e = { tagName: tag, className: '', attrs: {}, children: [], parentNode: null, disabled: false, dataset: {}, _html: '', handlers: {}, + classList: { add(c) { if (!e.className.split(' ').includes(c)) e.className = (e.className + ' ' + c).trim(); }, remove(c) { e.className = e.className.split(' ').filter(x => x && x !== c).join(' '); }, contains(c) { return e.className.split(' ').includes(c); } }, + setAttribute(k, v) { e.attrs[k] = String(v); if (k === 'class') e.className = String(v); }, getAttribute(k) { return k in e.attrs ? e.attrs[k] : null; }, removeAttribute(k) { delete e.attrs[k]; }, + appendChild(c) { c.parentNode = e; e.children.push(c); return c; }, + remove() { if (e.parentNode) e.parentNode.children = e.parentNode.children.filter(c => c !== e); e.parentNode = null; }, + addEventListener(n, f) { e.handlers[n] = f; }, click() { if (e.disabled) return; if (e.handlers.click) e.handlers.click({ target: e }); }, + get firstElementChild() { return e.children[0] || null; }, + get textContent() { return e._html.replace(/<[^>]+>/g, ''); }, + querySelector(sel) { const cls = sel.replace(/^\\./, ''); const walk = n => { for (const c of n.children) { if (c.classList.contains(cls)) return c; const d = walk(c); if (d) return d; } return null; }; return walk(e); }, + querySelectorAll(sel) { const out = []; const walk = n => { for (const c of n.children) { if (sel.includes('[data-ham-key]') && c.attrs['data-ham-key'] != null) out.push(c); walk(c); } }; walk(e); return out; }, + }; + Object.defineProperty(e, 'innerHTML', { get() { return e._html; }, set(v) { + e._html = String(v); e.children = []; + const outer = e._html.match(/^
]*>([\\s\\S]*)<\\/div>$/); + if (outer) { const d = el('div'); d.className = outer[1]; e.appendChild(d); d.innerHTML = outer[2]; return; } + for (const m of e._html.matchAll(/]*)>([\\s\\S]*?)<\\/button>/g)) { + const b = el('button'); b.className = (m[1].match(/class="([^"]*)"/) || [, ''])[1]; b._html = m[2]; + b.disabled = /\\sdisabled\\b/.test(m[1]); if (/aria-disabled="true"/.test(m[1])) b.attrs['aria-disabled'] = 'true'; + if (/data-initial-focus/.test(m[1])) b.attrs['data-initial-focus'] = ''; + e.appendChild(b); + } + } }); + return e; +} +const body = el('body'); const panel = el('div'); +global.document = { body, getElementById: id => id === 'activity-monitor-panel' ? panel : null, createElement: el, createTextNode: v => ({ nodeValue: v, parentNode: null }) }; +global.hiveRememberModalOpen = x => x; +// The shared dialog wiring (tooltips-dialogs.js, covered by its own +// tests): Enter/click on the ok selector submits, Cancel closes null. +global.hiveWireDialog = (overlay, resolve, cancelValue, okSel, cancelSel, submit) => { + const close = v => { overlay.remove(); resolve(v); }; + overlay.hiveDialogClose = () => close(cancelValue); + const ok = overlay.querySelector(okSel); if (ok) ok.addEventListener('click', () => submit(close)); + const cancel = overlay.querySelector(cancelSel); if (cancel) cancel.addEventListener('click', () => close(cancelValue)); + return close; +}; +function esc(s) { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } +const toasts = []; global.showToast = (t, k) => toasts.push({ t, k }); +global.window = { _hiveUser: 'owner' }; +var _stageTracker = { items: [] }; +function stageTrackerItemKey(it) { return (it.repo || '') + '/' + (it.kind || '') + '#' + (Number(it.number) || 0); } +function stageTrackerRefOf(it) { return it.repo + '#' + it.number; } +function stageTrackerSentinelPreface() { return ''; } +function stageTrackerPRParked(it) { return Number(it.stage) === 85; } +function stageTrackerParkedNestedPRs() { return []; } +function stageTrackerNestedOpenPRs() { return []; } +function stageTrackerRunActions() { return { toasts: [], pending: [] }; } +function stageTrackerTargetKey(t) { return t ? stageTrackerItemKey(t) : ''; } +function stageTrackerItemState() { return ''; } +function stageTrackerItemByKey() { return null; } +function stageTrackerActionRequest(item, id) { return id === 'decide:delegate' ? { url: '/api/repos/' + item.repo + '/items/' + item.number + '/decide-delegated', body: { type: 'pr', head: item.head || '' } } : null; } +var _stageTrackerPending = []; +var _stageTrackerPlanPrefetch = {}; var _stageTrackerDelegateOpen = {}; +`; + +const src = [ + dom, + constLine('STAGE_TRACKER_PLAN_BUTTON_DELEGATE'), constLine('STAGE_TRACKER_PLAN_BUTTON_MERGE'), constLine('STAGE_TRACKER_PLAN_MERGE_ACTIONS'), + constLine('STAGE_TRACKER_PLAN_TITLE'), constLine('STAGE_TRACKER_PLAN_EYEBROW'), constLine('STAGE_TRACKER_PLAN_NEXT_MAX'), constLine('STAGE_TRACKER_PLAN_TITLE_MAX'), + constLine('STAGE_TRACKER_PLAN_RAILS'), constLine('STAGE_TRACKER_PLAN_MERGE_WHY'), constLine('STAGE_TRACKER_DELEGATE_ALL_MIN'), + constLine('STAGE_TRACKER_PLAN_PREFETCH_TTL_MS'), constLine('STAGE_TRACKER_PLAN_ASKING'), constLine('STAGE_TRACKER_PLAN_RETRY'), + fn('hiveDialogEscape'), fn('stageTrackerPlanSentence'), fn('stageTrackerPlanTruncate'), + fn('stageTrackerDelegatePlanView'), fn('stageTrackerDelegatePlanHtml'), fn('stageTrackerDelegatePlanVisibleText'), + fn('stageTrackerDelegatePlanMergeAction'), fn('stageTrackerDelegatePlanOffersMerge'), fn('stageTrackerDelegatePlanMergeLabel'), + fn('stageTrackerDelegatePlanMergeable'), fn('stageTrackerDelegatePlanMergeReason'), + fn('stageTrackerDecisionTarget'), fn('stageTrackerDelegateTargets'), + fn('stageTrackerPlanPrefetchKey'), fn('stageTrackerRequestDelegatePlan'), fn('stageTrackerPlanPrefetched'), + fn('stageTrackerFetchDelegatePlan'), fn('stageTrackerPrefetchDelegatePlans'), + fn('stageTrackerDelegatePlanSkeletonHtml'), fn('stageTrackerDelegatePlanErrorHtml'), fn('stageTrackerDelegatePlanDialog'), + fn('stageTrackerDelegateButtonBusy'), fn('stageTrackerDelegatePreview'), + fn('stageTrackerPendingSync'), fn('stageTrackerSetPending'), fn('stageTrackerClearPending'), + 'module.exports = { stageTrackerDelegatePreview, stageTrackerPrefetchDelegatePlans, stageTrackerDelegatePlanSkeletonHtml, body, panel, toasts, pending: () => _stageTrackerPending, resetCache: () => { _stageTrackerPlanPrefetch = {}; } };', +].join('\n'); +const m = { exports: {} }; +new Function('module', 'require', src)(m, require); +const T = m.exports; + +const PLAN = { would: 'approve', summary: 'Approve o/r#8 and let the merge queue take it.', why: 'CI is green and a reviewer approved it.', consequences: ['Hive posts /lgtm.'], mergeable_as_is: false, alternatives: [] }; +const item = { repo: 'o/r', kind: 'pr', number: 8, stage: 85, head: 'abc' }; +function button() { const b = T.body.appendChild(Object.assign(document.createElement('button'), {})); b.className = 'ham-lead-act'; b.innerHTML = 'Let hive decide'; return b; } +function deferredFetch() { + const calls = []; let release; + const gate = new Promise(r => { release = r; }); + global.fetch = async (url, init) => { calls.push({ url, body: JSON.parse(init.body) }); const r = await gate; return r; }; + return { calls, release: (ok, data) => release({ ok, status: ok ? 200 : 502, json: async () => data }) }; +} +const tick = () => new Promise(r => setImmediate(r)); +const overlay = () => T.body.children.find(c => c.className === 'hive-dialog-overlay') || null; + +test.beforeEach(() => { T.body.children = []; T.resetCache(); T.toasts.length = 0; }); + +test('click: busy button, in-flight row caption and an instant skeleton that fills with the plan', async () => { + const f = deferredFetch(); + const btn = button(); + const p = T.stageTrackerDelegatePreview([item], { button: btn }); + await tick(); + assert.strictEqual(btn.disabled, true, 'the button is disabled while the plan is fetched'); + assert.strictEqual(btn.getAttribute('aria-busy'), 'true'); + assert.ok(btn.innerHTML.includes('Asking the hive…') && btn.innerHTML.includes('cue-acting-spin'), 'the label swaps to the working glyph + text: ' + btn.innerHTML); + assert.ok(btn.classList.contains('ham-asking')); + assert.deepStrictEqual(T.pending().map(x => x.caption), ['Asking the hive…'], 'the row wears the tracker\'s in-flight caption'); + const ov = overlay(); + assert.ok(ov, 'the preview opens before the plan is back'); + const dialog = ov.firstElementChild; + assert.ok(dialog.innerHTML.includes('ham-plan-skeleton') && dialog.innerHTML.includes('aria-busy="true"'), 'it opens as a skeleton'); + assert.ok(dialog.innerHTML.includes('Let hive decide') && dialog.innerHTML.includes('o/r#8'), 'title and subject are real'); + assert.ok(dialog.innerHTML.includes('ham-plan-placeholder'), 'placeholder lines stand where the plan goes'); + assert.strictEqual(dialog.querySelector('.primary').disabled, true, 'Confirm is disabled on the skeleton'); + assert.strictEqual(dialog.querySelector('.cancel').disabled, false, 'Cancel is live on the skeleton'); + assert.strictEqual(f.calls.length, 1); + assert.strictEqual(f.calls[0].body.head, 'abc', 'the head rides the request for the server cache key'); + f.release(true, PLAN); + await tick(); await tick(); + assert.ok(!dialog.innerHTML.includes('ham-plan-skeleton'), 'the skeleton gives way to the plan'); + assert.ok(dialog.innerHTML.includes('Approve o/r#8'), dialog.innerHTML); + assert.strictEqual(dialog.querySelector('.primary').disabled, false, 'Confirm is live once the plan is in'); + assert.strictEqual(btn.disabled, false, 'the button restores'); + assert.strictEqual(btn.getAttribute('aria-busy'), null); + assert.strictEqual(btn.innerHTML, 'Let hive decide'); + assert.deepStrictEqual(T.pending(), [], 'the row caption lifts'); + dialog.querySelector('.primary').click(); + assert.deepStrictEqual(await p, { chosen: 'Let hive do that · previewed approve' }); + assert.strictEqual(overlay(), null, 'the dialog closes'); +}); + +test('a second click while the preview is open is ignored', async () => { + const f = deferredFetch(); + const btn = button(); + const first = T.stageTrackerDelegatePreview([item], { button: btn }); + const second = T.stageTrackerDelegatePreview([item], { button: btn }); + assert.strictEqual(await second, null, 'the double click runs nothing'); + await tick(); + assert.strictEqual(f.calls.length, 1, 'one plan request'); + assert.strictEqual(T.body.children.filter(c => c.className === 'hive-dialog-overlay').length, 1, 'one dialog'); + f.release(true, PLAN); + await tick(); await tick(); + overlay().querySelector('.cancel').click(); + assert.strictEqual(await first, null); + // Once closed, the row can be asked again (cache cleared so it fetches). + T.resetCache(); + const f2 = deferredFetch(); + const again = T.stageTrackerDelegatePreview([item], { button: btn }); + await tick(); + assert.strictEqual(f2.calls.length, 1); + f2.release(true, PLAN); await tick(); await tick(); + overlay().querySelector('.cancel').click(); + assert.strictEqual(await again, null); +}); + +test('a failed plan shows inline with Retry; Retry fetches again and fills', async () => { + const f = deferredFetch(); + const btn = button(); + const p = T.stageTrackerDelegatePreview([item], { button: btn }); + await tick(); + f.release(false, { error: 'GitHub 502' }); + await tick(); await tick(); + const dialog = overlay().firstElementChild; + assert.ok(dialog.innerHTML.includes('ham-plan-error') && dialog.innerHTML.includes('Could not preview: o/r#8 (GitHub 502)'), dialog.innerHTML); + assert.ok(dialog.querySelector('.ham-plan-retry'), 'Retry is offered'); + assert.ok(dialog.querySelector('.cancel'), 'Cancel stays'); + assert.strictEqual(btn.disabled, false, 'the button restores on error'); + assert.strictEqual(T.toasts.length, 0, 'the error is in the dialog, not a toast'); + const f2 = deferredFetch(); + dialog.querySelector('.ham-plan-retry').click(); + await tick(); + assert.strictEqual(f2.calls.length, 1, 'Retry asks again'); + assert.ok(dialog.innerHTML.includes('ham-plan-skeleton'), 'Retry shows the skeleton again'); + f2.release(true, PLAN); + await tick(); await tick(); + assert.ok(dialog.innerHTML.includes('Approve o/r#8')); + dialog.querySelector('.primary').click(); + assert.deepStrictEqual(await p, { chosen: 'Let hive do that · previewed approve' }); +}); + +test('a plan prefetched as the options came into view answers the click without a request', async () => { + const f = deferredFetch(); + T.stageTrackerPrefetchDelegatePlans([item]); + await tick(); + assert.strictEqual(f.calls.length, 1); + assert.strictEqual(f.calls[0].body.prefetch, true, 'the prefetch says so'); + T.stageTrackerPrefetchDelegatePlans([item]); + assert.strictEqual(f.calls.length, 1, 'a warm row is not asked twice'); + f.release(true, PLAN); + await tick(); await tick(); + const btn = button(); + const p = T.stageTrackerDelegatePreview([item], { button: btn }); + await tick(); await tick(); + assert.strictEqual(f.calls.length, 1, 'the click reuses the prefetched plan'); + const dialog = overlay().firstElementChild; + assert.ok(dialog.innerHTML.includes('Approve o/r#8'), 'the plan is in at once'); + dialog.querySelector('.cancel').click(); + assert.strictEqual(await p, null); + // A new head is a new plan. + const f2 = deferredFetch(); + T.stageTrackerPrefetchDelegatePlans([Object.assign({}, item, { head: 'def' })]); + await tick(); + assert.strictEqual(f2.calls.length, 1, 'a pushed head is fetched afresh'); + f2.release(true, PLAN); +}); + +test('the skeleton is honest markup: real title, status role for the working line, disabled primary', () => { + const h = T.stageTrackerDelegatePlanSkeletonHtml([item], ''); + assert.ok(h.includes('class="hive-dialog-title">Let hive decide<')); + assert.ok(h.includes('role="status"') && h.includes('toast-spinner cue-acting-spin'), 'the working line reuses the tracker\'s acting glyph'); + assert.ok(/class="[^"]*primary" disabled aria-disabled="true"/.test(h)); + assert.ok(!/class="[^"]*cancel"[^>]*disabled/.test(h), 'Cancel is never disabled'); + assert.ok(!h.includes('style='), 'no inline styles'); +}); diff --git a/src/pkg/dashboard/stage_tracker_human_reason.go b/src/pkg/dashboard/stage_tracker_human_reason.go new file mode 100644 index 0000000000..0f1a3c9c5e --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_human_reason.go @@ -0,0 +1,237 @@ +package dashboard + +import ( + "slices" + "strconv" + "strings" + "unicode/utf8" +) + +// Owner (hivecommons/hive#15773): "when i see 'pr in progress' on the +// chevron - i have no idea when it needs a human at that stage". The 👤 +// marker on a lit chevron must always come with its reason: the chevron +// word names what the person is wanted for ("PR in progress · #15759 +// needs a decision", "Ready for human merge · workflow files"), and the +// full question stays in the tooltip. stageTrackerHumanReason is the ONE +// place that reason is worded, from the fields the payload already +// carries; stageTrackerResolveHumanReasons stamps it on every item (and +// nested PR) whose next move is a person's, so the SPA never draws the +// marker alone. +// +// The same pass settles the covered-issue rule the owner raised on +// #15503: an issue riding a PR that waits on a decision does not inherit +// the PR's actionable chip — it carries decision_pending_on (the PR +// number) and a caption that says the PR is what waits — only the PR row +// offers "Let hive decide". + +// stageTrackerHumanReasonMax bounds the chevron's reason: a few words, +// never a sentence (the tooltip has the sentence). +const stageTrackerHumanReasonMax = 40 + +// Chevron reasons shared by more than one place. +const ( + humanReasonNeedsDecision = "needs a decision" + humanReasonSentinel = "security finding" + humanReasonTriage = "needs triage" + humanReasonPriorArt = "confirm prior art" + humanReasonAdvisory = "read & close" + humanReasonHumanMerge = "a maintainer merges" + humanReasonRedundant = "close as redundant?" + humanReasonReviewerQuery = "reviewer's question" + humanReasonPermissions = "hive not permitted" + humanReasonEscalated = "flagged needs-human" + humanReasonSupersededClose = "superseded — close?" + humanReasonWaitsOnPerson = "waits on a person" +) + +// stageTrackerHumanReason words why a person is the next mover on it, in +// at most stageTrackerHumanReasonMax characters; "" when the item's next +// move is not a person's. covering is the PR an issue rides (nil for a PR +// or an issue riding nothing in the snapshot). +func stageTrackerHumanReason(it StageTrackerItem, covering *StageTrackerItem) string { + if it.StageActor == nil || it.StageActor.Kind != StageActorHuman { + return "" + } + return stageTrackerHumanReasonClip(stageTrackerHumanReasonWords(it, covering)) +} + +func stageTrackerHumanReasonWords(it StageTrackerItem, covering *StageTrackerItem) string { + // An issue riding its PR: the PR is what waits on the person. + if covering != nil && it.Kind == "issue" { + ref := "#" + strconv.Itoa(covering.Number) + if why := stageTrackerHumanReasonWords(*covering, nil); why != "" { + return ref + " " + stageTrackerHumanReasonForPR(why, covering) + } + return ref + " " + humanReasonWaitsOnPerson + } + if it.Superseded != nil && it.Superseded.CloserPR > 0 { + return humanReasonSupersededClose + } + if it.SentinelAlert { + return humanReasonSentinel + } + if adv := it.Advisory; adv != nil { + return humanReasonAdvisory + } + if d := it.DecisionNeeded; d != nil { + if d.RedundantOf > 0 { + return humanReasonRedundant + } + switch d.AskedBy { + case decisionAskedBySentinel: + return humanReasonSentinel + case decisionAskedByReviewer: + return humanReasonReviewerQuery + case decisionAskedByApp, decisionAskedByBlocker: + return humanReasonPermissions + case decisionAskedByEscalation: + return humanReasonEscalated + case decisionAskedByTriage: + return humanReasonTriage + } + } + switch it.Stage { + case trackerNumberTriageNeeded: + return humanReasonTriage + case trackerNumberPossiblyExists: + return humanReasonPriorArt + case trackerNumberNeedsDecision, trackerNumberIssueDecision: + if step, _ := stageTrackerUnauthorized(it.Reason); step != "" { + return humanReasonPermissions + } + return humanReasonNeedsDecision + case trackerNumberReadyForHuman: + if _, word, _ := stageTrackerHumanMergeReason(it.Reason); word != "" { + return word + } + return humanReasonHumanMerge + case trackerNumberFixing: + return stageTrackerHumanReasonAuthor(it, "pushes a fix") + case trackerNumberNeedsAuthor, trackerNumberReturned: + return stageTrackerHumanReasonAuthor(it, "must act") + } + if slices.Contains(it.Modifiers, modNeedsDecision) || slices.Contains(it.Modifiers, modNeedsHuman) { + return humanReasonNeedsDecision + } + // The actor line's own words, clipped: never an empty reason. + if why := strings.TrimSpace(it.StageActor.Why); why != "" { + return why + } + return humanReasonWaitsOnPerson +} + +// stageTrackerHumanReasonForPR turns a PR's own reason into the clause an +// issue's chevron reads after "#N": "needs a decision" stays, a merge-gate +// word becomes "needs a human merge", an author clause keeps its verb. +func stageTrackerHumanReasonForPR(why string, pr *StageTrackerItem) string { + switch pr.Stage { + case trackerNumberReadyForHuman: + return "needs a human merge" + case trackerNumberNeedsDecision, trackerNumberIssueDecision: + if why == humanReasonSentinel || why == humanReasonPermissions || why == humanReasonRedundant { + return humanReasonNeedsDecision + " · " + why + } + return humanReasonNeedsDecision + } + return why +} + +func stageTrackerHumanReasonAuthor(it StageTrackerItem, verb string) string { + if a := strings.TrimSpace(it.Author); a != "" { + return "@" + a + " " + verb + } + return "the author " + verb +} + +// stageTrackerHumanReasonClip trims to the budget on a word boundary. +func stageTrackerHumanReasonClip(s string) string { + s = strings.TrimSpace(s) + if utf8.RuneCountInString(s) <= stageTrackerHumanReasonMax { + return s + } + runes := []rune(s) + cut := stageTrackerHumanReasonMax - 1 + for i := cut; i > stageTrackerHumanReasonMax/2; i-- { + if runes[i] == ' ' { + cut = i + break + } + } + return strings.TrimRight(string(runes[:cut]), " ,;—-·") + "…" +} + +// stageTrackerCoveredDecisionCaption is the covered issue's caption while +// its PR waits on a decision: the PR is what waits, not the issue. +func stageTrackerCoveredDecisionCaption(pr int) string { + return "Covered by PR #" + strconv.Itoa(pr) + " — waiting for a decision on the PR" +} + +// stageTrackerLeadLinkedPR is the linked PR an issue rides: the one drawn +// under this issue, else the first listed; nil without linked PRs. +func stageTrackerLeadLinkedPR(it *StageTrackerItem) *StageTrackerLinkedPR { + if len(it.LinkedPRs) == 0 { + return nil + } + for j := range it.LinkedPRs { + if lp := &it.LinkedPRs[j]; lp.DrawnUnder == 0 || lp.DrawnUnder == it.Number { + return lp + } + } + return &it.LinkedPRs[0] +} + +// stageTrackerIssueRidesPR reports an issue whose actor and caption are +// its covering PR's (the same test stageTrackerResolveActors applies). +func stageTrackerIssueRidesPR(it *StageTrackerItem) bool { + return it.Kind == "issue" && !slices.Contains(it.Modifiers, modHold) && + (it.Mirrored || it.Stage == trackerNumberPRInProgress || it.Stage == trackerNumberCoveredByPR || it.Actor == "its PR") +} + +// stageTrackerResolveHumanReasons runs after stageTrackerResolveActors: +// every item whose next mover is a person carries human_reason; nested +// PRs carry their PR's; an issue riding a PR parked on a decision carries +// decision_pending_on and the covered-decision caption. +func stageTrackerResolveHumanReasons(items []StageTrackerItem) { + prs := map[string]*StageTrackerItem{} + for i := range items { + if items[i].Kind == "pr" { + prs[items[i].Repo+"#"+strconv.Itoa(items[i].Number)] = &items[i] + } + } + for i := range items { + it := &items[i] + if it.Kind == "pr" { + it.HumanReason = stageTrackerHumanReason(*it, nil) + } + } + for i := range items { + it := &items[i] + if it.Kind != "issue" { + continue + } + for j := range it.LinkedPRs { + if pr := prs[it.Repo+"#"+strconv.Itoa(it.LinkedPRs[j].Number)]; pr != nil { + it.LinkedPRs[j].HumanReason = pr.HumanReason + } + } + var covering *StageTrackerItem + if stageTrackerIssueRidesPR(it) { + if lead := stageTrackerLeadLinkedPR(it); lead != nil { + covering = prs[it.Repo+"#"+strconv.Itoa(lead.Number)] + } + } + if covering != nil && stageTrackerPRWaitsOnDecision(covering) { + it.DecisionPendingOn = covering.Number + it.DecisionNeeded = nil + it.Caption = stageTrackerCoveredDecisionCaption(covering.Number) + } + it.HumanReason = stageTrackerHumanReason(*it, covering) + } +} + +// stageTrackerPRWaitsOnDecision: the PR is parked at 085 on a person's +// decision. Other human stops (071 needs-author, 090 human merge) keep the +// issue's ordinary "Covered by PR #N — " narration. +func stageTrackerPRWaitsOnDecision(pr *StageTrackerItem) bool { + return pr.Stage == trackerNumberNeedsDecision && pr.StageActor != nil && pr.StageActor.Kind == StageActorHuman +} diff --git a/src/pkg/dashboard/stage_tracker_human_reason_test.go b/src/pkg/dashboard/stage_tracker_human_reason_test.go new file mode 100644 index 0000000000..31849487b6 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_human_reason_test.go @@ -0,0 +1,168 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + "unicode/utf8" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine/prstage" +) + +// TestStageTrackerHumanReasonNeverShipsBareMarker (hivecommons/hive#15773, +// "when i see 'pr in progress' on the chevron - i have no idea when it +// needs a human at that stage"): every item whose actor is a person +// carries a short human_reason, across every stage, kind and parking +// flag the actor logic knows. +func TestStageTrackerHumanReasonNeverShipsBareMarker(t *testing.T) { + now := time.Date(2026, 10, 28, 18, 0, 0, 0, time.UTC) + stages := []int{0, trackerNumberActionable, trackerNumberTriageNeeded, trackerNumberPossiblyExists, trackerNumberClaimed, trackerNumberPRInProgress, trackerNumberCoveredByPR, trackerNumberIssueDecision, trackerNumberReviewPending, trackerNumberReviewed, trackerNumberFixing, trackerNumberNeedsAuthor, trackerNumberReturned, trackerNumberAdopted, trackerNumberAwaitingMerge, trackerNumberNeedsDecision, trackerNumberReadyForHuman, trackerNumberPreMergeSoak} + variants := []func(*StageTrackerItem){ + func(*StageTrackerItem) {}, + func(it *StageTrackerItem) { it.Modifiers = []string{modNeedsHuman} }, + func(it *StageTrackerItem) { it.Modifiers = []string{modNeedsDecision} }, + func(it *StageTrackerItem) { + it.Modifiers = []string{modUnauthorized} + it.Reason = prstage.StageReasonUnauthorizedPrefix + prstage.UnauthorizedStepApproveWorkflowRuns + }, + func(it *StageTrackerItem) { it.SentinelAlert = true; it.SentinelReason = "secret in diff" }, + func(it *StageTrackerItem) { it.Advisory = &StageTrackerAdvisory{Caption: "advisory"} }, + func(it *StageTrackerItem) { + it.DecisionNeeded = &StageTrackerDecision{AskedBy: decisionAskedByReviewer, Question: "Is the schema change intended?"} + }, + func(it *StageTrackerItem) { + it.DecisionNeeded = &StageTrackerDecision{AskedBy: decisionAskedBySentinel} + }, + func(it *StageTrackerItem) { + it.DecisionNeeded = &StageTrackerDecision{AskedBy: decisionAskedByReviewer, RedundantOf: 41} + }, + func(it *StageTrackerItem) { it.Superseded = &github.ReviewQueueSuperseded{CloserPR: 77} }, + func(it *StageTrackerItem) { + it.Reason = prstage.ContributorLaneReasonWorkflowPath + it.ManualMerge = true + }, + } + seen := 0 + for _, kind := range []string{"pr", "issue"} { + for _, ak := range []string{authorKindHuman, authorKindHive, authorKindClanker, ""} { + for _, st := range stages { + for vi, v := range variants { + it := StageTrackerItem{Kind: kind, Repo: "acme/docs", Number: 1000 + vi, Author: "pat", AuthorKind: ak, Stage: st} + v(&it) + it.StageActor = stageTrackerStageActor(it, nil, now) + if it.StageActor == nil || it.StageActor.Kind != StageActorHuman { + continue + } + seen++ + got := stageTrackerHumanReason(it, nil) + if got == "" { + t.Errorf("%s stage %03d variant %d (%s): human marker without human_reason (why=%q)", kind, st, vi, ak, it.StageActor.Why) + continue + } + if n := utf8.RuneCountInString(got); n > stageTrackerHumanReasonMax { + t.Errorf("%s stage %03d variant %d: human_reason %q is %d runes (max %d)", kind, st, vi, got, n, stageTrackerHumanReasonMax) + } + } + } + } + } + if seen < 20 { + t.Fatalf("only %d human-actor variants exercised; the matrix no longer reaches the human branches", seen) + } + if got := stageTrackerHumanReason(StageTrackerItem{Kind: "pr", Stage: trackerNumberFixing, StageActor: &StageTrackerActor{Kind: StageActorHive}}, nil); got != "" { + t.Fatalf("a hive-actor row must not carry a human_reason, got %q", got) + } +} + +// TestStageTrackerHumanReasonWords: the chevron clause names what the +// person is wanted for, in the words the owner asked for. +func TestStageTrackerHumanReasonWords(t *testing.T) { + human := &StageTrackerActor{Kind: StageActorHuman, Why: "a maintainer must decide"} + for _, tc := range []struct { + name string + it StageTrackerItem + want string + }{ + {"085", StageTrackerItem{Kind: "pr", Stage: trackerNumberNeedsDecision, StageActor: human}, "needs a decision"}, + {"085 reviewer", StageTrackerItem{Kind: "pr", Stage: trackerNumberNeedsDecision, StageActor: human, DecisionNeeded: &StageTrackerDecision{AskedBy: decisionAskedByReviewer}}, "reviewer's question"}, + {"085 redundant", StageTrackerItem{Kind: "pr", Stage: trackerNumberNeedsDecision, StageActor: human, DecisionNeeded: &StageTrackerDecision{AskedBy: decisionAskedByReviewer, RedundantOf: 9}}, "close as redundant?"}, + {"sentinel", StageTrackerItem{Kind: "pr", Stage: trackerNumberNeedsDecision, StageActor: human, SentinelAlert: true}, "security finding"}, + {"045", StageTrackerItem{Kind: "issue", Stage: trackerNumberIssueDecision, StageActor: human}, "needs a decision"}, + {"045 unauthorized", StageTrackerItem{Kind: "issue", Stage: trackerNumberIssueDecision, StageActor: human, Reason: prstage.StageReasonUnauthorizedPrefix + prstage.UnauthorizedStepApproveWorkflowRuns}, "hive not permitted"}, + {"090 workflow files", StageTrackerItem{Kind: "pr", Stage: trackerNumberReadyForHuman, StageActor: human, Reason: prstage.ContributorLaneReasonWorkflowPath}, "workflow files"}, + {"090 plain", StageTrackerItem{Kind: "pr", Stage: trackerNumberReadyForHuman, StageActor: human}, "a maintainer merges"}, + {"advisory", StageTrackerItem{Kind: "issue", Stage: trackerNumberActionable, StageActor: human, Advisory: &StageTrackerAdvisory{Caption: "x"}}, "read & close"}, + {"triage", StageTrackerItem{Kind: "issue", Stage: trackerNumberTriageNeeded, StageActor: human}, "needs triage"}, + {"prior art", StageTrackerItem{Kind: "issue", Stage: trackerNumberPossiblyExists, StageActor: human}, "confirm prior art"}, + {"070 human author", StageTrackerItem{Kind: "pr", Stage: trackerNumberFixing, Author: "pat", StageActor: human}, "@pat pushes a fix"}, + {"071", StageTrackerItem{Kind: "pr", Stage: trackerNumberNeedsAuthor, Author: "pat", StageActor: human}, "@pat must act"}, + {"superseded", StageTrackerItem{Kind: "pr", Stage: trackerNumberReturned, StageActor: human, Superseded: &github.ReviewQueueSuperseded{CloserPR: 3}}, "superseded — close?"}, + {"fallback clips the why", StageTrackerItem{Kind: "pr", Stage: trackerNumberReviewed, StageActor: &StageTrackerActor{Kind: StageActorHuman, Why: "the hive is waiting for the repository owner to flip the switch on auto-merge"}}, "the hive is waiting for the repository…"}, + } { + if got := stageTrackerHumanReason(tc.it, nil); got != tc.want { + t.Errorf("%s: human_reason = %q, want %q", tc.name, got, tc.want) + } + } + covering := &StageTrackerItem{Kind: "pr", Number: 15759, Stage: trackerNumberNeedsDecision, StageActor: human} + if got := stageTrackerHumanReason(StageTrackerItem{Kind: "issue", Stage: trackerNumberCoveredByPR, StageActor: human}, covering); got != "#15759 needs a decision" { + t.Fatalf("covered issue human_reason = %q", got) + } + covering.Stage, covering.Reason = trackerNumberReadyForHuman, prstage.ContributorLaneReasonWorkflowPath + if got := stageTrackerHumanReason(StageTrackerItem{Kind: "issue", Stage: trackerNumberCoveredByPR, StageActor: human}, covering); got != "#15759 needs a human merge" { + t.Fatalf("covered issue (090 PR) human_reason = %q", got) + } +} + +// TestStageTrackerCoveredIssueDecisionPending (hivecommons/hive#15773: +// #15503, a secondary issue "under #15502" covered by PR #15759 at 085, +// showed the PR's "Let hive decide" chip and "PR in progress 👤"): the +// issues riding a PR parked on a decision carry decision_pending_on, the +// covered-decision caption and a human_reason that names the PR; the PR +// alone keeps decision_needed. +func TestStageTrackerCoveredIssueDecisionPending(t *testing.T) { + human := &StageTrackerActor{Kind: StageActorHuman, Login: "", Why: "a maintainer must decide: the reviewer asked whether the schema change is intended"} + decision := &StageTrackerDecision{AskedBy: decisionAskedByReviewer, Question: "Is the schema change intended?"} + lp := StageTrackerLinkedPR{Number: 15759, DrawnUnder: 15502, DecisionNeeded: decision} + items := []StageTrackerItem{ + {Kind: "issue", Repo: "acme/docs", Number: 15502, Stage: trackerNumberCoveredByPR, Caption: "Covered by PR #15759 — a maintainer must decide", LinkedPRs: []StageTrackerLinkedPR{lp}, DecisionNeeded: decision, StageActor: &StageTrackerActor{Kind: StageActorHive}}, + {Kind: "issue", Repo: "acme/docs", Number: 15503, Stage: trackerNumberCoveredByPR, Caption: "Covered by PR #15759 — a maintainer must decide", LinkedPRs: []StageTrackerLinkedPR{lp}, DecisionNeeded: decision, StageActor: &StageTrackerActor{Kind: StageActorHive}}, + {Kind: "pr", Repo: "acme/docs", Number: 15759, Stage: trackerNumberNeedsDecision, DecisionNeeded: decision, StageActor: human}, + // A covered issue whose PR is simply being worked: no pending chip. + {Kind: "issue", Repo: "acme/docs", Number: 15600, Stage: trackerNumberCoveredByPR, LinkedPRs: []StageTrackerLinkedPR{{Number: 15601}}, StageActor: &StageTrackerActor{Kind: StageActorHive}}, + {Kind: "pr", Repo: "acme/docs", Number: 15601, Stage: trackerNumberReviewPending, StageActor: &StageTrackerActor{Kind: StageActorHive}}, + } + stageTrackerResolveActors(items) + stageTrackerResolveHumanReasons(items) + byNum := map[int]StageTrackerItem{} + for _, it := range items { + byNum[it.Number] = it + } + for _, n := range []int{15502, 15503} { + it := byNum[n] + if it.DecisionPendingOn != 15759 { + t.Errorf("#%d decision_pending_on = %d, want 15759", n, it.DecisionPendingOn) + } + if it.DecisionNeeded != nil { + t.Errorf("#%d still carries decision_needed; only the PR row offers the decision", n) + } + if it.Caption != "Covered by PR #15759 — waiting for a decision on the PR" { + t.Errorf("#%d caption = %q", n, it.Caption) + } + if it.StageActor == nil || it.StageActor.Kind != StageActorHuman { + t.Errorf("#%d actor = %+v, want the PR's human actor", n, it.StageActor) + } + if it.HumanReason != "#15759 needs a decision" { + t.Errorf("#%d human_reason = %q", n, it.HumanReason) + } + if len(it.LinkedPRs) != 1 || it.LinkedPRs[0].HumanReason != "reviewer's question" { + t.Errorf("#%d linked PR human_reason = %+v", n, it.LinkedPRs) + } + } + if pr := byNum[15759]; pr.DecisionNeeded == nil || pr.DecisionPendingOn != 0 || pr.HumanReason != "reviewer's question" { + t.Fatalf("PR row = decision_needed %v pending_on %d reason %q", pr.DecisionNeeded != nil, pr.DecisionPendingOn, pr.HumanReason) + } + if it := byNum[15600]; it.DecisionPendingOn != 0 || it.HumanReason != "" || !strings.HasPrefix(it.Caption, "") { + t.Fatalf("issue riding a working PR: pending_on %d reason %q", it.DecisionPendingOn, it.HumanReason) + } +} diff --git a/src/pkg/dashboard/stage_tracker_lead_action_test.go b/src/pkg/dashboard/stage_tracker_lead_action_test.go index ea28fc7b66..af3f7b940b 100644 --- a/src/pkg/dashboard/stage_tracker_lead_action_test.go +++ b/src/pkg/dashboard/stage_tracker_lead_action_test.go @@ -23,7 +23,7 @@ func TestStageTrackerLeadActionInline(t *testing.T) { for _, want := range []string{ `class="ham-lead-act`, `e.target.closest('.ham-lead-act[data-ham-act]')`, - `stageTrackerDecisionRun(item, b.dataset.hamAct)`, + `stageTrackerDecisionRun(item, b.dataset.hamAct, b)`, `stageTrackerChipsHtml(shown) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(item, nowMs, subRows) : '')`, `stageTrackerChipsHtml(pr) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(pr, nowMs) : '')`, `.ham-lead-act[aria-disabled="true"]`, diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index 5319d9c6cb..d87abac03c 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -431,6 +431,8 @@ func TestStageTrackerMotionRowStamp(t *testing.T) { jsConstLine(t, html, "STAGE_TRACKER_MOTION_HUMAN_MODS"), jsFunc(t, html, "stageTrackerMotion"), jsFunc(t, html, "stageTrackerShortAgo"), + jsFunc(t, html, "stageTrackerHumanReasonOf"), + jsFunc(t, html, "stageTrackerHumanReasonHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), @@ -564,6 +566,8 @@ func TestStageTrackerMotionPreviewSample(t *testing.T) { jsFunc(t, html, "stageTrackerHeaderHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerHumanReasonOf"), + jsFunc(t, html, "stageTrackerHumanReasonHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), diff --git a/src/pkg/dashboard/stage_tracker_new_test.go b/src/pkg/dashboard/stage_tracker_new_test.go index 367f4333b8..56377e184b 100644 --- a/src/pkg/dashboard/stage_tracker_new_test.go +++ b/src/pkg/dashboard/stage_tracker_new_test.go @@ -293,6 +293,8 @@ func TestStageTrackerNewRowRendering(t *testing.T) { jsFunc(t, html, "stageTrackerActorTip"), jsFunc(t, html, "stageTrackerHeadline"), jsFunc(t, html, "stageTrackerSegments"), + jsFunc(t, html, "stageTrackerHumanReasonOf"), + jsFunc(t, html, "stageTrackerHumanReasonHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerTooltip"), }, "\n") + ` diff --git a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go index ce2e5e117d..e353b02a28 100644 --- a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go +++ b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go @@ -152,6 +152,8 @@ func stageTrackerRepoGroupingHarness(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerMotion"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerHumanReasonOf"), + jsFunc(t, html, "stageTrackerHumanReasonHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 64f5d0d02c..914924b65b 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -96,6 +96,9 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerLeadAction"), jsFunc(t, html, "stageTrackerMaintainerMoved"), jsFunc(t, html, "stageTrackerDevWarn"), + jsFunc(t, html, "stageTrackerDecisionPendingOn"), + jsFunc(t, html, "stageTrackerDecisionPendingChipHtml"), + jsFunc(t, html, "stageTrackerLeadDrawnElsewhere"), jsFunc(t, html, "stageTrackerLeadActionOnRow"), jsFunc(t, html, "stageTrackerLeadActionHtml"), jsFunc(t, html, "stageTrackerMenuTextHtml"), @@ -784,7 +787,7 @@ function stageTrackerAfterActions() {} return { ok: true, status: 200, json: async () => ({ status: 'done', result: { action: STAGE_TRACKER_ACTION_NOOP, target: { repo: issue.repo, kind: 'pr', number }, outcome: 'No change' } }) }; }; for (const selected of [[issue], [issue, a, b], [b, issue, a]]) { - calls.length = 0; dialogs.length = 0; + calls.length = 0; dialogs.length = 0; _stageTrackerPlanPrefetch = {}; // a fresh click, not the cached plan (#15773) await runRowAction('decide:delegate', selected); // Let hive decide previews first: one plan call per PR, then one // decide call per PR after the operator picks (#15126). @@ -808,7 +811,7 @@ function stageTrackerAfterActions() {} // one parked PR (of two open) delegates that PR alone — never the other // in-flight PR, which only the explicit delegate-all touches. for (const selected of [oneParked, [oneParked], [oneParked, b]]) { - calls.length = 0; dialogs.length = 0; + calls.length = 0; dialogs.length = 0; _stageTrackerPlanPrefetch = {}; // a fresh click, not the cached plan (#15773) await runRowAction('decide:delegate', selected); assert.deepStrictEqual(calls.filter(c => !c.url.endsWith('/plan')).map(c => c.url), ['/api/repos/hivecommons/hive/items/15020/decide-delegated']); assert.strictEqual(dialogs.length, 1); @@ -861,14 +864,25 @@ func stageTrackerConfirmOptOutJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerDelegatePlanMergeLabel"), jsFunc(t, html, "stageTrackerDelegatePlanMergeable"), jsFunc(t, html, "stageTrackerDelegatePlanMergeReason"), + jsConstLine(t, html, "STAGE_TRACKER_PLAN_PREFETCH_TTL_MS"), + jsConstLine(t, html, "STAGE_TRACKER_PLAN_ASKING"), + jsConstLine(t, html, "STAGE_TRACKER_PLAN_RETRY"), + "var _stageTrackerPlanPrefetch = {}; var _stageTrackerDelegateOpen = {};", + jsFunc(t, html, "stageTrackerPlanPrefetchKey"), + jsFunc(t, html, "stageTrackerRequestDelegatePlan"), + jsFunc(t, html, "stageTrackerPlanPrefetched"), jsFunc(t, html, "stageTrackerFetchDelegatePlan"), + jsFunc(t, html, "stageTrackerPrefetchDelegatePlans"), + jsFunc(t, html, "stageTrackerDelegateButtonBusy"), jsFunc(t, html, "stageTrackerDelegatePreview"), jsFunc(t, html, "stageTrackerActionPayload"), jsFunc(t, html, "stageTrackerDirectionCarrier"), // The preview dialog is recorded like the confirms; its answer is - // the "Let hive do that" button unless a test sets planAnswer. + // the "Let hive do that" button unless a test sets planAnswer. A + // plan that failed to fetch is recorded as an error dialog and + // answers Cancel (hivecommons/hive#15773). `let planAnswer = null; -function stageTrackerDelegatePlanDialog(plans, sentinel) { const view = stageTrackerDelegatePlanView(plans, sentinel); const html = stageTrackerDelegatePlanHtml(view); dialogs.push({ kind: 'plan', cfg: { title: view.title, message: stageTrackerDelegatePlanVisibleText(html), html, view, plans } }); return Promise.resolve(planAnswer === null ? { chosen: 'Let hive do that · previewed ' + plans.map(p => p.would || '?').join('/') } : planAnswer); }`, +async function stageTrackerDelegatePlanDialog(items, sentinel, fetchPlans) { const plans = await fetchPlans(false); const failed = plans.filter(pl => pl.error); if (failed.length) { dialogs.push({ kind: 'plan-error', cfg: { failed } }); return null; } const view = stageTrackerDelegatePlanView(plans, sentinel); const html = stageTrackerDelegatePlanHtml(view); dialogs.push({ kind: 'plan', cfg: { title: view.title, message: stageTrackerDelegatePlanVisibleText(html), html, view, plans } }); return planAnswer === null ? { chosen: 'Let hive do that · previewed ' + plans.map(p => p.would || '?').join('/') } : planAnswer; }`, `const store = {}; global.localStorage = { getItem: k => (k in store ? store[k] : null), setItem: (k, v) => { store[k] = String(v); }, removeItem: k => { delete store[k]; } }; global.window = { _hiveUser: 'clubanderson' }; const dialogs = []; let dialogAnswer = true; diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index 7b5cb5ead3..192c39bd7a 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -93,6 +93,8 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerTrainIconHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerHumanReasonOf"), + jsFunc(t, html, "stageTrackerHumanReasonHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 4579caa97d..d49fe44e66 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -34,6 +34,13 @@ .ham-chip:hover { color: var(--text); border-color: var(--line-strong); } .ham-chip[hidden] { display: none; } .ham-chip .ham-chip-n { color: var(--text-faint); margin-left: var(--sp-1); } + /* A covered issue's passive "decision pending on #N" chip: muted, + never a call to action, scrolls to the PR row that holds the button. */ + .ham-chip-passive { color: var(--text-faint); border-style: dashed; font-weight: var(--fw-medium); } + .ham-chip-passive:hover { color: var(--muted); border-color: var(--line); } + /* The reason after the chevron word ("PR in progress · #N needs a + decision"): quieter than the word, never wraps on its own. */ + .ham-human-reason { color: var(--muted); font-weight: var(--fw-medium); white-space: nowrap; } .ham-input { flex: 0 1 18em; min-width: 8em; padding: var(--sp-1) var(--sp-3); background: var(--bg); color: var(--text); border: var(--line-width) solid var(--line); border-radius: var(--r-pill); font-size: var(--fs-sm); outline: none; } .ham-input:focus { border-color: var(--line-strong); } .ham-dir { padding: var(--sp-1) var(--sp-2); min-width: 2em; } @@ -424,6 +431,19 @@ .ham-plan-finding { color: var(--status-error); } .ham-plan-ruled-out { padding-left: 1.4em; } .ham-plan-rails { font-size: var(--fs-xs); color: var(--text-faint); } + /* The preview while the plan is on its way (the let-hive-decide busy fix): + the sentence line carries the tracker's working glyph and "Asking + the hive…"; placeholder lines shimmer where the why / then will be. + The clicked lead chip wears the same glyph and label meanwhile. */ + .ham-plan-skeleton .ham-plan-sentence { color: var(--muted); font-weight: var(--fw-medium); } + .ham-plan-placeholder { display: block; height: var(--sp-4); margin: 0 0 var(--sp-3); border-radius: var(--r-pill); width: 72%; background: linear-gradient(90deg, var(--line-subtle) 0%, var(--surface-3) 50%, var(--line-subtle) 100%); background-size: 200% 100%; animation: ham-plan-shimmer 1.4s linear infinite; } + .ham-plan-placeholder-wide { width: 94%; } + .ham-plan-placeholder-short { width: 48%; } + .ham-plan-error { color: var(--status-error); font-weight: var(--fw-medium); } + .ham-lead-act.ham-asking, .ham-chip.ham-asking { display: inline-flex; align-items: center; gap: var(--sp-2); cursor: progress; opacity: .85; } + .ham-lead-act.ham-asking .cue-acting-spin, .ham-chip.ham-asking .cue-acting-spin { color: currentColor; } + @keyframes ham-plan-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } } + @media (prefers-reduced-motion: reduce) { .ham-plan-placeholder { animation: none; background: var(--line-subtle); } } .ham-lineage { color: var(--muted); text-decoration: none; display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-lineage:hover { color: var(--text); } .ham-plan-body, .ham-plan-note { white-space: pre-wrap; } diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index 36d27ba1f3..243ecc2baf 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -490,9 +490,27 @@ // button — "Let hive decide" showed twice per item (hive#15320 → // #15647, hive#15338 → #15648). The ⋯ menu's "Decide PR #N…" stays on // the parent. subRows: the linked PRs drawn as sub-rows, or none. + // A covered issue never offers the decision its PR is parked on + // (hivecommons/hive#15773, #15503 "under #15502", covered by #15759): + // the PR row carries "Let hive decide"; the issue draws the passive + // "decision pending on #N" chip (stageTrackerDecisionPendingChipHtml). + function stageTrackerDecisionPendingOn(item) { + if (!item || item.kind !== 'issue') return 0; + return Number(item.decision_pending_on) || 0; + } + // Pure: the PR a decision lead acts on is drawn as a sub-row under + // ANOTHER issue (a secondary issue's covering PR, drawn_under the + // primary): that row carries the button, this one must not. + function stageTrackerLeadDrawnElsewhere(item, a) { + if (!a || !a.target || a.target.kind !== 'pr' || !/^decide:/.test(String(a.id || '')) || !Array.isArray(item.linked_prs)) return false; + const lp = item.linked_prs.find(x => x && Number(x.number) === Number(a.target.number)); + return !!lp && Number(lp.drawn_under) > 0 && Number(lp.drawn_under) !== Number(item.number); + } function stageTrackerLeadActionOnRow(item, ctx, subRows) { const a = stageTrackerLeadAction(item, ctx); - if (!a || !a.target || !Array.isArray(subRows) || !subRows.length || item.kind !== 'issue') return a; + if (!a || item.kind !== 'issue') return a; + if (stageTrackerDecisionPendingOn(item) || stageTrackerLeadDrawnElsewhere(item, a)) return null; + if (!a.target || !Array.isArray(subRows) || !subRows.length) return a; const t = a.target; if (t.kind !== 'pr') return a; const lp = subRows.find(x => x && Number(x.number) === Number(t.number) && !x.superseded && (!x.repo || !t.repo || x.repo === t.repo)); @@ -504,9 +522,16 @@ // id, hint and enable/disable reason as the ⋯ menu entry it mirrors; // '' when the row has no lead. Click handling is delegated in // stageTrackerWireRowActions and runs runRowAction, the menu's path. + function stageTrackerDecisionPendingChipHtml(item) { + const n = stageTrackerDecisionPendingOn(item); + if (!n) return ''; + const key = stageTrackerItemKey({ repo: item.repo, kind: 'pr', number: n }); + const tip = `PR #${n} is parked on a decision — the "Let hive decide" button is on the PR row. Click to show it.`; + return ``; + } function stageTrackerLeadActionHtml(item, ctx, subRows) { const a = stageTrackerLeadActionOnRow(item, ctx, subRows); - if (!a) return ''; + if (!a) return stageTrackerDecisionPendingChipHtml(item); const label = String(a.label || a.id); const tip = a.enabled ? String(a.hint || a.note || a.consequence || '') : String(a.why || ''); const ref = typeof stageTrackerRefOf === 'function' ? stageTrackerRefOf(item) : ''; @@ -684,6 +709,7 @@ el.style.setProperty('left', pos.left + 'px'); el.style.setProperty('top', pos.top + 'px'); const m = { el, items, restore: at.restore || at.anchor || null }; + stageTrackerPrefetchDelegatePlans(items); m.onAway = e => { if (e.type !== 'pointerdown' || !el.contains(e.target)) stageTrackerCloseMenu(false); }; m.onKey = e => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); stageTrackerCloseMenu(true); return; } @@ -770,8 +796,21 @@ const key = sub ? sub.dataset.hamSubKey : (row ? row.dataset.hamKey : ''); const item = key ? stageTrackerItemByKey(_stageTracker, key) : null; if (!item) return; - stageTrackerDecisionRun(item, b.dataset.hamAct); + stageTrackerDecisionRun(item, b.dataset.hamAct, b); }); + // Hovering or focusing a "Let hive decide" lead warms its plan so + // the click answers at once (hivecommons/hive#15773). + const warm = e => { + const b = e.target && e.target.closest ? e.target.closest('.ham-lead-act[data-ham-act="decide:delegate"]') : null; + if (!b || b.getAttribute('aria-disabled') === 'true') return; + const sub = b.closest('[data-ham-sub-key]'); + const row = b.closest('.ham-row[data-ham-key]'); + const key = sub ? sub.dataset.hamSubKey : (row ? row.dataset.hamKey : ''); + const item = key ? stageTrackerItemByKey(_stageTracker, key) : null; + if (item) stageTrackerPrefetchDelegatePlans([item]); + }; + el.addEventListener('pointerover', warm); + el.addEventListener('focusin', warm); // Cmd/Ctrl- or Shift-click anywhere on a row (not on its links or // buttons) selects it too. el.addEventListener('click', e => { @@ -890,8 +929,8 @@
`; } // Run a popover action down the row context menu's path. - function stageTrackerDecisionRun(item, act) { - if (typeof runRowAction === 'function') return runRowAction(act, item); + function stageTrackerDecisionRun(item, act, button) { + if (typeof runRowAction === 'function') return runRowAction(act, item, { button }); return stageTrackerDoAction([item], act); } function stageTrackerCloseDecisionPop(refocus) { @@ -940,6 +979,7 @@ el.style.setProperty('top', pos.top + 'px'); trigger.setAttribute('aria-expanded', 'true'); const p = { el, key, item, pinned: !!pin, timer: 0 }; + stageTrackerPrefetchDelegatePlans([item]); p.onAway = e => { if (e.type !== 'pointerdown' || !(el.contains(e.target) || (e.target.closest && e.target.closest('.ham-decision-trigger') === stageTrackerDecisionTrigger(key)))) stageTrackerCloseDecisionPop(false); }; p.onKey = e => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); stageTrackerCloseDecisionPop(true); return; } @@ -967,7 +1007,7 @@ e.preventDefault(); e.stopPropagation(); const act = b.dataset.hamAct; stageTrackerCloseDecisionPop(true); - stageTrackerDecisionRun(p.item, act); + stageTrackerDecisionRun(p.item, act, b); }); document.addEventListener('pointerdown', p.onAway, true); document.addEventListener('keydown', p.onKey, true); @@ -1049,7 +1089,7 @@ const items = stageTrackerItemsForKeys(el ? stageTrackerRowKeys(el).filter(k => _stageTrackerSel.has(k)) : []); if (!items.length) return; if (id === 'decide') { stageTrackerOpenMenu(items, { anchor: btn, restore: btn, expandDecide: true }); return; } - stageTrackerDoAction(items, id); + runRowAction(id, items, { button: btn }); } // Pure: the selection bar — count, Clear, and the shared actions // (disabled ones keep their tooltip, so aria-disabled rather than disabled). @@ -1094,6 +1134,8 @@ } if (id === 'decide:delegate' || id === 'decide:delegate:rerun') { const body = { type, reason: item.reason || '', caption: item.caption || '', sentinel_reason: item.sentinel_reason || '' }; + // The head keys the server's plan cache (hivecommons/hive#15773). + if (item.head) body.head = item.head; // Re-run skips the "already recorded" dedup on a stuck decision. if (id === 'decide:delegate:rerun') body.force = true; if (payload.chosen) body.chosen = payload.chosen; @@ -1544,41 +1586,173 @@ for (const pl of plans || []) for (const a of pl.alternatives || []) if (a.action === action && a.enabled === false && a.reason_if_disabled) return a.reason_if_disabled; return ''; } - async function stageTrackerFetchDelegatePlan(item) { + // The plan request, and the short client-side cache in front of it + // (hivecommons/hive#15773): a plan asked for ahead of the click — as + // the row's decision options came into view — answers the click at + // once. Keyed by row and head; a failed fetch is never reused. + const STAGE_TRACKER_PLAN_PREFETCH_TTL_MS = 60000; + var _stageTrackerPlanPrefetch = {}; + function stageTrackerPlanPrefetchKey(item) { return stageTrackerItemKey(item) + '@' + String(item.head || ''); } + async function stageTrackerRequestDelegatePlan(item, prefetch) { const req = stageTrackerActionRequest(item, 'decide:delegate', {}); if (!req) return { ref: stageTrackerRefOf(item), number: item.number, error: 'no route' }; try { - const r = await fetch(req.url + '/plan', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(req.body) }); + const body = prefetch ? Object.assign({}, req.body, { prefetch: true }) : req.body; + const r = await fetch(req.url + '/plan', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const data = await r.json().catch(() => ({})); if (!r.ok) return { ref: stageTrackerRefOf(item), number: item.number, error: data.error || ('HTTP ' + r.status) }; return Object.assign({ ref: stageTrackerRefOf(item) + (typeof stageTrackerLineageClause === 'function' ? stageTrackerLineageClause(item) : '') }, data); } catch (e) { return { ref: stageTrackerRefOf(item), number: item.number, error: String(e && e.message || e) }; } } - // The preview: resolves { chosen } for Let hive do that, { chosen, - // merge: } for the merge button, null on Cancel. - function stageTrackerDelegatePlanDialog(plans, sentinel) { - const view = stageTrackerDelegatePlanView(plans, sentinel); + // Pure-ish: the live prefetched plan for the item, or null. + function stageTrackerPlanPrefetched(item, now) { + const e = _stageTrackerPlanPrefetch[stageTrackerPlanPrefetchKey(item)]; + if (!e) return null; + if ((typeof now === 'number' ? now : Date.now()) - e.at > STAGE_TRACKER_PLAN_PREFETCH_TTL_MS) { delete _stageTrackerPlanPrefetch[stageTrackerPlanPrefetchKey(item)]; return null; } + return e; + } + function stageTrackerFetchDelegatePlan(item, fresh) { + const key = stageTrackerPlanPrefetchKey(item); + const live = fresh ? null : stageTrackerPlanPrefetched(item); + if (live) return live.promise; + const entry = { at: Date.now(), promise: null }; + entry.promise = stageTrackerRequestDelegatePlan(item, false).then(pl => { if (pl && pl.error && _stageTrackerPlanPrefetch[key] === entry) delete _stageTrackerPlanPrefetch[key]; return pl; }); + _stageTrackerPlanPrefetch[key] = entry; + return entry.promise; + } + // Warm the plan for the rows whose "Let hive decide" is in view; a + // row that is not a delegate target, or already warm, is skipped. + function stageTrackerPrefetchDelegatePlans(items) { + for (const it of (items || [])) { + for (const target of stageTrackerDelegateTargets(it)) { + if (!target || stageTrackerPlanPrefetched(target)) continue; + const key = stageTrackerPlanPrefetchKey(target); + const entry = { at: Date.now(), promise: null }; + entry.promise = stageTrackerRequestDelegatePlan(target, true).then(pl => { if (pl && pl.error && _stageTrackerPlanPrefetch[key] === entry) delete _stageTrackerPlanPrefetch[key]; return pl; }); + _stageTrackerPlanPrefetch[key] = entry; + } + } + } + // The preview as a skeleton while the plan is on its way: the real + // title, the subject, placeholder lines, Cancel live and the primary + // disabled (hivecommons/hive#15773). The skeleton reuses the row's + // working glyph so the dialog says "working" the way the tracker does. + const STAGE_TRACKER_PLAN_ASKING = 'Asking the hive…'; + const STAGE_TRACKER_PLAN_RETRY = 'Retry'; + function stageTrackerDelegatePlanSkeletonHtml(items, sentinel) { + const esc = hiveDialogEscape; + const subject = (items || []).map(stageTrackerRefOf).join(', '); + return '
' + esc(STAGE_TRACKER_PLAN_TITLE) + '
' + + '
' + esc(subject) + (sentinel ? ' ⚠ Sentinel' : '') + '
' + + '
' + + '
' + esc(STAGE_TRACKER_PLAN_EYEBROW) + '
' + + '

' + esc(STAGE_TRACKER_PLAN_ASKING) + '

' + + '' + + '
' + + '
' + + '' + + '' + + '
'; + } + // The preview when the plan could not be fetched: the error inline, + // Cancel and Retry. + function stageTrackerDelegatePlanErrorHtml(items, failed) { + const esc = hiveDialogEscape; + const subject = (items || []).map(stageTrackerRefOf).join(', '); + return '
' + esc(STAGE_TRACKER_PLAN_TITLE) + '
' + + '
' + esc(subject) + '
' + + '
' + + '' + + '
' + + '
' + + '' + + '' + + '
'; + } + // The preview: opens at once as a skeleton, fills when the plans land, + // shows a fetch failure inline with Retry. Resolves { chosen } for Let + // hive do that, { chosen, merge: } for the merge button, + // null on Cancel. fetchPlans(fresh) returns the plans' promise. + function stageTrackerDelegatePlanDialog(items, sentinel, fetchPlans) { return new Promise(resolve => { const overlay = document.createElement('div'); overlay.className = 'hive-dialog-overlay'; hiveRememberModalOpen(overlay); - overlay.innerHTML = ''; + overlay.innerHTML = ''; document.body.appendChild(overlay); - const would = plans.map(pl => pl.would || '?').filter((v, i, a) => a.indexOf(v) === i).join('/'); - hiveWireDialog(overlay, resolve, null, '.primary', '.cancel', close => close({ chosen: STAGE_TRACKER_PLAN_BUTTON_DELEGATE + ' · previewed ' + would })); - const merge = overlay.querySelector('.ham-plan-merge'); - if (merge && view.mergeable) merge.addEventListener('click', () => { overlay.hiveDialogClose = null; overlay.remove(); resolve({ chosen: view.mergeLabel + ' · previewed ' + would, merge: view.mergeAction }); }); + const dialog = overlay.firstElementChild || overlay; + let settled = false; + const done = v => { if (settled) return; settled = true; resolve(v); }; + // Each phase wires its own buttons; the skeleton's primary is + // disabled so Enter and a click do nothing until the plan is in. + const wire = (view, plans) => { + const would = (plans || []).map(pl => pl.would || '?').filter((v, i, a) => a.indexOf(v) === i).join('/'); + hiveWireDialog(overlay, done, null, view ? '.primary' : '.ham-plan-retry', '.cancel', close => { + if (!view) { load(true); return; } + close({ chosen: STAGE_TRACKER_PLAN_BUTTON_DELEGATE + ' · previewed ' + would }); + }); + const merge = overlay.querySelector('.ham-plan-merge'); + if (view && merge && view.mergeable) merge.addEventListener('click', () => { overlay.hiveDialogClose = null; overlay.remove(); done({ chosen: view.mergeLabel + ' · previewed ' + would, merge: view.mergeAction }); }); + }; + const load = async fresh => { + if (fresh) { dialog.innerHTML = stageTrackerDelegatePlanSkeletonHtml(items, sentinel); hiveWireDialog(overlay, done, null, '.primary', '.cancel', () => {}); } + const plans = await fetchPlans(!!fresh); + if (settled || !overlay.parentNode) return; + const failed = plans.filter(pl => pl.error); + if (failed.length) { dialog.innerHTML = stageTrackerDelegatePlanErrorHtml(items, failed); wire(null, plans); return; } + const view = stageTrackerDelegatePlanView(plans, sentinel); + dialog.innerHTML = stageTrackerDelegatePlanHtml(view); + wire(view, plans); + }; + hiveWireDialog(overlay, done, null, '.primary', '.cancel', () => {}); + load(false); }); } + // The clicked button while the plan is on its way: disabled, + // aria-busy, "Asking the hive…" behind the tracker's working glyph + // (the same one the stage chips use); restored afterwards. + function stageTrackerDelegateButtonBusy(btn, on) { + if (!btn || typeof btn.setAttribute !== 'function') return; + if (on) { + if (btn.getAttribute('aria-busy') === 'true') return; + btn.dataset.hamIdleLabel = btn.innerHTML; + btn.setAttribute('aria-busy', 'true'); + btn.disabled = true; + btn.innerHTML = '' + esc(STAGE_TRACKER_PLAN_ASKING); + if (btn.classList) btn.classList.add('ham-asking'); + } else { + if (btn.getAttribute('aria-busy') !== 'true') return; + btn.removeAttribute('aria-busy'); + btn.disabled = false; + if (btn.dataset.hamIdleLabel != null) { btn.innerHTML = btn.dataset.hamIdleLabel; delete btn.dataset.hamIdleLabel; } + if (btn.classList) btn.classList.remove('ham-asking'); + } + } // Let hive decide → plan → preview → act. Returns the delegate payload, // or null when cancelled or when the operator took the merge // alternative (which runs as its own row action with the chosen button - // recorded on the ledger). - async function stageTrackerDelegatePreview(items) { - const plans = await Promise.all(items.map(stageTrackerFetchDelegatePlan)); - const failed = plans.filter(pl => pl.error); - if (failed.length) { showToast('Could not preview ' + failed.map(pl => pl.ref + ' (' + pl.error + ')').join(', '), 'error'); return null; } - const picked = await stageTrackerDelegatePlanDialog(plans, stageTrackerSentinelPreface(items)); + // recorded on the ledger). opts.button is the clicked button, made + // busy while the plan is fetched; a second click while one preview is + // open for any of the same rows is ignored (hivecommons/hive#15773). + var _stageTrackerDelegateOpen = {}; + async function stageTrackerDelegatePreview(items, opts) { + const keys = items.map(stageTrackerItemKey); + if (keys.some(k => _stageTrackerDelegateOpen[k])) return null; + for (const k of keys) _stageTrackerDelegateOpen[k] = true; + const btn = opts && opts.button; + stageTrackerDelegateButtonBusy(btn, true); + const pend = stageTrackerSetPending(keys, STAGE_TRACKER_PLAN_ASKING); + const fetchPlans = async fresh => { + try { return await Promise.all(items.map(it => stageTrackerFetchDelegatePlan(it, fresh))); } + finally { stageTrackerClearPending(pend); stageTrackerDelegateButtonBusy(btn, false); } + }; + let picked = null; + try { picked = await stageTrackerDelegatePlanDialog(items, stageTrackerSentinelPreface(items), fetchPlans); } + finally { + for (const k of keys) delete _stageTrackerDelegateOpen[k]; + stageTrackerClearPending(pend); + stageTrackerDelegateButtonBusy(btn, false); + } if (!picked) return null; if (picked.merge) { await stageTrackerRunActions(items, picked.merge, { comment: '', chosen: picked.chosen }, items); @@ -1586,7 +1760,7 @@ } return { chosen: picked.chosen }; } - async function stageTrackerActionPayload(items, id) { + async function stageTrackerActionPayload(items, id, opts) { const refs = items.map(stageTrackerRefOf).join(', '); const who = window._hiveUser || 'you'; const prs = items.length > 0 && items.every(it => it.kind === 'pr'); @@ -1596,7 +1770,7 @@ case 'decide:delegate': // Preview first (hivecommons/hive#15126): nothing is written // until the operator picks a button. - return stageTrackerDelegatePreview(items); + return stageTrackerDelegatePreview(items, opts); case 'decide:delegate-all': { // Confirms as Let hive decide (same opt-out key), naming each PR. const prs = [].concat(...items.map(stageTrackerNestedOpenPRs)); @@ -1998,7 +2172,7 @@ const refs = (rows || []).map(stageTrackerRefOf).filter(Boolean).join(', '); if (typeof showToast === 'function') showToast(stageTrackerActionLabel(id) + ': nothing to act on' + (refs ? ' — ' + refs + ' is not waiting on that decision' : ''), 'warning'); } - async function runRowAction(action, row) { + async function runRowAction(action, row, opts) { let items = Array.isArray(row) ? row.slice() : (row ? [row] : []); const id = action; const rows = items.slice(); @@ -2063,7 +2237,7 @@ .filter(t => t && !seen[stageTrackerItemKey(t)] && (seen[stageTrackerItemKey(t)] = true)); if (!items.length) { stageTrackerNothingToActOn(id, rows); return { toasts: [], pending: [] }; } } - const payload = await stageTrackerActionPayload(items, id); + const payload = await stageTrackerActionPayload(items, id, opts); 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 }; diff --git a/src/pkg/dashboard/static-src/js/tracker-merged.js b/src/pkg/dashboard/static-src/js/tracker-merged.js index b7b6c30ae0..2982b77488 100644 --- a/src/pkg/dashboard/static-src/js/tracker-merged.js +++ b/src/pkg/dashboard/static-src/js/tracker-merged.js @@ -877,7 +877,9 @@ // already left the board, say so and offer the list instead. function hamBannerShowRow(rowKey) { const el = document.getElementById('activity-monitor-panel'); - const row = el && rowKey ? el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) : null; + // A nested PR sub-row answers to its sub-key when it has no row of + // its own (a covered issue's "decision pending on #N" chip). + const row = el && rowKey ? (el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) || el.querySelector(`[data-ham-sub-key="${CSS.escape(rowKey)}"]`)) : null; if (!row) { showToast('That row has left the board — the merge is in the Merged list.', 'info'); hamMergedToggle(true); return false; } if (typeof row.scrollIntoView === 'function') row.scrollIntoView({ block: 'center', behavior: stageTrackerReducedMotion() ? 'auto' : 'smooth' }); row.classList.remove('cue-merged'); void row.offsetWidth; stageTrackerTransient(row, 'cue-merged', 1600); diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index 74d8377c4d..ea40cd12f4 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -180,6 +180,20 @@ const sa = item && item.stage_actor; return sa && typeof sa === 'object' && sa.kind ? sa : null; } + // Pure: the server's human_reason for the row (a PR sub-row carries its + // own); '' when the next move is not a person's. + function stageTrackerHumanReasonOf(item) { + if (!item || stageTrackerActorKind(item) !== 'human') return ''; + return String(item.human_reason || '').trim(); + } + // Pure: the chevron's " · reason" span, or '' when there is no reason + // or the word already says it. + function stageTrackerHumanReasonHtml(reason, word) { + reason = String(reason || '').trim(); + if (!reason) return ''; + if (word && String(word).toLowerCase().indexOf(reason.toLowerCase()) >= 0) return ''; + return ` · ${esc(reason)}`; + } function stageTrackerActorKind(item) { // Guarded: test harnesses lift this function by name without the 000-new helpers. const fresh = typeof stageTrackerNewState === 'function' ? stageTrackerNewState(item) : null; @@ -351,7 +365,10 @@ const from = range && range.from != null ? range.from : -Infinity; const to = range && range.to != null ? range.to : Infinity; const actorKind = stageTrackerActorKind(item); - const actorIco = actorKind ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind) : ''; + // The 👤 marker never ships alone (hivecommons/hive#15773): the + // server's human_reason rides the icon's title and the chevron word. + const humanReason = actorKind === 'human' ? stageTrackerHumanReasonOf(item) : ''; + const actorIco = actorKind ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind + (humanReason ? ' — ' + humanReason : '')) : ''; const actorTip = stageTrackerActorTip(item); const claimant = typeof stageTrackerClaimant === 'function' ? stageTrackerClaimant(item) : null; const holderShort = claimant ? stageTrackerClaimantShort(claimant) : ''; @@ -425,7 +442,11 @@ // A detour word that already names the holder ("Returned to // @bob's clanker") does not repeat them after the dot. const detourHolder = sg.detour && holderShort && sg.detour.text.indexOf(holderShort) >= 0 ? '' : holderHtml; - const word = sg.detour ? `${esc(sg.detour.text)}${detourHolder}` : (gateWord || `${esc(sg.short)}${holderHtml}`); + // The reason a person is wanted follows the word after a middot + // ("PR in progress · #15759 needs a decision"); the full question + // stays in the tooltip. + const reasonHtml = active && !sg.cap ? stageTrackerHumanReasonHtml(humanReason, sg.detour ? sg.detour.text : sg.short) : ''; + const word = sg.detour ? `${esc(sg.detour.text)}${reasonHtml}${detourHolder}` : (gateWord ? gateWord.replace(/<\/span>\s*$/, reasonHtml + '') : `${esc(sg.short)}${reasonHtml}${holderHtml}`); const gateCue = gateWord && typeof stageTrackerGateCueHtml === 'function' ? stageTrackerGateCueHtml(item, nowMs, trains) : ''; // The agent-working spinner (tracker-cues) names the agent and what // it did, so a spinning glyph is never unexplained. @@ -955,7 +976,7 @@ stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), - last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, + last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, human_reason: lp.human_reason || '', claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; } // Pure: whether a linked PR is still open (not merged / closed / diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index ae78cd1483..0c8d4b0018 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1363,6 +1363,13 @@ .ham-chip:hover { color: var(--text); border-color: var(--line-strong); } .ham-chip[hidden] { display: none; } .ham-chip .ham-chip-n { color: var(--text-faint); margin-left: var(--sp-1); } + /* A covered issue's passive "decision pending on #N" chip: muted, + never a call to action, scrolls to the PR row that holds the button. */ + .ham-chip-passive { color: var(--text-faint); border-style: dashed; font-weight: var(--fw-medium); } + .ham-chip-passive:hover { color: var(--muted); border-color: var(--line); } + /* The reason after the chevron word ("PR in progress · #N needs a + decision"): quieter than the word, never wraps on its own. */ + .ham-human-reason { color: var(--muted); font-weight: var(--fw-medium); white-space: nowrap; } .ham-input { flex: 0 1 18em; min-width: 8em; padding: var(--sp-1) var(--sp-3); background: var(--bg); color: var(--text); border: var(--line-width) solid var(--line); border-radius: var(--r-pill); font-size: var(--fs-sm); outline: none; } .ham-input:focus { border-color: var(--line-strong); } .ham-dir { padding: var(--sp-1) var(--sp-2); min-width: 2em; } @@ -1753,6 +1760,19 @@ .ham-plan-finding { color: var(--status-error); } .ham-plan-ruled-out { padding-left: 1.4em; } .ham-plan-rails { font-size: var(--fs-xs); color: var(--text-faint); } + /* The preview while the plan is on its way (the let-hive-decide busy fix): + the sentence line carries the tracker's working glyph and "Asking + the hive…"; placeholder lines shimmer where the why / then will be. + The clicked lead chip wears the same glyph and label meanwhile. */ + .ham-plan-skeleton .ham-plan-sentence { color: var(--muted); font-weight: var(--fw-medium); } + .ham-plan-placeholder { display: block; height: var(--sp-4); margin: 0 0 var(--sp-3); border-radius: var(--r-pill); width: 72%; background: linear-gradient(90deg, var(--line-subtle) 0%, var(--surface-3) 50%, var(--line-subtle) 100%); background-size: 200% 100%; animation: ham-plan-shimmer 1.4s linear infinite; } + .ham-plan-placeholder-wide { width: 94%; } + .ham-plan-placeholder-short { width: 48%; } + .ham-plan-error { color: var(--status-error); font-weight: var(--fw-medium); } + .ham-lead-act.ham-asking, .ham-chip.ham-asking { display: inline-flex; align-items: center; gap: var(--sp-2); cursor: progress; opacity: .85; } + .ham-lead-act.ham-asking .cue-acting-spin, .ham-chip.ham-asking .cue-acting-spin { color: currentColor; } + @keyframes ham-plan-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } } + @media (prefers-reduced-motion: reduce) { .ham-plan-placeholder { animation: none; background: var(--line-subtle); } } .ham-lineage { color: var(--muted); text-decoration: none; display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-lineage:hover { color: var(--text); } .ham-plan-body, .ham-plan-note { white-space: pre-wrap; } @@ -16498,6 +16518,20 @@

Where to get help

const sa = item && item.stage_actor; return sa && typeof sa === 'object' && sa.kind ? sa : null; } + // Pure: the server's human_reason for the row (a PR sub-row carries its + // own); '' when the next move is not a person's. + function stageTrackerHumanReasonOf(item) { + if (!item || stageTrackerActorKind(item) !== 'human') return ''; + return String(item.human_reason || '').trim(); + } + // Pure: the chevron's " · reason" span, or '' when there is no reason + // or the word already says it. + function stageTrackerHumanReasonHtml(reason, word) { + reason = String(reason || '').trim(); + if (!reason) return ''; + if (word && String(word).toLowerCase().indexOf(reason.toLowerCase()) >= 0) return ''; + return ` · ${esc(reason)}`; + } function stageTrackerActorKind(item) { // Guarded: test harnesses lift this function by name without the 000-new helpers. const fresh = typeof stageTrackerNewState === 'function' ? stageTrackerNewState(item) : null; @@ -16669,7 +16703,10 @@

Where to get help

const from = range && range.from != null ? range.from : -Infinity; const to = range && range.to != null ? range.to : Infinity; const actorKind = stageTrackerActorKind(item); - const actorIco = actorKind ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind) : ''; + // The 👤 marker never ships alone (hivecommons/hive#15773): the + // server's human_reason rides the icon's title and the chevron word. + const humanReason = actorKind === 'human' ? stageTrackerHumanReasonOf(item) : ''; + const actorIco = actorKind ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind + (humanReason ? ' — ' + humanReason : '')) : ''; const actorTip = stageTrackerActorTip(item); const claimant = typeof stageTrackerClaimant === 'function' ? stageTrackerClaimant(item) : null; const holderShort = claimant ? stageTrackerClaimantShort(claimant) : ''; @@ -16743,7 +16780,11 @@

Where to get help

// A detour word that already names the holder ("Returned to // @bob's clanker") does not repeat them after the dot. const detourHolder = sg.detour && holderShort && sg.detour.text.indexOf(holderShort) >= 0 ? '' : holderHtml; - const word = sg.detour ? `${esc(sg.detour.text)}${detourHolder}` : (gateWord || `${esc(sg.short)}${holderHtml}`); + // The reason a person is wanted follows the word after a middot + // ("PR in progress · #15759 needs a decision"); the full question + // stays in the tooltip. + const reasonHtml = active && !sg.cap ? stageTrackerHumanReasonHtml(humanReason, sg.detour ? sg.detour.text : sg.short) : ''; + const word = sg.detour ? `${esc(sg.detour.text)}${reasonHtml}${detourHolder}` : (gateWord ? gateWord.replace(/<\/span>\s*$/, reasonHtml + '') : `${esc(sg.short)}${reasonHtml}${holderHtml}`); const gateCue = gateWord && typeof stageTrackerGateCueHtml === 'function' ? stageTrackerGateCueHtml(item, nowMs, trains) : ''; // The agent-working spinner (tracker-cues) names the agent and what // it did, so a spinning glyph is never unexplained. @@ -17273,7 +17314,7 @@

Where to get help

stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), - last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, + last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, human_reason: lp.human_reason || '', claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; } // Pure: whether a linked PR is still open (not merged / closed / @@ -19954,9 +19995,27 @@

All labels

// button — "Let hive decide" showed twice per item (hive#15320 → // #15647, hive#15338 → #15648). The ⋯ menu's "Decide PR #N…" stays on // the parent. subRows: the linked PRs drawn as sub-rows, or none. + // A covered issue never offers the decision its PR is parked on + // (hivecommons/hive#15773, #15503 "under #15502", covered by #15759): + // the PR row carries "Let hive decide"; the issue draws the passive + // "decision pending on #N" chip (stageTrackerDecisionPendingChipHtml). + function stageTrackerDecisionPendingOn(item) { + if (!item || item.kind !== 'issue') return 0; + return Number(item.decision_pending_on) || 0; + } + // Pure: the PR a decision lead acts on is drawn as a sub-row under + // ANOTHER issue (a secondary issue's covering PR, drawn_under the + // primary): that row carries the button, this one must not. + function stageTrackerLeadDrawnElsewhere(item, a) { + if (!a || !a.target || a.target.kind !== 'pr' || !/^decide:/.test(String(a.id || '')) || !Array.isArray(item.linked_prs)) return false; + const lp = item.linked_prs.find(x => x && Number(x.number) === Number(a.target.number)); + return !!lp && Number(lp.drawn_under) > 0 && Number(lp.drawn_under) !== Number(item.number); + } function stageTrackerLeadActionOnRow(item, ctx, subRows) { const a = stageTrackerLeadAction(item, ctx); - if (!a || !a.target || !Array.isArray(subRows) || !subRows.length || item.kind !== 'issue') return a; + if (!a || item.kind !== 'issue') return a; + if (stageTrackerDecisionPendingOn(item) || stageTrackerLeadDrawnElsewhere(item, a)) return null; + if (!a.target || !Array.isArray(subRows) || !subRows.length) return a; const t = a.target; if (t.kind !== 'pr') return a; const lp = subRows.find(x => x && Number(x.number) === Number(t.number) && !x.superseded && (!x.repo || !t.repo || x.repo === t.repo)); @@ -19968,9 +20027,16 @@

All labels

// id, hint and enable/disable reason as the ⋯ menu entry it mirrors; // '' when the row has no lead. Click handling is delegated in // stageTrackerWireRowActions and runs runRowAction, the menu's path. + function stageTrackerDecisionPendingChipHtml(item) { + const n = stageTrackerDecisionPendingOn(item); + if (!n) return ''; + const key = stageTrackerItemKey({ repo: item.repo, kind: 'pr', number: n }); + const tip = `PR #${n} is parked on a decision — the "Let hive decide" button is on the PR row. Click to show it.`; + return ``; + } function stageTrackerLeadActionHtml(item, ctx, subRows) { const a = stageTrackerLeadActionOnRow(item, ctx, subRows); - if (!a) return ''; + if (!a) return stageTrackerDecisionPendingChipHtml(item); const label = String(a.label || a.id); const tip = a.enabled ? String(a.hint || a.note || a.consequence || '') : String(a.why || ''); const ref = typeof stageTrackerRefOf === 'function' ? stageTrackerRefOf(item) : ''; @@ -20148,6 +20214,7 @@

All labels

el.style.setProperty('left', pos.left + 'px'); el.style.setProperty('top', pos.top + 'px'); const m = { el, items, restore: at.restore || at.anchor || null }; + stageTrackerPrefetchDelegatePlans(items); m.onAway = e => { if (e.type !== 'pointerdown' || !el.contains(e.target)) stageTrackerCloseMenu(false); }; m.onKey = e => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); stageTrackerCloseMenu(true); return; } @@ -20234,8 +20301,21 @@

All labels

const key = sub ? sub.dataset.hamSubKey : (row ? row.dataset.hamKey : ''); const item = key ? stageTrackerItemByKey(_stageTracker, key) : null; if (!item) return; - stageTrackerDecisionRun(item, b.dataset.hamAct); + stageTrackerDecisionRun(item, b.dataset.hamAct, b); }); + // Hovering or focusing a "Let hive decide" lead warms its plan so + // the click answers at once (hivecommons/hive#15773). + const warm = e => { + const b = e.target && e.target.closest ? e.target.closest('.ham-lead-act[data-ham-act="decide:delegate"]') : null; + if (!b || b.getAttribute('aria-disabled') === 'true') return; + const sub = b.closest('[data-ham-sub-key]'); + const row = b.closest('.ham-row[data-ham-key]'); + const key = sub ? sub.dataset.hamSubKey : (row ? row.dataset.hamKey : ''); + const item = key ? stageTrackerItemByKey(_stageTracker, key) : null; + if (item) stageTrackerPrefetchDelegatePlans([item]); + }; + el.addEventListener('pointerover', warm); + el.addEventListener('focusin', warm); // Cmd/Ctrl- or Shift-click anywhere on a row (not on its links or // buttons) selects it too. el.addEventListener('click', e => { @@ -20354,8 +20434,8 @@

All labels

`; } // Run a popover action down the row context menu's path. - function stageTrackerDecisionRun(item, act) { - if (typeof runRowAction === 'function') return runRowAction(act, item); + function stageTrackerDecisionRun(item, act, button) { + if (typeof runRowAction === 'function') return runRowAction(act, item, { button }); return stageTrackerDoAction([item], act); } function stageTrackerCloseDecisionPop(refocus) { @@ -20404,6 +20484,7 @@

All labels

el.style.setProperty('top', pos.top + 'px'); trigger.setAttribute('aria-expanded', 'true'); const p = { el, key, item, pinned: !!pin, timer: 0 }; + stageTrackerPrefetchDelegatePlans([item]); p.onAway = e => { if (e.type !== 'pointerdown' || !(el.contains(e.target) || (e.target.closest && e.target.closest('.ham-decision-trigger') === stageTrackerDecisionTrigger(key)))) stageTrackerCloseDecisionPop(false); }; p.onKey = e => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); stageTrackerCloseDecisionPop(true); return; } @@ -20431,7 +20512,7 @@

All labels

e.preventDefault(); e.stopPropagation(); const act = b.dataset.hamAct; stageTrackerCloseDecisionPop(true); - stageTrackerDecisionRun(p.item, act); + stageTrackerDecisionRun(p.item, act, b); }); document.addEventListener('pointerdown', p.onAway, true); document.addEventListener('keydown', p.onKey, true); @@ -20513,7 +20594,7 @@

All labels

const items = stageTrackerItemsForKeys(el ? stageTrackerRowKeys(el).filter(k => _stageTrackerSel.has(k)) : []); if (!items.length) return; if (id === 'decide') { stageTrackerOpenMenu(items, { anchor: btn, restore: btn, expandDecide: true }); return; } - stageTrackerDoAction(items, id); + runRowAction(id, items, { button: btn }); } // Pure: the selection bar — count, Clear, and the shared actions // (disabled ones keep their tooltip, so aria-disabled rather than disabled). @@ -20558,6 +20639,8 @@

All labels

} if (id === 'decide:delegate' || id === 'decide:delegate:rerun') { const body = { type, reason: item.reason || '', caption: item.caption || '', sentinel_reason: item.sentinel_reason || '' }; + // The head keys the server's plan cache (hivecommons/hive#15773). + if (item.head) body.head = item.head; // Re-run skips the "already recorded" dedup on a stuck decision. if (id === 'decide:delegate:rerun') body.force = true; if (payload.chosen) body.chosen = payload.chosen; @@ -21008,41 +21091,173 @@

All labels

for (const pl of plans || []) for (const a of pl.alternatives || []) if (a.action === action && a.enabled === false && a.reason_if_disabled) return a.reason_if_disabled; return ''; } - async function stageTrackerFetchDelegatePlan(item) { + // The plan request, and the short client-side cache in front of it + // (hivecommons/hive#15773): a plan asked for ahead of the click — as + // the row's decision options came into view — answers the click at + // once. Keyed by row and head; a failed fetch is never reused. + const STAGE_TRACKER_PLAN_PREFETCH_TTL_MS = 60000; + var _stageTrackerPlanPrefetch = {}; + function stageTrackerPlanPrefetchKey(item) { return stageTrackerItemKey(item) + '@' + String(item.head || ''); } + async function stageTrackerRequestDelegatePlan(item, prefetch) { const req = stageTrackerActionRequest(item, 'decide:delegate', {}); if (!req) return { ref: stageTrackerRefOf(item), number: item.number, error: 'no route' }; try { - const r = await fetch(req.url + '/plan', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(req.body) }); + const body = prefetch ? Object.assign({}, req.body, { prefetch: true }) : req.body; + const r = await fetch(req.url + '/plan', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const data = await r.json().catch(() => ({})); if (!r.ok) return { ref: stageTrackerRefOf(item), number: item.number, error: data.error || ('HTTP ' + r.status) }; return Object.assign({ ref: stageTrackerRefOf(item) + (typeof stageTrackerLineageClause === 'function' ? stageTrackerLineageClause(item) : '') }, data); } catch (e) { return { ref: stageTrackerRefOf(item), number: item.number, error: String(e && e.message || e) }; } } - // The preview: resolves { chosen } for Let hive do that, { chosen, - // merge: } for the merge button, null on Cancel. - function stageTrackerDelegatePlanDialog(plans, sentinel) { - const view = stageTrackerDelegatePlanView(plans, sentinel); + // Pure-ish: the live prefetched plan for the item, or null. + function stageTrackerPlanPrefetched(item, now) { + const e = _stageTrackerPlanPrefetch[stageTrackerPlanPrefetchKey(item)]; + if (!e) return null; + if ((typeof now === 'number' ? now : Date.now()) - e.at > STAGE_TRACKER_PLAN_PREFETCH_TTL_MS) { delete _stageTrackerPlanPrefetch[stageTrackerPlanPrefetchKey(item)]; return null; } + return e; + } + function stageTrackerFetchDelegatePlan(item, fresh) { + const key = stageTrackerPlanPrefetchKey(item); + const live = fresh ? null : stageTrackerPlanPrefetched(item); + if (live) return live.promise; + const entry = { at: Date.now(), promise: null }; + entry.promise = stageTrackerRequestDelegatePlan(item, false).then(pl => { if (pl && pl.error && _stageTrackerPlanPrefetch[key] === entry) delete _stageTrackerPlanPrefetch[key]; return pl; }); + _stageTrackerPlanPrefetch[key] = entry; + return entry.promise; + } + // Warm the plan for the rows whose "Let hive decide" is in view; a + // row that is not a delegate target, or already warm, is skipped. + function stageTrackerPrefetchDelegatePlans(items) { + for (const it of (items || [])) { + for (const target of stageTrackerDelegateTargets(it)) { + if (!target || stageTrackerPlanPrefetched(target)) continue; + const key = stageTrackerPlanPrefetchKey(target); + const entry = { at: Date.now(), promise: null }; + entry.promise = stageTrackerRequestDelegatePlan(target, true).then(pl => { if (pl && pl.error && _stageTrackerPlanPrefetch[key] === entry) delete _stageTrackerPlanPrefetch[key]; return pl; }); + _stageTrackerPlanPrefetch[key] = entry; + } + } + } + // The preview as a skeleton while the plan is on its way: the real + // title, the subject, placeholder lines, Cancel live and the primary + // disabled (hivecommons/hive#15773). The skeleton reuses the row's + // working glyph so the dialog says "working" the way the tracker does. + const STAGE_TRACKER_PLAN_ASKING = 'Asking the hive…'; + const STAGE_TRACKER_PLAN_RETRY = 'Retry'; + function stageTrackerDelegatePlanSkeletonHtml(items, sentinel) { + const esc = hiveDialogEscape; + const subject = (items || []).map(stageTrackerRefOf).join(', '); + return '
' + esc(STAGE_TRACKER_PLAN_TITLE) + '
' + + '
' + esc(subject) + (sentinel ? ' ⚠ Sentinel' : '') + '
' + + '
' + + '
' + esc(STAGE_TRACKER_PLAN_EYEBROW) + '
' + + '

' + esc(STAGE_TRACKER_PLAN_ASKING) + '

' + + '' + + '
' + + '
' + + '' + + '' + + '
'; + } + // The preview when the plan could not be fetched: the error inline, + // Cancel and Retry. + function stageTrackerDelegatePlanErrorHtml(items, failed) { + const esc = hiveDialogEscape; + const subject = (items || []).map(stageTrackerRefOf).join(', '); + return '
' + esc(STAGE_TRACKER_PLAN_TITLE) + '
' + + '
' + esc(subject) + '
' + + '
' + + '' + + '
' + + '
' + + '' + + '' + + '
'; + } + // The preview: opens at once as a skeleton, fills when the plans land, + // shows a fetch failure inline with Retry. Resolves { chosen } for Let + // hive do that, { chosen, merge: } for the merge button, + // null on Cancel. fetchPlans(fresh) returns the plans' promise. + function stageTrackerDelegatePlanDialog(items, sentinel, fetchPlans) { return new Promise(resolve => { const overlay = document.createElement('div'); overlay.className = 'hive-dialog-overlay'; hiveRememberModalOpen(overlay); - overlay.innerHTML = ''; + overlay.innerHTML = ''; document.body.appendChild(overlay); - const would = plans.map(pl => pl.would || '?').filter((v, i, a) => a.indexOf(v) === i).join('/'); - hiveWireDialog(overlay, resolve, null, '.primary', '.cancel', close => close({ chosen: STAGE_TRACKER_PLAN_BUTTON_DELEGATE + ' · previewed ' + would })); - const merge = overlay.querySelector('.ham-plan-merge'); - if (merge && view.mergeable) merge.addEventListener('click', () => { overlay.hiveDialogClose = null; overlay.remove(); resolve({ chosen: view.mergeLabel + ' · previewed ' + would, merge: view.mergeAction }); }); - }); + const dialog = overlay.firstElementChild || overlay; + let settled = false; + const done = v => { if (settled) return; settled = true; resolve(v); }; + // Each phase wires its own buttons; the skeleton's primary is + // disabled so Enter and a click do nothing until the plan is in. + const wire = (view, plans) => { + const would = (plans || []).map(pl => pl.would || '?').filter((v, i, a) => a.indexOf(v) === i).join('/'); + hiveWireDialog(overlay, done, null, view ? '.primary' : '.ham-plan-retry', '.cancel', close => { + if (!view) { load(true); return; } + close({ chosen: STAGE_TRACKER_PLAN_BUTTON_DELEGATE + ' · previewed ' + would }); + }); + const merge = overlay.querySelector('.ham-plan-merge'); + if (view && merge && view.mergeable) merge.addEventListener('click', () => { overlay.hiveDialogClose = null; overlay.remove(); done({ chosen: view.mergeLabel + ' · previewed ' + would, merge: view.mergeAction }); }); + }; + const load = async fresh => { + if (fresh) { dialog.innerHTML = stageTrackerDelegatePlanSkeletonHtml(items, sentinel); hiveWireDialog(overlay, done, null, '.primary', '.cancel', () => {}); } + const plans = await fetchPlans(!!fresh); + if (settled || !overlay.parentNode) return; + const failed = plans.filter(pl => pl.error); + if (failed.length) { dialog.innerHTML = stageTrackerDelegatePlanErrorHtml(items, failed); wire(null, plans); return; } + const view = stageTrackerDelegatePlanView(plans, sentinel); + dialog.innerHTML = stageTrackerDelegatePlanHtml(view); + wire(view, plans); + }; + hiveWireDialog(overlay, done, null, '.primary', '.cancel', () => {}); + load(false); + }); + } + // The clicked button while the plan is on its way: disabled, + // aria-busy, "Asking the hive…" behind the tracker's working glyph + // (the same one the stage chips use); restored afterwards. + function stageTrackerDelegateButtonBusy(btn, on) { + if (!btn || typeof btn.setAttribute !== 'function') return; + if (on) { + if (btn.getAttribute('aria-busy') === 'true') return; + btn.dataset.hamIdleLabel = btn.innerHTML; + btn.setAttribute('aria-busy', 'true'); + btn.disabled = true; + btn.innerHTML = '' + esc(STAGE_TRACKER_PLAN_ASKING); + if (btn.classList) btn.classList.add('ham-asking'); + } else { + if (btn.getAttribute('aria-busy') !== 'true') return; + btn.removeAttribute('aria-busy'); + btn.disabled = false; + if (btn.dataset.hamIdleLabel != null) { btn.innerHTML = btn.dataset.hamIdleLabel; delete btn.dataset.hamIdleLabel; } + if (btn.classList) btn.classList.remove('ham-asking'); + } } // Let hive decide → plan → preview → act. Returns the delegate payload, // or null when cancelled or when the operator took the merge // alternative (which runs as its own row action with the chosen button - // recorded on the ledger). - async function stageTrackerDelegatePreview(items) { - const plans = await Promise.all(items.map(stageTrackerFetchDelegatePlan)); - const failed = plans.filter(pl => pl.error); - if (failed.length) { showToast('Could not preview ' + failed.map(pl => pl.ref + ' (' + pl.error + ')').join(', '), 'error'); return null; } - const picked = await stageTrackerDelegatePlanDialog(plans, stageTrackerSentinelPreface(items)); + // recorded on the ledger). opts.button is the clicked button, made + // busy while the plan is fetched; a second click while one preview is + // open for any of the same rows is ignored (hivecommons/hive#15773). + var _stageTrackerDelegateOpen = {}; + async function stageTrackerDelegatePreview(items, opts) { + const keys = items.map(stageTrackerItemKey); + if (keys.some(k => _stageTrackerDelegateOpen[k])) return null; + for (const k of keys) _stageTrackerDelegateOpen[k] = true; + const btn = opts && opts.button; + stageTrackerDelegateButtonBusy(btn, true); + const pend = stageTrackerSetPending(keys, STAGE_TRACKER_PLAN_ASKING); + const fetchPlans = async fresh => { + try { return await Promise.all(items.map(it => stageTrackerFetchDelegatePlan(it, fresh))); } + finally { stageTrackerClearPending(pend); stageTrackerDelegateButtonBusy(btn, false); } + }; + let picked = null; + try { picked = await stageTrackerDelegatePlanDialog(items, stageTrackerSentinelPreface(items), fetchPlans); } + finally { + for (const k of keys) delete _stageTrackerDelegateOpen[k]; + stageTrackerClearPending(pend); + stageTrackerDelegateButtonBusy(btn, false); + } if (!picked) return null; if (picked.merge) { await stageTrackerRunActions(items, picked.merge, { comment: '', chosen: picked.chosen }, items); @@ -21050,7 +21265,7 @@

All labels

} return { chosen: picked.chosen }; } - async function stageTrackerActionPayload(items, id) { + async function stageTrackerActionPayload(items, id, opts) { const refs = items.map(stageTrackerRefOf).join(', '); const who = window._hiveUser || 'you'; const prs = items.length > 0 && items.every(it => it.kind === 'pr'); @@ -21060,7 +21275,7 @@

All labels

case 'decide:delegate': // Preview first (hivecommons/hive#15126): nothing is written // until the operator picks a button. - return stageTrackerDelegatePreview(items); + return stageTrackerDelegatePreview(items, opts); case 'decide:delegate-all': { // Confirms as Let hive decide (same opt-out key), naming each PR. const prs = [].concat(...items.map(stageTrackerNestedOpenPRs)); @@ -21462,7 +21677,7 @@

All labels

const refs = (rows || []).map(stageTrackerRefOf).filter(Boolean).join(', '); if (typeof showToast === 'function') showToast(stageTrackerActionLabel(id) + ': nothing to act on' + (refs ? ' — ' + refs + ' is not waiting on that decision' : ''), 'warning'); } - async function runRowAction(action, row) { + async function runRowAction(action, row, opts) { let items = Array.isArray(row) ? row.slice() : (row ? [row] : []); const id = action; const rows = items.slice(); @@ -21527,7 +21742,7 @@

All labels

.filter(t => t && !seen[stageTrackerItemKey(t)] && (seen[stageTrackerItemKey(t)] = true)); if (!items.length) { stageTrackerNothingToActOn(id, rows); return { toasts: [], pending: [] }; } } - const payload = await stageTrackerActionPayload(items, id); + const payload = await stageTrackerActionPayload(items, id, opts); 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 }; @@ -22548,7 +22763,9 @@

All labels

// already left the board, say so and offer the list instead. function hamBannerShowRow(rowKey) { const el = document.getElementById('activity-monitor-panel'); - const row = el && rowKey ? el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) : null; + // A nested PR sub-row answers to its sub-key when it has no row of + // its own (a covered issue's "decision pending on #N" chip). + const row = el && rowKey ? (el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) || el.querySelector(`[data-ham-sub-key="${CSS.escape(rowKey)}"]`)) : null; if (!row) { showToast('That row has left the board — the merge is in the Merged list.', 'info'); hamMergedToggle(true); return false; } if (typeof row.scrollIntoView === 'function') row.scrollIntoView({ block: 'center', behavior: stageTrackerReducedMotion() ? 'auto' : 'smooth' }); row.classList.remove('cue-merged'); void row.offsetWidth; stageTrackerTransient(row, 'cue-merged', 1600);