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.

Super Tab backend: Lead guard and close requests for removed agents (#1633)

0xken15f6e4357c258b
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 94dee4bb5..44ab418b3 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -350,7 +350,7 @@ describe('agent member identities', () => {
const tab = (await store.create(owner, randomUUID(), 'People and agents')).id
const operationId = randomUUID()
const command: Command = { type: 'agent.add', conversationId: 'lead', machineId: 'test-host',
- harnessId: randomUUID(), name: 'Lead', configuration: config, lead: true }
+ harnessId: randomUUID(), name: 'Lead', configuration: config, lead: false }
const added = await run(tab, command, owner, undefined, operationId)
const agentId = added.result.agentId as string
const first = await store.read(owner, tab)
@@ -552,8 +552,8 @@ describe('private swarm projects on the real control API', () => {
await expect(store.native.read(host, tab, context.contextId)).rejects.toMatchObject({ code: 'NATIVE_CONTEXT_REVOKED' })
expect(await store.mayObserve(peer, tab, 'test-host', harnessId, host.sub)).toBe(false)
- // Removing a roster row cannot erase the terminal's private history.
- await run(tab, { type: 'agent.remove', agentId })
+ // Removing a roster row, here with its project, cannot erase the terminal's private history.
+ await run(tab, { type: 'project.delete', projectId })
const other = await fixture()
await expect(run(other.tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId,
name: 'Moved lead', configuration: config, lead: false })).rejects.toMatchObject({ code: 'PROJECT_SESSION' })
@@ -811,7 +811,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
expect((await store.messages(host, tab, group, { messageId: question }, lead)).messages).toEqual([])
expect((await app.inject({ url: `/api/super-tabs/${tab}/conversations/lead/messages?messageId=${question}`,
headers: { authorization: `Bearer ${peer.sub}` } })).statusCode).toBe(403)
- await run(tab, { type: 'agent.remove', agentId: lead })
+ await run(tab, { type: 'project.delete', projectId: 'lead' })
const removed = await app.inject({ url, headers })
expect(removed.statusCode).toBe(409)
expect(removed.json().error.code).toBe('AGENT_UNAVAILABLE')
@@ -935,7 +935,9 @@ describe('Super Tabs on a real Mongo replica set', () => {
const race = await Promise.allSettled([run(tab, next, host, lead), run(tab, { ...next, configuration: { ...config, effort: 'low' } }, host, lead)])
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1)
expect(await db.superTabConfiguration.count({ where: { tabId: tab } })).toBe(3)
- await run(tab, { type: 'agent.remove', agentId: lead })
+ // A Lead leaves only with its project, and a project with active work is not deleted.
+ await run(tab, { type: 'work.cancel', conversationId: 'lead', assignmentId: assigned.result.assignmentId as string, reason: 'The project closes.' })
+ await run(tab, { type: 'project.delete', projectId: 'lead' })
await expect(run(tab, next, host, lead)).rejects.toMatchObject({ code: 'AGENT_UNAVAILABLE' })
expect(await db.superTabConfiguration.count({ where: { tabId: tab } })).toBe(3)
})
@@ -958,8 +960,9 @@ describe('Super Tabs on a real Mongo replica set', () => {
text: expect.stringContaining(`A message for ${displayName} is waiting. There is unsent text in ${displayName}'s input box.`) })
await store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'done', uncertain: false })
expect(await store.delivery(host, tab, lead, delivery.id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })).toEqual({ noticed: false })
- await run(tab, { type: 'agent.remove', agentId: lead })
- expect((await store.messages(owner, tab, 'lead', {})).messages[1]!.author).toMatchObject({ displayName })
+ // A Lead leaves only with its project; its stored rows keep its name.
+ await run(tab, { type: 'project.delete', projectId: 'lead' })
+ expect((await db.superTabMessage.findUnique({ where: { id: rows[1]!.id } }))!.author).toMatchObject({ displayName })
})
it('names the machine and its owner for a question on screen and sends the notice to the Lead, once', async () => {
@@ -1014,14 +1017,16 @@ describe('Super Tabs on a real Mongo replica set', () => {
})
it.each(['delivered', 'answered', 'cancelled'] as const)('clears a delivery hold when it becomes %s', async status => {
- const { tab, lead } = await fixture()
- await run(tab, message('Finish this held instruction.'))
- const delivery = (await store.deliveries(host, tab, lead))[0]!
- await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })
- await store.delivery(host, tab, lead, delivery.id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })
- if (status === 'delivered') await store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'typed', uncertain: false })
- else if (status === 'answered') await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Finished.', replyTo: delivery.messageId, recipientIds: [] }, host, lead)
- else await run(tab, { type: 'agent.remove', agentId: lead })
+ const { tab } = await fixture()
+ const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(), name: 'Worker',
+ configuration: config, lead: false })).result.agentId as string
+ await run(tab, { ...message('Finish this held instruction.'), recipientIds: [worker] } as Command)
+ const delivery = (await store.deliveries(host, tab, worker))[0]!
+ await store.delivery(host, tab, worker, delivery.id, { type: 'claim', claimId: 'claim' })
+ await store.delivery(host, tab, worker, delivery.id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })
+ if (status === 'delivered') await store.delivery(host, tab, worker, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'typed', uncertain: false })
+ else if (status === 'answered') await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Finished.', replyTo: delivery.messageId, recipientIds: [] }, host, worker)
+ else await run(tab, { type: 'agent.remove', agentId: worker })
const saved = await db.superTabDelivery.findUnique({ where: { id: delivery.id } })
expect(saved).toMatchObject({ status, holdReason: null, holdSince: null })
const row = (await store.messages(owner, tab, 'lead', { messageId: delivery.messageId })).messages[0]!
@@ -1052,7 +1057,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
const first = (await store.deliveries(host, tab, lead))[0]!
await store.delivery(host, tab, lead, first.id, { type: 'claim', claimId: 'claim' })
await store.delivery(host, tab, lead, first.id, { type: 'ack', claimId: 'claim', receipt: 'unclear', uncertain: true })
- await run(tab, { type: 'agent.remove', agentId: lead })
+ await run(tab, { type: 'project.delete', projectId: 'lead' })
expect(await store.deliveryReceipt(host, tab, lead, first.id)).toEqual({ id: first.id, status: 'cancelled' })
await expect(store.deliveries(host, tab, lead)).rejects.toMatchObject({ code: 'AGENT_UNAVAILABLE' })
await expect(store.deliveryReceipt(peer, tab, lead, first.id)).rejects.toMatchObject({ code: 'FORBIDDEN' })
@@ -1942,7 +1947,8 @@ it('lets a person force-withdraw a stuck stop, clears its fence and retires the
})
it('refuses to stop a finished worker that is the Lead of another Swarm', async () => {
- const first = await fixture(), second = await fixture(), native = randomUUID()
+ // The other Swarm has no Lead yet: the shared session becomes its first.
+ const first = await fixture(), second = { tab: (await store.create(owner, randomUUID(), 'Other')).id }, native = randomUUID()
const group = (await run(first.tab, { type: 'conversation.create', title: 'Finished worker', brief: 'Work', checks: [{ description: 'Done', independent: false }] })).result.conversationId as string
const worker = (await run(first.tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: native, name: 'Worker', configuration: config, lead: false })).result.agentId as string
const assignmentId = (await run(first.tab, { type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId as string
@@ -2047,3 +2053,41 @@ describe('the owner\'s Lead machine joins its Swarm', () => {
expect((await store.hostTabs(owner, machineId)).map(r => [r.agent.contributorId, r.joinSwarm])).toEqual([[peer.sub, false]])
})
})
+
+describe('Lead safety on the host roster', () => {
+ it('marks the Lead, refuses removing it, and lists removed sessions to close until their machine owner confirms', async () => {
+ const { tab, lead } = await fixture()
+ const harness = randomUUID()
+ const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: harness, name: 'Worker',
+ configuration: config, lead: false })).result.agentId as string
+ const rows = async () => (await store.hostTabs(host, 'test-host')).filter(r => r.tabId === tab)
+ expect((await rows()).map(r => [r.agent.id, r.lead])).toEqual([[lead, true], [worker, false]])
+ await expect(run(tab, { type: 'agent.remove', agentId: lead })).rejects.toMatchObject({ code: 'LEAD_PROTECTED',
+ message: expect.stringContaining('is the Product Manager of project Pilot. Delete the project first.') })
+
+ await run(tab, { type: 'agent.remove', agentId: worker })
+ const closing = (id: string, harnessId: string) => ({ tabId: tab, agent: { id, harnessId, machineId: 'test-host' }, closeSession: true, active: false })
+ expect(await rows()).toEqual([expect.objectContaining({ agent: expect.objectContaining({ id: lead }) }), closing(worker, harness)])
+ // What the host sends: its own account, no agent, one operation per session.
+ const confirm = (agentId: string, harnessId: string, user = host) =>
+ run(tab, { type: 'agent.sessionClosed', agentId, harnessId }, user, undefined, `session-closed-${agentId}-${harnessId}`)
+ expect((await store.read(owner, tab)).state).not.toHaveProperty('closingSessions')
+ // Neither the Swarm owner nor an outsider can confirm it, and a refusal writes nothing; the machine's owner can,
+ // though it is not in the Swarm.
+ const revision = (await store.read(owner, tab)).revision
+ await expect(confirm(worker, harness, owner)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(confirm(worker, harness, peer)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ expect((await store.read(owner, tab)).revision).toBe(revision)
+ const receipt = await confirm(worker, harness)
+ expect(await confirm(worker, harness)).toEqual(receipt)
+ await expect(run(tab, { type: 'agent.sessionClosed', agentId: worker, harnessId: harness }, host)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ expect((await rows()).map(r => r.agent.id)).toEqual([lead])
+
+ // Deleting the project takes its Lead, and its host is asked to close the session even with no agent left on the machine.
+ const leadHarness = (await store.read(owner, tab)).state.agents.find(a => a.id === lead)!.harnessId
+ await run(tab, { type: 'project.delete', projectId: 'lead' })
+ expect(await rows()).toEqual([closing(lead, leadHarness)])
+ await confirm(lead, leadHarness)
+ expect(await rows()).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index e75b4ff61..46d490079 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -106,10 +106,10 @@ describe('person removal notices', () => {
])
})
- it('posts a notice without claiming inactive work stopped or delivering to the removed Lead', () => {
- const f = fixture(), worker = f.add('lead', 'owner', 'lead', true)
+ it('posts a notice without claiming inactive work stopped or delivering to the removed group lead', () => {
+ const f = fixture(), group = f.group(), worker = f.add('worker', 'owner', group, true)
const effects = f.run({ type: 'agent.remove', agentId: worker })
- expect(effects.messages).toEqual([expect.objectContaining({ conversationId: 'lead', recipients: [] })])
+ expect(effects.messages).toEqual([expect.objectContaining({ conversationId: group, recipients: [] })])
expect(effects.messages[0]!.text).not.toContain('task')
})
@@ -907,6 +907,8 @@ describe('message attachments', () => {
expect(removed.messages).toEqual([])
expect(removed.cancelledAgents).toContain(worker)
expect(f.state.agents.some(a => a.id === worker)).toBe(false)
+ // Its host closed the session before confirming; nothing is left for it to close.
+ expect(f.state.closingSessions).toBeUndefined()
})
})
@@ -1515,24 +1517,24 @@ describe('machine.remove', () => {
it('takes the machine out with the Swarm\'s agents on it, and tells each group whose task needs a new worker', () => {
const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group(), worker = f.add('worker', 'owner', group)
+ f.state.agents.find(a => a.id === lead)!.machineId = 'elsewhere'
contribute(f)
f.run({ type: 'work.assign', conversationId: group, agentId: worker })
f.state.harnessReservations = [{ machineId: 'host', harnessId: 'old', generation: 'g0', renewed: false }, { machineId: 'elsewhere', harnessId: 'x', generation: 'g0', renewed: false }]
const named = (id: string) => { const a = f.state.agents.find(x => x.id === id)!; return a.displayName ?? a.name }
- const workerName = named(worker), leadName = named(lead)
+ const workerName = named(worker)
const effects = f.run({ type: 'machine.remove', machineId: 'host' })
expect(f.state.machines).toEqual([])
- expect(f.state.agents).toEqual([])
- expect(effects.result.removedAgents).toEqual([lead, worker])
+ 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' })])
expect(f.state.conversations.find(c => c.id === group)!.assignment!.status).toBe('reconciling')
const notice = effects.messages.find(m => m.conversationId === group)!
expect(notice).toMatchObject({ author: { kind: 'person', id: 'owner' }, source: { kind: 'system' } })
- // The group's Lead left with the machine too.
- expect(notice.text).toBe(`owner removed Studio from the Swarm, and ${leadName} and ${workerName} with it. Its task "Offline editing" needs to be assigned again or closed.`)
- expect(notice.recipients).toEqual([])
- expect(effects.messages.find(m => m.conversationId === 'lead')!.text).toBe(`owner removed Studio from the Swarm, and ${leadName} with it.`)
+ expect(notice.text).toBe(`owner removed Studio from the Swarm, and ${workerName} with it. Its task "Offline editing" needs to be assigned again or closed.`)
+ expect(notice.recipients).toEqual([lead])
+ expect(effects.messages.map(m => m.conversationId)).toEqual([group])
expect(new Set(effects.messages.map(m => m.id)).size).toBe(effects.messages.length)
})
@@ -1583,3 +1585,94 @@ describe('machine.remove', () => {
expect(commandSchema.safeParse({ type: 'machine.remove', machineId: 'host', extra: true }).success).toBe(false)
})
})
+
+describe('Lead protection', () => {
+ const refused = (project = 'Pilot') => expect.objectContaining({ code: 'LEAD_PROTECTED',
+ message: expect.stringMatching(new RegExp(`is the Product Manager of project ${project}\\. Delete the project first\\.$`)) })
+ const hostOwner: Actor = { kind: 'person', userId: 'host-owner', email: '[email protected]' }
+ const closing = (agentId: string, harnessId: string) => ({ agentId, machineId: 'host', harnessId, machineOwnerId: 'host-owner' })
+
+ it('refuses removing the Lead as an agent, with its machine, or with the person who contributed it', () => {
+ const f = fixture()
+ 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: '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])
+ expect(f.state.people.map(p => p.id)).toEqual(['owner', 'peer'])
+ })
+
+ it('refuses clearing or replacing the Lead, so it can never be released afterwards', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), other = f.add('other'), group = f.group()
+ expect(() => f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: lead, present: false, lead: false })).toThrow(refused())
+ expect(() => f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: other, present: true, lead: true })).toThrow(refused())
+ expect(() => f.add('other', 'owner', 'lead', true)).toThrow(refused())
+ expect(() => f.run({ type: 'agent.release', agentId: lead, decision: 'stop' })).toThrow(refused())
+ expect(f.state.conversations[0]!.leadId).toBe(lead)
+ // Its other groups and the Lead conversation's other members are not protected.
+ f.run({ type: 'conversation.agent', conversationId: group, agentId: lead, present: false, lead: false })
+ f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: other, present: false, lead: false })
+ expect(f.state.conversations.find(c => c.id === group)!.leadId).toBeNull()
+ })
+
+ it('protects the Lead of a Swarm from before projects', () => {
+ const f = fixture()
+ delete f.state.projects
+ const lead = f.add('lead', 'owner', 'lead', true)
+ expect(() => f.run({ type: 'agent.remove', agentId: lead })).toThrow(refused())
+ })
+
+ it('lets only deleting its project take the Lead, and asks its host to close the session', () => {
+ const f = fixture()
+ const { projectId, conversationId } = f.run({ type: 'project.create', name: 'Docs', visibility: 'public', brief: 'Docs' }).result as { projectId: string; conversationId: string }
+ const lead = f.add('docs-lead', 'owner', conversationId, true)
+ expect(() => f.run({ type: 'agent.remove', agentId: lead })).toThrow(refused('Docs'))
+ const effects = f.run({ type: 'project.delete', projectId })
+ expect(f.state.agents).toEqual([])
+ expect(effects.cancelledAgents).toEqual([lead])
+ expect(f.state.closingSessions).toEqual([closing(lead, 'docs-lead')])
+ })
+
+ it('asks the host to close the session of every agent a person removes, and shows it to nobody else', () => {
+ const f = fixture(), worker = f.add('worker')
+ f.run({ type: 'agent.remove', agentId: worker })
+ expect(f.state.closingSessions).toEqual([closing(worker, 'worker')])
+ expect(visibleState(f.state, owner)).not.toHaveProperty('closingSessions')
+
+ const g = fixture(), other = g.add('other')
+ g.run({ type: 'machine.remove', machineId: 'host' })
+ expect(g.state.closingSessions).toEqual([closing(other, 'other')])
+
+ const h = fixture()
+ h.invite()
+ const theirs = h.add('theirs', 'peer')
+ h.run({ type: 'member.remove', userId: 'peer' }, peer)
+ expect(h.state.closingSessions).toEqual([closing(theirs, 'theirs')])
+ })
+
+ it('drops a close request and the slot held for its session once the machine owner says it closed', () => {
+ const f = fixture(), worker = f.add('worker')
+ f.run({ type: 'agent.remove', agentId: worker })
+ expect(f.state.harnessReservations).toEqual([expect.objectContaining({ machineId: 'host', harnessId: 'worker' })])
+ const closed = { type: 'agent.sessionClosed', agentId: worker, harnessId: 'worker' } as Command
+ const nothing = expect.objectContaining({ code: 'NOT_FOUND', status: 404 })
+ // Another account learns nothing, not even whether a close is pending.
+ expect(() => f.run(closed)).toThrow(nothing)
+ expect(() => f.run({ ...closed, harnessId: 'other' } as Command, hostOwner)).toThrow(nothing)
+ f.run(closed, hostOwner)
+ expect(f.state.closingSessions).toBeUndefined()
+ expect(f.state.harnessReservations).toEqual([])
+ expect(f.state.releasedHarnesses).toEqual([{ machineId: 'host', harnessId: 'worker' }])
+ // Only the store's receipt answers an exact retry; a new confirmation finds nothing to close.
+ expect(() => f.run(closed, hostOwner)).toThrow(nothing)
+ })
+
+ it('forgets a close request when the same session is added back before its host closed it', () => {
+ const f = fixture(), worker = f.add('worker')
+ f.run({ type: 'agent.remove', agentId: worker })
+ f.add('worker')
+ expect(f.state.closingSessions).toBeUndefined()
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 45c88c3e5..895a09d02 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -10,7 +10,7 @@ import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type Rou
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 { agentProjectId, deleteProject, groupProject, inviteLanding, manageProject, mutableProjects, placeRules, projectMembers, projectOf, projectRules, readAgent, readConversation, readProject, sameProject, SKILL_MODE_NAMES, skillModeOf, type SwarmProject } from './projects.js'
+import { agentProjectId, deleteProject, groupProject, inviteLanding, ledProject, manageProject, mutableProjects, placeRules, projectMembers, projectOf, projectRules, readAgent, readConversation, readProject, sameProject, SKILL_MODE_NAMES, skillModeOf, 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)
@@ -86,6 +86,7 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('agent.stopLease'), agentId: id, releaseId: id }).strict(),
z.object({ type: z.literal('agent.remove'), agentId: id, releaseId: id.optional() }).strict(),
z.object({ type: z.literal('agent.release'), agentId: id, decision: z.enum(['keep', 'stop']) }).strict(),
+ z.object({ type: z.literal('agent.sessionClosed'), agentId: id, harnessId: id }).strict(),
z.object({ type: z.literal('agent.configuration'), previousVersion: id.nullable(), configuration }).strict(),
z.object({ type: z.literal('agent.rebind'), agentId: id, machineId: id, projectId: id,
previousHarnessId: id, harnessId: id, configuration,
@@ -169,10 +170,35 @@ function controls(state: SuperTabState, actor: Actor, conversationId = 'lead'):
}
}
+/** A project's Lead (Product Manager) leaves only with its project: every other removal path refuses it. */
+function protectLead(state: SuperTabState, agentId: string): void {
+ const project = ledProject(state, agentId), target = state.agents.find(a => a.id === agentId)
+ if (project && target) {
+ fail('LEAD_PROTECTED', `${target.displayName ?? target.name} is the Product Manager of project ${project.name}. Delete the project first.`)
+ }
+}
+
+/** The host proved this session stopped: its slot is free, and a late observation cannot list it as running. */
+function releaseHarness(state: SuperTabState, machineId: string, harnessId: string): void {
+ state.releasedHarnesses ??= []
+ if (!state.releasedHarnesses.some(r => r.machineId === machineId && r.harnessId === harnessId)) state.releasedHarnesses.push({ machineId, harnessId })
+ state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== machineId || r.harnessId !== harnessId)
+ const observation = state.machines?.find(m => m.machineId === machineId)?.observation
+ if (observation) {
+ observation.runningHarnessIds = observation.runningHarnessIds.filter(id => id !== harnessId)
+ if (!observation.stoppedHarnessIds.includes(harnessId)) observation.stoppedHarnessIds.push(harnessId)
+ }
+}
+
+function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabState['closingSessions']>[number]) => boolean): void {
+ state.closingSessions = state.closingSessions?.filter(keep)
+ if (!state.closingSessions?.length) delete state.closingSessions
+}
+
/** 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') return
+ if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed') 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).
@@ -234,6 +260,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
result.conversationId = invite.conversationId
return effects
}
+ // The host of a removed agent may have left the Swarm with it: the machine owner the request names confirms the close.
+ // Anyone else, or a second confirmation, is told the same thing and writes nothing; the store answers an exact retry.
+ if (command.type === 'agent.sessionClosed') {
+ const request = state.closingSessions?.find(c => c.agentId === command.agentId && c.harnessId === command.harnessId
+ && actor.kind === 'person' && c.machineOwnerId === actor.userId) ?? fail('NOT_FOUND', 'This machine has no session waiting to close.', 404)
+ dropClosing(state, c => c !== request)
+ releaseHarness(state, request.machineId, request.harnessId)
+ return effects
+ }
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
const sender = author(state, actor, !leaving)
@@ -311,7 +346,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
effects.routeDecisions.push({ op: 'final', id: decision.id, final: finalOf(decision), ...(override ? { override } : {}), ...(assignmentId ? { assignmentId } : {}) })
return { decision, expected, override }
}
- const removeAgent = (target: Agent) => {
+ /** Deleting its project is the only removal that takes a Lead. `close: false` when its host already closed the session. */
+ const removeAgent = (target: Agent, { lead = false, close = true } = {}) => {
+ if (!lead) protectLead(state, target.id)
+ if (close && !state.closingSessions?.some(c => c.agentId === target.id && c.harnessId === target.harnessId)) {
+ (state.closingSessions ??= []).push({ agentId: target.id, machineId: target.machineId, harnessId: target.harnessId, machineOwnerId: target.machineOwnerId })
+ }
state.agents = state.agents.filter(a => a.id !== target.id)
effects.cancelledAgents.push(target.id)
for (const group of state.conversations) {
@@ -321,6 +361,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
}
+ /** Changing or clearing the Lead of a project's Lead conversation would let it be stopped next. */
+ const keepLead = (group: Conversation, next: string | null) => {
+ if (group.leadId && group.leadId !== next && group.id === groupProject(state, group).leadConversationId) protectLead(state, group.leadId)
+ }
+
switch (command.type) {
case 'project.report': {
const project = readProject(state, actor, command.projectId)
@@ -390,10 +435,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
break
}
case 'project.delete': {
- // Its owner confirmed a permanent delete; nothing in Desktop removes agents one by one, so the project takes its
- // own agents with it. Their machines release the native sessions as they would for any removed agent.
+ // Its owner confirmed a permanent delete, so the project takes its own agents with it, its Lead included, and their
+ // hosts close their sessions.
const project = manageProject(state, actor, command.projectId)
- for (const target of state.agents.filter(a => agentProjectId(state, a) === project.id)) removeAgent(target)
+ for (const target of state.agents.filter(a => agentProjectId(state, a) === project.id)) removeAgent(target, { lead: true })
deleteProject(state, actor, command.projectId)
break
}
@@ -596,6 +641,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (existing?.workDecision === 'stop' && command.lead) fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')
if (existing && agentRole(existing) === 'reviewer' && command.lead) fail('REVIEWER_NOT_LEAD', 'A Reviewer reviews work and cannot lead a group.')
if (!existing) reserveHarnessSlot(state, command.machineId, command.harnessId, operationId)
+ // Added back before its host closed it: the session stays open.
+ if (!existing) dropClosing(state, c => c.machineId !== command.machineId || c.harnessId !== command.harnessId)
if (!existing) state.agents.push({ id: agentId, machineId: command.machineId, harnessId: command.harnessId,
...(state.projects ? { projectId: project.id } : {}),
machineOwnerId: grant.machineOwnerId, contributorId: grant.contributorId, membershipGeneration: contributor.generation,
@@ -609,6 +656,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
if (!group.agentIds.includes(agentId)) group.agentIds.push(agentId)
if (command.lead) {
+ keepLead(group, agentId)
if (group.leadId && group.leadId !== agentId && activeWork(group)) fail('WORK_ACTIVE', 'Reconcile active work before replacing its lead.')
group.leadId = agentId
}
@@ -770,6 +818,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const isLead = actor.kind === 'agent' && conversation(state, project.leadConversationId).leadId === actor.agentId
const isOwner = actor.kind === 'person' && [state.ownerId, target.contributorId].includes(actor.userId)
if (!isLead && !isOwner) fail('FORBIDDEN', 'Only this project’s Lead, the contributor or tab owner can release a worker.', 403)
+ protectLead(state, target.id)
if (state.conversations.some(c => c.leadId === target.id)) fail('LEAD_REQUIRED', 'Release workers only; keep the Lead running.')
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id)) fail('WORK_ACTIVE', 'Finish active work before releasing this worker.')
if (reviewing(state, target.id)) fail('WORK_ACTIVE', 'This Reviewer is reviewing active work. Remove it from that group or wait for the work to end.')
@@ -801,18 +850,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (hostStop && (command.releaseId !== target.releaseId || !target.releaseId)) fail('STALE_RELEASE', 'Read the current stop request before confirming removal.')
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id)) fail('WORK_ACTIVE', 'Finish active work before stopping this worker.')
// Administrative withdrawal never attests physical stopping or releases native capacity.
- if (hostStop) {
- state.releasedHarnesses ??= []
- if (!state.releasedHarnesses.some(r => r.machineId === target.machineId && r.harnessId === target.harnessId)) {
- state.releasedHarnesses.push({ machineId: target.machineId, harnessId: target.harnessId })
- }
- state.harnessReservations = state.harnessReservations?.filter(r => r.machineId !== target.machineId || r.harnessId !== target.harnessId)
- const observation = state.machines?.find(m => m.machineId === target.machineId)?.observation
- if (observation) {
- observation.runningHarnessIds = observation.runningHarnessIds.filter(id => id !== target.harnessId)
- if (!observation.stoppedHarnessIds.includes(target.harnessId)) observation.stoppedHarnessIds.push(target.harnessId)
- }
- }
+ if (hostStop) releaseHarness(state, target.machineId, target.harnessId)
if (actor.kind === 'agent') result.releasedBy = actor.machineOwnerId
if (forceStop) result.forceReleased = target.id
} else if (target.workDecision === 'stop') {
@@ -826,7 +864,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
const affected = actor.kind === 'person' ? state.conversations.filter(group => group.agentIds.includes(target.id)
|| group.leadId === target.id || group.assignment?.agentId === target.id) : []
- removeAgent(target)
+ removeAgent(target, { close: !hostStop })
for (const group of affected) {
const task = group.assignment?.agentId === target.id && activeWork(group)
? ` Its task "${group.title}" needs to be assigned again or closed.` : ''
@@ -851,6 +889,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (activeWork(group) && (group.assignment?.agentId === command.agentId || group.leadId === command.agentId)) {
fail('WORK_ACTIVE', 'Reconcile this agent’s assignment before removing it from the conversation.')
}
+ if (group.leadId === command.agentId) keepLead(group, null)
group.agentIds = group.agentIds.filter(id => id !== command.agentId)
if (group.leadId === command.agentId) group.leadId = null
} else {
@@ -859,6 +898,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// Adding a Reviewer to a group reuses it, as assigning work reuses a Builder.
if (reviewer) delete member.workDecision
if (command.lead) {
+ keepLead(group, command.agentId)
if (group.leadId && group.leadId !== command.agentId && activeWork(group)) fail('WORK_ACTIVE', 'Reconcile active work before replacing its lead.')
group.leadId = command.agentId
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index f8dda2af4..ce4a0ccb7 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -159,6 +159,8 @@ export interface SuperTabState {
harnessReservations?: Array<{ machineId: string; harnessId: string; generation: string; renewed: boolean }>
/** Native stop receipts survive late replaceable machine observations. */
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 }>
}
export type Actor =
| { kind: 'person'; userId: string; email: string }
@@ -289,6 +291,8 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
delete visible.sharing
delete visible.harnessReservations
delete visible.releasedHarnesses
+ // 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
numberConversations(visible)
delete visible.retiredConversationNumber
placeRules(visible)
diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.ts
index 45b80338b..8c9fd0501 100644
--- a/backend/src/superTabs/projects.test.ts
+++ b/backend/src/superTabs/projects.test.ts
@@ -156,7 +156,6 @@ describe('projects inside an invite-only swarm', () => {
expect(() => f.run(command, actor(workerId))).toThrow('coordinating lead')
expect(() => f.run(command, actor(otherId))).toThrow('unavailable')
}
- f.run({ type: 'agent.remove', agentId: leadId })
f.run({ type: 'agent.remove', agentId: workerId })
f.run({ type: 'project.delete', projectId: 'lead' })
expect(() => f.run({ type: 'tab.rename', name: 'Forbidden' }, actor(otherId))).toThrow('unavailable')
@@ -181,7 +180,7 @@ describe('projects inside an invite-only swarm', () => {
})
it('removes only its own agents, even one that left every workgroup', () => {
- const f = setup(), p = f.project(), agentId = f.add(p.conversationId, 'idle'), otherId = f.add('lead', 'other')
+ const f = setup(), p = f.project(), agentId = f.add(p.conversationId, 'idle', false), otherId = f.add('lead', 'other')
f.run({ type: 'conversation.agent', conversationId: p.conversationId, agentId, present: false, lead: false })
f.run({ type: 'project.delete', projectId: p.projectId })
expect(projectsOf(f.state).map(p => p.id)).toEqual(['lead'])
@@ -234,7 +233,7 @@ describe('projects inside an invite-only swarm', () => {
})
it('keeps active work visible after its contributed agent is removed', () => {
- const f = setup(), p = f.project(), agentId = f.add(p.conversationId, 'worker')
+ const f = setup(), p = f.project(), agentId = f.add(p.conversationId, 'worker', false)
f.run({ type: 'work.define', conversationId: p.conversationId, brief: 'Finish the task',
checks: [{ description: 'Verified', independent: false }] })
f.run({ type: 'work.assign', conversationId: p.conversationId, agentId })
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index ed8bd485f..123fa2bf7 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -50,6 +50,11 @@ export function agentProjectId(state: SuperTabState, target: Agent): string {
return target.projectId ?? state.conversations.find(c => c.agentIds.includes(target.id))?.projectId ?? 'lead'
}
+/** The project whose Lead (Product Manager) this agent is: the Lead of that project's Lead conversation. */
+export function ledProject(state: SuperTabState, agentId: string): SwarmProject | undefined {
+ return projectsOf(state).find(p => state.conversations.some(c => c.id === p.leadConversationId && c.leadId === agentId))
+}
+
export function canReadProject(state: SuperTabState, actor: Actor, project: SwarmProject): boolean {
if (actor.kind === 'agent') {
const target = state.agents.find(a => a.id === actor.agentId)
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index cadbf1b41..954c05ac8 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -10,7 +10,7 @@ import { attachmentMime, attachmentName, AttachmentTooLarge, checkedType, MAX_AT
import { randomBytes } from 'node:crypto'
import type { Readable } from 'node:stream'
import { logger } from '../utils/logger.js'
-import { canReadAgent, canReadProject, groupProject, projectsOf, agentProjectId, readConversation, skillModeOf, type ProjectVisibility } from './projects.js'
+import { canReadAgent, canReadProject, groupProject, ledProject, projectsOf, agentProjectId, readConversation, skillModeOf, type ProjectVisibility } from './projects.js'
import { bindSession, makeProjectPrivate } from './sessionScope.js'
import { noteProjectReports, projectUpdateRequest } from './projectUpdates.js'
import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
@@ -38,9 +38,13 @@ const stateOf = (row: SuperTab): SuperTabState => {
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.conversations.filter(activeWork).map(c => c.assignment!.execution.machineId), ...(state.closingSessions ?? []).map(c => c.machineId)])],
})
+/** 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. */
+const HOST_TABS = { orderBy: { updatedAt: 'desc' as const }, take: 100 }
+
/** Retrying a transaction never repeats a host action. All effects here are durable database writes. */
async function transaction<T>(db: PrismaClient, body: (tx: Transaction) => Promise<T>): Promise<T> {
for (let attempt = 0; ; attempt++) {
@@ -324,9 +328,11 @@ 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)
- const actor = hostMachineId && 'startId' in command
- ? await this.poolHostActor(tx, user, original, hostMachineId, command.startId)
- : await this.actor(tx, user, original, asAgentId)
+ // 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 }
+ : hostMachineId && 'startId' in command
+ ? await this.poolHostActor(tx, user, original, hostMachineId, command.startId)
+ : await this.actor(tx, user, original, asAgentId)
const receiptId = stableId(tabId, actorKey(actor), operationId)
const requestHash = hash(command)
const prior = await tx.superTabOperation.findUnique({ where: { id: receiptId } })
@@ -359,7 +365,7 @@ export class SuperTabStore {
}
return { revision: prior.revision, result: prior.result }
}
- if (command.type !== 'invite.accept') author(original, actor)
+ if (command.type !== 'invite.accept' && command.type !== 'agent.sessionClosed') 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)
@@ -743,7 +749,7 @@ export class SuperTabStore {
return transaction(this.db, async tx => {
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 } }, take: 100 })
+ const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, ...HOST_TABS })
return rows.flatMap(row => {
const state = stateOf(row)
let pool
@@ -792,7 +798,7 @@ export class SuperTabStore {
return transaction(this.db, async tx => {
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 } }, take: 100 })
+ const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, ...HOST_TABS })
const result = []
for (const row of rows) {
const state = stateOf(row)
@@ -816,11 +822,16 @@ export class SuperTabStore {
const home = projectsOf(state).find(p => p.id === agentProjectId(state, target))
const skillMode = home ? skillModeOf(home) : 'orchestration'
result.push({ tabId: row.id, tabName: state.name, revision: row.revision, paused: state.paused, active, attention, agent: target, joinSwarm, skillMode,
+ lead: !!ledProject(state, target.id),
stopRequested: target.workDecision === 'stop' && !state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id),
observers: people.filter(p => p.id !== user.sub &&
canReadAgent(state, { kind: 'person', userId: p.id, email: p.email }, target))
.map(p => ({ email: p.email, userId: p.id })) })
}
+ // Not `active`, so a host from before close requests leaves the session to its automatic cleanup.
+ 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 })
+ }
}
return result
})
@@ -847,7 +858,7 @@ export class SuperTabStore {
return transaction(this.db, async tx => {
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 } }, take: 100 })
+ const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, ...HOST_TABS })
return rows.flatMap(row => stateOf(row).conversations.filter(activeWork).flatMap(group => {
const work = group.assignment!
return work.execution.machineId === machineId && work.execution.machineOwnerId === user.sub