The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Batch U: Add this Mac (#2105), proposal attachments (#2103), composer error per chat (#2120), leaderboard tabs (#2097) (#2124)
0xken152a98fb764dc7
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex d0a2a3a25..cd552a2f8 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -3,11 +3,14 @@ import { execFile } from 'node:child_process'import { promisify } from 'node:util'import { join } from 'node:path'import { tmpdir } from 'node:os'+import { Readable } from 'node:stream'+import { crc32, deflateSync, inflateSync } from 'node:zlib'import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'+import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'import type { Command } from '../src/superTabs/commands.js'import { poolRows } from './hostRows.test-support.js'@@ -39,7 +42,8 @@ afterAll(async () => {/** A Swarm whose PM runs on the owner's Mac, peer a member with their own Mac in the Machines list, and Buddies on. */async function swarm() {- const store = new SuperTabStore(db, () => Date.now())+ const files = new MemoryAttachmentStore()+ const store = new SuperTabStore(db, () => Date.now(), { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })const tab = (await store.create(owner, randomUUID(), 'Buddies', 'public')).idconst execute = (command: Command, user = owner, asAgentId?: string, hostMachineId?: string) =>store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId, hostMachineId)@@ -53,7 +57,7 @@ async function swarm() {diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })await execute({ type: 'tab.buddies', enabled: true })- return { store, tab, execute, lead }+ return { store, tab, execute, lead, files }}/** peer's Buddy, added and started by peer-mac's host as a running host does. */@@ -68,6 +72,39 @@ async function buddy(f: Awaited<ReturnType<typeof swarm>>) {return { chat, agentId, pool }}+/** A complete PNG: one opaque red pixel, its chunks' checksums real, as a screenshot tool writes one. */+function png(): Buffer {+ const chunk = (type: string, data: Buffer) => {+ const body = Buffer.concat([Buffer.from(type, 'latin1'), data])+ const length = Buffer.alloc(4), sum = Buffer.alloc(4)+ length.writeUInt32BE(data.length)+ sum.writeUInt32BE(crc32(body))+ return Buffer.concat([length, body, sum])+ }+ const header = Buffer.alloc(13)+ header.writeUInt32BE(1, 0)+ header.writeUInt32BE(1, 4)+ header.set([8, 6, 0, 0, 0], 8)+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', header),+ chunk('IDAT', deflateSync(Buffer.from([0, 255, 0, 0, 255]))), chunk('IEND', Buffer.alloc(0))])+}++/** What an image viewer reads from a PNG: its size and its first pixel, after checking every chunk's checksum. */+function openPng(bytes: Buffer): { width: number; height: number; pixel: number[] } {+ if (!bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) throw new Error('not a PNG')+ let at = 8, width = 0, height = 0+ const data: Buffer[] = []+ for (;;) {+ const length = bytes.readUInt32BE(at), type = bytes.toString('latin1', at + 4, at + 8), body = bytes.subarray(at + 8, at + 8 + length)+ if (crc32(bytes.subarray(at + 4, at + 8 + length)) !== bytes.readUInt32BE(at + 8 + length)) throw new Error(`bad ${type} checksum`)+ if (type === 'IHDR') { width = body.readUInt32BE(0); height = body.readUInt32BE(4) }+ if (type === 'IDAT') data.push(body)+ at += 12 + length+ if (type === 'IEND') break+ }+ return { width, height, pixel: [...inflateSync(Buffer.concat(data)).subarray(1, 5)] }+}+describe('a Buddy through the store', () => {it('starts on its owner\'s machine from a list older hosts do not read, and joins its owner\'s chat', async () => {const f = await swarm()@@ -107,4 +144,59 @@ describe('a Buddy through the store', () => {await expect(f.execute({ type: 'message.send', conversationId: 'lead', text: 'Hi PM', replyTo: null, recipientIds: [] }, peer, agentId)).rejects.toThrow('A Buddy posts only in its own chat')})++ it('carries the files its owner handed it on the proposal, for the PM to open, and no other file', async () => {+ const f = await swarm()+ const { chat, agentId } = await buddy(f)+ const upload = async (name: string, mime: string, bytes: Buffer, conversationId = chat, asBuddy = true) =>+ (await f.store.upload(peer, f.tab, conversationId, { name, mime, body: Readable.from([bytes]) }, asBuddy ? agentId : undefined)).attachment.id+ const plan = await upload('plan.md', 'text/markdown', Buffer.from('# Offline sync\n'))+ const shot = await upload('shot.png', 'image/png', png())+ // A log its owner sent in their chat, and one they uploaded but never sent.+ const log = await upload('sync.log', 'text/plain', Buffer.from('conflict at 10:02\n'), chat, false)+ const sentIn = String((await f.execute({ type: 'message.send', conversationId: chat, text: 'Here is the log', replyTo: null, recipientIds: [], attachmentIds: [log] }, peer)).result.messageId)+ const unsent = await upload('draft.txt', 'text/plain', Buffer.from('not for the PM'), chat, false)+ const ask = async () => String((await f.execute({ type: 'message.send', conversationId: chat, text: 'Send it to the PM with the plan', replyTo: null, recipientIds: [] }, peer)).result.messageId)+ const propose = async (attachmentIds: string[], ownerMessageId?: string) => f.execute({ type: 'buddy.propose', conversationId: chat,+ ownerMessageId: ownerMessageId ?? await ask(), goal: 'Offline sync', scope: 'Desktop only', priority: 'normal', attachmentIds }, peer, agentId)++ await expect(propose([plan, unsent])).rejects.toThrow('Upload this file again')+ await expect(propose([plan, 'a'.repeat(24), 'b'.repeat(24), 'c'.repeat(24), 'd'.repeat(24), 'e'.repeat(24)])).rejects.toThrow('at most 5 files')+ const sent = await propose([plan, shot, log])+ const id = String(sent.result.messageId)+ const read = (await f.store.messages(owner, f.tab, 'lead', {}, f.lead)).messages.find(m => m.id === id)+ expect(read?.attachments?.map(a => [a.name, a.mime, a.url.startsWith('https://cdn.example.test/super-tabs/')])).toEqual([+ ['plan.md', 'text/markdown', true], ['shot.png', 'image/png', true], ['sync.log', 'text/plain', true]])+ expect((await f.store.messages(owner, f.tab, 'lead', {})).messages.find(m => m.id === id)?.attachments).toHaveLength(3)+ // Each opens from its link as the apps open it: the picture shown in place, the plan and the log as their own text.+ const opened = (url: string) => f.files.objects.get(new URL(url).pathname.slice(1))!+ const [planFile, shotFile, logFile] = read!.attachments!.map(a => opened(a.url))+ expect(openPng(shotFile!.bytes)).toEqual({ width: 1, height: 1, pixel: [255, 0, 0, 255] })+ expect(shotFile).toMatchObject({ contentType: 'image/png', contentDisposition: "inline; filename*=UTF-8''shot.png" })+ expect([planFile!.bytes.toString(), logFile!.bytes.toString()]).toEqual(['# Offline sync\n', 'conflict at 10:02\n'])+ expect(planFile).toMatchObject({ contentDisposition: "attachment; filename*=UTF-8''plan.md" })+ // Its own files go with the proposal; its owner's stays with their message too.+ const rows = await db.superTabAttachment.findMany({ where: { tabId: f.tab, id: { in: [plan, shot, log, unsent] } } })+ expect(Object.fromEntries(rows.map(r => [r.id, r.usedBy ?? null]))).toEqual({ [plan]: id, [shot]: id, [log]: sentIn, [unsent]: null })+ // Each goes with one proposal at most: a file it already sent, and its owner's file already proposed, go again only+ // as new files. Nor does one its owner sent outside their chat.+ await expect(propose([plan])).rejects.toThrow('Upload this file again')+ await expect(propose([log])).rejects.toThrow('already went with a proposal')+ // Two proposals racing for one file of its owner's: one carries it.+ const again = await upload('again.log', 'text/plain', Buffer.from('conflict at 10:05\n'), chat, false)+ await f.execute({ type: 'message.send', conversationId: chat, text: 'And this one', replyTo: null, recipientIds: [], attachmentIds: [again] }, peer)+ const [first, second] = [await ask(), await ask()]+ const raced = await Promise.allSettled([propose([again], first), propose([again], second)])+ expect(raced.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])+ expect(await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: 'lead', source: { equals: { kind: 'buddy-proposal', personId: peer.sub, ownerMessageId: first } } } })+ + await db.superTabMessage.count({ where: { tabId: f.tab, conversationId: 'lead', source: { equals: { kind: 'buddy-proposal', personId: peer.sub, ownerMessageId: second } } } })).toBe(1)+ const elsewhere = await upload('other.txt', 'text/plain', Buffer.from('project chat'), 'lead', false)+ await f.execute({ type: 'message.send', conversationId: 'lead', text: 'FYI', replyTo: null, recipientIds: [], attachmentIds: [elsewhere] }, peer)+ await expect(propose([elsewhere])).rejects.toThrow('Upload this file again')+ // Nor can it post a file in the project chat any other way.+ await expect(upload('leak.md', 'text/markdown', Buffer.from('x'), 'lead')).rejects.toThrow('does not participate')+ const loose = await upload('loose.md', 'text/markdown', Buffer.from('x'))+ await expect(f.execute({ type: 'message.send', conversationId: 'lead', text: '', replyTo: null, recipientIds: [], attachmentIds: [loose] }, peer, agentId))+ .rejects.toThrow('Attach this file again')+ })})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 9f5951eaf..c38e268bb 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1169,6 +1169,9 @@ model SuperTabAttachment {size IntobjectKey StringusedBy String?+ /// The Buddy proposal that carried this file, when its owner sent it in their Buddy chat (superTabs/store.ts proposable):+ /// each file goes with one proposal at most. Their own message keeps it as `usedBy`.+ proposedBy String?/// `avatar` for a profile picture (superTabs/profile.ts), which no message sends; absent on a chat file.purpose String?createdAt DateTime @default(now())diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex 6bb8ff9a4..87dc2ebea 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -373,6 +373,36 @@ describe('a Buddy\'s proposal to the PM', () => {author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } } }).messages).toHaveLength(1)})+ it('carries the files the store found it may send, on the proposal message in the project chat', () => {+ const { f, propose } = asked()+ const files = [{ id: 'plan', name: 'plan.md', mime: 'text/markdown', size: 120, url: 'https://cdn.example.test/t/k1/plan.md' },+ { id: 'shot', name: 'shot.png', mime: 'image/png', size: 2048, url: 'https://cdn.example.test/t/k2/shot.png' }]+ const posted = f.run({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId: 'ask', ...proposal, attachmentIds: ['plan', 'shot', 'plan'] }, buddy,+ { proposalAsk: { id: 'ask', conversationId: f.chat, source: false, createdAt: 900,+ author: { kind: 'person', id: 'peer', name: 'peer', membershipGeneration: 'first' } }, attachments: files }).messages+ expect(posted).toEqual([expect.objectContaining({ conversationId: f.app.conversationId, attachments: files,+ source: { kind: 'buddy-proposal', personId: 'peer', ownerMessageId: 'ask' } })])+ expect(propose('ask2').messages[0]).not.toHaveProperty('attachments')+ })++ it('refuses a file the store did not find it may send, and more than five', () => {+ const { f } = asked()+ const context = { proposalAsk: { id: 'ask', conversationId: f.chat, source: false, createdAt: 900,+ author: { kind: 'person' as const, id: 'peer', name: 'peer', membershipGeneration: 'first' } } }+ expect(() => f.run({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId: 'ask', ...proposal, attachmentIds: ['elsewhere'] }, buddy, context))+ .toThrow('Upload this file again')+ expect(() => f.run({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId: 'ask', ...proposal, attachmentIds: ['a', 'b', 'c', 'd', 'e', 'f'] }, buddy, context))+ .toThrow('at most 5 files')+ expect(group(f, f.chat).proposals).toBeUndefined()+ })++ it('never posts a file in the project chat outside a proposal', () => {+ const { f } = asked()+ expect(() => f.run({ type: 'message.send', conversationId: f.app.conversationId, text: '', replyTo: null, recipientIds: [], attachmentIds: ['plan'] }, buddy,+ { attachments: [{ id: 'plan', name: 'plan.md', mime: 'text/markdown', size: 120, url: 'https://cdn.example.test/t/k1/plan.md' }] }))+ .toThrow('A Buddy posts only in its own chat')+ })+it('is a Buddy\'s alone, and only while Buddies are on', () => {const { f, propose } = asked()expect(() => f.run({ type: 'buddy.propose', conversationId: f.app.conversationId, ownerMessageId: 'ask', ...proposal }, agentActor(f.pm))).toThrow('Only a Buddy')diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.tsindex 04a855c59..61e9ffea5 100644--- a/backend/src/superTabs/buddies.ts+++ b/backend/src/superTabs/buddies.ts@@ -49,6 +49,8 @@ export function requireBuddyCommand(buddy: Agent, command: { type: string; conveexport const MAX_PROPOSAL_ASKS = 200/** How long an owner's message, other than their newest in the chat, may still be named as asking for a proposal. */export const PROPOSAL_ASK_MS = 60 * 60_000+/** The files one proposal may carry: its plan, spec, log or screenshot, each held to a chat file's own limits. */+export const MAX_PROPOSAL_ATTACHMENTS = 5/** Written by the server, never the Buddy: who it is for and on whose behalf, then the three parts the PM needs. */export function proposalText(owner: string, proposal: { goal: string; scope: string; priority: string }): string {diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex fc290276f..e8e1d0eea 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -20,14 +20,15 @@ import { digestStartsAfter, knownTimeZone } from './digest.js'import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'import { workspaceCan, type WorkspaceRole } from './workspaces.js'-import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordDecision, recordMerged, recordPost, recordReview, recordRun, recordStatus } from './leaderboard/record.js'+import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordDecision, recordMerged, recordPost, recordProposal, recordReview, recordRun, recordStatus,+ recordVerdict } from './leaderboard/record.js'import { WEEK_MS } from './leaderboard/week.js'import { react, reactionSchema, type ReactionTarget } from './reactions.js'import { shipNotice, shippedAt } from './ship.js'import { openReview, openReviewOf, projectPullRequest, verdictPending } from './autoReview.js'import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, markConfidential, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'-import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, PROPOSAL_ASK_MS, proposalText, requireBuddyCommand } from './buddies.js'+import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, PROPOSAL_ASK_MS, proposalText, requireBuddyCommand } from './buddies.js'import { CODEX_BUDDY_REFUSAL } from './buddyContract.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)@@ -117,7 +118,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('project.roles.reset'), projectId: id, roles: roleSet }).strict(),// `audience`: a private conversation that only these people and the project's Lead read (projects.ts canReadGroup).z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(), checks: z.array(check).max(40),- audience: z.object({ personIds: z.array(id).max(200) }).strict().optional(), requesterId: id.optional() }).strict()+ audience: z.object({ personIds: z.array(id).max(200) }).strict().optional(), requesterId: id.optional(),+ // The Buddy's proposal message in the project chat the group comes from (Lead, 2026-10-29): the Buddy earns when it ships.+ proposalMessageId: id.optional() }).strict().refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.').refine(c => !c.task || renderWorkTask(c.task).length <= 8000, 'Keep the rendered task within 8,000 characters.'),z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),@@ -130,9 +133,10 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), roleId: roleId.optional(), initialMessage: text.optional() }).strict(),z.object({ type: z.literal('agent.start'), request: startRequestSchema, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),// A Buddy's proposal for its owner, posted in its project's chat: `conversationId` is its own chat, and `ownerMessageId` its- // owner's message there asking for it.+ // owner's message there asking for it. Its files are its own uploads in that chat, or files its owner sent there (store.ts proposable).z.object({ type: z.literal('buddy.propose'), conversationId: id, ownerMessageId: id, goal: z.string().trim().min(1).max(2000),- scope: z.string().trim().min(1).max(4000), priority: z.enum(['low', 'normal', 'high']) }).strict(),+ scope: z.string().trim().min(1).max(4000), priority: z.enum(['low', 'normal', 'high']),+ attachmentIds: z.array(id).max(MAX_PROPOSAL_ATTACHMENTS, `Attach at most ${MAX_PROPOSAL_ATTACHMENTS} files to a proposal.`).optional() }).strict(),z.object({ type: z.literal('buddy.remove'), projectId: id }).strict(),// A person's own Buddy in a project, on a machine of the Swarm (buddies.ts).z.object({ type: z.literal('buddy.create'), projectId: id, machineId: id, engine: swarmEngine, model: z.string().trim().min(1).max(200).optional() }).strict(),@@ -269,6 +273,8 @@ export interface CommandContext {/** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */openTags?: Array<{ messageId: string; createdAt: number }>/** The message a Buddy's proposal names as its owner's request, loaded from this tab by the store. */+ /** The proposal a new group names as its origin (conversation.create proposalMessageId), loaded from this tab by the store. */+ proposal?: { id: string; conversationId: string; author: Author; source: Record<string, unknown> | null }proposalAsk?: { id: string; conversationId: string; author: Author; source: boolean; createdAt: number/** The owner's newest message in that chat, which may always be named. */newestOwnerMessageId?: string }@@ -280,7 +286,8 @@ export interface CommandContext {confirmedStopped?: boolean/** An uncertain receipt and its original message, read transactionally. */delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string; attachments?: Attachment[] }- /** The files `message.send` names, each checked by the store: uploaded by this actor to this conversation, and unused. */+ /** The files `message.send` or `buddy.propose` names, each checked by the store: uploaded by this actor to this conversation and+ * unused, or for a proposal, sent there by its Buddy's owner (store.ts proposable). */attachments?: Attachment[]/** The avatar upload `member.avatar` or `agent.avatar` names, checked by the store the same way (profile.ts). */avatarUpload?: AvatarUpload@@ -475,6 +482,18 @@ function requester(state: SuperTabState, project: SwarmProject, personId: stringif (!canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)) fail('REQUESTER_UNAVAILABLE', 'Name a person who can read this project.', 400)return member.id}+/** The Buddy whose proposal a new group comes from: the message must be a Buddy's proposal posted in the project's chat. Its+ * row is the Swarm's own (buddy.propose), so a Buddy removed since still earns for it. */+function proposalOf(state: SuperTabState, project: SwarmProject, proposal: CommandContext['proposal']): { buddyId: string; messageId: string } {+ const author = proposal?.author+ const buddy = author?.kind === 'agent' ? state.agents.find(a => a.id === author.id) : undefined+ if (!proposal || proposal.conversationId !== project.leadConversationId || proposal.source?.kind !== 'buddy-proposal'+ || author?.kind !== 'agent' || (buddy && !isBuddy(buddy))) {+ fail('PROPOSAL_UNKNOWN', 'Name a Buddy\'s proposal posted in this project\'s chat, or leave the proposal out.', 400)+ }+ return { buddyId: author.id, messageId: proposal.id }+}+function open(state: SuperTabState, conversationId: string) {const group = conversation(state, conversationId)if (group.archived) fail('ARCHIVED', 'Reopen this conversation before changing its work.')@@ -1129,7 +1148,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (command.audience) {pmChatClosed(true)// A private conversation is chat only: no task, checks or review, so private work never reaches other Leads.- if (command.task || command.checks.length || command.reviewOf || command.requesterId) fail('AUDIENCE_CHAT_ONLY', 'A private conversation is chat only.', 400)+ if (command.task || command.checks.length || command.reviewOf || command.requesterId || command.proposalMessageId) {+ fail('AUDIENCE_CHAT_ONLY', 'A private conversation is chat only.', 400)+ }if (actor.kind === 'person' && !command.audience.personIds.includes(actor.userId)) {fail('AUDIENCE_SELF', 'Open a private conversation with yourself in it.', 403)}@@ -1159,6 +1180,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commachecks: command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null })),})recordAsked(state.conversations.at(-1)!, requesterId, context.now)+ if (command.proposalMessageId) recordProposal(state.conversations.at(-1)!, proposalOf(state, project, context.proposal))result.conversationId = operationIdresult.number = numberif (brief) message(operationId, brief, [], null, SYSTEM_ROW)@@ -1363,11 +1385,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafail('PROPOSAL_STALE', 'Send a proposal for your owner\'s newest message in your chat, or one from the last hour. Ask them again.', 403)}if (chat.proposals?.includes(command.ownerMessageId)) fail('PROPOSAL_SENT', 'A proposal was already sent for that message. Ask your owner before sending another.')+ const attachments = [...new Set(command.attachmentIds ?? [])]+ .map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))chat.proposals = [...chat.proposals ?? [], command.ownerMessageId].slice(-MAX_PROPOSAL_ASKS)const project = projectOf(state, agentProjectId(state, self)), home = conversation(state, project.leadConversationId)const name = owner.email.split('@')[0]!message(home.id, proposalText(name, command), home.leadId && home.agentIds.includes(home.leadId) ? [home.leadId] : [], null,- { kind: 'buddy-proposal', personId: owner.id, ownerMessageId: command.ownerMessageId })+ { kind: 'buddy-proposal', personId: owner.id, ownerMessageId: command.ownerMessageId }, attachments)break}case 'buddy.remove': {@@ -2039,6 +2063,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commacheck.evidence = command.evidencecheck.passedBy = command.passed ? actorKey(actor) : nullrecordReview(group, check, command.passed)+ if (actor.kind === 'agent') recordVerdict(state, group, check, agent(state, actor.agentId), context.now)if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)break}diff --git a/backend/src/superTabs/leaderboard/contract.ts b/backend/src/superTabs/leaderboard/contract.tsindex efe22b7be..f02daebb2 100644--- a/backend/src/superTabs/leaderboard/contract.ts+++ b/backend/src/superTabs/leaderboard/contract.ts@@ -43,6 +43,40 @@ export interface WeekGoal { shipped: number; points: number; medianAskToShipMs:* cheaper models without lower quality). */export interface ModelShare { attempts: number; grid: number; reviewed: { grid: number; subscription: number }; passedFirst: { grid: number; subscription: number } }+/** A permanent agent of the project, its PM or a Buddy, scored by name like a person (Dee, 2026-10-29). */+export interface AgentScore {+ agentId: string+ displayName: string+ kind: 'pm' | 'buddy'+ /** A Buddy's person; null for the PM. */+ personId: string | null+ machineId: string+ /** SHIPPED_POINTS for each request shipped this week: the PM's of groups it led, a Buddy's of groups opened from its proposals. */+ points: number+ rank: number+ shipped: number+}++/** The temporary workers, Builders and Reviewers, by what they ran on, never by agent: a worker lives for an hour (Dee,+ * 2026-10-29). Which model to route which work to is read from these, so every number is a recorded one. */+export interface ModelScore {+ engine: string+ model: string | null+ /** Null for attempts recorded before efforts were. */+ effort: string | null+ /** A model served on the Swarm's grid. */+ grid: boolean+ /** SHIPPED_POINTS per request it shipped this week, REVIEW_POINTS per review verdict it gave. */+ points: number+ rank: number+ /** Requests its attempt shipped this week; median times to ship from that attempt's assignment, and from the request's first. */+ shipped: { count: number; medianAttemptMs: number | null; medianRequestMs: number | null }+ /** This week's attempts on it with a first review on record, and how many passed it. */+ firstReview: { reviewed: number; passed: number }+ /** Review verdicts it gave this week. */+ reviews: number+}+export interface Leaderboard {projectId: stringweek: number@@ -54,4 +88,8 @@ export interface Leaderboard {waiting: { total: number; people: Array<{ personId: string; count: number; conversationIds: string[] }> }/** Absent from a backend before it. */models: { thisWeek: ModelShare; lastWeek: ModelShare }+ /** The project's PM and Buddies, most points first. Absent from a backend before them. */+ agents: AgentScore[]+ /** Every model that worked this week, most points first. Absent from a backend before it. */+ byModel: ModelScore[]}diff --git a/backend/src/superTabs/leaderboard/read.test.ts b/backend/src/superTabs/leaderboard/read.test.tsindex e5eec0582..41ec926ca 100644--- a/backend/src/superTabs/leaderboard/read.test.ts+++ b/backend/src/superTabs/leaderboard/read.test.ts@@ -20,7 +20,7 @@ describe('the dormant groups the leaderboard sums', () => {expect(await recentDormantGroups(tx, 'tab', 'web', since)).toEqual([{ id: 'g1', requesterId: 'peer', ledger: { shippedAt: since + 1 }, assignment: { id: 'a1', status: 'done' } }])const [{ pipeline }] = asked as [{ pipeline: Array<Record<string, Record<string, unknown>>> }]expect(pipeline[0]!.$match).toEqual({ tabId: 'tab', deleted: false, dormant: true, lastActivityAt: { $gte: { $date: new Date(since).toISOString() } }, projectId: { $in: ['web'] } })- expect(Object.keys(pipeline[1]!.$project!).sort()).toEqual(['_id', ...['archived', 'assignment.id', 'assignment.status', 'audience', 'id', 'kind', 'ledger',+ expect(Object.keys(pipeline[1]!.$project!).sort()).toEqual(['_id', ...['archived', 'assignment.id', 'assignment.status', 'audience', 'id', 'kind', 'leadId', 'ledger','projectId', 'pullRequestUrls', 'requesterId', 'reviewOf', 'title'].map(field => `data.${field}`)].sort())})diff --git a/backend/src/superTabs/leaderboard/read.ts b/backend/src/superTabs/leaderboard/read.tsindex f1f42aa47..5504b5dcf 100644--- a/backend/src/superTabs/leaderboard/read.ts+++ b/backend/src/superTabs/leaderboard/read.ts@@ -17,7 +17,7 @@ export function readableWeek(week: number | undefined, now: number): number {/** What the board reads of a group (stats.ts, record.ts waitsNow) and its read check (projects.ts canReadGroup); the title* names it in a person's details. */-const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'audience', 'requesterId', 'reviewOf', 'archived', 'pullRequestUrls', 'ledger',+const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'leadId', 'audience', 'requesterId', 'reviewOf', 'archived', 'pullRequestUrls', 'ledger','assignment.id', 'assignment.status'] as const/** Dormant groups of one project active since [since]: a request shipped in a week the board sums wrote its Done row then.diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.tsindex cddac3225..1b2d8ff46 100644--- a/backend/src/superTabs/leaderboard/record.test.ts+++ b/backend/src/superTabs/leaderboard/record.test.ts@@ -527,7 +527,18 @@ describe('the model behind each assignment, and its first review (roadmap, Dec:f.at(5_000)const id = f.create(owner, { checks: independent })const { assignmentId } = f.assign(id)- expect(f.group(id).ledger!.runs).toEqual([{ assignmentId, engine: 'claude', model: 'opus', at: 5_000 }])+ expect(f.group(id).ledger!.runs).toEqual([{ assignmentId, engine: 'claude', model: 'opus', effort: 'high', at: 5_000 }])+ })++ it('records no effort that names none: what Claude Code reports as auto, or a start that left the engine its own', () => {+ for (const effort of ['auto', 'default', null]) {+ const f = fixture()+ const id = f.create(owner, { checks: independent })+ const worker = f.add(`w-${effort}`, id)+ f.state.agents.find(a => a.id === worker)!.configuration.effort = effort+ f.assign(id, worker)+ expect(f.group(id).ledger!.runs![0], String(effort)).not.toHaveProperty('effort')+ }})it('names the grid model from the start of an agent from before agents kept it, while that start is loaded', () => {@@ -540,7 +551,7 @@ describe('the model behind each assignment, and its first review (roadmap, Dec:gridModel: 'moonshotai/kimi-k3', gridName: 'swarm-0123456789ab',requirements: { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 80, tools: [], devices: [], quotaRequired: false } } }]const { assignmentId } = f.assign(id, worker)- expect(f.group(id).ledger!.runs).toEqual([{ assignmentId, engine: 'claude', model: 'moonshotai/kimi-k3', grid: true, at: 1_000 }])+ expect(f.group(id).ledger!.runs).toEqual([{ assignmentId, engine: 'claude', model: 'moonshotai/kimi-k3', effort: 'high', grid: true, at: 1_000 }])})it('keeps the first verdict on an independent check as the assignment\'s first review, and ignores later and other checks', () => {@@ -583,6 +594,45 @@ describe('the model behind each assignment, and its first review (roadmap, Dec:expect(g.group(both).ledger!.runs![0]).toMatchObject({ firstReview: true })})+ it('records each finished review verdict an agent gives, with the model it ran on, for the reviewer models\' points', () => {+ const f = fixture()+ f.at(7_000)+ const id = f.create(owner, { checks: independent })+ const { assignmentId } = f.assign(id)+ const reviewer = f.add('reviewer', id)+ f.state.agents.find(a => a.id === reviewer)!.configuration = { ...config, engine: 'codex', model: 'gpt-5.5', effort: 'medium' }+ verdict(f, id, assignmentId, false, true, f.asAgent(reviewer))+ verdict(f, id, assignmentId, true, true, f.asAgent(reviewer))+ // A person's verdict, and one on a check that is not a review, are no model's review.+ verdict(f, id, assignmentId, true)+ verdict(f, id, assignmentId, true, false, f.asAgent(reviewer))+ expect(f.group(id).ledger!.reviews).toEqual([+ { week: weekStart(7_000), engine: 'codex', model: 'gpt-5.5', effort: 'medium', count: 2 },+ ])+ })++ it('counts every verdict exactly, however many a group gets in a week (review of #2097)', () => {+ const f = fixture()+ const id = f.create(owner, { checks: independent })+ const { assignmentId } = f.assign(id)+ const reviewer = f.add('reviewer', id)+ for (let i = 0; i < 45; i++) verdict(f, id, assignmentId, i % 2 === 0, true, f.asAgent(reviewer))+ expect(f.group(id).ledger!.reviews).toEqual([{ week: weekStart(1_000), engine: 'claude', model: 'opus', effort: 'high', count: 45 }])+ })++ it('keeps review counts for the weeks the board reads, and drops older ones', () => {+ const f = fixture()+ const id = f.create(owner, { checks: independent })+ const { assignmentId } = f.assign(id)+ const reviewer = f.add('reviewer', id)+ const start = weekStart(Date.UTC(2026, 9, 26))+ for (let back = 6; back >= 0; back--) {+ f.at(start - back * WEEK_MS + DAY_MS)+ verdict(f, id, assignmentId, true, true, f.asAgent(reviewer))+ }+ expect(f.group(id).ledger!.reviews!.map(r => (start - r.week) / WEEK_MS)).toEqual([4, 3, 2, 1, 0])+ })+it('keeps the last 20 assignments of a group', () => {const f = fixture()const id = f.create(owner, { checks: independent })@@ -596,4 +646,160 @@ describe('the model behind each assignment, and its first review (roadmap, Dec:expect(f.group(id).ledger!.runs).toHaveLength(20)expect(f.group(id).ledger!.runs!.map(r => r.assignmentId)).not.toContain(first)})++ it('takes the first assignment time from the kept attempts for a request recorded before it was kept (review of #2097)', () => {+ const f = fixture()+ const id = f.create(owner, { checks: independent })+ const worker = f.add('worker', id)+ f.at(10_000)+ const first = f.assign(id, worker)+ f.run({ type: 'work.cancel', conversationId: id, assignmentId: first.assignmentId, reason: 'Again.' })+ // As a group recorded before the time was kept.+ delete f.group(id).ledger!.firstAssignedAt+ f.at(10_001)+ f.assign(id, worker)+ expect(f.group(id).ledger!.firstAssignedAt).toBe(10_000)+ })++ it('records the attempt a request shipped on, and keeps it through a later attempt (review of #2097)', () => {+ const f = fixture()+ f.at(5_000)+ const id = f.create(owner, { checks })+ const { worker, assignmentId } = f.assign(id)+ f.at(6_000)+ f.passChecks(id, assignmentId)+ f.status(id, assignmentId, worker, 'done', 'Shipped at rev abc.')+ const shippedBy = { assignmentId, at: 5_000, engine: 'claude', model: 'opus', effort: 'high' }+ expect(f.group(id).ledger!.shippedBy).toEqual(shippedBy)+ // Reopened and worked again on another model: the ship stays the first attempt's.+ const other = f.add('other', id)+ f.state.agents.find(a => a.id === other)!.configuration = { ...config, model: 'sonnet' }+ f.at(7_000)+ f.assign(id, other)+ expect(f.group(id).ledger!.shippedBy).toEqual(shippedBy)+ })++ it('keeps who led the group and the attempt when it shipped, through a later lead and a later merge record (review of #2097)', () => {+ const f = fixture()+ const lead = f.add('lead', 'lead', true)+ const id = f.create(owner, { checks })+ expect(f.group(id).leadId).toBe(lead)+ f.at(1_000)+ const { worker, assignmentId } = f.assign(id)+ f.passChecks(id, assignmentId)+ f.status(id, assignmentId, worker, 'done', 'Shipped at rev abc.')+ const shippedBy = f.group(id).ledger!.shippedBy+ expect(f.group(id).ledger!.shippedLeadId).toBe(lead)+ f.group(id).leadId = 'someone-else'+ f.at(2_000)+ f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: 'https://github.com/o/r/pull/7' })+ expect(f.group(id).ledger).toMatchObject({ shippedAt: 2_000, shippedLeadId: lead, shippedBy })+ })++ it('keeps the shipping attempt through a later assignment before the merge is recorded (review of #2097)', () => {+ const f = fixture()+ const id = f.create(owner, { checks })+ f.at(1_000)+ const { worker, assignmentId } = f.assign(id)+ f.passChecks(id, assignmentId)+ f.status(id, assignmentId, worker, 'done', 'Shipped at rev abc.')+ const other = f.add('other', id)+ f.state.agents.find(a => a.id === other)!.configuration = { ...config, model: 'sonnet' }+ f.at(1_500)+ f.assign(id, other)+ f.at(2_000)+ f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: 'https://github.com/o/r/pull/7' })+ expect(f.group(id).ledger!.shippedBy).toMatchObject({ assignmentId, model: 'opus', at: 1_000 })+ })++ it('ships on the attempt that ran when the recorded merge happened', () => {+ const f = fixture()+ const id = f.create(owner, { checks })+ f.at(5_000)+ const first = f.assign(id)+ f.run({ type: 'work.cancel', conversationId: id, assignmentId: first.assignmentId, reason: 'Again.' })+ f.at(8_000)+ f.assign(id, f.add('second', id))+ f.at(9_000)+ f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: 'https://github.com/o/r/pull/7', mergedAt: new Date(6_000).toISOString() })+ expect(f.group(id).ledger!.shippedBy).toMatchObject({ assignmentId: first.assignmentId, at: 5_000 })+ })++ it('takes the snapshot again when a merge recorded later moves the ship earlier than Done (review of #2097)', () => {+ const f = fixture()+ const lead = f.add('lead', 'lead', true)+ const id = f.create(owner, { checks })+ f.at(5_000)+ const a = f.assign(id)+ f.run({ type: 'work.cancel', conversationId: id, assignmentId: a.assignmentId, reason: 'Again.' })+ const other = f.add('other', id)+ f.state.agents.find(x => x.id === other)!.configuration = { ...config, model: 'sonnet' }+ f.at(8_000)+ const b = f.assign(id, other)+ f.at(8_500)+ f.passChecks(id, b.assignmentId)+ f.status(id, b.assignmentId, other, 'done', 'Shipped at rev abc.')+ expect(f.group(id).ledger!.shippedBy).toMatchObject({ assignmentId: b.assignmentId, model: 'sonnet' })+ f.group(id).leadId = 'someone-else'+ f.at(9_000)+ f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: 'https://github.com/o/r/pull/7', mergedAt: new Date(6_000).toISOString() })+ // The attempt running at the merge, with the lead kept from the ship (no lead history is recorded).+ expect(f.group(id).ledger).toMatchObject({ shippedAt: 6_000, shippedBy: { assignmentId: a.assignmentId, model: 'opus', at: 5_000 },+ shippedLeadId: lead })+ })++ it('ships on the earliest attempt when the merge came before any attempt started', () => {+ const f = fixture()+ const id = f.create(owner, { checks })+ f.at(5_000)+ const { assignmentId } = f.assign(id)+ f.at(9_000)+ f.run({ type: 'conversation.merged', conversationId: id, pullRequestUrl: 'https://github.com/o/r/pull/7', mergedAt: new Date(4_000).toISOString() })+ expect(f.group(id).ledger).toMatchObject({ shippedAt: 4_000, shippedBy: { assignmentId, at: 5_000 } })+ })++ it('keeps the request\'s first assignment time once its first attempt has rolled off (review of #2097)', () => {+ const f = fixture()+ const id = f.create(owner, { checks: independent })+ const worker = f.add('worker', id)+ for (let i = 0; i < 21; i++) {+ f.at(10_000 + i)+ const { assignmentId } = f.assign(id, worker)+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })+ }+ expect(f.group(id).ledger!.runs![0]!.at).toBe(10_001)+ expect(f.group(id).ledger!.firstAssignedAt).toBe(10_000)+ })+})++describe('a group opened from a Buddy\'s proposal (Lead, 2026-10-29: the Buddy earns when it ships)', () => {+ /** A Buddy of the owner in the project, and its proposal posted in the project chat. */+ function proposed(f: ReturnType<typeof fixture>) {+ const buddy = f.add('buddy')+ f.state.agents.find(a => a.id === buddy)!.buddyOf = { personId: 'owner', generation: 'g' }+ const proposal: NonNullable<CommandContext['proposal']> = { id: 'm-proposal', conversationId: 'lead',+ author: { kind: 'agent', id: buddy, name: 'buddy', membershipGeneration: 'g' }, source: { kind: 'buddy-proposal', personId: 'owner', ownerMessageId: 'm-ask' } }+ return { buddy, proposal }+ }+ const createFrom = (f: ReturnType<typeof fixture>, proposal: CommandContext['proposal']) =>+ f.run(commandSchema.parse({ type: 'conversation.create', title: 'Dark mode', brief: 'Add it.', checks, proposalMessageId: 'm-proposal' }), owner,+ { proposal }).result.conversationId as string++ it('records the Buddy whose proposal the group comes from', () => {+ const f = fixture()+ f.at(5_000)+ const { buddy, proposal } = proposed(f)+ const id = createFrom(f, proposal)+ expect(f.group(id).ledger).toEqual({ askedAt: 5_000, proposal: { buddyId: buddy, messageId: 'm-proposal' } })+ })++ it('refuses a link to a message that is not a Buddy\'s proposal in this project\'s chat', () => {+ const f = fixture()+ const { proposal } = proposed(f)+ const lead = f.add('not-buddy')+ for (const wrong of [undefined, { ...proposal, source: null }, { ...proposal, conversationId: 'elsewhere' },+ { ...proposal, author: { ...proposal.author, id: lead } }, { ...proposal, author: { ...proposal.author, kind: 'person' as const, id: 'owner' } }]) {+ expect(() => createFrom(f, wrong), JSON.stringify(wrong)).toThrow(/proposal/i)+ }+ })})diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.tsindex f4157ba5a..563f9442b 100644--- a/backend/src/superTabs/leaderboard/record.ts+++ b/backend/src/superTabs/leaderboard/record.ts@@ -2,9 +2,9 @@* What the leaderboard counts, recorded as it happens on the group it happened in (docs/swarms.md, Leaderboard): when a* request was asked and first shipped, which item waits on a person, and who answered it. Only facts and times, never text.*/-import { isLeads, type Actor, type Agent, type Assignment, type Author, type Check, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'+import { isLeads, type Actor, type Agent, type AgentConfiguration, type Assignment, type Author, type Check, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'import { groupProject, ledProject } from '../projects.js'-import { WEEK_MS } from './week.js'+import { WEEK_MS, weekStart } from './week.js'import type { UnblockKind } from './contract.js'/** How a person unblocked work (Dee, 2026-10-28): answered a decision, approved the Lead's plan, answered work waiting on them,@@ -15,8 +15,15 @@ export interface Unblock { personId: string; at: number; waitedMs: number; kind?* cheaper models without lower quality). `grid`: a model served on the Swarm's grid, named by its start, since the engine* reports none of its own. `firstVerdicts`: each independent check's first verdict during this attempt, by check id.* `firstReview`: false once any of them failed, true once every independent check passed its first, absent until then. */-export interface Run { assignmentId: string; engine: string; model: string | null; grid?: true; at: number+export interface Run extends RanOn { assignmentId: string; at: numberfirstVerdicts?: Record<string, boolean>; firstReview?: boolean }+/** What an agent ran on: its engine, the model (a grid model's own name, `grid` set), and its effort when it names one;+ * absent from attempts recorded before efforts were (Lead, 2026-10-29: never guessed afterwards). */+export interface RanOn { engine: string; model: string | null; effort?: string; grid?: true }+/** How many review verdicts agents running on one model gave on the group's work in one week (Monday 00:00 UTC): a reviewer+ * model's points (Lead, 2026-10-29). Counted, not listed, so no cap ever drops an earned point (review of #2097). A+ * person's verdict is no model's. */+export interface ReviewCount extends RanOn { week: number; count: number }/** A group's leaderboard bookkeeping; readers never get it whole (read/views.ts groupView). */export interface GroupLedger {askedAt?: number@@ -33,6 +40,17 @@ export interface GroupLedger {unblocks?: Unblock[]/** The last MAX_RUNS attempts, oldest first. */runs?: Run[]+ /** When its first attempt was assigned: kept apart, as that attempt rolls off [runs] after MAX_RUNS (review of #2097). */+ firstAssignedAt?: number+ /** The attempt it shipped on, and what that ran on, kept from the moment it shipped: a later attempt or older attempts+ * rolling off never move its model's credit (review of #2097). */+ shippedBy?: RanOn & { assignmentId: string; at: number }+ /** Who led the group when it shipped, null for nobody: the PM's credit, kept whoever leads it later (review of #2097). */+ shippedLeadId?: string | null+ /** Review verdicts by week and model, for the last LEDGER_WEEKS weeks, oldest first. */+ reviews?: ReviewCount[]+ /** The Buddy's proposal the group was opened from: the Buddy earns when it ships (Lead, 2026-10-29). */+ proposal?: { buddyId: string; messageId: string }}/** The leaderboard reads this week and last; a little more keeps a streak and week boundaries safe. */@@ -58,7 +76,28 @@ export function recordStatus(group: Conversation, assignment: Assignment, previoif (assignment.status === 'needs_human' && messageId && (previous !== 'needs_human' || !open)) {ledger.waiting = { assignmentId: assignment.id, since: now, messageId, ...decisionId ? { decisionId } : {} }} else if (assignment.status !== 'needs_human') delete ledger.waiting- if (assignment.status === 'done') ledger.shippedAt ??= now+ if (assignment.status === 'done' && ledger.shippedAt == null) {+ ledger.shippedAt = now+ shipOn(group, ledger.runs?.find(r => r.assignmentId === assignment.id))+ }+}++/** Keeps who led a request when it first shipped, and the attempt it shipped on: the given one, else the last one+ * assigned by the time it shipped. Once kept, never rewritten. */+function shipOn(group: Conversation, run?: Run): void {+ const ledger = group.ledger!+ if (ledger.shippedLeadId !== undefined) return+ ledger.shippedLeadId = group.leadId ?? null+ shipAttempt(ledger, run)+}++/** The attempt a request shipped on: the given one, else the latest started by the time it shipped, else (merged before any+ * attempt started) the earliest. */+function shipAttempt(ledger: GroupLedger, run?: Run): void {+ const shipping = run ?? ledger.runs?.filter(r => r.at <= ledger.shippedAt!).at(-1) ?? ledger.runs?.[0]+ if (!shipping) return+ const { firstVerdicts: _verdicts, firstReview: _review, ...shippedBy } = shipping+ ledger.shippedBy = shippedBy}/** One GitHub pull request link, as a merge record names it (model.ts appendPullRequestUrls finds the same in text). */@@ -68,8 +107,13 @@ export const PULL_REQUEST_URL = /^https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z* when Done came first, and whatever its work does next, so work lost or cancelled after the merge still counts. */export function recordMerged(group: Conversation, mergedAt: number): void {const ledger = group.ledger ??= {}+ const before = ledger.shippedAtledger.mergedAt = Math.min(ledger.mergedAt ?? mergedAt, mergedAt)ledger.shippedAt = ledger.mergedAt+ // Who led it and which attempt shipped are kept from the first time it shipped. A merge that moves the ship earlier+ // takes the attempt running then; the lead stays, as no history of leads is kept (Lead, 2026-10-29).+ if (ledger.shippedLeadId !== undefined && before != null && ledger.shippedAt < before) shipAttempt(ledger)+ else shipOn(group)}/** The person a waiting item waits on: its requester while still a member, otherwise the project's owner. */@@ -148,17 +192,48 @@ export function waitsNow(group: Conversation): boolean {return group.assignment?.status === 'needs_human' && !(waiting?.assignmentId === group.assignment.id && waiting.answeredAt != null)}-/** An assignment records the model its agent runs: the grid model its start named, else what its engine reports. An agent- * started before it kept its grid model has it only on its start, which is here while that start is not finished. */+/** An assignment records what its agent runs on (ranOn), for the board's models. */export function recordRun(state: SuperTabState, group: Conversation, assignment: Assignment, worker: Agent, now: number): void {- const gridModel = worker.gridModel- ?? state.starts?.find(s => s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)?.request.gridModel- const run: Run = { assignmentId: assignment.id, engine: assignment.configuration.engine,- model: gridModel ?? assignment.configuration.model, ...(gridModel ? { grid: true as const } : {}), at: now }+ const run: Run = { assignmentId: assignment.id, ...ranOn(state, worker, assignment.configuration), at: now }const ledger = group.ledger ??= {}+ // A request recorded before this time was kept still has its first attempt in [runs] until 20 more roll it off; only a+ // request with no attempt yet starts now (review of #2097).+ ledger.firstAssignedAt ??= ledger.runs?.[0]?.at ?? nowledger.runs = [...ledger.runs ?? [], run].slice(-MAX_RUNS)}+/** An agent's verdict on an independent check is one finished review by the model it runs on. */+export function recordVerdict(state: SuperTabState, group: Conversation, check: Check, reviewer: Agent, now: number): void {+ if (!check.independent) return+ const ledger = group.ledger ??= {}+ const on = ranOn(state, reviewer, reviewer.configuration), week = weekStart(now)+ // Only the weeks the board reads: one row per week and model, however many verdicts.+ const kept = (ledger.reviews ?? []).filter(r => week - r.week < LEDGER_WEEKS * WEEK_MS)+ const same = kept.find(r => r.week === week && r.engine === on.engine && r.model === on.model && r.effort === on.effort && r.grid === on.grid)+ if (same) same.count+++ else kept.push({ week, ...on, count: 1 })+ ledger.reviews = kept+}++/** A group opened from a Buddy's proposal remembers it, for the Buddy's points when it ships. */+export function recordProposal(group: Conversation, proposal: { buddyId: string; messageId: string }): void {+ (group.ledger ??= {}).proposal = proposal+}++/** What [worker] runs on: the grid model its start named, else what its configuration reports. An agent started before it+ * kept its grid model has it only on its start, which is here while that start is not finished. */+function ranOn(state: SuperTabState, worker: Agent, configuration: AgentConfiguration): RanOn {+ const gridModel = worker.gridModel+ ?? state.starts?.find(s => s.harnessId === worker.harnessId && s.request.machineId === worker.machineId)?.request.gridModel+ const effort = namedEffort(configuration.effort)+ return { engine: configuration.engine, model: gridModel ?? configuration.model, ...(effort ? { effort } : {}), ...(gridModel ? { grid: true as const } : {}) }+}++/** An effort that says which one runs: 'auto' is what Claude Code reports for one it was launched with, and 'default' what a+ * start asks when it leaves the engine its own (desktop agent_line.dart reads them the same way). */+const namedEffort = (effort: string | null): string | undefined =>+ effort && effort !== 'auto' && effort !== 'default' ? effort : undefined+/** Each independent check's first verdict during an attempt is its first review; later verdicts are repairs and never* rewrite it. The attempt passed its first review only when every independent check passed the first time (review of* #1808: one check passing first used to count as a pass while another failed). */diff --git a/backend/src/superTabs/leaderboard/stats.test.ts b/backend/src/superTabs/leaderboard/stats.test.tsindex 2270d1b0f..054ed0a68 100644--- a/backend/src/superTabs/leaderboard/stats.test.ts+++ b/backend/src/superTabs/leaderboard/stats.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest'import type { ContributedMachine } from '../machines.js'-import { createSuperTab, type Assignment, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'-import type { GroupLedger } from './record.js'+import { createSuperTab, type Agent, type Assignment, type Conversation, type SuperTabState, type WorkStatus } from '../model.js'+import type { GroupLedger, Run } from './record.js'import { leaderboard } from './stats.js'import { DAY_MS, WEEK_MS } from './week.js'@@ -277,3 +277,141 @@ describe('Models: the share of work on the Swarm\'s grid, and how often it passe})})})++describe('Models: temporary workers by engine, model and effort, never by agent (Dee, 2026-10-29)', () => {+ /** An attempt on [model] at [at]; `firstReview` when its review is on record. */+ const run = (assignmentId: string, at: number, model = 'opus', effort: string | null = 'high', extra: Partial<Run> = {}): Run =>+ ({ assignmentId, engine: model.startsWith('gpt') ? 'codex' : 'claude', model, ...effort ? { effort } : {}, at, ...extra })+ /** A request shipped at [shippedAt] after [runs]. */+ const landed = (shippedAt: number, runs: Run[], extra: Partial<GroupLedger> = {}) =>+ shipped('dee', runs[0]?.at ?? shippedAt, shippedAt, { ledger: { askedAt: runs[0]?.at ?? shippedAt, shippedAt, runs, ...extra } })+ const model = (view: ReturnType<typeof board>, name: string, effort: string | null = 'high') =>+ view.byModel.find(m => m.model === name && m.effort === effort)!++ it('credits a shipped request to the model of the attempt that shipped it, 3 points, never to earlier attempts', () => {+ const view = board(swarm(), [landed(WEEK + 5 * HOUR, [run('a1', WEEK, 'gpt-5.5', 'medium'), run('a2', WEEK + 2 * HOUR)])])+ expect(model(view, 'opus')).toMatchObject({ engine: 'claude', points: 3, shipped: { count: 1 } })+ expect(model(view, 'gpt-5.5', 'medium')).toMatchObject({ points: 0, shipped: { count: 0 } })+ })++ it('times each shipped request from its shipping attempt and from its first attempt, as medians', () => {+ const view = board(swarm(), [+ landed(WEEK + 5 * HOUR, [run('a1', WEEK), run('a2', WEEK + 4 * HOUR)]),+ landed(WEEK + 3 * HOUR, [run('b1', WEEK + HOUR)]),+ landed(WEEK + 10 * HOUR, [run('c1', WEEK + 2 * HOUR)]),+ ])+ // Attempts: 1, 2 and 8 hours; requests: 5, 2 and 8 hours.+ expect(model(view, 'opus').shipped).toEqual({ count: 3, medianAttemptMs: 2 * HOUR, medianRequestMs: 5 * HOUR })+ })++ it('counts the week\'s attempts with a first review on record, and how many passed it', () => {+ const view = board(swarm(), [group({ status: 'working', ledger: { runs: [+ run('a1', WEEK, 'opus', 'high', { firstReview: true }), run('a2', WEEK + HOUR, 'opus', 'high', { firstReview: false }),+ run('a3', WEEK + 2 * HOUR, 'opus', 'high', { firstReview: true }), run('a4', WEEK + 3 * HOUR),+ run('a5', LAST, 'opus', 'high', { firstReview: true }),+ ] } })])+ expect(model(view, 'opus').firstReview).toEqual({ reviewed: 3, passed: 2 })+ })++ it('gives a reviewer model 1 point per finished review verdict of the week', () => {+ const counted = (week: number, count: number) => ({ week, engine: 'codex', model: 'gpt-5.5', effort: 'medium', count })+ const view = board(swarm(), [group({ status: 'review', ledger: { reviews: [counted(LAST, 1), counted(WEEK, 2)] } }),+ group({ status: 'review', ledger: { reviews: [counted(WEEK, 41)] } })])+ expect(model(view, 'gpt-5.5', 'medium')).toMatchObject({ points: 43, reviews: 43, shipped: { count: 0 } })+ })++ it('credits the model recorded when the request shipped, though its attempts have aged out since (review of #2097)', () => {+ const shippedBy = { assignmentId: 'a1', at: WEEK, engine: 'codex', model: 'gpt-5.5', effort: 'medium' }+ const view = board(swarm(), [landed(WEEK + 2 * HOUR, [], { shippedBy }),+ landed(WEEK + 2 * HOUR, [run('b1', WEEK + 3 * HOUR)], { shippedBy })])+ expect(model(view, 'gpt-5.5', 'medium').shipped).toMatchObject({ count: 2, medianAttemptMs: 2 * HOUR })+ expect(model(view, 'opus').shipped.count).toBe(0)+ })++ it('never times a ship as negative, when it merged before its attempt started (review of #2097)', () => {+ const shippedBy = { assignmentId: 'a1', at: WEEK + 2 * HOUR, engine: 'claude', model: 'opus', effort: 'high' }+ const view = board(swarm(), [landed(WEEK + HOUR, [run('a1', WEEK + 2 * HOUR)], { shippedBy, firstAssignedAt: WEEK + 2 * HOUR })])+ expect(model(view, 'opus').shipped).toMatchObject({ count: 1, medianAttemptMs: 0, medianRequestMs: 0 })+ })++ it('times the whole request from its first assignment, kept after its first attempt rolled off (review of #2097)', () => {+ const view = board(swarm(), [landed(WEEK + 5 * HOUR, [run('a21', WEEK + 4 * HOUR)], { firstAssignedAt: WEEK })])+ expect(model(view, 'opus').shipped).toMatchObject({ medianAttemptMs: HOUR, medianRequestMs: 5 * HOUR })+ })++ it('keeps each effort apart, and attempts recorded before effort was as their own row', () => {+ const view = board(swarm(), [landed(WEEK + HOUR, [run('a1', WEEK, 'opus', 'high')]), landed(WEEK + HOUR, [run('b1', WEEK, 'opus', 'xhigh')]),+ landed(WEEK + HOUR, [run('c1', WEEK, 'opus', null)])])+ expect(view.byModel.map(m => [m.model, m.effort, m.shipped.count])).toEqual([['opus', null, 1], ['opus', 'high', 1], ['opus', 'xhigh', 1]])+ })++ it('ranks models by points, ties sharing a place, and says which ran on the grid', () => {+ const view = board(swarm(), [landed(WEEK + HOUR, [run('a1', WEEK)]), landed(WEEK + HOUR, [run('a2', WEEK)]),+ landed(WEEK + HOUR, [run('b1', WEEK, 'moonshotai/kimi-k3', null, { grid: true })]),+ landed(WEEK + HOUR, [run('c1', WEEK, 'gpt-5.5', null)])])+ expect(view.byModel.map(m => [m.model, m.points, m.rank, m.grid])).toEqual([+ ['opus', 6, 1, false], ['gpt-5.5', 3, 2, false], ['moonshotai/kimi-k3', 3, 2, true]])+ })++ it('counts only requests shipped in the week, and nothing from a private conversation', () => {+ const view = board(swarm(), [landed(LAST + HOUR, [run('a1', LAST)]),+ landed(WEEK + HOUR, [run('b1', WEEK)]),+ { ...landed(WEEK + HOUR, [run('c1', WEEK)]), audience: { people: [{ id: 'dee', generation: 'g' }] } }])+ expect(model(view, 'opus').shipped.count).toBe(1)+ })+})++describe('Agents: the permanent agents, the PM and Buddies, by name like people (Dee, 2026-10-29)', () => {+ /** The project's PM, a Buddy of Dee's, and a builder, in [state]. */+ function agents(state: SuperTabState) {+ const agent = (id: string, extra: Partial<Agent> = {}): Agent => ({ id, projectId: 'lead', machineId: `mac-${id}`, harnessId: `h-${id}`,+ machineOwnerId: 'ken', contributorId: 'ken', membershipGeneration: 'g', name: id, displayName: id[0]!.toUpperCase() + id.slice(1),+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }, ...extra })+ state.agents.push(agent('river'), agent('sparky', { buddyOf: { personId: 'dee', generation: 'g' } }), agent('builder'))+ state.conversations.find(c => c.id === 'lead')!.leadId = 'river'+ return state+ }+ const of = (view: ReturnType<typeof board>, id: string) => view.agents.find(a => a.agentId === id)!++ it('lists the PM and the Buddies, never a builder or reviewer', () => {+ const view = board(agents(swarm()), [])+ expect(view.agents.map(a => [a.agentId, a.displayName, a.kind, a.personId, a.machineId])).toEqual([+ ['river', 'River', 'pm', null, 'mac-river'], ['sparky', 'Sparky', 'buddy', 'dee', 'mac-sparky']])+ })++ it('gives the PM 3 points per request of a group it led that shipped this week', () => {+ const view = board(agents(swarm()), [shipped('dee', WEEK, WEEK + HOUR, { leadId: 'river' }), shipped('ken', WEEK, WEEK + 2 * HOUR, { leadId: 'river' }),+ shipped('dee', LAST, LAST + HOUR, { leadId: 'river' }), shipped('dee', WEEK, WEEK + HOUR, { leadId: 'someone-else' })])+ expect(of(view, 'river')).toMatchObject({ points: 6, shipped: 2, rank: 1 })+ })++ it('credits a group opened from a proposal with no person named as its requester (review of #2097)', () => {+ const run = { assignmentId: 'a1', engine: 'claude', model: 'opus', effort: 'high', at: WEEK }+ const fromProposal = group({ leadId: 'river', status: 'done', pullRequestUrls: ['https://github.com/o/r/pull/1'],+ ledger: { askedAt: WEEK, shippedAt: WEEK + HOUR, runs: [run], proposal: { buddyId: 'sparky', messageId: 'm1' } } })+ const view = board(agents(swarm()), [fromProposal])+ expect(of(view, 'sparky')).toMatchObject({ points: 3, shipped: 1 })+ expect(of(view, 'river')).toMatchObject({ points: 3, shipped: 1 })+ expect(view.byModel.find(m => m.model === 'opus')!.shipped.count).toBe(1)+ // A person's points still need them to have asked.+ expect(view.people.every(p => p.shipped.count === 0)).toBe(true)+ })++ it('credits the PM who led the group when it shipped, not whoever leads it now (review of #2097)', () => {+ const ledger = (shippedLeadId: string | null) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, shippedLeadId })+ const view = board(agents(swarm()), [+ shipped('dee', WEEK, WEEK + HOUR, { leadId: 'someone-else', ledger: ledger('river') }),+ shipped('dee', WEEK, WEEK + HOUR, { leadId: null, ledger: ledger('river') }),+ // Led by nobody when it shipped: nobody's credit, though River leads it now.+ shipped('dee', WEEK, WEEK + HOUR, { leadId: 'river', ledger: ledger(null) }),+ ])+ expect(of(view, 'river')).toMatchObject({ points: 6, shipped: 2 })+ })++ it('gives a Buddy 3 points per group opened from its proposal that shipped this week', () => {+ const fromProposal = { askedAt: WEEK, shippedAt: WEEK + HOUR, proposal: { buddyId: 'sparky', messageId: 'm1' } }+ const view = board(agents(swarm()), [shipped('dee', WEEK, WEEK + HOUR, { ledger: fromProposal }), shipped('dee', WEEK, WEEK + HOUR)])+ expect(of(view, 'sparky')).toMatchObject({ points: 3, shipped: 1 })+ expect(of(view, 'river')).toMatchObject({ points: 0, shipped: 0, rank: 2 })+ })+})diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.tsindex 01261ab8b..39264fcb8 100644--- a/backend/src/superTabs/leaderboard/stats.ts+++ b/backend/src/superTabs/leaderboard/stats.ts@@ -6,12 +6,15 @@*/import type { ContributedMachine } from '../machines.js'import { isLeads, type Conversation, type SuperTabState } from '../model.js'-import { canReadProject, projectOf } from '../projects.js'-import { waitedOn, waitsNow, type Unblock } from './record.js'+import { isBuddy } from '../buddies.js'+import { agentProjectId, canReadProject, projectOf } from '../projects.js'+import { waitedOn, waitsNow, type RanOn, type Unblock } from './record.js'import { DAY_MS, WEEK_MS } from './week.js'-import type { Leaderboard, Medal, ModelShare, PersonDetails, PersonScore, WeekGoal } from './contract.js'+import type { AgentScore, Leaderboard, Medal, ModelScore, ModelShare, PersonDetails, PersonScore, WeekGoal } from './contract.js'export const SHIPPED_POINTS = 3+/** A reviewer model's point for each review verdict it gave (Lead, 2026-10-29). */+export const REVIEW_POINTS = 1export const UNBLOCK_POINTS = 1const HOUR_MS = 3_600_000/** One more point per this many hours an item waited, up to UNBLOCK_MAX_WAIT_POINTS more: an answer is worth a ship at most@@ -43,7 +46,10 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectIconst visible = groups.filter(g => !isLeads(g) && !g.audience && (g.projectId ?? 'lead') === projectId)const shared = visible.filter(g => g.id !== project.leadConversationId)const requests = shared.filter(g => !g.reviewOf)- const landed = requests.filter(g => g.requesterId && g.ledger?.shippedAt != null && (g.pullRequestUrls?.length ?? 0) > 0)+ // Shipped with a PR: what agents and models are credited for. A person's points also need them to have asked (review+ // of #2097: a group opened from a Buddy's proposal may name no requester).+ const shippedRequests = requests.filter(g => g.ledger?.shippedAt != null && (g.pullRequestUrls?.length ?? 0) > 0)+ const landed = shippedRequests.filter(g => g.requesterId)const players = state.people.filter(p => canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project))const inWeek = (at: number, start = week) => at >= start && at < start + WEEK_MS// Each person's records, gathered once: the board scores every player three times (Diego's issue file, 2026-10-27).@@ -92,9 +98,70 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectIpeople,waiting: waitingNow(state, shared),models: { thisWeek: modelShare(requests, week), lastWeek: modelShare(requests, week - WEEK_MS) },+ agents: agentScores(state, projectId, shippedRequests.filter(g => inWeek(g.ledger!.shippedAt!))),+ byModel: modelScores(requests, shippedRequests.filter(g => inWeek(g.ledger!.shippedAt!)), inWeek),}}+/** The project's PM and Buddies with the requests each shipped this week: the PM by the groups it led, a Buddy by the groups+ * opened from its proposals. Builders and Reviewers are counted by model instead (modelScores). */+function agentScores(state: SuperTabState, projectId: string, shippedThisWeek: Conversation[]): AgentScore[] {+ const pmId = state.conversations.find(c => c.id === projectOf(state, projectId).leadConversationId)?.leadId+ const scored = state.agents+ .filter(a => a.id === pmId || (isBuddy(a) && agentProjectId(state, a) === projectId))+ .map(a => {+ const buddy = isBuddy(a)+ // The lead recorded when it shipped; a request shipped before that was recorded, its lead now.+ const ledBy = (g: Conversation) => g.ledger?.shippedLeadId !== undefined ? g.ledger.shippedLeadId : g.leadId+ const shipped = shippedThisWeek.filter(g => buddy ? g.ledger?.proposal?.buddyId === a.id : ledBy(g) === a.id).length+ return { agentId: a.id, displayName: a.displayName ?? a.name, kind: buddy ? 'buddy' as const : 'pm' as const,+ personId: a.buddyOf?.personId ?? null, machineId: a.machineId, points: shipped * SHIPPED_POINTS, shipped }+ })+ .sort((a, b) => b.points - a.points || (a.kind === b.kind ? a.displayName.localeCompare(b.displayName) : a.kind === 'pm' ? -1 : 1))+ return scored.map(entry => ({ ...entry, rank: 1 + scored.filter(other => other.points > entry.points).length }))+}++/** Every model that worked this week: the requests its attempts shipped, the first reviews of its attempts, and the review+ * verdicts it gave. A request ships on its last attempt before it shipped. */+function modelScores(requests: Conversation[], shippedThisWeek: Conversation[], inWeek: (at: number) => boolean): ModelScore[] {+ const rows = new Map<string, ModelScore & { attemptMs: number[]; requestMs: number[] }>()+ const row = (on: RanOn) => {+ const key = JSON.stringify([on.engine, on.model, on.effort ?? null])+ let entry = rows.get(key)+ if (!entry) rows.set(key, entry = { engine: on.engine, model: on.model, effort: on.effort ?? null, grid: !!on.grid, points: 0, rank: 0,+ shipped: { count: 0, medianAttemptMs: null, medianRequestMs: null }, firstReview: { reviewed: 0, passed: 0 }, reviews: 0,+ attemptMs: [], requestMs: [] })+ return entry+ }+ for (const group of shippedThisWeek) {+ // The attempt recorded when it shipped; a request shipped before that was recorded, its last attempt by then.+ const ledger = group.ledger!, shippedAt = ledger.shippedAt!, runs = (ledger.runs ?? []).filter(r => r.at <= shippedAt)+ const last: RanOn & { at: number } | undefined = ledger.shippedBy ?? runs.at(-1)+ if (!last) continue+ const entry = row(last)+ entry.shipped.count+++ // Merged before its attempt started: shipped at once, never in negative time (Lead, 2026-10-29).+ entry.attemptMs.push(Math.max(0, shippedAt - last.at))+ const first = ledger.firstAssignedAt ?? runs[0]?.at+ if (first != null) entry.requestMs.push(Math.max(0, shippedAt - first))+ }+ for (const group of requests) {+ for (const run of group.ledger?.runs ?? []) {+ if (!inWeek(run.at)) continue+ const entry = row(run)+ if (run.firstReview === undefined) continue+ entry.firstReview.reviewed+++ if (run.firstReview) entry.firstReview.passed+++ }+ for (const counted of group.ledger?.reviews ?? []) if (inWeek(counted.week)) row(counted).reviews += counted.count+ }+ const scored = [...rows.values()].map(({ attemptMs, requestMs, ...entry }) => ({ ...entry,+ points: entry.shipped.count * SHIPPED_POINTS + entry.reviews * REVIEW_POINTS,+ shipped: { ...entry.shipped, medianAttemptMs: median(attemptMs), medianRequestMs: median(requestMs) } }))+ .sort((a, b) => b.points - a.points || (a.model ?? '').localeCompare(b.model ?? '') || (a.effort ?? '').localeCompare(b.effort ?? ''))+ return scored.map(entry => ({ ...entry, rank: 1 + scored.filter(other => other.points > entry.points).length }))+}+/** One point per answer, and more the longer its item waited, capped. */const unblockPoints = (unblock: Unblock): number =>UNBLOCK_POINTS + Math.min(UNBLOCK_MAX_WAIT_POINTS, Math.floor(unblock.waitedMs / (UNBLOCK_HOURS_PER_POINT * HOUR_MS)))diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 916b18309..85c29a10b 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -60,8 +60,11 @@ type ReactCommand = Extract<Command, { type: 'message.react' }>const reactionId = (tabId: string, actor: Actor, command: ReactCommand) => stableId(tabId, command.messageId, actorKey(actor), command.emoji)const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValuetype SendCommand = Extract<Command, { type: 'message.send' }>+type ProposeCommand = Extract<Command, { type: 'buddy.propose' }>// Prisma on MongoDB: `usedBy: null` alone misses rows that never had the field.const unused = { OR: [{ usedBy: null }, { usedBy: { isSet: false } }] }+const unproposed = { OR: [{ proposedBy: null }, { proposedBy: { isSet: false } }] }+const PROPOSED = 'This file already went with a proposal. Ask your owner to send it in your chat again.'const hash = (value: unknown): string => createHash('sha256').update(JSON.stringify(value)).digest('hex')/** The fields of a Swarm's row the store reads. A migrated row still keeps its whole old state (`legacyState`, about 1 MB* for a busy Swarm) until the maintenance script removes it, and every command and read loads this row. */@@ -1017,6 +1020,13 @@ export class SuperTabStore {const asked = await tx.superTabMessage.findFirst({ where: { id: command.askedIn.messageId, tabId, conversationId: command.askedIn.conversationId } })if (asked) context.askedIn = { author: asked.author as unknown as Author, source: !!asked.source, createdAt: asked.createdAt.getTime() }}+ if (command.type === 'conversation.create' && command.proposalMessageId) {+ // By id within this tab: the proposal a new group comes from (leaderboard/record.ts recordProposal).+ const proposal = await tx.superTabMessage.findFirst({ where: { id: command.proposalMessageId, tabId },+ select: { id: true, conversationId: true, author: true, source: true } })+ if (proposal) context.proposal = { id: proposal.id, conversationId: proposal.conversationId, author: proposal.author as unknown as Author,+ source: proposal.source as Record<string, unknown> | null }+ }if (command.type === 'buddy.propose') {const asked = await tx.superTabMessage.findFirst({ where: { id: command.ownerMessageId, tabId, conversationId: command.conversationId } })// The newest message its owner wrote there: the chat's newest rows, the Buddy's and the owner's in turn.@@ -1046,7 +1056,14 @@ export class SuperTabStore {context.repeatedDecision = await repeatOf(tx, tabId, ask) ?? nullcontext.openDecisions = context.repeatedDecision ? null : await fullFor(tx, tabId, ask)}- if (command.type === 'message.send' && command.attachmentIds?.length) context.attachments = await this.sendable(tx, tabId, actor, command)+ // The files this command sends, and those it takes from the uploads waiting for a message: a chat file it sent before+ // stays with that message, and a proposal may carry one its Buddy's owner sent in their chat.+ let claimed: string[] = [], proposed: string[] = []+ if (command.type === 'message.send' && command.attachmentIds?.length) {+ context.attachments = await this.sendable(tx, tabId, actor, command)+ claimed = context.attachments.map(a => a.id)+ }+ if (command.type === 'buddy.propose' && command.attachmentIds?.length) ({ attachments: context.attachments, claimed, proposed } = await this.proposable(tx, original, actor, command))if (command.type === 'message.react') context.reaction = await this.reactionTarget(tx, tabId, actor, command)if ((command.type === 'member.avatar' || command.type === 'agent.avatar') && command.avatar?.kind === 'upload') {context.avatarUpload = await this.avatarUpload(tx, tabId, actor, command.avatar.id)@@ -1271,11 +1288,17 @@ export class SuperTabStore {if (command.type === 'decision.ask') effects.result.decisionIds = ids}if (effects.decisionAnswer) await recordAnswer(tx, tabId, effects.decisionAnswer, context.now)- if (context.attachments?.length) {+ if (claimed.length) {// Conflicts with a concurrent send of the same file: only one message can take it.- const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: { in: context.attachments.map(a => a.id) }, ...unused },+ const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: { in: claimed }, ...unused },data: { usedBy: effects.result.messageId as string } })- if (taken.count !== context.attachments.length) fail('ATTACHMENT_USED', 'This file was already sent. Attach it again to send it in another message.')+ if (taken.count !== claimed.length) fail('ATTACHMENT_USED', 'This file was already sent. Attach it again to send it in another message.')+ }+ if (proposed.length) {+ // Conflicts with a concurrent proposal carrying the same file of its owner's: only one can take it.+ const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: { in: proposed }, ...unproposed },+ data: { proposedBy: effects.result.messageId as string } })+ if (taken.count !== proposed.length) fail('ATTACHMENT_USED', PROPOSED)}// On 2026-10-20 a Lead answered a message it had already read, then answered it again when the held// delivery was finally typed. An agent's reply settles that agent's own deliveries of the message.@@ -1478,6 +1501,25 @@ export class SuperTabStore {})}+ /**+ * The files a Buddy's proposal names (buddies.ts), and which of them it takes. Only what its owner handed it: its own upload+ * to its chat, still unsent, which the proposal then takes like a chat message; or a file its owner sent in that chat,+ * which stays with their message too and goes with one proposal at most. Nothing else is found, so the command refuses+ * it, its own order of refusals first. The server cannot tell where an upload's bytes came from on the Buddy's machine:+ * that is its CLI's folder check and its guard (lib/buddyGuard.ts), and here only what it uploaded to its own chat.+ */+ private async proposable(tx: Transaction, state: SuperTabState, actor: Actor, command: ProposeCommand): Promise<{ attachments: Attachment[]; claimed: string[]; proposed: string[] }> {+ const attachments = this.attachments ?? fail('ATTACHMENTS_UNAVAILABLE', 'File attachments are not available on this server.', 503)+ const ownerId = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId)?.buddyOf?.personId : undefined+ if (!ownerId) return { attachments: [], claimed: [], proposed: [] }+ const ids = [...new Set(command.attachmentIds)]+ const rows = await tx.superTabAttachment.findMany({ where: { tabId: state.id, id: { in: ids }, conversationId: command.conversationId } })+ const own = rows.filter(r => !r.purpose && r.actorKey === actorKey(actor) && !r.usedBy)+ const handed = rows.filter(r => !r.purpose && r.actorKey === `person:${ownerId}` && !!r.usedBy)+ return { attachments: [...own, ...handed].map(row => ({ id: row.id, name: row.name, mime: row.mime, size: row.size, url: publicUrl(attachments.publicBase, row.objectKey) })),+ claimed: own.map(r => r.id), proposed: handed.map(r => r.id) }+ }+/** The message a reaction names, when it is in that conversation and this actor may see it, and whether the actor already* reacted to it with that emoji. An agent-only notice is its recipient's alone. */private async reactionTarget(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand): Promise<ReactionTarget | undefined> {diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex 691f6799f..887953076 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -568,6 +568,7 @@ You are one person's Buddy for one project. You help them think a request throug- Only when your owner asks (for example "send to the PM"), never on your own, and once for each time they ask.- Write the goal, the scope and a priority (low, normal or high) from what you agreed. Put in only what your owner wants sent; anything private stays in your chat.- Send it with harness super-tab --tab TAB propose OPERATION_ID '{"conversationId":"CHAT","ownerMessageId":"MESSAGE","goal":"...","scope":"...","priority":"normal"}', where MESSAGE is the id of your owner's message asking you to send it.+- To hand the PM a plan, spec, log or screenshot, attach it, up to 5 files of 10 MB each: add --attach PATH for a file inside your folder, and "attachmentIds":["ID"] in the JSON for a file your owner sent in your chat (its id is on their message). Attach only what your owner wants sent; nothing from anywhere else.- The Swarm posts it in the project chat as one message to the PM, marked as on your owner's behalf. Tell your owner it went; the PM answers in the project chat.## Limitsdiff --git a/cli/src/superTabs/attach.spec.ts b/cli/src/superTabs/attach.spec.tsnew file mode 100644index 000000000..4dfeb1c5c--- /dev/null+++ b/cli/src/superTabs/attach.spec.ts@@ -0,0 +1,73 @@+import { mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'+import { execFile, execFileSync } from 'node:child_process'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { afterEach, expect, it, vi } from 'vitest'++/** A name swapped while it is checked: right after it was opened, before its real path is read. */+const swap = vi.hoisted(() => ({ at: '', to: '', move: '' }))+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ const native = (path: Parameters<typeof fs.realpathSync.native>[0]) => {+ if (swap.at && path === swap.at) {+ if (swap.move) fs.renameSync(swap.at, swap.move)+ else fs.unlinkSync(swap.at)+ fs.symlinkSync(swap.to, swap.at)+ swap.at = ''+ }+ return fs.realpathSync.native(path)+ }+ const realpathSync = Object.assign((...args: Parameters<typeof fs.realpathSync>) => fs.realpathSync(...args), { native })+ return { ...fs, default: { ...fs, realpathSync }, realpathSync }+})+const { readInsideFolder } = await import('./attach.js')++const made: string[] = []+afterEach(() => { for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true }) })+const dir = (prefix: string) => { const path = mkdtempSync(join(tmpdir(), prefix)); made.push(path); return path }++it('reads a file inside the folder whole, by its own name and type', () => {+ const folder = dir('buddy-folder-')+ writeFileSync(join(folder, 'plan.md'), '# Plan\n')+ expect(readInsideFolder([join(folder, 'plan.md')], folder)).toEqual([{ name: 'plan.md', type: 'text/markdown', bytes: Buffer.from('# Plan\n') }])+})++it('refuses a name swapped for a link out of the folder between opening it and checking where it is', () => {+ const folder = dir('buddy-folder-'), outside = dir('buddy-outside-')+ writeFileSync(join(folder, 'plan.md'), '# Plan\n')+ writeFileSync(join(outside, 'secret.txt'), 'outside bytes')+ Object.assign(swap, { at: join(folder, 'plan.md'), to: join(outside, 'secret.txt') })+ expect(() => readInsideFolder([join(folder, 'plan.md')], folder)).toThrow('is outside your folder')+ // The opened file moved out with its one name, and the name now leads to another file inside: the file opened is not+ // the one named.+ unlinkSync(join(folder, 'plan.md'))+ writeFileSync(join(folder, 'plan.md'), '# Plan\n')+ writeFileSync(join(folder, 'other.md'), '# Other\n')+ Object.assign(swap, { at: join(folder, 'plan.md'), to: join(folder, 'other.md'), move: join(outside, 'moved.md') })+ expect(() => readInsideFolder([join(folder, 'plan.md')], folder)).toThrow('is outside your folder')+})++it('refuses a link as the last name, a folder inside, and a file over the limit', () => {+ const folder = dir('buddy-folder-')+ writeFileSync(join(folder, 'plan.md'), '# Plan\n')+ symlinkSync(join(folder, 'plan.md'), join(folder, 'alias.md'))+ expect(() => readInsideFolder([join(folder, 'alias.md')], folder)).toThrow('is outside your folder')+ expect(() => readInsideFolder([folder.concat('/')], folder)).toThrow('is outside your folder')+ writeFileSync(join(folder, 'big.bin'), Buffer.alloc(10 * 1024 * 1024 + 1))+ expect(() => readInsideFolder([join(folder, 'big.bin')], folder)).toThrow('over the 10.0 MB limit')+})++// Run apart: a blocking open stops the whole process, which no test timeout in it can end (re-check of #2103).+it.skipIf(process.platform === 'win32')('refuses a named pipe and the terminal\'s input without waiting on them', async () => {+ const folder = dir('buddy-folder-')+ execFileSync('mkfifo', [join(folder, 'pipe.md')])+ const script = `+ const { readInsideFolder } = await import(${JSON.stringify(new URL('./attach.ts', import.meta.url).pathname)})+ const tried = (path) => { try { readInsideFolder([path], process.argv[1]); return 'read' } catch (error) { return error.message } }+ console.log(JSON.stringify([tried(process.argv[2]), tried('/dev/stdin')]))+ `+ const { stdout } = await promisify(execFile)(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script, folder, join(folder, 'pipe.md')],+ { timeout: 15_000 })+ expect(JSON.parse(stdout.trim())).toEqual([`${join(folder, 'pipe.md')} is not a file.`, expect.stringContaining('/dev/stdin is outside your folder')])+}, 20_000)diff --git a/cli/src/superTabs/attach.ts b/cli/src/superTabs/attach.tsindex cdc1c164f..7bea02270 100644--- a/cli/src/superTabs/attach.ts+++ b/cli/src/superTabs/attach.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto'-import { openAsBlob } from 'node:fs'+import { closeSync, constants, fstatSync, lstatSync, openAsBlob, openSync, readSync, realpathSync } from 'node:fs'import { stat } from 'node:fs/promises'-import { basename, extname } from 'node:path'+import { basename, extname, isAbsolute, relative, sep } from 'node:path'import { localCredentialHeaders } from '../lib/localCredential.js'import { ATTACHMENT_TOTAL_MS } from '../lib/superTabAttachmentProxy.js'import { object } from './wire.js'@@ -30,14 +30,17 @@ const value = (answer: Record<string, unknown>) => {/** One file of `post --attach`, multipart to this computer's daemon, which streams it on to the backend with the account's* token (lib/superTabAttachmentProxy.ts). Its own deadline, not a service answer's half minute: on a slow uplink 10 MB* takes longer, and the daemon ends it once no bytes move. */-async function uploadOne(path: string, target: UploadTarget, agentId: string, fetcher: typeof fetch): Promise<string> {- const info = await stat(path)- if (!info.isFile()) throw new Error(`${path} is not a file.`)- if (info.size > MAX_ATTACHMENT_BYTES) throw new Error(`${basename(path)} is over the ${formatSize(MAX_ATTACHMENT_BYTES)} limit (${info.size} bytes).`)+async function uploadOne(file: string | CheckedFile, target: UploadTarget, agentId: string, fetcher: typeof fetch): Promise<string> {const form = new FormData()form.append('conversationId', target.conversationId)- // Read from disk as it is sent, never whole.- form.append('file', await openAsBlob(path, { type: mimeOf(path) }), basename(path))+ if (typeof file === 'string') {+ const info = await stat(file)+ if (!info.isFile()) throw new Error(`${file} is not a file.`)+ if (info.size > MAX_ATTACHMENT_BYTES) throw new Error(`${basename(file)} is over the ${formatSize(MAX_ATTACHMENT_BYTES)} limit (${info.size} bytes).`)+ // Read from disk as it is sent, never whole.+ form.append('file', await openAsBlob(file, { type: mimeOf(file) }), basename(file))+ } else form.append('file', new Blob([file.bytes], { type: file.type }), file.name)+ const name = typeof file === 'string' ? basename(file) : file.nameconst response = await fetcher(`http://127.0.0.1:${target.port}/api/super-tabs/${target.tabId}/attachments?asAgentId=${agentId}`, {method: 'POST', body: form, signal: AbortSignal.timeout(UPLOAD_MS),// The local API's write gate, and its credential over TCP.@@ -46,18 +49,58 @@ async function uploadOne(path: string, target: UploadTarget, agentId: string, feconst body = object(await response.json().catch(() => ({})))const attachment = object(object(body.data).attachment)if (!response.ok || typeof attachment.id !== 'string') {- throw new Error(String(object(body.error).message ?? body.message ?? `Could not upload ${basename(path)} (HTTP ${response.status}).`))+ throw new Error(String(object(body.error).message ?? body.message ?? `Could not upload ${name} (HTTP ${response.status}).`))}return attachment.id}-export interface UploadTarget { tabId: string; conversationId: string; port: number; dataDir: string }+/** `sentIn`: where the message these files go with is written, when not where they are uploaded (a Buddy's proposal is+ * uploaded to its chat and posted in the project chat). */+export interface UploadTarget { tabId: string; conversationId: string; sentIn?: string; port: number; dataDir: string }++/** Folders in a Buddy's folder that are not the project's files: its repository's records, its remote's credentials among+ * them, and Harness's own. Compared in lower case: on a case-insensitive Mac `.GIT` is the same folder. */+const RECORDS = new Set(['.git', '.harness'])++/** A file read once, after its checks, and sent as those bytes. */+export interface CheckedFile { name: string; type: string; bytes: Buffer }++/**+ * A Buddy's proposal files, each read from the one descriptor its checks were made on (security review of #2103): only a+ * regular file inside its own folder, the one place it may read (lib/buddyGuard.ts), never under its repository's or+ * Harness's records. The last name is opened without following a link or waiting; the file must have that one name (a hard link+ * would give a file outside a second name inside), and the real path's file must be the one opened, so a name swapped+ * for a link after the check is refused or never read. Each is at most a chat file's size, so read whole.+ */+export function readInsideFolder(paths: string[], folder: string): CheckedFile[] {+ const root = realpathSync.native(folder)+ return paths.map(path => {+ const outside = () => new Error(`${path} is outside your folder. Attach only files inside your folder; name a file your owner sent in your chat by its id.`)+ let fd: number+ // Never waiting on the open: a named pipe with no writer held the proposal forever (re-check of #2103). A regular+ // file reads the same without blocking, and anything else is refused below before a byte is read.+ try { fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)) } catch (error) {+ throw (error as NodeJS.ErrnoException).code === 'ELOOP' ? outside() : new Error(`${path} is not a file.`)+ }+ try {+ const opened = fstatSync(fd), real = realpathSync.native(path), inside = relative(root, real), named = lstatSync(real)+ if (!inside || inside.startsWith('..') || isAbsolute(inside) || RECORDS.has(inside.split(sep)[0]!.toLowerCase())) throw outside()+ if (!opened.isFile()) throw new Error(`${path} is not a file.`)+ if (opened.nlink !== 1 || named.ino !== opened.ino || named.dev !== opened.dev) throw outside()+ if (opened.size > MAX_ATTACHMENT_BYTES) throw new Error(`${basename(path)} is over the ${formatSize(MAX_ATTACHMENT_BYTES)} limit (${opened.size} bytes).`)+ const bytes = Buffer.alloc(opened.size)+ let read = 0+ for (let got = -1; read < bytes.length && got !== 0; read += got) got = readSync(fd, bytes, read, bytes.length - read, read)+ return { name: basename(real), type: mimeOf(real), bytes: bytes.subarray(0, read) }+ } finally { closeSync(fd) }+ })+}/** Uploads each file of `post --attach` and answers the ids `message.send` names. Repeating a post whose message already* went out uploads nothing and names that message's files, so the send returns its receipt. */-export async function uploadAttachments(paths: string[], operationId: string, target: UploadTarget, request: Request,+export async function uploadAttachments(paths: Array<string | CheckedFile>, operationId: string, target: UploadTarget, request: Request,fetcher: typeof fetch = fetch): Promise<string[]> {- const earlier = value(await request({ action: 'attachment', step: 'sent', conversationId: target.conversationId, operationId }))+ const earlier = value(await request({ action: 'attachment', step: 'sent', conversationId: target.sentIn ?? target.conversationId, operationId }))if (Array.isArray(earlier.attachmentIds)) return earlier.attachmentIds.map(String)if (typeof earlier.agentId !== 'string') throw new Error('Update Harness on this computer to attach files.')const ids: string[] = []diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.tsindex 95917acef..646b562eb 100644--- a/cli/src/superTabs/command.spec.ts+++ b/cli/src/superTabs/command.spec.ts@@ -147,6 +147,136 @@ it('uploads each --attach file to the daemon\'s local upload route as the agent,expect(calls.map(c => c.step ?? c.action)).toEqual(['sent', 'sent'])} finally { rmSync(dir, { recursive: true, force: true }) }})+it('parses propose with up to 5 --attach files, always as a proposal', () => {+ const json = JSON.stringify({ type: 'message.send', conversationId: 'chat', ownerMessageId: 'ask', goal: 'G', scope: 'S', priority: 'normal' })+ expect(parseSuperTabArgs([...prefix, 'propose', 'op-1', json, '--attach', 'plan.md', '--attach', 'shot.png'], where).payload)+ .toMatchObject({ action: 'command', attach: [resolve('plan.md'), resolve('shot.png')], command: { type: 'buddy.propose', conversationId: 'chat' } })+ expect(parseSuperTabArgs([...prefix, 'propose', 'op-1', json], where).payload).not.toHaveProperty('attach')+ expect(() => parseSuperTabArgs([...prefix, 'propose', 'op-1', json, ...['a', 'b', 'c', 'd', 'e', 'f'].flatMap(f => ['--attach', f])], where))+ .toThrow('Attach at most 5 files to a proposal.')+ for (const tail of [['--attach'], ['--attach', ''], ['--reply-to', 'm1'], ['extra']]) {+ expect(() => parseSuperTabArgs([...prefix, 'propose', 'op-1', json, ...tail], where)).toThrow('harness super-tab')+ }+})+it('attaches to a proposal only files inside the Buddy\'s own folder, uploaded to its chat, beside the files its owner sent', async () => {+ const { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, linkSync, rmSync } = await import('node:fs')+ const { join } = await import('node:path')+ const { tmpdir } = await import('node:os')+ const folder = mkdtempSync(join(tmpdir(), 'buddy-folder-')), outside = mkdtempSync(join(tmpdir(), 'buddy-outside-'))+ try {+ writeFileSync(join(folder, 'plan.md'), '# Plan\n')+ mkdirSync(join(folder, 'docs'))+ writeFileSync(join(folder, 'docs', 'shot.png'), Buffer.from([1, 2, 3]))+ writeFileSync(join(outside, 'secret.txt'), 'not the Buddy\'s')+ symlinkSync(join(outside, 'secret.txt'), join(folder, 'link.txt'))+ for (const dir of ['.git', '.harness']) { mkdirSync(join(folder, dir)); writeFileSync(join(folder, dir, 'config'), 'token') }+ // The same records in other letters: one folder on a case-insensitive Mac, their own on Linux.+ for (const dir of ['.GIT', '.Harness']) {+ try { mkdirSync(join(folder, dir)) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }+ writeFileSync(join(folder, dir, 'config'), 'token')+ }+ // A second name inside the folder for a file outside it.+ linkSync(join(outside, 'secret.txt'), join(folder, 'hard.txt'))+ const calls: Array<Record<string, unknown>> = []+ let frames: unknown[] = [{ id: 'buddy-harness', engine: 'claude', status: 'active', tmuxPane: '%7', project: { cwd: folder } }]+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {+ if (type === 'agents_list') return { agents: frames }+ calls.push(payload)+ if (payload.action === 'status') return { ok: true, value: { state: { projects: [{ id: 'p', leadConversationId: 'lead' }],+ conversations: [{ id: 'lead', projectId: 'p' }, { id: 'chat', projectId: 'p', kind: 'buddy' }] } } }+ if (payload.step === 'sent') return { ok: true, value: { agentId: 'buddy', attachmentIds: null } }+ return { ok: true, value: { revision: 9, result: { messageId: 'm' } } }+ })+ let uploads = 0+ const fetch = vi.fn(async () => new Response(JSON.stringify({ success: true, data: { attachment: { id: `f${++uploads}` } } }), { status: 200 }))+ const deps = { where: () => where, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }), print: vi.fn(), pane: '%7',+ fetch: fetch as unknown as typeof globalThis.fetch }+ const json = JSON.stringify({ conversationId: 'chat', ownerMessageId: 'ask', goal: 'G', scope: 'S', priority: 'normal', attachmentIds: ['owner-log'] })+ const propose = (...files: string[]) => superTabCommand([...prefix, 'propose', 'op', json, ...files.flatMap(f => ['--attach', f])], deps)+ const error = () => JSON.parse(deps.print.mock.calls.at(-1)![0]).error as string++ expect(await propose(join(folder, 'plan.md'), join(folder, 'docs', '..', 'docs', 'shot.png'))).toBe(0)+ // Uploaded into its chat; a retry would look for the proposal in the project chat.+ expect(calls.filter(c => c.step === 'sent')).toEqual([expect.objectContaining({ conversationId: 'lead', operationId: 'op' })])+ expect(fetch.mock.calls.map(c => ((c as unknown as [string, RequestInit])[1].body as FormData).get('conversationId'))).toEqual(['chat', 'chat'])+ expect(calls.at(-1)).toMatchObject({ operationId: 'op', command: { type: 'buddy.propose', attachmentIds: ['owner-log', 'f1', 'f2'] } })+ expect(calls.at(-1)).not.toHaveProperty('attach')++ // Outside its folder, through a link, or in its repository's and Harness's own records: refused before any upload.+ calls.length = 0+ for (const path of [join(outside, 'secret.txt'), join(folder, 'link.txt'), join(folder, 'hard.txt'), join(folder, '.git', 'config'),+ join(folder, '.harness', 'config'), join(folder, '.GIT', 'config'), join(folder, '.Harness', 'config'), folder]) {+ expect(await propose(path), path).toBe(1)+ expect(error()).toContain('Attach only files inside your folder')+ }+ // Its owner's files count too, before anything is uploaded.+ expect(await propose(...Array(5).fill(join(folder, 'plan.md')))).toBe(1)+ expect(error()).toBe('Attach at most 5 files to a proposal.')+ expect(await propose(join(folder, 'missing.md'))).toBe(1)+ expect(error()).toContain('missing.md')+ // Only from its own terminal, where its folder is known: never through another machine's daemon.+ for (const relay of [['--machine', 'other-mac'], ['--port', '14002']]) {+ expect(await superTabCommand(['--tab', 'tab', '--agent', 'agent', ...relay, 'propose', 'op', json, '--attach', join(folder, 'plan.md')], deps)).toBe(1)+ expect(error()).toContain('from your Buddy\'s own terminal')+ }+ frames = []+ expect(await propose(join(folder, 'plan.md'))).toBe(1)+ expect(error()).toContain('from your Buddy\'s own terminal')+ expect(fetch).toHaveBeenCalledTimes(2)+ expect(calls.filter(c => c.action === 'command')).toEqual([])++ // Already sent: nothing is uploaded and the proposal names the files it went with.+ frames = [{ id: 'buddy-harness', engine: 'claude', status: 'active', tmuxPane: '%7', project: { cwd: folder } }]+ request.mockImplementation(async (type: string, payload: Record<string, unknown> = {}) => {+ if (type === 'agents_list') return { agents: frames }+ calls.push(payload)+ if (payload.action === 'status') return { ok: true, value: { state: { projects: [{ id: 'p', leadConversationId: 'lead' }], conversations: [{ id: 'chat', projectId: 'p' }] } } }+ if (payload.step === 'sent') return { ok: true, value: { agentId: 'buddy', attachmentIds: ['owner-log', 'f1', 'f2'] } }+ return { ok: true, value: { revision: 9, result: { messageId: 'm' } } }+ })+ expect(await propose(join(folder, 'plan.md'), join(folder, 'docs', 'shot.png'))).toBe(0)+ expect(calls.at(-1)).toMatchObject({ command: { attachmentIds: ['owner-log', 'f1', 'f2'] } })+ expect(fetch).toHaveBeenCalledTimes(2)+ } finally {+ rmSync(folder, { recursive: true, force: true })+ rmSync(outside, { recursive: true, force: true })+ }+})+it('sends a proposal file\'s bytes as they were when checked, even if the path then turns into a link out of the folder', async () => {+ const { mkdtempSync, writeFileSync, symlinkSync, unlinkSync, rmSync } = await import('node:fs')+ const { join } = await import('node:path')+ const { tmpdir } = await import('node:os')+ const folder = mkdtempSync(join(tmpdir(), 'buddy-folder-')), outside = mkdtempSync(join(tmpdir(), 'buddy-outside-'))+ try {+ writeFileSync(join(folder, 'plan.md'), '# Plan\n')+ writeFileSync(join(outside, 'secret.txt'), 'outside bytes')+ const frames = [{ id: 'buddy-harness', engine: 'claude', status: 'active', tmuxPane: '%7', project: { cwd: folder } }]+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {+ if (type === 'agents_list') return { agents: frames }+ if (payload.action === 'status') return { ok: true, value: { state: { projects: [{ id: 'p', leadConversationId: 'lead' }], conversations: [{ id: 'chat', projectId: 'p' }] } } }+ if (payload.step === 'sent') {+ // After the check, before the upload: the checked name now points outside.+ unlinkSync(join(folder, 'plan.md'))+ symlinkSync(join(outside, 'secret.txt'), join(folder, 'plan.md'))+ return { ok: true, value: { agentId: 'buddy', attachmentIds: null } }+ }+ return { ok: true, value: { revision: 9, result: { messageId: 'm' } } }+ })+ const sent: string[] = []+ const fetch = vi.fn(async (_url: string, init?: RequestInit) => {+ sent.push(await ((init!.body as FormData).get('file') as File).text())+ return new Response(JSON.stringify({ success: true, data: { attachment: { id: 'f1' } } }), { status: 200 })+ })+ const deps = { where: () => where, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }), print: vi.fn(), pane: '%7',+ fetch: fetch as unknown as typeof globalThis.fetch }+ const json = JSON.stringify({ conversationId: 'chat', ownerMessageId: 'ask', goal: 'G', scope: 'S', priority: 'normal' })+ expect(await superTabCommand([...prefix, 'propose', 'op', json, '--attach', join(folder, 'plan.md')], deps)).toBe(0)+ expect(sent).toEqual(['# Plan\n'])+ } finally {+ rmSync(folder, { recursive: true, force: true })+ rmSync(outside, { recursive: true, force: true })+ }+})it('parses screen AGENT [--scrollback N] and type AGENT [TEXT] [--key K]...', () => {expect(parseSuperTabArgs([...prefix, 'screen', 'worker'], where).payload).toMatchObject({ action: 'screen', command: { type: 'agent.screen', agentId: 'worker' } })expect(parseSuperTabArgs([...prefix, 'screen', 'worker', '--scrollback', '120'], where).payload).toMatchObject({ command: { type: 'agent.screen', agentId: 'worker', scrollback: 120 } })diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.tsindex dd25d2cb8..519256559 100644--- a/cli/src/superTabs/command.ts+++ b/cli/src/superTabs/command.ts@@ -6,11 +6,13 @@ import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daimport { callerOf, outsideCaller, type Frame } from '../agentClient/model.js'import { identifier } from './host.js'import { resolve } from 'node:path'-import { uploadAttachments } from './attach.js'+import { readInsideFolder, uploadAttachments, type UploadTarget } from './attach.js'import { keyName } from './terminal.js'import { randomUUID } from 'node:crypto'-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | decisions [--answered] | costs [--days N] | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | command OPERATION_ID JSON | propose OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | decisions [--answered] | costs [--days N] | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'+/** The files one proposal may carry (backend buddies.ts MAX_PROPOSAL_ATTACHMENTS). */+const MAX_PROPOSAL_FILES = 5export function parseSuperTabArgs(argv: readonly string[], where: Where) {const positional: string[] = []let tabId = '', agentId = ''@@ -52,9 +54,17 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {command: { type: 'message.send', conversationId: first, text: second, replyTo, recipientIds: [], ...(mentions.length ? { mentions } : {}) } })} else if (action === 'command' && identifier(first) && second && positional.length === 3) {Object.assign(payload, { operationId: first, command: JSON.parse(second) })- } else if (action === 'propose' && identifier(first) && second && positional.length === 3) {+ } else if (action === 'propose' && identifier(first) && second) {+ const attach: string[] = []+ for (let i = 3; i < positional.length; i += 2) {+ const [flag, value] = [positional[i], positional[i + 1]]+ if (flag === '--attach' && value) attach.push(resolve(value))+ else throw new Error(USAGE)+ }+ if (attach.length > MAX_PROPOSAL_FILES) throw new Error(`Attach at most ${MAX_PROPOSAL_FILES} files to a proposal.`)// A Buddy's proposal for its owner (backend buddies.ts): only ever that command, whatever the JSON says it is.- Object.assign(payload, { action: 'command', operationId: first, command: { ...JSON.parse(second), type: 'buddy.propose' } })+ Object.assign(payload, { action: 'command', operationId: first, ...(attach.length ? { attach } : {}),+ command: { ...JSON.parse(second), type: 'buddy.propose' } })} else if (action === 'start' && identifier(first) && second && positional.length === 3) {Object.assign(payload, { operationId: first, request: JSON.parse(second) })} else if (action === 'resume' && identifier(first) && positional.length === 2) payload.startId = first@@ -104,7 +114,8 @@ export async function superTabCommand(argv: readonly string[], deps: {let operationId: unknownconst print = deps.print ?? console.logtry {- const request = parseSuperTabArgs(argv, (deps.where ?? (() => whereFor(process.env.TMUX_PANE)))())+ const here = (deps.where ?? (() => whereFor(process.env.TMUX_PANE)))()+ const request = parseSuperTabArgs(argv, here)operationId = request.payload.operationIddaemon = await (deps.open ?? openDaemon)(request.where)const owners = request.payload.action === 'backend' || request.payload.action === 'setMachineAgents'@@ -163,8 +174,11 @@ export async function superTabCommand(argv: readonly string[], deps: {// this process holds no account credential.if (Array.isArray(attach)) {const command = object(payload.command)- command.attachmentIds = await uploadAttachments(attach as string[], String(payload.operationId), { tabId: String(payload.tabId),- conversationId: String(command.conversationId), port: request.where.port, dataDir: request.where.dataDir }, scoped, deps.fetch)+ const target = { tabId: String(payload.tabId), conversationId: String(command.conversationId), port: request.where.port, dataDir: request.where.dataDir }+ command.attachmentIds = command.type === 'buddy.propose'+ ? await proposalFiles(attach as string[], String(payload.operationId), command, target, daemon, scoped, { ...deps,+ local: request.where.machineId === here.machineId && request.where.port === here.port })+ : await uploadAttachments(attach as string[], String(payload.operationId), target, scoped, deps.fetch)}result = await daemon.request('super_tabs', payload, 30_000)}@@ -176,6 +190,30 @@ export async function superTabCommand(argv: readonly string[], deps: {} finally { daemon?.close() }}+/** A Buddy's proposal files (backend buddies.ts): those in its own folder, as its harness here records it, uploaded to its+ * chat beside the files its owner sent there, which the proposal names by id. A repeat finds the proposal in the project+ * chat and names the files it went with. */+async function proposalFiles(paths: string[], operationId: string, command: Record<string, unknown>, target: UploadTarget, daemon: Daemon,+ scoped: (payload: Record<string, unknown>) => Promise<Record<string, unknown>>, deps: { pane?: string; fetch?: typeof fetch; local: boolean }): Promise<string[]> {+ // Its folder is on this machine: through another machine's daemon (--machine, --port) its pane would name someone else's.+ if (!deps.local) throw new Error('Attach files to a proposal from your Buddy\'s own terminal.')+ const named = Array.isArray(command.attachmentIds) ? command.attachmentIds.map(String) : []+ // Counted before any upload, so a refused proposal leaves no file behind.+ if (new Set(named).size + paths.length > MAX_PROPOSAL_FILES) throw new Error(`Attach at most ${MAX_PROPOSAL_FILES} files to a proposal.`)+ const listed = await daemon.request('agents_list')+ const frames = Array.isArray(listed.agents) ? listed.agents as Frame[] : []+ const caller = callerOf(frames, deps.pane ?? process.env.TMUX_PANE, String(daemon.machineId))+ const folder = frames.find(f => f.id === caller?.agentId)?.project?.cwd+ if (!folder) throw new Error('Attach files to a proposal from your Buddy\'s own terminal.')+ const files = readInsideFolder(paths, folder)+ const state = object(object((await scoped({ action: 'status' })).value).state)+ const projectId = (Array.isArray(state.conversations) ? state.conversations : []).map(object).find(c => c.id === target.conversationId)?.projectId+ const home = (Array.isArray(state.projects) ? state.projects : []).map(object).find(p => p.id === projectId)?.leadConversationId+ if (typeof home !== 'string') throw new Error('Name your own chat: a proposal comes from there.')+ const uploaded = await uploadAttachments(files, operationId, { ...target, sentIn: home }, scoped, deps.fetch)+ return [...new Set([...named, ...uploaded])]+}+/** How often a terminal result is read: the backend holds each read about 20 s, and the worker's machine has 10 s to pick a* request up and 30 s to answer it, after which the backend answers with the reason. */const TERMINAL_READS = 3diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex dc7962038..176da97ff 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -58,7 +58,7 @@ const HELP = {release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',resume: 'resume START_ID: finish a pending start without creating another agent.',// Buddies (backend superTabs/buddies.ts): a person adds and removes their own; the Buddy proposes only when they ask.- buddies: 'Buddies, once the Swarm owner turns them on (tab.buddies): each person may add their own Buddy per project (buddy.create with projectId, machineId of a Swarm machine, engine claude or codex) and remove it (buddy.remove with projectId). It brainstorms with them in a chat only they read. propose OPERATION_ID JSON: a Buddy only, when its owner asks: {"conversationId":"its chat","ownerMessageId":"their message asking","goal":"...","scope":"...","priority":"low|normal|high"}. The Swarm posts it in the project chat to the PM, marked as on the owner\'s behalf. A Buddy is never assigned work.',+ buddies: 'Buddies, once the Swarm owner turns them on (tab.buddies): each person may add their own Buddy per project (buddy.create with projectId, machineId of a Swarm machine, engine claude or codex) and remove it (buddy.remove with projectId). It brainstorms with them in a chat only they read. propose OPERATION_ID JSON [--attach PATH]...: a Buddy only, when its owner asks: {"conversationId":"its chat","ownerMessageId":"their message asking","goal":"...","scope":"...","priority":"low|normal|high","attachmentIds":["a file its owner sent in its chat"]}. --attach adds a file inside its own folder; up to 5 files in all, 10 MB each. The Swarm posts it in the project chat to the PM, marked as on the owner\'s behalf. A Buddy is never assigned work.',// A person's own command, for the machines they added; an agent's terminal is refused (command.ts), so no agent raises its// own machine's room (Lead, 2026-10-28).setAgents: 'set-agents MACHINE_ID COUNT: for a machine\'s owner, from their own terminal, not an agent\'s: how many Swarm agents may run on that machine at once. Each agent still needs free memory when it starts. A machine may offer one agent for every 2 GB of its memory, and at least 4; a larger number is refused.',diff --git a/desktop/lib/super_tabs/attachment_upload.dart b/desktop/lib/super_tabs/attachment_upload.dartindex 466abcf26..9259d6ae3 100644--- a/desktop/lib/super_tabs/attachment_upload.dart+++ b/desktop/lib/super_tabs/attachment_upload.dart@@ -1,8 +1,10 @@+import 'dart:convert';import 'dart:typed_data';import 'package:dio/dio.dart';import '../api/api_client.dart';+import '../logging/app_log.dart';import 'controller.dart';/// What the backend allows one message to carry.@@ -113,9 +115,15 @@ SuperTabUpload uploadWith(ApiClient Function() api) =>};/// What a refused upload says. The backend answers `{error: {code, message}}`;-/// the local daemon, a bare code string such as `{error: 'FORBIDDEN'}`.+/// the local daemon, a bare code string such as `{error: 'FORBIDDEN'}`. Either+/// may reach here as a String Dio did not decode.SuperTabFailure superTabUploadRefusal(Response<dynamic> response) {- final body = response.data;+ var body = response.data;+ if (body is String) {+ try {+ body = jsonDecode(body);+ } catch (_) {}+ }final error = body is Map ? body['error'] : null;final code = error is Map? error['code'] as String?@@ -123,6 +131,11 @@ SuperTabFailure superTabUploadRefusal(Response<dynamic> response) {? error: null;final message = error is Map ? error['message'] as String? : null;+ // The code and status only, never the message: a refusal can quote what was sent.+ appLog.warn(+ 'super-tabs',+ 'upload refused: ${code ?? 'no code'} (status ${response.statusCode})',+ );return SuperTabFailure(code ?? 'UPLOAD_FAILED',message ??@@ -131,7 +144,8 @@ SuperTabFailure superTabUploadRefusal(Response<dynamic> response) {'ATTACHMENT_TOO_LARGE' => 'That file is over 10 MB.','AVATAR_TOO_LARGE' => 'That picture is over 1 MB.','AVATAR_TYPE' => 'Use a PNG, JPEG or WebP picture.',- _ => 'Could not upload the file. Try again.',+ null => 'Could not upload the file. Try again.',+ _ => 'Could not upload the file ($code). Try again.',},statusCode: response.statusCode ?? 0,);diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dartindex 31311bcee..b45397b61 100644--- a/desktop/lib/super_tabs/buddies.dart+++ b/desktop/lib/super_tabs/buddies.dart@@ -2,13 +2,16 @@ import 'dart:async';import 'package:flutter/material.dart';+import '../models/model_search_catalog.dart' show thisComputerName;import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_dialog.dart';import '../shared/widgets/app_select_field.dart';+import '../state/app_state.dart';import '../widgets/desktop_chrome.dart';import 'controller.dart';import 'dialog_scope.dart';import 'identity.dart';+import 'machines.dart';import 'model.dart';/// The engines a Buddy runs on (spec: Buddies, 10-28).@@ -81,23 +84,27 @@ String buddyMachineName(SuperTabController c, String machineId) {: 'another machine';}-/// Add a Buddy: project, one of the reader's own machines, and engine.+/// Add a Buddy: project, one of the reader's own machines, and engine. With+/// [app], a reader with no machine in the Swarm can add this computer from+/// the dialog.Future<void> showAddBuddy(BuildContext context,SuperTabController c, {String? projectId,+ AppNotifier? app,}) => showAppDialog<void>(context: context,builder: (context) => SuperTabDialogScope(controller: c,- child: _AddBuddyDialog(controller: c, projectId: projectId),+ child: _AddBuddyDialog(controller: c, projectId: projectId, app: app),),);class _AddBuddyDialog extends StatefulWidget {- const _AddBuddyDialog({required this.controller, this.projectId});+ const _AddBuddyDialog({required this.controller, this.projectId, this.app});final SuperTabController controller;final String? projectId;+ final AppNotifier? app;@overrideState<_AddBuddyDialog> createState() => _AddBuddyDialogState();@@ -111,6 +118,9 @@ class _AddBuddyDialogState extends State<_AddBuddyDialog> {String? _project, _machine;String _engine = 'claude';bool _busy = false;++ /// This computer's Add machine form is open over the dialog.+ bool _addingMachine = false;String? _error;@override@@ -145,6 +155,23 @@ class _AddBuddyDialogState extends State<_AddBuddyDialog> {: machines.firstOrNull?.id;}+ /// Runs the Add machine form for this computer, then selects what it added.+ Future<void> _addThisComputer(AppNotifier app) async {+ if (_busy || _addingMachine) return;+ setState(() => _addingMachine = true);+ String? added;+ try {+ added = await showAddMachine(context, c, app);+ } finally {+ if (mounted) {+ setState(() {+ _addingMachine = false;+ if (added != null) _machine = added;+ });+ }+ }+ }+Future<void> _submit() async {final project = _project, machine = _listedMachine;if (_busy || project == null || machine == null) return;@@ -168,6 +195,43 @@ class _AddBuddyDialogState extends State<_AddBuddyDialog> {});}+ /// The Machine field when none of the reader's machines is in the Swarm:+ /// this computer can be added from here.+ Widget _noMachine() {+ final app = widget.app;+ if (app == null) {+ return Text(+ 'A Buddy runs on one of your own machines. Add one of yours to this '+ 'Swarm first.',+ style: DesktopChrome.metadata(),+ );+ }+ return ListenableBuilder(+ listenable: app,+ builder: (context, _) {+ final refusal = thisComputerRefusal(app, c);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'None of your machines is in this Swarm yet.',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 4),+ TextButton(+ onPressed:+ _busy || _addingMachine || !c.canWrite || refusal != null+ ? null+ : () => unawaited(_addThisComputer(app)),+ child: Text('Add ${thisComputerName()}'),+ ),+ if (refusal != null) Text(refusal, style: DesktopChrome.metadata()),+ ],+ );+ },+ );+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -220,15 +284,15 @@ class _AddBuddyDialogState extends State<_AddBuddyDialog> {),const SizedBox(height: 12),Row(+ // With no machine the label sits on the line it names.+ crossAxisAlignment: machines.isEmpty+ ? CrossAxisAlignment.start+ : CrossAxisAlignment.center,children: [label('Machine'),Expanded(child: machines.isEmpty- ? Text(- 'A Buddy runs on one of your own machines. Add '- 'one of yours to this Swarm first.',- style: DesktopChrome.metadata(),- )+ ? _noMachine(): AppSelectField<String>(key: const ValueKey('super-buddy-machine'),value: _listedMachine ?? '',diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 147ca6f89..e2e598861 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -237,6 +237,15 @@ class SuperTabController extends ChangeNotifier {int? get visibilityEpoch => _parts?.epoch;String? error, operationError, operationErrorCode;+ /// Why the files of each conversation's last send did not go up. Kept apart+ /// from [operationError] so it shows only under its own conversation.+ final _uploadErrors = <String, String>{};++ /// What the composer of [conversationId] says went wrong: the last action's+ /// [operationError], else its own upload failure.+ String? composerError(String conversationId) =>+ operationError ?? _uploadErrors[conversationId];+/// One line for the sender after a command succeeds, from the backend: that a/// credential was removed from what they sent and should be revoked.String? operationNotice;@@ -487,8 +496,10 @@ class SuperTabController extends ChangeNotifier {limitBytes: kSuperTabAttachmentMaxBytes,limitFiles: kSuperTabAttachmentMaxFiles,);- // Taking a chip off while its files go up gives the upload up.files.addListener(() {+ // Changing the files answers a refused upload.+ if (_uploadErrors.remove(id) != null) _changed();+ // Taking a chip off while its files go up gives the upload up.if (uploading &&_sending?.conversationId == id &&!files.files.toSet().containsAll(_sending!.files)) {@@ -2464,6 +2475,8 @@ class SuperTabController extends ChangeNotifier {String conversationId,List<HarnessAttachment> files,) async {+ // Any send of this conversation answers its last refused upload.+ _uploadErrors.remove(conversationId);if (files.isEmpty) return const [];final run = ++_uploadRun;uploading = true;@@ -2486,12 +2499,12 @@ class SuperTabController extends ChangeNotifier {return ids;} catch (failure) {if (!_disposed && run == _uploadRun) {- operationError = failure is SuperTabFailure+ // Into the conversation the files were for, whichever is shown now.+ _uploadErrors[conversationId] = failure is SuperTabFailure? failure.message: failure is TimeoutException? 'The upload stopped moving. Try again.': 'Could not upload ${files.length == 1 ? 'the file' : 'the files'}. Try again.';- operationErrorCode = failure is SuperTabFailure ? failure.code : null;}return null;} finally {diff --git a/desktop/lib/super_tabs/leaderboard/model.dart b/desktop/lib/super_tabs/leaderboard/model.dartindex 7339ed1b4..cdd6dea97 100644--- a/desktop/lib/super_tabs/leaderboard/model.dart+++ b/desktop/lib/super_tabs/leaderboard/model.dart@@ -19,7 +19,11 @@ class SuperTabLeaderboard {: projectId = json['projectId'] as String? ?? '',week = _int(json['week']),people = _list(json['people']).map(SuperTabPersonScore.fromJson).toList(),- waiting = SuperTabWaiting.fromJson(_map(json['waiting']));+ waiting = SuperTabWaiting.fromJson(_map(json['waiting'])),+ agents = _list(json['agents']).map(SuperTabAgentScore.fromJson).toList(),+ byModel = _list(json['byModel'])+ .map(SuperTabModelScore.fromJson)+ .toList();final String projectId;@@ -29,6 +33,81 @@ class SuperTabLeaderboard {/// Most points first.final List<SuperTabPersonScore> people;final SuperTabWaiting waiting;++ /// The project's PM and Buddies, most points first; empty from a server+ /// before them.+ final List<SuperTabAgentScore> agents;++ /// Every model that worked the week, most points first; empty from a+ /// server before them.+ final List<SuperTabModelScore> byModel;+}++/// A permanent agent, the PM or a Buddy, scored by name like a person+/// (Dee, 2026-10-29).+class SuperTabAgentScore {+ SuperTabAgentScore.fromJson(Map<String, dynamic> json)+ : agentId = json['agentId'] as String? ?? '',+ displayName = json['displayName'] as String? ?? '',+ buddy = json['kind'] == 'buddy',+ personId = _text(json['personId']),+ machineId = json['machineId'] as String? ?? '',+ points = _int(json['points']),+ rank = _int(json['rank']),+ shipped = _int(json['shipped']);++ final String agentId, displayName, machineId;++ /// A Buddy, else the project's PM.+ final bool buddy;++ /// A Buddy's person; null for the PM.+ final String? personId;++ /// The PM's: requests of the groups it led that shipped; a Buddy's: groups+ /// opened from its proposals that shipped.+ final int points, rank, shipped;+}++/// The temporary workers by what they ran on, never by agent (Dee,+/// 2026-10-29).+class SuperTabModelScore {+ SuperTabModelScore.fromJson(Map<String, dynamic> json)+ : engine = json['engine'] as String? ?? '',+ model = _text(json['model']),+ effort = _text(json['effort']),+ grid = json['grid'] == true,+ points = _int(json['points']),+ rank = _int(json['rank']),+ shipped = _int(_map(json['shipped'])['count']),+ medianAttemptMs = _optional(_map(json['shipped'])['medianAttemptMs']),+ medianRequestMs = _optional(_map(json['shipped'])['medianRequestMs']),+ reviewed = _int(_map(json['firstReview'])['reviewed']),+ passed = _int(_map(json['firstReview'])['passed']),+ reviews = _int(json['reviews']);++ final String engine;++ /// Null when the engine reported none; [effort] null for attempts recorded+ /// before efforts were.+ final String? model, effort;++ /// Served on the Swarm's grid.+ final bool grid;+ final int points, rank, shipped;++ /// Median time to ship from the shipping attempt's assignment, and from the+ /// request's first assignment.+ final int? medianAttemptMs, medianRequestMs;++ /// This week's attempts with a first review on record, and how many passed.+ final int reviewed, passed;++ /// Review verdicts it gave.+ final int reviews;++ /// One key per row: engine, model and effort.+ String get key => 'model-$engine-${model ?? ''}-${effort ?? ''}';}class SuperTabPersonScore {diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dartindex 1363f32e3..7bf89eb72 100644--- a/desktop/lib/super_tabs/leaderboard/person_row.dart+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart@@ -23,12 +23,12 @@ const _avatarSize = SuperTabAvatar.rowSize;/// Numbers and rankings (desktop design system): the rank a bold numeral in/// secondary ink, the points the one emphasized number, every figure in a/// column of one width so the column holds row under row.-TextStyle _rankStyle() => grid.AppType.label(+TextStyle leaderboardRankStyle() => grid.AppType.label(fontWeight: FontWeight.w700,color: grid.AppPalette.textSecondary,fontFeatures: grid.AppFont.tabularFigures,);-TextStyle _pointsStyle() => grid.AppType.label(+TextStyle leaderboardPointsStyle() => grid.AppType.label(fontWeight: grid.AppFont.semibold,color: grid.AppPalette.textPrimary,fontFeatures: grid.AppFont.tabularFigures,@@ -63,7 +63,18 @@ class LeaderboardColumns {factory LeaderboardColumns.of(BuildContext context,List<SuperTabPersonScore> scores,- ) {+ ) => LeaderboardColumns.measure(+ context,+ ranks: scores.map((score) => score.rank),+ points: scores.map((score) => score.points),+ );++ /// The columns for any ranked list: people, agents or models.+ factory LeaderboardColumns.measure(+ BuildContext context, {+ required Iterable<int> ranks,+ required Iterable<int> points,+ }) {final scaler = MediaQuery.textScalerOf(context);double width(String text, TextStyle style) {final painter = TextPainter(@@ -81,11 +92,8 @@ class LeaderboardColumns {.map((value) => '$value').fold('0', (a, b) => b.length > a.length ? b : a);return LeaderboardColumns(- rank: width(widest(scores.map((score) => score.rank)), _rankStyle()),- points: width(- widest(scores.map((score) => score.points)),- _pointsStyle(),- ),+ rank: width(widest(ranks), leaderboardRankStyle()),+ points: width(widest(points), leaderboardPointsStyle()),);}@@ -175,7 +183,7 @@ class LeaderboardPersonRow extends StatelessWidget {'${score.rank}',maxLines: 1,textAlign: TextAlign.right,- style: _rankStyle(),+ style: leaderboardRankStyle(),),),const SizedBox(width: _gap),@@ -189,7 +197,7 @@ class LeaderboardPersonRow extends StatelessWidget {children: [_name(),if (numbers.isNotEmpty)- _Numbers(+ LeaderboardNumbers(key: ValueKey('leaderboard-meta-${person.id}'),parts: numbers,),@@ -206,7 +214,7 @@ class LeaderboardPersonRow extends StatelessWidget {child: Text('${score.points}',maxLines: 1,- style: _pointsStyle(),+ style: leaderboardPointsStyle(),),),),@@ -233,15 +241,7 @@ class LeaderboardPersonRow extends StatelessWidget {if (leaderboardCrowned(score))WidgetSpan(alignment: PlaceholderAlignment.middle,- child: Padding(- padding: const EdgeInsets.only(left: _halfGap),- child: Semantics(- key: ValueKey('leaderboard-crown-${person.id}'),- label: 'Number one $weekName',- excludeSemantics: true,- child: Text('\u{1F451}', style: DesktopChrome.metadata()),- ),- ),+ child: LeaderboardCrown(id: person.id, weekName: weekName),),if (person.statusAt(clock.now()) case final status?)TextSpan(@@ -258,21 +258,57 @@ class LeaderboardPersonRow extends StatelessWidget {);}+/// Number one's crown beside their name: content artwork, said in words, at+/// the metadata size so a crowned row is as tall as any other (Team and+/// celebration, design system). [id] keys it per row.+class LeaderboardCrown extends StatelessWidget {+ const LeaderboardCrown({super.key, required this.id, required this.weekName});+ final String id;++ /// The week the board shows, as the crown says it: "Number one last week".+ final String weekName;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.only(left: _halfGap),+ child: Semantics(+ key: ValueKey('leaderboard-crown-$id'),+ label: 'Number one $weekName',+ excludeSemantics: true,+ child: Text('\u{1F451}', style: DesktopChrome.metadata()),+ ),+ );+}+/// A person's numbers joined by a spaced middle dot. Where the line does not/// fit, whole items fall off its end, never part of a word; the whole line,/// lent in agent-hours, is on hover.-class _Numbers extends StatelessWidget {- const _Numbers({super.key, required this.parts});+class LeaderboardNumbers extends StatelessWidget {+ const LeaderboardNumbers({+ super.key,+ required this.parts,+ this.tooltip,+ this.lines = 1,+ });final List<String> parts;+ /// How many lines whole items may take: a model's numbers are the routing+ /// measurement, so its row gives them two.+ final int lines;++ /// What hovering shows; the whole line, lent in agent-hours, when not given.+ final String? tooltip;+@overrideWidget build(BuildContext context) {final style = DesktopChrome.metadata();final scaler = MediaQuery.textScalerOf(context);return Tooltip(- message: parts- .map((part) => part.replaceFirst(' hour', ' agent-hour'))- .join(' · '),+ message:+ tooltip ??+ parts+ .map((part) => part.replaceFirst(' hour', ' agent-hour'))+ .join(' · '),child: LayoutBuilder(builder: (context, constraints) {bool fits(String text) {@@ -280,7 +316,7 @@ class _Numbers extends StatelessWidget {text: TextSpan(text: text, style: style),textDirection: TextDirection.ltr,textScaler: scaler,- maxLines: 1,+ maxLines: lines,)..layout(maxWidth: constraints.maxWidth);final fits = !painter.didExceedMaxLines;painter.dispose();@@ -297,7 +333,7 @@ class _Numbers extends StatelessWidget {final wraps = !fits(text);return Text(text,- maxLines: wraps ? 2 : 1,+ maxLines: wraps ? lines + 1 : lines,overflow: TextOverflow.ellipsis,style: style,);diff --git a/desktop/lib/super_tabs/leaderboard/tabs.dart b/desktop/lib/super_tabs/leaderboard/tabs.dartnew file mode 100644index 000000000..066512242--- /dev/null+++ b/desktop/lib/super_tabs/leaderboard/tabs.dart@@ -0,0 +1,84 @@+import 'package:flutter/material.dart';++import '../../shared/theme/app_theme.dart' as grid;+import '../../widgets/desktop_chrome.dart';+import '../../widgets/finger_target.dart';++/// The leaderboard's three lists (Dee, 2026-10-29): people, the permanent+/// agents (the PM and Buddies), and the temporary workers by model.+enum LeaderboardTab { humans, agents, models }++extension LeaderboardTabLabel on LeaderboardTab {+ String get label => switch (this) {+ LeaderboardTab.humans => 'Humans',+ LeaderboardTab.agents => 'Agents',+ LeaderboardTab.models => 'Models',+ };+}++/// The board's heading: Humans, Agents and Models as scope pills, the+/// chosen one selected (the design system's scope selector), then [actions]+/// (the week, Invite people) at the trailing edge. In a pane too narrow for+/// one line the actions take the next one.+class LeaderboardHeader extends StatelessWidget {+ const LeaderboardHeader({+ super.key,+ required this.selected,+ required this.onSelect,+ this.actions = const [],+ });+ final LeaderboardTab selected;+ final ValueChanged<LeaderboardTab> onSelect;+ final List<Widget> actions;++ static const _gap = grid.AppDesktop.controlGap;++ @override+ Widget build(BuildContext context) => Padding(+ // The section headings' insets: the spacing scale's 16, 12 and 4.+ padding: const EdgeInsets.fromLTRB(+ DesktopChrome.groupGap,+ 0,+ _gap + _gap / 2,+ _gap / 2,+ ),+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: DesktopChrome.controlHeight),+ child: Wrap(+ alignment: WrapAlignment.spaceBetween,+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: _gap,+ runSpacing: _gap / 2,+ children: [+ // Enlarged text in a narrow pane scrolls the pills rather than+ // cutting a name short.+ SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (final tab in LeaderboardTab.values) ...[+ if (tab != LeaderboardTab.values.first)+ const SizedBox(width: _gap / 2),+ // A phone's pill is a finger's height.+ fingerTarget(+ enabled: workspaceIsCompact(context),+ DesktopPill(+ key: ValueKey('leaderboard-tab-${tab.name}'),+ label: tab.label,+ compact: true,+ selected: tab == selected,+ onPressed: () => onSelect(tab),+ ),+ ),+ ],+ ],+ ),+ ),+ if (actions.isNotEmpty)+ Row(mainAxisSize: MainAxisSize.min, children: actions),+ ],+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/leaderboard/worker_rows.dart b/desktop/lib/super_tabs/leaderboard/worker_rows.dartnew file mode 100644index 000000000..9460fa31b--- /dev/null+++ b/desktop/lib/super_tabs/leaderboard/worker_rows.dart@@ -0,0 +1,280 @@+import 'package:flutter/material.dart';++import '../../core/runtime_model_name.dart';+import '../../shared/theme/app_theme.dart' as grid;+import '../../widgets/desktop_chrome.dart';+import '../../widgets/engine_identity.dart';+import '../../widgets/finger_target.dart';+import '../identity.dart';+import '../model.dart';+import 'format.dart';+import 'model.dart';+import 'person_row.dart';++/// The gap between a row's columns, and half of it: the spacing scale's 8+/// and 4.+const _gap = grid.AppDesktop.controlGap;+const _halfGap = _gap / 2;++/// One ranked row of the Agents or Models list, built like a person's+/// (Numbers and rankings): the rank as a bold numeral in its column, the+/// identity, the name with a quiet tag and, for number one, the crown, a quiet+/// line of non-zero numbers in words, and the points at the trailing edge.+class _ScoreRow extends StatelessWidget {+ const _ScoreRow({+ required this.id,+ required this.rank,+ required this.points,+ required this.columns,+ required this.identity,+ required this.name,+ required this.tag,+ required this.numbers,+ required this.crowned,+ required this.weekName,+ this.numbersTooltip,+ this.numberLines = 1,+ });+ final String id, name, weekName;+ final int rank, points;+ final LeaderboardColumns columns;+ final Widget identity;++ /// Quietly after the name: "PM · Mac Studio", "grid".+ final String? tag;+ final List<String> numbers;+ final String? numbersTooltip;+ final int numberLines;+ final bool crowned;++ @override+ Widget build(BuildContext context) => Padding(+ key: ValueKey('leaderboard-row-$id'),+ padding: const EdgeInsets.symmetric(horizontal: _gap),+ child: ConstrainedBox(+ constraints: BoxConstraints(+ minHeight: fingerHeight(+ grid.AppControl.heightField,+ enabled: workspaceIsCompact(context),+ ),+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: _gap,+ vertical: _halfGap,+ ),+ child: Row(+ children: [+ SizedBox(+ width: columns.rank,+ child: Text(+ '$rank',+ maxLines: 1,+ textAlign: TextAlign.right,+ style: leaderboardRankStyle(),+ ),+ ),+ const SizedBox(width: _gap),+ SizedBox.square(+ dimension: SuperTabAvatar.rowSize,+ child: Center(child: identity),+ ),+ const SizedBox(width: _gap),+ Expanded(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text.rich(+ TextSpan(+ text: name,+ children: [+ if (crowned)+ WidgetSpan(+ alignment: PlaceholderAlignment.middle,+ child: LeaderboardCrown(id: id, weekName: weekName),+ ),+ if (tag case final tag?)+ TextSpan(+ text: ' $tag',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ if (numbers.isNotEmpty)+ LeaderboardNumbers(+ key: ValueKey('leaderboard-numbers-$id'),+ parts: numbers,+ tooltip: numbersTooltip,+ lines: numberLines,+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.only(left: _gap),+ child: SizedBox(+ width: columns.points,+ child: Align(+ alignment: Alignment.centerRight,+ child: Semantics(+ label: plural(points, 'point'),+ excludeSemantics: true,+ child: Text(+ '$points',+ maxLines: 1,+ style: leaderboardPointsStyle(),+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+}++/// The PM or a Buddy, by name like a person: "PM · openharness" (the project+/// it leads) or "Buddy · dee" beside the name, and what they shipped beneath.+class LeaderboardAgentRow extends StatelessWidget {+ const LeaderboardAgentRow({+ super.key,+ required this.score,+ required this.agent,+ required this.columns,+ required this.weekName,+ this.projectName,+ this.ownerName,+ });+ final SuperTabAgentScore score;++ /// The agent as the Swarm shows it, for its avatar; null once it left.+ final SuperTabAgent? agent;+ final LeaderboardColumns columns;+ final String weekName;++ /// The project the PM leads, and a Buddy's person, as the Swarm names them.+ final String? projectName, ownerName;++ @override+ Widget build(BuildContext context) {+ final agent = this.agent;+ return _ScoreRow(+ id: 'agent-${score.agentId}',+ rank: score.rank,+ points: score.points,+ columns: columns,+ weekName: weekName,+ crowned: score.rank == 1 && score.points > 0,+ identity: agent == null+ ? SuperTabAvatar(+ identity: 'agent:${score.agentId}',+ name: score.displayName,+ size: SuperTabAvatar.rowSize,+ pattern: true,+ )+ : SuperTabAvatar.agent(agent, size: SuperTabAvatar.rowSize),+ name: score.displayName,+ tag: score.buddy+ ? ['Buddy', ?ownerName].join(' · ')+ : ['PM', ?projectName].join(' · '),+ numbers: [+ if (score.shipped > 0)+ score.buddy+ ? plural(score.shipped, 'proposal shipped', 'proposals shipped')+ : '${score.shipped} shipped',+ ],+ );+ }+}++/// A model the temporary workers ran on, never an agent: "Opus · high", its+/// engine's mark, and its numbers in words; the time from the request's first+/// attempt on hover.+class LeaderboardModelRow extends StatelessWidget {+ const LeaderboardModelRow({+ super.key,+ required this.score,+ required this.columns,+ required this.weekName,+ });+ final SuperTabModelScore score;+ final LeaderboardColumns columns;+ final String weekName;++ @override+ Widget build(BuildContext context) {+ final score = this.score;+ final name = [+ switch (score.model) {+ final String model => modelDisplayName(model),+ null => engineIdentity(score.engine).label,+ },+ ?score.effort,+ ].join(' · ');+ return _ScoreRow(+ id: score.key,+ rank: score.rank,+ points: score.points,+ columns: columns,+ weekName: weekName,+ crowned: score.rank == 1 && score.points > 0,+ identity: EngineMark(engine: score.engine),+ name: name,+ tag: score.grid ? 'grid' : null,+ numbers: leaderboardModelNumbers(score),+ numbersTooltip: leaderboardModelNumbers(score, full: true).join(' · '),+ numberLines: 2,+ );+ }+}++/// A model's numbers in words, each left out at zero: "31 shipped", "82%+/// passed first review", "47 min to ship", "5 reviews". [full] is the hover+/// text: the counts behind the share, and the time from the request's first+/// attempt beside the shipping attempt's.+List<String> leaderboardModelNumbers(+ SuperTabModelScore score, {+ bool full = false,+}) {+ final attempt = score.medianAttemptMs, request = score.medianRequestMs;+ return [+ if (score.shipped > 0) '${score.shipped} shipped',+ if (score.reviewed > 0)+ full+ ? '${score.passed} of ${score.reviewed} passed first review'+ : '${(score.passed * 100 / score.reviewed).round()}% passed first review',+ if (attempt != null)+ full+ ? [+ '${leaderboardDuration(attempt)} from the shipping attempt',+ if (request != null)+ '${leaderboardDuration(request)} from the first',+ ].join(', ')+ : '${leaderboardDuration(attempt)} to ship',+ if (score.reviews > 0) plural(score.reviews, 'review'),+ ];+}++/// A list with nothing to show this week, said as quiet text.+class LeaderboardEmpty extends StatelessWidget {+ const LeaderboardEmpty(this.text, {super.key});+ final String text;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.fromLTRB(+ DesktopChrome.groupGap,+ 0,+ DesktopChrome.groupGap,+ DesktopChrome.controlGap / 2,+ ),+ child: Text(text, style: DesktopChrome.metadata()),+ );+}diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 259b48c6a..817b47bc7 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -114,6 +114,9 @@ class SuperTabMachines extends StatefulWidget {State<SuperTabMachines> createState() => _SuperTabMachinesState();}+/// The engines whose allowance a machine row shows, in this order.+const _chipEngines = ['claude', 'codex'];+class _MachineChoice {const _MachineChoice({required this.id,@@ -514,6 +517,586 @@ class _MachinePickerState extends State<_MachinePicker> {}}+/// Adds a machine of the reader's to the Swarm through the Add machine form,+/// for Add a Buddy. Resolves to the added machine's id, null when it was not.+Future<String?> showAddMachine(+ BuildContext context,+ SuperTabController c,+ AppNotifier app, {+ Future<MachineResources?> Function(String machineId)? readLocal,+}) => _contributeDialog(+ context,+ c,+ app,+ sampleOf: (_) => null,+ canRemove: (_) => false,+ removeReason: (_) => null,+ remove: (_) {},+ readLocal: readLocal,+);++/// Why [m] cannot be added to the Swarm now, in the Add machine form's words;+/// null when it can.+({IconData icon, String message})? _machineUnavailable(+ MachineState m, {+ required bool inSwarm,+}) {+ if (inSwarm) {+ return (icon: AppIcons.circleCheck, message: 'Already in this Swarm');+ }+ if (m.needsLink) {+ return (+ icon: AppIcons.unlink,+ message: 'Not linked. Link this computer from Machines.',+ );+ }+ if (m.isOffline) {+ return (+ icon: AppIcons.cloudOff,+ message: 'Offline. Open Harness on this computer to add it.',+ );+ }+ return null;+}++/// Why this computer cannot be added to the Swarm from here, as the Add+/// machine form says it; null when it can.+String? thisComputerRefusal(AppNotifier app, SuperTabController c) {+ final here = app.machineStates.values+ .where((m) => m.isLocalMachine)+ .firstOrNull;+ if (here == null || here.belongsToOtherAccount) {+ return 'No computer is connected to this account yet.';+ }+ final inSwarm = (c.snapshot?.machines ?? const <Map<String, dynamic>>[]).any(+ (m) => m['machineId'] == here.machine.machineId,+ );+ return _machineUnavailable(here, inSwarm: inSwarm)?.message;+}++/// The Add machine form, or with [existing] that machine's settings: one+/// place for the Machines panel and for Add a Buddy. Resolves to the machine's+/// id once it was added or saved, null when the person cancelled or it could+/// not be. The panel's own knowledge comes in as callbacks: [sampleOf] a+/// reading it already holds, [canRemove], [removeReason] and [remove] for+/// Remove from this Swarm, and [readLocal] in place of+/// [AppNotifier.readMachineResources].+Future<String?> _contributeDialog(+ BuildContext context,+ SuperTabController c,+ AppNotifier app, {+ Map<String, dynamic>? existing,+ _MachineView? view,+ required MachineResources? Function(String machineId) sampleOf,+ required bool Function(String machineId) canRemove,+ required String? Function(String machineId) removeReason,+ required void Function(_MachineView view) remove,+ Future<MachineResources?> Function(String machineId)? readLocal,+}) async {+ final isConfigure = existing != null;+ final existingId = existing?['machineId'] as String?;+ bool isExisting(MachineState m) =>+ existingId != null && m.machine.machineId == existingId;+ // "Already in this tab" means already CONTRIBUTED — an agent already+ // running there (unconfirmed) does not count, or a freshly created tab+ // whose lead runs on this Mac could never contribute it. `_ids` (agents+ // too) is for the machine-card panel below, not this dialog.+ final contributed = {+ for (final m in c.snapshot?.machines ?? const <Map<String, dynamic>>[])+ m['machineId'] as String,+ };+ // Unavailable computers stay inspectable in the picker, but another+ // account's computers must never be offered for contribution. One choice+ // per computer: a Mac's Harness Team account in this Swarm is part of its+ // Mac's row, and joins and leaves with it (SuperTabSnapshot.placeOf).+ bool ownRow(MachineState m) =>+ (c.snapshot?.placeOf(m.machine.machineId) ?? m.machine.machineId) ==+ m.machine.machineId;+ List<MachineState> ownedMachines() => app.machineStates.values+ .where((m) => !m.belongsToOtherAccount && ownRow(m))+ .toList();+ ({IconData icon, String message})? unavailable(MachineState m) =>+ _machineUnavailable(+ m,+ inSwarm: !isExisting(m) && contributed.contains(m.machine.machineId),+ );++ bool canSelect(MachineState? m) =>+ m != null && !m.belongsToOtherAccount && unavailable(m) == null;+ final addable = ownedMachines().where(canSelect).toList();+ String labelFor(MachineState m) => m.isLocalMachine+ ? 'This Mac (${m.machine.displayName})'+ : m.machine.displayName;+ String? machineId =+ existingId ??+ addable.where((m) => m.isLocalMachine).firstOrNull?.machine.machineId ??+ addable.firstOrNull?.machine.machineId;+ String? error;+ String? added;+ var busy = false;+ String? setupId;+ // The agent slots the owner is choosing. A machine already in this Swarm+ // starts at the number it has; a new one starts at what its total memory+ // suggests, worked out here rather than by preparation (below).+ int? storedSlots(String? id) {+ final row = id == null+ ? null+ : c.snapshot?.machines.where((m) => m['machineId'] == id).firstOrNull;+ final current = row?['maxAgents'];+ return current is num ? current.toInt() : null;+ }++ // Readings this dialog has taken itself, keyed by machine. The panel's own+ // samples stand in for a machine it already reads.+ final suggestions = <String, int>{};+ final maximums = <String, int>{};++ /// What this machine's own memory says, once a reading has answered. Null+ /// while one is still coming, or when it failed.+ int? memorySuggestion(String? id) =>+ id == null ? null : suggestions[id] ?? _suggestedAgentSlots(sampleOf(id));++ int maximumFor(String? id) => id == null+ ? _agentSlotsMin+ : maximums[id] ??+ _maxAgentSlots(sampleOf(id)) ??+ _clampAgentSlots(storedSlots(id) ?? _agentSlotsMin);++ int slotsFor(String? id) {+ final stored = storedSlots(id);+ if (stored != null) return _clampAgentSlots(stored);+ return memorySuggestion(id) ?? _agentSlotsMin;+ }++ var slots = slotsFor(machineId);+ var slotsEdited = false;++ // Machine settings: As memory allows, or At most a number (Dee,+ // 2026-10-29). Memory is known from this dialog's reading, the panel's+ // sample, or what the machine last reported to the Swarm.+ MachineResources? settingsResources() =>+ (existingId == null ? null : sampleOf(existingId)) ?? view?.resources;+ int? memoryMaximum() =>+ maximums[existingId] ?? _maxAgentSlots(settingsResources());++ // Until the owner touches either, both follow what is known: a stored+ // limit at or above the maximum is as memory allows, and one below it is+ // the owner's own. With the maximum unknown a stored number is kept, and+ // a machine with no number of its own starts at At most its suggestion,+ // as Add machine does (review of #2084).+ bool? memoryEdited;+ int? atMostEdited;+ bool memoryChoice() {+ if (memoryEdited != null) return memoryEdited!;+ final stored = storedSlots(existingId);+ final maximum = memoryMaximum();+ return stored != null && maximum != null && stored >= maximum;+ }++ // With nothing known, every machine may offer four.+ int atMostMaximum() =>+ memoryMaximum() ??+ _clampAgentSlots(storedSlots(existingId) ?? _agentSlotsFloor);+ int atMostValue() {+ if (atMostEdited != null) return atMostEdited!;+ final stored = storedSlots(existingId);+ final maximum = memoryMaximum();+ if (stored != null && (maximum == null || stored < maximum)) {+ return _clampAgentSlots(stored);+ }+ final suggested =+ suggestions[existingId] ?? _suggestedAgentSlots(settingsResources());+ return (suggested ?? maximum ?? stored ?? _agentSlotsFloor).clamp(+ _agentSlotsMin,+ atMostMaximum(),+ );+ }++ /// Why this machine's settings cannot be saved from here, in settings'+ /// own words; null when they can.+ String? settingsUnavailable() {+ final m = app.stateOf(existingId!);+ if (m == null) {+ return 'This computer can’t reach that machine. Sign in to Harness '+ 'there with this account to change its settings.';+ }+ // The machine by name: "this computer" is the one you're on.+ final name = superTabMachineName(m.machine.displayName);+ if (m.belongsToOtherAccount) {+ return '$name is signed in to another account.';+ }+ if (m.needsLink) return 'Not linked. Link $name from Machines.';+ if (m.isOffline) {+ return 'Offline. Open Harness on $name to change its settings.';+ }+ return null;+ }++ // As memory allows saves the machine's maximum: its own figure from+ // setup (it measured the machine just now), else the one known here,+ // else what an older Harness's setup offered.+ int memoryLimit(Map<String, dynamic> prepared) {+ final offeredMaximum = prepared['maxAvailableAgents'];+ if (offeredMaximum is num) return _clampAgentSlots(offeredMaximum);+ final offered = prepared['maxAgents'];+ return memoryMaximum() ??+ (offered is num+ ? _clampAgentSlots(offered)+ : storedSlots(existingId) ?? _agentSlotsFloor);+ }++ // The open dialog and its own setState, once it is built: a reading+ // answers while the form is open, and the field has to repaint when it+ // does. Both are read only while the dialog is still there — one that+ // arrives after it closed has nothing to repaint.+ BuildContext? dialog;+ void Function(void Function())? repaint;+ final reading = <String>{};++ /// Start the field where this machine's own memory says, without asking+ /// preparation: preparation sets the project up, probes engines and takes+ /// one of its 32 setup slots, and opening a form the owner may cancel is+ /// no reason to do that. A configured machine still needs its RAM reading+ /// for the stepper limit, but its chosen number is never replaced.+ Future<void> suggestSlots() async {+ final id = machineId;+ if (id == null || !canSelect(app.stateOf(id)) || !reading.add(id)) {+ return;+ }+ MachineResources? resources;+ try {+ resources = await (readLocal ?? app.readMachineResources)(id);+ } catch (_) {+ return;+ }+ final suggested = _suggestedAgentSlots(resources);+ // The picker may have moved on to another machine, whose own reading is+ // the one that belongs in the field now — or the dialog may have closed.+ if (suggested == null || machineId != id || dialog?.mounted != true) {+ return;+ }+ suggestions[id] = suggested;+ maximums[id] = _maxAgentSlots(resources)!;+ // Repaint the limit, but never replace a number the owner chose.+ repaint?.call(() {+ if (!slotsEdited && storedSlots(id) == null) slots = suggested;+ });+ }++ await showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ child: ListenableBuilder(+ listenable: app,+ builder: (context, _) => StatefulBuilder(+ builder: (context, update) {+ dialog = context;+ repaint = update;+ // Not awaited: the form is usable immediately, and the number+ // only has to be there by the time the owner reads it. Each+ // machine is read once, so a rebuild does not read again.+ unawaited(suggestSlots());+ Future<void> save() async {+ if (busy ||+ !c.canWrite ||+ machineId == null ||+ !canSelect(app.stateOf(machineId!))) {+ return;+ }+ final selected = machineId!;+ // Settings save what is on screen now: preparation below may+ // learn a different maximum, and that must not turn the+ // owner's At most into As memory allows (review of #2084).+ final atMost = isConfigure && !memoryChoice()+ ? atMostValue()+ : null;+ update(() {+ busy = true;+ error = null;+ });+ try {+ setupId ??= superTabOperationId();+ final deadline = DateTime.now().add(const Duration(minutes: 5));+ Map<String, dynamic> prepared;+ while (true) {+ if (!context.mounted || !c.canWrite) return;+ prepared = await app.superTabMachineRequest(selected, {+ 'action': 'prepareContribution',+ 'tabId': c.tabId,+ 'scope': 'swarm',+ 'operationId': setupId,+ });+ if (prepared['state'] == 'ready' &&+ prepared['scope'] == 'swarm') {+ break;+ }+ if (prepared['state'] != 'preparing') {+ throw const SuperTabFailure(+ 'UPDATE_REQUIRED',+ 'Update Harness on this machine, then try again.',+ );+ }+ if (DateTime.now().isAfter(deadline)) {+ throw const SuperTabFailure(+ 'SETUP_PENDING',+ 'Project setup is still running. Try again to check its progress.',+ );+ }+ await Future<void>.delayed(const Duration(seconds: 1));+ }+ if (!context.mounted || !c.canWrite) return;+ final machine = app.stateOf(selected);+ final engines =+ (prepared['engines'] as List?)+ ?.whereType<String>()+ .where((engine) => _chipEngines.contains(engine))+ .toSet()+ .toList() ??+ <String>[];+ if (engines.isEmpty) {+ throw const SuperTabFailure(+ 'NO_SWARM_ENGINE',+ 'Install Claude Code or Codex on this machine, then try again.',+ );+ }+ // A machine with no number of its own whose reading failed,+ // or had not answered yet, is showing the floor rather than+ // a suggestion. The owner never chose that, so send what+ // preparation offered instead — the number the field would+ // have shown had the reading arrived.+ final offered = prepared['maxAgents'];+ final offeredMaximum = prepared['maxAvailableAgents'];+ if (offeredMaximum is num) {+ maximums[selected] = _clampAgentSlots(offeredMaximum);+ }+ if (!slotsEdited &&+ storedSlots(selected) == null &&+ memorySuggestion(selected) == null &&+ offered is num) {+ slots = _clampAgentSlots(offered);+ }+ // An earlier lost reply leaves an uncertain attempt holding+ // its own receipt, and only one action may be in flight:+ // check that one first, then send the number the owner is+ // looking at — the stored attempt cannot know it was changed.+ if (c.pendingCommand?['type'] == 'machine.contribute') {+ // If that attempt cannot be confirmed, its own error is+ // the one worth showing: it says why it is still unclear.+ if (await c.retry() == null) {+ if (!context.mounted) return;+ throw SuperTabFailure(+ c.operationErrorCode ?? 'CONTRIBUTION_FAILED',+ c.operationError ??+ 'The earlier attempt is still not confirmed. '+ 'Try again to check it.',+ );+ }+ if (!context.mounted || !c.canWrite) return;+ }+ final result = await c.command({+ 'type': 'machine.contribute',+ 'machineId': selected,+ 'name': machine!.machine.displayName,+ 'cwd': prepared['cwd'],+ if (prepared['scope'] != null) 'scope': prepared['scope'],+ 'engines': engines,+ 'maxAgents': !isConfigure+ ? slots+ : atMost ?? memoryLimit(prepared),+ });+ if (result == null) {+ throw SuperTabFailure(+ 'CONTRIBUTION_FAILED',+ c.operationError ?? 'Could not add this machine.',+ );+ }+ await app.wakeSuperTabHost(selected);+ // This Mac, added while its person is here: macOS asks once+ // for the Harness Team account (cli/src/team/autoSetup.ts).+ if (app.stateOf(selected)?.isLocalMachine == true) {+ unawaited(app.offerTeamAccount('contribute', tabId: c.tabId));+ }+ added = selected;+ if (context.mounted) Navigator.pop(context);+ } catch (failure) {+ if (context.mounted) {+ update(() {+ busy = false;+ error = failure.toString();+ if (failure is! SuperTabFailure ||+ failure.code != 'SETUP_PENDING') {+ setupId = null;+ }+ });+ }+ }+ }++ final own = ownedMachines();+ final canSave =+ machineId != null && canSelect(app.stateOf(machineId!));+ if (isConfigure) {+ final current = app.stateOf(existingId!);+ final why = settingsUnavailable();+ return SuperTabDetailDialog(+ title: superTabMachineName(+ current?.machine.displayName ??+ existing['name'] as String? ??+ existingId,+ ),+ body: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ _AgentsLimit(+ memory: memoryChoice(),+ value: atMostValue(),+ maximum: atMostMaximum(),+ busy: busy,+ onMemory: () => update(() => memoryEdited = true),+ onAtMost: (next) => update(() {+ memoryEdited = false;+ atMostEdited = next;+ }),+ ),+ // Why it cannot be removed, in words rather than a dimmed button alone.+ if (view != null && canRemove(view.id))+ if (removeReason(view.id) case final reason?) ...[+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(reason, style: DesktopChrome.metadata()),+ ],+ if (!canSave && why != null) ...[+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(why, style: DesktopChrome.metadata()),+ ],+ if (error != null) ...[+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(error!, style: DesktopChrome.metadata()),+ ],+ ],+ ),+ // One clear action at the right; the rarer one quiet at the+ // left, as in the machine's details.+ leadingActions: [+ if (view != null && canRemove(view.id))+ TextButton(+ style: superTabQuietAction,+ onPressed: busy || removeReason(view.id) != null+ ? null+ : () {+ Navigator.pop(context);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ remove(view);+ });+ },+ child: const Text('Remove from this Swarm'),+ ),+ ],+ actions: [+ FilledButton(+ onPressed: busy || !canSave ? null : save,+ child: Text(busy ? 'Saving…' : 'Save'),+ ),+ ],+ );+ }+ return SuperTabDetailDialog(+ title: 'Add machine',+ body: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (own.isNotEmpty)+ _MachinePicker(+ value: machineId,+ busy: busy,+ choices: [+ for (final m in own)+ _MachineChoice(+ id: m.machine.machineId,+ label: labelFor(m),+ unavailable: unavailable(m),+ ),+ ],+ onChanged: (id) {+ if (busy || !canSelect(app.stateOf(id))) return;+ update(() {+ machineId = id;+ setupId = null;+ error = null;+ // Another machine has its own number: the one it+ // already offers, or its own suggestion.+ slots = slotsFor(id);+ slotsEdited = false;+ });+ unawaited(suggestSlots());+ },+ )+ else+ Text(+ 'No computer is connected to this account yet.',+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: 16),+ if (own.isNotEmpty) ...[+ Text(+ "The Swarm's product managers can start agents here with this machine's signed-in accounts. "+ 'They run without asking for permission, in projects cloned to ~/harnesses/swarms.',+ style: DesktopChrome.text(),+ ),+ ] else ...[+ Text(+ 'To add another computer, install Harness on it and sign in with '+ 'this account, or approve a device with no screen from Machines.',+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: 4),+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ onPressed: () {+ Navigator.pop(context);+ app.requestMachines();+ },+ child: const Text('Open Machines'),+ ),+ ),+ ],+ if (own.isNotEmpty) ...[+ const SizedBox(height: 16),+ _AgentSlots(+ value: slots,+ maximum: maximumFor(machineId),+ busy: busy,+ onChanged: (next) => update(() {+ slots = next;+ slotsEdited = true;+ }),+ ),+ ],+ if (error != null) ...[+ const SizedBox(height: 12),+ Text(error!, style: DesktopChrome.metadata()),+ ],+ ],+ ),+ actions: [+ if (own.isNotEmpty)+ FilledButton(+ onPressed: busy || !canSave ? null : save,+ child: Text(busy ? 'Preparing…' : 'Add machine'),+ ),+ ],+ );+ },+ ),+ ),+ ),+ );+ return added;+}+class _SuperTabMachinesState extends State<SuperTabMachines> {final _samples = <String, (MachineResources, DateTime)>{};String? _selectedMachineId;@@ -642,524 +1225,19 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {}) async {final app = widget.app;if (app == null) return;- final isConfigure = existing != null;- final existingId = existing?['machineId'] as String?;- bool isExisting(MachineState m) =>- existingId != null && m.machine.machineId == existingId;- // "Already in this tab" means already CONTRIBUTED — an agent already- // running there (unconfirmed) does not count, or a freshly created tab- // whose lead runs on this Mac could never contribute it. `_ids` (agents- // too) is for the machine-card panel below, not this dialog.- final contributed = {- for (final m in c.snapshot?.machines ?? const <Map<String, dynamic>>[])- m['machineId'] as String,- };- // Unavailable computers stay inspectable in the picker, but another- // account's computers must never be offered for contribution. One choice- // per computer: a Mac's Harness Team account in this Swarm is part of its- // Mac's row, and joins and leaves with it (SuperTabSnapshot.placeOf).- bool ownRow(MachineState m) =>- (c.snapshot?.placeOf(m.machine.machineId) ?? m.machine.machineId) ==- m.machine.machineId;- List<MachineState> ownedMachines() => app.machineStates.values- .where((m) => !m.belongsToOtherAccount && ownRow(m))- .toList();- ({IconData icon, String message})? unavailable(MachineState m) {- if (!isExisting(m) && contributed.contains(m.machine.machineId)) {- return (icon: AppIcons.circleCheck, message: 'Already in this Swarm');- }- if (m.needsLink) {- return (- icon: AppIcons.unlink,- message: 'Not linked. Link this computer from Machines.',- );- }- if (m.isOffline) {- return (- icon: AppIcons.cloudOff,- message: 'Offline. Open Harness on this computer to add it.',- );- }- return null;- }-- bool canSelect(MachineState? m) =>- m != null && !m.belongsToOtherAccount && unavailable(m) == null;- final addable = ownedMachines().where(canSelect).toList();- String labelFor(MachineState m) => m.isLocalMachine- ? 'This Mac (${m.machine.displayName})'- : m.machine.displayName;- String? machineId =- existingId ??- addable.where((m) => m.isLocalMachine).firstOrNull?.machine.machineId ??- addable.firstOrNull?.machine.machineId;- String? error;- var busy = false;- String? setupId;- // The agent slots the owner is choosing. A machine already in this Swarm- // starts at the number it has; a new one starts at what its total memory- // suggests, worked out here rather than by preparation (below).- int? storedSlots(String? id) {- final row = id == null- ? null- : c.snapshot?.machines.where((m) => m['machineId'] == id).firstOrNull;- final current = row?['maxAgents'];- return current is num ? current.toInt() : null;- }-- // Readings this dialog has taken itself, keyed by machine. The panel's own- // samples stand in for a machine it already reads.- final suggestions = <String, int>{};- final maximums = <String, int>{};-- /// What this machine's own memory says, once a reading has answered. Null- /// while one is still coming, or when it failed.- int? memorySuggestion(String? id) => id == null- ? null- : suggestions[id] ?? _suggestedAgentSlots(_samples[id]?.$1);-- int maximumFor(String? id) => id == null- ? _agentSlotsMin- : maximums[id] ??- _maxAgentSlots(_samples[id]?.$1) ??- _clampAgentSlots(storedSlots(id) ?? _agentSlotsMin);-- int slotsFor(String? id) {- final stored = storedSlots(id);- if (stored != null) return _clampAgentSlots(stored);- return memorySuggestion(id) ?? _agentSlotsMin;- }-- var slots = slotsFor(machineId);- var slotsEdited = false;-- // Machine settings: As memory allows, or At most a number (Dee,- // 2026-10-29). Memory is known from this dialog's reading, the panel's- // sample, or what the machine last reported to the Swarm.- MachineResources? settingsResources() =>- _samples[existingId]?.$1 ?? view?.resources;- int? memoryMaximum() =>- maximums[existingId] ?? _maxAgentSlots(settingsResources());-- // Until the owner touches either, both follow what is known: a stored- // limit at or above the maximum is as memory allows, and one below it is- // the owner's own. With the maximum unknown a stored number is kept, and- // a machine with no number of its own starts at At most its suggestion,- // as Add machine does (review of #2084).- bool? memoryEdited;- int? atMostEdited;- bool memoryChoice() {- if (memoryEdited != null) return memoryEdited!;- final stored = storedSlots(existingId);- final maximum = memoryMaximum();- return stored != null && maximum != null && stored >= maximum;- }-- // With nothing known, every machine may offer four.- int atMostMaximum() =>- memoryMaximum() ??- _clampAgentSlots(storedSlots(existingId) ?? _agentSlotsFloor);- int atMostValue() {- if (atMostEdited != null) return atMostEdited!;- final stored = storedSlots(existingId);- final maximum = memoryMaximum();- if (stored != null && (maximum == null || stored < maximum)) {- return _clampAgentSlots(stored);- }- final suggested =- suggestions[existingId] ?? _suggestedAgentSlots(settingsResources());- return (suggested ?? maximum ?? stored ?? _agentSlotsFloor).clamp(- _agentSlotsMin,- atMostMaximum(),- );- }-- /// Why this machine's settings cannot be saved from here, in settings'- /// own words; null when they can.- String? settingsUnavailable() {- final m = app.stateOf(existingId!);- if (m == null) {- return 'This computer can’t reach that machine. Sign in to Harness '- 'there with this account to change its settings.';- }- // The machine by name: "this computer" is the one you're on.- final name = superTabMachineName(m.machine.displayName);- if (m.belongsToOtherAccount) {- return '$name is signed in to another account.';- }- if (m.needsLink) return 'Not linked. Link $name from Machines.';- if (m.isOffline) {- return 'Offline. Open Harness on $name to change its settings.';- }- return null;- }-- // As memory allows saves the machine's maximum: its own figure from- // setup (it measured the machine just now), else the one known here,- // else what an older Harness's setup offered.- int memoryLimit(Map<String, dynamic> prepared) {- final offeredMaximum = prepared['maxAvailableAgents'];- if (offeredMaximum is num) return _clampAgentSlots(offeredMaximum);- final offered = prepared['maxAgents'];- return memoryMaximum() ??- (offered is num- ? _clampAgentSlots(offered)- : storedSlots(existingId) ?? _agentSlotsFloor);- }-- // The open dialog and its own setState, once it is built: a reading- // answers while the form is open, and the field has to repaint when it- // does. Both are read only while the dialog is still there — one that- // arrives after it closed has nothing to repaint.- BuildContext? dialog;- void Function(void Function())? repaint;- final reading = <String>{};-- /// Start the field where this machine's own memory says, without asking- /// preparation: preparation sets the project up, probes engines and takes- /// one of its 32 setup slots, and opening a form the owner may cancel is- /// no reason to do that. A configured machine still needs its RAM reading- /// for the stepper limit, but its chosen number is never replaced.- Future<void> suggestSlots() async {- final id = machineId;- if (id == null || !canSelect(app.stateOf(id)) || !reading.add(id)) {- return;- }- MachineResources? resources;- try {- resources = await (widget.readLocal ?? app.readMachineResources)(id);- } catch (_) {- return;- }- final suggested = _suggestedAgentSlots(resources);- // The picker may have moved on to another machine, whose own reading is- // the one that belongs in the field now — or the dialog may have closed.- if (suggested == null || machineId != id || dialog?.mounted != true) {- return;- }- suggestions[id] = suggested;- maximums[id] = _maxAgentSlots(resources)!;- // Repaint the limit, but never replace a number the owner chose.- repaint?.call(() {- if (!slotsEdited && storedSlots(id) == null) slots = suggested;- });- }-- await showAppDialog<void>(- context: context,- builder: (context) => SuperTabDialogScope(- controller: c,- child: ListenableBuilder(- listenable: app,- builder: (context, _) => StatefulBuilder(- builder: (context, update) {- dialog = context;- repaint = update;- // Not awaited: the form is usable immediately, and the number- // only has to be there by the time the owner reads it. Each- // machine is read once, so a rebuild does not read again.- unawaited(suggestSlots());- Future<void> save() async {- if (busy ||- !c.canWrite ||- machineId == null ||- !canSelect(app.stateOf(machineId!))) {- return;- }- final selected = machineId!;- // Settings save what is on screen now: preparation below may- // learn a different maximum, and that must not turn the- // owner's At most into As memory allows (review of #2084).- final atMost = isConfigure && !memoryChoice()- ? atMostValue()- : null;- update(() {- busy = true;- error = null;- });- try {- setupId ??= superTabOperationId();- final deadline = DateTime.now().add(- const Duration(minutes: 5),- );- Map<String, dynamic> prepared;- while (true) {- if (!context.mounted || !c.canWrite) return;- prepared = await app.superTabMachineRequest(selected, {- 'action': 'prepareContribution',- 'tabId': c.tabId,- 'scope': 'swarm',- 'operationId': setupId,- });- if (prepared['state'] == 'ready' &&- prepared['scope'] == 'swarm') {- break;- }- if (prepared['state'] != 'preparing') {- throw const SuperTabFailure(- 'UPDATE_REQUIRED',- 'Update Harness on this machine, then try again.',- );- }- if (DateTime.now().isAfter(deadline)) {- throw const SuperTabFailure(- 'SETUP_PENDING',- 'Project setup is still running. Try again to check its progress.',- );- }- await Future<void>.delayed(const Duration(seconds: 1));- }- if (!context.mounted || !c.canWrite) return;- final machine = app.stateOf(selected);- final engines =- (prepared['engines'] as List?)- ?.whereType<String>()- .where((engine) => _chipEngines.contains(engine))- .toSet()- .toList() ??- <String>[];- if (engines.isEmpty) {- throw const SuperTabFailure(- 'NO_SWARM_ENGINE',- 'Install Claude Code or Codex on this machine, then try again.',- );- }- // A machine with no number of its own whose reading failed,- // or had not answered yet, is showing the floor rather than- // a suggestion. The owner never chose that, so send what- // preparation offered instead — the number the field would- // have shown had the reading arrived.- final offered = prepared['maxAgents'];- final offeredMaximum = prepared['maxAvailableAgents'];- if (offeredMaximum is num) {- maximums[selected] = _clampAgentSlots(offeredMaximum);- }- if (!slotsEdited &&- storedSlots(selected) == null &&- memorySuggestion(selected) == null &&- offered is num) {- slots = _clampAgentSlots(offered);- }- // An earlier lost reply leaves an uncertain attempt holding- // its own receipt, and only one action may be in flight:- // check that one first, then send the number the owner is- // looking at — the stored attempt cannot know it was changed.- if (c.pendingCommand?['type'] == 'machine.contribute') {- // If that attempt cannot be confirmed, its own error is- // the one worth showing: it says why it is still unclear.- if (await c.retry() == null) {- if (!context.mounted) return;- throw SuperTabFailure(- c.operationErrorCode ?? 'CONTRIBUTION_FAILED',- c.operationError ??- 'The earlier attempt is still not confirmed. '- 'Try again to check it.',- );- }- if (!context.mounted || !c.canWrite) return;- }- final result = await c.command({- 'type': 'machine.contribute',- 'machineId': selected,- 'name': machine!.machine.displayName,- 'cwd': prepared['cwd'],- if (prepared['scope'] != null) 'scope': prepared['scope'],- 'engines': engines,- 'maxAgents': !isConfigure- ? slots- : atMost ?? memoryLimit(prepared),- });- if (result == null) {- throw SuperTabFailure(- 'CONTRIBUTION_FAILED',- c.operationError ?? 'Could not add this machine.',- );- }- await app.wakeSuperTabHost(selected);- // This Mac, added while its person is here: macOS asks once- // for the Harness Team account (cli/src/team/autoSetup.ts).- if (app.stateOf(selected)?.isLocalMachine == true) {- unawaited(- app.offerTeamAccount('contribute', tabId: c.tabId),- );- }- if (context.mounted) Navigator.pop(context);- } catch (failure) {- if (context.mounted) {- update(() {- busy = false;- error = failure.toString();- if (failure is! SuperTabFailure ||- failure.code != 'SETUP_PENDING') {- setupId = null;- }- });- }- }- }-- final own = ownedMachines();- final canSave =- machineId != null && canSelect(app.stateOf(machineId!));- if (isConfigure) {- final current = app.stateOf(existingId!);- final why = settingsUnavailable();- return SuperTabDetailDialog(- title: superTabMachineName(- current?.machine.displayName ??- existing['name'] as String? ??- existingId,- ),- body: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- _AgentsLimit(- memory: memoryChoice(),- value: atMostValue(),- maximum: atMostMaximum(),- busy: busy,- onMemory: () => update(() => memoryEdited = true),- onAtMost: (next) => update(() {- memoryEdited = false;- atMostEdited = next;- }),- ),- // Why it cannot be removed, in words rather than a dimmed button alone.- if (view != null && _canRemove(view.id))- if (_removeReason(view.id) case final reason?) ...[- const SizedBox(height: grid.AppDesktop.controlGap),- Text(reason, style: DesktopChrome.metadata()),- ],- if (!canSave && why != null) ...[- const SizedBox(height: grid.AppDesktop.controlGap),- Text(why, style: DesktopChrome.metadata()),- ],- if (error != null) ...[- const SizedBox(height: grid.AppDesktop.controlGap),- Text(error!, style: DesktopChrome.metadata()),- ],- ],- ),- // One clear action at the right; the rarer one quiet at the- // left, as in the machine's details.- leadingActions: [- if (view != null && _canRemove(view.id))- TextButton(- style: superTabQuietAction,- onPressed: busy || _removeReason(view.id) != null- ? null- : () {- Navigator.pop(context);- WidgetsBinding.instance.addPostFrameCallback((- _,- ) {- if (mounted) unawaited(_remove(view));- });- },- child: const Text('Remove from this Swarm'),- ),- ],- actions: [- FilledButton(- onPressed: busy || !canSave ? null : save,- child: Text(busy ? 'Saving…' : 'Save'),- ),- ],- );- }- return SuperTabDetailDialog(- title: 'Add machine',- body: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (own.isNotEmpty)- _MachinePicker(- value: machineId,- busy: busy,- choices: [- for (final m in own)- _MachineChoice(- id: m.machine.machineId,- label: labelFor(m),- unavailable: unavailable(m),- ),- ],- onChanged: (id) {- if (busy || !canSelect(app.stateOf(id))) return;- update(() {- machineId = id;- setupId = null;- error = null;- // Another machine has its own number: the one it- // already offers, or its own suggestion.- slots = slotsFor(id);- slotsEdited = false;- });- unawaited(suggestSlots());- },- )- else- Text(- 'No computer is connected to this account yet.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 16),- if (own.isNotEmpty) ...[- Text(- "The Swarm's product managers can start agents here with this machine's signed-in accounts. "- 'They run without asking for permission, in projects cloned to ~/harnesses/swarms.',- style: DesktopChrome.text(),- ),- ] else ...[- Text(- 'To add another computer, install Harness on it and sign in with '- 'this account, or approve a device with no screen from Machines.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 4),- Align(- alignment: Alignment.centerLeft,- child: TextButton(- onPressed: () {- Navigator.pop(context);- app.requestMachines();- },- child: const Text('Open Machines'),- ),- ),- ],- if (own.isNotEmpty) ...[- const SizedBox(height: 16),- _AgentSlots(- value: slots,- maximum: maximumFor(machineId),- busy: busy,- onChanged: (next) => update(() {- slots = next;- slotsEdited = true;- }),- ),- ],- if (error != null) ...[- const SizedBox(height: 12),- Text(error!, style: DesktopChrome.metadata()),- ],- ],- ),- actions: [- if (own.isNotEmpty)- FilledButton(- onPressed: busy || !canSave ? null : save,- child: Text(busy ? 'Preparing…' : 'Add machine'),- ),- ],- );- },- ),- ),- ),+ await _contributeDialog(+ context,+ c,+ app,+ existing: existing,+ view: view,+ sampleOf: (id) => _samples[id]?.$1,+ canRemove: _canRemove,+ removeReason: _removeReason,+ remove: (v) {+ if (mounted) unawaited(_remove(v));+ },+ readLocal: widget.readLocal,);}@@ -1207,9 +1285,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {: '${minutes ~/ 1440}d';}- /// The engines whose allowance a machine row shows, in this order.- static const _chipEngines = ['claude', 'codex'];-/// Everything a machine's row, its tooltip and its details say of it, read once per build._MachineView _view(String id) {final app = widget.app, snapshot = c.snapshot!;diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 36ab4a803..ab3410694 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -831,7 +831,7 @@ class ProjectSidebar extends StatelessWidget {!controller.saving &&!controller.hasPendingAction &&buddyProjects(controller).isNotEmpty- ? () => unawaited(showAddBuddy(context, controller))+ ? () => unawaited(showAddBuddy(context, controller, app: app)): null,addTooltip: 'Add a Buddy',endInset: 0,diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dartindex 25007d1d4..822fb17c3 100644--- a/desktop/lib/super_tabs/roster.dart+++ b/desktop/lib/super_tabs/roster.dart@@ -2,15 +2,18 @@ import 'dart:async';import 'package:flutter/material.dart';+import '../shared/theme/app_icons.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_icon_button.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/finger_target.dart';import '../widgets/engine_identity.dart';import '../widgets/harness_activity_mark.dart';import 'agent_details.dart';@@ -22,7 +25,9 @@ import 'leaderboard/format.dart';import 'leaderboard/model.dart';import 'leaderboard/person_row.dart';import 'leaderboard/reader.dart';+import 'leaderboard/tabs.dart';import 'leaderboard/waiting_line.dart';+import 'leaderboard/worker_rows.dart';import 'model.dart';import 'profile_sheet.dart';import 'section_heading.dart';@@ -67,6 +72,9 @@ class _SuperTabRosterState extends State<SuperTabRoster> {);String? _boardProject;+ /// Which of the board's lists shows: people, agents or models.+ var _tab = LeaderboardTab.humans;+/// The project of the open conversation, whose board Humans show.String get _projectId => c.snapshot?.projectFor(c.selectedId)?.id ?? 'lead';@@ -524,11 +532,11 @@ class _SuperTabRosterState extends State<SuperTabRoster> {final columns = board == null || board.people.isEmpty? null: LeaderboardColumns.of(context, board.people);+ final week = weekName(_board.week, current);return [- SuperTabSectionHeading(- 'Humans',- onAdd: c.isOwner ? widget.onInvite : null,- addTooltip: 'Invite people',+ LeaderboardHeader(+ selected: _tab,+ onSelect: (tab) => setState(() => _tab = tab),actions: [if (board != null || _board.week != null)AppSelectField<int>(@@ -549,6 +557,16 @@ class _SuperTabRosterState extends State<SuperTabRoster> {onChanged: (week) =>unawaited(_board.showWeek(week == current ? null : week)),),+ if (c.isOwner && _tab == LeaderboardTab.humans)+ // A phone's add action is a finger's size, as the headings' is.+ fingerTarget(+ enabled: workspaceIsCompact(context),+ AppIconButton(+ icon: AppIcons.plus,+ tooltip: 'Invite people',+ onPressed: widget.onInvite,+ ),+ ),],),if (_board.error case final error?)@@ -561,27 +579,33 @@ class _SuperTabRosterState extends State<SuperTabRoster> {),child: Text(error, style: DesktopChrome.metadata()),),- for (final person in ranked)- LeaderboardPersonRow(- person: person,- score: scores[person.id],- columns: columns,- own: person.id == c.accountId,- weekName: weekName(_board.week, current),- onTap: () => _person(person, scores[person.id]),- ),- if (board != null && board.waiting.total > 0)- LeaderboardWaitingLine(- waiting: board.waiting,- viewerId: c.accountId,- nameOf: (id) {- final person = state?.people.where((p) => p.id == id).firstOrNull;- return person == null- ? 'Former member'- : leaderboardName(person, scores[id]);- },- onAnswer: widget.onAnswer,- ),+ if (_tab == LeaderboardTab.agents)+ ..._agentScores(board, week)+ else if (_tab == LeaderboardTab.models)+ ..._modelScores(board, week)+ else ...[+ for (final person in ranked)+ LeaderboardPersonRow(+ person: person,+ score: scores[person.id],+ columns: columns,+ own: person.id == c.accountId,+ weekName: week,+ onTap: () => _person(person, scores[person.id]),+ ),+ if (board != null && board.waiting.total > 0)+ LeaderboardWaitingLine(+ waiting: board.waiting,+ viewerId: c.accountId,+ nameOf: (id) {+ final person = state?.people.where((p) => p.id == id).firstOrNull;+ return person == null+ ? 'Former member'+ : leaderboardName(person, scores[id]);+ },+ onAnswer: widget.onAnswer,+ ),+ ],const SizedBox(height: DesktopChrome.groupGap),SuperTabSectionHeading('Agents',@@ -600,6 +624,58 @@ class _SuperTabRosterState extends State<SuperTabRoster> {];}+ /// The project's PM and Buddies, ranked like people (Dee, 2026-10-29).+ List<Widget> _agentScores(SuperTabLeaderboard? board, String week) {+ final scores = board?.agents ?? const <SuperTabAgentScore>[];+ if (board == null) return const [];+ if (scores.isEmpty) {+ return const [LeaderboardEmpty('No PM or Buddy in this project yet')];+ }+ final snapshot = c.snapshot;+ final columns = LeaderboardColumns.measure(+ context,+ ranks: scores.map((s) => s.rank),+ points: scores.map((s) => s.points),+ );+ return [+ for (final score in scores)+ LeaderboardAgentRow(+ score: score,+ agent: snapshot?.agents+ .where((a) => a.id == score.agentId)+ .firstOrNull,+ columns: columns,+ weekName: week,+ projectName: snapshot?.projects+ .where((p) => p.id == board.projectId)+ .firstOrNull+ ?.name,+ ownerName: switch (snapshot?.people+ .where((p) => p.id == score.personId)+ .firstOrNull) {+ final person? => superTabPersonName(person.email),+ null => null,+ },+ ),+ ];+ }++ /// The models the Builders and Reviewers ran on, never the agents.+ List<Widget> _modelScores(SuperTabLeaderboard? board, String week) {+ final scores = board?.byModel ?? const <SuperTabModelScore>[];+ if (board == null) return const [];+ if (scores.isEmpty) return [LeaderboardEmpty('No model worked $week')];+ final columns = LeaderboardColumns.measure(+ context,+ ranks: scores.map((s) => s.rank),+ points: scores.map((s) => s.points),+ );+ return [+ for (final score in scores)+ LeaderboardModelRow(score: score, columns: columns, weekName: week),+ ];+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 3cd191686..8fbe01e09 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -1134,7 +1134,9 @@ class _SuperTabViewState extends State<SuperTabView>if (c.buddiesOn && c.buddyChat(projectId) == null) {// No Buddy here yet: the shortcut offers to add one.if (c.canWrite) {- unawaited(showAddBuddy(context, c, projectId: projectId));+ unawaited(+ showAddBuddy(context, c, projectId: projectId, app: widget.app),+ );}return Future.value(false);}@@ -2585,14 +2587,14 @@ class _SuperTabViewState extends State<SuperTabView>],),),- if (c.operationError != null && !errorInRow)+ if (c.composerError(c.selectedId) != null && !errorInRow)Padding(padding: const EdgeInsets.symmetric(horizontal: 24),child: Row(children: [Expanded(child: Text(- c.operationError!,+ c.composerError(c.selectedId)!,style: DesktopChrome.control(),),),diff --git a/desktop/test/super_tab_agent_line_test.dart b/desktop/test/super_tab_agent_line_test.dartindex f3b37a347..819b94c74 100644--- a/desktop/test/super_tab_agent_line_test.dart+++ b/desktop/test/super_tab_agent_line_test.dart@@ -303,7 +303,7 @@ void main() {tester,) async {await _swarm(tester, agents: [_agent('Atlas', 'm1')]);- expect(find.text('Agents'), findsOneWidget);+ expect(find.text('Agents'), findsWidgets);expect(find.byTooltip('Team at a glance'), findsNothing);expect(find.text('Team at a glance'), findsNothing);});diff --git a/desktop/test/super_tab_attachments_test.dart b/desktop/test/super_tab_attachments_test.dartindex 3dbbb45f8..45f6ce361 100644--- a/desktop/test/super_tab_attachments_test.dart+++ b/desktop/test/super_tab_attachments_test.dart@@ -309,6 +309,27 @@ void main() {await close(tester, controller);});+ testWidgets('a failed upload says so under its own conversation only', (+ tester,+ ) async {+ final (server, controller) = await open(tester);+ server.failUpload = 'two.png';+ controller.attachments('lead').add([HarnessAttachment('two.png', _png)]);+ await tester.pump();+ await tester.tap(send);+ await tester.pumpAndSettle();+ expect(find.text('The file is too large.'), findsOneWidget);++ await controller.select('offline');+ await tester.pumpAndSettle();+ expect(find.text('The file is too large.'), findsNothing);++ await controller.select('lead');+ await tester.pumpAndSettle();+ expect(find.text('The file is too large.'), findsOneWidget);+ await close(tester, controller);+ });+testWidgets('a failed upload keeps the draft and the files, and a retry ''sends only the file that did not go up', (tester) async {final (server, controller) = await open(tester);@@ -326,7 +347,7 @@ void main() {expect(server.posts, isEmpty);expect(controller.draft('lead'), 'Look');expect(names(controller), ['one.png', 'two.png']);- expect(controller.operationError, 'The file is too large.');+ expect(controller.composerError('lead'), 'The file is too large.');expect(find.text('The file is too large.'), findsOneWidget);expect(controller.uploading, isFalse);@@ -427,7 +448,7 @@ void main() {expect(token?.isCancelled, isTrue);expect(controller.uploading, isFalse);expect(- controller.operationError,+ controller.composerError('lead'),'The upload stopped moving. Try again.',);expect(names(controller), ['a.png']);@@ -477,7 +498,7 @@ void main() {expect(token?.isCancelled, isTrue);expect(controller.uploading, isFalse);- expect(controller.operationError, isNull);+ expect(controller.composerError('lead'), isNull);expect(names(controller), ['b.png']);expect(server.posts, isEmpty);await close(tester, controller);diff --git a/desktop/test/super_tab_buddy_add_machine_test.dart b/desktop/test/super_tab_buddy_add_machine_test.dartnew file mode 100644index 000000000..4c3e79260--- /dev/null+++ b/desktop/test/super_tab_buddy_add_machine_test.dart@@ -0,0 +1,166 @@+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/buddies.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/identity.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;+import 'support/capture.dart';++/// Add a Buddy for a person with no machine in the Swarm (Scholes, 10-29): the+/// dialog offers this computer through the Add machine flow instead of ending.+/// Set to a folder to write the PR's pictures there.+final shots = Platform.environment['SUPER_TAB_BUDDY_SHOTS'];++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ Future<({SuperTabLaunchFixture f, SuperTabController c})> open(+ WidgetTester tester, {+ Brightness brightness = Brightness.light,+ void Function(SuperTabLaunchFixture f)? prepare,+ }) async {+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final server = f.connection.server;+ server.state['buddies'] = true;+ server.state['machines'] = <dynamic>[];+ server.state['project'] = {+ 'machineId': 'm',+ 'cwd': '/work/project',+ 'scope': 'swarm',+ 'repositoryUrl': null,+ };+ prepare?.call(f);+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showAddBuddy(context, c, app: f.app),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ return (f: f, c: c);+ }++ Future<void> close(+ WidgetTester tester,+ SuperTabLaunchFixture f,+ SuperTabController c,+ ) async {+ debugDefaultTargetPlatformOverride = null;+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ }++ final addThisMac = find.widgetWithText(TextButton, 'Add this Mac');+ final submit = find.widgetWithText(FilledButton, 'Add Buddy');++ testWidgets(+ 'with no machine of theirs in the Swarm, it offers to add this Mac',+ (tester) async {+ final (:f, :c) = await open(tester);++ expect(+ find.text('None of your machines is in this Swarm yet.'),+ findsOneWidget,+ );+ expect(addThisMac, findsOneWidget);+ expect(+ find.textContaining('Add one of yours to this Swarm first'),+ findsNothing,+ );+ expect(tester.widget<FilledButton>(submit).onPressed, isNull);+ await close(tester, f, c);+ },+ );++ testWidgets('adding this Mac returns to Add a Buddy with it selected', (+ tester,+ ) async {+ final (:f, :c) = await open(tester);+ final name = f.app.stateOf('m')!.machine.displayName;++ await tester.tap(addThisMac);+ await tester.pumpAndSettle();+ expect(find.text('Add machine'), findsWidgets);+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(seconds: 1));+ }+ await tester.pumpAndSettle();++ expect(find.text('Add a Buddy'), findsOneWidget);+ expect(find.text('Add machine'), findsNothing);+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-buddy-machine')),+ matching: find.text(superTabMachineName(name)),+ ),+ findsOneWidget,+ );+ expect(tester.widget<FilledButton>(submit).onPressed, isNotNull);+ expect(addThisMac, findsNothing);+ await close(tester, f, c);+ });++ testWidgets('a computer that cannot be added shows the flow\'s own reason', (+ tester,+ ) async {+ final (:f, :c) = await open(+ tester,+ prepare: (f) => f.app.machineStates['m']!.nodeOnline = false,+ );++ expect(+ find.text('Offline. Open Harness on this computer to add it.'),+ findsOneWidget,+ );+ expect(tester.widget<TextButton>(addThisMac).onPressed, isNull);+ expect(tester.widget<FilledButton>(submit).onPressed, isNull);+ await close(tester, f, c);+ });++ for (final brightness in Brightness.values) {+ testWidgets('pictures in ${brightness.name}', (tester) async {+ if (shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final (:f, :c) = await open(tester, brightness: brightness);+ await captureWindow(tester, shots, 'buddy-no-machine-${brightness.name}');+ await tester.tap(addThisMac);+ await tester.pumpAndSettle();+ await captureWindow(+ tester,+ shots,+ 'buddy-add-machine-${brightness.name}',+ );+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(seconds: 1));+ }+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'buddy-added-${brightness.name}');+ await close(tester, f, c);+ });+ }+}diff --git a/desktop/test/super_tab_composer_error_test.dart b/desktop/test/super_tab_composer_error_test.dartnew file mode 100644index 000000000..61b5f1d8d--- /dev/null+++ b/desktop/test/super_tab_composer_error_test.dart@@ -0,0 +1,172 @@+// A composer's upload error belongs to its conversation, and a refused upload+// says why.+import 'dart:async';+import 'dart:typed_data';++import 'package:dio/dio.dart' show RequestOptions, Response;+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/harness_attachments.dart';+import 'package:harness/super_tabs/attachment_upload.dart';+import 'package:harness/super_tabs/controller.dart';++import 'support/super_tab_fixture.dart';++final _png = Uint8List.fromList([1, 2, 3]);++void main() {+ group('the composer error is per conversation', () {+ late ConversationServer server;+ late SuperTabController c;++ setUp(() async {+ server = ConversationServer();+ c = server.controller();+ await c.refresh();+ });+ tearDown(() => c.dispose());++ test('refused in one conversation, it shows only there', () async {+ server.failUpload = 'a.png';+ c.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ await c.send();+ expect(c.composerError('lead'), 'The file is too large.');++ await c.select('offline');+ expect(c.composerError('offline'), isNull);++ await c.select('lead');+ expect(c.composerError('lead'), 'The file is too large.');+ });++ test('each conversation keeps its own', () async {+ server.failUpload = 'a.png';+ c.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ await c.send();+ await c.select('offline');+ server.failUploadCode = 'OTHER';+ c.attachments('offline').add([HarnessAttachment('a.png', _png)]);+ await c.send();++ expect(c.composerError('offline'), 'The file is too large.');+ expect(c.composerError('lead'), 'The file is too large.');+ // Another conversation's upload starting clears only its own.+ server.failUpload = null;+ await c.send();+ expect(c.composerError('offline'), isNull);+ expect(c.composerError('lead'), 'The file is too large.');+ });++ Future<void> refuseFile() async {+ server.failUpload = 'a.png';+ c.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ await c.send();+ expect(c.composerError('lead'), 'The file is too large.');+ }++ test('taking the file off clears the refusal', () async {+ await refuseFile();+ c.attachments('lead').clear();+ expect(c.composerError('lead'), isNull);+ });++ test(+ 'a text-only send that goes through clears a resolved refusal',+ () async {+ await refuseFile();+ c.attachments('lead').clear();+ c.setDraft('lead', 'Send without the file');+ expect(await c.send(), isNotNull);+ expect(server.posts, isNotEmpty);+ expect(c.composerError('lead'), isNull);+ },+ );++ test('a send blocked afterwards says why, over the old refusal', () async {+ await refuseFile();+ c.attachments('lead').clear();+ c.setDraft('lead', 'Hello');+ await c.send(recipients: ['no-longer-present']);+ expect(c.operationError, contains('mentioned agent'));+ expect(c.composerError('lead'), c.operationError);+ });++ test('an upload still running at a switch fails into its own '+ 'conversation, not the one now shown', () async {+ final gate = Completer<Map<String, dynamic>>();+ c.dispose();+ c = server.controller(+ upload: ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) => gate.future,+ );+ await c.refresh();+ c.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ final sending = c.send();+ await Future<void>.delayed(Duration.zero);+ expect(c.uploading, isTrue);++ await c.select('offline');+ gate.completeError(+ const SuperTabFailure('FORBIDDEN', 'No files here.', statusCode: 403),+ );+ await sending;++ expect(c.composerError('offline'), isNull);+ await c.select('lead');+ expect(c.composerError('lead'), 'No files here.');+ });+ });++ group('superTabUploadRefusal', () {+ Response<dynamic> answer(int status, Object? body) => Response(+ requestOptions: RequestOptions(),+ statusCode: status,+ data: body,+ );++ test('reads a body Dio left as a String', () {+ final failure = superTabUploadRefusal(+ answer(403, '{"success":false,"error":{"code":"X","message":"M"}}'),+ );+ expect(failure.message, 'M');+ expect(failure.code, 'X');+ expect(failure.statusCode, 403);+ });++ test('names a code it has no words for', () {+ final failure = superTabUploadRefusal(+ answer(403, {'error': 'FORBIDDEN_HOST'}),+ );+ expect(failure.code, 'FORBIDDEN_HOST');+ expect(+ failure.message,+ 'Could not upload the file (FORBIDDEN_HOST). Try again.',+ );+ });++ test('a body that says nothing keeps the plain words', () {+ expect(+ superTabUploadRefusal(answer(500, 'oops')).message,+ 'Could not upload the file. Try again.',+ );+ });++ test('the codes it knows keep their words', () {+ expect(+ superTabUploadRefusal(answer(403, {'error': 'FORBIDDEN'})).message,+ 'You can’t send files in this conversation.',+ );+ expect(+ superTabUploadRefusal(answer(413, {'error': 'ATTACHMENT_TOO_LARGE'}))+ .message,+ 'That file is over 10 MB.',+ );+ });+ });+}diff --git a/desktop/test/super_tab_leaderboard_tabs_test.dart b/desktop/test/super_tab_leaderboard_tabs_test.dartnew file mode 100644index 000000000..ed7aee1d9--- /dev/null+++ b/desktop/test/super_tab_leaderboard_tabs_test.dart@@ -0,0 +1,314 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/leaderboard/model.dart';+import 'package:harness/super_tabs/leaderboard/worker_rows.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/humans_fixture.dart';+import 'support/super_tab_fixture.dart';++/// Agents and Models beside Humans on the leaderboard (Dee, 2026-10-29):+/// "permanent and temp workers, just like humans". Agents are the PM and the+/// Buddies by name; Models are the Builders and Reviewers by what they ran on,+/// never by agent. Both keep the one-number rows and the crown.+ConversationServer tabsSwarm({bool empty = false}) {+ final server = humansSwarm();+ final agents = server.state['agents'] as List;+ (agents.first as Map)['machineId'] = 'studio';+ server.state['agents'] = <Object>[+ ...agents,+ <String, dynamic>{+ ...(agents.first as Map).cast<String, dynamic>(),+ 'id': 'sparky',+ 'harnessId': 'h-sparky',+ 'name': 'Sparky',+ 'displayName': 'Sparky',+ 'buddyOf': {'personId': 'peer', 'generation': 'g'},+ },+ ];+ server.leaderboard!['agents'] = empty+ ? <Map<String, dynamic>>[]+ : [+ {+ 'agentId': 'lead-agent',+ 'displayName': 'River',+ 'kind': 'pm',+ 'personId': null,+ 'machineId': 'studio',+ 'points': 36,+ 'rank': 1,+ 'shipped': 12,+ },+ {+ 'agentId': 'sparky',+ 'displayName': 'Sparky',+ 'kind': 'buddy',+ 'personId': 'peer',+ 'machineId': 'studio',+ 'points': 12,+ 'rank': 2,+ 'shipped': 4,+ },+ ];+ Map<String, dynamic> model(+ String engine,+ String? model,+ String? effort,+ int points,+ int rank, {+ int shipped = 0,+ int? attemptMs,+ int? requestMs,+ int reviewed = 0,+ int passed = 0,+ int reviews = 0,+ }) => {+ 'engine': engine,+ 'model': model,+ 'effort': effort,+ 'grid': false,+ 'points': points,+ 'rank': rank,+ 'shipped': {+ 'count': shipped,+ 'medianAttemptMs': attemptMs,+ 'medianRequestMs': requestMs,+ },+ 'firstReview': {'reviewed': reviewed, 'passed': passed},+ 'reviews': reviews,+ };+ server.leaderboard!['byModel'] = empty+ ? <Map<String, dynamic>>[]+ : [+ model(+ 'claude',+ 'opus',+ 'high',+ 93,+ 1,+ shipped: 31,+ attemptMs: 47 * 60000,+ requestMs: 3 * 3600000,+ reviewed: 34,+ passed: 28,+ ),+ model('codex', 'gpt-5.5', null, 52, 2, shipped: 17),+ model('codex', 'gpt-5.5', 'medium', 5, 3, reviews: 5),+ ];+ return server;+}++void main() {+ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ await tester.binding.setSurfaceSize(const Size(1300, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final controller = server.controller(+ account: 'peer',+ initial: {'tabId': 'tab', 'accountId': 'peer', 'selectedId': 'lead'},+ );+ await controller.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: controller,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return controller;+ }++ Future<void> close(WidgetTester tester, SuperTabController controller) async {+ await tester.pumpWidget(const SizedBox());+ await controller.flush();+ controller.dispose();+ }++ Finder tab(String name) => find.byKey(ValueKey('leaderboard-tab-$name'));+ Finder row(String id) => find.byKey(ValueKey('leaderboard-row-$id'));+ Finder inRow(String id, Finder finder) =>+ find.descendant(of: row(id), matching: finder);+ Future<void> open(WidgetTester tester, String name) async {+ await tester.ensureVisible(tab(name));+ await tester.tap(tab(name));+ await tester.pumpAndSettle();+ }++ testWidgets(+ 'offers Humans, Agents and Models beside the week, Humans first',+ (tester) async {+ final semantics = tester.ensureSemantics();+ final controller = await show(tester, tabsSwarm());+ for (final name in ['humans', 'agents', 'models']) {+ expect(tab(name), findsOneWidget, reason: name);+ }+ expect(tester.getSemantics(tab('humans')), isSemantics(isSelected: true));+ expect(find.byKey(const ValueKey('super-person-peer')), findsOneWidget);+ await open(tester, 'agents');+ expect(find.byKey(const ValueKey('super-person-peer')), findsNothing);+ expect(row('agent-lead-agent'), findsOneWidget);+ expect(tester.getSemantics(tab('agents')), isSemantics(isSelected: true));+ // The week stays where it was.+ expect(find.byKey(const ValueKey('leaderboard-week')), findsOneWidget);+ semantics.dispose();+ await close(tester, controller);+ },+ );++ testWidgets(+ 'lists the PM and Buddies by name: role, what they shipped, one number, a crown for #1',+ (tester) async {+ final semantics = tester.ensureSemantics();+ final controller = await show(tester, tabsSwarm());+ await open(tester, 'agents');+ expect(+ inRow('agent-lead-agent', find.textContaining('River')),+ findsOneWidget,+ );+ expect(+ inRow('agent-lead-agent', find.textContaining('PM · Pilot')),+ findsOneWidget,+ );+ expect(+ inRow('agent-lead-agent', find.text('12 shipped')),+ findsOneWidget,+ );+ expect(inRow('agent-lead-agent', find.text('36')), findsOneWidget);+ expect(+ inRow('agent-sparky', find.textContaining('Buddy · ken.tran')),+ findsNothing,+ );+ expect(+ inRow('agent-sparky', find.textContaining('Buddy · dee')),+ findsOneWidget,+ );+ expect(+ inRow('agent-sparky', find.text('4 proposals shipped')),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('leaderboard-crown-agent-lead-agent')),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('leaderboard-crown-agent-sparky')),+ findsNothing,+ );+ expect(+ find.bySemanticsLabel(RegExp('Number one this week')),+ findsOneWidget,+ );+ // The points share one right-aligned column.+ expect(+ tester.getTopRight(inRow('agent-lead-agent', find.text('36'))).dx,+ tester.getTopRight(inRow('agent-sparky', find.text('12'))).dx,+ );+ semantics.dispose();+ await close(tester, controller);+ },+ );++ testWidgets(+ 'lists models by what they ran on, never an agent\'s name, with their numbers in words',+ (tester) async {+ final controller = await show(tester, tabsSwarm());+ await open(tester, 'models');+ final opus = 'model-claude-opus-high', codex = 'model-codex-gpt-5.5-';+ final reviewer = 'model-codex-gpt-5.5-medium';+ expect(inRow(opus, find.textContaining('Opus · high')), findsOneWidget);+ // What fits of the line, whole items from its start; all of it on hover.+ const line = '31 shipped · 82% passed first review · 47 min to ship';+ final shown = tester+ .widget<Text>(+ find.descendant(+ of: find.byKey(ValueKey('leaderboard-numbers-$opus')),+ matching: find.byType(Text),+ ),+ )+ .data!;+ expect(shown, startsWith('31 shipped'));+ expect(+ shown == line || line.substring(shown.length).startsWith(' · '),+ isTrue,+ reason: shown,+ );+ expect(inRow(opus, find.text('93')), findsOneWidget);+ expect(inRow(codex, find.textContaining('GPT-5.5')), findsOneWidget);+ expect(inRow(codex, find.text('17 shipped')), findsOneWidget);+ expect(+ inRow(reviewer, find.textContaining('GPT-5.5 · medium')),+ findsOneWidget,+ );+ expect(inRow(reviewer, find.text('5 reviews')), findsOneWidget);+ // The time from the request's first attempt is on hover.+ expect(+ find.byTooltip(+ '31 shipped · 28 of 34 passed first review · 47 min from the shipping attempt, 3 h from the first',+ ),+ findsOneWidget,+ );+ expect(find.byKey(ValueKey('leaderboard-crown-$opus')), findsOneWidget);+ // Workers are never named: no agent's name in the list.+ for (final id in [opus, codex, reviewer]) {+ expect(inRow(id, find.textContaining('River')), findsNothing);+ }+ expect(+ tester.getTopRight(inRow(opus, find.text('93'))).dx,+ tester.getTopRight(inRow(reviewer, find.text('5'))).dx,+ );+ await close(tester, controller);+ },+ );++ testWidgets('says so when no agent or model has anything this week', (+ tester,+ ) async {+ final controller = await show(tester, tabsSwarm(empty: true));+ await open(tester, 'agents');+ expect(find.text('No PM or Buddy in this project yet'), findsOneWidget);+ await open(tester, 'models');+ expect(find.text('No model worked this week'), findsOneWidget);+ await close(tester, controller);+ });++ test('writes a model\'s numbers in words, a share as a whole percent, zeros left out', () {+ SuperTabModelScore score(Map<String, dynamic> extra) =>+ SuperTabModelScore.fromJson({+ 'engine': 'claude',+ 'model': 'opus',+ ...extra,+ });+ final opus = score({+ 'shipped': {+ 'count': 31,+ 'medianAttemptMs': 47 * 60000,+ 'medianRequestMs': 3 * 3600000,+ },+ 'firstReview': {'reviewed': 34, 'passed': 28},+ });+ expect(leaderboardModelNumbers(opus), [+ '31 shipped',+ '82% passed first review',+ '47 min to ship',+ ]);+ expect(leaderboardModelNumbers(opus, full: true), [+ '31 shipped',+ '28 of 34 passed first review',+ '47 min from the shipping attempt, 3 h from the first',+ ]);+ expect(leaderboardModelNumbers(score({'reviews': 1})), ['1 review']);+ expect(leaderboardModelNumbers(score({})), isEmpty);+ });+}diff --git a/desktop/test/super_tab_picker_test.dart b/desktop/test/super_tab_picker_test.dartindex 0dec81fe1..945b4cb3c 100644--- a/desktop/test/super_tab_picker_test.dart+++ b/desktop/test/super_tab_picker_test.dart@@ -1,4 +1,3 @@-import 'dart:convert';import 'dart:io';import 'dart:ui' as ui;@@ -16,6 +15,7 @@ import 'package:harness/state/harness_placement.dart';import 'package:harness/state/new_harness.dart';import 'package:harness/state/swarm_catalog.dart';import 'package:harness/super_tabs/project_sidebar.dart';+import 'package:harness/widgets/desktop_chrome.dart';import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/widgets/swarm_switcher.dart';@@ -222,7 +222,15 @@ void main() {final shared = f.app.activeSwarm;expect(find.text('Add agent to Pilot'), findsOneWidget);expect(find.text('Starts in Offline editing.'), findsOneWidget);- expect(find.text('Models'), findsNothing);+ // The picker has no Models scope (the leaderboard's Models list sits+ // behind it, outside the picker).+ expect(+ find.descendant(+ of: find.byType(DesktopDialogSurface),+ matching: find.text('Models'),+ ),+ findsNothing,+ );expect(find.text('Store'), findsNothing);final search = tester.widget<SwarmSearchResults>(find.byType(SwarmSearchResults))diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex d81384a9f..92095e54c 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -660,6 +660,21 @@ class ConversationServer {..['resolvedBy'] = 'done';state['mentionsWaiting'] = (state['mentionsWaiting'] as int) - 1;revision++;+ } else if (command['type'] == 'machine.contribute') {+ // As the backend: the reader's machine is in the Swarm, whole.+ state['machines'] = <dynamic>[+ ...state['machines'] as List? ?? const [],+ {+ 'machineId': command['machineId'],+ 'name': command['name'],+ 'contributorId': reader ?? 'owner',+ 'scope': command['scope'],+ 'engines': command['engines'],+ 'maxAgents': command['maxAgents'],+ 'availableSlots': command['maxAgents'],+ },+ ];+ revision++;} else if (command['type'] == 'buddy.create') {// As the backend's Buddy create: a start for the reader's Buddy and// its chat, fixed per person and project. The fixture's host starts itdiff --git a/desktop/test/swarm_projects_test.dart b/desktop/test/swarm_projects_test.dartindex 660079e8d..c72faa0ab 100644--- a/desktop/test/swarm_projects_test.dart+++ b/desktop/test/swarm_projects_test.dart@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_icons.dart';import 'package:harness/super_tabs/view.dart';+import 'package:harness/super_tabs/section_heading.dart';import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/project_visibility.dart';@@ -70,7 +71,14 @@ void main() {expect(find.text('Leads'), findsNothing);expect(find.text('Projects'), findsOneWidget);expect(find.text('Humans'), findsOneWidget);- expect(find.text('Agents'), findsOneWidget);+ // The roster's heading; the leaderboard's Agents pill is the other one.+ expect(+ find.descendant(+ of: find.byType(SuperTabSectionHeading),+ matching: find.text('Agents'),+ ),+ findsOneWidget,+ );final create = find.byTooltip('New project');final project = find.byKey(const ValueKey('super-group-lead'));expect(diff --git a/docs/swarms.md b/docs/swarms.mdindex 7f03c7425..13e77fbb8 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -188,8 +188,8 @@ product manager can see what its terminal shows.A Buddy is a person's own agent in one project. They brainstorm with it in a chat that only they and their Buddy read:it asks what they want and why, offers two or three options with the one it recommends, and agrees the scope with-them. When they say to send it to the product manager, it posts one proposal (goal, scope and priority) in the project-chat. The proposal is addressed to the product manager and marked as on that person's behalf. The product manager assigns+them. When they say to send it to the product manager, it posts one proposal (goal, scope and priority, and up to five+files such as a plan, spec, log or screenshot) in the project chat. The proposal is addressed to the product manager and marked as on that person's behalf. The product manager assignsthe work as usual; a Buddy never assigns work, starts agents, changes code or opens pull requests.The Swarm's owner turns Buddies on for the Swarm; they are off until then. Turning them off removes every Buddy, fails@@ -216,6 +216,11 @@ any still starting, and stops their posts. Their chats stay for their owners to- Nobody else is ever added to a Buddy chat, the Swarm's owner and the product manager included.- A proposal is sent only for its owner's own message in their Buddy chat that asked for it: their newest message there,or one from the last hour, and only once for each such message. The server writes the "on behalf of" label, so a Buddy cannot leave it out or change it.+- A proposal's files are only ones its owner handed it: a file inside the Buddy's own copy of the project (checked by+ its real path on its own machine, so never through a link out of it, and never the repository's or Harness's own+ records), or a file its owner sent in their Buddy chat. Each file has a chat file's limits (10 MB). The server accepts+ a Buddy's file only in its own chat and only on a proposal, so it cannot post a file in the project chat any other way.+ The files show on the proposal message like any message's files, for the product manager and every member.- Nobody else reads a Buddy chat: not the product manager, and not the project's or the Swarm's owner. Private mattersstay there; the Buddy posts only what its owner asks it to send.- Removing a Buddy, the owner leaving the Swarm, or deleting the project closes its session. Adding a Buddy again