Skip to content

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

In the Swarm, a Mac with a Harness Team account is one machine (#1700)

Deeb303eaf3a290
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
index feb9fd8cf..939900f9f 100644
--- a/backend/integration/superTabTeam.test.ts
+++ b/backend/integration/superTabTeam.test.ts
@@ -432,3 +432,41 @@ describe('a teammate\'s work and the machines that take it', () => {
await expect(run(f.tab, { type: 'work.assign', conversationId: f.teamGroup, agentId: old })).rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED' })
})
})
+
+// One machine (docs/plans/2026-10-24-swarm-team-account.md): the person's Mac and its Harness Team account are one
+// machine. Its team account joins where the Mac is added, through the Mac's own daemon, and takes the teammates' work
+// started on the Mac.
+describe('one machine: a Mac and its Harness Team account', () => {
+ it('the Mac\'s host adds its team account, which then takes the owner\'s project started on the Mac', async () => {
+ await db.machine.update({ where: { machineId: 'team-mac' }, data: { hostMachineId: 'personal-mac' } })
+ try {
+ const tab = (await store.create(owner, randomUUID(), 'One machine')).id
+ const invitation = await run(tab, { type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)
+ await run(tab, { type: 'machine.contribute', machineId: 'personal-mac', name: 'MacBook Pro', cwd: '/work', scope: 'swarm', engines: ['codex'], maxAgents: 3 }, person)
+ const joins = async () => (await store.hostTabs(person, 'personal-mac')).filter(r => r.tabId === tab && 'joinTeam' in r)
+ expect(await joins()).toEqual([{ tabId: tab, joinTeam: { machineId: 'team-mac', name: 'MacBook Pro', maxAgents: 3 } }])
+ // The team account's own daemon is never asked, and cannot add itself.
+ expect((await store.hostTabs(team, 'team-mac')).some(r => 'joinTeam' in r)).toBe(false)
+ await expect(store.execute(team, tab, { operationId: randomUUID(), command: { type: 'machine.contribute', machineId: 'team-mac', name: 'x', cwd: '/team',
+ scope: 'swarm', engines: ['codex'], maxAgents: 1, ifMissing: true } })).rejects.toMatchObject(LIMITED)
+ // The Mac's host adds it, as the person: the backend gives it the Mac's name and slots, and the Mac it lives on.
+ await run(tab, { type: 'machine.contribute', machineId: 'team-mac', name: 'MacBook Pro · Team', cwd: '/team', scope: 'swarm', engines: ['codex'],
+ maxAgents: 1, ifMissing: true }, person)
+ expect(await joins()).toEqual([])
+ const listed = (await store.read(owner, tab)).state.machines!.find(m => m.machineId === 'team-mac')!
+ expect(listed).toMatchObject({ hostMachineId: 'personal-mac', name: 'MacBook Pro', maxAgents: 3, cwd: '/team' })
+ const generation = (await store.hostPools(team, 'team-mac')).find(p => p.tabId === tab)!.machine.generation
+ await store.observeMachine(team, tab, 'team-mac', reading(generation))
+ const group = String((await run(tab, { type: 'conversation.create', projectId: 'lead', title: 'Work', brief: 'Do it',
+ checks: [{ description: 'Verified', independent: false }] })).result.conversationId)
+ const started = await run(tab, { type: 'agent.start', request: { conversationId: group, machineId: 'personal-mac', engine: 'codex', name: 'Builder',
+ cwd: '/work/lead', worktree: false, requirements } })
+ const queued = (await store.hostPools(team, 'team-mac')).find(p => p.tabId === tab)!.starts
+ expect(queued).toEqual([expect.objectContaining({ id: started.result.startId, request: expect.objectContaining({ machineId: 'team-mac', cwd: '/team/lead' }) })])
+ expect((await store.hostPools(person, 'personal-mac')).find(p => p.tabId === tab)!.starts).toEqual([])
+ } finally {
+ await db.machine.update({ where: { machineId: 'team-mac' }, data: { hostMachineId: null } })
+ }
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index d8a0f6030..f0f0212fd 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -246,6 +246,11 @@ model Machine {
// normal sign-in serves. Null on rows that predate it (never a team machine). A team session acts only for a
// row marked `team`; Swarm routing reads it (Task 3 of docs/plans/2026-10-24-swarm-team-account.md).
sessionKind String?
+ // A team machine's Mac: the machineId of the owner's own machine on the computer whose Harness Team account this
+ // is, so every list shows that Mac once ("One machine" in docs/plans/2026-10-24-swarm-team-account.md). Copied from
+ // the team session (`HarnessSession.hostMachineId`) whenever that session registers its machine; nothing a team
+ // session sends sets it. Null for every other machine, a dedicated one (`harness team on`) included.
+ hostMachineId String?
// Version string the CLIENT reported on its LAST adapter-ws connect (remote machines only) — the
// client sends it as `?v=` and it is overwritten every time, so it reflects the most recent connect.
// Self-declared and sanitized at the upgrade; null for a machine that never connected or a client
@@ -1327,6 +1332,9 @@ model HarnessSession {
kind String?
/// With `kind: team`: the computer it is bound to (normalized, lib/deviceAuth.ts:normalizeComputerId).
computerId String?
+ /// With `kind: team`: the machine of the Mac whose team account this is, recorded when the code was minted
+ /// (routes/auth.ts) and copied onto the team machine (`Machine.hostMachineId`). Null for a dedicated machine.
+ hostMachineId String?
createdAt DateTime @default(now())
lastUsedAt DateTime @default(now())
/// Slides forward on every refresh: a phone in use stays signed in, one left in a drawer does not.
diff --git a/backend/src/lib/harnessSession.test.ts b/backend/src/lib/harnessSession.test.ts
index f7df13b7b..ef3eb331a 100644
--- a/backend/src/lib/harnessSession.test.ts
+++ b/backend/src/lib/harnessSession.test.ts
@@ -591,3 +591,114 @@ describe('team sessions — a computer turning itself into a team machine', () =
}
})
})
+
+// One machine (docs/plans/2026-10-24-swarm-team-account.md): a Mac's team account is a mechanism under the scenes, so
+// every list shows that Mac once. Its team machine records the Mac it lives on: the minting computer's own machine, or,
+// from an Autonomous sign-in, the machine the CLI names, which must be one of the account's ordinary machines here.
+describe('team sessions — the Mac a team account lives on', () => {
+ const LAPTOP = 'efefefefefefefefefefefefefefefef'
+ const TEAM = 'abababababababababababababababab'
+ let app: FastifyInstance
+ const signedIn = { sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod' as const }
+ beforeEach(async () => {
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ registerAuthMiddleware(app, async (token, env, opts) => token === 'sso-token' ? signedIn : authenticateAccessToken(token, env, opts))
+ await app.register(authRoutes)
+ await app.ready()
+ fakes.machines.push(
+ { userId: USER.id, computerId: LAPTOP, machineId: 'laptop-machine', autonomousEnv: 'prod', sessionKind: 'computer' },
+ { userId: USER.id, computerId: 'c'.repeat(32), machineId: 'other-machine', autonomousEnv: 'prod', sessionKind: 'computer' },
+ { userId: USER.id, computerId: 'd'.repeat(32), machineId: 'older-machine', autonomousEnv: 'prod' },
+ { userId: 'u2', computerId: 'e'.repeat(32), machineId: 'their-machine', autonomousEnv: 'prod', sessionKind: 'computer' },
+ { userId: USER.id, computerId: '1'.repeat(32), machineId: 'stag-machine', autonomousEnv: 'stag', sessionKind: 'computer' },
+ { userId: USER.id, computerId: '2'.repeat(32), machineId: 'gone-machine', autonomousEnv: 'prod', sessionKind: 'computer', deletedAt: new Date() },
+ { userId: USER.id, computerId: '3'.repeat(32), machineId: 'dedicated-machine', autonomousEnv: 'prod', sessionKind: 'team' },
+ )
+ })
+ const mint = (authorization: string, payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/auth/handoff', headers: { authorization }, payload })
+ const redeem = (code: string) => app.inject({ method: 'POST', url: '/api/auth/handoff/redeem', payload: { code, label: 'MacBook Pro · Team', computerId: TEAM } })
+ const handoffCodes = () => [...fakes.redis.keys()].filter((key) => key.startsWith('hnauth:handoff:'))
+ function computerSession(id: string, computerId?: string): string {
+ const token = newHarnessToken(HARNESS_ACCESS_PREFIX)
+ fakes.sessions.push({ id, userId: USER.id, label: 'MacBook Pro', kind: 'computer', refreshHash: `unused-${id}`, ...(computerId ? { computerId } : {}) })
+ fakes.redis.set(`hnauth:access:${harnessTokenHash(token)}`, JSON.stringify({ sessionId: id, userId: USER.id }))
+ return token
+ }
+
+ it('a computer signed in by QR records its own machine, named or not', async () => {
+ const laptop = computerSession('laptop-session', LAPTOP)
+ for (const payload of [{ kind: 'team' }, { kind: 'team', hostMachineId: 'laptop-machine' }]) {
+ const minted = await mint(`Bearer ${laptop}`, payload)
+ expect(minted.statusCode, minted.body).toBe(200)
+ expect((await redeem(minted.json().data.code)).statusCode).toBe(200)
+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'team', computerId: TEAM, hostMachineId: 'laptop-machine' })
+ }
+ })
+
+ it('a computer session may name any of its own computer\'s machines', async () => {
+ fakes.machines.push({ userId: USER.id, computerId: LAPTOP, machineId: 'laptop-second', autonomousEnv: 'prod', sessionKind: 'computer' })
+ const minted = await mint(`Bearer ${computerSession('laptop-session', LAPTOP)}`, { kind: 'team', hostMachineId: 'laptop-second' })
+ expect(minted.statusCode, minted.body).toBe(200)
+ expect((await redeem(minted.json().data.code)).statusCode).toBe(200)
+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'team', hostMachineId: 'laptop-second' })
+ })
+
+ it('a computer session may not name another machine as its Mac', async () => {
+ const res = await mint(`Bearer ${computerSession('laptop-session', LAPTOP)}`, { kind: 'team', hostMachineId: 'other-machine' })
+ expect(res.statusCode).toBe(403)
+ expect(res.json().error.code).toBe('HANDOFF_NOT_ALLOWED')
+ expect(handoffCodes()).toEqual([])
+ })
+
+ it('an Autonomous sign-in names its own machine, which is recorded', async () => {
+ for (const hostMachineId of ['laptop-machine', 'older-machine']) {
+ const minted = await mint('Bearer sso-token', { kind: 'team', hostMachineId })
+ expect(minted.statusCode, minted.body).toBe(200)
+ expect((await redeem(minted.json().data.code)).statusCode).toBe(200)
+ expect(fakes.sessions.at(-1)).toMatchObject({ kind: 'team', hostMachineId })
+ }
+ })
+
+ it('refuses a machine that is not one of the account\'s ordinary machines in this environment, minting nothing', async () => {
+ for (const hostMachineId of ['their-machine', 'stag-machine', 'gone-machine', 'dedicated-machine', 'no-such-machine']) {
+ const res = await mint('Bearer sso-token', { kind: 'team', hostMachineId })
+ expect(res.statusCode, hostMachineId).toBe(403)
+ expect(res.json().error.code).toBe('HANDOFF_NOT_ALLOWED')
+ }
+ expect(handoffCodes()).toEqual([])
+ })
+
+ it('names a Mac only for a team code, never for a phone or a computer turning itself into one', async () => {
+ for (const payload of [{ hostMachineId: 'laptop-machine' }, { kind: 'viewer', hostMachineId: 'laptop-machine' },
+ { kind: 'team', computerId: LAPTOP, hostMachineId: 'laptop-machine' }]) {
+ const res = await mint('Bearer sso-token', payload)
+ expect(res.statusCode, JSON.stringify(payload)).toBe(400)
+ expect(res.json().error.code).toBe('INVALID_HANDOFF_KIND')
+ }
+ for (const hostMachineId of [1, '', 'x'.repeat(200), null]) {
+ const res = await mint('Bearer sso-token', { kind: 'team', hostMachineId })
+ expect(res.statusCode, JSON.stringify(hostMachineId)).toBe(400)
+ expect(res.json().error.code).toBe('INVALID_MACHINE_ID')
+ }
+ expect(handoffCodes()).toEqual([])
+ })
+
+ it('without a Mac the code mints as before and records none', async () => {
+ const minted = await mint('Bearer sso-token', { kind: 'team' })
+ // What the code holds is the same JSON as before, so a server from before this change redeems it the same way.
+ expect(handoffCodes().map((key) => JSON.parse(fakes.redis.get(key)!))).toEqual([{ userId: USER.id, kind: 'team' }])
+ expect((await redeem(minted.json().data.code)).statusCode).toBe(200)
+ expect(fakes.sessions.at(-1)!.hostMachineId).toBeUndefined()
+ })
+
+ it('redeeming again (a repair run) records the Mac on the team machine that already exists', async () => {
+ fakes.machines.push({ userId: USER.id, computerId: TEAM, machineId: 'team-machine', autonomousEnv: 'prod', sessionKind: 'team' })
+ const minted = await mint('Bearer sso-token', { kind: 'team', hostMachineId: 'laptop-machine' })
+ expect((await redeem(minted.json().data.code)).statusCode).toBe(200)
+ expect(fakes.machines.find((m) => m.machineId === 'team-machine')).toMatchObject({ hostMachineId: 'laptop-machine' })
+ // A dedicated machine and the person's own machines are untouched.
+ expect(fakes.machines.find((m) => m.machineId === 'dedicated-machine')!.hostMachineId).toBeUndefined()
+ expect(fakes.machines.find((m) => m.machineId === 'laptop-machine')!.hostMachineId).toBeUndefined()
+ })
+})
diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.ts
index ad520e36c..4386386f7 100644
--- a/backend/src/lib/harnessSession.ts
+++ b/backend/src/lib/harnessSession.ts
@@ -97,23 +97,26 @@ export type QrSignInKind = 'viewer' | 'computer'
export async function startHandoff(
userId: string,
kind: HandoffKind = 'viewer',
- /** A team code for this computer turning itself into a team machine, already proven to be that computer. */
- { convert }: { convert?: string } = {},
+ /** `convert`: a team code for this computer turning itself into a team machine, already proven to be that computer.
+ * `host`: the machine of the Mac whose team account redeems this code, already checked to be one of the account's
+ * own (routes/auth.ts); the team machine records it, so lists show that Mac once. */
+ { convert, host }: { convert?: string; host?: string } = {},
): Promise<{ code: string; expiresIn: number; kind: HandoffKind }> {
const code = newHarnessToken(HARNESS_HANDOFF_PREFIX)
- const held = kind === 'team' ? JSON.stringify({ userId, kind, ...(convert ? { convert } : {}) }) : userId
+ const held = kind === 'team' ? JSON.stringify({ userId, kind, ...(convert ? { convert } : {}), ...(host ? { host } : {}) }) : userId
await pub.set(handoffKey(harnessTokenHash(code)), held, 'EX', HANDOFF_TTL_SEC)
return { code, expiresIn: HANDOFF_TTL_SEC, kind }
}
/** Who a spent code was minted for, and as what; null for anything else. */
-function handoffOf(held: unknown): { userId: string; kind: HandoffKind; convert?: string } | null {
+function handoffOf(held: unknown): { userId: string; kind: HandoffKind; convert?: string; host?: string } | null {
if (typeof held !== 'string' || !held) return null
if (!held.startsWith('{')) return { userId: held, kind: 'viewer' }
try {
- const parsed = JSON.parse(held) as { userId?: unknown; kind?: unknown; convert?: unknown }
+ const parsed = JSON.parse(held) as { userId?: unknown; kind?: unknown; convert?: unknown; host?: unknown }
if (typeof parsed.userId !== 'string' || !parsed.userId || parsed.kind !== 'team') return null
- return { userId: parsed.userId, kind: 'team', ...(typeof parsed.convert === 'string' && parsed.convert ? { convert: parsed.convert } : {}) }
+ return { userId: parsed.userId, kind: 'team', ...(typeof parsed.convert === 'string' && parsed.convert ? { convert: parsed.convert } : {}),
+ ...(typeof parsed.host === 'string' && parsed.host ? { host: parsed.host } : {}) }
} catch { return null }
}
@@ -138,7 +141,13 @@ export async function redeemHandoff(code: string, label: string, computerId?: st
// The computer that asked to become a team machine, and no other.
if (handoff.convert) return handoff.convert === computer ? convertComputer(handoff.userId, label || 'Team', computer) : null
if (await computerHeldByAnotherSignIn(handoff.userId, computer)) return null
- return createSession(handoff.userId, label || 'Team', 'team', computer)
+ // A repair run signs the same team account in again: its machine already exists and records its Mac now. A new one
+ // records it when it registers (MachineService.resolveForTeamComputer), from the session made here.
+ if (handoff.host) {
+ await prisma.machine.updateMany({ where: { userId: handoff.userId, computerId: computer, sessionKind: 'team', ...machineAlive },
+ data: { hostMachineId: handoff.host } })
+ }
+ return createSession(handoff.userId, label || 'Team', 'team', computer, handoff.host)
}
// Not yet revoked. A session is created without `revokedAt`, and on MongoDB `revokedAt: null` alone
@@ -187,7 +196,7 @@ async function computerHeldByAnotherSignIn(userId: string, computerId: string):
}
/** A new session for [userId]: a refresh token (stored hashed) and its first access token. */
-async function createSession(userId: string, label: string, kind: HarnessSessionKind, computerId?: string): Promise<HarnessTokens | null> {
+async function createSession(userId: string, label: string, kind: HarnessSessionKind, computerId?: string, hostMachineId?: string): Promise<HarnessTokens | null> {
const user = await userService.get(userId)
if (!user) return null
const refreshToken = newHarnessToken(kind === 'team' ? HARNESS_TEAM_REFRESH_PREFIX : HARNESS_REFRESH_PREFIX)
@@ -199,6 +208,8 @@ async function createSession(userId: string, label: string, kind: HarnessSession
kind,
// A team session's bound computer; a computer's own, as its QR sign-in declared it (what lets it convert itself).
...(kind !== 'viewer' && computerId ? { computerId } : {}),
+ // A team session's Mac, which its machine records (MachineService.resolveForTeamComputer).
+ ...(kind === 'team' && hostMachineId ? { hostMachineId } : {}),
expiresAt: sessionExpiry(),
},
})
diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts
index 8ce9d3762..0dbeca248 100644
--- a/backend/src/routes/auth.ts
+++ b/backend/src/routes/auth.ts
@@ -61,6 +61,25 @@ async function isThisComputer(user: AuthUser, computerId: string, proof: unknown
return once === 'OK'
}
+/**
+ * The Mac a team code's account lives on ("One machine", docs/plans/2026-10-24-swarm-team-account.md): its team
+ * machine records it, so every list shows that Mac once. A Harness computer session's is its own machine, and it may
+ * name no other. Any other sign-in, an Autonomous one above all, names it ([named]): one of the account's ordinary
+ * machines in this environment, never a team machine. Null when none is known, false when [named] is not allowed.
+ */
+async function teamHostMachine(user: AuthUser, named: string | undefined): Promise<string | null | false> {
+ const ordinary = (row: { sessionKind: string | null } | null | undefined) => !!row && row.sessionKind !== 'team'
+ if (user.harnessSessionKind === 'computer' && user.harnessComputerId) {
+ const own = (await prisma.machine.findMany({ where: { userId: user.sub, computerId: user.harnessComputerId, autonomousEnv: user.autonomousEnv,
+ ...machineAlive } })).filter(ordinary)
+ if (named !== undefined) return own.some(row => row.machineId === named) ? named : false
+ return own[0]?.machineId ?? null
+ }
+ if (named === undefined) return null
+ const machine = await prisma.machine.findFirst({ where: { machineId: named, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ return ordinary(machine) ? named : false
+}
+
/** Reporting only: a sign-in whose attribution cannot be stored still signs in. */
async function recordAttribution(userId: string, attribution: SignInAttribution): Promise<void> {
try {
@@ -285,22 +304,30 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
// lifetime, same answer, which names the kind minted. A team session can never mint one of either kind.
// `{ kind: 'team', computerId }` is a computer turning ITSELF into a team machine (`harness team on`): only
// that computer may ask (isThisComputer), and the code redeems for that computer alone.
- app.post<{ Body: { kind?: unknown; computerId?: unknown; proof?: unknown } | undefined }>('/api/auth/handoff', async (req, reply) => {
+ // `{ kind: 'team', hostMachineId }` names the Mac the team account lives on (teamHostMachine); a computer's own
+ // session need not name it. A team session can never set or change it: it cannot mint.
+ app.post<{ Body: { kind?: unknown; computerId?: unknown; proof?: unknown; hostMachineId?: unknown } | undefined }>('/api/auth/handoff', async (req, reply) => {
if (req.user!.harnessSessionId && req.user!.harnessSessionKind !== 'computer') {
return sendError(reply, 'Add a phone from a computer signed in to Harness', 'HANDOFF_NOT_ALLOWED', 403)
}
- const body = req.body && typeof req.body === 'object' ? req.body as { kind?: unknown; computerId?: unknown; proof?: unknown } : {}
+ const body = req.body && typeof req.body === 'object' ? req.body as { kind?: unknown; computerId?: unknown; proof?: unknown; hostMachineId?: unknown } : {}
const asked = body.kind
- if ((asked !== undefined && asked !== 'viewer' && asked !== 'team') || (body.computerId !== undefined && asked !== 'team')) {
+ if ((asked !== undefined && asked !== 'viewer' && asked !== 'team') || (body.computerId !== undefined && asked !== 'team')
+ || (body.hostMachineId !== undefined && (asked !== 'team' || body.computerId !== undefined))) {
return sendError(reply, 'Ask for a phone or a team sign-in code', 'INVALID_HANDOFF_KIND', 400)
}
const convert = body.computerId === undefined ? undefined : typeof body.computerId === 'string' ? normalizeComputerId(body.computerId) : null
if (convert === null) return sendError(reply, 'Name this computer by its id', 'INVALID_COMPUTER_ID', 400)
+ const named = body.hostMachineId === undefined ? undefined
+ : typeof body.hostMachineId === 'string' && body.hostMachineId && body.hostMachineId.length <= 128 ? body.hostMachineId : null
+ if (named === null) return sendError(reply, 'Name the machine by its id', 'INVALID_MACHINE_ID', 400)
try {
if (convert && !(await isThisComputer(req.user!, convert, body.proof))) {
return sendError(reply, 'Only this computer can make itself a team machine', 'HANDOFF_NOT_ALLOWED', 403)
}
- return sendSuccess(reply, await startHandoff(req.user!.sub, asked === 'team' ? 'team' : 'viewer', convert ? { convert } : {}))
+ const host = asked === 'team' && !convert ? await teamHostMachine(req.user!, named) : null
+ if (host === false) return sendError(reply, 'That machine is not one of this account\'s computers', 'HANDOFF_NOT_ALLOWED', 403)
+ return sendSuccess(reply, await startHandoff(req.user!.sub, asked === 'team' ? 'team' : 'viewer', convert ? { convert } : host ? { host } : {}))
} catch (e) {
logger.error('handoff start failed', e)
return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
diff --git a/backend/src/services/MachineService.computer.test.ts b/backend/src/services/MachineService.computer.test.ts
index 0dbc52629..862e0f94f 100644
--- a/backend/src/services/MachineService.computer.test.ts
+++ b/backend/src/services/MachineService.computer.test.ts
@@ -15,13 +15,14 @@ const consumeNewIdQuota = vi.hoisted(() => vi.fn())
const findUnique = vi.hoisted(() => vi.fn())
const update = vi.hoisted(() => vi.fn())
const sessionUpdateMany = vi.hoisted(() => vi.fn())
+const sessionFindUnique = vi.hoisted(() => vi.fn())
vi.mock('../lib/prisma.js', () => ({
machineAlive: {},
prisma: {
machine: { findMany, count, create, findUnique, update },
subscriptionPlan: { findFirst: planFindFirst },
- harnessSession: { updateMany: sessionUpdateMany },
+ harnessSession: { updateMany: sessionUpdateMany, findUnique: sessionFindUnique },
},
}))
vi.mock('../lib/bus.js', () => ({
@@ -52,6 +53,8 @@ beforeEach(() => {
redisSet.mockResolvedValue('OK')
consumeNewIdQuota.mockResolvedValue(true)
create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ ...data }))
+ sessionFindUnique.mockResolvedValue({ hostMachineId: null })
+ update.mockImplementation(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => ({ ...where, ...data }))
})
describe('resolveOrCreateForComputer', () => {
@@ -108,6 +111,34 @@ describe('resolveForTeamComputer', () => {
expect(findMany).not.toHaveBeenCalled()
})
+ // One machine: the team machine records the Mac its session was minted for, from the session and nothing it sends.
+ it('records its session\'s Mac on a machine it creates', async () => {
+ sessionFindUnique.mockResolvedValue({ hostMachineId: 'laptop' })
+ await machineService.resolveForTeamComputer(team, TEAM, 'MacBook Pro · Team')
+ expect(sessionFindUnique).toHaveBeenCalledWith({ where: { id: 'team-session' }, select: { hostMachineId: true } })
+ expect(create).toHaveBeenCalledWith({ data: expect.objectContaining({ sessionKind: 'team', hostMachineId: 'laptop' }) })
+ })
+
+ it('records its session\'s Mac on the machine it reuses when that differs, and leaves one it already names', async () => {
+ sessionFindUnique.mockResolvedValue({ hostMachineId: 'laptop' })
+ findMany.mockResolvedValue([{ machineId: 'm1', billingStatus: 'not_required', sessionKind: 'team', hostMachineId: null }])
+ expect(await machineService.resolveForTeamComputer(team, TEAM, 'x')).toMatchObject({ machine: { machineId: 'm1', hostMachineId: 'laptop' } })
+ expect(update).toHaveBeenCalledWith({ where: { machineId: 'm1' }, data: { hostMachineId: 'laptop' } })
+ update.mockClear()
+ findMany.mockResolvedValue([{ machineId: 'm1', billingStatus: 'not_required', sessionKind: 'team', hostMachineId: 'laptop' }])
+ await machineService.resolveForTeamComputer(team, TEAM, 'x')
+ expect(update).not.toHaveBeenCalled()
+ })
+
+ it('a session that names no Mac (a dedicated machine) records none and clears nothing', async () => {
+ findMany.mockResolvedValue([{ machineId: 'm1', billingStatus: 'not_required', sessionKind: 'team', hostMachineId: 'laptop' }])
+ await machineService.resolveForTeamComputer(team, TEAM, 'x')
+ expect(update).not.toHaveBeenCalled()
+ findMany.mockResolvedValue([])
+ await machineService.resolveForTeamComputer(team, TEAM, 'x')
+ expect(create.mock.calls.at(-1)![0].data).not.toHaveProperty('hostMachineId')
+ })
+
it('refuses a computer the account runs under a normal sign-in, rows from before the kind was kept included', async () => {
for (const sessionKind of ['computer', null, undefined]) {
findMany.mockResolvedValue([{ machineId: 'm1', billingStatus: 'not_required', sessionKind }])
diff --git a/backend/src/services/MachineService.list.test.ts b/backend/src/services/MachineService.list.test.ts
index 964d717f7..32d896f5f 100644
--- a/backend/src/services/MachineService.list.test.ts
+++ b/backend/src/services/MachineService.list.test.ts
@@ -137,3 +137,21 @@ describe('listForUser — a remote machine\'s presence', () => {
expect(await statusOf()).toEqual({ up: 'running', down: 'offline', unreadable: 'unknown' })
})
})
+
+// One machine (docs/plans/2026-10-24-swarm-team-account.md): a Mac's team machine names the Mac it lives on, so a list
+// can show that Mac once. Only a team machine names one; a row that is no longer a team machine names none.
+describe('listForUser — the Mac a team machine lives on', () => {
+ beforeEach(() => {
+ findMany.mockImplementation(async ({ where }: { where: Where }) => [
+ { ...base, machineId: 'laptop', userId: 'u1', sessionKind: 'computer' },
+ { ...base, machineId: 'laptop-team', userId: 'u1', sessionKind: 'team', hostMachineId: 'laptop' },
+ { ...base, machineId: 'mini', userId: 'u1', sessionKind: 'team' },
+ { ...base, machineId: 'taken-over', userId: 'u1', sessionKind: 'computer', hostMachineId: 'laptop' },
+ ].filter((r) => matches(r, where)))
+ })
+
+ it('is returned for a team machine on a Mac, and null for every other machine', async () => {
+ const hosts = Object.fromEntries((await machineService.listForUser('u1')).map((m) => [m.machineId, m.hostMachineId]))
+ expect(hosts).toEqual({ laptop: null, 'laptop-team': 'laptop', mini: null, 'taken-over': null })
+ })
+})
diff --git a/backend/src/services/MachineService.ts b/backend/src/services/MachineService.ts
index f56a99039..8783d89bb 100644
--- a/backend/src/services/MachineService.ts
+++ b/backend/src/services/MachineService.ts
@@ -60,6 +60,9 @@ export interface OwnerMachine {
// How that computer signed in on its last connect: `team` for a Mac's team account (lib/teamSession.ts),
// `computer` for any other sign-in, null before it was recorded.
sessionKind: 'team' | 'computer' | null
+ // A team machine's Mac: the machineId of the account's own machine on the computer whose Harness Team account this
+ // is. A list shows that Mac once, this machine folded into it. Null for every other machine.
+ hostMachineId: string | null
}
interface PlanInfo {
@@ -96,6 +99,8 @@ function toOwner(b: Machine, status = 'unknown', agentCount = 0, plan?: PlanInfo
name: b.name ?? null,
hostname: b.hostname ?? null,
sessionKind: b.sessionKind === 'team' || b.sessionKind === 'computer' ? b.sessionKind : null,
+ // Only while it is a team machine: one a normal sign-in took over is a machine of its own again.
+ hostMachineId: b.sessionKind === 'team' ? b.hostMachineId ?? null : null,
}
}
@@ -427,6 +432,8 @@ export const machineService = {
claimedMachineId?: string,
/** How the computer is signing in, recorded on a machine created now (`Machine.sessionKind`). */
sessionKind?: 'team' | 'computer',
+ /** A team machine's Mac, recorded on a machine created now (`Machine.hostMachineId`). */
+ hostMachineId?: string,
): Promise<{ machine: Machine; created: boolean }> {
// A caller that still holds a machine id we have DELETED must be told so, never quietly given a
// new machine. Deletion is soft, so `machineAlive` below simply does not find the old row — and
@@ -500,6 +507,7 @@ export const machineService = {
// a later connect only ever refreshes `hostname`, never this.
name: label.trim().slice(0, 120) || null,
...(sessionKind ? { sessionKind } : {}),
+ ...(hostMachineId ? { hostMachineId } : {}),
},
})
await publishDeviceMachineListChanged(userId, { reason: 'created' }).catch(() => { /* best effort */ })
@@ -523,9 +531,17 @@ export const machineService = {
if (user.harnessSessionKind !== 'team' || !user.harnessComputerId || computerId !== user.harnessComputerId) throw refuse()
const held = await prisma.machine.findMany({ where: { userId: user.sub, computerId, ...machineAlive }, select: { sessionKind: true } })
if (held.some((row) => row.sessionKind !== 'team')) throw refuse()
- const resolved = await machineService.resolveOrCreateForComputer(user.sub, user.autonomousEnv, computerId, label, claimedMachineId, 'team')
+ // The Mac this team account lives on, as its owner's computer said when the code was minted (routes/auth.ts): from the
+ // session, never from what the team daemon sends, so a team session cannot set or change it.
+ const hostMachineId = user.harnessSessionId
+ ? (await prisma.harnessSession.findUnique({ where: { id: user.harnessSessionId }, select: { hostMachineId: true } }))?.hostMachineId ?? undefined
+ : undefined
+ const resolved = await machineService.resolveOrCreateForComputer(user.sub, user.autonomousEnv, computerId, label, claimedMachineId, 'team', hostMachineId)
// Another sign-in took the row between the check and here: still not this session's machine.
if (resolved.machine.sessionKind !== 'team') throw refuse()
+ if (hostMachineId && resolved.machine.hostMachineId !== hostMachineId) {
+ return { ...resolved, machine: await prisma.machine.update({ where: { machineId: resolved.machine.machineId }, data: { hostMachineId } }) }
+ }
return resolved
},
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index bccbe2843..7d98debe0 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,4 +1,4 @@
-import { admitMachineStart, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, ownedMachine, requireTeamWork, teamWorkCheck, type ContributedMachine } from './machines.js'
+import { admitMachineStart, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, ownedMachine, requireTeamWork, teamMachineFor, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
import { assignAgentDisplayNames } from './agentNames.js'
import { z } from 'zod'
import {
@@ -194,7 +194,9 @@ export interface CommandContext {
operationId: string
now: number
/** Read from host ownership/access records by the store, never copied from the request. */
- contribution?: { machineOwnerId: string; contributorId: string; hostGrant?: string | null }
+ contribution?: { machineOwnerId: string; contributorId: string; hostGrant?: string | null
+ /** A Harness Team account's machine: the Mac it lives on, from its account row (machines.ts ContributedMachine). */
+ hostMachineId?: string }
/** Loaded from this tab and conversation by the store. */
reply?: { id: string; conversationId: string; author: Author }
/** The message a Lead quotes as the owner's request for a rule or skill mode change, loaded from this tab by the store. */
@@ -455,9 +457,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
/** A hard rule refuses an agent, unless it carries out what a person chose by hand. A person is not blocked: the
* command goes through and the group is told. */
const machineName = (id: string) => state.machines?.find(m => m.machineId === id)?.name ?? id
+ /** The Mac a Harness Team account's machine is, for a machines rule naming the Mac (machines.ts teamStartRequest). */
+ const macOf = (id: string) => state.machines?.find(m => m.machineId === id)?.hostMachineId
const groupRules = (conversationId: string) => projectRules(state, groupProject(state, conversation(state, conversationId)).id)
const ruled = (target: RunTarget, conversationId: string, done: string, personChose = false) => {
- const why = broken(groupRules(conversationId), target, machineName)
+ const why = broken(groupRules(conversationId), target, machineName, macOf)
if (!why) return
if (actor.kind === 'agent' && !personChose) fail('RULE_BROKEN', `${why} Route again.`, 403)
result.warnings = [why]
@@ -513,8 +517,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const project = groupProject(state, conversation(state, conversationId))
const member = candidate.kind === 'member' ? state.agents.find(a => a.id === candidate.agentId) : undefined
if (candidate.kind === 'member' && !member) return null
- const contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === candidate.machineId)?.contributorId ?? starter
- return teamWorkCheck(state, member?.machineId ?? candidate.machineId, contributor, project, context.now, context.teamMachines)
+ // A new agent on a Mac for a teammate's project runs in the Mac's Harness Team account (machines.ts teamStartRequest).
+ const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project)
+ const contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === machineId)?.contributorId ?? starter
+ return teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines)
}
/** Deleting its project is the only removal that takes a Lead. `close: false` when its host already closed the session. */
const removeAgent = (target: Agent, { lead = false, close = true } = {}) => {
@@ -787,8 +793,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// A late cleanup would delete the new contribution's folders.
const cleaning = state.machines.some(m => m.machineId === command.machineId && m.removal)
|| !!state.machineCleanups?.some(c => c.machineId === command.machineId)
+ // A Mac's Harness Team account joins by itself wherever its owner added the Mac, as that Mac (cli/src/superTabs/host.ts).
+ const mac = context.contribution?.hostMachineId
+ ? state.machines.find(m => m.machineId === context.contribution!.hostMachineId && m.contributorId === actor.userId && !m.removal) : undefined
if (command.ifMissing) {
- if (actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Swarm owner adds a machine automatically.', 403)
+ if (actor.userId !== state.ownerId && !mac) fail('OWNER_REQUIRED', 'Only the Swarm owner adds a machine automatically.', 403)
if (cleaning || state.machines.some(m => m.machineId === command.machineId)) break
}
if (cleaning) fail('MACHINE_CLEANING', 'This machine is still cleaning up after its removal. Add it again once that finishes.')
@@ -810,9 +819,14 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
if (state.starts?.some(s => s.request.machineId === command.machineId && (!s.harnessId || (s.poolGeneration && !s.poolSettled)) && !s.error)) fail('STARTS_PENDING', 'Reconcile pending starts before changing this contribution.')
state.machines = state.machines.filter(m => m.machineId !== command.machineId)
- state.machines.push({ machineId: command.machineId, name: command.name, cwd: command.cwd, engines: [...new Set(command.engines)], maxAgents: command.maxAgents,
- ...(command.scope ? { scope: command.scope } : {}),
- contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused: false })
+ const host = context.contribution?.hostMachineId
+ state.machines.push({ machineId: command.machineId, name: mac?.name ?? command.name, cwd: command.cwd, engines: [...new Set(command.engines)],
+ maxAgents: mac?.maxAgents ?? command.maxAgents, ...(command.scope ? { scope: command.scope } : {}),
+ contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused: mac?.paused ?? false,
+ ...(host ? { hostMachineId: host } : {}) })
+ // A Mac given other slots or a new name gives its team account the same; its own folder, engines and grant stay.
+ const added = state.machines.at(-1)!
+ for (const team of teamPoolsOf(state, added)) if (!team.removal) Object.assign(team, { name: added.name, maxAgents: added.maxAgents, paused: false })
break
}
case 'machine.pause': {
@@ -820,6 +834,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (actor.kind !== 'person' || actor.userId !== pool.contributorId) fail('OWNER_REQUIRED', 'Only its contributor can change this machine.', 403)
if (pool.removal) fail('MACHINE_REMOVED', 'This machine is being removed from the Swarm.')
pool.paused = command.paused
+ // Its Harness Team account is the same Mac.
+ for (const team of teamPoolsOf(state, pool)) if (!team.removal) team.paused = command.paused
break
}
case 'machine.remove': {
@@ -829,7 +845,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person removes a machine from the Swarm.', 403)
const { pool, members } = ownedMachine(state, actor, command.machineId)
if (pool?.removal) fail('MACHINE_REMOVED', 'This machine is already being removed from the Swarm.')
- const removed = removeMachine(command.machineId, pool, members, machine => `${who} removed ${machine} from the Swarm`)
+ // The Mac leaves with its Harness Team account and the agents there, told once as the Mac; that account's host cleans
+ // its own folders.
+ const moving = pool ? teamPoolsOf(state, pool).filter(m => !m.removal) : []
+ const removed = removeMachine(command.machineId, pool, [...members, ...state.agents.filter(a => moving.some(m => m.machineId === a.machineId))],
+ machine => `${who} removed ${machine} from the Swarm`)
+ for (const team of moving) removeMachine(team.machineId, team, [], machine => `${who} removed ${machine} from the Swarm`)
if (pool) result.removalId = operationId
result.removedAgents = [...removed]
break
@@ -1010,15 +1031,18 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) {
fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')
}
- const pool = admitMachineStart(state, command.request, context.now, undefined, context.teamMachines)
+ // A teammate's project started on a Mac runs in that Mac's Harness Team account, never as its owner (machines.ts).
+ const request = teamStartRequest(state, command.request, home)
+ const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines)
// Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).
- if (!pool) requireTeamWork(state, command.request.machineId, grant.contributorId, home, context.now, context.teamMachines)
+ if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines)
state.starts.push({ ...(pool ? { poolGeneration: pool.generation } : {}), ...(command.routeDecisionId ? { routeDecisionId: command.routeDecisionId } : {}), id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),
contributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: grant.machineOwnerId,
- hostGrant: grant.hostGrant ?? null, request: command.request, harnessId: null, dispatched: false, error: null })
+ hostGrant: grant.hostGrant ?? null, request, harnessId: null, dispatched: false, error: null })
result.startId = operationId
let personChose = false
if (command.routeDecisionId) {
+ // The pick names the machine the Lead named: the Mac, when the start then went to its team account.
const r = command.request
const model = r.model ?? 'default', effort = r.effort ?? 'default'
const { decision, expected, override } = linkDecision(r.conversationId,
@@ -1030,7 +1054,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
{ kind: 'route-override', decisionId: decision.id, by: 'lead' })
personChose = !override && decision.override?.by === 'person'
}
- ruled(startTarget(command.request), command.request.conversationId, `${who} started ${command.request.name}`, personChose)
+ ruled(startTarget(request), request.conversationId, `${who} started ${request.name}`, personChose)
break
}
case 'agent.startDispatch':
@@ -1047,7 +1071,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
fail('SWARM_ENGINE', 'A Swarm agent runs only Claude Code or Codex.', 400)
}
// A start recorded before a rule was added is not launched past it, unless a person asked for it by hand.
- const why = actor.kind === 'agent' && !(start.routeDecisionId && context.routeDecision?.override?.by === 'person') && broken(groupRules(start.request.conversationId), startTarget(start.request), machineName)
+ const why = actor.kind === 'agent' && !(start.routeDecisionId && context.routeDecision?.override?.by === 'person') && broken(groupRules(start.request.conversationId), startTarget(start.request), machineName, macOf)
if (why) fail('RULE_BROKEN', `${why} This start was not launched. Route again.`, 403)
requireWorkerDecisions(state, actor, open(state, start.request.conversationId))
const grant = context.contribution ?? fail('HOST_REQUIRED', 'The original machine grant is unavailable.', 403)
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index ccfa75a63..caf95fce1 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -19,6 +19,11 @@ export interface ContributedMachine {
* the report: `team` for a Mac's team account (lib/teamSession.ts), `computer` for any other. Absent on older readings.
* `privacy` is kept only from a team session's reading (observedPrivacy). */
observation?: Omit<MachineObservation, 'privacy'> & { receivedAt: number; sessionKind?: 'team' | 'computer'; privacy?: StoredPrivacy }
+ /** A Mac's Harness Team account: the machine of the Mac it lives on, stamped by the store from its account row
+ * (`Machine.hostMachineId`), never taken from the command. Such a pool is that Mac under the scenes ("One machine",
+ * docs/plans/2026-10-24-swarm-team-account.md): it shows the Mac's name, joins where the Mac was added, follows the
+ * Mac's pause, slots and removal, and runs teammates' projects started on the Mac (teamStartRequest). */
+ hostMachineId?: string
/** Set by machine.remove: an online machine stays listed, paused, while its host deletes the Swarm's folders there, until
* the host says it cleaned up (machine.cleaned) or REMOVAL_FALLBACK_MS passes. An offline one leaves the list at once and
* its cleanup waits for its host (expireRemovals). */
@@ -181,6 +186,50 @@ export function teamWorkCheck(state: SuperTabState, machineId: string, contribut
return teamWorkRefusal(pool, now, teamMachines.includes(machineId))
}
+// ── One machine: a Mac and its Harness Team account ─────────────────────────────────────────────────────────────────
+// The team account is how a Mac runs teammates' work without its owner's files, not a machine of its own to anyone: a
+// Lead names the Mac, and the work for another person's project lands in the Mac's team account.
+
+/** Every pool of a Harness Team account on the Mac [pool] is, under the same grant: one, or more once the account was
+ * removed and set up again (a new account and machine, the old one's pool still listed). They go with the Mac. */
+export function teamPoolsOf(state: SuperTabState, pool: ContributedMachine): ContributedMachine[] {
+ if (pool.hostMachineId) return []
+ return state.machines?.filter(m => m.hostMachineId === pool.machineId && m.contributorId === pool.contributorId) ?? []
+}
+
+/** The one of them that runs teammates' work on the Mac: not being removed, and the last to report. Undefined when none. */
+export function teamPoolOf(state: SuperTabState, pool: ContributedMachine): ContributedMachine | undefined {
+ return teamPoolsOf(state, pool).filter(m => !m.removal)
+ .reduce<ContributedMachine | undefined>((best, m) => !best || (m.observation?.receivedAt ?? -1) >= (best.observation?.receivedAt ?? -1) ? m : best, undefined)
+}
+
+/** Where a new agent for [project] runs when a start names [machineId]: the Mac's team account when the project is not
+ * its contributor's own and the Mac has one in this Swarm, else the machine named. */
+export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject): string {
+ const pool = state.machines?.find(m => m.machineId === machineId)
+ if (!pool || project.ownerId === pool.contributorId) return machineId
+ return teamPoolOf(state, pool)?.machineId ?? machineId
+}
+
+/** The folder a start for [project] uses on [pool]: what admitMachineStart accepts there. */
+export function projectFolder(pool: ContributedMachine, project: SwarmProject): string {
+ return pool.scope === 'swarm'
+ ? project.repository?.machineId === pool.machineId ? project.repository.cwd : `${pool.cwd.replace(/\/+$/, '')}/${project.id}`
+ : pool.cwd
+}
+
+/**
+ * A start on a Mac for another person's project, moved to the Mac's Harness Team account: its machine, and its folder in
+ * place of the Mac's own for that project. Every other start is returned as it is, so the Mac's owner's own projects
+ * stay with the owner's daemon, and a Mac without a team account here refuses it as before (teamWorkCheck).
+ */
+export function teamStartRequest(state: SuperTabState, request: AgentStartRequest, project: SwarmProject): AgentStartRequest {
+ const machineId = teamMachineFor(state, request.machineId, project)
+ if (machineId === request.machineId) return request
+ const pool = state.machines!.find(m => m.machineId === request.machineId)!, team = state.machines!.find(m => m.machineId === machineId)!
+ return { ...request, machineId, cwd: request.cwd === projectFolder(pool, project) ? projectFolder(team, project) : request.cwd }
+}
+
/** Refuses with the refusal's code and sentence: 403, or 409 like any start on an offline machine. */
export function failTeamWork(refusal: TeamWorkRefusal, after = ''): never {
fail(refusal.code, `${refusal.reason}${after}`, refusal.code === 'MACHINE_OFFLINE' ? 409 : 403)
@@ -234,7 +283,10 @@ export function ownedMachine(state: SuperTabState, actor: Actor, machineId: stri
/** What removing the machine would do, for its owner's confirmation. */
export function removalPreview(state: SuperTabState, actor: Actor, machineId: string) {
- const { members } = ownedMachine(state, actor, machineId)
+ const owned = ownedMachine(state, actor, machineId)
+ // A Mac leaves with its Harness Team account and the agents there (commands.ts machine.remove).
+ const teams = owned.pool ? teamPoolsOf(state, owned.pool).filter(m => !m.removal).map(m => m.machineId) : []
+ const members = [...owned.members, ...state.agents.filter(a => teams.includes(a.machineId))]
const led = members.map(a => ledProject(state, a.id)).find(Boolean)
return {
blockedBy: led ? { projectId: led.id, projectName: led.name } : null,
@@ -268,8 +320,15 @@ export function expireRemovals(state: SuperTabState, now: number): void {
}
}
-/** Pending intents reserve slots too. Only an explicit host stop frees a launched slot. */
+/** Pending intents reserve slots too. Only an explicit host stop frees a launched slot. A Mac and its Harness Team account
+ * share the Mac's slots (One machine, teamStartRequest): each counts what runs on both. */
export function machineSlots(state: SuperTabState, pool: ContributedMachine) {
+ const mac = pool.hostMachineId ? state.machines?.find(m => m.machineId === pool.hostMachineId && m.contributorId === pool.contributorId) : pool
+ const team = mac && teamPoolOf(state, mac)
+ return [...new Set([pool, mac, team])].reduce((sum, each) => sum + (each ? poolSlots(state, each) : 0), 0)
+}
+
+function poolSlots(state: SuperTabState, pool: ContributedMachine) {
const reservations = (state.harnessReservations ?? []).filter(r => r.machineId === pool.machineId)
const live = new Set(reservations.map(r => r.harnessId))
const released = (state.releasedHarnesses ?? []).filter(r => r.machineId === pool.machineId && !live.has(r.harnessId)).map(r => r.harnessId)
@@ -335,9 +394,7 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
if (!pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')
// Before the request's own fields: a machine that takes none of this project's work says so first.
requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines)
- const cwd = pool.scope === 'swarm'
- ? project.repository?.machineId === pool.machineId ? project.repository.cwd : `${pool.cwd.replace(/\/+$/, '')}/${project.id}`
- : pool.cwd
+ const cwd = projectFolder(pool, project)
// Every refused field is named, with what the machine does accept. Values the caller sent are not echoed: an account
// setting can be a path or a name of the caller's own.
const refused: string[] = []
diff --git a/backend/src/superTabs/rules.ts b/backend/src/superTabs/rules.ts
index 0fc247ebe..679059587 100644
--- a/backend/src/superTabs/rules.ts
+++ b/backend/src/superTabs/rules.ts
@@ -50,13 +50,17 @@ export function modelMatches(ruleModel: string, model: string | null): boolean {
}
/** Why a hard rule rules the target out, or null when none does. A machines rule names the machines it allows now: a removed
- * machine leaves the rule but stays in the owner's words (machine.remove). */
-export function broken(rules: SwarmRule[] | undefined, target: RunTarget, machineName = (id: string) => id): string | null {
+ * machine leaves the rule but stays in the owner's words (machine.remove). A Mac's Harness Team account is that Mac
+ * ([macOf], machines.ts teamStartRequest), so a rule naming the Mac allows it. */
+export function broken(rules: SwarmRule[] | undefined, target: RunTarget, machineName = (id: string) => id,
+ macOf: (id: string) => string | undefined = () => undefined): string | null {
+ const mac = macOf(target.machineId)
for (const { rule, text } of rules ?? []) {
const engineName = ENGINE[target.engine] ?? target.engine
const out = rule.kind === 'forbidModel' ? (!rule.engine || rule.engine === target.engine)
&& modelMatches(rule.model, target.model) && `${engineName} ${target.model}`
- : rule.kind === 'machines' ? !rule.machineIds.includes(target.machineId) && `this machine (it allows only ${rule.machineIds.map(machineName).join(', ')})`
+ : rule.kind === 'machines' ? !rule.machineIds.includes(target.machineId) && !(mac && rule.machineIds.includes(mac))
+ && `this machine (it allows only ${rule.machineIds.map(machineName).join(', ')})`
: rule.kind === 'minEffort' ? (!rule.engine || rule.engine === target.engine) && rank(target.effort) < rank(rule.effort)
&& `${engineName} at ${target.effort && rank(target.effort) >= 0 ? `${target.effort} effort` : 'an unnamed effort'}`
: false
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 7bac618b6..67d10c6a1 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -277,11 +277,13 @@ export class SuperTabStore {
person(state, contributorId)
const machine = await tx.machine.findFirst({ where: { machineId: command.machineId, autonomousEnv: state.environment, ...machineAlive } })
if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This machine is unavailable.', 403)
+ // A Mac's Harness Team account names its Mac from its own account row, which only its owner's sign-in set (machines.ts).
+ const host = machine.sessionKind === 'team' && machine.hostMachineId ? { hostMachineId: machine.hostMachineId } : {}
if (pooled) {
const pool = machineContribution(state, command.machineId)
if (pool) {
if (pool.contributorId !== machine.userId) fail('CONTRIBUTION_REVOKED', 'The machine owner changed.', 403)
- return { machineOwnerId: machine.userId, contributorId: pool.contributorId, hostGrant: null }
+ return { machineOwnerId: machine.userId, contributorId: pool.contributorId, hostGrant: null, ...host }
}
}
let hostGrant: string | null = null
@@ -295,7 +297,7 @@ export class SuperTabStore {
}
hostGrant = machineShareGrant(share, contributor.email)
}
- return { machineOwnerId: machine.userId, contributorId, hostGrant }
+ return { machineOwnerId: machine.userId, contributorId, hostGrant, ...host }
}
async create(user: AuthUser, operationId: string, name: string, projectVisibility?: ProjectVisibility) {
@@ -1287,9 +1289,19 @@ export class SuperTabStore {
// A cleanup is never cut by that limit: a machine in more than 100 Swarms would otherwise keep a removed Swarm's folders.
const cleaning = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, cleanupMachineIds: { has: machineId },
id: { notIn: rows.map(r => r.id) } } })
+ // This Mac's Harness Team account, which joins wherever this Mac is added (machines.ts): asked of the owner's own daemon only.
+ const teams = isTeamSession(user) ? [] : await tx.machine.findMany({ where: { userId: user.sub, hostMachineId: machineId, sessionKind: 'team',
+ autonomousEnv: user.autonomousEnv, ...machineAlive }, select: { machineId: true } })
const result = []
for (const row of rows) {
const state = stateOf(row)
+ // Where its owner added this Mac and its team account is missing, this host adds that account, prepared by its own
+ // daemon (cli/src/superTabs/host.ts); the backend gives it the Mac's name, slots and pause (commands.ts).
+ const mac = state.machines?.find(m => m.machineId === machineId && m.contributorId === user.sub && m.scope === 'swarm' && !m.removal)
+ for (const team of mac ? teams : []) {
+ if (state.machines?.some(m => m.machineId === team.machineId) || state.machineCleanups?.some(c => c.machineId === team.machineId)) continue
+ result.push({ tabId: row.id, joinTeam: { machineId: team.machineId, name: mac!.name, maxAgents: mac!.maxAgents } })
+ }
const people = await tx.user.findMany({ where: { id: { in: state.people.map(p => p.id) }, autonomousEnv: state.environment }, select: { id: true, email: true } })
for (const target of state.agents.filter(a => a.machineId === machineId && a.machineOwnerId === user.sub)) {
try { agent(state, target.id); await this.agentGrant(tx, state, target) }
diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.ts
index d7ca8f827..451ee6f1f 100644
--- a/backend/src/superTabs/teamRouting.test.ts
+++ b/backend/src/superTabs/teamRouting.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { applyCommand, type Command, type CommandContext } from './commands.js'
-import { admitMachineStart, machineObservationSchema, observedPrivacy, PRIVACY_FRESH_MS, teamWorkRefusal, type ContributedMachine, type MachinePrivacy } from './machines.js'
+import { admitMachineStart, machineObservationSchema, machineSlots, observedPrivacy, PRIVACY_FRESH_MS, removalPreview, teamWorkRefusal, type ContributedMachine, type MachinePrivacy } from './machines.js'
import { createSuperTab, SuperTabError, visibleState, type Actor, type AgentConfiguration, type AgentStart, type SuperTabState } from './model.js'
import type { RouteDecision } from './routeRecord.js'
@@ -369,3 +369,177 @@ describe('until a team account is required everywhere', () => {
expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-team') }, owner, f.pooled('mate-team')))?.code).toBe('PRIVACY_CHECK_FAILED')
})
})
+
+// One machine ("One machine" in docs/plans/2026-10-24-swarm-team-account.md): a Mac's Harness Team account is a
+// mechanism under the scenes. Its pool names the Mac it lives on (`hostMachineId`), shows the Mac's name, joins where
+// the Mac was added and follows the Mac's pause, slots and removal. A teammate's project started on the Mac runs in
+// the team account; the Mac's owner's own projects stay with the owner's daemon.
+describe('one machine: a Mac and its Harness Team account', () => {
+ function oneMachine() {
+ const f = swarm()
+ Object.assign(f.machine('mate-team'), { hostMachineId: 'mate-mac', name: 'MacBook Pro', cwd: '/team-swarm' })
+ return f
+ }
+
+ it('a teammate\'s project started on the Mac runs in its Harness Team account, in that account\'s folder', () => {
+ const f = oneMachine(), group = f.group()
+ f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac'))
+ expect(f.state.starts).toEqual([expect.objectContaining({ poolGeneration: 'g1', machineOwnerId: 'mate',
+ request: expect.objectContaining({ machineId: 'mate-team', cwd: '/team-swarm/lead' }) })])
+ // A Lead that already named the team account's folder keeps it.
+ f.run({ type: 'agent.start', request: { ...f.request(group, 'mate-mac'), cwd: '/team-swarm/lead' } }, owner, f.pooled('mate-mac'))
+ expect(f.state.starts![1]!.request).toMatchObject({ machineId: 'mate-team', cwd: '/team-swarm/lead' })
+ })
+
+ it('is refused with the team account\'s own reason, and never falls back to the Mac\'s owner', () => {
+ const f = oneMachine(), group = f.group()
+ f.machine('mate-team').observation = reading('team', FAILED)
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac')))).toMatchObject({
+ code: 'PRIVACY_CHECK_FAILED', message: 'The Harness Team account on MacBook Pro is not private (gitconfig: it could read its owner\'s ~/.gitconfig), so it runs only its owner\'s projects.' })
+ f.machine('mate-team').observation = reading('team', PASSED, NOW - 60_000)
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac')))?.code).toBe('MACHINE_OFFLINE')
+ expect(f.state.starts ?? []).toEqual([])
+ })
+
+ it('leaves the Mac\'s owner\'s own projects on the owner\'s daemon', () => {
+ const f = oneMachine(), mine = f.group(f.mine, mate)
+ f.run({ type: 'agent.start', request: f.request(mine, 'mate-mac', f.mine) }, mate, f.pooled('mate-mac'))
+ expect(f.state.starts![0]!.request).toMatchObject({ machineId: 'mate-mac', cwd: `/swarm/${f.mine}` })
+ })
+
+ it('still takes a start that names the team account\'s machine directly', () => {
+ const f = oneMachine(), group = f.group()
+ f.run({ type: 'agent.start', request: { ...f.request(group, 'mate-team'), cwd: '/team-swarm/lead' } }, owner, f.pooled('mate-team'))
+ expect(f.state.starts![0]!.request).toMatchObject({ machineId: 'mate-team' })
+ })
+
+ it('a Mac whose team account is not in the Swarm refuses as before', () => {
+ const f = oneMachine(), group = f.group()
+ f.state.machines = f.state.machines!.filter(m => m.machineId !== 'mate-team')
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac')))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ })
+
+ it('a machines rule naming the Mac allows its team account', () => {
+ const f = oneMachine(), group = f.group()
+ f.run({ type: 'rule.set', projectId: 'lead', rule: { kind: 'machines', machineIds: ['mate-mac'] }, text: 'Only the MacBook Pro.' })
+ const effects = f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac'))
+ expect(effects.result.warnings).toBeUndefined()
+ expect(effects.messages).toEqual([])
+ })
+
+ it('a route that picked the Mac for a teammate\'s project keeps it, and the start there is the pick', () => {
+ const f = oneMachine()
+ const lead = String(f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: 'lead', name: 'Lead', configuration: config, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId)
+ const group = f.group(), leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'owner' }
+ const candidate = { id: 'c0', kind: 'new', machineId: 'mate-mac', engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2,
+ title: 'Builder on MacBook Pro', label: 'Codex' }
+ const effects = f.run({ type: 'route.record', conversationId: group, decision: { assessment: { difficulty: 'medium', risk: 'low', why: 'A small change.' },
+ candidates: [candidate], excluded: [], floor: 2, notes: false, pick: 'c0', via: 'order', p: null, belowFloor: false, why: 'Policy order.' } } as Command,
+ leadActor, { recentRoutes: 0 })
+ const recorded = effects.routeDecisions[0] as unknown as { id: string; record: RouteDecision['record'] }
+ expect(recorded.record.candidates).toEqual([expect.objectContaining({ id: 'c0' })])
+ const decision = { id: recorded.id, conversationId: group, record: recorded.record, final: null, override: null, assignmentId: null, outcome: null } as unknown as RouteDecision
+ const started = f.run({ type: 'agent.start', routeDecisionId: recorded.id, request: { ...f.request(group, 'mate-mac'), model: 'default', effort: 'default' } },
+ leadActor, { ...f.pooled('mate-mac'), routeDecision: decision })
+ expect(f.state.starts!.at(-1)!.request.machineId).toBe('mate-team')
+ expect(started.routeDecisions).toEqual([expect.objectContaining({ op: 'final', id: recorded.id })])
+ expect(started.routeDecisions[0]).not.toHaveProperty('override')
+ })
+
+ it('joins by itself where its owner added the Mac, under the Mac\'s name, slots and pause', () => {
+ const f = swarm()
+ f.state.machines = f.state.machines!.filter(m => m.machineId !== 'mate-team')
+ f.machine('mate-mac').paused = true
+ const join = { type: 'machine.contribute', machineId: 'mate-team', name: 'MacBook Pro · Team', cwd: '/team-swarm', scope: 'swarm', engines: ['codex'],
+ maxAgents: 2, ifMissing: true } as Command
+ f.run(join, mate, { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostMachineId: 'mate-mac' } })
+ expect(f.machine('mate-team')).toMatchObject({ hostMachineId: 'mate-mac', name: 'MacBook Pro', cwd: '/team-swarm', maxAgents: 4, paused: true, contributorId: 'mate' })
+ // Once there, a join again changes nothing.
+ f.run({ ...join, maxAgents: 1 } as Command, mate, { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostMachineId: 'mate-mac' } })
+ expect(f.machine('mate-team').maxAgents).toBe(4)
+ })
+
+ it('never joins by itself where its Mac is not in the Swarm', () => {
+ const f = swarm()
+ f.state.machines = f.state.machines!.filter(m => m.machineId !== 'mate-team' && m.machineId !== 'mate-mac')
+ expect(refusal(() => f.run({ type: 'machine.contribute', machineId: 'mate-team', name: 'x', cwd: '/team-swarm', scope: 'swarm', engines: ['codex'],
+ maxAgents: 2, ifMissing: true } as Command, mate, { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostMachineId: 'mate-mac' } }))?.code).toBe('OWNER_REQUIRED')
+ })
+
+ it('follows its Mac: paused, given other slots, renamed and removed with it', () => {
+ const f = oneMachine()
+ const teamAgent = f.member('team-agent', 'mate-team', 'mate')
+ f.run({ type: 'machine.pause', machineId: 'mate-mac', paused: true }, mate)
+ expect(f.machine('mate-team').paused).toBe(true)
+ f.run({ type: 'machine.contribute', machineId: 'mate-mac', name: 'Work MacBook', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 6 }, mate,
+ { contribution: { machineOwnerId: 'mate', contributorId: 'mate' } })
+ expect(f.machine('mate-team')).toMatchObject({ maxAgents: 6, paused: false, name: 'Work MacBook', generation: 'g1' })
+ const removed = f.run({ type: 'machine.remove', machineId: 'mate-mac' }, mate)
+ expect(f.machine('mate-team').removal).toMatchObject({ state: 'cleaning' })
+ expect(removed.result.removedAgents).toContain(teamAgent)
+ expect(f.state.agents.some(a => a.id === teamAgent)).toBe(false)
+ })
+
+ it('a teammate never moves another person\'s team account with their own Mac', () => {
+ const f = oneMachine()
+ f.machine('mate-team').contributorId = 'owner'
+ f.run({ type: 'machine.pause', machineId: 'mate-mac', paused: true }, mate)
+ expect(f.machine('mate-team').paused).toBe(false)
+ })
+})
+
+describe('one machine: the Mac\'s agent slots', () => {
+ it('are shared by the Mac and its Harness Team account', () => {
+ const f = swarm(), group = f.group()
+ Object.assign(f.machine('mate-team'), { hostMachineId: 'mate-mac', name: 'MacBook Pro', cwd: '/team-swarm', maxAgents: 2 })
+ f.machine('mate-mac').maxAgents = 2
+ f.member('mine', 'mate-mac', 'mate', f.mine)
+ f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac'))
+ // One on the owner's daemon and one in the team account: the Mac's two slots are taken, whichever side asks.
+ expect(machineSlots(f.state, f.machine('mate-mac'))).toBe(2)
+ expect(machineSlots(f.state, f.machine('mate-team'))).toBe(2)
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac')))?.code).toBe('MACHINE_FULL')
+ // A machine without a team account counts only its own.
+ expect(machineSlots(f.state, f.machine('owner-mac'))).toBe(0)
+ })
+})
+
+describe('one machine: a Mac whose Harness Team account was made again', () => {
+ // `harness team remove`, then `harness team setup`: a new account, computer and machine, while the old team machine's
+ // pool is still in the Swarm, silent. The Mac joins with the new one too (store.ts hostTabs).
+ function remade() {
+ const f = swarm()
+ Object.assign(f.machine('mate-team'), { hostMachineId: 'mate-mac', name: 'MacBook Pro', cwd: '/old-team', observation: reading('team', PASSED, NOW - 3_600_000) })
+ f.state.machines!.push({ ...structuredClone(f.machine('mate-team')), machineId: 'mate-team-2', cwd: '/team-swarm', observation: reading('team', PASSED) })
+ return f
+ }
+
+ it('sends a teammate\'s start on the Mac to the account that runs, not the old one', () => {
+ const f = remade(), group = f.group()
+ f.member('old-agent', 'mate-team', 'mate')
+ f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac'))
+ expect(f.state.starts![0]!.request).toMatchObject({ machineId: 'mate-team-2', cwd: '/team-swarm/lead' })
+ // The old account's leftover agent holds none of the Mac's slots.
+ expect(machineSlots(f.state, f.machine('mate-mac'))).toBe(1)
+ })
+
+ it('pauses and removes both with the Mac, and its removal preview names every agent it takes', () => {
+ const f = remade()
+ const old = f.member('old-agent', 'mate-team', 'mate'), fresh = f.member('new-agent', 'mate-team-2', 'mate')
+ f.run({ type: 'machine.pause', machineId: 'mate-mac', paused: true }, mate)
+ expect([f.machine('mate-team').paused, f.machine('mate-team-2').paused]).toEqual([true, true])
+ expect(removalPreview(f.state, mate, 'mate-mac').agents.map(a => a.id).sort()).toEqual([fresh, old].sort())
+ f.run({ type: 'machine.remove', machineId: 'mate-mac' }, mate)
+ expect(f.machine('mate-team-2').removal?.state).toBe('cleaning')
+ // The silent old one leaves the list at once; its cleanup waits for its host, as for any offline machine.
+ expect(f.state.machines!.some(m => m.machineId === 'mate-team')).toBe(false)
+ expect(f.state.machineCleanups).toEqual(expect.arrayContaining([expect.objectContaining({ machineId: 'mate-team' })]))
+ })
+
+ it('never sends work to an account that is being removed', () => {
+ const f = swarm(), group = f.group()
+ Object.assign(f.machine('mate-team'), { hostMachineId: 'mate-mac', name: 'MacBook Pro', removal: { id: 'r', state: 'cleaning', requestedAt: new Date(NOW).toISOString() } })
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac')))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ })
+})
diff --git a/cli/src/superTabs/contribution.spec.ts b/cli/src/superTabs/contribution.spec.ts
index f01ae6bcf..e828d786b 100644
--- a/cli/src/superTabs/contribution.spec.ts
+++ b/cli/src/superTabs/contribution.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
-import { ContributionPreparations, prepareContribution } from './contribution.js'
+import { ContributionPreparations, prepareContribution, prepareTeamContribution } from './contribution.js'
import { mkdtemp, rm, stat } from 'node:fs/promises'
import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -43,6 +43,23 @@ describe('one-field machine preparation', () => {
await rm(dataDir, { recursive: true, force: true })
}
})
+ // A Mac's Harness Team account reads no Swarm as the person (backend lib/teamSession.ts): its Mac's daemon adds it, and it
+ // prepares its own swarm workspace without that read ("One machine", docs/plans/2026-10-24-swarm-team-account.md).
+ it('prepares a Harness Team account\'s swarm workspace without reading the Swarm, and only that', async () => {
+ const f = fixture()
+ const dataDir = await mkdtemp(join(tmpdir(), 'harness-swarm-contribution-'))
+ try {
+ const core = fakeCore({ dataDir })
+ const team = { ...f.deps, team: () => true }
+ const result = await prepareContribution(core, { tabId: 'tab', scope: 'swarm' }, team as never)
+ expect(result).toMatchObject({ scope: 'swarm', cwd: join(homedir(), 'harnesses', 'swarms', 'tab'), engines: ['claude', 'codex'] })
+ expect(f.deps.backend).not.toHaveBeenCalled()
+ await expect(prepareContribution(core, { tabId: 'tab' }, team as never)).rejects.toThrow('swarm')
+ } finally {
+ await rm(join(homedir(), 'harnesses', 'swarms', 'tab'), { recursive: true, force: true })
+ await rm(dataDir, { recursive: true, force: true })
+ }
+ })
it('uses the lead project on its host and probes all engines without inventing authentication', async () => {
const f = fixture()
expect(await f.run()).toEqual({ ok: true, state: 'ready', cwd: '/repo', engines: ['claude', 'codex'], maxAgents: 8, maxAvailableAgents: 16 })
@@ -129,3 +146,33 @@ describe('one-field machine preparation', () => {
expect(jobs.read({ tabId: 'tab', operationId: 'extra' })).toMatchObject({ error: 'SETUP_BUSY' })
})
})
+
+describe('this Mac\'s Harness Team account preparing through the relay', () => {
+ function relay(answers: Record<string, unknown>[]) {
+ const core = fakeCore()
+ const request = vi.fn(async () => answers.shift() ?? { ok: true, state: 'preparing' })
+ const close = vi.fn()
+ const open = vi.fn(async () => ({ machineId: 'team-1', request, close }))
+ let clock = 0
+ const deps = { open, sleep: vi.fn(async () => { clock += 1_000 }), deadlineMs: 3_000, now: () => clock }
+ return { core, request, close, open, deps }
+ }
+
+ it('asks the team account\'s own daemon, keeps one receipt while it prepares, and closes the line', async () => {
+ const r = relay([{ ok: true, state: 'preparing' }, { ok: true, state: 'ready', scope: 'swarm', cwd: '/Users/harnessteam/harnesses/swarms/tab', engines: ['codex'] }])
+ expect(await prepareTeamContribution(r.core, { tabId: 'tab', machineId: 'team-1' }, r.deps as never)).toMatchObject({ cwd: '/Users/harnessteam/harnesses/swarms/tab' })
+ expect(r.open).toHaveBeenCalledWith({ dataDir: r.core.dataDir, port: r.core.daemon.port, machineId: r.core.daemon.machineId() }, 'team-1')
+ const [first, second] = r.request.mock.calls as unknown as [string, Record<string, unknown>][]
+ expect(first![1]).toMatchObject({ action: 'prepareContribution', tabId: 'tab', scope: 'swarm' })
+ expect(second![1].operationId).toBe(first![1].operationId)
+ expect(r.close).toHaveBeenCalledOnce()
+ })
+
+ it('says why it could not, and gives up after its deadline', async () => {
+ const failed = relay([{ error: 'SETUP_FAILED', detail: 'Install Claude Code or Codex on this machine, then try again.' }])
+ await expect(prepareTeamContribution(failed.core, { tabId: 'tab', machineId: 'team-1' }, failed.deps as never)).rejects.toThrow('Install Claude Code or Codex')
+ const slow = relay([])
+ await expect(prepareTeamContribution(slow.core, { tabId: 'tab', machineId: 'team-1' }, slow.deps as never)).rejects.toThrow('still preparing')
+ expect(slow.close).toHaveBeenCalledOnce()
+ })
+})
diff --git a/cli/src/superTabs/contribution.ts b/cli/src/superTabs/contribution.ts
index c134d83ae..52e0c48f8 100644
--- a/cli/src/superTabs/contribution.ts
+++ b/cli/src/superTabs/contribution.ts
@@ -4,17 +4,24 @@ import { parseProjectFolder, prepareProjectFolder } from '../lib/projectFolder.j
import { readCapabilities, START_REQUIREMENTS } from './capacity.js'
import { backend, identifier, object } from './host.js'
import { mkdir } from 'node:fs/promises'
+import { readAuthSession } from '../lib/authSession.js'
+import { randomUUID } from 'node:crypto'
import { repairSwarmCloneTrust, swarmCloneRoot, swarmCloneRoots } from './cloneTrust.js'
type Json = Record<string, unknown>
/** Owner-only setup. Reuses the regular checkout preparation and engine probe;
* it neither launches an agent nor grants the team access to the computer. */
-export async function prepareContribution(core: CoreApi, input: Json, deps = {
- backend, open: openDaemon, prepare: prepareProjectFolder, capacity: readCapabilities,
-}): Promise<Json> {
+export async function prepareContribution(core: CoreApi, input: Json, deps: {
+ backend: typeof backend; open: typeof openDaemon; prepare: typeof prepareProjectFolder; capacity: typeof readCapabilities; team?: () => boolean
+} = { backend, open: openDaemon, prepare: prepareProjectFolder, capacity: readCapabilities }): Promise<Json> {
if (!identifier(input.tabId)) throw new Error('Choose a Super Tab.')
- const answer = object(await deps.backend(core, 'GET', `/api/super-tabs/${input.tabId}`))
+ // A Mac's Harness Team account reads no Swarm as the person (backend lib/teamSession.ts). Its Mac's daemon adds it, as a
+ // swarm workspace in its own clone root (host.ts joinTeams), so it needs no read ("One machine" in
+ // docs/plans/2026-10-24-swarm-team-account.md).
+ const team = (deps.team ?? (() => readAuthSession()?.kind === 'team'))()
+ if (team && input.scope !== 'swarm') throw new Error('A Harness Team account joins a Swarm only as a swarm workspace.')
+ const answer = team ? {} : object(await deps.backend(core, 'GET', `/api/super-tabs/${input.tabId}`))
const state = object(answer.state), project = object(state.project)
const machineId = core.daemon.machineId()
const existing = (Array.isArray(state.machines) ? state.machines.map(object) : []).find(m => m.machineId === machineId)
@@ -54,6 +61,29 @@ export async function prepareContribution(core: CoreApi, input: Json, deps = {
} finally { connection.close() }
}
+/**
+ * This Mac's Harness Team account preparing its own swarm workspace (prepareContribution, in that account's daemon), asked
+ * through the relay as Desktop asks a machine it adds: its folder and engines are its own, which this Mac's daemon cannot
+ * see. Polls the same receipt while it prepares ("One machine" in docs/plans/2026-10-24-swarm-team-account.md).
+ */
+export async function prepareTeamContribution(core: CoreApi, input: { tabId: string; machineId: string }, deps = {
+ open: openDaemon, sleep: (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)), deadlineMs: 5 * 60_000, now: Date.now,
+}): Promise<Json> {
+ const connection = await deps.open({ dataDir: core.dataDir, port: core.daemon.port, machineId: core.daemon.machineId() }, input.machineId)
+ try {
+ const operationId = randomUUID(), deadline = deps.now() + deps.deadlineMs
+ for (;;) {
+ const answer = object(await connection.request('super_tabs', { action: 'prepareContribution', tabId: input.tabId, scope: 'swarm', operationId }, 30_000))
+ if (answer.state === 'ready' && answer.scope === 'swarm' && typeof answer.cwd === 'string') return answer
+ if (answer.state !== 'preparing') {
+ throw new Error(typeof answer.detail === 'string' ? answer.detail : `The Harness Team account could not prepare its workspace (${String(answer.error ?? 'no answer')}).`)
+ }
+ if (deps.now() >= deadline) throw new Error('The Harness Team account is still preparing its workspace.')
+ await deps.sleep(1_000)
+ }
+ } finally { connection.close() }
+}
+
/** Cloning can outlive one RPC. Poll the same receipt instead of blocking the
* core/service request or dispatching another checkout after a timeout. */
export class ContributionPreparations {
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index cb0ca7f7e..83e5b70b7 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -1121,6 +1121,64 @@ describe('adding the machine its own Lead runs on to the Swarm', () => {
})
})
+// One machine (docs/plans/2026-10-24-swarm-team-account.md): this Mac's Harness Team account is this Mac under the scenes.
+// Where its owner added this Mac, the roster names the team account still missing (backend store.ts hostTabs `joinTeam`);
+// the team account prepares its own workspace, asked through the relay, and this host adds it as the person.
+describe('adding this Mac\'s Harness Team account where this Mac was added', () => {
+ function joining() {
+ const dir = mkdtempSync(join(tmpdir(), 'super-tab-team-join-')); roots.push(dir)
+ const rows: Record<string, unknown>[] = [{ tabId: 'own', joinTeam: { machineId: 'team-1', name: 'MacBook Pro', maxAgents: 4 } }, { tabId: 'other', joinTeam: {} }]
+ const commands: unknown[] = [], refusals: string[] = []
+ let clock = 0
+ const call: CoreApi['account']['backend'] = vi.fn(async (method, path, body) => {
+ if (path.endsWith('/commands')) {
+ commands.push({ path, ...(body as object) })
+ const code = refusals.shift()
+ if (code) return { status: 409, body: { success: false, error: { code, message: `Refused: ${code}` } } }
+ return { status: 200, body: { success: true, data: {} } }
+ }
+ return { status: 200, body: { success: true, data: path.includes('/hosts/') ? rows : [] } }
+ })
+ const core = fakeCore({ dataDir: dir, account: { backend: call, machineName: vi.fn(() => 'MacBook Pro') } })
+ const prepareTeam = vi.fn(async () => ({ ok: true, state: 'ready', cwd: '/Users/harnessteam/harnesses/swarms/own', engines: ['claude'], maxAgents: 8, scope: 'swarm' }))
+ const prepare = vi.fn()
+ const log = vi.fn()
+ const host = new SuperTabHost(core, 'machine-1', { log, now: () => clock, prepareContribution: prepare as never, prepareTeam }); hosts.push(host)
+ const pass = async (at: number) => {
+ clock = at
+ const tries = prepareTeam.mock.calls.length, heard = commands.length + log.mock.calls.length
+ await host.tick()
+ if (prepareTeam.mock.calls.length > tries) await vi.waitFor(() => expect(commands.length + log.mock.calls.length).toBeGreaterThan(heard))
+ }
+ return { core, rows, commands, refusals, prepareTeam, prepare, log, pass }
+ }
+
+ it('adds it once, prepared by its own daemon, with this Mac\'s name and slots', async () => {
+ const t = joining()
+ await t.pass(0)
+ expect(t.prepareTeam).toHaveBeenCalledExactlyOnceWith(t.core, { tabId: 'own', machineId: 'team-1' })
+ expect(t.prepare).not.toHaveBeenCalled()
+ expect(t.commands).toEqual([{ path: '/api/super-tabs/own/commands', operationId: expect.any(String), command: { type: 'machine.contribute',
+ machineId: 'team-1', name: 'MacBook Pro', cwd: '/Users/harnessteam/harnesses/swarms/own', scope: 'swarm', engines: ['claude'], maxAgents: 4, ifMissing: true } }])
+ t.rows.splice(0, 1)
+ await t.pass(120_000)
+ expect(t.prepareTeam).toHaveBeenCalledTimes(1)
+ })
+
+ it('backs off while the team account cannot prepare (offline, signed out), and says why', async () => {
+ const t = joining()
+ t.prepareTeam.mockRejectedValueOnce(new Error('That machine is not reachable now.'))
+ await t.pass(0)
+ expect(t.commands).toEqual([])
+ expect(t.log).toHaveBeenCalledWith('Could not add this Mac\'s Harness Team account to its Swarm: That machine is not reachable now.')
+ await t.pass(59_000)
+ expect(t.prepareTeam).toHaveBeenCalledTimes(1)
+ await t.pass(60_000)
+ expect(t.prepareTeam).toHaveBeenCalledTimes(2)
+ expect(t.commands).toHaveLength(1)
+ })
+})
+
describe('built-in skill text after a CLI update', () => {
const older = '---\nname: swarm-dev\n---\nAn older release of this skill.\n'
function syncFixture(stale = true, mode?: 'default' | 'orchestration') {
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index da44107d9..f88fed23f 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -15,7 +15,7 @@ import { readAuthSession } from '../lib/authSession.js'
import { computerId } from '../lib/daemonState.js'
import { noticeReason, WithheldDeliveries } from './withheld.js'
import { attentionOf } from './attention.js'
-import { prepareContribution } from './contribution.js'
+import { prepareContribution, prepareTeamContribution } from './contribution.js'
import { hostname } from 'node:os'
import { replacementObservations } from './replacements.js'
import { TerminalHost } from './terminal.js'
@@ -92,6 +92,8 @@ export interface SuperTabHostOptions {
observers?: typeof publishObservers
attachedFiles?: typeof attachedFiles
prepareContribution?: typeof prepareContribution
+ /** This Mac's Harness Team account preparing its workspace through the relay (contribution.ts), for a spec. */
+ prepareTeam?: (core: CoreApi, input: { tabId: string; machineId: string }) => Promise<Record<string, unknown>>
/** The `… super-tab` prefix agents are told to run (superTabs/shortCommand.ts), for a spec. */
agentCommand?: (core: CoreApi, machineId: string) => Promise<string>
/** The Swarm start this machine made of a harness (superTabs/reservations.ts), or null. */
@@ -169,8 +171,11 @@ export class SuperTabHost {
private shareWoken = false
private readonly attachedFiles: typeof attachedFiles
private readonly prepareContribution: typeof prepareContribution
+ private readonly prepareTeam: NonNullable<SuperTabHostOptions['prepareTeam']>
/** Per tab the roster marks, the add in progress or when the next may run. */
private readonly joins = new Map<string, { running: boolean; failures: number; retryAt: number }>()
+ /** This Mac's Harness Team account being added to a Swarm, by `tabId:machineId` (joinTeams). */
+ private readonly teamJoins = new Map<string, { running: boolean; failures: number; retryAt: number }>()
/** Each delivery's downloaded files, so input held by a busy terminal is not downloaded again on every retry. Only a
* complete download is kept: a failed one is tried again before the next delivery of the same message. */
private readonly files = new Map<string, string>()
@@ -234,6 +239,7 @@ export class SuperTabHost {
this.observers = options.observers ?? publishObservers
this.attachedFiles = options.attachedFiles ?? attachedFiles
this.prepareContribution = options.prepareContribution ?? prepareContribution
+ this.prepareTeam = options.prepareTeam ?? ((core, input) => prepareTeamContribution(core, input))
this.agentCommand = options.agentCommand ?? defaultAgentCommand
this.startReceipt = options.startReceipt ?? (() => null)
this.now = options.now ?? Date.now
@@ -512,6 +518,7 @@ export class SuperTabHost {
this.wakeShare(data)
this.publishAttention(data)
this.joinSwarms(data)
+ this.joinTeams(data)
this.cleanRemoved(data)
// Off the poll: a screen read waits on the core, and never delays the input leases below.
if (this.core.superTabs) void this.terminal.tick(data)
@@ -775,6 +782,40 @@ export class SuperTabHost {
}
}
+ /**
+ * This Mac's Harness Team account joins wherever its owner added this Mac ("One machine" in
+ * docs/plans/2026-10-24-swarm-team-account.md): the roster names each Swarm where it is missing (backend store.ts hostTabs
+ * `joinTeam`). It prepares its own folder and engines, asked through the relay, and this host adds it as the person, who
+ * owns both; the backend gives it this Mac's name, slots and pause. Retried like joinSwarms while it is offline.
+ */
+ private joinTeams(rows: unknown[]): void {
+ const marked = new Map<string, { tabId: string; machineId: string; name: unknown; maxAgents: unknown }>()
+ for (const row of rows.map(object)) {
+ const team = object(row.joinTeam)
+ if (identifier(row.tabId) && identifier(team.machineId)) {
+ marked.set(`${row.tabId}:${team.machineId}`, { tabId: row.tabId, machineId: team.machineId, name: team.name, maxAgents: team.maxAgents })
+ }
+ }
+ for (const [key, join] of this.teamJoins) if (!marked.has(key) && !join.running) this.teamJoins.delete(key)
+ for (const [key, team] of marked) {
+ const join = this.teamJoins.get(key) ?? { running: false, failures: 0, retryAt: 0 }
+ if (join.running || join.retryAt > this.now()) continue
+ join.running = true
+ this.teamJoins.set(key, join)
+ void (async () => {
+ const prepared = await this.prepareTeam(this.core, { tabId: team.tabId, machineId: team.machineId })
+ await backend(this.core, 'POST', `/api/super-tabs/${team.tabId}/commands`, { operationId: randomUUID(), command: {
+ type: 'machine.contribute', machineId: team.machineId, name: typeof team.name === 'string' && team.name ? team.name : this.core.account.machineName() ?? hostname(),
+ cwd: prepared.cwd, scope: 'swarm', engines: prepared.engines,
+ maxAgents: typeof team.maxAgents === 'number' ? team.maxAgents : prepared.maxAgents, ifMissing: true } })
+ })().then(() => { join.failures = 0; join.retryAt = this.now() + JOIN_RETRY_MS }, error => {
+ join.retryAt = error instanceof SuperTabHostError && JOIN_FINAL.has(error.code) ? Infinity
+ : this.now() + Math.min(JOIN_RETRY_MAX_MS, JOIN_RETRY_MS * 2 ** join.failures++)
+ this.log(`Could not add this Mac's Harness Team account to its Swarm: ${error instanceof Error ? error.message : String(error)}`)
+ }).finally(() => { join.running = false })
+ }
+ }
+
/** Its owner removed this machine from a Swarm: the roster names the cleanup until this host acknowledges it, so a host
* that restarted part-way cleans again. Off the poll: deleting folders never delays deliveries. */
private cleanRemoved(rows: unknown[]): void {
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 4da0cc5d2..a76996a07 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -792,6 +792,52 @@ describe('routing contributed capacity', () => {
const silent = await runPool(offline, false, {}, owners)
expect(silent.answer.excluded).not.toEqual(expect.arrayContaining([expect.objectContaining({ reason: expect.stringContaining('Contributed laptop is offline.') })]))
})
+ // One machine (docs/plans/2026-10-24-swarm-team-account.md): a Mac's Harness Team account is that Mac. The Lead is offered
+ // the Mac once: a teammate's project starts in the team account, the Mac's owner's own projects stay with the owner.
+ describe('a Mac and its Harness Team account', () => {
+ const NO_ACCOUNT = 'MacBook Pro has no Harness Team account yet, so it runs only its owner\'s projects.'
+ const mac = () => ({ ...healthy(), name: 'MacBook Pro', scope: 'swarm', cwd: '/mate/swarm', contributorId: 'mate',
+ teamWork: { allowed: false, code: 'TEAM_ACCOUNT_REQUIRED', reason: NO_ACCOUNT } })
+ const team = () => ({ ...healthy(), machineId: 'm1-team', hostMachineId: 'm1', name: 'MacBook Pro', scope: 'swarm', cwd: '/team/swarm', contributorId: 'mate',
+ teamWork: { allowed: true } })
+ async function route(ownerId: string, machines: Record<string, unknown>[] = [mac(), team()], rules: unknown[] = []) {
+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: { state: { id: 'tab', agents: [agents[1]], conversations: conversations(), machines,
+ projects: [{ id: 'lead', ownerId, repository: { repositoryUrl: 'https://github.com/example/project' } }], ...(rules.length ? { rules } : {}) } },
+ policy: { policy, warnings: [] }, machines: [] } } })
+ const answer = await routeTask(input, s, where, opener())
+ const decision = s.mock.calls.find(c => c[0].action === 'command')?.[0].command.decision
+ return { answer, candidates: (decision?.candidates ?? []) as Array<{ machineId: string; kind: string }>,
+ excluded: (decision?.excluded ?? answer.excluded ?? []) as Array<{ reason: string }> }
+ }
+
+ it('starts a teammate\'s project in the team account, under the Mac\'s name, without calling the Mac unfit', async () => {
+ const { answer, candidates, excluded } = await route('owner')
+ expect(answer).toMatchObject({ ok: true, pick: { machineId: 'm1-team' } })
+ expect(answer.next).toContain('/team/swarm/lead')
+ expect(candidates.filter(c => c.kind === 'new').map(c => c.machineId)).toEqual(expect.arrayContaining(['m1-team']))
+ expect(candidates.some(c => c.kind === 'new' && c.machineId === 'm1')).toBe(false)
+ expect(excluded.some(e => e.reason === NO_ACCOUNT)).toBe(false)
+ })
+
+ it('keeps the Mac\'s owner\'s own project with the owner, never the team account', async () => {
+ const { answer, candidates } = await route('mate')
+ expect(answer).toMatchObject({ ok: true, pick: { machineId: 'm1' } })
+ expect(candidates.some(c => c.machineId === 'm1-team')).toBe(false)
+ })
+
+ it('says the team account\'s own reason when it cannot take the work, and still offers nothing as the owner', async () => {
+ const reason = 'The Harness Team account on MacBook Pro is not private (gitconfig: it could read its owner\'s ~/.gitconfig), so it runs only its owner\'s projects.'
+ const { answer, excluded } = await route('owner', [mac(), { ...team(), teamWork: { allowed: false, code: 'PRIVACY_CHECK_FAILED', reason } }])
+ expect(answer).toMatchObject({ error: 'NO_CANDIDATE' })
+ expect(excluded.map(e => e.reason)).toContain(reason)
+ expect(excluded.some(e => e.reason === NO_ACCOUNT)).toBe(false)
+ })
+
+ it('a machines rule naming the Mac allows its team account', async () => {
+ const rules = [{ id: 'r1', projectId: 'lead', rule: { kind: 'machines', machineIds: ['m1'] }, text: 'Only the MacBook Pro.' }]
+ expect((await route('owner', undefined, rules)).answer).toMatchObject({ ok: true, pick: { machineId: 'm1-team' } })
+ })
+ })
it('refuses unobserved tools and devices, without probing arbitrary paths on a teammate computer', async () => {
expect((await runPool(healthy(), false, { tools: ['docker'], devices: ['/dev/fixture'] })).answer.ok).not.toBe(true)
})
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 3015f13bd..cbf12f765 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -131,7 +131,11 @@ export async function routeTask(input: { tabId: string; conversationId: string;
if (review) assessment = { ...assessment, kind: 'review' }
// A backend from before rules keeps none, so routing there is the policy order alone. Rules bind only their own project's
// groups; a backend from before per-project rules gives none a project, and its rules bind every group.
- const rules = list(state.rules).filter(r => r.rule && typeof r.text === 'string' && (r.projectId === undefined || r.projectId === projectId)) as unknown as SwarmRule[]
+ // A Mac's Harness Team account is that Mac (One machine, below): a machines rule naming the Mac allows it too.
+ const macOf = new Map(list(state.machines).filter(m => typeof m.hostMachineId === 'string').map(m => [String(m.machineId), String(m.hostMachineId)]))
+ const rules = (list(state.rules).filter(r => r.rule && typeof r.text === 'string' && (r.projectId === undefined || r.projectId === projectId)) as unknown as SwarmRule[])
+ .map(r => r.rule.kind !== 'machines' ? r : { ...r, rule: { ...r.rule,
+ machineIds: [...r.rule.machineIds, ...[...macOf].filter(([, mac]) => r.rule.kind === 'machines' && r.rule.machineIds.includes(mac)).map(([team]) => team)] } })
const members = agents.filter(a => !busy.has(String(a.id)) && (a.role === 'reviewer') === review && ENGINES.includes(String(object(a.configuration).engine))).map(a => withLaunchEffort(a, list(state.starts)))
// A new agent starts only on a machine in the Swarm's Machines list (the backend refuses any other): a contributed machine, or
// one an agent of the Swarm runs on. The Lead runs here, so its own machine is always listed. Of the account's machines
@@ -139,7 +143,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// (production, 2026-10-21). A member may run on a machine only its collaborator can open; the Lead tries that machine
// too, but a member there is unknown, never offline.
const swarmMachines = new Set([where.machineId, ...list(state.machines).map(m => String(m.machineId)), ...agents.map(a => String(a.machineId))])
- const machines = new Map<string, { name: string; status: string; account: boolean; pool?: Json }>()
+ const machines = new Map<string, { name: string; status: string; account: boolean; pool?: Json; folded?: boolean }>()
for (const m of list(value.machines)) if (swarmMachines.has(String(m.machineId))) machines.set(String(m.machineId), { name: String(m.name), status: String(m.status ?? 'unknown'), account: true })
// The Lead's own machine is the account's even when the list could not be read.
if (!machines.has(where.machineId)) machines.set(where.machineId, { name: where.machineId, status: 'unknown', account: true })
@@ -162,6 +166,14 @@ export async function routeTask(input: { tabId: string; conversationId: string;
}
machines.set(String(pool.machineId), { name: String(pool.name), status: 'contributed', account: false, pool })
}
+ // One machine (docs/plans/2026-10-24-swarm-team-account.md): a Mac's Harness Team account is that Mac, under its name. A
+ // teammate's project starts only in the team account and the Mac's owner's own projects only with the owner, so only one
+ // of the two offers new agents here, and the other is not listed as unfit; agents already on either stay members.
+ for (const [team, mac] of macOf) {
+ const pool = machines.get(team)?.pool
+ if (!pool || !machines.has(mac)) continue
+ machines.get(projectOwner === pool.contributorId ? team : mac)!.folded = true
+ }
const enabled = policy.models.filter(m => m.enabled && ENGINES.includes(m.engine))
// The probes do not wait for the context reads: the machines, the task's folder and the group's talk and log are read
@@ -303,12 +315,13 @@ export function localProbes(state: Json, policy: Policy, probes: Probe[], a: Ass
refusals: base.refusals.filter(r => !SUBSCRIPTION.test(r)), gridModel: m.model, gridName: m.grid, gridLabel: m.label, gridKind: m.kind })))
}
-async function probeMachine(machineId: string, { name: machineName, status, account, pool }: { name: string; status: string; account: boolean; pool?: Json },
+async function probeMachine(machineId: string, { name: machineName, status, account, pool, folded }: { name: string; status: string; account: boolean; pool?: Json; folded?: boolean },
members: Json[], allModels: Policy['models'], policy: Policy, a: Assessment, where: Where, open: typeof openDaemon): Promise<Probe[]> {
const listedEngines = Array.isArray(pool?.engines) ? pool.engines.filter((engine): engine is string => typeof engine === 'string') : []
const legacy = listedEngines.some(engine => !ENGINES.includes(engine))
const installed = legacy ? list(object(pool?.observation).quotas).map(quota => quota.engine) : listedEngines
- const models = pool ? allModels.filter(m => installed.includes(m.engine)) : account ? allModels : []
+ // A Mac folded into its Harness Team account, or the other way round, offers no new agent of its own (routeTask).
+ const models = folded ? [] : pool ? allModels.filter(m => installed.includes(m.engine)) : account ? allModels : []
const engines = [...new Set([...models.map(m => m.engine), ...members.map(m => String(object(m.configuration).engine) as 'claude' | 'codex')])]
const memberProbe = (m: Json, refusals: string[] = [], quota = UNKNOWN_QUOTA, frame: MemberFrame | null = null, terminalUnverified = false): Probe => {
const c = object(m.configuration), engine = String(c.engine) as 'claude' | 'codex'
diff --git a/cli/src/team/handoff.spec.ts b/cli/src/team/handoff.spec.ts
index 4d6461b8e..f06aee03c 100644
--- a/cli/src/team/handoff.spec.ts
+++ b/cli/src/team/handoff.spec.ts
@@ -29,6 +29,27 @@ describe('mintTeamHandoff', () => {
expect(post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team' }, headers)
})
+ // One machine (docs/plans/2026-10-24-swarm-team-account.md): the team machine records the Mac it lives on, so every
+ // list shows that Mac once. The backend checks the machine is one of the account's own.
+ it('names this computer\'s own machine as the Mac the team account lives on, once it has one', async () => {
+ const post = vi.fn(async () => ({ code: CODE, expiresIn: 90 }))
+ await mintTeamHandoff(async () => ({ session: { ...computer, machineId: 'machine-placeholder-1' }, headers }), post as never)
+ expect(post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team', hostMachineId: 'machine-placeholder-1' }, headers)
+ })
+
+ it('mints without naming its Mac when the backend refuses that machine, so setup still signs the team account in', async () => {
+ const post = vi.fn(async (_path: string, body: Record<string, unknown>) => {
+ if (body.hostMachineId) throw Object.assign(new Error('That machine is not one of this account\'s computers'), { status: 403 })
+ return { code: CODE, expiresIn: 90 }
+ })
+ await expect(mintTeamHandoff(async () => ({ session: { ...computer, machineId: 'stale-machine' }, headers }), post as never)).resolves.toEqual({ code: CODE, expiresIn: 90 })
+ expect(post.mock.calls.map(c => c[1])).toEqual([{ kind: 'team', hostMachineId: 'stale-machine' }, { kind: 'team' }])
+ // Any other failure is not asked again.
+ const down = vi.fn(async () => { throw Object.assign(new Error('Bad gateway'), { status: 502 }) })
+ await expect(mintTeamHandoff(async () => ({ session: { ...computer, machineId: 'm' }, headers }), down as never)).rejects.toMatchObject({ code: 'BACKEND' })
+ expect(down).toHaveBeenCalledTimes(1)
+ })
+
it('refuses a team sign-in, a signed-out computer and an answer without a code', async () => {
const post = vi.fn(async () => ({ code: CODE }))
await expect(mintTeamHandoff(async () => ({ session: { ...computer, kind: 'team' }, headers }), post as never)).rejects.toMatchObject({ code: 'TEAM_SESSION' })
diff --git a/cli/src/team/handoff.ts b/cli/src/team/handoff.ts
index 1a2e21673..e170fdcab 100644
--- a/cli/src/team/handoff.ts
+++ b/cli/src/team/handoff.ts
@@ -25,7 +25,9 @@ export type Delete = <T>(path: string, headers?: Record<string, string>) => Prom
type SignedIn = { session: AuthSession; headers: Record<string, string> }
export class TeamSignInError extends Error {
- constructor(message: string, readonly code: 'NOT_SIGNED_IN' | 'TEAM_SESSION' | 'EXPIRED' | 'BACKEND' | 'NOT_TEAM' | 'UNSAFE_FILE' | 'NO_PROOF') {
+ constructor(message: string, readonly code: 'NOT_SIGNED_IN' | 'TEAM_SESSION' | 'EXPIRED' | 'BACKEND' | 'NOT_TEAM' | 'UNSAFE_FILE' | 'NO_PROOF',
+ /** The backend's HTTP status, when it answered with one. */
+ readonly status?: number) {
super(message)
this.name = 'TeamSignInError'
}
@@ -61,9 +63,20 @@ async function signedIn(auth: () => Promise<SignedIn>): Promise<SignedIn> {
return answer
}
-/** A team handoff code from this computer's own sign-in. Refused for a team sign-in: it may not hand one out. */
+/** A team handoff code from this computer's own sign-in. Refused for a team sign-in: it may not hand one out. It names this
+ * computer's machine as the Mac the team account lives on, which the backend checks is one of the account's own and the team
+ * machine records, so every list shows this Mac once (docs/plans/2026-10-24-swarm-team-account.md, "One machine"). */
export async function mintTeamHandoff(auth: () => Promise<SignedIn>, post: Post): Promise<{ code: string; expiresIn: number }> {
- const { headers } = await signedIn(auth)
+ const { session, headers } = await signedIn(auth)
+ if (session.machineId) {
+ try {
+ return await requestCode(post, { kind: 'team', hostMachineId: session.machineId }, headers)
+ } catch (error) {
+ // A machine id the backend no longer takes as this computer's (deleted, stale): the team account still signs in,
+ // listed as a machine of its own until a setup names its Mac again.
+ if ((error as TeamSignInError).status !== 403) throw error
+ }
+ }
return requestCode(post, { kind: 'team' }, headers)
}
@@ -115,7 +128,7 @@ async function requestCode(post: Post, body: Record<string, unknown>, headers: R
try {
minted = await post('/api/auth/handoff', body, headers)
} catch (error) {
- throw new TeamSignInError(`Harness would not give a team sign-in code: ${(error as Error).message}`, 'BACKEND')
+ throw new TeamSignInError(`Harness would not give a team sign-in code: ${(error as Error).message}`, 'BACKEND', (error as { status?: number }).status)
}
if (typeof minted?.code !== 'string' || !HANDOFF_CODE.test(minted.code)) {
throw new TeamSignInError('Harness answered without a team sign-in code.', 'BACKEND')
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index bdab71566..44dc9dadf 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -72,14 +72,15 @@ class SuperTabAgentInfo {
_known(agent.configuration['model'] as String?);
String? get engine =>
_known(agent.engine) == null ? null : engineIdentity(agent.engine).label;
- String? get machine =>
- _known(app?.stateOf(agent.machineId)?.machine.displayName) ??
- _known(
- controller.snapshot?.machines
- .where((m) => m['machineId'] == agent.machineId)
- .firstOrNull?['name']
- as String?,
- );
+
+ /// The computer it runs on: the Mac, for an agent in that Mac's Harness Team account ([SuperTabSnapshot.placeOf]).
+ String? get machine {
+ final place =
+ controller.snapshot?.placeOf(agent.machineId) ?? agent.machineId;
+ return _known(app?.stateOf(place)?.machine.displayName) ??
+ _known(controller.snapshot?.pool(place)?['name'] as String?);
+ }
+
String? get folder => _known(native?.project?.cwd);
DateTime? get started => native?.createdAt;
DateTime? get lastActive => native?.lastActivityAt;
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 694f91351..9dc12a3a6 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -375,6 +375,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
m['machineId'] as String,
};
+ /// The rows: one per computer, a Mac's Harness Team account inside its Mac's ([SuperTabSnapshot.placeOf]).
+ Iterable<String> get _rowIds =>
+ _ids.where((id) => (c.snapshot?.placeOf(id) ?? id) == id);
+
@override
void initState() {
super.initState();
@@ -482,9 +486,14 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
m['machineId'] as String,
};
// Unavailable computers stay inspectable in the picker, but another
- // account's computers must never be offered for contribution.
+ // 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)
+ .where((m) => !m.belongsToOtherAccount && ownRow(m))
.toList();
({IconData icon, String message})? unavailable(MachineState m) {
if (!isExisting(m) && contributed.contains(m.machine.machineId)) {
@@ -906,26 +915,35 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
/// 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, state = app?.stateOf(id);
- final shared = c.snapshot?.machines
- .where((m) => m['machineId'] == id)
- .firstOrNull;
- final agents = c.snapshot!.agents.where((a) => a.machineId == id).toList();
+ final app = widget.app, snapshot = c.snapshot!;
+ final shared = snapshot.pool(id);
+ // The Mac's Harness Team account is part of its row: its agents are listed here, and everyone but the Mac's owner
+ // reads its availability, since it runs their agents, also while the owner is away from the Mac. The owner reads
+ // their own computer. Actions stay the Mac's; the backend changes its team account with it.
+ final team = snapshot.teamPoolOf(id);
+ final teamId = team?['machineId'] as String?;
+ final agents = snapshot.agents
+ .where((a) => snapshot.placeOf(a.machineId) == id)
+ .toList();
final contributor =
shared?['contributorId'] as String? ??
agents.firstOrNull?.contributorId;
- final person = c.snapshot!.people
+ final person = snapshot.people
.where((p) => p.id == contributor)
.firstOrNull;
+ final teammateView = team != null && contributor != c.accountId;
+ final reading = teammateView ? team : shared;
+ final readId = teammateView ? teamId! : id;
+ final state = app?.stateOf(readId);
final observation = superTabMap(
- shared?['observation'] ?? const <String, dynamic>{},
+ reading?['observation'] ?? const <String, dynamic>{},
);
final now = widget.now();
final received = observation['receivedAt'];
final observedAt = received is num
? DateTime.fromMillisecondsSinceEpoch(received.toInt())
: null;
- final sample = _samples[id];
+ final sample = _samples[readId];
final connected =
state?.connectionStatus == ConnectionStatus.connected &&
state?.nodeOnline != false;
@@ -933,7 +951,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
// this very computer when it contributes and its own sample is the newer, which is why it stays live while
// the Swarm cannot be read. Any other contributing machine is known by what it reports through the Swarm.
final direct =
- shared == null ||
+ reading == null ||
(state?.isLocalMachine == true &&
sample != null &&
(observedAt == null || sample.$2.isAfter(observedAt)));
@@ -944,7 +962,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
// The Swarm cannot be read: a machine's silence is not known to be its own, so it is not offline.
unreachable: !direct && c.backendUnreachable,
refreshing: direct
- ? _awaiting.contains(id)
+ ? _awaiting.contains(readId)
: _swarmReadsAtReturn != null && c.stateReads <= _swarmReadsAtReturn!,
connected: direct ? connected : null,
);
@@ -972,9 +990,9 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
final value = direct ? sample?.$1 : observed;
final name =
shared?['name'] as String? ??
- state?.machine.displayName ??
+ app?.stateOf(id)?.machine.displayName ??
'Unavailable machine';
- final configured = (shared?['engines'] as List?)
+ final configured = (reading?['engines'] as List?)
?.whereType<String>()
.toList();
final allowed =
@@ -1003,10 +1021,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
for (final raw in observation['quotas'] as List? ?? [])
// Routing reads quota for these two only; other engines drew "—".
if (const {'claude', 'codex'}.contains(superTabMap(raw)['engine']))
- _quotaRow(superTabMap(raw), id),
+ _quotaRow(superTabMap(raw), readId),
];
}
- final paused = shared?['paused'] == true;
+ final paused = reading?['paused'] == true;
final removal = shared?['removal'];
final cleaning =
removal is Map && superTabMap(removal)['state'] == 'cleaning';
@@ -1108,6 +1126,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
localModels: localModels,
id: id,
name: name,
+ problem: _teammatesLine(shared, team, contributor),
owner: person,
contributor: contributor,
shared: shared,
@@ -1140,11 +1159,34 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
);
}
- /// Every agent of the Swarm on [machineId]: removing the machine takes them all with it.
- List<SuperTabAgent> _agentsOn(String machineId) => [
- for (final a in c.snapshot?.agents ?? const <SuperTabAgent>[])
- if (a.machineId == machineId) a,
- ];
+ /// Why teammates' agents cannot run on this row's computer, in its one line; null when they can, when nobody
+ /// else starts work in this Swarm, or when the row already reads offline: the computer's own silence, or, for
+ /// anyone but the Mac's owner, its Harness Team account's. A Mac with a team account answers for that account.
+ String? _teammatesLine(
+ Map<String, dynamic>? shared,
+ Map<String, dynamic>? team,
+ String? contributor,
+ ) {
+ if (c.snapshot?.hasTeammates != true) return null;
+ final work = (team ?? shared)?['teamWork'];
+ if (work is! Map || work['allowed'] != false) return null;
+ final code = work['code'];
+ if (code == 'MACHINE_OFFLINE' &&
+ (team == null || contributor != c.accountId)) {
+ return null;
+ }
+ return superTabTeammatesPaused(code);
+ }
+
+ /// Every agent of the Swarm on [machineId]'s row, its Mac's Harness Team account's included: removing the machine
+ /// takes them all with it.
+ List<SuperTabAgent> _agentsOn(String machineId) {
+ final snapshot = c.snapshot;
+ return [
+ for (final a in snapshot?.agents ?? const <SuperTabAgent>[])
+ if (snapshot!.placeOf(a.machineId) == machineId) a,
+ ];
+ }
String? _removeReason(String machineId) {
final snapshot = c.snapshot;
@@ -1535,6 +1577,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
view.cleaning
? 'Cleaning up'
: superTabMachineStateLabel(view.status),
+ ?view.problem,
if (view.tip.isNotEmpty) view.tip,
].join(', '),
child: Tooltip(
@@ -1729,7 +1772,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
/// Keep offline machines in the same list and on the same columns.
List<Widget> _machines() {
- final views = [for (final id in _ids) _view(id)];
+ final views = [for (final id in _rowIds) _view(id)];
String key(_MachineView view) =>
superTabMachineName(view.name).toLowerCase();
int rank(_MachineView view) => switch (view.status) {
@@ -1879,11 +1922,15 @@ class _MachineView {
required this.engines,
required this.allowances,
required this.tip,
+ this.problem,
this.apiModels = const [],
this.localModels = const [],
});
final String id, name, details, tip;
+
+ /// Its one line when teammates' agents cannot run there ([superTabTeammatesPaused]); null otherwise.
+ final String? problem;
final SuperTabPerson? owner;
final String? contributor;
final Map<String, dynamic>? shared;
@@ -1938,6 +1985,20 @@ String? superMachineAllowanceNote(Iterable<String> lines) {
].join(' · ');
}
+/// A machine row's line when teammates' agents cannot run there, from the Swarm's refusal code (backend
+/// superTabs/machines.ts `teamWorkRefusal`); null for a code this build does not know.
+String? superTabTeammatesPaused(Object? code) {
+ final why = switch (code) {
+ 'MACHINE_OFFLINE' => 'Harness Team account offline',
+ 'TEAM_ACCOUNT_REQUIRED' => 'not set up',
+ 'PRIVACY_UNCHECKED' => 'privacy not checked yet',
+ 'PRIVACY_CHECK_FAILED' => 'privacy check failed',
+ 'PRIVACY_CHECK_STALE' => 'privacy check out of date',
+ _ => null,
+ };
+ return why == null ? null : "Teammates' agents paused: $why";
+}
+
/// One engine's allowance on a machine: its mark and remaining share on the row, its windows on hover.
class _Allowance {
const _Allowance({
@@ -2025,7 +2086,7 @@ class _MachineLine extends StatelessWidget {
)..layout(maxWidth: constraints.maxWidth);
final truncated = painter.didExceedMaxLines;
painter.dispose();
- return truncated
+ final title = truncated
? Tooltip(
message: [
name,
@@ -2035,6 +2096,22 @@ class _MachineLine extends StatelessWidget {
child: text,
)
: text;
+ final problem = view.problem;
+ if (problem == null) return title;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ title,
+ Text(
+ problem,
+ key: ValueKey('super-machine-problem-${view.id}'),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ );
},
),
),
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 70a067e73..16ade4b23 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -283,6 +283,53 @@ class SuperTabSnapshot {
String agentName(String id, {String fallback = 'Agent'}) =>
agent(id)?.displayName ?? agent(id)?.name ?? fallback;
+ /// [machineId]'s contribution to this Swarm, if it has one.
+ Map<String, dynamic>? pool(String machineId) =>
+ machines.where((m) => m['machineId'] == machineId).firstOrNull;
+
+ /// The Mac a Harness Team account's pool is part of: the machine its pool names as `hostMachineId` (stamped by the
+ /// backend), while that Mac is in this Swarm too, from the same person (docs/plans/2026-10-24-swarm-team-account.md).
+ /// Null for every other pool, a machine used only for agents included.
+ String? _macOf(Map<String, dynamic>? team) {
+ final host = team?['hostMachineId'];
+ if (host is! String || host == team!['machineId']) return null;
+ final mac = pool(host);
+ return mac != null &&
+ mac['hostMachineId'] == null &&
+ mac['contributorId'] == team['contributorId']
+ ? host
+ : null;
+ }
+
+ /// Every Harness Team account's pool in [machineId]'s row: one, or more once the account was set up again and its old
+ /// pool is still listed (backend superTabs/machines.ts `teamPoolsOf`). The backend changes them with the Mac.
+ List<Map<String, dynamic>> teamPoolsOf(String machineId) => [
+ for (final m in machines)
+ if (_macOf(m) == machineId) m,
+ ];
+
+ /// The one of them that runs teammates' work on the Mac: not being removed, and the last to report (backend
+ /// superTabs/machines.ts `teamPoolOf`). Null when there is none.
+ Map<String, dynamic>? teamPoolOf(String machineId) {
+ num reported(Map<String, dynamic> m) => switch (m['observation']) {
+ {'receivedAt': final num at} => at,
+ _ => -1,
+ };
+ Map<String, dynamic>? best;
+ for (final m in teamPoolsOf(machineId)) {
+ if (m['removal'] != null) continue;
+ if (best == null || reported(m) >= reported(best)) best = m;
+ }
+ return best;
+ }
+
+ /// The machine [machineId] is shown as in this Swarm, one row per computer: the Mac, for its Harness Team account
+ /// while that Mac is in the Swarm too; [machineId] itself otherwise.
+ String placeOf(String machineId) => _macOf(pool(machineId)) ?? machineId;
+
+ /// Whether more than one person can start work here: teammates' agents are a question only then.
+ bool get hasTeammates => people.where((p) => p.role != 'viewer').length > 1;
+
// Resolve the person shown in chat from the same identity as the roster.
// Recorded labels remain the fallback for agents no longer in the Swarm.
String authorName(SuperTabMessage message) => message.fromAgent
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index 543185436..20ac27783 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -62,12 +62,11 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
Future<void> _remove(SuperTabAgent agent) async {
var busy = false, attempted = false;
final name = c.snapshot!.agentName(agent.id);
+ // The Mac, for an agent in that Mac's Harness Team account.
+ final place = c.snapshot?.placeOf(agent.machineId) ?? agent.machineId;
final machine =
- widget.app?.stateOf(agent.machineId)?.machine.displayName ??
- c.snapshot?.machines
- .where((m) => m['machineId'] == agent.machineId)
- .firstOrNull?['name']
- as String? ??
+ widget.app?.stateOf(place)?.machine.displayName ??
+ c.snapshot?.pool(place)?['name'] as String? ??
'its computer';
await showAppDialog<void>(
context: context,
diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dart
index 670e67c4b..519aa8cb5 100644
--- a/desktop/test/super_tab_machines_test.dart
+++ b/desktop/test/super_tab_machines_test.dart
@@ -1990,6 +1990,43 @@ void main() {
},
);
+ testWidgets(
+ 'Add machine: a Mac\'s Harness Team account in the Swarm is not offered beside its Mac; it joins and leaves with the Mac',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ // Its pool names the Mac (stamped by the backend); the account's machine itself is an ordinary one to the app.
+ f.connection.server.state['machines'] = [
+ {'machineId': 'm', 'contributorId': 'owner'},
+ {'machineId': 'm-team', 'contributorId': 'owner', 'hostMachineId': 'm'},
+ ];
+ const team = Machine(
+ machineId: 'm-team',
+ authMode: MachineAuthMode.remote,
+ name: 'This Mac · Team',
+ );
+ f.app.machines = [...f.app.machines, team];
+ f.app.machineStates['m-team'] = MachineState(team)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await _openAddMachineDialog(tester, f, c);
+
+ await tester.tap(_picker);
+ await tester.pumpAndSettle();
+ expect(_option('m'), findsOneWidget);
+ expect(_option('m-team'), findsNothing);
+ expect(find.textContaining('This Mac · Team'), findsNothing);
+
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
testWidgets(
'Add machine: offline and unlinked owned machines are disabled with status tooltips; shared machines stay excluded',
(tester) async {
diff --git a/desktop/test/super_tab_team_machine_test.dart b/desktop/test/super_tab_team_machine_test.dart
new file mode 100644
index 000000000..6c5d664a9
--- /dev/null
+++ b/desktop/test/super_tab_team_machine_test.dart
@@ -0,0 +1,294 @@
+// One machine per Mac in the Swarm (docs/plans/2026-10-24-swarm-team-account.md): a Mac's Harness Team account is a
+// second contribution, its pool naming the Mac as `hostMachineId`, and the Swarm shows the Mac alone. Its agents read as
+// on the Mac; teammates read the account's availability, which runs while the owner is away from the Mac; the only new
+// words are one line when teammates' agents cannot run there.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/agent_details.dart';
+import 'package:harness/super_tabs/machines.dart';
+
+import 'support/super_tab_fixture.dart';
+
+const _offlineAge = 10 * 60 * 1000;
+
+Map<String, dynamic> _pool(
+ String id, {
+ String name = 'MacBook Pro',
+ String contributor = 'peer',
+ String? host,
+ int age = 0,
+ Map<String, dynamic>? teamWork,
+}) => {
+ 'machineId': id,
+ 'name': name,
+ 'contributorId': contributor,
+ 'scope': 'swarm',
+ 'cwd': '/swarm',
+ 'engines': ['codex'],
+ 'maxAgents': 4,
+ 'paused': false,
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch - age},
+ 'hostMachineId': ?host,
+ 'teamWork': teamWork ?? {'allowed': true},
+};
+
+Map<String, dynamic> _refused(String code) => {
+ 'allowed': false,
+ 'code': code,
+ 'reason': 'Refused ($code).',
+};
+
+Map<String, dynamic> _agent(String id, String machineId) => {
+ 'id': id,
+ 'name': id,
+ 'displayName': id == 'a1' ? 'Mira' : 'River',
+ 'machineId': machineId,
+ 'harnessId': 'h-$id',
+ 'contributorId': 'peer',
+ 'machineOwnerId': 'peer',
+ 'configuration': <String, dynamic>{'engine': 'codex'},
+};
+
+/// The owner's Swarm with a teammate, `peer`, whose Mac is in it.
+ConversationServer _swarm({bool viewer = false}) {
+ final server = ConversationServer();
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'role': viewer ? 'viewer' : 'collaborator',
+ });
+ return server;
+}
+
+Future<dynamic> _mount(
+ WidgetTester tester,
+ ConversationServer server, {
+ String account = 'owner',
+}) async {
+ final c = server.controller(account: account);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMachines(controller: c, onAddAgent: (_) {}),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+Future<void> _unmount(WidgetTester tester, dynamic c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+}
+
+Finder _row(String id) => find.byKey(ValueKey('super-machine-$id'));
+Finder _state(String id, String status) =>
+ find.byKey(ValueKey('super-machine-state-$id-$status'));
+Finder _problem(String id) => find.byKey(ValueKey('super-machine-problem-$id'));
+String? _problemText(WidgetTester tester, String id) =>
+ tester.widget<Text>(_problem(id)).data;
+
+void main() {
+ testWidgets(
+ 'a Mac and its Harness Team account are one row, with every agent of both under it',
+ (tester) async {
+ final server = _swarm();
+ server.state['machines'] = [
+ _pool('mac'),
+ _pool('mac-team', name: 'MacBook Pro · Team', host: 'mac'),
+ ];
+ server.state['agents'] = [_agent('a1', 'mac'), _agent('a2', 'mac-team')];
+ final c = await _mount(tester, server);
+ expect(_row('mac'), findsOneWidget);
+ expect(_row('mac-team'), findsNothing);
+ expect(find.text('MacBook Pro · Team'), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-machine-toggle-mac')));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('super-machine-agent-mac-a1')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('super-machine-agent-mac-a2')),
+ findsOneWidget,
+ );
+ // The agent in the team account is on the Mac, wherever its machine is named.
+ final river = c.snapshot!.agent('a2')!;
+ expect(SuperTabAgentInfo(c, null, river).machine, 'MacBook Pro');
+ expect(c.snapshot!.placeOf('mac-team'), 'mac');
+ await _unmount(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'an account set up again leaves its old pool listed: still one row, read from the newer account',
+ (tester) async {
+ final server = _swarm();
+ // The owner is away from the Mac. The old account stopped reporting; the new one runs teammates' work.
+ server.state['machines'] = [
+ _pool('mac', age: _offlineAge),
+ _pool('mac-team-new', host: 'mac'),
+ _pool('mac-team-old', host: 'mac', age: _offlineAge * 2),
+ ];
+ server.state['agents'] = [
+ _agent('a1', 'mac-team-old'),
+ _agent('a2', 'mac-team-new'),
+ ];
+ // A teammate reads the team account that runs their agents.
+ final c = await _mount(tester, server);
+ expect(_row('mac'), findsOneWidget);
+ expect(_row('mac-team-new'), findsNothing);
+ expect(_row('mac-team-old'), findsNothing);
+ expect(_state('mac', 'live'), findsOneWidget);
+ expect(c.snapshot!.teamPoolOf('mac')!['machineId'], 'mac-team-new');
+ await tester.tap(find.byKey(const ValueKey('super-machine-toggle-mac')));
+ await tester.pumpAndSettle();
+ for (final agent in ['a1', 'a2']) {
+ expect(
+ find.byKey(ValueKey('super-machine-agent-mac-$agent')),
+ findsOneWidget,
+ );
+ }
+ await _unmount(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'a Harness Team account whose Mac is not in the Swarm is a row of its own',
+ (tester) async {
+ final server = _swarm();
+ server.state['machines'] = [
+ _pool('mac-team', name: 'MacBook Pro · Team', host: 'mac'),
+ // A machine used only for agents has no host: its own row, as before.
+ _pool('box', name: 'Mac mini'),
+ ];
+ final c = await _mount(tester, server);
+ expect(_row('mac-team'), findsOneWidget);
+ expect(_row('box'), findsOneWidget);
+ expect(c.snapshot!.placeOf('mac-team'), 'mac-team');
+ await _unmount(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'the Mac\'s owner reads their own computer; teammates read the Harness Team account',
+ (tester) async {
+ final server = _swarm();
+ // The owner is away from the Mac: their own daemon is silent, the team account runs.
+ server.state['machines'] = [
+ _pool('mac', age: _offlineAge),
+ _pool('mac-team', host: 'mac'),
+ ];
+ var c = await _mount(tester, server, account: 'peer');
+ expect(_state('mac', 'offline'), findsOneWidget);
+ await _unmount(tester, c);
+ c = await _mount(tester, server);
+ expect(_state('mac', 'live'), findsOneWidget);
+ await _unmount(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'one line says when teammates\' agents cannot run on the Mac, and why',
+ (tester) async {
+ const reasons = {
+ 'PRIVACY_CHECK_FAILED':
+ "Teammates' agents paused: privacy check failed",
+ 'PRIVACY_CHECK_STALE':
+ "Teammates' agents paused: privacy check out of date",
+ 'PRIVACY_UNCHECKED':
+ "Teammates' agents paused: privacy not checked yet",
+ 'TEAM_ACCOUNT_REQUIRED': "Teammates' agents paused: not set up",
+ };
+ for (final MapEntry(key: code, value: line) in reasons.entries) {
+ final server = _swarm();
+ server.state['machines'] = [
+ _pool('mac', teamWork: _refused('TEAM_ACCOUNT_REQUIRED')),
+ _pool('mac-team', host: 'mac', teamWork: _refused(code)),
+ ];
+ for (final account in ['peer', 'owner']) {
+ final c = await _mount(tester, server, account: account);
+ expect(_problemText(tester, 'mac'), line, reason: '$code, $account');
+ await _unmount(tester, c);
+ }
+ }
+ },
+ );
+
+ testWidgets('without a Harness Team account the Mac\'s own refusal says so', (
+ tester,
+ ) async {
+ final server = _swarm();
+ server.state['machines'] = [
+ _pool('mac', teamWork: _refused('TEAM_ACCOUNT_REQUIRED')),
+ ];
+ final c = await _mount(tester, server);
+ expect(_problemText(tester, 'mac'), "Teammates' agents paused: not set up");
+ await _unmount(tester, c);
+ });
+
+ testWidgets('the line stays away when it would say nothing new', (
+ tester,
+ ) async {
+ Future<void> quiet(
+ List<Map<String, dynamic>> machines, {
+ String account = 'owner',
+ bool viewer = false,
+ }) async {
+ final server = _swarm(viewer: viewer);
+ server.state['machines'] = machines;
+ final c = await _mount(tester, server, account: account);
+ expect(_problem('mac'), findsNothing, reason: '$machines $account');
+ await _unmount(tester, c);
+ }
+
+ // Teammates' agents can run there.
+ await quiet([
+ _pool('mac', teamWork: _refused('TEAM_ACCOUNT_REQUIRED')),
+ _pool('mac-team', host: 'mac'),
+ ]);
+ // Nobody else can start work in this Swarm: a viewer cannot.
+ await quiet([
+ _pool('mac', teamWork: _refused('TEAM_ACCOUNT_REQUIRED')),
+ ], viewer: true);
+ // The row already reads offline: the Mac's own silence, and for a teammate the team account's.
+ await quiet([
+ _pool('mac', age: _offlineAge, teamWork: _refused('MACHINE_OFFLINE')),
+ ]);
+ await quiet([
+ _pool('mac'),
+ _pool(
+ 'mac-team',
+ host: 'mac',
+ age: _offlineAge,
+ teamWork: _refused('MACHINE_OFFLINE'),
+ ),
+ ]);
+ });
+
+ testWidgets(
+ 'the Mac\'s owner hears that its Harness Team account is offline',
+ (tester) async {
+ final server = _swarm();
+ server.state['machines'] = [
+ _pool('mac'),
+ _pool(
+ 'mac-team',
+ host: 'mac',
+ age: _offlineAge,
+ teamWork: _refused('MACHINE_OFFLINE'),
+ ),
+ ];
+ final c = await _mount(tester, server, account: 'peer');
+ expect(_state('mac', 'live'), findsOneWidget);
+ expect(
+ _problemText(tester, 'mac'),
+ "Teammates' agents paused: Harness Team account offline",
+ );
+ await _unmount(tester, c);
+ },
+ );
+}
diff --git a/docs/naming-system.md b/docs/naming-system.md
index bc6a5cae2..8ea0677b5 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -118,6 +118,10 @@ activity summaries or infer a work timer from the session's age. Engine names be
Chat headings and quoted replies use the same current agent identity as the roster, including
older messages. When an agent has left, its recorded author name remains available in history.
Machine rows show a computer icon, name, owner avatar, status and right-hand disclosure.
+In the Swarm's views, a Mac and its Harness Team account are one row, and agents in that account
+read as on the Mac. App-wide machine lists still show the team account as its own machine.
+When teammates' agents cannot run on a machine, its row adds one line, such as
+**Teammates' agents paused: privacy check failed**. There is no badge.
Clicking the name opens labeled details; disclosure shows agents with their names, role badges
and status, followed by known resources and model allowances. Offline machines stay in the
same list and omit stale readings. Rows share the projects' alignment and full-width highlight.
diff --git a/docs/plans/2026-10-24-swarm-team-account.md b/docs/plans/2026-10-24-swarm-team-account.md
index cad68363d..3d5f88515 100644
--- a/docs/plans/2026-10-24-swarm-team-account.md
+++ b/docs/plans/2026-10-24-swarm-team-account.md
@@ -11,7 +11,7 @@
## The experience
1. A person's Mac joins a Swarm. macOS asks once for an administrator password. There is no Harness setup screen.
-2. Harness creates a hidden standard user, makes the owner's home folder private, and runs a second Harness daemon as that user. It appears as its own machine, e.g. "MacBook Pro · Team", marked **Private ✓** once the privacy check passes.
+2. Harness creates a hidden standard user, makes the owner's home folder private, and runs a second Harness daemon as that user. In the Swarm it is not a machine of its own: the Swarm's views show the Mac once (see **One machine**). Outside the Swarm, Harness lists it as its own machine, e.g. "MacBook Pro · Team", as before.
3. Teammates' work only runs on Team machines. The owner's own agents keep running as the owner, as today.
4. The owner approves Claude Code and Codex for team work once, in the browser. That is an explicit choice to share that subscription.
5. Agents push and open PRs with a Harness GitHub App token for that one repository. The machine owner's GitHub login is never used.
@@ -102,6 +102,16 @@ Files: `backend/src/superTabs/commands.ts` (`message.send`), a small detector mo
- [ ] Tests for JWTs, GitHub tokens, OpenAI and Anthropic keys, AWS keys, Slack tokens and private key blocks; ordinary hashes and commit ids pass.
- [ ] Redact before storing, keep the rest of the message, and tell the sender what was removed and that the credential should be revoked.
+## One machine
+
+Owner, 24 Oct 2026: "The isolated team account is just an under-the-scenes mechanism." A Mac with a Harness Team account is one machine in the Swarm's views, for the owner and for teammates: the machines view, Add machine, and wherever an agent's computer is named. Swarm is a hidden feature, so this lives in Super Tab code only (`desktop/lib/super_tabs/`, `cli/src/superTabs/`, `cli/src/team/`, and the backend's Swarm state and team sign-in). App-wide lists are unchanged: Desktop's rail, Machines, pickers, menus and web onboarding, `harness machines` and hn list the team account as its own machine, as before.
+
+- **The link.** The team machine records the Mac it lives on, `Machine.hostMachineId`. `POST /api/auth/handoff` with `{ "kind": "team" }` records the Mac in the code. From a Harness computer session, that is one of the computer's own machines, and naming another is refused. Any other sign-in passes `hostMachineId`: one of the account's ordinary machines (not a team one), in the same environment. Otherwise the answer is 403 `HANDOFF_NOT_ALLOWED`, and nothing is minted. `harness team setup` sends its own machine id. If that id is refused (stale or deleted), setup mints again without it, so the team account still signs in, listed as its own row. The team session keeps the Mac (`HarnessSession.hostMachineId`), and its machine copies it each time it registers. A repair run also updates a team machine that already exists. Nothing a team session sends sets or changes it. A dedicated machine (`harness team on`) has no Mac and stays its own row.
+- **Both rows stay in the API.** `GET /api/machines` returns `hostMachineId` on a team machine that lives on a Mac, and null on every other machine. The team account's daemon still reads the account's machines with `sessionKind`, so roster sync keeps leaving team machines out (`machineKinds.ts`). App-wide clients do not read it: Desktop's shared `Machine` model, `harness machines` and hn list the team machine as a row of its own, as before.
+- **In a Swarm.** The team machine's pool carries `hostMachineId` too, stamped by the store from the account row. Wherever its owner adds the Mac, the Mac's own daemon adds the team account: the roster names it (`joinTeam`), the team account prepares its own folder and engines through the relay, and the Mac's daemon contributes it as the person (`ifMissing`). The pool takes the Mac's name, agent slots and pause. Pausing, reconfiguring or removing the Mac does the same to it. An account removed and set up again leaves its old pool listed beside the new one: both go with the Mac, and only the last to report, not being removed, takes work. Desktop's Swarm machines view folds from the pools alone: a pool whose `hostMachineId` names another pool of the same person in this Swarm is shown inside that Mac's row, with its agents, and Add machine does not offer it. A team account not yet in the Swarm is still offered there under its own name; adding the Mac adds it. Agents in the team account read as on the Mac. Teammates see the team account's status (it runs while the owner is logged out of macOS); the owner sees their own daemon's.
+- **Routing.** A start on the Mac for a project its contributor does not own goes to the Mac's team account, in that account's folder, if `teamWorkCheck` passes. Otherwise it is refused with the team account's reason, and it never falls back to the owner. The owner's own projects stay with the owner's daemon. A start that names the team machine still works. The Lead's route offers the Mac once: the team account for a teammate's project, the owner's daemon for the owner's own. A machines rule naming the Mac allows its team account.
+- **The only new copy** is a line on a Swarm machine row, shown only when teammates' agents cannot run there: `Teammates' agents paused: privacy check failed`. The other endings are `Harness Team account offline`, `not set up`, `privacy not checked yet` and `privacy check out of date`, one for each `teamWorkRefusal` code. There is no badge, setup button or setting.
+
## Out of scope
VMs; team accounts on Windows and Linux (dedicated machines use `harness team on`); blocking the team user from the owner's local network services with per-user firewall rules (next); pooling or reselling subscriptions.