diff --git a/changelog.d/fixed-15808-merging-now-celebration.md b/changelog.d/fixed-15808-merging-now-celebration.md new file mode 100644 index 0000000000..a03b61677b --- /dev/null +++ b/changelog.d/fixed-15808-merging-now-celebration.md @@ -0,0 +1 @@ +- Activity monitor: "⟳ Mergeable · merging now ⬡" no longer lingers for minutes — the sweep clock now marks only the PR actually under evaluation, and a merge call that returns patches the cached snapshot and nudges the SPA at once, so the row reaches ✓ within one poll. Every hive-performed merge (trusted-author, self-authored, contributor and stage-engine lanes alike) celebrates exactly once — toast with the PR number, bee flight, odometer +1 after landing — even when the row vanished before the SPA saw the merged state (reconciled by `recently_merged` / `recently_closed` on removal) — a merge whose row is not on the board (below the fold, filtered, already evicted; #15707) now flies its bee from the toast's ✓ to the counter instead of skipping bee and odometer; a row that vanishes because its PR was closed, not merged, shows a neutral "#N closed · " toast instead of disappearing silently. The merge-gate "Merging · merge landed" bridge is now a ceiling, not a fixed delay: `dashboard.stage_tracker.merged_hold_s` (default `8`, min `3`), with the celebration launching as soon as the merged fact arrives; a merge call or sweep in flight for over 60 s reads "merging · waiting for GitHub…" ([#15808](https://github.com/hivecommons/hive/issues/15808)). diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index fea330b76a..e5f6f6ea4b 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:1631` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1632` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1633` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index e007e73333..d9821e9a61 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:1638` | diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index f41d563955..e3d6e648a6 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:1611` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1612` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1613` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1619` | +| `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:1624` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1625` | +| `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:1626` | +| `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:1627` | +| `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:1628` | +| `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:1629` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1630` | | `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..b112c244ac 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:1691` | | `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/operator-reference.md b/src/docs/operator-reference.md index f702ae9479..0492a60440 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -2018,6 +2018,7 @@ dashboard: waiting_push_stale_h: 4 # hours without a push on a CI / Review row before the pill's age turns muted-amber toast_info_s: 15 # how long the tracker's result / waiting-on-you toasts stay (3-120 s); the merge banner stays twice as long toast_error_s: 30 # how long a failed row action's toast stays (3-120 s); editable from the Activity Monitor's ⚙ → Toasts & timing + merged_hold_s: 8 # ceiling on the "Merging · merge landed" bridge; celebration fires on the merged fact (min 3) ``` ## `HIVE_GITHUB_TOKEN` permissions diff --git a/src/docs/webhooks.md b/src/docs/webhooks.md index fe4a46d49b..d46de916a5 100644 --- a/src/docs/webhooks.md +++ b/src/docs/webhooks.md @@ -122,6 +122,7 @@ These are the acceptance criteria of #13373 and the tests that hold them. | `dashboard.stage_tracker.webhook_refresh_replay_window_s` | `1800` | how long a re-read is remembered and re-applied to every status snapshot the governor publishes, so a cycle that enumerated before the close cannot re-list the item | | `dashboard.stage_tracker.closed_sweep_interval_s` | `300` | how often (driven by status publishes) each repo's items closed since the last look are listed (one call per repo) and rows still shown are evicted; negative disables | | `dashboard.stage_tracker.waiting_push_stale_h` | `4` | hours a CI / Review row may go without a push (booked from the `pull_request` synchronize / `push` re-read, enumerate as fallback) before its pill's age takes the muted-amber tone; negative disables | +| `dashboard.stage_tracker.merged_hold_s` | `8` | ceiling (seconds, floor `3`) on how long a row stays at "Merging · merge landed" after the payload dropped it before the merged fact arrives; the celebration (toast, bee, odometer) launches as soon as the merge is confirmed, not at the end of the hold (hivecommons/hive#15808) | | health window | `2 × governor.eval_interval_s` (10 min at the defaults) | how recent the newest verified delivery must be for webhooks to count as healthy | | recovery hysteresis | `WebhookRecoveryHealthyWindows` = `2` | consecutive healthy windows required before the cadence returns to webhook mode after a degradation | diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index da59c81a46..3f7edac76d 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -4974,6 +4974,13 @@ type DashboardStageTrackerConfig struct { // ToastErrorS is the same for error toasts. 0 means the default (30); // values are clamped to 3..120. ToastErrorS int `yaml:"toast_error_s,omitempty" json:"toast_error_s,omitempty"` + // MergedHoldS is how many seconds the activity monitor keeps a row at + // "Merging · merge landed" after the payload dropped it, bridging the + // gap until the SPA has the merged fact (hivecommons/hive#15808). The + // celebration launches as soon as that fact arrives, so this is a + // ceiling, not a delay. 0 means the default (8); values under 3 read + // as 3. + MergedHoldS int `yaml:"merged_hold_s,omitempty" json:"merged_hold_s,omitempty"` } // Defaults and bounds for dashboard.stage_tracker.toast_info_s and @@ -5013,6 +5020,26 @@ func (c *Config) StageTrackerToastError() time.Duration { return time.Duration(stageTrackerToastSeconds(c.Dashboard.StageTracker.ToastErrorS, DefaultStageTrackerToastErrorS)) * time.Second } +// defaultStageTrackerMergedHold is the default +// dashboard.stage_tracker.merged_hold_s; minStageTrackerMergedHold its floor. +const ( + defaultStageTrackerMergedHold = 8 * time.Second + minStageTrackerMergedHold = 3 * time.Second +) + +// StageTrackerMergedHold is the effective dashboard.stage_tracker.merged_hold_s +// as a duration: the default when unset, never under the floor. +func (c *Config) StageTrackerMergedHold() time.Duration { + if c == nil || c.Dashboard.StageTracker.MergedHoldS == 0 { + return defaultStageTrackerMergedHold + } + d := time.Duration(c.Dashboard.StageTracker.MergedHoldS) * time.Second + if d < minStageTrackerMergedHold { + return minStageTrackerMergedHold + } + return d +} + // defaultStageTrackerWaitingPushStale is the default // dashboard.stage_tracker.waiting_push_stale_h. const defaultStageTrackerWaitingPushStale = 4 * time.Hour diff --git a/src/pkg/config/stage_tracker_merged_hold_test.go b/src/pkg/config/stage_tracker_merged_hold_test.go new file mode 100644 index 0000000000..aaac2c07cf --- /dev/null +++ b/src/pkg/config/stage_tracker_merged_hold_test.go @@ -0,0 +1,22 @@ +package config + +import ( + "testing" + "time" +) + +// TestStageTrackerMergedHold: dashboard.stage_tracker.merged_hold_s is the +// default (8 s) when unset or on a nil config, floors at 3 s, and is taken +// as given otherwise (hivecommons/hive#15808). +func TestStageTrackerMergedHold(t *testing.T) { + if got := (*Config)(nil).StageTrackerMergedHold(); got != 8*time.Second { + t.Fatalf("nil config: got %s, want 8s", got) + } + for in, want := range map[int]time.Duration{0: 8 * time.Second, 1: 3 * time.Second, 3: 3 * time.Second, 45: 45 * time.Second} { + c := &Config{} + c.Dashboard.StageTracker.MergedHoldS = in + if got := c.StageTrackerMergedHold(); got != want { + t.Errorf("merged_hold_s=%d: got %s, want %s", in, got, want) + } + } +} diff --git a/src/pkg/dashboard/merge_attempt_note_test.go b/src/pkg/dashboard/merge_attempt_note_test.go new file mode 100644 index 0000000000..7b949954c3 --- /dev/null +++ b/src/pkg/dashboard/merge_attempt_note_test.go @@ -0,0 +1,121 @@ +package dashboard + +import ( + "errors" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// hivecommons/hive#15808: a merge attempt that landed patches the cached +// snapshot like a webhook `closed` read — the row leaves as merged, the +// merged ledger records it as the hive's, and open tabs are nudged — so +// the celebration never waits on the webhook or the next enumerate. +func TestNoteMergeAttemptMergedEvictsRowRecordsLedgerAndNudges(t *testing.T) { + now := time.Date(2026, 10, 30, 15, 30, 0, 0, time.UTC) + t.Cleanup(github.ResetWebhookTrackerForTestWithClock(func() time.Time { return now })) + s, _ := stageTrackerFixture(t, now) + clock := now + s.stageTrackerNudge.now = func() time.Time { return clock } + if _, _, _, fresh := s.stageTrackerPayload(s.status, now); !fresh { + t.Fatal("first payload builds") + } + ch := make(chan []byte, 4) + s.sseMu.Lock() + s.sseClients[ch] = struct{}{} + s.sseMu.Unlock() + + attempts := github.NewMergeAttempts(func() time.Time { return clock }) + attempts.SetOnChange(s.noteMergeAttempt) + attempts.BeginOnHead("acme/console", 101, github.PRAuditPathSweep, "abc1234") + select { + case f := <-ch: + if !strings.HasPrefix(string(f), "event: stage-tracker\n") { + t.Fatalf("frame = %q", f) + } + default: + t.Fatal("beginning a merge attempt must nudge open tabs") + } + if _, _, _, fresh := s.stageTrackerPayload(s.status, now); !fresh { + t.Fatal("beginning a merge attempt must drop the memoised payload") + } + s.sseMu.Lock() + s.sseClients[ch] = struct{}{} + s.sseMu.Unlock() + + // Past the nudge coalescing window, so the landing's nudge goes out at once. + clock = now.Add(2 * stageTrackerNudgeInterval) + attempts.End("acme/console", 101, true, nil) + + s.statusMu.RLock() + cur := s.status + s.statusMu.RUnlock() + after := s.buildStageTracker(cur, s.stageStore, now) + for _, it := range after.Items { + if it.Kind == "pr" && it.Number == 101 { + t.Fatalf("merged PR 101 still listed open: %+v", it) + } + } + recent := s.mergedLedger().Summary(now, time.UTC).Recent + found := false + for _, e := range recent { + if e.Number == 101 { + found = true + if e.MergedBy != MergedByHive || !e.MergedAt.Equal(clock) { + t.Fatalf("ledger entry = %+v, want merged by hive at %s", e, clock) + } + } + } + if !found { + t.Fatalf("merged ledger recent = %+v, want PR 101", recent) + } + select { + case f := <-ch: + if !strings.HasPrefix(string(f), "event: stage-tracker\n") { + t.Fatalf("frame = %q", f) + } + default: + t.Fatal("a landed merge must nudge open tabs") + } +} + +// A refused attempt (or one on a PR the snapshot never listed) still drops +// the memoised payload and nudges, so "Merge failed" shows within one poll. +func TestNoteMergeAttemptRefusedNudgesWithoutEvicting(t *testing.T) { + now := time.Date(2026, 10, 30, 15, 30, 0, 0, time.UTC) + t.Cleanup(github.ResetWebhookTrackerForTestWithClock(func() time.Time { return now })) + s, _ := stageTrackerFixture(t, now) + clock := now + s.stageTrackerNudge.now = func() time.Time { return clock } + if _, _, _, fresh := s.stageTrackerPayload(s.status, now); !fresh { + t.Fatal("first payload builds") + } + attempts := github.NewMergeAttempts(func() time.Time { return clock }) + attempts.SetOnChange(s.noteMergeAttempt) + attempts.Begin("acme/console", 101, github.PRAuditPathSweep) + if _, _, _, fresh := s.stageTrackerPayload(s.status, now); !fresh { + t.Fatal("beginning a merge attempt must drop the memoised payload") + } + ch := make(chan []byte, 4) + s.sseMu.Lock() + s.sseClients[ch] = struct{}{} + s.sseMu.Unlock() + clock = now.Add(2 * stageTrackerNudgeInterval) + attempts.End("acme/console", 101, false, errors.New("base branch was modified")) + + s.statusMu.RLock() + cur := s.status + s.statusMu.RUnlock() + after := s.buildStageTracker(cur, s.stageStore, now) + trackerItem(t, after, "pr", 101) + if len(s.mergedLedger().Summary(now, time.UTC).Recent) != 0 { + t.Fatal("a refused merge must not reach the merged ledger") + } + select { + case <-ch: + default: + t.Fatal("a refused merge attempt must nudge open tabs") + } +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 091eac8b87..c9b45643e9 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -186,8 +186,13 @@ type Server struct { // "Merged" chip (merged_ledger.go); built lazily by mergedLedger. merged *MergedLedger mergedOnce sync.Once - sidebar interface{} - sidebarMu sync.RWMutex + // recentlyClosed is the in-memory list behind + // StageTrackerResponse.RecentlyClosed (stage_tracker_recently_closed.go). + recentlyClosedMu sync.Mutex + recentlyClosed []StageTrackerClosed + + sidebar interface{} + sidebarMu sync.RWMutex // startedAt marks process start, used by /api/livez to bound the // startup-grace window before the first heartbeat has to have succeeded. @@ -1526,8 +1531,8 @@ func NewServerWithAuth(port int, authToken string, logger *slog.Logger) *Server } s.registerCoreRoutes() // A merge attempt beginning or ending is a tracker change the next poll - // must see (hivecommons/hive#15245). - github.DefaultMergeAttempts().SetOnChange(func() { s.invalidateStageTrackerCache() }) + // must see (hivecommons/hive#15245, #15808). + github.DefaultMergeAttempts().SetOnChange(s.noteMergeAttempt) return s } diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 63101fb6a2..d16c1fe4e3 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -81,6 +81,17 @@ type StageTrackerResponse struct { // the SPA tell "merged" from "closed" between two polls and play its // opt-in merge sound for the right rows. RecentlyMerged []StageTrackerMerged `json:"recently_merged,omitempty"` + // RecentlyClosed lists the pull requests that left Items closed but + // not merged within stageTrackerMergedWindow — superseded, withdrawn, + // closed by a decision — as the webhook / sweep / audit paths saw them + // (stage_tracker_recently_closed.go). With RecentlyMerged it lets the + // SPA tell a close from a merge when a row vanishes between two polls + // and say so instead of staying silent (hivecommons/hive#15808). + RecentlyClosed []StageTrackerClosed `json:"recently_closed,omitempty"` + // MergedHoldMS is dashboard.stage_tracker.merged_hold_s in + // milliseconds: how long the SPA may keep a vanished row at "Merging · + // merge landed" while it waits for the merged fact. + MergedHoldMS int `json:"merged_hold_ms"` // Merged24h is the same list over the last 24 hours, newest first. It // seeded the SPA's former "Merged today" counter; the Merged chip now // reads Merged (the durable ledger) and this stays for older SPAs. @@ -114,7 +125,14 @@ type StageTrackerMerged struct { MergedAt time.Time `json:"merged_at"` } -// stageTrackerMergedWindow bounds RecentlyMerged. It is deliberately much +// StageTrackerClosed is one recently closed, unmerged pull request. +type StageTrackerClosed struct { + Repo string `json:"repo"` + Number int `json:"number"` + ClosedAt time.Time `json:"closed_at"` +} + +// stageTrackerMergedWindow bounds RecentlyMerged (and RecentlyClosed). It is deliberately much // longer than the cache TTL plus the SPA's 30 s poll: a tab that missed a // few polls (throttled in the background) still sees the merge it was // watching for, and the SPA dedupes per PR so a longer list never replays. diff --git a/src/pkg/dashboard/stage_tracker_actor_icon_test.go b/src/pkg/dashboard/stage_tracker_actor_icon_test.go index 1b3460dd77..a65d5b28a7 100644 --- a/src/pkg/dashboard/stage_tracker_actor_icon_test.go +++ b/src/pkg/dashboard/stage_tracker_actor_icon_test.go @@ -203,7 +203,7 @@ func TestStageTrackerMergedCounterPlacement(t *testing.T) { t.Errorf("index.html still carries the retired %q", gone) } } - for _, fn := range []string{"celebrateRow", "stageTrackerMergedCountDraw", "hamMergedToggle"} { + for _, fn := range []string{"stageTrackerFlyGlyph", "stageTrackerMergedCountDraw", "hamMergedToggle"} { src := jsFunc(t, html, fn) if strings.Contains(src, "getElementById('activity-monitor-merged')") || !strings.Contains(src, "stageTrackerMergedChip()") { t.Errorf("%s must resolve the chip through stageTrackerMergedChip() so the flight, the draw and the popover share one node", fn) diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index 029fce0787..c7e366de7b 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -32,6 +32,8 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } qualify := stageTrackerRepoQualifier(status) resp.RecentlyMerged = s.stageTrackerRecentlyMerged(now, qualify) + resp.RecentlyClosed = s.stageTrackerRecentlyClosed(now) + resp.MergedHoldMS = int(s.stageTrackerMergedHold() / time.Millisecond) resp.Merged24h = s.stageTrackerMergedSince(now, stageTrackerMergedDayWindow, qualify) resp.Merged = s.mergedSummaryNow(now) if status == nil { diff --git a/src/pkg/dashboard/stage_tracker_cues_test.go b/src/pkg/dashboard/stage_tracker_cues_test.go index 11a91c2943..b1a1a37a4d 100644 --- a/src/pkg/dashboard/stage_tracker_cues_test.go +++ b/src/pkg/dashboard/stage_tracker_cues_test.go @@ -354,6 +354,9 @@ func stageTrackerCelebrateJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerRectInView"), jsFunc(t, html, "stageTrackerFlightTarget"), jsFunc(t, html, "celebrateRow"), + jsFunc(t, html, "stageTrackerFlyGlyph"), + jsFunc(t, html, "stageTrackerDetachedOrigin"), + jsFunc(t, html, "celebrateDetached"), jsFunc(t, html, "stageTrackerMergeBannerNumber"), jsFunc(t, html, "stageTrackerMergeBannerText"), jsFunc(t, html, "stageTrackerMergeBanner"), @@ -432,7 +435,7 @@ let renders = 0; function renderStageTracker() { renders++; } const srcs = new Map(); function stageTrackerRowSrcOf(node) { return srcs.get(node); } let _stageTrackerEvents = {}; const STAGE_TRACKER_TERMINAL = 110; -var _stageTrackerPRHost = {}; var _stageTrackerPRTitle = {}; var _stageTrackerMergeState = null, _stageTrackerZapped = {}, _stageTrackerMerged = { server: null, local: {} }, _stageTrackerMergedShown = 0, _stageTrackerCelebrating = {}, _stageTrackerCelebratePending = {}, _stageTrackerMergedHeld = {}, _stageTrackerFlights = 0, _stageTrackerReleaseTimer = 0; +var _stageTrackerPRHost = {}; var _stageTrackerPRTitle = {}; var _stageTrackerMergeState = null, _stageTrackerZapped = {}, _stageTrackerMerged = { server: null, local: {} }, _stageTrackerMergedShown = 0, _stageTrackerCelebrating = {}, _stageTrackerCelebratePending = {}, _stageTrackerFlights = 0, _stageTrackerReleaseTimer = 0; let settingsClosed = 0; function closeStageTrackerSettings() { settingsClosed++; } const odoText = e => e.getAttribute('data-odo-value'); const flights = () => body.children.filter(c => c.classList.contains('cue-flight')); @@ -501,8 +504,11 @@ assert.strictEqual(flights().length, 0); assert.strictEqual(odoText(n), '7'); assert.ok(panel.querySelector('[data-ham-key="o/r/pr#8"]').classList.contains('cue-merged')); reduced = false; -// 4. A merged PR not on the board still counts. +// 4. A merged PR not on the board still counts — and its bee flies from +// the toast (#15808): the count rolls when it lands, not before. stageTrackerNoteMerges(items(9)); stageTrackerNoteMerges(payloadMerged(9)); tick(0); +assert.strictEqual(odoText(n), '7', 'held for the detached bee'); assert.strictEqual(flights().length, 1, 'a bee with no row'); +tick(STAGE_TRACKER_CELEBRATE_FLY_MS * 1.5 + 1); assert.strictEqual(odoText(n), '8'); assert.strictEqual(flights().length, 0); assert.ok(banners.children.some(b => /#9<\/span> merged/.test(b.innerHTML) && !b.innerHTML.includes('hamBannerShowRow')), 'its banner has no "show row" (no row)'); @@ -857,37 +863,24 @@ console.log('ok'); } // TestStageTrackerOdometerWaitsForMergingHoldNode (owner: "the odometer -// still updates before the bee animation lands on it"): the merge gate's -// hold (#15245) masks a landed merge as still open for the banner's -// lifetime, and the poll that brought it also brings the server's raised -// ledger total. The drum used to roll on that poll — the hold kept the -// bee grounded while nothing kept the number — so the landing, a full -// hold later, found nothing left to roll. The chip now holds the masked -// merges back like flights to come: the number waits through the hold, -// through the flight, and rolls once on the landing. Runs the real hold -// functions (the other celebration tests stub them off). +// still updates before the bee animation lands on it"; then #15808: the +// "Merging · merge landed" mask "displays too long"): with the real hold +// functions in place of the stubs, the poll that brings the merged fact +// launches the bee at once — the hold no longer masks a known merge for +// a fixed window — and the drum still rolls only on the landing (#15763), +// through a bridged poll (PR dropped before its fact) and through two +// merges in quick succession. func TestStageTrackerOdometerWaitsForMergingHoldNode(t *testing.T) { html := indexHTML(t) for _, want := range []string{ - "_stageTrackerMergedHeld = {};", - "masked.held.forEach(k => { _stageTrackerMergedHeld[k] = true; });", - "stageTrackerMergedHoldback(_stageTrackerMerged, _stageTrackerCelebratePending, _stageTrackerMergedHeld)", + "stageTrackerMergedHoldback(_stageTrackerMerged, _stageTrackerCelebratePending)", + "function stageTrackerMergedInFlight() { return _stageTrackerFlights > 0 || Object.keys(_stageTrackerCelebratePending).length > 0; }", } { if !strings.Contains(html, want) { t.Errorf("index.html missing %q", want) } } - holdOn := strings.Join([]string{ - jsConstLine(t, html, "STAGE_TRACKER_MERGING_HOLD_MS"), - jsConstLine(t, html, "STAGE_TRACKER_MERGE_QUEUE"), - "var _stageTrackerMergingHold = {}; var _stageTrackerPRItems = {}; var _stageTrackerMergingHoldTimer = 0; var _stageTracker = null;", - jsFunc(t, html, "stageTrackerPRItemsOf"), - jsFunc(t, html, "stageTrackerMergingHoldLive"), - jsFunc(t, html, "stageTrackerMergingHoldNext"), - jsFunc(t, html, "stageTrackerMergingHoldMask"), - jsFunc(t, html, "stageTrackerMergingHoldSchedule"), - jsFunc(t, html, "stageTrackerMergingHoldRelease"), - }, "\n") + holdOn := stageTrackerMergingHoldJS(t, html) js := strings.Replace(stageTrackerCelebrateJS(t, html), stageTrackerMergingHoldOffJS, holdOn, 1) if js == stageTrackerCelebrateJS(t, html) { t.Fatal("the hold stub was not swapped for the real functions") @@ -901,65 +894,69 @@ const pr = (num, stage, mg) => Object.assign({ repo: 'o/r', kind: 'pr', number: // The poll handler: remember the payload (the hold's release re-reads it) and note it. const poll = d => { _stageTracker = d; stageTrackerNoteMerges(d); }; panel.appendChild(row('o/r/pr#1')); -poll({ items: [pr(1, 90)], merged: srv(40, 2, rec(31, 30)) }); +poll({ items: [pr(1, 90)], merged: srv(40, 2, rec(31, 30)), merged_hold_ms: 8000 }); assert.strictEqual(odoText(n), '40', 'hydrated'); assert.strictEqual(odoText(sub), '2 today · 2 this week'); +assert.strictEqual(stageTrackerMergingHoldMs(), 8000, 'knob read from the payload'); // The sweep is merging #1: the gate says so. tick(5000); const T = clock; poll({ items: [pr(1, 95, { state: 'merging', merging_since: iso(T) })], merged: srv(40, 2, rec(31, 30)) }); assert.strictEqual(odoText(n), '40'); -// Next poll: #1 landed — the items dropped it, the ledger counts it (41), -// recently_merged settles it. The hold masks the merge for the banner's -// lifetime, so no bee launches yet; the number must wait with it. -tick(5000); +// Next poll: the items dropped #1 but neither the ledger nor +// recently_merged has it yet — the bridge: no bee, no roll, the row is +// synthesised at "Merging" (stageTrackerMergingHoldView) and a release is +// scheduled for the hold's end. +tick(2000); +poll({ items: [], merged: srv(40, 2, rec(31, 30)) }); +tick(0); +assert.strictEqual(flights().length, 0, 'no merged fact yet: no bee'); +assert.strictEqual(odoText(n), '40'); +assert.strictEqual(stageTrackerMergingHoldView(_stageTracker, _stageTrackerMergingHold, clock).items.length, 1, 'bridged row'); +assert.ok(_stageTrackerMergingHoldTimer, 'release scheduled'); +// The merged fact lands 3 s later (well inside the 8 s window): the bee +// launches NOW, the number waits for it. +tick(3000); poll({ items: [], recently_merged: [{ repo: 'o/r', number: 1, merged_at: iso(clock) }], merged: srv(41, 3, rec(1, 31, 30)) }); tick(0); -assert.strictEqual(flights().length, 0, 'the hold keeps the bee grounded'); -assert.strictEqual(odoText(n), '40', 'the total waits for the bee (it used to roll here, a full hold early)'); assert.strictEqual(rolling(n).length, 0); +assert.strictEqual(flights().length, 1, 'the bee launches with the merged fact, not at the end of a fixed hold'); +assert.deepStrictEqual(_stageTrackerMergingHold, {}, 'hold dropped with the fact'); +assert.strictEqual(odoText(n), '40', 'held under the flight'); assert.strictEqual(rolling(n).length, 0); assert.strictEqual(odoText(sub), '2 today · 2 this week', 'so does the day line'); -assert.ok(!chip.classList.contains('cue-tick'), 'no pop'); +assert.ok(!chip.classList.contains('cue-tick'), 'no pop yet'); assert.deepStrictEqual(zaps, []); -// A further poll inside the hold with the same numbers: still waiting. -tick(10000); -poll({ items: [], recently_merged: [{ repo: 'o/r', number: 1, merged_at: iso(T) }], merged: srv(41, 3, rec(1, 31, 30)) }); -assert.strictEqual(odoText(n), '40', 'a repeat poll does not leak the number either'); -// The hold ends: the merge is re-read as fresh, the bee launches, the number still waits. -tick(T + STAGE_TRACKER_MERGING_HOLD_MS - clock + 60); -tick(0); -assert.strictEqual(flights().length, 1, 'the bee launches when the hold ends'); -assert.strictEqual(odoText(n), '40', 'held under the flight'); assert.strictEqual(rolling(n).length, 0); +assert.strictEqual(banners.children.length, 1, 'one merge banner'); assert.ok(banners.children[0].innerHTML.includes('#1'), banners.children[0].innerHTML); // The bee lands: one roll, to the server's number. flights()[0]._ev.animationend(); assert.strictEqual(flights().length, 0); assert.strictEqual(odoText(n), '41', 'the landing rolls it'); assert.strictEqual(rolling(n).length, 1, 'rolled, not set'); assert.strictEqual(odoText(sub), '3 today · 3 this week'); assert.ok(chip.classList.contains('cue-tick'), 'pop with the roll'); assert.deepStrictEqual(zaps, [1], 'zap with the roll'); -assert.ok(chip.title.startsWith('Merged: 41 all time'), chip.title); tick(STAGE_TRACKER_ODOMETER_MS + 100); +// The scheduled release fires later and finds nothing to do: no second celebration. +tick(10000); +assert.strictEqual(flights().length, 0); assert.strictEqual(banners.children.length, 1, 'celebrated exactly once'); // Steady afterwards: the same ledger does not move it again. poll({ items: [], merged: srv(41, 3, rec(1, 31, 30)) }); assert.strictEqual(odoText(n), '41'); assert.strictEqual(rolling(n).length, 0); -// Two merges in quick succession, each through its own hold: nothing is lost — the display ends on the server's value. +// Two merges in quick succession, their facts arriving with the polls +// that drop them (the webhook-style patch, #15808): each flies at once; +// the number ends on the server's value after the last landing. zaps.length = 0; chip.classList.remove('cue-tick'); panel.appendChild(row('o/r/pr#2')); panel.appendChild(row('o/r/pr#3')); poll({ items: [pr(2, 90), pr(3, 90)], merged: srv(41, 3, rec(1, 31, 30)) }); -tick(1000); const T2 = clock; -poll({ items: [pr(2, 95, { state: 'merging', merging_since: iso(T2) }), pr(3, 90)], merged: srv(41, 3, rec(1, 31, 30)) }); -tick(3000); const T3 = clock; -poll({ items: [pr(3, 95, { state: 'merging', merging_since: iso(T3) })], recently_merged: [{ repo: 'o/r', number: 2 }], merged: srv(42, 4, rec(2, 1, 31, 30)) }); -assert.strictEqual(odoText(n), '41', '#2 held'); +tick(1000); +poll({ items: [pr(2, 95, { state: 'merging', merging_since: iso(clock) }), pr(3, 90)], merged: srv(41, 3, rec(1, 31, 30)) }); tick(3000); +poll({ items: [pr(3, 95, { state: 'merging', merging_since: iso(clock) })], recently_merged: [{ repo: 'o/r', number: 2 }], merged: srv(42, 4, rec(2, 1, 31, 30)) }); +tick(0); +assert.strictEqual(flights().length, 1, '#2 flies at once'); +assert.strictEqual(odoText(n), '41', 'held under #2'); +tick(1000); poll({ items: [], recently_merged: [{ repo: 'o/r', number: 2 }, { repo: 'o/r', number: 3 }], merged: srv(43, 5, rec(3, 2, 1, 31, 30)) }); -assert.strictEqual(odoText(n), '41', '#2 and #3 held'); -// #2's hold ends first: its bee flies and lands; the number still waits for #3, whose hold is live. -tick(T2 + STAGE_TRACKER_MERGING_HOLD_MS - clock + 60); tick(0); -assert.strictEqual(flights().length, 1, '#2 flies'); +tick(0); +assert.strictEqual(flights().length, 2, '#3 flies too'); flights()[0]._ev.animationend(); -assert.strictEqual(odoText(n), '41', 'still held: #3 is masked (its bee is to come), and a landing never leaves a merge uncounted'); -// #3's hold ends: its bee flies and lands; the display reaches the server's value. -tick(T3 + STAGE_TRACKER_MERGING_HOLD_MS - clock + 60); tick(0); -assert.strictEqual(flights().length, 1, '#3 flies'); -assert.strictEqual(odoText(n), '41', 'held under its flight'); +assert.strictEqual(odoText(n), '41', 'still held: #3 is in the air, and a landing never leaves a merge uncounted'); flights()[0]._ev.animationend(); assert.strictEqual(odoText(n), '43', 'final displayed value == server value'); assert.strictEqual(odoText(sub), '5 today · 5 this week'); @@ -1060,3 +1057,53 @@ func TestStageTrackerMergeBannersAboveChatFab(t *testing.T) { t.Errorf(".hive-chat-fab z-index moved; keep it below --z-merge-banner (10001): %s", fab) } } + +// TestStageTrackerDetachedCelebrationNode (hivecommons/hive#15808, #15707): +// a merge whose row is not in the DOM — below the fold, filtered, already +// evicted — still gets all three: the toast, a bee that flies from the +// toast's ✓ to the chip, and the odometer rolling +1 once it lands. The +// pipeline is one: no second toast, flight or count for the same PR on a +// later payload. +func TestStageTrackerDetachedCelebrationNode(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerCelebrateJS(t, html)+stageTrackerCelebrateFixture+` +stageTrackerSetCelebrate(true); +panel.rect = { left: 0, top: 100, width: 900, height: 600 }; +const srv = (all, today, recent) => ({ all_time: all, today, total_7d: today, total_30d: today, recent, tz: 'UTC', day_start: clock - 3600000 }); +const rec = (num) => ({ repo: 'o/r', number: num, title: 't' + num, merged_at: new Date(clock).toISOString(), lane: 'trusted-author' }); +// #15707 was listed open once but never drawn into the panel (below the +// fold / filtered / evicted by the webhook before the ledger listed it). +stageTrackerNoteMerges(Object.assign(items(1, 15707), { merged: srv(40, 1, []) })); +stageTrackerMergedCountDraw(false); +assert.strictEqual(odoText(n), '40', 'seeded'); +assert.strictEqual(flights().length, 0); +// Merged fact arrives; the row is not in the DOM. +stageTrackerNoteMerges({ items: items(1).items, recently_merged: [{ repo: 'o/r', number: 15707 }], merged: srv(41, 2, [rec(15707)]) }); +stageTrackerMergedCountDraw(false); +assert.strictEqual(banners.children.length, 1, 'toast'); +assert.ok(banners.children[0].innerHTML.includes('#15707'), 'toast names the PR'); +assert.strictEqual(odoText(n), '40', 'odometer waits for the bee (#15763)'); +tick(0); +assert.strictEqual(flights().length, 1, 'bee flies without a row'); +assert.strictEqual(odoText(n), '40', 'still held while in flight'); +tick(STAGE_TRACKER_CELEBRATE_FLY_MS * 1.5 + 10); +assert.strictEqual(flights().length, 0, 'landed'); +assert.strictEqual(odoText(n), '41', 'odometer +1 after landing'); +assert.deepStrictEqual(zaps, [1], 'one zap'); +// Same PR again (ledger still lists it; payload repeats): nothing more. +stageTrackerNoteMerges({ items: items(1).items, recently_merged: [{ repo: 'o/r', number: 15707 }], merged: srv(41, 2, [rec(15707)]) }); +tick(STAGE_TRACKER_CELEBRATE_FLY_MS * 1.5 + 10); +assert.strictEqual(banners.children.length, 1, 'one toast'); +assert.strictEqual(flights().length, 0, 'no second bee'); +assert.strictEqual(odoText(n), '41', 'count unchanged'); +assert.deepStrictEqual(zaps, [1]); +// Pure origin: banner box wins, then the panel's foot, then the viewport, else null. +const bn = { left: 10, top: 20, width: 16, height: 16 }; +assert.strictEqual(stageTrackerDetachedOrigin(bn, panel.rect, 1280, 800), bn); +const foot = stageTrackerDetachedOrigin(null, panel.rect, 1280, 800); +assert.strictEqual(foot.left + foot.width / 2, 450, 'panel centre'); +assert.ok(foot.top + foot.height <= 700, 'at the panel foot'); +assert.strictEqual(stageTrackerDetachedOrigin(null, null, 1280, 800).top + 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, 800); +assert.strictEqual(stageTrackerDetachedOrigin(null, null, 0, 0), null); +`) +} diff --git a/src/pkg/dashboard/stage_tracker_merge_gate.go b/src/pkg/dashboard/stage_tracker_merge_gate.go index 468e1e9fb1..0f60dcf110 100644 --- a/src/pkg/dashboard/stage_tracker_merge_gate.go +++ b/src/pkg/dashboard/stage_tracker_merge_gate.go @@ -51,6 +51,9 @@ type StageTrackerMergeGate struct { // SweepRunning is true while an automerge pass that evaluates this PR // is in flight. SweepRunning bool `json:"sweep_running,omitempty"` + // SweepingSince is when that pass started, so the SPA can say + // "waiting for GitHub…" once it has been on the PR a while (#15808). + SweepingSince *time.Time `json:"sweeping_since,omitempty"` // LastSweepAt is when the lane last evaluated this PR (the stage // record's LastSeen). LastSweepAt *time.Time `json:"last_sweep_at,omitempty"` @@ -164,6 +167,10 @@ func stageTrackerMergeGate(repo string, number int, stage stagelabels.Stage, rec } if sweep.OnPR(repo, number) { mg.SweepRunning = true + if !sweep.StartedAt.IsZero() { + t := sweep.StartedAt + mg.SweepingSince = &t + } } else if !sweep.NextFloorAt.IsZero() && sweep.NextFloorAt.After(now) { t := sweep.NextFloorAt mg.NextSweepAt = &t diff --git a/src/pkg/dashboard/stage_tracker_merge_gate_test.go b/src/pkg/dashboard/stage_tracker_merge_gate_test.go index 3c2eedf73d..8b575b20e0 100644 --- a/src/pkg/dashboard/stage_tracker_merge_gate_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_gate_test.go @@ -363,7 +363,8 @@ func stageTrackerTrainProvisionalJS(t *testing.T, html string) string { // stageTrackerSoakClockJS lifts the soak-clock helpers the gate pill reads. func stageTrackerSoakClockJS(t *testing.T, html string) string { t.Helper() - return jsFunc(t, html, "stageTrackerSoakClock") + "\n" + + return jsConstLine(t, html, "STAGE_TRACKER_MERGING_SLOW_MS") + "\n" + + jsFunc(t, html, "stageTrackerSoakClock") + "\n" + jsFunc(t, html, "stageTrackerSoakLeftText") + "\n" + jsFunc(t, html, "stageTrackerClockText") + "\n" + jsFunc(t, html, "stageTrackerNextPassWords") + "\n" + diff --git a/src/pkg/dashboard/stage_tracker_merging_hold_test.go b/src/pkg/dashboard/stage_tracker_merging_hold_test.go index 56517ce938..24929f956e 100644 --- a/src/pkg/dashboard/stage_tracker_merging_hold_test.go +++ b/src/pkg/dashboard/stage_tracker_merging_hold_test.go @@ -97,51 +97,82 @@ func TestStageTrackerMergeGateAttemptOverlay(t *testing.T) { } // stageTrackerMergingHoldOffJS stands in for the merge-gate "Merging" hold -// (#15245) in harnesses that watch what happens the moment a merge is -// seen: no hold, every merge is read as fresh at once. The hold itself is -// covered by TestStageTrackerMergingHold. +// (#15245, #15808) in harnesses that watch what happens the moment a +// merge is seen: no hold, no closed list. The hold itself is covered by +// TestStageTrackerMergingHold. const stageTrackerMergingHoldOffJS = ` -var _stageTrackerMergingHold = {}; var _stageTrackerPRItems = {}; +var _stageTrackerMergingHold = {}; var _stageTrackerPRItems = {}; var _stageTrackerPRLast = {}; var _stageTrackerClosedNoted = {}; var _stageTrackerMergingHoldMs = 8000; +function stageTrackerMergingHoldMsOf(d, cur) { return cur; } function stageTrackerPRItemsOf() { return {}; } function stageTrackerMergingHoldNext() { return {}; } -function stageTrackerMergingHoldMask(raw) { return { state: raw, held: [], until: 0 }; } +function stageTrackerMergingHoldUntil() { return 0; } function stageTrackerMergingHoldSchedule() {} +function stageTrackerNewlyClosed() { return []; } ` +// stageTrackerMergingHoldJS lifts the real hold and closed-reconcile +// functions. +func stageTrackerMergingHoldJS(t *testing.T, html string) string { + t.Helper() + return strings.Join([]string{ + jsConstLine(t, html, "STAGE_TRACKER_MERGE_QUEUE"), + jsConstLine(t, html, "STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS"), + jsConstLine(t, html, "STAGE_TRACKER_MERGING_HOLD_MIN_MS"), + jsConstLine(t, html, "STAGE_TRACKER_CLOSED_REASON_MAX"), + "var _stageTrackerMergingHoldMs = STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; var _stageTrackerMergingHold = {}; var _stageTrackerPRItems = {}; var _stageTrackerPRLast = {}; var _stageTrackerClosedNoted = {}; var _stageTrackerMergingHoldTimer = 0; var _stageTracker = null;", + jsFunc(t, html, "stageTrackerMergingHoldMsOf"), + jsFunc(t, html, "stageTrackerMergingHoldMs"), + jsFunc(t, html, "stageTrackerPRItemsOf"), + jsFunc(t, html, "stageTrackerMergingHoldLive"), + jsFunc(t, html, "stageTrackerMergingHoldNext"), + jsFunc(t, html, "stageTrackerMergingHoldUntil"), + jsFunc(t, html, "stageTrackerMergingHoldItem"), + jsFunc(t, html, "stageTrackerMergingHoldView"), + jsFunc(t, html, "stageTrackerMergingHoldSchedule"), + jsFunc(t, html, "stageTrackerMergingHoldRelease"), + jsFunc(t, html, "stageTrackerNewlyClosed"), + jsFunc(t, html, "stageTrackerClosedReason"), + jsFunc(t, html, "stageTrackerClosedToastText"), + jsFunc(t, html, "stageTrackerClosedToast"), + }, "\n") +} + // TestStageTrackerMergingHold runs the SPA's merge-gate hold under node -// with an explicit clock (hivecommons/hive#15245): "Merging" stays lit -// for at least the merge banner's lifetime before a row advances to ✓, -// whether or not the payload ever showed the merge in flight; a refused -// merge drops the hold at once. +// with an explicit clock (hivecommons/hive#15245, #15808): a row the +// payload dropped mid-merge stays at "Merging" only until the merged fact +// lands — then the merge is fresh at once — or the hold window +// (merged_hold_ms, default 8 s, floor 3 s) passes; a merge whose fact +// arrives with the poll is never masked; a refused merge drops the hold. func TestStageTrackerMergingHold(t *testing.T) { html := indexHTML(t) for _, want := range []string{ - "const STAGE_TRACKER_MERGING_HOLD_MS = STAGE_TRACKER_MERGE_BANNER_MS;", - "_stageTrackerMergingHold = stageTrackerMergingHoldNext(_stageTrackerMergingHold, d, _stageTrackerMergeState, raw, _stageTrackerPRItems, nowMs);", + "_stageTrackerMergingHoldMs = stageTrackerMergingHoldMsOf(d, _stageTrackerMergingHoldMs);", + "_stageTrackerMergingHold = stageTrackerMergingHoldNext(_stageTrackerMergingHold, d, raw, nowMs);", "stageTrackerMergingHoldView(_stageTracker, _stageTrackerMergingHold, nowMs)", } { if !strings.Contains(html, want) { t.Errorf("index.html missing %q", want) } } + if strings.Contains(html, "STAGE_TRACKER_MERGING_HOLD_MS") || strings.Contains(html, "_stageTrackerMergedHeld") { + t.Error("the fixed 30 s hold mask is gone: no STAGE_TRACKER_MERGING_HOLD_MS / _stageTrackerMergedHeld") + } runStageTrackerRowActionsScript(t, strings.Join([]string{ jsConstLine(t, html, "STAGE_TRACKER_TERMINAL"), - jsConstLine(t, html, "STAGE_TRACKER_MERGE_BANNER_MS"), - jsConstLine(t, html, "STAGE_TRACKER_MERGING_HOLD_MS"), - jsConstLine(t, html, "STAGE_TRACKER_MERGE_QUEUE"), jsFunc(t, html, "stageTrackerPRKey"), jsFunc(t, html, "stageTrackerMergeState"), jsFunc(t, html, "stageTrackerCarryOpen"), jsFunc(t, html, "stageTrackerNewlyMerged"), - jsFunc(t, html, "stageTrackerPRItemsOf"), - jsFunc(t, html, "stageTrackerMergingHoldLive"), - jsFunc(t, html, "stageTrackerMergingHoldNext"), - jsFunc(t, html, "stageTrackerMergingHoldMask"), - jsFunc(t, html, "stageTrackerMergingHoldItem"), - jsFunc(t, html, "stageTrackerMergingHoldView"), + stageTrackerMergingHoldJS(t, html), }, "\n")+` const assert = require('assert'); -assert.strictEqual(STAGE_TRACKER_MERGING_HOLD_MS, STAGE_TRACKER_MERGE_BANNER_MS, 'the hold is the toast lifetime'); +assert.strictEqual(STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS, 8000, 'default hold 8 s'); +assert.strictEqual(STAGE_TRACKER_MERGING_HOLD_MIN_MS, 3000, 'floor 3 s'); +assert.strictEqual(stageTrackerMergingHoldMsOf({ merged_hold_ms: 12000 }, 8000), 12000); +assert.strictEqual(stageTrackerMergingHoldMsOf({ merged_hold_ms: 1000 }, 8000), 3000, 'clamped to the floor'); +assert.strictEqual(stageTrackerMergingHoldMsOf({}, 5000), 5000, 'absent: value in force'); +assert.strictEqual(stageTrackerMergingHoldMsOf(null, 0), 8000, 'absent, nothing in force: default'); +const HOLD = stageTrackerMergingHoldMs(); const T0 = Date.parse('2026-10-28T21:31:00Z'); const iso = ms => new Date(ms).toISOString(); const pr = (n, stage, mg) => Object.assign({ kind: 'pr', repo: 'o/r', number: n, stage, title: 'feat ' + n }, mg ? { merge_gate: mg } : {}); @@ -150,39 +181,36 @@ const K = n => stageTrackerPRKey('o/r', n); // One poll loop: feed payloads in order with an explicit clock, the way // stageTrackerNoteMerges does, and return what each poll read as fresh. function run(polls) { - let holds = {}, state = null, items = {}; + let holds = {}, state = null; const out = []; for (const [nowMs, d] of polls) { const raw = stageTrackerCarryOpen(state, stageTrackerMergeState(d)); - holds = stageTrackerMergingHoldNext(holds, d, state, raw, items, nowMs); - const masked = stageTrackerMergingHoldMask(raw, holds, nowMs); - items = stageTrackerPRItemsOf(d); - const fresh = stageTrackerNewlyMerged(state, masked.state); - state = masked.state; - out.push({ fresh, held: masked.held, until: masked.until, holds, view: stageTrackerMergingHoldView(d, holds, nowMs) }); + holds = stageTrackerMergingHoldNext(holds, d, raw, nowMs); + const until = stageTrackerMergingHoldUntil(holds, nowMs); + const fresh = stageTrackerNewlyMerged(state, raw); + state = raw; + out.push({ fresh, until, holds, view: stageTrackerMergingHoldView(d, holds, nowMs) }); } return out; } // 1. The sweep's merge call is seen in flight (merging_since) at T0; the -// next poll (30 s later) reports the PR merged. The merge is masked -// until T0 + hold; the board keeps a stage-100 "Merging" row for #1 -// with the gate saying the merge landed; the poll at/after the end -// reads it as fresh and the synthesised row is gone. +// next poll drops the PR but the merged fact has not landed yet: the +// board keeps a stage-100 "Merging" row for #1, the gate waiting for +// GitHub. The poll that brings the merged fact reads it fresh AT ONCE +// (no 30 s wait) and the synthesised row is gone. let r = run([ [T0 - 30000, { items: [pr(1, 60), pr(2, 50)] }], - [T0 + 3000, { items: [pr(1, 100, { state: 'merging', merging_since: iso(T0), merge_path: 'sweep' }), pr(2, 50)] }], - [T0 + 15000, { items: [pr(2, 50)], recently_merged: [{ repo: 'o/r', number: 1 }] }], - [T0 + 29000, { items: [pr(2, 50)], recently_merged: [{ repo: 'o/r', number: 1 }] }], - [T0 + STAGE_TRACKER_MERGING_HOLD_MS, { items: [pr(2, 50)], recently_merged: [{ repo: 'o/r', number: 1 }] }], + [T0 + 1000, { items: [pr(1, 100, { state: 'merging', merging_since: iso(T0), merge_path: 'sweep' }), pr(2, 50)] }], + [T0 + 3000, { items: [pr(2, 50)] }], + [T0 + 5000, { items: [pr(2, 50)], recently_merged: [{ repo: 'o/r', number: 1 }] }], ]); assert.deepStrictEqual(r[1].fresh, [], 'in flight: nothing fresh'); assert.strictEqual(r[1].holds[K(1)].since, T0, 'hold opens from merging_since'); assert.strictEqual(r[1].holds[K(1)].path, 'sweep'); assert.strictEqual(r[1].view.items.length, 2, 'payload lists the PR: no synthesised row'); -assert.deepStrictEqual(r[2].fresh, [], 'merged inside the hold: masked'); -assert.deepStrictEqual(r[2].held, [K(1)]); -assert.strictEqual(r[2].until, T0 + STAGE_TRACKER_MERGING_HOLD_MS, 'release scheduled for the hold end'); +assert.deepStrictEqual(r[2].fresh, [], 'dropped without the merged fact: nothing fresh yet'); +assert.strictEqual(r[2].until, T0 + HOLD, 'release scheduled for the hold end'); const held = r[2].view.items.find(it => it.number === 1); assert.ok(held && held.held_merging === true, 'held row synthesised'); assert.strictEqual(held.stage, STAGE_TRACKER_MERGE_QUEUE); @@ -194,78 +222,120 @@ assert.strictEqual(held.merge_gate.merge_path, 'sweep'); assert.strictEqual(held.actor, 'hive'); assert.strictEqual(held.stage_actor.kind, 'hive'); assert.strictEqual(held.title, 'feat 1', 'row keeps its last item'); -assert.deepStrictEqual(r[3].fresh, [], 'still masked one second before the end'); -assert.deepStrictEqual(r[4].fresh, [K(1)], 'at the hold end the merge is fresh'); -assert.deepStrictEqual(r[4].held, []); -assert.strictEqual(r[4].until, 0); -assert.deepStrictEqual(r[4].holds, {}, 'hold dropped once its window passed'); -assert.strictEqual(r[4].view, r[4].view, 'view is the payload itself once nothing is held'); -assert.strictEqual(r[4].view.items.length, 1); +assert.ok(held.caption.includes('waiting for GitHub'), held.caption); +assert.deepStrictEqual(r[3].fresh, [K(1)], 'the merged fact makes it fresh at once, 5 s into an 8 s window'); +assert.deepStrictEqual(r[3].holds, {}, 'hold dropped with the merged fact'); +assert.strictEqual(r[3].until, 0); +assert.strictEqual(r[3].view.items.length, 1, 'no synthesised row once nothing is held'); // 2. A merge never seen in flight (060 at one poll, merged at the next): -// the hold opens from that poll, from the last open item, so "Merging" -// still shows before ✓. +// fresh on that poll — no hold, no mask (the fixed "Merging" dwell is +// gone, #15808). r = run([ [T0, { items: [pr(3, 60)] }], [T0 + 30000, { items: [], recently_merged: [{ repo: 'o/r', number: 3 }] }], - [T0 + 30000 + STAGE_TRACKER_MERGING_HOLD_MS - 1, { items: [], recently_merged: [{ repo: 'o/r', number: 3 }] }], - [T0 + 30000 + STAGE_TRACKER_MERGING_HOLD_MS, { items: [], recently_merged: [{ repo: 'o/r', number: 3 }] }], ]); -assert.deepStrictEqual(r[1].fresh, [], 'surprise merge: masked'); -assert.strictEqual(r[1].holds[K(3)].since, T0 + 30000, 'hold opens at the poll that reported it'); -assert.strictEqual(r[1].view.items.length, 1, 'row stays on the board'); -assert.strictEqual(r[1].view.items[0].stage, STAGE_TRACKER_MERGE_QUEUE); -assert.strictEqual(r[1].view.items[0].merge_gate.merge_path, undefined, 'no path known'); -assert.deepStrictEqual(r[2].fresh, []); -assert.deepStrictEqual(r[3].fresh, [K(3)], 'fresh exactly at the hold end'); +assert.deepStrictEqual(r[1].fresh, [K(3)], 'surprise merge: fresh at once'); +assert.deepStrictEqual(r[1].holds, {}); +assert.strictEqual(r[1].view.items.length, 0); -// 3. A merge seen in flight long enough ago: no extra wait. Seen merging -// at T0, merged reported at T0 + hold + 5 s: fresh at once. +// 3. The merged fact arrives with the very poll that drops the PR +// (webhook-style patch, the common case now): fresh at once. r = run([ [T0, { items: [pr(4, 100, { state: 'merging', merging_since: iso(T0) })] }], - [T0 + STAGE_TRACKER_MERGING_HOLD_MS + 5000, { items: [], recently_merged: [{ repo: 'o/r', number: 4 }] }], + [T0 + 2000, { items: [], recently_merged: [{ repo: 'o/r', number: 4 }] }], ]); -assert.deepStrictEqual(r[1].fresh, [K(4)], 'hold already satisfied: fresh now'); +assert.deepStrictEqual(r[1].fresh, [K(4)]); assert.deepStrictEqual(r[1].holds, {}); -// 4. A refused merge drops the hold at once; the row is the payload's -// (merge-failed at the gate), not a synthesised one. +// 4. The merged fact never arrives: the hold expires at its window and +// the row leaves; nothing is read as fresh (a later recently_merged +// entry still settles it through stageTrackerCarryOpen). r = run([ [T0, { items: [pr(5, 100, { state: 'merging', merging_since: iso(T0) })] }], - [T0 + 2000, { items: [pr(5, 90, { state: 'merge-failed', merge_failed: '405 not mergeable' })] }], + [T0 + 2000, { items: [] }], + [T0 + HOLD - 1, { items: [] }], + [T0 + HOLD, { items: [] }], + [T0 + HOLD + 60000, { items: [], recently_merged: [{ repo: 'o/r', number: 5 }] }], ]); -assert.ok(r[0].holds[K(5)]); +assert.strictEqual(r[1].view.items.length, 1, 'bridged'); +assert.strictEqual(r[2].view.items.length, 1, 'still bridged one ms before the end'); +assert.deepStrictEqual(r[3].holds, {}, 'window passed: hold dropped'); +assert.strictEqual(r[3].view.items.length, 0); +assert.deepStrictEqual(r[3].fresh, []); +assert.deepStrictEqual(r[4].fresh, [K(5)], 'the late fact still settles it'); + +// 5. A refused merge drops the hold at once; the row is the payload's +// (merge-failed at the gate), not a synthesised one. +r = run([ + [T0, { items: [pr(6, 100, { state: 'merging', merging_since: iso(T0) })] }], + [T0 + 2000, { items: [pr(6, 90, { state: 'merge-failed', merge_failed: '405 not mergeable' })] }], +]); +assert.ok(r[0].holds[K(6)]); assert.deepStrictEqual(r[1].holds, {}, 'merge-failed drops the hold'); assert.strictEqual(r[1].view.items[0].merge_gate.state, 'merge-failed'); // …as does a PR that is back open at another gate state without merging. r = run([ - [T0, { items: [pr(6, 100, { state: 'merging', merging_since: iso(T0) })] }], - [T0 + 2000, { items: [pr(6, 95, { state: 'soaking' })] }], + [T0, { items: [pr(7, 100, { state: 'merging', merging_since: iso(T0) })] }], + [T0 + 2000, { items: [pr(7, 95, { state: 'soaking' })] }], ]); assert.deepStrictEqual(r[1].holds, {}, 'back to soaking: no hold'); -// 5. Merging_since missing: the hold runs from first sight and is kept +// 6. merging_since missing: the hold runs from first sight and is kept // across polls; a non-PR item never holds. r = run([ - [T0, { items: [pr(7, 100, { state: 'merging' }), { kind: 'issue', repo: 'o/r', number: 8, stage: 100, merge_gate: { state: 'merging' } }] }], - [T0 + 1000, { items: [pr(7, 100, { state: 'merging' })] }], + [T0, { items: [pr(8, 100, { state: 'merging' }), { kind: 'issue', repo: 'o/r', number: 9, stage: 100, merge_gate: { state: 'merging' } }] }], + [T0 + 1000, { items: [pr(8, 100, { state: 'merging' })] }], ]); -assert.strictEqual(r[0].holds[K(7)].since, T0); -assert.strictEqual(r[1].holds[K(7)].since, T0, 'since kept from the first sight'); +assert.strictEqual(r[0].holds[K(8)].since, T0); +assert.strictEqual(r[1].holds[K(8)].since, T0, 'since kept from the first sight'); assert.strictEqual(Object.keys(r[0].holds).length, 1, 'issues do not hold'); -// Mask leaves state untouched for keys without a live hold and does not -// mutate its input. -const raw = { a: true, b: false }; -const m = stageTrackerMergingHoldMask(raw, { a: { since: T0 - STAGE_TRACKER_MERGING_HOLD_MS - 1 } }, T0); -assert.deepStrictEqual(m, { state: { a: true, b: false }, held: [], until: 0 }); -assert.deepStrictEqual(raw, { a: true, b: false }); +// 7. The knob: a payload's merged_hold_ms stretches the bridge. +_stageTrackerMergingHoldMs = stageTrackerMergingHoldMsOf({ merged_hold_ms: 20000 }, _stageTrackerMergingHoldMs); +r = run([ + [T0, { items: [pr(10, 100, { state: 'merging', merging_since: iso(T0) })] }], + [T0 + 15000, { items: [] }], +]); +assert.strictEqual(r[1].view.items.length, 1, 'still bridged at 15 s under a 20 s hold'); +_stageTrackerMergingHoldMs = STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; + +// ---- Closed, not merged (#15808) ---- +// The tab saw #11 and #12 open; the next payload drops #11 and lists it +// in recently_closed: one key, once. #12 (still open) and #13 (never +// seen) are not reported; a merged PR in both lists reads as merged. +let state = stageTrackerCarryOpen(null, stageTrackerMergeState({ items: [pr(11, 50, {}), pr(12, 50)] })); +let d = { items: [pr(12, 50)], recently_closed: [{ repo: 'o/r', number: 11 }, { repo: 'o/r', number: 12 }, { repo: 'o/r', number: 13 }] }; +let raw = stageTrackerCarryOpen(state, stageTrackerMergeState(d)); +const noted = {}; +let closed = stageTrackerNewlyClosed(d, state, raw, stageTrackerPRItemsOf(d), noted); +assert.deepStrictEqual(closed, [K(11)]); +closed.forEach(k => { noted[k] = true; }); +assert.deepStrictEqual(stageTrackerNewlyClosed(d, state, raw, stageTrackerPRItemsOf(d), noted), [], 'noted once'); +d = { items: [], recently_closed: [{ repo: 'o/r', number: 12 }], recently_merged: [{ repo: 'o/r', number: 12 }] }; +raw = stageTrackerCarryOpen(state, stageTrackerMergeState(d)); +assert.deepStrictEqual(stageTrackerNewlyClosed(d, state, raw, {}, noted), [], 'merged outranks closed'); +assert.deepStrictEqual(stageTrackerNewlyClosed({ recently_closed: [{ repo: 'o/r', number: 11 }] }, null, {}, {}, {}), [], 'first poll: nothing to compare'); +// The reason comes from the row's last item. +assert.strictEqual(stageTrackerClosedReason({ caption: 'Superseded by #15783 — hive carries the fix there', superseded_by: 15783 }), 'superseded by #15783'); +assert.strictEqual(stageTrackerClosedReason({ caption: 'closed as superseded by #15783 after adoption' }), 'superseded by #15783'); +assert.strictEqual(stageTrackerClosedReason({ caption: 'Duplicate of #40; held out of the queue' }), 'duplicate of #40'); +assert.strictEqual(stageTrackerClosedReason({ caption: 'Awaiting review; reviewer verdict pending' }), 'Awaiting review'); +assert.strictEqual(stageTrackerClosedReason({ caption: 'x'.repeat(100) }).length, STAGE_TRACKER_CLOSED_REASON_MAX); +assert.strictEqual(stageTrackerClosedReason(null), 'closed without merging'); +assert.strictEqual(stageTrackerClosedReason({ caption: '' }), 'closed without merging'); +assert.strictEqual(stageTrackerClosedToastText(K(15793), { superseded_by: 15783 }), '#15793 closed · superseded by #15783'); +const toasts = []; +global.showToast = (msg, type) => { toasts.push([type, msg]); return {}; }; +stageTrackerClosedToast(K(15793), { caption: 'superseded by #15783' }); +assert.deepStrictEqual(toasts, [['info', '#15793 closed · superseded by #15783']], 'neutral info toast, standard countdown'); console.log('ok'); `) } // TestStageTrackerMergeGateInfoMerging: the gate pill's words for a live -// merge call, a held row and a refused merge (hivecommons/hive#15245). +// merge call (and a slow one), a held row and a refused merge +// (hivecommons/hive#15245, #15808). func TestStageTrackerMergeGateInfoMerging(t *testing.T) { html := indexHTML(t) runStageTrackerRowActionsScript(t, strings.Join([]string{ @@ -282,17 +352,23 @@ func TestStageTrackerMergeGateInfoMerging(t *testing.T) { const assert = require('assert'); const now = Date.parse('2026-10-28T21:31:00Z'); const item = mg => ({ kind: 'pr', repo: 'o/r', number: 1, stage: 100, merge_gate: mg }); -let info = stageTrackerMergeGateInfoFor(item({ state: 'merging', merging_since: new Date(now - 4000).toISOString(), merge_path: 'sweep' }), now); +let info = stageTrackerMergeGateInfoFor(item({ state: 'merging', merging_since: new Date(now - 4000).toISOString(), merge_path: 'sweep' }), null, now); assert.strictEqual(info.word, 'Merging'); assert.strictEqual(info.detail, 'merge call in flight'); assert.strictEqual(info.cue, 'merging'); assert.ok(info.tip.includes('automerge sweep') && info.tip.includes('in flight'), info.tip); -info = stageTrackerMergeGateInfoFor(item({ state: 'merging', merging_since: new Date(now - 4000).toISOString(), merge_path: 'dashboard', held: true }), now); -assert.strictEqual(info.detail, 'merge landed'); +info = stageTrackerMergeGateInfoFor(item({ state: 'merging', merging_since: new Date(now - 4000).toISOString(), merge_path: 'dashboard', held: true }), null, now); +assert.strictEqual(info.detail, 'waiting for GitHub', 'a held row waits for the merged fact (#15808)'); assert.ok(info.tip.includes('maintainer merge from the dashboard') && info.tip.includes('✓'), info.tip); -info = stageTrackerMergeGateInfoFor(item({ state: 'merging' }), now); +// A merge call in flight longer than STAGE_TRACKER_MERGING_SLOW_MS says so +// rather than spinning without a reason (#15808). +info = stageTrackerMergeGateInfoFor(item({ state: 'merging', merging_since: new Date(now - STAGE_TRACKER_MERGING_SLOW_MS - 1000).toISOString(), merge_path: 'sweep' }), null, now); +assert.strictEqual(info.detail, 'merging · waiting for GitHub…'); +assert.ok(info.tip.includes('longer than usual'), info.tip); +assert.strictEqual(info.cue, 'merging'); +info = stageTrackerMergeGateInfoFor(item({ state: 'merging' }), null, now); assert.strictEqual(info.detail, '', 'legacy 100 record: word alone'); -info = stageTrackerMergeGateInfoFor(Object.assign(item({ state: 'merge-failed', merge_failed: 'merging PR o/r#1 (abc): 405 Pull Request is not mergeable\nmore', merge_failed_at: new Date(now - 9000).toISOString(), merge_path: 'relay' }), { stage: 90 }), now); +info = stageTrackerMergeGateInfoFor(Object.assign(item({ state: 'merge-failed', merge_failed: 'merging PR o/r#1 (abc): 405 Pull Request is not mergeable\nmore', merge_failed_at: new Date(now - 9000).toISOString(), merge_path: 'relay' }), { stage: 90 }), null, now); assert.strictEqual(info.state, 'merge-failed'); assert.strictEqual(info.word, 'Merge failed'); assert.strictEqual(info.detail, 'branch protection', 'kind words, never the raw error'); @@ -304,3 +380,55 @@ assert.strictEqual(stageTrackerMergeFailedShort('x'.repeat(80)).length, STAGE_TR console.log('ok'); `) } + +// TestStageTrackerRemovedRowReconcileNode (hivecommons/hive#15808): a row +// that leaves the payload is reconciled on removal with the real hold and +// closed-list functions in the celebration harness — gone with the merged +// fact (here only the durable ledger's recent list carries it) → exactly +// one celebration (banner, bee, count on landing), never a second on the +// next poll; gone and listed in recently_closed → one neutral info toast +// with the reason from the row's last caption, no bee, no banner, no +// count. +func TestStageTrackerRemovedRowReconcileNode(t *testing.T) { + html := indexHTML(t) + js := strings.Replace(stageTrackerCelebrateJS(t, html), stageTrackerMergingHoldOffJS, stageTrackerMergingHoldJS(t, html), 1) + runStageTrackerRowActionsScript(t, js+stageTrackerCelebrateFixture+` +const iso = ms => new Date(ms).toISOString(); +const rec = (...nums) => nums.map(x => ({ repo: 'o/r', number: x, title: 'fix ' + x, merged_at: iso(clock), merged_by: 'hive', lane: 'hive' })); +const srv = (all, today, recent) => ({ all_time: all, today, total_7d: today, total_30d: today, recent, tz: 'UTC', day_start: iso(stageTrackerLocalMidnight(clock)) }); +const pr = (num, stage, extra) => Object.assign({ repo: 'o/r', kind: 'pr', number: num, stage, title: 'fix ' + num }, extra || {}); +const poll = d => { _stageTracker = d; stageTrackerNoteMerges(d); }; +panel.appendChild(row('o/r/pr#5')); panel.appendChild(row('o/r/pr#6')); +poll({ items: [pr(5, 50), pr(6, 50, { caption: 'Superseded by #7 — hive carries the fix there', superseded_by: 7 })], merged: srv(10, 1, rec(3)) }); +assert.strictEqual(odoText(n), '10'); +// #5 vanishes; the SPA never saw merging or a terminal stage, only the +// ledger's recent list says merged → celebrate once. +tick(10000); +poll({ items: [pr(6, 50, { caption: 'Superseded by #7 — hive carries the fix there', superseded_by: 7 })], merged: srv(11, 2, rec(5, 3)) }); +tick(0); +assert.strictEqual(banners.children.length, 1, 'one banner'); assert.ok(banners.children[0].innerHTML.includes('#5')); +assert.strictEqual(flights().length, 1, 'one bee'); +assert.strictEqual(odoText(n), '10', 'count waits for the landing'); +assert.deepStrictEqual(toasts, [], 'a merge is not a closed toast'); +flights()[0]._ev.animationend(); +assert.strictEqual(odoText(n), '11'); +tick(10000); +poll({ items: [pr(6, 50, { caption: 'Superseded by #7 — hive carries the fix there', superseded_by: 7 })], merged: srv(11, 2, rec(5, 3)) }); +tick(0); +assert.strictEqual(banners.children.length, 1, 'never a second celebration'); assert.strictEqual(flights().length, 0); +// #6 vanishes closed, not merged: one info toast naming the reason. +tick(10000); +poll({ items: [], recently_closed: [{ repo: 'o/r', number: 6, closed_at: iso(clock) }], merged: srv(11, 2, rec(5, 3)) }); +tick(0); +assert.deepStrictEqual(toasts, [['info', '#6 closed · superseded by #7']]); +assert.strictEqual(banners.children.length, 1, 'no merge banner for a close'); assert.strictEqual(flights().length, 0, 'no bee'); +assert.strictEqual(odoText(n), '11', 'no count'); +tick(10000); +poll({ items: [], recently_closed: [{ repo: 'o/r', number: 6, closed_at: iso(clock) }], merged: srv(11, 2, rec(5, 3)) }); +assert.strictEqual(toasts.length, 1, 'toasted once'); +// A PR this tab never saw open and that closes is not news. +poll({ items: [], recently_closed: [{ repo: 'o/r', number: 6 }, { repo: 'o/r', number: 8 }], merged: srv(11, 2, rec(5, 3)) }); +assert.strictEqual(toasts.length, 1); +console.log('ok'); +`) +} diff --git a/src/pkg/dashboard/stage_tracker_recently_closed.go b/src/pkg/dashboard/stage_tracker_recently_closed.go new file mode 100644 index 0000000000..a74ba1e5ef --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_recently_closed.go @@ -0,0 +1,98 @@ +package dashboard + +import ( + "sort" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" +) + +// The activity monitor only ever lists open work, so a PR that closed +// without merging simply drops out of Items; the SPA could not tell that +// from a merge whose audit entry had not landed yet, and said nothing +// (hivecommons/hive#15808: #15793, superseded by #15783, "vanished"). Every +// closed-unmerged PR snapshot that reaches applyWebhookItemSnapshots — a +// webhook's embedded state or confirming read, the closed sweep, a +// hive-mediated close (ApplyPRTerminalAudit) — is remembered here for +// stageTrackerMergedWindow and served as recently_closed, the closed twin +// of recently_merged. + +// stageTrackerRecentlyClosedCap bounds the in-memory list. +const stageTrackerRecentlyClosedCap = 200 + +// noteClosedSnapshots remembers every closed, unmerged PR among snaps. +func (s *Server) noteClosedSnapshots(snaps []github.WebhookItemSnapshot) { + if s == nil || len(snaps) == 0 { + return + } + now := time.Now() + qualify := s.mergedRepoQualifier() + s.recentlyClosedMu.Lock() + defer s.recentlyClosedMu.Unlock() + for _, snap := range snaps { + if !snap.IsPR || snap.Open() || snap.Merged || snap.Number <= 0 || snap.Repo == "" { + continue + } + repo := qualify(snap.Repo) + at := snap.UpdatedAt + if at.IsZero() || at.After(now) { + at = now + } + dup := false + for i := range s.recentlyClosed { + if s.recentlyClosed[i].Number == snap.Number && strings.EqualFold(s.recentlyClosed[i].Repo, repo) { + dup = true + break + } + } + if dup { + continue + } + s.recentlyClosed = append(s.recentlyClosed, StageTrackerClosed{Repo: repo, Number: snap.Number, ClosedAt: at.UTC()}) + } + s.pruneRecentlyClosedLocked(now) +} + +// pruneRecentlyClosedLocked drops entries older than the window and, past +// the cap, the oldest. Caller holds recentlyClosedMu. +func (s *Server) pruneRecentlyClosedLocked(now time.Time) { + cut := now.Add(-stageTrackerMergedWindow) + kept := s.recentlyClosed[:0] + for _, e := range s.recentlyClosed { + if !e.ClosedAt.Before(cut) { + kept = append(kept, e) + } + } + if len(kept) > stageTrackerRecentlyClosedCap { + kept = kept[len(kept)-stageTrackerRecentlyClosedCap:] + } + s.recentlyClosed = kept +} + +// stageTrackerRecentlyClosed is the list as the payload carries it: newest +// first, within stageTrackerMergedWindow of now. +func (s *Server) stageTrackerRecentlyClosed(now time.Time) []StageTrackerClosed { + if s == nil { + return nil + } + s.recentlyClosedMu.Lock() + defer s.recentlyClosedMu.Unlock() + s.pruneRecentlyClosedLocked(now) + if len(s.recentlyClosed) == 0 { + return nil + } + out := append([]StageTrackerClosed(nil), s.recentlyClosed...) + sort.SliceStable(out, func(i, j int) bool { return out[i].ClosedAt.After(out[j].ClosedAt) }) + return out +} + +// stageTrackerMergedHold is dashboard.stage_tracker.merged_hold_s as the +// server reads it (the config default when no config is wired). +func (s *Server) stageTrackerMergedHold() time.Duration { + if s != nil && s.deps != nil && s.deps.Config != nil { + return s.deps.Config.StageTrackerMergedHold() + } + return (*config.Config)(nil).StageTrackerMergedHold() +} diff --git a/src/pkg/dashboard/stage_tracker_recently_closed_test.go b/src/pkg/dashboard/stage_tracker_recently_closed_test.go new file mode 100644 index 0000000000..98da1eef9d --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_recently_closed_test.go @@ -0,0 +1,51 @@ +package dashboard + +import ( + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" +) + +// TestStageTrackerRecentlyClosed: closed-unmerged PR snapshots are +// remembered once each, newest first, within the merged window; open, +// merged and issue snapshots are not (hivecommons/hive#15808). +func TestStageTrackerRecentlyClosed(t *testing.T) { + s := &Server{} + now := time.Now() + snaps := []github.WebhookItemSnapshot{ + {Repo: "o/r", Number: 15793, IsPR: true, State: "closed", UpdatedAt: now.Add(-time.Minute)}, + {Repo: "o/r", Number: 15805, IsPR: true, State: "closed", Merged: true, UpdatedAt: now}, + {Repo: "o/r", Number: 15791, IsPR: true, State: "open"}, + {Repo: "o/r", Number: 7, IsPR: false, State: "closed"}, + {Repo: "o/r", Number: 15700, IsPR: true, State: "closed", UpdatedAt: now.Add(-stageTrackerMergedWindow - time.Minute)}, + {Repo: "o/r", Number: 15790, IsPR: true, State: "closed", UpdatedAt: now}, + } + s.noteClosedSnapshots(snaps) + s.noteClosedSnapshots(snaps[:1]) + got := s.stageTrackerRecentlyClosed(now) + if len(got) != 2 || got[0].Number != 15790 || got[1].Number != 15793 { + t.Fatalf("recently closed = %+v, want [15790 15793]", got) + } + if got := s.stageTrackerRecentlyClosed(now.Add(stageTrackerMergedWindow + time.Second)); got != nil { + t.Fatalf("outside the window = %+v, want none", got) + } +} + +// TestStageTrackerMergedHoldKnob: dashboard.stage_tracker.merged_hold_s +// defaults to 8 s, floors at 3 s, and the server reads the config default +// with no config wired. +func TestStageTrackerMergedHoldKnob(t *testing.T) { + cases := map[int]time.Duration{0: 8 * time.Second, 1: 3 * time.Second, 3: 3 * time.Second, 20: 20 * time.Second} + for in, want := range cases { + c := &config.Config{} + c.Dashboard.StageTracker.MergedHoldS = in + if got := c.StageTrackerMergedHold(); got != want { + t.Errorf("merged_hold_s=%d: got %s, want %s", in, got, want) + } + } + if got := (&Server{}).stageTrackerMergedHold(); got != 8*time.Second { + t.Errorf("server default = %s, want 8s", got) + } +} diff --git a/src/pkg/dashboard/static-src/js/tracker-merged.js b/src/pkg/dashboard/static-src/js/tracker-merged.js index 2732784dd9..d100c047b4 100644 --- a/src/pkg/dashboard/static-src/js/tracker-merged.js +++ b/src/pkg/dashboard/static-src/js/tracker-merged.js @@ -49,21 +49,26 @@ function stageTrackerNoteMerges(d) { const nowMs = Date.now(); + _stageTrackerMergingHoldMs = stageTrackerMergingHoldMsOf(d, _stageTrackerMergingHoldMs); const raw = stageTrackerCarryOpen(_stageTrackerMergeState, stageTrackerMergeState(d)); - // The merge gate holds "Merging" for at least the merge toast's - // lifetime before the row advances to ✓ (hivecommons/hive#15245): a - // merge that lands inside the hold is masked as still open until it - // ends, then re-read as fresh. - _stageTrackerMergingHold = stageTrackerMergingHoldNext(_stageTrackerMergingHold, d, _stageTrackerMergeState, raw, _stageTrackerPRItems, nowMs); - const masked = stageTrackerMergingHoldMask(raw, _stageTrackerMergingHold, nowMs); - if (masked.until) stageTrackerMergingHoldSchedule(masked.until - nowMs); - // The Merged chip holds the masked merges back too: the server - // already counts them, their glyph has not even launched yet. - _stageTrackerMergedHeld = {}; - masked.held.forEach(k => { _stageTrackerMergedHeld[k] = true; }); + // The merge gate's hold (hivecommons/hive#15245, #15808) keeps a + // row the payload dropped mid-merge on the board at "Merging" until + // the merged fact arrives (then the merge is fresh at once) or the + // hold window passes. + _stageTrackerMergingHold = stageTrackerMergingHoldNext(_stageTrackerMergingHold, d, raw, nowMs); + const until = stageTrackerMergingHoldUntil(_stageTrackerMergingHold, nowMs); + if (until) stageTrackerMergingHoldSchedule(until - nowMs); + const prevItems = _stageTrackerPRItems; _stageTrackerPRItems = stageTrackerPRItemsOf(d); - const next = masked.state; + Object.assign(_stageTrackerPRLast, _stageTrackerPRItems); + const next = raw; const fresh = stageTrackerNewlyMerged(_stageTrackerMergeState, next).filter(k => !_stageTrackerZapped[k]); + // A PR that left the board closed, not merged (recently_closed, the + // closed twin of recently_merged): say so once, neutrally — no bee, + // no count — instead of letting the row vanish in silence. + const closed = stageTrackerNewlyClosed(d, _stageTrackerMergeState, next, _stageTrackerPRItems, _stageTrackerClosedNoted); + const closedItems = closed.map(k => prevItems[k] || _stageTrackerPRLast[k]); + closed.forEach(k => { _stageTrackerClosedNoted[k] = true; delete next[k]; delete _stageTrackerPRLast[k]; }); _stageTrackerMergeState = next; // A merged PR is no longer in this payload, so its last host survives. if (typeof stageTrackerPRHosts === 'function') Object.assign(_stageTrackerPRHost, stageTrackerPRHosts(d)); @@ -73,33 +78,54 @@ if (celebrate) fresh.forEach(k => { _stageTrackerCelebratePending[k] = true; }); if (typeof stageTrackerMergedSync === 'function') stageTrackerMergedSync(d, fresh, Date.now()); if (typeof stageTrackerQueueSync === 'function') stageTrackerQueueSync(d && d.items, Date.now()); + if (typeof stageTrackerClosedToast === 'function') closed.forEach((k, i) => stageTrackerClosedToast(k, closedItems[i])); if (!fresh.length) return; fresh.forEach(k => { _stageTrackerZapped[k] = true; }); if (celebrate) { stageTrackerCelebrateMerges(fresh); return; } if (stageTrackerSoundGate()) stageTrackerPlayZap(Math.min(fresh.length, STAGE_TRACKER_SOUND_MAX_PLAYS)); } - /* ---- Merge gate: "Merging" held for the toast's lifetime (#15245) ---- - Operator: "I have seen some items go straight to merge without - showing in the Merge gate column as 'merging' for at least as long - as the merge toast is open." The sweep merges inside one pass, so a - PR can go from 060/090/095 to merged between two polls and the - intermediate state is never on screen. The payload's merge_gate now - says merging (with merging_since) while the merge call is in flight; - the SPA keeps a hold per PR from the first moment it saw merging — - or, for a merge it never saw coming, from the poll that reported it - merged — and until STAGE_TRACKER_MERGING_HOLD_MS (the merge - banner's lifetime) has passed the row stays on the board at 100 - "Merging" (its last item, synthesised when the payload dropped it) - and the merge is not counted as fresh. When the hold ends the merge - is re-read: the row advances to ✓, the banner opens, the chip bumps. - A refused merge (merge_gate.state merge-failed) drops the hold at - once and the pill says why. All pure except the schedule/release - pair; run under node by stage_tracker_merging_hold_test.go. */ + /* ---- Merge gate: "Merging" bridged until the merged fact (#15245, #15808) ---- + Operator (#15245): "I have seen some items go straight to merge + without showing in the Merge gate column as 'merging'." The sweep + merges inside one pass, so a PR can go from 060/090/095 to merged + between two polls. The payload's merge_gate says merging (with + merging_since) while the merge call is in flight; when the payload + then drops the PR before the merged fact (recently_merged / the + ledger) has landed, the SPA keeps a hold per PR — from the moment + it saw merging — and until the hold window has passed the row stays + on the board at 100 "Merging" (its last item, synthesised), the + gate saying it is waiting for GitHub to confirm. + Operator (#15808): the hold used to be a fixed 30 s mask over the + merged fact itself — "Merging · merge landed" sat there while the + bee waited — and a row that vanished without the SPA seeing merged + never celebrated. Now the hold only bridges the gap: the moment the + merged fact is in a payload the hold drops, the merge is fresh and + the celebration launches (bee, then the odometer on its landing, + #15763). The window is dashboard.stage_tracker.merged_hold_s + (payload merged_hold_ms; default 8 s, floor 3 s), a ceiling, not a + delay. A refused merge (merge-failed) drops the hold at once. All + pure except the schedule/release pair; run under node by + stage_tracker_merging_hold_test.go. */ const STAGE_TRACKER_MERGE_QUEUE = 100; + const STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS = 8000; + const STAGE_TRACKER_MERGING_HOLD_MIN_MS = 3000; + var _stageTrackerMergingHoldMs = STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; var _stageTrackerMergingHold = {}; var _stageTrackerPRItems = {}; + // PR key → the last item ever seen for it (survives the payload + // dropping it: the closed toast's reason, the hold's row). + var _stageTrackerPRLast = {}; + var _stageTrackerClosedNoted = {}; var _stageTrackerMergingHoldTimer = 0; + // Pure: the hold window from a payload's merged_hold_ms (clamped to the + // floor), else the value in force. + function stageTrackerMergingHoldMsOf(d, cur) { + const n = d && typeof d === 'object' ? Number(d.merged_hold_ms) : 0; + if (!(n > 0)) return cur || STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; + return Math.max(STAGE_TRACKER_MERGING_HOLD_MIN_MS, n); + } + function stageTrackerMergingHoldMs() { return _stageTrackerMergingHoldMs || STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; } // Pure: PR key → item for one payload (the last open item a hold // synthesises its row from). function stageTrackerPRItemsOf(d) { @@ -107,21 +133,19 @@ for (const it of ((d && Array.isArray(d.items)) ? d.items : [])) if (it && it.kind === 'pr') out[stageTrackerPRKey(it.repo, it.number)] = it; return out; } - // Pure: whether a hold is still inside its minimum window at nowMs. - function stageTrackerMergingHoldLive(hold, nowMs) { return !!hold && nowMs < hold.since + STAGE_TRACKER_MERGING_HOLD_MS; } - // Pure: the holds after one payload. prevState / rawState are the - // merge-state maps (PR key → merged?) before and after it; prevItems the - // PR items of the previous payload. + // Pure: whether a hold is still inside its window at nowMs. + function stageTrackerMergingHoldLive(hold, nowMs) { return !!hold && nowMs < hold.since + stageTrackerMergingHoldMs(); } + // Pure: the holds after one payload. rawState is the merge-state map + // (PR key → merged?) after it. // • a PR the payload shows at merge_gate.state 'merging' opens (or // keeps) a hold from merging_since (else from now, else the one it had) - // • a PR shown at 'merge-failed' — or open at any other state after a - // hold the payload no longer backs — drops its hold at once - // • a PR open before and merged now with no hold opens one from now, - // from its last open item, so "Merging" shows before ✓ - // • a hold whose window has passed is dropped (its merge, if any, is - // then read as fresh) - function stageTrackerMergingHoldNext(prev, d, prevState, rawState, prevItems, nowMs) { - prev = prev || {}; prevState = prevState || {}; rawState = rawState || {}; prevItems = prevItems || {}; + // • a PR shown at 'merge-failed' — or open at any other state — drops + // its hold at once + // • a held PR the payload dropped keeps its hold while the window is + // live and the merged fact is still missing; the merged fact (or + // the window's end) drops it — the merge is then read as fresh + function stageTrackerMergingHoldNext(prev, d, rawState, nowMs) { + prev = prev || {}; rawState = rawState || {}; const out = {}; const items = stageTrackerPRItemsOf(d); for (const key of Object.keys(items)) { @@ -134,39 +158,29 @@ // 'merge-failed' or any other open state: no hold. } for (const key of Object.keys(prev)) { - if (out[key] || items[key]) continue; + if (out[key] || items[key] || rawState[key] === true) continue; if (stageTrackerMergingHoldLive(prev[key], nowMs)) out[key] = prev[key]; } - for (const key of Object.keys(rawState)) { - // prev[key]: it was held and the window already passed — no second hold. - if (rawState[key] !== true || prevState[key] !== false || out[key] || prev[key] || items[key] || !prevItems[key]) continue; - out[key] = { since: nowMs, item: prevItems[key], path: '' }; - } return out; } - // Pure: rawState with every PR under a live hold read as still open; - // until is the earliest ms at which a masked hold ends (0 when none). - function stageTrackerMergingHoldMask(rawState, holds, nowMs) { - const state = Object.assign({}, rawState || {}); + // Pure: the earliest ms at which a live hold ends (0 when none). + function stageTrackerMergingHoldUntil(holds, nowMs) { let until = 0; - const held = []; for (const key of Object.keys(holds || {})) { const h = holds[key]; - if (state[key] !== true || !stageTrackerMergingHoldLive(h, nowMs)) continue; - state[key] = false; - held.push(key); - const end = h.since + STAGE_TRACKER_MERGING_HOLD_MS; + if (!stageTrackerMergingHoldLive(h, nowMs)) continue; + const end = h.since + stageTrackerMergingHoldMs(); if (!until || end < until) until = end; } - return { state, held: held.sort(), until }; + return until; } // Pure: the row a held PR shows while the payload no longer lists it — - // its last open item at 100 "Merging", the gate saying the merge landed. + // its last item at 100 "Merging", the gate waiting for GitHub's word. function stageTrackerMergingHoldItem(hold, key) { const base = hold && hold.item ? hold.item : { kind: 'pr' }; const mg = Object.assign({}, base.merge_gate || {}, { state: 'merging', merging_since: new Date(hold.since).toISOString(), held: true, sweep_running: false, next_sweep_at: '', soak_until: '', soak_remaining_seconds: 0 }); if (hold.path) mg.merge_path = hold.path; - return Object.assign({}, base, { stage: STAGE_TRACKER_MERGE_QUEUE, stage_slug: 'merge-queue', stage_label: 'stage/100-merge-queue', merge_gate: mg, caption: 'Merging now — the merge landed; ✓ follows', actor: 'hive', stage_actor: Object.assign({}, base.stage_actor || {}, { kind: 'hive', login: '', why: 'hive merged it; the row advances to ✓ in a moment' }), soak_remaining_seconds: 0, modifiers: (Array.isArray(base.modifiers) ? base.modifiers : []).filter(m => m !== 'stalled' && m !== 'blocked'), held_merging: true }); + return Object.assign({}, base, { stage: STAGE_TRACKER_MERGE_QUEUE, stage_slug: 'merge-queue', stage_label: 'stage/100-merge-queue', merge_gate: mg, caption: 'Merging — waiting for GitHub to confirm; ✓ follows', actor: 'hive', stage_actor: Object.assign({}, base.stage_actor || {}, { kind: 'hive', login: '', why: 'hive issued the merge; the row advances to ✓ once GitHub confirms' }), soak_remaining_seconds: 0, modifiers: (Array.isArray(base.modifiers) ? base.modifiers : []).filter(m => m !== 'stalled' && m !== 'blocked'), held_merging: true }); } // Pure: the payload as rendered — its items plus a synthesised row for // every live hold the payload dropped; d itself when there is none. @@ -182,7 +196,7 @@ return Object.assign({}, d, { items: d.items.concat(extra) }); } // Stateful: when the earliest live hold ends, re-read the last payload so - // the held merges come through as fresh and the rows advance to ✓. + // the synthesised row leaves the board. function stageTrackerMergingHoldSchedule(inMs) { if (_stageTrackerMergingHoldTimer) return; _stageTrackerMergingHoldTimer = setTimeout(stageTrackerMergingHoldRelease, Math.max(50, inMs + 50)); @@ -194,6 +208,55 @@ renderStageTracker(); } + /* ---- Closed, not merged: a neutral word on the way out (#15808) ---- + Operator: #15793 "vanished" at 11:46:54 and read as a silent merge; + it had been closed as superseded by #15783. Items only list open + work, so the SPA learns of a close the same way it learns of a + merge: a side list (recently_closed) names the PRs that left closed. + Every PR this tab saw open that the list now says closed gets one + info toast — "#15793 closed · superseded by #15783", the reason read + from the row's last caption — with the standard countdown; no bee, + no odometer. */ + const STAGE_TRACKER_CLOSED_REASON_MAX = 72; + // Pure: PR keys the tab saw open (prevState false, or carried open) that + // d.recently_closed lists, not merged, not listed open now, not yet noted. + function stageTrackerNewlyClosed(d, prevState, rawState, items, noted) { + const list = d && Array.isArray(d.recently_closed) ? d.recently_closed : []; + if (!list.length || !prevState) return []; + const out = []; + for (const c of list) { + if (!c || !c.repo || !c.number) continue; + const key = stageTrackerPRKey(c.repo, c.number); + if (prevState[key] !== false || rawState[key] === true || (items && items[key]) || (noted && noted[key]) || out.indexOf(key) >= 0) continue; + out.push(key); + } + return out.sort(); + } + // Pure: why a closed PR left, from its last item — "superseded by + // #15783" when the row said so, else its caption's first clause. + function stageTrackerClosedReason(it) { + if (!it) return 'closed without merging'; + const sup = Number(it.superseded_by) || Number(it.superseded && it.superseded.by) || 0; + const cap = String(it.caption || ''); + const m = cap.match(/superseded by #(\d+)/i) || cap.match(/duplicate of #(\d+)/i); + if (sup > 0) return 'superseded by #' + sup; + if (m) return (m[0].toLowerCase().startsWith('dup') ? 'duplicate of #' : 'superseded by #') + m[1]; + let clause = cap.split(/[;—]|\. /)[0].trim(); + if (!clause) return 'closed without merging'; + if (clause.length > STAGE_TRACKER_CLOSED_REASON_MAX) clause = clause.slice(0, STAGE_TRACKER_CLOSED_REASON_MAX - 1).trimEnd() + '…'; + return clause; + } + // Pure: the toast's words. + function stageTrackerClosedToastText(key, it) { + const n = Number(String(key || '').slice(String(key || '').indexOf('/pr#') + 4)) || 0; + return (n ? '#' + n + ' ' : '') + 'closed · ' + stageTrackerClosedReason(it); + } + // Stateful: one neutral toast for a PR that left the board closed. + function stageTrackerClosedToast(key, it) { + if (typeof showToast !== 'function') return null; + return showToast(stageTrackerClosedToastText(key, it), 'info'); + } + /* ---- tracker-cues: merged — pinned row, glyph flight, "Merged" chip --- Owner: "subtle but noticeable … a merge count that rises, and the celebration is something that rises out of the column and into the @@ -272,8 +335,6 @@ const STAGE_TRACKER_MERGED_LIST_MAX = 20; const STAGE_TRACKER_MERGE_BANNER_MS = 30000; const STAGE_TRACKER_MERGE_BANNER_MAX = 5; - // The merge gate's minimum "Merging" dwell is the merge banner's lifetime (#15245). - const STAGE_TRACKER_MERGING_HOLD_MS = STAGE_TRACKER_MERGE_BANNER_MS; function stageTrackerCelebrateSetting() { try { return localStorage.getItem(STAGE_TRACKER_CELEBRATE_KEY) !== '0'; } catch { return true; } } @@ -394,12 +455,6 @@ // Merges whose glyph is still on its way: the count holds them back // until stageTrackerCelebrateTick lands them. var _stageTrackerCelebratePending = {}; - // Merges the merge-gate hold (#15245) still masks as open: the server - // counts them already, the SPA has not read them as fresh yet, so no - // glyph is pending for them. Without this the drum rolled on the poll - // that brought the merge — a full banner-lifetime before the bee - // launched — and the landing found nothing left to roll. - var _stageTrackerMergedHeld = {}; // Stateful: fold one payload into the state and redraw the chip. The // count only bumps (pop + zap) through stageTrackerCelebrateTick; a // plain reload draws the server's number without a flourish. @@ -418,13 +473,12 @@ return stageTrackerMergedChip.node; } // Pure: how many merges the server already counts whose bump the chip - // still owes the bee — a glyph pending or in the air, or a merge the - // merge-gate hold masks until its flight can launch — so the landing + // still owes the bee — a glyph pending or in the air — so the landing // is when it bumps. - function stageTrackerMergedHoldback(state, pending, held) { + function stageTrackerMergedHoldback(state, pending) { const known = {}; for (const e of ((state && state.server && state.server.recent) || [])) known[stageTrackerMergedIdent(e.repo, e.number)] = true; - const keys = Object.assign({}, held || {}, pending || {}); + const keys = Object.assign({}, pending || {}); let n = 0; for (const key of Object.keys(keys)) { const i = key.indexOf('/pr#'); if (i > 0 && known[stageTrackerMergedIdent(key.slice(0, i), key.slice(i + 4))]) n++; } return n; @@ -580,18 +634,17 @@ } // Stateful: whether a celebration glyph is in the air or about to be // (stageTrackerCelebrateMerges staggers the launches; a merge is - // pending from the payload that brought it, or masked by the merge - // gate's hold until then). The drum and the zap wait on this; the - // flight's own end — its animationend, or stageTrackerAfter's timer - // at STAGE_TRACKER_CELEBRATE_FLY_MS when the event never fires — is - // what clears it. - // A merge the merge-gate hold still masks counts as a flight to come: - // its glyph launches when the hold ends and re-reads it as fresh. - function stageTrackerMergedInFlight() { return _stageTrackerFlights > 0 || Object.keys(_stageTrackerCelebratePending).length > 0 || Object.keys(_stageTrackerMergedHeld).length > 0; } + // pending from the payload that brought it). The drum and the zap + // wait on this; the flight's own end — its animationend, or + // stageTrackerAfter's timer at STAGE_TRACKER_CELEBRATE_FLY_MS when the + // event never fires — is what clears it. (The merge-gate hold no + // longer masks a known merge, #15808: the glyph is pending from the + // payload that brings the merged fact.) + function stageTrackerMergedInFlight() { return _stageTrackerFlights > 0 || Object.keys(_stageTrackerCelebratePending).length > 0; } function stageTrackerMergedCountDraw(tick) { const chip = stageTrackerMergedChip(); const now = Date.now(); - const txt = stageTrackerMergedText(_stageTrackerMerged, now, stageTrackerMergedHoldback(_stageTrackerMerged, _stageTrackerCelebratePending, _stageTrackerMergedHeld)); + const txt = stageTrackerMergedText(_stageTrackerMerged, now, stageTrackerMergedHoldback(_stageTrackerMerged, _stageTrackerCelebratePending)); // Never backwards within a tab: a server that has not caught up yet // (or lost a merge) does not make the number drop. if (txt.count > _stageTrackerMergedShown || tick) _stageTrackerMergedShown = Math.max(_stageTrackerMergedShown, txt.count); @@ -724,14 +777,38 @@ const startAt = now + i * STAGE_TRACKER_CELEBRATE_STAGGER_MS; if (rowKey) _stageTrackerCelebrating[rowKey] = { key, kind: 'merged', until: startAt + STAGE_TRACKER_CELEBRATE_PIN_MS }; const number = Number(key.slice(key.indexOf('/pr#') + 4)) || 0; - stageTrackerMergeBanner({ key, rowKey, number, repo: key.slice(0, key.indexOf('/pr#')), at: now }); + const banner = stageTrackerMergeBanner({ key, rowKey, number, repo: key.slice(0, key.indexOf('/pr#')), at: now }); setTimeout(() => { const row = rowKey && el ? el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) : null; if (row) celebrateRow(row, { kind: 'merged', key, number }); - else stageTrackerCelebrateTick(key); + else celebrateDetached(key, banner); }, i * STAGE_TRACKER_CELEBRATE_STAGGER_MS); }); } + // Pure: where a row-less glyph takes off — the banner's ✓ when it has + // a box, else the bottom centre of the panel (or the viewport). Null + // when nothing has a box (no layout, e.g. a hidden tab). + function stageTrackerDetachedOrigin(bannerRect, panelRect, vw, vh) { + const ok = r => !!r && r.width > 0 && r.height > 0; + if (ok(bannerRect)) return bannerRect; + if (ok(panelRect)) return { left: panelRect.left + panelRect.width / 2 - STAGE_TRACKER_CELEBRATE_GLYPH_HALF, top: Math.min(panelRect.top + panelRect.height, vh) - 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, width: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, height: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF }; + if (vw > 0 && vh > 0) return { left: vw / 2 - STAGE_TRACKER_CELEBRATE_GLYPH_HALF, top: vh - 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, width: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, height: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF }; + return null; + } + // Stateful: celebrate a merge whose row is not on the board (below the + // fold, filtered, another page, already evicted — hivecommons/hive#15808: + // #15707's toast showed, but no bee and no count). The glyph flies from + // the toast's ✓ (else the panel's foot) to the chip; the count rolls + // when it lands, exactly as for a drawn row. The toast, the bee and the + // odometer are one pipeline: a merged fact that reaches here has all three. + function celebrateDetached(key, banner, preview) { + const rect = el => el && typeof el.getBoundingClientRect === 'function' ? el.getBoundingClientRect() : null; + const ico = banner && typeof banner.querySelector === 'function' ? banner.querySelector('.merge-banner-ico') : null; + const vw = window.innerWidth || 0, vh = window.innerHeight || 0; + const from = stageTrackerDetachedOrigin(rect(ico) || rect(banner), rect(document.getElementById('activity-monitor-panel')), vw, vh); + if (!from) { stageTrackerCelebrateTick(key, preview); return { flew: false, lands: false }; } + return stageTrackerFlyGlyph(from, key, preview); + } // Pure: the rows a render must keep although the payload dropped them — // every celebrating row still inside its pin window, as the node it // already has (its HTML is replayed so the reconcile keeps it). @@ -792,13 +869,19 @@ } if (kind !== 'merged') return { flew: false }; const cap = rowEl.querySelector('.ham-seg.cap'); - if (!cap || _stageTrackerFlights >= STAGE_TRACKER_CELEBRATE_MAX_FLIGHTS || typeof cap.getBoundingClientRect !== 'function') { + if (!cap || typeof cap.getBoundingClientRect !== 'function') return celebrateDetached(key, null, preview); + return stageTrackerFlyGlyph(cap.getBoundingClientRect(), key, preview); + } + // Stateful: fly the glyph from a box to the chip (or fade it in place + // under reduced motion; count at once over the flight cap). Landing + // calls stageTrackerCelebrateTick, which rolls the odometer (#15763). + function stageTrackerFlyGlyph(from, key, preview) { + if (!from || _stageTrackerFlights >= STAGE_TRACKER_CELEBRATE_MAX_FLIGHTS) { stageTrackerCelebrateTick(key, preview); return { flew: false, lands: false }; } const reduced = stageTrackerReducedMotion(); const chip = stageTrackerMergedChip(); - const from = cap.getBoundingClientRect(); const vw = window.innerWidth || 0, vh = window.innerHeight || 0; const to = reduced ? { lands: false, dx: 0, dy: 0 } : stageTrackerFlightTarget(from, chip && typeof chip.getBoundingClientRect === 'function' ? chip.getBoundingClientRect() : null, vw, vh); const glyph = document.createElement('span'); diff --git a/src/pkg/dashboard/static-src/js/tracker-words-core.js b/src/pkg/dashboard/static-src/js/tracker-words-core.js index e70caaf2b5..061a99880d 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -93,6 +93,9 @@ // it alone); stage_tracker_merge_gate_test.go pins the two equal. const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Ready for auto merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' }; // merge_gate.merge_path (the merge call's issuer) in words (#15245). + // A merge call (or a sweep's pass on a soaked PR) older than this says + // "waiting for GitHub…" rather than spinning without a reason (#15808). + const STAGE_TRACKER_MERGING_SLOW_MS = 60000; const STAGE_TRACKER_MERGE_PATH_WORDS = { sweep: 'automerge sweep', dashboard: 'maintainer merge from the dashboard', relay: 'hive-merge relay', forge: 'forge adapter', queue: 'merge queue' }; const STAGE_TRACKER_MERGE_FAILED_SHORT_MAX = 60; const STAGE_TRACKER_ACTIVE_WORD = { 15: 'Triage needed', 17: 'Possibly exists', 60: 'Review passed', 80: 'Ready for auto merge', 95: 'Soaking', 100: 'Merging', 45: 'Needs human decision', 85: 'Needs human decision' }; diff --git a/src/pkg/dashboard/static-src/js/tracker-words-gate.js b/src/pkg/dashboard/static-src/js/tracker-words-gate.js index c865eb6163..d11667f688 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-gate.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-gate.js @@ -195,7 +195,7 @@ // At 060/080 the stage keeps its own word and the detail says // "soak 12m left"; at 095 the soak is the stage. clock.prefix = state === 'soaking' ? '' : 'soak '; - const soak = stageTrackerSoakWords(clock, nowMs, nextAt, !!mg.sweep_running); + const soak = stageTrackerSoakWords(clock, nowMs, nextAt, !!mg.sweep_running, clock.sweepingSince); return { state, word: clock.restarted || state === 'soaking' ? soak.word : word, detail: soak.detail, tip: soak.tip + lastSeen, cue: soak.cue || 'soaking', until: clock.restarted ? 0 : clock.until, soak: soak.tip, soakClock: clock }; } // 060 Review passed: the pill carries the lane's own recorded reason @@ -217,13 +217,16 @@ } if (state === 'merging') { // A live merge call (merging_since, hivecommons/hive#15245) says - // who issued it and how long ago; a held row (the SPA keeping - // "Merging" lit for the toast's lifetime after the merge landed) - // says the ✓ follows. Without either, the lane's 100 record. + // who issued it and how long ago — and, past + // STAGE_TRACKER_MERGING_SLOW_MS, that it is waiting for GitHub + // (#15808); a held row (the SPA bridging the gap until the merged + // fact lands) says the ✓ follows. Without either, the lane's 100 + // record. const since = mg.merging_since ? Date.parse(mg.merging_since) : 0; const sinceWords = since > 0 ? ' since ' + stageTrackerAgoText(since, nowMs) : ''; const who = STAGE_TRACKER_MERGE_PATH_WORDS[mg.merge_path] || ''; - if (mg.held) return { state, word, detail: 'merge landed', tip: 'hive merged it' + (who ? ' (' + who + ')' : '') + sinceWords + '; the row advances to ✓ in a moment.', cue: 'merging', until: 0 }; + if (mg.held) return { state, word, detail: 'waiting for GitHub', tip: 'hive issued the merge' + (who ? ' (' + who + ')' : '') + sinceWords + '; waiting for GitHub to confirm — the row advances to ✓ the moment it does.', cue: 'merging', until: 0 }; + if (since > 0 && nowMs - since > STAGE_TRACKER_MERGING_SLOW_MS) return { state, word, detail: 'merging · waiting for GitHub…', tip: 'hive is merging it' + (who ? ' (' + who + ')' : '') + ' — the merge call has been in flight' + sinceWords + ', longer than usual; waiting for GitHub to answer.', cue: 'merging', until: 0 }; if (since > 0) return { state, word, detail: 'merge call in flight', tip: 'hive is merging it now' + (who ? ' (' + who + ')' : '') + ' — the merge call has been in flight' + sinceWords + '.', cue: 'merging', until: 0 }; return { state, word, detail: '', tip: 'Admitted and soaked; hive is merging it now (GitHub merge queue / merge window).' + lastSeen, cue: 'merging', until: 0 }; } @@ -308,7 +311,7 @@ // words and the hover sentence (data-ham-soak-tip is the sentence // currently written into the row's titles; the tick swaps it out). const c = info.soakClock; - const soakAttrs = c ? ` data-ham-soak="1" data-ham-until="${c.until}" data-ham-until-kind="soaking" data-ham-soak-window="${c.windowS}" data-ham-soak-head="${esc(c.head)}" data-ham-soak-restarted="${c.restarted ? 1 : 0}" data-ham-soak-prefix="${esc(c.prefix || '')}" data-ham-next="${c.nextAt || 0}" data-ham-sweeping="${c.sweepRunning ? 1 : 0}" data-ham-soak-tip="${esc(info.soak)}"` : ''; + const soakAttrs = c ? ` data-ham-soak="1" data-ham-until="${c.until}" data-ham-until-kind="soaking" data-ham-soak-window="${c.windowS}" data-ham-soak-head="${esc(c.head)}" data-ham-soak-restarted="${c.restarted ? 1 : 0}" data-ham-soak-prefix="${esc(c.prefix || '')}" data-ham-next="${c.nextAt || 0}" data-ham-sweeping="${c.sweepRunning ? 1 : 0}" data-ham-sweeping-since="${c.sweepingSince || 0}" data-ham-soak-tip="${esc(info.soak)}"` : ''; const detail = info.detail ? ` · ${esc(info.detail)}` : ''; return `${esc(info.word)}${detail}`; } @@ -337,7 +340,7 @@ } if (!(until > 0)) return null; const rowHead = String((src && src.head) || (item && item.head) || ''); - return { until, started, windowS, head, restarted: !!(head && rowHead && head !== rowHead), fromSoak, nextAt: mg.next_sweep_at ? Date.parse(mg.next_sweep_at) : 0, sweepRunning: !!mg.sweep_running }; + return { until, started, windowS, head, restarted: !!(head && rowHead && head !== rowHead), fromSoak, nextAt: mg.next_sweep_at ? Date.parse(mg.next_sweep_at) : 0, sweepRunning: !!mg.sweep_running, sweepingSince: mg.sweeping_since ? Date.parse(mg.sweeping_since) || 0 : 0 }; } // Pure: "12m 30s" / "45s" / "1h 05m" for the hover; '' when none. function stageTrackerSoakLeftText(ms) { @@ -366,10 +369,13 @@ // live time left and the end time // complete — past until, waiting for the lane's next pass: // "Soaking · complete" - // mergeable — past until and the lane's pass is on it now: - // "Mergeable · merging now" + // mergeable — past until and the lane's pass is on this PR now: + // "Mergeable · merging now"; past + // STAGE_TRACKER_MERGING_SLOW_MS of that (sweepingSince) + // "Mergeable · merging · waiting for GitHub…", so a + // spinner never sits without a visible reason (#15808) // restarted — "Soak restarted · new head" - function stageTrackerSoakWords(clock, nowMs, nextAt, sweepRunning) { + function stageTrackerSoakWords(clock, nowMs, nextAt, sweepRunning, sweepingSince) { const short = clock.head ? clock.head.slice(0, 7) : ''; const who = short ? 'Head ' + short : 'The head'; const mins = clock.windowS > 0 ? Math.round(clock.windowS / 60) : 0; @@ -384,6 +390,9 @@ } const soaked = who + ' sat ' + window + ' without new commits — soaked since ' + stageTrackerClockText(clock.until) + '. '; if (sweepRunning) { + if (sweepingSince > 0 && nowMs - sweepingSince > STAGE_TRACKER_MERGING_SLOW_MS) { + return { word: 'Mergeable', detail: (prefix ? 'soaked — ' : '') + 'merging · waiting for GitHub…', tip: soaked + "Mergeable — hive's pass has been on it since " + stageTrackerAgoText(sweepingSince, nowMs) + '; waiting for GitHub to answer.', cue: 'running' }; + } return { word: 'Mergeable', detail: prefix ? 'soaked — merging now' : 'merging now', tip: soaked + 'Mergeable — merging now.', cue: 'running' }; } const next = stageTrackerNextPassWords(nextAt, nowMs); @@ -425,7 +434,7 @@ // the time left reads right at hover time without a re-render. function stageTrackerSoakTick(n, nowMs) { const clock = { until: Number(n.getAttribute('data-ham-until')), windowS: Number(n.getAttribute('data-ham-soak-window')) || 0, head: n.getAttribute('data-ham-soak-head') || '', restarted: n.getAttribute('data-ham-soak-restarted') === '1', prefix: n.getAttribute('data-ham-soak-prefix') || '' }; - const words = stageTrackerSoakWords(clock, nowMs, Number(n.getAttribute('data-ham-next')) || 0, n.getAttribute('data-ham-sweeping') === '1'); + const words = stageTrackerSoakWords(clock, nowMs, Number(n.getAttribute('data-ham-next')) || 0, n.getAttribute('data-ham-sweeping') === '1', Number(n.getAttribute('data-ham-sweeping-since')) || 0); const t = '· ' + words.detail; if (n.textContent !== t) n.textContent = t; // At 095 the soak owns the pill word too: a soaked head under the diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index a918d7bacd..d0f5596b5a 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14557,6 +14557,9 @@

Where to get help

// it alone); stage_tracker_merge_gate_test.go pins the two equal. const STAGE_TRACKER_MERGE_GATE_WORD = { 'gate-pending': 'Review passed', ready: 'Ready for auto merge', soaking: 'Soaking', merging: 'Merging', merged: 'Merged', 'merge-failed': 'Merge failed' }; // merge_gate.merge_path (the merge call's issuer) in words (#15245). + // A merge call (or a sweep's pass on a soaked PR) older than this says + // "waiting for GitHub…" rather than spinning without a reason (#15808). + const STAGE_TRACKER_MERGING_SLOW_MS = 60000; const STAGE_TRACKER_MERGE_PATH_WORDS = { sweep: 'automerge sweep', dashboard: 'maintainer merge from the dashboard', relay: 'hive-merge relay', forge: 'forge adapter', queue: 'merge queue' }; const STAGE_TRACKER_MERGE_FAILED_SHORT_MAX = 60; const STAGE_TRACKER_ACTIVE_WORD = { 15: 'Triage needed', 17: 'Possibly exists', 60: 'Review passed', 80: 'Ready for auto merge', 95: 'Soaking', 100: 'Merging', 45: 'Needs human decision', 85: 'Needs human decision' }; @@ -15613,7 +15616,7 @@

Where to get help

// At 060/080 the stage keeps its own word and the detail says // "soak 12m left"; at 095 the soak is the stage. clock.prefix = state === 'soaking' ? '' : 'soak '; - const soak = stageTrackerSoakWords(clock, nowMs, nextAt, !!mg.sweep_running); + const soak = stageTrackerSoakWords(clock, nowMs, nextAt, !!mg.sweep_running, clock.sweepingSince); return { state, word: clock.restarted || state === 'soaking' ? soak.word : word, detail: soak.detail, tip: soak.tip + lastSeen, cue: soak.cue || 'soaking', until: clock.restarted ? 0 : clock.until, soak: soak.tip, soakClock: clock }; } // 060 Review passed: the pill carries the lane's own recorded reason @@ -15635,13 +15638,16 @@

Where to get help

} if (state === 'merging') { // A live merge call (merging_since, hivecommons/hive#15245) says - // who issued it and how long ago; a held row (the SPA keeping - // "Merging" lit for the toast's lifetime after the merge landed) - // says the ✓ follows. Without either, the lane's 100 record. + // who issued it and how long ago — and, past + // STAGE_TRACKER_MERGING_SLOW_MS, that it is waiting for GitHub + // (#15808); a held row (the SPA bridging the gap until the merged + // fact lands) says the ✓ follows. Without either, the lane's 100 + // record. const since = mg.merging_since ? Date.parse(mg.merging_since) : 0; const sinceWords = since > 0 ? ' since ' + stageTrackerAgoText(since, nowMs) : ''; const who = STAGE_TRACKER_MERGE_PATH_WORDS[mg.merge_path] || ''; - if (mg.held) return { state, word, detail: 'merge landed', tip: 'hive merged it' + (who ? ' (' + who + ')' : '') + sinceWords + '; the row advances to ✓ in a moment.', cue: 'merging', until: 0 }; + if (mg.held) return { state, word, detail: 'waiting for GitHub', tip: 'hive issued the merge' + (who ? ' (' + who + ')' : '') + sinceWords + '; waiting for GitHub to confirm — the row advances to ✓ the moment it does.', cue: 'merging', until: 0 }; + if (since > 0 && nowMs - since > STAGE_TRACKER_MERGING_SLOW_MS) return { state, word, detail: 'merging · waiting for GitHub…', tip: 'hive is merging it' + (who ? ' (' + who + ')' : '') + ' — the merge call has been in flight' + sinceWords + ', longer than usual; waiting for GitHub to answer.', cue: 'merging', until: 0 }; if (since > 0) return { state, word, detail: 'merge call in flight', tip: 'hive is merging it now' + (who ? ' (' + who + ')' : '') + ' — the merge call has been in flight' + sinceWords + '.', cue: 'merging', until: 0 }; return { state, word, detail: '', tip: 'Admitted and soaked; hive is merging it now (GitHub merge queue / merge window).' + lastSeen, cue: 'merging', until: 0 }; } @@ -15726,7 +15732,7 @@

Where to get help

// words and the hover sentence (data-ham-soak-tip is the sentence // currently written into the row's titles; the tick swaps it out). const c = info.soakClock; - const soakAttrs = c ? ` data-ham-soak="1" data-ham-until="${c.until}" data-ham-until-kind="soaking" data-ham-soak-window="${c.windowS}" data-ham-soak-head="${esc(c.head)}" data-ham-soak-restarted="${c.restarted ? 1 : 0}" data-ham-soak-prefix="${esc(c.prefix || '')}" data-ham-next="${c.nextAt || 0}" data-ham-sweeping="${c.sweepRunning ? 1 : 0}" data-ham-soak-tip="${esc(info.soak)}"` : ''; + const soakAttrs = c ? ` data-ham-soak="1" data-ham-until="${c.until}" data-ham-until-kind="soaking" data-ham-soak-window="${c.windowS}" data-ham-soak-head="${esc(c.head)}" data-ham-soak-restarted="${c.restarted ? 1 : 0}" data-ham-soak-prefix="${esc(c.prefix || '')}" data-ham-next="${c.nextAt || 0}" data-ham-sweeping="${c.sweepRunning ? 1 : 0}" data-ham-sweeping-since="${c.sweepingSince || 0}" data-ham-soak-tip="${esc(info.soak)}"` : ''; const detail = info.detail ? ` · ${esc(info.detail)}` : ''; return `${esc(info.word)}${detail}`; } @@ -15755,7 +15761,7 @@

Where to get help

} if (!(until > 0)) return null; const rowHead = String((src && src.head) || (item && item.head) || ''); - return { until, started, windowS, head, restarted: !!(head && rowHead && head !== rowHead), fromSoak, nextAt: mg.next_sweep_at ? Date.parse(mg.next_sweep_at) : 0, sweepRunning: !!mg.sweep_running }; + return { until, started, windowS, head, restarted: !!(head && rowHead && head !== rowHead), fromSoak, nextAt: mg.next_sweep_at ? Date.parse(mg.next_sweep_at) : 0, sweepRunning: !!mg.sweep_running, sweepingSince: mg.sweeping_since ? Date.parse(mg.sweeping_since) || 0 : 0 }; } // Pure: "12m 30s" / "45s" / "1h 05m" for the hover; '' when none. function stageTrackerSoakLeftText(ms) { @@ -15784,10 +15790,13 @@

