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.

Combined merge 10-30 A: eight reviewed PRs (#2263 #2273 #2275 #2277 #2281 #2285 #2286 #2289) (#2291)

0xken15549f7b0f3c58
diff --git a/backend/integration/superTabIndexes.test.ts b/backend/integration/superTabIndexes.test.ts
index d41752020..957fa2280 100644
--- a/backend/integration/superTabIndexes.test.ts
+++ b/backend/integration/superTabIndexes.test.ts
@@ -12,7 +12,8 @@ import { readEvidence } from '../src/superTabs/evidence/store.js'
import { recentDecisions } from '../src/superTabs/routeDecisions.js'
import { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'
import { revokeNativeContexts } from '../src/superTabs/native.js'
-import { outsider, peer, swarm } from '../src/superTabs/read/fixture.test-support.js'
+import { outsider, owner, peer, richSwarm, swarm } from '../src/superTabs/read/fixture.test-support.js'
+import { threadSummaries } from '../src/superTabs/threads.js'
import type { SuperTabState } from '../src/superTabs/model.js'
// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
@@ -100,7 +101,7 @@ describe('message page reads', () => {
expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, messageId: 1 }'], docsExamined: 1001, returned: 1001 })
})
- it('reads a page\'s threads through the tabId+conversationId+thread index, examining only their messages', async () => {
+ it('reads a page\'s threads through the tabId+conversationId+thread index, examining only their messages and returning a few', async () => {
// 300 top-level messages in one conversation, every tenth with three replies, beside another conversation's.
const rows = []
for (const conversationId of ['t0', 't1']) {
@@ -115,11 +116,56 @@ describe('message page reads', () => {
createdAt: new Date(T0 + row.sequence * 1000) })) })
const roots = Array.from({ length: 100 }, (_, i) => `t0-m${pad(100 + i)}`)
const [threads, profile] = await profiled('SuperTabMessage', () => pageThreads(db, 'T', 't0', roots))
- expect(threads).toHaveLength(130)
- expect(threads.filter(row => row.id !== row.thread).map(row => row.id).slice(0, 3)).toEqual(['t0-m100-r1', 't0-m100-r2', 't0-m100-r3'])
+ // Each root, and of each thread's three replies by one author the first and the last, which stands for all three.
+ expect(threads).toHaveLength(120)
+ expect(threads.filter(row => row.id !== row.thread).slice(0, 2).map(row => [row.id, row.count])).toEqual([['t0-m100-r1', 0], ['t0-m100-r3', 3]])
expect(threads[0]).toEqual({ thread: 't0-m100', id: 't0-m100', author: expect.objectContaining({ id: 'owner' }), mentions: [],
- sequence: 400, createdAt: new Date(T0 + 400_000), agentOnly: false, routing: false })
- expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, conversationId: 1, thread: 1, sequence: 1 }'], docsExamined: 130, returned: 130 })
+ sequence: 400, createdAt: new Date(T0 + 400_000), agentOnly: false, routing: false, count: 1 })
+ expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, conversationId: 1, thread: 1, sequence: 1 }'], docsExamined: 130, returned: 1 })
+ })
+
+ it('sums up a 500-reply thread from a few rows: what each reader may see, counted in the database', async () => {
+ // One long thread: 500 replies. Every tenth an agent-only note to another agent (no reader counts it), five route rows
+ // (a Buddy never reads them), a person who is not in the Swarm writing every third, the owner renamed after reply 100,
+ // and the last two replies written by one command (one sequence). Beside it, a thread whose only reply is hidden, and a
+ // short one. Each reader's summaries are the ones every reply read gave before (written out here by hand).
+ const s = richSwarm()
+ const group = s.state.conversations.find(c => c.id === s.web)!
+ const person = (id: string, displayName?: string) => ({ kind: 'person' as const, id, name: id, ...displayName ? { displayName } : {}, membershipGeneration: 'gen' })
+ const agent = (id: string) => ({ kind: 'agent' as const, id, name: id, membershipGeneration: 'gen' })
+ const rows: Array<{ id: string; thread: string; sequence: number; author: unknown; mentions?: string[]; source?: object; recipientIds?: string[] }> = [
+ { id: 'qa-root', thread: 'qa-root', sequence: 10_000, author: person(owner.userId, 'Owner now') },
+ { id: 'qb-root', thread: 'qb-root', sequence: 5_000, author: agent('lead') },
+ { id: 'qb-r1', thread: 'qb-root', sequence: 5_001, author: agent('ghost'), source: { kind: 'agent-only' }, recipientIds: ['a1'] },
+ { id: 'qc-root', thread: 'qc-root', sequence: 20_000, author: agent('lead') },
+ { id: 'qc-r1', thread: 'qc-root', sequence: 20_001, author: person(peer.userId) },
+ ]
+ for (let i = 0; i < 500; i++) {
+ const hidden = i % 10 === 9, route = i % 100 === 50
+ const author = hidden ? agent('ghost') : route ? agent('lead') : [person(owner.userId, i < 100 ? 'Owner before' : 'Owner now'), person('stranger'), agent('a1')][i % 3]
+ rows.push({ id: `qa-r${pad(i)}`, thread: 'qa-root', sequence: i === 498 ? 10_498 : 10_001 + i, author,
+ mentions: { 8: ['stranger'], 19: [peer.userId], 50: [outsider.userId], 307: [peer.userId, outsider.userId] }[i] ?? [],
+ ...hidden ? { source: { kind: 'agent-only' }, recipientIds: ['a1'] } : route ? { source: { kind: 'route' } } : {} })
+ }
+ await db.superTabMessage.createMany({ data: rows.map(row => ({ recipientIds: [], mentions: [], ...row, tabId: 'T', conversationId: 'qa', text: 'x',
+ author: row.author as object, createdAt: new Date(T0 + row.sequence * 1000) })) })
+ // Replies in the same thread id elsewhere, another conversation's and another Swarm's: never counted, named or read.
+ await db.superTabMessage.createMany({ data: [['T', 'qz'], ['U', 'qa']].map(([tabId, conversationId]) => ({ id: `${tabId}-${conversationId}-r`, tabId: tabId!,
+ conversationId: conversationId!, thread: 'qa-root', sequence: 30_000, text: 'x', author: person('elsewhere'), recipientIds: [], mentions: [outsider.userId],
+ createdAt: new Date(T0 + 30_000_000) })) })
+ const [threads, profile] = await profiled('SuperTabMessage', () => pageThreads(db, 'T', 'qa', ['qa-root', 'qb-root', 'qc-root']))
+ const last = { lastSequence: 10_498, lastAt: new Date(T0 + 10_498_000) }
+ expect(threadSummaries(s.state, group, threads)).toEqual([
+ { id: 'qa-root', replies: 450, ...last, authors: [person(owner.userId, 'Owner before'), agent('a1'), agent('lead')],
+ people: [owner.userId, outsider.userId, peer.userId] },
+ { id: 'qc-root', replies: 1, lastSequence: 20_001, lastAt: new Date(T0 + 20_001_000), authors: [person(peer.userId)], people: [peer.userId] },
+ ])
+ // A Buddy's page leaves the route rows out first (store.ts messages).
+ expect(threadSummaries(s.state, group, threads.filter(row => !row.routing))[0]).toEqual({ id: 'qa-root', replies: 445, ...last,
+ authors: [person(owner.userId, 'Owner before'), agent('a1')], people: [owner.userId, peer.userId, outsider.userId] })
+ // A few rows per author and kind of row, however long the thread: the database counts, not the server.
+ expect(threads.length).toBeLessThan(30)
+ expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, conversationId: 1, thread: 1, sequence: 1 }'], docsExamined: 505, returned: 1 })
})
it('reads a page of reactions through the tabId+messageId index, examining only the reactions it returns', async () => {
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index a4fd8c717..3cee6691d 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -46,7 +46,7 @@ afterAll(async () => {
})
/** A Swarm whose Lead runs on one of host's machines and whose worker runs on another, assigned "Ship the parser". */
-async function swarm({ legacy = false, client = db, hooks, independent = false }: { legacy?: boolean; client?: PrismaClient; hooks?: SuperTabStoreHooks; independent?: boolean } = {}) {
+async function swarm({ legacy = false, client = db, hooks, independent = false, engines = ['codex'] }: { legacy?: boolean; client?: PrismaClient; hooks?: SuperTabStoreHooks; independent?: boolean; engines?: string[] } = {}) {
let now = 10_000_000
const timed = new SuperTabStore(client, () => now, null, hooks)
const tab = (await timed.create(owner, randomUUID(), 'Liveness', legacy ? undefined : 'public')).id
@@ -55,7 +55,7 @@ async function swarm({ legacy = false, client = db, hooks, independent = false }
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)
for (const [machineId, name] of [['lead-host', 'Lead Mac'], ['test-host', 'Worker Mac']]) {
- await execute({ type: 'machine.contribute', machineId: machineId!, name: name!, cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)
+ await execute({ type: 'machine.contribute', machineId: machineId!, name: name!, cwd: '/repo', engines, maxAgents: 4 }, host)
}
const generations = new Map<string, string>()
for (const machineId of ['lead-host', 'test-host']) generations.set(machineId, (await poolRows(timed, host, machineId)).find(p => p.tabId === tab)!.machine.generation)
@@ -665,6 +665,33 @@ describe('work waiting for its review', () => {
})
})
+// Review of #2275: the review-capacity notice took the command's own message id, which the Ready for review row already had,
+// so the real write hit a duplicate key and rolled the whole status back: no Builder could hand over during a quota shortage.
+describe('a Ready for review while no Reviewer of another engine can start', () => {
+ it('saves the hand-over and tells the project chat once, through the store\'s write', async () => {
+ const f = await swarm({ engines: ['codex', 'claude'] })
+ const outForDays = [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: new Date(f.clock.now + 3 * 86_400_000).toISOString() }] }]
+ await f.observe('lead-host', [f.harness.lead], { quotas: outForDays })
+ await f.observe('test-host', [f.harness.worker], { quotas: outForDays })
+ const status = (status: 'review' | 'working', result: string) =>
+ f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status, result }, host, f.worker)
+ const handed = await status('review', 'Ready for review: PR #7 at 4f9c2e1')
+ expect((await f.assignment()).status).toBe('review')
+ const rows = await db.superTabMessage.findMany({ where: { tabId: f.tab }, orderBy: { sequence: 'asc' } })
+ const notices = rows.filter(m => (m.source as { kind?: string } | null)?.kind === 'review-capacity')
+ expect(notices).toHaveLength(1)
+ expect(notices[0]!.text).toMatch(/^Reviews of Codex builds fall back to Codex at its top tier: Claude Code is unavailable/)
+ // The command's own row stays the hand-over.
+ expect(rows.find(m => m.id === handed.result.messageId)!.text).toContain('Ready for review: PR #7 at 4f9c2e1')
+ const project = (await f.timed.read(owner, f.tab)).state.projects![0]!
+ expect(project.reviewCapacity).toEqual({ claude: 'out' })
+ // Handed over again, the cause is the same: said once.
+ await status('working', 'Fixing')
+ await status('review', 'Ready for review: PR #7 at 5a0d3f2')
+ expect((await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => (m.source as { kind?: string } | null)?.kind === 'review-capacity')).toHaveLength(1)
+ })
+})
+
describe('a machine\'s report', () => {
/** `n` conversations whose work finished but that are not yet quiet, each with a long brief: copies of a real one. */
async function finishedGroups(f: Awaited<ReturnType<typeof swarm>>, n: number) {
diff --git a/backend/src/superTabs/agentNames.test.ts b/backend/src/superTabs/agentNames.test.ts
index 14df168a4..4ab666f62 100644
--- a/backend/src/superTabs/agentNames.test.ts
+++ b/backend/src/superTabs/agentNames.test.ts
@@ -46,6 +46,31 @@ describe('individual agent names', () => {
expect(agents.map(a => a.name)).toContain('Lead')
})
+ it('gives Reviewers member names like Builders, also one that kept "Reviewer" as its name (Dee, 2026-10-30)', () => {
+ // Three Reviewers once read "Reviewer" three times: the role was not a role's name here, so it stuck.
+ const agents: NamedAgent[] = [
+ { id: 'r-1', name: 'Reviewer' },
+ { id: 'r-2', name: 'Reviewer', displayName: 'Reviewer' },
+ { id: 'r-3', name: 'reviewer 2' },
+ { id: 'kept', name: 'Reviewer', displayName: 'Quinn' },
+ ]
+ assignAgentDisplayNames(agents)
+ const names = agents.map(a => a.displayName!)
+ for (const name of names.slice(0, 3)) expect(name).not.toMatch(/reviewer/i)
+ expect(new Set(names).size).toBe(names.length)
+ expect(agents[3]!.displayName).toBe('Quinn')
+ expect(agentDisplayName([{ id: 'r', name: 'Reviewer', displayName: 'Reviewer' }], 'r')).not.toBe('Reviewer')
+ })
+
+ it('keeps every other stored name, even one that reads like a role or an automatic session (review of #2281)', () => {
+ // A Buddy may be named "claude-2026-10-30" (buddies.ts accepts it); only a stored "Reviewer" is replaced.
+ const kept = ['Dev', 'PM', 'Lead 2', 'claude-2026-10-30', 'codex-2026-10-30T09']
+ const agents: NamedAgent[] = kept.map((displayName, i) => ({ id: `k-${i}`, name: 'Builder', displayName }))
+ assignAgentDisplayNames(agents)
+ expect(agents.map(a => a.displayName)).toEqual(kept)
+ for (const [i, name] of kept.entries()) expect(agentDisplayName(agents, `k-${i}`)).toBe(name)
+ })
+
it('resolves legacy identities before filtering private projects without mutating reads', () => {
const state = legacyState(), original = structuredClone(state)
const all = visibleState(state, owner), publicOnly = visibleState(state, peer)
diff --git a/backend/src/superTabs/agentNames.ts b/backend/src/superTabs/agentNames.ts
index 8605efcfd..1e541e07c 100644
--- a/backend/src/superTabs/agentNames.ts
+++ b/backend/src/superTabs/agentNames.ts
@@ -13,11 +13,19 @@ const defaults = /^(?:lead|builder|agent|new agent|product manager|engineer|pm|d
/** A role's name, never a member's: an agent named so is given a member name instead (assignAgentDisplayNames). */
export const isRoleName = (name: string): boolean => defaults.test(name.trim())
const automatic = /^(?:claude|codex|pi|agent)-\d{4}-\d{2}-\d{2}(?:[-T].*)?$/i
+/** The Reviewer role's name is no member's either (Dee, 2026-10-30: three "Reviewer" rows). Kept out of isRoleName, whose
+ * Buddy check reserves it on its own (buddies.ts BUDDY_RESERVED). */
+const reviewer = /^reviewer(?:[\s#-]+\d+)?$/i
+/** Whether [name] names a role or an automatic session rather than a member. */
+const unnamed = (name: string): boolean => defaults.test(name) || reviewer.test(name) || automatic.test(name)
function chosen(agent: NamedAgent): string | undefined {
- if (agent.displayName?.trim()) return agent.displayName
+ // Every Reviewer kept "Reviewer" as its member name until 2026-10-30: that one stored name is given a real one.
+ // Any other stored name stays, even one that reads like a role (a Buddy may be named so).
+ const shown = agent.displayName?.trim()
+ if (shown && !reviewer.test(shown)) return agent.displayName
const name = agent.name.trim()
- return name && !defaults.test(name) && !automatic.test(name) ? name : undefined
+ return name && !unnamed(name) ? name : undefined
}
export function assignAgentDisplayNames(agents: NamedAgent[]): void {
@@ -46,7 +54,7 @@ export function assignAgentDisplayNames(agents: NamedAgent[]): void {
export function agentDisplayName(agents: NamedAgent[], id: string): string | undefined {
const member = agents.find(agent => agent.id === id)
if (!member) return undefined
- if (member.displayName) return member.displayName
+ if (member.displayName && !reviewer.test(member.displayName.trim())) return member.displayName
const named = agents.map(agent => ({ ...agent }))
assignAgentDisplayNames(named)
return named.find(agent => agent.id === id)!.displayName
diff --git a/backend/src/superTabs/autoReview.ts b/backend/src/superTabs/autoReview.ts
index d7df39d14..a15c0a65a 100644
--- a/backend/src/superTabs/autoReview.ts
+++ b/backend/src/superTabs/autoReview.ts
@@ -92,7 +92,7 @@ export interface OpenedReview { review: Conversation; reviewer: Agent | null; me
* notices are (liveness.ts), never as the Engineer (#610 review); [engineer] writes them only in a group with no Lead.
*/
export function openReview(state: SuperTabState, group: Conversation, handoff: string, pullRequest: string,
- context: { operationId: string; now: number; engineer: Author; mayWork: (agent: Agent) => boolean }): OpenedReview | null {
+ context: { operationId: string; now: number; engineer: Author; mayWork: (agent: Agent) => boolean; sameEngine?: (agent: Agent) => string | null }): OpenedReview | null {
const project = groupProject(state, group)
// On Custom skills without a reviewer role there are no review groups (commands.ts requireCustomRole).
if (state.paused || (skillSetOf(project) === 'custom' && !project.roles?.some(r => r.kind === 'reviewer'))) return null
@@ -125,7 +125,9 @@ export function openReview(state: SuperTabState, group: Conversation, handoff: s
execution: { machineId: reviewer.machineId, harnessId: reviewer.harnessId, machineOwnerId: reviewer.machineOwnerId }, result: null }
renewLease(review.assignment, context.now)
recordRun(state, review, review.assignment, reviewer, context.now)
- messages.push(row('assign', `${brief}\n\nAcceptance checks:\n- ${VERDICT_CHECK}`, [reviewer.id]))
+ // A review on its Builder's own engine says so first, as work.assign does (rules.ts sameEngineReview).
+ const sameEngine = context.sameEngine?.(reviewer)
+ messages.push(row('assign', `${sameEngine ? `${sameEngine}\n\n` : ''}${brief}\n\nAcceptance checks:\n- ${VERDICT_CHECK}`, [reviewer.id]))
}
const name = reviewer && (reviewer.displayName ?? reviewer.name)
if (leadId) messages.push(row('lead', reviewer
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 185694a43..04cfe5d4d 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1356,27 +1356,50 @@ describe('Reviewer role', () => {
})
it('lets a Claude-only Swarm review a Claude Builder\'s work on Opus, never below the top tier, and records why on the decision', () => {
- const { f, leadActor, group, builder } = reviewed()
+ const { f, leadActor, group, builder, reviewer } = reviewed()
// Every agent runs Claude and no machine offers Codex: no Reviewer of another engine can run here.
for (const a of f.state.agents) a.configuration = { ...a.configuration, engine: 'claude' }
f.run({ type: 'work.assign', conversationId: group, agentId: builder })
const review = f.run({ type: 'conversation.create', title: 'Review', brief: 'Review it.', reviewOf: group, checks: [{ description: 'Verdict', independent: false }] },
leadActor).result.conversationId as string
const route = (pick: Record<string, unknown>) => f.run({ type: 'route.record', conversationId: review, decision: record({ candidates: [candidate('c0', pick)], pick: 'c0' }) } as Command, leadActor)
- expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: 'No Reviewer on another engine than the Builder\'s (Claude) can run in this Swarm, so the review runs on it at the top tier.' } })
+ const same = 'same-engine review: no Reviewer of another engine has quota, so the review runs on Claude, the Builder\'s engine, at its top tier.'
+ const routed = route({})
+ expect(routed.routeDecisions[0]).toMatchObject({ record: { sameEngine: same } })
+ // Its route line says so (Lead, 2026-10-30).
+ expect(routed.messages.find(m => m.conversationId === review)!.text).toMatch(/ · same-engine review: no Reviewer of another engine has quota$/)
expect(() => route({ model: 'sonnet', effort: 'medium', quality: 2 }))
- .toThrow('A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can run in this Swarm. Route again.')
+ .toThrow('A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm. Route again.')
expect(() => route({ model: 'default', effort: 'default' })).toThrow('Claude default is 1.')
expect(() => route({ model: 'default', effort: 'default', gridModel: 'moonshotai/kimi-k3', gridName: 'swarm-g' })).toThrow('never runs on a model served on the Swarm\'s grid')
// A machine that offers Codex makes the other engine available, and the same engine is refused again.
- f.state.machines = [{ machineId: 'codex-box', contributorId: 'owner', engines: ['codex'] } as never]
+ // Each run hands back a new state, so the machine is set afresh before each.
+ const codexBox = (reading: Record<string, unknown> = {}) => {
+ f.state.machines = [{ machineId: 'codex-box', contributorId: 'owner', engines: ['codex'], observation: { receivedAt: 1000, quotas: [], ...reading } } as never]
+ }
+ const weekly = (resetsIn: number) => ({ quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: new Date(1000 + resetsIn).toISOString() }] }] })
+ codexBox()
expect(() => route({})).toThrow('A review runs on another engine than the reviewed Builder\'s, Claude. Route again.')
+ // Unless it could not start within the start window: out of quota for days (2026-10-30), or offline.
+ codexBox(weekly(3 * 86_400_000))
+ expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: same } })
+ codexBox(weekly(10 * 60_000))
+ expect(() => route({})).toThrow('A review runs on another engine than the reviewed Builder\'s, Claude. Route again.')
+ codexBox({ receivedAt: -3_600_000 })
+ expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: same } })
+ codexBox()
// Unless that machine may not run the review: the owner's rules, or the task's own machine (review of ee4ee6c9a).
f.run({ type: 'rule.set', rule: { kind: 'machines', machineIds: ['host', 'machine'] }, text: 'Only our machines.' } as Command)
expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: expect.stringContaining('top tier') } })
f.run({ type: 'rule.remove', ruleId: f.state.rules!.at(-1)!.id } as Command)
f.state.conversations.find(c => c.id === review)!.task = { goal: 'g', changes: 'c', constraints: 'k', owns: [], requires: { machines: ['machine'] } }
expect(route({}).routeDecisions[0]).toMatchObject({ record: { sameEngine: expect.stringContaining('top tier') } })
+ // The Reviewer's brief says it first, assigned by hand too.
+ delete f.state.conversations.find(c => c.id === review)!.task
+ codexBox(weekly(3 * 86_400_000))
+ const assigned = f.run({ type: 'work.assign', conversationId: review, agentId: reviewer })
+ expect(assigned.result.warnings).toBeUndefined()
+ expect(assigned.messages.find(m => m.recipients.includes(reviewer))!.text).toMatch(new RegExp(`^${same.replace(/[.()]/g, '\\$&')}\n\nReview it\.`))
})
it('never lets a small or unnamed model review: a review needs a model the policy names at quality 2 or more', () => {
@@ -1603,6 +1626,18 @@ describe('Reviewer role', () => {
return { ...setup, fresh, built, builderActor, markReady, reviews }
}
+ // Overnight 2026-10-30 reviews waited hours with every other-engine Reviewer out of quota, and nobody was told.
+ it('tells the project chat once when no new Reviewer on another engine than the Builder\'s can start, tagging who can fix it', () => {
+ const { f, markReady } = ready()
+ teamMachine(f, 'owner')
+ f.state.machines![0]!.observation!.quotas = [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }]
+ const said = markReady(`Ready: yes.\n${pr}`).messages.filter(m => m.source?.kind === 'review-capacity')
+ expect(said).toMatchObject([{ conversationId: f.state.projects![0]!.leadConversationId, recipients: [], mentions: ['owner'] }])
+ expect(said[0]!.text).toBe('Reviews of Codex builds cannot start a new Reviewer: Claude Code is unavailable on every machine this project may use (Studio: out of quota). '
+ + 'More Claude Code quota, Claude Code signed in on another machine, or another machine in the Swarm would unblock them. @owner can fix it.')
+ expect(markReady(`Ready: yes, again.\n${pr}`).messages.filter(m => m.source?.kind === 'review-capacity')).toEqual([])
+ })
+
it('opens "Review: <group>" with the handoff, the checks and the link, assigns a free Reviewer and adds it to the reviewed group', () => {
const { f, lead, group, reviewer, fresh, markReady, reviews } = ready()
f.run({ type: 'agent.release', agentId: reviewer, decision: 'stop' }, { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' })
@@ -1756,8 +1791,11 @@ describe('Reviewer role', () => {
for (const a of f.state.agents) a.configuration = { ...a.configuration, engine: 'claude' }
f.state.agents.find(a => a.id === reviewer)!.configuration.model = 'claude-sonnet-4-5'
f.state.agents.find(a => a.id === fresh)!.configuration.model = 'claude-opus-4-7'
- markReady(`Ready. ${pr}`)
+ const effects = markReady(`Ready. ${pr}`)
expect(reviews()[0]!.assignment!.agentId).toBe(fresh)
+ // Its brief says first why it reviews on the Builder's engine (Lead, 2026-10-30).
+ const brief = effects.messages.find(m => m.conversationId === reviews()[0]!.id && m.recipients.includes(fresh))!.text
+ expect(brief).toMatch(/^same-engine review: no Reviewer of another engine has quota, so the review runs on Claude, the Builder's engine, at its top tier\.\n\nGive an independent verdict/)
})
it('gives the review to a strong Reviewer on another engine, and to an Engineer on the grid even a Reviewer on its relay engine', () => {
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 1318335cc..e394861a8 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -11,7 +11,7 @@ import {
import { jobKindOf } from './evidence/jobKind.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { DEFAULT_ROUTING_POLICY, routingOverrideSaveSchema, type RoutingPolicy } from './routingPolicy.js'
-import { agentTarget, askedInSchema, broken, MAX_RULES, reviewRefusal, RULE_MESSAGE_MS, sameEngineReview, ruleSchema, ruleTextSchema, startTarget, unmet, type RunTarget } from './rules.js'
+import { agentTarget, askedInSchema, broken, MAX_RULES, reviewRefusal, RULE_MESSAGE_MS, SAME_ENGINE, sameEngineReview, ruleSchema, ruleTextSchema, startTarget, unmet, type RunTarget } from './rules.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'
import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'
@@ -19,6 +19,7 @@ import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead,
import { leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, reviewFoundProblems, waitingForReview } from './liveness.js'
import { ABANDONED, failureNotice, MACHINE_REMOVED } from './startFailure.js'
import { noteStartFailed, noteStartSucceeded, resumeEngine } from './engineHealth.js'
+import { reviewCapacityNotice } from './reviewCapacity.js'
import { digestStartsAfter, knownTimeZone } from './digest.js'
import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'
import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'
@@ -677,7 +678,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (rule) return { code: 'RULE_BROKEN', why: rule }
const requirement = unmet(conversation(state, conversationId).task?.requires, target, macOf)
if (requirement) return { code: 'REQUIREMENT_UNMET', why: requirement }
- const review = reviewRefusal(state, conversation(state, conversationId).reviewOf, target, policy, mayRun(conversationId, true))
+ const review = reviewRefusal(state, conversation(state, conversationId).reviewOf, target, policy, mayRun(conversationId, true), context.now)
if (review) return { code: 'REVIEW_REFUSED', why: review }
const stepped = builds ? stepUpRefusal(conversation(state, conversationId), target, policy) : null
return stepped ? { code: 'STEPPED_UP', why: stepped } : null
@@ -2037,7 +2038,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// The step this attempt is comes from the group alone (stepUp.ts), and why a review stays on its Builder's engine from
// the server's own judgement (rules.ts).
const step = conversation(state, command.conversationId).stepUp
- const sameEngine = sameEngineReview(state, conversation(state, command.conversationId).reviewOf, member ? agentTarget(state, member) : chosen, policy, mayRun(command.conversationId, true))
+ const sameEngine = sameEngineReview(state, conversation(state, command.conversationId).reviewOf, member ? agentTarget(state, member) : chosen, policy, mayRun(command.conversationId, true), context.now)
const { stepUp: _sent, sameEngine: _said, jobKind: _kind, ...made } = decision
const jobKind = jobKindOf(conversation(state, command.conversationId), decision.assessment.kind)
effects.routeDecisions.push({ op: 'create', id: operationId, conversationId: command.conversationId,
@@ -2045,7 +2046,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
result.routeDecisionId = operationId
// The row quotes the Lead's reason for the task; the verdict's own text stays in the decision record.
const reason = decision.assessment.why
- message(command.conversationId, `Routed to ${chosen.title} — ${via} · "${reason}"`, [], null, bookkeeping(command.conversationId, {
+ message(command.conversationId, `Routed to ${chosen.title} — ${via} · "${reason}"${sameEngine ? ` · ${SAME_ENGINE}` : ''}`, [], null, bookkeeping(command.conversationId, {
kind: 'route', decisionId: operationId, via: decision.via, p: decision.p, belowFloor: decision.belowFloor, why: reason,
...(decision.via === 'order' && decision.fallback ? { fallback: decision.fallback } : {}),
pick: { id: chosen.id, title: chosen.title },
@@ -2157,7 +2158,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
personChose = !override && decision.override?.by === 'person'
}
ruled(agentTarget(state, worker), group.id, `${who} assigned ${worker.name}`, personChose)
- message(group.id, `${group.brief}${carryOver(group)}\n\nAcceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`, [worker.id], null, SYSTEM_ROW)
+ // A review on its Builder's own engine says so first, so its Reviewer knows why (rules.ts sameEngineReview).
+ const sameEngine = sameEngineReview(state, group.reviewOf, agentTarget(state, worker), policy, mayRun(group.id, true), context.now)
+ message(group.id, `${sameEngine ? `${sameEngine}\n\n` : ''}${group.brief}${carryOver(group)}\n\nAcceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\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: stableId(operationId, 'route-override'), conversationId: group.id, author: sender,
@@ -2220,8 +2223,14 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const opened = pullRequest && openReview(state, group, command.result!, pullRequest, { operationId, now: context.now, engineer: sender,
// The owner's hard rules hold as for work.assign; the reviewed task's own requirement is its Engineer's, not its Reviewer's.
mayWork: a => !teamWorkCheck(state, a.machineId, a.contributorId, groupProject(state, group), context.now, context.teamMachines, context.otherWorkspaceMachines)
- && !broken(groupRules(group.id), agentTarget(state, a), machineName, macOf) && !reviewRefusal(state, group.id, agentTarget(state, a), policy, mayRun(group.id, false)) })
+ && !broken(groupRules(group.id), agentTarget(state, a), machineName, macOf) && !reviewRefusal(state, group.id, agentTarget(state, a), policy, mayRun(group.id, false), context.now),
+ sameEngine: a => sameEngineReview(state, group.id, agentTarget(state, a), policy, mayRun(group.id, false), context.now) })
if (opened) effects.messages.push(...opened.messages)
+ // No new Reviewer on another engine can start, or soon none will: the project's chat hears it once (reviewCapacity.ts).
+ const short = command.status === 'review' && !group.reviewOf ? reviewCapacityNotice(state, group, policy, mayRun(group.id, false), context.now) : null
+ // A row of its own beside the command's, as the ship notice is: written as the Engineer who handed over.
+ if (short) effects.messages.push({ id: stableId(operationId, 'review-capacity', short.source.engine), conversationId: short.conversationId, author: sender,
+ text: short.text, replyTo: null, recipients: [], source: short.source, ...(short.mentions.length ? { mentions: short.mentions } : {}) })
// Shipped before this command: the leaderboard marks this Done as shipped just above (recordStatus).
if (command.status === 'done' && shippedAt(conversation(original, group.id)) == null) {
appendPullRequestUrls(group, [command.result, ...group.checks.map(check => check.evidence)])
@@ -2341,6 +2350,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
// A Buddy hears the project-chat rows about its person's proposals and requested work (buddyNews.ts).
for (const draft of effects.messages) tellBuddies(state, draft, draft.replyTo && draft.replyTo === context.reply?.id ? context.reply.threadSource ?? null : null)
+ // Each row is stored under its id: two alike roll the whole command back on a duplicate key, in the store alone (review of
+ // #2275: the review-capacity notice took the Ready for review row's id, so no Builder could hand over during a shortage).
+ const ids = new Set<string>()
+ for (const draft of effects.messages) {
+ if (ids.has(draft.id)) throw new Error(`Command ${command.type} wrote two messages with the id ${draft.id}.`)
+ ids.add(draft.id)
+ }
return effects
}
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 6a8f29b76..8ac44613b 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -64,6 +64,7 @@ export function renewLease(assignment: Assignment, now: number): void {
/** A hand-off: a result that says it is ready for review and names a revision (a commit hash). Right after '@', 'at ' or
* 'head ', the forms hand-offs use, any 7-40 hex digits count, since a short hash can be all digits or all letters;
* anywhere else it needs a digit and a letter, so dates and other numbers do not count (review of #2176). */
+// Desktop reads hand-offs with a copy of these two (desktop/lib/super_tabs/agent_mark.dart): change both together.
const READY_FOR_REVIEW = /\bready for review\b/i
const REVISION = /(?:@|\b(?:at|head)\s+)[0-9a-f]{7,40}\b|\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/i
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index d61a0764b..95fb25e5e 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -415,6 +415,8 @@ export const NOTICE_READERS = {
rule: 'people', 'project-report': 'people', route: 'people', 'route-override': 'people', 'buddy-proposal': 'people',
'decision-delegated': 'people', 'machine-removed': 'people', 'machine-left': 'people', ship: 'people', 'auto-review': 'people',
'auto-archive': 'people', native: 'people',
+ // No new Reviewer can start, or soon none will, tagging who can fix it (reviewCapacity.ts).
+ 'review-capacity': 'people',
// #2177's rulings: a failed start and a terminal's alert or typed input stay the people's to see.
'start-timeout': 'people', 'terminal-alert': 'people', 'terminal-input': 'people',
} as const satisfies Record<string, 'people' | 'recipients' | 'agent'>
diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.ts
index 94a8ed67a..1fb38fa01 100644
--- a/backend/src/superTabs/pageReads.ts
+++ b/backend/src/superTabs/pageReads.ts
@@ -131,19 +131,61 @@ export async function deliveredCopies(tx: Transaction, tabId: string, rows: Read
return new Set(copies.filter(row => reached.has(stableId(row.id, 'lead'))).map(row => row.id))
}
-/** `routing`: a route, override or rule row (buddies.ts routingRow), which a Buddy never reads, as a reply or a thread's root. */
-export interface ThreadReply { thread: string; id: string; author: Author; mentions: string[]; sequence: number; createdAt: Date; agentOnly: boolean; routing: boolean }
+/** `routing`: a route, override or rule row (buddies.ts routingRow), which a Buddy never reads, as a reply or a thread's root.
+ * `count`: how many of the thread's rows this one stands for (pageThreads); a row without it is one. */
+export interface ThreadReply { thread: string; id: string; author: Author; mentions: string[]; sequence: number; createdAt: Date; agentOnly: boolean; routing: boolean
+ count?: number }
-/** Every message of the threads rooted at `roots` in one conversation, roots included, oldest first: what the page's thread
- * summaries are counted from. Matched as the page reads are, so the tabId+conversationId+thread index bounds it. */
+/** The rows of one thread that every reader sees or skips alike: one author, and one kind of row (agentOnly, routingRow). */
+interface ThreadPart { thread: string; root: boolean; kind?: unknown; only?: unknown; to: boolean }
+/** One row of a part, by its place in the thread. */
+interface ThreadPlace { s: number; i: string; at: unknown; author: Author; slot?: number }
+
+/**
+ * The threads rooted at `roots` in one conversation, roots included, oldest first, as a few rows that stand for all of them:
+ * what the page's thread summaries are counted from (threads.ts). The database groups the rows of each part (ThreadPart) and
+ * returns its oldest and newest row, how many it has (`count` on the newest), and where each person it tags is first tagged.
+ * That is every place a summary reads: first appearances, the newest reply of each author, the count and the last reply. So
+ * a poll that brings one reply of a 500-reply thread gets a few rows back, not 500, while the summaries stay what every
+ * row gave (integration/superTabIndexes.test.ts). Matched as the page reads are, so the thread index bounds it; the database
+ * still examines each of the threads' rows.
+ */
export async function pageThreads(tx: Transaction, tabId: string, conversationId: string, roots: string[]): Promise<ThreadReply[]> {
- // Sorted here: a $sort in the pipeline makes the planner walk the conversation's sequence index instead.
- const rows = await tx.superTabMessage.aggregateRaw({ pipeline: [{ $match: { tabId, conversationId, thread: { $in: roots } } },
- { $project: { thread: 1, author: 1, mentions: 1, sequence: 1, createdAt: 1, source: 1, recipientIds: 1 } }] }) as unknown as Array<Record<string, unknown>>
- const copies = await deliveredCopies(tx, tabId, rows.filter(row => row._id === row.thread)
- .map(row => ({ id: row._id as string, source: row.source, recipientIds: (row.recipientIds ?? []) as string[] })))
- return rows.map(row => ({ thread: row.thread as string, id: row._id as string, author: row.author as Author,
- mentions: (row.mentions ?? []) as string[], sequence: row.sequence as number, createdAt: new Date(ms(row.createdAt)),
- agentOnly: copies.has(row._id as string) || agentOnly(row.source, (row.recipientIds ?? []) as string[]), routing: routingRow(row.source) }))
- .sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : 1))
+ const root = { $eq: ['$_id', '$thread'] }
+ const part = { thread: '$thread', root, kind: '$source.kind', only: '$source.recipientsOnly',
+ to: { $gt: [{ $size: { $ifNull: ['$recipientIds', []] } }, 0] }, author: { kind: '$author.kind', id: '$author.id' } }
+ // (sequence, id) lead each place, so the database's min and max order rows as the sort below does (ids are ASCII).
+ const place = { s: '$sequence', i: '$_id', at: '$createdAt', author: '$author' }
+ // No $sort: it makes the planner walk the conversation's sequence index instead.
+ const [found] = await readBy(tx, 'SuperTabMessage', 'thread', [{ $match: { tabId, conversationId, thread: { $in: roots } } },
+ { $facet: {
+ parts: [{ $group: { _id: part, count: { $sum: 1 }, oldest: { $min: place }, newest: { $max: place },
+ // A root is its part's only row: what deliveredCopies reads of it.
+ root: { $first: { $cond: [root, { source: '$source', recipientIds: '$recipientIds' }, '$$REMOVE'] } } } }],
+ mentions: [{ $unwind: { path: '$mentions', includeArrayIndex: 'slot' } },
+ { $group: { _id: { ...part, person: '$mentions' }, first: { $min: { s: '$sequence', i: '$_id', slot: { $toInt: '$slot' }, at: '$createdAt', author: '$author' } } } }],
+ } }]) as unknown as Array<{
+ parts: Array<{ _id: ThreadPart; count: number; oldest: ThreadPlace; newest: ThreadPlace; root?: { source?: unknown; recipientIds?: string[] } | null }>
+ mentions: Array<{ _id: ThreadPart & { person: string }; first: ThreadPlace }>
+ }>
+ const parts = found?.parts ?? [], mentions = found?.mentions ?? []
+ const copies = await deliveredCopies(tx, tabId, parts.flatMap(p => p._id.root && p.root
+ ? [{ id: p._id.thread, source: p.root.source, recipientIds: p.root.recipientIds ?? [] }] : []))
+ // agentOnly reads only whether a row has recipients, not who they are.
+ const hidden = (key: ThreadPart) => (key.root && copies.has(key.thread))
+ || agentOnly({ kind: key.kind, recipientsOnly: key.only }, key.to ? ['recipient'] : [])
+ const rows = new Map<string, ThreadReply & { slots: Array<[number, string]> }>()
+ const row = (key: ThreadPart, at: ThreadPlace) => {
+ let kept = rows.get(at.i)
+ if (!kept) rows.set(at.i, kept = { thread: key.thread, id: at.i, author: at.author, mentions: [], sequence: at.s, createdAt: new Date(ms(at.at)),
+ agentOnly: hidden(key), routing: routingRow({ kind: key.kind }), count: 0, slots: [] })
+ return kept
+ }
+ for (const p of parts) {
+ row(p._id, p.oldest)
+ row(p._id, p.newest).count = p.count
+ }
+ for (const m of mentions) row(m._id, m.first).slots.push([m.first.slot!, m._id.person])
+ return [...rows.values()].map(({ slots, ...reply }) => ({ ...reply, mentions: slots.sort((a, b) => a[0] - b[0]).map(([, person]) => person) }))
+ .sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : 1))
}
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 5763ee442..59b19357b 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -37,6 +37,9 @@ export interface SwarmProject {
roles?: ProjectRole[]
/** Its Product Manager started by the Swarm on one of its machines, or waiting for one (leadStart.ts). */
lead?: import('./leadStart.js').LeadPlacement
+ /** What its chat was last told of new Reviewers per engine (reviewCapacity.ts): none can start, or they soon will not.
+ * Absent once a machine is usable again, so the next shortage is told. */
+ reviewCapacity?: Partial<Record<'claude' | 'codex', 'out' | 'low'>>
}
export const skillModeOf = (project: SwarmProject): SkillMode => project.skillMode ?? 'orchestration'
diff --git a/backend/src/superTabs/reviewCapacity.test.ts b/backend/src/superTabs/reviewCapacity.test.ts
new file mode 100644
index 000000000..0524de6e8
--- /dev/null
+++ b/backend/src/superTabs/reviewCapacity.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it } from 'vitest'
+import type { ContributedMachine } from './machines.js'
+import { createSuperTab, type Conversation, type SuperTabState } from './model.js'
+import { DEFAULT_ROUTING_POLICY } from './routingPolicy.js'
+import { RELAYED_QUOTA, reviewCapacityNotice } from './reviewCapacity.js'
+
+// Overnight 2026-10-30, 12 pull requests waited hours for a review: every Codex Reviewer was out of weekly quota, a Claude
+// Reviewer may not check a Claude build, and nobody was told until people noticed in the morning (Tony: "don't let the
+// workflow get stuck"). The notice says so in the project chat, once per cause, tagging who can fix it.
+
+const NOW = 10_000_000
+const HOUR = 3_600_000
+
+type Window = { name: string; usedPercent: number }
+function machine(id: string, name: string, contributorId: string, codex: { windows?: Window[]; known?: boolean; signedIn?: boolean } | null,
+ extra: Partial<ContributedMachine> = {}): ContributedMachine {
+ return { machineId: id, name, contributorId, membershipGeneration: 'g', generation: 'g1', cwd: '/swarm', scope: 'swarm', engines: codex ? ['claude', 'codex'] : ['claude'],
+ maxAgents: 4, paused: false, ...extra,
+ observation: { generation: 'g1', receivedAt: NOW - 1000, sessionKind: 'computer',
+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,
+ deviceType: null, chip: null, os: null, gpuPercent: null },
+ tools: {}, runningHarnessIds: [], stoppedHarnessIds: [],
+ readiness: { engines: [{ engine: 'claude', installed: true, signedIn: true }, ...codex ? [{ engine: 'codex', installed: true, signedIn: codex.signedIn ?? true }] : []] },
+ quotas: codex ? [{ engine: 'codex', known: codex.known ?? true, windows: (codex.windows ?? []).map(w => ({ ...w, resetsAt: null })) }] : [],
+ ...extra.observation } as ContributedMachine['observation'] }
+}
+const out = [{ name: 'weekly', usedPercent: 100 }]
+const low = [{ name: 'weekly', usedPercent: 85 }]
+const plenty = [{ name: '5-hour', usedPercent: 10 }, { name: 'weekly', usedPercent: 15 }]
+
+/** A Swarm whose project has a build group [built] on [engine] and machines [machines]; Ken's project, Tony a teammate. */
+function swarm(machines: ContributedMachine[], engine = 'claude', visibility: 'public' | 'private' = 'public') {
+ const state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'ken', email: '[email protected]' }, 'prod')
+ state.people.push({ id: 'tony', email: '[email protected]', role: 'collaborator', generation: 'gt' }, { id: 'huy', email: '[email protected]', role: 'collaborator', generation: 'gh' })
+ state.projects![0]!.visibility = visibility
+ state.machines = machines
+ const built: Conversation = { id: 'built', number: 7, title: 'Offline edits', leadId: null, agentIds: [], archived: false, brief: 'Build it.', checks: [], lastMessageSequence: 0,
+ assignment: { id: 'a1', agentId: 'builder', status: 'review', configuration: { engine, model: 'claude-opus-4-7', effort: 'high' }, result: null } } as unknown as Conversation
+ state.conversations.push(built)
+ return { state, built, project: state.projects![0]! }
+}
+const anyMachine = () => true
+const notice = (state: SuperTabState, group: Conversation, mayRun: (machineId: string) => boolean = anyMachine, now = NOW) =>
+ reviewCapacityNotice(state, group, DEFAULT_ROUTING_POLICY, target => mayRun(target.machineId), now)
+
+describe('the notice that new Reviewers cannot start', () => {
+ it('says once in the project chat that no Codex Reviewer can start, naming each machine and tagging its owner', () => {
+ const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('huy-mac', 'MacBookPro2021', 'huy', { windows: plenty, signedIn: false }),
+ machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: [{ name: '5-hour', usedPercent: 100 }, { name: 'weekly', usedPercent: 40 }] })])
+ const first = notice(state, built)
+ expect(first).toMatchObject({ conversationId: project.leadConversationId, mentions: ['ken', 'huy', 'tony'], source: { kind: 'review-capacity', engine: 'codex', cause: 'out' } })
+ // Claude Opus can still start on these machines, so reviews fall back to it (rules.ts judgeReview).
+ expect(first!.text).toBe('Reviews of Claude Code builds fall back to Claude Code at its top tier: Codex is unavailable on every machine this project may use '
+ + '(Mac Studio: out of quota; MacBookPro2021: signed out; MacBook Pro 19: out of quota). More Codex quota, Codex signed in on another machine, '
+ + 'or another machine in the Swarm would bring back reviews on another engine. @ken15 @huy @tony can fix it.')
+ // A person's own numbers are never shown to the others.
+ expect(first!.text).not.toMatch(/\d+ ?%/)
+ expect(notice(state, built, anyMachine, NOW + HOUR)).toBeNull()
+ })
+
+ it('says reviews cannot start when no top-tier Reviewer of the Builder\'s own engine can start either', () => {
+ const studio = machine('studio', 'Mac Studio', 'ken', { windows: out })
+ studio.observation!.readiness!.engines![0]!.signedIn = false
+ const { state, built } = swarm([studio])
+ expect(notice(state, built)!.text).toBe('Reviews of Claude Code builds cannot start a new Reviewer: Codex is unavailable on every machine this project may use '
+ + '(Mac Studio: out of quota). More Codex quota, Codex signed in on another machine, or another machine in the Swarm would unblock them. @ken15 can fix it.')
+ })
+
+ it('counts a paused machine as unable to start a Reviewer, as the route does', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: plenty }, { paused: true })])
+ expect(notice(state, built)!.text).toContain('(Mac Studio: paused)')
+ })
+
+ it('warns once when every Codex machine is close to running out of weekly quota, and again when it runs out', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: low }), machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: out })])
+ const warned = notice(state, built)
+ expect(warned).toMatchObject({ mentions: ['ken', 'tony'], source: { kind: 'review-capacity', engine: 'codex', cause: 'low' } })
+ expect(warned!.text).toBe('Codex quota for reviewing Claude Code builds is close to running out on every machine this project may use '
+ + '(Mac Studio: close to running out; MacBook Pro 19: out of quota). More Codex quota, Codex signed in on another machine, '
+ + 'or another machine in the Swarm would keep reviews going. @ken15 @tony can fix it.')
+ expect(notice(state, built)).toBeNull()
+ state.machines![0]!.observation!.quotas[0]!.windows[0]!.usedPercent = 100
+ expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
+ expect(notice(state, built)).toBeNull()
+ })
+
+ it('says nothing while one Codex machine has quota, and once it recovers, says it again the next time it runs out', () => {
+ const { state, built, project } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: plenty })])
+ expect(notice(state, built)).toBeNull()
+ state.machines![1]!.observation!.quotas[0]!.windows = out.map(w => ({ ...w, resetsAt: null }))
+ expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
+ state.machines![0]!.observation!.quotas[0]!.windows = plenty.map(w => ({ ...w, resetsAt: null }))
+ expect(notice(state, built)).toBeNull()
+ expect(project.reviewCapacity).toBeUndefined()
+ state.machines![0]!.observation!.quotas[0]!.windows = out.map(w => ({ ...w, resetsAt: null }))
+ expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
+ })
+
+ it('counts a quota it cannot read as usable, as starts do, and says nothing with no Codex machine at all (Claude reviews at its top tier)', () => {
+ const unread = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('x', 'Unread', 'tony', { known: false })])
+ expect(notice(unread.state, unread.built)).toBeNull()
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', null)])
+ expect(notice(state, built)).toBeNull()
+ })
+
+ it('reads a Team account\'s quota from its Mac when the account spends that subscription through the relay', () => {
+ const mac = machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: out })
+ const team = machine('tony-team', 'MacBook Pro 19', 'tony', { known: false }, { hostMachineId: 'tony-mac' })
+ team.observation!.quotaReasons = { codex: RELAYED_QUOTA }
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), mac, team])
+ // The Mac is named once: the account is that Mac.
+ expect(notice(state, built)!.text).toContain('(Mac Studio: out of quota; MacBook Pro 19: out of quota)')
+ // Unknown for another reason, the account stays usable, as a start there is.
+ team.observation!.quotaReasons = { codex: 'The allowance reader on this machine did not answer.' }
+ const again = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), mac, team])
+ expect(notice(again.state, again.built)).toBeNull()
+ })
+
+ it('says nothing while a used-up window resets inside the start window, as the review rule waits for it (rules.ts)', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out })])
+ state.machines![0]!.observation!.quotas[0]!.windows[0]!.resetsAt = new Date(NOW + 10 * 60_000).toISOString()
+ expect(notice(state, built)).toBeNull()
+ state.machines![0]!.observation!.quotas[0]!.windows[0]!.resetsAt = new Date(NOW + 3 * 24 * HOUR).toISOString()
+ expect(notice(state, built)).toMatchObject({ source: { cause: 'out' } })
+ })
+
+ it('counts an offline machine as unavailable, and leaves out machines this project may not use', () => {
+ const offline = machine('tony-mac', 'MacBook Pro 19', 'tony', { windows: plenty })
+ offline.observation!.receivedAt = NOW - HOUR
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), offline, machine('ruled', 'Ruled out', 'huy', { windows: plenty })])
+ const said = notice(state, built, id => id !== 'ruled')
+ expect(said!.text).toContain('(Mac Studio: out of quota; MacBook Pro 19: offline)')
+ expect(said!.mentions).toEqual(['ken', 'tony'])
+ })
+
+ it('tags only people who read the project, and names no machine of someone who does not', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), machine('tony-mac', 'Tony private Mac', 'tony', { windows: out })], 'claude', 'private')
+ const said = notice(state, built)
+ expect(said!.mentions).toEqual(['ken'])
+ expect(said!.text).not.toContain('tony')
+ expect(said!.text).not.toContain('Tony private Mac')
+ expect(said!.text).toContain('(Mac Studio: out of quota; another machine: out of quota)')
+ })
+
+ it('neither counts nor names a Buddy-only machine, which is its person\'s alone', () => {
+ const buddy = machine('buddy', 'Huy private laptop', 'huy', { windows: plenty }, { buddyOnly: true })
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out }), buddy])
+ const said = notice(state, built)
+ expect(said).toMatchObject({ mentions: ['ken'], source: { cause: 'out' } })
+ expect(said!.text).not.toContain('Huy private laptop')
+ })
+
+ it('says nothing for a build on a grid model, which any strong engine reviews, or a group with no build', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out })])
+ const grid = swarm([machine('studio', 'Mac Studio', 'ken', { windows: out })])
+ grid.state.agents.push({ id: 'builder', gridModel: 'moonshotai/kimi-k3' } as never)
+ expect(notice(grid.state, grid.built)).toBeNull()
+ expect(notice(state, { ...built, assignment: null })).toBeNull()
+ })
+
+ it('reviews a Codex build with Claude, the same way', () => {
+ const { state, built } = swarm([machine('studio', 'Mac Studio', 'ken', { windows: plenty })], 'codex')
+ state.machines![0]!.observation!.quotas = [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 100, resetsAt: null }] }]
+ expect(notice(state, built)).toMatchObject({ source: { engine: 'claude', cause: 'out' } })
+ expect(notice(state, built)).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/reviewCapacity.ts b/backend/src/superTabs/reviewCapacity.ts
new file mode 100644
index 000000000..cccfd28de
--- /dev/null
+++ b/backend/src/superTabs/reviewCapacity.ts
@@ -0,0 +1,83 @@
+/** Whether new Reviewers can still start for a project's builds, said once in its chat when they cannot or soon will not.
+ * Overnight 2026-10-30, 12 pull requests waited hours for a review: every Codex Reviewer was out of weekly quota, a Claude
+ * Reviewer may not check a Claude build (rules.ts judgeReview), and nobody was told until people noticed in the morning
+ * (Tony: "don't let the workflow get stuck"). Checked when an Engineer hands work over for review (commands.ts work.status). */
+import type { Conversation, SuperTabState } from './model.js'
+import { canReadProject, groupProject, projectRules } from './projects.js'
+import { canStart, STANDING, standing, type Standing } from './reviewSeats.js'
+import { liftEffort, type MayRun } from './rules.js'
+import type { RoutingPolicy } from './routingPolicy.js'
+import { usernameOf } from './usernames.js'
+
+export { RELAYED_QUOTA } from './reviewSeats.js'
+const ENGINES = ['claude', 'codex'] as const
+const NAME: Record<string, string> = { claude: 'Claude Code', codex: 'Codex' }
+
+export type Cause = 'out' | 'low'
+export interface ReviewCapacityNotice { conversationId: string; text: string; mentions: string[]; source: { kind: 'review-capacity'; engine: string; cause: Cause } }
+
+/** Each machine the project may start a Reviewer of [engine] on, on a policy row of [quality] or more, as one: a Mac and its
+ * Harness Team account are one machine (machines.ts teamStartRequest), standing as the better of the two. */
+function seats(state: SuperTabState, group: Conversation, engine: string, policy: RoutingPolicy, mayRun: MayRun, now: number, quality = 2) {
+ const rules = projectRules(state, groupProject(state, group).id)
+ const rows = policy.models.filter(row => row.enabled && row.engine === engine && row.quality >= quality)
+ const byMac = new Map<string, { name: string; contributorId: string; standing: Standing }>()
+ for (const pool of state.machines ?? []) {
+ if (pool.buddyOnly || pool.removal || !pool.engines.includes(engine)) continue
+ if (!rows.some(row => mayRun({ machineId: pool.machineId, engine, model: row.model, effort: liftEffort(rules, engine, row.effort) }, pool.contributorId))) continue
+ const key = pool.hostMachineId ?? pool.machineId, here = standing(state, pool, engine, now), seen = byMac.get(key)
+ if (!seen) byMac.set(key, { name: pool.name, contributorId: pool.contributorId, standing: here })
+ else if (STANDING.indexOf(here) < STANDING.indexOf(seen.standing)) seen.standing = here
+ }
+ return [...byMac.values()]
+}
+
+/**
+ * The notice for [group]'s review when no new Reviewer on another engine than its Builder's can start on any machine the
+ * project may use (cause `out`), or when each is close to running out of weekly quota (`low`); null otherwise. Said once
+ * per cause and engine: the project keeps which it last said, and forgets it once a machine is usable again. With no
+ * machine of the other engine at all the Builder's own engine reviews at its top tier (rules.ts), so nothing is said; nor
+ * for a build on a grid model, which either engine reviews. While a top-tier Reviewer of the Builder's own engine can start,
+ * reviews fall back to it (rules.ts judgeReview), and the notice says so rather than that they cannot start. Tags the
+ * owners of those machines who read the project and have a username.
+ */
+export function reviewCapacityNotice(state: SuperTabState, group: Conversation, policy: RoutingPolicy, mayRun: MayRun, now: number): ReviewCapacityNotice | null {
+ const assignment = group.assignment
+ if (!assignment) return null
+ const worker = state.agents.find(a => a.id === assignment.agentId)
+ if (worker?.gridModel) return null
+ const built = worker?.configuration.engine ?? assignment.configuration.engine
+ const engine = ENGINES.find(e => e !== built)
+ if (!engine) return null
+ const project = groupProject(state, group)
+ const places = seats(state, group, engine, policy, mayRun, now)
+ const said = project.reviewCapacity?.[engine]
+ const forget = () => {
+ if (!said) return
+ const { [engine]: _gone, ...others } = project.reviewCapacity!
+ if (Object.keys(others).length) project.reviewCapacity = others
+ else delete project.reviewCapacity
+ }
+ if (!places.length || places.some(p => p.standing === 'usable')) { forget(); return null }
+ const cause: Cause = places.some(p => p.standing === 'close to running out') ? 'low' : 'out'
+ // Out after low is news; low after out is not, but is kept so running out again is.
+ if (said === cause || (said === 'out' && cause === 'low')) { project.reviewCapacity = { ...project.reviewCapacity, [engine]: cause }; return null }
+ project.reviewCapacity = { ...project.reviewCapacity, [engine]: cause }
+
+ const person = (id: string) => state.people.find(p => p.id === id)
+ const reads = (id: string) => { const p = person(id); return !!p && canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project) }
+ // A machine of someone who cannot read this project is not named here.
+ const list = places.map(p => `${reads(p.contributorId) ? p.name : 'another machine'}: ${p.standing}`).join('; ')
+ // A tag is a username; someone without one is not tagged, never named by their email (review of #2275).
+ const mentions = [...new Set(places.map(p => p.contributorId))].filter(id => reads(id) && usernameOf(state, id))
+ const who = mentions.map(id => `@${usernameOf(state, id)}`).join(' ')
+ const fixes = `More ${NAME[engine]} quota, ${NAME[engine]} signed in on another machine, or another machine in the Swarm`
+ const fallback = cause === 'out' && seats(state, group, built, policy, mayRun, now, 3).some(p => canStart(p.standing))
+ const text = (cause === 'low'
+ ? `${NAME[engine]} quota for reviewing ${NAME[built]} builds is close to running out on every machine this project may use (${list}). ${fixes} would keep reviews going.`
+ : fallback
+ ? `Reviews of ${NAME[built]} builds fall back to ${NAME[built]} at its top tier: ${NAME[engine]} is unavailable on every machine this project may use (${list}). ${fixes} would bring back reviews on another engine.`
+ : `Reviews of ${NAME[built]} builds cannot start a new Reviewer: ${NAME[engine]} is unavailable on every machine this project may use (${list}). ${fixes} would unblock them.`)
+ + (who ? ` ${who} can fix it.` : '')
+ return { conversationId: project.leadConversationId, text, mentions, source: { kind: 'review-capacity', engine, cause } }
+}
diff --git a/backend/src/superTabs/reviewRules.test.ts b/backend/src/superTabs/reviewRules.test.ts
index 47fd9baa1..bc530cea9 100644
--- a/backend/src/superTabs/reviewRules.test.ts
+++ b/backend/src/superTabs/reviewRules.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest'
import { DEFAULT_ROUTING_POLICY as policy } from './routingPolicy.js'
-import { agentTarget, broken, reviewRefusal, startTarget, targetQuality } from './rules.js'
+import { agentTarget, broken, reviewRefusal, SAME_ENGINE, sameEngineReview, startTarget, targetQuality } from './rules.js'
import { effectivePolicy } from './routingPolicy.js'
import { cheapAttempt } from './stepUp.js'
import { recordRun } from './leaderboard/record.js'
@@ -35,6 +35,63 @@ describe('reviews and step-ups by what each attempt runs on', () => {
})
})
+// 2026-10-30: every Codex Reviewer was out of weekly quota for days, yet a Claude build's top-tier Claude review was refused
+// because Codex machines existed, and reviews waited all morning (Tony). Another engine counts only where a Reviewer of it
+// could start within the start window: on a machine the review may use, online, with quota now or once a window resets
+// inside the window.
+describe('a review on its Builder\'s own engine when no Reviewer of another engine could start soon', () => {
+ const NOW = Date.parse('2026-10-30T09:00:00Z'), MIN = 60_000, DAY = 86_400_000
+ const opus = { id: 'reviewer', machineId: 'allowed', harnessId: 'hr', contributorId: 'owner', configuration: { engine: 'claude', model: 'opus', effort: 'high' } }
+ const codexBox = (resetsIn: number | null, usedPercent = 100, extra: Record<string, unknown> = {}) => ({ machineId: 'codex-box', contributorId: 'tony', engines: ['codex'],
+ observation: { receivedAt: NOW - 1000, readiness: { engines: [{ engine: 'codex', installed: true, signedIn: true }] },
+ quotas: [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent, resetsAt: resetsIn === null ? null : new Date(NOW + resetsIn).toISOString() }] }] }, ...extra })
+ const judge = (machines: unknown[], rules: unknown[] = []) => {
+ const state = stateOf(opus)
+ Object.assign(state, { machines, rules })
+ const target = agentTarget(state, opus as any)
+ return { refusal: reviewRefusal(state, 'work', target, policy, undefined, NOW), note: sameEngineReview(state, 'work', target, policy, undefined, NOW) }
+ }
+
+ it('lets Claude Opus review a Claude build while every Codex machine is out of quota for days, and says why', () => {
+ expect(judge([codexBox(3 * DAY)])).toEqual({ refusal: null, note: expect.stringMatching(new RegExp(`^${SAME_ENGINE}`)) })
+ expect(SAME_ENGINE).toBe('same-engine review: no Reviewer of another engine has quota')
+ // Nor does an exhausted window that never says when it resets count.
+ expect(judge([codexBox(null)]).refusal).toBeNull()
+ })
+
+ it('still refuses Claude while Codex resets inside the start window, or has quota now', () => {
+ expect(judge([codexBox(10 * MIN)])).toEqual({ refusal: 'A review runs on another engine than the reviewed Builder\'s, Claude.', note: null })
+ expect(judge([codexBox(3 * DAY, 40)]).refusal).toBe('A review runs on another engine than the reviewed Builder\'s, Claude.')
+ // A quota it cannot read stays usable, as a start there is.
+ const unread = codexBox(3 * DAY); unread.observation.quotas[0]!.known = false
+ expect(judge([unread]).refusal).not.toBeNull()
+ })
+
+ it('lets Claude review when Codex runs only on a machine the owner left out, or one that is offline, signed out or suspended', () => {
+ const owners = [{ projectId: 'p', rule: { kind: 'machines', machineIds: ['allowed'] }, text: 'Only the approved machine.' }]
+ expect(judge([codexBox(3 * DAY, 40)], owners)).toEqual({ refusal: null, note: expect.stringMatching(new RegExp(`^${SAME_ENGINE}`)) })
+ const offline = codexBox(3 * DAY, 40); offline.observation.receivedAt = NOW - 10 * MIN
+ expect(judge([offline]).refusal).toBeNull()
+ const signedOut = codexBox(3 * DAY, 40); signedOut.observation.readiness.engines[0]!.signedIn = false
+ expect(judge([signedOut]).refusal).toBeNull()
+ expect(judge([codexBox(3 * DAY, 40, { engineSuspensions: { codex: { at: NOW - MIN, fine: true } } })]).refusal).toBeNull()
+ // Paused by its owner, as the CLI's route reads it (review of #2275: the route offered Claude, the server refused it).
+ expect(judge([codexBox(3 * DAY, 40, { paused: true })])).toEqual({ refusal: null, note: expect.stringMatching(new RegExp(`^${SAME_ENGINE}`)) })
+ })
+
+ it('counts a Codex agent on a machine outside the contributions while it is up, and not once a usage limit holds it past the window', () => {
+ const codexAgent = { id: 'codex', machineId: 'elsewhere', harnessId: 'hx', contributorId: 'owner', configuration: { engine: 'codex', model: 'default', effort: 'high' } } as any
+ const state = stateOf(opus)
+ state.agents.push(codexAgent)
+ const target = agentTarget(state, opus as any)
+ expect(reviewRefusal(state, 'work', target, policy, undefined, NOW)).not.toBeNull()
+ codexAgent.limitedUntil = new Date(NOW + 5 * MIN).toISOString()
+ expect(reviewRefusal(state, 'work', target, policy, undefined, NOW)).not.toBeNull()
+ codexAgent.limitedUntil = new Date(NOW + 2 * DAY).toISOString()
+ expect(reviewRefusal(state, 'work', target, policy, undefined, NOW)).toBeNull()
+ })
+})
+
// A Codex Reviewer started on a model named for it (Lead, 10-30: a gpt-6.1-sol Reviewer was refused as quality 1, and on a Mac
// whose Codex default is a local model no review could run).
describe('a Codex Reviewer on a named model', () => {
diff --git a/backend/src/superTabs/reviewSeats.ts b/backend/src/superTabs/reviewSeats.ts
new file mode 100644
index 000000000..86271fb23
--- /dev/null
+++ b/backend/src/superTabs/reviewSeats.ts
@@ -0,0 +1,57 @@
+/** Whether a new Reviewer of an engine could start on a contributed machine soon: what both the review rule (rules.ts
+ * judgeReview) and the project chat's notice (reviewCapacity.ts) read. On 2026-10-30 every Codex Reviewer was out of weekly
+ * quota for days, yet a Claude build's top-tier Claude review was refused because Codex machines existed; reviews waited
+ * all morning (Tony). */
+import { suspendedEngines } from './engineHealth.js'
+import { MACHINE_FRESH_MS, type ContributedMachine } from './machines.js'
+import type { SuperTabState } from './model.js'
+
+/** What a Harness Team account says of an engine that spends its Mac owner's subscription through the owner's relay: the
+ * allowance is that subscription's, read on the Mac. The same sentence as cli superTabs/capacity.ts RELAYED_QUOTA, which
+ * writes it. */
+export const RELAYED_QUOTA = "This account runs on its owner's subscription; its allowance is read on the owner's machine."
+/** How soon a Reviewer has to be able to start to count: a start still not running after this long is abandoned
+ * (store.ts ABANDONED_START_MS), so a review waiting longer than that is stuck. A window that resets inside it counts as
+ * quota; one out for longer does not (cli superTabs/route.ts REVIEW_START_MS). */
+export const REVIEW_START_MS = 15 * 60_000
+/** Weekly allowance left, in percent, at or below which an engine is close to running out: the route keeps the policy's
+ * reserve (10) back, so about one more day of reviews is left. */
+const LOW_LEFT = 20
+
+/** How a machine stands for a new Reviewer on an engine, best first. Words only: a person's own numbers stay theirs. */
+export const STANDING = ['usable', 'close to running out', 'out of quota', 'signed out', 'suspended', 'paused', 'offline'] as const
+export type Standing = typeof STANDING[number]
+/** A Reviewer could start there within REVIEW_START_MS. */
+export const canStart = (s: Standing) => s === 'usable' || s === 'close to running out'
+
+/** The engine's quota reading for [pool]: its own, or for a Team account that spends its Mac's subscription, the Mac's. */
+function quotaOf(state: SuperTabState, pool: ContributedMachine, engine: string, now: number) {
+ const own = pool.observation?.quotas.find(q => q.engine === engine)
+ if (own?.known || !pool.hostMachineId || pool.observation?.quotaReasons?.[engine] !== RELAYED_QUOTA) return own
+ const mac = state.machines?.find(m => m.machineId === pool.hostMachineId && m.contributorId === pool.contributorId)
+ return mac?.observation && now - mac.observation.receivedAt <= MACHINE_FRESH_MS ? mac.observation.quotas.find(q => q.engine === engine) : own
+}
+
+function resetMs(value: string | number | null): number | null {
+ if (typeof value === 'number') return value > 1e10 ? value : value * 1000
+ if (typeof value === 'string') { const ms = Date.parse(value); return Number.isFinite(ms) ? ms : null }
+ return null
+}
+
+/** How [pool] stands for a new Reviewer of [engine] at [now]. A usage window that is used up but resets within
+ * REVIEW_START_MS is not out: the Reviewer starts once it does. */
+export function standing(state: SuperTabState, pool: ContributedMachine, engine: string, now: number): Standing {
+ const reading = pool.observation
+ if (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) return 'offline'
+ // Its owner paused new work there, as the CLI's route reads it (routeCommand.ts probeMachine) and starts refuse it.
+ if (pool.paused) return 'paused'
+ if (reading.readiness?.engines?.find(e => e.engine === engine)?.signedIn === false) return 'signed out'
+ if (suspendedEngines(pool, now)[engine]) return 'suspended'
+ const quota = quotaOf(state, pool, engine, now)
+ // A quota it cannot read stays usable, as a start there is (engineHealth.ts engineUnusable).
+ if (!quota?.known) return 'usable'
+ const soon = (w: { resetsAt: string | number | null }) => { const at = resetMs(w.resetsAt); return at !== null && at - now <= REVIEW_START_MS }
+ if (quota.windows.some(w => w.usedPercent >= 100 && !soon(w))) return 'out of quota'
+ const weekly = quota.windows.find(w => w.name === 'weekly')
+ return weekly && !(weekly.usedPercent >= 100) && 100 - weekly.usedPercent <= LOW_LEFT ? 'close to running out' : 'usable'
+}
diff --git a/backend/src/superTabs/rules.ts b/backend/src/superTabs/rules.ts
index 42fbba55b..66e9668a3 100644
--- a/backend/src/superTabs/rules.ts
+++ b/backend/src/superTabs/rules.ts
@@ -5,6 +5,8 @@
import { z } from 'zod'
import type { Agent, SuperTabState, TaskRequirement } from './model.js'
import type { RoutingPolicy } from './routingPolicy.js'
+import { downSince } from './machines.js'
+import { canStart, REVIEW_START_MS, standing } from './reviewSeats.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const engine = z.enum(['claude', 'codex'])
@@ -128,30 +130,43 @@ export const targetQuality = (policy: RoutingPolicy, t: RunTarget) => policyQual
const familyOf = (t: { engine: string; gridModel?: string }) => t.gridModel ? `grid:${t.gridModel}` : t.engine
/** Whether a new Reviewer may run [target] for [contributorId]'s machine: its owner's rules, the task's machine and team
- * access, as the command judges them. Busy, offline or short of quota still counts as able, within its start window. */
+ * access, as the command judges them. Whether it could start soon is judged apart (reviewSeats.ts). */
export type MayRun = (target: RunTarget, contributorId: string) => boolean
-/** Whether a strong Reviewer of another family than [builder]'s can run in this Swarm: on a machine an agent runs on or a
- * contributed machine offers, with an engine other than the Builder's and an enabled policy row of quality 2 or more that
- * [mayRun] allows there (review of ee4ee6c9a: an engine the owner rules out blocked the fallback). */
-function otherFamilyReviews(state: SuperTabState, builder: { engine: string; gridModel?: string }, policy: RoutingPolicy, mayRun: MayRun): boolean {
- const places = [...state.agents.filter(a => !a.gridModel && !a.buddyOf).map(a => ({ machineId: a.machineId, contributorId: a.contributorId, engines: [a.configuration.engine] })),
- ...(state.machines ?? []).filter(m => !m.buddyOnly).map(m => ({ machineId: m.machineId, contributorId: m.contributorId, engines: m.engines }))]
- return places.some(place => place.engines.some(engine => familyOf({ engine }) !== familyOf(builder) && policy.models.some(row => row.enabled && row.engine === engine
- && row.quality >= 2 && mayRun({ machineId: place.machineId, engine, model: row.model, effort: liftEffort(state.rules, engine, row.effort) }, place.contributorId))))
+/** Whether a strong Reviewer of another family than [builder]'s could start in this Swarm within REVIEW_START_MS: with an
+ * engine other than the Builder's and an enabled policy row of quality 2 or more that [mayRun] allows there (review of
+ * ee4ee6c9a: an engine the owner rules out blocked the fallback), on a contributed machine that is online, signed in, not
+ * suspended and has that engine's quota now or once a window resets inside the start window, or on a machine an agent of
+ * that engine runs on that is up and not held by a usage limit past it. Busy still counts: a Reviewer frees up. One out of
+ * quota for days, offline or left out by the owner's machines does not (2026-10-30: reviews of Claude builds waited all
+ * morning on Codex machines out of weekly quota). */
+function otherFamilyReviews(state: SuperTabState, builder: { engine: string; gridModel?: string }, policy: RoutingPolicy, mayRun: MayRun, now: number): boolean {
+ const pool = (machineId: string) => state.machines?.find(m => m.machineId === machineId)
+ const soon = (agent: Agent) => !downSince(state, agent, now) && !(agent.limitedUntil && Date.parse(agent.limitedUntil) - now > REVIEW_START_MS)
+ const places = [...state.agents.filter(a => !a.gridModel && !a.buddyOf && soon(a)).map(a => ({ machineId: a.machineId, contributorId: a.contributorId, engines: [a.configuration.engine] })),
+ ...(state.machines ?? []).filter(m => !m.buddyOnly && !m.removal).map(m => ({ machineId: m.machineId, contributorId: m.contributorId, engines: m.engines }))]
+ // A machine that reports its readings is judged by them; one that does not (an agent's host outside the contributions)
+ // by its agent alone, whatever its quota, which nothing reports there. Stricter than the CLI's route on purpose: an
+ // unknown counts as a Reviewer that could start, so the same-engine fallback is never taken on a guess.
+ const starts = (machineId: string, engine: string) => { const m = pool(machineId); return !m || canStart(standing(state, m, engine, now)) }
+ return places.some(place => place.engines.some(engine => familyOf({ engine }) !== familyOf(builder) && starts(place.machineId, engine)
+ && policy.models.some(row => row.enabled && row.engine === engine && row.quality >= 2
+ && mayRun({ machineId: place.machineId, engine, model: row.model, effort: liftEffort(state.rules, engine, row.effort) }, place.contributorId))))
}
/** The effort a new agent on a row starts at: the row's, or the owner's minimum when the row leaves it to the engine (cli
* superTabs/route.ts liftEffort). */
-function liftEffort(rules: SwarmRule[] | undefined, engine: string, effort: string): string {
+export function liftEffort(rules: SwarmRule[] | undefined, engine: string, effort: string): string {
if (rank(effort) >= 0) return effort
const least = Math.max(-1, ...(rules ?? []).flatMap(({ rule }) => rule.kind === 'minEffort' && (!rule.engine || rule.engine === engine) ? [rank(rule.effort)] : []))
return least < 0 ? effort : EFFORTS[least]!
}
+/** How a review on its Builder's own engine starts its route line and its brief (Lead, 2026-10-30; cli superTabs/route.ts). */
+export const SAME_ENGINE = 'same-engine review: no Reviewer of another engine has quota'
/** How [target] may review the work of group [reviewed] (Ken, 2026-10-29: a small model never reviews again): never on a model
* served on the Swarm's grid or one the policy rates below 2, and on another model family than the reviewed Builder's while
* a strong Reviewer of another family can run here. With none, the Builder's own engine at its top tier, noted (Lead,
* 2026-10-29: a Swarm of one engine keeps its automatic reviews). */
-function judgeReview(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun): { refusal: string } | { note: string } | null {
+function judgeReview(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun, now: number): { refusal: string } | { note: string } | null {
if (!reviewed) return null
if (target.gridModel) return { refusal: 'A review never runs on a model served on the Swarm\'s grid.' }
const quality = targetQuality(policy, target)
@@ -162,9 +177,9 @@ function judgeReview(state: SuperTabState, reviewed: string | undefined, target:
const builder = worker ? agentTarget(state, worker) : assignment ? { engine: assignment.configuration.engine } : null
// A grid target was refused above, so the same family is the target's engine.
if (!builder || familyOf(builder) !== familyOf(target)) return null
- if (otherFamilyReviews(state, builder, policy, mayRun)) return { refusal: `A review runs on another engine than the reviewed Builder's, ${engine}.` }
- return quality === 3 ? { note: `No Reviewer on another engine than the Builder's (${engine}) can run in this Swarm, so the review runs on it at the top tier.` }
- : { refusal: `A review on the reviewed Builder's engine, ${engine}, needs its top tier (quality 3): no Reviewer on another engine can run in this Swarm.` }
+ if (otherFamilyReviews(state, builder, policy, mayRun, now)) return { refusal: `A review runs on another engine than the reviewed Builder's, ${engine}.` }
+ return quality === 3 ? { note: `${SAME_ENGINE}, so the review runs on ${engine}, the Builder's engine, at its top tier.` }
+ : { refusal: `A review on the reviewed Builder's engine, ${engine}, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.` }
}
/** Why [target] may not review the work of group [reviewed]; null when it may, or nothing is reviewed. */
/** Without the command's own judgement, a machine may run a review where the owner's rules for the reviewed group's project
@@ -174,12 +189,14 @@ const ownerAllows = (state: SuperTabState, reviewed: string | undefined): MayRun
const rules = (state.rules ?? []).filter(r => !r.projectId || !projectId || r.projectId === projectId)
return target => !broken(rules, target)
}
-export function reviewRefusal(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun = ownerAllows(state, reviewed)): string | null {
- const judged = judgeReview(state, reviewed, target, policy, mayRun)
+export function reviewRefusal(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun = ownerAllows(state, reviewed),
+ now = Date.now()): string | null {
+ const judged = judgeReview(state, reviewed, target, policy, mayRun, now)
return judged && 'refusal' in judged ? judged.refusal : null
}
/** Why [target] reviews on the reviewed Builder's own engine, when it may only because no other engine can; null otherwise. */
-export function sameEngineReview(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun = ownerAllows(state, reviewed)): string | null {
- const judged = judgeReview(state, reviewed, target, policy, mayRun)
+export function sameEngineReview(state: SuperTabState, reviewed: string | undefined, target: RunTarget, policy: RoutingPolicy, mayRun: MayRun = ownerAllows(state, reviewed),
+ now = Date.now()): string | null {
+ const judged = judgeReview(state, reviewed, target, policy, mayRun, now)
return judged && 'note' in judged ? judged.note : null
}
diff --git a/backend/src/superTabs/threads.test.ts b/backend/src/superTabs/threads.test.ts
new file mode 100644
index 000000000..11f08790a
--- /dev/null
+++ b/backend/src/superTabs/threads.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest'
+import type { Author } from './model.js'
+import type { ThreadReply } from './pageReads.js'
+import { NOW, outsider, owner, peer, richSwarm } from './read/fixture.test-support.js'
+import { threadSummaries } from './threads.js'
+
+const s = richSwarm()
+const web = s.state.conversations.find(c => c.id === s.web)!
+// A private project's conversation: only its owner reads it.
+const secret = s.state.conversations.find(c => c.id === s.secretGroup)!
+const person = (id: string): Author => ({ kind: 'person', id, name: id, membershipGeneration: 'gen' })
+const agent = (id: string): Author => ({ kind: 'agent', id, name: id, membershipGeneration: 'gen' })
+const reply = (thread: string, id: string, sequence: number, author: Author, extra: Partial<ThreadReply> = {}): ThreadReply =>
+ ({ thread, id, author, mentions: [], sequence, createdAt: new Date(NOW + sequence), agentOnly: false, routing: false, ...extra })
+
+describe('thread summaries', () => {
+ // One row per message, as the inbox read passes them (#2256): a 500-reply thread where every 25th reply is an agent-only
+ // note to someone else, the owner and an agent take turns, and a teammate writes once in the middle.
+ const rows = [reply('r', 'r', 0, agent('lead')), ...Array.from({ length: 500 }, (_, i) => i % 25 === 24
+ ? reply('r', `r-${i}`, 1 + i, agent('ghost'), { agentOnly: true, mentions: [peer.userId] })
+ : reply('r', `r-${i}`, 1 + i, i === 300 ? person(peer.userId) : i % 2 ? agent('a1') : person(owner.userId),
+ { mentions: i === 5 ? [outsider.userId] : [] }))]
+
+ it('sums up a 500-reply thread from one row per message: hidden replies neither counted nor naming anyone', () => {
+ expect(threadSummaries(s.state, web, rows)).toEqual([{ id: 'r', replies: 480, lastSequence: 499, lastAt: new Date(NOW + 499),
+ authors: [person(owner.userId), agent('a1'), person(peer.userId)], people: [owner.userId, outsider.userId, peer.userId] }])
+ })
+
+ it('names only the people who read the conversation now', () => {
+ expect(threadSummaries(s.state, secret, rows)).toEqual([{ id: 'r', replies: 480, lastSequence: 499, lastAt: new Date(NOW + 499),
+ authors: [person(owner.userId), agent('a1')], people: [owner.userId] }])
+ })
+
+ it('counts a row that stands for several replies as that many', () => {
+ expect(threadSummaries(s.state, web, [reply('r', 'r', 0, agent('lead')), reply('r', 'r-0', 1, agent('a1'), { count: 0 }),
+ reply('r', 'r-9', 9, agent('a1'), { count: 7 })])).toEqual([{ id: 'r', replies: 7, lastSequence: 9, lastAt: new Date(NOW + 9),
+ authors: [agent('a1')], people: [] }])
+ })
+
+ it('leaves out a thread whose replies are all hidden, and keeps the others in the order they started', () => {
+ expect(threadSummaries(s.state, web, [reply('a', 'a', 0, agent('lead')), reply('b', 'b', 1, agent('lead')),
+ reply('a', 'a-1', 2, agent('ghost'), { agentOnly: true }), reply('b', 'b-1', 3, agent('a1'))]).map(t => t.id)).toEqual(['b'])
+ })
+})
diff --git a/backend/src/superTabs/threads.ts b/backend/src/superTabs/threads.ts
index a05efee7f..29b2bc881 100644
--- a/backend/src/superTabs/threads.ts
+++ b/backend/src/superTabs/threads.ts
@@ -14,14 +14,20 @@ export interface ThreadSummary {
people: string[]
}
-/** Summaries of the threads in `rows` (pageThreads), roots with no reply left out. Only people who can read the conversation
- * now are named, as an author or among `people`: someone who left keeps their replies but is no longer listed. */
+/** Summaries of the threads in `rows` (pageThreads, oldest first), roots with no reply left out; a row counts as `count`
+ * replies. Only people who can read the conversation now are named, as an author or among `people`: someone who left keeps
+ * their replies but is no longer listed. */
export function threadSummaries(state: SuperTabState, group: Conversation, rows: ThreadReply[]): ThreadSummary[] {
const reads = new Map<string, boolean>()
const readable = (author: Pick<Author, 'kind' | 'id'>) => author.kind !== 'person' || (reads.get(author.id)
?? reads.set(author.id, canReadGroup(state, { kind: 'person', userId: author.id, email: '' }, group)).get(author.id)!)
const threads = new Map<string, ThreadReply[]>()
- for (const row of rows) if (!row.agentOnly) threads.set(row.thread, [...threads.get(row.thread) ?? [], row])
+ for (const row of rows) {
+ if (row.agentOnly) continue
+ const thread = threads.get(row.thread)
+ if (thread) thread.push(row)
+ else threads.set(row.thread, [row])
+ }
return [...threads].flatMap(([id, thread]) => {
const replies = thread.filter(row => row.id !== id)
const last = replies.at(-1)
@@ -30,6 +36,6 @@ export function threadSummaries(state: SuperTabState, group: Conversation, rows:
.filter(person => readable({ kind: 'person', id: person }))
const authors = [...new Map(replies.toReversed().map(row => [`${row.author.kind}:${row.author.id}`, row.author])).values()]
.filter(readable).slice(0, 3)
- return [{ id, replies: replies.length, lastSequence: last.sequence, lastAt: last.createdAt, authors, people }]
+ return [{ id, replies: replies.reduce((sum, row) => sum + (row.count ?? 1), 0), lastSequence: last.sequence, lastAt: last.createdAt, authors, people }]
})
}
diff --git a/cli/src/superTabs/capacity.ts b/cli/src/superTabs/capacity.ts
index 0ca827937..ca5e6227a 100644
--- a/cli/src/superTabs/capacity.ts
+++ b/cli/src/superTabs/capacity.ts
@@ -102,6 +102,9 @@ export function quotaOf(reply: Json, engine: string, customAccount: boolean) {
}
return { known: windows.length > 0, account: typeof reading?.account === 'string' ? reading.account : null, windows }
}
+/** Said of an engine in a Harness Team account that spends its owner's subscription through the owner's relay: the
+ * route reads that subscription's allowance from the owner's Mac (routeCommand.ts), matching this exact sentence. */
+export const RELAYED_QUOTA = "This account runs on its owner's subscription; its allowance is read on the owner's machine."
const VENDOR: Record<string, string> = { claude: 'Anthropic', codex: 'OpenAI' }
/** Why [engine]'s allowance could not be read from the account reader's [reply], or null when it was. Words only: no
* account, token or plan. [relayed]: a Harness Team account, whose engines spend the owner's subscription through the
@@ -112,7 +115,7 @@ export function quotaUnknownReason(reply: Json, engine: string, relayed: boolean
const vendor = VENDOR[engine] ?? 'The vendor'
if (!reading) return 'The allowance reader on this machine did not answer.'
if (reading.outcome === 'signedOut') {
- if (relayed) return "This account runs on its owner's subscription; its allowance is read on the owner's machine."
+ if (relayed) return RELAYED_QUOTA
return typeof reading.message === 'string' && /expired/i.test(reading.message)
? 'The stored sign-in has expired; it renews the next time the engine runs here.'
: 'No subscription sign-in is stored on this machine.'
diff --git a/cli/src/superTabs/retention.ts b/cli/src/superTabs/retention.ts
index 0261d8263..dd69389c4 100644
--- a/cli/src/superTabs/retention.ts
+++ b/cli/src/superTabs/retention.ts
@@ -58,7 +58,10 @@ export function mayBeLead(dataDir: string, agentId: string): boolean {
/** Whether a close may reach a Buddy, for the core's close guard. Like `mayBeLead`, a file that cannot be read may name
* anyone until the host's next roster rewrites it; with no file, or one from before Buddies were kept, none is. Unlike a
- * Lead, a Buddy lapses with a roster nobody confirms for a week, as every other member does. */
+ * Lead, a Buddy lapses with a roster nobody confirms for a week, as every other member does.
+ * So protection lasts up to 7 days (`RETENTION_LAPSE_MS`) after the last roster this host read: while the roster cannot
+ * be read (offline, signed out, or this file unreadable), a Buddy, or anyone when the file is unreadable, stays
+ * protected until then, and a close stops it again after that. Stop Harness stops it throughout. */
export function mayBeBuddy(dataDir: string, agentId: string, now = Date.now()): boolean {
const file = retentionFile(dataDir)
if (!existsSync(file) || now - statSync(file).mtimeMs > RETENTION_LAPSE_MS) return false
diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.ts
index 91026622d..8ff588bed 100644
--- a/cli/src/superTabs/route.spec.ts
+++ b/cli/src/superTabs/route.spec.ts
@@ -75,7 +75,7 @@ describe('quota and rates', () => {
describe('choose', () => {
it('returns NO_CANDIDATE with reasons when nothing can run', () => {
expect(choose([probe({ refusals: ['Machine is offline.'] })], policy, a())).toEqual({ error: 'NO_CANDIDATE',
- excluded: [{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Machine is offline.' }] })
+ excluded: [{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Machine is offline.', machine: 'remote-1' }] })
})
it('shows only floor-meeting candidates, ordered by effective cost, quality, room on the tightest window, member first', () => {
const r = choose([
@@ -102,7 +102,7 @@ describe('choose', () => {
const r = ok(choose([probe({ quality: 1 }), probe({ quality: 1, machineName: 'mac', quota: windows([90, null], [90, null]) })], policy, a({ difficulty: 'high' }), NOW))
expect(r.belowFloor).toBe(true)
expect(r.shown.map(s => s.fit.status)).toEqual(['fits'])
- expect(r.excluded).toEqual([{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Its quota could not be read in full, and another candidate\'s quota fits this task.' }])
+ expect(r.excluded).toEqual([{ title: 'New agent · Claude sonnet medium · remote-1', reason: 'Its quota could not be read in full, and another candidate\'s quota fits this task.', machine: 'remote-1' }])
// Under the reserve is short, and goes after a candidate that is only partly known.
const reserve = ok(choose([probe({ quota: windows([10, null], [90, null]) }), probe({ machineName: 'mac', quota: windows([90, null], null) })], policy, a(), NOW))
expect(reserve.shown.map(s => [s.machineName, s.fit.status])).toEqual([['mac', 'unknown']])
@@ -140,7 +140,7 @@ describe('strength, fit and effective cost', () => {
const r = route([on(OPUS, 'a', windows([25, 4 * H], [80, 5 * D], 'A')), on(CODEX, 'a', windows([85, 3 * H], [80, 5 * D]))], { difficulty: 'high', size: 'large' })
expect(picks(r)).toEqual(['default on a'])
expect(r.shown[0].fit.account).toBe('a:codex')
- expect(r.excluded).toEqual([{ title: 'New agent · Claude opus high · a', reason: 'The 5-hour window is expected to run out about a quarter of the way in; resets in 4h.' }])
+ expect(r.excluded).toEqual([{ title: 'New agent · Claude opus high · a', reason: 'The 5-hour window is expected to run out about a quarter of the way in; resets in 4h.', machine: 'a' }])
})
it('3. low, small: Haiku on the account whose weekly window has room, not on the one nearly spent for the week', () => {
const A = windows([80, 4 * H], [12, 5 * D], 'A'), B = windows([60, 4 * H], [70, 5 * D], 'B')
@@ -210,7 +210,7 @@ describe('strength, fit and effective cost', () => {
expect(metered).toEqual({ known: true, leftPercent: null, resetsAt: null, metered: true })
const r = route([on(SONNET, 'key', metered), on(SONNET, 'sub', windows([90, 3 * H], [80, 5 * D], 'S')), on(SONNET, 'unread', unknown)], { difficulty: 'low' })
expect(r.shown.map(s => [s.machineName, s.fit.status])).toEqual([['sub', 'fits'], ['key', 'fits']])
- expect(r.excluded).toEqual([{ title: 'New agent · Claude sonnet medium · unread', reason: 'Its quota could not be read in full, and another candidate\'s quota fits this task.' }])
+ expect(r.excluded).toEqual([{ title: 'New agent · Claude sonnet medium · unread', reason: 'Its quota could not be read in full, and another candidate\'s quota fits this task.', machine: 'unread' }])
expect(r.shown[1].fit).toEqual({ status: 'fits', coverage: null, effectiveCost: 2, expiring: 0, spend: { '5-hour': 30, weekly: 4 }, account: 'key:claude' })
expect(r.shown[1].label).toContain('fits: metered, no usage window to run out')
expect(r.shown[1].label).toContain('quota metered')
@@ -472,7 +472,7 @@ describe('the owner\'s rules', () => {
it('leaves out a candidate that breaks a hard rule, with the owner\'s words as the reason', () => {
const r = ok(choose([haiku, sonnet], policy, a(), NOW, [], [rule({ kind: 'forbidModel', model: 'HAIKU' }, 'No Haiku.')]))
expect(r.shown.map(s => s.machineName)).toEqual(['mac'])
- expect(r.excluded).toEqual([{ title: 'New agent · Claude haiku auto · cheap', reason: 'Breaks the owner\'s rule: No Haiku.' }])
+ expect(r.excluded).toEqual([{ title: 'New agent · Claude haiku auto · cheap', reason: 'Breaks the owner\'s rule: No Haiku.', machine: 'cheap' }])
// A full model id is caught too, a rule for another engine is not, and `default` is never matched.
expect(breaks([rule({ kind: 'forbidModel', model: 'haiku' })], { machineId: 'm', engine: 'claude', model: 'claude-haiku-4-5', effort: 'high' })).toContain('Rule.')
expect(breaks([rule({ kind: 'forbidModel', engine: 'codex', model: 'haiku' })], { machineId: 'm', engine: 'claude', model: 'haiku', effort: 'high' })).toBeNull()
@@ -486,7 +486,7 @@ describe('the owner\'s rules', () => {
expect(titles(r)).toEqual(['New agent · Claude sonnet medium · other'])
// When nobody is left, the Lead is told why each one was left out.
expect(choose([sonnet], policy, a(), NOW, [], [rule({ kind: 'machines', machineIds: ['m9'] }, 'Only m9.')]))
- .toEqual({ error: 'NO_CANDIDATE', excluded: [{ title: 'New agent · Claude sonnet medium · mac', reason: 'Breaks the owner\'s rule: Only m9.' }] })
+ .toEqual({ error: 'NO_CANDIDATE', excluded: [{ title: 'New agent · Claude sonnet medium · mac', reason: 'Breaks the owner\'s rule: Only m9.', machine: 'mac' }] })
})
it('holds a minimum effort, and lifts a new agent whose effort the engine chooses to that minimum', () => {
const codex = probe({ machineName: 'box', engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2 })
@@ -673,7 +673,7 @@ describe('local models on the Swarm\'s grid', () => {
// With no Reviewer of another engine anywhere, the Builder's own engine reviews at its top tier only (Lead, 2026-10-29).
expect(reviewRefusals(probe({ model: 'opus', quality: 3 }), { engine: 'claude' }, false)).toEqual([])
expect(reviewRefusals(probe(), { engine: 'claude' }, false))
- .toEqual(['A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can run in this Swarm.'])
+ .toEqual(['A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.'])
})
it('says why a named model the Swarm has is never offered to Builders, rather than to share it', () => {
diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.ts
index b4b19365e..c159dd618 100644
--- a/cli/src/superTabs/route.ts
+++ b/cli/src/superTabs/route.ts
@@ -35,7 +35,10 @@ export interface QuotaWindow { name: string | null; leftPercent: number; resetsA
* usage window to run out. */
export interface Quota { known: boolean; leftPercent: number | null; resetsAt: number | null; windows?: QuotaWindow[]; account?: string; metered?: true
/** Why an unknown allowance could not be read, as its machine said (cli superTabs/capacity.ts quotaUnknownReason). */
- why?: string }
+ why?: string
+ /** The machine this reading is from, when it is not the candidate's own: a Harness Team account's Mac, whose subscription
+ * the account spends (routeCommand.ts relayedReadings). */
+ from?: string }
/** The task's folder as the Lead's machine sees it. `unknown` means it could not be read, `none` that it is not a repository,
* `missing` that the Lead's machine has no such folder (a member elsewhere may). */
export interface TaskFolder { cwd: string; kind: 'git' | 'none' | 'missing' | 'unknown'; name: string | null; root: string | null; remote: string | null }
@@ -50,6 +53,9 @@ export interface Probe {
/** Members: the frame (null when it could not be read), whether the member is in the task's repository, and its earlier work in this Super Tab. */
frame?: MemberFrame | null; repo?: 'same' | 'different' | 'unknown'; earlier?: Array<{ group: string; outcome: string }>
terminalUnverified?: boolean
+ /** Why no agent of its engine starts on its machine within REVIEW_START_MS, whatever its quota: offline, paused, signed out,
+ * suspended, or a member held by a usage limit past it. Read by [otherFamilyReviews]. */
+ cannotStart?: string
/** New agents: what the machine has. */
load?: MachineLoad
/** A new agent on a model served on the Swarm's grid: free, reached through the grid relay, `model`/`effort` `default`.
@@ -65,7 +71,9 @@ export interface Fit { status: 'fits' | 'unknown' | 'short'; coverage: number |
export interface Commitment { account: string; spend: Partial<Record<Window, number>>; size: Size; createdAt: number }
export interface Shown extends Probe { id: string; title: string; label: string; fit: Fit }
/** `short` is set when no candidate is expected to cover the task, to tell the Lead. */
-export interface Choice { shown: Shown[]; excluded: Array<{ title: string; reason: string }>; floor: number; belowFloor: boolean; short?: string
+/** A candidate left out and why; [machine] names its machine, absent for a model that is not offered anywhere. */
+export interface Excluded { title: string; reason: string; machine?: string }
+export interface Choice { shown: Shown[]; excluded: Excluded[]; floor: number; belowFloor: boolean; short?: string
/** Every candidate left runs on an account the route was asked to avoid (`choose` `avoid`). */
avoided?: string }
export interface Verdict { pick: Shown; via: 'order' | 'only'; p: null; why: string }
@@ -237,14 +245,32 @@ export function reviewRefusals(p: Probe, builder: Reviewed | null, otherFamily:
if (p.quality < 2) return [`A review needs a model of quality 2 or more, and ${ENGINE[p.engine]} ${p.model} is ${p.quality}.`]
if (!builder || familyOf(builder) !== familyOf(p)) return []
if (otherFamily) return [`A review runs on another engine than the reviewed Builder's, ${ENGINE[p.engine]}.`]
- return p.quality < 3 ? [`A review on the reviewed Builder's engine, ${ENGINE[p.engine]}, needs its top tier (quality 3): no Reviewer on another engine can run in this Swarm.`] : []
+ return p.quality < 3 ? [`A review on the reviewed Builder's engine, ${ENGINE[p.engine]}, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.`] : []
}
-/** Whether a strong Reviewer of another family than [builder]'s can run: a candidate off the grid, rated 2 or more, of
- * another family, that the owner's [rules] let run at the effort it would start at. Busy, offline or short of quota it
- * still counts, within its start window; the caller leaves out the machines the task or its access rules out (review of
- * ee4ee6c9a: an engine the owner ruled out blocked the fallback). */
-export const otherFamilyReviews = (probes: Probe[], builder: Reviewed | null, rules: SwarmRule[]) =>
- !!builder && probes.some(p => !p.gridModel && p.quality >= 2 && familyOf(p) !== familyOf(builder) && !breaks(rules, lifted(rules, p)))
+/** How soon a Reviewer has to be able to start to count: a start still not running after this long is abandoned (backend
+ * superTabs/store.ts ABANDONED_START_MS). A window that resets inside it counts as quota; one out for longer does not (backend
+ * superTabs/reviewSeats.ts REVIEW_START_MS). */
+export const REVIEW_START_MS = 15 * 60_000
+/** How the route line and the brief of a review on its Builder's own engine start (Lead, 2026-10-30; backend superTabs/rules.ts). */
+export const SAME_ENGINE = 'same-engine review: no Reviewer of another engine has quota'
+/** Whether [q] has quota now, or once each used-up window resets within REVIEW_START_MS. One it cannot read, or metered, does,
+ * as a start there does. */
+export function quotaWithin(q: Quota, now: number): boolean {
+ if (!q.known || q.metered) return true
+ const soon = (resetsAt: number | null) => resetsAt !== null && resetsAt - now <= REVIEW_START_MS
+ return q.windows?.length ? q.windows.every(w => w.leftPercent > 0 || soon(w.resetsAt)) : q.leftPercent === null || q.leftPercent > 0 || soon(q.resetsAt)
+}
+/** Whether a strong Reviewer of another family than [builder]'s could start within REVIEW_START_MS: a candidate off the grid,
+ * rated 2 or more, of another family, that the owner's [rules] let run at the effort it would start at, whose machine is up
+ * ([Probe.cannotStart]) with quota now or once a window resets inside the window. Busy still counts: a Reviewer frees up. One
+ * out of quota for days or offline does not (2026-10-30: reviews of Claude builds waited all morning on Codex machines out of
+ * weekly quota); the caller leaves out the machines the task or its access rules out (review of ee4ee6c9a: an engine the
+ * owner ruled out blocked the fallback). */
+export const otherFamilyReviews = (probes: Probe[], builder: Reviewed | null, rules: SwarmRule[], now: number = Date.now()) =>
+ !!builder && probes.some(p => !p.gridModel && p.quality >= 2 && familyOf(p) !== familyOf(builder) && !p.cannotStart && quotaWithin(p.quota, now)
+ && !breaks(rules, lifted(rules, p)))
+/** Whether [p] reviews on [builder]'s own model family. */
+export const sameFamily = (p: Probe, builder: Reviewed | null) => !!builder && familyOf(builder) === familyOf(p)
/** A task that stepped up from a cheaper model takes no grid model and nothing below the step's floor; the server refuses
* the same (backend superTabs/stepUp.ts stepUpRefusal). */
@@ -301,6 +327,7 @@ const resetsIn = (resetsAt: number, now: number) => span(Math.max(0, resetsAt -
function quotaText(q: Quota, now: number): string {
if (q.metered) return 'quota metered'
if (!q.known || q.leftPercent === null) return q.why ? `quota unknown (${q.why})` : 'quota unknown'
+ if (q.from) return `quota read on ${cut(q.from, 40)}, whose subscription this account spends: ${quotaText({ ...q, from: undefined }, now).replace(/^quota /, '')}`
if (q.windows?.length) {
return `quota ${q.windows.map(w => `${w.name ?? 'window'} ${Math.round(w.leftPercent)}% left${w.resetsAt === null ? '' : ` (resets in ${resetsIn(w.resetsAt, now)})`}`).join(', ')}`
}
@@ -420,7 +447,7 @@ function withEveryMachine<T extends { machineId: string }>(ranked: T[]): T[] {
/** `avoid`: accounts of agents that lost this task (a review's Reviewer whose model kept failing): any other account goes first. */
export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now(), open: Commitment[] = [], rules: SwarmRule[] = [], held: HeldModel[] = [],
- avoid: string[] = []): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {
+ avoid: string[] = []): Choice | { error: 'NO_CANDIDATE'; excluded: Excluded[] } {
// A lifted row can equal another row on the same machine (Codex `default` lifted to high beside Codex high); one is kept.
// A person asking for a local model considers local models alone, whatever their strength.
if (a.local) probes = probes.filter(p => p.gridModel)
@@ -430,7 +457,7 @@ export function choose(probes: Probe[], policy: Policy, a: Assessment, now: numb
const raised = probes.map(p => lifted(rules, p)), key = (p: Probe) => `${p.kind}\0${p.machineId}\0${p.engine}\0${p.model}\0${p.effort}\0${p.gridModel ?? ''}`
const ruled = raised.filter((p, i) => p === probes[i] || !raised.some((q, j) => j !== i && key(q) === key(p) && (q === probes[j] || j < i)))
.map(p => { const why = breaks(rules, p); return why ? { ...p, refusals: [...p.refusals, why] } : p })
- const excluded = ruled.filter(p => p.refusals.length).map(p => ({ title: titleOf(p), reason: p.refusals.join(' ') }))
+ const excluded: Excluded[] = ruled.filter(p => p.refusals.length).map(p => ({ title: titleOf(p), reason: p.refusals.join(' '), machine: p.machineName }))
const viable = ruled.filter(p => !p.refusals.length)
// Nothing offered: a model that is served but taken says who has it, rather than reading as unshared.
const heldNamed = named ? held.filter(m => words(named).every(w => words(`${m.model} ${m.label}`).join('').includes(w))) : []
@@ -451,10 +478,10 @@ export function choose(probes: Probe[], policy: Policy, a: Assessment, now: numb
// An account whose model kept failing this task waits while any other account is offered.
const fresh = strongest.filter(p => !avoid.includes(p.fit.account))
const sized = fresh.length ? fresh : strongest
- if (fresh.length) excluded.push(...strongest.filter(p => !fresh.includes(p)).map(p => ({ title: titleOf(p), reason: AVOIDED })))
+ if (fresh.length) excluded.push(...strongest.filter(p => !fresh.includes(p)).map(p => ({ title: titleOf(p), reason: AVOIDED, machine: p.machineName })))
// Only the first group that has anyone is shown: those that fit, then those whose quota is not fully known, then the short.
const status = (['fits', 'unknown', 'short'] as const).find(s => sized.some(p => p.fit.status === s))!
- excluded.push(...sized.filter(p => p.fit.status !== status).map(p => ({ title: titleOf(p), reason: p.fit.status === 'unknown' ? UNREAD : runsOut(p.tight!) })))
+ excluded.push(...sized.filter(p => p.fit.status !== status).map(p => ({ title: titleOf(p), reason: p.fit.status === 'unknown' ? UNREAD : runsOut(p.tight!), machine: p.machineName })))
// When every candidate is short, the one expected to get furthest goes first.
const soft = softOf(rules, a)
const set = sized.filter(p => p.fit.status === status).sort((x, y) => status === 'short' ? y.fit.coverage! - x.fit.coverage! || compare(x, y, soft) : compare(x, y, soft))
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 514f3f257..9725e67da 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { heldLocalModels, localProbes, NO_SWARM_AGENTS_ON, offlineModels, routeTask, STALL_RETRY_MS, stalled } from './routeCommand.js'
import type { describeScmProject } from '../scm/scmProjects.js'
-import { admission, quotaOf } from './capacity.js'
+import { admission, quotaOf, RELAYED_QUOTA } from './capacity.js'
import type { Assessment, Policy, Probe } from './route.js'
const policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: '', models: [
@@ -264,7 +264,7 @@ describe('routeTask', () => {
const s = scoped({ tab: t })
expect(await routeTask(input, s, where as never, opener(), () => 'op')).toMatchObject({ ok: true, pick: { kind: 'new', engine: 'claude', model: 'opus' } })
expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([{ title: 'Multiply · Claude sonnet medium · remote-1',
- reason: 'A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can run in this Swarm.' }]))
+ reason: 'A review on the reviewed Builder\'s engine, Claude, needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.' }]))
// A Builder still in the Swarm is read from its agent: on a grid model, Claude may review it.
t.state.agents.push({ id: 'b1', name: 'Kimi', machineId: 'm1', harnessId: 'hb', configuration: { engine: 'claude', model: 'default', effort: 'default' }, gridModel: 'moonshotai/kimi-k3' } as never)
Object.assign(t.state.conversations[2]!, { assignment: { id: 'b', agentId: 'b1', status: 'review' } })
@@ -294,6 +294,58 @@ describe('routeTask', () => {
expect(await routeWith(pool('m2', ['codex'], { contributorId: 'mate', teamWork: { allowed: false, code: 'TEAM_ACCOUNT_REQUIRED', reason: 'Not a Team machine.' } })))
.toMatchObject({ ok: true, pick: { engine: 'claude', model: 'opus', machineId: 'm1' } })
})
+ // 2026-10-30: every Codex Reviewer was out of weekly quota for days, yet Claude builds' top-tier Claude reviews were refused
+ // because Codex machines existed; reviews waited all morning (Tony). Another engine counts only where a Reviewer could start
+ // within the start window: on an allowed machine, online, with quota now or once a window resets inside it.
+ describe('a review on its Builder\'s own engine when no Reviewer of another engine could start soon', () => {
+ const DAY = 86_400_000, MIN = 60_000
+ const pool = (machineId: string, engines: string[], weekly: { usedPercent: number; resetsIn: number } = { usedPercent: 10, resetsIn: 5 * DAY }, patch: Record<string, unknown> = {}) => ({
+ machineId, name: machineId, cwd: '/w', engines, paused: false, contributorId: 'owner',
+ observation: { receivedAt: Date.now(), resources: { memoryTotalBytes: 32e9, memoryUsedBytes: 2e9, projectDiskFreeBytes: 200e9 }, tools: { git: true }, runningHarnessIds: [],
+ quotas: engines.map(engine => ({ engine, known: true, windows: [{ name: '5-hour', usedPercent: 20, resetsAt: Date.now() + 3600000 },
+ { name: 'weekly', usedPercent: engine === 'codex' ? weekly.usedPercent : 10, resetsAt: Date.now() + (engine === 'codex' ? weekly.resetsIn : 5 * DAY) }] })) }, ...patch })
+ const both = { ...policy, models: policy.models.map(m => ({ ...m, enabled: true })) }
+ const routeWith = async (codexBox: Record<string, unknown>, rules: unknown[] = []) => {
+ const t = tab(); t.state.agents = [agents[1]] as never
+ t.state.conversations.push({ id: 'g0', title: 'Built', leadId: 'lead', agentIds: ['lead'], archived: false, brief: '', checks: [],
+ assignment: { id: 'b', agentId: 'gone', status: 'review', configuration: { engine: 'claude' } } } as never)
+ Object.assign(t.state.conversations[1]!, { reviewOf: 'g0' })
+ Object.assign(t.state, { machines: [pool('m1', ['claude']), codexBox], rules })
+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: t, policy: { policy: both, warnings: [] }, machines: [] } } })
+ const result = await routeTask(input, s, where as never, opener(), () => 'op')
+ return { result, decision: 'error' in result ? null : recorded(s).command.decision }
+ }
+ const sameEngine = { ok: true, pick: { engine: 'claude', model: 'opus', machineId: 'm1' }, why: expect.stringMatching(/^same-engine review: no Reviewer of another engine has quota\. /) }
+
+ it('lets Claude Opus review a Claude build while Codex is out of quota for days, and its route line says why', async () => {
+ const { result, decision } = await routeWith(pool('m2', ['codex'], { usedPercent: 100, resetsIn: 3 * DAY }))
+ expect(result).toMatchObject(sameEngine)
+ expect(decision.why).toMatch(/^same-engine review: no Reviewer of another engine has quota\. /)
+ // Still never below the top tier.
+ expect(decision.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ title: expect.stringContaining('Claude sonnet'),
+ reason: expect.stringContaining('needs its top tier (quality 3): no Reviewer on another engine can start soon in this Swarm.') })]))
+ })
+
+ it('still refuses Claude while Codex resets inside the start window, so the review waits for it', async () => {
+ const { result } = await routeWith(pool('m2', ['codex'], { usedPercent: 100, resetsIn: 10 * MIN }))
+ expect(result).toMatchObject({ error: 'NO_CANDIDATE' })
+ expect((result as { excluded: Array<{ title: string; reason: string }> }).excluded).toEqual(expect.arrayContaining([
+ expect.objectContaining({ title: expect.stringContaining('Claude opus'), reason: 'A review runs on another engine than the reviewed Builder\'s, Claude.' })]))
+ // And with quota now, Codex reviews.
+ expect((await routeWith(pool('m2', ['codex']))).result).toMatchObject({ ok: true, pick: { engine: 'codex', machineId: 'm2' } })
+ })
+
+ it('lets Claude review when Codex runs only on a machine the owner left out, or one that is offline or signed out', async () => {
+ const ownersMachines = [{ id: 'r1', rule: { kind: 'machines', machineIds: ['m1'] }, text: 'Only m1.' }]
+ expect((await routeWith(pool('m2', ['codex']), ownersMachines)).result).toMatchObject(sameEngine)
+ const offline = pool('m2', ['codex']); (offline.observation as { receivedAt: number }).receivedAt = Date.now() - 10 * MIN
+ expect((await routeWith(offline)).result).toMatchObject(sameEngine)
+ const signedOut = pool('m2', ['codex']); Object.assign(signedOut.observation, { readiness: { engines: [{ engine: 'codex', installed: true, signedIn: false }] } })
+ expect((await routeWith(signedOut)).result).toMatchObject(sameEngine)
+ // Paused by its owner, as the server reads it (backend superTabs/reviewSeats.ts; review of #2275).
+ expect((await routeWith(pool('m2', ['codex'], undefined, { paused: true }))).result).toMatchObject(sameEngine)
+ })
+ })
it('tells the Lead how to assign a member or start a new agent with the decision', async () => {
const member = await routeTask(input, scoped(), where as never, opener(), () => 'op')
// Cheapest first: the member on sonnet.
@@ -1296,6 +1348,67 @@ describe('routing contributed capacity', () => {
const rules = [{ id: 'r1', projectId: 'lead', rule: { kind: 'machines', machineIds: ['m1'] }, text: 'Only the MacBook Pro.' }]
expect((await route('owner', undefined, rules)).answer).toMatchObject({ ok: true, pick: { machineId: 'm1-team' } })
})
+
+ // 2026-10-30 overnight: Codex in Tony's team account was never offered for reviews. The account spends Tony's own
+ // subscription through the relay, so it reads its quota as unknown, and the route dropped every unknown candidate while
+ // another machine's quota fit. The Mac's own reading is that subscription's.
+ describe('a team account that spends its Mac\'s subscription through the relay', () => {
+ const relayed = (why = RELAYED_QUOTA) => ({ ...team(), observation: { ...team().observation, quotas: [{ engine: 'claude', known: false, windows: [] }],
+ quotaReasons: { claude: why } } })
+ // Full readings, both windows, as every Claude account reports them.
+ const full = <T extends ReturnType<typeof healthy>>(pool: T): T => ({ ...pool, observation: { ...pool.observation, quotas: [{ engine: 'claude', known: true,
+ windows: [{ name: '5-hour', usedPercent: 20, resetsAt: Date.now() + 3_600_000 }, { name: 'weekly', usedPercent: 30, resetsAt: Date.now() + 4 * 86_400_000 }] }] } })
+ const fullMac = () => full(mac())
+ // Another machine whose quota fits, as MacBookPro2021's Codex read that night.
+ const other = () => full({ ...healthy(), machineId: 'm9', name: 'Other Mac', scope: 'swarm', cwd: '/other/swarm', contributorId: 'owner' })
+ const fit = (s: ReturnType<typeof scoped>, machineId: string) =>
+ (recorded(s).command.decision.candidates as Array<{ machineId: string; kind: string; label: string; fit: { status: string; account: string } }>)
+ .find(c => c.machineId === machineId && c.kind === 'new')
+ async function routeWith(machines: Record<string, unknown>[]) {
+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: { state: { id: 'tab', agents: [agents[1]], conversations: conversations(), machines,
+ projects: [{ id: 'lead', ownerId: 'owner', repository: { repositoryUrl: 'https://github.com/example/project' } }] } },
+ policy: { policy, warnings: [] }, machines: [] } } })
+ return { answer: await routeTask(input, s, where, opener()), s }
+ }
+
+ it('reads the Mac\'s quota for it, on the Mac\'s account, and says so in its line', async () => {
+ const { s } = await routeWith([fullMac(), relayed(), other()])
+ const row = fit(s, 'm1-team')
+ expect(row).toMatchObject({ fit: { status: 'fits', account: 'm1:claude' } })
+ expect(row!.label).toContain('quota read on MacBook Pro, whose subscription this account spends')
+ expect(row!.label).toContain('5-hour 80% left')
+ expect(recorded(s).command.decision.excluded).not.toEqual(expect.arrayContaining([expect.objectContaining({ title: expect.stringContaining('MacBook Pro') })]))
+ })
+
+ it('keeps the quota unknown when the account says it cannot read it for another reason', async () => {
+ const { s } = await routeWith([fullMac(), relayed('The allowance reader on this machine did not answer.'), other()])
+ expect(fit(s, 'm1-team')).toBeUndefined()
+ expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ title: 'New agent · Claude opus high · MacBook Pro',
+ reason: expect.stringContaining('could not be read in full') })]))
+ })
+
+ // The decision kept its exclusions, but the Lead's answer showed none, so nobody saw why the Mac was never offered.
+ it('tells the Lead each machine it left out and why, whether it picked another or found none', async () => {
+ const reason = 'The Harness Team account on MacBook Pro is not private (gitconfig: it could read its owner\'s ~/.gitconfig), so it runs only its owner\'s projects.'
+ const refused = { ...relayed(), teamWork: { allowed: false, code: 'PRIVACY_CHECK_FAILED', reason } }
+ const picked = await routeWith([fullMac(), refused, other()])
+ expect(picked.answer).toMatchObject({ ok: true, pick: { machineId: 'm9' } })
+ expect(picked.answer.leftOut).toEqual([{ machine: 'MacBook Pro', reasons: [reason] }])
+ const none = await routeWith([fullMac(), refused])
+ expect(none.answer).toMatchObject({ error: 'NO_CANDIDATE' })
+ expect(none.answer.leftOut).toEqual(expect.arrayContaining([{ machine: 'MacBook Pro', reasons: [reason] }]))
+ // A machine with a row offered is not left out, though its other rows were.
+ expect((await routeWith([fullMac(), relayed(), other()])).answer.leftOut).toEqual([])
+ })
+
+ it('borrows nothing from a Mac whose reading is stale or that another person contributed', async () => {
+ const stale = fullMac(); stale.observation = { ...stale.observation, receivedAt: 0 }
+ for (const host of [stale, { ...fullMac(), contributorId: 'someone-else' }]) {
+ const { s } = await routeWith([host, relayed(), other()])
+ expect(fit(s, 'm1-team')).toBeUndefined()
+ }
+ })
+ })
})
it('refuses unobserved tools and devices, without probing arbitrary paths on a teammate computer', async () => {
expect((await runPool(healthy(), false, { tools: ['docker'], devices: ['/dev/fixture'] })).answer.ok).not.toBe(true)
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index de261fd46..7d5fd6eb9 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -4,10 +4,10 @@
* and records the decision in the tab. */
import { randomUUID } from 'node:crypto'
import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'
-import { requiredToolReason, startRequirements } from './capacity.js'
+import { RELAYED_QUOTA, requiredToolReason, startRequirements } from './capacity.js'
import { inspectCapacity, type ScopedRequest } from './start.js'
import { ENDED_WORK, object, within } from './wire.js'
-import { accountOf, API_BUILDERS, choose, decide, gridQuality, parseAssessment, quotaOf2, rateFor, recordOf, otherFamilyReviews, repoMatch, repositoryKey, reviewRefusals, stepUpRefusals, type Assessment, type Reviewed, type RecordShape, type Commitment, type HeldModel, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'
+import { accountOf, API_BUILDERS, choose, decide, gridQuality, parseAssessment, quotaOf2, rateFor, recordOf, otherFamilyReviews, repoMatch, repositoryKey, REVIEW_START_MS, reviewRefusals, SAME_ENGINE, sameFamily, stepUpRefusals, type Assessment, type Reviewed, type RecordShape, type Commitment, type Excluded, type HeldModel, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'
import { stat } from 'node:fs/promises'
import { describeScmProject } from '../scm/scmProjects.js'
@@ -98,6 +98,19 @@ export function unreadyPool(pool: Json, project: Json | undefined, projectId: st
const app = githubApp && projectOwner !== pool.contributorId
return { all, engines, push: needsPush && !app && checkout?.push === false ? NO_PUSH : null }
}
+/** A Harness Team account's engines that spend its Mac owner's subscription through the owner's relay, each with the Mac's
+ * fresh reading of that subscription: the account itself holds no sign-in to read, so it reports its allowance unknown,
+ * and the route left out every such candidate while another machine's quota fit. Codex in Tony's team account was never
+ * offered for reviews on 2026-10-30 overnight, while all other Codex reviewers were out of quota. Only an engine the
+ * account says is relayed (capacity.ts RELAYED_QUOTA), and only from its own Mac under the same contribution. */
+export function relayedReadings(pool: Json, pools: Json[], now = Date.now()): { relayedQuotas?: Record<string, Json> } {
+ const host = typeof pool.hostMachineId === 'string' ? pools.find(m => m.machineId === pool.hostMachineId && m.contributorId === pool.contributorId) : undefined
+ const reading = object(host?.observation), reasons = object(object(pool.observation).quotaReasons)
+ if (!host || !finite(reading.receivedAt) || now - reading.receivedAt >= 45_000) return {}
+ const relayed = Object.fromEntries(list(reading.quotas).filter(q => q.known === true && reasons[String(q.engine)] === RELAYED_QUOTA)
+ .map(q => [String(q.engine), { quota: q, from: String(host.name), account: `${String(host.machineId)}:${String(q.engine)}` }]))
+ return Object.keys(relayed).length ? { relayedQuotas: relayed } : {}
+}
/** A running member keeps its engine and memory, but still needs a live terminal, account allowance and the task's tools. */
function memberRefusals(running: boolean | null, quota: Probe['quota'], tools: string[], devices: string[], reportedTools: Json, reportedDevices: Json, toolProbeErrors: Json): string[] {
return [
@@ -245,6 +258,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
...(original.scope !== 'swarm' && projectId !== 'lead' ? { projectUnavailable: true } : {}),
...(original.scope === 'swarm' && repository.machineId !== original.machineId && typeof repository.repositoryUrl !== 'string'
? { repositoryUnavailable: true } : {}),
+ ...relayedReadings(original, list(state.machines)),
}
machines.set(String(pool.machineId), { name: String(pool.name), status: 'contributed', account: false, pool,
unready: unreadyPool(original, project, projectId, !review, object(value.tab).githubApp === true, projectOwner) })
@@ -291,8 +305,11 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// The backend writes the mark with its loss's reason (backend superTabs/liveness.ts loseTask).
return marked ? [`It lost its last task (${String(object(marked).reason)}). It takes work again once a person assigns it by hand or the Lead replaces it.`] : []
}
- const probes = probed.flat().map(p => p.kind === 'member' ? { ...p, repo: repoMatch(folder, p.frame ?? null, p.machineId === where.machineId),
- refusals: [...p.refusals, ...limited(p.agentId), ...lostTask(p.agentId)],
+ // A member held by a usage limit past the start window, or anything on a machine that is offline, starts nothing soon.
+ const heldPast = (agentId: string | undefined) => Date.parse(String(members.find(m => m.id === agentId)?.limitedUntil)) - Date.now() > REVIEW_START_MS
+ const probes = probed.flat().map(p => p.cannotStart || !p.refusals.includes(OFFLINE) ? p : { ...p, cannotStart: OFFLINE })
+ .map(p => p.kind === 'member' ? { ...p, repo: repoMatch(folder, p.frame ?? null, p.machineId === where.machineId),
+ refusals: [...p.refusals, ...limited(p.agentId), ...lostTask(p.agentId)], ...(!p.cannotStart && heldPast(p.agentId) ? { cannotStart: limited(p.agentId)[0] } : {}),
earlier: ended.filter(e => e.agentId === p.agentId).reverse().slice(0, 3).map(e => ({ group: e.group, outcome: e.outcome })) } : p)
probes.push(...localProbes(state, policy, probes, assessment, review))
// A Mac's Harness Team account is that Mac, as for the owner's machines rule.
@@ -308,7 +325,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
const builder = review ? reviewedBuilder(conversations.find(c => c.id === group.reviewOf), agents) : null
// Another engine counts only on a machine the task may run on, and that its access lets take this project's work.
const teamRefused = (p: Probe) => { const why = machines.get(p.machineId)?.pool?.teammatesRefused; return typeof why === 'string' && p.refusals.includes(why) }
- const otherFamily = otherFamilyReviews(probes.filter(p => !outside(p.machineId) && !teamRefused(p)), builder, rules)
+ const otherFamily = otherFamilyReviews(probes.filter(p => !outside(p.machineId) && !teamRefused(p)), builder, rules, Date.now())
const step = finite(object(group.stepUp).floor) ? { floor: object(group.stepUp).floor as number } : null
for (const [i, p] of probes.entries()) {
const refusals = [...(outside(p.machineId) ? [ELSEWHERE] : []), ...(p.kind === 'member' && !checked(p.agentId) ? [UNCHECKED_DEVICE] : []),
@@ -328,8 +345,10 @@ export async function routeTask(input: { tabId: string; conversationId: string;
const choice = choose(probes, policy, assessment, Date.now(), working, rules, heldLocalModels(state), avoid)
choice.excluded.push(...offlineModels(state, policy, assessment, review))
// The task stays in the Lead's queue rather than going where it cannot be done.
- if ('error' in choice) return required.machines || required.devices.length ? { ...choice, waiting: true, detail: WAITING } : choice
- const verdict = decide(choice)
+ if ('error' in choice) return { ...choice, leftOut: leftOut(choice.excluded, []), ...required.machines || required.devices.length ? { waiting: true, detail: WAITING } : {} }
+ const decided = decide(choice)
+ // A review on its Builder's own engine says why first (Lead, 2026-10-30); the server writes it on the decision and the brief.
+ const verdict = review && !otherFamily && sameFamily(decided.pick, builder) ? { ...decided, why: `${SAME_ENGINE}. ${decided.why}` } : decided
const operationId = `route-${newId()}`
const record = (shape: RecordShape) => scoped({ action: 'command', operationId,
command: { type: 'route.record', conversationId: input.conversationId, decision: recordOf(choice, verdict, assessment, policy, shape) } })
@@ -347,6 +366,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
ok: true, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : { unrecorded: true }),
pick: publicOf(verdict.pick), via: verdict.via, p: verdict.p, belowFloor: choice.belowFloor, why: verdict.why,
alternatives: alternativesTo(verdict.pick, choice.shown).map(publicOf),
+ leftOut: leftOut(choice.excluded, choice.shown),
warnings: [...(Array.isArray(effective.warnings) ? effective.warnings : []), ...(value.machinesUnreadable === true ? [MACHINES_UNREADABLE] : []),
...(choice.shown.some(p => p.kind === 'member' && p.terminalUnverified) ? ["A member's terminal could not be verified from its machine's snapshot. Check it before assignment."] : []),
...(choice.short ? [choice.short] : []), ...(choice.avoided ? [choice.avoided] : [])],
@@ -360,6 +380,20 @@ export async function routeTask(input: { tabId: string; conversationId: string;
}
}
+/** Each machine none of whose candidates is offered, with why, for the Lead's answer: the decision kept the exclusions, but the
+ * answer showed none, so nobody saw why Tony's Mac was never offered for reviews (2026-10-30). In the order first left out;
+ * at most [MAX_LEFT_OUT] machines and [MAX_REASONS] distinct reasons each. */
+export function leftOut(excluded: Excluded[], shown: Array<{ machineName: string }>): Array<{ machine: string; reasons: string[] }> {
+ const offered = new Set(shown.map(s => s.machineName)), out = new Map<string, Set<string>>()
+ for (const e of excluded) {
+ if (!e.machine || offered.has(e.machine)) continue
+ const reasons = out.get(e.machine) ?? out.set(e.machine, new Set()).get(e.machine)!
+ if (reasons.size < MAX_REASONS) reasons.add(e.reason.length > 300 ? `${e.reason.slice(0, 299)}…` : e.reason)
+ }
+ return [...out].slice(0, MAX_LEFT_OUT).map(([machine, reasons]) => ({ machine, reasons: [...reasons] }))
+}
+const MAX_LEFT_OUT = 20, MAX_REASONS = 4
+
/** What the reviewed group's last attempt ran on: its agent's engine and grid model while it is here, else its assignment's
* engine. Null before any attempt. */
function reviewedBuilder(reviewed: Json | undefined, agents: Json[]): Reviewed | null {
@@ -495,8 +529,16 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
const observed = object(pool.observation), resources = object(observed.resources)
const fresh = finite(observed.receivedAt) && Date.now() - observed.receivedAt < 45_000
const quotas = list(observed.quotas)
- const quota = (engine: string) => { const q = quotas.find(q => q.engine === engine); return fresh && q ? quotaOf2({ known: q.known === true, windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt, name: text(w.name) ?? undefined })),
- why: text(object(observed.quotaReasons)[engine]) }) : UNKNOWN_QUOTA }
+ const read = (q: Json, extra: { why?: string | null; account?: string } = {}) => quotaOf2({ known: q.known === true,
+ windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt, name: text(w.name) ?? undefined })), ...extra })
+ const quota = (engine: string): Probe['quota'] => {
+ const q = quotas.find(q => q.engine === engine)
+ if (!fresh || !q) return UNKNOWN_QUOTA
+ // A Harness Team account's engine on its Mac's subscription: that subscription's reading, on its account (relayedReadings).
+ const relayed = q.known !== true ? object(object(pool.relayedQuotas)[engine]) : {}
+ if (typeof relayed.from === 'string') return { ...read(object(relayed.quota), { account: String(relayed.account) }), from: relayed.from }
+ return read(q, { why: text(object(observed.quotaReasons)[engine]) })
+ }
const blocked = [...(!fresh ? [OFFLINE] : []), ...(pool.paused ? ['New work is paused on this machine.'] : [])]
const tools = object(observed.tools)
/** Work for a project its owner does not run here: a new agent runs under the contribution, a member under its own grant. */
@@ -510,18 +552,20 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
...needs.tools.map(t => requiredToolReason(t, tools[t], object(observed.toolProbeErrors)[t])).filter((reason): reason is string => reason !== null),
...(needs.devices.length ? ['Required devices have not been reported.'] : []),
...unready.all, ...(unready.push ? [unready.push] : []), ...(stuck ? [STALLED] : [])]
+ // What keeps any agent of an engine from starting here soon, whatever its quota (route.ts otherFamilyReviews).
+ const unable = (engine: string) => { const why = blocked[0] ?? unready.engines[engine]; return why ? { cannotStart: why } : {} }
return [...members.map(m => {
- const allowance = quota(String(object(m.configuration).engine))
+ const engine = String(object(m.configuration).engine), allowance = quota(engine)
const running = Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.includes(m.harnessId) : null
- return memberProbe(m, fresh ? [...memberRefusals(running, allowance, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)),
+ return { ...memberProbe(m, fresh ? [...memberRefusals(running, allowance, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)),
...teammates(m.contributorId), ...(unready.push ? [unready.push] : [])] : [OFFLINE],
- allowance, null, fresh && running === null)
+ allowance, null, fresh && running === null), ...unable(engine) }
}),
- ...models.map(m => newProbe(m, [...newReasons, ...(unready.engines[m.engine] ? [unready.engines[m.engine]!] : []),
+ ...models.map(m => ({ ...newProbe(m, [...newReasons, ...(unready.engines[m.engine] ? [unready.engines[m.engine]!] : []),
...(quota(m.engine).leftPercent === 0 ? ['Subscription exhausted.'] : [])], quota(m.engine), fresh && quota(m.engine).known,
{ agents: Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.length : null,
freeMemoryBytes: finite(resources.memoryTotalBytes) && finite(resources.memoryUsedBytes) ? resources.memoryTotalBytes - resources.memoryUsedBytes : null,
- hasFolder: finite(resources.projectDiskFreeBytes) }))]
+ hasFolder: finite(resources.projectDiskFreeBytes) }), ...unable(m.engine) }))]
}
// The account says this machine is off, so nothing there can run or be asked.
if (account && status === 'offline') return [...members.map(m => memberProbe(m, [OFFLINE])), ...offline()]
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 44418954a..b93252118 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -685,6 +685,11 @@ enum AttachIntent { person, automatic }
/// select there, or the first phone or app.
typedef MachinesRequest = ({String? devicePub, bool phones});
+/// Change agent on a Swarm Buddy, which keeps running and so keeps its agent
+/// (hn's `BUDDY_KEEPS_ITS_AGENT`, word for word).
+const buddyKeepsItsAgent =
+ 'A Swarm Buddy keeps its agent. To use another agent, its person removes the Buddy and adds a new one.';
+
class AppNotifier extends ChangeNotifier {
final AuthSession session;
@@ -17046,6 +17051,9 @@ class AppNotifier extends ChangeNotifier {
final saved = await close('now');
if (saved['closed'] != true) {
change.preservingViews = false;
+ // A Swarm Buddy keeps running, so it keeps its agent. The daemon's
+ // refusal speaks of Stop Harness, which is no help here.
+ if (saved['keptRunning'] == true) return buddyKeepsItsAgent;
return saved['detail'] as String? ??
'Could not save and stop this conversation. Its agent has not been changed.';
}
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index a89ea12a0..3650650f3 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -12,6 +12,7 @@ import '../state/app_state.dart';
import '../state/harness_activity.dart';
import '../widgets/desktop_chrome.dart';
import '../widgets/engine_identity.dart';
+import 'agent_mark.dart';
import 'controller.dart';
import 'identity.dart';
import 'model.dart';
@@ -44,6 +45,8 @@ class SuperTabAgentInfo {
(g) =>
!g.closed &&
g.assignment?['agentId'] == agent.id &&
+ // Never a task the viewer may not read (review of #2281).
+ superTabGroupReadable(controller, g) &&
!const {
'done',
'stopped',
@@ -147,6 +150,9 @@ class SuperTabAgentInfo {
'planned' => 'Assigned to "${group.title}"',
'blocked' => 'Stuck on "${group.title}"',
'review' => 'Waiting for review on "${group.title}"',
+ // Handed over with its status still working, as the Swarm reads it.
+ 'working' when SuperTabAgentWork(group).handedOver =>
+ 'Waiting for review on "${group.title}"',
'reconciling' => 'Checking "${group.title}"',
// Its machine died, it stalled or hit a limit, and the Lead hands it on (backend liveness.ts).
'lost' => 'Lost "${group.title}"',
@@ -251,7 +257,18 @@ Future<void> showSuperTabAgentDetails(
listenable: Listenable.merge([controller, ?app]),
builder: (context, _) {
final current = controller.snapshot?.agent(agent.id) ?? agent;
- final info = SuperTabAgentInfo(controller, app, current);
+ // The same words the Agents list's hover says: the Swarm's state first.
+ final info = SuperTabAgentInfo(
+ controller,
+ app,
+ current,
+ activity: superTabAgentState(
+ controller,
+ app,
+ current,
+ now: superTabServerNow(controller, DateTime.now()),
+ ).words,
+ );
final group = info.taskGroup;
final pr = info.latestGroupPr;
final name = controller.snapshot?.agentName(agent.id) ?? agent.name;
diff --git a/desktop/lib/super_tabs/agent_line.dart b/desktop/lib/super_tabs/agent_line.dart
index 0c1cd4bd7..764d6873a 100644
--- a/desktop/lib/super_tabs/agent_line.dart
+++ b/desktop/lib/super_tabs/agent_line.dart
@@ -1,5 +1,6 @@
import '../state/harness_activity.dart';
import 'agent_details.dart';
+import 'agent_mark.dart';
/// An agent row's one line (Dee, 2026-10-27: "it's hard to monitor the team"): its state, where it runs, and on which
/// model and effort. Read from the Swarm the person already sees, so nobody sees an agent or a machine they could not
@@ -71,7 +72,11 @@ SuperTabAgentGlance superTabAgentGlance(
work == 'needs_human' ||
activity == HarnessActivity.needsInput =>
'Waiting',
- _ when work == 'review' => 'In review',
+ _
+ when work == 'review' ||
+ (info.taskGroup != null &&
+ SuperTabAgentWork(info.taskGroup!).handedOver) =>
+ 'In review',
_ when work == 'reconciling' => 'Checking',
_ when activity == HarnessActivity.working => 'Working',
_ when work == 'planned' || work == 'working' => 'Assigned',
diff --git a/desktop/lib/super_tabs/agent_mark.dart b/desktop/lib/super_tabs/agent_mark.dart
new file mode 100644
index 000000000..e8637732a
--- /dev/null
+++ b/desktop/lib/super_tabs/agent_mark.dart
@@ -0,0 +1,342 @@
+import 'dart:math' as math;
+
+import '../state/app_state.dart';
+import '../state/harness_activity.dart';
+import 'agent_details.dart';
+import 'controller.dart';
+import 'machine_status.dart';
+import 'model.dart';
+
+/// How long progress holds a task, and how long a session its machine lists
+/// as running may go without a screen change and still renew it: the
+/// backend's LEASE_MS and QUIET_RUNNING_MS - LEASE_MS (superTabs/liveness.ts).
+/// The Swarm stores only the lease an agent's own posts set; the renewal its
+/// machine's reports give is never written into the task, so it is worked out
+/// here from the reports every Desktop receives.
+const _lease = Duration(minutes: 5);
+const _quietRunning = Duration(minutes: 25);
+
+/// A hand-off, as the backend reads one: a result saying it is ready for
+/// review and naming a revision. A copy of READY_FOR_REVIEW and REVISION in
+/// backend/src/superTabs/liveness.ts (waitingForReview): change both together.
+final _readyForReview = RegExp(r'\bready for review\b', caseSensitive: false);
+final _revision = RegExp(
+ r'(?:@|\b(?:at|head)\s+)[0-9a-f]{7,40}\b|\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b',
+ caseSensitive: false,
+);
+
+/// The work an agent's row talks about: a question it waits on, its current
+/// task, or a finished one whose pull request has not merged yet. Only a group
+/// the viewer reads.
+class SuperTabAgentWork {
+ const SuperTabAgentWork(this.group, {this.awaitingMerge = false});
+ final SuperTabConversation group;
+
+ /// Done, with its pull request still open: the agent waits on its merge.
+ final bool awaitingMerge;
+
+ Map<String, dynamic>? get _assignment => group.assignment;
+ String? get status => _assignment?['status'] as String?;
+
+ /// Working, but handed over for review: the Swarm holds it without progress
+ /// until a review finds problems in it (liveness.ts waitingForReview).
+ bool get handedOver {
+ final result = _assignment?['result'];
+ return status == 'working' &&
+ _assignment?['reviewFoundAt'] == null &&
+ result is String &&
+ _readyForReview.hasMatch(result) &&
+ _revision.hasMatch(result);
+ }
+
+ /// When the agent last reported progress on it (backend assignment.progressAt).
+ DateTime? get progressAt => _time(_assignment?['progressAt']);
+
+ /// Until when its own last post holds it (backend assignment.leaseUntil).
+ DateTime? get leaseUntil => _time(_assignment?['leaseUntil']);
+
+ static DateTime? _time(Object? ms) =>
+ ms is num ? DateTime.fromMillisecondsSinceEpoch(ms.toInt()) : null;
+}
+
+/// Whether the viewer reads [group]: never a Buddy chat, and a private group
+/// only when its people include them. The server sends no other; this keeps a
+/// task, its title and a click to it away if one ever arrived.
+bool superTabGroupReadable(SuperTabController c, SuperTabConversation group) =>
+ !group.isBuddyChat &&
+ (group.audience == null || group.audience!.contains(c.accountId));
+
+/// [agent]'s work, and its current task (for the Swarm's word on its start).
+({SuperTabAgentWork? work, SuperTabConversation? task}) _workOf(
+ SuperTabController c,
+ SuperTabAgent agent,
+) {
+ final groups = [
+ for (final g in c.snapshot?.conversations ?? const <SuperTabConversation>[])
+ if (!g.closed &&
+ g.assignment?['agentId'] == agent.id &&
+ superTabGroupReadable(c, g))
+ g,
+ ];
+ final task = SuperTabAgentInfo(c, null, agent).taskGroup;
+ // A question waiting on a person comes first, from whichever of its open
+ // groups asks it: that is where its row's click goes.
+ if (groups
+ .where((g) => superTabWorkWaits(g.assignment?['status']))
+ .firstOrNull
+ case final asking?) {
+ return (work: SuperTabAgentWork(asking), task: task);
+ }
+ if (task != null) return (work: SuperTabAgentWork(task), task: task);
+ final merging = groups
+ .where(
+ (g) =>
+ g.assignment?['status'] == 'done' &&
+ g.cards.pullRequests.isNotEmpty &&
+ !g.cards.pullRequests.any((pr) => pr.merged),
+ )
+ .firstOrNull;
+ return (
+ work: merging == null
+ ? null
+ : SuperTabAgentWork(merging, awaitingMerge: true),
+ task: null,
+ );
+}
+
+/// This Mac's own reading of the agent; null when it has none, or reads its
+/// status as unknown.
+HarnessActivity? superTabLocalActivity(AppNotifier? app, SuperTabAgent agent) {
+ final local = app == null
+ ? null
+ : harnessActivity(app, agent.machineId, agent.harnessId);
+ return local == HarnessActivity.unknown ? null : local;
+}
+
+Map<String, dynamic>? _report(SuperTabController c, SuperTabAgent agent) =>
+ switch (c.snapshot?.pool(agent.machineId)?['observation']) {
+ final Map report => report.cast<String, dynamic>(),
+ _ => null,
+ };
+
+/// When the agent's task stops being held (liveness.ts leaseEnd): its own
+/// last post's lease, or 5 minutes after its machine last renewed it, by
+/// listing it running with a screen change in the last 25 minutes,
+/// whichever is later. Null when nothing ever renewed it.
+DateTime? superTabLeaseEnd(
+ SuperTabController c,
+ SuperTabAgent agent,
+ SuperTabAgentWork work,
+) {
+ final own = work.leaseUntil;
+ final report = _report(c, agent);
+ final received = report?['receivedAt'];
+ DateTime? renewed;
+ if (report != null && received is num) {
+ final running = report['runningHarnessIds'];
+ final progress = report['harnessProgress'];
+ if (running is! List) {
+ // A report that lists no sessions says nothing about this one.
+ } else if (!running.contains(agent.harnessId)) {
+ // Not listed running: it last renewed when it went down.
+ renewed = agent.downSince;
+ } else if (progress is! Map) {
+ renewed = DateTime.fromMillisecondsSinceEpoch(received.toInt());
+ } else if (progress[agent.harnessId] case final num at) {
+ renewed = DateTime.fromMillisecondsSinceEpoch(
+ math.min(received.toInt(), at.toInt() + _quietRunning.inMilliseconds),
+ );
+ }
+ }
+ final reported = renewed?.add(_lease);
+ if (own == null) return reported;
+ if (reported == null) return own;
+ return own.isAfter(reported) ? own : reported;
+}
+
+/// What the Swarm knows of an agent this Mac cannot see that stops it
+/// running (Dee, 2026-10-29): its computer silent, offline; its session
+/// stopped; its start failed. Null when none is known. While the Swarm
+/// cannot be read, its computers are not called offline.
+HarnessActivity? superTabSwarmDown(
+ SuperTabController c,
+ SuperTabAgent agent,
+ SuperTabConversation? task,
+ DateTime now,
+) {
+ // The computer it runs on reports for itself: a Harness Team account
+ // shown as its Mac has its own heartbeat.
+ final machine = c.snapshot?.pool(agent.machineId);
+ final at = switch (machine?['observation']) {
+ {'receivedAt': final num at} => at.toInt(),
+ _ => null,
+ };
+ if (machine != null &&
+ !c.backendUnreachable &&
+ superTabMachineStatus(
+ age: at == null
+ ? null
+ : now.difference(DateTime.fromMillisecondsSinceEpoch(at)),
+ ) ==
+ SuperTabMachineStatus.offline) {
+ return HarnessActivity.offline;
+ }
+ if (agent.downSince != null) return HarnessActivity.paused;
+ return task?.liveness?['state'] == 'orphaned' &&
+ task?.liveness?['why'] == 'start-failed'
+ ? HarnessActivity.failed
+ : null;
+}
+
+/// An agent as its row shows it: its [work], its [mark], and the activity
+/// its [words] go by.
+class SuperTabAgentState {
+ const SuperTabAgentState({
+ required this.work,
+ required this.mark,
+ required this.words,
+ });
+ final SuperTabAgentWork? work;
+
+ /// The mark its row shows, and the order it takes (Dee, 2026-10-30).
+ final HarnessActivity mark;
+
+ /// The activity its hover, its details, and its state word when it holds
+ /// no task go by. They read the task itself, so they say Lost, In review
+ /// or Assigned where the mark only shows a glyph, and claim Working only
+ /// for a turn running here or a task the Swarm still holds.
+ final HarnessActivity? words;
+}
+
+/// [agent]'s state, worked out once per build, at [now] by the Swarm's clock
+/// ([superTabServerNow]).
+///
+/// The Swarm's state comes first, since every Desktop receives it, so an
+/// agent on another computer reads the same here as on its own. This Mac's
+/// reading wins only when it is live: a turn running, a question on screen,
+/// starting, failed. Unseen here, the Swarm's word that it stopped comes
+/// next. This Mac's idle, stopped or offline never beats a task the Swarm
+/// still holds: a Mac that sees a shared machine reads every agent there
+/// idle, since no turn is reported to it.
+///
+/// Lost work is down; needs_human or blocked needs you; in review, handed
+/// over, or done with its pull request still open, waits (✓); held is
+/// working, and past its lease nobody can say (◌); nothing held, idle.
+SuperTabAgentState superTabAgentState(
+ SuperTabController c,
+ AppNotifier? app,
+ SuperTabAgent agent, {
+ required DateTime now,
+}) {
+ final (:work, :task) = _workOf(c, agent);
+ final status = work?.status;
+ final local = superTabLocalActivity(app, agent);
+ final down = local == null ? superTabSwarmDown(c, agent, task, now) : null;
+ final held = status == 'working' || status == 'planned';
+ final handedOver = work?.handedOver == true;
+ final end = work == null ? null : superTabLeaseEnd(c, agent, work);
+ final holding = held && !handedOver && end != null && end.isAfter(now);
+
+ HarnessActivity? words() {
+ if (local
+ case HarnessActivity.needsInput ||
+ HarnessActivity.failed ||
+ HarnessActivity.starting) {
+ return local;
+ }
+ if (down != null) return down;
+ if (holding) return HarnessActivity.working;
+ if (local case HarnessActivity.paused || HarnessActivity.offline) {
+ return local;
+ }
+ if (superTabWorkWaits(status)) return HarnessActivity.needsInput;
+ return local;
+ }
+
+ HarnessActivity mark() {
+ if (status == 'lost') return HarnessActivity.offline;
+ if (local
+ case HarnessActivity.needsInput ||
+ HarnessActivity.failed ||
+ HarnessActivity.starting ||
+ HarnessActivity.working) {
+ return local!;
+ }
+ if (down != null) return down;
+ if (holding) return HarnessActivity.working;
+ if (local case HarnessActivity.paused || HarnessActivity.offline) {
+ return local!;
+ }
+ if (superTabWorkWaits(status) ||
+ (local == null && agent.alerting.contains('prompt'))) {
+ return HarnessActivity.needsInput;
+ }
+ if (status == 'review' || handedOver || work?.awaitingMerge == true) {
+ return HarnessActivity.done;
+ }
+ // Held past its lease: nobody vouches for it, whatever this Mac reads.
+ // A server without leases says only that the task is held.
+ if (held) {
+ return end == null
+ ? local ?? HarnessActivity.working
+ : HarnessActivity.unknown;
+ }
+ if (status == 'reconciling') return local ?? HarnessActivity.unknown;
+ return local ?? HarnessActivity.idle;
+ }
+
+ return SuperTabAgentState(work: work, mark: mark(), words: words());
+}
+
+/// How long since an agent's last progress, shortest: "now", "4m", "2h", "3d".
+String superTabAgentAge(Duration age) =>
+ age.inMinutes < 1 ? 'now' : superTabAgoShort(age);
+
+/// The Swarm's clock, as far as its machines' reports tell it.
+class _ServerClock {
+ int? _evidence;
+ final _samples = <({DateTime at, Duration offset})>[];
+}
+
+final _clocks = Expando<_ServerClock>();
+
+/// How long a reading of the Swarm's clock counts: past it, with no new
+/// report from any machine, this Mac's own clock is used again.
+const _clockWindow = Duration(minutes: 10);
+
+/// [local] by the Swarm's clock, so a Mac whose clock runs fast or slow
+/// reads leases and ages as the Swarm does (review of #2281). Each machine
+/// report is stamped by the server on arrival, every few seconds, so a report
+/// newer than the last one seen is no later than the server's now: each such
+/// reading is a lower bound of the offset, and the largest of the last 10
+/// minutes is the best. Until one arrives, this Mac's own clock is used.
+DateTime superTabServerNow(SuperTabController c, DateTime local) {
+ final clock = _clocks[c] ??= _ServerClock();
+ int? newest;
+ for (final machine in c.snapshot?.machines ?? const <Map>[]) {
+ if (machine['observation'] case {'receivedAt': final num at}) {
+ newest = math.max(newest ?? 0, at.toInt());
+ }
+ }
+ // The first report read may be hours old (every machine silent): it is
+ // only a baseline. A newer one arrived since, so it is fresh.
+ if (newest != null) {
+ final before = clock._evidence;
+ if (before == null || newest < before) {
+ clock._evidence = newest;
+ } else if (newest > before) {
+ clock._evidence = newest;
+ clock._samples.add((
+ at: local,
+ offset: DateTime.fromMillisecondsSinceEpoch(newest).difference(local),
+ ));
+ }
+ }
+ clock._samples.removeWhere(
+ (s) => local.difference(s.at) > _clockWindow || s.at.isAfter(local),
+ );
+ if (clock._samples.isEmpty) return local;
+ return local.add(
+ clock._samples.map((s) => s.offset).reduce((a, b) => a > b ? a : b),
+ );
+}
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index b0a85cf65..8bc901574 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -51,6 +51,7 @@ class SuperTabMessageRow extends StatefulWidget {
this.thread,
this.threadUnread = false,
this.onOpenThread,
+ this.member,
this.link,
this.linkTarget,
this.onOpenLink,
@@ -70,6 +71,10 @@ class SuperTabMessageRow extends StatefulWidget {
/// reply's mark.
final VoidCallback? onOpenThread;
+ /// Who a thread's reply author is in the Swarm now, for the faces on its
+ /// reply line; without it each shows the face its recorded name gives.
+ final SuperTabMemberOf? member;
+
/// The person a Buddy's proposal speaks for, by name, from the server's tag
/// on it ([SuperTabMessage.proposalOwnerId]); null for any other message.
final String? proposalOwner;
@@ -504,6 +509,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
thread: thread,
unread: widget.threadUnread,
onOpen: open,
+ member: widget.member,
),
...widget.receipts,
],
@@ -703,6 +709,15 @@ class _SuperTabLinkState extends State<SuperTabLink> {
}
}
+/// Who a message author is in the Swarm as last read, by kind and id: the
+/// person, or the agent, whose face their own messages wear. Both are null
+/// for someone no longer in it.
+typedef SuperTabMemberOf =
+ ({SuperTabPerson? person, SuperTabAgent? agent}) Function(
+ String kind,
+ String id,
+ );
+
/// The line under a thread's root: who replied, how many replies, and when
/// the last came. Bold while the thread has a reply the reader has not seen.
class SuperTabThreadLine extends StatelessWidget {
@@ -711,12 +726,38 @@ class SuperTabThreadLine extends StatelessWidget {
required this.thread,
required this.unread,
required this.onOpen,
+ this.member,
});
final SuperTabThread thread;
final bool unread;
final VoidCallback onOpen;
+ /// Dresses each reply author as their own messages are: a person's
+ /// picture and status, an agent's avatar.
+ final SuperTabMemberOf? member;
+
+ Widget _face(Map<String, dynamic> author) {
+ const size = grid.AppDesktop.iconSize;
+ final kind = author['kind'] as String? ?? '';
+ final id = author['id'] as String? ?? '';
+ switch ((kind, member?.call(kind, id))) {
+ case ('agent', (agent: final agent?, person: _)):
+ return SuperTabAvatar.agent(agent, size: size, engineBadge: false);
+ case ('person', (person: final person?, agent: _)):
+ return SuperTabAvatar.person(person, size: size);
+ }
+ // Someone no longer in the Swarm keeps the face their recorded name gives.
+ return SuperTabAvatar(
+ identity: '$kind:$id',
+ name: kind == 'agent'
+ ? (author['displayName'] ?? author['name'] ?? 'Agent') as String
+ : superTabPersonName(author['name'] as String? ?? ''),
+ size: size,
+ pattern: kind == 'agent',
+ );
+ }
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -731,15 +772,7 @@ class SuperTabThreadLine extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
for (final author in thread.authors) ...[
- SuperTabAvatar(
- identity: '${author['kind']}:${author['id']}',
- name: author['kind'] == 'agent'
- ? (author['displayName'] ?? author['name'] ?? 'Agent')
- as String
- : superTabPersonName(author['name'] as String? ?? ''),
- size: grid.AppDesktop.iconSize,
- pattern: author['kind'] == 'agent',
- ),
+ _face(author),
const SizedBox(width: grid.AppDesktop.menuInset),
],
Text(
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index 81c3ab871..12cab9533 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -3,17 +3,19 @@ import 'dart:async';
import 'package:collection/collection.dart' show mergeSort;
import 'package:flutter/material.dart';
+import '../core/relative_time.dart';
+
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/appearance_prefs_store.dart';
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_select_field.dart';
import '../state/app_state.dart';
-import '../state/harness_activity.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import '../widgets/desktop_chrome.dart';
import '../widgets/harness_activity_mark.dart';
import 'agent_details.dart';
+import 'agent_mark.dart';
import 'controller.dart';
import 'detail_dialog.dart';
import 'dialog_scope.dart';
@@ -24,7 +26,6 @@ import 'leaderboard/model.dart';
import 'leaderboard/person_row.dart';
import 'leaderboard/reader.dart';
import 'leaderboard/waiting_line.dart';
-import 'machine_status.dart';
import 'model.dart';
import 'profile_sheet.dart';
import 'section_heading.dart';
@@ -51,7 +52,8 @@ class SuperTabRoster extends StatefulWidget {
final ValueChanged<SuperTabAgent> onOpenAgent;
final ValueChanged<SuperTabConversation> onAddAgent;
- /// Opens a conversation where an agent waits on a person.
+ /// Opens a conversation: one where an agent waits on a person, or an agent
+ /// row's task.
final ValueChanged<String> onAnswer;
/// The open project's week board, shared with the sidebar's Models; the
@@ -70,8 +72,22 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
late final SuperTabLeaderboardReader _board =
widget.board ?? (_ownBoard = SuperTabProjectBoard(c));
+ /// One tick for the whole list, so ages and leases stay true on a quiet
+ /// Swarm (review of #2281); a change in the Swarm rebuilds it anyway.
+ Timer? _tick;
+
+ @override
+ void initState() {
+ super.initState();
+ _tick = Timer.periodic(
+ const Duration(seconds: 30),
+ (_) => mounted ? setState(() {}) : null,
+ );
+ }
+
@override
void dispose() {
+ _tick?.cancel();
_ownBoard?.dispose();
super.dispose();
}
@@ -197,74 +213,6 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
);
}
- /// This Mac's reading of the agent; null when it cannot see it, or reads
- /// its status as unknown.
- HarnessActivity? _native(SuperTabAgent agent) {
- final app = widget.app;
- final native = app == null
- ? null
- : harnessActivity(app, agent.machineId, agent.harnessId);
- return native == HarnessActivity.unknown ? null : native;
- }
-
- HarnessActivity _activity(SuperTabAgent agent) {
- final native = _native(agent);
- // Keep the shared lifecycle precedence. A retained workgroup question must
- // not make a stopped or disconnected harness look available for input.
- if (native == HarnessActivity.offline ||
- native == HarnessActivity.paused ||
- native == HarnessActivity.starting ||
- native == HarnessActivity.failed ||
- native == HarnessActivity.needsInput) {
- return native!;
- }
- if (native == null) {
- if (_swarmDown(agent) case final down?) return down;
- }
- if (c.snapshot?.conversations.any(
- (group) =>
- !group.closed &&
- group.assignment?['agentId'] == agent.id &&
- superTabWorkWaits(group.assignment?['status']),
- ) ==
- true) {
- return HarnessActivity.needsInput;
- }
- return native ?? HarnessActivity.unknown;
- }
-
- /// What the Swarm knows of an agent this Mac cannot see that stops it
- /// running (Dee, 2026-10-29): its computer silent, offline; its session
- /// stopped; its start failed. Null when none is known. While the Swarm
- /// cannot be read, its computers are not called offline.
- HarnessActivity? _swarmDown(SuperTabAgent agent) {
- // The computer it runs on reports for itself: a Harness Team account
- // shown as its Mac has its own heartbeat.
- final machine = c.snapshot?.pool(agent.machineId);
- final at = switch (machine?['observation']) {
- {'receivedAt': final num at} => at.toInt(),
- _ => null,
- };
- if (machine != null &&
- !c.backendUnreachable &&
- superTabMachineStatus(
- age: at == null
- ? null
- : widget.now().difference(
- DateTime.fromMillisecondsSinceEpoch(at),
- ),
- ) ==
- SuperTabMachineStatus.offline) {
- return HarnessActivity.offline;
- }
- if (agent.downSince != null) return HarnessActivity.paused;
- final task = SuperTabAgentInfo(c, null, agent).taskGroup;
- return task?.liveness?['state'] == 'orphaned' &&
- task?.liveness?['why'] == 'start-failed'
- ? HarnessActivity.failed
- : null;
- }
-
/// A person's email and role, and their week when the board has them. One's
/// own also opens the profile sheet, where one's avatar and status change.
Future<void> _person(SuperTabPerson person, SuperTabPersonScore? score) =>
@@ -375,38 +323,15 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
},
);
- /// The mark an agent's row shows, which also orders the list: its activity,
- /// except that lost work shows the tabs' Offline, since nothing runs it
- /// (Dee, 2026-10-29). An agent this Mac cannot see, and the Swarm knows
- /// nothing stopping, takes its mark from its work: a prompt on its screen
- /// needs input; finished and in review, done; a task under way, working;
- /// nothing held, idle. Its words still say only Assigned for a task.
- HarnessActivity _shownActivity(SuperTabAgentInfo info) {
- final work = info.taskGroup?.assignment?['status'];
- if (work == 'lost') return HarnessActivity.offline;
- final activity = info.activity ?? HarnessActivity.unknown;
- if (activity != HarnessActivity.unknown || _native(info.agent) != null) {
- return activity;
- }
- if (info.agent.alerting.contains('prompt')) {
- return HarnessActivity.needsInput;
- }
- return switch (work) {
- 'review' => HarnessActivity.done,
- 'working' || 'planned' => HarnessActivity.working,
- _ => HarnessActivity.idle,
- };
- }
-
/// An agent's row, in the shape the people's rows share (Dee, 2026-10-29):
/// avatar, name and role chip, today's one status line beneath, and the
/// tabs' status mark at the right. No rank and no points.
- Widget _agent(SuperTabAgent agent) {
- final name = c.snapshot!.agentName(agent.id), activity = _activity(agent);
- final info = SuperTabAgentInfo(c, widget.app, agent, activity: activity);
- final shown = _shownActivity(info);
- // One line, readable in a second (Dee, 2026-10-27): state, machine, model and effort. The task is in the tooltip.
- final glance = superTabAgentGlance(info);
+ Widget _agent(SuperTabAgent agent, SuperTabAgentState state, DateTime now) {
+ final name = c.snapshot!.agentName(agent.id), shown = state.mark;
+ final info = SuperTabAgentInfo(c, widget.app, agent, activity: state.words);
+ final work = state.work;
+ // The state in a word, where it runs, its engine, model and effort: on hover (Dee, 2026-10-30).
+ final glance = superTabAgentGlance(info, now: now);
final project = c.snapshot!.projects
.where((p) => p.id == _agentProjectId(agent))
.firstOrNull;
@@ -427,10 +352,28 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
: 'Dev');
final status = info.status ?? 'Status unavailable';
final tooltip = [
- [name, role, ?project?.name].join(' · '),
- if (info.tooltip.isNotEmpty) info.tooltip,
- if (!info.tooltip.contains(status)) status,
+ [name, role, ?project?.name, ?info.engine].join(' · '),
+ glance.line,
+ if (status != glance.label) status,
+ if (info.lastActive case final at?) 'Last active ${relativeAgo(at, now)}',
].join('\n');
+ // The row's details line (Dee, 2026-10-30): the task in plain words and
+ // how long since its last progress; with no task, the state in a word.
+ final limited = glance.label.startsWith('Limited until')
+ ? glance.label
+ : null;
+ final detail = work == null
+ ? glance.label
+ : [
+ ?limited,
+ work.group.title,
+ if (work.progressAt case final at?)
+ superTabAgentAge(now.difference(at)),
+ ].join(' · ');
+ // A task opens its conversation, a needs-you one at its question; no task, the details.
+ void open() => work == null
+ ? unawaited(_details(agent))
+ : widget.onAnswer(work.group.id);
final theme = terminalThemeFor(
grid.AppTheme.surfacePalette,
terminalThemeStore.value,
@@ -476,7 +419,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
},
child: SuperTabMemberRow(
rowKey: ValueKey('super-member-${agent.id}'),
- onTap: () => unawaited(_details(agent)),
+ onTap: open,
onLongPress: () => unawaited(_details(agent)),
avatar: SuperTabAvatar.agent(
agent,
@@ -486,7 +429,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
),
name: _agentIdentity(name, role, badge),
detail: Text(
- glance.line,
+ detail,
key: ValueKey('super-member-line-${agent.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -559,17 +502,30 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
return byName != 0 ? byName : a.id.compareTo(b.id);
});
// Most urgent first, as the tabs order their marks: needs input, working,
- // idle, offline. Equals keep today's order, the Lead first.
- final shown = {
+ // idle, offline; within a mark, the most recent progress first (Dee,
+ // 2026-10-30). Equals keep today's order, the Lead first. Each agent's
+ // state is worked out once, by the Swarm's clock.
+ final now = superTabServerNow(c, widget.now());
+ final states = {
for (final agent in [...leads, ...agents])
- agent.id: _shownActivity(
- SuperTabAgentInfo(c, widget.app, agent, activity: _activity(agent)),
- ),
+ agent.id: superTabAgentState(c, widget.app, agent, now: now),
+ };
+ final progress = {
+ for (final MapEntry(:key, :value) in states.entries)
+ key: value.work?.progressAt,
};
final listed = [...leads, ...agents];
mergeSort(
listed,
- compare: (a, b) => shown[a.id]!.index - shown[b.id]!.index,
+ compare: (a, b) {
+ final byMark = states[a.id]!.mark.index - states[b.id]!.mark.index;
+ if (byMark != 0) return byMark;
+ final pa = progress[a.id], pb = progress[b.id];
+ if (pa == null || pb == null) {
+ return (pa == null ? 1 : 0) - (pb == null ? 1 : 0);
+ }
+ return pb.compareTo(pa);
+ },
);
final current = leaderboardWeekOf(widget.now());
// One points column for every person's row.
@@ -653,7 +609,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
: null,
addTooltip: 'Add agent',
),
- for (final agent in listed) _agent(agent),
+ for (final agent in listed) _agent(agent, states[agent.id]!, now),
];
}
diff --git a/desktop/lib/super_tabs/swarm_switcher.dart b/desktop/lib/super_tabs/swarm_switcher.dart
index 3bd36b5c8..40928171f 100644
--- a/desktop/lib/super_tabs/swarm_switcher.dart
+++ b/desktop/lib/super_tabs/swarm_switcher.dart
@@ -49,7 +49,10 @@ class PersonalSwarm extends ChangeNotifier {
/// Swarms taken away from each account while shown here: listed no more,
/// even once their tab has let them go.
final _lost = <String, Set<String>>{};
- String? _error, _errorAccount;
+
+ /// Why picking Personal failed last: for the account and the Swarm tab it
+ /// was picked in, so it never shows under another tab's Swarm.
+ ({String account, String tab, String message})? _error;
String? get _account => app.currentUser?.id;
static String _key(String account) => 'super_tab.personal.$account';
@@ -79,11 +82,16 @@ class PersonalSwarm extends ChangeNotifier {
bool get busy =>
_creating.containsKey(_account) || _adding.contains(_account);
- /// Why creating Personal or adding this computer to it failed last.
- String? get error => _errorAccount == _account ? _error : null;
+ /// Why picking Personal in Swarm tab [tab] failed last, if it did.
+ String? errorIn(String tab) => switch (_error) {
+ (:final account, tab: final failed, :final message)
+ when account == _account && failed == tab =>
+ message,
+ _ => null,
+ };
- void clearError() {
- if (_error == null) return;
+ void clearError(String tab) {
+ if (errorIn(tab) == null) return;
_error = null;
notifyListeners();
}
@@ -147,36 +155,30 @@ class PersonalSwarm extends ChangeNotifier {
/// asked of the server, which creates it the first time. A Swarm merely
/// named Personal is never taken for it.
Future<String> _create(String account) async {
- _error = null;
- try {
- await _read(account);
- if (_picked(account) case final known?) return known;
- final created = await app.superTabs.map(
- 'POST',
- '/api/super-tabs',
- body: {
- 'operationId': kPersonalSwarmOperation,
- 'name': kPersonalSwarmName,
- },
+ await _read(account);
+ if (_picked(account) case final known?) return known;
+ final created = await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs',
+ body: {
+ 'operationId': kPersonalSwarmOperation,
+ 'name': kPersonalSwarmName,
+ },
+ );
+ if (_account != account) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ final id = created['id'];
+ if (id is! String || id.isEmpty) {
+ throw const SuperTabFailure(
+ 'INVALID_RESPONSE',
+ 'Could not create your Personal Swarm. Try again.',
);
- if (_account != account) {
- throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
- }
- final id = created['id'];
- if (id is! String || id.isEmpty) {
- throw const SuperTabFailure(
- 'INVALID_RESPONSE',
- 'Could not create your Personal Swarm. Try again.',
- );
- }
- // Discovery may list it before this tab shows it: no second tab.
- app.superTabs.deferTabDiscovery(id);
- _remember(account, id);
- return id;
- } catch (failure) {
- _fail(account, failure, 'Could not create your Personal Swarm.');
- rethrow;
}
+ // Discovery may list it before this tab shows it: no second tab.
+ app.superTabs.deferTabDiscovery(id);
+ _remember(account, id);
+ return id;
}
void _remember(String account, String id) {
@@ -187,12 +189,9 @@ class PersonalSwarm extends ChangeNotifier {
);
}
- void _fail(String account, Object failure, String fallback) {
+ void _fail(String account, String tab, String message) {
if (_account != account) return;
- final message = failure is SuperTabFailure ? failure.message : fallback;
- if (failure is SuperTabFailure && failure.code == 'ACCOUNT_CHANGED') return;
- _error = message;
- _errorAccount = account;
+ _error = (account: account, tab: tab, message: message);
notifyListeners();
}
@@ -203,15 +202,26 @@ class PersonalSwarm extends ChangeNotifier {
final account = _account;
final shown = _tabShowing(swarmId);
if (account == null || shown == null) return;
+ clearError(swarmId);
final String personal;
try {
personal = await ensure();
- } catch (_) {
+ } catch (failure) {
+ if (_tabShowing(swarmId) == shown &&
+ !(failure is SuperTabFailure && failure.code == 'ACCOUNT_CHANGED')) {
+ _fail(
+ account,
+ swarmId,
+ failure is SuperTabFailure
+ ? failure.message
+ : 'Could not create your Personal Swarm.',
+ );
+ }
return;
}
if (_account != account || _tabShowing(swarmId) != shown) return;
app.showSuperTabIn(swarmId, personal, kPersonalSwarmName);
- await _addThisComputer(account, personal);
+ await _addThisComputer(account, swarmId, personal);
}
String? _tabShowing(String swarmId) =>
@@ -219,7 +229,11 @@ class PersonalSwarm extends ChangeNotifier {
/// This computer, added as Add machine adds it: only the person's own,
/// linked and online, and never a Harness Team account's machine.
- Future<void> _addThisComputer(String account, String personal) async {
+ Future<void> _addThisComputer(
+ String account,
+ String tab,
+ String personal,
+ ) async {
final here = app.machineStates.values
.where(
(m) =>
@@ -264,9 +278,19 @@ class PersonalSwarm extends ChangeNotifier {
offerTeamAccount: false,
);
} catch (failure) {
- // A request still out when Personal was let go answers no one.
- if (opened == null || alive()) {
- _fail(account, failure, 'Could not add this computer to Personal.');
+ // Only while the tab still shows Personal: once it moved on, Personal
+ // was let go, and what was still out (its saved state being read, an
+ // add on its way) answers no one.
+ if (_tabShowing(tab) == personal && (opened == null || alive())) {
+ const headline = 'Could not add this computer to Personal.';
+ final reason = failure is SuperTabFailure ? failure.message : null;
+ _fail(
+ account,
+ tab,
+ reason == null || reason == 'Could not add this machine.'
+ ? headline
+ : '$headline $reason',
+ );
}
} finally {
_adding.remove(account);
@@ -415,7 +439,9 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {
consumeOutsideTap: true,
alignmentOffset: const Offset(0, grid.AppControl.menuGap),
style: grid.AppMenu.style(minWidth: width, maxWidth: width),
- onOpen: personal.clearError,
+ onOpen: () {
+ if (_tab case final tab?) personal.clearError(tab);
+ },
// As wide as the row it opens from.
menuChildren: [
for (final item in <Widget>[
@@ -475,7 +501,7 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {
),
),
),
- if (personal.error case final error?) ...[
+ if (personal.errorIn(_tab ?? '') case final error?) ...[
// Under the row's label, as the row's own text column.
Row(
key: const ValueKey('super-swarm-switcher-error'),
diff --git a/desktop/lib/super_tabs/unread_line.dart b/desktop/lib/super_tabs/unread_line.dart
index 537334015..4efb3afbd 100644
--- a/desktop/lib/super_tabs/unread_line.dart
+++ b/desktop/lib/super_tabs/unread_line.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -51,8 +52,22 @@ class SuperTabUnreadLines {
/// The line on screen, to tell whether it is scrolled out of view.
final key = GlobalKey(debugLabel: 'New messages line');
- /// Whether the reader is scrolled away from the line, so the jump pill shows.
- bool away = false;
+ /// Whether the reader is scrolled away from the line, and whether it is
+ /// below them.
+ bool away = false, below = false;
+
+ /// Conversations whose line has been in view this visit.
+ final _seen = <String>{};
+
+ /// [id]'s line came into view: reading on needs no way back to it.
+ void saw(String id) => _seen.add(id);
+
+ /// Whether [id]'s line has been in view this visit.
+ bool seen(String id) => _seen.contains(id);
+
+ /// Whether [id] offers the jump back to its line: placed, out of view, and
+ /// not yet seen this visit (a link opened the chat elsewhere).
+ bool offersJump(String id) => away && _at[id] != null && !_seen.contains(id);
/// The message [id]'s line sits above, or null.
String? lineAt(String id) => _at[id];
@@ -118,15 +133,16 @@ class SuperTabUnreadLines {
_loading.remove(id);
_loaded.remove(id);
_failed.remove(id);
+ _seen.remove(id);
catchUps.forget(id);
- away = false;
+ away = below = false;
}
/// Read with Esc: no line or card until the next visit.
void clear(String id) {
_at[id] = null;
catchUps.dismiss(id);
- away = false;
+ away = below = false;
}
void reset() {
@@ -134,8 +150,9 @@ class SuperTabUnreadLines {
_loading.clear();
_loaded.clear();
_failed.clear();
+ _seen.clear();
catchUps.reset();
- away = false;
+ away = below = false;
}
}
@@ -175,17 +192,74 @@ class SuperTabNewMessagesLine extends StatelessWidget {
}
}
-/// Shown while the New messages line is scrolled out of view: takes the reader back to it.
+/// Shown while the New messages line, not yet seen this visit, is out of view: takes the reader back to it.
class SuperTabJumpToUnread extends StatelessWidget {
- const SuperTabJumpToUnread({super.key, required this.onPressed});
+ const SuperTabJumpToUnread({
+ super.key,
+ required this.onPressed,
+ this.down = false,
+ });
final VoidCallback onPressed;
+ /// The line is below the reader (a link opened the chat above it).
+ final bool down;
+
@override
Widget build(BuildContext context) => FilledButton.icon(
key: const ValueKey('super-jump-unread'),
onPressed: onPressed,
- icon: const Icon(AppIcons.chevronUp, size: grid.AppDesktop.iconSize),
+ icon: Icon(
+ down ? AppIcons.chevronDown : AppIcons.chevronUp,
+ size: grid.AppDesktop.iconSize,
+ ),
label: const Text('Jump to first unread'),
);
}
+
+/// The jump pill's place above the list ([child], or nothing). When it opens
+/// or closes, [scroll] moves by the same height in that frame, so the messages
+/// under the reader's eye stay where they were.
+class SuperTabUnreadBand extends SingleChildRenderObjectWidget {
+ const SuperTabUnreadBand({super.key, required this.scroll, super.child});
+
+ final ScrollController? scroll;
+
+ @override
+ RenderObject createRenderObject(BuildContext context) =>
+ RenderSuperTabUnreadBand(scroll);
+
+ @override
+ void updateRenderObject(
+ BuildContext context,
+ RenderSuperTabUnreadBand renderObject,
+ ) => renderObject.scroll = scroll;
+}
+
+class RenderSuperTabUnreadBand extends RenderProxyBox {
+ RenderSuperTabUnreadBand(this.scroll);
+
+ ScrollController? scroll;
+ double? _height;
+
+ @override
+ void performLayout() {
+ super.performLayout();
+ final previous = _height;
+ _height = size.height;
+ final scroll = this.scroll;
+ if (previous == null ||
+ previous == size.height ||
+ scroll == null ||
+ !scroll.hasClients ||
+ !scroll.position.hasPixels) {
+ return;
+ }
+ // Laid out before the list below it, which then takes the corrected
+ // offset: the list's top moves by the change, and the messages do not.
+ // Only the view's edge moves, not the content, so this is not a
+ // correctBy (which moves the place the chat's list keeps as well).
+ final position = scroll.position;
+ position.correctPixels(position.pixels + size.height - previous);
+ }
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 24729e02a..e94e87f07 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -140,6 +140,13 @@ class _SuperTabViewState extends State<SuperTabView>
bool _showNotifications = false;
// The message a tag opened, scrolled to once it is laid out.
String? _target;
+ // The conversation a link or tag opened at its own message this visit: its
+ // New messages line stays where it is, reached by the jump pill.
+ String? _openedAtMessage;
+ // The jump to a message or line still landing: its passing scroll neither
+ // counts the line as seen nor shows the pill. Each jump takes a new number.
+ int? _landing;
+ int _landings = 0;
final _targetKey = GlobalKey();
// A quote followed to its original: the search still reading older pages,
// the reply to come back to (its row's top in the list), and the message
@@ -339,6 +346,7 @@ class _SuperTabViewState extends State<SuperTabView>
final draft = c.accessRevoked ? '' : c.draft(id);
if (_selected != id) {
_unread.forget(_selected);
+ _openedAtMessage = null;
_scrollRequest++;
_jumpingToEnd = false;
// A search or a way back belongs to the conversation it started in. The
@@ -374,7 +382,7 @@ class _SuperTabViewState extends State<SuperTabView>
} else if (_unread.waitsForHistory(id)) {
// The line is placed once the messages reach back to the mark.
} else if (_unread.decide(id, shown, mark, own: c.isOwn)) {
- _revealUnreadLine(id);
+ if (_openedAtMessage != id) _revealUnreadLine(id);
_loadCatchUp(id, mark);
} else if (firstView || (grew && atEnd)) {
_followEnd(id);
@@ -516,14 +524,18 @@ class _SuperTabViewState extends State<SuperTabView>
void _revealUnreadLine(String id) {
final messageId = _unread.lineAt(id);
if (messageId == null) return;
- _scrollRequest++;
+ final request = ++_scrollRequest;
_jumpingToEnd = false;
_follow(id, false);
- _target = messageId;
+ // Rebuilt so the target's key moves to the line's row from any row an
+ // earlier jump marked.
+ setState(() => _target = messageId);
_revealTarget(
id,
0,
arrived: (row) {
+ // A link or tag opened since takes the reader to its message instead.
+ if (request != _scrollRequest) return;
// The line itself, not its row: with the catch-up card under it the
// row can be taller than the view, and its top would go above it.
final line = _unread.key.currentContext;
@@ -531,9 +543,7 @@ class _SuperTabViewState extends State<SuperTabView>
Scrollable.ensureVisible(
line != null && line.mounted ? line : row,
alignment: .15,
- ).then((_) {
- _checkUnreadLine();
- }),
+ ),
);
},
);
@@ -547,24 +557,35 @@ class _SuperTabViewState extends State<SuperTabView>
}),
);
- /// Shows the jump pill while the reader is scrolled away from the line, and
- /// Jump to latest while the list is away from its newest message.
+ /// Shows the jump pill while the reader is away from a line not yet seen,
+ /// and Jump to latest while the list is away from its newest message.
void _checkUnreadLine() {
final scroll = _scroll[c.selectedId];
- var away = false;
- if (_unread.lineAt(c.selectedId) != null &&
- scroll != null &&
- scroll.hasClients) {
+ var away = false, below = false;
+ // A jump still landing passes lines it does not stop at: measured once
+ // it has landed.
+ if (_unread.lineAt(c.selectedId) case final lineAt?
+ when scroll != null && scroll.hasClients && _landing == null) {
final line = _unread.key.currentContext;
final top = line == null ? null : _topInList(line);
- away = top == null || top < 0 || top > scroll.position.viewportDimension;
+ final view = scroll.position.viewportDimension;
+ away = top == null || top < 0 || top > view;
+ if (!away) _unread.saw(c.selectedId);
+ // A line not laid out is told by its place in the list; once seen, no
+ // pill needs its direction.
+ below = top != null
+ ? top > view
+ : !_unread.seen(c.selectedId) &&
+ _below(c.selectedId, lineAt, scroll.position);
}
final id = c.selectedId;
final awayFromEnd =
scroll != null &&
scroll.hasClients &&
scroll.position.extentAfter >= 40;
- if ((away == _unread.away && awayFromEnd == _awayFromEnd.contains(id)) ||
+ if ((away == _unread.away &&
+ below == _unread.below &&
+ awayFromEnd == _awayFromEnd.contains(id)) ||
!mounted) {
return;
}
@@ -577,6 +598,7 @@ class _SuperTabViewState extends State<SuperTabView>
}
setState(() {
_unread.away = away;
+ _unread.below = below;
if (awayFromEnd) {
_awayFromEnd.add(id);
} else {
@@ -585,6 +607,16 @@ class _SuperTabViewState extends State<SuperTabView>
});
}
+ /// Whether [messageId]'s row in [id]'s list is below [position]'s view, by
+ /// its place in the list.
+ bool _below(String id, String messageId, ScrollPosition position) {
+ final entries = superTabTranscriptEntries(_shownMessages(id));
+ final row = _rowShowing(id, messageId);
+ final index = entries.indexWhere((e) => e.message.id == row);
+ return index >= 0 &&
+ _estimate(position, index, entries.length) > position.pixels;
+ }
+
/// Esc: everything loaded in the open conversation is read, line and all.
bool _readAll() {
final id = c.selectedId, group = c.selected;
@@ -1489,6 +1521,7 @@ class _SuperTabViewState extends State<SuperTabView>
_showPullRequests = false;
_back = null;
_target = shownBy;
+ _openedAtMessage = id;
// Stop following the end: the linked message is what to see.
_scrollRequest++;
_jumpingToEnd = false;
@@ -1612,6 +1645,7 @@ class _SuperTabViewState extends State<SuperTabView>
_replies[id] = message;
}
_target = message.id;
+ _openedAtMessage = id;
// Stop following the end: the tagged message is what to see.
_scrollRequest++;
_jumpingToEnd = false;
@@ -1622,30 +1656,45 @@ class _SuperTabViewState extends State<SuperTabView>
}
/// The list is lazy: jump near the target until its row is built, then
- /// bring it into view, or hand its row to [arrived] to place it.
+ /// bring it into view, or hand its row to [arrived] to place it. Until it
+ /// has landed or given up, the New messages line is not measured.
void _revealTarget(
String id,
int attempt, {
void Function(BuildContext row)? arrived,
+ int? landing,
}) {
+ landing ??= _landing = ++_landings;
WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted || c.selectedId != id || _target == null) return;
+ if (!mounted) return;
+ if (c.selectedId != id || _target == null) return _landed(landing!);
if (_targetKey.currentContext case final target?) {
if (arrived != null) {
arrived(target);
} else {
unawaited(Scrollable.ensureVisible(target, alignment: .3));
}
- return;
+ return _landed(landing!);
}
final scroll = _scroll[id];
final entries = superTabTranscriptEntries(_shownMessages(id));
final index = entries.indexWhere((e) => e.message.id == _target);
if (scroll == null || !scroll.hasClients || index < 0 || attempt > 20) {
- return;
+ return _landed(landing!);
}
scroll.jumpTo(_estimate(scroll.position, index, entries.length));
- _revealTarget(id, attempt + 1, arrived: arrived);
+ _revealTarget(id, attempt + 1, arrived: arrived, landing: landing);
+ });
+ WidgetsBinding.instance.scheduleFrame();
+ }
+
+ /// Jump [landing] is over: the line is measured where the list lays out
+ /// next, unless a newer jump has started.
+ void _landed(int landing) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || _landing != landing) return;
+ _landing = null;
+ _checkUnreadLine();
});
WidgetsBinding.instance.scheduleFrame();
}
@@ -2276,6 +2325,7 @@ class _SuperTabViewState extends State<SuperTabView>
author: _shownAuthor(c, message),
proposalOwner: _proposalOwner(message),
person: person,
+ member: _member,
grouped: grouped,
reply: reply,
replyAuthor: reply == null ? null : _shownAuthor(c, reply),
@@ -2328,6 +2378,20 @@ class _SuperTabViewState extends State<SuperTabView>
}
}
+ /// A reply author as the Swarm last read them, so a thread's line shows
+ /// the faces their own messages wear; both null for anyone no longer in
+ /// it.
+ ({SuperTabPerson? person, SuperTabAgent? agent}) _member(
+ String kind,
+ String id,
+ ) {
+ _index();
+ return (
+ person: kind == 'person' ? _people[id] : null,
+ agent: kind == 'agent' ? c.snapshot?.agent(id) : null,
+ );
+ }
+
Widget _message(
SuperTabMessage message,
bool grouped,
@@ -2412,6 +2476,7 @@ class _SuperTabViewState extends State<SuperTabView>
},
agent: agent,
person: message.fromAgent ? null : _people[message.authorId],
+ member: _member,
onOpenAgent: agent == null ? null : () => _openAgent(agent),
machineName: agent == null ? null : widget.machineName(agent.machineId),
grouped: grouped,
@@ -2919,188 +2984,211 @@ class _SuperTabViewState extends State<SuperTabView>
),
),
)
- : Stack(
+ : Column(
children: [
- NotificationListener<ScrollNotification>(
- onNotification: (event) {
- if (event.depth != 0) return false;
- if (event is ScrollStartNotification &&
- event.dragDetails != null) {
- _scrollRequest++;
- _jumpingToEnd = false;
- }
- if (_jumpingToEnd) return false;
- final id = c.selectedId;
- final atEnd = event.metrics.extentAfter < 40;
- _follow(id, atEnd);
- // Once the scroll ends, so keeping the place never
- // cuts a drag short.
- if (event is ScrollEndNotification) {
- _readEarlierNearTop(id, event.metrics);
- }
- if (atEnd) {
- // A row still sending has no place in the transcript.
- final sequence =
- actualMessages.lastOrNull?.sequence ?? 0;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted && c.selectedId == id) {
- _readToEnd(id, sequence);
- }
- });
- }
- return false;
- },
- child: SelectionArea(
- child: CustomScrollView(
- controller: _scroll[c.selectedId],
- key: PageStorageKey(
- 'super-messages-${c.tabId}-${c.selectedId}',
- ),
- // Pages read in grow upward from the rows first
- // shown, new messages downward: no row on screen
- // moves for either.
- center: _newerRows,
- slivers: [
- // Its spinner runs only near the view.
- SliverLayoutBuilder(
- builder: (context, constraints) =>
- SliverToBoxAdapter(
- child: Padding(
- padding: EdgeInsets.only(
- top: grid.AppDesktop.controlGap,
- ),
- child: _earlierRow(
- near:
- constraints.remainingCacheExtent >
- 0,
- ),
- ),
- ),
- ),
- SliverList(
- delegate: SliverChildBuilderDelegate(
- (context, index) => row(split - 1 - index),
- childCount: split,
- findChildIndexCallback: (key) =>
- switch (rowOf(key)) {
- final i? when i < split => split - 1 - i,
- _ => null,
- },
+ // Above the list, never over a message.
+ SuperTabUnreadBand(
+ key: ValueKey('super-unread-band-${c.selectedId}'),
+ scroll: _scroll[c.selectedId],
+ child: _unread.offersJump(c.selectedId)
+ ? Padding(
+ padding: const EdgeInsets.fromLTRB(
+ grid.AppDesktop.panelPadding,
+ grid.AppDesktop.controlGap,
+ grid.AppDesktop.panelPadding,
+ 0,
),
- ),
- SliverPadding(
- key: _newerRows,
- padding: EdgeInsets.only(
- bottom: grid.AppDesktop.controlGap,
- ),
- sliver: SliverList(
- delegate: SliverChildBuilderDelegate(
- // Messages on their way end the list.
- (context, index) => row(split + index),
- childCount: entries.length - split,
- findChildIndexCallback: (key) =>
- switch (rowOf(key)) {
- final i? when i >= split => i - split,
- _ => null,
- },
+ child: Center(
+ child: SuperTabJumpToUnread(
+ down: _unread.below,
+ onPressed: () =>
+ _revealUnreadLine(c.selectedId),
),
),
- ),
- ],
- ),
- ),
+ )
+ : null,
),
- if (finding != null)
- Positioned(
- top: 12,
- left: 20,
- right: 20,
- child: Center(
- child: Material(
- key: const ValueKey('super-reply-finding'),
- color: DesktopChrome.surface,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(
- DesktopChrome.controlRadius,
- ),
- side: BorderSide(color: DesktopChrome.rim),
- ),
- child: Padding(
- padding: const EdgeInsets.only(left: 12),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Flexible(
- child: Semantics(
- liveRegion: true,
- child: Text(
- finding.pages == 0
- ? 'Finding the original message…'
- : 'Finding the original message… '
- '${finding.pages} '
- '${finding.pages == 1 ? 'page' : 'pages'} back',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(),
- ),
+ Expanded(
+ child: Stack(
+ children: [
+ NotificationListener<ScrollNotification>(
+ onNotification: (event) {
+ if (event.depth != 0) return false;
+ if (event is ScrollStartNotification &&
+ event.dragDetails != null) {
+ _scrollRequest++;
+ _jumpingToEnd = false;
+ }
+ if (_jumpingToEnd) return false;
+ final id = c.selectedId;
+ final atEnd = event.metrics.extentAfter < 40;
+ _follow(id, atEnd);
+ // Once the scroll ends, so keeping the place never
+ // cuts a drag short.
+ if (event is ScrollEndNotification) {
+ _readEarlierNearTop(id, event.metrics);
+ }
+ if (atEnd) {
+ // A row still sending has no place in the transcript.
+ final sequence =
+ actualMessages.lastOrNull?.sequence ?? 0;
+ WidgetsBinding.instance.addPostFrameCallback((
+ _,
+ ) {
+ if (mounted && c.selectedId == id) {
+ _readToEnd(id, sequence);
+ }
+ });
+ }
+ return false;
+ },
+ child: SelectionArea(
+ child: CustomScrollView(
+ controller: _scroll[c.selectedId],
+ key: PageStorageKey(
+ 'super-messages-${c.tabId}-${c.selectedId}',
+ ),
+ // Pages read in grow upward from the rows first
+ // shown, new messages downward: no row on screen
+ // moves for either.
+ center: _newerRows,
+ slivers: [
+ // Its spinner runs only near the view.
+ SliverLayoutBuilder(
+ builder: (context, constraints) =>
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: EdgeInsets.only(
+ top: grid.AppDesktop.controlGap,
+ ),
+ child: _earlierRow(
+ near:
+ constraints
+ .remainingCacheExtent >
+ 0,
+ ),
+ ),
+ ),
+ ),
+ SliverList(
+ delegate: SliverChildBuilderDelegate(
+ (context, index) =>
+ row(split - 1 - index),
+ childCount: split,
+ findChildIndexCallback: (key) =>
+ switch (rowOf(key)) {
+ final i? when i < split =>
+ split - 1 - i,
+ _ => null,
+ },
),
),
- const SizedBox(width: 4),
- TextButton(
- onPressed: () => setState(() {
- _jumpRequest++;
- _finding = null;
- }),
- child: const Text('Cancel'),
+ SliverPadding(
+ key: _newerRows,
+ padding: EdgeInsets.only(
+ bottom: grid.AppDesktop.controlGap,
+ ),
+ sliver: SliverList(
+ delegate: SliverChildBuilderDelegate(
+ // Messages on their way end the list.
+ (context, index) => row(split + index),
+ childCount: entries.length - split,
+ findChildIndexCallback: (key) =>
+ switch (rowOf(key)) {
+ final i? when i >= split =>
+ i - split,
+ _ => null,
+ },
+ ),
+ ),
),
],
),
),
),
- ),
- ),
- if (_unread.away && _unread.lineAt(c.selectedId) != null)
- Positioned(
- top: grid.AppDesktop.controlGap,
- left: grid.AppDesktop.panelPadding,
- right: grid.AppDesktop.panelPadding,
- child: Center(
- child: SuperTabJumpToUnread(
- onPressed: () => _revealUnreadLine(c.selectedId),
- ),
- ),
- ),
- if (newCount > 0 || back || awayFromEnd)
- Positioned(
- bottom: 12,
- left: 20,
- right: 20,
- child: Center(
- child: Wrap(
- spacing: 8,
- runSpacing: 8,
- alignment: WrapAlignment.center,
- children: [
- if (back)
- FilledButton.icon(
- key: const ValueKey('super-reply-back'),
- onPressed: _goBack,
- icon: const Icon(
- AppIcons.chevronDown,
- size: 16,
+ if (finding != null)
+ Positioned(
+ top: 12,
+ left: 20,
+ right: 20,
+ child: Center(
+ child: Material(
+ key: const ValueKey('super-reply-finding'),
+ color: DesktopChrome.surface,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ side: BorderSide(color: DesktopChrome.rim),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.only(left: 12),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Flexible(
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ finding.pages == 0
+ ? 'Finding the original message…'
+ : 'Finding the original message… '
+ '${finding.pages} '
+ '${finding.pages == 1 ? 'page' : 'pages'} back',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ ),
+ ),
+ const SizedBox(width: 4),
+ TextButton(
+ onPressed: () => setState(() {
+ _jumpRequest++;
+ _finding = null;
+ }),
+ child: const Text('Cancel'),
+ ),
+ ],
+ ),
),
- label: const Text('Back to reply'),
),
- if (newCount > 0 || awayFromEnd)
- SuperTabJumpToLatest(
- onPressed: _jumpToLatest,
- count: newCount,
- more: moreNew,
+ ),
+ ),
+ if (newCount > 0 || back || awayFromEnd)
+ Positioned(
+ bottom: 12,
+ left: 20,
+ right: 20,
+ child: Center(
+ child: Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ alignment: WrapAlignment.center,
+ children: [
+ if (back)
+ FilledButton.icon(
+ key: const ValueKey('super-reply-back'),
+ onPressed: _goBack,
+ icon: const Icon(
+ AppIcons.chevronDown,
+ size: 16,
+ ),
+ label: const Text('Back to reply'),
+ ),
+ if (newCount > 0 || awayFromEnd)
+ SuperTabJumpToLatest(
+ onPressed: _jumpToLatest,
+ count: newCount,
+ more: moreNew,
+ ),
+ ],
),
- ],
- ),
- ),
+ ),
+ ),
+ ],
),
+ ),
],
),
),
diff --git a/desktop/test/agent_change_test.dart b/desktop/test/agent_change_test.dart
index 305aaa372..e0c27c0e6 100644
--- a/desktop/test/agent_change_test.dart
+++ b/desktop/test/agent_change_test.dart
@@ -28,6 +28,8 @@ class SwitchConnection extends MonitorConnection {
late AppNotifier app;
final events = <String>[];
String? closeError;
+ /// The machine's whole refusal, as a daemon sends it (a Swarm Buddy's, say).
+ Map<String, dynamic>? closeRefusal;
Completer<void>? holdClose;
Completer<void>? holdHandoff;
Map<String, dynamic> recent = {'asks': <String>[], 'events': <Object>[]};
@@ -78,6 +80,14 @@ class SwitchConnection extends MonitorConnection {
if (closeError != null) {
return {'error': 'SAVE_FAILED', 'detail': closeError};
}
+ if (closeRefusal case final refusal?) {
+ throw WsRequestFailure(
+ responseType: 'agent_close_result',
+ code: refusal['error'] as String,
+ detail: refusal['detail'] as String?,
+ payload: refusal,
+ );
+ }
await app.handleEventForTest('m', {
'type': 'agent_deleted',
'agentId': 'a0',
@@ -1166,6 +1176,29 @@ void main() {
expect(connection.creations.single['engine'], 'claude');
});
+ test('a Buddy keeps its agent, and the refusal says how to use another', () async {
+ // The daemon's refusal speaks of Stop Harness, which is no help to someone changing the agent.
+ final connection = SwitchConnection()
+ ..closeRefusal = {
+ 'error': 'BUDDY_PROTECTED',
+ 'detail':
+ 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.',
+ 'keptRunning': true,
+ };
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final pane = app.panes.single;
+ expect(
+ await app.changeAgent('m', 'a0', 'opencode'),
+ 'A Swarm Buddy keeps its agent. To use another agent, its person removes the Buddy and adds a new one.',
+ );
+ expect(connection.creations, isEmpty);
+ expect(app.panes.single, same(pane));
+ expect(pane.agentId, 'a0');
+ expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
+ });
+
test('a failed launch preserves the stopped session and permits a different agent', () async {
final connection = SwitchConnection()
..creationError = 'OpenCode is missing';
diff --git a/desktop/test/super_tab_agent_line_test.dart b/desktop/test/super_tab_agent_line_test.dart
index 819b94c74..f5e704341 100644
--- a/desktop/test/super_tab_agent_line_test.dart
+++ b/desktop/test/super_tab_agent_line_test.dart
@@ -118,8 +118,15 @@ Future<ConversationServer> _swarm(
}
Finder _row(String id) => find.byKey(ValueKey('super-member-$id'));
-Finder _line(String id, String text) =>
- find.descendant(of: _row(id), matching: find.text(text));
+
+/// The row's state, machine, model and effort, now on hover (Dee, 2026-10-30):
+/// the row's own line is its task.
+Finder _line(String id, String text) => find.ancestor(
+ of: _row(id),
+ matching: find.byWidgetPredicate(
+ (w) => w is Tooltip && (w.message ?? '').split('\n').contains(text),
+ ),
+);
void main() {
group('an agent row', () {
diff --git a/desktop/test/super_tab_jump_to_unread_shots_test.dart b/desktop/test/super_tab_jump_to_unread_shots_test.dart
new file mode 100644
index 000000000..05fa4e8a2
--- /dev/null
+++ b/desktop/test/super_tab_jump_to_unread_shots_test.dart
@@ -0,0 +1,225 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/message_link.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_UNREAD_SHOTS'];
+final _picture = GlobalKey();
+
+const _line = ValueKey('super-new-messages-line');
+const _jump = ValueKey('super-jump-unread');
+const _buddyChat = 'buddy-peer-lead';
+
+const _updates = [
+ 'Reading the offline queue before the reconnect.',
+ 'The reconnect keeps every queued edit in order.',
+ 'Two devices editing at once settle on the newest edit.',
+ 'Pushed the branch; the checks are running.',
+];
+
+Future<void> _shot(WidgetTester tester, String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+/// A Swarm read by the peer: the Lead chat and the peer's own Buddy chat,
+/// each with 60 messages from an agent, read on another device up to 20.
+ConversationServer _swarm() {
+ final server = ConversationServer();
+ server.state['projects'] = [projectFixture('lead', 'web-project', 'lead')];
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'peer', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.state['conversations'] = [
+ conversationFixture('lead', 'Lead'),
+ {
+ ...conversationFixture(_buddyChat, "scholes's Buddy"),
+ 'projectId': 'lead',
+ 'kind': 'buddy',
+ 'buddyOwnerId': 'peer',
+ },
+ ];
+ for (final (chat, author) in [
+ ('lead', {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'}),
+ (_buddyChat, {'kind': 'agent', 'id': 'buddy-agent', 'name': 'Buddy'}),
+ ]) {
+ for (var i = 1; i <= 60; i++) {
+ server.append(
+ '${_updates[i % _updates.length]} ($i)',
+ conversationId: chat,
+ );
+ server.messages.last['author'] = author;
+ }
+ }
+ server
+ ..markReadElsewhere('lead', 20, reader: 'peer')
+ ..markReadElsewhere(_buddyChat, 81, reader: 'peer');
+ return server;
+}
+
+Future<SuperTabController> _show(
+ WidgetTester tester,
+ ConversationServer server,
+ Brightness brightness,
+) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller(account: 'peer');
+ addTearDown(c.dispose);
+ final before = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = before);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => RepaintBoundary(key: _picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+Finder _list(String chat) =>
+ find.byKey(PageStorageKey('super-messages-tab-$chat'));
+
+ScrollPosition _scroll(WidgetTester tester, String chat) =>
+ tester.widget<ScrollView>(_list(chat)).controller!.position;
+
+/// Scrolls [chat]'s list by [by] in mouse-wheel steps, as a reader does.
+Future<void> _wheel(WidgetTester tester, String chat, double by) async {
+ final at = tester.getCenter(_list(chat));
+ final step = by.sign * 100;
+ for (var moved = 0.0; moved.abs() < by.abs(); moved += step) {
+ tester.binding.handlePointerEvent(
+ PointerScrollEvent(position: at, scrollDelta: Offset(0, step)),
+ );
+ await tester.pump();
+ }
+ await tester.pumpAndSettle();
+}
+
+/// The pill, when shown, is clear of the message list: it covers no message.
+void _coversNoMessage(WidgetTester tester, String chat) {
+ if (find.byKey(_jump).evaluate().isEmpty) return;
+ final pill = tester.getRect(find.byKey(_jump));
+ final list = tester.getRect(_list(chat));
+ expect(pill.bottom, lessThanOrEqualTo(list.top));
+}
+
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+
+ for (final brightness in Brightness.values) {
+ final theme = brightness.name;
+
+ testWidgets('project chat read past the line ($theme)', (tester) async {
+ final server = _swarm();
+ await _show(tester, server, brightness);
+ final position = _scroll(tester, 'lead');
+ await _wheel(tester, 'lead', 700);
+ await _shot(tester, 'project-read-past-line-$theme');
+ expect(find.byKey(_line).hitTestable(), findsNothing);
+ expect(position.extentAfter, greaterThan(40));
+ // Seen when the chat opened at it: reading on needs no way back.
+ expect(find.byKey(_jump), findsNothing);
+ _coversNoMessage(tester, 'lead');
+ });
+
+ testWidgets('project chat read back above the line ($theme)', (
+ tester,
+ ) async {
+ final server = _swarm();
+ await _show(tester, server, brightness);
+ await _wheel(tester, 'lead', -900);
+ await _shot(tester, 'project-read-above-line-$theme');
+ expect(find.byKey(_line).hitTestable(), findsNothing);
+ expect(find.byKey(_jump), findsNothing);
+ _coversNoMessage(tester, 'lead');
+ });
+
+ testWidgets('Buddy chat with Decisions for you, read past the line '
+ '($theme)', (tester) async {
+ final server = _swarm()
+ ..ask([
+ 'Ship the offline queue this week?',
+ ], conversationId: _buddyChat);
+ final c = await _show(tester, server, brightness);
+ await c.select(_buddyChat);
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Decisions for you'), findsOne);
+ await _wheel(tester, _buddyChat, 700);
+ await _shot(tester, 'buddy-read-past-line-$theme');
+ expect(find.byKey(_line).hitTestable(), findsNothing);
+ expect(find.byKey(_jump), findsNothing);
+ _coversNoMessage(tester, _buddyChat);
+ });
+
+ testWidgets('Buddy chat opened at a linked message, with Decisions for '
+ 'you ($theme)', (tester) async {
+ final server = _swarm()
+ ..ask([
+ 'Ship the offline queue this week?',
+ ], conversationId: _buddyChat);
+ final c = await _show(tester, server, brightness);
+ // The Buddy chat's newest message: its messages are 61 to 120.
+ c.openMessageLink(
+ const SwarmMessageLink(
+ tabId: 'tab',
+ conversationId: _buddyChat,
+ messageId: 'message-118',
+ ),
+ );
+ await tester.pumpAndSettle();
+ await _shot(tester, 'buddy-opened-at-link-$theme');
+ expect(c.selectedId, _buddyChat);
+ expect(find.byKey(_jump), findsOne);
+ final decisions = tester.getRect(
+ find.byKey(const ValueKey('super-pm-decisions')),
+ );
+ final pill = tester.getRect(find.byKey(_jump));
+ // Below Decisions for you, above the messages: covering neither.
+ expect(pill.top, greaterThanOrEqualTo(decisions.bottom));
+ _coversNoMessage(tester, _buddyChat);
+ await tester.tap(find.byKey(_jump));
+ await tester.pumpAndSettle();
+ await _shot(tester, 'buddy-back-at-line-$theme');
+ expect(find.byKey(_jump), findsNothing);
+ expect(
+ tester.getRect(find.byKey(const ValueKey('super-pm-decisions'))),
+ decisions,
+ );
+ });
+ }
+}
diff --git a/desktop/test/super_tab_new_messages_shots_test.dart b/desktop/test/super_tab_new_messages_shots_test.dart
index 82da42163..be9c35693 100644
--- a/desktop/test/super_tab_new_messages_shots_test.dart
+++ b/desktop/test/super_tab_new_messages_shots_test.dart
@@ -20,8 +20,8 @@ const _updates = [
'Pushed the branch; the checks are running.',
];
-/// The chat opened at its New messages line, and scrolled to the end with the
-/// pill that jumps back to it.
+/// The chat opened at its New messages line, and scrolled on to the end: the
+/// line was seen, so no pill jumps back to it.
void main() {
setUpAll(() async {
if (shots != null) await loadPreviewFonts();
@@ -90,8 +90,8 @@ void main() {
.position;
list.jumpTo(list.maxScrollExtent);
await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('super-jump-unread')), findsOne);
- await shot('pill');
+ expect(find.byKey(const ValueKey('super-jump-unread')), findsNothing);
+ await shot('read-on');
});
}
}
diff --git a/desktop/test/super_tab_new_messages_test.dart b/desktop/test/super_tab_new_messages_test.dart
index f3bfc4ac0..560e0985c 100644
--- a/desktop/test/super_tab_new_messages_test.dart
+++ b/desktop/test/super_tab_new_messages_test.dart
@@ -1,10 +1,13 @@
import 'dart:async';
+import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/message_link.dart';
import 'package:harness/super_tabs/view.dart';
import 'support/super_tab_fixture.dart';
@@ -21,8 +24,12 @@ ConversationServer _server(int count) {
return server;
}
-void _fromLead(ConversationServer server, String text) {
- server.append(text);
+void _fromLead(
+ ConversationServer server,
+ String text, {
+ String conversationId = 'lead',
+}) {
+ server.append(text, conversationId: conversationId);
server.messages.last['author'] = {
'kind': 'agent',
'id': 'lead-agent',
@@ -64,10 +71,10 @@ void main() {
.position;
/// Whether [finder]'s top edge is inside the message list's viewport.
- bool onScreen(WidgetTester tester, Finder finder) {
+ bool onScreen(WidgetTester tester, Finder finder, {String chat = 'lead'}) {
if (finder.evaluate().isEmpty) return false;
final list = tester.getRect(
- find.byKey(const PageStorageKey('super-messages-tab-lead')),
+ find.byKey(PageStorageKey('super-messages-tab-$chat')),
);
final top = tester.getTopLeft(finder).dy;
return top >= list.top && top < list.bottom;
@@ -398,21 +405,252 @@ void main() {
);
});
- testWidgets('scrolled away from the line, a pill jumps back to it', (
- tester,
- ) async {
+ testWidgets('once the line has been seen, reading on to the end offers no '
+ 'way back to it', (tester) async {
final server = _server(60)..markReadElsewhere('lead', 20);
await show(tester, server);
+ expect(onScreen(tester, find.byKey(_line)), isTrue);
+ final position = scroll(tester);
+ position.jumpTo(position.maxScrollExtent);
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, find.byKey(_line)), isFalse);
expect(find.byKey(_jump), findsNothing);
+ });
+
+ /// The offline chat's 60 messages from the Lead, read up to [mark].
+ ConversationServer offlineChat(int mark) {
+ final server = _server(2);
+ for (var i = 1; i <= 60; i++) {
+ _fromLead(server, 'Offline $i', conversationId: 'offline');
+ }
+ server.markReadElsewhere('offline', mark);
+ return server;
+ }
+
+ testWidgets('in a long chat, the line on screen as it opens offers no way '
+ 'back to it', (tester) async {
+ final server = _server(150)..markReadElsewhere('lead', 20);
+ await show(tester, server);
+ expect(onScreen(tester, find.byKey(_line)), isTrue);
+ expect(find.byKey(_jump), findsNothing);
+ // Seen, so reading on does not bring it back either.
final position = scroll(tester);
position.jumpTo(position.maxScrollExtent);
await tester.pumpAndSettle();
expect(onScreen(tester, find.byKey(_line)), isFalse);
+ expect(find.byKey(_jump), findsNothing);
+ });
+
+ testWidgets('a long chat opening at its line never shows the pill on the '
+ 'way there', (tester) async {
+ final server = _server(150)..markReadElsewhere('lead', 20);
+ final c = server.controller();
+ await c.refresh();
+ addTearDown(c.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ for (var frame = 0; frame < 60; frame++) {
+ await tester.pump(const Duration(milliseconds: 16));
+ expect(find.byKey(_jump), findsNothing, reason: 'frame $frame');
+ }
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, find.byKey(_line)), isTrue);
+ });
+
+ testWidgets('opened at a linked message with the line near the top, the '
+ 'pill is still the way back to it', (tester) async {
+ final c = await show(tester, offlineChat(8));
+ c.openMessageLink(
+ const SwarmMessageLink(
+ tabId: 'tab',
+ conversationId: 'offline',
+ messageId: 'message-50',
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ onScreen(
+ tester,
+ find.byKey(const ValueKey('super-message-message-50')),
+ chat: 'offline',
+ ),
+ isTrue,
+ );
+ // The jump to the link passed the line; the reader never saw it.
+ expect(onScreen(tester, find.byKey(_line), chat: 'offline'), isFalse);
expect(find.byKey(_jump), findsOneWidget);
- expect(find.text('Jump to first unread'), findsOneWidget);
await tester.tap(find.byKey(_jump));
await tester.pumpAndSettle();
- expect(onScreen(tester, find.byKey(_line)), isTrue);
+ expect(onScreen(tester, find.byKey(_line), chat: 'offline'), isTrue);
+ expect(find.byKey(_jump), findsNothing);
+ });
+
+ testWidgets('opened at a linked message below the line, a pill above the '
+ 'list takes the reader back to it, then goes', (tester) async {
+ final server = _server(2);
+ for (var i = 1; i <= 60; i++) {
+ _fromLead(server, 'Offline $i', conversationId: 'offline');
+ }
+ server.markReadElsewhere('offline', 22);
+ final c = await show(tester, server);
+ c.openMessageLink(
+ const SwarmMessageLink(
+ tabId: 'tab',
+ conversationId: 'offline',
+ messageId: 'message-60',
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'offline');
+ expect(
+ onScreen(
+ tester,
+ find.byKey(const ValueKey('super-message-message-60')),
+ chat: 'offline',
+ ),
+ isTrue,
+ );
+ expect(onScreen(tester, find.byKey(_line), chat: 'offline'), isFalse);
+ expect(find.byKey(_jump), findsOneWidget);
+ // In its own place above the list: it covers no message.
+ final list = tester.getRect(
+ find.byKey(const PageStorageKey('super-messages-tab-offline')),
+ );
+ expect(
+ tester.getRect(find.byKey(_jump)).bottom,
+ lessThanOrEqualTo(list.top),
+ );
+ await tester.tap(find.byKey(_jump));
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, find.byKey(_line), chat: 'offline'), isTrue);
+ expect(find.byKey(_jump), findsNothing);
+ final position = tester
+ .widget<ScrollView>(
+ find.byKey(const PageStorageKey('super-messages-tab-offline')),
+ )
+ .controller!
+ .position;
+ position.jumpTo(position.maxScrollExtent);
+ await tester.pumpAndSettle();
+ expect(find.byKey(_jump), findsNothing);
+ });
+
+ testWidgets('opened at a linked message above the line, the pill points '
+ 'down to it', (tester) async {
+ final server = _server(2);
+ for (var i = 1; i <= 60; i++) {
+ _fromLead(server, 'Offline $i', conversationId: 'offline');
+ }
+ server.markReadElsewhere('offline', 42);
+ final c = await show(tester, server);
+ c.openMessageLink(
+ const SwarmMessageLink(
+ tabId: 'tab',
+ conversationId: 'offline',
+ messageId: 'message-12',
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ onScreen(
+ tester,
+ find.byKey(const ValueKey('super-message-message-12')),
+ chat: 'offline',
+ ),
+ isTrue,
+ );
+ expect(onScreen(tester, find.byKey(_line), chat: 'offline'), isFalse);
+ expect(find.byKey(_jump), findsOneWidget);
+ expect(
+ find.descendant(
+ of: find.byKey(_jump),
+ matching: find.byIcon(AppIcons.chevronDown),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(_jump));
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, find.byKey(_line), chat: 'offline'), isTrue);
+ expect(find.byKey(_jump), findsNothing);
+ });
+
+ Finder offlineList() =>
+ find.byKey(const PageStorageKey('super-messages-tab-offline'));
+
+ Future<double> linkedTop(
+ WidgetTester tester,
+ ConversationServer server,
+ ) async {
+ final c = await show(tester, server);
+ c.openMessageLink(
+ const SwarmMessageLink(
+ tabId: 'tab',
+ conversationId: 'offline',
+ messageId: 'message-45',
+ ),
+ );
+ await tester.pumpAndSettle();
+ return tester
+ .getTopLeft(find.byKey(const ValueKey('super-message-message-45')))
+ .dy;
+ }
+
+ testWidgets('the pill\'s band appearing leaves the linked message where '
+ 'the link put it', (tester) async {
+ final read = await linkedTop(tester, offlineChat(62));
+ expect(find.byKey(_jump), findsNothing);
+ final unread = await linkedTop(tester, offlineChat(22));
+ expect(find.byKey(_jump), findsOneWidget);
+ expect(unread, read);
+ });
+
+ testWidgets('the band going as the reader scrolls up to the line moves the '
+ 'messages only by the scroll', (tester) async {
+ await linkedTop(tester, offlineChat(22));
+ expect(find.byKey(_jump), findsOneWidget);
+ final rows = find.byWidgetPredicate(
+ (w) =>
+ w.key is ValueKey<String> &&
+ (w.key! as ValueKey<String>).value.startsWith(
+ 'super-message-message-',
+ ),
+ );
+ var steps = 0;
+ while (find.byKey(_jump).evaluate().isNotEmpty && steps++ < 60) {
+ final list = tester.getRect(offlineList());
+ // A message in the middle of the view, still on screen after the step.
+ final middle = rows.evaluate().map((e) => e.widget.key!).firstWhere((
+ key,
+ ) {
+ final top = tester.getTopLeft(find.byKey(key)).dy;
+ return top > list.center.dy - 100 && top < list.center.dy + 100;
+ });
+ final before = tester.getTopLeft(find.byKey(middle)).dy;
+ tester.binding.handlePointerEvent(
+ PointerScrollEvent(
+ position: list.center,
+ scrollDelta: const Offset(0, -30),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ tester.getTopLeft(find.byKey(middle)).dy - before,
+ moreOrLessEquals(30, epsilon: .5),
+ reason: 'step $steps',
+ );
+ }
expect(find.byKey(_jump), findsNothing);
});
diff --git a/desktop/test/super_tab_roster_test.dart b/desktop/test/super_tab_roster_test.dart
index fc04212ec..fcc4c32a6 100644
--- a/desktop/test/super_tab_roster_test.dart
+++ b/desktop/test/super_tab_roster_test.dart
@@ -30,6 +30,7 @@ class RosterFixture {
late final controller = server.controller(account: account);
SuperTabAgent? opened;
SuperTabConversation? added;
+ String? answered;
final boundary = GlobalKey();
bool disposed = false;
@@ -72,6 +73,7 @@ class RosterFixture {
bool nativeState = true,
Brightness brightness = Brightness.dark,
double scale = 1,
+ DateTime Function()? now,
}) async {
await tester.pumpWidget(
RepaintBoundary(
@@ -93,8 +95,9 @@ class RosterFixture {
app: nativeState ? app : null,
onInvite: () {},
onAddAgent: (group) => added = group,
- onAnswer: (_) {},
+ onAnswer: (id) => answered = id,
onOpenAgent: (agent) => opened = agent,
+ now: now ?? DateTime.now,
),
),
),
@@ -107,10 +110,21 @@ class RosterFixture {
Finder inRow(int i, Finder child) =>
find.descendant(of: row(i), matching: child);
- /// The row's one line: state, machine, model and effort (team glance, 2026-10-27).
+ /// The row's details line: its task and the time since its last progress,
+ /// or its state in a word (Dee, 2026-10-30).
Finder line(int i) => find.byKey(ValueKey('super-member-line-agent-$i'));
String lineText(WidgetTester tester, int i) =>
tester.widget<Text>(line(i)).data!;
+
+ /// The hover's state line: state, machine, model and effort (team glance,
+ /// 2026-10-27), on the row until 2026-10-30.
+ String glanceText(WidgetTester tester, int i) => tester
+ .widgetList<Tooltip>(
+ find.ancestor(of: row(i), matching: find.byType(Tooltip)),
+ )
+ .single
+ .message!
+ .split('\n')[1];
HarnessActivity activity(WidgetTester tester, int i) =>
tester.widget<ActivityMark>(inRow(i, find.byType(ActivityMark))).activity;
@@ -193,7 +207,7 @@ void main() {
).toUtc().toIso8601String();
await f.controller.refresh();
await f.show(tester);
- expect(f.lineText(tester, 1), 'Limited until 09:05 · Test host');
+ expect(f.glanceText(tester, 1), 'Limited until 09:05 · Test host');
expect(rowTooltip(tester, f, 1), contains('Limited until 09:05'));
await captureBoundary(
tester,
@@ -211,7 +225,7 @@ void main() {
await f.controller.refresh();
await tester.pumpAndSettle();
expect(find.textContaining('Limited until'), findsNothing);
- expect(f.lineText(tester, 1), 'Assigned · Test host');
+ expect(f.glanceText(tester, 1), 'Assigned · Test host');
expect(
rowTooltip(tester, f, 1),
contains('Assigned to "Offline editing"'),
@@ -221,50 +235,47 @@ void main() {
},
);
- testWidgets(
- 'agent tooltip combines known model, machine, task and activity',
- (tester) async {
- final f = await fixture(tester);
- final lastActive = DateTime.now().subtract(const Duration(hours: 2));
- (f.server.state['agents'] as List)[1]['configuration'] = {
- 'engine': 'claude',
- 'model': 'opus',
- };
- (f.server.state['conversations'] as List)[1]['assignment'] = {
- 'agentId': 'agent-1',
- 'status': 'working',
- };
- f.app.stateOf('m')!.agents = [
- Agent(
- id: 'a1',
- name: 'Multiply',
- engine: 'claude',
- lastActivityAt: lastActive,
- ),
- ];
- f.app.stateOf('m')!.processingAgentIds.add('a1');
- await f.controller.refresh();
- await f.show(tester);
- expect(
- rowTooltip(tester, f, 1),
- contains(
- 'Claude Opus · Test host · Working on "Offline editing" · Last active 2 hours ago',
- ),
- );
- expect(
- rowTooltip(tester, f, 1),
- contains('Sage · Engineer · openharness'),
- );
- expect(f.lineText(tester, 1), 'Working · Test host · Opus');
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: Offset.zero);
- await mouse.moveTo(tester.getCenter(f.row(1)));
- await tester.pumpAndSettle(const Duration(milliseconds: 800));
- expect(find.text(rowTooltip(tester, f, 1)), findsOneWidget);
- await mouse.removePointer();
- await f.close(tester);
- },
- );
+ testWidgets('agent tooltip combines known model, machine, task and activity', (
+ tester,
+ ) async {
+ final f = await fixture(tester);
+ final lastActive = DateTime.now().subtract(const Duration(hours: 2));
+ (f.server.state['agents'] as List)[1]['configuration'] = {
+ 'engine': 'claude',
+ 'model': 'opus',
+ };
+ (f.server.state['conversations'] as List)[1]['assignment'] = {
+ 'agentId': 'agent-1',
+ 'status': 'working',
+ };
+ f.app.stateOf('m')!.agents = [
+ Agent(
+ id: 'a1',
+ name: 'Multiply',
+ engine: 'claude',
+ lastActivityAt: lastActive,
+ ),
+ ];
+ f.app.stateOf('m')!.processingAgentIds.add('a1');
+ await f.controller.refresh();
+ await f.show(tester);
+ // Who, then where and on what, then the task, then when (Dee, 2026-10-30).
+ expect(
+ rowTooltip(tester, f, 1),
+ 'Sage · Engineer · openharness · Claude\n'
+ 'Working · Test host · Opus\n'
+ 'Working on "Offline editing"\n'
+ 'Last active 2 hours ago',
+ );
+ expect(f.glanceText(tester, 1), 'Working · Test host · Opus');
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: Offset.zero);
+ await mouse.moveTo(tester.getCenter(f.row(1)));
+ await tester.pumpAndSettle(const Duration(milliseconds: 800));
+ expect(find.text(rowTooltip(tester, f, 1)), findsOneWidget);
+ await mouse.removePointer();
+ await f.close(tester);
+ });
// The PM's row and details read the configuration's raw "opus" or "claude-opus-5-5" (2026-10-28): both name the
// model as people know it.
@@ -279,9 +290,9 @@ void main() {
};
await f.controller.refresh();
await f.show(tester);
- expect(f.lineText(tester, 1), contains('Opus 5.5'));
- expect(f.lineText(tester, 1), isNot(contains('unknown')));
- await tester.tap(f.row(1));
+ expect(f.glanceText(tester, 1), contains('Opus 5.5'));
+ expect(f.glanceText(tester, 1), isNot(contains('unknown')));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(
find.descendant(
@@ -305,10 +316,10 @@ void main() {
);
expect(rowTooltip(tester, f, 0), contains('Codex'));
// No native state and no task: idle as far as the Swarm's work goes; the tooltip says what is not known.
- expect(f.lineText(tester, 0), 'Idle');
+ expect(f.glanceText(tester, 0), 'Idle');
expect(rowTooltip(tester, f, 0), contains('Status unavailable'));
expect(rowTooltip(tester, f, 0), isNot(contains('Last active')));
- await tester.tap(f.row(0));
+ await tester.longPress(f.row(0));
await tester.pumpAndSettle();
for (final absent in [
'Model',
@@ -345,7 +356,7 @@ void main() {
await f.controller.refresh();
await f.show(tester);
expect(f.activity(tester, 1), HarnessActivity.needsInput);
- expect(f.lineText(tester, 1), 'Waiting · Test host');
+ expect(f.glanceText(tester, 1), 'Waiting · Test host');
expect(rowTooltip(tester, f, 1), contains('Needs input'));
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
await f.close(tester);
@@ -365,7 +376,7 @@ void main() {
await f.show(tester);
final tooltip = rowTooltip(tester, f, 1);
expect(tooltip, contains(title));
- expect(f.lineText(tester, 1), 'Working · Test host');
+ expect(f.glanceText(tester, 1), 'Working · Test host');
expect(tester.getSize(f.line(1)).height, lessThan(30));
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
@@ -418,7 +429,7 @@ void main() {
];
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.widgetWithText(TextButton, 'Offline editing'), findsOneWidget);
@@ -462,7 +473,7 @@ void main() {
);
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(
find.byTooltip('https://github.com/acme/project/pull/42'),
@@ -495,7 +506,7 @@ void main() {
}
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(
find.byTooltip('https://github.com/acme/project/pull/42'),
@@ -532,7 +543,7 @@ void main() {
};
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(
find.byTooltip('https://github.com/acme/project/pull/42'),
@@ -567,7 +578,7 @@ void main() {
}
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.text('Latest PR'), findsNothing);
expect(f.controller.messages('offline').length, 300);
@@ -592,7 +603,7 @@ void main() {
};
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.text('Unrecognized setting'), findsOneWidget);
expect(find.text('unmapped-mode-id'), findsNothing);
@@ -620,7 +631,7 @@ void main() {
};
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.text('Read only, asks you'), findsOneWidget);
expect(find.text('Unrecognized setting'), findsNothing);
@@ -645,7 +656,7 @@ void main() {
};
await f.controller.refresh();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.text('Reads only, never asks'), findsOneWidget);
expect(find.text('Unrecognized setting'), findsNothing);
@@ -669,7 +680,7 @@ void main() {
rowTooltip(tester, f, 1),
contains('Waiting for a person to answer'),
);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.text('Who can answer'), findsOneWidget);
expect(
@@ -684,7 +695,7 @@ void main() {
await tester.pumpAndSettle();
f.app.stateOf('m')!.blockedAgents.clear();
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.text('Who can answer'), findsNothing);
await f.close(tester);
@@ -694,7 +705,7 @@ void main() {
group('agent details Owner', () {
Future<void> openDetails(WidgetTester tester, RosterFixture f) async {
await f.show(tester);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
}
@@ -753,7 +764,7 @@ void main() {
expect(f.controller.snapshot!.agents.first.id, 'agent-0');
expect(f.controller.snapshot!.agents.first.harnessId, 'replacement');
expect(f.controller.snapshot!.agents.first.engine, 'claude');
- await tester.tap(f.row(0));
+ await tester.longPress(f.row(0));
await tester.pumpAndSettle();
expect(find.text('Claude'), findsOneWidget);
expect(find.text('Sonnet'), findsOneWidget);
@@ -1188,7 +1199,7 @@ void main() {
tester.getTopLeft(f.row(1)).dy,
lessThan(tester.getTopLeft(f.row(3)).dy),
);
- await tester.tap(f.row(1));
+ await tester.longPress(f.row(1));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
await tester.tap(find.widgetWithText(FilledButton, 'Open terminal'));
@@ -1270,12 +1281,12 @@ void main() {
..['assignment'] = {'agentId': 'agent-1', 'status': 'planned'};
await f.controller.refresh();
await f.show(tester, nativeState: false);
- expect(f.lineText(tester, 1), 'Assigned');
+ expect(f.glanceText(tester, 1), 'Assigned');
expect(
rowTooltip(tester, f, 1),
contains('Assigned to "Polish navigation"'),
);
- expect(f.lineText(tester, 0), 'Idle');
+ expect(f.glanceText(tester, 0), 'Idle');
// Unseen by this computer, the Swarm's held task gives the mark; the words
// still say only Assigned.
expect(f.activity(tester, 1), HarnessActivity.working);
@@ -1331,7 +1342,7 @@ void main() {
: 'Assigned to "Polish navigation"';
expect(f.activity(tester, 1), shown);
expect(
- f.lineText(tester, 1),
+ f.glanceText(tester, 1),
activity == HarnessActivity.working
? 'Working · Test host'
: 'Assigned · Test host',
@@ -1343,7 +1354,7 @@ void main() {
}
await f.show(tester, nativeState: false);
expect(f.activity(tester, 1), HarnessActivity.working);
- expect(f.lineText(tester, 1), 'Assigned');
+ expect(f.glanceText(tester, 1), 'Assigned');
await f.close(tester);
},
);
@@ -1362,7 +1373,7 @@ void main() {
(f.server.state['conversations'] as List).add(currentTask);
await f.controller.refresh();
await f.show(tester, nativeState: false);
- expect(f.lineText(tester, 1), 'Assigned');
+ expect(f.glanceText(tester, 1), 'Assigned');
expect(
rowTooltip(tester, f, 1),
contains('Assigned to "Polish navigation"'),
@@ -1372,7 +1383,7 @@ void main() {
(currentTask['assignment'] as Map)['status'] = 'cancelled';
await f.controller.refresh();
await tester.pumpAndSettle();
- expect(f.lineText(tester, 1), 'Idle');
+ expect(f.glanceText(tester, 1), 'Idle');
expect(rowTooltip(tester, f, 1), isNot(contains('Polish navigation')));
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
await f.close(tester);
@@ -1391,7 +1402,8 @@ void main() {
),
(
'review',
- HarnessActivity.idle,
+ // In review waits on its reviewer whatever this Mac reads (Dee, 2026-10-30).
+ HarnessActivity.done,
'Waiting for review on "Polish navigation"',
'In review · Test host',
),
@@ -1408,7 +1420,7 @@ void main() {
await f.controller.refresh();
await f.show(tester);
expect(f.activity(tester, 1), activity);
- expect(f.lineText(tester, 1), line);
+ expect(f.glanceText(tester, 1), line);
expect(rowTooltip(tester, f, 1), contains(label));
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
}
@@ -1481,7 +1493,7 @@ void main() {
];
await f.show(tester);
expect(f.activity(tester, 1), activity);
- expect(f.lineText(tester, 1), '$line · Test host');
+ expect(f.glanceText(tester, 1), '$line · Test host');
expect(rowTooltip(tester, f, 1), contains(status));
expect(f.inRow(1, find.textContaining('Working')), findsNothing);
expect(rowTooltip(tester, f, 1), isNot(contains('Working on')));
@@ -1630,10 +1642,10 @@ void main() {
expect(tops.toSet(), hasLength(expected.length));
// The words agree with the mark where something stops the agent; a task
// with no turn seen still reads Assigned.
- expect(f.lineText(tester, 6), startsWith('Down'));
- expect(f.lineText(tester, 7), startsWith('Down'));
- expect(f.lineText(tester, 8), startsWith('Down'));
- expect(f.lineText(tester, 1), startsWith('Assigned'));
+ expect(f.glanceText(tester, 6), startsWith('Down'));
+ expect(f.glanceText(tester, 7), startsWith('Down'));
+ expect(f.glanceText(tester, 8), startsWith('Down'));
+ expect(f.glanceText(tester, 1), startsWith('Assigned'));
final saved = grid.AppTheme.brightness.value;
addTearDown(() => grid.AppTheme.brightness.value = saved);
for (final brightness in Brightness.values) {
@@ -1681,13 +1693,13 @@ void main() {
reports(mac: silent, team: now);
await f.controller.refresh();
await f.show(tester);
- expect(f.lineText(tester, 1), startsWith('Idle · Mac Studio'));
+ expect(f.glanceText(tester, 1), startsWith('Idle · Mac Studio'));
expect(f.activity(tester, 1), HarnessActivity.idle);
reports(mac: now, team: silent);
await f.controller.refresh();
await f.show(tester);
expect(f.activity(tester, 1), HarnessActivity.offline);
- expect(f.lineText(tester, 1), startsWith('Down'));
+ expect(f.glanceText(tester, 1), startsWith('Down'));
await f.close(tester);
},
);
@@ -1732,7 +1744,11 @@ void main() {
await f.show(tester, nativeState: false);
expect(f.activity(tester, 1), HarnessActivity.working);
expect(f.activity(tester, 3), HarnessActivity.idle);
- expect(find.text('Private plans'), findsNothing);
+ // Nor its title, on the row's task line or on hover.
+ expect(find.textContaining('Private plans'), findsNothing);
+ expect(find.textContaining('Mira and Sparky'), findsNothing);
+ expect(f.lineText(tester, 3), 'Idle');
+ expect(rowTooltip(tester, f, 3), isNot(contains('Private plans')));
// The same group, once the reader is in it, does change the mark.
((private['audience'] as Map)['people'] as List).add({'id': 'owner'});
await f.controller.refresh();
@@ -1777,7 +1793,7 @@ void main() {
expect(f.activity(tester, 0), HarnessActivity.idle);
// Lost work reads Lost on its line; its mark is the tabs' Offline.
expect(f.activity(tester, 4), HarnessActivity.offline);
- expect(f.lineText(tester, 4), startsWith('Lost'));
+ expect(f.glanceText(tester, 4), startsWith('Lost'));
final tops = [
for (final i in [3, 1, 0, 4]) tester.getTopLeft(f.row(i)).dy,
];
@@ -2051,4 +2067,682 @@ void main() {
);
}
}
+
+ group('Swarm-first marks (Dee, 2026-10-30)', () {
+ /// A task the Swarm holds for [agent], with its last progress [ago] and
+ /// its lease, as the backend sends them (assignment.progressAt and
+ /// leaseUntil, five minutes apart).
+ Map<String, dynamic> task(
+ String id,
+ String title,
+ String agent,
+ String status, {
+ required Duration ago,
+ Duration lease = const Duration(minutes: 5),
+ }) {
+ final at = DateTime.now().subtract(ago).millisecondsSinceEpoch;
+ return {
+ ...conversationFixture(id, title),
+ 'assignment': {
+ 'agentId': agent,
+ 'status': status,
+ 'progressAt': at,
+ 'leaseUntil': at + lease.inMilliseconds,
+ },
+ };
+ }
+
+ /// This Mac sees the agents' machine (a shared one, as Dee's Mac sees the
+ /// Mac Studio) and has no turn reported for any of them: it reads idle.
+ void seenIdleHere(RosterFixture f) {
+ f.app.stateOf('m')!.agents = [
+ for (final i in [0, 1, 3])
+ Agent(id: 'a$i', name: 'n$i', engine: 'codex'),
+ ];
+ }
+
+ testWidgets(
+ 'an agent this Mac reads as idle shows the Swarm\'s fresh work: working and in review',
+ (tester) async {
+ final f = await fixture(tester);
+ (f.server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 4, seconds: 10),
+ ),
+ task(
+ 't3',
+ 'Reviewer names',
+ 'agent-3',
+ 'review',
+ ago: const Duration(minutes: 20, seconds: 10),
+ ),
+ ]);
+ await f.controller.refresh();
+ seenIdleHere(f);
+ await f.show(tester);
+ expect(f.activity(tester, 1), HarnessActivity.working);
+ expect(f.activity(tester, 3), HarnessActivity.done);
+ expect(f.activity(tester, 0), HarnessActivity.idle);
+ // The details line: the task in plain words and the time since its
+ // last progress; no task, the state in a word.
+ expect(f.lineText(tester, 1), 'Sidebar rescan fix · 4m');
+ expect(f.lineText(tester, 3), 'Reviewer names · 20m');
+ expect(f.lineText(tester, 0), 'Idle');
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'a task past its lease is status unavailable; a done task waits for its merge',
+ (tester) async {
+ final f = await fixture(tester);
+ final done =
+ task(
+ 't3',
+ 'Reviewer names',
+ 'agent-3',
+ 'done',
+ ago: const Duration(minutes: 30),
+ )
+ ..['cards'] = {
+ 'pullRequests': [
+ <String, Object>{
+ 'url': 'https://github.com/o/r/pull/7',
+ 'messageId': 'pr-card',
+ },
+ ],
+ };
+ (f.server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 9),
+ ),
+ done,
+ ]);
+ await f.controller.refresh();
+ await f.show(tester, nativeState: false);
+ // Nothing has said how agent-1 is for longer than its lease.
+ expect(f.activity(tester, 1), HarnessActivity.unknown);
+ expect(f.lineText(tester, 1), 'Sidebar rescan fix · 9m');
+ // Its pull request not merged yet: waiting, with the task it waits on.
+ expect(f.activity(tester, 3), HarnessActivity.done);
+ expect(f.lineText(tester, 3), 'Reviewer names · 30m');
+ // Merged: nothing left for it, idle.
+ ((done['cards'] as Map)['pullRequests'] as List).first['mergedAt'] =
+ DateTime.now().millisecondsSinceEpoch;
+ await f.controller.refresh();
+ await tester.pumpAndSettle();
+ expect(f.activity(tester, 3), HarnessActivity.idle);
+ expect(f.lineText(tester, 3), 'Idle');
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'this Mac\'s reading wins only when it is live; past its lease a held task is status unavailable',
+ (tester) async {
+ final f = await fixture(tester);
+ (f.server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 9),
+ ),
+ task(
+ 't3',
+ 'Reviewer names',
+ 'agent-3',
+ 'review',
+ ago: const Duration(minutes: 2),
+ ),
+ ]);
+ await f.controller.refresh();
+ seenIdleHere(f);
+ // A turn running here is fresher than a review status.
+ f.app.stateOf('m')!.processingAgentIds.add('a3');
+ await f.show(tester);
+ expect(f.activity(tester, 3), HarnessActivity.working);
+ // Past its lease, nobody vouches for it: a held task is never idle
+ // while the Swarm holds it, and this Mac's idle is no live reading.
+ expect(f.activity(tester, 1), HarnessActivity.unknown);
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'machine, engine, model and effort are on hover, not on the row; most recent progress first within a mark',
+ (tester) async {
+ final f = await fixture(tester);
+ final agents = f.server.state['agents'] as List;
+ (agents[1] as Map)['configuration'] = {
+ 'engine': 'claude',
+ 'model': 'opus',
+ 'effort': 'high',
+ };
+ f.server.state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'name': 'Mac Studio',
+ 'contributorId': 'owner',
+ 'observation': {
+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,
+ },
+ },
+ ];
+ (f.server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 4),
+ ),
+ task(
+ 't3',
+ 'Reviewer names',
+ 'agent-3',
+ 'working',
+ ago: const Duration(minutes: 1),
+ ),
+ ]);
+ await f.controller.refresh();
+ await f.show(tester, nativeState: false);
+ final tip = rowTooltip(tester, f, 1);
+ expect(tip, contains('Mac Studio'));
+ expect(tip, contains('Claude'));
+ expect(tip, contains('Opus'));
+ expect(tip, contains('high'));
+ expect(tip, contains('Sidebar rescan fix'));
+ final line = f.lineText(tester, 1);
+ for (final word in ['Claude', 'Opus', 'high', 'Mac Studio']) {
+ expect(line, isNot(contains(word)));
+ }
+ // Both working: the one heard from a minute ago comes first.
+ expect(
+ tester.getTopLeft(f.row(3)).dy,
+ lessThan(tester.getTopLeft(f.row(1)).dy),
+ );
+ expect(
+ tester.getTopLeft(f.row(1)).dy,
+ lessThan(tester.getTopLeft(f.row(0)).dy),
+ );
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'clicking a row opens its task\'s conversation; a needs-you row its question; no task, its details',
+ (tester) async {
+ final f = await fixture(tester);
+ (f.server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 1),
+ ),
+ task(
+ 't3',
+ 'Pick a sign-in page',
+ 'agent-3',
+ 'needs_human',
+ ago: const Duration(minutes: 12),
+ ),
+ ]);
+ await f.controller.refresh();
+ await f.show(tester, nativeState: false);
+ expect(f.activity(tester, 3), HarnessActivity.needsInput);
+ await tester.tap(f.row(1));
+ await tester.pumpAndSettle();
+ expect(f.answered, 't1');
+ await tester.tap(f.row(3));
+ await tester.pumpAndSettle();
+ expect(f.answered, 't3');
+ f.answered = null;
+ await tester.tap(f.row(0));
+ await tester.pumpAndSettle();
+ expect(f.answered, isNull);
+ expect(find.widgetWithText(AlertDialog, 'Role'), findsOneWidget);
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'every mark, as a Mac that sees the agents\' machine only through sharing shows them (screenshots)',
+ (tester) async {
+ final f = await fixture(tester);
+ await tester.binding.setSurfaceSize(const Size(340, 640));
+ final now = DateTime.now().millisecondsSinceEpoch;
+ // The agents run on the Mac Studio; this Mac reads it through sharing
+ // and has no turn reported for any of them (Dee's view, 2026-10-30).
+ f.server.state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'name': 'Mac Studio',
+ 'contributorId': 'owner',
+ 'observation': {'receivedAt': now},
+ },
+ ];
+ final agents = f.server.state['agents'] as List;
+ final base = (agents[1] as Map).cast<String, Object>();
+ for (final (i, name) in [
+ (4, 'Juno'),
+ (5, 'Iris'),
+ (6, 'Orion'),
+ (7, 'Wren'),
+ (8, 'Reed'),
+ (9, 'Milo'),
+ ]) {
+ agents.add({
+ ...base,
+ 'id': 'agent-$i',
+ 'harnessId': 'a$i',
+ 'name': name,
+ 'displayName': name,
+ });
+ }
+ (agents[8] as Map)['downSince'] = '2026-10-30T01:00:00.000Z';
+ final merge =
+ task(
+ 't5',
+ 'Reviewer names in the Swarm',
+ 'agent-5',
+ 'done',
+ ago: const Duration(minutes: 26),
+ )
+ ..['cards'] = <String, Object>{
+ 'pullRequests': [
+ <String, Object>{
+ 'url': 'https://github.com/o/r/pull/7',
+ 'messageId': 'pr-card',
+ },
+ ],
+ };
+ (f.server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 4),
+ ),
+ task(
+ 't3',
+ 'Pick a sign-in page',
+ 'agent-3',
+ 'needs_human',
+ ago: const Duration(minutes: 12),
+ ),
+ task(
+ 't4',
+ 'Agents list status marks',
+ 'agent-4',
+ 'review',
+ ago: const Duration(minutes: 7),
+ ),
+ merge,
+ task(
+ 't6',
+ 'Phone Home screen',
+ 'agent-6',
+ 'working',
+ ago: const Duration(minutes: 11),
+ ),
+ task(
+ 't7',
+ 'Night digest',
+ 'agent-7',
+ 'lost',
+ ago: const Duration(hours: 3),
+ ),
+ {
+ ...task(
+ 't9',
+ 'Firmware build',
+ 'agent-9',
+ 'working',
+ ago: const Duration(minutes: 2),
+ ),
+ 'liveness': {
+ 'state': 'orphaned',
+ 'why': 'start-failed',
+ 'since': now,
+ },
+ },
+ ]);
+ await f.controller.refresh();
+ f.app.stateOf('m')!.agents = [
+ for (final i in [0, 1, 3, 4, 5, 7])
+ Agent(id: 'a$i', name: 'n$i', engine: 'codex'),
+ ];
+ final expected = {
+ 3: HarnessActivity.needsInput,
+ 4: HarnessActivity.done,
+ 5: HarnessActivity.done,
+ 1: HarnessActivity.working,
+ 0: HarnessActivity.idle,
+ 7: HarnessActivity.offline,
+ };
+ final saved = grid.AppTheme.brightness.value;
+ addTearDown(() => grid.AppTheme.brightness.value = saved);
+ for (final brightness in Brightness.values) {
+ grid.AppTheme.brightness.value = brightness;
+ await f.show(tester, brightness: brightness);
+ for (final MapEntry(key: i, value: activity) in expected.entries) {
+ expect(f.activity(tester, i), activity, reason: 'agent-$i');
+ }
+ // Unseen here and past its lease: nobody can say; stopped; a failed
+ // start.
+ expect(f.activity(tester, 6), HarnessActivity.unknown);
+ expect(f.activity(tester, 8), HarnessActivity.paused);
+ expect(f.activity(tester, 9), HarnessActivity.failed);
+ expect(f.lineText(tester, 1), 'Sidebar rescan fix · 4m');
+ await captureBoundary(
+ tester,
+ f.boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary,
+ captureDir,
+ 'agents-every-mark-from-another-mac-${brightness.name}',
+ );
+ }
+ await f.close(tester);
+ },
+ );
+
+ /// The agents' machine as the Swarm last heard it, [ago] before [at]:
+ /// which sessions run and each one's last screen change (backend
+ /// observation, liveness.ts reportRenewedAt).
+ void reports(
+ RosterFixture f, {
+ required DateTime at,
+ Map<String, Duration> progress = const {},
+ Duration ago = Duration.zero,
+ }) => f.server.state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'name': 'Mac Studio',
+ 'contributorId': 'owner',
+ 'observation': {
+ 'receivedAt': at.subtract(ago).millisecondsSinceEpoch,
+ 'runningHarnessIds': [for (final id in progress.keys) id],
+ 'stoppedHarnessIds': <String>[],
+ 'harnessProgress': {
+ for (final MapEntry(:key, :value) in progress.entries)
+ key: at.subtract(value).millisecondsSinceEpoch,
+ },
+ },
+ },
+ ];
+
+ testWidgets(
+ 'a quiet agent its machine still reports running is working, past the lease its last post set (review of #2281)',
+ (tester) async {
+ final f = await fixture(tester);
+ // Its last status 9 minutes ago; its machine showed its screen change
+ // a minute ago: the Swarm holds its task (liveness.ts leaseEnd).
+ reports(
+ f,
+ at: DateTime.now(),
+ progress: {'a1': const Duration(minutes: 1)},
+ );
+ (f.server.state['conversations'] as List).add(
+ task(
+ 't1',
+ 'Long test suite',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 9),
+ ),
+ );
+ await f.controller.refresh();
+ seenIdleHere(f);
+ await f.show(tester);
+ expect(f.activity(tester, 1), HarnessActivity.working);
+ await f.show(tester, nativeState: false);
+ expect(f.activity(tester, 1), HarnessActivity.working);
+ // A screen still for 26 minutes no longer renews it: 5 minutes after
+ // its last renewal at 25, nobody vouches for it.
+ reports(
+ f,
+ at: DateTime.now(),
+ progress: {'a1': const Duration(minutes: 31)},
+ );
+ await f.controller.refresh();
+ await f.show(tester);
+ expect(f.activity(tester, 1), HarnessActivity.unknown);
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'work handed over for review waits (✓) while its status still says working',
+ (tester) async {
+ final f = await fixture(tester);
+ final handed = task(
+ 't1',
+ 'Agents list marks',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 40),
+ );
+ (handed['assignment'] as Map)['result'] =
+ 'Ready for review: PR #2281 at b4c4fa903';
+ (f.server.state['conversations'] as List).add(handed);
+ await f.controller.refresh();
+ seenIdleHere(f);
+ await f.show(tester);
+ expect(f.activity(tester, 1), HarnessActivity.done);
+ // Its words say so too, as for work in review.
+ expect(f.glanceText(tester, 1), startsWith('In review'));
+ expect(
+ rowTooltip(tester, f, 1),
+ contains('Waiting for review on "Agents list marks"'),
+ );
+ expect(rowTooltip(tester, f, 1), isNot(contains('Assigned')));
+ // Once a review finds problems, it is the Engineer's to fix again.
+ (handed['assignment'] as Map)['reviewFoundAt'] =
+ DateTime.now().millisecondsSinceEpoch;
+ await f.controller.refresh();
+ await tester.pumpAndSettle();
+ expect(f.activity(tester, 1), HarnessActivity.unknown);
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'a Mac whose clock runs 5 minutes fast still reads a live lease by the Swarm\'s clock',
+ (tester) async {
+ final f = await fixture(tester);
+ final server = DateTime.now();
+ // The first report read is only a baseline; the next one, newer,
+ // proves the server's time (review of #2281).
+ reports(f, at: server.subtract(const Duration(seconds: 10)));
+ await f.controller.refresh();
+ await f.show(
+ tester,
+ nativeState: false,
+ now: () => DateTime.now().add(const Duration(minutes: 5)),
+ );
+ reports(f, at: server);
+ // A minute and a half of its five left by the server's clock.
+ (f.server.state['conversations'] as List).add(
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 3, seconds: 30),
+ ),
+ );
+ await f.controller.refresh();
+ await f.show(
+ tester,
+ nativeState: false,
+ now: () => DateTime.now().add(const Duration(minutes: 5)),
+ );
+ expect(f.activity(tester, 1), HarnessActivity.working);
+ expect(f.lineText(tester, 1), 'Sidebar rescan fix · 3m');
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'a Swarm whose machines all went silent hours ago is read by this Mac\'s clock, not their last report',
+ (tester) async {
+ final f = await fixture(tester);
+ final now = DateTime.now();
+ reports(
+ f,
+ at: now.subtract(const Duration(hours: 2)),
+ progress: {'a1': Duration.zero},
+ );
+ (f.server.state['conversations'] as List).add(
+ task(
+ 't1',
+ 'Night digest',
+ 'agent-1',
+ 'working',
+ ago: const Duration(hours: 2, minutes: 1),
+ ),
+ );
+ await f.controller.refresh();
+ await f.show(tester, nativeState: false);
+ expect(f.activity(tester, 1), isNot(HarnessActivity.working));
+ expect(f.lineText(tester, 1), 'Night digest · 2h');
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'on a quiet Swarm the list ticks: the age moves and an expired lease stops showing working',
+ (tester) async {
+ final f = await fixture(tester);
+ var clock = DateTime.now();
+ reports(f, at: clock);
+ (f.server.state['conversations'] as List).add(
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 4, seconds: 50),
+ ),
+ );
+ await f.controller.refresh();
+ await f.show(tester, nativeState: false, now: () => clock);
+ expect(f.activity(tester, 1), HarnessActivity.working);
+ expect(f.lineText(tester, 1), 'Sidebar rescan fix · 4m');
+ // Nothing changes in the Swarm; only time passes.
+ clock = clock.add(const Duration(seconds: 30));
+ await tester.pump(const Duration(seconds: 30));
+ expect(f.activity(tester, 1), HarnessActivity.unknown);
+ expect(f.lineText(tester, 1), 'Sidebar rescan fix · 5m');
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'a group a broken server sends that the viewer may not read gives no mark, title, click or details',
+ (tester) async {
+ final f = await fixture(tester);
+ (f.server.state['people'] as List).add({
+ 'id': 'mira',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ f.server.parts.leaksHiddenGroups = true;
+ (f.server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ {
+ ...task(
+ 'private',
+ 'Private plans',
+ 'agent-3',
+ 'working',
+ ago: const Duration(minutes: 1),
+ ),
+ 'audience': {
+ 'people': [
+ {'id': 'mira'},
+ ],
+ },
+ },
+ {
+ ...task(
+ 'buddy',
+ 'Mira and Sparky',
+ 'agent-1',
+ 'needs_human',
+ ago: const Duration(minutes: 1),
+ ),
+ 'kind': 'buddy',
+ 'buddyOwnerId': 'mira',
+ },
+ ]);
+ await f.controller.refresh();
+ // The broken server did send them.
+ expect(
+ f.controller.snapshot!.conversations.map((g) => g.id),
+ containsAll(['private', 'buddy']),
+ );
+ await f.show(tester, nativeState: false);
+ expect(f.activity(tester, 3), HarnessActivity.idle);
+ expect(f.activity(tester, 1), HarnessActivity.idle);
+ for (final title in ['Private plans', 'Mira and Sparky']) {
+ expect(find.textContaining(title), findsNothing);
+ expect(rowTooltip(tester, f, 3), isNot(contains(title)));
+ expect(rowTooltip(tester, f, 1), isNot(contains(title)));
+ }
+ expect(
+ SuperTabAgentInfo(
+ f.controller,
+ null,
+ f.controller.snapshot!.agent('agent-3')!,
+ ).taskGroup,
+ isNull,
+ );
+ // No task it may read: a click opens the details, which name none.
+ await tester.tap(f.row(3));
+ await tester.pumpAndSettle();
+ expect(f.answered, isNull);
+ expect(find.widgetWithText(AlertDialog, 'Role'), findsOneWidget);
+ expect(find.text('Task'), findsNothing);
+ expect(find.textContaining('Private plans'), findsNothing);
+ await f.close(tester);
+ },
+ );
+
+ testWidgets(
+ 'access revoked while the list is open clears every row and task title',
+ (tester) async {
+ final f = await fixture(tester);
+ (f.server.state['conversations'] as List).add(
+ task(
+ 't1',
+ 'Sidebar rescan fix',
+ 'agent-1',
+ 'working',
+ ago: const Duration(minutes: 1),
+ ),
+ );
+ await f.controller.refresh();
+ await f.show(tester, nativeState: false);
+ expect(find.text('Sidebar rescan fix · 1m'), findsOneWidget);
+ f.controller.revokeAccess('Access removed');
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Sidebar rescan fix'), findsNothing);
+ expect(f.row(1), findsNothing);
+ await f.close(tester);
+ },
+ );
+ });
}
diff --git a/desktop/test/super_tab_swarm_switcher_test.dart b/desktop/test/super_tab_swarm_switcher_test.dart
index 9218639fc..e51526ea7 100644
--- a/desktop/test/super_tab_swarm_switcher_test.dart
+++ b/desktop/test/super_tab_swarm_switcher_test.dart
@@ -35,6 +35,9 @@ class _Backend {
/// While set, preparing a machine for a Swarm waits for it.
Completer<void>? holdPrepare;
+ /// Machines answer preparing with this state ('ready' sets them up).
+ String prepareState = 'ready';
+
/// The Swarm an account's personal-swarm request already made, by account.
final personalOf = <String, String>{};
@@ -152,7 +155,7 @@ class _Connection extends WsConn {
if (action == 'prepareContribution') {
if (backend.holdPrepare case final hold?) await hold.future;
return {
- 'state': 'ready',
+ 'state': backend.prepareState,
'scope': 'swarm',
'cwd': '/Users/person/harnesses/swarm',
'engines': ['claude', 'codex'],
@@ -234,6 +237,17 @@ Future<(AppNotifier, _Backend)> _twoTabs({
return (app, backend);
}
+/// A store whose reads of one key wait for [hold], as a slow disk does.
+class _SlowStore extends MemoryStore {
+ String? slowKey;
+ Completer<void>? hold;
+ @override
+ Future<String?> read(String key) async {
+ if (key == slowKey) await hold?.future;
+ return super.read(key);
+ }
+}
+
Future<SuperTabController> _pumpBar(
WidgetTester tester,
AppNotifier app, {
@@ -550,7 +564,10 @@ void main() {
await _settle();
expect(backend.creates, isEmpty);
expect(backend.machineCalls, isEmpty);
- expect(personal.error, AppNotifier.teamComputerSwarmMessage);
+ expect(
+ personal.errorIn(app.activeSwarmId),
+ AppNotifier.teamComputerSwarmMessage,
+ );
expect(app.activeSwarm.superTabId, 'alpha');
});
@@ -670,7 +687,7 @@ void main() {
answer.complete();
await picking;
await _settle();
- expect(PersonalSwarm.of(app).error, isNull);
+ expect(PersonalSwarm.of(app).errorIn(tab), isNull);
expect(_shown(app, tab), 'gamma');
});
@@ -766,7 +783,7 @@ void main() {
await late;
await _settle();
expect(_shown(other, tab2), 'alpha');
- expect(PersonalSwarm.of(other).error, isNull);
+ expect(PersonalSwarm.of(other).errorIn(tab2), isNull);
});
for (final dropdown in [true, false]) {
@@ -815,6 +832,58 @@ void main() {
});
}
+ test('a failure to add this computer says so in the tab Personal was '
+ 'picked in, and only there', () async {
+ final (app, backend) = await _twoTabs();
+ final alphaTab = app.activeSwarmId;
+ final betaTab = app.swarms.firstWhere((s) => s.superTabId == 'beta').id;
+ backend.prepareState = 'unknown';
+ await PersonalSwarm.of(app).show(alphaTab);
+ await _settle();
+ expect(
+ PersonalSwarm.of(app).errorIn(alphaTab),
+ 'Could not add this computer to Personal. '
+ 'Update Harness on this machine, then try again.',
+ );
+ expect(PersonalSwarm.of(app).errorIn(betaTab), isNull);
+ });
+
+ test('a failed creation says so only in the tab it was picked in', () async {
+ final (app, backend) = await _twoTabs();
+ final alphaTab = app.activeSwarmId;
+ final betaTab = app.swarms.firstWhere((s) => s.superTabId == 'beta').id;
+ backend.failCreate = true;
+ await PersonalSwarm.of(app).show(alphaTab);
+ await _settle();
+ expect(
+ PersonalSwarm.of(app).errorIn(alphaTab),
+ 'Swarm is busy. Try again.',
+ );
+ expect(PersonalSwarm.of(app).errorIn(betaTab), isNull);
+ });
+
+ test('a tab that moves on while Personal’s saved state is read shows no '
+ 'error', () async {
+ final store = _SlowStore();
+ final (app, backend) = await _twoTabs(store: store);
+ final tab = app.activeSwarmId;
+ const id = 'swarm-owner-$kPersonalSwarmOperation';
+ store
+ ..slowKey = 'super_tab.owner.$id'
+ ..hold = Completer<void>();
+ final picking = PersonalSwarm.of(app).show(tab);
+ await _settle();
+ expect(_shown(app, tab), id);
+ // The person moves the tab on before Personal has opened.
+ app.showSuperTabIn(tab, 'gamma', 'Gamma');
+ store.hold!.complete();
+ await picking;
+ await _settle();
+ expect(PersonalSwarm.of(app).errorIn(tab), isNull);
+ expect(backend.contributions(id), isEmpty);
+ expect(_shown(app, tab), 'gamma');
+ });
+
testWidgets('a failed creation says so under the bar, and picking Personal '
'again creates it', (tester) async {
late AppNotifier app;
diff --git a/desktop/test/super_tab_threads_shots_test.dart b/desktop/test/super_tab_threads_shots_test.dart
index 5be8b5919..e17fcbef8 100644
--- a/desktop/test/super_tab_threads_shots_test.dart
+++ b/desktop/test/super_tab_threads_shots_test.dart
@@ -1,4 +1,6 @@
+import 'dart:async';
import 'dart:io';
+import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
@@ -17,16 +19,41 @@ final shots = Platform.environment['SUPER_TAB_THREAD_SHOTS'];
/// the thread open beside it, in both appearances.
void main() {
setUpAll(() async {
- if (shots != null) await loadPreviewFonts();
+ if (shots == null) return;
+ await loadPreviewFonts();
+ // Uploaded pictures, served from memory: the test fonts draw no emoji,
+ // so presets would show as boxes.
+ HttpOverrides.global = _Pictures({
+ 'ken': await _disc(const Color(0xFFE07A2E), const Color(0xFF7A3A10)),
+ 'pm': await _disc(const Color(0xFF3FA37A), const Color(0xFF1D5A42)),
+ });
});
for (final brightness in Brightness.values) {
testWidgets('screenshots for review (${brightness.name})', (tester) async {
final picture = GlobalKey();
final server = ConversationServer()..threads = true;
+ // Faces as each wears them on their own messages: a person's picture,
+ // the PM's avatar.
(server.state['people'] as List)
..add({'id': 'dee', 'email': '[email protected]', 'role': 'collaborator'})
- ..add({'id': 'ken', 'email': '[email protected]', 'role': 'owner'});
+ ..add({
+ 'id': 'ken',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'avatar': {'kind': 'upload', 'url': superTabSignedAvatar('ken')},
+ });
+ (server.state['agents'] as List).add({
+ 'id': 'pm',
+ 'projectId': 'lead',
+ 'name': 'Lead',
+ 'displayName': 'River',
+ 'machineId': 'studio',
+ 'harnessId': 'h-pm',
+ 'contributorId': 'ken',
+ 'configuration': {'engine': 'claude', 'model': 'opus'},
+ 'avatar': {'kind': 'upload', 'url': superTabSignedAvatar('pm')},
+ });
const pm = {
'kind': 'agent',
'id': 'pm',
@@ -110,6 +137,11 @@ void main() {
),
);
await tester.pumpAndSettle();
+ // The pictures arrive over (fake) HTTP.
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 200)),
+ );
+ await tester.pumpAndSettle();
Future<void> shot(String name) => tester.runAsync(() async {
final boundary =
@@ -134,3 +166,88 @@ void main() {
}, skip: shots == null);
}
}
+
+/// A round picture in two tones, as someone might upload.
+Future<Uint8List> _disc(Color light, Color dark) async {
+ final recorder = ui.PictureRecorder();
+ const size = 96.0;
+ Canvas(recorder)
+ ..drawRect(const Rect.fromLTWH(0, 0, size, size), Paint()..color = light)
+ ..drawCircle(
+ const Offset(size / 2, size * .42),
+ size * .2,
+ Paint()..color = dark,
+ )
+ ..drawOval(
+ const Rect.fromLTWH(size * .18, size * .66, size * .64, size * .6),
+ Paint()..color = dark,
+ );
+ final image = await recorder.endRecording().toImage(96, 96);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ image.dispose();
+ return png!.buffer.asUint8List();
+}
+
+/// Serves each avatar link's picture by the id in its path.
+class _Pictures extends HttpOverrides {
+ _Pictures(this.byId);
+ final Map<String, Uint8List> byId;
+ @override
+ HttpClient createHttpClient(SecurityContext? context) => _Client(byId);
+}
+
+class _Client implements HttpClient {
+ _Client(this.byId);
+ final Map<String, Uint8List> byId;
+ @override
+ bool autoUncompress = false;
+ @override
+ Future<HttpClientRequest> getUrl(Uri url) async =>
+ _Request(byId[url.pathSegments.last] ?? Uint8List(0));
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _Request implements HttpClientRequest {
+ _Request(this.bytes);
+ final Uint8List bytes;
+ @override
+ HttpHeaders get headers => _Headers();
+ @override
+ Future<HttpClientResponse> close() async => _Response(bytes);
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _Headers implements HttpHeaders {
+ @override
+ void add(String name, Object value, {bool preserveHeaderCase = false}) {}
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _Response extends Stream<List<int>> implements HttpClientResponse {
+ _Response(this.bytes);
+ final Uint8List bytes;
+ @override
+ int get statusCode => bytes.isEmpty ? 404 : 200;
+ @override
+ int get contentLength => bytes.length;
+ @override
+ HttpClientResponseCompressionState get compressionState =>
+ HttpClientResponseCompressionState.notCompressed;
+ @override
+ StreamSubscription<List<int>> listen(
+ void Function(List<int>)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) => Stream.value(bytes as List<int>).listen(
+ onData,
+ onError: onError,
+ onDone: onDone,
+ cancelOnError: cancelOnError,
+ );
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
diff --git a/desktop/test/super_tab_threads_test.dart b/desktop/test/super_tab_threads_test.dart
index 59cf4de61..f02d859d5 100644
--- a/desktop/test/super_tab_threads_test.dart
+++ b/desktop/test/super_tab_threads_test.dart
@@ -6,6 +6,7 @@ import 'package:flutter/semantics.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/identity.dart';
import 'package:harness/super_tabs/message_link.dart';
import 'package:harness/super_tabs/message_row.dart';
import 'package:harness/super_tabs/model.dart';
@@ -305,6 +306,140 @@ void main() {
expect(c.openedThread?.root, 'message-1');
});
+ group('the replies row shows each replier as their own messages do', () {
+ const river = {
+ 'kind': 'agent',
+ 'id': 'river',
+ 'name': 'Lead',
+ 'displayName': 'River',
+ };
+ const gone = {'kind': 'person', 'id': 'gone', 'name': '[email protected]'};
+ Map<String, dynamic> riverRow({String displayName = 'River'}) => {
+ 'id': 'river',
+ 'projectId': 'lead',
+ 'name': 'Lead',
+ 'displayName': displayName,
+ 'machineId': 'm',
+ 'harnessId': 'h-river',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude', 'model': 'opus'},
+ 'avatar': {'kind': 'preset', 'key': 'owl'},
+ };
+
+ /// A root by the owner answered by [peer], who has a picture and a
+ /// status, the agent River, and someone no longer in the Swarm.
+ ConversationServer answered({
+ Map<String, Object> peerAvatar = const {
+ 'kind': 'upload',
+ 'url': 'https://storage.googleapis.com/avatars/peer?X-Goog-Expires=3600&X-Goog-Signature=fixture',
+ },
+ }) {
+ final server = ConversationServer()..threads = true;
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'username': 'pia',
+ 'role': 'collaborator',
+ 'avatar': peerAvatar,
+ 'status': {'text': 'Coffee break', 'emoji': '☕'},
+ });
+ (server.state['agents'] as List).add(riverRow());
+ server.append('Who wants this?');
+ for (final author in [gone, river, peer]) {
+ server.append('Me.');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = author;
+ }
+ return server;
+ }
+
+ List<SuperTabAvatar> faces(WidgetTester tester) => tester
+ .widgetList<SuperTabAvatar>(
+ find.descendant(
+ of: line('message-1'),
+ matching: find.byType(SuperTabAvatar),
+ ),
+ )
+ .toList();
+
+ testWidgets('a person their uploaded picture and status, an agent its '
+ 'avatar, and someone who left the face their name gives', (
+ tester,
+ ) async {
+ await show(tester, answered());
+ final [person, agent, left] = faces(tester);
+ expect(person.identity, 'person:peer');
+ expect(person.name, 'pia');
+ expect(person.picture, isA<SuperTabUploadedAvatar>());
+ expect(person.status?.text, 'Coffee break');
+ expect(agent.identity, 'agent:river');
+ expect(agent.name, 'River');
+ expect(agent.picture, isA<SuperTabPresetAvatar>());
+ expect(agent.pattern, isTrue);
+ // The row names the engine already where an agent writes; its reply
+ // line does not badge it either.
+ expect(agent.engine, isNull);
+ expect(left.identity, 'person:gone');
+ expect(left.name, 'gone');
+ expect(left.picture, isNull);
+ expect(left.status, isNull);
+ // Its size is unchanged.
+ expect(
+ tester.getSize(find.byWidget(person)).width,
+ grid.AppDesktop.iconSize,
+ );
+ });
+
+ testWidgets('a person with a preset shows it', (tester) async {
+ await show(
+ tester,
+ answered(peerAvatar: const {'kind': 'preset', 'key': 'fox'}),
+ );
+ expect(
+ find.descendant(of: line('message-1'), matching: find.text('🦊')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: line('message-1'), matching: find.text('🦉')),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a person who leaves and an agent removed while the chat is '
+ 'open fall back on the next read, and a renamed agent follows', (
+ tester,
+ ) async {
+ final server = answered(
+ peerAvatar: const {'kind': 'preset', 'key': 'fox'},
+ );
+ final c = await show(tester, server);
+ expect(faces(tester).first.picture, isNotNull);
+ (server.state['people'] as List).removeWhere(
+ (p) => (p as Map)['id'] == 'peer',
+ );
+ server.state['agents'] = [riverRow(displayName: 'Rio')];
+ await c.refresh();
+ await tester.pumpAndSettle();
+ var [person, agent, _] = faces(tester);
+ expect(person.picture, isNull);
+ expect(person.status, isNull);
+ expect(person.name, 'peer');
+ expect(agent.name, 'Rio');
+ expect(agent.picture, isA<SuperTabPresetAvatar>());
+ server.state['agents'] = <dynamic>[];
+ await c.refresh();
+ await tester.pumpAndSettle();
+ [_, agent, _] = faces(tester);
+ expect(agent.picture, isNull);
+ expect(agent.pattern, isTrue);
+ expect(agent.name, 'River');
+ expect(find.text('🦊'), findsNothing);
+ expect(find.text('🦉'), findsNothing);
+ });
+ });
+
testWidgets('the reply line is a button assistive technology can press', (
tester,
) async {
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index eb0c0e0e8..9a84e3f0b 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -46,6 +46,10 @@ Map<String, dynamic> projectFixture(
/// next version and a new `changedAt`, a part that is gone gets a tombstone. Tests keep changing the state as they
/// did; the reads see exactly those changes.
class SwarmPartsBackend {
+ /// A broken server that sends groups the reader may not read, so a test can
+ /// prove the app keeps them off screen itself.
+ bool leaksHiddenGroups = false;
+
/// The server's clock, one tick per change; a cursor is a tick.
int clock = 1000;
int _version = 100;
@@ -173,6 +177,13 @@ class SwarmPartsBackend {
/// by its audience (and the project's Lead, an agent), owners included, and
/// by each person only at the membership generation they were listed with
/// (backend projects.ts canReadGroup), when [state] gives them one.
+ bool _hides(
+ String id,
+ _HeldPart part,
+ String? reader,
+ Map<String, dynamic> state,
+ ) => !leaksHiddenGroups && _hidden(id, part, reader, state);
+
static bool _hidden(
String id,
_HeldPart part,
@@ -231,7 +242,7 @@ class SwarmPartsBackend {
final kind = entry.key.substring(0, entry.key.indexOf(':'));
if (kind == 'head' || entry.value.deleted) continue;
if (kind == 'groups' && dormant(entry.value.data)) continue;
- if (_hidden(entry.key, entry.value, reader, state)) continue;
+ if (_hides(entry.key, entry.value, reader, state)) continue;
(answer[kind] as List).add(_envelope(entry.key, entry.value));
}
return _measured('parts', answer);
@@ -259,7 +270,7 @@ class SwarmPartsBackend {
};
for (final entry in _ordered()) {
if (entry.value.changedAt <= since) continue;
- if (_hidden(entry.key, entry.value, reader, state)) continue;
+ if (_hides(entry.key, entry.value, reader, state)) continue;
final kind = entry.key.substring(0, entry.key.indexOf(':'));
if (kind == 'head') {
answer['head'] = _envelope(entry.key, entry.value);
@@ -276,7 +287,7 @@ class SwarmPartsBackend {
final held = _parts['groups:${segments[4]}'];
if (held == null ||
held.deleted ||
- _hidden('groups:${segments[4]}', held, reader, state)) {
+ _hides('groups:${segments[4]}', held, reader, state)) {
throw const SuperTabFailure(
'NOT_FOUND',
'Conversation not found.',
@@ -292,7 +303,7 @@ class SwarmPartsBackend {
if (entry.key.startsWith('groups:') &&
!entry.value.deleted &&
dormant(entry.value.data) &&
- !_hidden(entry.key, entry.value, reader, state) &&
+ !_hides(entry.key, entry.value, reader, state) &&
(projectId == null ||
(entry.value.data['projectId'] ?? 'lead') == projectId))
entry,
diff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dart
index 178bb3b31..da8c0c1e6 100644
--- a/mobile/lib/swarm/swarm_leaderboard.dart
+++ b/mobile/lib/swarm/swarm_leaderboard.dart
@@ -60,6 +60,26 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
SwarmReader? _swarm;
SwarmLeaderboardReader? _board;
+ /// The Swarm's reader was held and has been lost: it left the account's
+ /// list, or may no longer be read. Nothing of it is drawn, and no loading
+ /// stays up for an answer that will not come.
+ bool _lost = false;
+
+ /// The person's week this page opened, while it is up. What it shows is
+ /// this board's: it closes with the page, and when the account, the Swarm
+ /// or the project it was opened from is gone ([_closeWeek]).
+ ModalRoute<void>? _week;
+
+ @override
+ void didUpdateWidget(SwarmLeaderboardPage old) {
+ super.didUpdateWidget(old);
+ // Another Swarm or project: none of the last board stays.
+ if (old.swarmId != widget.swarmId || old.projectId != widget.projectId) {
+ _forget();
+ _attach();
+ }
+ }
+
@override
void didChangeDependencies() {
super.didChangeDependencies();
@@ -82,10 +102,28 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
void _attach() {
final session = _session;
final swarm = session?.inbox.reader(widget.swarmId);
- if (session == null || swarm == null || identical(swarm, _swarm)) return;
- _swarm?.removeListener(_changed);
- _swarm = swarm..addListener(_changed);
+ if (session == null) return;
+ // Off the list, or refused: what was read of it goes, and a reader that
+ // may not read it again is not followed. Not listed yet is only waiting.
+ if (swarm == null || swarm.accessRevoked) {
+ if (!_lost && (_swarm != null || swarm != null)) _lose();
+ return;
+ }
+ if (identical(swarm, _swarm)) return;
+ _swarm?.removeListener(_swarmChanged);
+ _lost = false;
+ _swarm = swarm..addListener(_swarmChanged);
+ _startBoard();
+ _changed();
+ }
+
+ void _startBoard() {
+ final session = _session, swarm = _swarm;
+ if (session == null || swarm == null) return;
_board?.dispose();
+ _board = null;
+ // A project the Swarm does not have is not asked for.
+ if (_projectGone(swarm.snapshot)) return;
_board = SwarmLeaderboardReader(
tabId: swarm.tabId,
projectId: widget.projectId,
@@ -93,25 +131,66 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
inFront: () => session.inbox.shown,
)..addListener(_changed);
_board!.start();
- _changed();
}
void _changed() {
if (mounted) setState(() {});
}
+ /// Whether [snapshot], once read, still has this page's project.
+ bool _projectGone(SuperTabSnapshot? snapshot) =>
+ snapshot != null &&
+ !snapshot.projects.any((p) => p.id == widget.projectId);
+
+ /// The Swarm's reader told of a change: revoked, nothing of it stays;
+ /// without the project any more, nothing of the project does either: its
+ /// week closes and its board is not read, until the project is back.
+ void _swarmChanged() {
+ final swarm = _swarm;
+ if (swarm == null) return;
+ if (swarm.accessRevoked) return _lose();
+ if (_projectGone(swarm.snapshot)) {
+ _closeWeek();
+ _board?.dispose();
+ _board = null;
+ } else if (_board == null) {
+ _startBoard();
+ }
+ _changed();
+ }
+
+ void _lose() {
+ _forget();
+ _lost = true;
+ _changed();
+ }
+
void _forget() {
- _swarm?.removeListener(_changed);
+ _swarm?.removeListener(_swarmChanged);
_swarm = null;
_board?.dispose();
_board = null;
+ _lost = false;
+ _closeWeek();
+ }
+
+ /// Closes the week open, if any: once this frame is done, as a page whose
+ /// reader goes away may not change the navigator while it builds.
+ void _closeWeek() {
+ final week = _week;
+ _week = null;
+ if (week == null) return;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (week.isActive) week.navigator?.removeRoute(week);
+ });
}
@override
void dispose() {
+ _closeWeek();
_session?.inbox.removeListener(_attach);
_session?.leave();
- _swarm?.removeListener(_changed);
+ _swarm?.removeListener(_swarmChanged);
_board?.dispose();
super.dispose();
}
@@ -165,8 +244,9 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
final reader = _board;
final board = reader?.board;
final current = swarmWeekOf(widget.now());
- // Signed out, or Swarm turned off: no account's board to show.
- if (_session == null) return const [];
+ // Signed out, or Swarm turned off: no account's board to show; nor of a
+ // Swarm that was lost, or of a project it does not have.
+ if (_session == null || _lost || _projectGone(snapshot)) return const [];
if (reader != null && reader.unavailable) {
return [
const SizedBox(height: AppSpace.m),
@@ -245,18 +325,36 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
name: nameOf(score),
own: score.personId == viewer,
columns: columns!,
- onTap: () => unawaited(
- showSwarmPersonWeek(
- context,
- score: score,
- person: personOf(score.personId),
- name: nameOf(score),
- ),
+ onTap: () => _openWeek(
+ context,
+ score,
+ personOf(score.personId),
+ nameOf(score),
),
),
];
}
+ void _openWeek(
+ BuildContext context,
+ SwarmScore score,
+ SuperTabPerson? person,
+ String name,
+ ) {
+ ModalRoute<void>? shown;
+ unawaited(
+ showSwarmPersonWeek(
+ context,
+ score: score,
+ person: person,
+ name: name,
+ opened: (route) => _week = shown = route,
+ ).whenComplete(() {
+ if (_week == shown) _week = null;
+ }),
+ );
+ }
+
/// The four weeks the board keeps, this one first, in a sheet.
Future<void> _pickWeek(
BuildContext context,
@@ -284,31 +382,41 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
],
),
);
- if (week == null || !mounted) return;
+ if (week == null || !mounted || !identical(reader, _board)) return;
await reader.showWeek(week == current ? null : week);
}
}
/// [score]'s week in a sheet, as the desktop shows it when a name is clicked:
/// from the leaderboard and from a project's Team. [opened] is told the
-/// sheet's route, for a screen that must close it itself.
+/// sheet's route before it is pushed, not when it first draws, so a screen
+/// that loses what the sheet shows between the tap and the next frame can
+/// still close it.
Future<void> showSwarmPersonWeek(
BuildContext context, {
required SwarmScore score,
required SuperTabPerson? person,
required String name,
ValueChanged<ModalRoute<void>>? opened,
-}) => showModalBottomSheet<void>(
- context: context,
- isScrollControlled: true,
- backgroundColor: AppGlass.rowFill,
- showDragHandle: true,
- shape: AppControl.sheetShape,
- builder: (context) {
- if (ModalRoute.of(context) case final ModalRoute<void> route?) {
- opened?.call(route);
- }
- return _Sheet(
+}) {
+ // What showModalBottomSheet gives its route, with its default options.
+ final navigator = Navigator.of(context);
+ final localizations = MaterialLocalizations.of(context);
+ final route = ModalBottomSheetRoute<void>(
+ capturedThemes: InheritedTheme.capture(
+ from: context,
+ to: navigator.context,
+ ),
+ isScrollControlled: true,
+ barrierLabel: localizations.scrimLabel,
+ barrierOnTapHint: localizations.scrimOnTapHint(
+ localizations.bottomSheetLabel,
+ ),
+ backgroundColor: AppGlass.rowFill,
+ showDragHandle: true,
+ shape: AppControl.sheetShape,
+ modalBarrierColor: Theme.of(context).bottomSheetTheme.modalBarrierColor,
+ builder: (context) => _Sheet(
key: const ValueKey('swarm-leaderboard-sheet'),
title: name,
leading: SwarmAvatar(
@@ -321,9 +429,11 @@ Future<void> showSwarmPersonWeek(
for (final (label, value) in swarmPersonWeek(score))
_WeekLine(label: label, value: value),
],
- );
- },
-);
+ ),
+ );
+ opened?.call(route);
+ return navigator.push(route);
+}
/// Figures of one width, so a column of numbers holds row under row.
const _figures = [FontFeature.tabularFigures()];
diff --git a/mobile/lib/swarm/swarm_thread_line.dart b/mobile/lib/swarm/swarm_thread_line.dart
index 47e154379..d78205369 100644
--- a/mobile/lib/swarm/swarm_thread_line.dart
+++ b/mobile/lib/swarm/swarm_thread_line.dart
@@ -105,6 +105,7 @@ class SwarmThreadLine extends StatelessWidget {
id: who.id,
agent: who.agent,
picture: who.look.picture,
+ status: who.look.status,
diameter: face,
),
const SizedBox(width: AppSpace.xs),
diff --git a/mobile/test/swarm/swarm_leaderboard_page_test.dart b/mobile/test/swarm/swarm_leaderboard_page_test.dart
index 75efae989..37a2e85ea 100644
--- a/mobile/test/swarm/swarm_leaderboard_page_test.dart
+++ b/mobile/test/swarm/swarm_leaderboard_page_test.dart
@@ -453,6 +453,262 @@ void main() {
}
});
+ group("a person's week closes when what opened it is lost", () {
+ const sheet = 'swarm-leaderboard-sheet';
+
+ /// The page over the scripted Swarm with diego's week open.
+ Future<({FakeSwarm fake, SwarmHost host, ValueNotifier<String?> account})>
+ withSheet(WidgetTester tester) async {
+ final fake = backend();
+ final account = ValueNotifier<String?>(me);
+ final host = await pump(tester, fake, signedIn: account);
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+ await tester.pumpAndSettle();
+ expect(inside(sheet, find.text('diego')), findsOneWidget);
+ return (fake: fake, host: host, account: account);
+ }
+
+ int boardReads(FakeSwarm fake) =>
+ fake.paths.where((p) => p.contains('/leaderboard')).length;
+
+ testWidgets('it stays while nothing is lost, a refresh included', (
+ tester,
+ ) async {
+ final (:fake, :host, account: _) = await withSheet(tester);
+
+ await host.session!.inbox.refresh();
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ expect(inside(sheet, find.text('diego')), findsOneWidget);
+ });
+
+ testWidgets('the Swarm leaving the account\'s list closes it, clears the '
+ 'board and reads no more', (tester) async {
+ final (:fake, :host, account: _) = await withSheet(tester);
+ final reads = boardReads(fake);
+
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': <Object>[],
+ 'next': null,
+ };
+ await host.session!.inbox.refresh();
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ expect(key('swarm-leaderboard-person-diego'), findsNothing);
+ expect(
+ key('swarm-leaderboard-loading'),
+ findsNothing,
+ reason: 'no loading for an answer that will not come',
+ );
+ await tester.pump(const Duration(minutes: 11));
+ expect(boardReads(fake), reads, reason: 'nothing read once revoked');
+ });
+
+ testWidgets('the project going from the Swarm closes it', (tester) async {
+ final (:fake, :host, account: _) = await withSheet(tester);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c3'),
+ 'head': part('head', 2, headData(projects: [])),
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ expect(host.session!.inbox.reader(tab)!.snapshot!.projects, isEmpty);
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ });
+
+ testWidgets('a sign-out closes it', (tester) async {
+ final (:fake, host: _, :account) = await withSheet(tester);
+ final reads = boardReads(fake);
+
+ account.value = null;
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ await tester.pump(const Duration(minutes: 11));
+ expect(boardReads(fake), reads);
+ });
+
+ testWidgets('another account closes it, and its board is the new one\'s', (
+ tester,
+ ) async {
+ final (:fake, host: _, :account) = await withSheet(tester);
+
+ account.value = 'person-other';
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ });
+
+ testWidgets('the page asked for another project closes it', (tester) async {
+ final fake = backend();
+ final account = ValueNotifier<String?>(me);
+ final host = await pump(tester, fake, signedIn: account);
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+ await tester.pumpAndSettle();
+ expect(key(sheet), findsOneWidget);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ home: SwarmLeaderboardPage(
+ swarmId: tab,
+ projectId: 'project-other',
+ now: () => now,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ expect(key('swarm-leaderboard-person-diego'), findsNothing);
+ expect(key('swarm-leaderboard-loading'), findsNothing);
+ expect(
+ fake.paths.where((p) => p.contains('projectId=project-other')),
+ isEmpty,
+ reason: 'a project the Swarm does not have is not asked for',
+ );
+ });
+
+ testWidgets('the project back on the Swarm reads its board again', (
+ tester,
+ ) async {
+ final (:fake, :host, account: _) = await withSheet(tester);
+ final reads = boardReads(fake);
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c3'),
+ 'head': part('head', 2, headData(projects: [])),
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(key('swarm-leaderboard-person-diego'), findsNothing);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c4'),
+ 'head': part('head', 3, headData()),
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-leaderboard-person-diego'), findsOneWidget);
+ expect(boardReads(fake), reads + 1);
+ expect(key(sheet), findsNothing, reason: 'the week stays closed');
+ });
+
+ /// The page with diego's row tapped and no frame drawn since: the sheet
+ /// is pushed but has not been built.
+ Future<({FakeSwarm fake, SwarmHost host})> tappedNotDrawn(
+ WidgetTester tester,
+ ) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+ expect(key(sheet), findsNothing, reason: 'no frame since the tap');
+ return (fake: fake, host: host);
+ }
+
+ testWidgets('access refused between the tap and the first frame of the '
+ 'week: it does not stay', (tester) async {
+ final (:fake, :host) = await tappedNotDrawn(tester);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ });
+
+ testWidgets('the Swarm dropped from the list between the tap and the '
+ 'first frame of the week: it does not stay', (tester) async {
+ final (:fake, :host) = await tappedNotDrawn(tester);
+
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': <Object>[],
+ 'next': null,
+ };
+ await host.session!.inbox.refresh();
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ });
+
+ testWidgets('the project removed between the tap and the first frame of '
+ 'the week: it does not stay', (tester) async {
+ final (:fake, :host) = await tappedNotDrawn(tester);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c3'),
+ 'head': part('head', 2, headData(projects: [])),
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ });
+
+ testWidgets('a signed-out account between the tap and the first frame '
+ 'of the week: it does not stay', (tester) async {
+ final fake = backend();
+ final account = ValueNotifier<String?>(me);
+ await pump(tester, fake, signedIn: account);
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+
+ account.value = null;
+ await tester.pumpAndSettle();
+
+ expect(key(sheet), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ });
+
+ testWidgets('a board read still out when access is lost shows nothing '
+ 'when it lands', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await tester.pumpAndSettle();
+ final gate = Completer<void>();
+ fake.routes[path] = (_) async {
+ await gate.future;
+ return board();
+ };
+ // A pull: the board is read again, and the answer is still out.
+ await tester.fling(
+ key('swarm-leaderboard-person-diego'),
+ const Offset(0, 400),
+ 1000,
+ );
+ for (var i = 0; i < 20 && boardReads(fake) < 2; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ expect(boardReads(fake), 2, reason: 'the pull is out');
+
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': <Object>[],
+ 'next': null,
+ };
+ await host.session!.inbox.refresh();
+ gate.complete();
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-leaderboard-person-diego'), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ expect(key('swarm-leaderboard-team'), findsNothing);
+ });
+ });
+
testWidgets('a read that fails with nothing shown offers Try again', (
tester,
) async {
diff --git a/mobile/test/swarm/swarm_project_c_test.dart b/mobile/test/swarm/swarm_project_c_test.dart
index d0fdcd1a1..680581f1a 100644
--- a/mobile/test/swarm/swarm_project_c_test.dart
+++ b/mobile/test/swarm/swarm_project_c_test.dart
@@ -1587,6 +1587,18 @@ void main() {
expect(find.text('diego'), findsNothing);
});
+ testWidgets("access taken away between the tap on a person and the week's "
+ 'first frame: it does not stay', (tester) async {
+ await team(tester, backend());
+ await tester.tap(key('swarm-member-person-diego'));
+
+ host(tester).session!.inbox.reader(tab)!.revoke();
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-leaderboard-sheet'), findsNothing);
+ expect(find.text('diego'), findsNothing);
+ });
+
testWidgets("the project taken off the Swarm with a person's week open, "
'the Swarm still read: the week closes', (tester) async {
final fake = await diegoWeek(tester);
diff --git a/mobile/test/swarm/swarm_thread_line_faces_test.dart b/mobile/test/swarm/swarm_thread_line_faces_test.dart
new file mode 100644
index 000000000..e63cfb49c
--- /dev/null
+++ b/mobile/test/swarm/swarm_thread_line_faces_test.dart
@@ -0,0 +1,75 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/parts.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+import 'package:harness_mobile/swarm/swarm_thread_line.dart';
+
+import 'swarm_fixture.dart';
+
+/// The faces on a thread's reply line are the ones its repliers wear on
+/// their own messages (Dee, 10-30): a person's picture and status, an
+/// agent's avatar, and for someone no longer in the Swarm the face their
+/// recorded name gives.
+void main() {
+ SuperTabSnapshot swarm() {
+ final load = firstLoad(
+ agents: [
+ {
+ ...agent('agent-lead', name: 'Lead', displayName: 'River'),
+ 'avatar': {'kind': 'preset', 'key': 'owl'},
+ },
+ ],
+ );
+ (load['members'] as List).add(
+ part('peer', 1, {
+ ...person('peer', role: 'collaborator'),
+ 'avatar': {'kind': 'preset', 'key': 'fox'},
+ 'status': {'text': 'Coffee break', 'emoji': '☕'},
+ }),
+ );
+ return SuperTabSnapshot.fromJson(SuperTabParts.firstLoad(load).state);
+ }
+
+ final thread = SuperTabThread.fromJson({
+ 'id': 'm1',
+ 'replies': 3,
+ 'lastSequence': 4,
+ 'authors': [
+ {'kind': 'person', 'id': 'peer', 'name': '[email protected]'},
+ {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},
+ {'kind': 'person', 'id': 'gone', 'name': '[email protected]'},
+ ],
+ 'people': ['peer', 'gone'],
+ });
+
+ testWidgets('a person shows their picture and status, an agent its '
+ 'avatar, and someone who left their initial', (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SwarmThreadLine(
+ thread: thread,
+ faces: swarmThreadFaces(swarm(), thread),
+ onOpen: () {},
+ ),
+ ),
+ ),
+ );
+ final [person, lead, left] = tester
+ .widgetList<SwarmChatAvatar>(find.byType(SwarmChatAvatar))
+ .toList();
+ expect(person.picture, isNotNull);
+ expect(person.status?.text, 'Coffee break');
+ expect(lead.picture, isNotNull);
+ expect(lead.status, isNull);
+ expect(left.picture, isNull);
+ expect(left.status, isNull);
+ expect(left.name, 'gone');
+ expect(find.text('🦊'), findsOneWidget);
+ expect(find.text('🦉'), findsOneWidget);
+ expect(find.text('G'), findsOneWidget);
+ // Their size is unchanged.
+ expect(tester.getSize(find.byWidget(left)).width, SwarmThreadLine.face);
+ });
+}
diff --git a/tui/src/agent_switch.rs b/tui/src/agent_switch.rs
index eb9da4651..1751dceb0 100644
--- a/tui/src/agent_switch.rs
+++ b/tui/src/agent_switch.rs
@@ -549,9 +549,18 @@ fn stop(app: &mut App, id: &str) {
request(app, id, "agent_close", payload, 35, stopped);
}
+/// Desktop's `buddyKeepsItsAgent`, word for word.
+const BUDDY_KEEPS_ITS_AGENT: &str = "A Swarm Buddy keeps its agent. To use another agent, its person removes the Buddy and adds a new one.";
+
fn stopped(app: &mut App, id: &str, reply: Reply) {
if !valid(app, id) { return }
let closed = reply.as_ref().ok().is_some_and(|r| r["closed"] == true);
+ // A Swarm Buddy keeps running, so it keeps its agent. The daemon's refusal speaks of Stop Harness: no help here.
+ if reply.as_ref().err().is_some_and(|e| e.code == "BUDDY_PROTECTED") || reply.as_ref().is_ok_and(|r| r["keptRunning"] == true) {
+ // A refusal, not a lost answer: nothing stopped, so the pane is not held for a replacement (Desktop's preservingViews).
+ if let Some(c) = app.agent_switch.changes.get_mut(id) { c.preserving = false; }
+ fail(app, id, BUDDY_KEEPS_ITS_AGENT); return;
+ }
if !closed {
let detail = reply.as_ref().err().map(|e| if e.detail.is_empty() { e.code.as_str() } else { &e.detail })
.or_else(|| reply.as_ref().ok().and_then(|r| r["detail"].as_str())).unwrap_or("The machine did not confirm the stop");
@@ -873,6 +882,20 @@ mod tests {
assert!(app.agent_switch.changes[&id].error.contains("No acknowledgement"));
}
+ #[tokio::test]
+ async fn a_buddy_keeps_its_agent_and_says_how_to_use_another() {
+ // The daemon refuses to stop a Swarm Buddy; its refusal speaks of Stop Harness, which is no help here.
+ let mut app = app();
+ let id = start(&mut app, "claude"); handoff(&mut app, &id);
+ stopped(&mut app, &id, Err(RpcError::new("BUDDY_PROTECTED", "This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.")));
+ assert!(sent(&app, "agent_create").is_empty());
+ assert_eq!(app.panes[&1].agent_id, "a1");
+ assert_eq!(app.fleet.agent("local", "a1").unwrap().status, "active");
+ assert_eq!(app.agent_switch.changes[&id].error, "A Swarm Buddy keeps its agent. To use another agent, its person removes the Buddy and adds a new one.");
+ // A refusal, not a lost answer: the pane is no longer held for a replacement, so a later stop closes it.
+ assert!(!preserves(&app, 1), "the pane is not held after the refusal");
+ }
+
#[tokio::test]
async fn unavailable_or_untrusted_handoff_holds_the_source_until_the_same_intent_recovers() {
for reply in [
diff --git a/tui/src/session_close.rs b/tui/src/session_close.rs
index 8e816061b..ac02dc87b 100644
--- a/tui/src/session_close.rs
+++ b/tui/src/session_close.rs
@@ -54,8 +54,10 @@ impl Identity {
}
}
+/// `kept`: a harness that keeps running on purpose (a Swarm Buddy; the daemon answers `keptRunning`). Nothing stops
+/// it, nothing asks about it, and its view closes as the others' do (Desktop's `kept_running`).
#[derive(Clone)]
-struct Target { identity: Identity, name: String, activity: String, closed: bool }
+struct Target { identity: Identity, name: String, activity: String, closed: bool, kept: bool }
#[derive(Clone)]
struct View { pane: u64, machine: String, agent: String, epoch: Option<(String, String)>, owner: String }
@@ -152,7 +154,7 @@ fn begin(app: &mut App, panes: Vec<u64>, title: &str, tab: Option<String>, retur
// hide it silently, or keep it with no way out.
if !a.close_supported || a.created_at_wire.is_empty() { unsupported = true; continue }
if seen.insert((a.machine_id.clone(), a.id.clone())) {
- targets.push(Target { identity: Identity::capture(app, a), name: a.name.clone(), activity: "unknown".into(), closed: false });
+ targets.push(Target { identity: Identity::capture(app, a), name: a.name.clone(), activity: "unknown".into(), closed: false, kept: false });
}
}
if views.is_empty() { return }
@@ -172,6 +174,7 @@ fn activity_label(activity: &str) -> &'static str {
"idle" => "Idle",
"stopped" => "Stopped",
"unconfirmed" => "Stop not confirmed",
+ "kept_running" => "Keeps running",
_ => "Activity unknown",
}
}
@@ -207,7 +210,7 @@ fn show(app: &mut App, message: &str, confirm: bool) -> bool {
let rows = |items: &mut Vec<_>, listed: &[&Target]| {
let space = room.saturating_sub(items.len() + 1);
for t in listed.iter().take(space) {
- let activity = activity_label(if t.closed { "stopped" } else { &t.activity });
+ let activity = activity_label(if t.closed { "stopped" } else if t.kept { "kept_running" } else { &t.activity });
items.push(menu::note(&if several { format!("{} · {} · {activity}", t.name, app.fleet.machine_name(&t.identity.machine)) }
else { format!("{} · {activity}", t.name) }));
}
@@ -215,7 +218,7 @@ fn show(app: &mut App, message: &str, confirm: bool) -> bool {
};
if confirm {
// Desktop's question: what needs attention, then what Stop will do.
- let pending: Vec<&Target> = op.targets.iter().filter(|t| !t.closed).collect();
+ let pending: Vec<&Target> = op.targets.iter().filter(|t| !t.closed && !t.kept).collect();
let attention: Vec<&Target> = pending.iter().copied().filter(|t| t.activity != "idle").collect();
if !attention.is_empty() { items.push(menu::note(&summary(&attention))); }
if !pending.is_empty() {
@@ -225,7 +228,7 @@ fn show(app: &mut App, message: &str, confirm: bool) -> bool {
}
rows(&mut items, &attention);
if op.shells && items.len() < room { items.push(menu::note("The terminal and its running commands will end.")); }
- let closed = op.targets.len() - pending.len();
+ let closed = op.targets.iter().filter(|t| t.closed).count();
if closed > 0 && items.len() < room {
items.push(menu::note(&format!("{closed} {} already closed.", if closed == 1 { "harness has" } else { "harnesses have" })));
}
@@ -272,7 +275,7 @@ fn advance(app: &mut App, id: &str) {
}
if op.at >= op.targets.len() {
if op.stage == Stage::Inspect {
- let confirm = op.shells || op.targets.iter().any(|t| !t.closed && t.activity != "idle");
+ let confirm = op.shells || op.targets.iter().any(|t| !t.closed && !t.kept && t.activity != "idle");
let op = app.session_close.operation.as_mut().unwrap();
op.at = 0;
if confirm {
@@ -290,7 +293,7 @@ fn advance(app: &mut App, id: &str) {
return;
}
let (index, target, mode) = (op.at, op.targets[op.at].clone(), if op.stage == Stage::Inspect { "inspect" } else if op.force { "now" } else { "idle" });
- if target.closed { app.session_close.operation.as_mut().unwrap().at += 1; advance(app, id); return }
+ if target.closed || target.kept { app.session_close.operation.as_mut().unwrap().at += 1; advance(app, id); return }
let id = id.to_string();
let payload = target.identity.payload(mode);
#[cfg(test)]
@@ -330,6 +333,15 @@ fn received(app: &mut App, id: &str, index: usize, mode: &str, reply: Result<Val
}
};
let activity = reply["activity"].as_str().unwrap_or("unknown").to_string();
+ // It keeps running on purpose (a Swarm Buddy), whether the inspect said so or the stop was refused: close only its view.
+ if reply["keptRunning"] == true {
+ let op = app.session_close.operation.as_mut().unwrap();
+ op.targets[index].kept = true;
+ op.targets[index].activity = activity;
+ op.at += 1;
+ advance(app, id);
+ return;
+ }
if reply["error"] == "SESSION_NOT_IDLE" && mode == "idle" {
if !showing(app, id) { fail(app, "Activity changed before stopping. Check the session before trying again.".into()); return }
let op = app.session_close.operation.as_mut().unwrap();
@@ -434,7 +446,13 @@ fn finish(app: &mut App) {
}
let mut seen = HashSet::new();
for view in views {
- if op.return_to_shell && crate::shell_context::is_session_visit(app, view.pane) { continue }
+ if op.return_to_shell && crate::shell_context::is_session_visit(app, view.pane) {
+ // A stopped harness's visit returns to its shell as it stops. A kept one (a Swarm Buddy) was not stopped,
+ // so return it here, as Close pane after a refused stop does (`dismiss`).
+ let kept = op.targets.iter().any(|t| t.kept && t.identity.machine == view.machine && t.identity.agent == view.agent);
+ if kept && view.matches(app) { crate::shell_context::leave(app, view.pane); }
+ continue;
+ }
if seen.insert(view.pane) && view.matches(app) {
app.close_pane(view.pane);
}
@@ -914,6 +932,69 @@ mod tests {
assert!(matches!(&app.modal, Some(Modal::Menu(menu)) if menu.items.iter().any(|i| i.label.contains("1 stopped"))));
}
+ // A Swarm Buddy keeps running on purpose: the daemon answers `keptRunning`, and only the view closes (Desktop's
+ // `_reviewSessionClose`). Nothing asks to stop it, and nothing is sent after the inspect.
+ #[tokio::test]
+ async fn closing_a_pane_on_a_buddy_closes_the_view_and_stops_nothing() {
+ for activity in ["idle", "working"] {
+ let mut app = app();
+ pane(&mut app, 1);
+ answer(&mut app, "inspect", json!({"activity":activity, "keptRunning":true}));
+ assert_eq!(modes(&app), ["inspect"], "{activity}: no stop is asked for");
+ assert!(app.modal.is_none(), "{activity}: no question and no failure");
+ assert!(app.session_close.operation.is_none());
+ assert!(!app.panes.contains_key(&1), "{activity}: the view closes"); assert!(app.panes.contains_key(&2));
+ assert_eq!(app.fleet.agent("local", "a1").unwrap().status, "active", "{activity}: the Buddy keeps running");
+ assert!(app.toast.as_ref().is_none_or(|t| !t.0.contains("not confirmed")));
+ }
+ }
+
+ #[tokio::test]
+ async fn a_tab_with_a_buddy_asks_and_stops_only_the_other_harnesses() {
+ let tab_with_buddy = || {
+ let mut app = app();
+ app.tabs[0].root.as_mut().unwrap().split(1, 3, crate::layout::Dir::Horizontal);
+ app.panes.insert(3, crate::pane::Pane::new(3, "local", "a2", 40, 20));
+ tab(&mut app, 0);
+ answer(&mut app, "inspect", json!({"activity":"working", "keptRunning":true}));
+ app
+ };
+ // The other one idle: it stops without a question, and every view of the tab closes.
+ let mut app = tab_with_buddy();
+ answer(&mut app, "inspect", json!({"activity":"idle"}));
+ assert_eq!(modes(&app), ["inspect", "inspect", "idle"]);
+ assert_eq!(app.session_close.sent[2].1["agentId"], "a2");
+ answer(&mut app, "idle", json!({"closed":true}));
+ assert!(!app.panes.contains_key(&1) && !app.panes.contains_key(&3));
+ assert_eq!(app.fleet.agent("local", "a1").unwrap().status, "active");
+ assert_eq!(app.fleet.agent("local", "a2").unwrap().status, "stopped");
+ assert!(app.modal.is_none());
+ // The other one working: the question names only it, and Stop stops only it.
+ let mut app = tab_with_buddy();
+ answer(&mut app, "inspect", json!({"activity":"working"}));
+ assert_eq!(notes(&app), ["1 harness is still working.", "Stopping this harness will close the tab “tab-1”. History will be saved.",
+ "Task 2 · Working"]);
+ key(&mut app, KeyCode::Char('s'));
+ assert_eq!(modes(&app), ["inspect", "inspect", "now"]);
+ assert_eq!(app.session_close.sent[2].1["agentId"], "a2");
+ answer(&mut app, "now", json!({"closed":true}));
+ assert!(!app.panes.contains_key(&1) && !app.panes.contains_key(&3));
+ assert_eq!(app.fleet.agent("local", "a1").unwrap().status, "active");
+ }
+
+ #[tokio::test]
+ async fn a_stop_refused_because_it_is_a_buddy_closes_the_view() {
+ // A harness that became a Buddy after its inspect: the stop is refused, it keeps running, and its view closes.
+ let mut app = app();
+ pane(&mut app, 1);
+ answer(&mut app, "inspect", json!({"activity":"idle"}));
+ answer(&mut app, "idle", json!({"error":"BUDDY_PROTECTED", "detail":"This is a Swarm Buddy.", "activity":"idle", "keptRunning":true}));
+ assert_eq!(modes(&app), ["inspect", "idle"]);
+ assert!(app.modal.is_none() && app.session_close.operation.is_none());
+ assert!(!app.panes.contains_key(&1)); assert!(app.panes.contains_key(&2));
+ assert_eq!(app.fleet.agent("local", "a1").unwrap().status, "active");
+ }
+
#[tokio::test]
async fn default_tmux_close_keys_inspect_but_custom_confirmation_is_unchanged() {
for button in ['x', '&'] {
diff --git a/tui/src/shell_context.rs b/tui/src/shell_context.rs
index 992e1621e..853b07eb7 100644
--- a/tui/src/shell_context.rs
+++ b/tui/src/shell_context.rs
@@ -1077,6 +1077,23 @@ mod tests {
assert_eq!(app.fleet.agent("local", "chosen").unwrap().status, "active");
}
#[tokio::test]
+ async fn closing_a_buddy_on_a_picked_session_returns_the_pane_to_its_shell() {
+ // A Swarm Buddy keeps running (the daemon answers keptRunning): no stop is sent, and the pane goes back to its
+ // shell as Close pane after a refused stop does. Before, the close skipped the stop and left the pane as it was.
+ let (mut app, token, pane) = visit_fixture(false);
+ let chosen = app.fleet.agents.get_mut(&("local".into(), "chosen".into())).unwrap();
+ chosen.close_supported = true;
+ chosen.created_at_wire = "2026-10-05T00:00:00.123Z".into();
+ chosen.terminal_available = true;
+ app.session_close.replies.extend([Ok(json!({"activity":"idle", "keptRunning":true}))]);
+ crate::session_close::pane(&mut app, pane);
+ assert_eq!(app.session_close.sent.len(), 1, "only the inspect; no stop");
+ assert!(app.modal.is_none());
+ assert_eq!(app.panes[&app.focused().unwrap()].agent_id, "shell");
+ assert!(app.shell_context.contexts[&token].visit.is_none());
+ assert_eq!(app.fleet.agent("local", "chosen").unwrap().status, "active");
+ }
+ #[tokio::test]
async fn retired_source_returns_to_its_surviving_shell_even_after_archive_is_removed() {
let (mut app,token,_) = visit_fixture(false);
let original = app.fleet.agents.get_mut(&("local".into(),"shell".into())).unwrap();