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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Batch B: push storm fix, leaderboard scoring, short-turn hold, dial follows Swarm tab (#1911)
0xken15a0efe60a3e22
diff --git a/backend/integration/superTabLeaderboard.test.ts b/backend/integration/superTabLeaderboard.test.tsindex 0f5583b47..e5a775470 100644--- a/backend/integration/superTabLeaderboard.test.ts+++ b/backend/integration/superTabLeaderboard.test.ts@@ -3,7 +3,7 @@ import { execFile } from 'node:child_process'import { promisify } from 'node:util'import { join } from 'node:path'import { tmpdir } from 'node:os'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { afterAll, beforeAll, describe, expect, it, onTestFinished } from 'vitest'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'import Fastify, { type FastifyInstance } from 'fastify'@@ -136,6 +136,24 @@ describe('the leaderboard read', () => {expect((await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&week=${WEEK + WEEK_MS}`)).status).toBe(400)})+ it('names people by their profile name, else their email, and scores last week for the arrow', async () => {+ const s = await scene()+ await db.user.update({ where: { id: peer.sub }, data: { name: 'Peer Person' } })+ onTestFinished(() => db.user.update({ where: { id: peer.sub }, data: { name: null } }).then(() => undefined))+ const { body } = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead`)+ expect(score(body, peer.sub)).toMatchObject({ displayName: 'Peer Person', points: 3, prevWeekPoints: 3 })+ expect(score(body, owner.sub).displayName).toBe('owner')+ })++ it('details what each person shipped, a dormant group\'s too, and never a private chat\'s title', async () => {+ const s = await scene()+ const now = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead`, peer)+ expect(score(now.body, peer.sub).details).toEqual({ shipped: [{ title: 'Fresh', prUrl: PR, mergedAt: NOW - HOUR }], unblocked: [], lent: [] })+ expect(JSON.stringify(now.body.data)).not.toMatch(/Peer and PM|Hidden/)+ const last = await get(`/api/super-tabs/${s.tabId}/leaderboard?projectId=lead&week=${WEEK - WEEK_MS}`, peer)+ expect(score(last.body, peer.sub).details.shipped).toEqual([{ title: 'Old', prUrl: PR, mergedAt: WEEK - 2 * 86_400_000 }])+ })+it('leaves the ledger out of the groups every reader loads', async () => {const s = await scene()const { body } = await get(`/api/super-tabs/${s.tabId}/parts`, peer)diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex c5bc2c8e7..b3b76028c 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -354,7 +354,8 @@ describe('host form (design 4.10)', () => {/** The owner's machine `host` contributed to the Swarm, a third agent whose only group is dormant, a queued start. */let machine = 'host'/** Each test has its own machine, so other tests' Swarms never show up in its host reads. */- const hostScene = async () => {+ /** [webRequester]: who asked for the Web work this machine's worker runs; the owner contributes the machine. */+ const hostScene = async (webRequester = owner.sub) => {machine = `m-${randomUUID().slice(0, 8)}`await db.machine.create({ data: { machineId: machine, userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })return scene((s, ids) => {@@ -368,6 +369,7 @@ describe('host form (design 4.10)', () => {s.run({ type: 'conversation.archive', conversationId: archived, archived: true })s.edit(state => {const pool = state.machines!.find(m => m.machineId === machine)!+ state.conversations.find(c => c.id === ids.web)!.requesterId = webRequester// One in a running group, one in a dormant group none of its agents is in: the host still has to settle it.state.starts = [[ids.web, 'queued'], [archived, 'queued-in-dormant']].map(([conversationId, id]) => ({ id: id!, creationId: 'c',actorKey: `person:${owner.sub}`, contributorId: owner.sub, membershipGeneration: pool.membershipGeneration,@@ -544,12 +546,13 @@ describe('host form (design 4.10)', () => {})it('sleeps through the Lent hours a reading credits to the machine\'s running workers', async () => {- const s = await hostScene()+ // Lent counts only work for someone else (leaderboard/lent.ts).+ const s = await hostScene(peer.sub)await reading(s.tabId, (await fullRead(s.tabId)).generation)const { cursor, generation } = await fullRead(s.tabId)await reading(s.tabId, generation)const lent = await db.$transaction(async tx => (await parts.loadActive(tx, s.tabId)).machines.find(m => m.key === machine)!.data!.contribution?.lent)- expect(lent?.[0]?.agentMs).toBeGreaterThan(0)+ expect(lent?.[0]?.busyMs).toBeGreaterThan(0)clock = Date.now()expect((await host(cursor)).body.data).toMatchObject({ tabs: [], removedTabIds: [] })})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 0da3aed59..85543f623 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -2817,6 +2817,40 @@ describe('Lead mentions', () => {})})+describe('leaderboard credits written by the store (leaderboard/record.ts)', () => {+ const unblocks = async (tab: string, group: string) => (await storedState(tab)).conversations.find(c => c.id === group)!.ledger?.unblocks ?? []++ it('credits a reply to a Lead\'s tag once, as a tag reply', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const group = (await run(tab, { type: 'conversation.create', title: 'Copy review', brief: '', checks: [] })).result.conversationId as string+ await run(tab, { type: 'conversation.agent', conversationId: group, agentId: lead, present: true, lead: true })+ const tag = (await run(tab, { type: 'message.send', conversationId: group, text: 'Confirm the copy?', replyTo: null, recipientIds: [], mentions: [peer.sub] },+ host, lead)).result.messageId as string+ await run(tab, { type: 'message.send', conversationId: group, text: 'Confirmed.', replyTo: null, recipientIds: [] }, peer)+ await run(tab, { type: 'message.send', conversationId: group, text: 'One more thing.', replyTo: null, recipientIds: [] }, peer)+ expect(await unblocks(tab, group)).toEqual([{ personId: peer.sub, at: expect.any(Number), waitedMs: expect.any(Number), kind: 'tag_reply', item: tag }])+ })++ it('credits "Duyệt" in reply to the Lead\'s ask as an approval, in the Lead conversation', async () => {+ const { tab, lead } = await fixture()+ const ask = (await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Plan: three steps. GO?', replyTo: null, recipientIds: [] }, host, lead))+ .result.messageId as string+ await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Duyệt nhé', replyTo: ask, recipientIds: [] })+ expect(await unblocks(tab, 'lead')).toEqual([expect.objectContaining({ personId: owner.sub, kind: 'approval', item: ask })])+ })++ it('credits the person asked for their decision answer', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const asked = await run(tab, { type: 'decision.ask', conversationId: 'lead', personId: peer.sub,+ questions: [{ question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' }] }, host, lead)+ const decisionId = (asked.result.decisionIds as string[])[0]!+ await run(tab, { type: 'decision.answer', decisionId, choice: 1 }, peer)+ expect(await unblocks(tab, 'lead')).toEqual([expect.objectContaining({ personId: peer.sub, kind: 'decision', item: decisionId })])+ })+})+describe('credentials in Swarm chat', () => {// Assembled at run time from obviously fake parts, never a credential-shaped literal.const jwt = [{ alg: 'HS256', typ: 'JWT' }, { sub: 'fixture-user' }].map(part => Buffer.from(JSON.stringify(part)).toString('base64url'))diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.tsindex 3c0d709ba..3fb71cf3a 100644--- a/backend/src/lib/bus.ts+++ b/backend/src/lib/bus.ts@@ -667,7 +667,8 @@ export function subscribeDeviceStatus(userId: string, cb: (msg: DeviceStatusMsg)// create/delete/rename happens on normal REST workers, while device/web sockets may live on another// worker, so Redis fans out "re-query the DB now".export interface DeviceMachineListChangedMsg {- reason: 'created' | 'deleted' | 'renamed' | 'updated' | 'environment_changed'+ /** `harness_shares`: a harness shared with the account was invited or taken back (routes/harnessShares.ts). */+ reason: 'created' | 'deleted' | 'renamed' | 'updated' | 'harness_shares' | 'environment_changed'autonomousEnv?: 'prod' | 'stag'}diff --git a/backend/src/routes/harnessShares.test.ts b/backend/src/routes/harnessShares.test.tsindex cc3045577..65daf1d4a 100644--- a/backend/src/routes/harnessShares.test.ts+++ b/backend/src/routes/harnessShares.test.ts@@ -14,6 +14,7 @@ vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof imporimport { harnessShareRoutes, recipientShare } from './harnessShares.js'import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'import { errorHandler } from '../middlewares/errorHandler.js'+import { logger } from '../utils/logger.js'const owner = { sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }const ken = { sub: 'ken', email: ' [email protected] ', role: 'user', autonomousEnv: 'prod' as const }@@ -36,7 +37,7 @@ describe('account-bound harness invitations', () => {app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, mocks.auth)await app.register(harnessShareRoutes); await app.ready()})- afterEach(async () => { await app.close() })+ afterEach(async () => { await app.close(); vi.restoreAllMocks() })const auth = { authorization: 'Bearer fixture' }function put(payload: unknown = input(), id: string = randomUUID()) {return app.inject({ method: 'PUT', url: `/api/harness-shares/${id}`, headers: auth, payload: payload as any })@@ -102,6 +103,12 @@ describe('account-bound harness invitations', () => {const earlier = await put()expect(earlier.statusCode).toBe(409)expect(earlier.json().error).not.toHaveProperty('id')+ // Any other failure to save is not a conflict: it stays a 500, and nobody is told of an invitation not saved.+ mocks.prisma.harnessShare.upsert.mockRejectedValue(new Prisma.PrismaClientKnownRequestError('Transaction conflict', { code: 'P2034', clientVersion: 'test' }))+ expect((await put()).statusCode).toBe(500)+ mocks.prisma.harnessShare.upsert.mockRejectedValue(new Error('db down'))+ expect((await put()).statusCode).toBe(500)+ expect(mocks.changed).not.toHaveBeenCalled()})it('discovers only active invitations for the signed-in email and environment, without machine secrets', async () => {mocks.auth.mockResolvedValue(ken)@@ -164,20 +171,23 @@ describe('account-bound harness invitations', () => {expect(mocks.changed).toHaveBeenCalledTimes(4)})it('tells the invited account that its list changed, so its apps need not poll for invitations', async () => {+ const info = vi.spyOn(logger, 'info').mockImplementation(() => logger)const id = randomUUID()// First read is the "may this grant be changed" check (no row yet); the second is the saved invitation.mocks.prisma.harnessShare.findUnique.mockResolvedValueOnce(null).mockResolvedValue({ id, recipientEmail: '[email protected]' })mocks.prisma.user.findUnique.mockResolvedValue({ id: 'ken' })expect((await put(input(), id)).statusCode).toBe(200)expect(mocks.prisma.user.findUnique).toHaveBeenCalledWith({ where: { email: '[email protected]' }, select: { id: true } })- expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'updated' })+ expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'harness_shares' })+ // Named in the log, so a burst of `machines_changed` on someone's app can be traced to the invitation behind it.+ expect(info).toHaveBeenCalledWith('harness share: told the recipient it changed', { shareId: id, recipientId: 'ken' })})it('tells the invited account when the owner takes the invitation back', async () => {const id = randomUUID()mocks.prisma.harnessShare.findUnique.mockResolvedValue({ id, recipientEmail: '[email protected]' })mocks.prisma.user.findUnique.mockResolvedValue({ id: 'ken' })expect((await app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })).statusCode).toBe(200)- expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'updated' })+ expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'harness_shares' })})it('invites an address with no account yet, and survives the lookup failing, without telling anyone', async () => {const id = randomUUID(), remove = () => app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })diff --git a/backend/src/routes/harnessShares.ts b/backend/src/routes/harnessShares.tsindex f9ad431af..8ef1374da 100644--- a/backend/src/routes/harnessShares.ts+++ b/backend/src/routes/harnessShares.ts@@ -8,6 +8,7 @@ import { machineBillingAllowsDataPlane } from '../lib/billingState.js'import { validateBody, validateParams } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'import type { AuthUser } from '../lib/ssoAuth.js'+import { logger } from '../utils/logger.js'import { TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, teamMachineScope } from '../lib/teamSession.js'const params = z.object({ id: z.string().uuid() })@@ -29,7 +30,9 @@ const body = z.object({/*** Shared harnesses arrive in the invited account's machine list, so an invitation given or taken back* is a list change for THAT account: poke its open apps (web tabs, and each computer's daemon → app)- * to re-read. This is what lets the app stop polling `/api/harness-shares` to discover invitations.+ * to re-read. This is what lets the app stop polling `/api/harness-shares` to discover invitations. The+ * reason says so: an app reads `/api/harness-shares` (seconds, through the owner's daemon) only when told+ * it changed, and every few minutes otherwise.* Best effort — the invitation is already persisted, and an address with no account has nobody to tell.*/async function tellRecipient(shareId: string): Promise<void> {@@ -37,7 +40,9 @@ async function tellRecipient(shareId: string): Promise<void> {const share = await prisma.harnessShare.findUnique({ where: { id: shareId } })if (!share) returnconst recipient = await prisma.user.findUnique({ where: { email: share.recipientEmail }, select: { id: true } })- if (recipient) await publishDeviceMachineListChanged(recipient.id, { reason: 'updated' })+ if (!recipient) return+ await publishDeviceMachineListChanged(recipient.id, { reason: 'harness_shares' })+ logger.info('harness share: told the recipient it changed', { shareId, recipientId: recipient.id })} catch { /* best effort */ }}diff --git a/backend/src/routes/machineShares.test.ts b/backend/src/routes/machineShares.test.tsindex 90722e995..2135c9ce2 100644--- a/backend/src/routes/machineShares.test.ts+++ b/backend/src/routes/machineShares.test.ts@@ -18,6 +18,7 @@ vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof imporimport { machineShareRoutes, SHARE_EMAILS_MAX } from './machineShares.js'import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'import { errorHandler } from '../middlewares/errorHandler.js'+import { logger } from '../utils/logger.js'const M1 = 'ab'.repeat(16)const dee = { sub: 'dee', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }@@ -46,7 +47,7 @@ describe('sharing a machine', () => {app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, mocks.auth)await app.register(machineShareRoutes); await app.ready()})- afterEach(async () => { await app.close() })+ afterEach(async () => { await app.close(); vi.restoreAllMocks() })const put = (payload: unknown, machineId = M1) =>app.inject({ method: 'PUT', url: `/api/machines/${machineId}/share`, headers: auth, payload: payload as any })@@ -84,6 +85,7 @@ describe('sharing a machine', () => {})it('writes normalized addresses (never the owner’s own) and the owner’s domain, and tells everyone affected', async () => {+ const info = vi.spyOn(logger, 'info').mockImplementation(() => logger)mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row({ emails: ['[email protected]'], domain: null }))mocks.prisma.user.findMany.mockResolvedValue([{ id: 'ann' }, { id: 'kim' }, { id: 'dee' }])mocks.prisma.machineShareAdd.findMany.mockImplementation(async (args: { select?: unknown }) => args.select ? [{ userId: 'lee' }] : [])@@ -97,6 +99,8 @@ describe('sharing a machine', () => {expect(mocks.prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { OR: [{ email: { in: ['[email protected]', '[email protected]'] } }, { email: { endsWith: '@acme.io' } }] } }))expect(mocks.listChanged.mock.calls.map(c => c[0]).sort()).toEqual(['ann', 'kim', 'lee'])+ // Named in the log, so a burst of `machines_changed` on someone's app can be traced to the machine whose sharing changed.+ expect(info).toHaveBeenCalledWith('machine share: told everyone it changed', { machineId: M1, ownerId: 'dee', told: 3 })})it('retries a concurrent policy update before choosing versions for the resulting grants', async () => {@@ -125,6 +129,25 @@ describe('sharing a machine', () => {expect(mocks.shareChanged).toHaveBeenCalledWith(M1)})+ it('tells no one when the owner’s daemon writes the policy it already holds', async () => {+ // A daemon whose own policy names an address the backend drops (the owner's own, a `.invalid` one) never+ // reads back what it wrote, so it writes again every two minutes; each write told every member to re-read.+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row({ emails: ['[email protected]', '[email protected]'] }))+ mocks.prisma.user.findMany.mockResolvedValue([{ id: 'ann' }])+ const res = await put({ emails: ['[email protected]', '[email protected]', '[email protected]'], sameDomain: true })+ expect(res.statusCode).toBe(200)+ expect(mocks.listChanged).not.toHaveBeenCalled()+ expect(mocks.shareChanged).not.toHaveBeenCalled()+ })++ it('tells everyone affected when only the domain changes', async () => {+ mocks.prisma.machineShare.findUnique.mockResolvedValueOnce(row({ domain: null }))+ mocks.prisma.user.findMany.mockResolvedValue([{ id: 'kim' }])+ expect((await put({ emails: ['[email protected]'], sameDomain: true })).statusCode).toBe(200)+ expect(mocks.listChanged.mock.calls.map(c => c[0])).toEqual(['kim'])+ expect(mocks.shareChanged).toHaveBeenCalledWith(M1)+ })+it('tells no one when nothing was ever shared, and a failure to tell does not fail the write', async () => {await put({ emails: [], sameDomain: false })expect(mocks.prisma.user.findMany).not.toHaveBeenCalled()diff --git a/backend/src/routes/machineShares.ts b/backend/src/routes/machineShares.tsindex aa4f64566..0a17e6389 100644--- a/backend/src/routes/machineShares.ts+++ b/backend/src/routes/machineShares.ts@@ -78,10 +78,17 @@ async function writePolicy(machineId: string, user: AuthUser, emails: string[],}}+/** Whether two policies share the machine with the same people: the same addresses, in any order, and the same domain. */+function samePolicy(a: MachineShare | null, b: MachineShare | null): boolean {+ const emails = (s: MachineShare | null) => [...new Set(s?.emails ?? [])].sort().join('\n')+ return emails(a) === emails(b) && (a?.domain ?? null) === (b?.domain ?? null)+}+/*** Everyone a change of the policy may add the machine to or take it from, their apps and daemons told to* read their Machines again: the addresses before and after, everyone at the domain before and after, and- * whoever had added it. Best effort, like Share's `tellRecipient`: the policy is written already.+ * whoever had added it. Best effort, like Share's `tellRecipient`: the policy is written already. Called only for a+ * policy that changed, so one side of it names someone.*/async function tellAffected(machineId: string, ownerId: string, before: MachineShare | null, after: MachineShare | null): Promise<void> {try {@@ -89,12 +96,13 @@ async function tellAffected(machineId: string, ownerId: string, before: MachineSconst domains = [...new Set([before?.domain, after?.domain].filter((d): d is string => !!d))]const where = [...emails.length ? [{ email: { in: emails } }] : [], ...domains.map(d => ({ email: { endsWith: `@${d}` } }))]const [users, adds] = await Promise.all([- where.length ? prisma.user.findMany({ where: { OR: where }, select: { id: true }, take: TELL_MAX }) : [],+ prisma.user.findMany({ where: { OR: where }, select: { id: true }, take: TELL_MAX }),prisma.machineShareAdd.findMany({ where: { machineId }, select: { userId: true }, take: TELL_MAX }),])const ids = new Set([...users.map(u => u.id), ...adds.map(a => a.userId)])ids.delete(ownerId)await Promise.all([...ids].map(id => publishDeviceMachineListChanged(id, { reason: 'updated' })))+ logger.info('machine share: told everyone it changed', { machineId, ownerId, told: ids.size })} catch (err) {logger.warn('machine share: could not tell everyone it changed', { machineId, error: String(err) })}@@ -126,8 +134,13 @@ export async function machineShareRoutes(app: FastifyInstance): Promise<void> {}}const { before, after } = await writePolicy(machineId, user, emails, domain)- await publishMachineShareChanged(machineId).catch(() => 0)- await tellAffected(machineId, user.sub, before, after)+ // Told only when who it is shared with changed. The owner's daemon writes its policy again every two minutes+ // while it reads back something else (an address the backend drops above), and each write told every member's+ // every app to re-read its machines and shares: Diego's app re-read them every 1 to 3 minutes (2026-10-28).+ if (!samePolicy(before, after)) {+ await publishMachineShareChanged(machineId).catch(() => 0)+ await tellAffected(machineId, user.sub, before, after)+ }sendSuccess(reply, await policyView(after, user))})diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 13158252f..fdfbf0ea1 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -229,12 +229,12 @@ describe('Super Tab collaboration policy', () => {{ kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' }).messages[0]!expect(posted.recipients).toEqual([])const reply = f.run({ type: 'message.send', conversationId: 'lead', text: 'Keep the local copy.', replyTo: posted.id, recipientIds: [] }, owner,- { reply: { id: posted.id, conversationId: 'lead', author: posted.author } })+ { reply: { id: posted.id, conversationId: 'lead', author: posted.author, createdAt: 0 } })expect(reply.messages[0]!.recipients).toEqual([worker])const fresh = f.run({ type: 'message.send', conversationId: 'lead', text: 'Continue.', replyTo: null, recipientIds: [] })expect(fresh.messages[0]!.recipients).toEqual([lead])expect(() => f.run({ type: 'message.send', conversationId: 'lead', text: 'Cross-group reply', replyTo: posted.id, recipientIds: [] }, owner,- { reply: { id: posted.id, conversationId: 'elsewhere', author: posted.author } })).toThrow('Reply to a message in this conversation')+ { reply: { id: posted.id, conversationId: 'elsewhere', author: posted.author, createdAt: 0 } })).toThrow('Reply to a message in this conversation')})it('delivers an assigned worker\'s own post to its Lead, and nobody else\'s', () => {@@ -265,7 +265,7 @@ describe('Super Tab collaboration policy', () => {const reply = history.find(m => m.id === replyTo)const sent = f.run({ type: 'message.send', conversationId: group, text: 'Update.', replyTo, recipientIds }, as(agentId), {recent: history.slice().reverse().slice(0, PAIR_CHAIN_LIMIT).map(m => ({ author: m.author as never, recipients: m.recipients })),- ...(reply ? { reply: { id: reply.id, conversationId: group, author: reply.author as never } } : {}),+ ...(reply ? { reply: { id: reply.id, conversationId: group, author: reply.author as never, createdAt: 0 } } : {}),}).messages[0]!history.push({ author: { kind: 'agent', id: agentId }, recipients: sent.recipients, id: sent.id })return sent@@ -309,7 +309,7 @@ describe('Super Tab collaboration policy', () => {history.push({ author: { kind: 'person', id: 'owner' }, recipients: personMessage.recipients, id: personMessage.id })expect(personMessage.recipients).toEqual([lead])const reply = f.run({ type: 'message.send', conversationId: group, text: 'Ask the worker', replyTo: personMessage.id, recipientIds: [] }, as(lead), {- reply: { id: personMessage.id, conversationId: group, author: personMessage.author },+ reply: { id: personMessage.id, conversationId: group, author: personMessage.author, createdAt: 0 },}).messages[0]!expect(reply.recipients).toEqual([])})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex db534d168..21b07e33a 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -19,7 +19,7 @@ import { digestStartsAfter, knownTimeZone } from './digest.js'import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'import { workspaceCan, type WorkspaceRole } from './workspaces.js'-import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAnswer, recordAsked, recordMerged, recordReview, recordRun, recordStatus } from './leaderboard/record.js'+import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordDecision, recordMerged, recordPost, recordReview, recordRun, recordStatus } from './leaderboard/record.js'import { WEEK_MS } from './leaderboard/week.js'import { react, reactionSchema, type ReactionTarget } from './reactions.js'import { shipNotice, shippedAt } from './ship.js'@@ -245,7 +245,9 @@ export interface CommandContext {/** A Harness Team account's machine: the Mac it lives on, from its account row (machines.ts ContributedMachine). */hostMachineId?: string }/** Loaded from this tab and conversation by the store. */- reply?: { id: string; conversationId: string; author: Author }+ reply?: { id: string; conversationId: string; author: Author; createdAt: number }+ /** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */+ openTags?: Array<{ messageId: string; createdAt: number }>/** The message a Lead quotes as the owner's request for a rule or skill mode change, loaded from this tab by the store. */askedIn?: { author: Author; source: boolean; createdAt: number }/** The newest messages of this conversation before the one being sent, newest first, loaded by the store for `message.send`. */@@ -1102,6 +1104,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commacase 'decision.answer': {const { answer, recipients, source } = answerDecision(state, actor, context.decision, command.choice, command.note ?? null)effects.decisionAnswer = answer+ recordDecision(conversation(state, context.decision!.conversationId), context.decision!, context.now)if (recipients.length) message(context.decision!.conversationId, ANSWERED_NOTICE, recipients, null, source)result.decisionId = answer.idbreak@@ -1574,7 +1577,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.message(group.id, command.text, recipients, command.replyTo, command.agentOnly ? AGENT_ONLY : undefined, attachments, mentions)- recordAnswer(state, group, actor, command.replyTo, context.now)+ recordPost(state, group, actor, { replyTo: command.replyTo, text: command.text, reply: context.reply, openTags: context.openTags }, context.now)if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)break}diff --git a/backend/src/superTabs/decisions.test.ts b/backend/src/superTabs/decisions.test.tsindex 33d6ff42e..24651a916 100644--- a/backend/src/superTabs/decisions.test.ts+++ b/backend/src/superTabs/decisions.test.ts@@ -77,7 +77,8 @@ describe('asking a person for decisions', () => {describe('answering a decision', () => {const open = (s: ReturnType<typeof swarm>, overrides: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'peer',- conversationId: s.group, askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], answeredAt: null, ...overrides })+ conversationId: s.group, askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], answeredAt: null,+ createdAt: 0, assignmentId: null, ...overrides })it('records the asked person\'s choice and tells the asking agent and the Lead with a notice only they read, carrying none of it', () => {const s = swarm()diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex db2b0a424..79771fa19 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -31,6 +31,8 @@ export interface DecisionDraft extends Question {/** The decision `decision.answer` names, read from SuperTabDecision by the store. */export interface DecisionTarget {id: string; personId: string; conversationId: string; askerAgentId: string; question: string; options: string[]; answeredAt: number | null+ /** When it was asked, and the task whose needs_human asked it: the leaderboard credits the answer (leaderboard/record.ts). */+ createdAt: number; assignmentId: string | null}export interface DecisionAnswer { id: string; choice: number; note: string | null }@@ -128,8 +130,9 @@ export async function fullFor(tx: Tx, tabId: string, ask: Parameters<typeof repeexport async function readAskedDecision(tx: Tx, tabId: string, id: string): Promise<DecisionTarget | undefined> {const row = await tx.superTabDecision.findFirst({ where: { id, tabId },- select: { id: true, personId: true, conversationId: true, askerAgentId: true, question: true, options: true, answeredAt: true } })- return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null } : undefined+ select: { id: true, personId: true, conversationId: true, askerAgentId: true, question: true, options: true, answeredAt: true, createdAt: true,+ assignmentId: true } })+ return row ? { ...row, answeredAt: row.answeredAt?.getTime() ?? null, createdAt: row.createdAt.getTime(), assignmentId: row.assignmentId ?? null } : undefined}/** Conflicts with a concurrent answer of the same decision: only the first one counts. */diff --git a/backend/src/superTabs/leaderboard/contract.ts b/backend/src/superTabs/leaderboard/contract.tsindex fdd3ed5a4..efe22b7be 100644--- a/backend/src/superTabs/leaderboard/contract.ts+++ b/backend/src/superTabs/leaderboard/contract.ts@@ -1,13 +1,27 @@/*** The leaderboard read's response (`GET /api/super-tabs/:tabId/leaderboard?projectId=&week=`), the `data` of the usual* envelope. Desktop/web (`desktop/lib/super_tabs/leaderboard`) mirror it by hand. Times are epoch milliseconds; people are- * member ids, which clients name from the members they already read. No text from any conversation is ever in it.+ * member ids. The only conversation text in it is the titles of conversations the reader may read (details); no message text.*/export type Medal = 'gold' | 'silver' | 'bronze'+export type UnblockKind = 'decision' | 'approval' | 'needs_human' | 'tag_reply'++/** What a person's numbers are made of this week, each list the 20 newest at most, from what the reader may read. */+export interface PersonDetails {+ /** `mergedAt`: when it shipped, its earliest recorded merge (leaderboard/record.ts shippedAt); `prUrl`: its last linked PR. */+ shipped: Array<{ title: string; prUrl: string; mergedAt: number }>+ unblocked: Array<{ title: string; conversationId: string; kind: UnblockKind; waitedMinutes: number }>+ /** Each machine's busy agent-hours this week, to one decimal, busiest first. */+ lent: Array<{ machineName: string; busyHours: number }>+}export interface PersonScore {personId: string+ /** Their profile name, else their email's local part. */+ displayName: stringpoints: number+ /** The same scoring for the week before, for the arrow against last week. */+ prevWeekPoints: number/** 1 for the most points; people with the same points share a rank. */rank: number/** For the top three ranks with points; null otherwise. */@@ -15,10 +29,11 @@ export interface PersonScore {shipped: { count: number; medianAskToShipMs: number | null }/** `agentMs`: the agent time the answers freed; `medianAnswerMs`: how long an item waited for the person's answer. */unblocked: { count: number; agentMs: number; medianAnswerMs: number | null }- /** Machines that ran Swarm agents this week, and the agent time they ran. */+ /** Machines whose agents worked on other people's tasks this week, and that busy agent time (leaderboard/lent.ts). */lent: { machines: number; agentMs: number }/** Days in a row, up to today, with a shipped request. */streakDays: number+ details: PersonDetails}export interface WeekGoal { shipped: number; points: number; medianAskToShipMs: number | null }diff --git a/backend/src/superTabs/leaderboard/lent.test.ts b/backend/src/superTabs/leaderboard/lent.test.tsindex 56609cfda..4bb34bdfb 100644--- a/backend/src/superTabs/leaderboard/lent.test.ts+++ b/backend/src/superTabs/leaderboard/lent.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { MACHINE_FRESH_MS, type ContributedMachine } from '../machines.js'-import { createSuperTab, type Agent, type Conversation, type SuperTabState } from '../model.js'+import { createSuperTab, type Agent, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'import { accrueLent } from './lent.js'import { weekStart } from './week.js'@@ -15,7 +15,13 @@ function machine(running: string[], receivedAt: number): ContributedMachine {}const agent = (id: string, extra: Partial<Agent> = {}): Agent => ({ id, machineId: 'mac', harnessId: `h-${id}`, machineOwnerId: 'owner', contributorId: 'owner',membershipGeneration: 'tab', name: id, configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }, ...extra })-function swarm(pool: ContributedMachine, agents: Agent[], conversations: Conversation[] = []): SuperTabState {+/** A task [agentId] works on, asked for by [requesterId]: someone else than the machine's contributor unless named. */+const task = (agentId: string, status: WorkStatus = 'working', requesterId: string | undefined = 'dee'): Conversation => ({ id: `task-${agentId}`,+ title: 'Task', leadId: null, agentIds: [agentId], archived: false, brief: '', checks: [], lastMessageSequence: 0, requesterId,+ assignment: { id: `a-${agentId}`, agentId, status, result: null, configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null,+ engineVersion: null }, execution: { machineId: 'mac', harnessId: `h-${agentId}`, machineOwnerId: 'owner' } } })+/** A Swarm whose agents each work on another person's task, unless [conversations] says otherwise. */+function swarm(pool: ContributedMachine, agents: Agent[], conversations: Conversation[] = agents.map(a => task(a.id))): SuperTabState {const state = createSuperTab('tab', 'Pilot', { id: 'owner', email: '[email protected]' }, 'prod')return { ...state, agents, machines: [pool], conversations: [...state.conversations, ...conversations] }}@@ -29,27 +35,42 @@ describe('the week a moment belongs to', () => {})describe('lent agent-hours from machine readings', () => {+ it('counts only agents working on a task someone other than the machine\'s contributor asked for', () => {+ const pool = machine(['h-busy', 'h-idle', 'h-own', 'h-waiting', 'h-team'], MONDAY)+ const state = swarm(pool, ['busy', 'idle', 'own', 'waiting', 'team'].map(id => agent(id)),+ [task('busy'), task('own', 'working', 'owner'), task('waiting', 'needs_human'), task('team', 'working', undefined)])+ accrueLent(state, pool, MONDAY + 10_000)+ // busy and team (a task nobody named asked for) worked; idle has no task, own is the contributor's, waiting waits on a person.+ expect(pool.lent).toEqual([{ week: MONDAY, busyMs: 20_000 }])+ })++ it('stops writing online hours: a week that has them gains busy hours beside them', () => {+ const pool = machine(['h-a'], MONDAY), state = swarm(pool, [agent('a')])+ pool.lent = [{ week: MONDAY, agentMs: 50_000 }]+ accrueLent(state, pool, MONDAY + 10_000)+ expect(pool.lent).toEqual([{ week: MONDAY, agentMs: 50_000, busyMs: 10_000 }])+ })+it('adds the time since the last reading for each Swarm agent the machine was running', () => {const pool = machine(['h-a', 'h-b'], MONDAY + 1_000), state = swarm(pool, [agent('a'), agent('b')])accrueLent(state, pool, MONDAY + 31_000)- expect(pool.lent).toEqual([{ week: MONDAY, agentMs: 60_000 }])+ expect(pool.lent).toEqual([{ week: MONDAY, busyMs: 60_000 }])})it('counts at most one fresh reading\'s worth across a gap, so a machine back from sleep earns no phantom hours', () => {const pool = machine(['h-a'], MONDAY), state = swarm(pool, [agent('a')])accrueLent(state, pool, MONDAY + 3_600_000)- expect(pool.lent).toEqual([{ week: MONDAY, agentMs: MACHINE_FRESH_MS }])+ expect(pool.lent).toEqual([{ week: MONDAY, busyMs: MACHINE_FRESH_MS }])})it('ignores sessions that are not Swarm agents on this machine', () => {const pool = machine(['h-a', 'someone-else'], MONDAY), state = swarm(pool, [agent('a'), agent('b', { machineId: 'other' })])accrueLent(state, pool, MONDAY + 10_000)- expect(pool.lent).toEqual([{ week: MONDAY, agentMs: 10_000 }])+ expect(pool.lent).toEqual([{ week: MONDAY, busyMs: 10_000 }])})it('leaves out an agent of a private conversation: private chats never count', () => {- const chat: Conversation = { id: 'chat', title: 'Chat', leadId: null, agentIds: ['pm'], archived: false, brief: '', checks: [], assignment: null,- lastMessageSequence: 0, audience: { people: [{ id: 'owner', generation: 'tab' }] } }+ const chat: Conversation = { ...task('pm'), id: 'chat', audience: { people: [{ id: 'owner', generation: 'tab' }] } }const pool = machine(['h-pm'], MONDAY), state = swarm(pool, [agent('pm')], [chat])accrueLent(state, pool, MONDAY + 10_000)expect(pool.lent).toBeUndefined()@@ -59,7 +80,7 @@ describe('lent agent-hours from machine readings', () => {const pool = machine(['h-lead-agent', 'h-builder'], MONDAY), state = swarm(pool, [agent('lead-agent'), agent('builder')])state.conversations.find(c => c.id === 'lead')!.leadId = 'lead-agent'accrueLent(state, pool, MONDAY + 10_000)- expect(pool.lent).toEqual([{ week: MONDAY, agentMs: 10_000 }])+ expect(pool.lent).toEqual([{ week: MONDAY, busyMs: 10_000 }])})it('adds nothing on the first reading', () => {@@ -76,6 +97,6 @@ describe('lent agent-hours from machine readings', () => {accrueLent(state, pool, pool.observation!.receivedAt + 5_000)}expect(pool.lent?.map(l => (l.week - MONDAY) / (7 * 86_400_000))).toEqual([2, 3, 4, 5, 6])- expect(pool.lent?.every(l => l.agentMs === 5_000)).toBe(true)+ expect(pool.lent?.every(l => l.busyMs === 5_000)).toBe(true)})})diff --git a/backend/src/superTabs/leaderboard/lent.ts b/backend/src/superTabs/leaderboard/lent.tsindex 1bc6e0c46..77b2b3653 100644--- a/backend/src/superTabs/leaderboard/lent.ts+++ b/backend/src/superTabs/leaderboard/lent.ts@@ -1,7 +1,8 @@/**- * Lent: agent-hours Swarm agents ran on a person's contributed machine, added up from that machine's readings and kept on- * its contribution by week (docs/swarms.md, Leaderboard). Agents of private chats never count, nor Leads: a Lead's session is- * confidential coordination, not lent build work (Lead's ruling on the review of #1762).+ * Lent: agent-hours Swarm agents on a person's contributed machine spent working on other people's tasks, added up from that+ * machine's readings and kept on its contribution by week (docs/swarms.md, Leaderboard). An idle or waiting agent lends+ * nothing, nor one on the contributor's own request (Dee, 2026-10-28). Agents of private chats never count, nor Leads: a+ * Lead's session is confidential coordination, not lent build work (Lead's ruling on the review of #1762).*/import { MACHINE_FRESH_MS, type ContributedMachine } from '../machines.js'import type { SuperTabState } from '../model.js'@@ -9,22 +10,27 @@ import { ledProject } from '../projects.js'import { LEDGER_WEEKS } from './record.js'import { WEEK_MS, weekStart } from './week.js'-export interface LentWeek { week: number; agentMs: number }+/** `busyMs`: agent time spent on other people's tasks, the only time Lent counts (Dee, 2026-10-28). `agentMs`: online agent+ * time, recorded before then and no longer counted or written. */+export interface LentWeek { week: number; agentMs?: number; busyMs?: number }/** Credits the time since the machine's previous reading, at most one fresh reading's worth, to each Swarm agent that- * reading showed running. Call it before the new reading replaces the previous one. */+ * reading showed running and that is working on a task someone else asked for: one nobody named counts as someone else's.+ * Call it before the new reading replaces the previous one. */export function accrueLent(state: SuperTabState, pool: ContributedMachine, now: number): void {const previous = pool.observationif (!previous) returnconst elapsed = Math.min(Math.max(0, now - previous.receivedAt), MACHINE_FRESH_MS)const running = new Set(previous.runningHarnessIds)const privateChats = state.conversations.filter(c => c.audience)- const counted = state.agents.filter(a => a.machineId === pool.machineId && running.has(a.harnessId)+ const busy = new Set(state.conversations.filter(c => !c.audience && c.assignment?.status === 'working' && c.requesterId !== pool.contributorId)+ .map(c => c.assignment!.agentId))+ const counted = state.agents.filter(a => a.machineId === pool.machineId && running.has(a.harnessId) && busy.has(a.id)&& !ledProject(state, a.id) && !privateChats.some(c => c.agentIds.includes(a.id)))if (!elapsed || !counted.length) returnconst week = weekStart(now)const kept = (pool.lent ?? []).filter(l => l.week > week - LEDGER_WEEKS * WEEK_MS)- const current = kept.find(l => l.week === week) ?? kept[kept.push({ week, agentMs: 0 }) - 1]!- current.agentMs += elapsed * counted.length+ const current = kept.find(l => l.week === week) ?? kept[kept.push({ week }) - 1]!+ current.busyMs = (current.busyMs ?? 0) + elapsed * counted.lengthpool.lent = kept}diff --git a/backend/src/superTabs/leaderboard/read.test.ts b/backend/src/superTabs/leaderboard/read.test.tsindex ca8106a90..78e84ebe6 100644--- a/backend/src/superTabs/leaderboard/read.test.ts+++ b/backend/src/superTabs/leaderboard/read.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import type { Prisma } from '@prisma/client'-import { recentDormantGroups } from './read.js'+import { profileNames, recentDormantGroups } from './read.js'// Diego's issue file (2026-10-27): the board loaded every dormant group of the last 5 weeks whole, once a minute per open// column. It reads only what the board and its read check use (stats.ts, projects.ts canReadGroup).@@ -21,7 +21,7 @@ describe('the dormant groups the leaderboard sums', () => {const [{ pipeline }] = asked as [{ pipeline: Array<Record<string, Record<string, unknown>>> }]expect(pipeline[0]!.$match).toEqual({ tabId: 'tab', deleted: false, dormant: true, lastActivityAt: { $gte: { $date: new Date(since).toISOString() } }, projectId: 'web' })expect(Object.keys(pipeline[1]!.$project!).sort()).toEqual(['_id', ...['archived', 'assignment.id', 'assignment.status', 'audience', 'id', 'kind', 'ledger',- 'projectId', 'pullRequestUrls', 'requesterId', 'reviewOf'].map(field => `data.${field}`)].sort())+ 'projectId', 'pullRequestUrls', 'requesterId', 'reviewOf', 'title'].map(field => `data.${field}`)].sort())})it('reads the default project\'s groups stored with no project too', async () => {@@ -30,3 +30,18 @@ describe('the dormant groups the leaderboard sums', () => {expect((asked[0] as { pipeline: Array<Record<string, Record<string, unknown>>> }).pipeline[0]!.$match).toMatchObject({ $or: [{ projectId: 'lead' }, { projectId: null }] })})})++describe('the names the board shows', () => {+ it('reads only the name of account ids, and leaves people without one to their email', async () => {+ const asked: unknown[] = []+ const tx = { user: { findMany: async (args: unknown) => { asked.push(args); return [{ id: 'a'.repeat(24), name: 'Dee Tran' }, { id: 'b'.repeat(24), name: null }] } } } as unknown as Prisma.TransactionClient+ expect(await profileNames(tx, ['a'.repeat(24), 'b'.repeat(24), 'owner'])).toEqual(new Map([['a'.repeat(24), 'Dee Tran']]))+ // A member id that is no account id would make the database refuse the whole read.+ expect(asked).toEqual([{ where: { id: { in: ['a'.repeat(24), 'b'.repeat(24)] } }, select: { id: true, name: true } }])+ })++ it('reads nothing when no member is an account', async () => {+ const tx = { user: { findMany: async () => { throw new Error('read') } } } as unknown as Prisma.TransactionClient+ expect(await profileNames(tx, ['owner'])).toEqual(new Map())+ })+})diff --git a/backend/src/superTabs/leaderboard/read.ts b/backend/src/superTabs/leaderboard/read.tsindex 0a75f0626..754dfed1d 100644--- a/backend/src/superTabs/leaderboard/read.ts+++ b/backend/src/superTabs/leaderboard/read.ts@@ -14,8 +14,9 @@ export function readableWeek(week: number | undefined, now: number): number {return week}-/** What the board reads of a group (stats.ts, record.ts waitsNow) and its read check (projects.ts canReadGroup). */-const BOARD_FIELDS = ['id', 'kind', 'projectId', 'audience', 'requesterId', 'reviewOf', 'archived', 'pullRequestUrls', 'ledger',+/** What the board reads of a group (stats.ts, record.ts waitsNow) and its read check (projects.ts canReadGroup); the title+ * names it in a person's details. */+const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'audience', 'requesterId', 'reviewOf', 'archived', 'pullRequestUrls', 'ledger','assignment.id', 'assignment.status'] as const/** Dormant groups of one project active since [since]: a request shipped in a week the board sums wrote its Done row then.@@ -30,3 +31,12 @@ export async function recentDormantGroups(tx: Prisma.TransactionClient, tabId: s] }) as unknown as Array<{ data: Conversation }>return rows.map(row => row.data)}++/** The profile names of the board's people (contract.ts displayName), one read by id for the few people of a Swarm. A member id+ * that is not an account id (an older fixture) has no name and goes by its email. */+export async function profileNames(tx: Prisma.TransactionClient, personIds: string[]): Promise<Map<string, string>> {+ const ids = personIds.filter(id => /^[0-9a-f]{24}$/.test(id))+ if (!ids.length) return new Map()+ const rows = await tx.user.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } })+ return new Map(rows.flatMap(row => row.name ? [[row.id, row.name] as const] : []))+}diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.tsindex 42bc13f77..4a8ecd29a 100644--- a/backend/src/superTabs/leaderboard/record.test.ts+++ b/backend/src/superTabs/leaderboard/record.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, type Command, type CommandContext } from '../commands.js'import { createSuperTab, type Actor, type AgentConfiguration, type Conversation } from '../model.js'+import type { DecisionTarget } from '../decisions.js'+import { MAX_UNBLOCKS } from './record.js'import { leaderboard } from './stats.js'import { DAY_MS, WEEK_MS, weekStart } from './week.js'@@ -285,7 +287,8 @@ describe('who unblocks waiting work', () => {expect(f.group(id).ledger?.waiting).toEqual({ assignmentId, since: 10_000, messageId: expect.any(String) })f.at(10_000 + 3 * 3_600_000)f.say(id, owner)- expect(f.group(id).ledger?.unblocks).toEqual([{ personId: 'owner', at: 10_000 + 3 * 3_600_000, waitedMs: 3 * 3_600_000 }])+ expect(f.group(id).ledger?.unblocks).toEqual([{ personId: 'owner', at: 10_000 + 3 * 3_600_000, waitedMs: 3 * 3_600_000, kind: 'needs_human',+ item: f.group(id).ledger!.waiting!.messageId }])expect(f.group(id).ledger?.waiting).toEqual({ assignmentId, since: 10_000, messageId: expect.any(String), answeredAt: 10_000 + 3 * 3_600_000 })})@@ -323,7 +326,7 @@ describe('who unblocks waiting work', () => {f.invitePeer()const id = f.create(), { worker, assignmentId } = f.assign(id)const asked = f.status(id, assignmentId, worker, 'needs_human', 'Flag?').messages[0]!- f.say(id, peer, 'Flag.', asked.id, { id: asked.id, conversationId: id, author: asked.author })+ f.say(id, peer, 'Flag.', asked.id, { id: asked.id, conversationId: id, author: asked.author, createdAt: 1_000 })expect(f.group(id).ledger?.unblocks).toEqual([expect.objectContaining({ personId: 'peer' })])})@@ -382,6 +385,124 @@ describe('who unblocks waiting work', () => {})})+describe('other ways a person unblocks work: decisions, approvals and tags', () => {+ const HOUR = 3_600_000+ const decision = (conversationId: string, extra: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'owner', conversationId,+ askerAgentId: 'gone', question: 'Ship how?', options: ['Behind a flag', 'To everyone'], answeredAt: null, createdAt: 2 * HOUR, assignmentId: null, ...extra })+ /** The project's Lead asks in its own conversation at [askedAt], returning what a reply to it carries. */+ const leadAsk = (f: ReturnType<typeof fixture>, askedAt = HOUR) => {+ const lead = f.add('lead', 'lead', true)+ f.at(askedAt)+ const asked = f.say('lead', f.asAgent(lead), 'Plan: three steps. Reply GO to start.').messages[0]!+ return { lead, reply: { id: asked.id, conversationId: 'lead', author: asked.author, createdAt: askedAt } }+ }+ const tagged = (f: ReturnType<typeof fixture>, id: string, text: string, openTags: CommandContext['openTags']) =>+ f.run({ type: 'message.send', conversationId: id, text, replyTo: null, recipientIds: [] }, owner, { openTags })++ it('credits a decision answer to the person asked, with how long it waited', () => {+ const f = fixture(), id = f.create()+ f.at(5 * HOUR)+ f.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0 }, owner, { decision: decision(id) })+ expect(f.group(id).ledger?.unblocks).toEqual([{ personId: 'owner', at: 5 * HOUR, waitedMs: 3 * HOUR, kind: 'decision', item: 'decision-1' }])+ })++ it('closes the wait a worker\'s needs-human decision belongs to, so a post after the answer counts nothing more', () => {+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)+ f.at(HOUR)+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')+ f.at(2 * HOUR)+ f.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0 }, owner, { decision: decision(id, { createdAt: HOUR, assignmentId }) })+ f.say(id, owner, 'Picked the flag.')+ expect(f.group(id).ledger?.unblocks).toEqual([expect.objectContaining({ kind: 'decision', waitedMs: HOUR })])+ expect(f.group(id).ledger?.waiting?.answeredAt).toBe(2 * HOUR)+ })++ it('counts a needs-human ask once when its person posts an answer before answering its decision', () => {+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)+ f.at(HOUR)+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')+ f.at(2 * HOUR)+ f.say(id, owner, 'Flag.')+ f.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0 }, owner, { decision: decision(id, { createdAt: HOUR, assignmentId }) })+ expect(f.group(id).ledger?.unblocks).toEqual([expect.objectContaining({ kind: 'needs_human' })])+ })++ it('leaves a wait open when the decision answered belongs to another attempt', () => {+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')+ f.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0 }, owner, { decision: decision(id, { createdAt: 0, assignmentId: 'earlier' }) })+ expect(f.group(id).ledger?.waiting?.answeredAt).toBeUndefined()+ })++ for (const word of ['GO', 'go ahead', 'Approve', 'approved, thanks', 'Duyệt', 'duyet nhe', 'DUYỆT nhé', ' Go!']) {+ it(`counts "${word}" in reply to the Lead's ask as an approval, with how long the ask waited`, () => {+ const f = fixture(), { reply } = leadAsk(f, HOUR)+ f.at(4 * HOUR)+ f.say('lead', owner, word, reply.id, reply)+ expect(f.group('lead').ledger?.unblocks).toEqual([{ personId: 'owner', at: 4 * HOUR, waitedMs: 3 * HOUR, kind: 'approval', item: reply.id }])+ })+ }++ for (const word of ['ok', 'OK, go', 'goal: ship Friday', 'approves nothing yet', 'no, not GO']) {+ it(`does not count "${word}" as an approval`, () => {+ const f = fixture(), { reply } = leadAsk(f)+ f.say('lead', owner, word, reply.id, reply)+ expect(f.group('lead').ledger?.unblocks).toBeUndefined()+ })+ }++ it('counts an approval only in reply to the project\'s Lead, never to another agent', () => {+ const f = fixture(), id = f.create(), { worker } = f.assign(id)+ const said = f.say(id, f.asAgent(worker), 'Shall I start?').messages[0]!+ f.say(id, owner, 'GO', said.id, { id: said.id, conversationId: id, author: said.author, createdAt: 1_000 })+ expect(f.group(id).ledger?.unblocks).toBeUndefined()+ })++ it('counts one approval per ask, however many people or times reply GO', () => {+ const f = fixture()+ f.invitePeer()+ const { reply } = leadAsk(f)+ f.say('lead', owner, 'GO', reply.id, reply)+ f.say('lead', owner, 'GO again', reply.id, reply)+ f.say('lead', peer, 'Approved', reply.id, reply)+ expect(f.group('lead').ledger?.unblocks).toEqual([expect.objectContaining({ personId: 'owner', kind: 'approval' })])+ })++ it('credits a reply to the tags waiting on the person once, timed from the oldest', () => {+ const f = fixture(), id = f.create()+ f.at(5 * HOUR)+ tagged(f, id, 'Here you go.', [{ messageId: 'tag-new', createdAt: 3 * HOUR }, { messageId: 'tag-old', createdAt: HOUR }])+ expect(f.group(id).ledger?.unblocks).toEqual([{ personId: 'owner', at: 5 * HOUR, waitedMs: 4 * HOUR, kind: 'tag_reply', item: 'tag-old' }])+ tagged(f, id, 'And again.', [{ messageId: 'tag-old', createdAt: HOUR }])+ expect(f.group(id).ledger?.unblocks).toHaveLength(1)+ })++ it('gives one post one credit: an answer to waiting work that also replies to a tag counts as the answer', () => {+ const f = fixture(), id = f.create(), { worker, assignmentId } = f.assign(id)+ f.status(id, assignmentId, worker, 'needs_human', 'Flag?')+ tagged(f, id, 'Flag.', [{ messageId: 'tag', createdAt: 0 }])+ expect(f.group(id).ledger?.unblocks).toEqual([expect.objectContaining({ kind: 'needs_human' })])+ })++ it('never credits a private conversation', () => {+ const f = fixture()+ const chat = f.run({ type: 'conversation.create', title: 'Me and PM', brief: '', checks: [], audience: { personIds: ['owner'] } }).result.conversationId as string+ tagged(f, chat, 'Hi.', [{ messageId: 'tag', createdAt: 0 }])+ expect(f.group(chat).ledger?.unblocks).toBeUndefined()+ })++ it(`keeps at most ${MAX_UNBLOCKS} credits on one conversation, the newest`, () => {+ const f = fixture(), id = f.create()+ for (let i = 0; i <= MAX_UNBLOCKS; i++) {+ f.at(10_000 + i)+ tagged(f, id, `Reply ${i}`, [{ messageId: `tag-${i}`, createdAt: 0 }])+ }+ const kept = f.group(id).ledger!.unblocks!+ expect(kept).toHaveLength(MAX_UNBLOCKS)+ expect(kept[0]!.item).toBe('tag-1')+ })+})+describe('the model behind each assignment, and its first review (roadmap, Dec: about 30% of work on cheaper models)', () => {const independent = [{ description: 'Works', independent: false }, { description: 'Independent review', independent: true }]/** Reads a check by its kind, so the order of the checks does not matter. */diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.tsindex 23a23b164..7153b22b5 100644--- a/backend/src/superTabs/leaderboard/record.ts+++ b/backend/src/superTabs/leaderboard/record.ts@@ -2,11 +2,15 @@* What the leaderboard counts, recorded as it happens on the group it happened in (docs/swarms.md, Leaderboard): when a* request was asked and first shipped, which item waits on a person, and who answered it. Only facts and times, never text.*/-import type { Actor, Agent, Assignment, Check, Conversation, SuperTabState, WorkStatus } from '../model.js'-import { groupProject } from '../projects.js'+import { isLeads, type Actor, type Agent, type Assignment, type Author, type Check, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'+import { groupProject, ledProject } from '../projects.js'import { WEEK_MS } from './week.js'+import type { UnblockKind } from './contract.js'-export interface Unblock { personId: string; at: number; waitedMs: number }+/** How a person unblocked work (Dee, 2026-10-28): answered a decision, approved the Lead's plan, answered work waiting on them,+ * or replied to a tag. `item`: what was answered (the decision, the Lead's ask, the waiting question or the tag message),+ * credited once. Both are absent from answers recorded before kinds, which were all answers to waiting work. */+export interface Unblock { personId: string; at: number; waitedMs: number; kind?: UnblockKind; item?: string }/** One attempt at a group's work: what it ran on and whether its first review passed (roadmap, Dec: about 30% of work on* cheaper models without lower quality). `grid`: a model served on the Swarm's grid, named by its start, since the engine* reports none of its own. `firstVerdicts`: each independent check's first verdict during this attempt, by check id.@@ -34,6 +38,8 @@ export interface GroupLedger {export const LEDGER_WEEKS = 5/** A group is one request; more attempts than this are a stuck task, and the oldest say nothing new. */export const MAX_RUNS = 20+/** Credits one conversation keeps, newest: a busy Lead conversation collects approvals and tag replies for weeks. */+export const MAX_UNBLOCKS = 200/** A shared group is asked when it is opened. A private conversation is chat only and never counts. */export function recordAsked(group: Conversation, requesterId: string | undefined, now: number): void {@@ -70,16 +76,61 @@ export function waitedOn(state: SuperTabState, group: Conversation): string {return requester ?? groupProject(state, group).ownerId}+/** What a person's post can answer besides waiting work: the message it replies to, and the tags waiting on the poster in+ * this conversation (mentions.ts), both read by the store. */+export interface PostContext { replyTo: string | null; text: string; reply?: { id: string; author: Author; createdAt: number }+ openTags?: Array<{ messageId: string; createdAt: number }> }++/** A person's post earns one credit at most, for the first it answers of: the work waiting on them, the Lead's ask it approves,+ * the oldest tag waiting on them here (Lead's rulings, 2026-10-28). Private chats never count. */+export function recordPost(state: SuperTabState, group: Conversation, actor: Actor, post: PostContext, now: number): void {+ if (actor.kind !== 'person' || group.audience || isLeads(group)) return+ if (recordAnswer(state, group, actor.userId, post.replyTo, now)) return+ const reply = post.reply+ if (reply && reply.author.kind === 'agent' && approves(post.text) && ledProject(state, reply.author.id)?.id === groupProject(state, group).id) {+ if (credit(group, { personId: actor.userId, at: now, waitedMs: now - reply.createdAt, kind: 'approval', item: reply.id })) return+ }+ const oldest = [...post.openTags ?? []].sort((a, b) => a.createdAt - b.createdAt)[0]+ if (oldest) credit(group, { personId: actor.userId, at: now, waitedMs: now - oldest.createdAt, kind: 'tag_reply', item: oldest.messageId })+}++/** A reply that starts with GO, approve(d) or duyệt, in any case, with or without accents; a bare "ok" is too ambiguous+ * (Lead, 2026-10-28). */+export function approves(text: string): boolean {+ const plain = text.normalize('NFD').replace(/\p{M}/gu, '').replace(/đ/giu, 'd').trim().toLowerCase()+ return /^(go|approved?|duyet)(?![\p{L}\p{N}])/u.test(plain)+}++/** The person asked answered a decision: credited from when it was asked. A decision a worker asked through needs_human is+ * that wait's question, asked in the same command (same time): answering it answers the wait, and once the wait is answered,+ * by a post or this decision, the other earns nothing more. */+export function recordDecision(group: Conversation, decision: { id: string; personId: string; createdAt: number; assignmentId: string | null }, now: number): void {+ if (group.audience || isLeads(group)) return+ const waiting = group.ledger?.waiting+ if (decision.assignmentId && waiting?.assignmentId === decision.assignmentId && waiting.since === decision.createdAt) {+ if (waiting.answeredAt != null) return+ waiting.answeredAt = now+ }+ credit(group, { personId: decision.personId, at: now, waitedMs: now - decision.createdAt, kind: 'decision', item: decision.id })+}+/** A person's post answers the waiting item when they are the one it waits on, or when it replies to the question itself;* a passer-by's chat earns nothing (Lead, 2026-10-27). One answer per wait. */-export function recordAnswer(state: SuperTabState, group: Conversation, actor: Actor, replyTo: string | null, now: number): void {+function recordAnswer(state: SuperTabState, group: Conversation, personId: string, replyTo: string | null, now: number): boolean {const waiting = group.ledger?.waiting- if (actor.kind !== 'person' || !waitsNow(group) || waiting?.assignmentId !== group.assignment!.id) return- if (actor.userId !== waitedOn(state, group) && replyTo !== waiting.messageId) return- const ledger = group.ledger!+ if (!waitsNow(group) || waiting?.assignmentId !== group.assignment!.id) return false+ if (personId !== waitedOn(state, group) && replyTo !== waiting.messageId) return falsewaiting.answeredAt = now- const kept = (ledger.unblocks ?? []).filter(u => now - u.at < LEDGER_WEEKS * WEEK_MS)- ledger.unblocks = [...kept, { personId: actor.userId, at: now, waitedMs: Math.max(0, now - waiting.since) }]+ return credit(group, { personId, at: now, waitedMs: now - waiting.since, kind: 'needs_human', item: waiting.messageId })+}++/** Adds a credit unless its item already has one; keeps the last LEDGER_WEEKS, at most MAX_UNBLOCKS. */+function credit(group: Conversation, unblock: Unblock & { item: string }): boolean {+ const ledger = group.ledger ??= {}+ if (ledger.unblocks?.some(u => u.item === unblock.item)) return false+ const kept = (ledger.unblocks ?? []).filter(u => unblock.at - u.at < LEDGER_WEEKS * WEEK_MS)+ ledger.unblocks = [...kept, { ...unblock, waitedMs: Math.max(0, unblock.waitedMs) }].slice(-MAX_UNBLOCKS)+ return true}/** Whether the group's work waits on a person now: needs a human and not yet answered. An item from before answers werediff --git a/backend/src/superTabs/leaderboard/stats.test.ts b/backend/src/superTabs/leaderboard/stats.test.tsindex 9d1f32ee9..2270d1b0f 100644--- a/backend/src/superTabs/leaderboard/stats.test.ts+++ b/backend/src/superTabs/leaderboard/stats.test.ts@@ -30,12 +30,12 @@ const shipped = (requesterId: string, askedAt: number, shippedAt: number, extra:group({ requesterId, status: 'done', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt, shippedAt }, ...extra })const answered = (...unblocks: Array<[personId: string, at: number, waitedMs: number]>) =>group({ status: 'working', ledger: { unblocks: unblocks.map(([personId, at, waitedMs]) => ({ personId, at, waitedMs })) } })-function machine(contributorId: string, lent: Array<[week: number, agentMs: number]>, machineId = `mac-${contributorId}`): ContributedMachine {+function machine(contributorId: string, lent: Array<[week: number, busyMs: number]>, machineId = `mac-${contributorId}`): ContributedMachine {return { machineId, name: machineId, contributorId, membershipGeneration: 'g', generation: 'g1', cwd: '/repo', scope: 'swarm', engines: ['claude'],- maxAgents: 2, paused: false, lent: lent.map(([week, agentMs]) => ({ week, agentMs })) }+ maxAgents: 2, paused: false, lent: lent.map(([week, busyMs]) => ({ week, busyMs })) }}-const board = (state: SuperTabState, groups: Conversation[], week = WEEK, now = NOW, machines = state.machines ?? []) =>- leaderboard({ state, groups, machines, projectId: 'lead', week, now })+const board = (state: SuperTabState, groups: Conversation[], week = WEEK, now = NOW, machines = state.machines ?? [], names?: ReadonlyMap<string, string>) =>+ leaderboard({ state, groups, machines, projectId: 'lead', week, now, names })const person = (view: ReturnType<typeof board>, id: string) => view.people.find(p => p.personId === id)!describe('Shipped: requests a person asked for, done with a linked PR, 3 points each', () => {@@ -71,15 +71,30 @@ describe('Shipped: requests a person asked for, done with a linked PR, 3 points})})-describe('Unblocked: waiting items a person answered, 1 point each plus 1 per 2 agent-hours waited', () => {- it('adds the answers and the agent-hours they freed', () => {+describe('Unblocked: items a person answered, 1 point each plus 1 per 2 hours each waited, at most 3', () => {+ it('weighs each answer by how long it waited', () => {const view = board(swarm(), [answered(['tony', WEEK + HOUR, 3 * HOUR], ['tony', WEEK + 2 * HOUR, 90 * 60_000]), answered(['tony', LAST, 10 * HOUR])])- // Two answers this week, 4.5 agent-hours between them: 2 + 2.- expect(person(view, 'tony')).toMatchObject({ points: 4, unblocked: { count: 2, agentMs: 4.5 * HOUR, medianAnswerMs: 2.25 * HOUR } })+ // 3 hours waited: 1 + 1; 1.5 hours: 1 + 0.+ expect(person(view, 'tony')).toMatchObject({ points: 3, unblocked: { count: 2, agentMs: 4.5 * HOUR, medianAnswerMs: 2.25 * HOUR } })+ })++ it('caps one answer at 3 points, however long it waited', () => {+ expect(person(board(swarm(), [answered(['tony', WEEK + HOUR, 30 * HOUR])]), 'tony').points).toBe(3)+ })++ it('counts approvals and answers in the project\'s Lead conversation, though its work never ships', () => {+ const lead = group({ id: 'lead', ledger: { unblocks: [{ personId: 'ken', at: WEEK + HOUR, waitedMs: 0, kind: 'approval', item: 'm1' }] } })+ expect(person(board(swarm(), [lead]), 'ken')).toMatchObject({ points: 1, unblocked: { count: 1 } })})})-describe('Lent: agent-hours run on a person\'s machines, 1 point per 10', () => {+describe('Lent: busy agent-hours run on a person\'s machines for other people\'s work, 1 point per 10', () => {+ it('leaves out the online hours recorded before only busy hours counted', () => {+ const state = swarm()+ state.machines = [{ ...machine('scholes', []), lent: [{ week: WEEK, agentMs: 40 * HOUR }] }]+ expect(person(board(state, []), 'scholes')).toMatchObject({ points: 0, lent: { machines: 0, agentMs: 0 }, details: { lent: [] } })+ })+it('counts this week\'s agent-hours on every machine the person contributed', () => {const state = swarm()state.machines = [machine('scholes', [[WEEK, 14 * HOUR], [LAST, 50 * HOUR]]), machine('scholes', [[WEEK, 7 * HOUR]], 'gpu'), machine('ken', [[LAST, 40 * HOUR]])]@@ -95,6 +110,59 @@ describe('Lent: agent-hours run on a person\'s machines, 1 point per 10', () =>})})+describe('last week\'s points, names and details', () => {+ it('scores the week before the same way, for the arrow against last week', () => {+ const view = board(swarm(), [shipped('dee', LAST, LAST + HOUR), answered(['dee', LAST + HOUR, 3 * HOUR]), shipped('dee', WEEK, WEEK + HOUR)])+ expect(person(view, 'dee')).toMatchObject({ points: 3, prevWeekPoints: 5 })+ })++ it('names each person by their profile name, else their email\'s local part', () => {+ const view = board(swarm(), [], WEEK, NOW, [], new Map([['dee', 'Dee Tran'], ['tony', ' ']]))+ expect(['dee', 'tony', 'ken'].map(id => person(view, id).displayName)).toEqual(['Dee Tran', 'tony', 'ken'])+ })++ it('lists the week\'s shipped requests, newest first, with their PR and when they landed', () => {+ const older = shipped('dee', WEEK, WEEK + HOUR, { title: 'Offline edits', pullRequestUrls: ['https://github.com/o/r/pull/1', 'https://github.com/o/r/pull/2'] })+ const newer = shipped('dee', WEEK, WEEK + 2 * HOUR, { title: 'Dark mode' })+ const view = board(swarm(), [older, newer, shipped('dee', LAST, LAST + HOUR)])+ expect(person(view, 'dee').details.shipped).toEqual([+ { title: 'Dark mode', prUrl: 'https://github.com/o/r/pull/1', mergedAt: WEEK + 2 * HOUR },+ { title: 'Offline edits', prUrl: 'https://github.com/o/r/pull/2', mergedAt: WEEK + HOUR }])+ })++ it('lists the week\'s unblocks, newest first, with their kind and how long each waited', () => {+ const asked = group({ title: 'Plan', ledger: { unblocks: [{ personId: 'ken', at: WEEK + 2 * HOUR, waitedMs: 90 * 60_000, kind: 'approval', item: 'm' },+ { personId: 'ken', at: LAST, waitedMs: 0, kind: 'decision', item: 'd' }] } })+ // An answer recorded before kinds were kept was an answer to waiting work.+ const old = group({ title: 'Flag', ledger: { unblocks: [{ personId: 'ken', at: WEEK + HOUR, waitedMs: 20_000 }] } })+ expect(person(board(swarm(), [asked, old]), 'ken').details.unblocked).toEqual([+ { title: 'Plan', conversationId: asked.id, kind: 'approval', waitedMinutes: 90 },+ { title: 'Flag', conversationId: old.id, kind: 'needs_human', waitedMinutes: 0 }])+ })++ it('lists each machine\'s busy hours this week, busiest first', () => {+ const state = swarm()+ state.machines = [machine('scholes', [[WEEK, 2.25 * HOUR]], 'Studio'), machine('scholes', [[WEEK, 14 * HOUR], [LAST, 5 * HOUR]], 'GPU box'),+ machine('scholes', [[LAST, 5 * HOUR]], 'Laptop')]+ expect(person(board(state, []), 'scholes').details.lent).toEqual([{ machineName: 'GPU box', busyHours: 14 }, { machineName: 'Studio', busyHours: 2.3 }])+ })++ it('keeps each list to the 20 newest', () => {+ const many = Array.from({ length: 25 }, (_, i) => shipped('dee', WEEK, WEEK + i * 60_000, { title: `R${i}` }))+ const answers = answered(...Array.from({ length: 25 }, (_, i): [string, number, number] => ['dee', WEEK + i * 60_000, 0]))+ const { details } = person(board(swarm(), [...many, answers]), 'dee')+ expect(details.shipped.map(s => s.title)).toEqual(Array.from({ length: 20 }, (_, i) => `R${24 - i}`))+ expect(details.unblocked).toHaveLength(20)+ })++ it('shows only what is in the groups the reader may read, never a private conversation\'s', () => {+ const secret = shipped('dee', WEEK, WEEK + HOUR, { title: 'Secret', audience: { people: [{ id: 'dee', generation: 'g' }] } })+ const chat = group({ title: 'Chat', audience: { people: [{ id: 'ken', generation: 'g' }] },+ ledger: { unblocks: [{ personId: 'ken', at: WEEK + HOUR, waitedMs: 0, kind: 'tag_reply', item: 't' }] } })+ expect(JSON.stringify(board(swarm(), [secret, chat]))).not.toMatch(/Secret|Chat/)+ })+})+describe('ranking and medals', () => {it('ranks by points with medals for the top three, ties sharing a place', () => {const view = board(swarm(), [shipped('ken', WEEK, WEEK + HOUR), shipped('ken', WEEK, WEEK + HOUR), shipped('dee', WEEK, WEEK + HOUR),diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.tsindex 55ec4c6ee..01261ab8b 100644--- a/backend/src/superTabs/leaderboard/stats.ts+++ b/backend/src/superTabs/leaderboard/stats.ts@@ -1,21 +1,26 @@/*** The leaderboard of one project and week (docs/swarms.md, Leaderboard): three numbers per person, Shipped, Unblocked and- * Lent, their points, a shipping streak, the team goal, and who agents wait on now. Pure: the read decides who may see it and- * hands in only the groups that reader may read. Private conversations are left out here too.+ * Lent, their points against last week's, what they are made of, a shipping streak, the team goal, and who agents wait on+ * now. Pure: the read decides who may see it and hands in only the groups that reader may read. Private conversations are+ * left out here too.*/import type { ContributedMachine } from '../machines.js'import { isLeads, type Conversation, type SuperTabState } from '../model.js'import { canReadProject, projectOf } from '../projects.js'-import { waitedOn, waitsNow } from './record.js'+import { waitedOn, waitsNow, type Unblock } from './record.js'import { DAY_MS, WEEK_MS } from './week.js'-import type { Leaderboard, Medal, ModelShare, PersonScore, WeekGoal } from './contract.js'+import type { Leaderboard, Medal, ModelShare, PersonDetails, PersonScore, WeekGoal } from './contract.js'export const SHIPPED_POINTS = 3export const UNBLOCK_POINTS = 1const HOUR_MS = 3_600_000-/** One more point per this many agent-hours an answer freed, and per this many agent-hours lent. */+/** One more point per this many hours an item waited, up to UNBLOCK_MAX_WAIT_POINTS more: an answer is worth a ship at most+ * (Lead's ruling, 2026-10-28). One point per this many busy agent-hours lent. */export const UNBLOCK_HOURS_PER_POINT = 2+export const UNBLOCK_MAX_WAIT_POINTS = 2export const LENT_HOURS_PER_POINT = 10+/** Each details list keeps the newest this many. */+export const DETAILS_LIMIT = 20const MEDALS: Medal[] = ['gold', 'silver', 'bronze']export interface LeaderboardInput {@@ -28,32 +33,44 @@ export interface LeaderboardInput {/** The Monday 00:00 UTC the week starts (week.ts). */week: numbernow: number+ /** People's profile names by id, read with the board (read.ts profileNames); absent ones go by their email. */+ names?: ReadonlyMap<string, string>}-export function leaderboard({ state, groups, machines: visibleMachines, projectId, week, now }: LeaderboardInput): Leaderboard {+export function leaderboard({ state, groups, machines: visibleMachines, projectId, week, now, names }: LeaderboardInput): Leaderboard {const project = projectOf(state, projectId)- const shared = groups.filter(g => !isLeads(g) && !g.audience && (g.projectId ?? 'lead') === projectId && g.id !== project.leadConversationId)+ // The Lead conversation is where plans are approved: its answers count, though nothing there is a request that ships.+ const visible = groups.filter(g => !isLeads(g) && !g.audience && (g.projectId ?? 'lead') === projectId)+ const shared = visible.filter(g => g.id !== project.leadConversationId)const requests = shared.filter(g => !g.reviewOf)const landed = requests.filter(g => g.requesterId && g.ledger?.shippedAt != null && (g.pullRequestUrls?.length ?? 0) > 0)const players = state.people.filter(p => canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project))const inWeek = (at: number, start = week) => at >= start && at < start + 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 answersBy = byKey(shared.flatMap(g => g.ledger?.unblocks ?? []), u => u.personId)+ const answersBy = byKey(visible.flatMap(group => (group.ledger?.unblocks ?? []).map(unblock => ({ ...unblock, group }))), u => u.personId)const machinesBy = byKey(visibleMachines, m => m.contributorId)const score = (personId: string, start: number) => {const shippedHere = (landedBy.get(personId) ?? []).filter(g => inWeek(g.ledger!.shippedAt!, start))const answers = (answersBy.get(personId) ?? []).filter(u => inWeek(u.at, start))const machines = (machinesBy.get(personId) ?? [])- .map(m => m.lent?.find(l => l.week === start)?.agentMs ?? 0).filter(ms => ms > 0)- const freedMs = sum(answers.map(u => u.waitedMs)), lentMs = sum(machines)- const points = shippedHere.length * SHIPPED_POINTS + answers.length * UNBLOCK_POINTS- + Math.floor(freedMs / (UNBLOCK_HOURS_PER_POINT * HOUR_MS)) + Math.floor(lentMs / (LENT_HOURS_PER_POINT * HOUR_MS))+ .map(m => ({ name: m.name, busyMs: m.lent?.find(l => l.week === start)?.busyMs ?? 0 })).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 details: PersonDetails = {+ shipped: newest(shippedHere, g => g.ledger!.shippedAt!)+ .map(g => ({ title: g.title, prUrl: g.pullRequestUrls!.at(-1)!, mergedAt: g.ledger!.shippedAt! })),+ unblocked: newest(answers, u => u.at)+ .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 })),+ }return {points,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 },+ details,}}const goal = (start: number): WeekGoal => {@@ -61,12 +78,13 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectIreturn { shipped: shippedHere.length, points: sum(players.map(p => score(p.id, start).points)), medianAskToShipMs: median(askToShip(shippedHere)) }}const today = Math.floor(Math.min(now, week + WEEK_MS - 1) / DAY_MS)- const scored = players.map(p => ({ personId: p.id, email: p.email, ...score(p.id, week),+ const scored = players.map(p => ({ personId: p.id, email: p.email, displayName: names?.get(p.id)?.trim() || p.email.split('@')[0]!,+ ...score(p.id, week), prevWeekPoints: score(p.id, week - WEEK_MS).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))- const people: PersonScore[] = scored.map(({ email: _email, ...entry }) => {+ const people: PersonScore[] = scored.map(({ email: _email, details, ...entry }) => {const rank = 1 + scored.filter(other => other.points > entry.points).length- return { ...entry, rank, medal: entry.points > 0 ? MEDALS[rank - 1] ?? null : null }+ return { ...entry, rank, medal: entry.points > 0 ? MEDALS[rank - 1] ?? null : null, details }})return {projectId, week,@@ -77,6 +95,11 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI}}+/** One point per answer, and more the longer its item waited, capped. */+const unblockPoints = (unblock: Unblock): number =>+ UNBLOCK_POINTS + Math.min(UNBLOCK_MAX_WAIT_POINTS, Math.floor(unblock.waitedMs / (UNBLOCK_HOURS_PER_POINT * HOUR_MS)))+const newest = <T>(items: T[], at: (item: T) => number): T[] => [...items].sort((a, b) => at(b) - at(a)).slice(0, DETAILS_LIMIT)+/** The attempts started in the week starting [start], by the kind of model they ran on. */function modelShare(requests: Conversation[], start: number): ModelShare {const runs = requests.flatMap(g => g.ledger?.runs ?? []).filter(r => r.at >= start && r.at < start + WEEK_MS)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 3398b9875..94a10fdc6 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -29,7 +29,7 @@ export interface ContributedMachine {* the host says it cleaned up (machine.cleaned) or REMOVAL_FALLBACK_MS passes. An offline one leaves the list at once and* its cleanup waits for its host (expireRemovals). */removal?: { id: string; state: 'cleaning'; requestedAt: string }- /** Agent-time Swarm agents ran here, by leaderboard week, kept by its readings (leaderboard/lent.ts). */+ /** Agent-time Swarm agents here spent on other people's tasks, by leaderboard week, kept by its readings (leaderboard/lent.ts). */lent?: import('./leaderboard/lent.js').LentWeek[]}/** A removed machine whose host never acknowledged in time: its records are gone, its host still cleans up on its next poll. */diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex 2f0d46f52..ae76b9959 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -51,6 +51,14 @@ export async function resolveByReply(tx: Tx, tabId: string, conversationId: stridata: { resolvedAt: new Date(now), resolvedBy: 'reply' } })}+/** The tags a person's post in this conversation is about to answer (resolveByReply), for the leaderboard's credit+ * (leaderboard/record.ts recordPost): only which message and when. */+export async function openTags(tx: Tx, tabId: string, conversationId: string, personId: string, now: number): Promise<Array<{ messageId: string; createdAt: number }>> {+ const rows = await tx.superTabMention.findMany({ where: { tabId, conversationId, personId, createdAt: { gt: new Date(now - MENTION_EXPIRY_MS), lte: new Date(now) },+ ...waiting }, select: { messageId: true, createdAt: true } })+ return rows.map(row => ({ messageId: row.messageId, createdAt: row.createdAt.getTime() }))+}+export async function readMention(tx: Tx, tabId: string, id: string): Promise<MentionTarget | undefined> {return await tx.superTabMention.findFirst({ where: { id, tabId }, select: { id: true, personId: true, conversationId: true } }) ?? undefined}diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 38af63dd5..1d8bf6557 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -15,7 +15,7 @@ import type { SwarmParts } from '../parts/index.js'import { canReadGroup, readProject } from '../projects.js'import { workspacesRequired } from '../workspaceStore.js'import type { Leaderboard } from '../leaderboard/contract.js'-import { readableWeek, recentDormantGroups } from '../leaderboard/read.js'+import { profileNames, readableWeek, recentDormantGroups } from '../leaderboard/read.js'import { LEDGER_WEEKS } from '../leaderboard/record.js'import { leaderboard } from '../leaderboard/stats.js'import { WEEK_MS } from '../leaderboard/week.js'@@ -121,7 +121,8 @@ export class SwarmReads {readProject(state, actor, projectId)const dormant = await recentDormantGroups(tx, tabId, projectId, now - LEDGER_WEEKS * WEEK_MS)const groups = [...state.conversations.filter(g => !g.dormant), ...dormant].filter(g => !isLeads(g) && canReadGroup(state, actor, g))- return leaderboard({ state, groups, machines: visibleState(state, actor, now).machines ?? [], projectId, week: start, now })+ const names = await profileNames(tx, state.people.map(p => p.id))+ return leaderboard({ state, groups, machines: visibleState(state, actor, now).machines ?? [], projectId, week: start, now, names })})}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 69e4ed466..89e202326 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -38,7 +38,7 @@ import { endedHolds, HOLDING, type WorkHold } from '../github/holds.js'import { accrueLent } from './leaderboard/lent.js'import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, type TerminalEffect } from './terminal.js'import { closeAssignment, closeUnassignedStart, readDecision, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'-import { listMentions, markDone, mentionsWaiting, readMention, resolveByReply, writeMentions } from './mentions.js'+import { listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, writeMentions } from './mentions.js'import { answerable, fullFor, listDecisions, readAskedDecision, recordAnswer, waitingIn, waitingInProject, writeDecisions } from './decisions.js'import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,@@ -818,8 +818,9 @@ export class SuperTabStore {}if (command.type === 'message.send' && command.replyTo) {const reply = await tx.superTabMessage.findFirst({ where: { id: command.replyTo, tabId, conversationId: command.conversationId } })- if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author }+ if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author, createdAt: reply.createdAt.getTime() }}+ if (command.type === 'message.send' && actor.kind === 'person') context.openTags = await openTags(tx, tabId, command.conversationId, actor.userId, context.now)if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy') && command.askedIn) {const asked = await tx.superTabMessage.findFirst({ where: { id: command.askedIn.messageId, tabId, conversationId: command.askedIn.conversationId } })if (asked) context.askedIn = { author: asked.author as unknown as Author, source: !!asked.source, createdAt: asked.createdAt.getTime() }diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex 1c7822c8d..5da52257e 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -980,7 +980,7 @@ describe('Swarm cards', () => {])})- it('says which Swarm project the window has open: only on a Swarm tab that names one, with the device mark', () => {+ it('says which Swarm project the window has open: only on a Swarm tab, with the device mark, and no project as none', () => {const host = new DaemonCableHost(wiring())expect(host.activeSwarmProject()).toBeNull() // no windowconst swarms = [@@ -994,8 +994,10 @@ describe('Swarm cards', () => {expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: 'p1', fromDevice: false })host.setSwarms({ active: 't2', swarms, tiles: [], fromDevice: true })expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: 'p1', fromDevice: true })+ // The Swarm tab on its Chat with PM or a DM: still that Swarm, with no project of its own (Diego, 2026-10-28:+ // the dial sat on "Nothing on this tab" while the window showed the Swarm).host.setSwarms({ active: 't3', swarms, tiles: [] })- expect(host.activeSwarmProject()).toBeNull()+ expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: '', fromDevice: false })})it('hands the wiring what a device asks, and answers nothing when the wiring has none', async () => {diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 5709098a6..70276564f 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -439,11 +439,15 @@ export class DaemonCableHost implements CableHost {this.wiring.superTabSelected?.(superTabId, projectId)}- /** The active tab when it is a Swarm with an open project; `fromDevice` when the announce was a device's own pick. */+ /**+ * The active tab when it is a Swarm, with its open project or '' when none is (its Chat with PM, a DM, or a Swarm+ * not loaded yet); `fromDevice` when the announce was a device's own pick. A Swarm tab with no project used to read+ * as no Swarm at all, and the dial stayed on "Nothing on this tab" while the window showed the Swarm.+ */activeSwarmProject(): { superTabId: string; projectId: string; fromDevice: boolean } | null {const app = this.swarmsconst tab = app?.swarms.find((s) => s.id === app.active)- return app && tab?.superTabId && tab.projectId ? { superTabId: tab.superTabId, projectId: tab.projectId, fromDevice: app.fromDevice === true } : null+ return app && tab?.superTabId ? { superTabId: tab.superTabId, projectId: tab.projectId ?? '', fromDevice: app.fromDevice === true } : null}selectSwarm(swarmId: string): void {diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex 10a482842..b90659a76 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -3969,6 +3969,77 @@ describe('swarm cards', () => {} finally { await session.stop() }})+ it('a Swarm tab with no project open still takes the dial into that Swarm: a focus with no Lead, again after away and back', async () => {+ const state = { cards: [card('st1')], open: null as { superTabId: string; projectId: string; fromDevice: boolean } | null }+ const { session, port } = await connect(cardHost(state))+ try {+ port.say(PRO)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ state.open = { superTabId: 'st1', projectId: '', fromDevice: false }+ await session.syncSwarmCards(true)+ expect(ofType(port, 'supertab.focus')).toEqual([{ t: 'supertab.focus', tab: 'st1', lead: '' }])+ void session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 450))+ expect(ofType(port, 'supertab.focus')).toHaveLength(1) // the same Swarm: not again+ state.open = null+ void session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 450))+ state.open = { superTabId: 'st1', projectId: '', fromDevice: false }+ void session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.focus')).toHaveLength(2), NEXT_TICKS)+ // A project opened on it later is a change, and names its Lead.+ state.open = { superTabId: 'st1', projectId: 'proj2', fromDevice: false }+ void session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.focus')).toHaveLength(3), NEXT_TICKS)+ expect(ofType(port, 'supertab.focus')[2]).toEqual({ t: 'supertab.focus', tab: 'st1', lead: 'lead2' })+ } finally { await session.stop() }+ })++ it('a Swarm the list does not hold yet sends no focus at all, and is entered when it arrives', async () => {+ const state = { cards: [] as SwarmCard[], open: { superTabId: 'st1', projectId: '', fromDevice: false } }+ const { session, port } = await connect(cardHost(state))+ try {+ port.say(PRO)+ await vi.waitFor(() => expect(ofType(port, 'supertabs')).toHaveLength(1))+ expect(ofType(port, 'supertab.focus')).toEqual([])+ state.cards = [card('st1')]+ void session.syncSwarmCards()+ await vi.waitFor(() => expect(ofType(port, 'supertab.focus')).toEqual([{ t: 'supertab.focus', tab: 'st1', lead: '' }]), NEXT_TICKS)+ } finally { await session.stop() }+ })++ it('logs why each Swarm focus was or was not sent, once per change', async () => {+ const lines: string[] = []+ const state = { cards: [] as SwarmCard[], open: null as { superTabId: string; projectId: string; fromDevice: boolean } | null }+ const { session, port } = await connect(cardHost(state, { log: (l) => lines.push(l) }))+ const focusLines = () => lines.filter((l) => l.startsWith('cable: swarm focus'))+ try {+ port.say(PRO)+ await vi.waitFor(() => expect(ofType(port, 'supertabs')).toHaveLength(1))+ expect(focusLines()).toEqual(['cable: swarm focus · not a Swarm tab'])+ state.open = { superTabId: 'st1', projectId: 'proj2', fromDevice: false }+ await session.syncSwarmCards(true)+ await session.syncSwarmCards(true) // the same answer again is not logged again+ expect(focusLines()).toEqual(['cable: swarm focus · not a Swarm tab', 'cable: swarm focus st1/proj2 · held: no such Swarm in the list'])+ state.cards = [card('st1', [lead(1)])]+ await session.syncSwarmCards(true)+ expect(focusLines().at(-1)).toBe('cable: swarm focus st1/proj2 · held: no Lead for that project')+ state.cards = [card('st1')]+ await session.syncSwarmCards(true)+ expect(focusLines().at(-1)).toBe('cable: swarm focus st1/proj2 → lead2')+ void session.syncSwarmCards()+ await new Promise((r) => setTimeout(r, 450))+ expect(focusLines().at(-1)).toBe('cable: swarm focus st1/proj2 · already sent')+ state.open = { superTabId: 'st1', projectId: '', fromDevice: false }+ await session.syncSwarmCards(true)+ expect(focusLines().at(-1)).toBe('cable: swarm focus st1 (no project) → its Leads')+ state.open = null+ await session.syncSwarmCards(true)+ expect(focusLines().at(-1)).toBe('cable: swarm focus · not a Swarm tab')+ expect(focusLines()).toHaveLength(7)+ } finally { await session.stop() }+ })+it('a project the list does not hold yet is followed when the list arrives', async () => {const state = { cards: [] as SwarmCard[], open: { superTabId: 'st1', projectId: 'proj1', fromDevice: false } }const { session, port } = await connect(cardHost(state))diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 7dce3b577..c1fc08316 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -347,7 +347,7 @@ export interface CableHost {swarmSay?(harnessId: string, text: string): Promise<boolean>/** A device picked a Lead: the window opens that Swarm tab and project. */superTabSelected?(superTabId: string, projectId: string): void- /** The Swarm tab the window has on screen and the project open in it; null when the active tab is not a Swarm or there is no window. */+ /** The Swarm tab the window has on screen and the project open in it ('' when none is); null when the active tab is not a Swarm or there is no window. */activeSwarmProject?(): { superTabId: string; projectId: string; fromDevice: boolean } | nullappName(): stringvoiceLang(): string@@ -2597,6 +2597,8 @@ export class CableSession {private openLead: { tabId: string; leadId: string } | null = null/** The Swarm project the Pro was last pointed at (or picked itself), so a repeat announce sends nothing. */private focusedKey = ''+ /** The last focus decision logged, so a burst of the same answer is one line. */+ private focusLogged = ''/** This cable session's name for the service, so one Pro closing its recap does not close another's. */private readonly cardSession = `c${++nextCardSession}`/** The project this Pro itself picked last and when: the desktop's announce of it is no news, and a stale one of another is held off. */@@ -2617,6 +2619,7 @@ export class CableSession {this.cardKeys.clear()this.cardIdsKey = ''this.focusedKey = ''+ this.focusLogged = ''this.picked = nullthis.lastRecapGet = nullif (this.openLead) this.host.swarmCardOpen?.(this.cardSession, this.openLead.tabId, null)@@ -2670,21 +2673,41 @@ export class CableSession {await this.pushSwarmFocus()}- /** Point the Pro at the Lead of the project the window has open, once per change and never at its own pick. */+ /**+ * Point the Pro at the Lead of the project the window has open, once per change and never at its own pick. A Swarm tab+ * with no project open (its Chat with PM, a DM) still takes the device into that Swarm: `lead: ''` lets it open on the+ * Lead it last showed there, else its first. A device from before that ignores an empty Lead, as it always has.+ *+ * Every decision is logged, once per change. This used to log nothing, and "the dial stayed on an empty tab" could+ * not be told apart from "no project", "no Lead" or "already sent" from the logs (Diego's dial, 2026-10-28).+ */private async pushSwarmFocus(): Promise<void> {const open = this.host.activeSwarmProject?.()- if (!open) { this.focusedKey = ''; return }+ if (!open) { this.focusedKey = ''; this.logFocus('cable: swarm focus · not a Swarm tab'); return }const key = `${open.superTabId}/${open.projectId}`- if (key === this.focusedKey) return+ const named = open.projectId ? key : `${open.superTabId} (no project)`+ if (key === this.focusedKey) { this.logFocus(`cable: swarm focus ${named} · already sent`); return }// Only the Pro that picked has nothing to follow; every other Pro still goes where the window went.- if (open.fromDevice && this.picked?.key === key) { this.focusedKey = key; return }+ if (open.fromDevice && this.picked?.key === key) { this.focusedKey = key; this.logFocus(`cable: swarm focus ${named} · the device's own pick`); return }// The desktop's announce from before it heard the pick: not where the window is going.- if (!open.fromDevice && this.picked && this.picked.key !== key && Date.now() - this.picked.at < PICK_ECHO_MS) return- const lead = this.host.swarmCards?.().find((c) => c.id === open.superTabId)?.leads.find((l) => l.projectId === open.projectId)+ if (!open.fromDevice && this.picked && this.picked.key !== key && Date.now() - this.picked.at < PICK_ECHO_MS) {+ this.logFocus(`cable: swarm focus ${named} · held: the device just picked another`)+ return+ }// Not in the list yet: asked again when it arrives.- if (!lead) return+ const card = this.host.swarmCards?.().find((c) => c.id === open.superTabId)+ if (!card) { this.logFocus(`cable: swarm focus ${named} · held: no such Swarm in the list`); return }+ const lead = open.projectId ? card.leads.find((l) => l.projectId === open.projectId) : undefined+ if (open.projectId && !lead) { this.logFocus(`cable: swarm focus ${named} · held: no Lead for that project`); return }this.focusedKey = key- await this.send({ t: 'supertab.focus', tab: open.superTabId, lead: lead.id })+ this.logFocus(`cable: swarm focus ${named} → ${lead ? lead.id : 'its Leads'}`)+ await this.send({ t: 'supertab.focus', tab: open.superTabId, lead: lead?.id ?? '' })+ }++ private logFocus(line: string): void {+ if (line === this.focusLogged) return+ this.focusLogged = line+ this.log(line)}/** A Lead's changed text, for the Pro that has that Lead's recap open. */diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.tsindex c68489d43..23f431ec9 100644--- a/cli/src/core/agents/forget.spec.ts+++ b/cli/src/core/agents/forget.spec.ts@@ -3,6 +3,7 @@ import { removePendingCursorTasks } from '../engines/cursorTasks.js'import type { RegisteredSession } from '../../lib/registry.js'import { createForgetSession, type ForgetDeps } from './forget.js'import { createRelaunchMarks } from '../transcripts/relaunch.js'+import { createShortTurnGuard, type ShortTurnGuard } from '../turns/shortTurnGuard.js'// Cursor's queued Tasks are cleared through the core's own door to them (core/engines/cursorTasks.ts).vi.mock('../engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))@@ -13,7 +14,12 @@ function setup() {['s1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],['fresh', { agentId: 'fresh', sessionId: '', engine: 'claude' } as RegisteredSession],])+ // Both sessions held by the short-turn guard: ten back-to-back turns of a second each.+ let at = 0+ const shortTurns = createShortTurnGuard({ now: () => at, log: () => {} })+ for (const session of ['s1', 'other']) for (let i = 0; i < 10; i++) { shortTurns.started(session, session); at += 1_000; shortTurns.ended(session) }const deps: ForgetDeps = {+ shortTurns,registry: { resolve: vi.fn((id: string) => agents.get(id)), unbindSession: vi.fn(() => true), removeAgent: vi.fn(() => true), remove: vi.fn(() => true) },stoppedAgents: { save: vi.fn() },syncRecapPool: vi.fn(),@@ -48,6 +54,9 @@ function expectLetGo(deps: ForgetDeps, sessionId: string, agentId: string) {expect(deps.neverFoldedHistory.has(sessionId)).toBe(false)expect(deps.replayedFirstTurn.has(sessionId)).toBe(false)expect(deps.turnStartedAt.has('other')).toBe(true)+ const shortTurns = deps.shortTurns as ShortTurnGuard+ expect(shortTurns.holding(sessionId)).toBe(0)+ expect(shortTurns.holding('other')).toBeGreaterThan(0)expect(deps.clearAgyIdleWatch).toHaveBeenCalledWith(sessionId)expect(deps.cursorDiscovery.remove).toHaveBeenCalledWith(sessionId)expect(deps.cursorSubagents.forget).toHaveBeenCalledWith(sessionId)diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.tsindex 2961fb886..dc3e604fd 100644--- a/cli/src/core/agents/forget.ts+++ b/cli/src/core/agents/forget.ts@@ -10,6 +10,7 @@ import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.jimport type { CursorSubagentManager } from '../../engines/cursor/subagent.js'import type { AutonomousDeviceInput } from '../deviceInput.js'import type { TurnRecaps } from '../turns/recaps.js'+import type { ShortTurnGuard } from '../turns/shortTurnGuard.js'import { sid } from '../../lib/log.js'import { sameProcessIdentity } from '../../lib/terminalRuntime.js'import type { RegisteredSession, registry } from '../../lib/registry.js'@@ -33,6 +34,8 @@ export interface ForgetDeps {normalizers: Pick<SessionNormalizers, 'forget'>forgetAttach: (sessionId: string) => voidturnStartedAt: Map<string, number>+ /** The short-turn guard's count and hold for each session (turns/shortTurnGuard.ts): gone with the session. */+ shortTurns?: Pick<ShortTurnGuard, 'forget'>/** Each agent's kept prompt (turns/funnel.ts), by agent: gone with the agent. */prompts: Map<string, string>/** Attach's two per-session marks (core/transcripts/attach.ts). */@@ -57,7 +60,7 @@ export interface ForgetDeps {export function createForgetSession({registry, stoppedAgents, syncRecapPool, normalizers, forgetAttach, turnStartedAt, prompts, neverFoldedHistory, replayedFirstTurn, relaunchMarks,clearAgyIdleWatch, cursorDiscovery, cursorSubagents, runtimeProfiles, watcher, stopHeartbeat, input,- deviceInput, detachDsh, mirror, clients, dataDir, onRemoved, owners,+ deviceInput, detachDsh, mirror, clients, dataDir, onRemoved, owners, shortTurns,}: ForgetDeps) {/** Release a mutable session binding, or remove the process-owned agent everywhere. */const forgetSession = (@@ -103,6 +106,7 @@ export function createForgetSession({normalizers.forget(sessionId)forgetAttach(sessionId)turnStartedAt.delete(sessionId)+ shortTurns?.forget(sessionId)neverFoldedHistory.delete(sessionId)// Both sets are per-session and must die with it: left behind they grow without bound in a daemon// that runs for days, and a session forgotten then re-registered under the same id would inherit adiff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex ef0be33cd..8b3bc51db 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -11,6 +11,7 @@ import type { SessionInputDelivery } from '../lib/sessionInput.js'import { TERMINAL_LEASE_REFUSED, type ProcessIdentity, type TerminalActionResult } from '../lib/terminalTypes.js'import { CLAUDE_REWIND_LIST, CODEX_BROWSING_SCROLLBACK } from '../lib/__fixtures__/rewindPickers.js'import { createInput, createMessageRequest, deviceInputDeps, heldScreen, messageWriter, sessionInputDeps, type InputDeps } from './input.js'+import { createShortTurnGuard } from './turns/shortTurnGuard.js'import { createScreens } from './engines/screens.js'import { screenFor } from '../engines/screens.js'import { readerEngine } from '../engines/worker/protocol.js'@@ -136,6 +137,19 @@ describe('the session input controller\'s dependencies', () => {expect(await wired.beforeTeamWrite!(agents.get('a1')!)).toBeNull()})+ it('holds an automatic write to an agent the short-turn guard holds, without reading its pane, until the hold ends', async () => {+ let at = 0+ const shortTurns = createShortTurnGuard({ now: () => at, log: () => {} })+ for (let i = 0; i < 10; i++) { shortTurns.started('s1', 'a1'); at += 1_000; shortTurns.ended('s1') }+ const { deps: given } = deps({ shortTurns })+ const wired = sessionInputDeps(given, () => lock([]))+ expect(await wired.beforeTeamWrite!(agents.get('a1')!, 'team:service:superTabs:d1')).toBe('team_waiting_control')+ expect(given.terminal.captureTerminal).not.toHaveBeenCalled()+ expect(await wired.beforeTeamWrite!(agents.get('cx')!, 'team:service:superTabs:d2')).toBeNull()+ at += 30_000+ expect(await wired.beforeTeamWrite!(agents.get('a1')!, 'team:service:superTabs:d1')).toBeNull()+ })+it('hands the controller the move gate when it was given one, and none otherwise', () => {const { deps: given } = deps()expect('moveGate' in sessionInputDeps(given, () => lock([]))).toBe(false)diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex caaa8de89..2649765e6 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -29,6 +29,7 @@ import type { TerminalControl } from './terminals/control.js'import { launchBound } from './engines/sessionBinding.js'import { inputContextIn } from '../lib/nativeTurnObservations.js'import { teamHold } from '../engines/kit/screen.js'+import type { ShortTurnGuard } from './turns/shortTurnGuard.js'type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }@@ -66,6 +67,8 @@ export interface InputDeps {/** Whether a typed delivery's maker queues it in the engine's own input while the agent works (the Swarm's chat,* superTabs/inCore/deliveries.ts), where the engine takes that; absent, every typed delivery waits for idle. */typesWhileBusy?: (deliveryId: string) => boolean+ /** An agent whose turns keep ending at once has its automatic writes held a while (turns/shortTurnGuard.ts). */+ shortTurns?: Pick<ShortTurnGuard, 'holding'>}/**@@ -165,6 +168,8 @@ export function sessionInputDeps(deliveries.settled(event)},beforeTeamWrite: async (session, deliveryId) => {+ // Before the pane is read: a held agent's Swarm deliveries are asked again every second.+ if (deps.shortTurns?.holding(session.sessionId)) return 'team_waiting_control'const capture = await captureTerminal(session.agentId)const screen = await deps.readScreen(session, capture)return deliveryHold(session, screen, capture, deliveryId)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 195384fee..f22615132 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1,5 +1,6 @@import { realTeamRelayLaunch } from '../team/relay.js'import { createGridAssignments } from './agents/gridAssignments.js'+import { createShortTurnGuard } from './turns/shortTurnGuard.js'import { createQuestionControls } from './engines/questionControls.js'import { masterRunsEngineQuestionControl } from '../harnessd/services.js'import { createModelControls } from './engines/modelControls.js'@@ -1341,8 +1342,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {hermesDb })backend.historyProvider = history.sessionGetbackend.sessionsProvider = history.sessionsList+ // An agent whose turns keep ending at once has its automatic writes held a while (core/turns/shortTurnGuard.ts).+ const shortTurns = createShortTurnGuard({ now: Date.now, log: (line) => console.warn(line) })// Everything the core writes into a pane, and the device's pane lock (core/input.ts).const inputs = createInput({+ shortTurns,// The Swarm's chat is queued in the engine's own input while an agent works (superTabs/inCore/deliveries.ts)....(swarm ? { typesWhileBusy: swarm.typesWhileBusy } : {}),readScreen: screens.read,@@ -1812,6 +1816,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// A live turn, however short and with no input of its own (a /loop wake-up, a background notification), restarts// the agent's quiet period: the mover's ticks alone, seconds apart, would miss it.working: (agentId) => hostQuiet.noteActivity(agentId, 'working'),+ shortTurns,})// Cursor's Task hooks and the sub-agents they start (core/engines/cursorTasks.ts).const cursorTasks = createCursorTaskHooks({ emitSessionEvents, watcher, registry, cursorNormalizers })@@ -1825,6 +1830,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {conversationOwners.settle()const forgetSession = createForgetSession({owners: conversationOwners,+ shortTurns,forgetAttach: attach.forget,onRemoved: (agentId) => forgetRestartRevision(agentId),relaunchMarks,diff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.tsindex c45d5278f..4f85c4afb 100644--- a/cli/src/core/turns/funnel.spec.ts+++ b/cli/src/core/turns/funnel.spec.ts@@ -3,6 +3,7 @@ import { deviceErrorText } from '../cardText.js'import { inlineSubmission } from '../../testing/inlineSubmission.js'import type { RegisteredSession } from '../../lib/registry.js'import { createEventFunnel, funnelFor, outsideConsumers, type FunnelDeps } from './funnel.js'+import { createShortTurnGuard } from './shortTurnGuard.js'type Event = Parameters<ReturnType<typeof funnelFor>>[1][number]const started = (userMessage = 'go'): Event => ({ type: 'turn_started', payload: { userMessage } }) as Event@@ -54,6 +55,17 @@ describe('the event funnel', () => {expect(working).not.toHaveBeenCalled()})+ it('tells the short-turn guard of each live turn start and end, never of a re-read', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ let at = 0+ const shortTurns = createShortTurnGuard({ now: () => at, log: () => {} })+ const { funnel } = setup('claude', { shortTurns })+ for (let i = 0; i < 10; i++) { funnel('s1', [started(), ended()], { replay: true }); funnel('s1', [started(), ended()], { resumed: true }); at += 1_000 }+ expect(shortTurns.holding('s1')).toBe(0)+ for (let i = 0; i < 10; i++) { funnel('s1', [started()]); at += 1_000; funnel('s1', [ended()]) }+ expect(shortTurns.holding('s1')).toBe(30_000)+ })+it('offers native observation after client dispatch without letting an observer break the turn', () => {vi.spyOn(console, 'log').mockImplementation(() => {})vi.spyOn(console, 'error').mockImplementation(() => {})diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.tsindex 4853f5e07..0c2c17288 100644--- a/cli/src/core/turns/funnel.ts+++ b/cli/src/core/turns/funnel.ts@@ -17,6 +17,7 @@ import { isDeviceInputBoundary } from '../deviceInput.js'import type { SubmissionReader } from '../../lib/submissionReader.js'import type { WifiFeed } from '../wifi.js'import type { TurnRecaps } from './recaps.js'+import type { ShortTurnGuard } from './shortTurnGuard.js'import { deviceErrorText } from '../cardText.js'import { preview, sid } from '../../lib/log.js'import type { CursorNormalizer } from '../../engines/cursor/normalizer.js'@@ -65,6 +66,9 @@ export interface FunnelDeps {/** The agent's engine is working now: a live turn start or its progress, never a re-read (the mover's quiet clock,* lib/hostMove/quiet.ts). */working?: (agentId: string) => void+ /** Each live turn's start and end, never a re-read: the short-turn guard holds automatic input to an agent that+ * loops (shortTurnGuard.ts). */+ shortTurns?: Pick<ShortTurnGuard, 'started' | 'ended'>}type OutsideConsumers = (consumer: string, call: () => void) => void@@ -105,7 +109,7 @@ export function outsideConsumers(options: {/** The funnel itself, over what it feeds. */export function funnelFor({bySession, tokenUsage, agentIdFor, turnActivity, isSubagentSession, clients, search, turnStartedAt, prompts, input,- deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, nativeTurns, outside = outsideConsumers(), working,+ deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, nativeTurns, outside = outsideConsumers(), working, shortTurns,}: FunnelDeps) {return (sessionId: string, events: Events, opts?: EmitOptions): void => {if (!events.length || !bySession(sessionId)?.active) return@@ -116,6 +120,8 @@ export function funnelFor({const replay = !!(opts?.resumed || opts?.replay)turnActivity.observe(sessionId, event.type, replay)if (!replay && isProgressEvent(event.type)) working?.(agentId)+ if (!replay && event.type === 'turn_started') shortTurns?.started(sessionId, agentId)+ else if (!replay && event.type === 'turn_ended') shortTurns?.ended(sessionId)const frame = correlateAgentEvent({ ...event, payload: { ...event.payload, activity: turnActivity.snapshot(sessionId) } }, sessionId, agentId)// A `turn_started` that is not a turn starting NOW — a turn picked back up at attach, or a prompt// re-read from a transcript that was already on disk — says so in the clear, beside `agentId`diff --git a/cli/src/core/turns/shortTurnGuard.spec.ts b/cli/src/core/turns/shortTurnGuard.spec.tsnew file mode 100644index 000000000..3b3dbf3ab--- /dev/null+++ b/cli/src/core/turns/shortTurnGuard.spec.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from 'vitest'+import { createShortTurnGuard } from './shortTurnGuard.js'++function setup() {+ let at = 1_000_000+ const lines: string[] = []+ const guard = createShortTurnGuard({ now: () => at, log: (line) => lines.push(line) })+ const wait = (ms: number) => { at += ms }+ /** One turn of [ms], started [gap] ms after the last one ended. */+ const turn = (session: string, ms: number, gap = 500) => {+ wait(gap); guard.started(session, `agent-${session}`); wait(ms); guard.ended(session)+ }+ const turns = (session: string, count: number, ms = 2_000, gap = 500) => { for (let i = 0; i < count; i++) turn(session, ms, gap) }+ return { guard, lines, wait, turn, turns }+}++describe('short-turn guard', () => {+ it('holds an agent after ten back-to-back turns under 10 s, and says so once', () => {+ const { guard, lines, turns } = setup()+ turns('s1', 10)+ expect(guard.holding('s1')).toBe(30_000)+ expect(lines).toEqual(['[turn-guard] loop session=s1 agent=agent-s1 turns=10 hold=30s'])+ })++ it('does not hold after nine', () => {+ const { guard, lines, turns } = setup()+ turns('s1', 9)+ expect(guard.holding('s1')).toBe(0)+ expect(lines).toEqual([])+ })++ it('a turn of 10 s or more starts the count again', () => {+ const { guard, turn, turns } = setup()+ turns('s1', 9)+ turn('s1', 10_000)+ turns('s1', 9)+ expect(guard.holding('s1')).toBe(0)+ })++ it('a pause of 10 s or more between turns starts the count again', () => {+ const { guard, turn, turns } = setup()+ turns('s1', 9)+ turn('s1', 2_000, 10_000)+ turns('s1', 8)+ expect(guard.holding('s1')).toBe(0)+ turn('s1', 2_000)+ expect(guard.holding('s1')).toBe(30_000)+ })++ it('counts each agent apart', () => {+ const { guard, turns } = setup()+ turns('s1', 5)+ turns('s2', 5)+ expect(guard.holding('s1')).toBe(0)+ expect(guard.holding('s2')).toBe(0)+ })++ it('the hold runs out, and a loop that goes on doubles it up to 30 minutes', () => {+ const { guard, lines, wait, turns } = setup()+ turns('s1', 10)+ wait(29_000)+ expect(guard.holding('s1')).toBe(1_000)+ wait(1_000)+ expect(guard.holding('s1')).toBe(0)+ const holds: number[] = []+ for (let i = 0; i < 8; i++) {+ turns('s1', 10)+ holds.push(guard.holding('s1'))+ wait(guard.holding('s1'))+ }+ expect(holds).toEqual([60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000, 1_800_000])+ expect(lines.at(-1)).toBe('[turn-guard] loop session=s1 agent=agent-s1 turns=10 hold=1800s')+ })++ it('a normal turn lifts the hold and the backoff', () => {+ const { guard, turn, turns } = setup()+ turns('s1', 10)+ turn('s1', 15_000)+ expect(guard.holding('s1')).toBe(0)+ turns('s1', 10)+ expect(guard.holding('s1')).toBe(30_000)+ })++ it('an end with no start counts nothing', () => {+ const { guard, wait } = setup()+ for (let i = 0; i < 20; i++) { wait(100); guard.ended('s1') }+ expect(guard.holding('s1')).toBe(0)+ })++ it('forgets an agent that ended, and keeps the others', () => {+ const { guard, turns } = setup()+ turns('s1', 10)+ turns('s2', 10)+ guard.forget('s1')+ expect(guard.holding('s1')).toBe(0)+ expect(guard.size).toBe(1)+ expect(guard.holding('s2')).toBeGreaterThan(0)+ })++ it('an agent that keeps turning is never the oldest, however many others come', () => {+ const { guard, turns } = setup()+ turns('looping', 10)+ for (let i = 0; i < 999; i++) turns(`other-${i}`, 1)+ turns('looping', 1)+ turns('newest', 1)+ expect(guard.size).toBe(1_000)+ // Still remembered: its next hold doubles rather than starting again at 30 s.+ turns('looping', 9)+ expect(guard.holding('looping')).toBe(60_000)+ })++ it('keeps at most 1000 agents, forgetting the oldest', () => {+ const { guard, turns } = setup()+ turns('first', 10)+ for (let i = 0; i < 1_000; i++) turns(`other-${i}`, 1)+ expect(guard.size).toBe(1_000)+ expect(guard.holding('first')).toBe(0)+ })+})diff --git a/cli/src/core/turns/shortTurnGuard.ts b/cli/src/core/turns/shortTurnGuard.tsnew file mode 100644index 000000000..541af7e18--- /dev/null+++ b/cli/src/core/turns/shortTurnGuard.ts@@ -0,0 +1,76 @@+/**+ * The short-turn guard: an agent whose turns keep ending in seconds and starting again at once is held from+ * automatic input for a while, so no path that types into it on its own can loop.+ *+ * Diego's daily report, 2026-10-28: 106k turns in a day against 1.2k–4.9k a day the week before, 104.5k of them+ * under 10 s, from a few macOS computers. The paths that type into an agent on their own (Swarm messages, Agent+ * Messages) each send once per message, but nothing stopped them typing again and again into an agent whose+ * every turn ends at once. Ten turns in a row, each under 10 s and starting within 10 s of the one before, is not a+ * person's pace: the agent's automatic input is held for 30 s, doubling while it goes on, up to 30 minutes. A turn+ * of 10 s or more lifts it. A person's input is never held.+ *+ * The log line has one fixed shape, so the prod watch can count it by session and agent.+ */+import { sid } from '../../lib/log.js'++export const SHORT_TURN_MS = 10_000+export const LOOP_TURNS = 10+const HOLD_FIRST_MS = 30_000+const HOLD_MAX_MS = 30 * 60_000+/** Sessions remembered; past it the one that turned least recently is forgotten. A daemon runs tens of agents, and a+ * session that ends is forgotten with the rest of its state (agents/forget.ts), so this is only the backstop. */+const KEPT = 1_000++interface Turns { agentId: string; startedAt?: number; endedAt?: number; streak: number; trips: number; holdUntil: number }++export interface ShortTurnGuardDeps {+ now: () => number+ log: (line: string) => void+}++export function createShortTurnGuard({ now, log }: ShortTurnGuardDeps) {+ const sessions = new Map<string, Turns>()+ return {+ get size(): number { return sessions.size },++ /** A turn started now (never a replayed one). */+ started(sessionId: string, agentId: string): void {+ // Moved to the newest end: an agent still turning, a looping one above all, is never the one forgotten.+ const turns = sessions.get(sessionId) ?? { agentId, streak: 0, trips: 0, holdUntil: 0 }+ sessions.delete(sessionId)+ sessions.set(sessionId, turns)+ if (sessions.size > KEPT) sessions.delete(sessions.keys().next().value!)+ turns.agentId = agentId+ // Not back to back: the count starts again, the backoff stays (a held agent's pause is its hold).+ if (turns.endedAt === undefined || now() - turns.endedAt >= SHORT_TURN_MS) turns.streak = 0+ turns.startedAt = now()+ },++ ended(sessionId: string): void {+ const turns = sessions.get(sessionId)+ if (turns?.startedAt === undefined) return+ const lasted = now() - turns.startedAt+ turns.startedAt = undefined+ turns.endedAt = now()+ if (lasted >= SHORT_TURN_MS) { turns.streak = 0; turns.trips = 0; turns.holdUntil = 0; return }+ if (++turns.streak < LOOP_TURNS) return+ const hold = Math.min(HOLD_MAX_MS, HOLD_FIRST_MS * 2 ** turns.trips++)+ turns.holdUntil = now() + hold+ turns.streak = 0+ log(`[turn-guard] loop session=${sid(sessionId)} agent=${sid(turns.agentId)} turns=${LOOP_TURNS} hold=${hold / 1000}s`)+ },++ /** The session ended: its turns and any hold go with it. */+ forget(sessionId: string): void {+ sessions.delete(sessionId)+ },++ /** How long automatic input to the agent is still held, in ms; 0 when it is not. */+ holding(sessionId: string): number {+ const turns = sessions.get(sessionId)+ return turns ? Math.max(0, turns.holdUntil - now()) : 0+ },+ }+}++export type ShortTurnGuard = ReturnType<typeof createShortTurnGuard>diff --git a/cli/src/services/sharedMachines.spec.ts b/cli/src/services/sharedMachines.spec.tsindex dd5cf3602..b2e18206f 100644--- a/cli/src/services/sharedMachines.spec.ts+++ b/cli/src/services/sharedMachines.spec.ts@@ -213,6 +213,27 @@ describe('shared machines', () => {expect(port.trust).toHaveBeenLastCalledWith({ pins: [], keys: [{ ...ann.machines[0], label: 'Machine · [email protected]', email: '[email protected]' }] })})+ it('keeps what the backend holds after telling it again, so an address it drops is written once and then left alone', async () => {+ // The backend never holds the owner's own address. Kept here, it read back as a different policy at every+ // read, so the daemon wrote it again every two minutes and each write told every member's apps to re-read.+ writeFileSync(file, JSON.stringify({ emails: ['[email protected]', '[email protected]'], sameDomain: false }))+ let held: string[] = []+ const port = fakePort({+ policy: vi.fn(async () => policy({ emails: held })),+ publish: vi.fn(async (emails: string[], sameDomain: boolean) => {+ held = emails.filter((e) => e !== '[email protected]')+ return policy({ emails: held, sameDomain })+ }),+ })+ start(port)+ await fire()+ expect(port.publish).toHaveBeenCalledExactlyOnceWith(['[email protected]', '[email protected]'], false)+ expect(readPolicy(file).emails).toEqual(['[email protected]'])+ await fire()+ await fire()+ expect(port.publish).toHaveBeenCalledOnce()+ })+it('changes only what it could read, and nothing when it read nothing', async () => {const port = fakePort({ shared: vi.fn(async () => down), policy: vi.fn(async () => down) })start(port)diff --git a/cli/src/services/sharedMachines.ts b/cli/src/services/sharedMachines.tsindex 04d0b1c86..4c0adf7e0 100644--- a/cli/src/services/sharedMachines.ts+++ b/cli/src/services/sharedMachines.ts@@ -214,11 +214,15 @@ export function startSharedMachines(core: CoreApi, overrides: Partial<SharedMach}let remote = await port.policy()// The backend is told again what this machine holds, whenever it says otherwise (a write that failed,- // a backend that lost it, the owner's domain now public).+ // a backend that lost it, the owner's domain now public). What it then holds is kept here, as `set` keeps it:+ // it drops an address it never shares with (the owner's own), and a policy still naming one read back as+ // different at every read, so it was written again every two minutes and each write had every member's+ // apps re-read their machines (Diego's, every 1 to 3 minutes, 2026-10-28).if (!failed(remote) && !samePolicy(local, remote)) {- const sameDomain = local.sameDomain && !!remote.domain- remote = await port.publish(local.emails, sameDomain)- if (!failed(remote) && sameDomain !== local.sameDomain) writePolicy(deps.file, { ...local, sameDomain })+ remote = await port.publish(local.emails, local.sameDomain && !!remote.domain)+ if (!failed(remote) && !samePolicy(local, remote)) {+ writePolicy(deps.file, { ...local, emails: remote.emails, sameDomain: remote.sameDomain })+ }}if (!failed(remote)) desired.keys = shares(local) ? trustedKeys(local, remote) : []if (desired.pins || desired.keys) {diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex 65e2d3179..2a15ae996 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -50,12 +50,16 @@ class ApiClient {final LocalDaemonTransport? localTransport;late final Dio _dio = _buildDio();+ /// The time, for when harness shares are read again ([sharesReadInterval], [sharesRetryDelays]).+ final DateTime Function() _clock;+ApiClient({required this.config,required this.session,this.auth,this.localTransport,- });+ DateTime Function()? clock,+ }) : _clock = clock ?? DateTime.now;Dio _buildDio() {final dio = attachHttpLog(@@ -698,12 +702,52 @@ class ApiClient {int _accountRevision = 0;int _machineRequestRevision = 0;+ /// How long a read of `/api/harness-shares` stands for, unless a push says they changed+ /// ([sharesChanged]). Read through this computer's daemon, it took 14 to 16 s, or failed with a 504+ /// after 20 s, on Diego's app (2026-10-28), where every `machines_changed` (one every 1 to 3 minutes,+ /// each four times) started another.+ static const sharesReadInterval = Duration(minutes: 5);++ /// How long a failed shares read waits before the next, the last shares read standing in meanwhile:+ /// a failure that only marked the list stale was read again at once, by recovery and the next push.+ static const sharesRetryDelays = [+ Duration(minutes: 1),+ Duration(minutes: 2),+ Duration(minutes: 5),+ ];++ /// When the last shares read that answered started; null while none has for this account.+ DateTime? _sharesReadAt;+ int _sharesFailures = 0;+ DateTime? _sharesRetryAt;++ /// Pushes saying the shares changed, and how many of them the last answered read covers.+ int _sharesAsked = 0;+ int _sharesAnswered = 0;++ /// A push said a harness shared with this account was invited or taken back: the next machine+ /// read reads the shares too, once any wait after a failure is over.+ void sharesChanged() => _sharesAsked++;++ bool _sharesDue(DateTime now) {+ final retryAt = _sharesRetryAt;+ if (retryAt != null && now.isBefore(retryAt)) return false;+ final readAt = _sharesReadAt;+ return readAt == null ||+ _sharesAsked > _sharesAnswered ||+ now.difference(readAt) >= sharesReadInterval;+ }+/// Sharing fallback belongs to the account that loaded it. Late responses/// must not refill it after sign-out or while a new sign-in is starting.void resetAccountCache() {++_accountRevision;_sharedMachines = [];lastMachinesStale = false;+ _sharesReadAt = null;+ _sharesRetryAt = null;+ _sharesFailures = 0;+ _sharesAnswered = _sharesAsked;}void _requireAccount(int revision) {@@ -730,22 +774,38 @@ class ApiClient {Machine.fromJson(Map<String, dynamic>.from(row as Map)),].where((m) => !owned.any((own) => own.machineId == m.machineId)).toList();var sharedMachines = _sharedMachines;- try {- final shared = await _dio.get('/api/harness-shares');- _requireAccount(account);- if (shared.statusCode == 404) {- sharedMachines = [];- } else {- final body = unwrapApiResponse(shared) as Map<String, dynamic>;- sharedMachines = [- for (final row in body['machines'] as List? ?? const [])- Machine.fromJson(Map<String, dynamic>.from(row as Map)),- ];+ final now = _clock();+ if (_sharesDue(now)) {+ final asked = _sharesAsked;+ try {+ final shared = await _dio.get('/api/harness-shares');+ _requireAccount(account);+ if (shared.statusCode == 404) {+ sharedMachines = [];+ } else {+ final body = unwrapApiResponse(shared) as Map<String, dynamic>;+ sharedMachines = [+ for (final row in body['machines'] as List? ?? const [])+ Machine.fromJson(Map<String, dynamic>.from(row as Map)),+ ];+ }+ _sharesReadAt = now;+ _sharesAnswered = asked;+ _sharesFailures = 0;+ _sharesRetryAt = null;+ } catch (error) {+ if (isUnauthorizedError(error)) rethrow;+ _requireAccount(account);+ final delay =+ sharesRetryDelays[_sharesFailures < sharesRetryDelays.length+ ? _sharesFailures+ : sharesRetryDelays.length - 1];+ _sharesFailures++;+ _sharesRetryAt = _clock().add(delay);}- } catch (error) {- if (isUnauthorizedError(error)) rethrow;- stale = true;}+ // With no shares read yet there is nothing to stand in for them: the list is stale until one answers.+ if (_sharesReadAt == null) stale = true;_requireAccount(account);if (request == _machineRequestRevision) {_sharedMachines = sharedMachines;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 67f74a8a3..35e6fd9b5 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1122,6 +1122,8 @@ class AppNotifier extends ChangeNotifier {// independently, with capped backoff and the same in-flight request as a manual retry.Timer? _machineRecoveryTimer;Timer? _sharingDiscoveryTimer;+ // A `machines_changed` push waiting for its copies from the other machines ([machinesPushCollapse]).+ Timer? _machinesPushTimer;// A viewer with no machine socket open hears no push at all — a machine that joins the account is// only found by this. See [_rereadMachinesWhileDeaf].late final _deafMachineListWatch = MachineListWatch(@@ -1826,6 +1828,15 @@ class AppNotifier extends ChangeNotifier {}}if (shown) _persistLayout();+ // The dial is told the project open in a Swarm tab only once the Swarm+ // has loaded: a tab shown (or restored) before that went out with no+ // project, and nothing told the dial again, so it stayed on an empty+ // tab (Diego, 2026-10-28). Said again when that project changes, not on+ // every read.+ if (_dialProjects.containsKey(controller.tabId) &&+ _dialProjects[controller.tabId] != _dialProject(controller)) {+ _announceOpenPanesToDial();+ }notifyListeners();},transport: (method, path, {body}) async {@@ -2457,6 +2468,7 @@ class AppNotifier extends ChangeNotifier {'${add.machineId}\u0000${add.agentId}',);if (!known && _sharedRereadAsked.add(add.machineId)) {+ api.sharesChanged();unawaited(_rereadMachinesInBackground(pushed: true));}continue;@@ -2595,6 +2607,7 @@ class AppNotifier extends ChangeNotifier {if (machine == null) {if (_foreignRosterEntry(pane.machineId, agentId) != null &&_sharedRereadAsked.add(pane.machineId)) {+ api.sharesChanged();unawaited(_rereadMachinesInBackground(pushed: true));}return;@@ -4854,6 +4867,11 @@ class AppNotifier extends ChangeNotifier {/// was most of the backend's traffic.static const machineListSafetyNetInterval = Duration(minutes: 5);+ /// How long a `machines_changed` push waits for the same push from the other machines. The backend+ /// tells every daemon socket of the account, and each relays it, so it reaches a window once per+ /// connected machine: four at once on Diego's app (2026-10-28), each a read of its own.+ static const machinesPushCollapse = Duration(seconds: 2);+/// How often a viewer that has no machine socket open re-reads the machine list. Every push/// (`machines_changed`, `device_keys_changed`) reaches a browser over the web socket of a machine/// it is connected to; with none connected — the person signed in on the web first and is now@@ -5616,6 +5634,20 @@ class AppNotifier extends ChangeNotifier {bool _announceFromDevice = false;int _devicePick = 0;+ /// The project each Swarm tab's row last told the dial, by backend tab id;+ /// null while its Swarm had not loaded. See `onSnapshot`.+ final _dialProjects = <String, String?>{};++ String? _dialProject(SuperTabController controller) =>+ controller.snapshot?.projectFor(controller.selectedId)?.id;++ /// The project open in this Swarm tab for its dial row, kept as told.+ String? _rememberDialProject(String tabId) =>+ _dialProjects[tabId] = switch (superTabs.peek(tabId)) {+ final controller? => _dialProject(controller),+ null => null,+ };+/// The tile roster and the tabs, to every daemon this window reaches over/// its loopback ([_deskConnection]) — never a relayed machine's.void _announceOpenPanesToDial() {@@ -5682,10 +5714,7 @@ class AppNotifier extends ChangeNotifier {// while the tab has not loaded: a project is not guessed.if (swarm.superTabId case final tabId?) ...{'superTabId': tabId,- if (superTabs.peek(tabId) case final controller?)- if (controller.snapshot?.projectFor(controller.selectedId)- case final project?)- 'projectId': project.id,+ 'projectId': ?_rememberDialProject(tabId),},'agentIds': [for (final pane in swarm.panes)@@ -7469,6 +7498,8 @@ class AppNotifier extends ChangeNotifier {_daemonSupervisionTimer = null;_sharingDiscoveryTimer?.cancel();_sharingDiscoveryTimer = null;+ _machinesPushTimer?.cancel();+ _machinesPushTimer = null;_deafMachineListWatch.stop();_groupSyncedAt.clear();_sharingDiscoveryBusy = false;@@ -21124,8 +21155,14 @@ class AppNotifier extends ChangeNotifier {case 'machines_changed':// The account's machine list changed somewhere: a machine created,// renamed or deleted, or a shared harness invited or taken back. The- // payload is only a reason; the list itself is re-read.- unawaited(_rereadMachinesInBackground(pushed: true));+ // payload is only a reason; the list itself is re-read, once for the+ // copies every connected machine relays. Only `harness_shares` has it+ // read the shares too, which take seconds (ApiClient.sharesChanged).+ if (payload['reason'] == 'harness_shares') api.sharesChanged();+ _machinesPushTimer ??= Timer(machinesPushCollapse, () {+ _machinesPushTimer = null;+ unawaited(_rereadMachinesInBackground(pushed: true));+ });break;case 'device_keys_changed':// The account's device key log grew. A viewer re-reads and verifies it itself; a desktop@@ -21755,6 +21792,7 @@ class AppNotifier extends ChangeNotifier {_disposed = true;_closeAttachmentSessions();_sharingDiscoveryTimer?.cancel();+ _machinesPushTimer?.cancel();_deafMachineListWatch.stop();_stopMachineRecovery();if (signingIn) cliLogin.cancel();diff --git a/desktop/test/api_client_test.dart b/desktop/test/api_client_test.dartindex 6b115d6e2..804e51394 100644--- a/desktop/test/api_client_test.dart+++ b/desktop/test/api_client_test.dart@@ -382,12 +382,14 @@ void main() {await request.response.close();});try {+ var now = DateTime(2026, 10, 28, 12);final api = ApiClient(config: AppConfig(apiBaseUrl: 'http://unused.invalid',localCliBaseUrl: 'http://127.0.0.1:${server.port}',),session: AuthSession(),+ clock: () => now,);final first = await api.machines();expect(first.map((m) => m.machineId), ['owned', 'shared']);@@ -400,16 +402,22 @@ void main() {shared.copyWith(name: 'Updated').sharedHarnesses.single.id,'grant',);+ // An outage keeps the grants last read, and is not a stale list that recovery reads again.+ api.sharesChanged();shareStatus = 503;expect((await api.machines()).last.machineId, 'shared');- expect(api.lastMachinesStale, isTrue);+ expect(api.lastMachinesStale, isFalse);+ // Taken back: read once the wait after the outage is over.+ now = now.add(ApiClient.sharesRetryDelays.first);shareStatus = 200;shares = [];expect((await api.machines()).map((m) => m.machineId), ['owned']);expect(api.lastMachinesStale, isFalse);+ api.sharesChanged();shareStatus = 404;expect((await api.machines()).single.machineId, 'owned');expect(api.lastMachinesStale, isFalse);+ api.sharesChanged();shareStatus = 401;await expectLater(api.machines(), throwsA(isA<ApiException>()));} finally {diff --git a/desktop/test/machine_inventory_api_test.dart b/desktop/test/machine_inventory_api_test.dartindex 49ff0e64a..e369d20b1 100644--- a/desktop/test/machine_inventory_api_test.dart+++ b/desktop/test/machine_inventory_api_test.dart@@ -36,9 +36,10 @@ Future<void> _reply(String name, {bool stale = false,bool fails = false,+ int status = 503,}) async {request.response- ..statusCode = fails ? 503 : 200+ ..statusCode = fails ? status : 200..headers.contentType = ContentType.json..write(jsonEncode(@@ -99,14 +100,117 @@ void main() {expect(previous.isStale, isFalse);expect(latest.isStale, isTrue);expect(api.lastMachinesStale, isTrue);+ api.sharesChanged();final fallback = api.machines();await _until(() => requests.machines.length == 3);await _reply(requests.machines.last, 'owned-next');await _until(() => requests.shares.length == 3);await _reply(requests.shares.last, 'unused', fails: true);final snapshot = await fallback as MachineInventory;+ // The last shares that were read stand in, as they are: not a stale list that recovery reads again.expect(snapshot.map((m) => m.machineId), ['owned-next', 'shared-current']);- expect(snapshot.isStale, isTrue);+ expect(snapshot.isStale, isFalse);+ });++ group('harness shares, read through the owner daemons in seconds', () {+ var now = DateTime(2026, 10, 28, 12);+ setUp(() {+ now = DateTime(2026, 10, 28, 12);+ api = ApiClient(+ config: AppConfig(+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',+ apiBaseUrl: 'http://unused.invalid',+ ),+ session: AuthSession(storage: MemoryStore()),+ clock: () => now,+ );+ });++ /// One machine read. [shared] answers its shares read with that machine, [status] fails it;+ /// with neither, no shares read is expected.+ Future<MachineInventory> load({String? shared, int? status}) async {+ final machines = requests.machines.length;+ final shares = requests.shares.length;+ var done = false;+ final pending = api.machines().whenComplete(() => done = true);+ await _until(() => requests.machines.length == machines + 1);+ await _reply(requests.machines.last, 'owned');+ final expected = shared != null || status != null;+ if (expected) {+ await _until(() => requests.shares.length == shares + 1);+ await _reply(+ requests.shares.last,+ shared ?? 'unused',+ fails: status != null,+ status: status ?? 503,+ );+ } else {+ await _until(() => done || requests.shares.length > shares);+ }+ expect(requests.shares.length, shares + (expected ? 1 : 0));+ return await pending as MachineInventory;+ }++ List<String> ids(MachineInventory list) => [+ for (final m in list) m.machineId,+ ];++ test('ten pushes a minute read them once; a push that says they changed reads them again', () async {+ expect(ids(await load(shared: 's1')), ['owned', 's1']);+ for (var i = 0; i < 10; i++) {+ now = now.add(const Duration(seconds: 6));+ final list = await load();+ expect(ids(list), ['owned', 's1']);+ expect(list.isStale, isFalse);+ }+ api.sharesChanged();+ expect(ids(await load(shared: 's2')), ['owned', 's2']);+ // And at most every five minutes otherwise.+ now = now.add(const Duration(minutes: 4, seconds: 59));+ await load();+ now = now.add(const Duration(seconds: 1));+ expect(ids(await load(shared: 's3')), ['owned', 's3']);+ });++ test('a failed read waits 1, 2, then 5 minutes, and keeps the last good shares meanwhile', () async {+ await load(shared: 's1');+ api.sharesChanged();+ // The daemon's 504 after 20 s (Diego's app log, 2026-10-28): every push started the same read again.+ expect(ids(await load(status: 504)), ['owned', 's1']);+ for (final wait in const [+ Duration(minutes: 1),+ Duration(minutes: 2),+ Duration(minutes: 5),+ ]) {+ now = now.add(wait - const Duration(seconds: 1));+ final kept = await load();+ expect(ids(kept), ['owned', 's1']);+ expect(kept.isStale, isFalse);+ now = now.add(const Duration(seconds: 1));+ if (wait.inMinutes < 5) await load(status: 502);+ }+ // Told meanwhile, it reads once the wait is over; a read that answers starts the waits over.+ expect(ids(await load(shared: 's2')), ['owned', 's2']);+ api.sharesChanged();+ await load(status: 504);+ now = now.add(const Duration(seconds: 59));+ await load();+ now = now.add(const Duration(seconds: 1));+ await load(shared: 's3');+ });++ test('with no shares read yet, a failure is a stale list, and the account changing starts over', () async {+ final first = await load(status: 504);+ expect(ids(first), ['owned']);+ expect(first.isStale, isTrue);+ expect(+ (await load()).isStale,+ isTrue,+ reason: 'still nothing good to show, and still waiting',+ );+ api.resetAccountCache();+ expect(ids(await load(shared: 'theirs')), ['owned', 'theirs']);+ });});test('a machine shared whole joins the list once added, and waits under Add machine before', () async {diff --git a/desktop/test/machine_list_push_test.dart b/desktop/test/machine_list_push_test.dartindex 6b12703cd..ab594b0e8 100644--- a/desktop/test/machine_list_push_test.dart+++ b/desktop/test/machine_list_push_test.dart@@ -23,8 +23,12 @@ const _computerId = 'aabbccddeeff0011';class _Api extends ApiClient {_Api() : super(config: AppConfig.dev, session: AuthSession());int reads = 0;+ int sharesTold = 0;Completer<void>? hold;+ @override+ void sharesChanged() => sharesTold++;+/// When set, every read waits on a gate of its own, so a test can finish/// them in the order it chooses.List<Completer<void>>? gates;@@ -149,11 +153,66 @@ void main() {await app.handleEventForTest('local-machine', _push);await tester.pump();+ expect(+ api.reads,+ 0,+ reason: 'the same push from the other machines may follow',+ );+ await tester.pump(AppNotifier.machinesPushCollapse);expect(api.reads, 1);app.dispose();});+ testWidgets(+ 'the same push from every machine connection costs one read, not one each',+ (tester) async {+ final api = _Api();+ final app = _signedIn(api);+ for (final id in ['m1', 'm2', 'm3']) {+ app.machineStates[id] = MachineState(+ Machine(machineId: id, name: id, authMode: MachineAuthMode.remote),+ );+ }++ // Diego's app, 2026-10-28: each push arrived four times at once, one per machine socket.+ for (final id in ['local-machine', 'm1', 'm2', 'm3']) {+ await app.handleEventForTest(id, _push);+ }+ await tester.pump(AppNotifier.machinesPushCollapse);+ await tester.pump();+ expect(api.reads, 1);+ await tester.pump(AppNotifier.machinesPushCollapse);+ expect(api.reads, 1);+ app.dispose();+ },+ );++ testWidgets(+ 'a push saying a harness share changed has the read read the shares',+ (tester) async {+ final api = _Api();+ final app = _signedIn(api);++ await app.handleEventForTest('local-machine', _push);+ await tester.pump(AppNotifier.machinesPushCollapse);+ expect(+ api.sharesTold,+ 0,+ reason: 'any other change reads them every few minutes',+ );++ await app.handleEventForTest('local-machine', const {+ 'type': 'machines_changed',+ 'payload': {'reason': 'harness_shares'},+ });+ expect(api.sharesTold, 1);+ await tester.pump(AppNotifier.machinesPushCollapse);+ expect(api.reads, 2);+ app.dispose();+ },+ );+testWidgets('a push is ignored once the person has signed out', (tester,) async {@@ -174,10 +233,12 @@ void main() {final app = _signedIn(api);// A bulk rename: the first push starts a read, the rest land while it is open.- for (var i = 0; i < 5; i++) {+ await app.handleEventForTest('local-machine', _push);+ await tester.pump(AppNotifier.machinesPushCollapse);+ for (var i = 0; i < 4; i++) {await app.handleEventForTest('local-machine', _push);+ await tester.pump(AppNotifier.machinesPushCollapse);}- await tester.pump();expect(api.reads, 1);// The open read may predate the later changes, so exactly one more follows it.@@ -201,7 +262,7 @@ void main() {await tester.pump();expect(api.reads, 1);await app.handleEventForTest('local-machine', _push);- await tester.pump();+ await tester.pump(AppNotifier.machinesPushCollapse);api.hold!.complete();api.hold = null;@@ -223,8 +284,9 @@ void main() {// Read #1 is ours; a second push asks for a follow-up once it is done.await app.handleEventForTest('local-machine', _push);- await tester.pump();+ await tester.pump(AppNotifier.machinesPushCollapse);await app.handleEventForTest('local-machine', _push);+ await tester.pump(AppNotifier.machinesPushCollapse);// The person presses Reload while #1 is still open: read #2 is theirs.final manual = app.retryMachines();await tester.pump();diff --git a/desktop/test/shared_tabs_desk_test.dart b/desktop/test/shared_tabs_desk_test.dartindex 13e459eea..90ce22072 100644--- a/desktop/test/shared_tabs_desk_test.dart+++ b/desktop/test/shared_tabs_desk_test.dart@@ -69,6 +69,10 @@ class _Api extends ApiClient {final _Desk board;List<Machine> list = const [];int machineReads = 0;+ int sharesTold = 0;++ @override+ void sharesChanged() => sharesTold++;@overrideFuture<Map<String, dynamic>?> desk() async => board.json();@@ -406,6 +410,8 @@ void main() {await _settle();expect(api.machineReads, greaterThanOrEqualTo(1));+ // The grant is a harness share: the read reads the shares, which it otherwise does every few minutes.+ expect(api.sharesTold, 1);expect(app.machineStates['ma']?.machine.isShared, isTrue);expect(desk.tab(_deskTab)?.panes.map((p) => p.key), [_key('ma', 'a1')]);final placed = jsonDecode(store.values[_placedKey]!) as Map;@@ -870,6 +876,7 @@ void main() {gate.complete();await _settle();expect(api.machineReads, greaterThanOrEqualTo(1));+ expect(api.sharesTold, 1, reason: 'the machine is a harness share: the read reads the shares');expect(pane.sharedHarness?.agentId, 'a1');expect(pane.sharedOwnerName, 'Alice');});diff --git a/desktop/test/super_tab_dial_test.dart b/desktop/test/super_tab_dial_test.dartindex 20a6a2fb1..896d44036 100644--- a/desktop/test/super_tab_dial_test.dart+++ b/desktop/test/super_tab_dial_test.dart@@ -56,6 +56,43 @@ void main() {expect(row(announces(f).last)['projectId'], 'design');});+ test('a Swarm tab restored on its project chat names that project once the Swarm loads', () async {+ // Diego's dial, 2026-10-28: the app came back on the Swarm's project+ // chat (`project-<id>`), the dial was told the tab before the Swarm had+ // loaded, and nothing told it again once it had.+ final f = SuperTabLaunchFixture(local: true);+ final server = f.connection.server;+ server.state['projects'] = [+ projectFixture('lead', 'Lamp OS', 'lead'),+ projectFixture('design', 'Design', 'project-design'),+ ];+ (server.state['conversations'] as List).add({+ ...conversationFixture('project-design', 'Lead'),+ 'projectId': 'design',+ });+ await f.store.write(+ 'super_tab.owner.$tabId',+ '{"tabId":"$tabId","accountId":"owner","selectedId":"project-design"}',+ );+ f.app.adoptPoolConnectionForTest('m', f.connection);+ final hold = server.holdReads = Completer<void>();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final c = await f.app.superTabs.open(tabId);+ expect(c.selectedId, 'project-design');+ f.app.announceWindowForeground();+ await settle();+ expect(row(announces(f).last).containsKey('projectId'), isFalse);+ final before = announces(f).length;+ server.holdReads = null;+ hold.complete();+ await c.refresh();+ await settle();+ expect(c.snapshot, isNotNull);+ final after = announces(f).skip(before).toList();+ expect(after, isNotEmpty);+ expect(row(after.last)['projectId'], 'design');+ });+test('a draft tab has no tab id', () async {final (f, _) = await open();f.app.newSwarm(newTabPage: true);diff --git a/desktop/test/web_machine_list_watch_test.dart b/desktop/test/web_machine_list_watch_test.dartindex 798026c58..a002a6d98 100644--- a/desktop/test/web_machine_list_watch_test.dart+++ b/desktop/test/web_machine_list_watch_test.dart@@ -272,25 +272,24 @@ void main() {await unmount(tester);});- testWidgets('a push reads at once and starts the pace over', (tester) async {- await mount(tester, machines: const [_asleep]);- expect(await readsIn(tester, 120), [4, 12, 27, 57, 87, 117]);-- expect(- await readAtOnce(- tester,- () => unawaited(- app.handleEventForTest(_studioId, const {- 'type': 'machines_changed',- 'payload': <String, dynamic>{},- }),- ),- ),- isTrue,- );- expect(await readsIn(tester, 12), [124, 132]);- await unmount(tester);- });+ testWidgets(+ 'a push reads once its copies from the other machines are in, and starts the pace over',+ (tester) async {+ await mount(tester, machines: const [_asleep]);+ expect(await readsIn(tester, 120), [4, 12, 27, 57, 87, 117]);++ unawaited(+ app.handleEventForTest(_studioId, const {+ 'type': 'machines_changed',+ 'payload': <String, dynamic>{},+ }),+ );+ // AppNotifier.machinesPushCollapse: the same push arrives once per connected machine.+ expect(await readsIn(tester, 2), [122]);+ expect(await readsIn(tester, 12), [126, 134]);+ await unmount(tester);+ },+ );testWidgets('the person\'s Retry reads at once and starts the pace over', (tester,diff --git a/devices/harness-device/firmware/main/cable_client.c b/devices/harness-device/firmware/main/cable_client.cindex f27add12a..6f267c3b0 100644--- a/devices/harness-device/firmware/main/cable_client.c+++ b/devices/harness-device/firmware/main/cable_client.c@@ -974,10 +974,11 @@ static void handle_supertab_recap(const cJSON *p)const bool none = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(p, "none"));ui_supertab_recap(tab, lead, none || !text ? "" : text, secs > 4294967295.0 ? 0xFFFFFFFFu : (uint32_t)secs, none);}+// `supertab.focus` {tab, lead}. An empty `lead` is the desktop on that Swarm's tab with no project open: still a focus.static void handle_supertab_focus(const cJSON *p){const char *tab = str_of(p, "tab"), *lead = str_of(p, "lead");- if (id_fits(tab) && id_fits(lead)) ui_supertab_focus(tab, lead);+ if (id_fits(tab) && lead && (!lead[0] || id_fits(lead))) ui_supertab_focus(tab, lead);}// `question` {agentId, id, questions, superTab?, attention?}. With a non-empty `superTab` it is a Super Tab wait: thediff --git a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.cindex 3df4771f9..212d36bb0 100644--- a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c+++ b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c@@ -597,6 +597,7 @@ static EXT_RAM_BSS_ATTR struct {int at; // that Lead's place, where the face lands when the Lead goesbool retried; // its recap was asked for a second timestruct { char tab[ID_MAX], lead[ID_MAX]; } focus[HT_SUPERTABS_MAX]; // the Lead the desktop last showed, per Swarm+ char pending[ID_MAX]; // a Swarm the desktop opened before its `swarms` frame said so (ui_supertab_focus)// Super Tab waits from this machine's harnesses, shown only through the Lead whose `local` names the harness.struct { char agent[ID_MAX], request[80], swarm[HT_SUPERTAB_NAME], text[240]; bool stuck, shown; } waits[SWARM_WAITS];} sw;@@ -4804,6 +4805,12 @@ void ui_service_model_picker(void)static EXT_RAM_BSS_ATTR cable_swarm_t desk_rows[SWARMS_MAX];static int desk_row_count;static char desk_selected[ID_MAX];+// Whether a desktop focus may take the dial into a Swarm now: from HOME or an agent, never while talking, nor over a+// question or a form.+static bool swarm_may_follow(void)+{+ return !s.voice_open && !question_view(s.view) && (s.view == HOME || s.view == AGENT);+}static void swarms_apply(void){// A tab with no agent (only shells or viewers, or nothing) is not listed: nothing on the dial can drive it. A@@ -4835,6 +4842,13 @@ static void swarms_apply(void)} else {swarm_desk_note();}+ // The focus came just before this frame (Diego's dial, 2026-10-28): the desktop has opened that Swarm's desk tab+ // now. Spent by any change of tab, so a later visit to the tab does not replay it.+ if (sw.pending[0] && selected_changed) {+ const ht_supertab_t *t = ht_supertabs_find(&swarm, sw.pending);+ if (t && t->tab[0] && !strcmp(t->tab, s.selected_tab) && !swarm_mode() && swarm_may_follow()) swarm_enter(t, "", false);+ sw.pending[0] = 0;+ }changed = changed || total_before != tabs_total();if (s.view == TABS && (changed || (selected_changed && !browsing))) {int index = browsing ? tab_index_of(focused) : tab_index_here();@@ -4986,23 +5000,28 @@ void ui_supertab_recap(const char *tab, const char *lead, const char *text, uintif (ht_supertabs_recap_put(&swarm, tab, lead, text, at, none)) change();display_unlock();}+// `lead` "" is the desktop on that Swarm's tab with no project open (its Chat with PM, a DM): the dial still goes in, on+// the Lead it last showed there, and one already in keeps its face.void ui_supertab_focus(const char *tab, const char *lead){if (!tab || !lead) return;display_lock();int slot = -1;- for (int i = 0; i < HT_SUPERTABS_MAX && slot < 0; i++) if (!strcmp(sw.focus[i].tab, tab)) slot = i;- for (int i = 0; i < HT_SUPERTABS_MAX && slot < 0; i++) if (!sw.focus[i].tab[0] || !ht_supertabs_find(&swarm, sw.focus[i].tab)) slot = i;+ for (int i = 0; i < HT_SUPERTABS_MAX && slot < 0 && lead[0]; i++) if (!strcmp(sw.focus[i].tab, tab)) slot = i;+ for (int i = 0; i < HT_SUPERTABS_MAX && slot < 0 && lead[0]; i++) if (!sw.focus[i].tab[0] || !ht_supertabs_find(&swarm, sw.focus[i].tab)) slot = i;if (slot >= 0) { COPY(sw.focus[slot].tab, tab); COPY(sw.focus[slot].lead, lead); }const ht_supertab_t *t = ht_supertabs_find(&swarm, tab);int i = swarm_lead_index(t, lead);// As `focus` today: never while talking, nor over a question or a form.bool free = !s.voice_open && !question_view(s.view) && s.view != FORM && s.view != DRAFT && s.view != DRAFT_OPTIONS;- if (i >= 0 && free) {+ sw.pending[0] = 0;+ if (t && (i >= 0 || !lead[0]) && free) {if (swarm_mode() && !strcmp(sw.tab, tab)) {- if (strcmp(sw.lead, lead)) swarm_show(t, i, false);- } else if (!swarm_mode() && t->tab[0] && !strcmp(s.selected_tab, t->tab) && (s.view == HOME || s.view == AGENT)) {- swarm_enter(t, lead, false); // the desktop opened this Swarm's tab: the dial goes in with it+ if (i >= 0 && strcmp(sw.lead, lead)) swarm_show(t, i, false);+ } else if (!swarm_mode() && t->tab[0] && swarm_may_follow()) {+ // The desktop opened this Swarm's tab: the dial goes in with it, or as soon as the `swarms` frame says so.+ if (!strcmp(s.selected_tab, t->tab)) swarm_enter(t, lead, false);+ else COPY(sw.pending, tab);}}change();diff --git a/devices/harness-device/firmware/test/test_cable_supertab.py b/devices/harness-device/firmware/test/test_cable_supertab.pyindex 5b729e5dc..7fa357d74 100644--- a/devices/harness-device/firmware/test/test_cable_supertab.py+++ b/devices/harness-device/firmware/test/test_cable_supertab.py@@ -151,6 +151,11 @@ int main(void) {assert(focus_calls==1 && !strcmp(got_tab,"s1") && !strcmp(got_lead,"L2"));feed(handle_supertab_focus,"{\"tab\":\"s1\"}");assert(focus_calls==1);+ // An empty Lead is the window on that Swarm with no project open: still a focus, for the Swarm.+ feed(handle_supertab_focus,"{\"tab\":\"s1\",\"lead\":\"\"}");+ assert(focus_calls==2 && !strcmp(got_tab,"s1") && !got_lead[0]);+ feed(handle_supertab_focus,"{\"tab\":\"\",\"lead\":\"\"}");+ assert(focus_calls==2);// A Super Tab wait goes to ui_supertab_wait, never to the question screen, and beeps only when the UI says so.feed_agent(handle_question,"{\"agentId\":\"h1\",\"name\":\"Lead\",\"id\":\"supertab:a1\",\"questions\":[{\"q\":\"Ship it?\"}],"diff --git a/devices/harness-device/firmware/test/test_touch_ui.py b/devices/harness-device/firmware/test/test_touch_ui.pyindex 93dd93f96..2aa3a14c5 100644--- a/devices/harness-device/firmware/test/test_touch_ui.py+++ b/devices/harness-device/firmware/test/test_touch_ui.py@@ -1638,6 +1638,28 @@ static void swarm_pane_checks(const char *dir) {// The Swarm gone from the list: back to TABS.{ const char ids[2][ID_MAX] = {"s3", "s2"}; ui_supertabs_ids(ids, 2); }assert(!swarm_mode() && s.view == TABS);+ // Diego's dial, 2026-10-28: the window on a Swarm tab with no project open (its Chat with PM, a DM) names no Lead.+ // The dial still goes into that Swarm, on the Lead the desktop last showed there, else the first by order; a dial+ // already in it keeps its face.+ swarm_setup(); COPY(s.selected_tab, "t1"); s.view = HOME; ui_supertab_focus("s1", "");+ assert(swarm_mode() && !strcmp(sw.tab, "s1") && !strcmp(sw.lead, "L0") && !wire_has(0, "select s1 L0"));+ ui_supertab_focus("s1", "L2"); ui_supertab_focus("s1", ""); assert(!strcmp(sw.lead, "L2"));+ swarm_leave(); ui_supertab_focus("s1", ""); assert(swarm_mode() && !strcmp(sw.lead, "L2"));+ swarm_leave(); s.voice_open = true; ui_supertab_focus("s1", ""); assert(!swarm_mode()); s.voice_open = false;+ // A focus that arrives just before the `swarms` frame that selects its desk tab enters when that frame lands…+ {+ swarm_setup(); s.view = HOME; ui_supertab_focus("s1", "L2"); assert(!swarm_mode());+ cable_swarm_t rows[3]; memcpy(rows, desk_rows, sizeof rows);+ ui_swarms_replace(rows, 3, "t1"); assert(swarm_mode() && !strcmp(sw.tab, "s1") && !strcmp(sw.lead, "L2"));+ // …once: leaving and coming back to the tab by itself does not replay it.+ swarm_leave(); ui_swarms_replace(rows, 3, "t0"); ui_swarms_replace(rows, 3, "t1"); assert(!swarm_mode());+ // One with no Lead waits the same way.+ ui_swarms_replace(rows, 3, "t0"); ui_supertab_focus("s1", ""); assert(!swarm_mode());+ ui_swarms_replace(rows, 3, "t1"); assert(swarm_mode() && !strcmp(sw.lead, "L2"));+ // The window going to another tab first spends it.+ swarm_leave(); ui_swarms_replace(rows, 3, "t0"); ui_supertab_focus("s1", "L3");+ ui_swarms_replace(rows, 3, "t2"); ui_swarms_replace(rows, 3, "t1"); assert(!swarm_mode());+ }// The side button: STOP for a busy Lead on this computer (its harness id), HOME for a remote one.swarm_setup(); enter_at("s1", "L0"); ui_boot_pressed(); assert(s.view == STOP && !strcmp(s.stop_agent, "h0"));dispatch((action_t){.kind = A_STOP_YES}); assert(!strcmp(stopped_agent, "h0") && s.view == HOME);diff --git a/docs/swarms.md b/docs/swarms.mdindex 597b32b69..3da6299e8 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -206,14 +206,32 @@ Each person has three numbers:to four weeks back). The request ships at the merge, even if its work is lostor cancelled afterwards. A group that is Done with a linked PR ships too; theearlier of the merge and Done is when it shipped. 3 points each.-- **Unblocked**: items needing a person that the person answered. An answer counts- when it comes from the person the item waits on, or when it replies to the- question itself. That person is the group's requester, or the project's owner- when the group has none. 1 point each, plus 1 point for every 2 hours the agents- waited for those answers.-- **Lent**: hours Swarm agents ran on the person's contributed machines, added up- from each machine's readings. A product manager's session doesn't count: it- coordinates in confidence and doesn't build. 1 point for every 10 hours.+- **Unblocked**: items needing a person that the person answered, each counted+ once:+ - a decision asked of them;+ - a plan the product manager asked them to approve. A reply to the product+ manager's message counts when it starts with GO, approve, approved or duyệt,+ in any case and with or without accents. A bare "ok" doesn't count;+ - an agent's "needs a human" question. The answer must come from the person the+ item waits on, or reply to the question itself. That person is the group's+ requester, or the project's owner when the group has none;+ - a tag addressed to them, answered by their next post in that conversation.++ One post counts once, even if it answers several of these. Approvals in the+ project chat count too. Each answer is 1 point, plus 1 point for every 2 hours+ the item waited, up to 3 points per answer.+- **Lent**: hours Swarm agents on the person's contributed machines spent working+ on tasks other people asked for, added up from each machine's readings. Idle or+ waiting agents don't count, and neither do the person's own requests. A product+ manager's session doesn't count either: it coordinates in confidence and doesn't+ build. 1 point for every 10 hours.++Each person also has last week's points, for the arrow against last week. Their+details list what they shipped (title, PR, when it merged), what they unblocked+(conversation, kind, how long it waited) and each machine's busy hours: the 20+newest of each, and only from conversations the reader can read. People go by+their profile name, or by the first part of their email when they haven't set+one.People with the same points share a place. A streak counts the days in a row,up to today, with a shipped request. Tapping a name shows that person's week:@@ -228,11 +246,11 @@ picker reaches back three weeks.items each, in name order. An item leaves the list as soon as it is answered. It is never ranked and never earns points. **Answer**opens the reader's own waiting item, or the first one when none waits on them.-Only facts count, never text. The leaderboard records when work was asked for and-shipped, who answered and how long agents waited. It never records what anyone-wrote. Private conversations, Chat with PM among them, never count and never-appear in it. Decisions asked of a person will count toward Unblocked once-decisions ship.+Only facts count, never message text. The leaderboard records when work was asked+for and shipped, who answered what kind of item, and how long it waited. It+never records what anyone wrote. The only text it shows is the title of a+conversation the reader can read. Private conversations, Chat with PM among+them, never count and never appear in it.## Avatars, status and celebrations