Where to get help

// live time left and the end time // complete — past until, waiting for the lane's next pass: // "Soaking · complete" - // mergeable — past until and the lane's pass is on it now: - // "Mergeable · merging now" + // mergeable — past until and the lane's pass is on this PR now: + // "Mergeable · merging now"; past + // STAGE_TRACKER_MERGING_SLOW_MS of that (sweepingSince) + // "Mergeable · merging · waiting for GitHub…", so a + // spinner never sits without a visible reason (#15808) // restarted — "Soak restarted · new head" - function stageTrackerSoakWords(clock, nowMs, nextAt, sweepRunning) { + function stageTrackerSoakWords(clock, nowMs, nextAt, sweepRunning, sweepingSince) { const short = clock.head ? clock.head.slice(0, 7) : ''; const who = short ? 'Head ' + short : 'The head'; const mins = clock.windowS > 0 ? Math.round(clock.windowS / 60) : 0; @@ -15802,6 +15811,9 @@

Where to get help

} const soaked = who + ' sat ' + window + ' without new commits — soaked since ' + stageTrackerClockText(clock.until) + '. '; if (sweepRunning) { + if (sweepingSince > 0 && nowMs - sweepingSince > STAGE_TRACKER_MERGING_SLOW_MS) { + return { word: 'Mergeable', detail: (prefix ? 'soaked — ' : '') + 'merging · waiting for GitHub…', tip: soaked + "Mergeable — hive's pass has been on it since " + stageTrackerAgoText(sweepingSince, nowMs) + '; waiting for GitHub to answer.', cue: 'running' }; + } return { word: 'Mergeable', detail: prefix ? 'soaked — merging now' : 'merging now', tip: soaked + 'Mergeable — merging now.', cue: 'running' }; } const next = stageTrackerNextPassWords(nextAt, nowMs); @@ -15843,7 +15855,7 @@

