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.

feat(backend): a person leaving the Swarm takes their machines out through the machine removal (#1671)

0xken154f6abd1fe285
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 2cd4cf19f..bcc531017 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -910,7 +910,8 @@ describe('Super Tabs on a real Mongo replica set', () => {
expect((await store.read(owner, tab)).state.agents[0]).toMatchObject({ contributorId: host.sub, machineOwnerId: host.sub, harnessId: 'pool-builder' })
await run(tab, { type: 'member.remove', userId: host.sub })
expect(await store.hostPools(host, 'pool-host')).toEqual([])
- await expect(store.observeMachine(host, tab, 'pool-host', observation)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ // The machine stays listed while its host cleans up, but its owner left: a reading is refused as theirs no longer.
+ await expect(store.observeMachine(host, tab, 'pool-host', observation)).rejects.toMatchObject({ code: 'FORBIDDEN' })
await expect(store.start(host, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })
})
@@ -1830,7 +1831,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
expect((await store.routeDecision(owner, tab, routeDecisionId)).outcome).toBe('failed')
})
- it('releases every queued route hold when its machine is removed', async () => {
+ it.each(['its owner removes it', 'its owner leaves the Swarm'] as const)('releases every queued route hold when its machine leaves because %s', async how => {
// The Lead runs elsewhere: a machine that hosts a project's Lead cannot leave the Swarm.
const tab = (await store.create(owner, randomUUID(), 'Pilot')).id
const leadMachineId = `lead-${randomUUID()}`
@@ -1849,7 +1850,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
const starts = [await routedStart(tab, lead), await routedStart(tab, lead)]
for (const { routeDecisionId } of starts) expect((await store.routeDecision(owner, tab, routeDecisionId)).outcome).toBeNull()
- await run(tab, { type: 'machine.remove', machineId: 'test-host' }, host)
+ await run(tab, how === 'its owner removes it' ? { type: 'machine.remove', machineId: 'test-host' } : { type: 'member.remove', userId: host.sub }, host)
const state = (await store.read(owner, tab)).state
for (const { routeDecisionId, startId } of starts) {
@@ -2577,6 +2578,20 @@ describe('machine removal', () => {
} finally { await db.superTab.deleteMany({ where: { id: { in: newer } } }) }
})
+ it('cleans up the machines of a person who leaves the Swarm, the same way as removing one', async () => {
+ const tab = await contributed()
+ const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Worker', configuration: config, lead: false }, host)).result.agentId as string
+ await run(tab, { type: 'member.remove', userId: host.sub }, host)
+ const [row] = await cleanups(tab)
+ expect(row).toEqual({ tabId: tab, cleanup: { machineId: 'test-host', removalId: expect.any(String) } })
+ expect((await store.hostTabs(host, 'test-host')).filter(r => r.tabId === tab && r.agent?.id === worker && 'closeSession' in r)).toHaveLength(1)
+ expect((await store.read(owner, tab)).state.machines!.map(m => m.removal?.state)).toEqual(['cleaning'])
+ expect((await cleaned(tab, (row as { cleanup: { removalId: string } }).cleanup.removalId)).statusCode).toBe(200)
+ expect(await cleanups(tab)).toEqual([])
+ expect((await store.read(owner, tab)).state.machines).toEqual([])
+ })
+
it('drops the machine\'s records after 24 hours without an acknowledgement, and still lists the cleanup to its host', async () => {
const tab = await contributed()
const removalId = (await run(tab, { type: 'machine.remove', machineId: 'test-host' }, host)).result.removalId as string
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 1f4c15568..e8de2d69e 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1656,6 +1656,39 @@ describe('machine.remove', () => {
text: 'Rule removed: Only host. Its only machine, Studio, left the Swarm.' })])
})
+ it.each(['leaves', 'is removed'] as const)('puts the machines of a person who %s through the same removal', how => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group()
+ f.state.agents.find(a => a.id === lead)!.machineId = 'elsewhere'
+ f.invite()
+ contribute(f, 'peer')
+ const worker = f.add('worker', 'peer', group), owners = f.add('owners', 'owner')
+ f.run({ type: 'work.assign', conversationId: group, agentId: worker })
+ f.state.rules = [{ id: 'both', projectId: 'lead', rule: { kind: 'machines', machineIds: ['host', 'elsewhere'] }, text: 'Only these two.',
+ askedBy: 'owner', askedIn: null, addedBy: 'person:owner', createdAt: '' }]
+ const effects = f.run({ type: 'member.remove', userId: 'peer' }, how === 'leaves' ? peer : owner)
+ const pool = f.state.machines!.find(m => m.machineId === 'host')!
+ expect([pool.removal?.state, pool.paused]).toEqual(['cleaning', true])
+ expect(f.state.agents.map(a => a.id)).toEqual([lead])
+ expect(f.state.agents.some(a => a.id === owners)).toBe(false)
+ expect(f.state.conversations.find(c => c.id === group)!.assignment!.status).toBe('reconciling')
+ expect(f.state.rules!.map(r => r.rule)).toEqual([{ kind: 'machines', machineIds: ['elsewhere'] }])
+ expect(effects.messages.map(m => [m.conversationId, m.text])).toEqual(expect.arrayContaining([
+ ['lead', 'Rule changed: Studio left the Swarm, so "Only these two." now allows only elsewhere.'],
+ [group, expect.stringContaining('Its task "Offline editing" needs to be assigned again or closed.')]]))
+ expect(new Set(effects.messages.map(m => m.id)).size).toBe(effects.messages.length)
+ f.run({ type: 'machine.cleaned', machineId: 'host', removalId: pool.removal!.id }, peer)
+ expect(f.state.machines).toEqual([])
+ })
+
+ it('refuses a person\'s leaving while their machine runs a Product Manager, whoever contributed that agent', () => {
+ const f = fixture()
+ f.invite()
+ contribute(f, 'peer')
+ f.add('lead', 'owner', 'lead', true)
+ expect(() => f.run({ type: 'member.remove', userId: 'peer' }, peer)).toThrow(expect.objectContaining({ code: 'LEAD_PROTECTED' }))
+ expect(f.state.machines!.map(m => m.removal)).toEqual([undefined])
+ })
+
it('previews what removal does for the machine owner only: its agents and their tasks, sole-source projects, and a Product Manager that blocks it', () => {
const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group(), worker = f.add('worker', 'owner', group)
contribute(f)
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 12234632e..52dd62419 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,4 +1,4 @@
-import { admitMachineStart, expireRemovals, machineContribution, ownedMachine } from './machines.js'
+import { admitMachineStart, expireRemovals, machineContribution, ownedMachine, type ContributedMachine } from './machines.js'
import { assignAgentDisplayNames } from './agentNames.js'
import { z } from 'zod'
import {
@@ -446,6 +446,55 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
}
+ /** Takes a machine out of the Swarm with every agent on it (machine.remove, or its owner leaving): each agent is removed
+ * like one agent, its pending starts fail, routing rules lose it, and a contributed machine stays paused and cleaning
+ * until its host deletes the Swarm's folders there (spec 2026-10-23-remove-machine.md). */
+ const removeMachine = (machineId: string, pool: ContributedMachine | undefined, members: Agent[], how: (machine: string) => string) => {
+ const pending = state.starts?.filter(s => s.request.machineId === machineId && !s.harnessId && !s.error) ?? []
+ // A launch already under way would arrive with nowhere to go; it finishes in moments.
+ if (pending.some(s => s.dispatched)) fail('STARTS_PENDING', 'An agent is starting on this machine. Try again in a moment.')
+ for (const start of pending) {
+ start.error = 'Its machine was removed from the Swarm.'
+ effects.messages.push({ id: stableId(operationId, 'start', start.id), conversationId: start.request.conversationId, author: sender,
+ text: `${start.request.name} will not start: its machine was removed from the Swarm.`, replyTo: null, recipients: [], source: SYSTEM_ROW })
+ }
+ const removed = new Set(members.map(a => a.id))
+ const affected = state.conversations.filter(group => group.agentIds.some(a => removed.has(a))
+ || (group.leadId && removed.has(group.leadId)) || (group.assignment && removed.has(group.assignment.agentId)))
+ .map(group => ({ group, names: members.filter(a => group.agentIds.includes(a.id) || group.leadId === a.id || group.assignment?.agentId === a.id)
+ .map(a => a.displayName ?? a.name), task: !!group.assignment && removed.has(group.assignment.agentId) && activeWork(group) }))
+ for (const target of members) removeAgent(target)
+ if (pool) {
+ // Paused, so routing in clients that do not know removals stops offering it too.
+ pool.removal = { id: operationId, state: 'cleaning', requestedAt: new Date(context.now).toISOString() }
+ pool.paused = true
+ }
+ // Its capacity left with it: no slot there is held for anyone now.
+ state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== machineId)
+ state.releasedHarnesses = state.releasedHarnesses?.filter(r => r.machineId !== machineId)
+ const machine = pool?.name ?? 'a machine'
+ // Routing rules naming it lose it; a machines rule left with none is removed, and its project's chat is told.
+ for (const rule of state.rules ?? []) {
+ if (rule.rule.kind !== 'machines' || !rule.rule.machineIds.includes(machineId)) continue
+ rule.rule.machineIds = rule.rule.machineIds.filter(m => m !== machineId)
+ // The owner's words stay as they are; the row says what the rule allows now.
+ const project = projectsOf(state).find(p => p.id === rule.projectId)
+ if (project) effects.messages.push({ id: stableId(operationId, 'rule', machineId, rule.id), conversationId: project.leadConversationId, author: sender,
+ text: rule.rule.machineIds.length ? `Rule changed: ${machine} left the Swarm, so "${rule.text}" now allows only ${rule.rule.machineIds.map(machineName).join(', ')}.`
+ : `Rule removed: ${rule.text} Its only machine, ${machine}, left the Swarm.`, replyTo: null, recipients: [], source: RULE_ROW })
+ }
+ state.rules = state.rules?.filter(r => r.rule.kind !== 'machines' || r.rule.machineIds.length)
+ if (!state.rules?.length) delete state.rules
+ for (const { group, names, task } of affected) {
+ const lead = group.leadId && group.agentIds.includes(group.leadId) ? group.leadId : null
+ const join = names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0]
+ effects.messages.push({ id: stableId(operationId, 'machine-removed', machineId, group.id), conversationId: group.id, author: sender,
+ text: `${how(machine)}, and ${join} with it.${task ? ` Its task "${group.title}" needs to be assigned again or closed.` : ''}`,
+ replyTo: null, recipients: lead ? [lead] : [], source: SYSTEM_ROW })
+ }
+ return removed
+ }
+
/** Projects in one Swarm changed the same code without knowing it (2026-10-23). When a task is created, defined or assigned,
* its Leads hear once per pair of tasks that it owns code another shared project's active task owns too. */
const alertOverlaps = (group: Conversation) => {
@@ -690,49 +739,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person removes a machine from the Swarm.', 403)
const { pool, members } = ownedMachine(state, actor, command.machineId)
if (pool?.removal) fail('MACHINE_REMOVED', 'This machine is already being removed from the Swarm.')
- const pending = state.starts?.filter(s => s.request.machineId === command.machineId && !s.harnessId && !s.error) ?? []
- // A launch already under way would arrive with nowhere to go; it finishes in moments.
- if (pending.some(s => s.dispatched)) fail('STARTS_PENDING', 'An agent is starting on this machine. Try again in a moment.')
- for (const start of pending) {
- start.error = 'Its machine was removed from the Swarm.'
- effects.messages.push({ id: stableId(operationId, 'start', start.id), conversationId: start.request.conversationId, author: sender,
- text: `${start.request.name} will not start: its machine was removed from the Swarm.`, replyTo: null, recipients: [], source: SYSTEM_ROW })
- }
- const removed = new Set(members.map(a => a.id))
- const affected = state.conversations.filter(group => group.agentIds.some(a => removed.has(a))
- || (group.leadId && removed.has(group.leadId)) || (group.assignment && removed.has(group.assignment.agentId)))
- .map(group => ({ group, names: members.filter(a => group.agentIds.includes(a.id) || group.leadId === a.id || group.assignment?.agentId === a.id)
- .map(a => a.displayName ?? a.name), task: !!group.assignment && removed.has(group.assignment.agentId) && activeWork(group) }))
- for (const target of members) removeAgent(target)
- if (pool) {
- // Paused, so routing in clients that do not know removals stops offering it too.
- pool.removal = { id: operationId, state: 'cleaning', requestedAt: new Date(context.now).toISOString() }
- pool.paused = true
- result.removalId = operationId
- }
- // Its capacity left with it: no slot there is held for anyone now.
- state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== command.machineId)
- state.releasedHarnesses = state.releasedHarnesses?.filter(r => r.machineId !== command.machineId)
- const machine = pool?.name ?? 'a machine'
- // Routing rules naming it lose it; a machines rule left with none is removed, and its project's chat is told.
- for (const rule of state.rules ?? []) {
- if (rule.rule.kind !== 'machines' || !rule.rule.machineIds.includes(command.machineId)) continue
- rule.rule.machineIds = rule.rule.machineIds.filter(m => m !== command.machineId)
- // The owner's words stay as they are; the row says what the rule allows now.
- const project = projectsOf(state).find(p => p.id === rule.projectId)
- if (project) effects.messages.push({ id: stableId(operationId, 'rule', rule.id), conversationId: project.leadConversationId, author: sender,
- text: rule.rule.machineIds.length ? `Rule changed: ${machine} left the Swarm, so "${rule.text}" now allows only ${rule.rule.machineIds.map(machineName).join(', ')}.`
- : `Rule removed: ${rule.text} Its only machine, ${machine}, left the Swarm.`, replyTo: null, recipients: [], source: RULE_ROW })
- }
- state.rules = state.rules?.filter(r => r.rule.kind !== 'machines' || r.rule.machineIds.length)
- if (!state.rules?.length) delete state.rules
- for (const { group, names, task } of affected) {
- const lead = group.leadId && group.agentIds.includes(group.leadId) ? group.leadId : null
- const join = names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0]
- effects.messages.push({ id: stableId(operationId, 'machine-removed', group.id), conversationId: group.id, author: sender,
- text: `${who} removed ${machine} from the Swarm, and ${join} with it.${task ? ` Its task "${group.title}" needs to be assigned again or closed.` : ''}`,
- replyTo: null, recipients: lead ? [lead] : [], source: SYSTEM_ROW })
- }
+ const removed = removeMachine(command.machineId, pool, members, machine => `${who} removed ${machine} from the Swarm`)
+ if (pool) result.removalId = operationId
result.removedAgents = [...removed]
break
}
@@ -1120,9 +1128,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
if (command.userId === state.ownerId) fail('OWNER_REQUIRED', 'The owner cannot leave their Super Tab.')
const member = person(state, command.userId)
+ // Their machines leave the way their owner removes one, so the Swarm's folders there are deleted too.
+ for (const pool of state.machines?.filter(m => m.contributorId === member.id && !m.removal) ?? []) {
+ removeMachine(pool.machineId, pool, state.agents.filter(a => a.machineId === pool.machineId), machine => `${machine} left the Swarm with its owner`)
+ }
for (const target of state.agents.filter(a => a.contributorId === member.id)) removeAgent(target)
- // A machine being removed stays until its host cleaned up.
- state.machines = state.machines?.filter(m => m.contributorId !== member.id || m.removal)
state.people = state.people.filter(p => p.id !== member.id)
state.invitations = state.invitations.filter(i => i.email !== member.email)
result.removedUserId = member.id
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 8766a784f..0cb617be1 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -606,9 +606,10 @@ export class SuperTabStore {
const start = original.starts?.find(s => s.id === command.startId)
if (start?.routeDecisionId) await closeUnassignedStart(tx, tabId, start.routeDecisionId, start.id, 'failed', context.now)
}
- if (command.type === 'machine.remove') {
+ // Starts a removed machine failed, whether its owner removed it or left the Swarm with it, release their route holds.
+ if (command.type === 'machine.remove' || command.type === 'member.remove') {
for (const start of original.starts ?? []) {
- if (!start.routeDecisionId || start.request.machineId !== command.machineId || start.harnessId || start.error) continue
+ if (!start.routeDecisionId || start.harnessId || start.error) continue
if (effects.state.starts?.find(s => s.id === start.id)?.error) {
await closeUnassignedStart(tx, tabId, start.routeDecisionId, start.id, 'failed', context.now)
}