From 4e8e5efb7dc424bf21316b1f1b9ff5f85bdad8c4 Mon Sep 17 00:00:00 2001 From: Karibhou <157208370+Karibhou@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:50:06 +0100 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20feature(hub):=20add=20the=20Fle?= =?UTF-8?q?et=20activity=20page=20/activity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the read-only hub Fleet activity board at /activity, linked as "πŸ“‘ Fleet activity" next to "πŸ”¬ Evidence" on the dashboard's Fleet quadrant card (#16063, part of #15965, RFC #15861 by @hanthor). - GET /activity: data-free shell; no valid session redirects to /login, otherwise requireAuth (not admin-only). Served with its own CSP following webstatic/csp_script_src.go (scripts/styles from 'self' only, script-src-attr and style-src-attr 'none', script-src-elem recomputed from the served bytes) and the static no-cache + ETag headers. - GET /activity/assets/{name}: the shared trackerrow asset (#16062), byte-identical, whitelisted to trackerrow.Files. - static/activity.js polls GET /api/hub/activity every 15 s with If-None-Match and redraws only on a new ETag. Hive column with stable colour chips linking to /api/saas/hives/{id}/open; rows link to GitHub; titles set as text; no action menus. Group-by-hive headers carry counts and freshness (stale, "upgrade to report activity", missing). Truncation, dropped events and stale/missing hives are always listed above the board. - The page defines the STAGE_TRACKER_* globals the shared asset reads; a test pins them to the spoke's values (#16067 / #16081). - /activity is noindex; docs page and changelog fragment. Hive-Run: hivecommons/hive#16063 Hive-Plan: hivecommons/hive#15965 decomposition, piece 2 of 3 (#16062 -> #16063 -> #16064) Hive-Spec: RFC-15861#D Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HRH6kmq5bGTopPWeCopPvU Signed-off-by: Karibhou <157208370+Karibhou@users.noreply.github.com> --- .../added-16063-hub-fleet-activity-page.md | 1 + src/docs/api-reference/hub-server.md | 2 + src/docs/documentation-map.md | 1 + src/docs/hosted-hub.md | 6 + src/docs/hub-fleet-activity.md | 112 +++++ src/pkg/hub/activity_page.go | 98 ++++ src/pkg/hub/activity_page_test.go | 468 ++++++++++++++++++ src/pkg/hub/assets/dashboard.html | 14 +- src/pkg/hub/canonical_url_test.go | 1 + src/pkg/hub/evidence_drilldown_ui_test.go | 11 + src/pkg/hub/robots.go | 1 + src/pkg/hub/robots_test.go | 3 + src/pkg/hub/server.go | 3 + src/pkg/hub/static/activity.css | 93 ++++ src/pkg/hub/static/activity.html | 51 ++ src/pkg/hub/static/activity.js | 381 ++++++++++++++ 16 files changed, 1245 insertions(+), 1 deletion(-) create mode 100644 changelog.d/added-16063-hub-fleet-activity-page.md create mode 100644 src/docs/hub-fleet-activity.md create mode 100644 src/pkg/hub/activity_page.go create mode 100644 src/pkg/hub/activity_page_test.go create mode 100644 src/pkg/hub/static/activity.css create mode 100644 src/pkg/hub/static/activity.html create mode 100644 src/pkg/hub/static/activity.js diff --git a/changelog.d/added-16063-hub-fleet-activity-page.md b/changelog.d/added-16063-hub-fleet-activity-page.md new file mode 100644 index 0000000000..eeb77f9974 --- /dev/null +++ b/changelog.d/added-16063-hub-fleet-activity-page.md @@ -0,0 +1 @@ +- The hub has a read-only **Fleet activity** page at `/activity`, linked as **πŸ“‘ Fleet activity** next to **πŸ”¬ Evidence**. It shows the open issues and PRs of the hives you can see, from `GET /api/hub/activity`, which scopes every hive to you server-side. It polls every 15 s with `If-None-Match` and redraws only when the ETag changes. A **Hive** column carries a colour chip that opens the hive's own tracker; rows link to GitHub, titles render as text, and there are no action menus. Group-by-hive draws a header per hive with its item count and freshness (`stale` after two missed heartbeats, "upgrade to report activity" for hives that send no activity, missing hives). A list above the board always names truncated items, dropped events and stale or missing hives. Rows use the shared tracker row asset, and the page is served with its own Content-Security-Policy (no inline scripts, handlers or styles). Display mode follows separately ([#16063](https://github.com/hivecommons/hive/issues/16063), part of [#15965](https://github.com/hivecommons/hive/issues/15965), RFC [#15861](https://github.com/hivecommons/hive/issues/15861)). diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index c71853ab6e..53416c5b7e 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -35,6 +35,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:522` | | `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1773` | | `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1774` | +| `GET` | `/activity` | Signed-in user | Fleet activity page ([#16063](https://github.com/hivecommons/hive/issues/16063)): read-only, data-free shell that polls `/api/hub/activity` every 15 s with `If-None-Match`. No session β†’ `307` to `/login`; blocked user β†’ `403`. Own Content-Security-Policy (scripts and styles from `'self'` only, `script-src-attr`/`style-src-attr` `'none'`), `Cache-Control: no-cache` + content `ETag`. See [Hub Fleet activity page](../hub-fleet-activity.md) | `pkg/hub/activity_page.go` | +| `GET` | `/activity/assets/{name}` | Public | The shared tracker row asset (`pkg/webassets/trackerrow`, [#16062](https://github.com/hivecommons/hive/issues/16062)) the Fleet activity page draws rows with, byte-identical; only names in `trackerrow.Files`, else `404`. `Cache-Control: no-cache` + content `ETag` | `pkg/hub/activity_page.go` | | `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1708` | | `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1709` | | `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1710` | diff --git a/src/docs/documentation-map.md b/src/docs/documentation-map.md index b2addf2d82..b2a27e120e 100644 --- a/src/docs/documentation-map.md +++ b/src/docs/documentation-map.md @@ -17,6 +17,7 @@ Documentation for the current Hive line (branch `v5`; the code and docs live und ### First installation - [Hosted Hive Hub onboarding](hosted-hub.md) β€” signing in at `https://hive.hivecommons.dev`, requesting a hosted hive, installing the GitHub App, configuring model gateways and Copilot login, reading `/fleet`, and fixing common setup problems. +- [Hub Fleet activity page](hub-fleet-activity.md) β€” the read-only `/activity` board of open issues and PRs across the hives you can see: per-viewer scoping, hive chips, group-by-hive freshness headers, always-visible truncation and stale-source disclosures, and 15-second ETag polling. - [Docker Compose quick start](quickstart-docker-compose.md) β€” default standalone installation, prerequisites, and verification. - [Podman quick start](quickstart-podman.md) β€” standalone Quadlet/systemd installation, with rootless/rootful prerequisites. - [Kubernetes deployment](kubernetes-deployment.md) β€” standalone cluster installation, storage, authentication, and dashboard access. Related: [health checks](health-checks.md). diff --git a/src/docs/hosted-hub.md b/src/docs/hosted-hub.md index a60e10494a..a206d083af 100644 --- a/src/docs/hosted-hub.md +++ b/src/docs/hosted-hub.md @@ -163,6 +163,12 @@ Key signals: (hive owner vs hub operator) are listed in the [fleet drift signals reference](fleet-drift-signals.md). +For the open issues and pull requests the hives you can see are working on, +open **πŸ“‘ Fleet activity** (next to **πŸ”¬ Evidence**) or +. It is a read-only board that refreshes +every 15 seconds and says which hives are stale or not reporting. See +[Hub Fleet activity page](hub-fleet-activity.md). + ## Common problems and fixes | Symptom | Likely cause | Fix | diff --git a/src/docs/hub-fleet-activity.md b/src/docs/hub-fleet-activity.md new file mode 100644 index 0000000000..4132d198cf --- /dev/null +++ b/src/docs/hub-fleet-activity.md @@ -0,0 +1,112 @@ +# Hub Fleet activity page + +The **Fleet activity** page at `https:///activity` is a read-only board of +the open issues and pull requests that the hives you can see are working on. +It is the hub-side view of the Activity Monitor: each spoke attaches a bounded +activity digest to its heartbeat, and the hub merges the digests of your hives +into one board. + +Open it from the **πŸ“‘ Fleet activity** link next to **πŸ”¬ Evidence** on the +dashboard's Fleet quadrant card, or go to `/activity` directly. You must be +signed in; a browser without a hub session is sent to `/login`. + +The design is RFC [#15861](https://github.com/hivecommons/hive/issues/15861) +by @hanthor, delivered in [#15965](https://github.com/hivecommons/hive/issues/15965) +and its children. The page itself is [#16063](https://github.com/hivecommons/hive/issues/16063). + +## Who sees what + +The page shows exactly what `GET /api/hub/activity` returns for you. That +endpoint decides access per hive on the server before it reads any data: + +- A hub admin sees every registered hive. +- Everyone else sees the hives they own and the hives they hold an unexpired + grant for. +- Another hive's rows, counts and freshness never reach your browser, so they + are not in the page and not in its ETag. + +The page itself carries no fleet data. It is a static shell that loads the +board from the endpoint. + +## Reading the board + +Each row is one open issue or PR: + +| Column | Shows | +| --- | --- | +| **Hive** | A colour chip per hive. The colour is stable per hive id. The chip opens that hive's own dashboard and tracker through the hub's hive route (`/api/saas/hives//open`), which signs you in or explains why it cannot. | +| **Item** | `owner/repo#N` and whether it is an issue or a PR. It links to the item on GitHub. | +| **Title** | The item title as plain text, capped at 200 characters by the hub. A leading `[agent]` tag is drawn as a chip. | +| **Stage** | The strip column the spoke tracker would light (Open, Actionable, Claimed, PR in progress, CI / Review, Merge gate, Merged) and the stage slug. | +| **Author** | `human`, `clanker` or `hive` when the spoke knows it. | + +Rows come in the endpoint's order: most urgent first, then furthest stage. + +**Group by hive** is on by default. It draws one header row per hive, even when +the hive has no open items. The header shows: + +- the item count, plus the hive's tracked total when the digest held some back; +- freshness: + - `fresh`: the hive's activity report is recent; + - `stale`: the last activity report is older than two missed heartbeats + (more than 4 minutes); + - `not reporting`: the hive heartbeats but sends no activity block. + Upgrade it to report activity; + - `missing`: you hold a grant for a hive the hub registry does not know. + +Turn grouping off for one flat list. The Hive column still tells rows apart. + +## What the board leaves out + +The list above the table is always visible. It never hides in a tooltip. It +names every gap in the data: + +- items left out by the hub's response cap; +- items a hive's own digest cap left out (`truncated`); +- events dropped before they reached the hub (`events_dropped`); +- stale, not-reporting and missing hives. + +When nothing is missing it says so: "All N hives reporting; nothing left out". + +## Refresh + +The page polls `GET /api/hub/activity` every 15 seconds with `If-None-Match`. +The hub answers `304 Not Modified` while nothing in your view changed, and the +board is redrawn only when the ETag changes. Polling pauses while the tab is +hidden and resumes, with an immediate refresh, when you come back. The status +line shows when the data last changed and when it was last checked. If your +session expires, the page sends you to `/login`. + +## What the page does not do + +- It has no action menus. The hub is visibility-only: act on an item on + GitHub, or from the hive's own tracker. +- Display mode (`?kiosk=1`, `am.*` URL state, `?display=1` and a + `hub-activity` playlist view) is not part of this page yet; it is tracked in + [#16064](https://github.com/hivecommons/hive/issues/16064). + +## Security + +- The page is served with its own Content-Security-Policy. Scripts and styles + load only as files from the hub (`'self'`). Inline scripts, inline event + handlers and inline style attributes are refused, and the page loads nothing + from other origins. +- Titles and every other value from a spoke are written as text, never parsed + as HTML. +- The page, its script and the shared row-presentation asset are revalidated + on every load (`Cache-Control: no-cache` with a content ETag), so a hub + upgrade is picked up on the next visit. +- `/activity` is marked `noindex` and is disallowed in `robots.txt`. + +## For operators + +- A spoke publishes its digest only when `hub.activity.enabled` is on. It is + on by default for hosted spokes and opt-in for self-hosted ones. A hive that + heartbeats without it shows as `not reporting`. +- Digests live in hub memory only. After a hub restart, hives show + `not reporting` until a later heartbeat carries a full digest again. +- Rows are drawn with the tracker's own row-presentation asset + (`src/pkg/webassets/trackerrow`), which the hub serves under + `/activity/assets/`. The page defines the stage constants that asset reads, + with the spoke's values, so a hub row lights the same column as the spoke + tracker. diff --git a/src/pkg/hub/activity_page.go b/src/pkg/hub/activity_page.go new file mode 100644 index 0000000000..1e30d2287c --- /dev/null +++ b/src/pkg/hub/activity_page.go @@ -0,0 +1,98 @@ +package hub + +import ( + "io/fs" + "net/http" + "slices" + + "github.com/hivecommons/hive/pkg/dashboard/webstatic" + "github.com/hivecommons/hive/pkg/webassets/trackerrow" +) + +// Fleet activity page (#16063, part of #15965 / RFC #15861 by @hanthor). +// +// GET /activity serves a data-free shell to signed-in users; the board is +// filled in the browser by polling GET /api/hub/activity (activity.go), +// which scopes every hive to the viewer server-side. The page is read-only: +// rows link to GitHub and the hive chip to the hive's own tracker, with no +// action menus. Rows are drawn with the shared tracker row asset +// (pkg/webassets/trackerrow, #16062), served from activityAssetPrefix. + +const ( + activityPagePath = "/activity" + activityAssetPrefix = "/activity/assets/" + activityPageFile = "static/activity.html" + + // activityPageCSP follows the script-src split of + // pkg/dashboard/webstatic/csp_script_src.go: scripts are files under + // 'self' (the document has no inline ` + idx := strings.Index(html, tag) + if idx < 0 { + t.Fatalf("activity.html does not load %s (want %s)", name, tag) + } + if idx < last { + t.Errorf("%s must load after the shared row asset files, in trackerrow.Files order", name) + } + last = idx + } + for _, want := range []string{`id="activity-board"`, `id="activity-disclosures"`, ``} { + if !strings.Contains(html, want) { + t.Errorf("activity.html missing %q", want) + } + } + + js := readActivityScript(t) + for _, want := range []string{"'" + activityPath + "'", "'If-None-Match'", "ACTIVITY_POLL_MS = 15000", "stageTrackerAnchor(", "stageTrackerSplitTitleTag("} { + if !strings.Contains(js, want) { + t.Errorf("activity.js missing %q", want) + } + } + // Visibility-only and text-only: no HTML sinks, no write calls, no + // action menus. + for _, banned := range []string{"innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "data-action", "method:", "eval(", "new Function"} { + if strings.Contains(js, banned) { + t.Errorf("activity.js contains %q; the page renders text only and offers no actions", banned) + } + } +} + +func TestActivityPage_RoutesThroughTheHubMux(t *testing.T) { + t.Setenv("HUB_DATA_DIR", t.TempDir()) + srv := newHubServerForTest(t, withHubIdentity("test", "v5")) + serve := func(path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + srv.mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + return rec + } + + if rec := serve(activityPagePath); rec.Code != http.StatusTemporaryRedirect { + t.Errorf("GET /activity anonymous = %d, want redirect to login", rec.Code) + } + for _, name := range trackerrow.Files { + want, err := fs.ReadFile(trackerrow.FS, name) + if err != nil { + t.Fatal(err) + } + rec := serve(activityAssetPrefix + name) + if rec.Code != http.StatusOK { + t.Fatalf("GET %s%s = %d", activityAssetPrefix, name, rec.Code) + } + if rec.Body.String() != string(want) { + t.Errorf("%s must be served byte-identical to pkg/webassets/trackerrow", name) + } + if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/javascript") { + t.Errorf("%s Content-Type = %q, want text/javascript", name, ct) + } + if rec.Header().Get("Cache-Control") != "no-cache" || rec.Header().Get("ETag") != webstatic.ETagFor(want) { + t.Errorf("%s cache headers = %q / %q, want the static no-cache + content ETag", name, rec.Header().Get("Cache-Control"), rec.Header().Get("ETag")) + } + } + for _, bad := range []string{"nope.js", "trackerrow.go", "trackerrow_test.go"} { + if rec := serve(activityAssetPrefix + bad); rec.Code != http.StatusNotFound { + t.Errorf("GET %s%s = %d, want 404", activityAssetPrefix, bad, rec.Code) + } + } + if rec := serve("/static/activity.js"); rec.Code != http.StatusOK { + t.Errorf("GET /static/activity.js = %d, want 200", rec.Code) + } + if !hubNoIndexPath(activityPagePath) || !hubNoIndexPath(activityAssetPrefix+trackerrow.Files[0]) { + t.Errorf("/activity is a signed-in page and must be noindex") + } +} + +// Acceptance (#16063): two spokes heartbeating to one hub; through the page, +// a user scoped to one hive sees only that hive's rows and an admin sees +// both. The page shell carries no data; every row comes from the endpoint +// the page polls, which scopes per viewer. +func TestActivityPage_TwoSpokesScopedThroughThePage(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + s := newActivityHub() + postActivityHeartbeat(t, s, "hive-a", activityDigest("o/a", 1, 2)) + postActivityHeartbeat(t, s, "hive-b", activityDigest("o/b", 3)) + if err := saveSaaSUser(&SaaSUser{GitHubUsername: "alice", Hives: map[string]string{"hive-a": "viewer"}}); err != nil { + t.Fatal(err) + } + mkUser(t, "root") + + js := readActivityScript(t) + if !strings.Contains(js, "'"+activityPath+"'") { + t.Fatalf("the page must poll %s", activityPath) + } + for user, wantHives := range map[string][]string{"alice": {"hive-a"}, "root": {"hive-a", "hive-b"}} { + page := getActivityPage(t, s, user, "") + if page.Code != http.StatusOK { + t.Fatalf("%s: page status %d", user, page.Code) + } + for _, other := range []string{"hive-a", "hive-b", "o/a", "o/b"} { + if strings.Contains(page.Body.String(), other) { + t.Fatalf("%s: the page shell must carry no fleet data, found %q", user, other) + } + } + v := decodeActivity(t, getActivity(t, s, user, "", "")) + got := activityHiveIDs(v) + if len(got) != len(wantHives) { + t.Fatalf("%s sees rows of %v, want %v", user, got, wantHives) + } + for _, id := range wantHives { + if !got[id] { + t.Fatalf("%s sees rows of %v, want %v", user, got, wantHives) + } + } + if len(v.Hives) != len(wantHives) { + t.Fatalf("%s sees group headers %+v, want %v", user, v.Hives, wantHives) + } + } +} + +// The board's pure helpers, run under node with the shared row asset loaded +// first, exactly as the page loads them. +func TestActivityPage_BoardModel(t *testing.T) { + var sources []string + for _, name := range trackerrow.Files { + b, err := fs.ReadFile(trackerrow.FS, name) + if err != nil { + t.Fatal(err) + } + sources = append(sources, string(b)) + } + now := time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC) + view := map[string]any{ + "hives": []map[string]any{ + {"hive_id": "hive-a", "name": "Alpha", "status": "ok", "reporting": true, "received_at": now.Add(-time.Minute), "totals": map[string]any{"items": 4}, "truncated": 2}, + {"hive_id": "hive-b", "status": "stale", "reporting": true, "stale": true, "received_at": now.Add(-10 * time.Minute), "events_dropped": 5}, + {"hive_id": "hive-c", "name": "Gamma", "status": "not_reporting", "last_heartbeat": now.Add(-time.Minute)}, + {"hive_id": "hive-d", "status": "missing"}, + }, + "items": []map[string]any{ + {"hive_id": "hive-a", "repo": "o/a", "n": 7, "kind": "pr", "title": "[scanner] Fix the thing", "stage": "fixing", "stage_n": 70}, + {"hive_id": "hive-b", "repo": "o/b", "n": 9, "kind": "issue", "title": "Plain", "stage": "ready-for-human", "stage_n": 90}, + {"hive_id": "hive-a", "repo": "o/a", "n": 8, "kind": "issue", "title": "Open one", "stage": "open"}, + }, + "events": []any{}, + "truncated": 12, + } + vb, err := json.Marshal(view) + if err != nil { + t.Fatal(err) + } + src := strings.Join(append(sources, readActivityScript(t), + "var view = "+string(vb)+";", + "var now = Date.parse('"+now.Format(time.RFC3339)+"');", + "var groups = activityGroups(view, now);", + "result = {", + " groups: groups.map(function(g){ return {id: g.header.hiveId, label: g.header.label, count: g.header.count, freshness: g.header.freshness, note: g.header.note, rows: g.rows.map(function(r){ return r.number; })}; }),", + " disclosures: activityDisclosures(view, now),", + " rows: activityRows(view).map(function(r){ return {hive: r.hiveId, url: r.url, tag: r.tag, title: r.title, column: r.column, hiveURL: r.hiveURL}; }),", + " hue: [activityHiveHue('hive-a'), activityHiveHue('hive-a'), activityHiveHue('hive-b')],", + " odd: activityHiveURL('a/b c'),", + "};", + ), "\n") + var got struct { + Groups []struct { + ID, Label, Freshness, Note string + Count int + Rows []int + } + Disclosures []string + Rows []struct{ Hive, URL, Tag, Title, Column, HiveURL string } + Hue []int + Odd string + } + runEvidenceJS(t, src, &got) + + // One header per visible hive, in the API's order, even with no rows. + if len(got.Groups) != 4 { + t.Fatalf("groups = %+v, want one header per hive", got.Groups) + } + wantGroups := []struct { + id, label, freshness, note string + count int + rows []int + }{ + {"hive-a", "Alpha", "fresh", "", 2, []int{7, 8}}, + {"hive-b", "hive-b", "stale", "stale", 1, []int{9}}, + {"hive-c", "Gamma", "not reporting", "upgrade to report activity", 0, nil}, + {"hive-d", "hive-d", "missing", "not in the hub registry", 0, nil}, + } + for i, w := range wantGroups { + g := got.Groups[i] + if g.ID != w.id || g.Label != w.label || g.Freshness != w.freshness || g.Count != w.count || len(g.Rows) != len(w.rows) { + t.Errorf("group %d = %+v, want %+v", i, g, w) + continue + } + if !strings.Contains(g.Note, w.note) { + t.Errorf("group %s note = %q, want it to mention %q", w.id, g.Note, w.note) + } + for j := range w.rows { + if g.Rows[j] != w.rows[j] { + t.Errorf("group %s rows = %v, want %v", w.id, g.Rows, w.rows) + } + } + } + + // Truncation and stale/missing sources are always spelled out. + joined := strings.Join(got.Disclosures, "\n") + for _, want := range []string{"12 more items", "Alpha (hive-a): 2 items", "hive-b: 5 events dropped", "hive-b: stale", "Gamma (hive-c): upgrade to report activity", "hive-d: not in the hub registry"} { + if !strings.Contains(joined, want) { + t.Errorf("disclosures missing %q:\n%s", want, joined) + } + } + + if len(got.Rows) != 3 { + t.Fatalf("rows = %+v", got.Rows) + } + r := got.Rows[0] + if r.URL != "https://github.com/o/a/pull/7" || r.Tag != "scanner" || r.Title != "Fix the thing" || r.Column != "CI / Review" { + t.Errorf("PR row = %+v", r) + } + if r.HiveURL != "/api/saas/hives/hive-a/open" { + t.Errorf("hive chip link = %q, want the hub's hive open route", r.HiveURL) + } + if got.Rows[1].URL != "https://github.com/o/b/issues/9" || got.Rows[1].Column != "Merge gate" { + t.Errorf("issue row = %+v", got.Rows[1]) + } + if got.Rows[2].Column != "Open" { + t.Errorf("open row column = %q", got.Rows[2].Column) + } + if got.Hue[0] != got.Hue[1] || got.Hue[0] == got.Hue[2] || got.Hue[0] < 0 || got.Hue[0] >= 360 { + t.Errorf("hive hues %v must be stable per hive and differ between these two", got.Hue) + } + if got.Odd != "/api/saas/hives/a%2Fb%20c/open" { + t.Errorf("hive id must be path-escaped: %q", got.Odd) + } +} + +// The shared row asset reads the STAGE_TRACKER_* constants as free globals +// that only the spoke page defines (#16067 / #16081). The hub page must +// define every one the embedded asset references, with the spoke's value, +// or the hub would light different strip columns than the spoke tracker. +// The set is derived from the embedded files themselves, so a constant the +// asset starts reading fails here until the page defines it. +func TestActivityPage_DefinesTrackerRowGlobalsWithSpokeValues(t *testing.T) { + globalRe := regexp.MustCompile(`\bSTAGE_TRACKER_[A-Z_]+\b`) + required := map[string]bool{} + for _, name := range trackerrow.Files { + b, err := fs.ReadFile(trackerrow.FS, name) + if err != nil { + t.Fatal(err) + } + for _, g := range globalRe.FindAllString(string(b), -1) { + required[g] = true + } + } + if len(required) == 0 { + t.Fatal("found no STAGE_TRACKER_* globals in the shared row asset; the scan is broken") + } + + spokeFiles, err := filepath.Glob(filepath.Join("..", "dashboard", "static-src", "js", "*.js")) + if err != nil || len(spokeFiles) == 0 { + t.Fatalf("spoke static-src not found (%v)", err) + } + var spoke strings.Builder + for _, f := range spokeFiles { + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + spoke.Write(b) + spoke.WriteByte('\n') + } + js := readActivityScript(t) + decl := func(src, name string) string { + m := regexp.MustCompile(`(?m)^\s*const ` + name + ` = (.+?);`).FindStringSubmatch(src) + if m == nil { + return "" + } + return strings.TrimSpace(m[1]) + } + for name := range required { + want := decl(spoke.String(), name) + if want == "" { + t.Errorf("the spoke no longer defines %s; update the shared asset contract", name) + continue + } + if got := decl(js, name); got != want { + t.Errorf("activity.js %s = %q, want the spoke's %q", name, got, want) + } + } + if !strings.Contains(js, "function esc(") { + t.Errorf("activity.js must define esc(): tracker-row-title.js calls it") + } +} diff --git a/src/pkg/hub/assets/dashboard.html b/src/pkg/hub/assets/dashboard.html index 7f2069e70c..47d4e2340f 100644 --- a/src/pkg/hub/assets/dashboard.html +++ b/src/pkg/hub/assets/dashboard.html @@ -476,6 +476,8 @@ .fleet-quadrant-head { display: flex; align-items: center; gap: var(--sp-3); } .fleet-quadrant-evidence-btn { border: 1px solid var(--hub-dashboard-accent); background: color-mix(in srgb, var(--hub-dashboard-accent) 12%, transparent); color: var(--hub-dashboard-accent); border-radius: var(--r-pill); padding: var(--sp-0) var(--sp-3); font: inherit; font-size: var(--fs-2xs); font-weight: 600; cursor: pointer; white-space: nowrap; } .fleet-quadrant-evidence-btn:hover, .fleet-quadrant-evidence-btn:focus-visible { background: color-mix(in srgb, var(--hub-dashboard-accent) 25%, transparent); outline: none; } + .fleet-activity-link { border: 1px solid var(--line); border-radius: var(--r-pill); padding: var(--sp-0) var(--sp-3); font-size: var(--fs-2xs); font-weight: 600; color: var(--text); text-decoration: none; white-space: nowrap; } + .fleet-activity-link:hover, .fleet-activity-link:focus-visible { border-color: var(--hub-dashboard-accent); color: var(--hub-dashboard-accent); outline: none; } .fleet-quadrant-hint { font-size: var(--fs-2xs); color: var(--muted); margin-top: var(--sp-2); } .evidence-section { margin-bottom: var(--sp-8); } .evidence-title { font-size: var(--fs-base); color: var(--text); margin: 0 0 var(--sp-2); } @@ -1408,7 +1410,7 @@

' + - 'Fleet quadrant Β· ' + esc(scope) + ' Β· ' + esc(agg) + '' + fleetQuadrantEvidenceButtonHTML() + '' + + 'Fleet quadrant Β· ' + esc(scope) + ' Β· ' + esc(agg) + '' + fleetQuadrantEvidenceButtonHTML() + fleetActivityLinkHTML() + '' + '
' + axes + '
' + quadrantSummaryHTML(q, true) + fleetQuadrantHintHTML() + @@ -1439,6 +1441,16 @@

\uD83D\uDD2C Evidence'; } + /* fleetActivityLinkHTML links the read-only Fleet activity board + (/activity, #16063) next to Evidence. Unlike Evidence it is not + admin-only: GET /api/hub/activity scopes every hive to the viewer, so + every signed-in user gets the link. It stops propagation so an admin's + click does not also open the evidence modal from the card. */ + function fleetActivityLinkHTML() { + return '\uD83D\uDCE1 Fleet activity'; + } + function fleetQuadrantHintHTML() { if (!_isAdmin) return ''; return '
Click the chart or Evidence to open the fleet evidence details
'; diff --git a/src/pkg/hub/canonical_url_test.go b/src/pkg/hub/canonical_url_test.go index 9eb8ade41e..3ec55af05f 100644 --- a/src/pkg/hub/canonical_url_test.go +++ b/src/pkg/hub/canonical_url_test.go @@ -32,6 +32,7 @@ var staticPageCanonicals = map[string]string{ "cncf-reference-architecture-console.html": "/cncf-reference-architecture/console", "cncf-reference-architecture-bluefin.html": "/cncf-reference-architecture/bluefin", "my-hives.html": "/fleet", + "activity.html": "/activity", } const canonicalOrigin = "https://hive.hivecommons.dev" diff --git a/src/pkg/hub/evidence_drilldown_ui_test.go b/src/pkg/hub/evidence_drilldown_ui_test.go index ea3ae6eca7..9cf766f77d 100644 --- a/src/pkg/hub/evidence_drilldown_ui_test.go +++ b/src/pkg/hub/evidence_drilldown_ui_test.go @@ -170,6 +170,7 @@ func TestFleetQuadrantCardDrillGatedOnAdmin(t *testing.T) { jsFunc(t, "fleetQuadrantScopeLabel"), jsFunc(t, "fleetQuadrantDrillAttrs"), jsFunc(t, "fleetQuadrantEvidenceButtonHTML"), + jsFunc(t, "fleetActivityLinkHTML"), jsFunc(t, "fleetQuadrantHintHTML"), jsFunc(t, "fleetQuadrantHeaderHTML"), "_isAdmin = true; var admin = fleetQuadrantHeaderHTML();", @@ -197,6 +198,16 @@ func TestFleetQuadrantCardDrillGatedOnAdmin(t *testing.T) { t.Errorf("admin fleet card is missing %q:\n%s", want, got.Admin) } } + // The Fleet activity page (#16063) is linked next to Evidence for every + // signed-in viewer: GET /api/hub/activity scopes per hive, so members + // get the link too. + const activityLink = `πŸ“‘ Fleet activity` + if !strings.Contains(got.Admin, activityLink) || !strings.Contains(got.Member, activityLink) { + t.Errorf("fleet card must link the Fleet activity page for admins and members:\nadmin: %s\nmember: %s", got.Admin, got.Member) + } + if strings.Index(got.Admin, activityLink) < strings.Index(got.Admin, "πŸ”¬ Evidence") { + t.Errorf("Fleet activity belongs right after the Evidence button:\n%s", got.Admin) + } if strings.Count(got.Admin, "openEvidenceModal()") != 3 { t.Errorf("admin fleet card should wire the drill click, its keydown and the button, got:\n%s", got.Admin) } diff --git a/src/pkg/hub/robots.go b/src/pkg/hub/robots.go index 8c0d166324..2311c59251 100644 --- a/src/pkg/hub/robots.go +++ b/src/pkg/hub/robots.go @@ -46,6 +46,7 @@ var hubNoIndexPrefixes = []string{ "/access-denied", "/error/", "/fleet", + "/activity", "/my-hives", "/gh-setup", "/ws", diff --git a/src/pkg/hub/robots_test.go b/src/pkg/hub/robots_test.go index 4737f9b2ee..f5a4a229c8 100644 --- a/src/pkg/hub/robots_test.go +++ b/src/pkg/hub/robots_test.go @@ -110,6 +110,9 @@ func TestHubNoIndexPath(t *testing.T) { "/access-denied": true, "/error/503": true, "/fleet": true, + "/activity": true, + "/activity/assets/x.js": true, + "/activityx": false, "/my-hives": true, "/gh-setup": true, "/ws": true, diff --git a/src/pkg/hub/server.go b/src/pkg/hub/server.go index 38f966a5ac..ed5b663a79 100644 --- a/src/pkg/hub/server.go +++ b/src/pkg/hub/server.go @@ -1790,6 +1790,9 @@ func NewHubServer(port int, logger *slog.Logger, gitHash, gitBranch string) *Hub s.registerOAuth() s.registerSaaSRoutes() s.registerOpenRouterRoutes() + // Fleet activity page (#16063): signed-in, read-only board over + // GET /api/hub/activity. + s.registerActivityPageRoutes() go s.saveLoop() go s.refreshActiveMyHivesSnapshotsLoop() diff --git a/src/pkg/hub/static/activity.css b/src/pkg/hub/static/activity.css new file mode 100644 index 0000000000..3fcdb3e0cc --- /dev/null +++ b/src/pkg/hub/static/activity.css @@ -0,0 +1,93 @@ +/* Fleet activity page (#16063). Served from /static/ under the page's + style-src 'self'; no inline styles. Hive chip colours come from the + --hive-hue custom property, set through the CSSOM by activity.js. */ +* { box-sizing: border-box; } +html, body { + margin: 0; + background: var(--surface-1); + color: var(--text); + font-family: var(--font-ui); + font-size: 14px; + line-height: 1.5; +} +a { color: inherit; } +.activity-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--sp-6); + padding: var(--sp-5) clamp(1rem, 4vw, 4.5rem); + border-bottom: 1px solid var(--line); + background: var(--surface-0); + position: sticky; + top: 0; + z-index: 10; +} +.activity-brand { font-weight: 800; text-decoration: none; } +.activity-nav { display: flex; flex-wrap: wrap; gap: var(--sp-6); } +.activity-nav a { color: var(--text-muted); text-decoration: none; } +.activity-nav a.active, .activity-nav a:hover { color: var(--text); } +.activity-main { padding: var(--sp-6) clamp(1rem, 4vw, 4.5rem) var(--sp-9); } +.activity-titlebar h1 { margin: 0 0 var(--sp-2); font-size: 1.4rem; } +.activity-sub { margin: 0 0 var(--sp-5); color: var(--text-muted); } +.activity-controls { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-6); margin-bottom: var(--sp-5); } +.activity-toggle { display: inline-flex; align-items: center; gap: var(--sp-3); cursor: pointer; } +.activity-status { color: var(--text-muted); font-size: var(--fs-sm); } +.activity-status-bad { color: var(--status-error); } +.activity-disclosures { + list-style: none; + margin: 0 0 var(--sp-6); + padding: var(--sp-4) var(--sp-5); + border: 1px solid var(--line); + border-left: 3px solid var(--status-warn); + border-radius: 6px; + background: var(--surface-2); + font-size: var(--fs-base); +} +.activity-disclosures li + li { margin-top: var(--sp-2); } +.activity-board { width: 100%; border-collapse: collapse; font-size: var(--fs-base); } +.activity-board th, .activity-board td { text-align: left; padding: var(--sp-3) var(--sp-4); border-bottom: 1px solid var(--line-subtle); vertical-align: top; } +.activity-board thead th { color: var(--text-muted); font-weight: 600; font-size: var(--fs-sm); } +.activity-group th { background: var(--surface-2); font-weight: 600; } +.activity-group th > * + * { margin-left: var(--sp-5); } +.activity-group-count { color: var(--text); } +.activity-group-note { color: var(--text-muted); font-weight: 400; } +.activity-chip { + --hive-hue: 210; + display: inline-block; + padding: var(--sp-0) var(--sp-4); + border-radius: var(--r-pill); + border: 1px solid hsl(var(--hive-hue) 60% 55% / .6); + background: hsl(var(--hive-hue) 60% 50% / .18); + color: var(--text); + font-size: var(--fs-sm); + font-weight: 600; + text-decoration: none; + white-space: nowrap; +} +a.activity-chip:hover, a.activity-chip:focus-visible { background: hsl(var(--hive-hue) 60% 50% / .32); } +.activity-fresh { padding: var(--sp-0) var(--sp-3); border-radius: var(--r-pill); font-size: var(--fs-xs); border: 1px solid currentColor; } +.activity-fresh-fresh { color: var(--status-ok); } +.activity-fresh-stale { color: var(--status-warn); } +.activity-fresh-not-reporting { color: var(--status-neutral); } +.activity-fresh-missing { color: var(--status-error); } +.activity-number { white-space: nowrap; } +.activity-kind, .activity-stage, .activity-tag { + margin-left: var(--sp-3); + color: var(--text-muted); + font-size: var(--fs-xs); +} +.activity-tag { + margin: 0 var(--sp-3) 0 0; + padding: var(--sp-0) var(--sp-3); + border: 1px solid var(--line); + border-radius: var(--r-pill); +} +.activity-title { overflow-wrap: anywhere; } +.activity-column { font-weight: 600; } +.activity-empty { color: var(--text-muted); } +@media (max-width: 720px) { + .activity-board thead { display: none; } + .activity-board tr { display: block; padding: var(--sp-3) 0; } + .activity-board td, .activity-board th { display: block; border: 0; padding: var(--sp-1) var(--sp-4); } +} diff --git a/src/pkg/hub/static/activity.html b/src/pkg/hub/static/activity.html new file mode 100644 index 0000000000..722972aa3d --- /dev/null +++ b/src/pkg/hub/static/activity.html @@ -0,0 +1,51 @@ + + + + + + +Fleet activity β€” Hive Hub + + + + + + + + + + + +
+ 🐝 Hive + +
+
+
+