Where to get help

// the time left reads right at hover time without a re-render. function stageTrackerSoakTick(n, nowMs) { const clock = { until: Number(n.getAttribute('data-ham-until')), windowS: Number(n.getAttribute('data-ham-soak-window')) || 0, head: n.getAttribute('data-ham-soak-head') || '', restarted: n.getAttribute('data-ham-soak-restarted') === '1', prefix: n.getAttribute('data-ham-soak-prefix') || '' }; - const words = stageTrackerSoakWords(clock, nowMs, Number(n.getAttribute('data-ham-next')) || 0, n.getAttribute('data-ham-sweeping') === '1'); + const words = stageTrackerSoakWords(clock, nowMs, Number(n.getAttribute('data-ham-next')) || 0, n.getAttribute('data-ham-sweeping') === '1', Number(n.getAttribute('data-ham-sweeping-since')) || 0); const t = '· ' + words.detail; if (n.textContent !== t) n.textContent = t; // At 095 the soak owns the pill word too: a soaked head under the @@ -21794,21 +21806,26 @@

All labels

function stageTrackerNoteMerges(d) { const nowMs = Date.now(); + _stageTrackerMergingHoldMs = stageTrackerMergingHoldMsOf(d, _stageTrackerMergingHoldMs); const raw = stageTrackerCarryOpen(_stageTrackerMergeState, stageTrackerMergeState(d)); - // The merge gate holds "Merging" for at least the merge toast's - // lifetime before the row advances to ✓ (hivecommons/hive#15245): a - // merge that lands inside the hold is masked as still open until it - // ends, then re-read as fresh. - _stageTrackerMergingHold = stageTrackerMergingHoldNext(_stageTrackerMergingHold, d, _stageTrackerMergeState, raw, _stageTrackerPRItems, nowMs); - const masked = stageTrackerMergingHoldMask(raw, _stageTrackerMergingHold, nowMs); - if (masked.until) stageTrackerMergingHoldSchedule(masked.until - nowMs); - // The Merged chip holds the masked merges back too: the server - // already counts them, their glyph has not even launched yet. - _stageTrackerMergedHeld = {}; - masked.held.forEach(k => { _stageTrackerMergedHeld[k] = true; }); + // The merge gate's hold (hivecommons/hive#15245, #15808) keeps a + // row the payload dropped mid-merge on the board at "Merging" until + // the merged fact arrives (then the merge is fresh at once) or the + // hold window passes. + _stageTrackerMergingHold = stageTrackerMergingHoldNext(_stageTrackerMergingHold, d, raw, nowMs); + const until = stageTrackerMergingHoldUntil(_stageTrackerMergingHold, nowMs); + if (until) stageTrackerMergingHoldSchedule(until - nowMs); + const prevItems = _stageTrackerPRItems; _stageTrackerPRItems = stageTrackerPRItemsOf(d); - const next = masked.state; + Object.assign(_stageTrackerPRLast, _stageTrackerPRItems); + const next = raw; const fresh = stageTrackerNewlyMerged(_stageTrackerMergeState, next).filter(k => !_stageTrackerZapped[k]); + // A PR that left the board closed, not merged (recently_closed, the + // closed twin of recently_merged): say so once, neutrally — no bee, + // no count — instead of letting the row vanish in silence. + const closed = stageTrackerNewlyClosed(d, _stageTrackerMergeState, next, _stageTrackerPRItems, _stageTrackerClosedNoted); + const closedItems = closed.map(k => prevItems[k] || _stageTrackerPRLast[k]); + closed.forEach(k => { _stageTrackerClosedNoted[k] = true; delete next[k]; delete _stageTrackerPRLast[k]; }); _stageTrackerMergeState = next; // A merged PR is no longer in this payload, so its last host survives. if (typeof stageTrackerPRHosts === 'function') Object.assign(_stageTrackerPRHost, stageTrackerPRHosts(d)); @@ -21818,33 +21835,54 @@

All labels

if (celebrate) fresh.forEach(k => { _stageTrackerCelebratePending[k] = true; }); if (typeof stageTrackerMergedSync === 'function') stageTrackerMergedSync(d, fresh, Date.now()); if (typeof stageTrackerQueueSync === 'function') stageTrackerQueueSync(d && d.items, Date.now()); + if (typeof stageTrackerClosedToast === 'function') closed.forEach((k, i) => stageTrackerClosedToast(k, closedItems[i])); if (!fresh.length) return; fresh.forEach(k => { _stageTrackerZapped[k] = true; }); if (celebrate) { stageTrackerCelebrateMerges(fresh); return; } if (stageTrackerSoundGate()) stageTrackerPlayZap(Math.min(fresh.length, STAGE_TRACKER_SOUND_MAX_PLAYS)); } - /* ---- Merge gate: "Merging" held for the toast's lifetime (#15245) ---- - Operator: "I have seen some items go straight to merge without - showing in the Merge gate column as 'merging' for at least as long - as the merge toast is open." The sweep merges inside one pass, so a - PR can go from 060/090/095 to merged between two polls and the - intermediate state is never on screen. The payload's merge_gate now - says merging (with merging_since) while the merge call is in flight; - the SPA keeps a hold per PR from the first moment it saw merging — - or, for a merge it never saw coming, from the poll that reported it - merged — and until STAGE_TRACKER_MERGING_HOLD_MS (the merge - banner's lifetime) has passed the row stays on the board at 100 - "Merging" (its last item, synthesised when the payload dropped it) - and the merge is not counted as fresh. When the hold ends the merge - is re-read: the row advances to ✓, the banner opens, the chip bumps. - A refused merge (merge_gate.state merge-failed) drops the hold at - once and the pill says why. All pure except the schedule/release - pair; run under node by stage_tracker_merging_hold_test.go. */ + /* ---- Merge gate: "Merging" bridged until the merged fact (#15245, #15808) ---- + Operator (#15245): "I have seen some items go straight to merge + without showing in the Merge gate column as 'merging'." The sweep + merges inside one pass, so a PR can go from 060/090/095 to merged + between two polls. The payload's merge_gate says merging (with + merging_since) while the merge call is in flight; when the payload + then drops the PR before the merged fact (recently_merged / the + ledger) has landed, the SPA keeps a hold per PR — from the moment + it saw merging — and until the hold window has passed the row stays + on the board at 100 "Merging" (its last item, synthesised), the + gate saying it is waiting for GitHub to confirm. + Operator (#15808): the hold used to be a fixed 30 s mask over the + merged fact itself — "Merging · merge landed" sat there while the + bee waited — and a row that vanished without the SPA seeing merged + never celebrated. Now the hold only bridges the gap: the moment the + merged fact is in a payload the hold drops, the merge is fresh and + the celebration launches (bee, then the odometer on its landing, + #15763). The window is dashboard.stage_tracker.merged_hold_s + (payload merged_hold_ms; default 8 s, floor 3 s), a ceiling, not a + delay. A refused merge (merge-failed) drops the hold at once. All + pure except the schedule/release pair; run under node by + stage_tracker_merging_hold_test.go. */ const STAGE_TRACKER_MERGE_QUEUE = 100; + const STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS = 8000; + const STAGE_TRACKER_MERGING_HOLD_MIN_MS = 3000; + var _stageTrackerMergingHoldMs = STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; var _stageTrackerMergingHold = {}; var _stageTrackerPRItems = {}; + // PR key → the last item ever seen for it (survives the payload + // dropping it: the closed toast's reason, the hold's row). + var _stageTrackerPRLast = {}; + var _stageTrackerClosedNoted = {}; var _stageTrackerMergingHoldTimer = 0; + // Pure: the hold window from a payload's merged_hold_ms (clamped to the + // floor), else the value in force. + function stageTrackerMergingHoldMsOf(d, cur) { + const n = d && typeof d === 'object' ? Number(d.merged_hold_ms) : 0; + if (!(n > 0)) return cur || STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; + return Math.max(STAGE_TRACKER_MERGING_HOLD_MIN_MS, n); + } + function stageTrackerMergingHoldMs() { return _stageTrackerMergingHoldMs || STAGE_TRACKER_MERGING_HOLD_DEFAULT_MS; } // Pure: PR key → item for one payload (the last open item a hold // synthesises its row from). function stageTrackerPRItemsOf(d) { @@ -21852,21 +21890,19 @@

