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.

Swarm: a new project's PM runs on the Swarm machine its person chooses (#2215 combined with #2208) (#2228)

0xken15e89283586d76
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
index 9ad04afb4..369d7ae20 100644
--- a/backend/integration/superTabTeam.test.ts
+++ b/backend/integration/superTabTeam.test.ts
@@ -709,18 +709,18 @@ describe('one machine: a Mac and its Harness Team account', () => {
})
})
-// A project's Product Manager on another person's Team machine (leadStart.ts, Dee 10-29): placed by the store when a
-// machine reports, launched from a list older hosts do not read, and the project's Lead once it runs.
+// A project's Product Manager on another person's Team machine (leadStart.ts, Dee 10-29): on the machine its person names
+// (Ken 10-29), launched from a list older hosts do not read, and the project's Lead once it runs.
describe('a project\'s Product Manager on a teammate\'s Team machine', () => {
const capable = (generation: string) => ({ ...reading(generation), capabilities: ['leadStart'] }) as Parameters<SuperTabStore['observeMachine']>[3]
- it('waits for a machine that can run it, starts on the Team machine once it reports, and leads the project', async () => {
+ it('needs a machine named, starts on the Team machine named, and leads the project', async () => {
const f = await fixture()
const created = (await run(f.tab, { type: 'project.create', name: 'App', visibility: 'private', brief: 'Build it.' })).result
const projectId = String(created.projectId), home = String(created.conversationId)
- // The team daemon has not said it starts Product Managers yet: nothing is free, so it waits.
- const asked = await run(f.tab, { type: 'lead.start', projectId, machineId: null, engine: 'codex', repositoryUrl: 'https://github.com/example/app' })
- expect(asked.result).toMatchObject({ waiting: true })
+ // Only its person knows which machine stays on: none is chosen for them.
+ await expect(run(f.tab, { type: 'lead.start', projectId, machineId: null, engine: 'codex', repositoryUrl: 'https://github.com/example/app' }))
+ .rejects.toMatchObject({ code: 'MACHINE_REQUIRED', status: 400 })
expect((await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!.leadStarts).toBeUndefined()
// Contributed for every project, as a Mac added to a Swarm with projects is; the fixture's serves only the first. Its
// Builder of that first project goes, so the account can serve this project alone.
@@ -728,6 +728,7 @@ describe('a project\'s Product Manager on a teammate\'s Team machine', () => {
await run(f.tab, { type: 'agent.remove', agentId: f.builder })
const generation = (await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!.machine.generation
await store.observeMachine(team, f.tab, 'team-mac', capable(generation))
+ await run(f.tab, { type: 'lead.start', projectId, machineId: 'team-mac', engine: 'codex', repositoryUrl: 'https://github.com/example/app' })
const row = (await poolRows(store, team, 'team-mac')).find(p => p.tabId === f.tab)!
expect(row.leadStarts).toEqual([expect.objectContaining({ request: expect.objectContaining({ machineId: 'team-mac', cwd: `/team/${projectId}`,
leadFor: expect.objectContaining({ projectId, personId: owner.sub }) }) })])
@@ -739,7 +740,7 @@ describe('a project\'s Product Manager on a teammate\'s Team machine', () => {
expect(read.state.conversations.find(c => c.id === home)).toMatchObject({ leadId: agentId })
expect(read.state.projects!.find(p => p.id === projectId)!.lead).toMatchObject({ status: 'started', machineId: 'team-mac' })
expect((await store.messages(owner, f.tab, home, {})).messages.map(m => m.text))
- .toEqual(expect.arrayContaining(['Waiting for a machine to start the Product Manager.', 'Product Manager started on MacBook Pro · Team.']))
+ .toEqual(expect.arrayContaining(['Product Manager started on MacBook Pro · Team.']))
})
// The isolated confidential run (docs/performance/2026-10-27-pm-confidential-isolated-run.test.mts), its Team machine case:
@@ -831,13 +832,15 @@ describe('a project\'s Product Manager on a teammate\'s Team machine', () => {
expect(await start()).not.toBe('TEAM_ACCOUNT_HELD')
})
- it('is refused on the teammate\'s personal Mac even while the Swarm does not yet require Team accounts', async () => {
+ it('on the teammate\'s personal Mac with no Team account, starts there, as its owner (Ken 10-29)', async () => {
const f = await fixture()
const projectId = String((await run(f.tab, { type: 'project.create', name: 'App', visibility: 'private', brief: '' })).result.projectId)
await run(f.tab, { type: 'machine.contribute', machineId: 'personal-mac', name: 'MacBook Pro', cwd: '/work', scope: 'swarm', engines: ['codex'], maxAgents: 2 }, person)
const generation = (await poolRows(store, person, 'personal-mac')).find(p => p.tabId === f.tab)!.machine.generation
await store.observeMachine(person, f.tab, 'personal-mac', capable(generation))
- await expect(run(f.tab, { type: 'lead.start', projectId, machineId: 'personal-mac', engine: 'codex', repositoryUrl: 'https://github.com/example/app' }))
- .rejects.toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', status: 403 })
+ const placed = await run(f.tab, { type: 'lead.start', projectId, machineId: 'personal-mac', engine: 'codex', repositoryUrl: 'https://github.com/example/app' })
+ expect(placed.result).toMatchObject({ machineId: 'personal-mac' })
+ expect((await poolRows(store, person, 'personal-mac')).find(p => p.tabId === f.tab)!.leadStarts)
+ .toEqual([expect.objectContaining({ request: expect.objectContaining({ machineId: 'personal-mac', cwd: `/work/${projectId}` }) })])
})
})
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index ba90f0270..bc4b7dd00 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -180,6 +180,22 @@ describe('Super Tab collaboration policy', () => {
expect(machineSlots(f.state, f.state.machines![0]!)).toBe(1)
})
+ it('counts a finished start\'s harness only while its agent or its host says it runs', () => {
+ const f = fixture()
+ const pool = { machineId: 'host', name: 'Host', contributorId: 'owner', membershipGeneration: f.state.people[0]!.generation,
+ generation: 'pool', cwd: '/work', engines: ['codex'], maxAgents: 2, paused: false }
+ f.state.machines = [pool]
+ // A read keeps finished starts until they expire: one whose harness is long gone takes no slot.
+ f.state.starts = [{ poolGeneration: 'pool', id: 'old', creationId: 'super-old', actorKey: 'person:owner', contributorId: 'owner',
+ membershipGeneration: f.state.people[0]!.generation, machineOwnerId: 'owner', hostGrant: null, harnessId: 'gone', dispatched: true,
+ error: null, poolSettled: true, request: { conversationId: 'lead', machineId: 'host', engine: 'codex', name: 'Builder', cwd: '/work/lead',
+ worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } }]
+ expect(machineSlots(f.state, pool)).toBe(0)
+ // Started but not yet settled, it still holds its slot.
+ f.state.starts[0]!.poolSettled = false
+ expect(machineSlots(f.state, pool)).toBe(1)
+ })
+
it('a person withdrawing a stuck stop keeps its native slot until the host reports stopping', () => {
const f = fixture(), worker = f.add('worker')
f.state.agents[0]!.workDecision = 'awaiting'
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 36e80ff0e..4eaf979df 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -35,7 +35,7 @@ import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema,
import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, isConfidential, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'
import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, PROPOSAL_ASK_MS, proposalText, requireBuddyCommand } from './buddies.js'
import { CODEX_BUDDY_REFUSAL } from './buddyContract.js'
-import { LEAD_NAME, leadJoined, leadStartFailed, leadStarting, requestLead, WAITING_TEXT } from './leadStart.js'
+import { LEAD_NAME, leadJoined, leadStartFailed, leadStarting, placeLead } from './leadStart.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const title = z.string().trim().min(1).max(160)
@@ -943,9 +943,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (leadStarting(state, project.id)) fail('LEAD_STARTING', `This project's ${LEAD_NAME} is already starting.`)
if (!project.repository?.repositoryUrl && !command.repositoryUrl) fail('REPOSITORY_REQUIRED', 'Choose the repository this project works in.', 400)
const { type: _type, projectId: _projectId, machineId, ...request } = command
- const placed = requestLead(state, project, person(state, actor.userId), machineId, request, operationId, context)
- Object.assign(result, placed)
- if ('waiting' in placed) message(home.id, WAITING_TEXT, [], null, SYSTEM_ROW)
+ // Only its person knows which machine stays on (Ken, 10-29): a Desktop from before asked for the first free one.
+ if (!machineId) fail('MACHINE_REQUIRED', `Choose the machine the ${LEAD_NAME} runs on.`, 400)
+ const start = placeLead(state, project, person(state, actor.userId), machineId, request, operationId, context)
+ Object.assign(result, { startId: start.id, machineId: start.request.machineId })
break
}
case 'project.skills': {
@@ -1614,9 +1615,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const counted = !start.error
start.error = command.error
const suspended = counted ? noteStartFailed(state, start, context.now) : null
- // A Product Manager's start says so in its project's conversation only when it stops trying (leadStart.ts).
+ // A Product Manager's start says so in its project's conversation (leadStart.ts).
if (start.request.leadFor) {
- const ended = leadStartFailed(state, start, command.error, context.now)
+ const ended = leadStartFailed(state, start, command.error)
if (ended) message(start.request.conversationId, ended, [], null, SYSTEM_ROW)
break
}
diff --git a/backend/src/superTabs/leadStart.test.ts b/backend/src/superTabs/leadStart.test.ts
index e3970ddca..3a7098a17 100644
--- a/backend/src/superTabs/leadStart.test.ts
+++ b/backend/src/superTabs/leadStart.test.ts
@@ -1,11 +1,10 @@
import { afterEach, describe, expect, it } from 'vitest'
import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
import type { ContributedMachine, MachinePrivacy } from './machines.js'
-import type { LeadContext } from './leadStart.js'
import { createSuperTab, SuperTabError, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
-// A project's Product Manager started by the Swarm on one of its machines (Dee, 10-29, option B): on another person's Mac it
-// runs only in that Mac's Harness Team account, never as the Mac's owner; with no machine free it waits for one.
+// A project's Product Manager started by the Swarm on the machine its person names (Dee, 10-29, option B; Ken, 10-29): on
+// another person's Mac it runs in that Mac's Harness Team account when the account takes it, else on the Mac as its owner.
const NOW = 50_000_000
const MINUTE = 60_000
@@ -71,7 +70,7 @@ describe('starting a project\'s Product Manager on a Swarm machine', () => {
expect(f.project().repository).toEqual({ machineId: 'owner-mac', cwd: `/swarm/${f.app.projectId}`, repositoryUrl: REPO })
})
- it('on a teammate\'s Mac, runs in that Mac\'s Harness Team account and its folder, never as the Mac\'s owner', () => {
+ it('on a teammate\'s Mac, runs in that Mac\'s Harness Team account and its folder', () => {
const f = swarm()
f.lead('mate-mac')
expect(f.state.starts).toEqual([expect.objectContaining({ machineOwnerId: 'mate',
@@ -79,32 +78,66 @@ describe('starting a project\'s Product Manager on a Swarm machine', () => {
expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'mate-team', machineName: 'MacBook Pro' })
})
- it('is refused with the Team account\'s own reason, and records nothing', () => {
+ it('on a teammate\'s Mac whose Team account cannot take it now, runs on the Mac itself, as its owner', () => {
const f = swarm()
f.machine('mate-team').observation = reading('team', FAILED)
- expect(refusal(() => f.lead('mate-mac'))).toMatchObject({ code: 'PRIVACY_CHECK_FAILED', status: 403,
- 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), receivedAt: NOW - 10 * MINUTE }
- expect(refusal(() => f.lead('mate-mac'))?.code).toBe('MACHINE_OFFLINE')
- expect(f.state.starts ?? []).toEqual([])
- expect(f.project().lead).toBeUndefined()
+ f.lead('mate-mac')
+ expect(f.state.starts).toEqual([expect.objectContaining({ machineOwnerId: 'mate', contributorId: 'mate',
+ request: expect.objectContaining({ machineId: 'mate-mac', cwd: `/swarm/${f.app.projectId}` }) })])
+ expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'mate-mac', machineName: 'MacBook Pro' })
+ // Offline, or paused, the same.
+ const offline = swarm()
+ offline.machine('mate-team').observation = { ...reading('team', PASSED), receivedAt: NOW - 10 * MINUTE }
+ expect(offline.lead('mate-mac').result).toMatchObject({ machineId: 'mate-mac' })
+ const paused = swarm()
+ paused.machine('mate-team').paused = true
+ expect(paused.lead('mate-mac').result).toMatchObject({ machineId: 'mate-mac' })
+ })
+
+ it('on a teammate\'s Mac added as they joined, runs only in its Team account', () => {
+ const f = swarm()
+ f.machine('mate-mac').teamAccountOnly = true
+ expect(f.lead('mate-mac').result).toMatchObject({ machineId: 'mate-team' })
+ const failing = swarm()
+ failing.machine('mate-mac').teamAccountOnly = true
+ failing.machine('mate-team').observation = reading('team', FAILED)
+ expect(refusal(() => failing.lead('mate-mac'))?.code).toBe('PRIVACY_CHECK_FAILED')
+ const none = swarm()
+ none.machine('mate-mac').teamAccountOnly = true
+ none.state.machines = none.state.machines!.filter(m => m.machineId !== 'mate-team')
+ expect(refusal(() => none.lead('mate-mac'))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ expect(none.state.starts ?? []).toEqual([])
+ })
+
+ it('on a teammate\'s Mac with no Team account, runs on the Mac itself, whatever the Swarm\'s switch says for workers', () => {
+ process.env.SWARM_TEAM_ACCOUNT_REQUIRED = '1'
+ const f = swarm()
+ f.state.machines = f.state.machines!.filter(m => m.machineId !== 'mate-team')
+ expect(f.lead('mate-mac').result).toMatchObject({ machineId: 'mate-mac' })
+ // With no GitHub App the Team account takes no work: the Mac runs it itself.
+ expect(swarm().lead('mate-mac', {}, owner, { teamAccountsIdle: true }).result).toMatchObject({ machineId: 'mate-mac' })
})
- it('needs a Team account on another person\'s machine even while the Swarm does not yet require one', () => {
- // A worker would still run as the Mac's owner here; a Product Manager holds people's private chats, so it never does.
- delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED
+ it('named in a Team account itself, is refused with the account\'s own reason, and records nothing', () => {
const f = swarm()
- f.state.machines = f.state.machines!.filter(m => m.machineId !== 'mate-team')
- expect(refusal(() => f.lead('mate-mac'))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
- // With no GitHub App the Team account takes no work, so the Mac would run it itself: refused too.
- expect(refusal(() => swarm().lead('mate-mac', {}, owner, { teamAccountsIdle: true }))?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ f.machine('mate-team').observation = reading('team', FAILED)
+ expect(refusal(() => f.lead('mate-team'))).toMatchObject({ code: 'PRIVACY_CHECK_FAILED', status: 403,
+ 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), receivedAt: NOW - 10 * MINUTE }
+ expect(refusal(() => f.lead('mate-team'))?.code).toBe('MACHINE_OFFLINE')
expect(f.state.starts ?? []).toEqual([])
+ expect(f.project().lead).toBeUndefined()
})
it('is refused on a machine whose Harness is too old to start a Product Manager', () => {
const f = swarm()
f.machine('mate-team').observation = reading('team', PASSED, false)
- expect(refusal(() => f.lead('mate-mac'))).toMatchObject({ code: 'HOST_OUTDATED',
+ // Its Team account's host is too old: the Mac takes it.
+ expect(f.lead('mate-mac').result).toMatchObject({ machineId: 'mate-mac' })
+ const g = swarm()
+ g.machine('mate-team').observation = reading('team', PASSED, false)
+ g.machine('mate-mac').observation = reading('computer', undefined, false)
+ expect(refusal(() => g.lead('mate-mac'))).toMatchObject({ code: 'HOST_OUTDATED',
message: 'Update Harness on MacBook Pro to run a Product Manager there.' })
})
@@ -120,6 +153,28 @@ describe('starting a project\'s Product Manager on a Swarm machine', () => {
expect(f.state.starts ?? []).toEqual([])
})
+ it('is refused on a teammate\'s Mac once they left the Swarm, or while it is being removed, and records nothing', () => {
+ const left = swarm()
+ left.run({ type: 'member.remove', userId: 'mate' })
+ expect(refusal(() => left.lead('mate-mac'))?.code).toBe('CONTRIBUTION_REVOKED')
+ expect(left.state.starts ?? []).toEqual([])
+ const removing = swarm()
+ removing.machine('mate-mac').removal = { id: 'r1', state: 'cleaning', requestedAt: new Date(NOW).toISOString() }
+ removing.machine('mate-team').observation = reading('team', FAILED)
+ expect(refusal(() => removing.lead('mate-mac'))?.code).toBe('MACHINE_REMOVED')
+ expect(removing.state.starts ?? []).toEqual([])
+ })
+
+ it('refuses a private project it cannot read exactly as one that does not exist, naming neither', () => {
+ const f = swarm()
+ const hidden = refusal(() => f.lead('mate-mac', {}, mate))
+ const unknown = refusal(() => f.run({ type: 'lead.start', projectId: 'no-such-project', machineId: 'mate-mac', engine: 'claude', repositoryUrl: REPO }, mate))
+ expect(hidden).toMatchObject({ code: 'NOT_FOUND' })
+ expect([unknown?.code, unknown?.status, unknown?.message]).toEqual([hidden?.code, hidden?.status, hidden?.message])
+ expect(hidden?.message).not.toContain('App')
+ expect(f.state.starts ?? []).toEqual([])
+ })
+
it('needs the repository when the project has none yet', () => {
const f = swarm()
expect(refusal(() => f.lead('owner-mac', { repositoryUrl: undefined }))?.code).toBe('REPOSITORY_REQUIRED')
@@ -194,107 +249,88 @@ describe('a Product Manager\'s start, once its host reports it', () => {
})
})
-describe('a Product Manager waiting for a machine', () => {
- const full = (f: ReturnType<typeof swarm>, machineId: string) => { f.machine(machineId).maxAgents = 0 }
- const place = async (f: ReturnType<typeof swarm>, context: Partial<LeadContext> = {}) => {
- const { placeWaitingLeads } = await import('./leadStart.js')
- // Placed on a machine's reading: the machines report as of then.
- for (const m of f.state.machines!) if (m.observation) m.observation = { ...m.observation, receivedAt: context.now ?? NOW }
- const teamMachines = f.state.machines!.filter(m => m.observation?.sessionKind === 'team').map(m => m.machineId)
- return placeWaitingLeads(f.state, { now: NOW, teamMachines, ...context })
+// Security reviews 1 and 2 of #2228: the Team account was chosen before checking it could run the requested engine, so a
+// busy account, or one with that engine signed out or not offered, refused the start though the Mac itself could run it.
+describe('where a Product Manager on a teammate\'s Mac runs, for its engine', () => {
+ /** Another project's agent in the Mac's Team account. */
+ function busy(f: ReturnType<typeof swarm>) {
+ const web = f.run({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' }).result as { projectId: string }
+ const group = f.run({ type: 'conversation.create', projectId: web.projectId, title: 'Work', brief: 'Build it.', checks: [] }).result.conversationId as string
+ f.run({ type: 'agent.add', conversationId: group, machineId: 'mate-team', harnessId: 'web-worker', name: 'Builder', configuration: config, lead: false }, owner,
+ { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null } })
}
+ const signedOut = (engine: string): Reading => ({ ...reading('team', PASSED),
+ readiness: { engines: [{ engine, installed: true, signedIn: false }] } } as unknown as Reading)
- it('starts at once on a free machine, the project owner\'s own first', () => {
+ it('a Team account busy with another project\'s agents leaves it to the Mac itself, with the engine the Mac runs', () => {
const f = swarm()
- const asked = f.lead(null)
- expect(asked.result).toMatchObject({ machineId: 'owner-mac' })
- expect(f.project().lead).toMatchObject({ status: 'starting', chosen: null, machineId: 'owner-mac' })
+ f.machine('mate-team').engines = ['codex']
+ f.machine('mate-mac').engines = ['claude']
+ busy(f)
+ expect(f.lead('mate-mac', { engine: 'claude' }).result).toMatchObject({ machineId: 'mate-mac' })
+ const g = swarm()
+ g.machine('mate-team').engines = ['codex']
+ g.machine('mate-mac').engines = ['claude']
+ busy(g)
+ // Codex runs only in the busy account: refused for the Mac's reason, and nothing recorded.
+ expect(refusal(() => g.lead('mate-mac', { engine: 'codex' }))?.code).toBe('ENGINE_NOT_OFFERED')
+ expect((g.state.starts ?? []).filter(s => s.request.leadFor)).toEqual([])
+ })
+
+ it('a Team account with the engine signed out, or not offering it, leaves it to the Mac itself', () => {
+ const out = swarm()
+ out.machine('mate-team').observation = signedOut('claude')
+ expect(out.lead('mate-mac', { engine: 'claude' }).result).toMatchObject({ machineId: 'mate-mac' })
+ const offered = swarm()
+ offered.machine('mate-team').engines = ['codex']
+ expect(offered.lead('mate-mac', { engine: 'claude' }).result).toMatchObject({ machineId: 'mate-mac' })
+ // The engine it runs still goes to the Team account.
+ expect(swarm().lead('mate-mac', { engine: 'claude' }).result).toMatchObject({ machineId: 'mate-team' })
+ })
+
+ it('a Mac added as its person joined still runs it only in its Team account, refused when that cannot run the engine', () => {
+ const f = swarm()
+ f.machine('mate-mac').teamAccountOnly = true
+ f.machine('mate-team').observation = signedOut('claude')
+ expect(refusal(() => f.lead('mate-mac', { engine: 'claude' }))?.code).toBe('ENGINE_UNAVAILABLE')
+ expect(f.state.starts ?? []).toEqual([])
})
- it('then the free Team machine', () => {
+ it('New Project reads the same decision for each engine before the project exists, naming no other project', async () => {
+ const { leadChoices } = await import('./leadStart.js')
const f = swarm()
- full(f, 'owner-mac')
- expect(f.lead(null).result).toMatchObject({ machineId: 'mate-team' })
+ f.machine('mate-team').engines = ['codex']
+ f.machine('mate-mac').engines = ['claude']
+ const context = { now: NOW, teamMachines: ['mate-team'] }
+ // The owner's own machines are left to Desktop; the Team account row is read through its Mac.
+ expect(Object.keys(leadChoices(f.state, 'owner', context))).toEqual(['mate-mac'])
+ expect(leadChoices(f.state, 'owner', context)['mate-mac']).toEqual({ claude: { machineId: 'mate-mac' }, codex: { machineId: 'mate-team' } })
+ busy(f)
+ const choices = leadChoices(f.state, 'owner', context)['mate-mac']!
+ expect(choices.claude).toEqual({ machineId: 'mate-mac' })
+ expect(choices.codex).toEqual({ refused: 'Codex isn’t offered on MacBook Pro.' })
+ expect(JSON.stringify(choices)).not.toContain('Web')
+ // The same answer the start gives.
+ expect(refusal(() => f.lead('mate-mac', { engine: 'codex' }))?.message).toBe('Codex isn’t offered on MacBook Pro.')
})
+})
- it('with none free, waits and says so, then starts on the first one that frees up', async () => {
+describe('the machine a Product Manager starts on', () => {
+ it('is always named by its person: with none named it is refused, and nothing is recorded', () => {
const f = swarm()
- full(f, 'owner-mac')
- f.machine('mate-team').observation = reading('team', FAILED)
- const asked = f.lead(null)
- expect(asked.result).toMatchObject({ waiting: true })
- expect(asked.result).not.toHaveProperty('startId')
+ expect(refusal(() => f.lead(null))).toMatchObject({ code: 'MACHINE_REQUIRED', status: 400, message: 'Choose the machine the Product Manager runs on.' })
expect(f.state.starts ?? []).toEqual([])
- expect(f.project().lead).toMatchObject({ status: 'waiting', chosen: null })
- expect(asked.messages.map(m => m.text)).toEqual(['Waiting for a machine to start the Product Manager.'])
- // Nothing free yet: nothing changes.
- expect(await place(f)).toEqual([])
- expect(f.project().lead?.status).toBe('waiting')
- f.machine('owner-mac').maxAgents = 4
- expect(await place(f)).toEqual([f.app.projectId])
- expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'owner-mac', machineName: 'Owner Mac' })
- expect(f.state.starts).toEqual([expect.objectContaining({ actorKey: 'person:owner', request: expect.objectContaining({ machineId: 'owner-mac' }) })])
- })
-
- it('placed from the queue and failed there, waits for another machine and tries that one last', async () => {
- const f = swarm()
- const startId = f.lead(null).result.startId as string
- f.run({ type: 'agent.startFailed', startId, error: 'Out of disk.' }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner', hostGrant: null } })
- expect(f.project().lead).toMatchObject({ status: 'waiting', reason: 'Its machine could not prepare or launch it.', skipped: ['owner-mac'] })
- expect(await place(f, { now: NOW + MINUTE })).toEqual([f.app.projectId])
- expect(f.project().lead).toMatchObject({ status: 'starting', machineId: 'mate-team' })
- })
-
- // Security review 1 of #2089: a queued Product Manager that kept failing was placed again at every machine reading, each
- // failure a row in its conversation.
- it('failing again and again, waits longer each time, gives up after three, and says so once', async () => {
- const { LEAD_QUEUE_ATTEMPTS } = await import('./leadStart.js')
- expect(LEAD_QUEUE_ATTEMPTS).toBe(3)
- const f = swarm()
- const fail = (startId: string, now: number) => f.run({ type: 'agent.startFailed', startId, error: 'Out of disk.' }, owner,
- { now, contribution: { machineOwnerId: f.state.starts!.find(s => s.id === startId)!.machineOwnerId, contributorId: f.state.starts!.find(s => s.id === startId)!.contributorId, hostGrant: null } })
- const said = (effects: ReturnType<typeof f.run>) => effects.messages.filter(m => m.conversationId === f.app.conversationId).map(m => m.text)
- let startId = f.lead(null).result.startId as string
- expect(said(fail(startId, NOW))).toEqual([])
- expect(f.project().lead).toMatchObject({ status: 'waiting', failures: 1, retryAt: NOW + MINUTE })
- // Not before its time, then on the next free machine.
- expect(await place(f, { now: NOW + MINUTE - 1 })).toEqual([])
- expect(await place(f, { now: NOW + MINUTE })).toEqual([f.app.projectId])
- startId = f.project().lead!.startId!
- expect(said(fail(startId, NOW + MINUTE))).toEqual([])
- expect(f.project().lead).toMatchObject({ status: 'waiting', failures: 2, retryAt: NOW + 3 * MINUTE })
- expect(await place(f, { now: NOW + 3 * MINUTE })).toEqual([f.app.projectId])
- startId = f.project().lead!.startId!
- expect(said(fail(startId, NOW + 3 * MINUTE))).toEqual(['The Product Manager could not start after 3 tries. The last one: Its machine could not prepare or launch it. Start it again when a machine is ready.'])
- expect(f.project().lead).toMatchObject({ status: 'failed', failures: 3 })
- expect(await place(f, { now: NOW + 60 * MINUTE })).toEqual([])
- })
-
- it('is dropped when the person who asked left the Swarm, and waits while the Swarm is paused', async () => {
- const f = swarm()
- full(f, 'owner-mac'); full(f, 'mate-team')
- f.lead(null)
- f.machine('owner-mac').maxAgents = 4
- f.state.paused = true
- expect(await place(f)).toEqual([])
- f.state.paused = false
- f.state.people.find(p => p.id === 'owner')!.generation = 'rejoined'
- expect(await place(f)).toEqual([])
- expect(f.project().lead).toMatchObject({ status: 'failed', reason: 'The person who asked for it left the Swarm.' })
- })
-
- it('asked for again while waiting, takes the new request', () => {
+ expect(f.project().lead).toBeUndefined()
+ })
+
+ it('full, refuses it rather than placing it on another', () => {
const f = swarm()
- full(f, 'owner-mac'); full(f, 'mate-team')
- f.lead(null, { model: 'sonnet' })
- f.lead(null, { model: 'opus' })
- expect(f.project().lead).toMatchObject({ status: 'waiting', request: expect.objectContaining({ model: 'opus' }) })
+ f.machine('owner-mac').maxAgents = 0
+ expect(refusal(() => f.lead('owner-mac'))?.code).toBe('MACHINE_FULL')
+ expect(f.state.starts ?? []).toEqual([])
})
})
-// R2 (Lead, #895): a Team account runs every teammate's work as one macOS user, its folders holding other projects' clones.
-// Typing in a Product Manager there is a shell that reads them, so nobody types in it through the Swarm; its project's owner
-// may watch it, and the Mac's owner neither watches nor types. On the project owner's own machine nothing changes.
describe('the terminal of a Product Manager in a Team account', () => {
async function running(machineId: string) {
const f = swarm()
@@ -366,6 +402,52 @@ describe('the terminal of a Product Manager in a Team account', () => {
})
})
+// The trust change Ken chose (10-29): with no Team account able to take it, a teammate's Mac runs the Product Manager in
+// its owner's own account. That owner can read whatever the Product Manager reads on their Mac. Project members watch its
+// terminal live whichever account it runs in (Lead's ruling on #2228).
+describe('the terminal of a Product Manager on a teammate\'s Mac, as its owner', () => {
+ async function running(visibility: 'private' | 'public') {
+ const f = swarm()
+ if (visibility === 'public') f.run({ type: 'project.sharing', projectId: f.app.projectId, visibility: 'public', memberIds: [] })
+ f.machine('mate-team').observation = reading('team', FAILED)
+ const startId = f.lead('mate-mac').result.startId as string
+ const contribution = { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null }
+ const pm = f.run({ type: 'agent.started', startId, harnessId: 'pm', configuration: config }, owner, { contribution }).result.agentId as string
+ const { canWatchAgent } = await import('./projects.js')
+ const agent = f.state.agents.find(a => a.id === pm)!
+ const code = (actor: Actor, command: Command) => refusal(() => f.run(command, actor))?.code ?? 'ok'
+ return { agent, watch: (actor: Actor) => canWatchAgent(f.state, actor, agent),
+ screen: (actor: Actor) => code(actor, { type: 'agent.screen', agentId: pm, scrollback: 50 }),
+ input: (actor: Actor) => code(actor, { type: 'agent.input', agentId: pm, text: 'ls ~' }) }
+ }
+
+ it('runs on the Mac itself, outside any Team account', async () => {
+ const t = await running('private')
+ expect(t.agent).toMatchObject({ machineId: 'mate-mac', machineOwnerId: 'mate' })
+ expect((t.agent as { teamAccount?: boolean }).teamAccount).toBeUndefined()
+ })
+
+ it('its project\'s owner watches its terminal live, but neither types in it nor reads its screen in another person\'s account', async () => {
+ for (const visibility of ['private', 'public'] as const) {
+ const t = await running(visibility)
+ expect(t.watch(owner)).toBe(true)
+ expect(t.screen(owner)).toBe('TERMINAL_PRIVATE')
+ expect(t.input(owner)).toBe('TERMINAL_PRIVATE')
+ }
+ })
+
+ it('the Mac\'s owner reaches it through the Swarm only when they may read the project: a private one they are not in shows them nothing', async () => {
+ const hidden = await running('private')
+ expect(hidden.watch(mate)).toBe(false)
+ expect(hidden.screen(mate)).toBe('AGENT_UNAVAILABLE')
+ expect(hidden.input(mate)).toBe('AGENT_UNAVAILABLE')
+ const open = await running('public')
+ expect(open.watch(mate)).toBe(true)
+ expect(open.screen(mate)).toBe('ok')
+ expect(open.input(mate)).toBe('ok')
+ })
+})
+
// Every agent in a Team account runs as one macOS user and can read the others' files, the Product Manager's saved
// sessions with people's private chats among them. So a Team account hosting a Product Manager serves only its project.
describe('a Team account hosting a Product Manager', () => {
@@ -388,10 +470,10 @@ describe('a Team account hosting a Product Manager', () => {
it('is not where a Product Manager goes while another project\'s agents run there', () => {
const f = swarm(), web = other(f)
web.start()
- expect(refusal(() => f.lead('mate-mac'))).toMatchObject({ code: 'TEAM_ACCOUNT_BUSY',
+ expect(refusal(() => f.lead('mate-team'))).toMatchObject({ code: 'TEAM_ACCOUNT_BUSY',
message: 'The Harness Team account on MacBook Pro runs other projects\' agents, so it cannot host this Product Manager now.' })
- // From the queue it goes to the next free machine instead.
- expect(f.lead(null).result).toMatchObject({ machineId: 'owner-mac' })
+ // Named by its Mac, the Mac takes it itself.
+ expect(f.lead('mate-mac').result).toMatchObject({ machineId: 'mate-mac' })
})
it('holds an agent added by hand as it holds a start', () => {
diff --git a/backend/src/superTabs/leadStart.ts b/backend/src/superTabs/leadStart.ts
index 3b4d3ac1f..711e0dd66 100644
--- a/backend/src/superTabs/leadStart.ts
+++ b/backend/src/superTabs/leadStart.ts
@@ -1,12 +1,13 @@
/** A project's Product Manager started by the Swarm on one of its machines (Dee, 10-29, option B), as a Buddy's start is
- * (buddies.ts): recorded on the machine's contribution and launched by its host. On another person's Mac it runs only in
- * that Mac's Harness Team account, never as the Mac's owner, whatever the Swarm's switch (machines.ts teamAccountRequired)
- * says for workers: a Product Manager reads people's private chats. With no machine named, it waits for the first free
- * one. Desktop's own-machine flow (project.create, a local start, agent.add) is unchanged. */
-import { admitMachineStart, failTeamWork, machineContribution, machineSlots, projectFolder, projectsOnMachine, teamAccountPool, teamAccountSwarm, teamPoolOf, teamWorkRefusal,
- type ContributedMachine } from './machines.js'
-import { actorKey, fail, person, stableId, SuperTabError, type AgentStart, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'
-import { mutableProjects, projectsOf, type SwarmProject } from './projects.js'
+ * (buddies.ts): recorded on the machine's contribution and launched by its host. Any machine of the Swarm takes it (Ken,
+ * 10-29): on another person's Mac it runs in that Mac's Harness Team account when the account can take it now, else on the
+ * Mac itself, as its owner, whatever the Swarm's switch (machines.ts teamAccountRequired) says for workers. Its person always
+ * names the machine: only they know which one stays on (Ken, 10-29). Desktop's own-machine flow (project.create, a local
+ * start, agent.add) is unchanged. */
+import { admitMachineStart, contributedEngines, failTeamWork, machineContribution, projectFolder, projectsOnMachine, teamAccountPool, teamAccountSwarm, teamPoolOf,
+ teamWorkRefusal, type ContributedMachine } from './machines.js'
+import { actorKey, fail, person, SuperTabError, type AgentStart, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'
+import { projectsOf, type SwarmProject } from './projects.js'
import { failureNotice, publicReason } from './startFailure.js'
/** What a host reports it can launch: a Product Manager. A host from before it is never given one. */
@@ -15,28 +16,14 @@ export const LEAD_NAME = 'Product Manager'
export const LEAD_REQUIREMENTS: AgentStartRequest['requirements'] = { memoryBytes: 2 * 1024 ** 3, diskBytes: 1024 ** 3, maxCpuPercent: 85,
tools: ['git'], devices: [], quotaRequired: false }
-/** Where the project's Product Manager is: waiting for a machine, starting on one, started, or failed with the reason. */
+/** Where the project's Product Manager is: starting on the machine its person named, started, or failed with the reason. */
export interface LeadPlacement {
- status: 'waiting' | 'starting' | 'started' | 'failed'
- requestedAt: number
- requestedBy: { personId: string; generation: string }
- request: LeadRequest
- /** The machine the person named, or null: the first free one. */
- chosen: string | null
- machineId?: string
- machineName?: string
+ status: 'starting' | 'started' | 'failed'
+ machineId: string
+ machineName: string
startId?: string
reason?: string
- /** Machines a start from the queue already failed on, tried again only once no other is free. */
- skipped?: string[]
- /** How many starts from the queue failed, and when it is placed again: each wait twice the last (security review 1 of
- * #2089: one that kept failing was placed again at every machine reading, each failure a row in its conversation). */
- failures?: number
- retryAt?: number
}
-/** A Product Manager from the queue gives up after this many failed starts, and says so once. */
-export const LEAD_QUEUE_ATTEMPTS = 3
-const RETRY_BASE_MS = 60_000, RETRY_MAX_MS = 15 * 60_000
/** `repositoryUrl`: the address its folder is cloned from, recorded for a project that has none yet. */
export interface LeadRequest { engine: string; model?: string; effort?: string; branchRef?: string; repositoryUrl?: string }
@@ -47,41 +34,108 @@ export interface LeadContext {
teamAccountsIdle?: boolean
}
-/** The contribution [project]'s Product Manager runs in when placed on [machineId]: the machine itself for its own owner,
- * else the Mac's Harness Team account, refused with that account's reason. Never the Mac's owner's account. */
-function leadPool(state: SuperTabState, project: SwarmProject, machineId: string, context: LeadContext): ContributedMachine {
+/** The engines a Product Manager runs on, as people read them. */
+const LEAD_ENGINES = { claude: 'Claude Code', codex: 'Codex' } as const
+
+/** Admits [project]'s Product Manager as [start] asks, in [pool], or throws why not. Writes nothing. */
+function admitLead(state: SuperTabState, project: SwarmProject, pool: ContributedMachine, start: AgentStartRequest, context: LeadContext): void {
+ if (!contributedEngines(pool).includes(start.engine)) {
+ fail('ENGINE_NOT_OFFERED', `${LEAD_ENGINES[start.engine as keyof typeof LEAD_ENGINES] ?? start.engine} isn’t offered on ${pool.name}.`, 403)
+ }
+ admitMachineStart(state, start, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines, project)
+ // Its Team account will serve only this project (machines.ts productManagerOn), so not one running another's work now.
+ if (teamAccountPool(pool) && [...projectsOnMachine(state, pool.machineId)].some(id => id !== project.id)) {
+ fail('TEAM_ACCOUNT_BUSY', `The Harness Team account on ${pool.name} runs other projects' agents, so it cannot host this ${LEAD_NAME} now.`, 409)
+ }
+ if (!pool.observation?.capabilities?.includes(LEAD_CAPABILITY)) {
+ fail('HOST_OUTDATED', `Update Harness on ${pool.name} to run a ${LEAD_NAME} there.`, 409)
+ }
+}
+
+/** Where [project]'s Product Manager with [request]'s engine runs when its person names [machineId], as its start request; or
+ * throws why it cannot run there now. Writes nothing. The machine itself for its own owner; on another person's Mac, its
+ * Harness Team account when that admits this Product Manager with this engine now, else the Mac itself, as its owner,
+ * unless the Mac was added as its person joined. A Team account named itself keeps its rules and is refused with its reason.
+ * The start (placeLead) and New Project's machine list (leadChoices) both read it, so they never disagree. */
+export function leadHost(state: SuperTabState, project: SwarmProject, machineId: string, request: LeadRequest, leadFor: AgentStartRequest['leadFor'],
+ context: LeadContext): AgentStartRequest {
+ // A machine whose owner left the Swarm stays listed while its host cleans up. Its contribution is withdrawn; machineContribution
+ // would tell the person starting the Product Manager that they lost access themselves.
+ const listed = state.machines?.find(m => m.machineId === machineId)
+ if (listed && !state.people.some(p => p.id === listed.contributorId)) fail('CONTRIBUTION_REVOKED', 'This machine contribution was withdrawn.', 403)
const named = machineContribution(state, machineId) ?? fail('MACHINE_NOT_LISTED', 'Add this machine to the Swarm first.', 403)
- if (named.contributorId === project.ownerId) return named
+ const startIn = (pool: ContributedMachine): AgentStartRequest => ({ conversationId: project.leadConversationId, machineId: pool.machineId,
+ engine: request.engine, ...(request.model ? { model: request.model } : {}), ...(request.effort ? { effort: request.effort } : {}), name: LEAD_NAME,
+ cwd: projectFolder(pool, project), worktree: true, ...(request.branchRef ? { branchRef: request.branchRef } : {}), requirements: LEAD_REQUIREMENTS, leadFor })
const teamMachines = context.teamMachines ?? []
// With no GitHub App, or outside the Swarms Team accounts are tried in, a Team account takes no work (machines.ts
- // teamMachineFor) and the Mac would run it itself: refused, where a worker would go ahead.
- if (context.teamAccountsIdle || !teamAccountSwarm(state)) {
- fail('TEAM_ACCOUNT_REQUIRED', `Harness Team accounts take no work in this Swarm yet, so ${named.name} runs only its owner's projects.`, 403)
- }
- const pool = named.hostMachineId ? named : teamPoolOf(state, named, teamMachines) ?? named
- const refusal = teamWorkRefusal(pool, context.now, teamMachines.includes(pool.machineId), true,
+ // teamMachineFor).
+ const teamsWork = !context.teamAccountsIdle && teamAccountSwarm(state)
+ const refusal = (pool: ContributedMachine) => teamWorkRefusal(pool, context.now, teamMachines.includes(pool.machineId), true,
(context.otherWorkspaceMachines ?? []).includes(pool.machineId))
- if (refusal) failTeamWork(refusal)
- return pool
+ let candidates: ContributedMachine[]
+ if (named.contributorId === project.ownerId) candidates = [named]
+ else if (teamAccountPool(named)) {
+ if (!teamsWork) fail('TEAM_ACCOUNT_REQUIRED', `Harness Team accounts take no work in this Swarm yet, so ${named.name} runs only its owner's projects.`, 403)
+ const why = refusal(named)
+ if (why) failTeamWork(why)
+ candidates = [named]
+ } else {
+ const team = teamsWork ? teamPoolOf(state, named, teamMachines) : undefined
+ // A Mac added as its person joined, not lent, takes teammates' work only in its Team account (machines.ts teamAccountOnly).
+ if (named.teamAccountOnly) {
+ const pool = team ?? named
+ const why = refusal(pool)
+ if (why) failTeamWork(why)
+ candidates = [pool]
+ } else candidates = team && !refusal(team) ? [team, named] : [named]
+ }
+ // The Team account first, with every check its start has (engine, sign-in, room, other projects' work, its host); refused
+ // there for any reason, the Mac itself (security reviews 1 and 2 of #2228). The last one's reason is the answer.
+ for (const [i, pool] of candidates.entries()) {
+ const start = startIn(pool)
+ try {
+ admitLead(state, project, pool, start, context)
+ return start
+ } catch (error) {
+ if (!(error instanceof SuperTabError) || i === candidates.length - 1) throw error
+ }
+ }
+ throw new Error('unreachable: a Product Manager has at least one candidate machine')
+}
+
+/** Where New Project's Product Manager would run on each teammate's machine, for [personId] as its owner, by engine: the
+ * machine it runs in, or why it cannot run there now. The same answer leadHost gives the start, before the project exists, so
+ * Desktop shows the server's decision rather than working one out (security review 1 of #2228). The person's own machines
+ * are left to Desktop, which starts the Product Manager there itself; a Team account is read through its Mac. Reasons name
+ * no other project. */
+export function leadChoices(state: SuperTabState, personId: string, context: LeadContext): Record<string, Record<string, { machineId: string } | { refused: string }>> {
+ const by = state.people.find(p => p.id === personId)
+ if (!by || state.paused) return {}
+ const project = { id: '', name: '', ownerId: personId, leadConversationId: '', visibility: 'private', members: [], updateMinutes: 5,
+ skillMode: 'default' } as unknown as SwarmProject
+ const leadFor = { projectId: '', personId, generation: by.generation }
+ const choices: Record<string, Record<string, { machineId: string } | { refused: string }>> = {}
+ for (const machine of state.machines ?? []) {
+ if (machine.hostMachineId || machine.removal || machine.contributorId === personId) continue
+ choices[machine.machineId] = Object.fromEntries(Object.keys(LEAD_ENGINES).map(engine => {
+ try {
+ return [engine, { machineId: leadHost(state, project, machine.machineId, { engine }, leadFor, context).machineId }]
+ } catch (error) {
+ if (!(error instanceof SuperTabError)) throw error
+ return [engine, { refused: error.message }]
+ }
+ }))
+ }
+ return choices
}
/** Records the start of [project]'s Product Manager on [machineId] for [by], and marks the project starting. Refuses, and
* changes nothing, when that machine cannot take it now. */
export function placeLead(state: SuperTabState, project: SwarmProject, by: Person, machineId: string, request: LeadRequest,
startId: string, context: LeadContext): AgentStart {
- const pool = leadPool(state, project, machineId, context)
- const start: AgentStartRequest = { conversationId: project.leadConversationId, machineId: pool.machineId, engine: request.engine,
- ...(request.model ? { model: request.model } : {}), ...(request.effort ? { effort: request.effort } : {}), name: LEAD_NAME,
- cwd: projectFolder(pool, project), worktree: true, ...(request.branchRef ? { branchRef: request.branchRef } : {}),
- requirements: LEAD_REQUIREMENTS, leadFor: { projectId: project.id, personId: by.id, generation: by.generation } }
- admitMachineStart(state, start, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)
- // Its Team account will serve only this project (machines.ts productManagerOn), so not one running another's work now.
- if (teamAccountPool(pool) && [...projectsOnMachine(state, pool.machineId)].some(id => id !== project.id)) {
- fail('TEAM_ACCOUNT_BUSY', `The Harness Team account on ${pool.name} runs other projects' agents, so it cannot host this ${LEAD_NAME} now.`, 409)
- }
- if (!pool.observation?.capabilities?.includes(LEAD_CAPABILITY)) {
- fail('HOST_OUTDATED', `Update Harness on ${pool.name} to run a ${LEAD_NAME} there.`, 409)
- }
+ const start = leadHost(state, project, machineId, request, { projectId: project.id, personId: by.id, generation: by.generation }, context)
+ const pool = machineContribution(state, start.machineId)!
state.starts ??= []
if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')
const contributor = person(state, pool.contributorId)
@@ -91,8 +145,7 @@ export function placeLead(state: SuperTabState, project: SwarmProject, by: Perso
harnessId: null, dispatched: false, error: null, requestedAt: context.now }
state.starts.push(recorded)
project.repository ??= { machineId: pool.machineId, cwd: start.cwd, repositoryUrl: request.repositoryUrl ?? null }
- const { reason: _reason, ...placement } = project.lead!
- project.lead = { ...placement, status: 'starting', machineId: pool.machineId, machineName: pool.name, startId }
+ project.lead = { status: 'starting', machineId: pool.machineId, machineName: pool.name, startId }
return recorded
}
@@ -114,77 +167,14 @@ export function leadJoined(state: SuperTabState, start: AgentStart, home: Conver
return `${LEAD_NAME} started on ${placement?.machineName ?? state.machines?.find(m => m.machineId === start.request.machineId)?.name ?? 'its machine'}.`
}
-/** Its start failed with [reason] at [now]: on the machine its person chose, the project says why and waits for them; placed
- * from the queue, it waits for another machine, longer after each failure, and gives up after LEAD_QUEUE_ATTEMPTS. The line
- * its conversation shows, once, when it stops trying; null while it still waits. */
-export function leadStartFailed(state: SuperTabState, start: AgentStart, reason: string, now: number): string | null {
+/** Its start failed with [reason]: the project says why and waits for its person to name a machine again. The line its
+ * conversation shows; null for a start that is no longer the project's. */
+export function leadStartFailed(state: SuperTabState, start: AgentStart, reason: string): string | null {
const placement = placementOf(state, start)
if (!placement) return null
delete placement.startId
// Every reader of the project reads its placement: the reason a group member may read, never the host's own words, which
// can name a folder on the machine or a token problem (startFailure.ts). Its asker reads those on the start.
- const shown = publicReason(reason)
- if (placement.chosen !== null) {
- Object.assign(placement, { status: 'failed', reason: shown })
- return failureNotice(start.request.name, reason)
- }
- const failures = (placement.failures ?? 0) + 1
- delete placement.machineId
- delete placement.machineName
- if (failures >= LEAD_QUEUE_ATTEMPTS) {
- delete placement.retryAt
- Object.assign(placement, { status: 'failed', reason: shown, failures })
- return `The ${LEAD_NAME} could not start after ${failures} tries. The last one: ${shown} Start it again when a machine is ready.`
- }
- Object.assign(placement, { status: 'waiting', reason: shown, failures, retryAt: now + Math.min(RETRY_BASE_MS * 2 ** (failures - 1), RETRY_MAX_MS),
- skipped: [...new Set([...placement.skipped ?? [], start.request.machineId])].slice(-16) })
- return null
-}
-
-export const WAITING_TEXT = `Waiting for a machine to start the ${LEAD_NAME}.`
-
-/** lead.start: [project]'s Product Manager on [machineId], refused with the reason when it cannot run there now; or, with
- * none named, on the first free machine, else waiting for one (placeWaitingLeads). A request already waiting is replaced. */
-export function requestLead(state: SuperTabState, project: SwarmProject, by: Person, machineId: string | null, request: LeadRequest,
- operationId: string, context: LeadContext): { startId: string; machineId: string } | { waiting: true } {
- project.lead = { status: 'waiting', requestedAt: context.now, requestedBy: { personId: by.id, generation: by.generation }, request, chosen: machineId }
- const start = machineId ? placeLead(state, project, by, machineId, request, operationId, context) : placeOnFree(state, project, by, operationId, context)
- return start ? { startId: start.id, machineId: start.request.machineId } : { waiting: true }
-}
-
-/** The machines a waiting Product Manager is tried on, in order: the project owner's own, then the most free agent slots, and
- * last those a start from the queue already failed on. A Mac's Harness Team account is reached through its Mac. */
-function candidates(state: SuperTabState, project: SwarmProject): string[] {
- const skipped = project.lead?.skipped ?? []
- const rank = (m: ContributedMachine) => [skipped.includes(m.machineId) ? 1 : 0, m.contributorId === project.ownerId ? 0 : 1, machineSlots(state, m) - m.maxAgents] as const
- return (state.machines ?? []).filter(m => !m.hostMachineId).map(m => ({ m, r: rank(m) }))
- .sort((a, b) => a.r[0] - b.r[0] || a.r[1] - b.r[1] || a.r[2] - b.r[2]).map(({ m }) => m.machineId)
-}
-
-function placeOnFree(state: SuperTabState, project: SwarmProject, by: Person, startId: string, context: LeadContext): AgentStart | null {
- for (const machineId of candidates(state, project)) {
- try { return placeLead(state, project, by, machineId, project.lead!.request, startId, context) } catch (error) {
- // Each refusal comes before anything is written (placeLead), so the next machine sees the state unchanged.
- if (!(error instanceof SuperTabError)) throw error
- }
- }
- return null
-}
-
-/** On a machine's reading: each project whose Product Manager waits starts on the first free machine. The ids of those
- * placed. Nothing is read or written for a Swarm with none waiting. */
-export function placeWaitingLeads(state: SuperTabState, context: LeadContext): string[] {
- const waiting = projectsOf(state).filter(p => p.lead?.status === 'waiting' && !(p.lead.retryAt !== undefined && p.lead.retryAt > context.now))
- if (!waiting.length || state.paused) return []
- const placed: string[] = []
- for (const { id } of waiting) {
- const project = mutableProjects(state).find(p => p.id === id)!, lead = project.lead!
- const by = state.people.find(p => p.id === lead.requestedBy.personId && p.generation === lead.requestedBy.generation)
- if (!by) {
- Object.assign(lead, { status: 'failed', reason: 'The person who asked for it left the Swarm.' })
- continue
- }
- if (placeOnFree(state, project, by, stableId('lead-start', project.id, String(lead.requestedAt), String(context.now)), context)) placed.push(project.id)
- }
- return placed
+ Object.assign(placement, { status: 'failed', reason: publicReason(reason) })
+ return failureNotice(start.request.name, reason)
}
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 350fc5c2d..4bbbbce13 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -389,7 +389,7 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {
if (!report || now - report.receivedAt > MACHINE_FRESH_MS) return []
if (start.request.leadFor) {
start.error = `${machineName(state, start.request.machineId)}${LEAD_PICKUP_SUFFIX}`
- return leadNotice(state, start, leadStartFailed(state, start, start.error, now))
+ return leadNotice(state, start, leadStartFailed(state, start, start.error))
}
start.error = `${machineName(state, start.request.machineId)} did not start this Buddy. Update Harness on it, then add the Buddy again.`
return buddyNotice(state, start)
@@ -404,7 +404,7 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {
start.error = `${machine}${!named ? TIMED_OUT_SUFFIX : silent ? STOPPED_REPORTING_SUFFIX : STILL_PREPARING_SUFFIX}`
// Counted as a host's failure is (commands.ts agent.startFailed); the one that suspends its engine says so once.
const suspended = noteStartFailed(state, start, now)
- if (start.request.leadFor) return leadNotice(state, start, leadStartFailed(state, start, start.error, now))
+ if (start.request.leadFor) return leadNotice(state, start, leadStartFailed(state, start, start.error))
// Never a lookup that throws: these checks run inside every machine's report.
if (start.request.buddyOf) return buddyNotice(state, start)
const group = state.conversations.find(c => c.id === start.request.conversationId)
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index ceda5ddd1..7cb75f3ed 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -3,6 +3,7 @@ import { engineUnusable } from './engineHealth.js'
import { MAX_HARNESSES, tokensByModelSchema } from './costs/tokens.js'
import { activeWork, fail, person, stableId, type Actor, type Agent, type AgentStart, type AgentStartRequest, type MessageDraft, type SuperTabState } from './model.js'
import { WORKSPACE_LABEL } from './workspaces.js'
+import { startFinished } from './parts/write.js'
import { agentProjectId, canReadProject, groupProject, ledProject, projectsOf, teamAccountPool, type SwarmProject } from './projects.js'
export { teamAccountPool } from './projects.js'
import { conversation } from './model.js'
@@ -497,7 +498,9 @@ function poolSlots(state: SuperTabState, pool: ContributedMachine) {
let pending = 0
for (const start of state.starts ?? []) {
if (start.request.machineId !== pool.machineId || start.error) continue
- if (start.harnessId) { if (!stopped.has(start.harnessId)) running.add(start.harnessId) }
+ // A finished start's harness counts through its agent or its host's report. Reads keep finished starts until they expire,
+ // and counted every harness ever started there (Mac Studio, 10-29: 13 running, 121 counted, no free agents shown).
+ if (start.harnessId) { if (!startFinished(start) && !stopped.has(start.harnessId)) running.add(start.harnessId) }
else pending++
}
return running.size + pending
@@ -537,22 +540,25 @@ export function localModelAllowed(state: SuperTabState, request: AgentStartReque
/** `teamMachines`: the tab's machines whose account row is signed in as a team account, read by the store. A start is
* admitted again when its host launches it, so a Team machine whose check failed or went stale since never launches it. */
+/** [forProject]: the project it is for when that is not yet its conversation's, as New Project's Product Manager before the
+ * project exists (leadStart.ts leadChoices). */
export function admitMachineStart(state: SuperTabState, request: AgentStartRequest, now: number, start?: AgentStart, teamMachines: readonly string[] = [],
- otherWorkspaceMachines: readonly string[] = []) {
+ otherWorkspaceMachines: readonly string[] = [], forProject?: SwarmProject) {
const pool = machineContribution(state, request.machineId)
if (!pool) return null
if (pool.removal) fail('MACHINE_REMOVED', 'This machine is being removed from the Swarm.')
if (start && start.poolGeneration !== pool.generation) fail('CONTRIBUTION_REVOKED', 'This machine contribution changed. Reconcile the original start.', 403)
if (pool.paused) fail('MACHINE_PAUSED', 'New work is paused on this machine.')
- const project = groupProject(state, conversation(state, request.conversationId))
+ const project = forProject ?? groupProject(state, conversation(state, request.conversationId))
if (!pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')
const held = teamAccountPool(pool) ? productManagerOn(state, pool.machineId) : null
if (held && held !== project.id) {
fail('TEAM_ACCOUNT_HELD', `The Harness Team account on ${pool.name} runs another project's Product Manager, so it takes only that project's work for now.`, 403)
}
// Before the request's own fields: a machine that takes none of this project's work says so first. A Buddy is its owner's
- // own agent on their own machine (commands.ts buddy.create), as a Lead is: teammates' work rules do not apply to it.
- if (!request.buddyOf) requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines, otherWorkspaceMachines)
+ // own agent on their own machine (commands.ts buddy.create), as a Lead is: teammates' work rules do not apply to it. Nor to
+ // a Product Manager outside a Team account: any machine of the Swarm takes it (leadStart.ts, Ken 10-29).
+ if (!request.buddyOf && !(request.leadFor && !teamAccountPool(pool))) requireTeamWork(state, pool.machineId, pool.contributorId, project, now, teamMachines, otherWorkspaceMachines)
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.
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index d488c139e..50fabf690 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -61,7 +61,10 @@ export interface Derived {
/** `clientVersion`: the CLI version its daemon last connected with (routing reads a machine updated since its failed starts). */
machines: Record<string, { availableSlots: number; teamWork: { allowed: true } | { allowed: false; reason: string; [key: string]: unknown }; clientVersion?: string
/** Engines suspended there now after failed starts, with why (engineHealth.ts); absent when none. */
- suspendedEngines?: Record<string, string> }>
+ suspendedEngines?: Record<string, string>
+ /** A person reading a teammate's machine: where New Project's Product Manager would run there by engine, the machine
+ * (its Team account or itself), or why it cannot now (leadStart.ts leadChoices). Absent for their own machines. */
+ lead?: Record<string, { machineId: string } | { refused: string }> }>
/** A Lead agent only. */
otherProjectsWork?: OtherProjectWorkView[]
/** A person only. */
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index acdf678b7..2018a7553 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -249,7 +249,7 @@ export class SwarmReads {
readLastChangedAt(tx, cached, tabId),
])
return { parts: loaded, actor, lastChangedAt: newest,
- view: readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions,
+ view: readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, teamAccountsIdle: this.store.teamAccountsIdle,
...(counts ? { mentionsWaiting: counts[0].count, mentionsDigest: counts[0].digest, decisionsWaiting: counts[1].count,
decisionsDigest: counts[1].digest } : {}) }, state) }
}
diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.ts
index 5cd5d3910..ecb81df15 100644
--- a/backend/src/superTabs/read/views.test.ts
+++ b/backend/src/superTabs/read/views.test.ts
@@ -101,7 +101,16 @@ describe('reader view of the parts (design 4.1, 4.3)', () => {
const view = readerView(parts, peer, NOW, { teamMachines: [] })
expect(view.parts.machines.map(m => m.key)).toEqual(['mac'])
expect(view.parts.machines[0]!.data.observation!.runningHarnessIds).toEqual(['lead-harness'])
- expect(view.derived.machines).toEqual({ mac: { availableSlots: 1, teamWork: { allowed: true } } })
+ // A teammate's machine says where New Project's Product Manager would run there, by engine (leadStart.ts leadChoices).
+ expect(view.derived.machines).toEqual({ mac: { availableSlots: 1, teamWork: { allowed: true }, lead: {
+ claude: { refused: 'Claude Code isn’t offered on mac.' }, codex: { refused: 'Update Harness on mac to run a Product Manager there.' } } } })
+ })
+
+ it('tells only a person where New Project\'s Product Manager would run, and only on a teammate\'s machine', () => {
+ const { parts, s } = scene()
+ expect(readerView(parts, owner, NOW, { teamMachines: [] }).derived.machines.mac).not.toHaveProperty('lead')
+ expect(readerView(parts, agentActor(s.worker), NOW, { teamMachines: [] }).derived.machines.mac).not.toHaveProperty('lead')
+ expect(readerView(parts, peer, NOW, { teamMachines: [] }).derived.machines.mac).toHaveProperty('lead')
})
// The route leaves a suspended engine out and Desktop strikes it through (engineHealth.ts); 6 hours on it no longer shows.
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 47040455d..c3ac58858 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -4,6 +4,7 @@
* in `derived`, so a part never changes without a new version (Lead's ruling).
*/
import { suspendedEngines } from '../engineHealth.js'
+import { leadChoices } from '../leadStart.js'
import { isBuddyChat, isBuddyReader } from '../buddies.js'
import { agentWithoutMachine, groupWithoutMachines, isLeads, seenMachineIds, visibleState, withSeenRequirement, type Actor, type Agent, type Conversation, type SuperTabState } from '../model.js'
import { machineSlots, machineTeamWork, teamAccountSwarm, type ContributedMachine } from '../machines.js'
@@ -34,6 +35,8 @@ export interface ReadExtras {
teamMachines: string[]
/** Machines also contributed to a Swarm of another Workspace (store.ts otherWorkspaceMachines). */
otherWorkspaceMachines?: string[]
+ /** No Harness GitHub App on this server, so Team accounts take no work (store.ts teamAccountsIdle). */
+ teamAccountsIdle?: boolean
/** Each contributed machine's CLI version as its daemon last connected (store.ts machineFacts). */
machineVersions?: Record<string, string>
/** A person's open mentions, counted by the store. */
@@ -111,6 +114,11 @@ export const progressView = (data: NonNullable<SwarmParts['progress'][number]['d
({ ...data, requestedAt: data.requestedAt ?? null })
function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now: number, extras: ReadExtras): Derived {
+ // Where New Project's Product Manager would run on each teammate's machine, decided as its start decides (leadStart.ts).
+ const leads = actor.kind === 'person' && state.people.find(p => p.id === actor.userId)?.role !== 'viewer'
+ ? leadChoices(state, actor.userId, { now, teamMachines: extras.teamMachines, otherWorkspaceMachines: extras.otherWorkspaceMachines ?? [],
+ ...(extras.teamAccountsIdle ? { teamAccountsIdle: true } : {}) })
+ : {}
const machine = (pool: ContributedMachine) => {
const stored = state.machines!.find(m => m.machineId === pool.machineId)!
const refusal = machineTeamWork(state, stored, now, extras.teamMachines, extras.otherWorkspaceMachines ?? [])
@@ -118,7 +126,7 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
const suspended = suspendedEngines(stored, now)
return [pool.machineId, { availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, stored)),
teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const }, ...(version ? { clientVersion: version } : {}),
- ...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}) }] as const
+ ...(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}), ...(leads[pool.machineId] ? { lead: leads[pool.machineId] } : {}) }] as const
}
return {
agents: Object.fromEntries(visible.agents.map(seen => [seen.id, { downSince: seen.downSince ?? null, limitedUntil: seen.limitedUntil ?? null,
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 6caa29008..e0491ce28 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -20,7 +20,6 @@ import { randomBytes } from 'node:crypto'
import type { Readable } from 'node:stream'
import { logger } from '../utils/logger.js'
import { retryTransient } from './retry.js'
-import { placeWaitingLeads } from './leadStart.js'
import { buddyChatId } from './buddies.js'
import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, type ProjectVisibility } from './projects.js'
import { bindSession, makeProjectPrivate } from './sessionScope.js'
@@ -384,6 +383,10 @@ export class SuperTabStore {
get avatars(): AvatarStore | null { return this.attachments?.avatars ?? null }
/** The folder avatar keys start with (attachments.ts `avatarPrefix`). */
get avatarPrefix(): string { return trimPrefix(this.attachments?.avatarPrefix ?? this.attachments?.prefix ?? '') }
+ /** No Harness GitHub App on this server: Team accounts take no teammates' work (SuperTabStoreHooks.teamAccountsIdle). Reads
+ * decide New Project's Product Manager host as its start does (read/views.ts). */
+ get teamAccountsIdle(): boolean { return this.hooks.teamAccountsIdle === true }
+
constructor(readonly db: PrismaClient, readonly now: () => number = Date.now,
private readonly attachments: Attachments | null = null, private readonly hooks: SuperTabStoreHooks = {}) {
this.polls = hooks.polls ?? localPollMemory(now)
@@ -2214,12 +2217,6 @@ export class SuperTabStore {
// Its own agents lose their tasks at once (a stopped session); every 30 seconds it runs the Swarm's time checks too, so
// they keep running when the Lead's own machine is the one that died.
const checked = [...loseTasks(state, now, worker => worker.machineId === machineId), ...sweep ? sweepLiveness(state, now) : []]
- // A Product Manager waiting for a machine starts on the first free one (leadStart.ts). The Team machines are read only
- // while one waits.
- if (projectsOf(state).some(p => p.lead?.status === 'waiting')) {
- placeWaitingLeads(state, { now, teamMachines: await this.teamMachines(tx, state), otherWorkspaceMachines: await this.otherWorkspaceMachines(tx, state),
- ...(this.hooks.teamAccountsIdle ? { teamAccountsIdle: true } : {}) })
- }
return saved(checked)
})
}
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
index f1baa10cc..e6e493bb4 100644
--- a/desktop/lib/state/harness_launch_integration.dart
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -2,7 +2,7 @@ import 'harness_attachments.dart';
import 'lead_placement.dart';
/// A new project's Product Manager the Swarm starts rather than this
-/// Desktop: on [machineId], or with none the first free machine.
+/// Desktop, on [machineId].
class LeadSwarmStart {
const LeadSwarmStart({
required this.machineId,
@@ -12,8 +12,8 @@ class LeadSwarmStart {
required this.task,
this.files = const [],
});
- final String? machineId, repositoryUrl, title;
- final String engine, task;
+ final String? repositoryUrl, title;
+ final String machineId, engine, task;
final List<HarnessAttachment> files;
}
diff --git a/desktop/lib/state/lead_placement.dart b/desktop/lib/state/lead_placement.dart
index 268c3da96..db861a448 100644
--- a/desktop/lib/state/lead_placement.dart
+++ b/desktop/lib/state/lead_placement.dart
@@ -14,6 +14,7 @@ class LeadMachine {
this.own = true,
this.native = true,
this.team = false,
+ this.teamEngines,
this.engineRefusals = const {},
});
final String id, name;
@@ -38,6 +39,14 @@ class LeadMachine {
/// It runs in that machine's Harness Team account.
final bool team;
+ /// The engines it runs in that Mac's Harness Team account, as the server
+ /// decided (backend leadStart.ts leadChoices); the others run on the Mac
+ /// itself. Null from a server that does not say: then [team] holds for all.
+ final Set<String>? teamEngines;
+
+ /// It runs with [engine] in that Mac's Harness Team account.
+ bool inTeam(String engine) => teamEngines?.contains(engine) ?? team;
+
/// The repositories the Swarm already checked out there, as
/// [leadRepositoryKey] reads them.
final Set<String> repositories;
@@ -174,51 +183,14 @@ List<LeadMachine> rankLeadMachines(
);
}
-/// Where the Swarm places the Product Manager, or null when no machine can
-/// take it now.
-LeadMachine? bestLeadMachine(
- Iterable<LeadMachine> machines,
- String? repository,
-) => rankLeadMachines(
- machines,
- repository,
-).where((m) => m.startable).firstOrNull;
-
-/// Where the Product Manager starts and with which engine, or null when no
-/// machine can start it now. Never a machine that cannot run the engine it
-/// proposes. Your own machines come first: among them the best that runs
-/// [engine], else the best with another engine, unless the person chose
-/// [engine] ([engineChosen]); then a teammate's the same way.
-({LeadMachine machine, String engine})? bestLeadPlacement(
- Iterable<LeadMachine> machines,
- String? repository, {
- required String engine,
- bool engineChosen = false,
-}) {
- final ready = rankLeadMachines(
- machines,
- repository,
- ).where((m) => m.startable).toList();
- for (final own in [true, false]) {
- final group = ready.where((m) => m.own == own);
- if (group.where((m) => m.runs(engine)).firstOrNull case final machine?) {
- return (machine: machine, engine: engine);
- }
- final other = engineChosen ? null : group.firstOrNull;
- if (other != null) {
- return (machine: other, engine: other.leadEngines.first);
- }
- }
- return null;
-}
-
/// A machine's row detail, in words, so colour is never the only signal.
String leadMachineDetail(LeadMachine machine, String? repository) {
if (machine.unavailable case final why?) return why;
if (!machine.online) return 'Offline';
if (machine.leadEngines.isEmpty) {
+ // One reason for both engines (a paused or offline machine) said once.
return 'Can’t run a Product Manager: '
- '${[for (final engine in kLeadEngines) ?machine.engineRefusals[engine]].join(', ')}';
+ '${{for (final engine in kLeadEngines) ?machine.engineRefusals[engine]}.join(', ')}';
}
final free = machine.freeAgents;
if (free == null) return 'Online · Not in this Swarm';
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 89ff34063..6ee474bb9 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -517,6 +517,8 @@ class NewHarnessController extends ChangeNotifier {
// its machine, whatever machine this form was opened on.
if (this.integration case final request? when request.pending) {
_machineId = request.machineId ?? _machineId;
+ // Its person chose that machine when it was sent.
+ _leadPicked = request.machineId != null;
if (request.engine case final engine?) {
_engine = engine;
_harnessId = null;
@@ -1581,68 +1583,40 @@ class NewHarnessController extends ChangeNotifier {
/// Desktop: a teammate's Team account, or a machine of the person's this
/// Desktop is not connected to. The repo stays the one chosen on
/// [machineId]; that machine clones it. Null when this Desktop starts it on
- /// [machineId], or when it waits ([leadQueued]).
+ /// [machineId].
String? _swarmLeadMachine;
String? get leadSwarmMachine => _swarmLeadMachine;
- /// The machine the Product Manager starts on, as the Swarm lists it.
- LeadMachine? get leadMachine => integration?.leadMachines
- ?.where((m) => m.id == (_swarmLeadMachine ?? _machineId))
- .firstOrNull;
+ /// The person chose the Product Manager's machine: none is chosen for them,
+ /// since only they know which one stays on (Ken, 10-29).
+ bool _leadPicked = false;
+ bool get leadPicked => _leadPicked;
+
+ /// The machine the Product Manager starts on, as the Swarm lists it; null
+ /// until the person chooses one.
+ LeadMachine? get leadMachine => !_leadPicked
+ ? null
+ : integration?.leadMachines
+ ?.where((m) => m.id == (_swarmLeadMachine ?? _machineId))
+ .firstOrNull;
bool _paused(List<LeadMachine> machines) =>
machines.isNotEmpty &&
machines.every((m) => m.unavailable == kLeadSwarmPaused);
- /// The person chose the Product Manager's engine under Advanced: placement
- /// keeps it rather than switching to one a machine runs.
- bool _leadEngineChosen = false;
-
- /// Where the Product Manager starts and with which engine, or null.
- ({LeadMachine machine, String engine})? _leadPlacement(
- List<LeadMachine> machines,
- ) => bestLeadPlacement(
- machines,
- cloudRepository,
- engine: _engine,
- engineChosen: _leadEngineChosen,
- );
-
- /// [machine] could take the Product Manager once it is online and has room.
- bool _leadWaitsFor(LeadMachine machine) =>
- machine.unavailable == null &&
- (_leadEngineChosen
- ? machine.runs(_engine)
- : machine.leadEngines.isNotEmpty);
-
- bool _leadUnplaced(List<LeadMachine> machines) =>
- _swarmLeadMachine == null &&
- leadMachine?.startable != true &&
- !_paused(machines) &&
- _leadPlacement(machines) == null;
-
- /// No machine can take the Product Manager now: New Project asks the
- /// Swarm to start it on the first one that frees up.
- bool get leadQueued {
- final machines = integration?.leadMachines;
- return machines != null &&
- _leadUnplaced(machines) &&
- machines.any(_leadWaitsFor);
- }
-
- /// No machine could run the Product Manager even with room: each is
- /// another person's, or runs no engine it can start with.
+ /// No machine could start the Product Manager now: each is paused, offline,
+ /// full, another person's that cannot take it, or runs no engine it can
+ /// start with. Its list says why for each.
bool get leadNone {
final machines = integration?.leadMachines;
return machines != null &&
- _leadUnplaced(machines) &&
- !machines.any(_leadWaitsFor);
+ !_paused(machines) &&
+ !machines.any((m) => m.startable);
}
- /// The Swarm starts the Product Manager, on [leadSwarmMachine] or the first
- /// free machine; this Desktop does not.
- bool get leadThroughSwarm =>
- placesLead && (_swarmLeadMachine != null || leadQueued);
+ /// The Swarm starts the Product Manager, on [leadSwarmMachine]; this
+ /// Desktop does not.
+ bool get leadThroughSwarm => placesLead && _swarmLeadMachine != null;
/// The address the Swarm clones the chosen repo from, or null when it is
/// not known.
@@ -1661,14 +1635,10 @@ class NewHarnessController extends ChangeNotifier {
/// The Product Manager line: where it starts, its engine and model.
String get leadLine {
- if (leadQueued) {
- return 'All Swarm machines are busy. The project starts on the first '
- 'one that frees up.';
- }
final target = leadMachine;
final name = target == null
? machineLabel
- : target.team
+ : target.inTeam(_engine)
? '${target.name}’s Team account'
: target.name;
return ['Product Manager on $name', agentLabel, leadModelLabel].join(' · ');
@@ -1676,7 +1646,7 @@ class NewHarnessController extends ChangeNotifier {
/// Under [leadLine]: the repo that machine clones first, or null.
String? get leadCloneNote {
- if (leadQueued || _leadRepositoryName == null) return null;
+ if (_leadRepositoryName == null) return null;
final target = leadMachine;
final clones = leadThroughSwarm
? target != null && !target.has(leadRepositoryUrl)
@@ -1692,11 +1662,12 @@ class NewHarnessController extends ChangeNotifier {
return '$kLeadSwarmPaused. New Project can start once it resumes.';
}
if (leadNone) return 'No machine can run the Product Manager now.';
- if (leadMachine?.startable != true && !leadQueued) {
+ if (!_leadPicked) return 'Choose the machine the Product Manager runs on.';
+ if (leadMachine?.startable != true) {
final name = leadMachine?.name ?? machineLabel;
return '$name cannot start the Product Manager. Choose another machine.';
}
- final refusal = leadQueued ? null : leadMachine?.engineRefusals[_engine];
+ final refusal = leadMachine?.engineRefusals[_engine];
if (refusal != null) {
return '${leadMachine!.name} can’t run $agentLabel: $refusal. '
'Choose another engine under Advanced.';
@@ -1714,23 +1685,7 @@ class NewHarnessController extends ChangeNotifier {
return _leadModelListRefusal;
}
- /// Moves the Product Manager to the best machine the Swarm lists with an
- /// engine it runs there, unless it is already so placed; with none free,
- /// it waits ([leadQueued]).
- void placeLead() {
- final machines = integration?.leadMachines;
- if (machines == null || locked) return;
- final placed = _leadPlacement(machines);
- if (placed == null) return;
- if (placed.engine != _engine) _placeLeadEngine(placed.engine);
- if (placed.machine.id != leadMachine?.id) {
- chooseLeadMachine(placed.machine.id);
- } else {
- notifyListeners();
- }
- }
-
- /// The engine placement picked, as a choice the person did not make.
+ /// The engine a chosen machine runs, as a choice the person did not make.
void _placeLeadEngine(String engine) {
final touched = _selectionTouched;
_selectEngine(engine);
@@ -1747,12 +1702,12 @@ class NewHarnessController extends ChangeNotifier {
.firstOrNull;
// The machine chosen last wins over an engine it cannot run.
if (listed != null && listed.startable && !listed.runs(_engine)) {
- _leadEngineChosen = false;
_placeLeadEngine(listed.leadEngines.first);
}
if (listed != null && listed.startable && !listed.native) {
error = null;
_swarmLeadMachine = id;
+ _leadPicked = true;
notifyListeners();
return;
}
@@ -1770,6 +1725,7 @@ class NewHarnessController extends ChangeNotifier {
}
error = null;
_swarmLeadMachine = null;
+ _leadPicked = true;
final remote = _remoteOf(_machineId, _project);
_selectMachine(id);
if (remote != null) _keepRepository(id, remote, listed.name);
@@ -2589,11 +2545,9 @@ class NewHarnessController extends ChangeNotifier {
if (option.id != codingId) _selectEngine(option.id);
}
case NewHarnessField.agent:
+ // A machine that cannot run it says so (leadBlocked); the person
+ // chooses again, nothing moves on its own.
_selectEngine(option.id);
- if (placesLead) {
- _leadEngineChosen = true;
- if (leadMachine?.runs(_engine) == false) placeLead();
- }
case NewHarnessField.model:
_model = option.model;
_modelTouched = true;
@@ -4223,9 +4177,11 @@ class NewHarnessController extends ChangeNotifier {
);
}
if (isCloud) return _createCloud();
- // Whoever starts it, New Project never starts a Product Manager the
- // placement says cannot run.
- if (placesLead && leadBlocked != null) return _fail(leadBlocked!);
+ // Whoever starts it, New Project never starts a Product Manager on a
+ // machine the person did not choose, or one that cannot run it.
+ if (placesLead) {
+ if (leadBlocked case final why?) return _fail(why);
+ }
if (leadThroughSwarm) return _startInSwarm();
if (!checking) {
_syncGitProject();
@@ -4554,8 +4510,7 @@ class NewHarnessController extends ChangeNotifier {
/// A cloud harness: made by the cloud service on this machine (CLI
/// services/cloud.ts), which starts it at its maker; no folder, no install.
/// New Project's Product Manager the Swarm starts
- /// ([HarnessLaunchIntegration.startInSwarm]): on [leadSwarmMachine], or on
- /// the first machine that frees up.
+ /// ([HarnessLaunchIntegration.startInSwarm]) on [leadSwarmMachine].
Future<NewHarnessOutcome> _startInSwarm() async {
final start = integration?.startInSwarm;
if (start == null) {
@@ -4566,14 +4521,13 @@ class NewHarnessController extends ChangeNotifier {
if (leadBlocked case final why?) return _fail(why);
busy = true;
error = null;
- status = leadQueued
- ? 'Asking the Swarm to start the Product Manager…'
- : 'Asking ${leadMachine?.name ?? 'the machine'} to start the Product Manager…';
+ status =
+ 'Asking ${leadMachine?.name ?? 'the machine'} to start the Product Manager…';
notifyListeners();
try {
await start(
LeadSwarmStart(
- machineId: _swarmLeadMachine,
+ machineId: _swarmLeadMachine!,
engine: _engine,
repositoryUrl: leadRepositoryUrl,
title: _leadRepositoryName,
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
index 37b47f601..c5d9eafe9 100644
--- a/desktop/lib/super_tabs/launch.dart
+++ b/desktop/lib/super_tabs/launch.dart
@@ -18,7 +18,6 @@ import 'machine_icon.dart';
import 'machine_status.dart';
import 'model.dart';
import 'launch_prompt.dart';
-import 'identity.dart' show superTabPersonName;
/// Captures a conversation before opening New Harness. Its journal survives a
/// closed form or process; a recovered launch only reads the native receipt.
@@ -110,11 +109,10 @@ class SuperTabLaunch {
// A start already sent is repeated as it is: the server may
// have committed it and taken the machine's last slot, so
// its answer decides, not a fresh check.
- if (start.machineId case final machine?
- when saved['leadStartRequest'] == null) {
+ if (saved['leadStartRequest'] == null) {
await launch.recheckLeadMachine(
integration,
- machine,
+ start.machineId,
engine: start.engine,
);
}
@@ -302,10 +300,9 @@ class SuperTabLaunch {
}
/// The Swarm's machines, one row per computer, then the person's others,
- /// best first. A new project's Product Manager starts only on one of the
- /// person's own, connected to this Desktop: it runs on its owner's machine,
- /// in their account (Ken, 10-28; docs/swarms.md), so teammates' rows only
- /// say why not.
+ /// best first. A new project's Product Manager starts on any of them (Ken,
+ /// 10-29): a teammate's Mac runs it in its Harness Team account when that
+ /// takes it now, else itself, as its owner (backend leadStart.ts).
List<LeadMachine> leadMachinesOf(SuperTabSnapshot snapshot, {DateTime? now}) {
final at = (now ?? DateTime.now()).millisecondsSinceEpoch;
// A machine reports readiness and resources only once it has them.
@@ -320,61 +317,137 @@ class SuperTabLaunch {
// Its host says it can start a Product Manager (backend leadStart.ts).
final capable =
(observation['capabilities'] as List?)?.contains('leadStart') == true;
- // Another person's Mac runs one only in its Harness Team account.
- final team =
+ // Another person's Mac runs one in its Harness Team account when that
+ // takes it now, else itself; a Team account listed as its own machine
+ // only in itself.
+ final teamReading =
!own &&
(reading['hostMachineId'] != null ||
observation['sessionKind'] == 'team');
- final received = observation['receivedAt'];
- final online =
- received is num &&
- at - received < kSuperTabMachineOfflineAfter.inMilliseconds;
- final running = observation['runningHarnessIds'];
- final max = reading['maxAgents'];
- final checkouts = part(observation['readiness'])['checkouts'];
- final engineRefusals = leadEngineRefusals(
- offered: switch (reading['engines']) {
- final List engines => engines.whereType<String>().toSet(),
- _ => null,
- },
- readiness: {
- for (final raw
- in part(observation['readiness'])['engines'] as List? ?? const [])
- if (part(raw) case {'engine': final String engine} && final row)
- engine: (
- installed: row['installed'] as bool?,
- signedIn: row['signedIn'] as bool?,
- ),
- },
- usedPercents: {
- for (final raw in observation['quotas'] as List? ?? const [])
- if (part(raw) case {
- 'engine': final String engine,
- 'known': true,
- 'windows': final List windows,
- })
- engine: [
- for (final window in windows)
- if (part(window)['usedPercent'] case final num used) used,
- ],
- },
- // Read by servers with engine health (#2192); absent before.
- suspended: {
- for (final source in [pool, reading])
- if (source['suspendedEngines'] case final Map raw)
- for (final MapEntry(:key, :value) in raw.entries)
- if ((key, value) case (final String engine, final String why))
- engine: why,
- },
- );
- final device = part(observation['resources'])['deviceType'];
+ final teamRefusal = !teamReading
+ ? null
+ : switch (reading['teamWork']) {
+ {'allowed': false, 'reason': final String reason} => reason,
+ _ when !capable =>
+ 'Update Harness on $name to run a Product Manager there.',
+ _ => null,
+ };
+ bool fresh(Map<String, dynamic> observation) =>
+ switch (observation['receivedAt']) {
+ final num received =>
+ at - received < kSuperTabMachineOfflineAfter.inMilliseconds,
+ _ => false,
+ };
+ final team =
+ teamReading &&
+ teamRefusal == null &&
+ fresh(observation) &&
+ reading['paused'] != true;
+ final mac = part(pool['observation']);
+ // A Mac added as its person joined takes teammates' work only in its
+ // Team account (backend machines.ts teamAccountOnly).
+ final macTakes =
+ pool['teamAccountOnly'] != true &&
+ pool['hostMachineId'] == null &&
+ mac['sessionKind'] != 'team' &&
+ (mac['capabilities'] as List?)?.contains('leadStart') == true;
+ // On a teammate's machine the server decides, by engine, where it runs
+ // (backend leadStart.ts leadChoices), as the start itself does: Desktop
+ // shows that rather than working it out (security reviews 1 and 2 of
+ // #2228). A backend from before sends none.
+ final decided = <String, String>{}, refused = <String, String>{};
+ if (!own && pool['lead'] is Map) {
+ for (final MapEntry(:key, :value) in superTabMap(
+ pool['lead'],
+ ).entries) {
+ switch (value) {
+ case {'machineId': final String machine}:
+ decided[key] = machine;
+ case {'refused': final String why}:
+ // Its line adds its own full stop.
+ refused[key] = why.endsWith('.')
+ ? why.substring(0, why.length - 1)
+ : why;
+ }
+ }
+ }
+ final server = decided.isNotEmpty || refused.isNotEmpty;
+ final shownHost = [for (final engine in kLeadEngines) ?decided[engine]]
+ .firstOrNull;
+ // Where it would run: the server's machine for its first engine that
+ // runs; else the Mac itself when its Team account cannot.
+ final host = server
+ ? (shownHost == null
+ ? pool
+ : snapshot.machines
+ .where((m) => m['machineId'] == shownHost)
+ .firstOrNull ??
+ pool)
+ : teamReading && !team
+ ? pool
+ : reading;
+ final hostReading = part(host['observation']);
+ final online = fresh(hostReading);
+ final running = hostReading['runningHarnessIds'];
+ final max = host['maxAgents'];
+ final checkouts = part(hostReading['readiness'])['checkouts'];
+ final device = part(hostReading['resources'])['deviceType'];
+ // The engines it can run there, read where it would run.
+ final engineRefusals = server
+ ? {
+ for (final engine in kLeadEngines)
+ if (refused[engine] ?? (decided[engine] == null ? '' : null)
+ case final why?)
+ engine: why.isEmpty ? 'Not offered by this Swarm' : why,
+ }
+ : leadEngineRefusals(
+ offered: switch (host['engines']) {
+ final List engines => engines.whereType<String>().toSet(),
+ _ => null,
+ },
+ readiness: {
+ for (final raw
+ in part(hostReading['readiness'])['engines'] as List? ??
+ const [])
+ if (part(raw)
+ case {'engine': final String engine} && final row)
+ engine: (
+ installed: row['installed'] as bool?,
+ signedIn: row['signedIn'] as bool?,
+ ),
+ },
+ usedPercents: {
+ for (final raw in hostReading['quotas'] as List? ?? const [])
+ if (part(raw) case {
+ 'engine': final String engine,
+ 'known': true,
+ 'windows': final List windows,
+ })
+ engine: [
+ for (final window in windows)
+ if (part(window)['usedPercent'] case final num used)
+ used,
+ ],
+ },
+ // Read by servers with engine health (#2192); absent before.
+ suspended: {
+ for (final source in {pool, host})
+ if (source['suspendedEngines'] case final Map raw)
+ for (final MapEntry(:key, :value) in raw.entries)
+ if ((key, value) case (
+ final String engine,
+ final String why,
+ ))
+ engine: why,
+ },
+ );
return LeadMachine(
id: id,
name: name,
online: online,
// The server's count: it also holds pending starts and the Team
// account sharing a Mac. A backend without it: slots minus running.
- freeAgents: switch (reading['availableSlots']) {
+ freeAgents: switch (host['availableSlots']) {
final num slots => math.max(0, slots.toInt()),
_ => math.max(
0,
@@ -413,7 +486,13 @@ class SuperTabLaunch {
'laptopcomputer',
own: own,
native: own && connected,
- team: team,
+ team: server ? shownHost != null && shownHost != id : team,
+ teamEngines: server
+ ? {
+ for (final MapEntry(:key, :value) in decided.entries)
+ if (value != id) key,
+ }
+ : null,
engineRefusals: engineRefusals,
unavailable: snapshot.paused
? kLeadSwarmPaused
@@ -423,22 +502,19 @@ class SuperTabLaunch {
: capable
? null
: 'Not connected to this computer')
- : !team
- ? switch (snapshot.people
- .where((person) => person.id == pool['contributorId'])
- .firstOrNull) {
- final person? =>
- '${superTabPersonName(person.email)}’s personal account: '
- 'runs only ${superTabPersonName(person.email)}’s '
- 'projects. $_yoursNeed',
- null => '$name runs only its owner’s projects. $_yoursNeed',
- }
- : switch (reading['teamWork']) {
- {'allowed': false, 'reason': final String reason} => reason,
- _ when !capable =>
- 'Update Harness on $name to run a Product Manager there.',
- _ => null,
- },
+ // The server's reasons are each engine's (engineRefusals).
+ : server
+ ? null
+ : host['paused'] == true
+ ? 'Paused in this Swarm'
+ : team || macTakes
+ ? null
+ : teamRefusal ??
+ switch (pool['teamWork']) {
+ {'allowed': false, 'reason': final String reason} => reason,
+ _ =>
+ 'Update Harness on $name to run a Product Manager there.',
+ },
);
}
@@ -535,9 +611,8 @@ class SuperTabLaunch {
/// New Project's Product Manager started by the Swarm, not this Desktop
/// (backend leadStart.ts): creates the project, posts the task and files
/// to its chat, where such a Product Manager reads its request, and asks
- /// the Swarm to start it on [LeadSwarmStart.machineId], or on the first
- /// free machine. Each step keeps its receipt in the journal, so a retry
- /// repeats none of them.
+ /// the Swarm to start it on [LeadSwarmStart.machineId]. Each step keeps
+ /// its receipt in the journal, so a retry repeats none of them.
Future<void> startInSwarm(LeadSwarmStart start) async {
checkAccount();
saved['initialMessage'] = start.task;
@@ -1085,6 +1160,3 @@ class SuperTabLaunch {
checkAccount();
}
}
-
-/// Where a teammate's project's Product Manager may run instead.
-const _yoursNeed = 'Yours need your own computer or a Team account machine';
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 119b3e759..5a691c482 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -164,7 +164,6 @@ class NewHarnessFormState extends State<NewHarnessForm> {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
box.useDesktopChoices(widget.desktop);
- box.placeLead();
if (box.checking) _row = _Row.start;
_syncField();
// Restoring the successful agent can replace an unfocusable Terminal
@@ -2201,7 +2200,13 @@ class NewHarnessFormState extends State<NewHarnessForm> {
? null
: () => setState(() => _leadOpen = !_leadOpen),
// With no machine able to run it, the list says why for each.
- child: Text(box.leadNone ? 'See why' : 'Change'),
+ child: Text(
+ box.leadNone
+ ? 'See why'
+ : box.leadPicked
+ ? 'Change'
+ : 'Choose',
+ ),
),
),
),
@@ -2329,7 +2334,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
String? repository,
double order,
) {
- final chosen = machine.id == box.leadMachine?.id && !box.leadQueued;
+ final chosen = machine.id == box.leadMachine?.id;
final enabled = machine.startable && !box.locked;
final detail = leadMachineDetail(machine, repository);
return KeyedSubtree(
diff --git a/desktop/test/lead_placement_test.dart b/desktop/test/lead_placement_test.dart
index e258159b7..9009eb6cc 100644
--- a/desktop/test/lead_placement_test.dart
+++ b/desktop/test/lead_placement_test.dart
@@ -79,7 +79,6 @@ void main() {
'teammate',
'offline',
]);
- expect(bestLeadMachine(ranked, _repo)?.id, 'studio');
});
test('more free agents wins among otherwise equal machines', () {
@@ -105,20 +104,8 @@ void main() {
], _repo);
expect(ranked.map((m) => m.id), ['laptop', 'mine']);
expect(outside.startable, isTrue);
- expect(bestLeadMachine([outside], _repo)?.id, 'mine');
expect(leadMachineDetail(outside, _repo), 'Online · Not in this Swarm');
});
-
- test('no machine is best when none is online, free and allowed', () {
- expect(
- bestLeadMachine([
- _machine('offline', online: false),
- _machine('full', free: 0),
- _machine('teammate', unavailable: 'Not yours'),
- ], _repo),
- isNull,
- );
- });
});
group('leadMachineDetail', () {
@@ -176,36 +163,12 @@ void main() {
);
});
- group('bestLeadPlacement', () {
- test('never proposes Claude Code on a machine offering only Codex', () {
- // The rig ranks first (always on, more room), but cannot run Claude.
- final rig = _machine('rig', free: 14, engineRefusals: _claudeOff);
- final laptop = _machine('laptop', free: 2, maySleep: true);
- final placed = bestLeadPlacement([rig, laptop], _repo, engine: 'claude');
- expect((placed?.machine.id, placed?.engine), ('laptop', 'claude'));
- });
-
- test('switches to an engine the best machine runs when none runs the '
- 'chosen one', () {
- final rig = _machine('rig', engineRefusals: _claudeOff);
- final placed = bestLeadPlacement([rig], _repo, engine: 'claude');
- expect((placed?.machine.id, placed?.engine), ('rig', 'codex'));
- });
-
- test('an engine the person chose stays: no machine runs it, no place', () {
- final rig = _machine('rig', engineRefusals: _claudeOff);
- expect(
- bestLeadPlacement([rig], _repo, engine: 'claude', engineChosen: true),
- isNull,
- );
- });
-
- test('your own machine with another engine before a teammate’s with the '
- 'chosen one', () {
+ group('engines', () {
+ test('a machine offering only Codex still starts a Product Manager', () {
final rig = _machine('rig', engineRefusals: _claudeOff);
- final theirs = _machine('team', own: false, free: 30);
- final placed = bestLeadPlacement([theirs, rig], _repo, engine: 'claude');
- expect((placed?.machine.id, placed?.engine), ('rig', 'codex'));
+ expect(rig.runs('claude'), isFalse);
+ expect(rig.leadEngines, ['codex']);
+ expect(rig.startable, isTrue);
});
test('a machine that runs no Product Manager engine is not startable', () {
@@ -218,8 +181,7 @@ void main() {
);
expect(rig.startable, isFalse);
expect(rig.runs('codex'), isFalse);
- expect(bestLeadPlacement([rig], _repo, engine: 'claude'), isNull);
- expect(bestLeadMachine([rig], _repo), isNull);
+ expect(rig.leadEngines, isEmpty);
});
});
}
diff --git a/desktop/test/super_tab_launch_retry_test.dart b/desktop/test/super_tab_launch_retry_test.dart
index 5f4304433..2485d584c 100644
--- a/desktop/test/super_tab_launch_retry_test.dart
+++ b/desktop/test/super_tab_launch_retry_test.dart
@@ -117,6 +117,19 @@ void main() {
LostReplyConnection(store, 'message.send'),
);
configure(f);
+ (f.connection.server.state['machines'] as List).add({
+ 'machineId': 'far',
+ 'name': 'Office Mini',
+ 'contributorId': 'owner',
+ 'maxAgents': 8,
+ 'availableSlots': 3,
+ 'paused': false,
+ 'observation': {
+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,
+ 'runningHarnessIds': <String>[],
+ 'capabilities': ['leadStart'],
+ },
+ });
SuperTabLaunch.uploadForTest = f.connection.server.upload;
addTearDown(() => SuperTabLaunch.uploadForTest = null);
final files = HarnessAttachments()
@@ -124,6 +137,7 @@ void main() {
HarnessAttachment('plan.md', Uint8List.fromList([1, 2, 3])),
]);
final box = await f.box(newProject: true, attachments: files);
+ box.chooseLeadMachine('far');
expect(await box.create(), NewHarnessOutcome.failed);
final recovered = await box.create();
final c = f.connection as LostReplyConnection;
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 4aae65492..a2b0dc2eb 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -434,6 +434,9 @@ class SuperTabLaunchFixture {
bool newProject = false,
String? task = 'Discuss the architecture.',
String? harnessId,
+ // The machine its person chooses for New Project's Product Manager, when
+ // the list can start it there.
+ String? lead = 'm',
}) async {
final integration = await SuperTabLaunch.open(
app,
@@ -453,6 +456,10 @@ class SuperTabLaunchFixture {
);
addTearDown(box.dispose);
await Future<void>.delayed(Duration.zero);
+ if (integration.leadMachines?.any((m) => m.id == lead && m.startable) ??
+ false) {
+ box.chooseLeadMachine(lead!);
+ }
return box;
}
}
@@ -704,12 +711,11 @@ void main() {
'Update Harness on 2x 4090 Rig to run a Product Manager there.',
);
expect(machines[3].online, isFalse);
- expect(bestLeadMachine(machines, null)?.id, 'm');
},
);
test(
- 'with its only machine full, New Project queues, and needs a remote',
+ 'with its only machine full, New Project starts nothing and says so',
() async {
final f = SuperTabLaunchFixture();
f.connection.server.state['machines'] = [
@@ -728,13 +734,13 @@ void main() {
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
final box = await f.box(newProject: true);
expect(box.integration!.leadMachines!.single.startable, isFalse);
- expect(box.leadQueued, isTrue);
+ // The full machine cannot be chosen, and nothing is chosen for them:
+ // New Project says no machine can run it now (its list says why).
+ expect(box.leadNone, isTrue);
expect(await box.create(), NewHarnessOutcome.failed);
- // The Swarm clones the repo wherever it starts the PM.
- expect(
- box.error,
- 'Choose a repo with a remote, so the Swarm can clone it for the Product Manager.',
- );
+ expect(box.error, 'No machine can run the Product Manager now.');
+ box.chooseLeadMachine('m');
+ expect(box.leadPicked, isFalse);
expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
expect(f.connection.server.posts, isEmpty);
},
@@ -821,11 +827,70 @@ void main() {
expect(diego.team, isTrue);
});
+ for (final (what, rows) in [
+ ('has no Team account', [machineRow('rig', '2x 4090 Rig', lead: true)]),
+ (
+ 'has an offline Team account',
+ [
+ machineRow('rig', '2x 4090 Rig', lead: true),
+ {
+ ...machineRow(
+ 'rig-team',
+ '2x 4090 Rig',
+ host: 'rig',
+ kind: 'team',
+ available: 1,
+ lead: true,
+ ),
+ 'observation': {
+ 'receivedAt': 0,
+ 'sessionKind': 'team',
+ 'runningHarnessIds': <String>[],
+ 'capabilities': ['leadStart'],
+ },
+ },
+ ],
+ ),
+ (
+ 'has a Team account that cannot take it now',
+ [
+ machineRow('rig', '2x 4090 Rig', lead: true),
+ machineRow(
+ 'rig-team',
+ '2x 4090 Rig',
+ host: 'rig',
+ kind: 'team',
+ available: 1,
+ lead: true,
+ teamWork: {
+ 'allowed': false,
+ 'code': 'PRIVACY_CHECK_FAILED',
+ 'reason': 'The Harness Team account on 2x 4090 Rig is not private (sharing), so it runs only its owner’s projects.',
+ },
+ ),
+ ],
+ ),
+ ]) {
+ test('a teammate’s Mac that $what takes the PM itself', () async {
+ final f = SuperTabLaunchFixture();
+ addDiego(f);
+ f.connection.server.state['machines'] = rows;
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final box = await f.box(newProject: true);
+ final rig = box.integration!.leadMachines!.where((m) => !m.own).single;
+ expect(rig.unavailable, isNull);
+ expect(rig.startable, isTrue);
+ // The Mac's own room, not its Team account's.
+ expect(rig.freeAgents, 4);
+ expect((rig.team, rig.native), (false, false));
+ });
+ }
+
for (final (what, rows, reason) in [
(
- 'has no Team account',
- [machineRow('rig', '2x 4090 Rig', lead: true)],
- 'diego’s personal account: runs only diego’s projects. Yours need your own computer or a Team account machine',
+ 'has no Team account and runs an older Harness',
+ [machineRow('rig', '2x 4090 Rig')],
+ 'Update Harness on 2x 4090 Rig to run a Product Manager there.',
),
(
'fails its Team account’s privacy check',
@@ -846,6 +911,32 @@ void main() {
],
'The Harness Team account on Diego MacBook is not private (sharing), so it runs only its owner’s projects.',
),
+ (
+ 'was added as its person joined and has no Team account',
+ [
+ {
+ ...machineRow(
+ 'rig',
+ '2x 4090 Rig',
+ lead: true,
+ teamWork: {
+ 'allowed': false,
+ 'code': 'TEAM_ACCOUNT_REQUIRED',
+ 'reason': '2x 4090 Rig has no Harness Team account yet, so it runs only its owner’s projects.',
+ },
+ ),
+ 'teamAccountOnly': true,
+ },
+ ],
+ '2x 4090 Rig has no Harness Team account yet, so it runs only its owner’s projects.',
+ ),
+ (
+ 'is paused',
+ [
+ {...machineRow('rig', '2x 4090 Rig', lead: true), 'paused': true},
+ ],
+ 'Paused in this Swarm',
+ ),
(
'runs an older Harness',
[
@@ -949,6 +1040,112 @@ void main() {
},
};
+ // Security reviews 1 and 2 of #2228: the server decides where a teammate's
+ // Mac runs the PM, by engine (backend leadStart.ts leadChoices), and New
+ // Project shows that rather than working it out from the readings.
+ group('the server’s decision of where the PM runs', () {
+ // Diego's Mac runs Claude Code; its Team account, fresh and private,
+ // offers only Codex.
+ List<Map<String, dynamic>> rows(Map<String, dynamic> lead) => [
+ {
+ ...offering(machineRow('diego-mac', 'Diego MacBook', lead: true), [
+ 'claude',
+ ]),
+ 'lead': lead,
+ },
+ offering(
+ machineRow(
+ 'diego-team',
+ 'Diego MacBook',
+ host: 'diego-mac',
+ kind: 'team',
+ lead: true,
+ ),
+ ['codex'],
+ ),
+ ];
+
+ test('a busy Team account: Codex is refused and Claude Code runs on the '
+ 'Mac itself, so New Project starts it there', () async {
+ final f = SuperTabLaunchFixture();
+ addDiego(f);
+ knownRepo(f);
+ f.connection.server.state['machines'] = rows({
+ 'claude': {'machineId': 'diego-mac'},
+ 'codex': {'refused': 'Codex isn’t offered on Diego MacBook.'},
+ });
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final box = await f.box(newProject: true, engine: 'codex', lead: null);
+ final mac = box.integration!.leadMachines!.singleWhere(
+ (m) => m.id == 'diego-mac',
+ );
+ expect(mac.engineRefusals, {
+ 'codex': 'Codex isn’t offered on Diego MacBook',
+ });
+ expect((mac.startable, mac.inTeam('claude')), (true, false));
+ box.chooseLeadMachine('diego-mac');
+ // The engine it can run there, on the Mac itself, as the server said.
+ expect(box.engine, 'claude');
+ expect(box.leadBlocked, isNull);
+ expect(box.leadLine, startsWith('Product Manager on Diego MacBook · '));
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(
+ commandsOf(f, 'lead.start').single,
+ containsPair('engine', 'claude'),
+ );
+ expect(
+ commandsOf(f, 'lead.start').single,
+ containsPair('machineId', 'diego-mac'),
+ );
+ });
+
+ test('each engine runs where the server says: Codex in the Team account, '
+ 'Claude Code on the Mac whose account signed it out', () async {
+ final f = SuperTabLaunchFixture();
+ addDiego(f);
+ knownRepo(f);
+ f.connection.server.state['machines'] = rows({
+ 'claude': {'machineId': 'diego-mac'},
+ 'codex': {'machineId': 'diego-team'},
+ });
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final box = await f.box(newProject: true, engine: 'codex', lead: null);
+ box.chooseLeadMachine('diego-mac');
+ expect(box.engine, 'codex');
+ expect(
+ box.leadLine,
+ startsWith('Product Manager on Diego MacBook’s Team account · Codex'),
+ );
+ box.focusField(NewHarnessField.agent);
+ box.accept(box.options.where((o) => o.id == 'claude').single);
+ expect(
+ box.leadLine,
+ startsWith('Product Manager on Diego MacBook · Claude Code'),
+ );
+ expect(box.leadBlocked, isNull);
+ });
+
+ test('with every engine refused, the Mac cannot be chosen and says why '
+ 'once', () async {
+ final f = SuperTabLaunchFixture();
+ addDiego(f);
+ f.connection.server.state['machines'] = rows({
+ 'claude': {'refused': 'New work is paused on this machine.'},
+ 'codex': {'refused': 'New work is paused on this machine.'},
+ });
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final box = await f.box(newProject: true, lead: null);
+ final mac = box.integration!.leadMachines!.singleWhere(
+ (m) => m.id == 'diego-mac',
+ );
+ expect(mac.startable, isFalse);
+ expect(
+ leadMachineDetail(mac, null),
+ 'Can’t run a Product Manager: New work is paused on this machine',
+ );
+ });
+ });
+
test('each machine says which Product Manager engines it cannot run, and '
'why', () async {
final f = SuperTabLaunchFixture();
@@ -1007,18 +1204,20 @@ void main() {
});
test(
- 'a machine offering only Codex is never proposed with Claude Code',
+ 'choosing a machine that offers only Codex switches the PM to Codex',
() async {
- Future<NewHarnessController> place(
+ Future<NewHarnessController> choose(
List<Map<String, dynamic>> rows,
+ String machine,
) async {
final f = SuperTabLaunchFixture();
noLocalEngines(f);
knownRepo(f);
f.connection.server.state['machines'] = rows;
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
- final box = await f.box(newProject: true, engine: 'claude');
- box.placeLead();
+ final box = await f.box(newProject: true, engine: 'claude', lead: null);
+ expect(box.leadMachine, isNull);
+ box.chooseLeadMachine(machine);
return box;
}
@@ -1026,18 +1225,16 @@ void main() {
machineRow('rig', '2x 4090 Rig', contributor: 'owner', lead: true),
['codex'],
);
- // Alone, the rig takes the PM with Codex.
- var box = await place([rig]);
+ final studio = offering(
+ machineRow('m', 'Mac Studio', contributor: 'owner'),
+ ['claude', 'codex'],
+ );
+ // The rig takes the PM with Codex, the engine it runs.
+ var box = await choose([rig, studio], 'rig');
expect((box.leadMachine?.id, box.engine), ('rig', 'codex'));
expect(box.leadBlocked, isNull);
- // With your Mac Studio running Claude Code, Claude Code stays.
- box = await place([
- rig,
- offering(machineRow('m', 'Mac Studio', contributor: 'owner'), [
- 'claude',
- 'codex',
- ]),
- ]);
+ // The Mac Studio runs Claude Code: Claude Code stays.
+ box = await choose([rig, studio], 'm');
expect((box.leadMachine?.id, box.engine), ('m', 'claude'));
expect(box.leadBlocked, isNull);
},
@@ -1058,15 +1255,13 @@ void main() {
];
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
final box = await f.box(newProject: true, engine: 'claude');
- box.placeLead();
- expect(box.leadQueued, isFalse);
expect(box.leadNone, isTrue);
expect(box.leadBlocked, 'No machine can run the Product Manager now.');
expect(await box.create(), NewHarnessOutcome.failed);
});
- test('an engine chosen under Advanced moves the PM to a machine that runs '
- 'it, or says why none does', () async {
+ test('an engine chosen under Advanced that the chosen machine cannot run '
+ 'says why, and the machine stays', () async {
final f = SuperTabLaunchFixture();
noLocalEngines(f);
f.connection.server.state['machines'] = [
@@ -1078,11 +1273,12 @@ void main() {
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
knownRepo(f);
final box = await f.box(newProject: true, engine: 'codex');
- box.placeLead();
+ box.chooseLeadMachine('rig');
expect(box.leadMachine?.id, 'rig');
box.focusField(NewHarnessField.agent);
box.accept(box.options.where((o) => o.id == 'claude').single);
expect(box.engine, 'claude');
+ expect(box.leadMachine?.id, 'rig');
expect(
box.leadBlocked,
'2x 4090 Rig can’t run Claude Code: Claude Code isn’t offered here. '
@@ -1127,7 +1323,7 @@ void main() {
];
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
final box = await f.box(newProject: true, engine: 'codex');
- box.placeLead();
+ box.chooseLeadMachine('rig');
expect((box.leadMachine?.id, box.leadBlocked), ('rig', null));
f.connection.server.state['machines'] = [rig(engines, readiness)];
expect(await box.create(), NewHarnessOutcome.failed);
@@ -1150,7 +1346,7 @@ void main() {
f.connection.server.state['machines'] = [studio(const [])];
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
final box = await f.box(newProject: true, engine: 'codex');
- box.placeLead();
+ box.chooseLeadMachine('m');
expect((box.leadMachine?.id, box.engine), ('m', 'codex'));
expect(box.leadMachine?.native, isTrue);
expect(box.leadThroughSwarm, isFalse);
@@ -1216,21 +1412,27 @@ void main() {
},
);
- test('with no machine free New Project queues the PM', () async {
- final f = SuperTabLaunchFixture();
- knownRepo(f);
- f.connection.server.state['machines'] = [
- machineRow('m', 'Mac Studio', contributor: 'owner', available: 0),
- ];
- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
- final box = await f.box(newProject: true);
- expect(box.leadQueued, isTrue);
- expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
- final start = commandsOf(f, 'lead.start').single;
- expect(start['machineId'], isNull);
- expect(start.containsKey('machineId'), isTrue);
- expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
- });
+ test(
+ 'New Project starts the PM only once its person chose the machine',
+ () async {
+ final f = SuperTabLaunchFixture();
+ knownRepo(f);
+ f.connection.server.state['machines'] = [
+ machineRow('m', 'Mac Studio', contributor: 'owner', available: 3),
+ ];
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final box = await f.box(newProject: true, lead: null);
+ expect(box.leadPicked, isFalse);
+ expect(box.leadMachine, isNull);
+ expect(
+ box.leadBlocked,
+ 'Choose the machine the Product Manager runs on.',
+ );
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(f.connection.server.posts, isEmpty);
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ },
+ );
test(
'a refused Swarm start says why, and a retry posts the task once',
@@ -1278,6 +1480,8 @@ void main() {
knownRepo(f);
f.connection.server.state['machines'] = [
machineRow('m', 'Mac Studio', contributor: 'owner', available: 0),
+ // Yours, but this Desktop has no connection to it: the Swarm starts it.
+ machineRow('far', 'Office Mini', contributor: 'owner', lead: true),
];
SuperTabLaunch.uploadForTest = f.connection.server.upload;
addTearDown(() => SuperTabLaunch.uploadForTest = null);
@@ -1286,7 +1490,7 @@ void main() {
..add([
HarnessAttachment('plan.md', Uint8List.fromList([1, 2, 3])),
]);
- final box = await f.box(newProject: true, attachments: files);
+ final box = await f.box(newProject: true, attachments: files, lead: 'far');
expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
final created = f.app.superTabs.peek(tabId)!.snapshot!.projects.last;
expect(
diff --git a/desktop/test/swarm_creation_form_test.dart b/desktop/test/swarm_creation_form_test.dart
index ce1e94352..04e0426e6 100644
--- a/desktop/test/swarm_creation_form_test.dart
+++ b/desktop/test/swarm_creation_form_test.dart
@@ -58,6 +58,9 @@ void main() {
List<LeadMachine>? leadMachines,
LeadModelList? leadModels,
void Function(SuperTabLaunchFixture f)? setup,
+ // The machine its person chooses for the Product Manager, when the list
+ // can start it there.
+ String? lead = 'm',
}) async {
final oldBrightness = grid.AppTheme.brightness.value;
grid.AppTheme.brightness.value = brightness;
@@ -118,6 +121,10 @@ void main() {
),
);
await tester.pumpAndSettle();
+ if (leadMachines?.any((m) => m.id == lead && m.startable) ?? false) {
+ box.chooseLeadMachine(lead!);
+ await tester.pumpAndSettle();
+ }
return (box, boundary);
}
@@ -477,19 +484,21 @@ void main() {
);
}
- testWidgets('The Swarm places the Product Manager on the best machine', (
+ testWidgets('Nothing moves the Product Manager to a machine by itself', (
tester,
) async {
final (box, _) = await mount(
tester,
setup: addLaptop,
leadMachines: rankLeadMachines([laptop, rig], null),
+ lead: null,
);
- expect(box.machineId, 'laptop');
+ expect(box.machineId, 'm');
+ expect(box.leadMachine, isNull);
expect(
find.descendant(
of: leadLine,
- matching: find.textContaining('Product Manager on Ken MacBook'),
+ matching: find.text('Choose the machine the Product Manager runs on.'),
),
findsOneWidget,
);
@@ -549,41 +558,64 @@ void main() {
for (final brightness in Brightness.values) {
testWidgets(
- 'With no machine free New Project queues the PM in ${brightness.name}',
+ 'New Project chooses no machine for the PM in ${brightness.name}',
(tester) async {
final (box, boundary) = await mount(
tester,
brightness: brightness,
- leadMachines: [studioFull, rig],
+ leadMachines: [studio, rig],
setup: agentIn,
+ lead: null,
);
- expect(box.leadQueued, isTrue);
- expect(box.leadThroughSwarm, isTrue);
+ expect(box.leadPicked, isFalse);
expect(
- find.text(
- 'All Swarm machines are busy. The project starts on the first one that frees up.',
- ),
+ find.text('Choose the machine the Product Manager runs on.'),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: change, matching: find.text('Choose')),
findsOneWidget,
);
box.setTask('Plan the launch');
await tester.pump();
- expect(tester.widget<FilledButton>(_start).onPressed, isNotNull);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
await shot(
tester,
boundary,
- 'new-project-lead-${brightness.name}-waiting',
+ 'new-project-lead-${brightness.name}-unchosen',
);
+ await tester.tap(change);
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-lead-machine-m')),
+ );
+ await tester.pumpAndSettle();
+ expect(box.leadPicked, isTrue);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNotNull);
await unmount(tester);
},
);
}
- testWidgets('A queued PM needs a repo the Swarm can clone', (tester) async {
- final (box, _) = await mount(tester, leadMachines: [studioFull, rig]);
- expect(
- box.leadBlocked,
- 'Choose a repo with a remote, so the Swarm can clone it for the Product Manager.',
+ testWidgets('A full machine cannot be chosen for the PM', (tester) async {
+ final (box, _) = await mount(
+ tester,
+ setup: addLaptop,
+ leadMachines: [studioFull, laptop, rig],
+ lead: null,
);
+ expect(box.leadPicked, isFalse);
+ expect(box.leadBlocked, 'Choose the machine the Product Manager runs on.');
+ box.chooseLeadMachine('m');
+ expect(box.leadPicked, isFalse);
+ expect(box.leadBlocked, 'Choose the machine the Product Manager runs on.');
+ await tester.pump();
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
+ // With every machine full or ruled out, it says none can run it now.
+ await unmount(tester);
+ final (none, _) = await mount(tester, leadMachines: [studioFull, rig]);
+ expect(none.leadNone, isTrue);
+ expect(none.leadBlocked, 'No machine can run the Product Manager now.');
expect(tester.widget<FilledButton>(_start).onPressed, isNull);
await unmount(tester);
});
@@ -597,9 +629,9 @@ void main() {
brightness: brightness,
leadMachines: [studioFull, diegoTeam],
setup: agentIn,
+ lead: 'diego-mac',
);
expect(box.leadThroughSwarm, isTrue);
- expect(box.leadQueued, isFalse);
expect(box.leadSwarmMachine, 'diego-mac');
// The repo stays the one chosen on your machine; Diego's Mac clones it.
expect(box.machineId, 'm');
@@ -945,8 +977,7 @@ void main() {
freeAgents: 20,
own: false,
unavailable:
- 'ken15’s personal account: runs only ken15’s projects. Yours '
- 'need your own computer or a Team account machine',
+ 'Update Harness on Mac Studio to run a Product Manager there.',
);
final (box, boundary) = await mount(
tester,
@@ -1037,6 +1068,7 @@ void main() {
textScale: 2,
leadMachines: [studioFull, diegoTeam],
setup: agentIn,
+ lead: 'diego-mac',
);
expect(find.text('Clones lamp-os there first'), findsOneWidget);
expect(tester.takeException(), isNull);
diff --git a/desktop/test/swarm_launch_recovery_test.dart b/desktop/test/swarm_launch_recovery_test.dart
index bf7de0fe2..a349566fa 100644
--- a/desktop/test/swarm_launch_recovery_test.dart
+++ b/desktop/test/swarm_launch_recovery_test.dart
@@ -113,6 +113,8 @@ void main() {
final next = await reopen(f, machineId: 'm');
expect(next.checking, isFalse);
expect(next.integration!.creationId, isNot(saved['creationId']));
+ // A new project: its person chooses the Product Manager's machine.
+ next.chooseLeadMachine('m');
expect(
await next.create(),
NewHarnessOutcome.created,
diff --git a/docs/swarms.md b/docs/swarms.md
index 9f8caa807..1a4dba800 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -66,6 +66,28 @@ contributed machine, plus every machine an agent of the Swarm already runs on
available, a person adds it to the Swarm under Machines; the host then clones
the project there.
+A new project's Product Manager starts on any machine of the Swarm (Ken, 2026-10-29). On another person's Mac it runs in
+that Mac's Harness Team account when the account can take it now, and otherwise on the Mac itself, in its owner's account,
+unless the Mac was added to the Swarm as its person joined: such a Mac takes it only in its Team account.
+
+Who can start it, where, and who then reaches it:
+
+- **Who starts it**: only the project's owner, a person (not an agent), with `lead.start`. They always name the machine
+ (only they know which one stays on); with none named the server refuses (`MACHINE_REQUIRED`), and nothing places it on
+ another machine. New Project chooses none for them.
+- **Where**: a machine on the Swarm's Machines list whose contribution is still valid, not paused or offline, with a free
+ agent slot, an engine it runs, and a Harness that starts Product Managers. New Project lists only these as choosable
+ and greys out the rest with the reason.
+- **Whose account**: on the owner's own machine, theirs. On a teammate's Mac, its Harness Team account when that account
+ admits this Product Manager with its engine now: privacy check passed, the engine offered, signed in and not suspended
+ there, a free slot, its host starts Product Managers, and no other project's work. Otherwise the Mac itself, in its
+ owner's account: **that owner can read whatever the Product Manager reads and writes on their Mac** (the trust change Ken
+ chose, 10-29). The server makes this choice for each engine (`leadChoices` in `leadStart.ts`), and New Project shows the
+ choice the start will make.
+- **Who watches it**: the project's members watch its terminal live, whichever account it runs in (the Mac's owner does
+ not when it runs in a Team account). Typing in it: nobody in a Team account; on a teammate's Mac itself, only that
+ Mac's owner, and only when they may read the project. A private project they are not in shows them nothing.
+
A Builder starts in a new worktree of the project's checkout on that machine.
The host clones a project once and reuses the checkout, so it is not kept up to
date. A start that names no `branchRef` therefore bases its worktree on the
@@ -198,7 +220,7 @@ Buddies are on in every Swarm; there is no setting. They replaced Chat with PM (
it sends (Ken, 2026-10-28), and, as with any session, so does the owner of the machine running it. The product
manager puts nothing there it would not say in the project chat.
- Each person may add one Buddy per project. They choose the project, one of their own machines in the Swarm's Machines
- list, and Claude Code (a Codex Buddy is refused for now; see below). Like a Product Manager, a Buddy runs only on its owner's own machine, in their own
+ list, and Claude Code (a Codex Buddy is refused for now; see below). A Buddy runs only on its owner's own machine, in their own
account: never on a machine shared with them, and never in a Harness Team account. A Buddy can't be added on a
Windows machine yet: Harness can't yet tell a Buddy's window from another agent's there. As a backstop, while a Buddy
runs on a Windows computer, agents there may not send to, start, tell or close other sessions, or speak as a named