Skip to content

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

Merge batch 11-06 j0530: #3209 #3227 (#3255)

0xken150f7874755105
diff --git a/backend/integration/superTabCommandLoads.test.ts b/backend/integration/superTabCommandLoads.test.ts
index 0c0b71859..27da67014 100644
--- a/backend/integration/superTabCommandLoads.test.ts
+++ b/backend/integration/superTabCommandLoads.test.ts
@@ -149,6 +149,9 @@ describe('a command in a Swarm with many awake conversations (#3146)', () => {
it('reads none of them whole once this server has read them, only the conversation it writes', async () => {
const f = await swarm(0, AWAKE)
+ // The awake ones were written straight to the database: the first post records their board pulse on the project chat
+ // (pulse.ts, task #3384), which the next command reads once, as it reads any part this server wrote.
+ await posted(f)
await posted(f)
const groups = (await profiled(db, () => posted(f))).filter(e => e.ns.endsWith('.SwarmGroup'))
const examined = groups.reduce((n, e) => n + (e.docsExamined ?? 0), 0)
diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.ts
index cf4150b81..3e5fa6a5b 100644
--- a/backend/integration/superTabRead.test.ts
+++ b/backend/integration/superTabRead.test.ts
@@ -17,6 +17,7 @@ import { noteChange, swarmTransaction } from '../src/superTabs/cache.js'
import { guardedWrite } from '../src/superTabs/parts/write.js'
import { migrateSwarm } from '../src/superTabs/migration/migrate.js'
import { SwarmReads } from '../src/superTabs/read/service.js'
+import { recordPulse } from '../src/superTabs/pulse.js'
import { decisionsWaiting, MAX_OPEN_DECISIONS, REFLECTION_DECISION } from '../src/superTabs/decisions.js'
import { waitingMentions, waitingTagConversations } from '../src/superTabs/mentions.js'
import { writeReadMark } from '../src/superTabs/readMarks.js'
@@ -98,7 +99,8 @@ async function scene<T = void>(extra: (s: ReturnType<typeof swarm>, ids: { web:
})
const more = extra(s, { web, done, lead, secret })
// Stored before its removal: the Swarm-wide Leads conversation, with the Lead in it; no read sends it now (model.ts leadsRemoved).
- s.edit(state => { storeOldLeads(state, [lead]) })
+ // The board's pulse as the commands that wrote this scene would have recorded it (pulse.ts), once its Leads are stored.
+ s.edit(state => { storeOldLeads(state, [lead]); recordPulse(state, MIGRATED) })
const tabId = `tab-${randomUUID()}`
const state = { ...structuredClone(s.state), id: tabId } as SuperTabState
await writeLegacySwarm(db, { state, revision: R, messages: [{ id: `${tabId}-m1`, conversationId: done, sequence: 5, text: 'Done',
@@ -1541,9 +1543,12 @@ describe('what a read costs the database (group 3b)', () => {
await new SuperTabStore(db).execute(owner, s.tabId, { operationId: randomUUID(),
command: { type: 'message.send', conversationId: s.web, text: 'One post', replyTo: null, recipientIds: [] } })
clock = Date.now()
- let groups = 0
- const bytes = await databaseBytes(async () => { groups = (await get(`/api/super-tabs/${s.tabId}/changes?cursor=${cursor}`, peer)).body.data.groups.length })
- expect(groups).toBe(1)
+ let groups: string[] = []
+ const bytes = await databaseBytes(async () => {
+ groups = (await get(`/api/super-tabs/${s.tabId}/changes?cursor=${cursor}`, peer)).body.data.groups.map((g: { key: string }) => g.key)
+ })
+ // The task, and its project's chat: the post is an ask the PM now owes, which the board's pulse there counts (task #3384).
+ expect(groups.sort()).toEqual([s.web, 'lead'].sort())
expect(bytes).toBeLessThan(30_000)
})
@@ -1952,3 +1957,38 @@ describe('a change poll reads only the starts it can send (prod 10-29)', () => {
})
})
})
+
+// Task #3384, ReviewPulse2's review of #3209: a change poll reads only the light base (the project chats and running work, light
+// fields), so a pulse worked out at read time from it lost the asks and Next up a first load showed, and both apps replace
+// `derived` on each poll. Every read now sends the pulse recorded on the project's chat: the same on a first load and on every
+// change poll after it, whether nothing changed or something did, through the read cache or straight from the database.
+describe('the board pulse on a first load and the change polls after it (task #3384)', () => {
+ for (const cached of [true, false]) {
+ it(`is the same on every read, ${cached ? 'through the read cache' : 'straight from the database'}`, async () => {
+ const s = await scene(state => { state.group('Next task') })
+ const store = new SuperTabStore(db, () => clock, null, cached ? {} : { readCache: null })
+ const reads = new SwarmReads(store, { now: () => clock })
+ const ask = (as: AuthUser, text: string) => store.execute(as, s.tabId, { operationId: randomUUID(),
+ command: { type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [] } as never })
+ clock = Date.now()
+ await ask(peer, 'Can the board show who works?')
+ const pulseOf = (derived: { pulse?: Record<string, unknown> }) => Object.values(derived.pulse ?? {}) as Array<{ asks: { count: number }; nextUp: { count: number } }>
+ const first = await reads.firstLoad(owner, s.tabId)
+ const [pilot] = pulseOf(first.derived)
+ expect(pilot?.asks.count).toBe(1)
+ expect(pilot?.nextUp.count).toBeGreaterThan(0)
+
+ clock = Date.now()
+ const quiet = await reads.changes(owner, s.tabId, first.cursor)
+ expect(quiet.reload).toBe(false)
+ expect((quiet as { derived: { pulse?: unknown } }).derived.pulse).toEqual(first.derived.pulse)
+
+ await ask(owner, 'And who is idle?')
+ clock = Date.now()
+ const changed = await reads.changes(owner, s.tabId, (quiet as { cursor: string }).cursor)
+ const full = await reads.firstLoad(owner, s.tabId)
+ expect(pulseOf(full.derived)[0]?.asks.count).toBe(2)
+ expect((changed as { derived: { pulse?: unknown } }).derived.pulse).toEqual(full.derived.pulse)
+ })
+ }
+})
diff --git a/backend/integration/superTabReviewSteps.test.ts b/backend/integration/superTabReviewSteps.test.ts
new file mode 100644
index 000000000..bb3f347ba
--- /dev/null
+++ b/backend/integration/superTabReviewSteps.test.ts
@@ -0,0 +1,96 @@
+import { randomUUID } from 'node:crypto'
+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, vi } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore, type SuperTabStoreHooks } from '../src/superTabs/store.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { SEED_RULES } from '../src/superTabs/policy.js'
+
+// Task #3401: a task's Ready reads its pull request's files from GitHub, outside the command's transaction, and the server
+// opens its review steps from them. A fresh loopback replica set, created here.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const owner: AuthUser = { sub: '220000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const host: AuthUser = { sub: '220000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const opus = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const REPO = 'https://github.com/acme/app'
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_review_steps_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ for (const user of [owner, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })
+ await db.machine.create({ data: { machineId: 'review-host', userId: host.sub, apiKey: 'fixture-review-host', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ await db.machineShare.create({ data: { machineId: 'review-host', ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A Swarm whose project has a GitHub repository, a PM, a task with its Engineer, and two Reviewers. */
+async function swarm(hooks: SuperTabStoreHooks) {
+ const store = new SuperTabStore(db, Date.now, undefined, hooks)
+ const tab = (await store.create(owner, randomUUID(), 'Reviews', 'public')).id
+ const execute = (command: Command, user = owner, asAgentId?: string) => store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)
+ const invitation = await execute({ type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
+ await execute({ type: 'machine.contribute', machineId: 'review-host', name: 'Review Mac', cwd: '/repo', engines: ['claude'], maxAgents: 8 }, host)
+ const add = async (conversationId: string, name: string, lead = false, roleName?: string) => String((await execute({ type: 'agent.add',
+ conversationId, machineId: 'review-host', harnessId: randomUUID(), name, configuration: opus, lead, ...roleName ? { roleName } : {} } as Command)).result.agentId)
+ const lead = await add('lead', 'PM', true)
+ const task = String((await execute({ type: 'conversation.create', title: 'Fix sign-in', brief: 'Sign in works offline.', checks: [] })).result.conversationId)
+ const dev = await add(task, 'Dev', false, 'Engineer')
+ const reviewers = [await add(task, 'Rev A', false, 'Reviewer'), await add(task, 'Rev B', false, 'Reviewer')]
+ const assignment = String((await execute({ type: 'work.assign', conversationId: task, agentId: dev })).result.assignmentId)
+ return { store, tab, execute, lead, task, dev, reviewers, assignment }
+}
+
+const stepsIn = async (tab: string, task: string) => (await db.swarmGroup.findMany({ where: { tabId: tab } }))
+ .map(row => row.data as { reviewOf?: string; step?: string; assignment?: { agentId: string; status: string } | null })
+ .filter(group => group.reviewOf === task)
+
+describe('a Ready through the store', () => {
+ it('reads the pull request\'s files and opens two security reviews for a sign-in change', async () => {
+ const pullRequestFiles = vi.fn(async (_repository: string | null, urls: string[]) => ({ urls, head: 'abc1234', files: ['backend/src/routes/auth.ts'] }))
+ const { tab, execute, task, dev, reviewers, assignment } = await swarm({ pullRequestFiles })
+ await execute({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'review', result: `Ready: ${REPO}/pull/7` }, host, dev)
+ expect(pullRequestFiles).toHaveBeenCalledWith(null, [`${REPO}/pull/7`])
+ const steps = await stepsIn(tab, task)
+ expect(steps.map(step => step.step).sort()).toEqual(['Security review 1', 'Security review 2'])
+ expect(steps.map(step => step.assignment?.agentId).sort()).toEqual([...reviewers].sort())
+ })
+
+ it('plans by the project\'s saved rules record', async () => {
+ const pullRequestFiles = vi.fn(async (_repository: string | null, urls: string[]) => ({ urls, head: 'abc1234', files: ['docs/a.md'] }))
+ const { tab, execute, task, dev, assignment } = await swarm({ pullRequestFiles })
+ const rules = { ...SEED_RULES, reviews: { ...SEED_RULES.reviews, defaultReads: 2 } }
+ await execute({ type: 'rules.set', projectId: 'lead', baseRevision: 0, rules, summary: 'Two reads for everything' } as Command)
+ await execute({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'review', result: `Ready: ${REPO}/pull/7` }, host, dev)
+ expect((await stepsIn(tab, task)).map(step => step.step).sort()).toEqual(['Review 1', 'Review 2'])
+ })
+
+ it('opens nothing when the Ready names no pull request, and never reads for a step\'s Ready', async () => {
+ const pullRequestFiles = vi.fn(async (_repository: string | null, urls: string[]) => ({ urls, head: 'abc1234', files: ['docs/a.md'] }))
+ const { tab, execute, task, dev, assignment } = await swarm({ pullRequestFiles })
+ await execute({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'review', result: 'Ready' }, host, dev)
+ expect(pullRequestFiles).not.toHaveBeenCalled()
+ expect(await stepsIn(tab, task)).toEqual([])
+ })
+
+ it('opens the strictest steps when the read throws, and the Ready still goes through', async () => {
+ const pullRequestFiles = vi.fn(async () => { throw new Error('GitHub down') })
+ const { tab, execute, task, dev, assignment } = await swarm({ pullRequestFiles })
+ await execute({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'review', result: `Ready: ${REPO}/pull/7` }, host, dev)
+ expect((await stepsIn(tab, task)).map(step => step.step).sort()).toEqual(['Security review 1', 'Security review 2'])
+ })
+})
diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.ts
index dfbb800b8..b35046f76 100644
--- a/backend/src/github/app.test.ts
+++ b/backend/src/github/app.test.ts
@@ -564,6 +564,30 @@ describe('who pushed a pull request, through the app', () => {
})
})
+// Task #3401: a task's Ready reads the files its pull request changes, and the server opens its review steps from them.
+describe('listing a pull request\'s files', () => {
+ it('lists every changed file across pages, a renamed file under both names, with the watch\'s read-only token', async () => {
+ const { app, github } = setup()
+ const { token } = await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)
+ github.files.set('acme/app#12', [...Array.from({ length: 150 }, (_, i) => ({ filename: `src/f${i}.ts`, status: 'modified' })),
+ { filename: 'src/session.ts', status: 'renamed', previous_filename: 'src/auth.ts' }])
+ const listed = await app.pullRequestFiles(repo, 12, token)
+ expect(listed).toHaveLength(152)
+ expect(listed!.map(f => f.filename)).toEqual(expect.arrayContaining(['src/f0.ts', 'src/f149.ts', 'src/session.ts', 'src/auth.ts']))
+ expect(github.calls.filter(c => c.path === '/repos/acme/app/pulls/12/files')).toHaveLength(2)
+ })
+
+ it('says it cannot tell when GitHub fails, and when the list may stop at GitHub\'s 3,000 files', async () => {
+ const { app, github } = setup()
+ const { token } = await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)
+ github.files.set('acme/app#12', Array.from({ length: 3000 }, (_, i) => ({ filename: `src/f${i}.ts`, status: 'modified' })))
+ expect(await app.pullRequestFiles(repo, 12, token)).toBeNull()
+ github.files.set('acme/app#12', [{ filename: 'a.ts', status: 'added' }])
+ github.control.pullsStatus = 500
+ expect(await app.pullRequestFiles(repo, 12, token)).toBeNull()
+ })
+})
+
// Dee, #1891: a task's pull request is watched for its Engineer (superTabs/pullRequestEvents.ts), with what the app holds.
describe('watching a pull request', () => {
const HEAD = 'abc1234def5678'
diff --git a/backend/src/github/app.ts b/backend/src/github/app.ts
index a3b6ce2bd..aa60fcf85 100644
--- a/backend/src/github/app.ts
+++ b/backend/src/github/app.ts
@@ -39,6 +39,8 @@ export const PUSH_ORIGIN_PERMISSIONS = { contents: 'read', pull_requests: 'read'
export const PULL_WATCH_PERMISSIONS = { pull_requests: 'read', checks: 'read', metadata: 'read' } as const
/** The watch's answers kept for conditional reads: an unchanged one comes back 304, which GitHub's rate limit does not count. */
const WATCH_KEPT = 2000
+/** Pages of 100 a pull request's file list reads: GitHub lists at most 3,000 files. */
+const PULL_FILES_PAGES = 30
const PUSH_ORIGINS_KEPT = 1000
const PUSH_UNKNOWN_MS = 60_000
export type TokenPermissions = Readonly<Record<string, 'read' | 'write'>>
@@ -656,6 +658,35 @@ export class GitHubApp {
}
}
+ /**
+ * The files pull request [number] changes, read with the watch's read-only token (task #3401: its review steps are planned
+ * from them): GET /pulls/{n}/files, 100 a page. A renamed file is listed under its old name too, so moving a file out of a
+ * sensitive path still counts as changing it. Null when GitHub cannot say, or when the list may be cut at GitHub's 3,000.
+ */
+ async pullRequestFiles(repository: GitHubRepository, number: number, token: string): Promise<Array<{ filename: string }> | null> {
+ const names = new Set<string>()
+ const text = (value: unknown) => typeof value === 'string' && value ? value : undefined
+ try {
+ for (let page = 1; page <= PULL_FILES_PAGES; page++) {
+ const answer = await this.call('GET', `/repos/${repository.owner}/${repository.name}/pulls/${number}/files?per_page=100&page=${page}`, `Bearer ${token}`)
+ if (answer.status !== 200 || !Array.isArray(answer.body)) return null
+ for (const file of answer.body as Array<Record<string, unknown>>) {
+ const filename = text(file.filename)
+ if (!filename) return null
+ names.add(filename)
+ const previous = text(file.previous_filename)
+ if (previous) names.add(previous)
+ }
+ if (answer.body.length < 100) return [...names].map(filename => ({ filename }))
+ }
+ // A full last page: GitHub lists at most 3,000 files, so more may exist.
+ return null
+ } catch (error) {
+ if (error instanceof GitHubAppError) return null
+ throw error
+ }
+ }
+
/** The default branch and whether pushing to it straight needs a pull request, read with the agent's own token
* (metadata and contents read): rulesets first (GET /repos/{owner}/{repo}/rules/branches/{branch}), then classic
* protection's flag on the branch. Remembered ten minutes; a failed read is `unknown`, never a refusal. */
diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.ts
index 6fccdf850..c2fc33ca7 100644
--- a/backend/src/github/fakeGitHub.ts
+++ b/backend/src/github/fakeGitHub.ts
@@ -31,6 +31,8 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
/** A pull request's reviews and conversation comments, by `owner/name#number`, lower case. */
const reviews = new Map<string, Array<{ id: number; user: { login: string }; author_association?: string; state: string; body: string; html_url: string }>>()
const comments = new Map<string, Array<{ id: number; user: { login: string }; author_association?: string; body: string; html_url: string }>>()
+ /** A pull request's changed files, by `owner/name#number`, lower case, as GET /pulls/{n}/files lists them (task #3401). */
+ const files = new Map<string, Array<{ filename: string; status: string; previous_filename?: string }>>()
/** Workflow runs by `owner/name`, lower case: each run's status and its jobs' statuses and runner labels. */
const actions = new Map<string, Array<{ id: number; status: string; jobs: Array<{ status: string; labels: string[] }> }>>()
/** Each installation's accepted permissions, by installation id, as GET /app/installations/{id} answers them. An
@@ -145,6 +147,13 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
return head[2] === 'check-runs' ? tagged({ total_count: checkRuns.get(key)?.length ?? 0, check_runs: checkRuns.get(key) ?? [] })
: tagged({ total_count: checkSuites.get(key)?.length ?? 0, check_suites: checkSuites.get(key) ?? [] })
}
+ const changed = /^\/pulls\/(\d+)\/files$/.exec(repoPath[3] ?? '')
+ if (changed) {
+ if (control.pullsStatus !== 200) return json(control.pullsStatus, { message: 'Server Error' })
+ const all = files.get(`${repoKey}#${changed[1]}`) ?? []
+ const size = Number(url.searchParams.get('per_page') ?? 30), page = Number(url.searchParams.get('page') ?? 1)
+ return json(200, all.slice((page - 1) * size, page * size))
+ }
const talk = /^\/(pulls|issues)\/(\d+)\/(reviews|comments)$/.exec(repoPath[3] ?? '')
if (talk) {
// Oldest first, a page at a time, with a Link to the last page as GitHub sends it.
@@ -159,7 +168,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
}
return json(404, { message: 'Not Found' })
}) as typeof globalThis.fetch
- return { fetch, calls, grants, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, revoked, issued, control, actions, permissions }
+ return { fetch, calls, grants, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, files, revoked, issued, control, actions, permissions }
}
/** A configured app talking to [github]. */
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 97a69155e..d13adcf82 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -25,6 +25,7 @@ import { GitHubAppError } from '../github/app.js'
import { projectGitHubAccess } from '../github/projectAccess.js'
import { projectCiLoad } from '../github/ciLoad.js'
import { projectBranchOrigin, projectPushOrigin } from '../github/pushOrigin.js'
+import { projectPullRequestFiles } from '../superTabs/pullRequestFiles.js'
import { githubSignIn, PrismaApprovals, readState, signState, stateSecret, type Approvals, type GitHubSignIn } from '../github/approvals.js'
import type { GitHubRepository } from '../github/repository.js'
import { githubRepository } from '../github/repository.js'
@@ -269,6 +270,8 @@ async function productionStore(github: GitHubTokens | null, approvals: Approvals
// A team account has no git login of its own: without the app it takes no teammates' work.
teamAccountsIdle: !github,
...(github ? { pushOrigin: projectPushOrigin(github.app), branchPushOrigin: projectBranchOrigin(github.app) } : {}),
+ // A task's Ready reads the files its pull requests change, and the server opens its review steps from them (task #3401).
+ ...(github ? { pullRequestFiles: projectPullRequestFiles(github.app) } : {}),
// A start or assignment its account cannot reach the repository from is refused at once, by the read Project details
// shows (task #3266): the token endpoint below would refuse it on the machine, after the start was queued.
...(github ? { repositoryReach: async (autonomousEnv: string, tabId: string, projectId: string, repositoryUrl: string) =>
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 0f873456d..b343d8cc6 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,3 +1,4 @@
+import { pulseProjectOf, recordPulse, owe, settleDeleted, settleReaction, settleReply, settleRequest } from './pulse.js'
import { applyPushOrigin, failPushUnknown, failTeamWritten, mainAccountMembers, markTeamWritten, mayName, requireTeamWrittenAccount, requireTeamWrittenMachine, stepMark, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
import { crewMoveFailed, takeOverCrewMember, wakeCrewMember } from './crewKeep.js'
import type { PushOrigin } from '../github/pushOrigin.js'
@@ -17,7 +18,9 @@ import {
type Actor, type AgentConfiguration, type AgentStart, type AgentStartRequest, type BuddySessionEntry, type WorkTask, type Agent, type Author, type Check, type CommandEffects, type Conversation, type SuperTabState,
} from './model.js'
import { jobKindOf } from './evidence/jobKind.js'
-import { endSteps, stepEndedRows, isStep, taskOwner } from './steps.js'
+import { endSteps, stepEndedRows, isStep, stepName, stepsOf, taskOwner } from './steps.js'
+import { reviewPlan, stepBrief, stepCheck, type PlannedStep, type StepKind } from './reviewTable.js'
+import { reviewerCandidates } from './reviewerPick.js'
import { recordCheckVerdict } from './checkVerdicts.js'
import { routeRecordSchema, routeTitle, startedAs, type KeptCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSaveSchema } from './routingPolicy.js'
@@ -569,8 +572,9 @@ export interface CommandContext {
instructions?: { revision: number; text: string; at?: number } | null
/** For `instructions.save`: the messages it names as approvals, loaded by id in this tab by the store (ruleGuard.ts). */
approvals?: ApprovalRow[]
- /** For `rules.set`: the project's newest stored rules revision, read by the store; null when none is saved yet, which is
- * the seed at revision 0 (policyStore.ts). Unread (undefined), nothing is saved. */
+ /** For `rules.set`, and for a task's Ready whose pull request files were read (its review table plans the steps, #3401):
+ * the project's newest stored rules revision, read by the store; null when none is saved yet, which is the seed at
+ * revision 0 (policyStore.ts). Unread (undefined), nothing is saved. */
projectRules?: { revision: number; rules: ProjectRules } | null
/** For `note.add` and `note.remove`: the project's stored notes, expired ones too, read by the store (instructions.ts). */
notes?: PmNote[]
@@ -620,6 +624,9 @@ export interface CommandContext {
pushOrigin?: PushOrigin
/** The pull requests [pushOrigin] read, as the store read them; none for a branch. A clean read clears only a mark it covered (teamWritten.ts). */
pushOriginPulls?: string[]
+ /** The files a Ready for review's task changes in its pull requests, and the head they were read at, read before the command
+ * (store.ts pullRequestFilesFor): `files` null when GitHub could not say. Absent with nothing to read: no step opens then. */
+ pullRequestFiles?: { urls: string[]; head: string | null; files: string[] | null; heads?: Array<{ url: string; head: string | null }> }
/** Whether the Harness GitHub App reaches the project's repository, read before an agent.start or work.assign (store.ts repositoryReachFor). */
repositoryReach?: RepositoryReach
/** The person's role in the Swarm's Workspace, read by the store for invitations (workspaces.ts); absent outside a Workspace. */
@@ -913,6 +920,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
let sender: Author | undefined
try { sender = author(effects.state, actor) } catch { sender = undefined }
syncTaskLines(original, effects, sender, stableId(original.id, actorKey(actor), context.operationId))
+ // Every open group is loaded for a command (parts/load.ts): the board's pulse is worked out on it (pulse.ts), for the project
+ // of the conversation the command names when it names one (it moves no other), else for every project.
+ recordPulse(effects.state, context.now, pulseProjectOf(effects.state, input))
return effects
}
@@ -1606,6 +1616,134 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
}
+ /** Every check work.assign makes before [worker] takes [group]'s work, throwing its refusal; nothing changes here, so a
+ * caller trying candidates in turn (openReviewSteps) catches the refusal and tries the next. */
+ const assignRefusal = (group: Conversation, worker: Agent) => {
+ if (state.starts?.some(s => s.poolGeneration && !s.poolSettled && s.request.machineId === worker.machineId && s.harnessId === worker.harnessId)) {
+ fail('START_PENDING', 'Wait for the host to finish this agent’s launch and model selection.')
+ }
+ if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
+ if (activeWork(group)) fail('WORK_ACTIVE', 'The current assignment must finish or be reconciled before reassignment.')
+ // Before anything changes: a task given to a closed session is lost at once, and its agent then stays listed until the
+ // task is handed on (closedAgents.ts removeClosedAgents). Without a task it leaves on its machine's next report.
+ // A crew member on its way to another machine takes work once there; an asleep one wakes for it, in place (crewKeep.ts),
+ // so its session is not closed (assignTo wakes it).
+ if (worker.movedTo) fail('CREW_MOVING', `${worker.displayName ?? worker.name} is moving to another machine. Assign it once it has moved.`)
+ if (!worker.asleep && sessionClosed(state, worker, context.now)) {
+ fail('AGENT_CLOSED', `${worker.displayName ?? worker.name}'s session was closed. Start a new agent for this task.`)
+ }
+ projectChatJoin(group, worker.id, worker.displayName ?? worker.name)
+ assignable(worker)
+ sameProject(state, group, worker)
+ const home = groupProject(state, group)
+ // A teammate's agent on a personal machine keeps what it has; it takes no new task for another person's project.
+ requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines, taskAccess(group))
+ // And what the task needs to reach, where it runs (machineAccess.ts): an assignment is held to it as a start is.
+ const unreached = accessRefusal(state, worker.machineId, home, taskAccess(group))
+ if (unreached) failTeamWork(unreached)
+ requireRepositoryReach(state, onTeamAccount(state, worker), worker.machineOwnerId, home, context.repositoryReach)
+ // Team-written code runs only in a Team account (teamWritten.ts, audit H2).
+ pushedRefusal(group, worker)
+ requireTeamWrittenAccount(state, group, worker)
+ if (worker.workDecision === 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
+ // A handed task does not occupy its Engineer (#3399 handed.ts): it may take this.
+ if (state.conversations.some(c => occupiesAgent(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
+ }
+ /** [worker] takes [group]'s work as assignment [assignmentId], after assignRefusal let it: what work.assign writes, and its
+ * brief to the worker. */
+ const assignTo = (group: Conversation, worker: Agent, assignmentId: string) => {
+ // An asleep crew member wakes for it: its host reopens the session in place (crewKeep.ts).
+ wakeCrewMember(worker, context.now)
+ // A Team agent's work marks the task (teamWritten.ts, audit H2).
+ marking(group, () => markTeamWritten(state, group, worker))
+ delete worker.workDecision
+ delete worker.releaseId
+ // Any assignment, an agent's or a person's, takes a worker that lost its task back into routing (model.ts lostTask).
+ delete worker.lostTask
+ if (!group.agentIds.includes(worker.id)) group.agentIds.push(worker.id)
+ // A step's agent works in its task's chat, where its owner and the other steps' agents are (task steps design).
+ const owning = isStep(group) ? state.conversations.find(c => c.id === group.reviewOf) : undefined
+ if (owning && !owning.agentIds.includes(worker.id) && joinsProject(state, owning, worker.id)) owning.agentIds.push(worker.id)
+ rememberAttempt(group)
+ group.assignment = { id: assignmentId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),
+ execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }
+ renewLease(group.assignment, context.now)
+ leadActed(group.id, 'assign')
+ recordRun(state, group, group.assignment, worker, context.now)
+ const others = othersWorkNotice(state, group, worker, context.now, ENGINE_NAMES[worker.configuration.engine] ?? worker.configuration.engine)
+ if (others) effects.messages.push({ id: stableId(assignmentId, 'others-work-notice'), conversationId: others.conversationId, author: sender,
+ replyTo: null, recipients: [], source: { kind: 'others-work-notice', machineId: others.machineId }, text: others.text })
+ group.checks.forEach(c => { c.evidence = null; c.passedBy = null; delete c.verdicts })
+ // The brief (a task with none: its title), and its acceptance checks when it has some: checks are information. Then
+ // whom this task's pull requests are for, from its own requester (projects.ts requestedByLine).
+ const requestedBy = requestedByLine(state, groupProject(state, group), group, worker)
+ message(group.id, [group.brief || group.title,
+ ...group.checks.length ? [`Acceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`] : [],
+ ...requestedBy ? [requestedBy] : []].join('\n\n'), [worker.id], null, SYSTEM_ROW, undefined, undefined, undefined, assignmentId)
+ const news = assignedNotice(state, group, sender, assignmentId)
+ if (news) effects.messages.push(news)
+ }
+ /** The kind of a step already open on a task, by its name, so a step its Engineer opened is reused, not doubled. */
+ const stepKind = (step: Conversation): StepKind | null => {
+ const name = stepName(step)
+ return /security/i.test(name) ? 'security' : /test/i.test(name) ? 'test' : /review|read/i.test(name) ? 'review' : null
+ }
+ /** A new step [planned] of [task], opened as conversation.create opens one with `reviewOf` and `step`. */
+ const openStep = (task: Conversation, planned: PlannedStep, read: NonNullable<CommandContext['pullRequestFiles']>) => {
+ const project = groupProject(state, task)
+ const leadId = conversation(state, project.leadConversationId).leadId
+ const id = stableId(operationId, 'review-step', planned.name)
+ const number = nextConversationNumber(state)
+ state.groupCounter = number
+ const pulls = read.heads ?? read.urls.map((url, i) => ({ url, head: i === 0 ? read.head : null }))
+ const brief = stepBrief(planned, { number: task.number ?? number, title: task.title, pulls })
+ state.conversations.push({ id, ...(state.projects ? { projectId: project.id } : {}), number, title: planned.name, leadId,
+ agentIds: leadId ? [leadId] : [], archived: false, brief, reviewOf: task.id,
+ // A step keeps its task's mark, as conversation.create's does (teamWritten.ts stepMark).
+ ...stepMark(state, task), step: planned.name,
+ assignment: null, lastMessageSequence: 0, checks: storedChecks([{ description: stepCheck(planned), independent: true }], id) })
+ const step = state.conversations.at(-1)!
+ message(id, brief, [], null, SYSTEM_ROW, undefined, undefined, undefined, stableId(id, 'brief'))
+ bindTaskCard(step, effects.messages.at(-1)!)
+ return step
+ }
+ /**
+ * A handed task's review steps (task #3401): the steps its changed files need (reviewTable.ts), each one already open of
+ * that name or kind reused (Workflow 3: the same step for a second round), the rest opened; each not working is assigned to
+ * the first free agent reviewerPick.ts ranks that work.assign's checks let through, its last agent first. A step still
+ * working is left with its agent, who hears this Ready (liveness.ts revisionReady). Nothing is refused: a step nobody may
+ * take stays open, and the PM hears it once.
+ */
+ const openReviewSteps = (task: Conversation, read: NonNullable<CommandContext['pullRequestFiles']>) => {
+ const existing = stepsOf(state, task.id).filter(step => !step.archived)
+ const taken = new Set<string>(), unassigned: string[] = []
+ for (const planned of reviewPlan(read.files, context.projectRules?.rules)) {
+ const free = (step: Conversation) => !taken.has(step.id)
+ let step = existing.find(s => free(s) && stepName(s) === planned.name) ?? existing.find(s => free(s) && stepKind(s) === planned.kind)
+ if (step) taken.add(step.id)
+ if (step && activeWork(step)) continue
+ // A step whose every check passed at this very head keeps its verdict: a repeated Ready (a CI rerun) asks nothing again.
+ if (step && read.head && step.checks.length && step.checks.every(check => check.passedBy
+ && (check.verdicts ?? []).some(verdict => verdict.passed && (verdict as { head?: string }).head === read.head))) continue
+ step ??= openStep(task, planned, read)
+ const previous = step.assignment?.agentId
+ const ranked = reviewerCandidates(state, task, planned.kind, read.head, context.now)
+ const ordered = [...ranked.filter(a => a.id === previous), ...ranked.filter(a => a.id !== previous)]
+ const target = step
+ const worker = ordered.find(candidate => {
+ try { assignRefusal(target, candidate); return true } catch (error) { if (error instanceof SuperTabError) return false; throw error }
+ })
+ if (worker) assignTo(step, worker, stableId(operationId, 'review-step-assign', step.id))
+ else unassigned.push(planned.name)
+ }
+ const leadId = conversation(state, groupProject(state, task).leadConversationId).leadId
+ if (unassigned.length && leadId) {
+ message(task.id, `No free reviewer for ${unassigned.join(', ')} of #${task.number}: no agent of this project is free, never built it, `
+ + 'runs a model at least as strong as its engineer and off the grid, and gave no verdict at this head. The step waits open: start or free one, '
+ + 'and assign it.', [leadId], null, SYSTEM_ROW, undefined, undefined, undefined, stableId(operationId, 'review-unassigned'))
+ }
+ }
+
/** Changing or clearing the Lead of a project's Lead conversation would let it be stopped next. */
const keepLead = (group: Conversation, next: string | null) => {
if (group.leadId && group.leadId !== next && group.id === groupProject(state, group).leadConversationId) protectLead(state, group.leadId, actor)
@@ -2346,6 +2484,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
fail('INVALID_REQUEST', 'A request message opens a task of its own: leave out proposalMessageId, reviewOf and audience.', 400)
}
const request = command.requestMessageId ? requestOf(state, project, context.request) : undefined
+ if (request) settleRequest(state, project, actor.kind === 'agent' ? actor.agentId : null, request.messageId)
const requesterId = command.requesterId ? requester(state, project, command.requesterId)
: proposalRequester(state, project, proposal?.personId) ?? request?.personId ?? (actor.kind === 'person' ? actor.userId : undefined)
// An agent's task says its goal, when it is done, its priority and who asked (taskContract.ts, task #3389). A step and a
@@ -3406,6 +3545,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
fail('FORBIDDEN', 'This agent does not participate in the conversation.', 403)
}
result.changed = react(group, command.messageId, command.on, context.reaction)
+ if (actor.kind === 'agent') settleReaction(state, group, actor.agentId, command.messageId, command.emoji, command.on)
// A reaction is how an agent acknowledges (ACK_ONLY refuses the post), so it settles the agent's delivery of that message.
if (actor.kind === 'agent' && command.on) effects.settles = { messageId: command.messageId, agentId: actor.agentId }
break
@@ -3417,6 +3557,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
break
case 'message.delete':
Object.assign(result, { changed: true }, deleteMessage(open(state, command.conversationId), actor, command.messageId, context.messageChange))
+ settleDeleted(open(state, command.conversationId), command.messageId)
break
case 'member.avatar':
setMemberAvatar(state, actor, command.avatar, context.avatarUpload)
@@ -3593,6 +3734,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// Its project on the row itself, so the row hides once its person loses that project (buddySessions.ts lostProjectRow).
if (session?.inSession) Object.assign(effects.messages.at(-1)!, { buddySession: true, ...(session.project ? { buddyProject: session.project } : {}) })
recordPost(state, group, actor, { replyTo: command.replyTo ?? command.answers ?? null, text, reply: context.reply, openTags: context.openTags }, context.now)
+ // What the PM owes (pulse.ts): a person's message that reached it, settled by its answer in the message's place.
+ if (!command.agentOnly) {
+ const sent = effects.messages.find(m => m.id === operationId)!
+ const root = command.replyTo && context.reply && !context.reply.agentOnly ? context.reply.thread ?? context.reply.id : null
+ if (actor.kind === 'person') owe(state, group, { id: sent.id, author: sent.author, recipients, thread: root, source: sent.source }, context.now)
+ else settleReply(state, group, actor.agentId, { answers: command.answers ?? null, thread: root })
+ }
if (actor.kind === 'agent') renewOwnTask(state, group, actor.agentId, context.now)
// A verdict is usually a post to the Engineer: its own step then waits for the new revision (liveness.ts waitingForRevision).
if (actor.kind === 'agent') toldEngineer(state, group, actor.agentId, recipients, text, context.now)
@@ -3735,38 +3883,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
case 'work.assign': {
chatOnly(command.conversationId)
projectChatWork(command.conversationId)
- const target = agent(state, command.agentId)
- if (state.starts?.some(s => s.poolGeneration && !s.poolSettled && s.request.machineId === target.machineId && s.harnessId === target.harnessId)) {
- fail('START_PENDING', 'Wait for the host to finish this agent’s launch and model selection.')
- }
const group = open(state, command.conversationId)
- if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
- if (activeWork(group)) fail('WORK_ACTIVE', 'The current assignment must finish or be reconciled before reassignment.')
const worker = agent(state, command.agentId)
- // Before anything changes: a task given to a closed session is lost at once, and its agent then stays listed until the
- // task is handed on (closedAgents.ts removeClosedAgents). Without a task it leaves on its machine's next report.
- // A crew member on its way to another machine takes work once there; an asleep one wakes for it, in place (crewKeep.ts).
- if (worker.movedTo) fail('CREW_MOVING', `${worker.displayName ?? worker.name} is moving to another machine. Assign it once it has moved.`)
- const woke = wakeCrewMember(worker, context.now)
- if (!woke && sessionClosed(state, worker, context.now)) {
- fail('AGENT_CLOSED', `${worker.displayName ?? worker.name}'s session was closed. Start a new agent for this task.`)
- }
- projectChatJoin(group, worker.id, worker.displayName ?? worker.name)
- assignable(worker)
- sameProject(state, group, worker)
+ assignRefusal(group, worker)
const home = groupProject(state, group)
- // A teammate's agent on a personal machine keeps what it has; it takes no new task for another person's project.
- requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines, taskAccess(group))
- // And what the task needs to reach, where it runs (machineAccess.ts): an assignment is held to it as a start is.
- const unreached = accessRefusal(state, worker.machineId, home, taskAccess(group))
- if (unreached) failTeamWork(unreached)
- requireRepositoryReach(state, onTeamAccount(state, worker), worker.machineOwnerId, home, context.repositoryReach)
- // Team-written code runs only in a Team account, and a Team agent's work marks the task (teamWritten.ts, audit H2).
- pushedRefusal(group, worker)
- requireTeamWrittenAccount(state, group, worker)
- marking(group, () => markTeamWritten(state, group, worker))
- if (worker.workDecision === 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
- if (state.conversations.some(c => occupiesAgent(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
// An older client assigns in a custom role: kept for older readers, and the role name it means for a worker without
// one (instructions.ts legacyRoleName). No command reads the role.
if (command.roleId) {
@@ -3774,24 +3894,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const roleName = worker.roleName ? undefined : legacyRoleName(home, { roleId: command.roleId })
if (roleName) worker.roleName = roleName
}
- delete worker.workDecision
- delete worker.releaseId
- // Any assignment, an agent's or a person's, takes a worker that lost its task back into routing (model.ts lostTask).
- delete worker.lostTask
- if (!group.agentIds.includes(worker.id)) group.agentIds.push(worker.id)
- // A step's agent works in its task's chat, where its owner and the other steps' agents are (task steps design).
- const owning = isStep(group) ? state.conversations.find(c => c.id === group.reviewOf) : undefined
- if (owning && !owning.agentIds.includes(worker.id) && joinsProject(state, owning, worker.id)) owning.agentIds.push(worker.id)
- rememberAttempt(group)
- group.assignment = { id: operationId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),
- execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }
- renewLease(group.assignment, context.now)
- leadActed(group.id, 'assign')
- recordRun(state, group, group.assignment, worker, context.now)
- const others = othersWorkNotice(state, group, worker, context.now, ENGINE_NAMES[worker.configuration.engine] ?? worker.configuration.engine)
- if (others) effects.messages.push({ id: stableId(operationId, 'others-work-notice'), conversationId: others.conversationId, author: sender,
- replyTo: null, recipients: [], source: { kind: 'others-work-notice', machineId: others.machineId }, text: others.text })
- group.checks.forEach(c => { c.evidence = null; c.passedBy = null; delete c.verdicts })
+ assignTo(group, worker, operationId)
result.assignmentId = operationId
let routeNote: { id: string; text: string; source: Record<string, unknown> } | null = null
if (command.routeDecisionId) {
@@ -3806,14 +3909,6 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
source: { kind: 'route-override', decisionId: decision.id, by: 'lead' } }
else if (routed) routeNote = { id: stableId(operationId, 'route'), ...routed }
}
- // The brief (a task with none: its title), and its acceptance checks when it has some: checks are information. Then
- // whom this task's pull requests are for, from its own requester (projects.ts requestedByLine).
- const requestedBy = requestedByLine(state, home, group, worker)
- message(group.id, [group.brief || group.title,
- ...group.checks.length ? [`Acceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`] : [],
- ...requestedBy ? [requestedBy] : []].join('\n\n'), [worker.id], null, SYSTEM_ROW)
- const news = assignedNotice(state, group, sender, operationId)
- if (news) effects.messages.push(news)
if (routeNote) effects.messages.push({ id: routeNote.id, conversationId: group.id, author: sender,
text: routeNote.text, replyTo: null, recipients: [], source: bookkeeping(group.id, routeNote.source) })
break
@@ -3891,8 +3986,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const asked = !command.ask ? '' : effects.result.notAsked ? `\n\n${effects.result.notAsked}` : `\n\nAsked ${agentWrittenNameOf(state, person(state, command.ask.personId).id)}.`
// The status set, on the row: a Done waits for the coordinator's next digest, what needs someone does not (store.ts writeMessages).
message(group.id, `${label}${command.result ? `\n\n${command.result}` : ''}${asked}`, recipients, null, { ...SYSTEM_ROW, status: command.status })
- // The server opens no review by itself: the agent whose work is ready opens and assigns it, as the project's instructions
- // say (project instructions, phase 4). When no machine the project may use can start either engine, or soon none
+ // The server opens a task's review steps when its pull request's files were read (openReviewSteps, below); when
+ // they were not, the agent whose work is ready opens and assigns them (project instructions, phase 4). When no machine the project may use can start either engine, or soon none
// will, the project's coordinator hears it once, in its chat (reviewCapacity.ts).
const short = command.status === 'review' && !group.reviewOf ? reviewCapacityNotice(state, group, context.now, (machineId, contributorId) =>
!teamWorkCheck(state, machineId, contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)) : null
@@ -3909,6 +4004,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
appendPullRequestUrls(group, [command.result, ...group.checks.map(check => check.evidence)], groupRepositoryUrl(state, group))
}
}
+ // A task's Ready hands it over: the server opens its review steps from the files it changes (task #3401).
+ if (command.status === 'review' && !isStep(group) && context.pullRequestFiles) openReviewSteps(group, context.pullRequestFiles)
if (actor.kind === 'agent') renewOwnTask(state, group, actor.agentId, context.now)
// The time it waited for its review never counts, whoever moved it on.
if (waited && activeWork(group) && !waitingForReview(assignment)) restartQuietTime(assignment, context.now)
diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.ts
index 5d829cf6f..3d0bed1a5 100644
--- a/backend/src/superTabs/instructions.test.ts
+++ b/backend/src/superTabs/instructions.test.ts
@@ -41,6 +41,10 @@ describe('the built-in template', () => {
expect(TEMPLATE_WORKFLOW).toContain("That is the PM's part until the Engineer reports.")
expect(TEMPLATE_WORKFLOW).toContain('The PM opens no task to hold, batch, triage or list work')
expect(TEMPLATE_WORKFLOW).toContain('adds a review step to its task')
+ // Task #3401: the server opens a ready pull request's steps from the files it changes; the Engineer opens them only
+ // where it opened none.
+ expect(TEMPLATE_WORKFLOW).toContain('2. When the pull request is ready, the server opens its review steps from the files it changes')
+ expect(TEMPLATE_WORKFLOW).toContain('Where it opened none, the Engineer adds a review step to its task')
expect(TEMPLATE_WORKFLOW).toContain('it adds no new step for a second round')
expect(TEMPLATE_WORKFLOW).toContain('run `mine`')
expect(TEMPLATE_WORKFLOW).toContain('read `task GROUP`')
diff --git a/backend/src/superTabs/instructionsTemplate.ts b/backend/src/superTabs/instructionsTemplate.ts
index a557a52a9..12b41ad04 100644
--- a/backend/src/superTabs/instructionsTemplate.ts
+++ b/backend/src/superTabs/instructionsTemplate.ts
@@ -80,7 +80,11 @@ export const TEMPLATE_WORKFLOW = `## Workflow
when the task needs that one agent; when no agent can take a role, it starts one.
That is the PM's part until the Engineer reports. The PM opens no task to hold, batch, triage or list work: that
goes in its notes or the project chat.
-2. When the pull request is ready, the Engineer adds a review step to its task, and a test step when the change is
+2. When the pull request is ready, the server opens its review steps from the files it changes and gives each to a free
+ agent of the project that never worked on this task, as strong as its Engineer and with no verdict at that head: a
+ review, two security reviews for sign-in, tokens, encryption, access, the Buddy guard, device links and deletion, and a
+ test step where the change runs. A step nobody was free for waits open, and the PM hears it once.
+ Where it opened none, the Engineer adds a review step to its task, and a test step when the change is
something a user sees or uses (screens, CLI commands, install and release, sign-in, connections between machines,
devices). It picks each Reviewer and Tester then, by Routing's order (the one the PM named, if any), never one that
worked on this task itself, assigns them and messages them directly.
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 266da1d40..2e63170d2 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -1,3 +1,4 @@
+import { recordPulse } from './pulse.js'
import { CREW_REOPEN_GRACE_MS, isCrew } from './crew.js'
import { activeWork, forRecipients, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,
type SuperTabState, type TaskLiveness } from './model.js'
@@ -452,7 +453,10 @@ function unpurged(state: SuperTabState, now: number): MessageDraft[] {
* Lead's poll runs them, where the whole active Swarm is loaded and the one they wake is listening: a machine's reading
* loads only running work and must write no group (read/host.ts). */
export function sweepForLead(state: SuperTabState, now: number): MessageDraft[] {
- return [...sweepLiveness(state, now), ...recordTaskStates(state, now)]
+ const drafts = [...sweepLiveness(state, now), ...recordTaskStates(state, now)]
+ // Where the whole active Swarm is loaded, as for a command: a task lost here may leave Working at 0 (pulse.ts).
+ recordPulse(state, now)
+ return drafts
}
/** A task whose agent has reported nothing itself (a status, check or post) this long is quiet, and its Lead is woken to act
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index cbd9302a3..46fcb61b4 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -444,6 +444,11 @@ export interface Conversation {
/** How urgent its task is (taskPriority.ts), set by conversation.create and work.priority. Absent on a step, a chat and a task
* from before priorities, which reads as P2. */
priority?: import('./taskPriority.js').TaskPriority
+ /** What its project's PM owes here (pulse.ts): people's messages that reached it, not answered, reacted to or made a task
+ * yet, at most MAX_OWED. Bookkeeping: readers get it counted in the pulse, never this list. */
+ owed?: import('./pulse.js').OwedAsk[]
+ /** On a project's chat: its project's pulse as last worked out (pulse.ts recordPulse), which every read sends in `derived`. */
+ pulse?: import('./pulse.js').Pulse
}
/** A step up: the attempt it opened (2 or 3), the least quality from then on, why, when, and what the failed attempt left for
* the next one's brief; the failed start that caused it, if one did. */
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 99acb55e5..ccabbc7ae 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -16,7 +16,7 @@ const conversation: Required<Conversation> = {
task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', teamWritten: true, teamWrittenBy: { kind: 'assigned' }, step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, lastPersonSequence: 0, heardAt: 0, pullRequestUrls: [], pullRequestEvents: {}, cards: {},
messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,
requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', buddySessions: [], buddyDownTold: true, liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },
- stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' }, queueRank: 1.5, notBefore: '2026-12-04', hold: { kind: 'requester' }, priority: 'P0',
+ stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' }, queueRank: 1.5, notBefore: '2026-12-04', hold: { kind: 'requester' }, priority: 'P0', owed: [], pulse: {} as never,
}
describe('the light conversation projection (parts/light.ts)', () => {
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index 9ae56019d..bcf865b0b 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -26,9 +26,9 @@ const running = { $and: [{ $ne: [{ $type: '$data.assignment.status' }, 'missing'
*/
export const GROUP_FIELDS = {
always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
- 'assignment.lost', 'reviewOf'],
+ 'assignment.lost', 'reviewOf', 'pulse'],
whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'teamWritten', 'teamWrittenBy', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore', 'hold', 'priority',
+ unread: ['number', 'brief', 'teamWritten', 'teamWrittenBy', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'heardAt', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp', 'queueRank', 'notBefore', 'hold', 'priority', 'owed',
'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.hold', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt', 'assignment.toldEngineerAt',
'assignment.reopened', 'assignment.handoffs', 'assignment.verdicts'],
} as const
diff --git a/backend/src/superTabs/pullRequestFiles.test.ts b/backend/src/superTabs/pullRequestFiles.test.ts
new file mode 100644
index 000000000..5a36e8de3
--- /dev/null
+++ b/backend/src/superTabs/pullRequestFiles.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from 'vitest'
+import { projectPullRequestFiles, type PullRequestFilesApp } from './pullRequestFiles.js'
+
+function fakeApp(files: Record<number, string[] | null>, heads: Record<number, string> = {}) {
+ const app: PullRequestFilesApp = {
+ resolve: vi.fn(async repository => ({ installation: 1, repository })),
+ createToken: vi.fn(async () => ({ token: 'read-token', expiresAt: '' })),
+ revoke: vi.fn(async () => {}),
+ watchPullRequest: vi.fn(async (_repository, number) => heads[number] ? { head: heads[number]! } as never : null),
+ pullRequestFiles: vi.fn(async (_repository, number) => files[number] === null ? null
+ : (files[number] ?? []).map(filename => ({ filename, status: 'modified', sha: 'x' }))),
+ }
+ return app
+}
+
+const REPO = 'https://github.com/acme/app'
+
+describe('projectPullRequestFiles', () => {
+ it('reads the head and the file names of the project\'s own pull requests, then revokes its token', async () => {
+ const app = fakeApp({ 7: ['a.ts', 'b.ts'], 8: ['b.ts', 'c.ts'] }, { 7: 'abc1234', 8: 'def5678' })
+ const read = await projectPullRequestFiles(app)(REPO, [`${REPO}/pull/7`, `${REPO}/pull/8`, 'https://github.com/other/repo/pull/9'])
+ expect(read).toEqual({ urls: [`${REPO}/pull/7`, `${REPO}/pull/8`], head: 'abc1234', files: ['a.ts', 'b.ts', 'c.ts'],
+ heads: [{ url: `${REPO}/pull/7`, head: 'abc1234' }, { url: `${REPO}/pull/8`, head: 'def5678' }] })
+ expect(app.pullRequestFiles).toHaveBeenCalledTimes(2)
+ expect(app.revoke).toHaveBeenCalledWith('read-token')
+ })
+
+ it('reads the files nothing pushed over: a head that moved while they were listed reads as unreadable', async () => {
+ const app = fakeApp({ 7: ['a.ts'] }, { 7: 'abc1234' })
+ let reads = 0
+ app.watchPullRequest = vi.fn(async () => ({ head: ++reads === 1 ? 'abc1234' : 'def5678' }) as never)
+ expect((await projectPullRequestFiles(app)(REPO, [`${REPO}/pull/7`]))?.files).toBeNull()
+ })
+
+ // Security review 2 of #3227 (Elm): only the first five were read, so a sixth changing sign-in planned an ordinary review.
+ it('plans as unread when a task links more of the project\'s pull requests than it reads', async () => {
+ const urls = Array.from({ length: 6 }, (_, i) => `${REPO}/pull/${i + 1}`)
+ const app = fakeApp(Object.fromEntries(urls.map((_, i) => [i + 1, ['docs/a.md']])), Object.fromEntries(urls.map((_, i) => [i + 1, 'abc1234'])))
+ const read = await projectPullRequestFiles(app)(REPO, urls)
+ expect(read?.files).toBeNull()
+ expect(read?.urls).toEqual(urls)
+ expect(app.pullRequestFiles).not.toHaveBeenCalled()
+ })
+
+ it('has nothing to read with no pull request of the project\'s repository', async () => {
+ const app = fakeApp({})
+ expect(await projectPullRequestFiles(app)(REPO, ['https://github.com/other/repo/pull/9'])).toBeNull()
+ expect(await projectPullRequestFiles(app)(null, [`${REPO}/pull/7`])).toBeNull()
+ expect(app.resolve).not.toHaveBeenCalled()
+ })
+
+ it('says it could not read the files when GitHub cannot, or the app is not installed, or a read throws', async () => {
+ expect((await projectPullRequestFiles(fakeApp({ 7: null }, { 7: 'abc1234' }))(REPO, [`${REPO}/pull/7`]))?.files).toBeNull()
+ const missing = fakeApp({ 7: ['a.ts'] })
+ missing.resolve = vi.fn(async () => null)
+ expect(await projectPullRequestFiles(missing)(REPO, [`${REPO}/pull/7`])).toEqual({ urls: [`${REPO}/pull/7`], head: null, files: null })
+ const broken = fakeApp({ 7: ['a.ts'] }, { 7: 'abc1234' })
+ broken.pullRequestFiles = vi.fn(async () => { throw new Error('socket hang up') })
+ expect((await projectPullRequestFiles(broken)(REPO, [`${REPO}/pull/7`]))?.files).toBeNull()
+ expect(broken.revoke).toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/superTabs/pullRequestFiles.ts b/backend/src/superTabs/pullRequestFiles.ts
new file mode 100644
index 000000000..5b9332976
--- /dev/null
+++ b/backend/src/superTabs/pullRequestFiles.ts
@@ -0,0 +1,64 @@
+/**
+ * The files a task's pull requests change, read with the Harness GitHub App when its Engineer hands it over (task #3401):
+ * what reviewTable.ts plans its review steps from. Only pull requests of the project's own repository are read, at most
+ * MAX_PULLS, with one read-only token revoked when done. Any failure reads as files null, which plans the strictest steps.
+ */
+import { PULL_WATCH_PERMISSIONS, type GitHubApp } from '../github/app.js'
+import { githubRepository, type GitHubRepository } from '../github/repository.js'
+import { logger } from '../utils/logger.js'
+
+/** What this read needs of the app: the pull request's head from its watch read, and its files (github/app.ts). */
+export interface PullRequestFilesApp {
+ resolve: GitHubApp['resolve']
+ createToken: GitHubApp['createToken']
+ revoke: GitHubApp['revoke']
+ watchPullRequest(repository: GitHubRepository, number: number, token: string): Promise<{ head: string } | null>
+ pullRequestFiles(repository: GitHubRepository, number: number, token: string): Promise<Array<{ filename: string }> | null>
+}
+
+/** What the store gives a Ready's command: the pull requests read, the first one's head (what a verdict is held to), each
+ * one's own head, and every file they change. */
+export interface PullRequestFilesRead { urls: string[]; head: string | null; files: string[] | null; heads?: Array<{ url: string; head: string | null }> }
+
+const MAX_PULLS = 5
+const PULL = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/([1-9][0-9]*)$/
+
+/** The store's hook: null when [urls] holds no pull request of [repositoryUrl]'s repository, so there is nothing to read. */
+export const projectPullRequestFiles = (app: PullRequestFilesApp) =>
+ async (repositoryUrl: string | null, urls: string[]): Promise<PullRequestFilesRead | null> => {
+ const repository = githubRepository(repositoryUrl)
+ if (!repository) return null
+ const own = urls.flatMap(url => {
+ const match = PULL.exec(url)
+ return match && match[1]!.toLowerCase() === repository.fullName.toLowerCase() ? [{ url, number: Number(match[2]) }] : []
+ })
+ if (!own.length) return null
+ const read: PullRequestFilesRead = { urls: own.map(pull => pull.url), head: null, files: null }
+ // More than it reads: the ones left unread could change anything, so the plan is as strict as the rules go, never one
+ // made from some of them (security review 2 of #3227).
+ if (own.length > MAX_PULLS) return read
+ let token: string | null = null
+ try {
+ const resolved = await app.resolve(repository)
+ if (!resolved) return read
+ token = (await app.createToken(resolved.installation, resolved.repository, PULL_WATCH_PERMISSIONS)).token
+ const files = new Set<string>(), heads: Array<{ url: string; head: string | null }> = []
+ for (const [i, pull] of own.entries()) {
+ // The files of the head the watch read: when a push moved it while they were listed, they read as unreadable.
+ const watch = await app.watchPullRequest(resolved.repository, pull.number, token)
+ if (i === 0) read.head = watch?.head ?? null
+ heads.push({ url: pull.url, head: watch?.head ?? null })
+ const listed = watch ? await app.pullRequestFiles(resolved.repository, pull.number, token) : null
+ const after = listed ? await app.watchPullRequest(resolved.repository, pull.number, token) : null
+ const changed = listed && after?.head === watch!.head ? listed : null
+ if (!changed) return { ...read, files: null }
+ for (const file of changed) files.add(file.filename)
+ }
+ return { ...read, files: [...files], heads }
+ } catch (error) {
+ logger.warn('[swarm-review-steps] pull request files not read', { error: error instanceof Error ? error.message : String(error) })
+ return { ...read, files: null }
+ } finally {
+ if (token) await app.revoke(token).catch(() => {})
+ }
+ }
diff --git a/backend/src/superTabs/pulse.test.ts b/backend/src/superTabs/pulse.test.ts
new file mode 100644
index 000000000..d032dcf22
--- /dev/null
+++ b/backend/src/superTabs/pulse.test.ts
@@ -0,0 +1,289 @@
+/**
+ * The board's pulse (task #3384, anh Dee's Swarm redesign, 11-05): what the PM owes and who works, from stored state, so
+ * nothing waits unseen. On 11-05 the board showed Working 0 and five people's asks unanswered for 3-10 h because nothing
+ * tracked what the PM owed and the idle checks ran only on the PM's poll.
+ */
+import { describe, expect, it } from 'vitest'
+import type { Command, CommandContext } from './commands.js'
+import type { Author } from './model.js'
+import { sweepForLead } from './liveness.js'
+import { projectsOf } from './projects.js'
+import { recordPulse, storedPulse } from './pulse.js'
+import { owner, stepsFixture } from './steps.test-support.js'
+
+const MINUTE = 60_000
+/** What a task an agent opens must say (commands.ts): at least one check, with a priority and who asked. */
+const DONE_WHEN = [{ description: 'It works', independent: false }]
+
+function setup() {
+ const f = stepsFixture()
+ const person: Author = { kind: 'person', id: 'owner', name: owner.email, membershipGeneration: f.state.people[0]!.generation } as Author
+ /** A message in [on] by [by] (a person when null); in reply to [reply] (its thread root [thread]) or answering [answers]. */
+ const post = (by: string | null, on: string, text: string, options: { reply?: string; thread?: string; answers?: string; replyAuthor?: Author; recipientIds?: string[] } = {}) => {
+ const target = options.reply ?? options.answers
+ const context: Partial<CommandContext> = target
+ ? { reply: { id: target, conversationId: on, author: options.replyAuthor ?? person, createdAt: 0, thread: options.thread ?? target } } : {}
+ const effects = f.run({ type: 'message.send', conversationId: on, text, replyTo: options.reply ?? null, recipientIds: options.recipientIds ?? [],
+ ...options.answers ? { answers: options.answers } : {} } as Command, by ? f.as(by) : owner, context)
+ return effects.result.messageId as string
+ }
+ const owed = (on = 'lead') => (f.group(on).owed ?? []).map(ask => ask.id)
+ const react = (by: string, on: string, messageId: string, emoji: string) => f.run({ type: 'message.react', conversationId: on, messageId, emoji, on: true } as Command,
+ f.as(by), { reaction: { messageId, reacted: false } })
+ const request = (id: string) => ({ id, conversationId: 'lead', replyTo: null, source: null, author: person })
+ const taskFrom = (ask: string) => f.run({ type: 'conversation.create', title: 'From the ask', brief: 'Do it.', checks: DONE_WHEN, priority: 'P2', requestMessageId: ask } as Command,
+ f.as(f.lead), { request: request(ask) } as Partial<CommandContext>)
+ return { f, post, owed, react, taskFrom, person, request }
+}
+
+describe('what the PM owes', () => {
+ it('is a person\'s message to the PM, with who asked and when', () => {
+ const { f, post } = setup()
+ const ask = post(null, 'lead', 'Can the board show who is working?')
+ expect(f.group('lead').owed).toEqual([{ id: ask, personId: 'owner', at: f.now, thread: ask }])
+ })
+
+ it('is not an agent\'s message, nor a person\'s to another agent', () => {
+ const { f, post, owed } = setup()
+ post(f.dev, 'lead', 'PR #12 is ready.')
+ const line = post(f.dev, 'lead', 'Engineer here: a question for Ken.')
+ // A person answering the Engineer's line in its thread talks to the Engineer, not the PM.
+ post(null, 'lead', 'Use the second option.', { reply: line, replyAuthor: { kind: 'agent', id: f.dev, name: 'dev' } as Author })
+ expect(owed()).toEqual([])
+ })
+
+ it('is not a message in a private chat', () => {
+ const { f, post, owed } = setup()
+ // An older Chat with PM: its audience is the person alone (new ones are closed, so it is written as stored).
+ f.state.conversations.push({ id: 'private', title: 'Chat with PM', leadId: f.lead, agentIds: [f.lead], archived: false, brief: '', checks: [],
+ assignment: null, lastMessageSequence: 0, audience: { people: [{ id: 'owner', generation: f.state.people[0]!.generation }] } } as never)
+ try { post(null, 'private', 'A private question.') } catch { /* closed to new messages: nothing can be owed there either */ }
+ expect(owed('private')).toEqual([])
+ })
+
+ it('is settled by the PM\'s reply in its thread, which settles the whole thread', () => {
+ const { f, post, owed } = setup()
+ const ask = post(null, 'lead', 'Why is Working 0?')
+ const more = post(null, 'lead', 'Still nothing.', { reply: ask })
+ const other = post(null, 'lead', 'And a second topic.')
+ expect(owed()).toEqual([ask, more, other])
+ post(f.lead, 'lead', 'Two agents start now.', { reply: more, thread: ask })
+ expect(owed()).toEqual([other])
+ })
+
+ it('is settled by the PM\'s answer right below it, that message alone', () => {
+ const { f, post, owed } = setup()
+ const first = post(null, 'lead', 'First ask.')
+ const second = post(null, 'lead', 'Second ask.')
+ post(f.lead, 'lead', 'Done.', { answers: second })
+ expect(owed()).toEqual([first])
+ })
+
+ it('is settled by the PM\'s verdict reaction, never by eyes', () => {
+ const { f, post, owed, react } = setup()
+ const ask = post(null, 'lead', 'Please merge #12.')
+ react(f.lead, 'lead', ask, 'eyes')
+ expect(owed()).toEqual([ask])
+ react(f.lead, 'lead', ask, 'check')
+ expect(owed()).toEqual([])
+ for (const emoji of ['thumbs_up', 'rocket', 'tada']) {
+ const next = post(null, 'lead', `Another ${emoji}.`)
+ react(f.lead, 'lead', next, emoji)
+ expect(owed()).toEqual([])
+ }
+ })
+
+ it('is settled by a task the PM opens from it', () => {
+ const { post, owed, taskFrom } = setup()
+ const ask = post(null, 'lead', 'Show unanswered asks on the board.')
+ taskFrom(ask)
+ expect(owed()).toEqual([])
+ })
+
+ // River's ruling on Hugo's review of #3209: only a task the PM opens from the ask settles it; one anyone else opens leaves the
+ // PM's answer owed.
+ it('is not settled by a task someone else opens from it', () => {
+ const { f, post, owed, request } = setup()
+ const ask = post(null, 'lead', 'Can we get dark mode?')
+ f.run({ type: 'conversation.create', title: 'Dark mode', brief: 'Dark mode.', checks: [], requestMessageId: ask } as Command, owner,
+ { request: request(ask) } as Partial<CommandContext>)
+ expect(owed()).toEqual([ask])
+ })
+
+ // ReviewPulse2's review of #3209: a deleted ask has nothing left to answer, and its link would open a message that is gone.
+ it('is settled when its message is deleted, kept as deleted or not', () => {
+ const { f, post, owed } = setup()
+ const [gone, kept] = [post(null, 'lead', 'Never mind.'), post(null, 'lead', 'Drop this too.')]
+ const remove = (messageId: string, hasReplies: boolean) => f.run({ type: 'message.delete', conversationId: 'lead', messageId } as Command, owner,
+ { messageChange: { messageId, author: { kind: 'person', id: 'owner' }, plain: true, deleted: false, hasFiles: false, hasReplies, text: 'x', sequence: 1 } })
+ remove(gone, false)
+ remove(kept, true)
+ expect(owed()).toEqual([])
+ })
+
+ // River, on ReviewPulse2's review of #3209: the asks of a person who left the Swarm are owed to nobody.
+ it('is settled when the person who asked leaves the Swarm', () => {
+ const { f, owed } = setup()
+ const peer = { kind: 'person' as const, userId: 'peer', email: '[email protected]' }
+ const invited = f.run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' } as Command)
+ f.run({ type: 'invite.accept', inviteId: invited.result.inviteId as string } as Command, peer)
+ f.run({ type: 'message.send', conversationId: 'lead', text: 'One ask before I go.', replyTo: null, recipientIds: [] } as Command, peer)
+ expect(owed()).toHaveLength(1)
+ f.run({ type: 'member.remove', userId: 'peer' } as Command)
+ expect(owed()).toEqual([])
+ })
+
+ it('is not settled by another agent\'s reply or reaction', () => {
+ const { f, post, owed, react } = setup()
+ const ask = post(null, 'lead', 'Who reviews #12?')
+ post(f.dev, 'lead', 'I can.', { reply: ask })
+ react(f.dev, 'lead', ask, 'check')
+ expect(owed()).toEqual([ask])
+ })
+
+ it('keeps the newest 50 of one chat', () => {
+ const { f, post, owed } = setup()
+ const asks = Array.from({ length: 55 }, (_, i) => { f.tick(MINUTE); return post(null, 'lead', `Ask ${i}.`) })
+ expect(owed()).toEqual(asks.slice(5))
+ })
+})
+
+describe('the pulse', () => {
+ /** The pulse as the next command or sweep records it on the project's chat (state edited by hand is counted too). */
+ const pulseOf = (f: ReturnType<typeof stepsFixture>) => { recordPulse(f.state, f.now); return storedPulse(f.state, projectsOf(f.state)[0]!)! }
+ /** The pulse as recorded, without working it out again. */
+ const stored = (f: ReturnType<typeof stepsFixture>) => storedPulse(f.state, projectsOf(f.state)[0]!)!
+ /** A task the PM opens, unassigned (Next up). */
+ const open = (f: ReturnType<typeof stepsFixture>, title: string, extra: { notBefore?: string } = {}) => {
+ const id = f.run({ type: 'conversation.create', title, brief: `${title}.`, checks: DONE_WHEN, priority: 'P2', requesterId: 'owner' } as Command, f.as(f.lead)).result.conversationId as string
+ if (extra.notBefore) f.run({ type: 'work.queue', conversationId: id, notBefore: extra.notBefore, hold: { kind: 'requester' } } as Command, f.as(f.lead))
+ return id
+ }
+ const status = (f: ReturnType<typeof stepsFixture>, task: string, by: string, value: string, result: string | null) =>
+ f.run({ type: 'work.status', conversationId: task, assignmentId: f.group(task).assignment!.id, status: value, result } as Command, f.as(by))
+
+ it('counts the asks the PM owes, the oldest one\'s age and who asked', () => {
+ const { f, post } = setup()
+ const first = post(null, 'lead', 'First.')
+ f.tick(4 * MINUTE)
+ post(null, 'lead', 'Second.')
+ const pulse = pulseOf(f)
+ expect(pulse.pmId).toBe(f.lead)
+ expect(pulse.asks).toMatchObject({ count: 2, oldestAt: f.now - 4 * MINUTE, personId: 'owner' })
+ expect(pulse.asks.list[0]).toEqual({ conversationId: 'lead', messageId: first, personId: 'owner', at: f.now - 4 * MINUTE })
+ })
+
+ it('counts Working of the crew: agents of the project with a task they work on, never the PM', () => {
+ const { f } = setup()
+ const idle = f.add('idle', f.task)
+ expect(pulseOf(f).working).toEqual({ count: 1, crew: 2, agentIds: [f.dev] })
+ status(f, f.task, f.dev, 'review', 'PR #12')
+ expect(pulseOf(f).working).toEqual({ count: 0, crew: 2, agentIds: [] })
+ expect(idle).toBeTruthy()
+ })
+
+ it('counts Next up: open tasks nobody is assigned, never a step or a task set for a later day', () => {
+ const { f } = setup()
+ const a = open(f, 'Board strip'), b = open(f, 'Phone strip')
+ f.step('Review')
+ open(f, 'Later', { notBefore: '2099-01-01' })
+ expect(pulseOf(f).nextUp).toEqual({ count: 2, conversationIds: [a, b] })
+ })
+
+ it('counts Lost with when the oldest lost its agent', () => {
+ const { f } = setup()
+ const lostAt = f.now
+ f.group(f.task).assignment!.status = 'lost'
+ f.group(f.task).assignment!.lost = { reason: 'its session stopped', at: lostAt }
+ f.tick(3 * MINUTE)
+ expect(pulseOf(f).lost).toEqual({ count: 1, since: lostAt, conversationIds: [f.task] })
+ })
+
+ // ReviewPulse2's review of the merge with #3390: a hold's reason is the one main records (heldReason.ts heldView), never the
+ // agent's result text; a hold with none recorded is "no reason", as the board shows it.
+ it('counts Held with the reason recorded for it: blocked or needs a person, and a task set for a later day', () => {
+ const { f } = setup()
+ const later = '2099-01-01T00:00:00.000Z'
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'blocked', result: null,
+ hold: { kind: 'reset', what: 'quota', at: later } } as Command, f.as(f.dev))
+ const other = open(f, 'Second')
+ const builder = f.add('builder', other)
+ f.run({ type: 'work.assign', conversationId: other, agentId: builder }, f.as(f.lead))
+ status(f, other, builder, 'needs_human', 'Which bucket should the logs go to?')
+ const dated = open(f, 'Later', { notBefore: '2099-01-01' })
+ const held = pulseOf(f).held
+ expect(held.count).toBe(3)
+ expect(held.withoutReason).toBe(1)
+ expect(held.list).toEqual([{ conversationId: f.task, reason: 'waits for a quota reset' },
+ { conversationId: other, reason: null }, { conversationId: dated, reason: 'the requester asked for later, not before 2099-01-01' }])
+ })
+
+ it('turns red for a hold with no reason recorded, not for one with a reason and no words', () => {
+ const { f } = setup()
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'blocked', result: null,
+ hold: { kind: 'requester' } } as Command, f.as(f.dev))
+ expect(pulseOf(f).redAt.held).toBeNull()
+ status(f, f.task, f.dev, 'blocked', 'Stuck on the key, says why in words only.')
+ expect(pulseOf(f).redAt.held).toBe(0)
+ })
+
+ it('counts a blocked task whose agent is gone as Lost, not Held: it waits for an agent first', () => {
+ const { f } = setup()
+ status(f, f.task, f.dev, 'blocked', 'Waiting for the key.')
+ f.group(f.task).liveness = { state: 'orphaned', why: 'removed', since: f.now }
+ expect(pulseOf(f).lost.conversationIds).toEqual([f.task])
+ expect(pulseOf(f).held.count).toBe(0)
+ })
+
+ it('gives no hold to a task set for a day already here', () => {
+ const { f } = setup()
+ const today = open(f, 'Today', { notBefore: new Date(f.now).toISOString().slice(0, 10) })
+ expect(pulseOf(f).held.count).toBe(0)
+ expect(pulseOf(f).nextUp.conversationIds).toContain(today)
+ })
+
+ it('says when each red rule turns red, by the limits it sends', () => {
+ const { f, post } = setup()
+ expect(pulseOf(f).limits).toEqual({ askMinutes: 15, idleMinutes: 10, lostMinutes: 10 })
+ expect(pulseOf(f).redAt).toEqual({ asks: null, idle: null, lost: null, held: null })
+ post(null, 'lead', 'An ask.')
+ const askedAt = f.now
+ expect(pulseOf(f).redAt.asks).toBe(askedAt + 15 * MINUTE)
+ status(f, f.task, f.dev, 'blocked', null)
+ expect(pulseOf(f).redAt.held).toBe(0)
+ })
+
+ it('a lost task turns red 10 minutes after it lost its agent', () => {
+ const { f } = setup()
+ f.group(f.task).assignment!.status = 'lost'
+ f.group(f.task).assignment!.lost = { reason: 'its session stopped', at: f.now }
+ expect(pulseOf(f).redAt.lost).toBe(f.now + 10 * MINUTE)
+ })
+
+ it('marks when Working fell to 0 while work waits, and turns red 10 minutes later; work again clears it', () => {
+ const { f } = setup()
+ open(f, 'Waiting task')
+ expect(pulseOf(f).idleSince).toBeNull()
+ f.tick(MINUTE)
+ status(f, f.task, f.dev, 'done', 'Merged.')
+ const idleAt = f.now
+ f.tick(MINUTE)
+ f.run({ type: 'message.send', conversationId: 'lead', text: 'Anyone?', replyTo: null, recipientIds: [] } as Command)
+ expect(stored(f).idleSince).toBe(idleAt)
+ expect(stored(f).asks.count).toBe(1)
+ expect(pulseOf(f).redAt.idle).toBe(idleAt + 10 * MINUTE)
+ const task = pulseOf(f).nextUp.conversationIds[0]!
+ f.run({ type: 'work.assign', conversationId: task, agentId: f.dev }, f.as(f.lead))
+ expect(pulseOf(f).idleSince).toBeNull()
+ expect(pulseOf(f).redAt.idle).toBeNull()
+ })
+
+ it('marks idle on the PM\'s sweep too, where a lost task is found', () => {
+ const { f } = setup()
+ f.group(f.task).assignment!.status = 'lost'
+ f.group(f.task).assignment!.lost = { reason: 'its session stopped', at: f.now }
+ sweepForLead(f.state, f.now)
+ expect(stored(f).idleSince).toBe(f.now)
+ expect(stored(f).lost.count).toBe(1)
+ })
+})
diff --git a/backend/src/superTabs/pulse.ts b/backend/src/superTabs/pulse.ts
new file mode 100644
index 000000000..978f192b3
--- /dev/null
+++ b/backend/src/superTabs/pulse.ts
@@ -0,0 +1,263 @@
+/**
+ * The board's pulse (task #3384, anh Dee's Swarm redesign, 11-05): what each project's PM owes and who works, from stored
+ * state, shown to everyone on the board so nothing waits unseen. On 11-05 the board showed Working 0 and five people's asks
+ * unanswered for 3-10 h: nothing tracked what the PM owed, and the idle checks ran only on the PM's poll.
+ *
+ * An owed ask is a person's message that reached the PM, kept on its conversation (`Conversation.owed`) until the PM answers
+ * it in its place (a reply in its thread, or an answer right below it), gives it a verdict reaction, or opens a task from it.
+ * Nothing here refuses anything: a settle that finds nothing does nothing.
+ */
+import { isBuddy, isBuddyChat } from './buddies.js'
+import { heldView, type HeldReason } from './heldReason.js'
+import { isLeads, type Author, type Conversation, type SuperTabState } from './model.js'
+import { agentProjectId, groupProject, type SwarmProject } from './projects.js'
+
+/** One person's message to the PM not settled yet: its id, who wrote it, when, and the root of the thread it is in (its own
+ * id for a top-level message). */
+export interface OwedAsk { id: string; personId: string; at: number; thread: string }
+
+/** At most this many asks are kept per conversation, the newest: a growth bound, far above what a PM leaves unanswered. */
+export const MAX_OWED = 50
+/** The reactions that answer an ask (reactions.ts): a verdict. Eyes says the PM saw it, and it still owes the answer. */
+export const VERDICT_REACTIONS: ReadonlySet<string> = new Set(['check', 'thumbs_up', 'rocket', 'tada'])
+
+/** The project [group] belongs to, or none for a conversation outside every project (the removed Leads chat, a person's one
+ * Buddy chat). Never throws: the pulse is never a reason for a command to fail. */
+function projectOfGroup(state: SuperTabState, group: Conversation): SwarmProject | undefined {
+ if (isLeads(group) || group.kind === 'swarm-buddy') return undefined
+ try { return groupProject(state, group) } catch { return undefined }
+}
+
+/** The agent leading [project]: its chat's Lead. */
+export function pmOf(state: SuperTabState, project: SwarmProject): string | null {
+ return state.conversations.find(c => c.id === project.leadConversationId)?.leadId ?? null
+}
+
+/** Whether asks in [group] count: a project's chat or task, never a private chat or a Buddy chat, whose words and people only
+ * their audience reads (the pulse is shown to every reader of the project). */
+const counted = (group: Conversation): boolean => !group.audience && !group.kind && !isBuddyChat(group)
+
+/** Records [message] as owed when a person wrote it and it reached [group]'s PM. */
+export function owe(state: SuperTabState, group: Conversation, message: { id: string; author: Author; recipients: readonly string[]; thread: string | null; source?: unknown }, now: number): void {
+ if (message.author.kind !== 'person' || message.source || !counted(group)) return
+ const project = projectOfGroup(state, group)
+ const pm = project && pmOf(state, project)
+ if (!pm || !message.recipients.includes(pm)) return
+ group.owed = [...(group.owed ?? []).filter(ask => ask.id !== message.id), { id: message.id, personId: message.author.id, at: now, thread: message.thread ?? message.id }]
+ .slice(-MAX_OWED)
+}
+
+function settle(group: Conversation, settled: (ask: OwedAsk) => boolean): void {
+ if (!group.owed) return
+ const left = group.owed.filter(ask => !settled(ask))
+ if (left.length === group.owed.length) return
+ if (left.length) group.owed = left
+ else delete group.owed
+}
+
+const byPm = (state: SuperTabState, group: Conversation, agentId: string): boolean => {
+ const project = projectOfGroup(state, group)
+ return !!project && pmOf(state, project) === agentId
+}
+
+/** The PM's post in [group]: a reply in a thread ([thread], its root) settles every ask in that thread; an answer right below a
+ * message ([answers]) settles that message. */
+export function settleReply(state: SuperTabState, group: Conversation, agentId: string, place: { answers: string | null; thread: string | null }): void {
+ if (!group.owed || !byPm(state, group, agentId)) return
+ settle(group, ask => ask.id === place.answers || (!!place.thread && ask.thread === place.thread))
+}
+
+/** The PM's verdict reaction on [messageId] settles it. */
+export function settleReaction(state: SuperTabState, group: Conversation, agentId: string, messageId: string, emoji: string, on: boolean): void {
+ if (!on || !VERDICT_REACTIONS.has(emoji) || !group.owed || !byPm(state, group, agentId)) return
+ settle(group, ask => ask.id === messageId)
+}
+
+/** [messageId], deleted by its author: nothing is left to answer, and its link would open a message that is gone. */
+export function settleDeleted(group: Conversation, messageId: string): void {
+ settle(group, ask => ask.id === messageId)
+}
+
+/** A task the PM opens from the person's request [messageId] in [project]'s chat settles it (commands.ts requestOf); one anyone
+ * else opens leaves the PM's answer owed (River's ruling on the review of #3209). */
+export function settleRequest(state: SuperTabState, project: SwarmProject, agentId: string | null, messageId: string): void {
+ const chat = state.conversations.find(c => c.id === project.leadConversationId)
+ if (chat && agentId && pmOf(state, project) === agentId) settle(chat, ask => ask.id === messageId)
+}
+
+
+/** When each rule turns the strip red (anh Dee's brief), sent with the pulse so no app holds a threshold. */
+export interface PulseLimits { askMinutes: number; idleMinutes: number; lostMinutes: number }
+export const PULSE_LIMITS: PulseLimits = { askMinutes: 15, idleMinutes: 10, lostMinutes: 10 }
+
+/** A project's pulse. `redAt`: when each rule turns red (0: already, by its nature), null while it cannot. */
+export interface Pulse {
+ pmId: string | null
+ asks: { count: number; oldestAt: number | null; personId: string | null; list: Array<{ conversationId: string; messageId: string; personId: string; at: number }> }
+ working: { count: number; crew: number; agentIds: string[] }
+ nextUp: { count: number; conversationIds: string[] }
+ lost: { count: number; since: number | null; conversationIds: string[] }
+ held: { count: number; withoutReason: number; list: Array<{ conversationId: string; reason: string | null }> }
+ idleSince: number | null
+ redAt: { asks: number | null; idle: number | null; lost: number | null; held: number | null }
+ limits: PulseLimits
+}
+
+const ENDED = new Set(['done', 'stopped', 'cancelled'])
+const MINUTE = 60_000
+
+/** The day [now] falls on, as a task's `notBefore` is written. */
+const dayOf = (now: number): string => new Date(now).toISOString().slice(0, 10)
+
+/** A recorded hold reason in a few words, as the strip's Held list shows it. */
+export function heldWords(reason: HeldReason): string {
+ switch (reason.kind) {
+ case 'task': return `waits on #${reason.taskNumber}`
+ case 'person': return 'waits on a person\'s answer'
+ case 'reset': return `waits for a ${reason.what} reset`
+ case 'requester': return 'the requester asked for later'
+ }
+}
+
+/**
+ * Whether [group] is held, and why (River's ruling, 11-05): its agent set blocked or needs a person, or nobody is assigned and
+ * it is set for a later day. Its reason is the one recorded for the hold (#3390, heldReason.ts heldView, the one place that
+ * reads it), in words; none recorded is no reason, as the board shows it. A date also says the day. ReviewPulse2 on the merge
+ * with #3390: the agent's result text decided it before, a second way to decide one thing.
+ */
+export function holdOf(group: Conversation, today: string): { reason: string | null } | null {
+ const assignment = group.assignment
+ const dated = !assignment && !!group.notBefore && group.notBefore > today
+ const stated = !!assignment && (assignment.status === 'blocked' || assignment.status === 'needs_human')
+ if (!dated && !stated) return null
+ const view = heldView(group)
+ const words = view && view.kind !== 'none' ? heldWords(view) : null
+ return { reason: words && dated ? `${words}, not before ${group.notBefore}` : words }
+}
+
+/** Whether [group] lost its agent: lost, or nobody holds it (liveness.ts `orphaned`), and since when. */
+function lostSince(group: Conversation): number | null {
+ const assignment = group.assignment
+ if (!assignment || ENDED.has(assignment.status)) return null
+ if (assignment.status === 'lost') return assignment.lost?.at ?? group.liveness?.since ?? 0
+ return group.liveness?.state === 'orphaned' ? group.liveness.since : null
+}
+
+interface Counts { working: Set<string>; crew: string[]; nextUp: string[]; lost: Array<{ id: string; since: number }>; held: Array<{ conversationId: string; reason: string | null }> }
+
+/** Each agent's project, worked out once for every project counted (agentProjectId may search the conversations). */
+export const agentProjects = (state: SuperTabState): Map<string, string> => new Map(state.agents.map(a => [a.id, agentProjectId(state, a)]))
+
+/** The Swarm's open conversations and agents by project, sorted out in one pass, so a pulse for every project costs one walk of
+ * the Swarm rather than one per project: recordPulse runs after every command (ENGINEERING 4). */
+export interface PulseIndex {
+ /** Each project's open tasks and steps, never its chat, a private chat or a Buddy chat. */
+ work: Map<string, Conversation[]>
+ /** Each project's open conversations that hold owed asks. */
+ owing: Map<string, Conversation[]>
+ /** Each project's agents but Buddies. */
+ agents: Map<string, string[]>
+}
+export function pulseIndex(state: SuperTabState, projectOfAgent = agentProjects(state), only?: string): PulseIndex {
+ const chats = new Set((state.projects ?? []).map(p => p.leadConversationId))
+ const index: PulseIndex = { work: new Map(), owing: new Map(), agents: new Map() }
+ const add = <T>(map: Map<string, T[]>, key: string, value: T) => { const list = map.get(key); if (list) list.push(value); else map.set(key, [value]) }
+ for (const group of state.conversations) {
+ if (group.archived || !counted(group)) continue
+ const projectId = group.projectId ?? 'lead'
+ if (only && projectId !== only) continue
+ if (group.owed?.length) add(index.owing, projectId, group)
+ if (!chats.has(group.id)) add(index.work, projectId, group)
+ }
+ for (const agent of state.agents) if (!isBuddy(agent)) add(index.agents, projectOfAgent.get(agent.id) ?? agentProjectId(state, agent), agent.id)
+ return index
+}
+
+function countWork(state: SuperTabState, project: SwarmProject, now: number, index: PulseIndex): Counts {
+ const pm = pmOf(state, project)
+ const crew = (index.agents.get(project.id) ?? []).filter(id => id !== pm)
+ const inCrew = new Set(crew), today = dayOf(now)
+ const counts: Counts = { working: new Set(), crew, nextUp: [], lost: [], held: [] }
+ for (const group of index.work.get(project.id) ?? []) {
+ const assignment = group.assignment
+ // Lost first: a blocked task whose agent is gone waits for an agent before anything else.
+ const since = lostSince(group)
+ if (since !== null) { counts.lost.push({ id: group.id, since }); continue }
+ const hold = holdOf(group, today)
+ if (hold) { counts.held.push({ conversationId: group.id, reason: hold.reason }); continue }
+ if (!assignment) { if (!group.reviewOf) counts.nextUp.push(group.id); continue }
+ if (assignment.status === 'working' && inCrew.has(assignment.agentId)) counts.working.add(assignment.agentId)
+ }
+ return counts
+}
+
+/** Working is 0 while work waits (Next up or lost). */
+const idle = (counts: Counts): boolean => !counts.working.size && (counts.nextUp.length > 0 || counts.lost.length > 0)
+
+/** The most of each list a stored pulse keeps (its counts stay whole): a growth bound on the project chat's part. */
+export const PULSE_LIST_MAX = 50
+
+/**
+ * Works out each project's pulse and keeps it on the project's chat, where every read finds it: a change poll reads only the
+ * light base (the project chats and running work, light fields: parts/light.ts), so a pulse derived at read time from it lost
+ * the asks and Next up a full read showed (Hugo's review of #3209). Run where every open group is loaded, after each command
+ * and on the PM's sweep, so the board reddens on time without anyone's poll. Writes only on a change. When Working fell to 0
+ * while work waits is kept in it (`idleSince`) from one run to the next.
+ */
+export function recordPulse(state: SuperTabState, now: number, only?: string): void {
+ // The asks of a person who left the Swarm are owed to nobody, however they left.
+ const people = new Set(state.people.map(p => p.id))
+ for (const group of state.conversations) if (group.owed?.some(ask => !people.has(ask.personId))) settle(group, ask => !people.has(ask.personId))
+ if (!state.projects?.length) return
+ // [only]: the one project a command's conversation is in, whose pulse alone it can move; every project otherwise.
+ const projects = only ? state.projects.filter(p => p.id === only) : state.projects
+ const index = pulseIndex(state, agentProjects(state), only), chats = new Map(state.conversations.map(c => [c.id, c]))
+ for (const project of projects) {
+ const chat = chats.get(project.leadConversationId)
+ if (!chat) continue
+ const pulse = projectPulse(state, project, now, PULSE_LIMITS, index, chat.pulse?.idleSince ?? null)
+ if (JSON.stringify(pulse) !== JSON.stringify(chat.pulse)) chat.pulse = pulse
+ }
+}
+
+/** The project of the conversation [command] names, whose pulse alone it can move; undefined for a command that names none, or
+ * a conversation outside every project, which may move any. */
+export function pulseProjectOf(state: SuperTabState, command: object): string | undefined {
+ const id = (command as { conversationId?: unknown }).conversationId
+ const group = typeof id === 'string' ? state.conversations.find(c => c.id === id) : undefined
+ return group ? projectOfGroup(state, group)?.id : undefined
+}
+
+/** [project]'s pulse as last recorded on its chat (recordPulse), or none. */
+export const storedPulse = (state: SuperTabState, project: SwarmProject): Pulse | undefined =>
+ state.conversations.find(c => c.id === project.leadConversationId)?.pulse
+
+/** [project]'s pulse at [now], from what is loaded: every open group, as a command or the PM's sweep loads them. [idleBefore]:
+ * when Working fell to 0 while work waits, as last recorded. */
+export function projectPulse(state: SuperTabState, project: SwarmProject, now: number, limits: PulseLimits = PULSE_LIMITS,
+ index = pulseIndex(state), idleBefore: number | null = null): Pulse {
+ const counts = countWork(state, project, now, index)
+ const asks = (index.owing.get(project.id) ?? [])
+ .flatMap(c => c.owed!.map(ask => ({ conversationId: c.id, messageId: ask.id, personId: ask.personId, at: ask.at })))
+ .sort((a, b) => a.at - b.at)
+ const oldest = asks[0]
+ const lostAt = counts.lost.length ? Math.min(...counts.lost.map(l => l.since)) : null
+ const idleSince = idle(counts) ? idleBefore ?? now : null
+ const withoutReason = counts.held.filter(h => h.reason === null).length
+ return {
+ pmId: pmOf(state, project),
+ asks: { count: asks.length, oldestAt: oldest?.at ?? null, personId: oldest?.personId ?? null, list: asks.slice(0, PULSE_LIST_MAX) },
+ working: { count: counts.working.size, crew: counts.crew.length, agentIds: counts.crew.filter(id => counts.working.has(id)).slice(0, PULSE_LIST_MAX) },
+ nextUp: { count: counts.nextUp.length, conversationIds: counts.nextUp.slice(0, PULSE_LIST_MAX) },
+ lost: { count: counts.lost.length, since: lostAt, conversationIds: counts.lost.map(l => l.id).slice(0, PULSE_LIST_MAX) },
+ held: { count: counts.held.length, withoutReason, list: counts.held.slice(0, PULSE_LIST_MAX) },
+ idleSince,
+ redAt: {
+ asks: oldest ? oldest.at + limits.askMinutes * MINUTE : null,
+ idle: idleSince === null ? null : idleSince + limits.idleMinutes * MINUTE,
+ lost: lostAt === null ? null : lostAt + limits.lostMinutes * MINUTE,
+ held: withoutReason ? 0 : null,
+ },
+ limits,
+ }
+}
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index a7adb8206..fabe78996 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -62,6 +62,8 @@ export interface ProgressView {
/** Values that change without a part changing (time, or several parts). Recomputed in full on every response;
* clients overlay it on the parts. */
export interface Derived {
+ /** The board's pulse of each project the reader sees (pulse.ts, task #3384), by project id. Absent from an older backend. */
+ pulse?: Record<string, import('../pulse.js').Pulse>
/** Every agent the reader can see. `workDecision` is null when the stored value stands; `roleId` null outside Custom. */
/** `roleName`: the role it goes by (instructions.ts roleNameOf), its stored one or what it is. */
agents: Record<string, { downSince: string | null; limitedUntil: string | null; workDecision: 'awaiting' | null; roleId: string | null; roleName: string }>
diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.ts
index c5b999793..deb54a755 100644
--- a/backend/src/superTabs/read/views.test.ts
+++ b/backend/src/superTabs/read/views.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest'
import { storeOldLeads } from '../leads.test-support.js'
import * as store from '../parts/index.js'
import { readerView } from './views.js'
-import { NOW, outsider, owner, peer, richSwarm } from './fixture.test-support.js'
+import { projectLightGroup, lightSelect } from '../parts/lightSelect.js'
+import { recordPulse } from '../pulse.js'
+import { fullSwarm, NOW, outsider, owner, peer, richSwarm } from './fixture.test-support.js'
import type { Actor } from '../model.js'
const R = 9_000
@@ -209,3 +211,58 @@ describe('instructions in the reader\'s view (project instructions, phase 2)', (
.toBe('Lead engineer')
})
})
+
+// Task #3384: the board's pulse is cross-part and timed, so it goes in `derived`, for each project the reader sees; what it is
+// counted from (a conversation's owed asks, a project's idle mark) is bookkeeping no reader gets.
+describe('the pulse on the read', () => {
+ it('is derived for each project the reader sees, never from a part', () => {
+ const { s } = scene()
+ s.edit(state => {
+ state.conversations.find(c => c.id === 'lead')!.owed = [{ id: 'ask', personId: peer.userId, at: NOW - MINUTE, thread: 'ask' }]
+ recordPulse(state, NOW - MINUTE)
+ })
+ const parts = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
+ const view = readerView(parts, peer, NOW, { teamMachines: [] })
+ const pilot = view.parts.head.data.projects!.find(p => p.name === 'Pilot')!
+ expect(view.derived.pulse?.[pilot.id]?.asks).toMatchObject({ count: 1, oldestAt: NOW - MINUTE, personId: peer.userId })
+ expect(Object.keys(view.derived.pulse ?? {})).toEqual(view.parts.head.data.projects!.map(p => p.id))
+ expect(view.parts.groups.find(g => g.key === 'lead')!.data).not.toHaveProperty('owed')
+ expect(view.parts.groups.find(g => g.key === 'lead')!.data).not.toHaveProperty('pulse')
+ const owners = readerView(parts, owner, NOW, { teamMachines: [] })
+ expect(Object.keys(owners.derived.pulse ?? {})).toHaveLength(2)
+ })
+
+ // River, on ReviewPulse2's review of #3209: the pulse's lists name conversations, so a reader gets only those they read; a
+ // Buddy reads only its person's own, so it gets the counts alone (they are its project's totals, which it may read).
+ it('names only conversations the reader may read: a Buddy gets the counts without the lists', () => {
+ const s = fullSwarm()
+ s.edit(state => {
+ state.conversations.find(c => c.id === 'lead')!.owed = [{ id: 'ask', personId: peer.userId, at: NOW - MINUTE, thread: 'ask' }]
+ recordPulse(state, NOW - MINUTE)
+ })
+ const parts = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
+ const pulseFor = (actor: Actor) => Object.values(readerView(parts, actor, NOW, { teamMachines: [] }).derived.pulse ?? {})[0]!
+ expect(pulseFor(peer).asks.list).toHaveLength(1)
+ const buddy = pulseFor(agentActor(s.buddy))
+ expect(buddy.asks).toMatchObject({ count: 1, list: [] })
+ expect([buddy.nextUp.conversationIds, buddy.lost.conversationIds, buddy.held.list, buddy.working.agentIds]).toEqual([[], [], [], []])
+ expect(buddy.nextUp.count).toBe(pulseFor(peer).nextUp.count)
+ })
+
+ // Hugo's review of #3209: a change poll reads the light base (parts/light.ts: the project chats and running work, light
+ // fields only), so a pulse derived from it lost the asks and Next up the first full read showed.
+ it('is the same from a change poll\'s light base as from a full read', () => {
+ const { s } = scene()
+ s.edit(state => {
+ state.conversations.find(c => c.id === 'lead')!.owed = [{ id: 'ask', personId: peer.userId, at: NOW - MINUTE, thread: 'ask' }]
+ recordPulse(state, NOW - MINUTE)
+ })
+ const parts = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
+ const light = { ...parts, ...lightSelect({ ...parts, groups: parts.groups.map(projectLightGroup) }, { groups: 'working' }), machines: parts.machines }
+ const full = readerView(parts, peer, NOW, { teamMachines: [] }).derived.pulse!
+ const pilot = Object.keys(full)[0]!
+ expect(full[pilot]!.asks.count).toBe(1)
+ expect(full[pilot]!.nextUp.count).toBeGreaterThan(0)
+ expect(readerView(light as never, peer, NOW, { teamMachines: [] }).derived.pulse).toEqual(full)
+ })
+})
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 76508041f..7e5a15b6f 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -12,6 +12,7 @@ import { availableSlots, slotCounter, machineTeamWork, type ContributedMachine }
import * as store from '../parts/index.js'
import type { Part, SwarmParts } from '../parts/index.js'
import { canReadGroup } from '../projects.js'
+import { storedPulse, type Pulse } from '../pulse.js'
import { coordinatorNameOf, roleNameOf } from '../instructions.js'
import { withAvatarView } from '../profile.js'
import { swarmUsernames } from '../usernames.js'
@@ -66,7 +67,7 @@ export const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, d
/** A group as readers get it: its message counter, a dormant flag only when dormant, never the store's bookkeeping or the
* leaderboard's (the leaderboard read sums it), except when it shipped. */
export function groupView(group: Conversation, seenMachines: ReadonlySet<string>): GroupView {
- const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger, proposals: _proposals, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)
+ const { messageSeq, reportSeq: _report, lastActivityAt: _activity, ledger, proposals: _proposals, owed: _owed, pulse: _pulse, dormant, audience, ...rest } = withSeenRequirement(group, seenMachines)
// A Buddy chat names its owner instead of an audience: an app from before Buddies takes a private chat of the reader
// alone for their Chat with PM, and would send what they write for the PM to their Buddy instead (buddies.ts).
const readers = isBuddyChat(group) ? { buddyOwnerId: audience!.people[0]!.id } : audience ? { audience } : {}
@@ -129,6 +130,41 @@ export function readerView(parts: SwarmParts, actor: Actor, now: number, extras:
export const progressView = (data: NonNullable<SwarmParts['progress'][number]['data']>): ProgressView =>
({ ...data, requestedAt: data.requestedAt ?? null })
+/** The board's pulse of each project the reader sees (pulse.ts, task #3384), as last recorded on its chat: the same from a full
+ * read and from a change poll's light base, which keeps the project chats and their pulse (parts/light.ts). A project with
+ * none recorded yet is left out, and the board draws no strip. Its lists name conversations: a project's reader reads every
+ * one of them (none is private: pulse.ts counted), each checked again where it is loaded; a Buddy reads only its person's
+ * own, so it gets the counts alone, the same on every read. */
+function pulses(state: SuperTabState, visible: SuperTabState, actor: Actor, buddy: boolean): Record<string, Pulse> | undefined {
+ if (!visible.projects?.length) return undefined
+ // One lookup by id for every listed conversation: a list names up to 50 per count (pulse.ts PULSE_LIST_MAX).
+ const groups = new Map(state.conversations.map(c => [c.id, c])), checked = new Map<string, boolean>()
+ const reads = (id: string) => {
+ const known = checked.get(id)
+ if (known !== undefined) return known
+ const group = groups.get(id)
+ const readable = !group || canReadGroup(state, actor, group)
+ checked.set(id, readable)
+ return readable
+ }
+ const out: Record<string, Pulse> = {}
+ for (const seen of visible.projects) {
+ const project = state.projects?.find(p => p.id === seen.id)
+ const pulse = project && storedPulse(state, project)
+ if (!pulse) continue
+ out[project.id] = buddy ? countsOnly(pulse) : { ...pulse,
+ asks: { ...pulse.asks, list: pulse.asks.list.filter(ask => reads(ask.conversationId)) },
+ nextUp: { ...pulse.nextUp, conversationIds: pulse.nextUp.conversationIds.filter(reads) },
+ lost: { ...pulse.lost, conversationIds: pulse.lost.conversationIds.filter(reads) },
+ held: { ...pulse.held, list: pulse.held.list.filter(hold => reads(hold.conversationId)) } }
+ }
+ return out
+}
+
+/** [pulse] without its lists: what a Buddy reader gets. */
+const countsOnly = (pulse: Pulse): Pulse => ({ ...pulse, asks: { ...pulse.asks, list: [] }, working: { ...pulse.working, agentIds: [] },
+ nextUp: { ...pulse.nextUp, conversationIds: [] }, lost: { ...pulse.lost, conversationIds: [] }, held: { ...pulse.held, list: [] } })
+
function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now: number, extras: ReadExtras): Derived {
// Where New Project's Product Manager would run on each teammate's machine, decided as its start decides (leadStart.ts).
const leads = actor.kind === 'person' && state.people.find(p => p.id === actor.userId)?.role !== 'viewer'
@@ -147,7 +183,9 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const }, ...(version ? { clientVersion: version } : {}),
...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}), ...(machineSuspended ? { machineSuspended } : {}), ...(leads[pool.machineId] ? { lead: leads[pool.machineId] } : {}) }] as const
}
+ const pulse = pulses(state, visible, actor, isBuddyReader(state, actor))
return {
+ ...(pulse ? { pulse } : {}),
agents: Object.fromEntries(visible.agents.map(seen => [seen.id, { downSince: seen.downSince ?? null, limitedUntil: seen.limitedUntil ?? null,
workDecision: seen.workDecision === 'awaiting' && state.agents.find(a => a.id === seen.id)!.workDecision !== 'awaiting' ? 'awaiting' as const : null,
roleId: seen.roleId ?? null,
diff --git a/backend/src/superTabs/reviewSteps.test.ts b/backend/src/superTabs/reviewSteps.test.ts
new file mode 100644
index 000000000..7ac3f33e2
--- /dev/null
+++ b/backend/src/superTabs/reviewSteps.test.ts
@@ -0,0 +1,165 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
+import { stepsOf } from './steps.js'
+import { SEED_RULES } from './policy.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const opus: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const PR = 'https://github.com/acme/app/pull/7'
+
+function fixture() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0, now = 1_000_000
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const contribution = { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }
+ const add = (harnessId: string, group: string, roleName?: string) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,
+ name: harnessId, configuration: opus, lead: false, ...roleName ? { roleName } : {} } as Command, owner, contribution).result.agentId as string
+ const lead = run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'pm', name: 'pm', configuration: opus, lead: true }, owner, contribution).result.agentId as string
+ const task = run({ type: 'conversation.create', title: 'Fix login', brief: 'Sign in works offline.', checks: [{ description: 'Signs in offline', independent: true }], priority: 'P2', requesterId: 'owner' }, as(lead)).result.conversationId as string
+ const dev = add('dev', task, 'Engineer')
+ run({ type: 'work.assign', conversationId: task, agentId: dev }, as(lead))
+ const group = (id: string) => state.conversations.find(c => c.id === id)!
+ const ready = (files: string[] | null, head = 'abc1234', fileContext = true, extra: Partial<CommandContext> = {}) => run({ type: 'work.status', conversationId: task,
+ assignmentId: group(task).assignment!.id, status: 'review', result: `Ready: ${PR}` } as Command, as(dev),
+ fileContext ? { pullRequestFiles: { urls: [PR], head, files }, ...extra } : extra)
+ const steps = () => stepsOf(state, task).map(step => ({ name: step.step, agent: step.assignment?.agentId ?? null, status: step.assignment?.status ?? null }))
+ return { run, as, add, lead, task, dev, group, ready, steps, tick: (ms: number) => { now += ms }, get state() { return state } }
+}
+
+describe('a handed task opens its review steps', () => {
+ it('a pull request touching sign-in code opens two security reviews, each to a different free Reviewer, never the Engineer', () => {
+ const f = fixture()
+ const a = f.add('rev-a', f.task, 'Reviewer'), b = f.add('rev-b', f.task, 'Reviewer')
+ f.ready(['backend/src/routes/auth.ts', 'docs/plans/x.md'])
+ const steps = f.steps()
+ expect(steps.map(s => s.name)).toEqual(['Security review 1', 'Security review 2'])
+ expect(steps.map(s => s.agent).sort()).toEqual([a, b].sort())
+ expect(steps.every(s => s.status === 'working' && s.agent !== f.dev)).toBe(true)
+ // Each Reviewer hears its step's brief, naming the area and the head.
+ const step = stepsOf(f.state, f.task)[0]!
+ expect(step.brief).toContain('Sign-in')
+ expect(step.brief).toContain('abc1234')
+ expect(step.checks).toHaveLength(1)
+ })
+
+ it('a docs pull request opens one read', () => {
+ const f = fixture()
+ const a = f.add('rev-a', f.task, 'Reviewer')
+ f.add('rev-b', f.task, 'Reviewer')
+ f.ready(['docs/a.md'])
+ expect(f.steps()).toEqual([{ name: 'Review', agent: expect.any(String), status: 'working' }])
+ expect([a, f.state.agents.find(x => x.name === 'rev-b')!.id]).toContain(f.steps()[0]!.agent)
+ })
+
+ it('a change that runs somewhere adds a test step for a Tester', () => {
+ const f = fixture()
+ f.add('rev', f.task, 'Reviewer')
+ const tester = f.add('tst', f.task, 'Tester')
+ f.ready(['desktop/lib/super_tabs/view.dart'])
+ expect(f.steps().map(s => s.name)).toEqual(['Review', 'Test'])
+ expect(f.steps()[1]!.agent).toBe(tester)
+ expect(stepsOf(f.state, f.task)[1]!.brief).toContain('Desktop on a Mac')
+ })
+
+ it('never gives a step to an agent with a verdict at this head', () => {
+ const f = fixture()
+ const judged = f.add('judged', f.task, 'Reviewer'), fresh = f.add('fresh', f.task, 'Reviewer')
+ f.group(f.task).checks = [{ id: 'c', description: 'Reviewed', independent: true, evidence: 'No', passedBy: null,
+ verdicts: [{ by: `agent:${judged}`, passed: false, evidence: 'No', at: 1, head: 'abc1234' } as never] }]
+ f.ready(['docs/a.md'])
+ expect(f.steps()[0]!.agent).toBe(fresh)
+ })
+
+ it('a second Ready reuses the steps: a finished one goes back to its Reviewer, a working one is left alone', () => {
+ const f = fixture()
+ const a = f.add('rev-a', f.task, 'Reviewer'), b = f.add('rev-b', f.task, 'Reviewer')
+ f.ready(['backend/src/routes/auth.ts'])
+ const [first, second] = stepsOf(f.state, f.task)
+ const firstAgent = first!.assignment!.agentId
+ f.run({ type: 'work.status', conversationId: first!.id, assignmentId: first!.assignment!.id, status: 'done', result: 'Ready to merge: No' } as Command, f.as(firstAgent))
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'working', result: 'Fixing' } as Command, f.as(f.dev))
+ f.tick(60_000)
+ f.ready(['backend/src/routes/auth.ts'], 'def5678')
+ expect(stepsOf(f.state, f.task).map(s => s.id)).toEqual([first!.id, second!.id])
+ expect(f.group(first!.id).assignment!.agentId).toBe(firstAgent)
+ expect(f.group(first!.id).assignment!.status).toBe('working')
+ expect(f.group(second!.id).assignment!.agentId).toBe([a, b].find(id => id !== firstAgent))
+ })
+
+ // Review of #3227 (Digest): a second Ready at the same head re-assigned a review that had passed there, and cleared its verdict.
+ it('a repeated Ready at the same head keeps a review that passed at that head', () => {
+ const f = fixture()
+ f.add('rev-a', f.task, 'Reviewer'); f.add('rev-b', f.task, 'Reviewer')
+ const head = 'abc1234'.padEnd(40, '0')
+ f.ready(['docs/a.md'], head)
+ const step = stepsOf(f.state, f.task)[0]!, reviewer = step.assignment!.agentId
+ f.group(step.id).checks[0]!.passedBy = `agent:${reviewer}`
+ f.group(step.id).checks[0]!.verdicts = [{ by: `agent:${reviewer}`, passed: true, evidence: 'Yes', at: 1, head } as never]
+ f.run({ type: 'work.status', conversationId: step.id, assignmentId: step.assignment!.id, status: 'done', result: 'Ready to merge: Yes' } as Command, f.as(reviewer))
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'working', result: 'CI rerun' } as Command, f.as(f.dev))
+ f.ready(['docs/a.md'], head)
+ expect(f.group(step.id).assignment).toMatchObject({ agentId: reviewer, status: 'done' })
+ expect(f.group(step.id).checks[0]!.passedBy).toBe(`agent:${reviewer}`)
+ })
+
+ it('reuses a step the Engineer opened itself, and adds only what is missing', () => {
+ const f = fixture()
+ f.add('rev-a', f.task, 'Reviewer'); f.add('rev-b', f.task, 'Reviewer')
+ const own = f.run({ type: 'conversation.create', title: 'Security review', reviewOf: f.task, step: 'Security review', brief: 'Read it.', checks: [] } as Command,
+ f.as(f.dev)).result.conversationId as string
+ f.ready(['backend/src/routes/auth.ts'])
+ expect(stepsOf(f.state, f.task).map(s => s.step)).toEqual(['Security review', 'Security review 2'])
+ expect(f.group(own).assignment?.status).toBe('working')
+ })
+
+ it('with nobody free, the step stays open and the PM is told once; the Ready itself goes through', () => {
+ const f = fixture()
+ const effects = f.ready(['backend/src/routes/auth.ts'])
+ expect(f.group(f.task).assignment!.status).toBe('review')
+ expect(f.steps()).toEqual([{ name: 'Security review 1', agent: null, status: null }, { name: 'Security review 2', agent: null, status: null }])
+ const told = effects.messages.filter(m => m.recipients.includes(f.lead) && /no free reviewer/i.test(m.text))
+ expect(told).toHaveLength(1)
+ expect(told[0]!.text).toContain('Security review 1')
+ })
+
+ it('plans the strictest reads when the files could not be read, and says so', () => {
+ const f = fixture()
+ f.add('rev-a', f.task, 'Reviewer'); f.add('rev-b', f.task, 'Reviewer')
+ f.ready(null)
+ expect(f.steps().map(s => s.name)).toEqual(['Security review 1', 'Security review 2'])
+ expect(stepsOf(f.state, f.task)[0]!.brief).toMatch(/could not be read/i)
+ })
+
+ it('plans by the project\'s saved rules, read with the files', () => {
+ const f = fixture()
+ f.add('rev-a', f.task, 'Reviewer'); f.add('rev-b', f.task, 'Reviewer')
+ f.ready(['docs/a.md'], 'abc1234', true, { projectRules: { revision: 1, rules: { ...SEED_RULES, reviews: { ...SEED_RULES.reviews, defaultReads: 2 } } } })
+ expect(f.steps().map(s => s.name)).toEqual(['Review 1', 'Review 2'])
+ })
+
+ it('opens nothing when no pull request files were read, as before', () => {
+ const f = fixture()
+ f.add('rev-a', f.task, 'Reviewer')
+ f.ready(['docs/a.md'], 'abc1234', false)
+ expect(f.steps()).toEqual([])
+ })
+
+ it('opens nothing on a step\'s own Ready', () => {
+ const f = fixture()
+ const a = f.add('rev-a', f.task, 'Reviewer')
+ f.add('rev-b', f.task, 'Reviewer')
+ f.ready(['docs/a.md'])
+ const step = stepsOf(f.state, f.task)[0]!
+ f.run({ type: 'work.status', conversationId: step.id, assignmentId: step.assignment!.id, status: 'review', result: 'Read' } as Command,
+ f.as(step.assignment!.agentId), { pullRequestFiles: { urls: [PR], head: 'abc1234', files: ['docs/a.md'] } })
+ expect(stepsOf(f.state, f.task)).toHaveLength(1)
+ expect(stepsOf(f.state, step.id)).toHaveLength(0)
+ expect(a).toBeTruthy()
+ })
+})
diff --git a/backend/src/superTabs/reviewTable.test.ts b/backend/src/superTabs/reviewTable.test.ts
new file mode 100644
index 000000000..724e70a1a
--- /dev/null
+++ b/backend/src/superTabs/reviewTable.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+import { SEED_RULES, type ProjectRules } from './policy.js'
+import { reviewPlan, sharedFiles, stepBrief } from './reviewTable.js'
+
+const names = (files: string[] | null, rules?: ProjectRules) => reviewPlan(files, rules).map(step => step.name)
+
+describe('reviewPlan', () => {
+ it('gives a docs-only change one read', () => {
+ expect(names(['docs/plans/x.md', 'README.md'])).toEqual(['Review'])
+ })
+
+ it('gives a sign-in change two security reviews, naming the area', () => {
+ const plan = reviewPlan(['backend/src/routes/auth.ts', 'docs/x.md'])
+ expect(plan.map(step => step.name)).toEqual(['Security review 1', 'Security review 2'])
+ expect(plan.every(step => step.kind === 'security' && step.areas.includes('Sign-in'))).toBe(true)
+ })
+
+ it('gives each sensitive area of the table two security reviews', () => {
+ for (const file of ['cli/src/lib/loginPage.ts', 'backend/src/github/holds.ts', 'cli/src/lib/e2ee/core.ts', 'backend/src/superTabs/machineAccess.ts',
+ 'cli/src/lib/buddyGuard.ts', 'cli/src/device/deviceLink.ts', 'backend/src/superTabs/purge.ts', 'cli/src/lib/worktreeDeletion.ts']) {
+ expect(reviewPlan([file]).filter(step => step.kind !== 'test').map(step => step.name), file).toEqual(['Security review 1', 'Security review 2'])
+ }
+ })
+
+ it('adds a test step where the change runs, and none for docs or tests alone', () => {
+ const plan = reviewPlan(['desktop/lib/super_tabs/view.dart', 'cli/src/superTabs/route.ts'])
+ expect(plan.map(step => step.name)).toEqual(['Review', 'Test'])
+ expect(plan.find(step => step.kind === 'test')?.where).toEqual(['Desktop on a Mac', 'The CLI on a Mac and on a Linux machine'])
+ expect(names(['desktop/test/super_tabs/view_test.dart', 'backend/src/superTabs/steps.test.ts', 'docs/a.md'])).toEqual(['Review'])
+ expect(names(['backend/src/superTabs/steps.ts'])).toEqual(['Review'])
+ })
+
+ it('plans the strictest reads when the files could not be read', () => {
+ const plan = reviewPlan(null)
+ expect(plan.map(step => step.name)).toEqual(['Security review 1', 'Security review 2'])
+ expect(plan[0]!.unread).toBe(true)
+ })
+
+ it('reads its numbers from the project rules it is given', () => {
+ const rules: ProjectRules = { ...SEED_RULES, reviews: { defaultReads: 2, rows: [{ area: 'Billing', reads: 3, paths: ['billing/**'] }],
+ test: [{ where: 'Staging', paths: ['web/**'] }], untested: ['**/*.md'] } }
+ expect(names(['a.ts'], rules)).toEqual(['Review 1', 'Review 2'])
+ expect(names(['billing/x.ts'], rules)).toEqual(['Security review 1', 'Security review 2', 'Security review 3'])
+ expect(reviewPlan(['web/a.ts'], rules).at(-1)).toMatchObject({ name: 'Test', where: ['Staging'] })
+ expect(names(['web/a.md'], rules)).toEqual(['Review 1', 'Review 2'])
+ })
+
+ it('reads the project rules seed when given none', () => {
+ expect(reviewPlan(['backend/src/routes/auth.ts'])).toEqual(reviewPlan(['backend/src/routes/auth.ts'], SEED_RULES))
+ })
+})
+
+describe('sharedFiles', () => {
+ it('names only the files two pull requests of a batch both touch', () => {
+ expect(sharedFiles([
+ { url: 'a', files: ['x.ts', 'y.ts'] },
+ { url: 'b', files: ['y.ts', 'z.ts'] },
+ { url: 'c', files: ['w.ts'] },
+ ])).toEqual([{ file: 'y.ts', urls: ['a', 'b'] }])
+ expect(sharedFiles([{ url: 'a', files: ['x.ts'] }, { url: 'b', files: ['z.ts'] }])).toEqual([])
+ })
+
+ it('counts a pull request whose files were not read as touching everything', () => {
+ expect(sharedFiles([{ url: 'a', files: null }, { url: 'b', files: ['z.ts'] }])).toEqual([{ file: '*', urls: ['a', 'b'] }])
+ })
+})
+
+// Security review 2 of #3227 (Elm, minor): each pull request's own list was pinned to its own head; the brief says so.
+describe('stepBrief', () => {
+ it('names each pull request with its own head', () => {
+ const [step] = reviewPlan(['docs/a.md'])
+ const brief = stepBrief(step!, { number: 9, title: 'Fix', pulls: [
+ { url: 'https://github.com/acme/app/pull/7', head: 'abc1234'.padEnd(40, '0') },
+ { url: 'https://github.com/acme/app/pull/8', head: 'def5678'.padEnd(40, '0') }] })
+ expect(brief).toContain('https://github.com/acme/app/pull/7 at head abc1234, https://github.com/acme/app/pull/8 at head def5678')
+ })
+})
diff --git a/backend/src/superTabs/reviewTable.ts b/backend/src/superTabs/reviewTable.ts
new file mode 100644
index 000000000..a2848a8fe
--- /dev/null
+++ b/backend/src/superTabs/reviewTable.ts
@@ -0,0 +1,64 @@
+/**
+ * Which review steps a pull request needs, from the files it changes (task #3401, anh Dee's Swarm redesign, 2026-11-05): one
+ * read by default; two security reviews for sign-in, tokens, encryption, access, the Buddy guard, device links and deletion
+ * (project instructions, Rules for every agent: Ken, 2026-10-29); a test step where the change runs (Workflow 2). The table is
+ * the project's rules record (policy.ts, #3393): its review rows, test rows and untested paths, read through its own matcher.
+ */
+import { requiredReads, SEED_RULES, testsFor, touchedRows, type ProjectRules } from './policy.js'
+
+export type StepKind = 'review' | 'security' | 'test'
+/** A step a pull request needs: its name in the task, its kind, the sensitive areas it touched, where a test runs, and
+ * `unread` when its files could not be read, so it was planned as strictly as the table goes. */
+export interface PlannedStep { name: string; kind: StepKind; areas: string[]; where?: string[]; unread?: true }
+
+/**
+ * The steps a change to [files] needs by the project's [rules], reads first: as many reads as requiredReads asks, each a
+ * security review when a sensitive row is touched; then a test step naming where testsFor says it runs. Files that could not
+ * be read (null) plan as strictly as the rules go, and no test: where it runs is unknown, and its brief says why.
+ */
+export function reviewPlan(files: readonly string[] | null, rules: ProjectRules = SEED_RULES): PlannedStep[] {
+ const touched = touchedRows(rules, files)
+ const reads = requiredReads(rules, files)
+ const security = touched.length > 0
+ const areas = touched.map(row => row.area)
+ const steps: PlannedStep[] = Array.from({ length: reads }, (_, i) => ({
+ name: `${security ? 'Security review' : 'Review'}${reads > 1 ? ` ${i + 1}` : ''}`,
+ kind: security ? 'security' as const : 'review' as const, areas,
+ ...(files === null ? { unread: true as const } : {}),
+ }))
+ const where = testsFor(rules, files)
+ if (where.length) steps.push({ name: 'Test', kind: 'test', areas: [], where })
+ return steps
+}
+
+/**
+ * The files two or more of a batch's pull requests change, with the pull requests changing each: a batch needs a
+ * combination read only when this is not empty (task #3401). A pull request whose files could not be read (null) is taken
+ * to touch everything, shown as the file `*`.
+ */
+export function sharedFiles(pulls: ReadonlyArray<{ url: string; files: readonly string[] | null }>): Array<{ file: string; urls: string[] }> {
+ const unread = pulls.filter(pull => pull.files === null).map(pull => pull.url)
+ if (unread.length && pulls.length > 1) return [{ file: '*', urls: pulls.map(pull => pull.url) }]
+ const by = new Map<string, string[]>()
+ for (const pull of pulls) for (const file of new Set(pull.files)) by.set(file, [...by.get(file) ?? [], pull.url])
+ return [...by].filter(([, urls]) => urls.length > 1).map(([file, urls]) => ({ file, urls }))
+}
+
+const short = (head: string | null) => head ? head.slice(0, 7) : null
+
+/** What a step's agent is asked to do: which pull requests, at which head, for which task, and why this step. */
+export function stepBrief(step: PlannedStep, task: { number: number; title: string; pulls: ReadonlyArray<{ url: string; head: string | null }> }): string {
+ // Each pull request at the head its own files were read at.
+ const pulls = task.pulls.length ? task.pulls.map(pull => short(pull.head) ? `${pull.url} at head ${short(pull.head)}` : pull.url).join(', ') : 'its pull request'
+ const what = step.kind === 'test'
+ ? `Test ${pulls} for task #${task.number} "${task.title}" as a user would, where it changes: ${step.where!.join('; ')}.`
+ : `${step.kind === 'security' ? 'Security-review' : 'Review'} ${pulls} for task #${task.number} "${task.title}".`
+ const why = step.unread ? ' Its changed files could not be read, so it is reviewed as strictly as the review table goes.'
+ : step.kind === 'security' ? ` It changes ${step.areas.join(', ')}: two independent security reviews before merge.` : ''
+ return `${what}${why} Record your verdict at the head you read, and send it to the task's Engineer with "Ready to merge: Yes", "No" or "With fixes".`
+}
+
+/** The acceptance check a step's agent records. */
+export const stepCheck = (step: PlannedStep): string => step.kind === 'test'
+ ? `Runs as a user would: ${step.where!.join('; ')}`
+ : `${step.kind === 'security' ? 'Security review' : 'Review'}: Ready to merge at the pull request's head`
diff --git a/backend/src/superTabs/reviewerPick.test.ts b/backend/src/superTabs/reviewerPick.test.ts
new file mode 100644
index 000000000..1aaa88642
--- /dev/null
+++ b/backend/src/superTabs/reviewerPick.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
+import type { ContributedMachine } from './machines.js'
+import { builtBy, reviewerCandidates, strengthOf } from './reviewerPick.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const opus: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const sonnet: AgentConfiguration = { ...opus, model: 'sonnet' }
+const sol: AgentConfiguration = { ...opus, engine: 'codex', model: 'gpt-6.1-sol' }
+
+function fixture(engineer: AgentConfiguration = opus) {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const now = 1_000_000
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const add = (harnessId: string, group: string, configuration = opus, extra: Record<string, unknown> = {}) => run({ type: 'agent.add', conversationId: group,
+ machineId: 'host', harnessId, name: harnessId, configuration, lead: false, ...extra } as Command, owner,
+ { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const lead = run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'pm', name: 'pm', configuration: opus, lead: true }, owner,
+ { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const task = run({ type: 'conversation.create', title: 'Fix login', brief: 'Sign in works offline.', checks: [{ description: 'Signs in offline', independent: true }], priority: 'P2', requesterId: 'owner' }, as(lead)).result.conversationId as string
+ const dev = add('dev', task, engineer)
+ run({ type: 'work.assign', conversationId: task, agentId: dev }, as(lead))
+ const group = (id: string) => state.conversations.find(c => c.id === id)!
+ const pick = (kind: 'review' | 'security' | 'test' = 'review', head: string | null = 'abc1234') =>
+ reviewerCandidates(state, group(task), kind, head, now).map(a => a.name)
+ return { run, as, add, lead, task, dev, group, pick, now, get state() { return state } }
+}
+
+describe('strengthOf', () => {
+ it('reads the catalog by engine, model and effort; a grid model or an unknown one has none', () => {
+ const f = fixture()
+ const agent = (name: string) => f.state.agents.find(a => a.name === name)!
+ f.add('o', 'lead', opus); f.add('s', 'lead', sonnet); f.add('x', 'lead', { ...opus, model: 'mystery' })
+ expect(strengthOf(f.state, agent('o'))).toBe(3)
+ expect(strengthOf(f.state, agent('s'))).toBe(2)
+ expect(strengthOf(f.state, agent('x'))).toBeNull()
+ const grid = agent('o')
+ grid.gridModel = 'kimi k3'
+ expect(strengthOf(f.state, grid)).toBeNull()
+ })
+})
+
+describe('builtBy', () => {
+ it('names the assignee and every agent that ran the task', () => {
+ const f = fixture()
+ expect([...builtBy(f.group(f.task))]).toEqual([f.dev])
+ })
+})
+
+describe('reviewerCandidates', () => {
+ it('is never the engineer, nor an agent that built the task before', () => {
+ const f = fixture()
+ const before = f.add('before', f.task)
+ f.group(f.task).ledger!.runs!.push({ ...f.group(f.task).ledger!.runs![0]!, agentId: before })
+ f.add('rev', f.task, opus, { roleName: 'Reviewer' })
+ expect(f.pick()).toEqual(['rev'])
+ })
+
+ it('is never a grid model, nor weaker than the engineer, nor of unknown strength', () => {
+ const f = fixture()
+ f.add('weak', f.task, sonnet, { roleName: 'Reviewer' })
+ f.add('mystery', f.task, { ...opus, model: 'mystery' }, { roleName: 'Reviewer' })
+ const grid = f.add('grid', f.task, opus, { roleName: 'Reviewer' })
+ f.state.agents.find(a => a.id === grid)!.gridModel = 'kimi k3'
+ f.add('strong', f.task, sol, { roleName: 'Reviewer' })
+ expect(f.pick()).toEqual(['strong'])
+ })
+
+ it('takes a weaker engineer\'s reviewer at its own strength or more', () => {
+ const f = fixture(sonnet)
+ f.add('s', f.task, sonnet, { roleName: 'Reviewer' })
+ f.add('o', f.task, opus, { roleName: 'Reviewer' })
+ expect(f.pick().sort()).toEqual(['o', 's'])
+ })
+
+ it('is never an agent with a verdict at this head; one at an older head may review again', () => {
+ const f = fixture()
+ const read = f.add('read', f.task, opus, { roleName: 'Reviewer' })
+ const older = f.add('older', f.task, opus, { roleName: 'Reviewer' })
+ f.group(f.task).checks = [{ id: 'c', description: 'Reviewed', independent: true, evidence: null, passedBy: null, verdicts: [
+ { by: `agent:${read}`, passed: true, evidence: 'Yes', at: 5, head: 'abc1234' },
+ { by: `agent:${older}`, passed: true, evidence: 'Yes', at: 5, head: 'fff0000' },
+ ] } as never]
+ expect(f.pick('security', 'abc1234')).toEqual(['older'])
+ })
+
+ it('compares whole heads: a verdict naming no head, or a prefix of this one, is not at this head (#3394)', () => {
+ const f = fixture()
+ const bare = f.add('bare', f.task, opus, { roleName: 'Reviewer' })
+ const prefix = f.add('prefix', f.task, opus, { roleName: 'Reviewer' })
+ const head = 'abc1234'.padEnd(40, '0')
+ f.group(f.task).checks = [{ id: 'c', description: 'Reviewed', independent: true, evidence: null, passedBy: null, verdicts: [
+ { by: `agent:${bare}`, passed: true, evidence: 'Yes', at: 50 },
+ { by: `agent:${prefix}`, passed: true, evidence: 'Yes', at: 50, head: 'abc1234' } as never,
+ ] }]
+ expect(f.pick('security', head).sort()).toEqual(['bare', 'prefix'])
+ })
+
+ it('is never busy, a PM, a Buddy, or holding another step of this task', () => {
+ const f = fixture()
+ const busy = f.add('busy', f.task, opus, { roleName: 'Reviewer' })
+ const other = f.run({ type: 'conversation.create', title: 'Other', brief: 'Other work.', checks: [{ description: 'Done', independent: false }], priority: 'P2', requesterId: 'owner' }, f.as(f.lead)).result.conversationId as string
+ f.run({ type: 'work.assign', conversationId: other, agentId: busy }, f.as(f.lead))
+ const buddy = f.add('buddy', f.task, opus, { roleName: 'Reviewer' })
+ f.state.agents.find(a => a.id === buddy)!.buddyOf = { personId: 'owner', generation: 'g' }
+ const holder = f.add('holder', f.task, opus, { roleName: 'Reviewer' })
+ const step = f.run({ type: 'conversation.create', title: 'Security review 1', reviewOf: f.task, step: 'Security review 1', brief: 'Read it.', checks: [] } as Command, f.as(f.dev)).result.conversationId as string
+ f.run({ type: 'work.assign', conversationId: step, agentId: holder }, f.as(f.dev))
+ f.add('free', f.task, opus, { roleName: 'Reviewer' })
+ expect(f.pick('security')).toEqual(['free'])
+ })
+
+ it('takes the step\'s role first, then any other free agent; never a Guide or an Integrator', () => {
+ const f = fixture()
+ f.add('eng', f.task, opus, { roleName: 'Engineer' })
+ f.add('guide', f.task, opus, { roleName: 'Guide' })
+ f.add('integrator', f.task, opus, { roleName: 'Integrator' })
+ f.add('tst', f.task, opus, { roleName: 'Tester' })
+ f.add('rev', f.task, opus, { roleName: 'Reviewer' })
+ const review = f.pick('review'), test = f.pick('test')
+ expect(review[0]).toBe('rev')
+ expect(review.slice(1).sort()).toEqual(['eng', 'tst'])
+ expect(test[0]).toBe('tst')
+ expect(test.slice(1).sort()).toEqual(['eng', 'rev'])
+ })
+
+ // Review of #3227 (Digest): on the live Swarm the Guides carry the role Reviewer and the Integrator none (an Engineer).
+ it('is never the Guide or the Integrator, whatever role name they carry', () => {
+ const f = fixture()
+ f.add('Guide', f.task, opus, { roleName: 'Reviewer' })
+ f.add('Guide2', f.task, opus, { roleName: 'Reviewer' })
+ f.add('Integrator', f.task, opus)
+ f.add('rev', f.task, opus, { roleName: 'Reviewer' })
+ expect(f.pick()).toEqual(['rev'])
+ })
+
+ it('is never an agent whose machine cannot start work now: out of quota, signed out, paused or offline', () => {
+ const f = fixture()
+ const machine = (machineId: string, usedPercent: number, extra: Partial<ContributedMachine> = {}): ContributedMachine => ({ machineId, name: machineId,
+ contributorId: 'owner', membershipGeneration: 'g', generation: 'g1', cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 4, paused: false,
+ observation: { generation: 'g1', receivedAt: f.now - 1000, sessionKind: 'computer', resources: {}, tools: {}, runningHarnessIds: [], stoppedHarnessIds: [],
+ readiness: { engines: [{ engine: 'claude', installed: true, signedIn: true }] },
+ quotas: [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent, resetsAt: null }] }] }, ...extra } as unknown as ContributedMachine)
+ f.add('tired-rev', f.task, opus, { roleName: 'Reviewer', machineId: 'tired' })
+ f.add('paused-rev', f.task, opus, { roleName: 'Reviewer', machineId: 'resting' })
+ f.add('rested-rev', f.task, opus, { roleName: 'Reviewer', machineId: 'rested' })
+ f.state.machines = [machine('tired', 100), machine('rested', 15), machine('resting', 15, { paused: true })]
+ expect(f.pick()).toEqual(['rested-rev'])
+ })
+
+ it('ranks by the model an agent runs, its engine\'s default included', () => {
+ const f = fixture(sol)
+ f.add('opus-rev', f.task, opus, { roleName: 'Reviewer' })
+ const own = f.add('default-rev', f.task, { ...sol, model: null, effort: null }, { roleName: 'Reviewer' })
+ f.state.agents.find(a => a.id === own)!.launchedDefault = true
+ expect(f.pick()).toEqual(['default-rev', 'opus-rev'])
+ })
+
+ it('is never an agent of another project', () => {
+ const f = fixture()
+ f.run({ type: 'project.create', name: 'Other', visibility: 'public' } as Command)
+ const otherLead = f.state.projects!.find(p => p.name === 'Other')!.leadConversationId
+ f.add('away', otherLead, opus, { roleName: 'Reviewer' })
+ expect(f.pick()).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/reviewerPick.ts b/backend/src/superTabs/reviewerPick.ts
new file mode 100644
index 000000000..6da759a8d
--- /dev/null
+++ b/backend/src/superTabs/reviewerPick.ts
@@ -0,0 +1,86 @@
+/**
+ * Who may take a handed task's review, security review or test step (task #3401, anh Dee's Swarm redesign, 2026-11-05): a
+ * free agent of the task's project that never worked on the task, runs no grid model, is at least as strong as its engineer,
+ * and gave no verdict at this head. The project instructions' rules that the server now keeps: a Reviewer is never the
+ * Engineer of the same task (Roles, Reviewer), two security reviews are independent (Rules for every agent), a model on the
+ * grid is never offered for a review (route).
+ */
+import { isBuddy } from './buddies.js'
+import { MODEL_CATALOG, namedDefault } from './catalog.js'
+import { roleNameOf } from './instructions.js'
+import { activeWork, workerIndex, type Agent, type CheckVerdict, type Conversation, type SuperTabState } from './model.js'
+import { agentProjectId, groupProject } from './projects.js'
+import { agentTarget, modelMatches } from './rules.js'
+import { canStart, standing } from './reviewSeats.js'
+import { stepsOf } from './steps.js'
+import type { StepKind } from './reviewTable.js'
+
+/** The agents that built [task]: its assignee and every agent its ledger says ran it. */
+export function builtBy(task: Conversation): Set<string> {
+ const ids = new Set<string>()
+ if (task.assignment) ids.add(task.assignment.agentId)
+ for (const run of task.ledger?.runs ?? []) if (run.agentId) ids.add(run.agentId)
+ return ids
+}
+
+/** The catalog's row for what [agent] runs (catalog.ts), or undefined: a grid model (never a reviewer), or a model the
+ * catalog does not list. An agent on its engine's own model is rated by the engine's named default. */
+function catalogRow(state: SuperTabState, agent: Agent) {
+ if (agent.gridModel) return undefined
+ const target = agentTarget(state, agent)
+ const named = target.launchedDefault && !target.model ? namedDefault(target.engine) : null
+ const model = named?.model ?? target.model, effort = named?.effort ?? target.effort
+ if (!model) return undefined
+ const rows = MODEL_CATALOG.models.filter(row => row.engine === target.engine && modelMatches(row.model, model))
+ return rows.find(row => row.effort === effort) ?? rows.reduce<typeof rows[number] | undefined>((a, b) => a && a.strength >= b.strength ? a : b, undefined)
+}
+
+/** The catalog's strength of what [agent] runs, or null where catalogRow has none. */
+export const strengthOf = (state: SuperTabState, agent: Agent): number | null => catalogRow(state, agent)?.strength ?? null
+
+/** The strongest the catalog rates: what an engineer of unknown strength is taken to be, so its reviewer is never weaker. */
+const TOP_STRENGTH = Math.max(...MODEL_CATALOG.models.map(row => row.strength))
+
+/** Roles with work of their own that never take a step (project instructions, Roles): the PM, its Guide and Integrator, a Buddy.
+ * By role name, and by the agent's own name too: on the live Swarm the Guides carry the role Reviewer and the Integrator none
+ * (review of #3227), so "Guide", "Guide2" or "Integrator" is never picked whatever role it was started in. */
+const NEVER = /^(pm|guide|integrator|buddy)$/i
+const NEVER_NAMED = /^(guide|integrator)\d*$/i
+const ROLE: Record<StepKind, RegExp> = { review: /review/i, security: /review/i, test: /test/i }
+
+/** Whether [verdict] was given at [head]: it names that whole head (#3394: heads are whole 40-character ids, and a verdict
+ * naming none counts at no head). */
+const atHead = (verdict: CheckVerdict & { head?: string }, head: string | null) => !!head && verdict.head === head
+
+/**
+ * The agents that may take a [kind] step of [task] at [head], best first: the step's own role (Reviewer, Tester) before any
+ * other free agent, then the cheaper of equal standing, then by id. Excluded: anyone that built the task; a grid model, an
+ * unknown model or one weaker than the engineer; anyone busy, coordinating a conversation, a Buddy, stopping, or of another
+ * project; anyone holding another open step of this task; anyone with a verdict at this head on the task or its steps.
+ */
+export function reviewerCandidates(state: SuperTabState, task: Conversation, kind: StepKind, head: string | null, now: number): Agent[] {
+ const projectId = groupProject(state, task).id
+ const index = workerIndex(state)
+ const built = builtBy(task)
+ const engineer = task.assignment ? state.agents.find(a => a.id === task.assignment!.agentId) : undefined
+ const bar = (engineer && strengthOf(state, engineer)) ?? TOP_STRENGTH
+ const steps = stepsOf(state, task.id)
+ const holding = new Set(steps.filter(step => activeWork(step)).map(step => step.assignment!.agentId))
+ const judged = new Set([task, ...steps].flatMap(group => group.checks.flatMap(check => check.verdicts ?? []))
+ .filter(verdict => atHead(verdict, head)).map(verdict => verdict.by))
+ const ranked = state.agents.flatMap(agent => {
+ if (built.has(agent.id) || index.leaders.has(agent.id) || index.working.has(agent.id) || holding.has(agent.id)) return []
+ if (isBuddy(agent) || agent.workDecision === 'stop' || agentProjectId(state, agent) !== projectId) return []
+ if (judged.has(`agent:${agent.id}`)) return []
+ const role = roleNameOf(state, agent)
+ if (NEVER.test(role) || NEVER_NAMED.test(agent.name) || NEVER_NAMED.test(agent.displayName ?? '')) return []
+ // Its machine can start work within the review's wait (reviewSeats.ts): not offline, paused, signed out, suspended or
+ // out of quota. A machine the state does not list is not judged here; work.assign's checks still hold it.
+ const pool = state.machines?.find(m => m.machineId === agent.machineId && m.contributorId === agent.contributorId)
+ if (pool && !canStart(standing(state, pool, agent.configuration.engine, now))) return []
+ const row = catalogRow(state, agent)
+ if (!row || row.strength < bar) return []
+ return [{ agent, rank: ROLE[kind].test(role) ? 0 : 1, cost: row.cost }]
+ })
+ return ranked.sort((a, b) => a.rank - b.rank || a.cost - b.cost || a.agent.id.localeCompare(b.agent.id)).map(entry => entry.agent)
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 6cbca43a3..1326bcf51 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -17,6 +17,7 @@ import { wavDurationMs } from '../lib/wav.js'
import { agentText, MAX_VOICE_BYTES, MAX_VOICE_MS, VOICE_CLAIM_MS, VOICE_TYPES, voiceFacts, voiceTranscript, voiceWaveform, type StoredVoice, type VoiceFacts } from './voiceMessages.js'
import { machineAlive } from '../lib/prisma.js'
import { pullRequestsIn, type PushOrigin } from '../github/pushOrigin.js'
+import type { PullRequestFilesRead } from './pullRequestFiles.js'
import type { RepositoryReach } from './repositoryReach.js'
import { githubRepository } from '../github/repository.js'
import { isTeamSession, teamMachine, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
@@ -379,6 +380,9 @@ export interface SuperTabStoreHooks {
workStarted?: (tabId: string, started: WorkHold[]) => void
/** Who pushed these pull requests of a project's repository (github/pushOrigin.ts): the worst of their answers. Absent with no GitHub App. */
pushOrigin?: (repositoryUrl: string | null, pullRequestUrls: string[]) => Promise<PushOrigin>
+ /** The files a handed task's pull requests change and their head (pullRequestFiles.ts), read before its Engineer's Ready so
+ * the server opens its review steps (task #3401). Null with nothing of the project's repository to read. Absent with no GitHub App. */
+ pullRequestFiles?: (repositoryUrl: string | null, pullRequestUrls: string[]) => Promise<PullRequestFilesRead | null>
/** The same for a branch a start names: its open pull request's answer, clean for the default branch, unknown with no pull request. */
branchPushOrigin?: (repositoryUrl: string | null, branch: string) => Promise<PushOrigin>
/** Whether the Harness GitHub App reaches a project's GitHub repository for this Swarm (github/projectAccess.ts), read before
@@ -1554,7 +1558,9 @@ export class SuperTabStore {
private async repositoryReachFor(user: AuthUser, tabId: string, command: unknown): Promise<RepositoryReach | undefined> {
const hook = this.hooks.repositoryReach
const asked = command as { type?: unknown; conversationId?: unknown; request?: { conversationId?: unknown } } | null
- const conversationId = asked?.type === 'agent.start' ? asked.request?.conversationId : asked?.type === 'work.assign' ? asked.conversationId : undefined
+ // A task's Ready assigns its review steps (task #3401), so it reads the reach as an assignment does.
+ const assigns = asked?.type === 'work.assign' || (asked?.type === 'work.status' && (asked as { status?: unknown }).status === 'review')
+ const conversationId = asked?.type === 'agent.start' ? asked.request?.conversationId : assigns ? asked!.conversationId : undefined
if (!hook || typeof conversationId !== 'string') return undefined
try {
const project = await transaction(this.db, async tx => {
@@ -1571,12 +1577,42 @@ export class SuperTabStore {
}
}
+ /**
+ * The files the pull requests of the task a Ready for review hands over change (task #3401), read outside the command's
+ * transaction as GitHub may take seconds, as pushOriginFor reads. Undefined for a step's Ready, a task naming no pull
+ * request, or no hook: no step opens then. A read that throws gives files null: the strictest steps open, never none.
+ */
+ private async pullRequestFilesFor(user: AuthUser, tabId: string, command: unknown): Promise<PullRequestFilesRead | undefined> {
+ const hook = this.hooks.pullRequestFiles
+ const asked = command as { type?: unknown; conversationId?: unknown; status?: unknown; result?: unknown } | null
+ if (!hook || asked?.type !== 'work.status' || asked.status !== 'review' || typeof asked.conversationId !== 'string') return undefined
+ let facts: { repositoryUrl: string | null; urls: string[] } | null = null
+ try {
+ facts = await transaction(this.db, async tx => {
+ const { state } = await this.load(tx, user, tabId, namedFor(command as Command))
+ const group = state.conversations.find(c => c.id === asked.conversationId)
+ if (!group || group.reviewOf) return null
+ const repositoryUrl = groupProject(state, group).repository?.repositoryUrl ?? null
+ const urls = [...group.pullRequestUrls ?? [], ...[typeof asked.result === 'string' ? asked.result : '', group.brief]
+ .flatMap(text => text ? pullRequestsIn(text, repositoryUrl) : [])]
+ return { repositoryUrl, urls: [...new Set(urls)] }
+ })
+ if (!facts?.urls.length) return undefined
+ return await hook(facts.repositoryUrl, facts.urls) ?? undefined
+ } catch (error) {
+ if (error instanceof SuperTabError || !facts) return undefined
+ logger.warn('[swarm-review-steps] pull request files not read', { tabId, error: error instanceof Error ? error.message : String(error) })
+ return { urls: facts.urls, head: null, files: null }
+ }
+ }
+
/** [only]: what the store alone may give a command: `overdue` for decision.answer (leaveOverdueDecisions), `movedTo` for
* machine.moved (computerSignedIn). */
private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
workspaceLeave = false, only: { overdue?: boolean; movedTo?: { machineId: string; ownerId: string } } = {}) {
const { operationId, command } = operationSchema.parse(input)
- const [pushOrigin, repositoryReach] = await Promise.all([this.pushOriginFor(user, tabId, command), this.repositoryReachFor(user, tabId, command)])
+ const [pushOrigin, repositoryReach, pullRequestFiles] = await Promise.all([this.pushOriginFor(user, tabId, command), this.repositoryReachFor(user, tabId, command),
+ this.pullRequestFilesFor(user, tabId, command)])
let ended: WorkHold[] = [], started: WorkHold[] = []
const done = await transaction(this.db, async tx => {
// A retried attempt starts again: only the attempt that commits says which tasks ended or started.
@@ -1865,6 +1901,12 @@ export class SuperTabStore {
}
if (pushOrigin) Object.assign(context, { pushOrigin: pushOrigin.origin, pushOriginPulls: pushOrigin.pulls })
if (repositoryReach) context.repositoryReach = repositoryReach
+ if (pullRequestFiles && command.type === 'work.status') {
+ context.pullRequestFiles = pullRequestFiles
+ // Its project's review table plans the steps: one indexed read of the newest rules revision (policyStore.ts).
+ const handed = original.conversations.find(c => c.id === command.conversationId)
+ if (handed) context.projectRules = await readRules(tx, tabId, groupProject(original, handed).id)
+ }
if (command.type === 'agent.screen' || command.type === 'agent.input') {
// A machine that is gone or no longer shared refuses at once instead of leaving the request to time out.
await this.agentGrant(tx, original, agent(original, command.agentId))
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 1e18a19ba..dde6ed2c2 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts', 'integration/superTabScorecard.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
- 'integration/superTabInstructions.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabMergeTrain.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
+ 'integration/superTabInstructions.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/superTabs/readContract.ts b/cli/src/superTabs/readContract.ts
index 743e7f964..3cb8c09de 100644
--- a/cli/src/superTabs/readContract.ts
+++ b/cli/src/superTabs/readContract.ts
@@ -35,6 +35,8 @@ export interface Derived {
otherProjectsWork?: Json[]
/** A project agent only: the account each project's PM runs on (backend superTabs/model.ts pmAccounts). */
pmAccounts?: Json[]
+ /** The board's pulse of each project the reader sees, by project id (backend superTabs/pulse.ts, task #3384). */
+ pulse?: Record<string, Json>
/** A person only. */
mentionsWaiting?: number
/** A person only: a digest of which of their tags wait, moving when one is made, answered or expires. */
diff --git a/cli/src/superTabs/reassemble.spec.ts b/cli/src/superTabs/reassemble.spec.ts
index 193443c57..7c74bb139 100644
--- a/cli/src/superTabs/reassemble.spec.ts
+++ b/cli/src/superTabs/reassemble.spec.ts
@@ -76,4 +76,15 @@ describe('the old Swarm state, rebuilt from parts', () => {
first.derived.pmAccounts = accounts
expect(reassemble(storeOf(first)).pmAccounts).toEqual(accounts)
})
+
+ // Task #3384: the status read shows each project's pulse (asks the PM owes, who works), on the project, and none from an
+ // older server.
+ it('lays each project\'s pulse on that project, and none when the read sends none', () => {
+ const first = readFixture<FirstLoad>('parts-lead')
+ const projects = (state: Json) => list(state.projects)
+ expect(projects(reassemble(storeOf(first)))[0]).not.toHaveProperty('pulse')
+ const pulse = { pmId: 'pm', asks: { count: 1, oldestAt: 1, personId: 'p', list: [] } }
+ first.derived.pulse = { '5000000000000000000000aa': pulse }
+ expect(projects(reassemble(storeOf(first)))[0]!.pulse).toEqual(pulse)
+ })
})
diff --git a/cli/src/superTabs/reassemble.ts b/cli/src/superTabs/reassemble.ts
index 4e6d85bb1..d8250808c 100644
--- a/cli/src/superTabs/reassemble.ts
+++ b/cli/src/superTabs/reassemble.ts
@@ -57,7 +57,10 @@ export function reassemble(store: PartsStore): Json {
if (projects) {
state.projects = projects.map(project => {
const stored = progress.get(String(project.id))
- return stored ? { ...project, progress: progressOf(stored, project.id, project.leadConversationId, groups) } : project
+ // The board's pulse (task #3384): what the PM owes and who works, shown by status on its project.
+ const pulse = derived.pulse?.[String(project.id)]
+ const withPulse = pulse ? { ...project, pulse } : project
+ return stored ? { ...withPulse, progress: progressOf(stored, project.id, project.leadConversationId, groups) } : withPulse
})
}
if (derived.otherProjectsWork !== undefined) state.otherProjectsWork = derived.otherProjectsWork
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 6518b550d..84180e708 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -1,6 +1,7 @@
import 'identity.dart' show superTabPersonName;
import 'live_card_model.dart';
import 'profile_model.dart';
+import 'pulse.dart';
export 'profile_model.dart';
@@ -767,6 +768,7 @@ class SuperTabSnapshot {
decisionsDigest = row['decisionsDigest'] as String?,
activityDigest = row['activityDigest'] as String?,
remindersDigest = row['remindersDigest'] as String?,
+ _pulses = SuperTabPulse.readAll(row['pulse']),
chatSettings = Map.unmodifiable({
if (row['chatSettings'] case final Map settings)
for (final MapEntry(:key, :value) in settings.entries)
@@ -909,6 +911,11 @@ class SuperTabSnapshot {
/// cleared; null from a backend before reminders (superTabs/reminders.ts).
final String? remindersDigest;
+ /// [projectId]'s board pulse (task #3384); null from a server before it,
+ /// or when its pulse could not be read.
+ SuperTabPulse? pulseOf(String projectId) => _pulses[projectId];
+ final Map<String, SuperTabPulse> _pulses;
+
/// The reader's own notification setting by conversation (backend chatSettings.ts); a chat not listed is at
/// [SuperTabNotify.mentions]. Never another person's.
final Map<String, SuperTabNotify> chatSettings;
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index acf823696..184ac753b 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -494,6 +494,8 @@ class SuperTabParts {
if (_derived['activityDigest'] case final String digest) {
state['activityDigest'] = digest;
}
+ // Each project's board pulse (backend superTabs/pulse.ts, task #3384).
+ if (_derived['pulse'] case final Map pulse) state['pulse'] = pulse;
// Sent only where the server does not try Harness Team accounts yet.
if (_derived['teamAccounts'] == false) state['teamAccounts'] = false;
// Sent by a server that takes a thread reply's New session.
diff --git a/desktop/lib/super_tabs/pulse.dart b/desktop/lib/super_tabs/pulse.dart
new file mode 100644
index 000000000..19a3a4976
--- /dev/null
+++ b/desktop/lib/super_tabs/pulse.dart
@@ -0,0 +1,188 @@
+/// A project's board pulse (task #3384): what waits for its PM and who works,
+/// as the server works it out per read (backend superTabs/pulse.ts) and sends
+/// it in `derived.pulse`. The server decides when each count turns red
+/// (`redAt`); the app holds no threshold of its own.
+library;
+
+/// A rule that turns a segment of the pulse red.
+enum SuperTabPulseRule {
+ /// An ask has waited too long for the PM.
+ asks,
+
+ /// Nobody has worked while work waited.
+ idle,
+
+ /// A lost task has had no agent too long.
+ lost,
+
+ /// A hold has no reason.
+ held,
+}
+
+/// A person's message to the PM not yet settled.
+typedef SuperTabPulseAsk = ({
+ String conversationId,
+ String messageId,
+ String? personId,
+ DateTime at,
+});
+
+/// A held task and why, null when nobody said.
+typedef SuperTabPulseHold = ({String conversationId, String? reason});
+
+class SuperTabPulse {
+ SuperTabPulse._(Map<String, dynamic> row)
+ : pmId = _optional<String>(row['pmId']),
+ asks = _asks(_map(row['asks'])),
+ working = _working(_map(row['working'])),
+ nextUp = _tasks(_map(row['nextUp'])),
+ lost = _tasks(_map(row['lost'])),
+ held = _held(_map(row['held'])),
+ limits = switch (row['limits']) {
+ final Map limits => (
+ askMinutes: _optional<num>(limits['askMinutes'])?.toInt(),
+ idleMinutes: _optional<num>(limits['idleMinutes'])?.toInt(),
+ lostMinutes: _optional<num>(limits['lostMinutes'])?.toInt(),
+ ),
+ _ => (askMinutes: null, idleMinutes: null, lostMinutes: null),
+ },
+ redAt = Map.unmodifiable({
+ for (final rule in SuperTabPulseRule.values)
+ rule: ?_time(_map(row['redAt'])[rule.name]),
+ });
+
+ /// [value]'s pulse; null for one this build cannot read, so the board draws
+ /// no strip rather than a wrong one.
+ static SuperTabPulse? read(Object? value) {
+ if (value is! Map) return null;
+ try {
+ return SuperTabPulse._(Map<String, dynamic>.from(value));
+ } on FormatException {
+ return null;
+ }
+ }
+
+ /// Every project's pulse in `derived.pulse`, by project id; empty from a
+ /// server before it.
+ static Map<String, SuperTabPulse> readAll(Object? value) => Map.unmodifiable({
+ if (value is Map)
+ for (final MapEntry(:key, :value) in value.entries)
+ if (key is String) key: ?read(value),
+ });
+
+ /// The project's PM, while it has one.
+ final String? pmId;
+ final ({
+ int count,
+ DateTime? oldestAt,
+ String? personId,
+ List<SuperTabPulseAsk> list,
+ })
+ asks;
+ final ({int count, int crew, List<String> agentIds}) working;
+ final ({int count, List<String> conversationIds}) nextUp, lost;
+ final ({int count, int withoutReason, List<SuperTabPulseHold> list}) held;
+
+ /// The limits behind `redAt`, only to say why a count is red.
+ final ({int? askMinutes, int? idleMinutes, int? lostMinutes}) limits;
+
+ /// When each rule turns red; a rule left out is not red.
+ final Map<SuperTabPulseRule, DateTime> redAt;
+
+ /// Whether [rule] is red at [now]: at its `redAt` or after it.
+ bool isRed(SuperTabPulseRule rule, DateTime now) {
+ final at = redAt[rule];
+ return at != null && !at.isAfter(now);
+ }
+
+ /// Whether any rule is red at [now].
+ bool anyRed(DateTime now) =>
+ SuperTabPulseRule.values.any((rule) => isRed(rule, now));
+
+ /// The next time after [now] a rule turns red, null when none will.
+ DateTime? nextRedAfter(DateTime now) {
+ DateTime? next;
+ for (final at in redAt.values) {
+ if (at.isAfter(now) && (next == null || at.isBefore(next))) next = at;
+ }
+ return next;
+ }
+
+ static ({
+ int count,
+ DateTime? oldestAt,
+ String? personId,
+ List<SuperTabPulseAsk> list,
+ })
+ _asks(Map<String, dynamic> row) => (
+ count: _count(row['count']),
+ oldestAt: _time(row['oldestAt']),
+ personId: _optional<String>(row['personId']),
+ list: List.unmodifiable([
+ for (final ask in _list(row['list']))
+ (
+ conversationId: _text(_map(ask)['conversationId']),
+ messageId: _text(_map(ask)['messageId']),
+ personId: _optional<String>(_map(ask)['personId']),
+ at: _time(_map(ask)['at']) ?? (throw const FormatException('at')),
+ ),
+ ]),
+ );
+
+ static ({int count, int crew, List<String> agentIds}) _working(
+ Map<String, dynamic> row,
+ ) => (
+ count: _count(row['count']),
+ crew: _count(row['crew']),
+ agentIds: _ids(row['agentIds']),
+ );
+
+ static ({int count, List<String> conversationIds}) _tasks(
+ Map<String, dynamic> row,
+ ) => (
+ count: _count(row['count']),
+ conversationIds: _ids(row['conversationIds']),
+ );
+
+ static ({int count, int withoutReason, List<SuperTabPulseHold> list}) _held(
+ Map<String, dynamic> row,
+ ) => (
+ count: _count(row['count']),
+ withoutReason: _count(row['withoutReason'] ?? 0),
+ list: List.unmodifiable([
+ for (final hold in _list(row['list']))
+ (
+ conversationId: _text(_map(hold)['conversationId']),
+ reason: switch (_map(hold)['reason']) {
+ final String reason when reason.trim().isNotEmpty => reason,
+ _ => null,
+ },
+ ),
+ ]),
+ );
+
+ static Map<String, dynamic> _map(Object? value) => value is Map
+ ? Map<String, dynamic>.from(value)
+ : throw const FormatException('Not a pulse object.');
+
+ static List<Object?> _list(Object? value) => switch (value) {
+ null => const [],
+ final List list => list,
+ _ => throw const FormatException('Not a pulse list.'),
+ };
+
+ static List<String> _ids(Object? value) =>
+ List.unmodifiable([for (final id in _list(value)) _text(id)]);
+
+ static String _text(Object? value) =>
+ value is String ? value : throw const FormatException('Not an id.');
+
+ static int _count(Object? value) => value is num
+ ? value.toInt()
+ : throw const FormatException('Not a count.');
+
+ static T? _optional<T>(Object? value) => value is T ? value : null;
+
+ static DateTime? _time(Object? value) =>
+ value is num ? DateTime.fromMillisecondsSinceEpoch(value.toInt()) : null;
+}
diff --git a/desktop/lib/super_tabs/pulse_strip.dart b/desktop/lib/super_tabs/pulse_strip.dart
new file mode 100644
index 000000000..c7cbfbaaa
--- /dev/null
+++ b/desktop/lib/super_tabs/pulse_strip.dart
@@ -0,0 +1,379 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_menu.dart';
+import '../widgets/desktop_chrome.dart';
+import 'backlog.dart';
+import 'machine_status.dart';
+import 'model.dart';
+import 'pulse.dart';
+import 'visible_tick.dart';
+
+/// The strip on top of a project's Tasks board (task #3384):
+/// `Waiting for River: 2 asks · oldest 14m (Huy) │ Working 6 of 10 │ Next up 7
+/// │ Lost 0 │ Held 3`. Each count opens its list. A count is red from its
+/// rule's `redAt` on, said by the error ink, a bold label and an alert icon
+/// together; the strip's rim turns red with it.
+class SuperTabPulseStrip extends StatefulWidget {
+ const SuperTabPulseStrip({
+ super.key,
+ required this.pulse,
+ required this.snapshot,
+ required this.projectId,
+ required this.now,
+ required this.onOpenTask,
+ required this.onOpenMessage,
+ });
+
+ final SuperTabPulse pulse;
+ final SuperTabSnapshot snapshot;
+ final String projectId;
+ final DateTime Function() now;
+ final ValueChanged<String> onOpenTask;
+ final void Function(String conversationId, String messageId) onOpenMessage;
+
+ /// A list's widest: room for a task title and its number on one line.
+ static const menuWidth = 340.0;
+
+ @override
+ State<SuperTabPulseStrip> createState() => _SuperTabPulseStripState();
+}
+
+class _SuperTabPulseStripState extends State<SuperTabPulseStrip>
+ with WidgetsBindingObserver, VisibleTick {
+ /// Wakes the strip for what changes with no new read: a `redAt` passing and
+ /// the oldest ask's age reaching its next step. Only while on screen.
+ Timer? _wake;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _arm();
+ }
+
+ @override
+ void didUpdateWidget(SuperTabPulseStrip old) {
+ super.didUpdateWidget(old);
+ _arm();
+ }
+
+ @override
+ void onScreenChanged(bool onScreen) => _arm();
+
+ @override
+ void dispose() {
+ _wake?.cancel();
+ super.dispose();
+ }
+
+ void _arm() {
+ _wake?.cancel();
+ _wake = null;
+ if (!onScreen) return;
+ final now = widget.now();
+ final pulse = widget.pulse;
+ final oldest = pulse.asks.count > 0 ? pulse.asks.oldestAt : null;
+ final waits = [
+ if (pulse.nextRedAfter(now) case final at?) at.difference(now),
+ if (oldest != null) _nextAgeStep(now.difference(oldest)),
+ ];
+ if (waits.isEmpty) return;
+ final wait = waits.reduce((a, b) => a < b ? a : b);
+ _wake = Timer(wait, () {
+ if (!mounted) return;
+ setState(() {});
+ _arm();
+ });
+ }
+
+ /// How long until [age], as [_age] writes it, reads differently.
+ static Duration _nextAgeStep(Duration age) {
+ final unit = age < const Duration(hours: 1)
+ ? const Duration(minutes: 1)
+ : age < const Duration(days: 1)
+ ? const Duration(hours: 1)
+ : const Duration(days: 1);
+ final into = Duration(
+ microseconds: age.inMicroseconds % unit.inMicroseconds,
+ );
+ return unit - into;
+ }
+
+ /// An age as the board's captions write it: now, 14m, 3h, 2d.
+ static String _age(Duration age) =>
+ age.inMinutes < 1 ? 'now' : superTabAgoShort(age);
+
+ SuperTabSnapshot get _snapshot => widget.snapshot;
+
+ String? _person(String? id) => id == null
+ ? null
+ : _snapshot.people.where((p) => p.id == id).firstOrNull?.shownName;
+
+ String get _pmName => _snapshot.agentName(
+ widget.pulse.pmId ?? '',
+ fallback: _snapshot.coordinatorNameOf(widget.projectId),
+ );
+
+ String _asksText(DateTime now) {
+ final asks = widget.pulse.asks;
+ if (asks.count == 0) return 'Nothing waiting for $_pmName';
+ final person = _person(asks.personId);
+ return [
+ 'Waiting for $_pmName: ${asks.count} ${asks.count == 1 ? 'ask' : 'asks'}',
+ if (asks.oldestAt case final at?)
+ 'oldest ${_age(now.difference(at))}${person == null ? '' : ' ($person)'}',
+ ].join(' · ');
+ }
+
+ String _heldText() {
+ final held = widget.pulse.held;
+ return held.withoutReason > 0
+ ? 'Held ${held.count} (${held.withoutReason} no reason)'
+ : 'Held ${held.count}';
+ }
+
+ /// Why [rule] is red, for its icon's tooltip and screen readers.
+ String _why(SuperTabPulseRule rule) {
+ final limits = widget.pulse.limits;
+ String over(int? minutes, String text) =>
+ minutes == null ? text : '$text $minutes minutes';
+ return switch (rule) {
+ SuperTabPulseRule.asks => over(
+ limits.askMinutes,
+ 'An ask has waited for $_pmName over',
+ ),
+ SuperTabPulseRule.idle => over(
+ limits.idleMinutes,
+ 'Nobody has worked while tasks waited for',
+ ),
+ SuperTabPulseRule.lost => over(
+ limits.lostMinutes,
+ 'A task has had no agent for',
+ ),
+ SuperTabPulseRule.held => 'A task is held with no reason',
+ };
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final now = widget.now();
+ final pulse = widget.pulse;
+ final error = Theme.of(context).colorScheme.error;
+ bool red(SuperTabPulseRule rule) => pulse.isRed(rule, now);
+ final parts = [
+ _segment(
+ 'asks',
+ _asksText(now),
+ red(SuperTabPulseRule.asks) ? SuperTabPulseRule.asks : null,
+ _askRows(now),
+ ),
+ _segment(
+ 'working',
+ 'Working ${pulse.working.count} of ${pulse.working.crew}',
+ red(SuperTabPulseRule.idle) ? SuperTabPulseRule.idle : null,
+ _agentRows(),
+ ),
+ _segment(
+ 'nextUp',
+ 'Next up ${pulse.nextUp.count}',
+ null,
+ _taskRows(pulse.nextUp.conversationIds, empty: 'No tasks next up'),
+ ),
+ _segment(
+ 'lost',
+ 'Lost ${pulse.lost.count}',
+ red(SuperTabPulseRule.lost) ? SuperTabPulseRule.lost : null,
+ _taskRows(pulse.lost.conversationIds, empty: 'No lost tasks'),
+ ),
+ _segment(
+ 'held',
+ _heldText(),
+ red(SuperTabPulseRule.held) ? SuperTabPulseRule.held : null,
+ _taskRows(
+ [for (final hold in pulse.held.list) hold.conversationId],
+ reasons: {
+ for (final hold in pulse.held.list)
+ hold.conversationId: hold.reason ?? 'No reason',
+ },
+ empty: 'No held tasks',
+ ),
+ ),
+ ];
+ return DecoratedBox(
+ key: const ValueKey('super-pulse'),
+ decoration: BoxDecoration(
+ color: grid.AppCard.base,
+ borderRadius: BorderRadius.circular(grid.AppCard.radius),
+ border: Border.all(
+ color: pulse.anyRed(now) ? error : grid.AppCard.hair,
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(grid.AppDesktop.listRowGap),
+ child: Wrap(
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ for (final (i, part) in parts.indexed) ...[
+ if (i > 0) _divider(),
+ part,
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _divider() => SizedBox(
+ height: AppIcons.inlineSize,
+ child: VerticalDivider(
+ width: grid.AppDesktop.listRowGap,
+ thickness: 1,
+ color: grid.AppCard.hair,
+ ),
+ );
+
+ /// One count: its words, red by [redBy] when that rule has passed, opening
+ /// [rows] beneath it.
+ Widget _segment(
+ String name,
+ String text,
+ SuperTabPulseRule? redBy,
+ List<Widget> rows,
+ ) {
+ final error = Theme.of(context).colorScheme.error;
+ final red = redBy != null;
+ final style =
+ DesktopChrome.control(color: red ? error : DesktopChrome.foreground)
+ .copyWith(
+ fontWeight: red ? FontWeight.w600 : FontWeight.w400,
+ fontFeatures: const [FontFeature.tabularFigures()],
+ );
+ return AppDropdown(
+ width: SuperTabPulseStrip.menuWidth,
+ consumeOutsideTap: false,
+ children: rows,
+ builder: (context, menu, _) => Semantics(
+ button: true,
+ child: InkWell(
+ key: ValueKey('super-pulse-$name'),
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ hoverColor: grid.AppSurface.hoverFill,
+ onTap: () => menu.isOpen ? menu.close() : menu.open(),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ vertical: grid.AppDesktop.menuInset,
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (red) ...[
+ Tooltip(
+ message: _why(redBy),
+ child: Icon(
+ AppIcons.circleAlert,
+ size: AppIcons.inlineSize,
+ color: error,
+ semanticLabel: _why(redBy),
+ ),
+ ),
+ const SizedBox(width: grid.AppDesktop.menuInset),
+ ],
+ Text(text, style: style),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// A row's age or task number at its end edge, one column down the list. Not
+ /// the row's note: a note shares the row's slack with the label half and
+ /// half, which cut a task's title short beside a three-figure number.
+ static Widget _aside(String text) => Text(
+ text,
+ style: DesktopChrome.metadata().copyWith(
+ fontFeatures: const [FontFeature.tabularFigures()],
+ ),
+ );
+
+ /// A row saying a list is empty, so a count of 0 still answers its tap.
+ static Widget _none(String text) => AppMenuItem(label: text, onPressed: null);
+
+ /// [conversationId]'s place, as the ask's row says where it was asked.
+ String? _placeOf(String conversationId) {
+ final project = _snapshot.projectById(widget.projectId);
+ if (project?.leadConversationId == conversationId) {
+ return '${project!.isPrivate ? '' : '# '}${project.name}';
+ }
+ final group = _snapshot.conversation(conversationId);
+ return group == null ? null : _label(group);
+ }
+
+ /// A task as a list names it: `#12 Its title`, the priority marker dropped as
+ /// the board's cards drop it.
+ static String _label(SuperTabConversation task) {
+ final title = superTabTitlePriority(task.title).title;
+ return task.number == null ? title : '#${task.number} $title';
+ }
+
+ List<Widget> _askRows(DateTime now) => [
+ for (final ask in widget.pulse.asks.list)
+ AppMenuItem(
+ key: ValueKey('super-pulse-ask-${ask.messageId}'),
+ label: _person(ask.personId) ?? 'Someone',
+ trailing: _aside(_age(now.difference(ask.at))),
+ detail: _placeOf(ask.conversationId),
+ onPressed: () =>
+ widget.onOpenMessage(ask.conversationId, ask.messageId),
+ ),
+ if (widget.pulse.asks.list.isEmpty) _none('No asks waiting'),
+ ];
+
+ /// The task [agentId] works on in this project, while the Swarm holds it.
+ SuperTabConversation? _taskOf(String agentId) => _snapshot.conversations
+ .where(
+ (g) =>
+ g.projectId == widget.projectId &&
+ g.assignment?['agentId'] == agentId &&
+ !g.closed &&
+ !superTabTaskShipped(g),
+ )
+ .firstOrNull;
+
+ List<Widget> _agentRows() => [
+ for (final id in widget.pulse.working.agentIds)
+ if (_taskOf(id) case final task)
+ AppMenuItem(
+ key: ValueKey('super-pulse-agent-$id'),
+ label: _snapshot.agentName(id),
+ detail: task == null ? null : _label(task),
+ onPressed: task == null ? null : () => widget.onOpenTask(task.id),
+ ),
+ if (widget.pulse.working.agentIds.isEmpty) _none('No agents working'),
+ ];
+
+ List<Widget> _taskRows(
+ List<String> ids, {
+ Map<String, String> reasons = const {},
+ required String empty,
+ }) => [
+ for (final id in ids)
+ if (_snapshot.conversation(id) case final task)
+ AppMenuItem(
+ key: ValueKey('super-pulse-task-$id'),
+ label: task == null
+ ? 'Task'
+ : superTabTitlePriority(task.title).title,
+ trailing: task?.number == null ? null : _aside('#${task!.number}'),
+ detail: reasons[id],
+ onPressed: () => widget.onOpenTask(id),
+ ),
+ if (ids.isEmpty) _none(empty),
+ ];
+}
diff --git a/desktop/lib/super_tabs/tasks_view.dart b/desktop/lib/super_tabs/tasks_view.dart
index c5c1e750e..8bf93e036 100644
--- a/desktop/lib/super_tabs/tasks_view.dart
+++ b/desktop/lib/super_tabs/tasks_view.dart
@@ -15,6 +15,7 @@ import 'backlog.dart';
import 'controller.dart';
import 'machine_status.dart';
import 'model.dart';
+import 'pulse_strip.dart';
import 'task_card.dart';
import 'task_groups.dart';
@@ -30,6 +31,7 @@ class SuperTabTasksView extends StatefulWidget {
required this.needsHuman,
required this.onOpenTask,
required this.onOpenProposal,
+ required this.onOpenMessage,
this.selectedId,
this.storage,
this.now = DateTime.now,
@@ -45,6 +47,9 @@ class SuperTabTasksView extends StatefulWidget {
/// Opens a proposal's thread in the project chat, by its message id.
final ValueChanged<String> onOpenProposal;
+ /// Opens a message in its conversation: an ask the pulse lists.
+ final void Function(String conversationId, String messageId) onOpenMessage;
+
/// The task (or proposal, by its message id) the reader has open: its card
/// shows selected (task #2948).
final String? selectedId;
@@ -183,10 +188,30 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
key: value.where(_keeps).toList(),
};
final empty = board.values.every((entries) => entries.isEmpty);
+ final pulse = c.snapshot?.pulseOf(project.id);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_bar(context),
+ // What waits for the PM and who works (task #3384); none from a
+ // server before it.
+ if (pulse != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ grid.AppDesktop.groupGap,
+ 0,
+ grid.AppDesktop.groupGap,
+ grid.AppDesktop.controlGap,
+ ),
+ child: SuperTabPulseStrip(
+ pulse: pulse,
+ snapshot: c.snapshot!,
+ projectId: project.id,
+ now: widget.now,
+ onOpenTask: widget.onOpenTask,
+ onOpenMessage: widget.onOpenMessage,
+ ),
+ ),
Expanded(
child: empty
? Center(
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 86a665f7b..1360fafd8 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -3433,6 +3433,7 @@ class _SuperTabViewState extends State<SuperTabView>
_tasksSelectedId = id;
_openThreadFromList(project.leadConversationId, id);
},
+ onOpenMessage: (id, messageId) => unawaited(_openMessage(id, messageId)),
);
}
diff --git a/desktop/test/screenshots/board-pulse/pulse-held-dark.png b/desktop/test/screenshots/board-pulse/pulse-held-dark.png
new file mode 100644
index 000000000..1b12eaa90
Binary files /dev/null and b/desktop/test/screenshots/board-pulse/pulse-held-dark.png differ
diff --git a/desktop/test/screenshots/board-pulse/pulse-held-light.png b/desktop/test/screenshots/board-pulse/pulse-held-light.png
new file mode 100644
index 000000000..ee45536a4
Binary files /dev/null and b/desktop/test/screenshots/board-pulse/pulse-held-light.png differ
diff --git a/desktop/test/screenshots/board-pulse/pulse-strip-dark.png b/desktop/test/screenshots/board-pulse/pulse-strip-dark.png
new file mode 100644
index 000000000..0084dc968
Binary files /dev/null and b/desktop/test/screenshots/board-pulse/pulse-strip-dark.png differ
diff --git a/desktop/test/screenshots/board-pulse/pulse-strip-light.png b/desktop/test/screenshots/board-pulse/pulse-strip-light.png
new file mode 100644
index 000000000..28108bf29
Binary files /dev/null and b/desktop/test/screenshots/board-pulse/pulse-strip-light.png differ
diff --git a/desktop/test/super_tab_pulse_shots_test.dart b/desktop/test/super_tab_pulse_shots_test.dart
new file mode 100644
index 000000000..c69798ef2
--- /dev/null
+++ b/desktop/test/super_tab_pulse_shots_test.dart
@@ -0,0 +1,63 @@
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+
+import 'super_tab_pulse_test.dart'
+ show closePulse, pulseFixture, pulseServer, segment, showPulse;
+import 'support/capture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_PULSE_SHOTS'];
+
+/// The board's pulse as the PR shows it (task #3384): the strip on top of the
+/// Board with the oldest ask over its limit and a hold without a reason, both
+/// red, and the Held list open, in both appearances.
+void main() {
+ setUpAll(() async {
+ await loadCaptureFonts(shots);
+ if (shots != null && Platform.isMacOS) {
+ for (final (family, path) in [
+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),
+ ]) {
+ final bytes = ByteData.sublistView(await File(path).readAsBytes());
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ }
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final view in ['strip', 'held']) {
+ testWidgets('screenshots for review ($view, ${brightness.name})', (
+ tester,
+ ) async {
+ final before = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = before);
+ final (c, _) = await showPulse(
+ tester,
+ pulseServer(
+ pulseFixture(
+ redAt: {
+ 'asks': DateTime(2026, 11, 4, 8, 59).millisecondsSinceEpoch,
+ 'held': DateTime(2026, 11, 4, 8, 50).millisecondsSinceEpoch,
+ },
+ ),
+ ),
+ brightness: brightness,
+ size: const Size(1500, 640),
+ );
+ if (view == 'held') {
+ await tester.tap(segment('held'));
+ await tester.pumpAndSettle();
+ expect(find.text('No reason'), findsOneWidget);
+ }
+ expect(tester.takeException(), isNull);
+ await captureWindow(tester, shots, 'pulse-$view-${brightness.name}');
+ await closePulse(tester, c);
+ });
+ }
+ }
+}
diff --git a/desktop/test/super_tab_pulse_test.dart b/desktop/test/super_tab_pulse_test.dart
new file mode 100644
index 000000000..e2410ed56
--- /dev/null
+++ b/desktop/test/super_tab_pulse_test.dart
@@ -0,0 +1,532 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/parts.dart';
+import 'package:harness/super_tabs/pulse.dart';
+import 'package:harness/super_tabs/tasks_view.dart';
+
+import 'super_tab_tasks_view_test.dart' show tasksServer;
+import 'support/memory_key_value_store.dart';
+import 'support/super_tab_fixture.dart';
+
+final pulseNow = DateTime(2026, 11, 4, 9);
+
+int _ago(Duration age) => pulseNow.subtract(age).millisecondsSinceEpoch;
+
+/// A project's pulse as the server sends it in `derived.pulse` (plan
+/// 2026-11-05-board-pulse-plan.md, Contract): two asks waiting for River, the
+/// oldest Scholes's 14 minutes ago; one of two agents working; two tasks next
+/// up; none lost; one held without a reason.
+Map<String, dynamic> pulseFixture({
+ Map<String, Object?> redAt = const {},
+ int asks = 2,
+ Duration oldest = const Duration(minutes: 14),
+ int lost = 0,
+}) => {
+ 'pmId': 'river',
+ 'asks': {
+ 'count': asks,
+ 'oldestAt': asks == 0 ? null : _ago(oldest),
+ 'personId': asks == 0 ? null : 'scholes',
+ 'list': [
+ if (asks > 0)
+ {
+ 'conversationId': 'lead',
+ 'messageId': 'm-old',
+ 'personId': 'scholes',
+ 'at': _ago(oldest),
+ },
+ if (asks > 1)
+ {
+ 'conversationId': 'tag',
+ 'messageId': 'm-new',
+ 'personId': 'tony',
+ 'at': _ago(const Duration(minutes: 3)),
+ },
+ ],
+ },
+ 'working': {
+ 'count': 1,
+ 'crew': 2,
+ 'agentIds': ['finch'],
+ },
+ 'nextUp': {
+ 'count': 2,
+ 'conversationIds': ['shipped-means', 'preview'],
+ },
+ 'lost': {
+ 'count': lost,
+ 'since': lost == 0 ? null : _ago(const Duration(minutes: 4)),
+ 'conversationIds': [if (lost > 0) 'preview'],
+ },
+ 'held': {
+ 'count': 2,
+ 'withoutReason': 1,
+ 'list': [
+ {'conversationId': 'test-copy', 'reason': null},
+ {'conversationId': 'tag', 'reason': 'Waiting on the design review'},
+ ],
+ },
+ 'idleSince': null,
+ 'redAt': {'asks': null, 'idle': null, 'lost': null, 'held': null, ...redAt},
+ 'limits': {'askMinutes': 15, 'idleMinutes': 10, 'lostMinutes': 10},
+};
+
+/// The Tasks view's project with River as its PM, and [pulse] on its read.
+ConversationServer pulseServer(Map<String, dynamic>? pulse) {
+ final server = tasksServer();
+ (server.state['agents'] as List).add({
+ 'id': 'river',
+ 'name': 'Product Manager',
+ 'displayName': 'River',
+ 'machineId': 'studio',
+ 'harnessId': 'h2',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ });
+ if (pulse != null) server.state['pulse'] = {'lead': pulse};
+ return server;
+}
+
+typedef Opened = ({List<String> tasks, List<(String, String)> messages});
+
+Future<(SuperTabController, Opened)> showPulse(
+ WidgetTester tester,
+ ConversationServer server, {
+ DateTime Function()? now,
+ Brightness brightness = Brightness.light,
+ Size size = const Size(1400, 700),
+}) async {
+ await tester.binding.setSurfaceSize(size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ await c.refresh();
+ final opened = (tasks: <String>[], messages: <(String, String)>[]);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabTasksView(
+ controller: c,
+ project: c.snapshot!.projects.single,
+ storage: MemoryKeyValueStore(),
+ needsHuman: (_) => 0,
+ onOpenTask: opened.tasks.add,
+ onOpenProposal: (_) {},
+ onOpenMessage: (conversation, message) =>
+ opened.messages.add((conversation, message)),
+ now: now ?? () => pulseNow,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return (c, opened);
+}
+
+Future<void> closePulse(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+}
+
+Finder segment(String name) => find.byKey(ValueKey('super-pulse-$name'));
+
+String segmentText(WidgetTester tester, String name) => tester
+ .widget<Text>(
+ find.descendant(of: segment(name), matching: find.byType(Text)),
+ )
+ .data!;
+
+/// Red shows three ways, never by color alone: the error ink, a bold label and
+/// the alert icon.
+bool isRed(WidgetTester tester, String name) {
+ final text = tester.widget<Text>(
+ find.descendant(of: segment(name), matching: find.byType(Text)),
+ );
+ final error = Theme.of(tester.element(segment(name))).colorScheme.error;
+ final icon = find
+ .descendant(
+ of: segment(name),
+ matching: find.byIcon(AppIcons.circleAlert),
+ )
+ .evaluate()
+ .isNotEmpty;
+ final red = text.style?.color == error;
+ final bold = (text.style?.fontWeight?.value ?? 400) >= 600;
+ expect(
+ [red, bold, icon],
+ anyOf(everyElement(isTrue), everyElement(isFalse)),
+ reason: '$name is red by ink, weight and icon together',
+ );
+ return red;
+}
+
+Color stripRim(WidgetTester tester) {
+ final box = tester.widget<DecoratedBox>(
+ find.byKey(const ValueKey('super-pulse')),
+ );
+ return ((box.decoration as BoxDecoration).border! as Border).top.color;
+}
+
+const segments = ['asks', 'working', 'nextUp', 'lost', 'held'];
+
+/// The board's pulse (task #3384): what waits for the PM and who works, on
+/// top of a project's Tasks board, red by the server's `redAt` alone.
+void main() {
+ group('parsing derived.pulse', () {
+ Map<String, dynamic> load(Object? pulse) {
+ final answer = jsonDecode(
+ File('test/super_tab_read_fixtures/first_load.json').readAsStringSync(),
+ ) as Map<String, dynamic>;
+ final derived = Map<String, dynamic>.of(
+ answer['derived'] as Map<String, dynamic>? ?? const {},
+ );
+ if (pulse != null) derived['pulse'] = pulse;
+ answer['derived'] = derived;
+ return SuperTabParts.firstLoad(answer).state;
+ }
+
+ test('each project\'s pulse reaches the snapshot', () {
+ final snapshot = SuperTabSnapshot.fromJson(
+ load({
+ '5701': pulseFixture(
+ redAt: {'asks': _ago(const Duration(minutes: 1))},
+ lost: 1,
+ ),
+ }),
+ );
+ final pulse = snapshot.pulseOf('5701')!;
+ expect(pulse.pmId, 'river');
+ expect(pulse.asks.count, 2);
+ expect(
+ pulse.asks.oldestAt,
+ pulseNow.subtract(const Duration(minutes: 14)),
+ );
+ expect(pulse.asks.personId, 'scholes');
+ expect(
+ [
+ for (final ask in pulse.asks.list)
+ (ask.conversationId, ask.messageId, ask.personId),
+ ],
+ [('lead', 'm-old', 'scholes'), ('tag', 'm-new', 'tony')],
+ );
+ expect(pulse.working.count, 1);
+ expect(pulse.working.crew, 2);
+ expect(pulse.working.agentIds, ['finch']);
+ expect(pulse.nextUp.count, 2);
+ expect(pulse.nextUp.conversationIds, ['shipped-means', 'preview']);
+ expect(pulse.lost.count, 1);
+ expect(pulse.lost.conversationIds, ['preview']);
+ expect(pulse.held.count, 2);
+ expect(pulse.held.withoutReason, 1);
+ expect(
+ [
+ for (final hold in pulse.held.list)
+ (hold.conversationId, hold.reason),
+ ],
+ [('test-copy', null), ('tag', 'Waiting on the design review')],
+ );
+ expect(
+ pulse.redAt[SuperTabPulseRule.asks],
+ pulseNow.subtract(const Duration(minutes: 1)),
+ );
+ expect(pulse.redAt[SuperTabPulseRule.idle], isNull);
+ expect(pulse.isRed(SuperTabPulseRule.asks, pulseNow), isTrue);
+ expect(pulse.isRed(SuperTabPulseRule.lost, pulseNow), isFalse);
+ });
+
+ test('an older server sends no pulse, and one that cannot be read is '
+ 'left out rather than drawn wrong', () {
+ expect(SuperTabSnapshot.fromJson(load(null)).pulseOf('5701'), isNull);
+ final broken = SuperTabSnapshot.fromJson(
+ load({
+ '5701': {'pmId': 'river', 'asks': 'two'},
+ }),
+ );
+ expect(broken.pulseOf('5701'), isNull);
+ });
+
+ test('a pulse is red at its redAt, not before', () {
+ final pulse = SuperTabPulse.read(
+ pulseFixture(redAt: {'held': pulseNow.millisecondsSinceEpoch}),
+ )!;
+ expect(pulse.isRed(SuperTabPulseRule.held, pulseNow), isTrue);
+ expect(
+ pulse.isRed(
+ SuperTabPulseRule.held,
+ pulseNow.subtract(const Duration(milliseconds: 1)),
+ ),
+ isFalse,
+ );
+ });
+ });
+
+ testWidgets('the strip reads what waits for the PM and who works', (
+ tester,
+ ) async {
+ final (c, _) = await showPulse(tester, pulseServer(pulseFixture()));
+ expect(find.byKey(const ValueKey('super-pulse')), findsOneWidget);
+ expect(
+ segmentText(tester, 'asks'),
+ 'Waiting for River: 2 asks · oldest 14m (scholes)',
+ );
+ expect(segmentText(tester, 'working'), 'Working 1 of 2');
+ expect(segmentText(tester, 'nextUp'), 'Next up 2');
+ expect(segmentText(tester, 'lost'), 'Lost 0');
+ expect(segmentText(tester, 'held'), 'Held 2 (1 no reason)');
+ // It sits on top of the board.
+ expect(
+ tester.getBottomLeft(find.byKey(const ValueKey('super-pulse'))).dy,
+ lessThanOrEqualTo(
+ tester.getTopLeft(find.byKey(const ValueKey('super-tasks-board'))).dy,
+ ),
+ );
+ for (final name in segments) {
+ expect(isRed(tester, name), isFalse, reason: name);
+ }
+ expect(
+ stripRim(tester),
+ isNot(Theme.of(tester.element(segment('asks'))).colorScheme.error),
+ );
+ await closePulse(tester, c);
+ });
+
+ testWidgets('with nothing waiting, and one ask hours old', (tester) async {
+ final server = pulseServer(pulseFixture(asks: 0));
+ final (c, _) = await showPulse(tester, server);
+ expect(segmentText(tester, 'asks'), 'Nothing waiting for River');
+ server.state['pulse'] = {
+ 'lead': pulseFixture(
+ asks: 1,
+ oldest: const Duration(hours: 3, minutes: 5),
+ ),
+ };
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(
+ segmentText(tester, 'asks'),
+ 'Waiting for River: 1 ask · oldest 3h (scholes)',
+ );
+ await closePulse(tester, c);
+ });
+
+ testWidgets('a held count with every reason given says nothing more', (
+ tester,
+ ) async {
+ final pulse = pulseFixture();
+ pulse['held'] = {
+ 'count': 1,
+ 'withoutReason': 0,
+ 'list': [
+ {'conversationId': 'tag', 'reason': 'Waiting on the design review'},
+ ],
+ };
+ final (c, _) = await showPulse(tester, pulseServer(pulse));
+ expect(segmentText(tester, 'held'), 'Held 1');
+ await closePulse(tester, c);
+ });
+
+ for (final (rule, name) in [
+ ('asks', 'asks'),
+ ('idle', 'working'),
+ ('lost', 'lost'),
+ ('held', 'held'),
+ ]) {
+ testWidgets('$name is red once its $rule redAt has passed', (tester) async {
+ final (c, _) = await showPulse(
+ tester,
+ pulseServer(
+ pulseFixture(redAt: {rule: _ago(const Duration(minutes: 1))}),
+ ),
+ );
+ for (final other in segments) {
+ expect(isRed(tester, other), other == name, reason: other);
+ }
+ expect(
+ stripRim(tester),
+ Theme.of(tester.element(segment(name))).colorScheme.error,
+ );
+ await closePulse(tester, c);
+ });
+ }
+
+ testWidgets(
+ 'a redAt still ahead turns red when it passes, with no new read',
+ (tester) async {
+ var now = pulseNow;
+ final (c, _) = await showPulse(
+ tester,
+ pulseServer(
+ pulseFixture(
+ redAt: {
+ 'asks': pulseNow
+ .add(const Duration(minutes: 1))
+ .millisecondsSinceEpoch,
+ },
+ ),
+ ),
+ now: () => now,
+ );
+ expect(isRed(tester, 'asks'), isFalse);
+ expect(
+ segmentText(tester, 'asks'),
+ 'Waiting for River: 2 asks · oldest 14m (scholes)',
+ );
+ now = now.add(const Duration(minutes: 1));
+ await tester.pump(const Duration(minutes: 1));
+ expect(isRed(tester, 'asks'), isTrue);
+ // The age moved on with the clock too.
+ expect(
+ segmentText(tester, 'asks'),
+ 'Waiting for River: 2 asks · oldest 15m (scholes)',
+ );
+ await closePulse(tester, c);
+ },
+ );
+
+ testWidgets('no strip from a server without the pulse', (tester) async {
+ final (c, _) = await showPulse(tester, pulseServer(null));
+ expect(find.byKey(const ValueKey('super-pulse')), findsNothing);
+ expect(find.byKey(const ValueKey('super-tasks-board')), findsOneWidget);
+ await closePulse(tester, c);
+ });
+
+ group('each count opens its list', () {
+ testWidgets('asks: who and how long, opening the message', (tester) async {
+ final (c, opened) = await showPulse(tester, pulseServer(pulseFixture()));
+ await tester.tap(segment('asks'));
+ await tester.pumpAndSettle();
+ final old = find.byKey(const ValueKey('super-pulse-ask-m-old'));
+ final recent = find.byKey(const ValueKey('super-pulse-ask-m-new'));
+ expect(
+ find.descendant(of: old, matching: find.text('scholes')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: old, matching: find.text('14m')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: recent, matching: find.text('tony')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: recent, matching: find.text('3m')),
+ findsOneWidget,
+ );
+ await tester.tap(old);
+ await tester.pumpAndSettle();
+ expect(opened.messages, [('lead', 'm-old')]);
+ expect(old, findsNothing);
+ await closePulse(tester, c);
+ });
+
+ testWidgets('working: the agents on work, opening the task', (
+ tester,
+ ) async {
+ final (c, opened) = await showPulse(tester, pulseServer(pulseFixture()));
+ await tester.tap(segment('working'));
+ await tester.pumpAndSettle();
+ final finch = find.byKey(const ValueKey('super-pulse-agent-finch'));
+ expect(
+ find.descendant(of: finch, matching: find.text('Finch2')),
+ findsOneWidget,
+ );
+ await tester.tap(finch);
+ await tester.pumpAndSettle();
+ expect(opened.tasks, ['tag']);
+ await closePulse(tester, c);
+ });
+
+ testWidgets('next up: the tasks by title and number', (tester) async {
+ final (c, opened) = await showPulse(tester, pulseServer(pulseFixture()));
+ await tester.tap(segment('nextUp'));
+ await tester.pumpAndSettle();
+ final row = find.byKey(const ValueKey('super-pulse-task-preview'));
+ expect(
+ find.descendant(
+ of: row,
+ matching: find.text('Remove the old preview route'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: row, matching: find.text('#11')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('super-pulse-task-shipped-means')),
+ findsOneWidget,
+ );
+ await tester.tap(row);
+ await tester.pumpAndSettle();
+ expect(opened.tasks, ['preview']);
+ await closePulse(tester, c);
+ });
+
+ testWidgets('lost: the tasks with no agent, or that none are', (
+ tester,
+ ) async {
+ final server = pulseServer(pulseFixture());
+ final (c, opened) = await showPulse(tester, server);
+ await tester.tap(segment('lost'));
+ await tester.pumpAndSettle();
+ expect(find.text('No lost tasks'), findsOneWidget);
+ await tester.tapAt(Offset.zero);
+ await tester.pumpAndSettle();
+ server.state['pulse'] = {'lead': pulseFixture(lost: 1)};
+ await c.refresh();
+ await tester.pumpAndSettle();
+ await tester.tap(segment('lost'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-pulse-task-preview')));
+ await tester.pumpAndSettle();
+ expect(opened.tasks, ['preview']);
+ await closePulse(tester, c);
+ });
+
+ testWidgets('held: each task with its reason, or no reason', (
+ tester,
+ ) async {
+ final (c, opened) = await showPulse(tester, pulseServer(pulseFixture()));
+ await tester.tap(segment('held'));
+ await tester.pumpAndSettle();
+ final none = find.byKey(const ValueKey('super-pulse-task-test-copy'));
+ final given = find.byKey(const ValueKey('super-pulse-task-tag'));
+ expect(
+ find.descendant(
+ of: none,
+ matching: find.text('First run of the test copy'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: none, matching: find.text('No reason')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: given,
+ matching: find.text('Waiting on the design review'),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(given);
+ await tester.pumpAndSettle();
+ expect(opened.tasks, ['tag']);
+ await closePulse(tester, c);
+ });
+ });
+}
diff --git a/desktop/test/super_tab_task_activity_test.dart b/desktop/test/super_tab_task_activity_test.dart
index ef394be8a..e2d07e4da 100644
--- a/desktop/test/super_tab_task_activity_test.dart
+++ b/desktop/test/super_tab_task_activity_test.dart
@@ -54,6 +54,7 @@ Future<SuperTabController> _show(
needsHuman: (task) => asking.contains(task.id) ? 1 : 0,
onOpenTask: (_) {},
onOpenProposal: (_) {},
+ onOpenMessage: (_, _) {},
now: () => _now,
),
),
diff --git a/desktop/test/super_tab_task_priority_test.dart b/desktop/test/super_tab_task_priority_test.dart
index b3aa922ff..17d3d32a0 100644
--- a/desktop/test/super_tab_task_priority_test.dart
+++ b/desktop/test/super_tab_task_priority_test.dart
@@ -74,6 +74,7 @@ Future<SuperTabController> _board(
needsHuman: (_) => 0,
onOpenTask: (_) {},
onOpenProposal: (_) {},
+ onOpenMessage: (_, _) {},
now: () => _now,
),
),
diff --git a/desktop/test/super_tab_tasks_view_test.dart b/desktop/test/super_tab_tasks_view_test.dart
index 7ce087edf..11febbb67 100644
--- a/desktop/test/super_tab_tasks_view_test.dart
+++ b/desktop/test/super_tab_tasks_view_test.dart
@@ -176,6 +176,7 @@ Future<SuperTabController> _show(
needsHuman: (task) => asking.contains(task.id) ? 1 : 0,
onOpenTask: (id) => opened?.add(id),
onOpenProposal: (id) => openedProposals?.add(id),
+ onOpenMessage: (_, _) {},
selectedId: selectedId,
now: () => _now,
),
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 663e051ee..fe7b65c87 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -190,6 +190,8 @@ class SwarmPartsBackend {
'decisionsDigest': state['decisionsDigest'],
if (state['otherProjectsWork'] != null)
'otherProjectsWork': state['otherProjectsWork'],
+ // Each project's board pulse (backend superTabs/pulse.ts, task #3384).
+ if (state['pulse'] != null) 'pulse': state['pulse'],
if (state['avatars'] != null) 'avatars': state['avatars'],
// Only where the server does not try Team accounts (backend read/views.ts).
if (state['teamAccounts'] == false) 'teamAccounts': false,
diff --git a/docs/plans/2026-11-05-board-pulse-plan.md b/docs/plans/2026-11-05-board-pulse-plan.md
new file mode 100644
index 000000000..3e9830825
--- /dev/null
+++ b/docs/plans/2026-11-05-board-pulse-plan.md
@@ -0,0 +1,114 @@
+# Board pulse: unanswered asks and who's working (task #3384)
+
+> Implemented by its Engineer test first, by superpowers:test-driven-development, plan task by plan task, as the project's
+> instructions say (Engineer role). No subagent-driven-development and no execution handoff.
+
+**Goal:** A strip on top of the board (Desktop, web, the phone's task list) shows what waits for the PM and who works:
+`Waiting for River: 2 asks · oldest 14m (Huy) │ Working 6 of 10 │ Next up 7 │ Lost 0 │ Held 3`. Each count opens its
+list. It turns red when an ask waits over 15 min, Working is 0 while work waits for 10 min, a lost task has had no agent
+for 10 min, or a hold has no reason.
+
+**Architecture:** The server keeps what the PM owes on each conversation (`owed`, a short list of a person's messages to the
+PM not yet settled) and settles it on the PM's reply in its place, its verdict reaction, or a task opened from it. It
+marks on the project when Working fell to 0 while work waits (`idleSince`). A new `pulse.ts` computes each project's pulse
+from stored state at read time and the read sends it in `derived.pulse` (cross-part, so never in a part). The CLI's status
+read lays it on each project. Desktop/web and the phone draw it from the same numbers; the server gives each rule's
+`redAt` time and the limits, so no app holds a threshold.
+
+**Tech Stack:** backend TypeScript (vitest), Flutter Desktop/web (`desktop/lib/super_tabs`), Flutter phone
+(`mobile/lib/swarm`), CLI status read (`cli/src/superTabs/reassemble.ts`, two lines).
+
+**Spec:** task #3384's brief (River, 2026-11-05) and River's ruling on Held (same day): Held = an open task whose agent
+set blocked or needs a human, its result as reason (empty = no reason), plus an unassigned task set "not before" a later
+day, its reason the date. One function (`holdOf`) decides it, so the coming hold-reason task switches it there.
+
+## Global Constraints
+
+- Swarm code stays out of `cli/src/core`. Never run a test that signs the Mac out of the real CLI; Desktop tests use a memory
+ store and a fake sign-in.
+- Act and notify: nothing here refuses anything. A settle that finds nothing does nothing.
+- Read only what changed: `owed` rides on the group part each message already writes; the pulse is derived per read from
+ the loaded state, like `derived.machines`.
+- Harness design language for both strips; light and dark screenshots in the PR.
+
+## Design
+
+- growth: `owed` holds at most 50 asks per conversation (newest kept); a settle removes its ask. `idleSince` is one number
+ per project, removed when the condition ends.
+- concurrency: both are written in the command's own group/head part write, under its version guard (parts/commit.ts).
+- read cost: one pass over the loaded groups and agents per visible project per read, as `derived.machines` does; no extra
+ database read.
+- scale: 10x groups is 10x that pass; the read latency metric (`[swarm-read]` timings) warns first.
+- compatibility: older apps ignore `derived.pulse`; a new app on an older server sees no pulse and draws no strip.
+- migration + rollback: no migration. Asks before the release are not owed (nothing recorded them); rollback leaves an
+ unread `owed` field on groups, stripped from reads.
+- audience: asks are recorded only in conversations without an audience (never a private or Buddy chat), so the pulse names
+ no one a project reader could not already see. `owed` is stripped from group views.
+- identity: asks are keyed by the person's member id, never a machine owner's login.
+- failure: a pulse that cannot be computed for a project is left out of `derived.pulse` and logged; the board draws no
+ strip rather than a wrong one.
+- platforms: Desktop macOS/Windows/web and the phone draw the same numbers; no process is started.
+
+## Review Focus
+
+- Settling: only the project's PM settles; a reply settles its message or its whole thread, an answer right below settles
+ that message, a verdict reaction (check, thumbs_up, rocket, tada; never eyes) settles its message, a task opened from a
+ request settles the request.
+- Counts match the board's columns (Next up, Working, Lost, Held) and the red rules use the server's `redAt`.
+
+## Contract (`derived.pulse[projectId]`)
+
+```json
+{ "pmId": "agent id or null",
+ "asks": { "count": 2, "oldestAt": 1793880000000, "personId": "member id or null",
+ "list": [{ "conversationId": "…", "messageId": "…", "personId": "…", "at": 1793880000000 }] },
+ "working": { "count": 6, "crew": 10, "agentIds": ["…"] },
+ "nextUp": { "count": 7, "conversationIds": ["…"] },
+ "lost": { "count": 0, "since": null, "conversationIds": [] },
+ "held": { "count": 3, "withoutReason": 1, "list": [{ "conversationId": "…", "reason": "text or null" }] },
+ "idleSince": null,
+ "redAt": { "asks": 1793880900000, "idle": null, "lost": null, "held": null },
+ "limits": { "askMinutes": 15, "idleMinutes": 10, "lostMinutes": 10 } }
+```
+
+A segment is red when its `redAt` is not null and not after now; the strip is red when any is.
+
+## Tasks
+
+### Task 1: owed asks recorded and settled
+
+**Files:** `backend/src/superTabs/pulse.ts` (new), `pulse.test.ts` (new), `commands.ts` (message.send, message.react,
+conversation.create), `model.ts` (`Conversation.owed`), `read/views.ts` (strip `owed`).
+
+**Interfaces:** `owe(state, group, ask)`, `settleReply(state, group, agentId, {answers, thread})`,
+`settleReaction(state, group, agentId, messageId, emoji)`, `settleRequest(state, group, messageId)`.
+
+- [ ] Failing tests: a person's message to the PM is owed; a message to another agent, a private chat's, an agent's are not;
+ the PM's reply in the thread, its answer right below, a verdict reaction and a task opened from the request each settle
+ it; eyes, another agent's reply and a person's reply do not; the list keeps 50.
+- [ ] Code that passes them.
+
+### Task 2: the pulse
+
+**Files:** `pulse.ts`, `pulse.test.ts`, `projects.ts` (`idleSince`), `store.ts` (mark on save), `read/views.ts` +
+`read/contract.ts` (`derived.pulse`), `cli/src/superTabs/reassemble.ts` (+ spec).
+
+- [ ] Failing tests: each count (asks with oldest and who, working of crew, next up, lost, held with and without reason)
+ and each red rule (ask over 15 min, Working 0 while work waits 10 min, lost 10 min, hold without reason), `idleSince`
+ set and cleared, `derived.pulse` on the read, the CLI status lays it on the project.
+- [ ] Code that passes them.
+
+### Task 3: Desktop/web strip
+
+**Files:** `desktop/lib/super_tabs/pulse.dart` (model + strip), `tasks_view.dart` (on top of the board), tests.
+
+- [ ] Failing widget tests: the strip's text, each segment red by `redAt`, tapping a count opens its list, no strip without
+ a pulse; light and dark golden screenshots.
+- [ ] Code that passes them.
+
+### Task 4: phone strip
+
+**Files:** `mobile/lib/swarm/swarm_pulse.dart` (new), `swarm_project_tasks.dart`, tests.
+
+- [ ] Failing widget tests as Task 3, on the task list; light and dark screenshots.
+- [ ] Code that passes them.
diff --git a/docs/plans/2026-11-05-review-steps-on-handed-plan.md b/docs/plans/2026-11-05-review-steps-on-handed-plan.md
new file mode 100644
index 000000000..6906386fc
--- /dev/null
+++ b/docs/plans/2026-11-05-review-steps-on-handed-plan.md
@@ -0,0 +1,129 @@
+# Reviews open by themselves from the changed files: implementation plan
+
+> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,
+> the failing test committed before its code. No Execution Handoff.
+
+**Goal:** When a task's pull request is handed (its Engineer's Ready for review), the server opens the task's review steps
+from a table of path rules (one read by default; two security reviews for sign-in, tokens, crypto, access, the Buddy guard,
+device links and deletion; a test step where the change runs) and assigns each to a free reviewer it picks by rule: never the
+engineer, never a grid model, at least as strong as the engineer, no verdict yet at this head. Nothing is refused: a step
+nobody is free for stays open and the PM is told once. A batch asks for a combination read only when two of its pull
+requests touch the same file (task #3401, requested by Dee through Harness).
+
+**Architecture:** The table is the project rules record's review section (`policy.ts`, #3393: rows with path globs, test
+rows, untested paths, read through its linear-time matcher, at most `MAX_WILDCARDS` wildcards per pattern, both from #3216).
+A new `reviewTable.ts` turns a pull request's changed files into the steps it needs (`reviewPlan`), and
+says which files two pull requests of a batch share (`sharedFiles`). A new `reviewerPick.ts` ranks the free agents for a step
+(`reviewerCandidates`). In `commands.ts`, `work.assign`'s checks and its writes split into two closures (`assignRefusal`,
+`assignTo`) so the server's own assignment runs the very same checks and writes; `work.status` `review` on a task (not a
+step) calls `openReviewSteps`, which opens each missing step as `conversation.create` with `reviewOf` and `step` would, and
+assigns it to the first candidate `assignRefusal` lets through. The files come in the command's context
+(`pullRequestFiles`), read by the store outside the transaction from GitHub, as `pushOrigin` is for the same command.
+
+**Tech Stack:** TypeScript backend (vitest unit tests on `applyCommand`).
+
+**Spec:** task #3401 brief (conversation 09910149766fbfb592f7e48f); siblings #3393 (rules record: its `reviews` section),
+#3394 (verdict `head`), #3399 (`handed` state).
+
+## Global Constraints
+
+- PR body first line: "Requested by Dee through Harness."
+- Owns `backend/src/superTabs/`; outside it only wiring: `backend/src/routes/superTabs.ts` (the hook), the new integration
+ test and its line in `vitest.super-tabs.config.ts`. The GitHub read is #3394's `pullRequestFiles` (agreed in its task),
+ not a second one; until #3394 lands the app has none, the hook reads nothing, and Ready is as before.
+- No new refusal: `removedRefusals.test.ts` stays green. The server's open never fails the Engineer's Ready.
+- Old clients: an Engineer that opens its own steps first keeps them: a step of the same name is reused, never doubled.
+- Fail safe: files GitHub cannot read (no app, an error, over 3,000 files) plan as the strictest table: one read and two
+ security reviews, and the step's brief says the files were not read.
+- Swarm code stays out of cli/src/core.
+
+## Design
+
+- growth: steps are groups that archive with their task (steps.ts endSteps); at most 4 per task per round, reused next round.
+- concurrency: the steps and their assignments are written in the Ready's own transaction (one command), so two Readies race
+ on the task's part as any two commands do; the GitHub read is outside it and only feeds the plan.
+- read cost: one GitHub read (`GET /pulls/N` head + `GET /pulls/N/files`, at most 30 pages of 100) per Ready of a task with
+ a pull request; nothing on any other command or read.
+- scale: 10x Readies is 10x that read; GitHub's rate limit warns first, logged by the hook on failure.
+- compatibility: old clients see ordinary steps; an Engineer still may open or assign a step itself.
+- migration + rollback: none; rolling back leaves the opened steps as ordinary steps.
+- audience: the files are the server's GitHub App read of the project's own repository, never a client's word; picks are
+ within the task's project and pass every check `work.assign` makes.
+- identity: the steps and their briefs are written by the Engineer's own Ready, as its other rows are; never as the
+ machine owner.
+- failure: a step nobody is free for stays open, with one notice to the PM naming it and why; a file read failure plans the
+ strictest steps and says so in the brief.
+- platforms: backend only.
+
+## Review Focus
+
+- A security-sensitive path always gets two security reviews by two different agents, neither the engineer.
+- The pick never names the engineer, a grid model, a weaker model, or an agent with a verdict at this head.
+- A second Ready reuses the same steps (Workflow 3), and adds only what the new files need.
+
+---
+
+### Task 1: the review table and its plan
+
+**Files:** Create `backend/src/superTabs/reviewTable.ts`, test `reviewTable.test.ts`.
+
+**Interfaces (first version; Task 6 moved the table to policy.ts):** `REVIEW_TABLE: ReviewTable` = `{ defaultReads: 1, rows: [{ area, reads, paths: glob[] }], test: [{ where,
+paths: glob[] }] }`; `globMatch(glob, path)`; `reviewPlan(files: string[] | null, table?) => PlannedStep[]` where
+`PlannedStep = { name: 'Review' | 'Security review 1' | 'Security review 2' | 'Test', kind: 'review' | 'security' | 'test',
+areas: string[], where?: string[] }`; `sharedFiles(pulls: Array<{ url, files }>) => Array<{ file, urls }>`.
+
+- [x] Test: a docs-only change plans one Review; a sign-in change (`backend/src/lib/auth*`, `backend/src/routes/auth*`,
+ `cli/src/**/login*`) plans Review + Security review 1 + 2 naming "Sign-in"; a Desktop change adds Test "Desktop on a Mac";
+ unread files plan the strictest; `sharedFiles` names only files in two pull requests.
+- [x] Code.
+
+### Task 2: who may review
+
+**Files:** Create `backend/src/superTabs/reviewerPick.ts`, test `reviewerPick.test.ts`.
+
+**Interfaces:** `builtBy(task) => Set<agentId>` (assignee and every run's agent); `strengthOf(agent) => number | null`
+(catalog.ts); `reviewerCandidates(state, task, kind, head, index) => Agent[]`, best first.
+
+- [x] Test: never the engineer or an earlier builder; never a grid model; never weaker than the engineer; never an agent
+ with a verdict at this head (a verdict's `head`, #3394; without one, any verdict since the task's Ready); never one
+ holding another open step of this task; never busy, a Lead or a Buddy; the step's role (Reviewer / Tester) first.
+- [x] Code.
+
+### Task 3: steps open on handed
+
+**Files:** Modify `backend/src/superTabs/commands.ts` (assign split, `openReviewSteps` on `work.status` review),
+`backend/src/superTabs/model.ts` (context type), test `reviewSteps.test.ts`.
+
+- [x] Test (acceptance): a PR touching sign-in code opens two security reviews and a read, each assigned to a different free
+ Reviewer, never the Engineer; a docs PR opens one read; a second Ready reuses the steps; with nobody free the step stays
+ open and the PM gets one notice; the Ready itself is never refused.
+- [x] Code.
+
+### Task 4: the files reach the command
+
+**Files:** Create `backend/src/superTabs/pullRequestFiles.ts` (the read, over #3394's app method), modify
+`backend/src/superTabs/store.ts` (hook, context, reach read for the Ready), `backend/src/routes/superTabs.ts` (wiring); tests
+`pullRequestFiles.test.ts`, `integration/superTabReviewSteps.test.ts`.
+
+- [x] Test: the hook reads the task's own-repository pull requests only, returns `null` files on any failure; the store
+ passes them to the Ready's context.
+- [x] Code.
+
+### Task 5: the template says so
+
+**Files:** `backend/src/superTabs/instructionsTemplate.ts`, `instructions.test.ts`.
+
+- [x] Test: Workflow 2 says the server opens a ready pull request's steps, and the Engineer opens them only where it opened none.
+- [x] Code.
+
+The combination read: `sharedFiles` is the batch's question (task #3402, the merge train, calls it); no batch code runs on
+the server before that task lands.
+
+### Task 6: one table, the project rules record (River, after review)
+
+**Files:** `reviewTable.ts` (reads the record; the matcher and its wildcard cap are #3216's, merged in),
+`commands.ts` / `store.ts` (the Ready reads the project's newest rules revision), `reviewerPick.ts` (whole heads only, #3394).
+
+- [x] Test: the plan follows the project's saved rules, in the command and through the store.
+- [x] Test: a verdict naming no head, or a prefix of the head, is not at this head.
+- [x] Code; the local `REVIEW_TABLE` and `globMatch` copy are gone, and `policy.ts` is #3216's as reviewed.
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index b28c50587..9f48c4ec5 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -1,6 +1,7 @@
import 'identity.dart' show superTabPersonName;
import 'live_card_model.dart';
import 'profile_model.dart';
+import 'pulse_model.dart';
export 'profile_model.dart';
@@ -731,6 +732,7 @@ class SuperTabSnapshot {
autoJoin = row['autoJoin'] == true,
mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,
mentionsDigest = row['mentionsDigest'] as String?,
+ pulses = SuperTabPulse.readAll(row['pulse']),
decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
decisionsDigest = row['decisionsDigest'] as String?,
activityDigest = row['activityDigest'] as String?,
@@ -846,6 +848,14 @@ class SuperTabSnapshot {
/// count may not; null from a backend before it (superTabs/mentions.ts).
final String? mentionsDigest;
+ /// Each project's board pulse by project id (backend superTabs/pulse.ts,
+ /// read `derived.pulse`); empty from a server before it.
+ final Map<String, SuperTabPulse> pulses;
+
+ /// [projectId]'s board pulse; null where the server sent none, and the
+ /// board draws no strip.
+ SuperTabPulse? pulseOf(String projectId) => pulses[projectId];
+
/// Decisions asked of the reader and not yet answered, Swarm-wide; 0 from a
/// backend before decisions (backend superTabs/decisions.ts).
final int decisionsWaiting;
diff --git a/mobile/lib/swarm/parts.dart b/mobile/lib/swarm/parts.dart
index acf823696..184ac753b 100644
--- a/mobile/lib/swarm/parts.dart
+++ b/mobile/lib/swarm/parts.dart
@@ -494,6 +494,8 @@ class SuperTabParts {
if (_derived['activityDigest'] case final String digest) {
state['activityDigest'] = digest;
}
+ // Each project's board pulse (backend superTabs/pulse.ts, task #3384).
+ if (_derived['pulse'] case final Map pulse) state['pulse'] = pulse;
// Sent only where the server does not try Harness Team accounts yet.
if (_derived['teamAccounts'] == false) state['teamAccounts'] = false;
// Sent by a server that takes a thread reply's New session.
diff --git a/mobile/lib/swarm/pulse_model.dart b/mobile/lib/swarm/pulse_model.dart
new file mode 100644
index 000000000..19a3a4976
--- /dev/null
+++ b/mobile/lib/swarm/pulse_model.dart
@@ -0,0 +1,188 @@
+/// A project's board pulse (task #3384): what waits for its PM and who works,
+/// as the server works it out per read (backend superTabs/pulse.ts) and sends
+/// it in `derived.pulse`. The server decides when each count turns red
+/// (`redAt`); the app holds no threshold of its own.
+library;
+
+/// A rule that turns a segment of the pulse red.
+enum SuperTabPulseRule {
+ /// An ask has waited too long for the PM.
+ asks,
+
+ /// Nobody has worked while work waited.
+ idle,
+
+ /// A lost task has had no agent too long.
+ lost,
+
+ /// A hold has no reason.
+ held,
+}
+
+/// A person's message to the PM not yet settled.
+typedef SuperTabPulseAsk = ({
+ String conversationId,
+ String messageId,
+ String? personId,
+ DateTime at,
+});
+
+/// A held task and why, null when nobody said.
+typedef SuperTabPulseHold = ({String conversationId, String? reason});
+
+class SuperTabPulse {
+ SuperTabPulse._(Map<String, dynamic> row)
+ : pmId = _optional<String>(row['pmId']),
+ asks = _asks(_map(row['asks'])),
+ working = _working(_map(row['working'])),
+ nextUp = _tasks(_map(row['nextUp'])),
+ lost = _tasks(_map(row['lost'])),
+ held = _held(_map(row['held'])),
+ limits = switch (row['limits']) {
+ final Map limits => (
+ askMinutes: _optional<num>(limits['askMinutes'])?.toInt(),
+ idleMinutes: _optional<num>(limits['idleMinutes'])?.toInt(),
+ lostMinutes: _optional<num>(limits['lostMinutes'])?.toInt(),
+ ),
+ _ => (askMinutes: null, idleMinutes: null, lostMinutes: null),
+ },
+ redAt = Map.unmodifiable({
+ for (final rule in SuperTabPulseRule.values)
+ rule: ?_time(_map(row['redAt'])[rule.name]),
+ });
+
+ /// [value]'s pulse; null for one this build cannot read, so the board draws
+ /// no strip rather than a wrong one.
+ static SuperTabPulse? read(Object? value) {
+ if (value is! Map) return null;
+ try {
+ return SuperTabPulse._(Map<String, dynamic>.from(value));
+ } on FormatException {
+ return null;
+ }
+ }
+
+ /// Every project's pulse in `derived.pulse`, by project id; empty from a
+ /// server before it.
+ static Map<String, SuperTabPulse> readAll(Object? value) => Map.unmodifiable({
+ if (value is Map)
+ for (final MapEntry(:key, :value) in value.entries)
+ if (key is String) key: ?read(value),
+ });
+
+ /// The project's PM, while it has one.
+ final String? pmId;
+ final ({
+ int count,
+ DateTime? oldestAt,
+ String? personId,
+ List<SuperTabPulseAsk> list,
+ })
+ asks;
+ final ({int count, int crew, List<String> agentIds}) working;
+ final ({int count, List<String> conversationIds}) nextUp, lost;
+ final ({int count, int withoutReason, List<SuperTabPulseHold> list}) held;
+
+ /// The limits behind `redAt`, only to say why a count is red.
+ final ({int? askMinutes, int? idleMinutes, int? lostMinutes}) limits;
+
+ /// When each rule turns red; a rule left out is not red.
+ final Map<SuperTabPulseRule, DateTime> redAt;
+
+ /// Whether [rule] is red at [now]: at its `redAt` or after it.
+ bool isRed(SuperTabPulseRule rule, DateTime now) {
+ final at = redAt[rule];
+ return at != null && !at.isAfter(now);
+ }
+
+ /// Whether any rule is red at [now].
+ bool anyRed(DateTime now) =>
+ SuperTabPulseRule.values.any((rule) => isRed(rule, now));
+
+ /// The next time after [now] a rule turns red, null when none will.
+ DateTime? nextRedAfter(DateTime now) {
+ DateTime? next;
+ for (final at in redAt.values) {
+ if (at.isAfter(now) && (next == null || at.isBefore(next))) next = at;
+ }
+ return next;
+ }
+
+ static ({
+ int count,
+ DateTime? oldestAt,
+ String? personId,
+ List<SuperTabPulseAsk> list,
+ })
+ _asks(Map<String, dynamic> row) => (
+ count: _count(row['count']),
+ oldestAt: _time(row['oldestAt']),
+ personId: _optional<String>(row['personId']),
+ list: List.unmodifiable([
+ for (final ask in _list(row['list']))
+ (
+ conversationId: _text(_map(ask)['conversationId']),
+ messageId: _text(_map(ask)['messageId']),
+ personId: _optional<String>(_map(ask)['personId']),
+ at: _time(_map(ask)['at']) ?? (throw const FormatException('at')),
+ ),
+ ]),
+ );
+
+ static ({int count, int crew, List<String> agentIds}) _working(
+ Map<String, dynamic> row,
+ ) => (
+ count: _count(row['count']),
+ crew: _count(row['crew']),
+ agentIds: _ids(row['agentIds']),
+ );
+
+ static ({int count, List<String> conversationIds}) _tasks(
+ Map<String, dynamic> row,
+ ) => (
+ count: _count(row['count']),
+ conversationIds: _ids(row['conversationIds']),
+ );
+
+ static ({int count, int withoutReason, List<SuperTabPulseHold> list}) _held(
+ Map<String, dynamic> row,
+ ) => (
+ count: _count(row['count']),
+ withoutReason: _count(row['withoutReason'] ?? 0),
+ list: List.unmodifiable([
+ for (final hold in _list(row['list']))
+ (
+ conversationId: _text(_map(hold)['conversationId']),
+ reason: switch (_map(hold)['reason']) {
+ final String reason when reason.trim().isNotEmpty => reason,
+ _ => null,
+ },
+ ),
+ ]),
+ );
+
+ static Map<String, dynamic> _map(Object? value) => value is Map
+ ? Map<String, dynamic>.from(value)
+ : throw const FormatException('Not a pulse object.');
+
+ static List<Object?> _list(Object? value) => switch (value) {
+ null => const [],
+ final List list => list,
+ _ => throw const FormatException('Not a pulse list.'),
+ };
+
+ static List<String> _ids(Object? value) =>
+ List.unmodifiable([for (final id in _list(value)) _text(id)]);
+
+ static String _text(Object? value) =>
+ value is String ? value : throw const FormatException('Not an id.');
+
+ static int _count(Object? value) => value is num
+ ? value.toInt()
+ : throw const FormatException('Not a count.');
+
+ static T? _optional<T>(Object? value) => value is T ? value : null;
+
+ static DateTime? _time(Object? value) =>
+ value is num ? DateTime.fromMillisecondsSinceEpoch(value.toInt()) : null;
+}
diff --git a/mobile/lib/swarm/swarm_project_tasks.dart b/mobile/lib/swarm/swarm_project_tasks.dart
index 5ddd88681..8c0dad98f 100644
--- a/mobile/lib/swarm/swarm_project_tasks.dart
+++ b/mobile/lib/swarm/swarm_project_tasks.dart
@@ -15,6 +15,7 @@ import 'swarm_home_rows.dart';
import 'swarm_inbox.dart';
import 'swarm_need_rows.dart';
import 'swarm_project_page.dart' show swarmProjectWork;
+import 'swarm_pulse.dart';
import 'swarm_reader.dart';
import 'swarm_row.dart';
import 'swarm_session.dart';
@@ -114,7 +115,9 @@ String? _projectOf(SuperTabSnapshot snapshot, SwarmNeed need) => switch (need) {
/// each need with Approve (a decision's recommended answer, held for Undo as
/// everywhere) or Reply, which opens where it was asked; "Working" with its
/// count, each task with its agent and its line; and "Done today", folded in
-/// one row. A row opens its chat ([onOpen]); a pull reads the Swarm again.
+/// one row. On top, the project's board pulse ([SwarmPulseStrip]) where the
+/// server sends one. A row opens its chat ([onOpen]); a pull reads the Swarm
+/// again.
class SwarmProjectTasks extends StatefulWidget {
const SwarmProjectTasks({
super.key,
@@ -167,6 +170,8 @@ class _SwarmProjectTasksState extends State<SwarmProjectTasks> {
onTap: () => widget.onOpen(g.id),
);
final done = tasks.doneToday.length;
+ // The board pulse on top, from a server that sends it.
+ final pulse = snapshot.pulseOf(widget.projectId) != null;
return RefreshIndicator(
onRefresh: reader.refresh,
child: ListView(
@@ -179,11 +184,17 @@ class _SwarmProjectTasksState extends State<SwarmProjectTasks> {
MediaQuery.paddingOf(context).bottom + AppSpace.xl,
),
children: [
+ if (pulse)
+ SwarmPulseStrip(
+ reader: reader,
+ projectId: widget.projectId,
+ onOpen: widget.onOpen,
+ ),
if (tasks.waiting.isNotEmpty) ...[
SwarmCaption(
'Waiting on you',
count: tasks.waiting.length,
- first: true,
+ first: !pulse,
),
SwarmGroup(
children: [
@@ -205,7 +216,7 @@ class _SwarmProjectTasksState extends State<SwarmProjectTasks> {
count: tasks.working.length,
countColor: AppColors.success,
countKey: const ValueKey('swarm-working-count'),
- first: tasks.waiting.isEmpty,
+ first: !pulse && tasks.waiting.isEmpty,
),
if (tasks.working.isEmpty)
Padding(
diff --git a/mobile/lib/swarm/swarm_project_team.dart b/mobile/lib/swarm/swarm_project_team.dart
index f4574ee32..c3274b89e 100644
--- a/mobile/lib/swarm/swarm_project_team.dart
+++ b/mobile/lib/swarm/swarm_project_team.dart
@@ -15,6 +15,7 @@ import 'swarm_chat_agents.dart';
import 'swarm_instructions_page.dart';
import 'swarm_leaderboard.dart';
import 'swarm_project_tasks.dart';
+import 'swarm_pulse.dart';
import 'swarm_reader.dart';
import 'swarm_row.dart';
import 'swarm_session.dart';
@@ -238,7 +239,8 @@ class SwarmProjectTeamSheet extends StatelessWidget {
/// A project's Team, as Swarm Home C draws it (Tony, 2026-10-30) to Dee's
/// rules (2026-10-29), one row shape for its agents ([SwarmMemberRow]). On
-/// top its open tasks, in the Tasks tab's rows: what waits on the person,
+/// top the project's board pulse ([SwarmPulseStrip]) where the server sends
+/// one, then its open tasks, in the Tasks tab's rows: what waits on the person,
/// then the work going on ([swarmProjectTasks]) — the first [workShown], and
/// a row that shows the rest in place — each opening its chat ([onOpen]).
/// Then its agents, each in its state with the task it holds, the most urgent
@@ -355,6 +357,8 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
final work = folds && !_allWork
? working.take(SwarmProjectTeam.workShown)
: working;
+ // The board pulse on top, from a server that sends it.
+ final pulse = snapshot.pulseOf(project.id) != null;
return RefreshIndicator(
onRefresh: reader.refresh,
child: ListView(
@@ -367,11 +371,17 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
MediaQuery.paddingOf(context).bottom + AppSpace.xl,
),
children: [
+ if (pulse)
+ SwarmPulseStrip(
+ reader: reader,
+ projectId: project.id,
+ onOpen: widget.onOpen,
+ ),
if (tasks.waiting.isNotEmpty) ...[
- const SwarmCaption(
+ SwarmCaption(
'Waiting on you',
- key: ValueKey('swarm-team-waiting-caption'),
- first: true,
+ key: const ValueKey('swarm-team-waiting-caption'),
+ first: !pulse,
),
SwarmGroup(
children: [
@@ -392,7 +402,7 @@ class _SwarmProjectTeamState extends State<SwarmProjectTeam> {
SwarmCaption(
'Working on',
key: const ValueKey('swarm-team-working-caption'),
- first: tasks.waiting.isEmpty,
+ first: !pulse && tasks.waiting.isEmpty,
),
if (working.isEmpty && tasks.waiting.isEmpty)
Padding(
diff --git a/mobile/lib/swarm/swarm_pulse.dart b/mobile/lib/swarm/swarm_pulse.dart
new file mode 100644
index 000000000..da3d90bc7
--- /dev/null
+++ b/mobile/lib/swarm/swarm_pulse.dart
@@ -0,0 +1,571 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/shared/widgets/touch_target.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+
+import 'model.dart';
+import 'pulse_model.dart';
+import 'swarm_leaderboard.dart' show swarmSheetRoute;
+import 'swarm_project_page.dart' show swarmChatRoute;
+import 'swarm_reader.dart';
+import 'swarm_row.dart';
+import 'swarm_style.dart';
+import 'swarm_task_status.dart' show swarmTaskPersonName;
+
+/// How long ago, shortest, for the pulse: "0m", "14m", "3h", "2d".
+String swarmPulseAge(Duration age) {
+ if (age.inHours < 1) return '${age.inMinutes < 0 ? 0 : age.inMinutes}m';
+ if (age.inDays < 1) return '${age.inHours}h';
+ return '${age.inDays}d';
+}
+
+/// When [pulse], drawn at [now], next reads differently: the soonest of a rule
+/// turning red and the oldest ask's age moving on ([swarmPulseAge]); null
+/// while neither will, so the strip keeps no timer (ENGINEERING 4).
+DateTime? swarmPulseNextWake(SuperTabPulse pulse, DateTime now) {
+ final oldest = pulse.asks.count > 0 ? pulse.asks.oldestAt : null;
+ final times = [
+ ?pulse.nextRedAfter(now),
+ if (oldest != null) now.add(_nextAgeStep(now.difference(oldest))),
+ ];
+ if (times.isEmpty) return null;
+ return times.reduce((a, b) => a.isBefore(b) ? a : b);
+}
+
+/// How long until [age], as [swarmPulseAge] writes it, reads differently.
+Duration _nextAgeStep(Duration age) {
+ if (age.isNegative) return -age;
+ final unit = age < const Duration(hours: 1)
+ ? const Duration(minutes: 1)
+ : age < const Duration(days: 1)
+ ? const Duration(hours: 1)
+ : const Duration(days: 1);
+ return unit -
+ Duration(microseconds: age.inMicroseconds % unit.inMicroseconds);
+}
+
+/// The name the pulse calls [pulse]'s PM by: its agent's name, or "the PM".
+String swarmPulsePmName(SuperTabSnapshot snapshot, SuperTabPulse pulse) =>
+ switch (pulse.pmId) {
+ final id? when snapshot.agent(id) != null => snapshot.agentName(id),
+ _ => 'the PM',
+ };
+
+/// The strip's words, part by part: each part's text and whether it is the
+/// count, which speaks louder than the words around it.
+typedef _Words = List<(String, bool)>;
+
+/// What the strip's asks say: "Waiting for River: 2 asks · oldest 14m (Huy)",
+/// or "Nothing waiting for River".
+_Words _askWords(SuperTabSnapshot snapshot, SuperTabPulse pulse, DateTime now) {
+ final pm = swarmPulsePmName(snapshot, pulse);
+ final asks = pulse.asks;
+ if (asks.count == 0) return [('Nothing waiting for $pm', false)];
+ final who = switch (asks.personId) {
+ final id? => swarmTaskPersonName(snapshot)(id),
+ null => null,
+ };
+ return [
+ ('Waiting for $pm: ', false),
+ (asks.count == 1 ? '1 ask' : '${asks.count} asks', true),
+ if (asks.oldestAt case final at?)
+ (' · oldest ${swarmPulseAge(now.difference(at))}', false),
+ if (who != null) (' ($who)', false),
+ ];
+}
+
+/// A project's board pulse (task #3384) on top of its task list: what waits
+/// for its PM, then who works of its crew, what is next up, lost and held,
+/// as the server counts them (`derived.pulse`). Nothing without a pulse: an
+/// older server sends none. Each count opens its list in a sheet
+/// ([showSwarmPulseList]). A part is red once the server's `redAt` for its
+/// rule has come — asks; idle, on Working; lost; held — with a mark and bold
+/// beside its colour; the app holds no threshold. It wakes when the next
+/// `redAt` comes and when the oldest ask's age next reads differently, and
+/// never while nothing it shows will change ([swarmPulseNextWake]).
+class SwarmPulseStrip extends StatefulWidget {
+ const SwarmPulseStrip({
+ super.key,
+ required this.reader,
+ required this.projectId,
+ required this.onOpen,
+ });
+
+ final SwarmReader reader;
+ final String projectId;
+
+ /// Opens one of the project's chats, by id: a task from a list.
+ final ValueChanged<String> onOpen;
+
+ @override
+ State<SwarmPulseStrip> createState() => _SwarmPulseStripState();
+}
+
+class _SwarmPulseStripState extends State<SwarmPulseStrip> {
+ late final AppLifecycleListener _lifecycle;
+
+ /// One timer, for the next time the strip reads differently
+ /// ([swarmPulseNextWake]); none while nothing will.
+ Timer? _wake;
+ DateTime? _wakeAt;
+
+ void _redraw() {
+ if (mounted) setState(() {});
+ }
+
+ @override
+ void initState() {
+ super.initState();
+ _lifecycle = AppLifecycleListener(onResume: _redraw);
+ }
+
+ @override
+ void dispose() {
+ _wake?.cancel();
+ _lifecycle.dispose();
+ super.dispose();
+ }
+
+ void _arm(SuperTabPulse? pulse, DateTime now) {
+ final next = pulse == null ? null : swarmPulseNextWake(pulse, now);
+ if (next == _wakeAt) return;
+ _wake?.cancel();
+ _wakeAt = next;
+ _wake = next == null
+ ? null
+ : Timer(next.difference(now), () {
+ _wakeAt = null;
+ _redraw();
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final snapshot = widget.reader.snapshot;
+ final pulse = snapshot?.pulseOf(widget.projectId);
+ if (snapshot == null || pulse == null) {
+ _arm(null, clock.now());
+ return const SizedBox.shrink();
+ }
+ final now = clock.now();
+ _arm(pulse, now);
+ void open(SwarmPulseList list) => unawaited(
+ showSwarmPulseList(
+ context,
+ reader: widget.reader,
+ projectId: widget.projectId,
+ list: list,
+ onOpen: widget.onOpen,
+ ),
+ );
+ bool red(SuperTabPulseRule rule) => pulse.isRed(rule, now);
+ final held = pulse.held;
+ return Padding(
+ key: const ValueKey('swarm-pulse'),
+ padding: const EdgeInsets.only(top: AppSpace.s),
+ child: SwarmGroup(
+ children: [
+ _Segment(
+ name: 'asks',
+ words: _askWords(snapshot, pulse, now),
+ red: red(SuperTabPulseRule.asks),
+ wide: true,
+ onTap: () => open(SwarmPulseList.asks),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),
+ child: Wrap(
+ spacing: AppSpace.xs,
+ children: [
+ _Segment(
+ name: 'working',
+ words: [
+ ('Working ', false),
+ ('${pulse.working.count}', true),
+ (' of ${pulse.working.crew}', false),
+ ],
+ red: red(SuperTabPulseRule.idle),
+ onTap: () => open(SwarmPulseList.working),
+ ),
+ _Segment(
+ name: 'next-up',
+ words: [('Next up ', false), ('${pulse.nextUp.count}', true)],
+ red: false,
+ onTap: () => open(SwarmPulseList.nextUp),
+ ),
+ _Segment(
+ name: 'lost',
+ words: [('Lost ', false), ('${pulse.lost.count}', true)],
+ red: red(SuperTabPulseRule.lost),
+ onTap: () => open(SwarmPulseList.lost),
+ ),
+ _Segment(
+ name: 'held',
+ words: [
+ ('Held ', false),
+ ('${held.count}', true),
+ if (held.withoutReason > 0)
+ (' (${held.withoutReason} no reason)', false),
+ ],
+ red: red(SuperTabPulseRule.held),
+ onTap: () => open(SwarmPulseList.held),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// One part of the strip, a thumb's touch tall: its words in the secondary
+/// ink, its count in the primary one; red, all of it in the error ink and
+/// bold after a mark, and heard as needing a look. [wide] takes the strip's
+/// width, with a chevron at its end.
+class _Segment extends StatelessWidget {
+ const _Segment({
+ required this.name,
+ required this.words,
+ required this.red,
+ required this.onTap,
+ this.wide = false,
+ });
+
+ final String name;
+ final _Words words;
+ final bool red, wide;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final heard = words.map((w) => w.$1).join();
+ final text = Text.rich(
+ TextSpan(
+ children: [
+ for (final (part, count) in words)
+ TextSpan(
+ text: part,
+ style: count && !red
+ ? TextStyle(
+ color: AppPalette.textPrimary,
+ fontWeight: AppFont.semibold,
+ )
+ : null,
+ ),
+ ],
+ ),
+ key: ValueKey('swarm-pulse-$name-text'),
+ maxLines: wide ? 2 : 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.caption(
+ color: red ? AppColors.danger : AppPalette.textSecondary,
+ fontWeight: red ? AppFont.semibold : null,
+ height: 1.35,
+ fontFeatures: const [FontFeature.tabularFigures()],
+ ),
+ );
+ final mark = red
+ ? [
+ Icon(
+ LucideIcons.circleAlert300,
+ key: ValueKey('swarm-pulse-$name-red'),
+ size: 16,
+ color: AppColors.danger,
+ ),
+ const SizedBox(width: AppSpace.xs),
+ ]
+ : const <Widget>[];
+ return Semantics(
+ button: true,
+ label: red ? '$heard, needs a look' : heard,
+ excludeSemantics: true,
+ onTap: onTap,
+ child: Material(
+ key: ValueKey('swarm-pulse-$name'),
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: onTap,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: minTouchTarget),
+ child: Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: wide ? AppSpace.l : AppSpace.s,
+ vertical: AppSpace.s,
+ ),
+ child: Row(
+ mainAxisSize: wide ? MainAxisSize.max : MainAxisSize.min,
+ children: [
+ ...mark,
+ if (wide) Expanded(child: text) else Flexible(child: text),
+ if (wide) ...[
+ const SizedBox(width: AppSpace.m),
+ Icon(
+ LucideIcons.chevronRight300,
+ size: 18,
+ color: AppPalette.textFaint,
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The lists the strip's counts open.
+enum SwarmPulseList { asks, working, nextUp, lost, held }
+
+/// [list] of [projectId]'s pulse in a sheet, kept up to date by [reader]'s
+/// reads: the asks, each its person, how long ago and where, opening its
+/// message in its conversation; the working agents, each opening the task it
+/// holds; or Next up's, Lost's or Held's tasks, Held's with each reason or
+/// "no reason", each opening its task ([onOpen]). Whatever opens goes over
+/// the sheet, and back comes back to it.
+Future<void> showSwarmPulseList(
+ BuildContext context, {
+ required SwarmReader reader,
+ required String projectId,
+ required SwarmPulseList list,
+ required ValueChanged<String> onOpen,
+}) => Navigator.of(context).push(
+ swarmSheetRoute<void>(
+ context,
+ builder: (context) => _PulseSheet(
+ reader: reader,
+ projectId: projectId,
+ list: list,
+ onOpen: onOpen,
+ ),
+ ),
+);
+
+class _PulseSheet extends StatelessWidget {
+ const _PulseSheet({
+ required this.reader,
+ required this.projectId,
+ required this.list,
+ required this.onOpen,
+ });
+
+ final SwarmReader reader;
+ final String projectId;
+ final SwarmPulseList list;
+ final ValueChanged<String> onOpen;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return ListenableBuilder(
+ listenable: reader,
+ builder: (context, _) {
+ final snapshot = reader.snapshot;
+ final pulse = snapshot?.pulseOf(projectId);
+ final pm = snapshot == null || pulse == null
+ ? 'the PM'
+ : swarmPulsePmName(snapshot, pulse);
+ final (title, none) = switch (list) {
+ SwarmPulseList.asks => (
+ 'Waiting for $pm',
+ 'Nothing waiting for $pm.',
+ ),
+ SwarmPulseList.working => ('Working', 'Nobody is working.'),
+ SwarmPulseList.nextUp => ('Next up', 'Nothing next up.'),
+ SwarmPulseList.lost => ('Lost', 'No lost tasks.'),
+ SwarmPulseList.held => ('Held', 'Nothing held.'),
+ };
+ final rows = snapshot == null || pulse == null
+ ? const <Widget>[]
+ : _rows(context, snapshot, pulse);
+ return ConstrainedBox(
+ key: const ValueKey('swarm-pulse-sheet'),
+ // Never over the status bar: a long list scrolls inside it.
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * .82,
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),
+ child: Row(
+ children: [
+ SwarmIconButton(
+ key: const ValueKey('swarm-pulse-close'),
+ icon: LucideIcons.x300,
+ label: 'Close',
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ const SizedBox(width: AppSpace.xs),
+ Expanded(
+ child: Text(
+ title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.heading(color: AppPalette.textPrimary),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Flexible(
+ child: ListView(
+ shrinkWrap: true,
+ padding: EdgeInsets.fromLTRB(
+ AppSpace.l,
+ AppSpace.s,
+ AppSpace.l,
+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,
+ ),
+ children: [
+ if (rows.isEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.xs,
+ ),
+ child: SwarmRow.line(none),
+ )
+ else
+ SwarmGroup(children: rows),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ List<Widget> _rows(
+ BuildContext context,
+ SuperTabSnapshot snapshot,
+ SuperTabPulse pulse,
+ ) {
+ final now = clock.now();
+ Widget task(String id, {String? Function()? reason}) {
+ final g = snapshot.conversation(id);
+ final why = reason?.call();
+ return SwarmRow(
+ key: ValueKey('swarm-pulse-task-$id'),
+ number: g?.number == null ? null : '#${g!.number}',
+ title: g?.title ?? 'A task',
+ detail: reason == null ? null : SwarmRow.line(why ?? 'no reason'),
+ onTap: () => onOpen(id),
+ );
+ }
+
+ return switch (list) {
+ SwarmPulseList.asks => [
+ for (final ask in pulse.asks.list) _askRow(context, snapshot, ask, now),
+ ],
+ SwarmPulseList.working => [
+ for (final id in pulse.working.agentIds) _agentRow(snapshot, id),
+ ],
+ SwarmPulseList.nextUp => [
+ for (final id in pulse.nextUp.conversationIds) task(id),
+ ],
+ SwarmPulseList.lost => [
+ for (final id in pulse.lost.conversationIds) task(id),
+ ],
+ SwarmPulseList.held => [
+ for (final hold in pulse.held.list)
+ task(hold.conversationId, reason: () => hold.reason),
+ ],
+ };
+ }
+
+ /// A person's ask: who, how long ago and where; a tap opens the message
+ /// in its conversation.
+ Widget _askRow(
+ BuildContext context,
+ SuperTabSnapshot snapshot,
+ SuperTabPulseAsk ask,
+ DateTime now,
+ ) {
+ final person = snapshot.people
+ .where((p) => p.id == ask.personId)
+ .firstOrNull;
+ final name = switch (ask.personId) {
+ final id? => swarmTaskPersonName(snapshot)(id),
+ null => null,
+ };
+ final chat = snapshot.conversation(ask.conversationId);
+ final where = switch (chat) {
+ null => null,
+ final g when g.number != null => '#${g.number} ${g.title}',
+ final g => g.title,
+ };
+ return SwarmRow(
+ key: ValueKey('swarm-pulse-ask-${ask.messageId}'),
+ leading: SwarmAvatar(
+ id: ask.personId ?? ask.messageId,
+ name: name ?? '?',
+ picture: person?.avatar,
+ ),
+ title: name ?? 'A person',
+ detail: SwarmRow.line(
+ ['${swarmPulseAge(now.difference(ask.at))} ago', ?where].join(' · '),
+ ),
+ onTap: () => unawaited(
+ Navigator.of(context).push(
+ swarmChatRoute(
+ swarmId: reader.tabId,
+ conversationId: ask.conversationId,
+ messageId: ask.messageId,
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// A working agent, with the task it holds, which a tap opens.
+ Widget _agentRow(SuperTabSnapshot snapshot, String id) {
+ final name = snapshot.agentName(id);
+ final held = [
+ for (final g in snapshot.conversations)
+ if (g.projectId == projectId &&
+ !g.closed &&
+ g.assignment?['agentId'] == id &&
+ !const {
+ 'done',
+ 'stopped',
+ 'cancelled',
+ }.contains(g.assignment?['status']))
+ g,
+ ];
+ final task =
+ held.where((g) => g.assignment?['status'] == 'working').firstOrNull ??
+ held.firstOrNull;
+ return SwarmRow(
+ key: ValueKey('swarm-pulse-agent-$id'),
+ leading: SwarmAvatar(
+ id: id,
+ name: name,
+ picture: snapshot.agent(id)?.avatar,
+ ),
+ title: name,
+ detail: task == null
+ ? null
+ : SwarmRow.line(
+ task.number == null
+ ? task.title
+ : '#${task.number} ${task.title}',
+ ),
+ onTap: task == null ? null : () => onOpen(task.id),
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_reader.dart b/mobile/lib/swarm/swarm_reader.dart
index 8804911ef..1b812f399 100644
--- a/mobile/lib/swarm/swarm_reader.dart
+++ b/mobile/lib/swarm/swarm_reader.dart
@@ -29,9 +29,12 @@ typedef _View = ({
/// [parts] as [accountId] reads them: whose Buddies are whose depends on who
/// reads. Each conversation carries when it last changed, which the state
-/// leaves out ([SuperTabConversation.changedAt]).
+/// leaves out ([SuperTabConversation.changedAt]), and each project's board
+/// pulse, from a server that sends it in `derived` ([SuperTabSnapshot.pulses];
+/// parts.dart stays the desktop's copy).
_View _viewOf(SuperTabParts parts, String accountId) {
final state = parts.state;
+ if (parts.derived['pulse'] case final Map pulse) state['pulse'] = pulse;
for (final conversation in state['conversations'] as List) {
if (conversation case {'id': final String id} && final Map row) {
row['changedAt'] = parts.groupChangedAt(id);
diff --git a/mobile/test/swarm/desktop_parity_test.dart b/mobile/test/swarm/desktop_parity_test.dart
index 573c93994..9fb862e44 100644
--- a/mobile/test/swarm/desktop_parity_test.dart
+++ b/mobile/test/swarm/desktop_parity_test.dart
@@ -23,6 +23,8 @@ const _copies = {
// Task steps design: a task's steps and its merged chat.
'lib/swarm/task_steps.dart': 'lib/super_tabs/task_steps.dart',
'lib/swarm/instructions_model.dart': 'lib/super_tabs/instructions_model.dart',
+ // Board pulse (task #3384): what waits for the PM and who works.
+ 'lib/swarm/pulse_model.dart': 'lib/super_tabs/pulse.dart',
};
/// The phone's model is ahead of main's desktop copy, so it is no exact copy
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-asks-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-320-asks-dark.png
new file mode 100644
index 000000000..3d2fad1b0
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-asks-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-asks-light.png b/mobile/test/swarm/screenshots/pulse/pulse-320-asks-light.png
new file mode 100644
index 000000000..803ad21fc
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-asks-light.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-held-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-320-held-dark.png
new file mode 100644
index 000000000..cb31ae2ea
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-held-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-held-light.png b/mobile/test/swarm/screenshots/pulse/pulse-320-held-light.png
new file mode 100644
index 000000000..07ca607e1
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-held-light.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-strip-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-dark.png
new file mode 100644
index 000000000..972defee1
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-strip-light.png b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-light.png
new file mode 100644
index 000000000..90bb9a750
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-light.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-strip-red-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-red-dark.png
new file mode 100644
index 000000000..432097048
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-red-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-320-strip-red-light.png b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-red-light.png
new file mode 100644
index 000000000..c39981a17
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-320-strip-red-light.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-asks-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-390-asks-dark.png
new file mode 100644
index 000000000..d6f71493a
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-asks-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-asks-light.png b/mobile/test/swarm/screenshots/pulse/pulse-390-asks-light.png
new file mode 100644
index 000000000..689002950
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-asks-light.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-held-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-390-held-dark.png
new file mode 100644
index 000000000..188d97386
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-held-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-held-light.png b/mobile/test/swarm/screenshots/pulse/pulse-390-held-light.png
new file mode 100644
index 000000000..54767db23
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-held-light.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-strip-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-dark.png
new file mode 100644
index 000000000..2d6c38e8e
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-strip-light.png b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-light.png
new file mode 100644
index 000000000..0ee4fa8b0
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-light.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-strip-red-dark.png b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-red-dark.png
new file mode 100644
index 000000000..1fb7c6bb9
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-red-dark.png differ
diff --git a/mobile/test/swarm/screenshots/pulse/pulse-390-strip-red-light.png b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-red-light.png
new file mode 100644
index 000000000..92b72c954
Binary files /dev/null and b/mobile/test/swarm/screenshots/pulse/pulse-390-strip-red-light.png differ
diff --git a/mobile/test/swarm/swarm_pulse_shots_test.dart b/mobile/test/swarm/swarm_pulse_shots_test.dart
new file mode 100644
index 000000000..95a6e3d15
--- /dev/null
+++ b/mobile/test/swarm/swarm_pulse_shots_test.dart
@@ -0,0 +1,285 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_tabs.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of the board pulse on the phone (task #3384): the strip
+/// on top of a project's Team sheet, calm and with every rule red, and the
+/// lists its asks and Held open. On 390- and 320-point phones in both phone
+/// themes, from made-up data only, to the folder `SWARM_PULSE_SHOTS` names
+/// (run this file alone, on a Mac).
+final shots = Platform.environment['SWARM_PULSE_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('the pulse strip and its lists, in both phone themes', (
+ tester,
+ ) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ // An iPhone's status bar and home indicator.
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ const huy = 'person-huy', mai = 'person-mai';
+ for (final (palette, size) in [
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper])
+ for (final size in const [Size(390, 844), Size(320, 568)])
+ (palette, size),
+ ]) {
+ for (final red in [false, true]) {
+ tester.view
+ ..physicalSize = size * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final now = clock.now();
+ int ago(Duration age) => now.subtract(age).millisecondsSinceEpoch;
+ const minute = Duration(minutes: 1);
+ final past = ago(minute);
+ Map<String, dynamic> task(
+ String id,
+ String title,
+ int number, {
+ String? status,
+ String worker = 'agent-atlas',
+ }) => {
+ ...groupData(
+ id,
+ title: title,
+ number: number,
+ agentIds: [if (status != null) worker],
+ status: status,
+ workerId: worker,
+ lastMessageSequence: 1,
+ ),
+ if (status != null)
+ 'assignment': {
+ 'id': 'attempt-$id',
+ 'agentId': worker,
+ 'status': status,
+ 'result': null,
+ 'progressAt': ago(minute * 4),
+ },
+ };
+ final derived = {
+ 'pulse': {
+ project: {
+ 'pmId': 'agent-lead',
+ 'asks': {
+ 'count': 2,
+ 'oldestAt': ago(minute * (red ? 24 : 14)),
+ 'personId': huy,
+ 'list': [
+ {
+ 'conversationId': leadChat,
+ 'messageId': 'm-1',
+ 'personId': huy,
+ 'at': ago(minute * (red ? 24 : 14)),
+ },
+ {
+ 'conversationId': 'g-search',
+ 'messageId': 'm-2',
+ 'personId': mai,
+ 'at': ago(minute * 3),
+ },
+ ],
+ },
+ 'working': {
+ 'count': red ? 0 : 6,
+ 'crew': 10,
+ 'agentIds': red ? <String>[] : ['agent-atlas', 'agent-nova'],
+ },
+ 'nextUp': {
+ 'count': 7,
+ 'conversationIds': ['g-docs', 'g-onboard'],
+ },
+ 'lost': {
+ 'count': red ? 1 : 0,
+ 'since': red ? ago(minute * 12) : null,
+ 'conversationIds': [if (red) 'g-sync'],
+ },
+ 'held': {
+ 'count': 3,
+ 'withoutReason': 1,
+ 'list': [
+ {
+ 'conversationId': 'g-billing',
+ 'reason': 'Waiting on the Stripe API key from finance',
+ },
+ {'conversationId': 'g-later', 'reason': 'Not before Monday'},
+ {'conversationId': 'g-export', 'reason': null},
+ ],
+ },
+ 'idleSince': red ? ago(minute * 11) : null,
+ 'redAt': {
+ 'asks': red ? past : ago(-minute),
+ 'idle': red ? past : null,
+ 'lost': red ? past : null,
+ 'held': red ? past : null,
+ },
+ 'limits': {
+ 'askMinutes': 15,
+ 'idleMinutes': 10,
+ 'lostMinutes': 10,
+ },
+ },
+ },
+ };
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ head: headData(name: 'OpenHarness'),
+ agents: [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ agent('agent-atlas', displayName: 'Atlas'),
+ agent('agent-nova', displayName: 'Nova'),
+ ],
+ groups: [
+ task('g-search', 'Search page', 6, status: 'working'),
+ task(
+ 'g-login',
+ 'Fix login',
+ 8,
+ status: 'working',
+ worker: 'agent-nova',
+ ),
+ task('g-docs', 'Docs for the CLI', 11),
+ task('g-onboard', 'Onboarding copy', 12),
+ task('g-sync', 'Sync settings', 13),
+ task('g-billing', 'Billing page', 9),
+ task('g-later', 'Weekly digest', 10),
+ task('g-export', 'Export to CSV', 14),
+ ],
+ derived: derived,
+ ),
+ 'members': [
+ part(me, 1, {...person(me), 'name': 'Ada'}),
+ part(huy, 1, {...person(huy, role: 'member'), 'name': 'Huy'}),
+ part(mai, 1, {...person(mai, role: 'member'), 'name': 'Mai'}),
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2', derived: derived);
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ final features = ExperimentalFeaturesStore(
+ storage: MemoryKeyValueStore(),
+ )..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => me,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmProjectPage(
+ swarmId: tab,
+ projectId: project,
+ tabs: SwarmProjectTab.homeC,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) => tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ final width = size.width.round();
+ await File('$shots/pulse-$width-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ Finder key(String value) => find.byKey(ValueKey(value));
+ await tester.tap(key('swarm-project-menu'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-project-menu-team'));
+ await tester.pumpAndSettle();
+ await capture(red ? 'strip-red' : 'strip');
+ if (!red) {
+ await tester.tap(key('swarm-pulse-asks'));
+ await tester.pumpAndSettle();
+ await capture('asks');
+ await tester.tap(key('swarm-pulse-close'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-pulse-held'));
+ await tester.pumpAndSettle();
+ await capture('held');
+ }
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ host.dispose();
+ account.dispose();
+ }
+ }
+ debugDisableShadows = true;
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_pulse_test.dart b/mobile/test/swarm/swarm_pulse_test.dart
new file mode 100644
index 000000000..9f4245df1
--- /dev/null
+++ b/mobile/test/swarm/swarm_pulse_test.dart
@@ -0,0 +1,584 @@
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/swarm/pulse_model.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_tabs.dart';
+import 'package:harness_mobile/swarm/swarm_pulse.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// The board pulse on the phone (task #3384, plan Task 4): a strip on top of
+/// a project's task list — the Team sheet's open tasks, and the Tasks tab —
+/// drawn from the read's `derived.pulse[projectId]`: what waits for the PM,
+/// who works, what is next up, lost and held. Each count opens its list; a
+/// segment is red by the server's `redAt` alone. Over a scripted backend: one
+/// Swarm, project Mobile, River its PM, Huy a person who asked.
+void main() {
+ const huy = 'person-huy';
+ const minute = Duration(minutes: 1);
+
+ /// The pulse the server sends for project Mobile, ages from [now].
+ Map<String, dynamic> pulseData(
+ DateTime now, {
+ int asks = 2,
+ Map<String, Object?> redAt = const {},
+ }) {
+ int ago(Duration age) => now.subtract(age).millisecondsSinceEpoch;
+ return {
+ 'pmId': 'agent-lead',
+ 'asks': {
+ 'count': asks,
+ 'oldestAt': asks == 0 ? null : ago(minute * 14),
+ 'personId': asks == 0 ? null : huy,
+ 'list': [
+ if (asks > 0) ...[
+ {
+ 'conversationId': leadChat,
+ 'messageId': 'm-huy',
+ 'personId': huy,
+ 'at': ago(minute * 14),
+ },
+ {
+ 'conversationId': 'g-work',
+ 'messageId': 'm-me',
+ 'personId': me,
+ 'at': ago(minute * 3),
+ },
+ ],
+ ],
+ },
+ 'working': {
+ 'count': 6,
+ 'crew': 10,
+ 'agentIds': ['agent-atlas'],
+ },
+ 'nextUp': {
+ 'count': 7,
+ 'conversationIds': ['g-next'],
+ },
+ 'lost': {'count': 0, 'since': null, 'conversationIds': <String>[]},
+ 'held': {
+ 'count': 3,
+ 'withoutReason': 1,
+ 'list': [
+ {'conversationId': 'g-held', 'reason': 'Waiting on the API key'},
+ {'conversationId': 'g-later', 'reason': null},
+ ],
+ },
+ 'idleSince': null,
+ 'redAt': {
+ 'asks': null,
+ 'idle': null,
+ 'lost': null,
+ 'held': null,
+ ...redAt,
+ },
+ 'limits': {'askMinutes': 15, 'idleMinutes': 10, 'lostMinutes': 10},
+ };
+ }
+
+ /// [pulse] null: a server from before the pulse.
+ FakeSwarm backend(Map<String, dynamic>? pulse) {
+ final fake = FakeSwarm();
+ final derived = <String, dynamic>{
+ if (pulse != null) 'pulse': {project: pulse},
+ };
+ Map<String, dynamic> task(
+ String id,
+ String title,
+ int number, {
+ String? status,
+ String worker = 'agent-atlas',
+ }) => groupData(
+ id,
+ title: title,
+ number: number,
+ agentIds: [if (status != null) worker],
+ status: status,
+ workerId: worker,
+ lastMessageSequence: 1,
+ );
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ agents: [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ agent('agent-builder', displayName: 'Nova'),
+ agent('agent-atlas', displayName: 'Atlas'),
+ ],
+ groups: [
+ task('g-work', 'Search page', 6, status: 'working'),
+ task('g-next', 'Docs', 7),
+ task('g-held', 'Billing', 9, status: 'needs_human'),
+ task('g-later', 'Later', 10),
+ ],
+ derived: derived,
+ ),
+ 'members': [
+ part(me, 1, person(me)),
+ part(huy, 1, {...person(huy, role: 'member'), 'name': 'Huy'}),
+ ],
+ };
+ // Each read, a change read too, sends the whole of `derived`.
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2', derived: derived);
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ /// Project Mobile's page, on [tabs].
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ SwarmProjectTab tab_ = SwarmProjectTab.chat,
+ List<SwarmProjectTab> tabs = SwarmProjectTab.homeC,
+ }) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: SwarmProjectPage(
+ swarmId: tab,
+ projectId: project,
+ tab: tab_,
+ tabs: tabs,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return host;
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ /// The Team sheet, its open tasks on top (Swarm Home C).
+ Future<void> openTeam(WidgetTester tester) async {
+ await tester.tap(key('swarm-project-menu'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-project-menu-team'));
+ await tester.pumpAndSettle();
+ }
+
+ /// The words of the strip's segment [name].
+ String words(WidgetTester tester, String name) => tester
+ .widget<Text>(key('swarm-pulse-$name-text'))
+ .textSpan!
+ .toPlainText();
+
+ bool red(WidgetTester tester, String name) {
+ final shown = key('swarm-pulse-$name-red').evaluate().isNotEmpty;
+ final style = tester.widget<Text>(key('swarm-pulse-$name-text')).style;
+ final inRed = style?.color == AppColors.danger;
+ expect(inRed, shown, reason: '$name: its colour and its mark agree');
+ if (shown) {
+ expect(style?.fontWeight, FontWeight.w600, reason: '$name: bold');
+ }
+ return shown;
+ }
+
+ const segments = ['asks', 'working', 'next-up', 'lost', 'held'];
+
+ group('derived.pulse', () {
+ /// A reader of the Swarm whose reads send [derived], then [next].
+ Future<SwarmReader> read(
+ Map<String, dynamic> derived, {
+ Map<String, dynamic>? next,
+ }) async {
+ final swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>
+ firstLoad(derived: derived);
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2', derived: next ?? derived);
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: swarm.request,
+ );
+ addTearDown(reader.dispose);
+ await reader.refresh();
+ return reader;
+ }
+
+ test('is read into each project of the snapshot', () async {
+ // Local, as Desktop's model (pulse_model.dart) reads the server's
+ // times.
+ final now = DateTime(2026, 11, 5, 12);
+ final reader = await read(
+ {
+ 'pulse': {
+ project: pulseData(
+ now,
+ redAt: {'asks': now.millisecondsSinceEpoch + 60000},
+ ),
+ },
+ },
+ next: {
+ 'pulse': {project: pulseData(now, asks: 0)},
+ },
+ );
+ final pulse = reader.snapshot!.pulseOf(project)!;
+ expect(pulse.pmId, 'agent-lead');
+ expect(pulse.asks.count, 2);
+ expect(pulse.asks.oldestAt, now.subtract(minute * 14));
+ expect(pulse.asks.personId, huy);
+ expect(pulse.asks.list.map((a) => a.messageId), ['m-huy', 'm-me']);
+ expect(pulse.asks.list.first.conversationId, leadChat);
+ expect(pulse.asks.list.first.at, now.subtract(minute * 14));
+ expect(pulse.working.count, 6);
+ expect(pulse.working.crew, 10);
+ expect(pulse.working.agentIds, ['agent-atlas']);
+ expect(pulse.nextUp.count, 7);
+ expect(pulse.nextUp.conversationIds, ['g-next']);
+ expect(pulse.lost.count, 0);
+ expect(pulse.lost.conversationIds, isEmpty);
+ expect(pulse.held.count, 3);
+ expect(pulse.held.withoutReason, 1);
+ expect(pulse.held.list.map((h) => (h.conversationId, h.reason)), [
+ ('g-held', 'Waiting on the API key'),
+ ('g-later', null),
+ ]);
+ expect(pulse.redAt[SuperTabPulseRule.asks], now.add(minute));
+ expect(pulse.redAt[SuperTabPulseRule.idle], isNull);
+ expect(pulse.isRed(SuperTabPulseRule.asks, now), isFalse);
+ expect(pulse.isRed(SuperTabPulseRule.asks, now.add(minute)), isTrue);
+ expect(pulse.nextRedAfter(now), now.add(minute));
+ expect(pulse.nextRedAfter(now.add(minute)), isNull);
+
+ // A change read moves it.
+ await reader.refresh();
+ expect(reader.snapshot!.pulseOf(project)!.asks.count, 0);
+ });
+
+ test('none from an older server, and none for a pulse it cannot '
+ 'read', () async {
+ expect((await read(const {})).snapshot!.pulseOf(project), isNull);
+ for (final odd in <Object?>['soon', 3, null, <String, Object?>{}]) {
+ final reader = await read({
+ 'pulse': {project: odd},
+ });
+ expect(reader.snapshot!.pulseOf(project), isNull, reason: '$odd');
+ }
+ });
+ });
+
+ group('the strip on the Team sheet', () {
+ testWidgets('says what waits for the PM and who works, as the server '
+ 'counts it', (tester) async {
+ await pump(tester, backend(pulseData(clock.now())));
+ await openTeam(tester);
+
+ expect(key('swarm-pulse'), findsOneWidget);
+ expect(
+ words(tester, 'asks'),
+ 'Waiting for River: 2 asks · oldest 14m (Huy)',
+ );
+ expect(words(tester, 'working'), 'Working 6 of 10');
+ expect(words(tester, 'next-up'), 'Next up 7');
+ expect(words(tester, 'lost'), 'Lost 0');
+ expect(words(tester, 'held'), 'Held 3 (1 no reason)');
+ // On top of the open tasks.
+ expect(
+ tester.getBottomLeft(key('swarm-pulse')).dy,
+ lessThanOrEqualTo(
+ tester.getTopLeft(key('swarm-team-working-caption')).dy,
+ ),
+ );
+ for (final name in segments) {
+ expect(red(tester, name), isFalse, reason: name);
+ }
+ // A segment is a thumb's touch tall.
+ for (final name in segments) {
+ expect(
+ tester.getSize(key('swarm-pulse-$name')).height,
+ greaterThanOrEqualTo(44),
+ reason: name,
+ );
+ }
+ });
+
+ testWidgets('with nothing asked: "Nothing waiting for River"', (
+ tester,
+ ) async {
+ await pump(tester, backend(pulseData(clock.now(), asks: 0)));
+ await openTeam(tester);
+ expect(words(tester, 'asks'), 'Nothing waiting for River');
+ });
+
+ testWidgets('its ages keep moving while it is open', (tester) async {
+ await pump(tester, backend(pulseData(clock.now())));
+ await openTeam(tester);
+ await tester.pump(minute);
+ expect(
+ words(tester, 'asks'),
+ 'Waiting for River: 2 asks · oldest 15m (Huy)',
+ );
+ });
+
+ testWidgets('no strip from a server without the pulse', (tester) async {
+ await pump(tester, backend(null));
+ await openTeam(tester);
+ expect(key('swarm-pulse'), findsNothing);
+ expect(key('swarm-team-working-caption'), findsOneWidget);
+ });
+
+ testWidgets('each segment is red once its redAt has come, with a mark '
+ 'and bold, never by colour alone', (tester) async {
+ final past = clock.now().subtract(minute).millisecondsSinceEpoch;
+ await pump(
+ tester,
+ backend(
+ pulseData(
+ clock.now(),
+ redAt: {'asks': past, 'idle': past, 'lost': past, 'held': past},
+ ),
+ ),
+ );
+ await openTeam(tester);
+ for (final name in ['asks', 'working', 'lost', 'held']) {
+ expect(red(tester, name), isTrue, reason: name);
+ }
+ // No rule turns Next up red.
+ expect(red(tester, 'next-up'), isFalse);
+ });
+
+ testWidgets('a redAt still to come is not red, and turns red when it '
+ 'passes', (tester) async {
+ final soon = clock.now().add(const Duration(seconds: 30));
+ await pump(
+ tester,
+ backend(
+ pulseData(
+ clock.now(),
+ redAt: {
+ 'asks': soon.millisecondsSinceEpoch,
+ 'held': clock.now().add(minute * 30).millisecondsSinceEpoch,
+ },
+ ),
+ ),
+ );
+ await openTeam(tester);
+ expect(red(tester, 'asks'), isFalse);
+ expect(red(tester, 'held'), isFalse);
+
+ // Before the minute's tick: the redAt itself wakes the strip.
+ await tester.pump(const Duration(seconds: 31));
+ expect(red(tester, 'asks'), isTrue);
+ expect(red(tester, 'held'), isFalse);
+ });
+
+ testWidgets('the asks open their list: who asked and how long ago; one '
+ 'opens its message in its conversation', (tester) async {
+ await pump(tester, backend(pulseData(clock.now())));
+ await openTeam(tester);
+
+ await tester.tap(key('swarm-pulse-asks'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-pulse-sheet'), findsOneWidget);
+ expect(
+ find.descendant(
+ of: key('swarm-pulse-sheet'),
+ matching: find.text('Waiting for River'),
+ ),
+ findsOneWidget,
+ );
+ final huyRow = key('swarm-pulse-ask-m-huy');
+ expect(
+ find.descendant(of: huyRow, matching: find.text('Huy')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: huyRow, matching: find.textContaining('14m')),
+ findsOneWidget,
+ );
+ expect(key('swarm-pulse-ask-m-me'), findsOneWidget);
+
+ await tester.tap(huyRow);
+ await tester.pumpAndSettle();
+ final opened = tester.widget<SwarmOpenedChat>(
+ find.byType(SwarmOpenedChat),
+ );
+ expect(opened.conversationId, leadChat);
+ expect(opened.messageId, 'm-huy');
+ });
+
+ testWidgets('Working opens the working agents', (tester) async {
+ await pump(tester, backend(pulseData(clock.now())));
+ await openTeam(tester);
+
+ await tester.tap(key('swarm-pulse-working'));
+ await tester.pumpAndSettle();
+ final row = key('swarm-pulse-agent-agent-atlas');
+ expect(
+ find.descendant(of: row, matching: find.text('Atlas')),
+ findsOneWidget,
+ );
+ // With the task it holds, which a tap opens.
+ expect(
+ find.descendant(of: row, matching: find.textContaining('Search page')),
+ findsOneWidget,
+ );
+ await tester.tap(row);
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<SwarmOpenedChat>(find.byType(SwarmOpenedChat))
+ .conversationId,
+ 'g-work',
+ );
+ });
+
+ testWidgets('Next up, Lost and Held open their tasks; Held says each '
+ "one's reason, or no reason", (tester) async {
+ await pump(tester, backend(pulseData(clock.now())));
+ await openTeam(tester);
+
+ await tester.tap(key('swarm-pulse-next-up'));
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: key('swarm-pulse-task-g-next'),
+ matching: find.textContaining('Docs', findRichText: true),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(key('swarm-pulse-close'));
+ await tester.pumpAndSettle();
+
+ await tester.tap(key('swarm-pulse-lost'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-pulse-sheet'), findsOneWidget);
+ expect(find.text('No lost tasks.'), findsOneWidget);
+ await tester.tap(key('swarm-pulse-close'));
+ await tester.pumpAndSettle();
+
+ await tester.tap(key('swarm-pulse-held'));
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: key('swarm-pulse-task-g-held'),
+ matching: find.text('Waiting on the API key'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: key('swarm-pulse-task-g-later'),
+ matching: find.text('no reason'),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(key('swarm-pulse-task-g-held'));
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<SwarmOpenedChat>(find.byType(SwarmOpenedChat))
+ .conversationId,
+ 'g-held',
+ );
+ });
+ });
+
+ testWidgets('the Tasks tab has the strip on top too', (tester) async {
+ await pump(
+ tester,
+ backend(pulseData(clock.now())),
+ tab_: SwarmProjectTab.tasks,
+ tabs: const [SwarmProjectTab.chat, SwarmProjectTab.tasks],
+ );
+ expect(
+ find.descendant(
+ of: key('swarm-project-tasks'),
+ matching: key('swarm-pulse'),
+ ),
+ findsOneWidget,
+ );
+ expect(words(tester, 'working'), 'Working 6 of 10');
+
+ await tester.tap(key('swarm-pulse-next-up'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-pulse-task-g-next'));
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<SwarmOpenedChat>(find.byType(SwarmOpenedChat))
+ .conversationId,
+ 'g-next',
+ );
+ });
+
+ // Hugo's review of #3209 (ENGINEERING 4: a timer that wakes while nothing
+ // changed is a defect): the strip wakes only when something it shows will
+ // read differently, the oldest ask's age or a rule turning red, never on a
+ // fixed tick.
+ group('when the strip wakes', () {
+ final now = DateTime(2026, 11, 5, 12);
+ SuperTabPulse pulse(Map<String, dynamic> data) => SuperTabPulse.read(data)!;
+
+ test('never, with no ask and no rule still to turn red', () {
+ expect(swarmPulseNextWake(pulse(pulseData(now, asks: 0)), now), isNull);
+ });
+
+ test('when the oldest ask\'s age next reads differently', () {
+ // 14 minutes old: 15m in a minute.
+ expect(swarmPulseNextWake(pulse(pulseData(now)), now), now.add(minute));
+ final older = pulseData(now)
+ ..['asks']['oldestAt'] = now
+ .subtract(const Duration(hours: 2, minutes: 10))
+ .millisecondsSinceEpoch;
+ // 2h 10m old: 3h in 50 minutes.
+ expect(swarmPulseNextWake(pulse(older), now), now.add(minute * 50));
+ });
+
+ test('when a rule turns red first', () {
+ final soon = now.add(const Duration(seconds: 30));
+ expect(
+ swarmPulseNextWake(
+ pulse(
+ pulseData(
+ now,
+ asks: 0,
+ redAt: {'idle': soon.millisecondsSinceEpoch},
+ ),
+ ),
+ now,
+ ),
+ soon,
+ );
+ });
+ });
+}