All labels

for (const it of ((d && Array.isArray(d.items)) ? d.items : [])) if (it && it.kind === 'pr') out[stageTrackerPRKey(it.repo, it.number)] = it; return out; } - // Pure: whether a hold is still inside its minimum window at nowMs. - function stageTrackerMergingHoldLive(hold, nowMs) { return !!hold && nowMs < hold.since + STAGE_TRACKER_MERGING_HOLD_MS; } - // Pure: the holds after one payload. prevState / rawState are the - // merge-state maps (PR key → merged?) before and after it; prevItems the - // PR items of the previous payload. + // Pure: whether a hold is still inside its window at nowMs. + function stageTrackerMergingHoldLive(hold, nowMs) { return !!hold && nowMs < hold.since + stageTrackerMergingHoldMs(); } + // Pure: the holds after one payload. rawState is the merge-state map + // (PR key → merged?) after it. // • a PR the payload shows at merge_gate.state 'merging' opens (or // keeps) a hold from merging_since (else from now, else the one it had) - // • a PR shown at 'merge-failed' — or open at any other state after a - // hold the payload no longer backs — drops its hold at once - // • a PR open before and merged now with no hold opens one from now, - // from its last open item, so "Merging" shows before ✓ - // • a hold whose window has passed is dropped (its merge, if any, is - // then read as fresh) - function stageTrackerMergingHoldNext(prev, d, prevState, rawState, prevItems, nowMs) { - prev = prev || {}; prevState = prevState || {}; rawState = rawState || {}; prevItems = prevItems || {}; + // • a PR shown at 'merge-failed' — or open at any other state — drops + // its hold at once + // • a held PR the payload dropped keeps its hold while the window is + // live and the merged fact is still missing; the merged fact (or + // the window's end) drops it — the merge is then read as fresh + function stageTrackerMergingHoldNext(prev, d, rawState, nowMs) { + prev = prev || {}; rawState = rawState || {}; const out = {}; const items = stageTrackerPRItemsOf(d); for (const key of Object.keys(items)) { @@ -21879,39 +21915,29 @@

