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.

Backend: a machine owner removes their machine from a Swarm (#1665)

0xken1509fabcc31076
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 79683cbc2..2cd4cf19f 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -656,7 +656,7 @@ describe('private swarm projects on the real control API', () => {
await expect(store.messages(peer, tab, conversationId, {})).rejects.toMatchObject({ code: 'NOT_FOUND' })
await expect(store.native.open(peer, tab, { operationId: randomUUID(), conversationId, agentId })).rejects.toMatchObject({ code: 'NOT_FOUND' })
expect(await store.mayObserve(peer, tab, 'test-host', harnessId, host.sub)).toBe(false)
- expect((await store.hostTabs(host, 'test-host')).find(t => t.agent.id === agentId)!.observers.map(p => p.userId)).not.toContain(peer.sub)
+ expect((await store.hostTabs(host, 'test-host')).find(t => t.agent?.id === agentId)!.observers.map(p => p.userId)).not.toContain(peer.sub)
await expect(store.messages(host, tab, 'lead', {}, agentId)).rejects.toMatchObject({ code: 'NOT_FOUND' })
await run(tab, { type: 'project.sharing', projectId, visibility: 'private', memberIds: [peer.sub] })
@@ -1338,7 +1338,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
name: 'Lead', configuration: config, lead: true }, peer)).result.agentId as string
const legacyLead = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
name: 'Old', configuration: config, lead: true })).result.agentId as string
- const modes = async () => Object.fromEntries((await store.hostTabs(host, 'test-host')).filter(r => r.tabId === tab).map(r => [r.agent.id, r.skillMode]))
+ const modes = async () => Object.fromEntries((await store.hostTabs(host, 'test-host')).filter(r => r.tabId === tab).map(r => [r.agent?.id, r.skillMode]))
expect(await modes()).toEqual({ [lead]: 'default', [legacyLead]: 'default' })
const say = async (text: string, user = peer) => (await run(tab, { ...message(text), conversationId: chat } as Command, user)).result.messageId as string
const skills = (messageId: string): Command => ({ type: 'project.skills', projectId, mode: 'orchestration', askedIn: { conversationId: chat, messageId } })
@@ -1849,7 +1849,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' })
+ await run(tab, { type: 'machine.remove', machineId: 'test-host' }, host)
const state = (await store.read(owner, tab)).state
for (const { routeDecisionId, startId } of starts) {
@@ -2092,7 +2092,7 @@ it('releases a finished worker through its execution host, cancels deliveries an
const { machineSlots } = await import('../src/superTabs/machines.js')
expect(machineSlots(before, before.machines![0]!)).toBe(2)
await run(tab, { type: 'agent.release', agentId: worker, decision: 'stop' }, host, lead)
- expect((await store.hostTabs(host, 'test-host')).find(r => r.agent.id === worker)).toMatchObject({ stopRequested: true })
+ expect((await store.hostTabs(host, 'test-host')).find(r => r.agent?.id === worker)).toMatchObject({ stopRequested: true })
await expect(run(tab, { type: 'agent.remove', agentId: worker }, owner, worker)).rejects.toMatchObject({ code: 'FORBIDDEN' })
const operation = randomUUID()
const releaseId = (await store.read(owner, tab)).state.agents.find(a => a.id === worker)!.releaseId!
@@ -2107,7 +2107,7 @@ it('releases a finished worker through its execution host, cancels deliveries an
const delayed = (await store.read(owner, tab)).state
expect(delayed.machines![0]!.availableSlots).toBe(3)
expect(await db.superTabDelivery.count({ where: { tabId: tab, agentId: worker, status: { in: ['queued', 'claimed', 'uncertain'] } } })).toBe(0)
- expect((await store.hostTabs(host, 'test-host')).some(r => r.agent.id === worker)).toBe(false)
+ expect((await store.hostTabs(host, 'test-host')).some(r => r.agent?.id === worker)).toBe(false)
// Re-contribution reserves a new runtime; ordinary removal must not reuse its old stop proof.
await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Renewed worker', configuration: config, lead: false })
await run(tab, { type: 'agent.remove', agentId: worker })
@@ -2527,3 +2527,67 @@ describe('a Swarm written by a later release', () => {
expect((await store.read(owner, tab)).state.conversations.find(c => c.id === created)!.number).toBe(8)
})
})
+
+describe('machine removal', () => {
+ const day = 24 * 3_600_000
+ async function contributed() {
+ const tab = (await store.create(owner, randomUUID(), 'Remove')).id
+ const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
+ await run(tab, { type: 'machine.contribute', machineId: 'test-host', name: 'Host', cwd: '/fixture/repo', engines: ['codex'], maxAgents: 4 }, host)
+ return tab
+ }
+ const cleanups = async (tab: string, from = store) => (await from.hostTabs(host, 'test-host')).filter(r => r.tabId === tab && 'cleanup' in r)
+ const cleaned = (tab: string, removalId: string) => app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`, headers: { authorization: `Bearer ${host.sub}` },
+ payload: { operationId: randomUUID(), command: { type: 'machine.cleaned', machineId: 'test-host', removalId } } })
+
+ it('previews the removal for the machine owner only, then lists a cleanup to its host until the host says it cleaned up', 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
+ const preview = (user: AuthUser) => app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/machines/test-host/removal`, headers: { authorization: `Bearer ${user.sub}` } })
+ const shown = await preview(host)
+ expect(shown.statusCode, shown.body).toBe(200)
+ expect(shown.json().data).toEqual({ blockedBy: null, agents: [{ id: worker, name: 'Worker', projectName: 'Remove' }], soleSourceProjects: [] })
+ expect((await preview(owner)).statusCode).toBe(403)
+ await expect(run(tab, { type: 'machine.remove', machineId: 'test-host' })).rejects.toMatchObject({ code: 'FORBIDDEN' })
+
+ const removalId = (await run(tab, { type: 'machine.remove', machineId: 'test-host' }, host)).result.removalId as string
+ expect((await store.read(owner, tab)).state.machines!.map(m => [m.removal?.state, m.paused])).toEqual([['cleaning', true]])
+ expect(await cleanups(tab)).toEqual([{ tabId: tab, cleanup: { machineId: 'test-host', removalId } }])
+ expect((await store.hostTabs(host, 'test-host')).filter(r => r.tabId === tab && r.agent?.id === worker && 'closeSession' in r)).toHaveLength(1)
+ expect((await store.hostTabs(owner, 'test-host').catch(() => []))).toEqual([])
+ // The machine owner's host acknowledges even after leaving the Swarm.
+ await run(tab, { type: 'member.remove', userId: host.sub }, host)
+ expect((await cleaned(tab, 'not-this-one')).statusCode).toBe(404)
+ const ack = await cleaned(tab, removalId)
+ expect(ack.statusCode, ack.body).toBe(200)
+ expect(await cleanups(tab)).toEqual([])
+ expect((await store.read(owner, tab)).state.machines).toEqual([])
+ })
+
+ it('lists a pending cleanup to its host even when the machine is in more than the 100 Swarms a host poll reads', async () => {
+ const tab = await contributed()
+ const removalId = (await run(tab, { type: 'machine.remove', machineId: 'test-host' }, host)).result.removalId as string
+ const newer = await Promise.all(Array.from({ length: 101 }, async () => (await store.create(owner, randomUUID(), 'Newer')).id))
+ await db.superTab.updateMany({ where: { id: { in: newer } }, data: { machineIds: ['test-host'] } })
+ try {
+ expect(await cleanups(tab)).toEqual([{ tabId: tab, cleanup: { machineId: 'test-host', removalId } }])
+ expect((await cleaned(tab, removalId)).statusCode).toBe(200)
+ } finally { await db.superTab.deleteMany({ where: { id: { in: newer } } }) }
+ })
+
+ 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
+ const later = new SuperTabStore(db, () => Date.now() + day)
+ expect((await later.read(owner, tab)).state.machines).toEqual([])
+ await later.execute(owner, tab, { operationId: randomUUID(), command: { type: 'tab.rename', name: 'A day later' } })
+ const stored = (await db.superTab.findUniqueOrThrow({ where: { id: tab } })).state as unknown as SuperTabState
+ expect([stored.machines, stored.machineCleanups]).toEqual([[], [{ machineId: 'test-host', removalId, machineOwnerId: host.sub }]])
+ expect(await cleanups(tab, later)).toEqual([{ tabId: tab, cleanup: { machineId: 'test-host', removalId } }])
+ await later.execute(host, tab, { operationId: randomUUID(), command: { type: 'machine.cleaned', machineId: 'test-host', removalId } })
+ expect(await cleanups(tab, later)).toEqual([])
+ expect(((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).state as unknown as SuperTabState).machineCleanups).toBeUndefined()
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index c05a86b2d..9ccf172bd 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -989,6 +989,8 @@ model SuperTab {
memberIds String[]
invitedEmails String[]
machineIds String[]
+ /// Machines whose host still has to clean up after their removal: read apart from the 100-Swarm host poll.
+ cleanupMachineIds String[] @default([])
revision Int @default(0)
state Json
createdAt DateTime @default(now())
@@ -997,6 +999,7 @@ model SuperTab {
@@index([autonomousEnv, memberIds])
@@index([autonomousEnv, invitedEmails])
@@index([autonomousEnv, machineIds])
+ @@index([autonomousEnv, cleanupMachineIds])
}
// A terminal retains its history when removed from a roster. These bindings
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 9d6dc2625..a7d4e0ed8 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -63,6 +63,8 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
if (!('startId' in req.body.command) || req.body.command.startId !== req.params.startId) throw new SuperTabError('FORBIDDEN', 'The host request must name this start.', 403)
return store.execute(req.user!, req.params.tabId, req.body, undefined, req.params.machineId)
}))
+ app.get<{ Params: z.infer<typeof machineParams> }>('/api/super-tabs/:tabId/machines/:machineId/removal', { preHandler: validateParams(machineParams) },
+ (req, reply) => respond(reply, () => store.machineRemoval(req.user!, req.params.tabId, req.params.machineId)))
app.post<{ Params: z.infer<typeof machineParams>; Body: z.infer<typeof machineObservationSchema> }>('/api/super-tabs/:tabId/machines/:machineId',
{ preHandler: [validateParams(machineParams), validateBody(machineObservationSchema)] },
(req, reply) => respond(reply, () => store.observeMachine(req.user!, req.params.tabId, req.params.machineId, req.body)))
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 64ade471c..1f4c15568 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { applyCommand, commandSchema, PAIR_CHAIN_LIMIT, type Command, type CommandContext } from './commands.js'
-import { machineSlots } from './machines.js'
+import { machineSlots, removalPreview } from './machines.js'
import { activeWork, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'
import type { RouteDecision } from './routeRecord.js'
import { agentTarget, broken } from './rules.js'
@@ -1262,7 +1262,7 @@ describe('the owner\'s rules', () => {
expect(() => startBy(f, f.leadActor, { model: 'sonnet', effort: undefined })).toThrow('rules out Claude at an unnamed effort')
expect(startBy(f, f.leadActor, { model: 'sonnet', effort: 'max' }).result.startId).toBeTruthy()
f.run(set({ kind: 'machines', machineIds: ['elsewhere'] }, 'Only elsewhere.'))
- expect(() => startBy(f, f.leadActor, { model: 'sonnet' })).toThrow('rules out this machine')
+ expect(() => startBy(f, f.leadActor, { model: 'sonnet' })).toThrow('The owner\'s rule "Only elsewhere." rules out this machine (it allows only elsewhere).')
})
it('lets a person through with a warning the group sees', () => {
const f = routed()
@@ -1526,7 +1526,8 @@ describe('machine.remove', () => {
const workerName = named(worker)
const effects = f.run({ type: 'machine.remove', machineId: 'host' })
- expect(f.state.machines).toEqual([])
+ expect(f.state.machines).toEqual([expect.objectContaining({ machineId: 'host', paused: true,
+ removal: { id: effects.result.removalId, state: 'cleaning', requestedAt: new Date(1000).toISOString() } })])
expect(f.state.agents.map(a => a.id)).toEqual([lead])
expect(effects.result.removedAgents).toEqual([worker])
expect(f.state.harnessReservations).toEqual([expect.objectContaining({ machineId: 'elsewhere' })])
@@ -1561,21 +1562,117 @@ describe('machine.remove', () => {
expect(g.state.machines).toHaveLength(1)
})
- it('lets the machine\'s owner take back what is all theirs, and leaves anyone else\'s to the Swarm owner', () => {
+ it('is only the machine owner\'s to remove, with every Swarm agent on it; the Swarm owner cannot remove another person\'s machine', () => {
const f = fixture()
f.invite()
contribute(f, 'peer')
f.add('theirs', 'peer')
+ const owners = f.add('owners', 'owner')
+ expect(() => f.run({ type: 'machine.remove', machineId: 'host' })).toThrow(expect.objectContaining({ code: 'FORBIDDEN', status: 403,
+ message: 'Only the machine\'s owner can remove it.' }))
f.run({ type: 'machine.remove', machineId: 'host' }, peer)
- expect(f.state.machines).toEqual([])
+ expect(f.state.agents.some(a => a.id === owners)).toBe(false)
+ expect(f.state.machines!.map(m => m.removal?.state)).toEqual(['cleaning'])
+ // A machine nobody contributed, with only shared agents, is theirs whose agents they all are.
const g = fixture()
g.invite()
- contribute(g, 'peer')
+ g.add('mine', 'peer')
g.add('owners', 'owner')
- expect(() => g.run({ type: 'machine.remove', machineId: 'host' }, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN', status: 403 }))
- g.run({ type: 'machine.remove', machineId: 'host' })
- expect(g.state.machines).toEqual([])
+ expect(() => g.run({ type: 'machine.remove', machineId: 'host' }, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ expect(() => g.run({ type: 'machine.remove', machineId: 'host' })).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ })
+
+ const cleaning = () => {
+ const f = fixture(), group = f.group()
+ contribute(f)
+ const removalId = f.run({ type: 'machine.remove', machineId: 'host' }).result.removalId as string
+ return { f, group, removalId }
+ }
+ const cleaned = (removalId: string): Command => ({ type: 'machine.cleaned', machineId: 'host', removalId })
+
+ it('keeps the machine paused and cleaning: no start, pause, re-adding or second removal until its owner\'s host says it cleaned up', () => {
+ const { f, group, removalId } = cleaning()
+ const request = { conversationId: group, machineId: 'host', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,
+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
+ expect(() => f.run({ type: 'agent.start', request }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })).toThrow('being removed')
+ expect(() => f.run({ type: 'machine.pause', machineId: 'host', paused: false })).toThrow('being removed')
+ expect(() => f.run({ type: 'machine.remove', machineId: 'host' })).toThrow('being removed')
+ const add = { type: 'machine.contribute', machineId: 'host', name: 'Studio', cwd: '/repo', engines: ['claude'], maxAgents: 2 } as Command
+ expect(() => f.run(add, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })).toThrow('still cleaning up')
+ f.invite()
+ expect(() => f.run(cleaned(removalId), peer)).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
+ expect(() => f.run(cleaned('other'))).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
+ f.run(cleaned(removalId))
+ expect(f.state.machines).toEqual([])
+ expect(() => f.run(cleaned(removalId))).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
+ f.run(add, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })
+ expect(f.state.machines!.map(m => m.removal)).toEqual([undefined])
+ })
+
+ it('lets the machine owner\'s host acknowledge after the owner left the Swarm', () => {
+ const f = fixture()
+ f.invite()
+ contribute(f, 'peer')
+ const removalId = f.run({ type: 'machine.remove', machineId: 'host' }, peer).result.removalId as string
+ f.run({ type: 'member.remove', userId: 'peer' }, peer)
+ expect(f.state.machines!.map(m => m.removal?.id)).toEqual([removalId])
+ f.run(cleaned(removalId), peer)
+ expect(f.state.machines).toEqual([])
+ })
+
+ it('drops the machine\'s records after 24 hours without an acknowledgement, and keeps the cleanup for its host', () => {
+ const { f, removalId } = cleaning()
+ const day = 24 * 3_600_000
+ f.run({ type: 'tab.rename', name: 'Still cleaning' }, owner, { now: 1000 + day - 1 })
+ expect(f.state.machines!.map(m => m.removal?.id)).toEqual([removalId])
+ expect(visibleState(f.state, owner, 1000 + day).machines).toEqual([])
+ f.run({ type: 'tab.rename', name: 'A day later' }, owner, { now: 1000 + day })
+ expect(f.state.machines).toEqual([])
+ expect(f.state.machineCleanups).toEqual([{ machineId: 'host', removalId, machineOwnerId: 'owner' }])
+ const add = { type: 'machine.contribute', machineId: 'host', name: 'Studio', cwd: '/repo', engines: ['claude'], maxAgents: 2 } as Command
+ expect(() => f.run(add, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' }, now: 1000 + day })).toThrow('still cleaning up')
+ f.run(cleaned(removalId), owner, { now: 1000 + day })
+ expect(f.state.machineCleanups).toBeUndefined()
+ })
+
+ it('takes the machine out of every project\'s machines rule, telling each project\'s chat, and removes a rule left empty', () => {
+ const f = fixture()
+ contribute(f)
+ const docs = f.run({ type: 'project.create', name: 'Docs', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }
+ const rule = (id: string, projectId: string, machineIds: string[]) => ({ id, projectId, rule: { kind: 'machines' as const, machineIds },
+ text: `Only ${machineIds.join(' and ')}.`, askedBy: 'owner', askedIn: null, addedBy: 'person:owner', createdAt: '' })
+ f.state.rules = [rule('both', 'lead', ['host', 'other']), rule('only', docs.projectId, ['host']), rule('elsewhere', docs.projectId, ['other']),
+ { ...rule('effort', 'lead', ['x']), rule: { kind: 'minEffort', effort: 'high' } }]
+ const effects = f.run({ type: 'machine.remove', machineId: 'host' })
+ expect(f.state.rules!.map(r => [r.id, r.rule])).toEqual([['both', { kind: 'machines', machineIds: ['other'] }],
+ ['elsewhere', { kind: 'machines', machineIds: ['other'] }], ['effort', { kind: 'minEffort', effort: 'high' }]])
+ // The owner's words stay as they were; the row says what the rule allows now.
+ expect(f.state.rules![0]!.text).toBe('Only host and other.')
+ expect(effects.messages).toEqual([
+ expect.objectContaining({ conversationId: 'lead', source: { kind: 'rule' },
+ text: 'Rule changed: Studio left the Swarm, so "Only host and other." now allows only other.' }),
+ expect.objectContaining({ conversationId: docs.conversationId, source: { kind: 'rule' },
+ text: 'Rule removed: Only host. Its only machine, Studio, left the Swarm.' })])
+ })
+
+ 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)
+ f.run({ type: 'work.assign', conversationId: group, agentId: worker })
+ f.state.project = { machineId: 'host', cwd: '/repo', repositoryUrl: null }
+ f.state.projects![0]!.repository = { machineId: 'host', cwd: '/repo', repositoryUrl: null }
+ const docs = f.run({ type: 'project.create', name: 'Docs', visibility: 'public', brief: '' }).result.projectId as string
+ f.state.projects!.find(p => p.id === docs)!.repository = { machineId: 'host', cwd: '/docs', repositoryUrl: 'https://github.com/example/docs' }
+ const named = (id: string) => { const a = f.state.agents.find(x => x.id === id)!; return a.displayName ?? a.name }
+ expect(removalPreview(f.state, owner, 'host')).toEqual({ blockedBy: { projectId: 'lead', projectName: 'Pilot' },
+ agents: [{ id: lead, name: named(lead), projectName: 'Pilot' }, { id: worker, name: named(worker), projectName: 'Pilot', task: 'Offline editing' }],
+ soleSourceProjects: [{ id: 'lead', name: 'Pilot' }] })
+ f.state.agents.find(a => a.id === lead)!.machineId = 'elsewhere'
+ expect(removalPreview(f.state, owner, 'host').blockedBy).toBeNull()
+ f.invite()
+ expect(() => removalPreview(f.state, peer, 'host')).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ expect(() => removalPreview(f.state, owner, 'nowhere')).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
})
it('is a person\'s to do, and only for a machine in the Swarm', () => {
@@ -1598,7 +1695,7 @@ describe('Lead protection', () => {
f.invite()
const lead = f.add('lead', 'peer', 'lead', true)
expect(() => f.run({ type: 'agent.remove', agentId: lead })).toThrow(refused())
- expect(() => f.run({ type: 'machine.remove', machineId: 'host' })).toThrow(refused())
+ expect(() => f.run({ type: 'machine.remove', machineId: 'host' }, peer)).toThrow(refused())
expect(() => f.run({ type: 'member.remove', userId: 'peer' })).toThrow(refused())
expect(() => f.run({ type: 'member.remove', userId: 'peer' }, peer)).toThrow(refused())
expect(f.state.agents.map(a => a.id)).toEqual([lead])
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 9032387cf..12234632e 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,4 +1,4 @@
-import { admitMachineStart, machineContribution } from './machines.js'
+import { admitMachineStart, expireRemovals, machineContribution, ownedMachine } from './machines.js'
import { assignAgentDisplayNames } from './agentNames.js'
import { z } from 'zod'
import {
@@ -11,7 +11,7 @@ import { routingOverrideSchema } from './routingPolicy.js'
import { agentTarget, askedInSchema, broken, MAX_RULES, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema, startTarget, type RunTarget } from './rules.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, type TerminalRequest } from './terminal.js'
-import { agentKind, agentProjectId, agentSetRole, deleteProject, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'
+import { agentKind, agentProjectId, agentSetRole, deleteProject, 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'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const title = z.string().trim().min(1).max(160)
@@ -63,6 +63,7 @@ export const commandSchema = z.discriminatedUnion('type', [
ifMissing: z.literal(true).optional() }).strict(),
z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),
z.object({ type: z.literal('machine.remove'), machineId: id }).strict(),
+ z.object({ type: z.literal('machine.cleaned'), machineId: id, removalId: id }).strict(),
z.object({ type: z.literal('tab.rename'), name: title }).strict(),
z.object({ type: z.literal('tab.project'), machineId: id, project }).strict(),
z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),
@@ -264,7 +265,7 @@ function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabS
/** Also checked before returning an idempotent receipt: a retry does not retain
* access after the person has been removed from a private project. */
export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {
- if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed') return
+ if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
author(state, actor, !leaving)
// An invitation's group is only where the person lands, and invite.create replaces a deleted one (inviteLanding).
@@ -312,6 +313,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
syncLeads(state)
numberConversations(state)
placeRules(state)
+ expireRemovals(state, context.now)
assignAgentDisplayNames(state.agents)
const result: Record<string, unknown> = {}
const effects: CommandEffects = { state, messages: [], cancelledAgents: [], previousAttempts: [], routeDecisions: [], result }
@@ -339,6 +341,18 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
releaseHarness(state, request.machineId, request.harnessId)
return effects
}
+ // A removed machine's host deleted the Swarm's folders there. Like a session close, its owner confirms it even after leaving.
+ if (command.type === 'machine.cleaned') {
+ const owns = (machineId: string, removalId: string, ownerId: string) => machineId === command.machineId && removalId === command.removalId
+ && actor.kind === 'person' && ownerId === actor.userId
+ const pool = state.machines?.find(m => m.removal && owns(m.machineId, m.removal.id, m.contributorId))
+ const cleanup = state.machineCleanups?.find(c => owns(c.machineId, c.removalId, c.machineOwnerId))
+ if (!pool && !cleanup) fail('NOT_FOUND', 'This machine has no cleanup waiting.', 404)
+ state.machines = state.machines?.filter(m => m !== pool)
+ state.machineCleanups = state.machineCleanups?.filter(c => c !== cleanup)
+ if (!state.machineCleanups?.length) delete state.machineCleanups
+ return effects
+ }
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
const sender = author(state, actor, !leaving)
@@ -365,9 +379,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const who = sender.kind === 'person' ? sender.name.split('@')[0]! : sender.name
/** A hard rule refuses an agent, unless it carries out what a person chose by hand. A person is not blocked: the
* command goes through and the group is told. */
+ const machineName = (id: string) => state.machines?.find(m => m.machineId === id)?.name ?? id
const groupRules = (conversationId: string) => projectRules(state, groupProject(state, conversation(state, conversationId)).id)
const ruled = (target: RunTarget, conversationId: string, done: string, personChose = false) => {
- const why = broken(groupRules(conversationId), target)
+ const why = broken(groupRules(conversationId), target, machineName)
if (!why) return
if (actor.kind === 'agent' && !personChose) fail('RULE_BROKEN', `${why} Route again.`, 403)
result.warnings = [why]
@@ -630,10 +645,14 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
state.machines ??= []
// The owner's host adds the machine its Lead runs on by itself (cli/src/superTabs/host.ts). It only fills a gap:
// on 2026-10-22 Ken's Mac ran the Lead of a Swarm it was never added to, so its starts bypassed the machine's slots.
+ // A late cleanup would delete the new contribution's folders.
+ const cleaning = state.machines.some(m => m.machineId === command.machineId && m.removal)
+ || !!state.machineCleanups?.some(c => c.machineId === command.machineId)
if (command.ifMissing) {
if (actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Swarm owner adds a machine automatically.', 403)
- if (state.machines.some(m => m.machineId === command.machineId)) break
+ if (cleaning || state.machines.some(m => m.machineId === command.machineId)) break
}
+ if (cleaning) fail('MACHINE_CLEANING', 'This machine is still cleaning up after its removal. Add it again once that finishes.')
if (!state.machines.some(m => m.machineId === command.machineId) && state.machines.length >= 32) fail('MACHINES_FULL', 'A Super Tab can have up to 32 contributed machines.')
// Before a machine was contributed, a Lead's start on it that never dispatched was left pending for good (12 on Ken's
// Mac that day) and refused every contribution. Those finish as failed; a dispatched or recent start still blocks.
@@ -660,21 +679,17 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'machine.pause': {
const pool = machineContribution(state, command.machineId) ?? fail('NOT_FOUND', 'This machine has not been contributed.', 404)
if (actor.kind !== 'person' || actor.userId !== pool.contributorId) fail('OWNER_REQUIRED', 'Only its contributor can change this machine.', 403)
+ if (pool.removal) fail('MACHINE_REMOVED', 'This machine is being removed from the Swarm.')
pool.paused = command.paused
break
}
case 'machine.remove': {
- // A machine leaves the Swarm with the Swarm's agents on it, the way Remove from Swarm withdraws one agent: their
- // processes keep running there, nothing is stopped. Withdrawing the contribution alone would leave it listed
- // wherever an agent still runs (desktop/lib/super_tabs/machines.dart lists both), and the host of an owner's
- // Lead adds such a machine back by itself (joinSwarm in store.ts).
+ // Its owner takes the machine out with every Swarm agent on it, each removed like one agent (its host closes the
+ // session; a Product Manager refuses it, protectLead). A contributed machine then stays listed, paused, while its
+ // host deletes the Swarm's folders there (spec 2026-10-23-remove-machine.md); one with only shared agents goes at once.
if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person removes a machine from the Swarm.', 403)
- const pool = state.machines?.find(m => m.machineId === command.machineId)
- const members = state.agents.filter(a => a.machineId === command.machineId)
- if (!pool && !members.length) fail('NOT_FOUND', 'This machine is not in the Swarm.', 404)
- // Its owner may take back what is all theirs; another person's agent on it is the Swarm owner's to remove.
- const theirs = (!pool || pool.contributorId === actor.userId) && members.every(a => a.contributorId === actor.userId)
- if (actor.userId !== state.ownerId && !theirs) fail('FORBIDDEN', 'Only the Swarm owner or the machine\'s owner can remove it.', 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.')
@@ -689,11 +704,28 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
.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)
- state.machines = state.machines?.filter(m => m.machineId !== command.machineId)
+ 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]
@@ -885,7 +917,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
fail('SWARM_ENGINE', 'A Swarm agent runs only Claude Code or Codex.', 400)
}
// A start recorded before a rule was added is not launched past it, unless a person asked for it by hand.
- const why = actor.kind === 'agent' && !(start.routeDecisionId && context.routeDecision?.override?.by === 'person') && broken(groupRules(start.request.conversationId), startTarget(start.request))
+ const why = actor.kind === 'agent' && !(start.routeDecisionId && context.routeDecision?.override?.by === 'person') && broken(groupRules(start.request.conversationId), startTarget(start.request), machineName)
if (why) fail('RULE_BROKEN', `${why} This start was not launched. Route again.`, 403)
requireWorkerDecisions(state, actor, open(state, start.request.conversationId))
const grant = context.contribution ?? fail('HOST_REQUIRED', 'The original machine grant is unavailable.', 403)
@@ -1089,7 +1121,8 @@ 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)
for (const target of state.agents.filter(a => a.contributorId === member.id)) removeAgent(target)
- state.machines = state.machines?.filter(m => m.contributorId !== member.id)
+ // 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/machines.ts b/backend/src/superTabs/machines.ts
index 7a8b78083..ce297c1b0 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -1,6 +1,6 @@
import { z } from 'zod'
-import { fail, person, type Agent, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
-import { groupProject } from './projects.js'
+import { activeWork, fail, person, type Actor, type Agent, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
+import { agentProjectId, groupProject, ledProject, projectsOf } from './projects.js'
import { conversation } from './model.js'
/** An explicit grant for this tab and project. It never creates a MachineShare. */
@@ -16,7 +16,13 @@ export interface ContributedMachine {
maxAgents: number
paused: boolean
observation?: MachineObservation & { receivedAt: number }
+ /** Set by machine.remove: the machine stays listed, paused, while its host deletes the Swarm's folders there, until the
+ * host says it cleaned up (machine.cleaned) or REMOVAL_FALLBACK_MS passes (expireRemovals). */
+ removal?: { id: string; state: 'cleaning'; requestedAt: string }
}
+/** A removed machine whose host never acknowledged in time: its records are gone, its host still cleans up on its next poll. */
+export interface MachineCleanup { machineId: string; removalId: string; machineOwnerId: string }
+export const REMOVAL_FALLBACK_MS = 24 * 3_600_000
/** Older contributions may name engines that Swarm no longer starts. Their fresh
* observation lists the supported engines that are actually installed. */
export function contributedEngines(pool: ContributedMachine, observation: MachineObservation | undefined = pool.observation): string[] {
@@ -80,6 +86,41 @@ export function machineContribution(state: SuperTabState, machineId: string) {
return pool
}
+/** A machine is its owner's to remove: whoever contributed it, or, for a machine with only shared agents, whoever
+ * contributed all of them. Not the Swarm owner (spec 2026-10-23-remove-machine.md, decision 1). */
+export function ownedMachine(state: SuperTabState, actor: Actor, machineId: string) {
+ const pool = state.machines?.find(m => m.machineId === machineId)
+ const members = state.agents.filter(a => a.machineId === machineId)
+ if (!pool && !members.length) fail('NOT_FOUND', 'This machine is not in the Swarm.', 404)
+ const ownerId = pool?.contributorId ?? (members.every(a => a.contributorId === members[0]!.contributorId) ? members[0]!.contributorId : null)
+ if (actor.kind !== 'person' || actor.userId !== ownerId) fail('FORBIDDEN', 'Only the machine\'s owner can remove it.', 403)
+ return { pool, members }
+}
+
+/** What removing the machine would do, for its owner's confirmation. */
+export function removalPreview(state: SuperTabState, actor: Actor, machineId: string) {
+ const { members } = ownedMachine(state, actor, machineId)
+ const led = members.map(a => ledProject(state, a.id)).find(Boolean)
+ return {
+ blockedBy: led ? { projectId: led.id, projectName: led.name } : null,
+ agents: members.map(a => {
+ const task = state.conversations.find(c => activeWork(c) && c.assignment!.agentId === a.id)
+ return { id: a.id, name: a.displayName ?? a.name, projectName: projectsOf(state).find(p => p.id === agentProjectId(state, a))?.name ?? '',
+ ...(task ? { task: task.title } : {}) }
+ }),
+ // Their code is only on this machine: no other machine can start agents for them until someone shares a repository.
+ soleSourceProjects: projectsOf(state).filter(p => p.repository?.machineId === machineId && !p.repository.repositoryUrl).map(p => ({ id: p.id, name: p.name })),
+ }
+}
+
+/** A removal its host has not acknowledged in a day: the machine's records go, and the cleanup waits for its host. */
+export function expireRemovals(state: SuperTabState, now: number): void {
+ for (const pool of state.machines?.filter(m => m.removal && now - Date.parse(m.removal.requestedAt) >= REMOVAL_FALLBACK_MS) ?? []) {
+ (state.machineCleanups ??= []).push({ machineId: pool.machineId, removalId: pool.removal!.id, machineOwnerId: pool.contributorId })
+ state.machines = state.machines!.filter(m => m !== pool)
+ }
+}
+
/** Pending intents reserve slots too. Only an explicit host stop frees a launched slot. */
export function machineSlots(state: SuperTabState, pool: ContributedMachine) {
const reservations = (state.harnessReservations ?? []).filter(r => r.machineId === pool.machineId)
@@ -106,6 +147,7 @@ export function machineSlots(state: SuperTabState, pool: ContributedMachine) {
export function admitMachineStart(state: SuperTabState, request: AgentStartRequest, now: number, start?: AgentStart) {
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))
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 70b271638..d71bdb159 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -1,7 +1,7 @@
import { createHash } from 'node:crypto'
import type { RouteDecisionEffect } from './routeRecord.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
-import { downSince } from './machines.js'
+import { downSince, expireRemovals } from './machines.js'
import { agentProjectId, agentSetRole, canReadAgent, canReadProject, groupProject, ledProject, placeRules, projectsOf, sharedWithLeads, skillSetOf, type ProjectVisibility, type SwarmProject } from './projects.js'
export type Role = 'owner' | 'collaborator' | 'viewer'
@@ -189,6 +189,8 @@ export interface SuperTabState {
releasedHarnesses?: Array<{ machineId: string; harnessId: string }>
/** Sessions of removed agents their host closes, listed to that host until it says they closed (agent.sessionClosed). */
closingSessions?: Array<{ agentId: string; machineId: string; harnessId: string; machineOwnerId: string }>
+ /** Removed machines whose host still has to clean up (machines.ts expireRemovals), listed only to that host. */
+ machineCleanups?: import('./machines.js').MachineCleanup[]
/** Conversations of a kind a later release added, set aside unchanged by a release that does not know it (parkLaterConversations). */
parkedConversations?: Conversation[]
}
@@ -385,6 +387,8 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
delete visible.overlapAlerts
// Only that machine's host roster lists them (store.ts hostTabs); a removed private agent's session is not every member's.
delete visible.closingSessions
+ delete visible.machineCleanups
+ expireRemovals(visible, now)
delete visible.parkedConversations
numberConversations(visible)
delete visible.retiredConversationNumber
diff --git a/backend/src/superTabs/rules.ts b/backend/src/superTabs/rules.ts
index c3f2d62a6..0fc247ebe 100644
--- a/backend/src/superTabs/rules.ts
+++ b/backend/src/superTabs/rules.ts
@@ -49,13 +49,14 @@ export function modelMatches(ruleModel: string, model: string | null): boolean {
return target !== 'default' && (target.includes(rule) || (FAMILY.exec(target)?.[0] === target && FAMILY.exec(rule)?.[0] === target))
}
-/** Why a hard rule rules the target out, or null when none does. */
-export function broken(rules: SwarmRule[] | undefined, target: RunTarget): string | null {
+/** Why a hard rule rules the target out, or null when none does. A machines rule names the machines it allows now: a removed
+ * machine leaves the rule but stays in the owner's words (machine.remove). */
+export function broken(rules: SwarmRule[] | undefined, target: RunTarget, machineName = (id: string) => id): string | null {
for (const { rule, text } of rules ?? []) {
const engineName = ENGINE[target.engine] ?? target.engine
const out = rule.kind === 'forbidModel' ? (!rule.engine || rule.engine === target.engine)
&& modelMatches(rule.model, target.model) && `${engineName} ${target.model}`
- : rule.kind === 'machines' ? !rule.machineIds.includes(target.machineId) && 'this machine'
+ : rule.kind === 'machines' ? !rule.machineIds.includes(target.machineId) && `this machine (it allows only ${rule.machineIds.map(machineName).join(', ')})`
: rule.kind === 'minEffort' ? (!rule.engine || rule.engine === target.engine) && rank(target.effort) < rank(rule.effort)
&& `${engineName} at ${target.effort && rank(target.effort) >= 0 ? `${target.effort} effort` : 'an unnamed effort'}`
: false
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index e862d98df..8766a784f 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1,4 +1,4 @@
-import { contributedEngines, machineContribution, machineObservationSchema, machineSlots, recordAgentPresence, type MachineObservation } from './machines.js'
+import { contributedEngines, machineContribution, machineObservationSchema, machineSlots, recordAgentPresence, removalPreview, type MachineObservation } from './machines.js'
import { createHash } from 'node:crypto'
import type { Prisma, PrismaClient, SuperTab, SuperTabDelivery } from '@prisma/client'
import type { AuthUser } from '../lib/ssoAuth.js'
@@ -64,8 +64,20 @@ async function restorePullRequestUrls(tx: Transaction, tabId: string, state: Sup
const indexes = (state: SuperTabState) => ({
memberIds: state.people.map(p => p.id), invitedEmails: state.invitations.map(i => i.email),
machineIds: [...new Set([...state.agents.map(a => a.machineId), ...(state.machines ?? []).map(m => m.machineId),
- ...state.conversations.filter(activeWork).map(c => c.assignment!.execution.machineId), ...(state.closingSessions ?? []).map(c => c.machineId)])],
+ ...state.conversations.filter(activeWork).map(c => c.assignment!.execution.machineId), ...(state.closingSessions ?? []).map(c => c.machineId),
+ ...(state.machineCleanups ?? []).map(c => c.machineId)])],
+ cleanupMachineIds: cleanups(state).map(c => c.machineId),
})
+/** Removed machines whose host has not yet said it cleaned up: still listed (machine.removal), or past the 24 h fallback. */
+const cleanups = (state: SuperTabState) => [
+ ...(state.machines ?? []).flatMap(m => m.removal ? [{ machineId: m.machineId, removalId: m.removal.id, machineOwnerId: m.contributorId }] : []),
+ ...(state.machineCleanups ?? [])]
+
+/** A machine its owner removed: its host deletes the Swarm's folders for this tab, then says so (machine.cleaned).
+ * The row has no agent, so a host from before removals skips it. */
+const cleanupRows = (tabId: string, state: SuperTabState, machineId: string, ownerId: string) =>
+ cleanups(state).filter(c => c.machineId === machineId && c.machineOwnerId === ownerId)
+ .map(({ removalId }) => ({ tabId, cleanup: { machineId, removalId } }))
/** A host reads its 100 most recently changed Swarms. Unordered, a Swarm just joined could be cut by older ones, such as
* Swarms only waiting for this machine to close a removed agent's session. */
@@ -360,8 +372,8 @@ export class SuperTabStore {
fail('FORBIDDEN', 'Only the execution host can confirm this removal.', 403)
}
if (hostMachineId && !['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) fail('FORBIDDEN', 'A host can only settle its queued starts.', 403)
- // A removed agent's host confirms its close as the machine owner, who may have left the Swarm with it.
- const actor: Actor = command.type === 'agent.sessionClosed' ? { kind: 'person', userId: user.sub, email: user.email }
+ // A removed agent's or machine's host confirms its close or cleanup as the machine owner, who may have left the Swarm with it.
+ const actor: Actor = command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned' ? { kind: 'person', userId: user.sub, email: user.email }
: hostMachineId && 'startId' in command
? await this.poolHostActor(tx, user, original, hostMachineId, command.startId)
: await this.actor(tx, user, original, asAgentId)
@@ -397,7 +409,7 @@ export class SuperTabStore {
}
return { revision: prior.revision, result: prior.result }
}
- if (command.type !== 'invite.accept' && command.type !== 'agent.sessionClosed') author(original, actor)
+ if (command.type !== 'invite.accept' && command.type !== 'agent.sessionClosed' && command.type !== 'machine.cleaned') author(original, actor)
const context: CommandContext = { operationId, now: this.now() }
if ('startId' in command && ['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) {
const start = original.starts?.find(s => s.id === command.startId)
@@ -972,6 +984,16 @@ export class SuperTabStore {
})
}
+ /** What removing a machine would do, for its owner's confirmation (machines.ts removalPreview). */
+ async machineRemoval(user: AuthUser, tabId: string, machineId: string) {
+ return transaction(this.db, async tx => {
+ const state = stateOf(await this.row(tx, user, tabId))
+ const actor = await this.actor(tx, user, state)
+ author(state, actor)
+ return removalPreview(state, actor, machineId)
+ })
+ }
+
async observeMachine(user: AuthUser, tabId: string, machineId: string, input: MachineObservation) {
const observation = machineObservationSchema.parse(input)
return transaction(this.db, async tx => {
@@ -1004,6 +1026,9 @@ export class SuperTabStore {
const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, ...HOST_TABS })
+ // A cleanup is never cut by that limit: a machine in more than 100 Swarms would otherwise keep a removed Swarm's folders.
+ const cleaning = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, cleanupMachineIds: { has: machineId },
+ id: { notIn: rows.map(r => r.id) } } })
const result = []
for (const row of rows) {
const state = stateOf(row)
@@ -1039,7 +1064,9 @@ export class SuperTabStore {
for (const { agentId: id, harnessId } of (state.closingSessions ?? []).filter(c => c.machineId === machineId && c.machineOwnerId === user.sub)) {
result.push({ tabId: row.id, agent: { id, harnessId, machineId }, closeSession: true as const, active: false })
}
+ result.push(...cleanupRows(row.id, state, machineId, user.sub))
}
+ for (const row of cleaning) result.push(...cleanupRows(row.id, stateOf(row), machineId, user.sub))
return result
})
}