diff --git a/changelog.d/fixed-contributor-presence-tooltip.md b/changelog.d/fixed-contributor-presence-tooltip.md new file mode 100644 index 0000000000..d3a03d229a --- /dev/null +++ b/changelog.d/fixed-contributor-presence-tooltip.md @@ -0,0 +1 @@ +- Kept the Contributors sidebar count and cards on one roster snapshot, and replaced relay IDs in its online tooltip with GitHub usernames without repeated ClankeR labels. diff --git a/dashboard/test/config-tooltip.test.js b/dashboard/test/config-tooltip.test.js index cdce459843..7d641033c9 100644 --- a/dashboard/test/config-tooltip.test.js +++ b/dashboard/test/config-tooltip.test.js @@ -75,6 +75,7 @@ class FakeElement { get textContent() { return this._textContent || ''; } set textContent(value) { this._textContent = String(value); + this.innerHTML = this._textContent.replace(/&/g, '&').replace(//g, '>'); for (const child of this.children) child.parentNode = null; this.children = []; } @@ -366,37 +367,41 @@ test('Contributors tooltip targets the count pill and supports focus without cha const pill = new FakeElement('span', 'badge-count oc-nav-count contributor-online-trigger'); pill.id = 'contributors-sidebar-badge'; h.root.appendChild(pill); - h.api.updateContributorBadge({ online: 2, registered: 4, presence_window: '15m', online_ids: ['clanker-a', 'clanker-b'] }); + h.api.updateContributorBadge({ online: 2, registered: 4, presence_window: '15m', online_ids: ['clanker-a', 'clanker-b'], online_logins: ['amy', 'bob'] }); assert.equal(pill.textContent, '2/4'); assert.equal(pill.getAttribute('title'), null, 'no duplicate browser-native title'); assert.match(pill.getAttribute('aria-label'), /2 online · 4 registered/); h.fire('document', 'focusin', pill); assert.equal(h.isOpen(), true); - assert.match(h.portal().innerHTML, /
  • clanker-a<\/li>
  • clanker-b<\/li>/); + assert.match(h.portal().innerHTML, /
  • @amy<\/li>
  • @bob<\/li>/); + assert.doesNotMatch(h.portal().innerHTML, /clanker-a|clanker-b|ClankeR/); - h.api.updateContributorBadge({ online: 1, registered: 4, online_ids: ['clanker-reconnected'] }); + h.api.updateContributorBadge({ online: 1, registered: 4, online_ids: ['clanker-reconnected'], online_logins: ['zed'] }); assert.equal(pill.textContent, '1/4'); - assert.match(h.portal().innerHTML, /
  • clanker-reconnected<\/li>/); - assert.doesNotMatch(h.portal().innerHTML, /clanker-a|clanker-b/); + assert.match(h.portal().innerHTML, /
  • @zed<\/li>/); + assert.doesNotMatch(h.portal().innerHTML, /@amy|@bob|clanker-/); - h.api.updateContributorBadge({ online: 0, registered: 4, online_ids: [] }); + h.api.updateContributorBadge({ online: 0, registered: 4, online_ids: [], online_logins: [] }); assert.equal(pill.textContent, '0/4'); - assert.match(h.portal().innerHTML, /No ClankeRs online/); + assert.match(h.portal().innerHTML, /No contributors online/); + h.api.updateContributorBadge(null); + assert.equal(pill.textContent, '0/4', 'failed refresh retains the last loaded count'); + assert.match(h.portal().innerHTML, /presence unavailable/); h.api.hideConfigTooltip(); h.fire('document', 'mouseover', pill); h.advance(h.api.openDelay); assert.equal(h.isOpen(), true, 'same pill also opens on hover'); }); -test('Contributors tooltip escapes IDs and distinguishes unavailable IDs from no online ClankeRs', () => { +test('Contributors tooltip escapes usernames and distinguishes unavailable names from nobody online', () => { const context = {}; vm.runInNewContext(['esc', 'contributorsOnlineTitle', 'contributorsOnlineTooltip'].map(extractFunction).join('\n'), context); - const html = context.contributorsOnlineTooltip({ online: 1, registered: 2, online_ids: ['&'] }); - assert.match(html, /
  • <img src=x onerror="bad">&<\/li>/); + const html = context.contributorsOnlineTooltip({ online: 1, registered: 2, online_logins: ['&'] }); + assert.match(html, /
  • @<img src=x onerror="bad">&<\/li>/); assert.doesNotMatch(html, /.svg`). | `pkg/dashboard/social_cards.go:112` | | `GET` | `/api/cards/achievement/{login}/{asset}` | Public | OpenAPI alias for a cacheable attained-achievement SVG (`asset` is `.svg`). | `pkg/dashboard/social_cards.go:113` | | `GET` | `/api/cards/leaderboard/{asset}` | Public | OpenAPI alias for a cacheable leaderboard-summary SVG (`contributors.svg`, `teams.svg`, or `swarm.svg`). | `pkg/dashboard/social_cards.go:114` | @@ -58,10 +58,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/share/player/{login}` | Public | Share landing page with Open Graph/Twitter metadata for a contributor card and link to the public dossier. | `pkg/dashboard/social_cards.go:115` | | `GET` | `/share/achievement/{login}/{achievementID}` | Public | Share landing page with metadata for an unlocked achievement card and link to the public dossier. | `pkg/dashboard/social_cards.go:116` | | `GET` | `/share/leaderboard/{board}` | Public | Share landing page with metadata for a public leaderboard card and link to live standings. | `pkg/dashboard/social_cards.go:117` | -| `PUT` | `/api/contribute/help-links` | Owner/read-write | Contribute Help Links | `pkg/dashboard/api_contribute.go:226` | -| `GET` | `/api/contribute/operators/message` | Public path; caller identity resolved server-side (401 anonymous, 403 without a profile) | Returns only the signed-in contributor's unacknowledged operator messages; no username/body field can select another recipient ([#8461](https://github.com/hivecommons/hive/issues/8461)). | `pkg/dashboard/api_contribute.go:261` | -| `POST` | `/api/contribute/operators/message` | Owner/read-write | Sends a sanitized, length-capped one-to-one operator note to a contributor profile, persists it until acknowledgement, and pushes it to matching live relay sockets only ([#8461](https://github.com/hivecommons/hive/issues/8461)). | `pkg/dashboard/api_contribute.go:262` | -| `POST` | `/api/contribute/operators/message/ack` | Public path; caller identity resolved server-side | Acknowledges the signed-in contributor's own message, optionally recording a short sanitized reply for operators. | `pkg/dashboard/api_contribute.go:263` | +| `PUT` | `/api/contribute/help-links` | Owner/read-write | Contribute Help Links | `pkg/dashboard/api_contribute.go:257` | +| `GET` | `/api/contribute/operators/message` | Public path; caller identity resolved server-side (401 anonymous, 403 without a profile) | Returns only the signed-in contributor's unacknowledged operator messages; no username/body field can select another recipient ([#8461](https://github.com/hivecommons/hive/issues/8461)). | `pkg/dashboard/api_contribute.go:292` | +| `POST` | `/api/contribute/operators/message` | Owner/read-write | Sends a sanitized, length-capped one-to-one operator note to a contributor profile, persists it until acknowledgement, and pushes it to matching live relay sockets only ([#8461](https://github.com/hivecommons/hive/issues/8461)). | `pkg/dashboard/api_contribute.go:293` | +| `POST` | `/api/contribute/operators/message/ack` | Public path; caller identity resolved server-side | Acknowledges the signed-in contributor's own message, optionally recording a short sanitized reply for operators. | `pkg/dashboard/api_contribute.go:294` | ### Issue claims (hivecommons/hive#8380) diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 54f8a5c488..7a1ca5dc82 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -48,21 +48,21 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:432` | | `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:461` | | `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:495` | -| `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:319` | -| `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:320` | -| `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:321` | -| `GET` | `/leaderboard` | Public | Leaderboard Page | `pkg/dashboard/api_contribute.go:323` | -| `GET` | `/api/leaderboard` | Public | Leaderboard API | `pkg/dashboard/api_contribute.go:324` | -| `GET` | `/api/leaderboard/teams` | Public | Team Leaderboards | `pkg/dashboard/api_contribute.go:325` | -| `GET` | `/api/leaderboard/style` | Public | Leaderboard Style | `pkg/dashboard/api_contribute.go:326` | +| `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:350` | +| `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:351` | +| `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:352` | +| `GET` | `/leaderboard` | Public | Leaderboard Page | `pkg/dashboard/api_contribute.go:354` | +| `GET` | `/api/leaderboard` | Public | Leaderboard API | `pkg/dashboard/api_contribute.go:355` | +| `GET` | `/api/leaderboard/teams` | Public | Team Leaderboards | `pkg/dashboard/api_contribute.go:356` | +| `GET` | `/api/leaderboard/style` | Public | Leaderboard Style | `pkg/dashboard/api_contribute.go:357` | | `GET` | `/api/leaderboard/battle-log` | Public | Scrubbed public Battle Log activity feed for leaderboard widgets. | `pkg/dashboard/battle_log.go:108` | | `GET` | `/api/leaderboard/hive-of-week` | Public | Featured weekly project metadata, configured render URLs (empty when none), gource source URL, and embed snippets. | `pkg/dashboard/battle_log.go:109` | | `GET` | `/api/leaderboard/gource-log` | Public | Gource custom log source for a project/week, derived from public hive event data. | `pkg/dashboard/battle_log.go:110` | | `POST` | `/api/leaderboard/hive-of-week/archive` | Owner only | Archive the selected project's weekly gource source log into knowledge; stores source only, never rendered video. | `pkg/dashboard/battle_log.go:111` | -| `GET` | `/api/leaderboard/contributor/{username}` | Public | Contributor Profile | `pkg/dashboard/api_contribute.go:333` | -| `GET` | `/api/hives` | Dashboard auth/session | Hives List | `pkg/dashboard/api_contribute.go:344` | -| `POST` | `/api/hives/register` | Dashboard auth/session | Hives Register | `pkg/dashboard/api_contribute.go:345` | -| `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:346` | -| `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:347` | -| `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:348` | +| `GET` | `/api/leaderboard/contributor/{username}` | Public | Contributor Profile | `pkg/dashboard/api_contribute.go:364` | +| `GET` | `/api/hives` | Dashboard auth/session | Hives List | `pkg/dashboard/api_contribute.go:375` | +| `POST` | `/api/hives/register` | Dashboard auth/session | Hives Register | `pkg/dashboard/api_contribute.go:376` | +| `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:377` | +| `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:378` | +| `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:379` | | `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1666` | diff --git a/src/pkg/dashboard/api_contribute.go b/src/pkg/dashboard/api_contribute.go index 436e6cf7f1..80c0539b61 100644 --- a/src/pkg/dashboard/api_contribute.go +++ b/src/pkg/dashboard/api_contribute.go @@ -83,9 +83,8 @@ var inviteTrustTiers = map[string]bool{"trusted": true, "merger": true, "advisor // the inviter username. An empty string means the token is invalid, tampered, // or expired — the caller must treat that as "no attribution" (a plain // self-registration), never as an error. -// ContributorPoolStatus feeds the sidebar's Contributors "online/total" -// pill and the section header. Online uses the SAME presence predicate the -// stage tracker's "waiting on @x (offline 13m)" reads +// ContributorPoolStatus summarizes the Contributors roster. Online uses the +// same presence predicate the stage tracker's waiting-on captions read // (ContributeWSHub.Presence): a registered contributor whose relay // heartbeat landed within governor.labels.stage.presence_window (15m by // default). Active is the older "has a live socket" count kept for callers @@ -96,6 +95,8 @@ type ContributorPoolStatus struct { Registered int `json:"registered"` // OnlineIDs contains the ClankeR contributor IDs counted by Online. OnlineIDs []string `json:"online_ids"` + // OnlineLogins names the people whose contributor relays are online. + OnlineLogins []string `json:"online_logins"` // PresenceWindow is the window Online was judged against ("15m"). PresenceWindow string `json:"presence_window"` ByRole map[string]int `json:"by_role,omitempty"` @@ -107,16 +108,42 @@ type ContributorPoolStatus struct { func (s *Server) BuildContributorPoolStatus() *ContributorPoolStatus { profiles := listContributorProfiles() + var heartbeats map[string]time.Time + window := config.DefaultPresenceWindow + if s.contributeHub != nil { + heartbeats = s.contributeHub.LastHeartbeats() + window = s.contributeHub.presenceWindow() + } + now := time.Now() + for i := range profiles { + profiles[i].Online = countOnlineContributors(profiles[i:i+1], heartbeats, window, now) == 1 + } + return s.contributorPoolStatus(profiles, window) +} + +func (s *Server) contributorPoolStatus(profiles []ContributorProfile, window time.Duration) *ContributorPoolStatus { active := 0 onlineIDs := []string{} + onlineLogins := []string{} + seenLogins := make(map[string]bool) var byRole map[string]int - window := config.DefaultPresenceWindow if s.contributeHub != nil { active = s.contributeHub.ActiveCount() byRole = s.contributeHub.RoleBreakdown() - window = s.contributeHub.presenceWindow() - onlineIDs = onlineContributorIDs(profiles, s.contributeHub.LastHeartbeats(), window, time.Now()) } + for _, p := range profiles { + if !p.Online { + continue + } + onlineIDs = append(onlineIDs, p.ContributorID) + login := strings.ToLower(strings.TrimSpace(p.GitHubUsername)) + if login != "" && !seenLogins[login] { + seenLogins[login] = true + onlineLogins = append(onlineLogins, login) + } + } + sort.Strings(onlineIDs) + sort.Strings(onlineLogins) abandoned, abandonedByLogin := contributorAbandonedCounts(profiles) return &ContributorPoolStatus{ Abandoned: abandoned, @@ -124,6 +151,7 @@ func (s *Server) BuildContributorPoolStatus() *ContributorPoolStatus { Active: active, Online: len(onlineIDs), OnlineIDs: onlineIDs, + OnlineLogins: onlineLogins, Registered: len(profiles), PresenceWindow: stageTrackerShortDuration(window), ByRole: byRole, @@ -163,7 +191,10 @@ func onlineContributorIDs(profiles []ContributorProfile, lastSeen map[string]tim } byUser := make(map[string]time.Time, len(lastSeen)) for user, t := range lastSeen { - byUser[strings.ToLower(strings.TrimSpace(user))] = t + login := strings.ToLower(strings.TrimSpace(user)) + if t.After(byUser[login]) { + byUser[login] = t + } } for _, p := range profiles { t, ok := byUser[strings.ToLower(strings.TrimSpace(p.GitHubUsername))] diff --git a/src/pkg/dashboard/contribute_admin.go b/src/pkg/dashboard/contribute_admin.go index bbf3f6642a..9e8b048187 100644 --- a/src/pkg/dashboard/contribute_admin.go +++ b/src/pkg/dashboard/contribute_admin.go @@ -68,6 +68,9 @@ func (s *Server) paneTailViewer(r *http.Request) bool { func (s *Server) handleContributorsList(w http.ResponseWriter, r *http.Request) { profiles := listContributorProfiles() + if profiles == nil { + profiles = []ContributorProfile{} + } var liveStates map[string]ContributorLiveState var heartbeats map[string]time.Time window := config.DefaultPresenceWindow @@ -95,7 +98,10 @@ func (s *Server) handleContributorsList(w http.ResponseWriter, r *http.Request) profiles[i].Sessions = ls.Sessions } } - jsonResponse(w, map[string]any{"contributors": profiles}) + jsonResponse(w, map[string]any{ + "contributors": profiles, + "contributorPool": s.contributorPoolStatus(profiles, window), + }) } func (s *Server) handleContributorGet(w http.ResponseWriter, r *http.Request) { diff --git a/src/pkg/dashboard/contributor_pool_online_test.go b/src/pkg/dashboard/contributor_pool_online_test.go index 1c15005902..9c658b8fa4 100644 --- a/src/pkg/dashboard/contributor_pool_online_test.go +++ b/src/pkg/dashboard/contributor_pool_online_test.go @@ -2,6 +2,7 @@ package dashboard import ( "encoding/json" + "net/http/httptest" "reflect" "testing" "time" @@ -37,6 +38,10 @@ func TestCountOnlineContributors(t *testing.T) { {name: "case-insensitive login match", profiles: profiles, seen: map[string]time.Time{ "karibhou": now.Add(-time.Minute), }, want: 1}, + {name: "freshest case-variant session wins", profiles: profiles, seen: map[string]time.Time{ + "Karibhou": now.Add(-time.Hour), + "karibhou": now.Add(-time.Minute), + }, want: 1}, {name: "mixed", profiles: profiles, seen: map[string]time.Time{ "Karibhou": now.Add(-time.Minute), "hanthor": now.Add(-13 * time.Minute), @@ -78,6 +83,29 @@ func TestBuildContributorPoolStatusOnline(t *testing.T) { if !reflect.DeepEqual(got.OnlineIDs, []string{"id-fresh"}) { t.Fatalf("online IDs = %v, want only id-fresh", got.OnlineIDs) } + if !reflect.DeepEqual(got.OnlineLogins, []string{"fresh"}) { + t.Fatalf("online logins = %v, want only fresh", got.OnlineLogins) + } + + w := httptest.NewRecorder() + s.handleContributorsList(w, httptest.NewRequest("GET", "/api/contributors", nil)) + var roster struct { + Contributors []ContributorProfile `json:"contributors"` + Pool ContributorPoolStatus `json:"contributorPool"` + } + if err := json.Unmarshal(w.Body.Bytes(), &roster); err != nil { + t.Fatalf("decode roster: %v\n%s", err, w.Body.String()) + } + var online int + for _, profile := range roster.Contributors { + if profile.Online { + online++ + } + } + if online != 1 || roster.Pool.Online != online || roster.Pool.Registered != len(roster.Contributors) || + !reflect.DeepEqual(roster.Pool.OnlineLogins, []string{"fresh"}) || roster.Pool.PresenceWindow != got.PresenceWindow { + t.Fatalf("roster and pool must share presence: %+v", roster) + } // A second session for the same contributor does not add another row. hub.connections["c3"] = &ContributorConnection{connID: "c3", profile: &ContributorProfile{ContributorID: "id-fresh", GitHubUsername: "fresh"}, lastPong: time.Now()} @@ -106,6 +134,41 @@ func TestBuildContributorPoolStatusOnline(t *testing.T) { if err := json.Unmarshal(data, &payload); err != nil || string(payload["online_ids"]) != "[]" { t.Fatalf("empty pool must encode online_ids: [], got %s (%v)", data, err) } + if string(payload["online_logins"]) != "[]" { + t.Fatalf("empty pool must encode online_logins: [], got %s", data) + } +} + +func TestContributorPoolOnlineLogins(t *testing.T) { + profiles := []ContributorProfile{ + {ContributorID: "relay-z", GitHubUsername: "Zed", Online: true}, + {ContributorID: "relay-a", GitHubUsername: " Amy ", Online: true}, + {ContributorID: "relay-a2", GitHubUsername: "AMY", Online: true}, + {ContributorID: "relay-offline", GitHubUsername: "offline"}, + } + pool := (&Server{}).contributorPoolStatus(profiles, 15*time.Minute) + if pool.Online != 3 || pool.Registered != 4 || + !reflect.DeepEqual(pool.OnlineIDs, []string{"relay-a", "relay-a2", "relay-z"}) || + !reflect.DeepEqual(pool.OnlineLogins, []string{"amy", "zed"}) { + t.Fatalf("pool must count online rows but list each person once: %+v", pool) + } +} + +func TestContributorsListEmptyRoster(t *testing.T) { + t.Setenv("HIVE_CONTRIBUTORS_DIR", t.TempDir()) + w := httptest.NewRecorder() + (&Server{}).handleContributorsList(w, httptest.NewRequest("GET", "/api/contributors", nil)) + var body struct { + Contributors json.RawMessage `json:"contributors"` + Pool ContributorPoolStatus `json:"contributorPool"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if string(body.Contributors) != "[]" || body.Pool.Registered != 0 || body.Pool.Online != 0 || + body.Pool.OnlineLogins == nil { + t.Fatalf("empty roster must serialize as an array with known zero counts: %s", w.Body.String()) + } } func TestOnlineContributorIDs(t *testing.T) { diff --git a/src/pkg/dashboard/nav_count_delta.test.js b/src/pkg/dashboard/nav_count_delta.test.js index 61d610e952..f086843d7f 100644 --- a/src/pkg/dashboard/nav_count_delta.test.js +++ b/src/pkg/dashboard/nav_count_delta.test.js @@ -39,11 +39,14 @@ function load() { vm.runInContext(source('nav-count-delta'), ctx); vm.runInContext(` var _kbCache = null, _kbInitialLoad = true, _kbRendered = false, _kbSetupView = 'none'; - var _cachedContributors = [], _stageTracker = null, _stageTrackerMoves = {}, _stageTrackerEvents = []; + var _cachedContributors = [], _contributorFetchID = 0, _stageTracker = null, _stageTrackerMoves = {}, _stageTrackerEvents = []; var _stageTrackerFilter = {repo: 'filtered-out'}, _stageTrackerGroup = 'none', _stageTrackerCelebrating = {}; function refreshSectionCardShell() {} function setSectionSummary() {} function contributorsSectionSummary() { return ''; } + function renderContributorFilters() {} + function renderContributors(rows) { renderedContributors = rows; } + var renderedContributors = null; function formatNumber(n) { return Number(n).toLocaleString('en-US'); } var knowledgeRenders = 0; function renderKnowledge() { knowledgeRenders++; } @@ -76,7 +79,7 @@ function load() { `, ctx); for (const [file, names] of [ ['knowledge', ['sidebarPairBadgeText', 'setSidebarPairBadge', 'setSidebarCountBadge', 'kbTotalFactsFromStats', 'kbFactsLabel', 'kbSidebarFactCount', 'fetchKnowledgeStats']], - ['contributors', ['contributorsOnlineTitle', 'contributorsOnlineTooltip', 'updateContributorBadge']], + ['contributors', ['contributorsOnlineTitle', 'contributorsOnlineTooltip', 'updateContributorBadge', 'fetchContributors']], ['tracker-waiting', ['stageTrackerWaitingOnYou', 'stageTrackerWaitingTitle', 'stageTrackerWaitKindWords', 'stageTrackerRenderWaiting']], ['tracker-words-stage', ['stageTrackerDefaultFilter']], ['tracker-filter-render', ['renderStageTracker']], @@ -286,6 +289,79 @@ test('contributors use online only, not active sockets or denominator changes', assert.equal(delta(badge), undefined); }); +test('contributor tooltip lists people only, with no relay IDs or repeated branding', () => { + const api = load(); + const tooltip = api.ctx.contributorsOnlineTooltip({ + online: 3, registered: 12, presence_window: '15m', + online_ids: ['c-first', 'c-second', 'c-third'], online_logins: ['amy', 'zed'], + }); + assert.match(tooltip, /3 online/); + assert.match(tooltip, /
  • @amy<\/li>
  • @zed<\/li>/); + assert.doesNotMatch(tooltip, /ClankeR|c-first|c-second|c-third/); + const unavailable = api.ctx.contributorsOnlineTooltip({ online: 1, registered: 12, online_ids: ['c-private'] }); + assert.match(unavailable, /names unavailable/); + assert.doesNotMatch(unavailable, /c-private|ClankeR/); + assert.match(api.ctx.contributorsOnlineTooltip({ online: 0, registered: 12, online_logins: [] }), /No contributors online/); +}); + +test('contributor cards and badge refresh from the same roster response', async () => { + const api = load(), badge = api.badge(IDS[2]); + const rows = [{ github_username: 'amy', online: true }, { github_username: 'zed', online: true }]; + api.ctx.fetch = async () => ({ ok: true, json: async () => ({ + contributors: rows, contributorPool: { online: 2, registered: 2, online_logins: ['amy', 'zed'] }, + }) }); + await api.ctx.fetchContributors(); + assert.equal(api.ctx.renderedContributors, rows); + assert.equal(badge.textContent, '2/2'); + assert.match(badge.children[0].innerHTML, /@amy/); + assert.match(badge.children[0].innerHTML, /@zed/); + assert.doesNotMatch(source('refresh'), /updateContributorBadge\(/, 'status polling must not overwrite roster presence'); + api.ctx.fetch = async () => ({ ok: true, json: async () => ({ + contributors: [], contributorPool: { online: 0, registered: 0, online_logins: [] }, + }) }); + await api.ctx.fetchContributors(); + assert.equal(api.ctx.renderedContributors.length, 0, 'removing the final contributor clears the roster'); + assert.equal(badge.textContent, '0/0'); + assert.match(badge.children[0].innerHTML, /No contributors online/); +}); + +test('out-of-order contributor responses cannot replace a newer roster or badge', async () => { + const api = load(), badge = api.badge(IDS[2]); + let releaseOld; + api.ctx.fetch = () => new Promise(resolve => { releaseOld = resolve; }); + const old = api.ctx.fetchContributors(); + const rows = [{ github_username: 'new', online: true }]; + api.ctx.fetch = async () => ({ ok: true, json: async () => ({ + contributors: rows, contributorPool: { online: 1, registered: 1, online_logins: ['new'] }, + }) }); + await api.ctx.fetchContributors(); + releaseOld({ ok: true, json: async () => ({ + contributors: [], contributorPool: { online: 0, registered: 0, online_logins: [] }, + }) }); + await old; + assert.equal(api.ctx.renderedContributors, rows); + assert.equal(badge.textContent, '1/1'); + assert.match(badge.children[0].innerHTML, /@new/); +}); + +test('failed contributor refresh reports unknown without replacing the last roster with zero', async () => { + const api = load(), badge = api.badge(IDS[2]); + const rows = [{ github_username: 'amy', online: true }]; + api.ctx.fetch = async () => ({ ok: true, json: async () => ({ + contributors: rows, contributorPool: { online: 1, registered: 1, online_logins: ['amy'] }, + }) }); + await api.ctx.fetchContributors(); + const warnings = []; + api.ctx.console = { warn: (...args) => warnings.push(args) }; + api.ctx.fetch = async () => ({ ok: false, status: 503 }); + await api.ctx.fetchContributors(); + assert.equal(warnings.length, 1); + assert.equal(api.ctx.renderedContributors, rows); + assert.equal(badge.textContent, '1/1'); + assert.match(badge.attrs['aria-label'], /presence unavailable/); + assert.match(badge.children[0].textContent, /presence unavailable/); +}); + test('knowledge uses numeric layer fact totals, independent of formatting and disabled priming', async () => { const api = load(), badge = api.badge(IDS[3]); await knowledge(api, stats(1000, 20)); diff --git a/src/pkg/dashboard/sidebar_pair_badge_test.go b/src/pkg/dashboard/sidebar_pair_badge_test.go index 1fd218d2c4..3f8b89b5c5 100644 --- a/src/pkg/dashboard/sidebar_pair_badge_test.go +++ b/src/pkg/dashboard/sidebar_pair_badge_test.go @@ -23,17 +23,20 @@ func TestSidebarPairBadgeWiring(t *testing.T) { `const pill = overviewSidebarPill(openIssues, openPRs, equationLabel, staleSince, unlisted);`, `setSidebarPairBadge(document.getElementById('overview-sidebar-badge'), pill.issues, pill.prs, pill.title);`, `if (data && data.actionableNow) setSidebarPairBadge(document.getElementById('governor-sidebar-badge'), issueCount, prCount, 'actionable: ' + issueCount + ' issues / ' + prCount + ' PRs')`, - // Contributors reads online/total off /api/status.contributorPool - // with the tracker's presence window in the tooltip (#15651). + // Contributors uses the roster response for both cards and counts. `Contributors`, `setSidebarPairBadge(sidebarBadge, onlineCount, totalCount);`, `tooltip.innerHTML = contributorsOnlineTooltip(pool);`, + `updateContributorBadge(data.contributorPool);`, `function contributorsOnlineTitle(online, total, window)`, ``, } { if !strings.Contains(html, want) { t.Errorf("index.html missing sidebar x/y pill wiring %q", want) } + if strings.Contains(html, "updateContributorBadge(data.contributorPool || null)") { + t.Fatal("cached /api/status must not overwrite the live contributor roster counts") + } } // The Overview pill is no longer fed by the stage tracker (that counted // only tracked items and drifted from the tile's "total open" figures). diff --git a/src/pkg/dashboard/static-src/js/contributors.js b/src/pkg/dashboard/static-src/js/contributors.js index ebb4434688..6ef77e6f6b 100644 --- a/src/pkg/dashboard/static-src/js/contributors.js +++ b/src/pkg/dashboard/static-src/js/contributors.js @@ -93,6 +93,7 @@ let _contributorFilters = new Set(); // Cache the last fetched contributor list for re-rendering on filter change let _cachedContributors = []; + let _contributorFetchID = 0; const CONTRIBUTOR_FILTER_ALL = 'all'; const CONTRIBUTOR_FILTER_ACTIVE = 'active'; @@ -154,14 +155,22 @@ } async function fetchContributors() { + const requestID = ++_contributorFetchID; try { const res = await fetch('/api/contributors'); - if (!res.ok) return; + if (!res.ok) throw new Error('HTTP ' + res.status); const data = await res.json(); - _cachedContributors = data.contributors || []; + if (requestID !== _contributorFetchID) return; + if (!Array.isArray(data.contributors)) throw new Error('Invalid contributor roster'); + _cachedContributors = data.contributors; renderContributorFilters(_cachedContributors); renderContributors(_cachedContributors); - } catch (e) { /* silently retry on next poll */ } + updateContributorBadge(data.contributorPool); + } catch (e) { + if (requestID !== _contributorFetchID) return; + console.warn('Failed to refresh contributors:', e); + updateContributorBadge(null); + } } const CONTRIB_TINT_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; @@ -507,7 +516,11 @@ const statusBadge = document.getElementById('contributors-status-badge'); if (!pool || !Number.isSafeInteger(pool.online) || pool.online < 0 || !Number.isSafeInteger(pool.registered) || pool.registered < 0) { - navCountDelta(sidebarBadge, null); + navCountDelta(sidebarBadge, null, 'Contributor presence unavailable'); + const tooltip = sidebarBadge && sidebarBadge.querySelector('.contributor-online-tooltip'); + if (tooltip) tooltip.textContent = 'Contributor presence unavailable; showing the last loaded roster'; + if (tooltip && _configTooltipTrigger === sidebarBadge) positionConfigTooltip(sidebarBadge); + if (statusBadge) statusBadge.title = 'Contributor presence unavailable; showing the last loaded roster'; return; } const onlineCount = pool.online; @@ -540,13 +553,14 @@ function contributorsOnlineTooltip(pool) { const online = Number(pool.online) || 0; const summary = esc(contributorsOnlineTitle(online, pool.registered, pool.presence_window)); - const ids = pool.online_ids; - if (!Array.isArray(ids) || ids.length !== online || ids.some(id => typeof id !== 'string' || !id)) { - return summary + '
    Online ClankeR IDs unavailable
    '; + const logins = pool.online_logins; + if (!Array.isArray(logins) || logins.length > online || (online > 0 && !logins.length) || + logins.some(login => typeof login !== 'string' || !login.trim())) { + return summary + '
    Online contributor names unavailable
    '; } - if (!ids.length) return summary + '
    No ClankeRs online
    '; - return summary + '
    Online ClankeRs
    '; + if (!logins.length) return summary + '
    No contributors online
    '; + return summary + '
    Online contributors
    '; } // contributorsOnlineTitle is the presence summary: "3 online · 12 registered diff --git a/src/pkg/dashboard/static-src/js/refresh.js b/src/pkg/dashboard/static-src/js/refresh.js index beda121ede..11193a0598 100644 --- a/src/pkg/dashboard/static-src/js/refresh.js +++ b/src/pkg/dashboard/static-src/js/refresh.js @@ -554,7 +554,6 @@ renderSwarm(data.swarm || {}); var reposBadge = document.getElementById('repos-sidebar-badge'); if (reposBadge) setSidebarCountBadge(reposBadge, (data.repos || []).length, (data.repos || []).length + ' repositories'); - updateContributorBadge(data.contributorPool || null); renderPlatform(data.platform || null); renderHiveAdvice(data.hiveAdvice || null); renderFleetReport(data.fleetReport || null); @@ -605,4 +604,3 @@ if (!_hashScrollPending) restoreScrollAnchor(scrollAnchor); } } - diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 27145bdd9e..99743be92b 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -43413,6 +43413,7 @@ let _contributorFilters = new Set(); // Cache the last fetched contributor list for re-rendering on filter change let _cachedContributors = []; + let _contributorFetchID = 0; const CONTRIBUTOR_FILTER_ALL = 'all'; const CONTRIBUTOR_FILTER_ACTIVE = 'active'; @@ -43474,14 +43475,22 @@ } async function fetchContributors() { + const requestID = ++_contributorFetchID; try { const res = await fetch('/api/contributors'); - if (!res.ok) return; + if (!res.ok) throw new Error('HTTP ' + res.status); const data = await res.json(); - _cachedContributors = data.contributors || []; + if (requestID !== _contributorFetchID) return; + if (!Array.isArray(data.contributors)) throw new Error('Invalid contributor roster'); + _cachedContributors = data.contributors; renderContributorFilters(_cachedContributors); renderContributors(_cachedContributors); - } catch (e) { /* silently retry on next poll */ } + updateContributorBadge(data.contributorPool); + } catch (e) { + if (requestID !== _contributorFetchID) return; + console.warn('Failed to refresh contributors:', e); + updateContributorBadge(null); + } } const CONTRIB_TINT_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; @@ -43827,7 +43836,11 @@ const statusBadge = document.getElementById('contributors-status-badge'); if (!pool || !Number.isSafeInteger(pool.online) || pool.online < 0 || !Number.isSafeInteger(pool.registered) || pool.registered < 0) { - navCountDelta(sidebarBadge, null); + navCountDelta(sidebarBadge, null, 'Contributor presence unavailable'); + const tooltip = sidebarBadge && sidebarBadge.querySelector('.contributor-online-tooltip'); + if (tooltip) tooltip.textContent = 'Contributor presence unavailable; showing the last loaded roster'; + if (tooltip && _configTooltipTrigger === sidebarBadge) positionConfigTooltip(sidebarBadge); + if (statusBadge) statusBadge.title = 'Contributor presence unavailable; showing the last loaded roster'; return; } const onlineCount = pool.online; @@ -43860,13 +43873,14 @@ function contributorsOnlineTooltip(pool) { const online = Number(pool.online) || 0; const summary = esc(contributorsOnlineTitle(online, pool.registered, pool.presence_window)); - const ids = pool.online_ids; - if (!Array.isArray(ids) || ids.length !== online || ids.some(id => typeof id !== 'string' || !id)) { - return summary + '
    Online ClankeR IDs unavailable
    '; + const logins = pool.online_logins; + if (!Array.isArray(logins) || logins.length > online || (online > 0 && !logins.length) || + logins.some(login => typeof login !== 'string' || !login.trim())) { + return summary + '
    Online contributor names unavailable
    '; } - if (!ids.length) return summary + '
    No ClankeRs online
    '; - return summary + '
    Online ClankeRs
    '; + if (!logins.length) return summary + '
    No contributors online
    '; + return summary + '
    Online contributors
    '; } // contributorsOnlineTitle is the presence summary: "3 online · 12 registered @@ -44448,7 +44462,6 @@ renderSwarm(data.swarm || {}); var reposBadge = document.getElementById('repos-sidebar-badge'); if (reposBadge) setSidebarCountBadge(reposBadge, (data.repos || []).length, (data.repos || []).length + ' repositories'); - updateContributorBadge(data.contributorPool || null); renderPlatform(data.platform || null); renderHiveAdvice(data.hiveAdvice || null); renderFleetReport(data.fleetReport || null); @@ -44499,7 +44512,6 @@ if (!_hashScrollPending) restoreScrollAnchor(scrollAnchor); } } - // ── Inception section ── let _inceptionState = null; let _campaigns = [];