All labels

// 'merge-failed' or any other open state: no hold. } for (const key of Object.keys(prev)) { - if (out[key] || items[key]) continue; + if (out[key] || items[key] || rawState[key] === true) continue; if (stageTrackerMergingHoldLive(prev[key], nowMs)) out[key] = prev[key]; } - for (const key of Object.keys(rawState)) { - // prev[key]: it was held and the window already passed — no second hold. - if (rawState[key] !== true || prevState[key] !== false || out[key] || prev[key] || items[key] || !prevItems[key]) continue; - out[key] = { since: nowMs, item: prevItems[key], path: '' }; - } return out; } - // Pure: rawState with every PR under a live hold read as still open; - // until is the earliest ms at which a masked hold ends (0 when none). - function stageTrackerMergingHoldMask(rawState, holds, nowMs) { - const state = Object.assign({}, rawState || {}); + // Pure: the earliest ms at which a live hold ends (0 when none). + function stageTrackerMergingHoldUntil(holds, nowMs) { let until = 0; - const held = []; for (const key of Object.keys(holds || {})) { const h = holds[key]; - if (state[key] !== true || !stageTrackerMergingHoldLive(h, nowMs)) continue; - state[key] = false; - held.push(key); - const end = h.since + STAGE_TRACKER_MERGING_HOLD_MS; + if (!stageTrackerMergingHoldLive(h, nowMs)) continue; + const end = h.since + stageTrackerMergingHoldMs(); if (!until || end < until) until = end; } - return { state, held: held.sort(), until }; + return until; } // Pure: the row a held PR shows while the payload no longer lists it — - // its last open item at 100 "Merging", the gate saying the merge landed. + // its last item at 100 "Merging", the gate waiting for GitHub's word. function stageTrackerMergingHoldItem(hold, key) { const base = hold && hold.item ? hold.item : { kind: 'pr' }; const mg = Object.assign({}, base.merge_gate || {}, { state: 'merging', merging_since: new Date(hold.since).toISOString(), held: true, sweep_running: false, next_sweep_at: '', soak_until: '', soak_remaining_seconds: 0 }); if (hold.path) mg.merge_path = hold.path; - return Object.assign({}, base, { stage: STAGE_TRACKER_MERGE_QUEUE, stage_slug: 'merge-queue', stage_label: 'stage/100-merge-queue', merge_gate: mg, caption: 'Merging now — the merge landed; ✓ follows', actor: 'hive', stage_actor: Object.assign({}, base.stage_actor || {}, { kind: 'hive', login: '', why: 'hive merged it; the row advances to ✓ in a moment' }), soak_remaining_seconds: 0, modifiers: (Array.isArray(base.modifiers) ? base.modifiers : []).filter(m => m !== 'stalled' && m !== 'blocked'), held_merging: true }); + return Object.assign({}, base, { stage: STAGE_TRACKER_MERGE_QUEUE, stage_slug: 'merge-queue', stage_label: 'stage/100-merge-queue', merge_gate: mg, caption: 'Merging — waiting for GitHub to confirm; ✓ follows', actor: 'hive', stage_actor: Object.assign({}, base.stage_actor || {}, { kind: 'hive', login: '', why: 'hive issued the merge; the row advances to ✓ once GitHub confirms' }), soak_remaining_seconds: 0, modifiers: (Array.isArray(base.modifiers) ? base.modifiers : []).filter(m => m !== 'stalled' && m !== 'blocked'), held_merging: true }); } // Pure: the payload as rendered — its items plus a synthesised row for // every live hold the payload dropped; d itself when there is none. @@ -21927,7 +21953,7 @@

