Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Add an org-wide weekly Leaderboard (#3450)

harness-for-autonomous[bot]57e129117515
diff --git a/backend/integration/superTabLeaderboard.test.ts b/backend/integration/superTabLeaderboard.test.ts
index 53dc8e9cf..4449968b6 100644
--- a/backend/integration/superTabLeaderboard.test.ts
+++ b/backend/integration/superTabLeaderboard.test.ts
@@ -252,14 +252,35 @@ describe('the leaderboard read', () => {
expect(JSON.stringify((await get(url, outsider)).body.data)).not.toContain('Secret PM')
})
- it('reads All projects\' dormant groups too, and refuses it for a week', async () => {
+ it('reads All projects\' dormant groups for both rolling periods and weeks', async () => {
const s = await scene(state => {
const secret = state.conversations.find(c => c.title === 'Hidden')!
Object.assign(secret, { dormant: true, lastActivityAt: new Date(NOW - 2 * HOUR).toISOString() })
})
const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&period=7d&scope=all`
expect(score((await get(url, owner)).body, peer.sub).details.shipped.map((d: { title: string }) => d.title)).toContain('Hidden')
- expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&scope=all`)).status).toBe(400)
+ const weekly = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&scope=all`)
+ expect(weekly.status).toBe(200)
+ expect(score(weekly.body, peer.sub).shipped.count).toBe(2)
+ })
+
+ it('weekly org scores include only readable projects and agents, even after another audience reads', async () => {
+ const s = await scene(state => {
+ const hidden = state.conversations.find(c => c.title === 'Hidden')!
+ const fresh = state.conversations.find(c => c.title === 'Fresh')!
+ hidden.ledger!.firstAssignedAt = NOW - 2 * HOUR
+ fresh.ledger!.firstAssignedAt = NOW - 2 * HOUR
+ state.agents.push({ ...state.agents[0]!, id: 'hidden-worker', harnessId: 'hidden-worker', projectId: hidden.projectId,
+ name: 'Private worker', contributorId: peer.sub, membershipGeneration: state.people.find(p => p.id === peer.sub)!.generation })
+ })
+ const url = `/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&scope=all`
+ const own = await get(url, owner), other = await get(url, outsider)
+ expect(own.status).toBe(200)
+ expect(other.status).toBe(200)
+ expect(score(own.body, peer.sub)).toMatchObject({ accepted: 2, agentsBrought: 1, shipped: { count: 2 }, points: 8 })
+ expect(score(other.body, peer.sub)).toMatchObject({ accepted: 1, agentsBrought: 0, shipped: { count: 1 }, points: 4 })
+ expect(JSON.stringify(other.body.data)).not.toMatch(/Hidden|Secret|Private worker/)
+ expect((await get(url, outsider)).body.data).toEqual(other.body.data)
})
it('answers the same whatever the reader asks twice', async () => {
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 0cb23caf0..9e23cb028 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -96,7 +96,6 @@ const costsQuery = z.object({ days: z.coerce.number().int().min(1).max(MAX_DAYS)
const scorecardQuery = z.object({ projectId: id, scope: z.literal('all').optional() }).strict()
const leaderboardQuery = z.object({ projectId: id, week: z.coerce.number().int().nonnegative().safe().optional(), period: z.enum(PERIODS).optional(), scope: z.literal('all').optional() }).strict()
.refine(query => query.week === undefined || query.period === undefined, 'Ask for a week or a period, not both.')
- .refine(query => query.scope === undefined || query.period !== undefined, 'All projects is read by period.')
const dormantQuery = agentQuery.extend({ dormant: z.literal('1'), projectId: id.optional(), before: cursor.optional() })
const groupParams = tabParams.extend({ conversationId: id })
const hostChangesQuery = z.object({ cursor: cursor.optional(), full: z.literal('1').optional() }).strict()
diff --git a/backend/src/superTabs/leaderboard/contract.ts b/backend/src/superTabs/leaderboard/contract.ts
index 315cf6a7b..ee398cbce 100644
--- a/backend/src/superTabs/leaderboard/contract.ts
+++ b/backend/src/superTabs/leaderboard/contract.ts
@@ -34,6 +34,10 @@ export interface BroughtMachine {
export interface PersonScore {
personId: string
+ /** Weekly org board only: requests first assigned this week, credited once to their requester. */
+ accepted?: number
+ /** Weekly org board only: visible own-account agents currently contributed; never earns points. */
+ agentsBrought?: number
/** Their profile name, else their email's local part. */
displayName: string
points: number
diff --git a/backend/src/superTabs/leaderboard/read.test.ts b/backend/src/superTabs/leaderboard/read.test.ts
index 88597a00c..1fb26fbf2 100644
--- a/backend/src/superTabs/leaderboard/read.test.ts
+++ b/backend/src/superTabs/leaderboard/read.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest'
import type { Prisma } from '@prisma/client'
-import { profileNames, recentDormantGroups } from './read.js'
+import { profileNames, recentDormantGroups, weeklyBoard } from './read.js'
+import { SwarmCache } from '../cache.js'
+import { MemoryStamps } from '../cache.test-support.js'
+import type { Leaderboard } from './contract.js'
import { DIRECT } from '../cachedReads.js'
import { weekStart } from './week.js'
@@ -52,3 +55,32 @@ describe('the names the board shows', () => {
expect(await profileNames(tx, ['owner'])).toEqual(new Map())
})
})
+
+describe('the weekly aggregate cache', () => {
+ it('reuses an unchanged aggregate, separates audiences, and invalidates on change or date rollover', async () => {
+ const stamps = new MemoryStamps(), cache = new SwarmCache(stamps)
+ let loads = 0
+ const now = Date.UTC(2026, 10, 3), week = weekStart(now)
+ const load = async () => ({ projectId: `load-${++loads}`, people: [] }) as unknown as Leaderboard
+ const read = async (actor = 'owner', at = now, start = week) => weeklyBoard(await cache.at(['tab']), 'tab', actor, 'lead', start, at, load)
+ expect((await read()).projectId).toBe('load-1')
+ expect((await read()).projectId).toBe('load-1')
+ expect((await read('peer')).projectId).toBe('load-2')
+ await stamps.bump('tab', ['main'])
+ expect((await read()).projectId).toBe('load-3')
+ await stamps.bump('tab', ['machine'])
+ expect((await read()).projectId).toBe('load-4')
+ expect((await read('owner', now + 86_400_000)).projectId).toBe('load-5')
+ expect((await read('owner', now, week - 7 * 86_400_000)).projectId).toBe('load-6')
+ })
+
+ it('does not keep results or failures when the shared stamps are unavailable', async () => {
+ let loads = 0
+ const load = async () => { loads++; if (loads === 1) throw new Error('offline'); return { people: [] } as unknown as Leaderboard }
+ const read = () => weeklyBoard(DIRECT, 'tab', 'owner', 'lead', 0, 0, load)
+ await expect(read()).rejects.toThrow('offline')
+ await read()
+ await read()
+ expect(loads).toBe(3)
+ })
+})
diff --git a/backend/src/superTabs/leaderboard/read.ts b/backend/src/superTabs/leaderboard/read.ts
index 3854d7ff8..c0593881f 100644
--- a/backend/src/superTabs/leaderboard/read.ts
+++ b/backend/src/superTabs/leaderboard/read.ts
@@ -6,7 +6,15 @@ import type { CacheView } from '../cache.js'
import { boardRule } from '../cachePatch.js'
import { indexOrder, lastActive, loadBoardGroups } from './boardGroups.js'
import { LEDGER_WEEKS } from './record.js'
-import { WEEK_MS, weekStart } from './week.js'
+import { DAY_MS, WEEK_MS, weekStart } from './week.js'
+import type { Leaderboard } from './contract.js'
+
+/** The caller rechecks access before this lookup. Actor-specific and invalidated by main and machine changes;
+ * the day also rolls shipping streaks forward without a write. Bounded by the existing SwarmCache budget and age. */
+export function weeklyBoard(cached: CacheView, tabId: string, actorKey: string, projectId: string, week: number, now: number,
+ load: () => Promise<Leaderboard>): Promise<Leaderboard> {
+ return cached.get(tabId, `weekly-board:${JSON.stringify([actorKey, projectId, week, Math.floor(now / DAY_MS)])}`, 'all', load)
+}
/** The weeks a reader can ask for: this one and the ones before it whose records are still kept. */
export function readableWeek(week: number | undefined, now: number): number {
diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.ts
index 32eea32a5..5ac236882 100644
--- a/backend/src/superTabs/leaderboard/stats.ts
+++ b/backend/src/superTabs/leaderboard/stats.ts
@@ -7,7 +7,7 @@
import type { ContributedMachine } from '../machines.js'
import { isLeads, type Agent, type Conversation, type SuperTabState } from '../model.js'
import { isBuddy, isSwarmBuddy } from '../buddies.js'
-import { agentProjectId, canReadProject, projectOf } from '../projects.js'
+import { agentProjectId, canReadProject, NO_PROJECT, projectOf } from '../projects.js'
import { firstAssignedAt, waitedOn, waitsNow, type RanOn, type Unblock } from './record.js'
import { lentIn, periodSpans, reviewsIn, weekSpan, within, type PeriodName, type Span } from './rolling.js'
import { broughtMachines, contributorsIn } from './brought.js'
@@ -45,9 +45,12 @@ export interface LeaderboardInput {
allProjects?: string[]
/** People's profile names by id, read with the board (read.ts profileNames); absent ones go by their email. */
names?: ReadonlyMap<string, string>
+ /** Agents the authenticated reader may see, before presentation redaction. */
+ visibleAgents?: Agent[]
}
-export function leaderboard({ state, groups, machines: visibleMachines, projectId, week, now, period, allProjects, names }: LeaderboardInput): Leaderboard {
+export function leaderboard({ state, groups, machines: visibleMachines, projectId, week, now, period, allProjects, names, visibleAgents = state.agents }: LeaderboardInput): Leaderboard {
+ const weeklyOrg = !!allProjects && !period
const project = projectOf(state, projectId)
// The Lead conversation is where plans are approved: its answers count, though nothing there is a request that ships.
const projectIds = new Set(allProjects ?? [projectId])
@@ -63,6 +66,13 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI
const { current, previous } = period ? periodSpans(period, now) : { current: weekSpan(week), previous: weekSpan(week - WEEK_MS) }
// Each person's records, gathered once: the board scores every player three times (Diego's issue file, 2026-10-27).
const landedBy = byKey(landed, g => g.requesterId!)
+ const acceptedBy = weeklyOrg ? byKey(requests.filter(g => g.requesterId && firstAssignedAt(g.ledger ?? {}) != null), g => g.requesterId!) : new Map<string, Conversation[]>()
+ const generations = new Map(state.people.map(p => [p.id, p.generation]))
+ // An idle v3 Regular agent and a Swarm Buddy have no project; visibility is resolved by the caller.
+ const agentProjects = new Set([...projectIds, NO_PROJECT])
+ const agentsBy = weeklyOrg ? byKey(visibleAgents.filter(a => !a.teamAccount && !a.buddySession
+ && generations.get(a.contributorId) === a.membershipGeneration
+ && agentProjects.has(agentProjectId(state, a))), a => a.contributorId) : new Map<string, Agent[]>()
const answersBy = byKey(visible.flatMap(group => (group.ledger?.unblocks ?? []).map(unblock => ({ ...unblock, group }))), u => u.personId)
const machinesBy = byKey(visibleMachines, m => m.contributorId)
// Under All projects, whether a board of this reader's already shows the person; a project's board lists only its own.
@@ -76,7 +86,9 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI
const lentOf = (m: ContributedMachine) => lentIn(m, span, now, { projects: projectIds, unsplit: sharesBoard(personId) })
const machines = (machinesBy.get(personId) ?? []).map(m => ({ name: m.name, busyMs: lentOf(m) })).filter(m => m.busyMs > 0)
const freedMs = sum(answers.map(u => u.waitedMs)), lentMs = sum(machines.map(m => m.busyMs))
- const points = shippedHere.length * SHIPPED_POINTS + sum(answers.map(unblockPoints)) + Math.floor(lentMs / (LENT_HOURS_PER_POINT * HOUR_MS))
+ const accepted = (acceptedBy.get(personId) ?? []).filter(g => within(firstAssignedAt(g.ledger!)!, span)).length
+ const points = shippedHere.length * SHIPPED_POINTS + sum(answers.map(unblockPoints))
+ + (weeklyOrg ? accepted : Math.floor(lentMs / (LENT_HOURS_PER_POINT * HOUR_MS)))
const details: PersonDetails = {
shipped: newest(shippedHere, g => g.ledger!.shippedAt!)
.map(g => ({ title: g.title, prUrl: g.pullRequestUrls!.at(-1)!, mergedAt: g.ledger!.shippedAt! })),
@@ -84,10 +96,12 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI
.map(u => ({ title: u.group.title, conversationId: u.group.id, kind: u.kind ?? 'needs_human', waitedMinutes: Math.round(u.waitedMs / 60_000) })),
lent: [...machines].sort((a, b) => b.busyMs - a.busyMs).slice(0, DETAILS_LIMIT)
.map(m => ({ machineName: m.name, busyHours: Math.round(m.busyMs / HOUR_MS * 10) / 10 })),
- brought: broughtMachines(state, machinesBy.get(personId) ?? [], visibleMachines, shippedRequests, span, lentOf).slice(0, DETAILS_LIMIT),
+ // The weekly board counts agents instead of presenting machine/subscription contributions.
+ brought: weeklyOrg ? [] : broughtMachines(state, machinesBy.get(personId) ?? [], visibleMachines, shippedRequests, span, lentOf).slice(0, DETAILS_LIMIT),
}
return {
points,
+ ...weeklyOrg ? { accepted, agentsBrought: agentsBy.get(personId)?.length ?? 0 } : {},
shipped: { count: shippedHere.length, medianAskToShipMs: median(askToShip(shippedHere)) },
unblocked: { count: answers.length, agentMs: freedMs, medianAnswerMs: median(answers.map(u => u.waitedMs)) },
lent: { machines: machines.length, agentMs: lentMs },
@@ -102,9 +116,11 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI
const scored = players.map(p => ({ personId: p.id, email: p.email, displayName: names?.get(p.id)?.trim() || p.email.split('@')[0]!,
...score(p.id, current), prevWeekPoints: previous && score(p.id, previous).points,
streakDays: streak(new Set((landedBy.get(p.id) ?? []).map(g => Math.floor(g.ledger!.shippedAt! / DAY_MS))), today) }))
- .sort((a, b) => b.points - a.points || a.email.localeCompare(b.email))
+ .sort((a, b) => (weeklyOrg ? b.shipped.count - a.shipped.count : 0) || b.points - a.points || a.email.localeCompare(b.email))
const people: PersonScore[] = scored.map(({ email: _email, details, ...entry }) => {
- const rank = 1 + scored.filter(other => other.points > entry.points).length
+ const rank = 1 + scored.filter(other => weeklyOrg
+ ? other.shipped.count > entry.shipped.count || (other.shipped.count === entry.shipped.count && other.points > entry.points)
+ : other.points > entry.points).length
return { ...entry, rank, medal: entry.points > 0 ? MEDALS[rank - 1] ?? null : null, details }
})
const shippedNow = shippedRequests.filter(g => within(g.ledger!.shippedAt!, current))
diff --git a/backend/src/superTabs/leaderboard/weekly.test.ts b/backend/src/superTabs/leaderboard/weekly.test.ts
new file mode 100644
index 000000000..2eabaad92
--- /dev/null
+++ b/backend/src/superTabs/leaderboard/weekly.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest'
+import { createSuperTab, type Agent, type Conversation } from '../model.js'
+import { leaderboard } from './stats.js'
+import { DAY_MS, WEEK_MS } from './week.js'
+
+const WEEK = Date.UTC(2026, 10, 2), NOW = WEEK + 3 * DAY_MS
+function fixture() {
+ const state = createSuperTab('tab', 'Org', { id: 'owner', email: '[email protected]' }, 'prod')
+ state.people.push({ id: 'peer', email: '[email protected]', role: 'collaborator', generation: 'g' })
+ state.projects!.push({ ...state.projects![0]!, id: 'other', leadConversationId: 'other-lead' })
+ const request = (id: string, person = 'owner', projectId = 'lead', extra: Partial<Conversation> = {}): Conversation => ({
+ id, projectId, title: id, leadId: null, agentIds: [], archived: false, brief: '', checks: [], assignment: null,
+ lastMessageSequence: 0, requesterId: person, pullRequestUrls: ['https://github.com/o/r/pull/1'],
+ ledger: { firstAssignedAt: WEEK + 1, shippedAt: WEEK + 2 }, ...extra,
+ })
+ const agent = (id: string, extra: Partial<Agent> = {}): Agent => ({
+ id, projectId: 'lead', name: id, machineId: 'mac', harnessId: id, machineOwnerId: 'owner', contributorId: 'owner',
+ membershipGeneration: 'tab', configuration: { engine: 'codex', model: 'gpt-6.1-sol', effort: 'high', contextWindow: null, engineVersion: null }, ...extra,
+ })
+ const read = (groups: Conversation[], projects = ['lead', 'other']) => leaderboard({ state, groups, machines: state.machines ?? [],
+ projectId: 'lead', week: WEEK, now: NOW, allProjects: projects })
+ return { state, request, agent, read }
+}
+
+describe('org-wide weekly team play', () => {
+ it('ranks shipped work first across readable projects, then points, and shares ties', () => {
+ const { request, read } = fixture()
+ const view = read([request('one'), request('two', 'owner', 'other'), request('peer', 'peer'),
+ request('help', 'peer', 'lead', { ledger: { unblocks: Array.from({ length: 10 }, (_, i) => ({ personId: 'peer', at: WEEK + i, waitedMs: 0 })) } })])
+ expect(view.people.map(p => [p.personId, p.rank, p.points, p.shipped.count])).toEqual([
+ ['owner', 1, 8, 2], ['peer', 2, 14, 1],
+ ])
+ const tied = read([request('a'), request('b', 'peer')])
+ expect(tied.people.map(p => p.rank)).toEqual([1, 1])
+ })
+
+ it('credits one acceptance at the first assignment, not on retries or review/private/hidden work', () => {
+ const { request, read } = fixture()
+ const view = read([
+ request('accepted', 'owner', 'lead', { pullRequestUrls: [], ledger: { firstAssignedAt: WEEK } }),
+ request('old', 'owner', 'lead', { pullRequestUrls: [], ledger: { firstAssignedAt: WEEK - 1, runs: [] } }),
+ request('next', 'owner', 'lead', { pullRequestUrls: [], ledger: { firstAssignedAt: WEEK + WEEK_MS } }),
+ request('review', 'owner', 'lead', { reviewOf: 'accepted' }),
+ request('private', 'owner', 'lead', { audience: { people: [{ id: 'owner', generation: 'tab' }] } }),
+ request('hidden', 'owner', 'other'),
+ ], ['lead'])
+ expect(view.people[0]).toMatchObject({ accepted: 1, points: 1, shipped: { count: 0 }, agentsBrought: 0 })
+ })
+
+ it('counts visible own-account agents once, with no agent or lending points', () => {
+ const { state, agent, read } = fixture()
+ state.agents = [agent('regular'), agent('other', { projectId: 'other' }), agent('team', { teamAccount: true }),
+ agent('session', { buddySession: { thread: 'thread', from: 1 } }), agent('old', { membershipGeneration: 'former' })]
+ state.machines = [{ machineId: 'mac', name: 'Mac', contributorId: 'owner', membershipGeneration: 'tab', generation: 'g',
+ cwd: '/repo', scope: 'swarm', engines: ['codex'], maxAgents: 8, paused: false, lent: [{ week: WEEK, busyMs: 100 * 3_600_000 }] }]
+ const view = read([], ['lead'])
+ expect(view.people.find(p => p.personId === 'owner')).toMatchObject({ agentsBrought: 1, points: 0, rank: 1 })
+ expect(view.goal.thisWeek.points).toBe(0)
+ })
+
+ it('counts a visible agent with no project before its first task, without points', () => {
+ const { state, agent } = fixture()
+ const idle = agent('idle', { projectId: '' })
+ state.agents = [idle, agent('hidden', { projectId: 'other' })]
+ const view = leaderboard({ state, groups: [], machines: [], projectId: 'lead', week: WEEK, now: NOW,
+ allProjects: ['lead'], visibleAgents: [idle] })
+ expect(view.people.find(p => p.personId === 'owner')).toMatchObject({ agentsBrought: 1, points: 0 })
+ })
+
+ it('preserves rolling and per-project scoring for existing clients', () => {
+ const { state, request } = fixture()
+ const args = { state, groups: [request('one')], machines: [], projectId: 'lead', week: WEEK, now: NOW }
+ expect(leaderboard(args).people[0]).toMatchObject({ points: 3 })
+ expect(leaderboard({ ...args, period: '7d', allProjects: ['lead'] }).people[0]).toMatchObject({ points: 3 })
+ })
+})
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index 079e0dff3..12dfe32f1 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -29,7 +29,7 @@ import { canReadGroup, canReadProject, projectsOf, readConversation, readProject
import { isBuddyReader } from '../buddies.js'
import { workspacesRequired } from '../workspaceStore.js'
import type { Leaderboard } from '../leaderboard/contract.js'
-import { profileNames, readableWeek, recentDormantGroups } from '../leaderboard/read.js'
+import { profileNames, readableWeek, recentDormantGroups, weeklyBoard } from '../leaderboard/read.js'
import { LEDGER_WEEKS } from '../leaderboard/record.js'
import type { PeriodName } from '../leaderboard/rolling.js'
import { leaderboard } from '../leaderboard/stats.js'
@@ -509,21 +509,34 @@ export class SwarmReads {
async leaderboard(user: AuthUser, tabId: string, projectId: string, week?: number, period?: PeriodName, allProjects = false): Promise<Leaderboard> {
if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
const now = this.now(), start = readableWeek(week, now)
- return this.read(user, tabId, async (tx, cached) => {
+ const began = performance.now()
+ const result = await this.read(user, tabId, async (tx, cached) => {
const state = parts.reassemble(await readParts(tx, cached, tabId), { share: true })
const actor = await this.store.actor(tx, user, state)
readProject(state, actor, projectId)
// Every project this reader reads, by the same check as the one asked for; what they may not read is never loaded.
const readable = allProjects ? projectsOf(state).filter(p => canReadProject(state, actor, p)).map(p => p.id) : undefined
- const dormant = await recentDormantGroups(tx, cached, tabId, readable ?? projectId, now - LEDGER_WEEKS * WEEK_MS)
- const groups = [...state.conversations.filter(g => !g.dormant), ...dormant].filter(g => !isLeads(g) && canReadGroup(state, actor, g))
- // Names change rarely and show on a board: read on the secondary (task #2970).
- const names = await profileNames(this.store.replica, state.people.map(p => p.id))
- // Which machines the reader sees, with the daily rows no other read carries.
- const machines = (visibleState(state, actor, now).machines ?? [])
- .map(m => ({ ...m, lentDays: state.machines?.find(own => own.machineId === m.machineId)?.lentDays }))
- return leaderboard({ state, groups, machines, projectId, week: start, now, period, allProjects: readable, names })
+ const load = async () => {
+ const dormant = await recentDormantGroups(tx, cached, tabId, readable ?? projectId, now - LEDGER_WEEKS * WEEK_MS)
+ const groups = [...state.conversations.filter(g => !g.dormant), ...dormant].filter(g => !isLeads(g) && canReadGroup(state, actor, g))
+ // Names change rarely and show on a board: read on the secondary (task #2970).
+ const names = await profileNames(this.store.replica, state.people.map(p => p.id))
+ const visible = visibleState(state, actor, now)
+ // Count only agents this reader sees, keeping ownership before presentation redaction (Buddy rows).
+ const agentIds = new Set(visible.agents.map(a => a.id))
+ const visibleAgents = state.agents.filter(a => agentIds.has(a.id))
+ const machines = (visible.machines ?? [])
+ .map(m => ({ ...m, lentDays: state.machines?.find(own => own.machineId === m.machineId)?.lentDays }))
+ return leaderboard({ state, groups, machines, visibleAgents, projectId, week: start, now, period, allProjects: readable, names })
+ }
+ // Access is resolved afresh above, even when the aggregate is held. Include the current audience in the key.
+ return allProjects && !period
+ ? weeklyBoard(cached, tabId, JSON.stringify([actor, readable]), projectId, start, now, load)
+ : load()
})
+ const elapsedMs = performance.now() - began
+ if (allProjects && !period && elapsedMs > 100) logger.warn('[weekly-leaderboard] slow read', { elapsedMs: Math.round(elapsedMs) })
+ return result
}
/** The stored scorecard days (scorecard/rows.ts) of one project, or of every project the reader reads (`allProjects`),
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index 98f82915e..2c0f549ee 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -153,7 +153,8 @@ export const LAUNCH_ERROR_CODES = [
// The engine itself: preparing it (engines/nativeLaunch.ts) and its start (core/agents/newPane.ts).
'engine_cannot_run', 'engine_install_failed', 'engine_did_not_start', 'engine_not_installed', 'start_timeout',
'engine_launch_refused',
- // A Codex launch in a home of its own (a Swarm Product Manager's) the owner's relay cannot sign in (team/relay.ts).
+ // A Codex launch the owner's subscription relay could not sign in. The relay is gone (#4137) and nothing sends it; kept
+ // because the contract is published and only extended.
'owner_relay_unavailable',
// A Store harness (core/agents/dshThrough.ts, services/storeLaunch.ts).
'dsh_not_installed', 'dsh_unavailable', 'dsh_runtime_failed',
diff --git a/desktop/lib/super_tabs/leaderboard/model.dart b/desktop/lib/super_tabs/leaderboard/model.dart
index e879ecb77..f0b4030ae 100644
--- a/desktop/lib/super_tabs/leaderboard/model.dart
+++ b/desktop/lib/super_tabs/leaderboard/model.dart
@@ -170,6 +170,8 @@ class SuperTabPersonScore {
points = _int(json['points']),
rank = _int(json['rank']),
medal = SuperTabMedal.values.asNameMap()[json['medal']],
+ accepted = _optional(json['accepted']),
+ agentsBrought = _optional(json['agentsBrought']),
shipped = _int(_map(json['shipped'])['count']),
medianAskToShipMs = _optional(_map(json['shipped'])['medianAskToShipMs']),
unblocked = _int(_map(json['unblocked'])['count']),
@@ -190,6 +192,9 @@ class SuperTabPersonScore {
final String personId;
final int points, rank;
+
+ /// Weekly org scores; null from a backend before this board.
+ final int? accepted, agentsBrought;
final SuperTabMedal? medal;
final int shipped, unblocked, lentMachines, streakDays;
diff --git a/desktop/lib/super_tabs/leaderboard/weekly_page.dart b/desktop/lib/super_tabs/leaderboard/weekly_page.dart
new file mode 100644
index 000000000..1f4face9c
--- /dev/null
+++ b/desktop/lib/super_tabs/leaderboard/weekly_page.dart
@@ -0,0 +1,344 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_icons.dart';
+import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/widgets/app_icon_button.dart';
+import '../../widgets/desktop_chrome.dart';
+import '../controller.dart';
+import '../identity.dart';
+import 'model.dart';
+
+/// The weekly org board, refreshed by the Swarm's existing change feed.
+/// It owns no poll timer and reads only while this page is mounted.
+class SuperTabWeeklyLeaderboardPage extends StatefulWidget {
+ const SuperTabWeeklyLeaderboardPage({super.key, required this.controller});
+ final SuperTabController controller;
+
+ @override
+ State<SuperTabWeeklyLeaderboardPage> createState() => _WeeklyBoardState();
+}
+
+class _WeeklyBoardState extends State<SuperTabWeeklyLeaderboardPage> {
+ static const _rowHeight = 56.0;
+ SuperTabLeaderboard? _board;
+ String? _error;
+ Object? _stamp;
+ bool _busy = false, _again = false;
+ int _generation = 0;
+ SuperTabController get c => widget.controller;
+
+ @override
+ void initState() {
+ super.initState();
+ c.addListener(_follow);
+ _follow();
+ }
+
+ @override
+ void didUpdateWidget(SuperTabWeeklyLeaderboardPage oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.controller == c) return;
+ oldWidget.controller.removeListener(_follow);
+ c.addListener(_follow);
+ _stamp = null;
+ _follow();
+ }
+
+ void _follow() {
+ final stamp = (
+ c.lastChangedAt,
+ c.accessRevoked,
+ c.snapshot?.projects.map((p) => p.id).join(','),
+ );
+ if (stamp == _stamp) return;
+ _stamp = stamp;
+ _refresh();
+ }
+
+ void _refresh() {
+ _generation++;
+ // Clear old audience data immediately, including while a request is in flight.
+ setState(() {
+ _board = null;
+ _error = null;
+ });
+ if (_busy) {
+ _again = true;
+ return;
+ }
+ unawaited(_load());
+ }
+
+ Future<void> _load() async {
+ if (c.accessRevoked) {
+ setState(() => _error = 'This leaderboard is no longer available.');
+ return;
+ }
+ final project = c.snapshot?.projects.firstOrNull?.id;
+ if (project == null) return;
+ final generation = _generation;
+ final controller = c;
+ setState(() => _busy = true);
+ try {
+ final answer = await controller
+ .request(
+ 'GET',
+ '/api/super-tabs/${Uri.encodeComponent(controller.tabId)}/leaderboard'
+ '?projectId=${Uri.encodeQueryComponent(project)}&scope=all',
+ )
+ .timeout(const Duration(seconds: 15));
+ if (!mounted || generation != _generation) return;
+ final board = SuperTabLeaderboard.fromJson(answer);
+ if (!board.allProjects ||
+ board.period != null ||
+ board.people.any(
+ (p) => p.accepted == null || p.agentsBrought == null,
+ )) {
+ _error = 'The weekly org leaderboard needs a newer server.';
+ } else {
+ _board = board;
+ }
+ } on SuperTabFailure catch (failure) {
+ if (!mounted || generation != _generation) return;
+ _error = failure.statusCode == 403 || failure.statusCode == 404
+ ? 'This leaderboard is no longer available.'
+ : failure.message;
+ } catch (_) {
+ if (!mounted || generation != _generation) return;
+ _error = "Couldn't load the leaderboard. Try again.";
+ } finally {
+ if (mounted) {
+ setState(() => _busy = false);
+ if (_again) {
+ _again = false;
+ unawaited(_load());
+ }
+ }
+ }
+ }
+
+ @override
+ void dispose() {
+ c.removeListener(_follow);
+ _generation++;
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final board = _board;
+ return ColoredBox(
+ color: grid.AppPalette.swarmWelcome,
+ child: Padding(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'This week',
+ style: DesktopChrome.text(medium: true),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'Across the projects you can read',
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ),
+ ),
+ AppIconButton(
+ icon: AppIcons.refreshCw,
+ tooltip: 'Refresh leaderboard',
+ onPressed: _busy ? null : _refresh,
+ spinning: _busy,
+ ),
+ ],
+ ),
+ const SizedBox(height: 24),
+ if (_error case final error?)
+ Expanded(
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ error,
+ textAlign: TextAlign.center,
+ style: DesktopChrome.text(),
+ ),
+ TextButton(
+ onPressed: _refresh,
+ child: const Text('Retry'),
+ ),
+ ],
+ ),
+ ),
+ )
+ else if (_busy)
+ const Expanded(
+ child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
+ )
+ else if (board == null || board.people.isEmpty)
+ Expanded(
+ child: Center(
+ child: Text(
+ c.snapshot?.projects.isEmpty == true
+ ? 'No projects to show yet.'
+ : 'A fresh week. Pick up a task and start shipping.',
+ style: DesktopChrome.text(),
+ textAlign: TextAlign.center,
+ ),
+ ),
+ )
+ else
+ Expanded(child: _table(board)),
+ const SizedBox(height: 16),
+ Text(
+ 'Agents brought earn no points.',
+ style: DesktopChrome.metadata(color: DesktopChrome.muted),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _table(SuperTabLeaderboard board) => LayoutBuilder(
+ builder: (context, constraints) {
+ return SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: SizedBox(
+ width: math.max(860, constraints.maxWidth),
+ height: constraints.maxHeight,
+ child: Column(
+ children: [
+ _line([
+ const SizedBox(width: 40),
+ Expanded(
+ child: Text(
+ 'Teammate',
+ style: DesktopChrome.metadata(color: DesktopChrome.muted),
+ ),
+ ),
+ for (final title in [
+ 'Shipped',
+ 'Accepted',
+ 'Unblocked',
+ 'Streak',
+ 'Agents',
+ 'Points',
+ ])
+ _cell(title, heading: true),
+ ], heading: true),
+ Expanded(
+ child: ListView.builder(
+ itemExtent: _rowHeight,
+ itemCount: board.people.length,
+ itemBuilder: (context, index) {
+ final score = board.people[index];
+ final person = c.snapshot?.people
+ .where((p) => p.id == score.personId)
+ .firstOrNull;
+ return _line([
+ SizedBox(
+ width: 40,
+ child: score.rank == 1 && score.points > 0
+ ? Icon(
+ AppIcons.trophy,
+ size: 18,
+ color: grid.AppPalette.swarmAccent,
+ )
+ : Text(
+ '${score.rank}',
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ Expanded(
+ child: Row(
+ children: [
+ if (person != null)
+ SuperTabAvatar.person(person, size: 28),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ score.displayName ??
+ person?.shownName ??
+ 'Teammate',
+ key: ValueKey(
+ 'weekly-person-${score.personId}',
+ ),
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(
+ medium: score.rank == 1 && score.points > 0,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ _cell('${score.shipped}', strong: true),
+ _cell('${score.accepted}'),
+ _cell('${score.unblocked}'),
+ _cell('${score.streakDays}d'),
+ _cell(
+ '${score.agentsBrought}',
+ key: ValueKey('weekly-agents-${score.personId}'),
+ ),
+ _cell('${score.points}', strong: true),
+ ]);
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+
+ Widget _cell(
+ String text, {
+ bool heading = false,
+ bool strong = false,
+ Key? key,
+ }) => SizedBox(
+ width: 84,
+ child: Text(
+ text,
+ key: key,
+ textAlign: TextAlign.right,
+ style: heading
+ ? DesktopChrome.metadata(color: DesktopChrome.muted)
+ : grid.AppType.label(
+ color: grid.AppPalette.textPrimary,
+ fontWeight: strong ? grid.AppFont.semibold : grid.AppFont.regular,
+ fontFeatures: grid.AppFont.tabularFigures,
+ ),
+ ),
+ );
+
+ Widget _line(List<Widget> children, {bool heading = false}) => Container(
+ height: heading ? 36 : _rowHeight,
+ padding: const EdgeInsets.symmetric(
+ horizontal: DesktopChrome.panelPadding / 2,
+ ),
+ decoration: BoxDecoration(
+ border: Border(bottom: BorderSide(color: grid.AppPalette.divider)),
+ ),
+ child: Row(children: children),
+ );
+}
diff --git a/desktop/lib/super_tabs/places.dart b/desktop/lib/super_tabs/places.dart
index 9b61d9de6..2d0a0d7a0 100644
--- a/desktop/lib/super_tabs/places.dart
+++ b/desktop/lib/super_tabs/places.dart
@@ -2,10 +2,9 @@ import 'package:flutter/foundation.dart';
import 'controller.dart';
-/// The Swarm's three pages in the sidebar, each one thing (anh Dee, 11-05,
-/// task #2996): what waits on the reader's answer, the tags of them, and the
-/// threads they follow.
-enum SwarmPage { decisions, mentions, threads }
+/// The Swarm's sidebar pages: answers, the weekly Desktop leaderboard,
+/// tags and followed threads.
+enum SwarmPage { decisions, leaderboard, mentions, threads }
/// A place the reader was in a Swarm: one of its pages, or a chat with the
/// thread open beside it ([root]) or none.
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index 6d36b04fe..2f31aa110 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -818,6 +818,15 @@ class ProjectSidebar extends StatelessWidget {
icon: AppIcons.flag,
waiting: decisions,
),
+ if (board)
+ _pageRow(
+ onPage,
+ target: SwarmPage.leaderboard,
+ key: 'super-leaderboard',
+ label: 'Leaderboard',
+ icon: AppIcons.trophy,
+ waiting: 0,
+ ),
// Mentions goes from the Desktop's left pane (Swarm v3, anh Dee 11-07).
if (!board)
_pageRow(
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 20a0e153b..107d4d659 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -29,6 +29,7 @@ import '../shortcuts/keymap.dart' show KeymapContext;
import 'chat_find.dart';
import 'chat_scroll.dart';
import 'leaderboard/reader.dart';
+import 'leaderboard/weekly_page.dart';
import 'jump_to_latest.dart';
import 'unread_line.dart';
import 'roster.dart';
@@ -3046,6 +3047,7 @@ class _SuperTabViewState extends State<SuperTabView>
: _pageShown != null
? switch (_pageShown!) {
SwarmPage.decisions => 'Decisions',
+ SwarmPage.leaderboard => 'Leaderboard',
SwarmPage.mentions => 'Mentions',
SwarmPage.threads => 'Threads',
}
@@ -6371,6 +6373,10 @@ class _SuperTabViewState extends State<SuperTabView>
)
: const SizedBox.shrink(),
switch (_pageShown) {
+ SwarmPage.leaderboard =>
+ SuperTabWeeklyLeaderboardPage(
+ controller: c,
+ ),
SwarmPage.decisions => SuperTabDecisionsPage(
activity: SuperTabActivity.of(c),
highlight: _highlight,
diff --git a/desktop/test/super_tab_pages_test.dart b/desktop/test/super_tab_pages_test.dart
index 0c606ed89..9be0875e9 100644
--- a/desktop/test/super_tab_pages_test.dart
+++ b/desktop/test/super_tab_pages_test.dart
@@ -72,6 +72,9 @@ Future<Opened> show(
now: () => _now,
),
SwarmPage.threads => throw UnimplementedError('threads page test'),
+ SwarmPage.leaderboard => throw UnimplementedError(
+ 'leaderboard has its own tests',
+ ),
},
),
),
diff --git a/desktop/test/super_tab_places_view_test.dart b/desktop/test/super_tab_places_view_test.dart
index 6ee039a9b..5ddd04a7a 100644
--- a/desktop/test/super_tab_places_view_test.dart
+++ b/desktop/test/super_tab_places_view_test.dart
@@ -28,6 +28,7 @@ void main() {
Future<(SuperTabController, ConversationServer)> show(
WidgetTester tester, {
void Function(ConversationServer server)? prepare,
+ bool board = false,
}) async {
await tester.binding.setSurfaceSize(const Size(1300, 800));
addTearDown(() => tester.binding.setSurfaceSize(null));
@@ -45,6 +46,7 @@ void main() {
theme: grid.buildAppTheme(brightness: Brightness.light),
home: Scaffold(
body: SuperTabView(
+ board: board,
controller: c,
onInvite: () {},
onAddAgent: (_) {},
@@ -73,6 +75,7 @@ void main() {
testWidgets('each row opens its page, named in the header', (tester) async {
final (c, _) = await show(tester);
+ expect(key('super-leaderboard'), findsNothing);
for (final (row, title, list) in [
('super-decisions', 'Decisions', 'super-decisions-list'),
('super-mentions', 'Mentions', 'super-mentions-list'),
@@ -86,6 +89,59 @@ void main() {
await end(tester, c);
});
+ testWidgets(
+ 'Leaderboard below Decisions opens this week and participates in Back and Forward',
+ (tester) async {
+ final (c, server) = await show(
+ tester,
+ board: true,
+ prepare: (server) {
+ server.leaderboard = {
+ 'projectId': 'lead',
+ 'allProjects': true,
+ 'week': 1793577600000,
+ 'people': [
+ {
+ 'personId': 'owner',
+ 'displayName': 'Owner',
+ 'rank': 1,
+ 'points': 4,
+ 'shipped': {'count': 1},
+ 'accepted': 1,
+ 'unblocked': {'count': 0},
+ 'agentsBrought': 2,
+ 'streakDays': 1,
+ },
+ ],
+ };
+ },
+ );
+ expect(key('super-leaderboard'), findsOneWidget);
+ expect(
+ tester.getTopLeft(key('super-leaderboard')).dy,
+ greaterThanOrEqualTo(tester.getBottomLeft(key('super-decisions')).dy),
+ );
+ await tap(tester, 'super-decisions');
+ await tap(tester, 'super-leaderboard');
+ expect(find.text('This week'), findsOneWidget);
+ expect(key('weekly-person-owner'), findsOneWidget);
+ expect(
+ server.leaderboardReads.any((path) {
+ final query = Uri.parse(path).queryParameters;
+ return query['scope'] == 'all' && !query.containsKey('period');
+ }),
+ isTrue,
+ );
+ SuperTabPlaces.of(c).step(-1);
+ await _settle(tester);
+ expect(key('super-decisions-list'), findsOneWidget);
+ SuperTabPlaces.of(c).step(1);
+ await _settle(tester);
+ expect(find.text('This week'), findsOneWidget);
+ await end(tester, c);
+ },
+ );
+
// Tuan, task #3751: on the Threads page a card's #-link to a task changed the chat behind the page, so
// nothing on screen moved and the link read as dead.
testWidgets('a #-link in a Threads card opens its task, as in the chat', (
diff --git a/desktop/test/super_tab_weekly_leaderboard_test.dart b/desktop/test/super_tab_weekly_leaderboard_test.dart
new file mode 100644
index 000000000..59451ae73
--- /dev/null
+++ b/desktop/test/super_tab_weekly_leaderboard_test.dart
@@ -0,0 +1,281 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/leaderboard/weekly_page.dart';
+import 'package:harness/super_tabs/view.dart';
+import 'package:harness/super_tabs/tasks/personal_tasks_pane.dart';
+
+import 'support/capture.dart';
+import 'support/humans_fixture.dart';
+import 'support/super_tab_fixture.dart';
+
+final shots = Platform.environment['SUPER_TAB_WEEKLY_LEADERBOARD_SHOTS'];
+
+ConversationServer weeklySwarm() {
+ final server = humansSwarm();
+ server.leaderboard!['allProjects'] = true;
+ server.leaderboard!['people'] = [
+ for (final (id, rank, shipped, accepted, unblocked, points, agents, streak)
+ in [
+ ('peer', 1, 6, 8, 3, 29, 3, 6),
+ ('tony', 2, 2, 4, 0, 10, 1, 2),
+ ('owner', 3, 1, 8, 4, 15, 1, 1),
+ ('scholes', 4, 0, 2, 2, 4, 1, 0),
+ ('diego', 5, 0, 1, 1, 2, 1, 0),
+ ('huy', 6, 0, 0, 0, 0, 1, 0),
+ ('maximilian.alexander.longname', 6, 0, 0, 0, 0, 0, 0),
+ ])
+ {
+ 'personId': id,
+ 'displayName':
+ {'peer': 'Dee', 'owner': 'Ken', 'tony': 'Tony'}[id] ?? id,
+ 'rank': rank,
+ 'points': points,
+ 'shipped': {'count': shipped},
+ 'accepted': accepted,
+ 'unblocked': {'count': unblocked},
+ 'agentsBrought': agents,
+ 'streakDays': streak,
+ },
+ ];
+ return server;
+}
+
+Future<SuperTabController> showBoard(
+ WidgetTester tester,
+ ConversationServer server, {
+ Brightness brightness = Brightness.light,
+ Size size = const Size(1120, 760),
+}) async {
+ await tester.binding.setSurfaceSize(size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);
+ final c = server.controller(
+ account: 'peer',
+ initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},
+ );
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(body: SuperTabWeeklyLeaderboardPage(controller: c)),
+ ),
+ );
+ await tester.pump();
+ return c;
+}
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+
+ for (final brightness in [Brightness.light, Brightness.dark]) {
+ testWidgets(
+ 'weekly org board shows team play without lending in ${brightness.name}',
+ (tester) async {
+ final server = weeklySwarm();
+ await showBoard(tester, server, brightness: brightness);
+ await tester.pumpAndSettle();
+ final uri = Uri.parse(server.leaderboardReads.single);
+ expect(uri.queryParameters, {'projectId': 'lead', 'scope': 'all'});
+ for (final name in [
+ 'This week',
+ 'Shipped',
+ 'Accepted',
+ 'Unblocked',
+ 'Streak',
+ 'Agents',
+ 'Points',
+ ]) {
+ expect(find.text(name), findsOneWidget);
+ }
+ expect(find.text('Lent'), findsNothing);
+ expect(find.text('Brought'), findsNothing);
+ expect(
+ find.byKey(const ValueKey('weekly-agents-peer')),
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<Text>(find.byKey(const ValueKey('weekly-agents-peer')))
+ .data,
+ '3',
+ );
+ expect(
+ tester
+ .getTopLeft(find.byKey(const ValueKey('weekly-person-peer')))
+ .dy,
+ lessThan(
+ tester
+ .getTopLeft(find.byKey(const ValueKey('weekly-person-owner')))
+ .dy,
+ ),
+ );
+ expect(find.text('Agents brought earn no points.'), findsOneWidget);
+ await captureWindow(tester, shots, 'weekly-${brightness.name}');
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets('Desktop opens the weekly board in ${brightness.name}', (
+ tester,
+ ) async {
+ final server = weeklySwarm();
+ final c = await showBoard(
+ tester,
+ server,
+ brightness: brightness,
+ size: const Size(1500, 900),
+ );
+ c.personalTasks!.apply({
+ 'approvalMode': 'autoApprove',
+ 'reset': true,
+ 'upserts': [
+ {
+ 'id': 'ready-to-ship',
+ 'version': 1,
+ 'at': 1,
+ 'projectId': 'lead',
+ 'projectName': 'Pilot',
+ 'title': 'Ship the weekly board',
+ 'status': 'working',
+ 'suggested': false,
+ 'canApprove': false,
+ 'agent': <String, dynamic>{},
+ },
+ ],
+ 'removed': <String>[],
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: SuperTabView(
+ board: true,
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byType(SuperTabPersonalTasksPane), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('personal-task-ready-to-ship')),
+ findsOneWidget,
+ );
+ await captureWindow(
+ tester,
+ shots,
+ 'weekly-board-tasks-${brightness.name}',
+ );
+ await tester.tap(find.byKey(const ValueKey('super-leaderboard')));
+ await tester.pumpAndSettle();
+ expect(find.text('This week'), findsOneWidget);
+ expect(find.byKey(const ValueKey('weekly-person-peer')), findsOneWidget);
+ expect(
+ tester.getTopLeft(find.byKey(const ValueKey('weekly-person-tony'))).dy,
+ lessThan(
+ tester
+ .getTopLeft(find.byKey(const ValueKey('weekly-person-owner')))
+ .dy,
+ ),
+ );
+ await captureWindow(tester, shots, 'weekly-desktop-${brightness.name}');
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ testWidgets('failed reads clear the board and Retry recovers', (
+ tester,
+ ) async {
+ final server = weeklySwarm()..failLeaderboardReads = 1;
+ await showBoard(tester, server);
+ await tester.pumpAndSettle();
+ expect(find.text('No connection.'), findsOneWidget);
+ await tester.tap(find.text('Retry'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('weekly-person-peer')), findsOneWidget);
+ server.leaderboardAnswer = (_) => throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'Unavailable',
+ statusCode: 403,
+ );
+ await tester.tap(find.byTooltip('Refresh leaderboard'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('weekly-person-peer')), findsNothing);
+ expect(
+ find.text('This leaderboard is no longer available.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets(
+ 'an older backend is identified without showing misleading scores',
+ (tester) async {
+ await showBoard(tester, humansSwarm());
+ await tester.pumpAndSettle();
+ expect(
+ find.text('The weekly org leaderboard needs a newer server.'),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('weekly-person-peer')), findsNothing);
+ },
+ );
+
+ testWidgets('an org with no readable projects makes no leaderboard request', (
+ tester,
+ ) async {
+ final server = weeklySwarm();
+ server.state['projects'] = <dynamic>[];
+ final c = await showBoard(tester, server);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(c.snapshot!.projects, isEmpty);
+ expect(server.leaderboardReads, isEmpty);
+ expect(find.text('No projects to show yet.'), findsOneWidget);
+ });
+
+ testWidgets(
+ 'changes during a read coalesce and stale responses never appear',
+ (tester) async {
+ final server = weeklySwarm();
+ final gate = Completer<void>();
+ server.leaderboardGate = gate.future;
+ final c = await showBoard(tester, server);
+ expect(server.leaderboardReads, hasLength(1));
+ for (var i = 0; i < 3; i++) {
+ server.state['name'] = 'Changed $i';
+ await c.refresh();
+ }
+ await tester.pump();
+ expect(server.leaderboardReads, hasLength(1));
+ gate.complete();
+ await tester.pumpAndSettle();
+ expect(server.leaderboardReads, hasLength(2));
+ expect(find.byKey(const ValueKey('weekly-person-peer')), findsOneWidget);
+ },
+ );
+
+ testWidgets('empty week and narrow pane remain usable', (tester) async {
+ final server = weeklySwarm();
+ server.leaderboard!['people'] = <dynamic>[];
+ await showBoard(tester, server, size: const Size(420, 600));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('A fresh week. Pick up a task and start shipping.'),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/docs/plans/2026-11-07-org-weekly-leaderboard-plan.md b/docs/plans/2026-11-07-org-weekly-leaderboard-plan.md
new file mode 100644
index 000000000..ce29f9f2c
--- /dev/null
+++ b/docs/plans/2026-11-07-org-weekly-leaderboard-plan.md
@@ -0,0 +1,92 @@
+# Org-wide weekly Leaderboard implementation plan
+
+**Working method:** Engineer implements each task test first, then independent whole-PR review and testing.
+
+**Goal:** Open this week's org-wide leaderboard directly below Decisions, celebrating shipped work and helpful teammates.
+
+**Architecture:** Reuse the existing authenticated leaderboard endpoint with `scope=all` and no rolling period. Its server-filtered project set supplies one weekly aggregate. Extend its rows with accepted tasks and agents brought, and show a dedicated page using the existing identity and theme components. Preserve rolling/per-project contracts for clients from the last 30 days.
+
+**Tech Stack:** TypeScript, existing Swarm parts cache, Flutter; no dependencies or database schema changes.
+
+**Spec:** Harness task #4122, conversation df920dc0232ebbcf644ad9f7. Integrate navigation on #4118's layout, merge after #4118.
+
+## Global Constraints
+
+- No change to who can read a project; server filters projects, groups and agents before aggregation.
+- Weekly org rank: shipped count descending, then points; equal shipped and points share rank. Points: existing 3 per ship and 1–3 per unblock, plus 1 per accepted task. Accepted means a request's first assignment this week, credited to its requester, consistent with shipped credit. Retries and review steps earn no acceptance credit.
+- Visible agents without a project count before their first task too (v3 Regular agents from #4116); the server remains the visibility gate.
+- Agents brought is the current count of visible, own-account agents contributed by each person, excluding Buddy sessions and Team accounts; it earns no points. No lent column on the weekly page.
+- Light and dark; Desktop tests use memory fixtures and fake sign-in. No release or production writes.
+
+## Review Focus
+
+- Hidden project activity or agent counts must never leak through a cached aggregate.
+- Agents brought and machine lending must never change weekly org points or rank.
+- Week boundaries, retries, review steps and private chats must not inflate accepted/shipped counts.
+- A failed read, revoked access or changing org must not show another audience's stale board.
+- The sidebar slot and browser-style back navigation must work with #4118's v3 layout.
+
+## Design
+
+1. Growth: no stored rows added; reuse the five-week ledger and bounded SwarmCache (byte, age and entry limits). Weekly aggregate entries expire/evict; week/day keys keep streaks current.
+2. Concurrency: reads only; existing command locks and cache stamps invalidate after mutations. Audience is checked before every cache lookup; cache key includes actor, anchor project and week. No new lock.
+3. Read cost: reuse existing indexed, projected dormant-group read and patched parts. Cache the weekly result so an unchanged stamp does not reread profiles or recompute scores. No new database query. Page refreshes on controller changes, coalescing in-flight requests; no new timer.
+4. Scale: existing limits bound projects, people, agents and the retained ledger. Measure the same 10x synthetic workload before/after; cache-hit reads should avoid aggregation. A content-free warning names slow weekly reads above 100 ms; no IDs or paths in it.
+5. Compatibility: backend first. Extend PersonScore with optional `accepted` and `agentsBrought`; Desktop understands their absence and shows an unavailable state for the weekly page until supported. Existing Desktop/mobile rolling and per-project consumers retain existing scoring and payload fields, including legacy lent fields for old clients.
+6. Migration/rollback: none; no persisted changes. Roll back Desktop or backend independently; the weekly page detects missing fields instead of mislabeling old scores. Existing clients ignore additive fields.
+7. Audience: existing readProject/canReadProject/canReadGroup checks and visibleState agents; cache is actor-specific and invalidated on membership/project changes. API is the only new presentation path; no messages, private titles, telemetry content, notifications or shares added.
+8. Identity: authenticated person's request, never the machine owner's identity; existing Team-session refusal remains.
+9. Failure: page shows loading, empty, unsupported or error with Retry; revoked access clears results. Existing cache bypass when stamps unavailable remains correct. No writes or retry loops.
+10. Platforms: backend Linux; shared Desktop macOS/Linux/Windows code. No process starts, new native calls, phone or web changes. Validate affected unit tests on macOS and rely on required Linux CI for full component suites.
+
+## Mockup
+
+```text
+Decisions Leaderboard This week · all readable projects
+Leaderboard Rank Teammate Shipped Accepted Unblocked Streak Agents Points
+My agents 1 Dee 9 11 4 5d 3 42
+Projects 2 Ken 6 8 3 3d 2 29
+ Agents brought are a count, with no points.
+```
+
+### Task 1: Weekly org scoring
+
+**Files:** `backend/src/superTabs/leaderboard/{stats.ts,contract.ts,weekly.test.ts}`.
+**Interfaces:** existing `leaderboard(LeaderboardInput): Leaderboard`; weekly all-project rows add `accepted: number` and `agentsBrought: number`; optional `visibleAgents: Agent[]` input supplies server-filtered agents.
+
+- [x] Commit failing tests for cross-project ships/rank, accepted first assignments, excluded review/private/hidden projects, zero agent/lending points and week boundaries.
+- [x] Run `npm test -- src/superTabs/leaderboard/weekly.test.ts`; record red.
+- [x] Implement weekly-only scoring, count agents once per person, preserve legacy scoring and fields.
+- [x] Run the new tests and existing stats/rolling/brought tests; commit green and push.
+
+### Task 2: Cached authenticated weekly read
+
+**Files:** `backend/src/superTabs/read/service.ts`, `backend/src/superTabs/leaderboard/{read.ts,read.test.ts}`, `backend/src/routes/superTabs.ts`, `backend/integration/superTabLeaderboard.test.ts`.
+**Interfaces:** cache helper `weeklyBoard(cached, tabId, actorKey, projectId, week, now, load): Promise<Leaderboard>`; existing endpoint remains unchanged.
+
+- [x] Commit tests proving unchanged-stamp reuse, actor separation, mutation invalidation and day/week rollover.
+- [x] Run affected test, observe red; use the existing CacheView rather than a new cache.
+- [x] Cache weekly aggregation after authorization, supply visible agents, emit a content-free slow-read warning.
+- [x] Run affected read/cache tests and typecheck; commit green and push.
+- [x] Extend route validation to allow `scope=all` without a rolling period. First watch the integration tests fail with 400, then verify weekly project/agent audience isolation through the real API.
+
+### Task 3: Weekly board page
+
+**Files:** `desktop/lib/super_tabs/leaderboard/{model.dart,weekly_page.dart}`, `desktop/test/super_tab_weekly_leaderboard_test.dart`.
+**Interfaces:** `SuperTabWeeklyLeaderboardPage(controller: SuperTabController)`; request existing endpoint with `scope=all`, without period; derive anchor from readable snapshot projects. Add optional accepted/agentsBrought parsed fields.
+
+- [x] Commit widget tests for all weekly columns/order, loading/empty/error/unsupported/revocation, coalesced change refresh and light/dark screenshots.
+- [x] Run the new widget file, observe red.
+- [x] Implement page with existing theme/identity, horizontal scroll at narrow widths, bounded lazy rows and request timeout.
+- [x] Run affected widget/model tests, analyze and capture light/dark screenshots; commit green and push.
+
+### Task 4: v3 navigation and handoff
+
+**Files:** #4118's `desktop/lib/super_tabs/{places.dart,project_sidebar.dart,view.dart}` and affected sidebar/view tests.
+**Interfaces:** `SwarmPage.leaderboard` opens Task 3's page, with title and Back/Forward support.
+
+- [x] Coordinate the shared slot; commit a test that tapping the row immediately below Decisions opens this week's board.
+- [x] Observe red, then add the slot and page wiring; verify dark/light, navigation and existing affected tests.
+- [x] Record before/after same-workload numbers, red/green evidence, platforms and design in the PR.
+- [ ] Independent review/test and ci/required at the stable head.
+- [ ] Integrate the final merged #4118 layout, validate the combined navigation, and merge only after #4118.