Fleet activity

+

Open issues and pull requests across the hives you can see. Read-only: open an item on GitHub, or a hive's own tracker to act on it.

+
+ + Loading… +
+
+ +
    + + + + + +
    HiveItemTitleStageAuthor
    + +
    + + diff --git a/src/pkg/hub/static/activity.js b/src/pkg/hub/static/activity.js new file mode 100644 index 0000000000..3b35ce4dd2 --- /dev/null +++ b/src/pkg/hub/static/activity.js @@ -0,0 +1,381 @@ +// Fleet activity board (#16063, part of #15965 / RFC #15861). +// +// Polls GET /api/hub/activity with If-None-Match every 15 s and re-renders +// only when the ETag changes. The endpoint scopes every hive to the viewer +// server-side; this page shows exactly what it returns. Visibility only: rows +// link to GitHub and the hive chip to that hive's own tracker; there are no +// action controls. Titles are set as text (textContent), never as HTML. +// +// Rows use the shared tracker row asset (pkg/webassets/trackerrow, loaded +// before this file): stageTrackerAnchor picks the strip column and +// stageTrackerSplitTitleTag splits the "[agent]" tag off a title. Both read +// the STAGE_TRACKER_* constants below as globals; their values must equal the +// spoke's (TestActivityPage_DefinesTrackerRowGlobalsWithSpokeValues). + +const STAGE_TRACKER_PATH = [0, 10, 20, 30, 50, 80]; +const STAGE_TRACKER_PR_COLUMN = 30; +const STAGE_TRACKER_MERGE_COLUMN = 80; +const STAGE_TRACKER_NEEDS_DECISION = 85; +const STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45; +const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10; +const STAGE_TRACKER_TRIAGE_NEEDED = 15; +const STAGE_TRACKER_POSSIBLY_EXISTS = 17; +const STAGE_TRACKER_PRE_MERGE_SOAK = 95; +const STAGE_TRACKER_TERMINAL = 110; + +// The digest carries stage numbers but not the spoke's stage table, so the +// detours' branch_from (stageTrackerBranchFrom in pkg/dashboard) is listed +// here: review-side detours hang off CI / Review, merge-side ones off the +// Merge gate. +const ACTIVITY_STAGE_DETOURS = [ + { number: 70, branch_from: 50 }, { number: 71, branch_from: 50 }, + { number: 72, branch_from: 50 }, { number: 74, branch_from: 50 }, + { number: 85, branch_from: 80 }, { number: 90, branch_from: 80 }, +]; +const ACTIVITY_COLUMN_LABELS = { 0: 'Open', 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 50: 'CI / Review', 80: 'Merge gate', 110: 'Merged' }; + +const ACTIVITY_API = '/api/hub/activity'; +const ACTIVITY_POLL_MS = 15000; + +// esc is the HTML escaper tracker-row-title.js expects from its host. This +// page never builds HTML strings; it is defined so the shared asset loads +// with its full contract. +function esc(s) { + return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { + return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; + }); +} + +function activityPlural(n, one, many) { + return n + ' ' + (n === 1 ? one : many); +} + +function activityAgo(iso, now) { + const t = Date.parse(iso || ''); + if (!isFinite(t)) return 'never'; + const s = Math.max(0, Math.round((now - t) / 1000)); + if (s < 60) return 'just now'; + if (s < 3600) return Math.floor(s / 60) + 'm ago'; + if (s < 86400) return Math.floor(s / 3600) + 'h ago'; + return Math.floor(s / 86400) + 'd ago'; +} + +function activityItemURL(it) { + const parts = String(it.repo || '').split('/'); + const n = Number(it.n); + if (parts.length !== 2 || !parts[0] || !parts[1] || !(n > 0)) return ''; + return 'https://github.com/' + parts.map(encodeURIComponent).join('/') + '/' + (it.kind === 'pr' ? 'pull' : 'issues') + '/' + n; +} + +// The hub's existing hive route: signs the viewer in to the hive's own +// dashboard (its tracker), or explains why it cannot. +function activityHiveURL(hiveId) { + const id = String(hiveId); + // "." and ".." survive encodeURIComponent and would resolve to another path. + if (!id || id === '.' || id === '..') return ''; + return '/api/saas/hives/' + encodeURIComponent(id) + '/open'; +} + +// A stable hue per hive id (FNV-1a), so a hive keeps its chip colour across +// polls and viewers. +function activityHiveHue(hiveId) { + let h = 0x811c9dc5; + const s = String(hiveId); + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 0x01000193) >>> 0; + } + return h % 360; +} + +function activityHiveDisplay(hv) { + return hv.name && hv.name !== hv.hive_id ? hv.name + ' (' + hv.hive_id + ')' : String(hv.hive_id); +} + +function activityColumn(it) { + const col = stageTrackerAnchor(Number(it.stage_n) || 0, ACTIVITY_STAGE_DETOURS, it.kind === 'pr' ? 'pr' : 'issue', null); + return ACTIVITY_COLUMN_LABELS[col] || ACTIVITY_COLUMN_LABELS[0]; +} + +function activityFreshness(hv) { + switch (hv.status) { + case 'missing': return 'missing'; + case 'not_reporting': return 'not reporting'; + case 'stale': return 'stale'; + } + return hv.stale ? 'stale' : 'fresh'; +} + +function activityHiveHeader(hv, count, now) { + const freshness = activityFreshness(hv); + let note = ''; + if (freshness === 'missing') { + note = 'not in the hub registry'; + } else if (freshness === 'not reporting') { + note = 'heartbeats but sends no activity β€” upgrade to report activity'; + } else if (freshness === 'stale') { + note = 'stale β€” last activity report ' + activityAgo(hv.received_at, now) + ', over two missed heartbeats'; + } else { + note = 'last activity report ' + activityAgo(hv.received_at, now); + } + return { + hiveId: String(hv.hive_id), + label: hv.name || String(hv.hive_id), + count: count, + total: hv.totals && Number(hv.totals.items) || 0, + truncated: Number(hv.truncated) || 0, + freshness: freshness, + note: note, + hue: activityHiveHue(hv.hive_id), + linkable: freshness !== 'missing', + }; +} + +function activityRows(view) { + const names = {}; + (view.hives || []).forEach(function (hv) { names[hv.hive_id] = hv.name || ''; }); + return (view.items || []).map(function (it) { + const parts = stageTrackerSplitTitleTag(it.title); + return { + hiveId: String(it.hive_id), + hiveLabel: names[it.hive_id] || String(it.hive_id), + hue: activityHiveHue(it.hive_id), + hiveURL: activityHiveURL(it.hive_id), + number: Number(it.n), + kind: it.kind === 'pr' ? 'PR' : 'Issue', + repo: String(it.repo || ''), + url: activityItemURL(it), + tag: parts.tag, + title: parts.text, + fullTitle: String(it.title || ''), + column: activityColumn(it), + stage: String(it.stage || ''), + author: it.author_kind || '', + }; + }); +} + +// activityGroups returns one group per visible hive, in the endpoint's +// order, each with its header and rows; a hive with no rows still gets its +// header so freshness and "upgrade to report activity" stay on the board. +function activityGroups(view, now) { + const rows = activityRows(view); + const byHive = {}; + rows.forEach(function (r) { (byHive[r.hiveId] = byHive[r.hiveId] || []).push(r); }); + const groups = (view.hives || []).map(function (hv) { + const mine = byHive[hv.hive_id] || []; + delete byHive[hv.hive_id]; + return { header: activityHiveHeader(hv, mine.length, now), rows: mine }; + }); + Object.keys(byHive).forEach(function (id) { + groups.push({ header: activityHiveHeader({ hive_id: id, status: 'ok' }, byHive[id].length, now), rows: byHive[id] }); + }); + return groups; +} + +// activityDisclosures spells out everything the board does not show: items +// left out by the hub's response cap or a hive's digest cap, dropped events, +// and stale, not-reporting or missing hives. It is rendered as a visible +// list on every poll. +function activityDisclosures(view, now) { + const out = []; + const cut = Number(view.truncated) || 0; + if (cut > 0) out.push(activityPlural(cut, 'more item', 'more items') + ' matched but were left out by the hub’s response cap'); + (view.hives || []).forEach(function (hv) { + const who = activityHiveDisplay(hv); + const freshness = activityFreshness(hv); + if (freshness === 'missing') out.push(who + ': not in the hub registry (access granted, but the hub does not know this hive)'); + if (freshness === 'not reporting') out.push(who + ': upgrade to report activity (it heartbeats but sends no activity)'); + if (freshness === 'stale') out.push(who + ': stale β€” last activity report ' + activityAgo(hv.received_at, now)); + if (Number(hv.truncated) > 0) out.push(who + ': ' + activityPlural(Number(hv.truncated), 'item', 'items') + ' left out by the hive’s digest cap'); + if (Number(hv.events_dropped) > 0) out.push(who + ': ' + activityPlural(Number(hv.events_dropped), 'event', 'events') + ' dropped before reaching the hub'); + }); + if (out.length === 0) { + const n = (view.hives || []).length; + out.push(n ? 'All ' + activityPlural(n, 'hive', 'hives') + ' reporting; nothing left out' : 'You cannot see any hive yet'); + } + return out; +} + +// ---- DOM (browser only) ---- + +function activityEl(tag, cls, text) { + const el = document.createElement(tag); + if (cls) el.className = cls; + if (text != null) el.textContent = String(text); + return el; +} + +function activityChip(hiveId, label, hue, href) { + const chip = activityEl(href ? 'a' : 'span', 'activity-chip', label); + chip.style.setProperty('--hive-hue', String(hue)); + chip.title = hiveId; + if (href) { + chip.href = href; + chip.title = 'Open ' + hiveId + '’s own tracker'; + } + return chip; +} + +function activityLink(href, cls, text) { + if (!href) return activityEl('span', cls, text); + const a = activityEl('a', cls, text); + a.href = href; + a.target = '_blank'; + a.rel = 'noopener noreferrer'; + return a; +} + +function activityRowEl(r, missing) { + const tr = activityEl('tr', 'activity-row'); + const hive = activityEl('td', 'activity-cell-hive'); + hive.appendChild(activityChip(r.hiveId, r.hiveLabel, r.hue, missing ? '' : r.hiveURL)); + const item = activityEl('td', 'activity-cell-item'); + item.appendChild(activityLink(r.url, 'activity-number', r.repo + '#' + r.number)); + item.appendChild(activityEl('span', 'activity-kind', r.kind)); + const title = activityEl('td', 'activity-cell-title'); + if (r.tag) title.appendChild(activityEl('span', 'activity-tag', r.tag)); + const t = activityLink(r.url, 'activity-title', r.title); + t.title = r.fullTitle; + title.appendChild(t); + const stage = activityEl('td', 'activity-cell-stage'); + stage.appendChild(activityEl('span', 'activity-column', r.column)); + if (r.stage) stage.appendChild(activityEl('span', 'activity-stage', r.stage)); + tr.append(hive, item, title, stage, activityEl('td', 'activity-cell-author', r.author || 'β€”')); + return tr; +} + +function activityHeaderEl(h) { + const tr = activityEl('tr', 'activity-group activity-group-' + h.freshness.replace(' ', '-')); + const cell = activityEl('th', ''); + cell.colSpan = 5; + cell.appendChild(activityChip(h.hiveId, h.label, h.hue, h.linkable ? activityHiveURL(h.hiveId) : '')); + let count = activityPlural(h.count, 'item', 'items'); + if (h.total > h.count) count += ' shown of ' + h.total + ' tracked'; + cell.appendChild(activityEl('span', 'activity-group-count', count)); + cell.appendChild(activityEl('span', 'activity-fresh activity-fresh-' + h.freshness.replace(' ', '-'), h.freshness)); + cell.appendChild(activityEl('span', 'activity-group-note', h.note)); + tr.appendChild(cell); + return tr; +} + +const ACTIVITY_FETCH_TIMEOUT_MS = 10000; +const activityState = { etag: '', view: null, grouped: true, timer: 0, updatedAt: 0, inflight: false }; + +function activityRender() { + const view = activityState.view; + if (!view) return; + const now = Date.now(); + const missing = {}; + (view.hives || []).forEach(function (hv) { if (hv.status === 'missing') missing[hv.hive_id] = true; }); + + const notes = document.createDocumentFragment(); + activityDisclosures(view, now).forEach(function (text) { notes.appendChild(activityEl('li', '', text)); }); + document.getElementById('activity-disclosures').replaceChildren(notes); + + const out = document.createDocumentFragment(); + if (activityState.grouped) { + activityGroups(view, now).forEach(function (g) { + out.appendChild(activityHeaderEl(g.header)); + g.rows.forEach(function (r) { out.appendChild(activityRowEl(r, missing[r.hiveId])); }); + }); + } else { + activityRows(view).forEach(function (r) { out.appendChild(activityRowEl(r, missing[r.hiveId])); }); + } + document.getElementById('activity-rows').replaceChildren(out); + document.getElementById('activity-empty').hidden = (view.items || []).length > 0; +} + +function activitySetStatus(text, bad) { + const el = document.getElementById('activity-status'); + el.textContent = text; + el.classList.toggle('activity-status-bad', !!bad); +} + +function activityClock(t) { + return new Date(t).toLocaleTimeString(); +} + +function activityFetchOptions(headers) { + const opts = { headers: headers, credentials: 'same-origin', cache: 'no-store' }; + if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') { + opts.signal = AbortSignal.timeout(ACTIVITY_FETCH_TIMEOUT_MS); + } + return opts; +} + +// activityPoll fetches once. It never throws: every failure is reported in +// the status line and the next poll retries. The ETag is kept only once its +// view has rendered, so a view that failed to render is fetched again rather +// than pinned by a 304. +async function activityPoll() { + if (activityState.inflight) return; + activityState.inflight = true; + try { + const headers = {}; + if (activityState.etag) headers['If-None-Match'] = activityState.etag; + let res; + try { + res = await fetch(ACTIVITY_API, activityFetchOptions(headers)); + } catch (e) { + activitySetStatus('Hub unreachable β€” retrying every 15 s', true); + return; + } + if (res.status === 401) { + window.location.assign('/login'); + return; + } + const checked = 'checked ' + activityClock(Date.now()); + if (res.status === 304) { + // Same data, but "N m ago" and staleness move with the clock. + activityRender(); + activitySetStatus('Updated ' + activityClock(activityState.updatedAt) + ' Β· ' + checked, false); + return; + } + if (!res.ok) { + activitySetStatus('Could not load activity (HTTP ' + res.status + ') β€” retrying every 15 s', true); + return; + } + const etag = res.headers.get('ETag') || ''; + const view = await res.json(); + if (!view || !Array.isArray(view.hives) || !Array.isArray(view.items)) throw new Error('unexpected activity payload'); + activityState.view = view; + activityRender(); + activityState.etag = etag; + activityState.updatedAt = Date.now(); + activitySetStatus('Updated ' + activityClock(activityState.updatedAt) + ' Β· ' + checked, false); + } catch (e) { + activityState.etag = ''; + activitySetStatus('The hub sent an unreadable response β€” retrying every 15 s', true); + } finally { + activityState.inflight = false; + } +} + +function activitySchedule() { + clearTimeout(activityState.timer); + activityState.timer = setTimeout(async function tick() { + try { + if (!document.hidden) await activityPoll(); + } finally { + activitySchedule(); + } + }, ACTIVITY_POLL_MS); +} + +function activityBoot() { + const toggle = document.getElementById('activity-group'); + activityState.grouped = toggle.checked; + toggle.addEventListener('change', function () { + activityState.grouped = toggle.checked; + activityRender(); + }); + document.addEventListener('visibilitychange', function () { + if (!document.hidden) activityPoll().finally(activitySchedule); + }); + activityPoll().finally(activitySchedule); +} + +if (typeof document !== 'undefined') { + document.addEventListener('DOMContentLoaded', activityBoot); +} From ea7dba6cc5f7483eb1aab245539238c52c877a1e Mon Sep 17 00:00:00 2001 From: Karibhou <157208370+Karibhou@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:47:08 +0100 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=8C=B1=20test(hub):=20assert=20the=20?= =?UTF-8?q?activity=20page=20globals=20against=20trackerrow.RequiredGlobal?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now that the branch carries #16081, TestActivityPage_DefinesTrackerRowGlobalsWithSpokeValues compares each STAGE_TRACKER_* declaration in static/activity.js with trackerrow.RequiredGlobals[i].Decl(), instead of re-deriving the names from the asset and re-parsing the spoke's static-src. The names stay pinned to the asset by TestRequiredGlobals and the values to the spoke by TestTrackerRowRequiredGlobalsDefinedBySpoke, so the hub now checks against the same single list instead of a second copy of the contract. Addresses the hive reviewer suggestion on #16084. Hive-Run: hivecommons/hive#16063 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HRH6kjQb8shmrV2ZP2K8GD Signed-off-by: Karibhou <157208370+Karibhou@users.noreply.github.com> --- src/pkg/hub/activity_page_test.go | 58 +++++++------------------------ 1 file changed, 13 insertions(+), 45 deletions(-) diff --git a/src/pkg/hub/activity_page_test.go b/src/pkg/hub/activity_page_test.go index aed1b8d16a..8ba95d2975 100644 --- a/src/pkg/hub/activity_page_test.go +++ b/src/pkg/hub/activity_page_test.go @@ -5,8 +5,6 @@ import ( "io/fs" "net/http" "net/http/httptest" - "os" - "path/filepath" "regexp" "strings" "testing" @@ -411,55 +409,25 @@ func TestActivityPage_BoardModel(t *testing.T) { // The shared row asset reads the STAGE_TRACKER_* constants as free globals // that only the spoke page defines (#16067 / #16081). The hub page must -// define every one the embedded asset references, with the spoke's value, -// or the hub would light different strip columns than the spoke tracker. -// The set is derived from the embedded files themselves, so a constant the -// asset starts reading fails here until the page defines it. +// define every one with the spoke's value, or the hub would light different +// strip columns than the spoke tracker. trackerrow.RequiredGlobals is that +// contract: TestRequiredGlobals keeps its names equal to what the embedded +// asset references, and TestTrackerRowRequiredGlobalsDefinedBySpoke pins its +// values to the spoke's declarations, so asserting against it here covers +// the hub with the same single list. func TestActivityPage_DefinesTrackerRowGlobalsWithSpokeValues(t *testing.T) { - globalRe := regexp.MustCompile(`\bSTAGE_TRACKER_[A-Z_]+\b`) - required := map[string]bool{} - for _, name := range trackerrow.Files { - b, err := fs.ReadFile(trackerrow.FS, name) - if err != nil { - t.Fatal(err) - } - for _, g := range globalRe.FindAllString(string(b), -1) { - required[g] = true - } - } - if len(required) == 0 { - t.Fatal("found no STAGE_TRACKER_* globals in the shared row asset; the scan is broken") - } - - spokeFiles, err := filepath.Glob(filepath.Join("..", "dashboard", "static-src", "js", "*.js")) - if err != nil || len(spokeFiles) == 0 { - t.Fatalf("spoke static-src not found (%v)", err) - } - var spoke strings.Builder - for _, f := range spokeFiles { - b, err := os.ReadFile(f) - if err != nil { - t.Fatal(err) - } - spoke.Write(b) - spoke.WriteByte('\n') + if len(trackerrow.RequiredGlobals) == 0 { + t.Fatal("trackerrow.RequiredGlobals is empty; the shared asset contract is missing") } js := readActivityScript(t) - decl := func(src, name string) string { - m := regexp.MustCompile(`(?m)^\s*const ` + name + ` = (.+?);`).FindStringSubmatch(src) + for _, g := range trackerrow.RequiredGlobals { + m := regexp.MustCompile(`(?m)^\s*(const ` + regexp.QuoteMeta(g.Name) + ` = .+?;)`).FindStringSubmatch(js) if m == nil { - return "" - } - return strings.TrimSpace(m[1]) - } - for name := range required { - want := decl(spoke.String(), name) - if want == "" { - t.Errorf("the spoke no longer defines %s; update the shared asset contract", name) + t.Errorf("activity.js must define %s: the shared row asset reads it (want %q)", g.Name, g.Decl()) continue } - if got := decl(js, name); got != want { - t.Errorf("activity.js %s = %q, want the spoke's %q", name, got, want) + if got := strings.TrimSpace(m[1]); got != g.Decl() { + t.Errorf("activity.js declares %q, trackerrow.RequiredGlobals pins the spoke's %q", got, g.Decl()) } } if !strings.Contains(js, "function esc(") {