All labels

return Object.assign({}, d, { items: d.items.concat(extra) }); } // Stateful: when the earliest live hold ends, re-read the last payload so - // the held merges come through as fresh and the rows advance to ✓. + // the synthesised row leaves the board. function stageTrackerMergingHoldSchedule(inMs) { if (_stageTrackerMergingHoldTimer) return; _stageTrackerMergingHoldTimer = setTimeout(stageTrackerMergingHoldRelease, Math.max(50, inMs + 50)); @@ -21939,6 +21965,55 @@

All labels

renderStageTracker(); } + /* ---- Closed, not merged: a neutral word on the way out (#15808) ---- + Operator: #15793 "vanished" at 11:46:54 and read as a silent merge; + it had been closed as superseded by #15783. Items only list open + work, so the SPA learns of a close the same way it learns of a + merge: a side list (recently_closed) names the PRs that left closed. + Every PR this tab saw open that the list now says closed gets one + info toast — "#15793 closed · superseded by #15783", the reason read + from the row's last caption — with the standard countdown; no bee, + no odometer. */ + const STAGE_TRACKER_CLOSED_REASON_MAX = 72; + // Pure: PR keys the tab saw open (prevState false, or carried open) that + // d.recently_closed lists, not merged, not listed open now, not yet noted. + function stageTrackerNewlyClosed(d, prevState, rawState, items, noted) { + const list = d && Array.isArray(d.recently_closed) ? d.recently_closed : []; + if (!list.length || !prevState) return []; + const out = []; + for (const c of list) { + if (!c || !c.repo || !c.number) continue; + const key = stageTrackerPRKey(c.repo, c.number); + if (prevState[key] !== false || rawState[key] === true || (items && items[key]) || (noted && noted[key]) || out.indexOf(key) >= 0) continue; + out.push(key); + } + return out.sort(); + } + // Pure: why a closed PR left, from its last item — "superseded by + // #15783" when the row said so, else its caption's first clause. + function stageTrackerClosedReason(it) { + if (!it) return 'closed without merging'; + const sup = Number(it.superseded_by) || Number(it.superseded && it.superseded.by) || 0; + const cap = String(it.caption || ''); + const m = cap.match(/superseded by #(\d+)/i) || cap.match(/duplicate of #(\d+)/i); + if (sup > 0) return 'superseded by #' + sup; + if (m) return (m[0].toLowerCase().startsWith('dup') ? 'duplicate of #' : 'superseded by #') + m[1]; + let clause = cap.split(/[;—]|\. /)[0].trim(); + if (!clause) return 'closed without merging'; + if (clause.length > STAGE_TRACKER_CLOSED_REASON_MAX) clause = clause.slice(0, STAGE_TRACKER_CLOSED_REASON_MAX - 1).trimEnd() + '…'; + return clause; + } + // Pure: the toast's words. + function stageTrackerClosedToastText(key, it) { + const n = Number(String(key || '').slice(String(key || '').indexOf('/pr#') + 4)) || 0; + return (n ? '#' + n + ' ' : '') + 'closed · ' + stageTrackerClosedReason(it); + } + // Stateful: one neutral toast for a PR that left the board closed. + function stageTrackerClosedToast(key, it) { + if (typeof showToast !== 'function') return null; + return showToast(stageTrackerClosedToastText(key, it), 'info'); + } + /* ---- tracker-cues: merged — pinned row, glyph flight, "Merged" chip --- Owner: "subtle but noticeable … a merge count that rises, and the celebration is something that rises out of the column and into the @@ -22017,8 +22092,6 @@

All labels

const STAGE_TRACKER_MERGED_LIST_MAX = 20; const STAGE_TRACKER_MERGE_BANNER_MS = 30000; const STAGE_TRACKER_MERGE_BANNER_MAX = 5; - // The merge gate's minimum "Merging" dwell is the merge banner's lifetime (#15245). - const STAGE_TRACKER_MERGING_HOLD_MS = STAGE_TRACKER_MERGE_BANNER_MS; function stageTrackerCelebrateSetting() { try { return localStorage.getItem(STAGE_TRACKER_CELEBRATE_KEY) !== '0'; } catch { return true; } } @@ -22139,12 +22212,6 @@

All labels

// Merges whose glyph is still on its way: the count holds them back // until stageTrackerCelebrateTick lands them. var _stageTrackerCelebratePending = {}; - // Merges the merge-gate hold (#15245) still masks as open: the server - // counts them already, the SPA has not read them as fresh yet, so no - // glyph is pending for them. Without this the drum rolled on the poll - // that brought the merge — a full banner-lifetime before the bee - // launched — and the landing found nothing left to roll. - var _stageTrackerMergedHeld = {}; // Stateful: fold one payload into the state and redraw the chip. The // count only bumps (pop + zap) through stageTrackerCelebrateTick; a // plain reload draws the server's number without a flourish. @@ -22163,13 +22230,12 @@

All labels

return stageTrackerMergedChip.node; } // Pure: how many merges the server already counts whose bump the chip - // still owes the bee — a glyph pending or in the air, or a merge the - // merge-gate hold masks until its flight can launch — so the landing + // still owes the bee — a glyph pending or in the air — so the landing // is when it bumps. - function stageTrackerMergedHoldback(state, pending, held) { + function stageTrackerMergedHoldback(state, pending) { const known = {}; for (const e of ((state && state.server && state.server.recent) || [])) known[stageTrackerMergedIdent(e.repo, e.number)] = true; - const keys = Object.assign({}, held || {}, pending || {}); + const keys = Object.assign({}, pending || {}); let n = 0; for (const key of Object.keys(keys)) { const i = key.indexOf('/pr#'); if (i > 0 && known[stageTrackerMergedIdent(key.slice(0, i), key.slice(i + 4))]) n++; } return n; @@ -22325,18 +22391,17 @@

All labels

} // Stateful: whether a celebration glyph is in the air or about to be // (stageTrackerCelebrateMerges staggers the launches; a merge is - // pending from the payload that brought it, or masked by the merge - // gate's hold until then). The drum and the zap wait on this; the - // flight's own end — its animationend, or stageTrackerAfter's timer - // at STAGE_TRACKER_CELEBRATE_FLY_MS when the event never fires — is - // what clears it. - // A merge the merge-gate hold still masks counts as a flight to come: - // its glyph launches when the hold ends and re-reads it as fresh. - function stageTrackerMergedInFlight() { return _stageTrackerFlights > 0 || Object.keys(_stageTrackerCelebratePending).length > 0 || Object.keys(_stageTrackerMergedHeld).length > 0; } + // pending from the payload that brought it). The drum and the zap + // wait on this; the flight's own end — its animationend, or + // stageTrackerAfter's timer at STAGE_TRACKER_CELEBRATE_FLY_MS when the + // event never fires — is what clears it. (The merge-gate hold no + // longer masks a known merge, #15808: the glyph is pending from the + // payload that brings the merged fact.) + function stageTrackerMergedInFlight() { return _stageTrackerFlights > 0 || Object.keys(_stageTrackerCelebratePending).length > 0; } function stageTrackerMergedCountDraw(tick) { const chip = stageTrackerMergedChip(); const now = Date.now(); - const txt = stageTrackerMergedText(_stageTrackerMerged, now, stageTrackerMergedHoldback(_stageTrackerMerged, _stageTrackerCelebratePending, _stageTrackerMergedHeld)); + const txt = stageTrackerMergedText(_stageTrackerMerged, now, stageTrackerMergedHoldback(_stageTrackerMerged, _stageTrackerCelebratePending)); // Never backwards within a tab: a server that has not caught up yet // (or lost a merge) does not make the number drop. if (txt.count > _stageTrackerMergedShown || tick) _stageTrackerMergedShown = Math.max(_stageTrackerMergedShown, txt.count); @@ -22469,14 +22534,38 @@

All labels

const startAt = now + i * STAGE_TRACKER_CELEBRATE_STAGGER_MS; if (rowKey) _stageTrackerCelebrating[rowKey] = { key, kind: 'merged', until: startAt + STAGE_TRACKER_CELEBRATE_PIN_MS }; const number = Number(key.slice(key.indexOf('/pr#') + 4)) || 0; - stageTrackerMergeBanner({ key, rowKey, number, repo: key.slice(0, key.indexOf('/pr#')), at: now }); + const banner = stageTrackerMergeBanner({ key, rowKey, number, repo: key.slice(0, key.indexOf('/pr#')), at: now }); setTimeout(() => { const row = rowKey && el ? el.querySelector(`[data-ham-key="${CSS.escape(rowKey)}"]`) : null; if (row) celebrateRow(row, { kind: 'merged', key, number }); - else stageTrackerCelebrateTick(key); + else celebrateDetached(key, banner); }, i * STAGE_TRACKER_CELEBRATE_STAGGER_MS); }); } + // Pure: where a row-less glyph takes off — the banner's ✓ when it has + // a box, else the bottom centre of the panel (or the viewport). Null + // when nothing has a box (no layout, e.g. a hidden tab). + function stageTrackerDetachedOrigin(bannerRect, panelRect, vw, vh) { + const ok = r => !!r && r.width > 0 && r.height > 0; + if (ok(bannerRect)) return bannerRect; + if (ok(panelRect)) return { left: panelRect.left + panelRect.width / 2 - STAGE_TRACKER_CELEBRATE_GLYPH_HALF, top: Math.min(panelRect.top + panelRect.height, vh) - 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, width: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, height: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF }; + if (vw > 0 && vh > 0) return { left: vw / 2 - STAGE_TRACKER_CELEBRATE_GLYPH_HALF, top: vh - 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, width: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF, height: 2 * STAGE_TRACKER_CELEBRATE_GLYPH_HALF }; + return null; + } + // Stateful: celebrate a merge whose row is not on the board (below the + // fold, filtered, another page, already evicted — hivecommons/hive#15808: + // #15707's toast showed, but no bee and no count). The glyph flies from + // the toast's ✓ (else the panel's foot) to the chip; the count rolls + // when it lands, exactly as for a drawn row. The toast, the bee and the + // odometer are one pipeline: a merged fact that reaches here has all three. + function celebrateDetached(key, banner, preview) { + const rect = el => el && typeof el.getBoundingClientRect === 'function' ? el.getBoundingClientRect() : null; + const ico = banner && typeof banner.querySelector === 'function' ? banner.querySelector('.merge-banner-ico') : null; + const vw = window.innerWidth || 0, vh = window.innerHeight || 0; + const from = stageTrackerDetachedOrigin(rect(ico) || rect(banner), rect(document.getElementById('activity-monitor-panel')), vw, vh); + if (!from) { stageTrackerCelebrateTick(key, preview); return { flew: false, lands: false }; } + return stageTrackerFlyGlyph(from, key, preview); + } // Pure: the rows a render must keep although the payload dropped them — // every celebrating row still inside its pin window, as the node it // already has (its HTML is replayed so the reconcile keeps it). @@ -22537,13 +22626,19 @@

All labels

} if (kind !== 'merged') return { flew: false }; const cap = rowEl.querySelector('.ham-seg.cap'); - if (!cap || _stageTrackerFlights >= STAGE_TRACKER_CELEBRATE_MAX_FLIGHTS || typeof cap.getBoundingClientRect !== 'function') { + if (!cap || typeof cap.getBoundingClientRect !== 'function') return celebrateDetached(key, null, preview); + return stageTrackerFlyGlyph(cap.getBoundingClientRect(), key, preview); + } + // Stateful: fly the glyph from a box to the chip (or fade it in place + // under reduced motion; count at once over the flight cap). Landing + // calls stageTrackerCelebrateTick, which rolls the odometer (#15763). + function stageTrackerFlyGlyph(from, key, preview) { + if (!from || _stageTrackerFlights >= STAGE_TRACKER_CELEBRATE_MAX_FLIGHTS) { stageTrackerCelebrateTick(key, preview); return { flew: false, lands: false }; } const reduced = stageTrackerReducedMotion(); const chip = stageTrackerMergedChip(); - const from = cap.getBoundingClientRect(); const vw = window.innerWidth || 0, vh = window.innerHeight || 0; const to = reduced ? { lands: false, dx: 0, dy: 0 } : stageTrackerFlightTarget(from, chip && typeof chip.getBoundingClientRect === 'function' ? chip.getBoundingClientRect() : null, vw, vh); const glyph = document.createElement('span'); diff --git a/src/pkg/dashboard/webhook_tracker_refresh.go b/src/pkg/dashboard/webhook_tracker_refresh.go index 74d042e218..f8dcced9df 100644 --- a/src/pkg/dashboard/webhook_tracker_refresh.go +++ b/src/pkg/dashboard/webhook_tracker_refresh.go @@ -284,6 +284,32 @@ func (s *Server) RefreshSelfEditedItem(repo string, number int, isPR bool) { s.trackerRefresher().enqueue([]trackerRefreshKey{{repo: repo, number: number, pr: isPR}}, selfEditDeliveryID) } +// selfMergeDeliveryID tags the snapshot patch a hive-performed merge +// applies the moment the merge call returns (hivecommons/hive#15808). +const selfMergeDeliveryID = "self:merge" + +// noteMergeAttempt is the merge-attempt registry's change hook +// (github.MergeAttempts.SetOnChange). Every change nudges open tabs so the +// row reads "Merging" within one SPA poll instead of waiting for the next +// enumerate; a merge that landed also patches the cached snapshot the way +// a webhook `closed` read would — the row leaves as merged and the merged +// ledger records it — so the celebration does not depend on the webhook +// arriving, whichever lane (self-authored, trusted-author, contributor, +// relay, dashboard) performed the merge (hivecommons/hive#15808). +func (s *Server) noteMergeAttempt(a github.MergeAttempt) { + if s == nil { + return + } + if a.Merged && !a.EndedAt.IsZero() { + snap := github.WebhookItemSnapshot{Repo: a.Repo, Number: a.Number, IsPR: true, State: "closed", Merged: true, + MergedByHive: true, MergedAt: a.EndedAt, UpdatedAt: a.EndedAt, HeadSHA: a.Head, FetchedAt: a.EndedAt, DeliveryID: selfMergeDeliveryID} + if s.applyWebhookItemSnapshots([]github.WebhookItemSnapshot{snap}) > 0 { + return + } + } + s.invalidateStageTrackerForWebhook() +} + // evictClosedWebhookItem applies the one payload fact the tracker trusts // without a confirming read: the item the delivery embeds is closed or // merged. Every `issues`, `issue_comment` and `pull_request*` payload carries @@ -353,6 +379,7 @@ func (s *Server) applyWebhookItemSnapshots(snaps []github.WebhookItemSnapshot) i return 0 } s.recordMergedSnapshots(snaps) + s.noteClosedSnapshots(snaps) s.notePushedSnapshots(snaps) if s.deps != nil && s.deps.ApplyWebhookItems != nil { s.deps.ApplyWebhookItems(snaps) diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index b5548fcc1c..5e8c28bfb7 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -468,7 +468,9 @@ func (c *Engine) SweepContributorLaneAutoMerges(ctx context.Context, opts AutoMe continue } result.Candidates++ + c.sweepClock.evaluating(displayRepo, number) event, reason, err := c.trySweepContributorLanePR(ctx, displayRepo, owner, repoName, number, policy) + c.sweepClock.evaluated() if err == nil { c.noteMergeTrainOutcome(stageLaneContributor, owner, repoName, number, pr.GetHead().GetSHA(), reason) } diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 1b4c5fe6bf..4f2fb3bd81 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -1036,7 +1036,9 @@ func (c *Engine) SweepQueuedAutoMerges(ctx context.Context, opts AutoMergeSweepO result.Skipped++ continue } + c.sweepClock.evaluating(repo, issue.GetNumber()) event, reason, err := c.trySweepQueuedPR(ctx, repo, owner, repoName, issue.GetNumber(), label) + c.sweepClock.evaluated() if err != nil { c.warn("automerge sweep skipped PR", "repo", repo, "pr", issue.GetNumber(), "reason", reason, "error", err) result.Skipped++ @@ -1263,7 +1265,9 @@ func (c *Engine) SweepSelfAuthoredAutoMerges(ctx context.Context, opts AutoMerge } result.Candidates++ repoCandidates++ + c.sweepClock.evaluating(repo, number) event, reason, err := c.trySweepSelfAuthoredPR(ctx, repo, owner, repoName, number, branchUpdateAttempts < selfAuthoredSweepMaxBranchUpdates) + c.sweepClock.evaluated() if event.BranchUpdated || reason == "updated-branch" || reason == "update-branch" { branchUpdateAttempts++ } @@ -1456,7 +1460,9 @@ func (c *Engine) SweepTrustedAuthorAutoMerges(ctx context.Context, opts AutoMerg continue } result.Candidates++ + c.sweepClock.evaluating(displayRepo, number) event, reason, err := c.trySweepTrustedAuthorPR(ctx, displayRepo, owner, repoName, number, policy) + c.sweepClock.evaluated() if err == nil { c.noteMergeTrainOutcome(stageLaneTrusted, owner, repoName, number, pr.GetHead().GetSHA(), reason) } diff --git a/src/pkg/github/automerge/sweep_clock.go b/src/pkg/github/automerge/sweep_clock.go index 7d47320a5a..8b5cddda0a 100644 --- a/src/pkg/github/automerge/sweep_clock.go +++ b/src/pkg/github/automerge/sweep_clock.go @@ -25,6 +25,14 @@ type SweepState struct { FloorEvery time.Duration // Targets names the PRs the running pass evaluates; nil means every PR. Targets SweepTargets + // EvalRepo/EvalNumber name the one PR a lane is evaluating right now + // (hivecommons/hive#15808). Once a pass has started walking PRs + // (Narrowed), OnPR is true only for that PR: a floor pass runs every + // lane serially over every PR and the dashboard must not read the + // whole pass as "merging now" on every soaked row. + EvalRepo string + EvalNumber int + Narrowed bool } // OnPR reports whether a pass is running now and evaluating repo#n. @@ -32,6 +40,10 @@ func (s SweepState) OnPR(repo string, n int) bool { if !s.Running { return false } + if s.Narrowed { + return s.EvalNumber == n && s.EvalNumber > 0 && + canonicalSweepRepo(s.EvalRepo) == canonicalSweepRepo(repo) + } if s.Targets == nil { return true } @@ -61,6 +73,28 @@ func (c *SweepClock) end(now time.Time) { } c.mu.Lock() c.st.Running, c.st.FinishedAt, c.st.Targets = false, now, nil + c.st.EvalRepo, c.st.EvalNumber, c.st.Narrowed = "", 0, false + c.mu.Unlock() +} + +// evaluating marks repo#n as the PR a lane is deciding on right now; the +// pass stays narrowed to one PR at a time until end. +func (c *SweepClock) evaluating(repo string, n int) { + if c == nil { + return + } + c.mu.Lock() + c.st.EvalRepo, c.st.EvalNumber, c.st.Narrowed = repo, n, true + c.mu.Unlock() +} + +// evaluated clears the current PR mark once a lane has decided on it. +func (c *SweepClock) evaluated() { + if c == nil { + return + } + c.mu.Lock() + c.st.EvalRepo, c.st.EvalNumber = "", 0 c.mu.Unlock() } diff --git a/src/pkg/github/automerge/sweep_clock_test.go b/src/pkg/github/automerge/sweep_clock_test.go index d32ecbfa3e..06d869cd09 100644 --- a/src/pkg/github/automerge/sweep_clock_test.go +++ b/src/pkg/github/automerge/sweep_clock_test.go @@ -53,3 +53,34 @@ func TestSweepClock(t *testing.T) { } c.end(t0.Add(5*time.Minute + time.Second)) } + +// TestSweepClockNarrowed: once a lane marks the PR it is evaluating, a +// full pass is "on" that PR only — not every soaked row — and between PRs +// (evaluated) it is on none, until end restores the idle shape +// (hivecommons/hive#15808). +func TestSweepClockNarrowed(t *testing.T) { + c := &SweepClock{} + t0 := time.Date(2026, 11, 3, 11, 30, 0, 0, time.UTC) + c.begin("floor", nil, t0) + c.evaluating("acme/console", 15805) + st := c.Snapshot() + if !st.OnPR("ACME/Console", 15805) || st.OnPR("acme/console", 15791) || st.OnPR("acme/other", 15805) { + t.Fatalf("narrowed pass is on the evaluated PR only: %+v", st) + } + c.evaluated() + if st = c.Snapshot(); !st.Running || st.OnPR("acme/console", 15805) || st.OnPR("acme/console", 15791) { + t.Fatalf("between PRs the pass is on none: %+v", st) + } + c.evaluating("acme/console", 15791) + if st = c.Snapshot(); !st.OnPR("acme/console", 15791) || st.OnPR("acme/console", 15805) { + t.Fatalf("moved on: %+v", st) + } + c.end(t0.Add(time.Minute)) + if st = c.Snapshot(); st.Running || st.Narrowed || st.OnPR("acme/console", 15791) { + t.Fatalf("ended: %+v", st) + } + c.begin("floor", nil, t0.Add(2*time.Minute)) + if st = c.Snapshot(); !st.OnPR("acme/console", 1) { + t.Fatalf("a fresh full pass before any mark is on every PR: %+v", st) + } +} diff --git a/src/pkg/github/merge_attempts.go b/src/pkg/github/merge_attempts.go index c0e743cc93..24f849d09b 100644 --- a/src/pkg/github/merge_attempts.go +++ b/src/pkg/github/merge_attempts.go @@ -53,7 +53,7 @@ type MergeAttempts struct { mu sync.Mutex items map[string]MergeAttempt now func() time.Time - onChange func() + onChange func(MergeAttempt) } // NewMergeAttempts returns an empty registry reading the clock from now @@ -69,10 +69,11 @@ func mergeAttemptKey(repo string, number int) string { return strings.ToLower(strings.TrimSpace(repo)) + "#" + strconv.Itoa(number) } -// SetOnChange registers fn to run (outside the lock) after every Begin and -// End; the dashboard uses it to invalidate its tracker cache so the next -// poll sees the attempt. -func (m *MergeAttempts) SetOnChange(fn func()) { +// SetOnChange registers fn to run (outside the lock) with the attempt as +// recorded after every Begin and End; the dashboard uses it to patch its +// tracker snapshot and nudge open tabs so the next poll sees the attempt +// (hivecommons/hive#15808). +func (m *MergeAttempts) SetOnChange(fn func(MergeAttempt)) { if m == nil { return } @@ -96,11 +97,12 @@ func (m *MergeAttempts) BeginOnHead(repo string, number int, path, head string) m.mu.Lock() now := m.now() m.purgeLocked(now) - m.items[mergeAttemptKey(repo, number)] = MergeAttempt{Repo: strings.TrimSpace(repo), Number: number, Path: path, StartedAt: now, Head: strings.TrimSpace(head)} + a := MergeAttempt{Repo: strings.TrimSpace(repo), Number: number, Path: path, StartedAt: now, Head: strings.TrimSpace(head)} + m.items[mergeAttemptKey(repo, number)] = a fn := m.onChange m.mu.Unlock() if fn != nil { - fn() + fn(a) } } @@ -129,7 +131,7 @@ func (m *MergeAttempts) End(repo string, number int, merged bool, err error) { fn := m.onChange m.mu.Unlock() if fn != nil { - fn() + fn(a) } } diff --git a/src/pkg/github/merge_attempts_test.go b/src/pkg/github/merge_attempts_test.go index be17ce88d6..08447a87af 100644 --- a/src/pkg/github/merge_attempts_test.go +++ b/src/pkg/github/merge_attempts_test.go @@ -14,7 +14,7 @@ func TestMergeAttemptsLifecycle(t *testing.T) { now := time.Date(2026, 10, 28, 21, 31, 0, 0, time.UTC) m := NewMergeAttempts(func() time.Time { return now }) changes := 0 - m.SetOnChange(func() { changes++ }) + m.SetOnChange(func(MergeAttempt) { changes++ }) m.Begin("HiveCommons/Hive", 15207, PRAuditPathSweep) a, ok := m.Get("hivecommons/hive", 15207)