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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Delete a Swarm: owner deletes, 7-day restore, purge after (Dee) (#2457)
0xken156311aad326cd
diff --git a/backend/integration/superTabDeletion.test.ts b/backend/integration/superTabDeletion.test.tsnew file mode 100644index 000000000..d6577e5b5--- /dev/null+++ b/backend/integration/superTabDeletion.test.ts@@ -0,0 +1,454 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { Readable } from 'node:stream'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { Prisma, PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore, type SwarmChanged } from '../src/superTabs/store.js'+import { MemoryAttachmentStore, type Attachments } from '../src/superTabs/attachments.js'+import type { Command } from '../src/superTabs/commands.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { machineSwarms } from '../src/superTabs/swarmRows.js'+import { SuperTabError } from '../src/superTabs/model.js'+import { PERSONAL_SWARM_OPERATION, SWARM_DELETE_GRACE_MS } from '../src/superTabs/deletion.js'+import { PURGE_MARGIN_MS, PURGE_RETRY_MS, PURGED_BY_TAB_ID, purgeDeletedSwarms, purgeFiles } from '../src/superTabs/purge.js'+import { sweepSwarms } from '../src/superTabs/sweeps.js'+import { sweepThreadMarks } from '../src/superTabs/readMarks.js'+import { sweepChatSettings } from '../src/superTabs/chatSettings.js'+import { backfillThreads } from '../src/superTabs/threadBackfill.js'+import { archiveFinishedGroups } from '../src/superTabs/archive.js'+import { beforeFirstWrite } from './interleave.test-support.js'+import { rosterRows } from './hostRows.test-support.js'++// Deleting a Swarm through the real store and Mongo (superTabs/deletion.ts, purge.ts): it leaves every list at once, every+// member's apps are told, its agents stop through their hosts and its machines are cleaned up, its owner alone restores it+// during the grace, and the purge after the grace removes its records and files and nobody else's.+let replica: MongoMemoryReplSet+let db: PrismaClient+const user = (n: number, name: string): AuthUser => ({ sub: `50000000000000000000000${n}`, email: `${name}@example.com`, autonomousEnv: 'prod', role: 'user' })+const owner = user(1, 'owner'), member = user(2, 'member'), host = user(3, 'host'), invitee = user(4, 'invitee')+const config = { engine: 'codex', model: 'gpt-6.1-sol', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' } as const++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`swarm_deletion_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ for (const u of [owner, member, host, invitee]) await db.user.create({ data: { id: u.sub, externalId: `fixture-${u.sub}`, email: u.email, autonomousEnv: u.autonomousEnv } })+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** A store on its own clock, telling what it would push to apps and observer sockets. */+function world(start = 1_800_000_000_000) {+ let now = start+ const files = new MemoryAttachmentStore()+ const attachments: Attachments = { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' }+ const changed: SwarmChanged[] = [], access: string[] = []+ const store = new SuperTabStore(db, () => now, attachments, { swarmChanged: change => changed.push(change), accessChanged: tabId => access.push(tabId) })+ const reads = new SwarmReads(store)+ return { store, reads, files, attachments, changed, access, clock: { get now() { return now }, set now(value: number) { now = value } } }+}++/** A Swarm with a member, a pending invitation, a message, a file, and a host's machine running its Product Manager and a worker. */+async function swarm(w: ReturnType<typeof world>, name = 'Lampos') {+ const tab = (await w.store.create(owner, randomUUID(), name, 'public')).id+ const execute = (command: Command, as = owner) => w.store.execute(as, tab, { operationId: randomUUID(), command })+ for (const u of [member, host]) {+ const invitation = await execute({ type: 'invite.create', email: u.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, u)+ }+ await execute({ type: 'invite.create', email: invitee.email, role: 'viewer', conversationId: 'lead' })+ const machineId = `host-${tab}`+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await execute({ type: 'machine.contribute', machineId, name: 'Studio', cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)+ const lead = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId, harnessId: randomUUID(), name: 'PM', configuration: config, lead: true }, host)).result.agentId)+ const worker = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId, harnessId: randomUUID(), name: 'Builder', configuration: config, lead: false }, host)).result.agentId)+ const hello = String((await execute({ type: 'message.send', conversationId: 'lead', text: 'hello', replyTo: null, recipientIds: [] })).result.messageId)+ await w.store.upload(member, tab, 'lead', { name: 'notes.txt', mime: 'text/plain', body: Readable.from(Buffer.from('notes')) })+ return { tab, execute, machineId, lead, worker, hello }+}++const refusal = async (body: () => Promise<unknown>) => {+ try { await body(); return 'answered' } catch (error) {+ // Only a Swarm refusal counts: a bug that throws anything else must fail the test, not pass it.+ if (!(error instanceof SuperTabError)) throw error+ const e = error as { code?: string; status?: number; unreachable?: boolean }+ return { code: e.code, status: e.status, unreachable: e.unreachable }+ }+}+// Word for word what the store answers about a Swarm that does not exist (checked below against a made-up id).+const MISSING = { code: 'NOT_FOUND', status: 404, unreachable: false }+const listed = async (w: ReturnType<typeof world>, who: AuthUser) => [...(await w.store.list(who)).tabs.map(t => t.id), ...(await w.reads.list(who)).tabs.map(t => t.id)]++describe('deleting a Swarm', () => {+ it('takes it off every member\'s and invitee\'s list in the same write, tells their apps, and reads like a missing Swarm', async () => {+ const w = world(), f = await swarm(w)+ for (const who of [owner, member, host]) expect(await listed(w, who)).toContain(f.tab)+ expect((await w.store.invitations(invitee)).map(i => i.tabId)).toContain(f.tab)+ expect((await w.store.workspaceList(owner)).workspaces.flatMap(o => o.swarms.map(s => s.id))).toContain(f.tab)+ w.changed.length = 0+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })++ for (const who of [owner, member, host]) expect(await listed(w, who)).not.toContain(f.tab)+ expect((await w.store.invitations(invitee)).map(i => i.tabId)).not.toContain(f.tab)+ expect((await w.store.workspaceList(owner)).workspaces.flatMap(o => o.swarms.map(s => s.id))).not.toContain(f.tab)+ // Every person's apps are told at once, and its observer sockets check again.+ expect(new Set(w.changed.filter(c => c.tabId === f.tab).flatMap(c => c.userIds))).toEqual(new Set([owner.sub, member.sub, host.sub]))+ expect(w.access).toContain(f.tab)+ // Every read, its owner's included, answers as a Swarm that does not exist; so do a message page and a file upload.+ for (const who of [owner, member]) {+ expect(await refusal(() => w.reads.firstLoad(who, f.tab))).toEqual(MISSING)+ expect(await refusal(() => w.store.read(who, f.tab))).toEqual(MISSING)+ expect(await refusal(() => w.store.messages(who, f.tab, 'lead', {}))).toEqual(MISSING)+ expect(await refusal(() => w.store.upload(who, f.tab, 'lead', { name: 'late.txt', mime: 'text/plain', body: Readable.from(Buffer.from('x')) }))).toEqual(MISSING)+ }+ const missing = randomUUID().replaceAll('-', '').slice(0, 24)+ expect(await refusal(() => w.reads.firstLoad(owner, missing))).toEqual(MISSING)+ // Only its owner sees it under Recently deleted, with its name and when it goes.+ expect((await w.store.deletedList(owner)).tabs).toContainEqual({ id: f.tab, name: 'Lampos', deletedAt: w.clock.now, purgeAt: w.clock.now + SWARM_DELETE_GRACE_MS })+ expect((await w.store.deletedList(member)).tabs).toEqual([])+ })++ it('is refused alike to a member, its agents and a made-up agent, and to anyone for the owner\'s Personal Swarm', async () => {+ const w = world(), f = await swarm(w)+ const del = { operationId: randomUUID(), command: { type: 'swarm.delete', name: 'Lampos' } as Command }+ for (const [who, as] of [[member, undefined], [host, f.lead], [host, f.worker], [host, 'ffffffffffffffffffffffff']] as const) {+ expect(await refusal(() => w.store.execute(who, f.tab, { ...del, operationId: randomUUID() }, as))).toEqual(MISSING)+ }+ expect(await listed(w, member)).toContain(f.tab)+ const personal = (await w.store.create(owner, PERSONAL_SWARM_OPERATION, 'Personal')).id+ expect(await refusal(() => w.store.execute(owner, personal, { operationId: randomUUID(), command: { type: 'swarm.delete', name: 'Personal' } })))+ .toEqual({ code: 'PERSONAL_SWARM', status: 409, unreachable: false })+ expect(await listed(w, owner)).toContain(personal)+ })++ it('stops its agents through their host and releases the machine, whose host still confirms both', async () => {+ const w = world(), f = await swarm(w)+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ const rows = (await rosterRows(w.store, host, f.machineId)).filter(r => r.tabId === f.tab)+ // The Product Manager and the worker each close; the machine is cleaned up; nothing else of the Swarm reaches the host.+ const closing = rows.filter(r => r.closeSession).map(r => r.agent!.id)+ expect(new Set(closing)).toEqual(new Set([f.lead, f.worker]))+ const cleanup = rows.find(r => r.cleanup)!.cleanup!+ expect(rows.filter(r => !r.closeSession && !r.cleanup)).toEqual([])+ for (const row of rows.filter(r => r.closeSession)) {+ await w.store.execute(host, f.tab, { operationId: randomUUID(), command: { type: 'agent.sessionClosed', agentId: row.agent!.id, harnessId: row.agent!.harnessId } as Command })+ }+ await w.store.execute(host, f.tab, { operationId: randomUUID(), command: { type: 'machine.cleaned', machineId: f.machineId, removalId: cleanup.removalId } })+ // Done: the host no longer finds the Swarm at all.+ expect(await machineSwarms(db, 'prod', f.machineId, 100)).not.toContain(f.tab)+ expect((await rosterRows(w.store, host, f.machineId)).filter(r => r.tabId === f.tab)).toEqual([])+ })++ it('is restored by its owner alone during the grace, with its people, chats and files and without agents', async () => {+ const w = world(), f = await swarm(w)+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ const restore = (who: AuthUser, as?: string) => w.store.execute(who, f.tab, { operationId: randomUUID(), command: { type: 'swarm.restore' } }, as)+ for (const [who, as] of [[member, undefined], [host, f.lead], [invitee, undefined]] as const) expect(await refusal(() => restore(who, as))).toEqual(MISSING)+ w.clock.now += SWARM_DELETE_GRACE_MS - 1+ w.changed.length = 0+ expect((await restore(owner)).result).toEqual({ restored: true })+ for (const who of [owner, member, host]) expect(await listed(w, who)).toContain(f.tab)+ expect(new Set(w.changed.filter(c => c.tabId === f.tab).flatMap(c => c.userIds))).toEqual(new Set([owner.sub, member.sub, host.sub]))+ expect((await w.store.read(member, f.tab)).state.agents).toEqual([])+ await w.reads.firstLoad(member, f.tab)+ expect((await w.store.messages(member, f.tab, 'lead', {})).messages.some(m => m.text === 'hello')).toBe(true)+ expect(w.files.objects.size).toBe(1)+ expect((await w.store.deletedList(owner)).tabs.map(t => t.id)).not.toContain(f.tab)+ })++ it('cannot be restored once its grace is over', async () => {+ const w = world(), f = await swarm(w)+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ w.clock.now += SWARM_DELETE_GRACE_MS+ expect(await refusal(() => f.execute({ type: 'swarm.restore' }))).toEqual(MISSING)+ expect((await w.store.deletedList(owner)).tabs.map(t => t.id)).not.toContain(f.tab)+ expect(await listed(w, owner)).not.toContain(f.tab)+ })+})++describe('the purge', () => {+ const counts = async (tabId: string) => {+ const each: Record<string, number> = {}+ for (const model of [...PURGED_BY_TAB_ID, 'superTabAttachment'] as const) {+ each[model] = await (db[model] as unknown as { count(args: { where: { tabId: string } }): Promise<number> }).count({ where: { tabId } })+ }+ return each+ }++ it('removes a deleted Swarm\'s records and files after its grace, and nothing of another Swarm', async () => {+ const w = world(), gone = await swarm(w, 'Gone'), kept = await swarm(w, 'Kept')+ await gone.execute({ type: 'swarm.delete', name: 'Gone' })+ const keptBefore = await counts(kept.tab)+ expect(Object.values(await counts(gone.tab)).some(n => n > 0)).toBe(true)+ expect(w.files.objects.size).toBe(2)+ const files = purgeFiles(w.attachments)++ // Within the grace, and its margin after, nothing goes.+ // (Other tests' deleted Swarms share this database, so each pass is judged by these two Swarms' records.)+ expect(await purgeDeletedSwarms(db, files, w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS - 1)).toMatchObject({ waiting: 0 })+ expect(await db.superTab.count({ where: { id: gone.tab } })).toBe(1)+ expect(await db.superTabMessage.count({ where: { tabId: gone.tab } })).toBeGreaterThan(0)++ expect(await purgeDeletedSwarms(db, files, w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS)).toMatchObject({ waiting: 0 })+ expect(Object.entries(await counts(gone.tab)).filter(([, n]) => n > 0)).toEqual([])+ expect(await db.superTab.count({ where: { id: gone.tab } })).toBe(0)+ const keptKey = (await db.superTabAttachment.findFirstOrThrow({ where: { tabId: kept.tab }, select: { objectKey: true } })).objectKey+ expect([...w.files.objects.keys()]).toEqual([keptKey])+ expect(await counts(kept.tab)).toEqual(keptBefore)+ expect(await listed(w, member)).toContain(kept.tab)+ // A second pass finds nothing left.+ expect(await purgeDeletedSwarms(db, files, w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS)).toEqual({ purged: 0, waiting: 0 })+ })++ it('keeps a restored Swarm, and keeps a Swarm whose file could not be removed for the next pass', async () => {+ const w = world(), f = await swarm(w)+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ await f.execute({ type: 'swarm.restore' })+ const after = w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS+ await purgeDeletedSwarms(db, purgeFiles(w.attachments), after)+ expect(await listed(w, member)).toContain(f.tab)+ expect(await db.superTabMessage.count({ where: { tabId: f.tab } })).toBeGreaterThan(0)++ const g = await swarm(w, 'Flaky')+ await g.execute({ type: 'swarm.delete', name: 'Flaky' })+ const broken = { chat: { delete: async () => { throw Object.assign(new Error('storage down'), { code: 503 }) } }, prefix: 'super-tabs', avatars: null, avatarPrefix: 'super-tabs' }+ expect((await purgeDeletedSwarms(db, broken, w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS)).waiting).toBeGreaterThanOrEqual(1)+ expect(await db.superTabAttachment.count({ where: { tabId: g.tab } })).toBe(1)+ expect(await db.superTab.count({ where: { id: g.tab } })).toBe(1)+ // Tried again only once its retry is due, so it never holds back a Swarm newly due.+ await purgeDeletedSwarms(db, purgeFiles(w.attachments), w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS)+ expect(await db.superTab.count({ where: { id: g.tab } })).toBe(1)+ await purgeDeletedSwarms(db, purgeFiles(w.attachments), w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS + PURGE_RETRY_MS)+ expect(await db.superTab.count({ where: { id: g.tab } })).toBe(0)+ })+})++// Security review 2 of #2457: what a deleted Swarm must keep, refuse or skip while it waits for its restore or its purge.+describe('while a Swarm is deleted', () => {+ const workspaceOf = async (w: ReturnType<typeof world>, tab: string) => (await w.store.read(owner, tab)).state.workspaceId!++ it('a restore leaves out whoever lost the Workspace meanwhile', async () => {+ const w = world(), f = await swarm(w)+ const workspaceId = await workspaceOf(w, f.tab)+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ // The member loses the Workspace, and no removal has reached this Swarm (a removal still open, say).+ await db.swarmWorkspaceMember.update({ where: { id: `${workspaceId}:${member.sub}` }, data: { removedAt: new Date(), removedBy: owner.sub } })+ await f.execute({ type: 'swarm.restore' })+ expect((await w.store.read(owner, f.tab)).state.people.map(p => p.id)).not.toContain(member.sub)+ expect(await listed(w, member)).not.toContain(f.tab)+ expect(await listed(w, host)).toContain(f.tab)+ })++ it('a Workspace removal takes the person out of a deleted Swarm too, so coming back to the Workspace does not bring them back', async () => {+ const w = world(), f = await swarm(w)+ const workspaceId = await workspaceOf(w, f.tab)+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ expect(await w.store.workspaces.remove(owner, workspaceId, member.sub)).toEqual({ userId: member.sub, pending: 0 })+ expect(await db.swarmMember.findUnique({ where: { id: `${f.tab}:${member.sub}` }, select: { deleted: true } })).toEqual({ deleted: true })+ // Back in the Workspace before the restore: still not back in this Swarm.+ await db.swarmWorkspaceMember.update({ where: { id: `${workspaceId}:${member.sub}` }, data: { removedAt: null, removedBy: null, purgeAt: null } })+ await f.execute({ type: 'swarm.restore' })+ expect((await w.store.read(owner, f.tab)).state.people.map(p => p.id)).not.toContain(member.sub)+ expect(await listed(w, member)).not.toContain(f.tab)+ })++ it('the hourly invitation sweep never writes it back onto an invitee\'s list, and the list never shows it', async () => {+ const w = world(), f = await swarm(w)+ const late = user(5, 'late')+ await db.user.upsert({ where: { id: late.sub }, create: { id: late.sub, externalId: `fixture-${late.sub}`, email: late.email, autonomousEnv: 'prod' }, update: {} })+ // Two invitations, a day apart: at the sweep's time the first has expired and the second has not.+ w.clock.now += 24 * 60 * 60 * 1000+ await f.execute({ type: 'invite.create', email: late.email, role: 'viewer', conversationId: 'lead' })+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ // A sweep that read the invitation index before the delete still finds the Swarm by it.+ await db.superTab.update({ where: { id: f.tab }, data: { invitedEmails: [invitee.email, late.email] } })+ const before = (await db.swarmHead.findUniqueOrThrow({ where: { id: `${f.tab}:head` } })).data as { invitations: unknown[] }+ const firstExpiry = Math.min(...(before.invitations as Array<{ expiresAt: number }>).map(i => i.expiresAt))+ await sweepSwarms(db, firstExpiry + 1)+ expect(((await db.swarmHead.findUniqueOrThrow({ where: { id: `${f.tab}:head` } })).data as { invitations: unknown[] }).invitations).toHaveLength(2)+ w.clock.now = firstExpiry + 1+ expect((await w.store.invitations(late)).map(i => i.tabId)).not.toContain(f.tab)+ })++ it('keeps everyone\'s thread follows and chat settings through the hourly sweeps, and a restore brings them back', async () => {+ const w = world(), f = await swarm(w)+ await w.reads.followThread(member, f.tab, 'lead', f.hello, true)+ await w.reads.setChatNotify(member, f.tab, 'lead', 'all')+ const kept = async () => [await db.superTabThreadMark.count({ where: { tabId: f.tab } }), await db.superTabChatSetting.count({ where: { tabId: f.tab } })]+ expect(await kept()).toEqual([1, 1])+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ await sweepThreadMarks(db, w.clock.now)+ await sweepChatSettings(db, w.clock.now)+ expect(await kept()).toEqual([1, 1])+ await f.execute({ type: 'swarm.restore' })+ expect((await w.reads.setChatNotify(member, f.tab, 'lead', 'all')).notify).toBe('all')+ })++ it('refuses a person\'s write that lands at the moment of the delete', async () => {+ const w = world(), tab = (await w.store.create(owner, randomUUID(), 'Racing', 'public')).id+ const invitation = await w.store.execute(owner, tab, { operationId: randomUUID(), command: { type: 'invite.create', email: member.email, role: 'collaborator', conversationId: 'lead' } })+ await w.store.execute(member, tab, { operationId: randomUUID(), command: { type: 'invite.accept', inviteId: invitation.result.inviteId as string } })+ // The member's post read the Swarm before the delete committed, and writes after it.+ let deleted = false+ const racing = new SuperTabStore(beforeFirstWrite(db, async () => {+ if (deleted) return+ deleted = true+ await w.store.execute(owner, tab, { operationId: randomUUID(), command: { type: 'swarm.delete', name: 'Racing' } })+ }), () => w.clock.now)+ expect(await refusal(() => racing.execute(member, tab, { operationId: randomUUID(),+ command: { type: 'message.send', conversationId: 'lead', text: 'after the delete', replyTo: null, recipientIds: [] } }))).toEqual(MISSING)+ expect(deleted).toBe(true)+ expect(await db.superTabMessage.count({ where: { tabId: tab, text: 'after the delete' } })).toBe(0)+ })++ /** A Swarm with an archived group whose reports are all summarized (so it may sleep), a finished start past its keeping,+ * a decision still waiting in that finished group, and a group finished weeks ago with a merged pull request; deleted or+ * not. Each background job changes the live one, so a check on the deleted one can fail (re-check 2 of #2457). */+ async function quietSwarm(w: ReturnType<typeof world>, name: string, deleted: boolean) {+ const f = await swarm(w, name)+ const group = String((await f.execute({ type: 'conversation.create', title: 'Old work', brief: 'Done long ago.',+ checks: [{ description: 'Done', independent: false }] })).result.conversationId)+ await f.execute({ type: 'conversation.archive', conversationId: group, archived: true })+ const progress = await db.swarmProgress.findUniqueOrThrow({ where: { id: `${f.tab}:lead` } })+ await db.swarmProgress.update({ where: { id: progress.id }, data: { data: { ...(progress.data as object), summarizedFloor: 1e9 } } })+ const prGroup = String((await f.execute({ type: 'conversation.create', title: 'Merged work', brief: 'Merged.',+ checks: [{ description: 'Done', independent: false }] })).result.conversationId)+ await db.superTabThreadBackfill.deleteMany({ where: { id: f.tab } })+ if (deleted) await f.execute({ type: 'swarm.delete', name })+ // Written as the records of work finished weeks ago would be.+ const old = new Date(w.clock.now - 30 * 24 * 60 * 60 * 1000)+ const row = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: prGroup } } })+ await db.swarmGroup.update({ where: { id: row.id }, data: { workFinished: true, lastActivityAt: old,+ data: { ...(row.data as object), assignment: { id: 'a1', agentId: 'gone', status: 'done', assignedAt: new Date(0).toISOString() },+ pullRequestUrls: [`https://github.com/example/${name}/pull/1`] } } })+ await db.swarmStart.create({ data: { id: `${f.tab}:start-old`, tabId: f.tab, key: 'start-old', version: 1, changedAt: old, ordinal: 0,+ machineId: f.machineId, conversationId: 'lead', finishedAt: old,+ data: { id: 'start-old', creationId: 'c', actorKey: `person:${owner.sub}`, contributorId: owner.sub, membershipGeneration: 'g', machineOwnerId: host.sub,+ hostGrant: null, error: 'It failed long ago.', request: { conversationId: 'lead', machineId: f.machineId, engine: 'codex', name: 'Builder', cwd: '/repo',+ worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } } })+ await db.superTabDecision.create({ data: { id: `${f.tab}:decision`, tabId: f.tab, batchId: 'b', projectId: 'lead', conversationId: group,+ personId: owner.sub, askerAgentId: f.lead, question: 'Ship it?', options: ['Yes', 'No'], recommended: 0, unblocks: 'Shipping', createdAt: old } })+ return { ...f, group }+ }++ it('is left alone by the background jobs, which change a live Swarm set up alike', async () => {+ const w = world(), live = await quietSwarm(w, 'Live', false), gone = await quietSwarm(w, 'Gone', true)+ const later = w.clock.now + 30 * 24 * 60 * 60 * 1000+ const state = async (f: typeof live) => ({+ asleep: (await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: f.group } } })).dormant,+ startKept: !(await db.swarmStart.findUniqueOrThrow({ where: { id: `${f.tab}:start-old` } })).deleted,+ decisionWaits: !(await db.superTabDecision.findUniqueOrThrow({ where: { id: `${f.tab}:decision` } })).answeredAt,+ backfilled: !!await db.superTabThreadBackfill.count({ where: { id: f.tab } }),+ })+ expect(await state(live)).toEqual({ asleep: false, startKept: true, decisionWaits: true, backfilled: false })+ expect(await state(gone)).toEqual({ asleep: false, startKept: true, decisionWaits: true, backfilled: false })++ // The archive pass first: the sleep sweep's write would make the merged group look recently active.+ const read: string[] = []+ await archiveFinishedGroups(db, w.store, { state: async url => { read.push(url); return 'merged' }, done: async () => {} }, w.clock.now)+ await sweepSwarms(db, later)+ await w.store.withdrawEndedDecisions()+ await backfillThreads(db, w.clock.now)++ expect(await state(live)).toEqual({ asleep: true, startKept: false, decisionWaits: false, backfilled: true })+ expect(await state(gone)).toEqual({ asleep: false, startKept: true, decisionWaits: true, backfilled: false })+ expect(read).toEqual(['https://github.com/example/Live/pull/1'])+ })+})++describe('the purge, everywhere', () => {+ /** Every collection that names a Swarm, from the schema itself: a model added later is purged, or this fails. */+ const SWARM_KEYED = Prisma.dmmf.datamodel.models.flatMap(model => {+ const field = model.fields.find(f => f.name === 'tabId' || f.name === 'superTabId')+ // Fields of its unique indexes besides the Swarm's id: each seed fills them, so two seeds never collide.+ const unique = [...new Set([...model.fields.filter(f => f.isUnique).map(f => f.name), ...model.uniqueFields.flat()])]+ .filter(name => name !== field?.name && name !== 'id')+ return field ? [{ model: model.name, collection: model.dbName ?? model.name, field: field.name, unique }] : []+ })+ // Agent Messages' desk tabs (AgentMessageTab, AgentMessageShare) name a desk tab, never a Swarm.+ const NOT_SWARMS = new Set(['AgentMessageTab', 'AgentMessageShare'])++ it('removes a record of the deleted Swarm from every collection that names one, and none of another Swarm', async () => {+ const w = world(), gone = await swarm(w, 'Gone'), kept = await swarm(w, 'Kept')+ await gone.execute({ type: 'swarm.delete', name: 'Gone' })+ const targets = SWARM_KEYED.filter(t => !NOT_SWARMS.has(t.model))+ expect(targets.length).toBeGreaterThan(30)+ for (const tabId of [gone.tab, kept.tab]) {+ // An attachment record names its stored file, outside the Swarm's folder here: the record goes, no file is touched.+ for (const t of targets) {+ const reply = await db.$runCommandRaw({ insert: t.collection, documents: [{ _id: `seed-${tabId}-${t.model}`, [t.field]: tabId,+ ...Object.fromEntries(t.unique.map(name => [name, `seed-${tabId}-${name}`])),+ ...t.model === 'SuperTabAttachment' ? { objectKey: `elsewhere/${tabId}/seed.txt` } : {} }] }) as { n?: number; writeErrors?: unknown }+ expect(reply, `${t.model}: ${JSON.stringify(reply).slice(0, 300)}`).toMatchObject({ n: 1 })+ }+ await db.$runCommandRaw({ insert: 'SuperTabThreadBackfill', documents: [{ _id: tabId, through: { $date: new Date(0).toISOString() } }] })+ }+ const left = async (tabId: string) => {+ const found: string[] = []+ for (const t of targets) {+ const n = Number((await db.$runCommandRaw({ count: t.collection, query: { [t.field]: tabId } }) as { n: unknown }).n)+ if (n) found.push(t.model)+ }+ if (Number((await db.$runCommandRaw({ count: 'SuperTabThreadBackfill', query: { _id: tabId } }) as { n: unknown }).n)) found.push('SuperTabThreadBackfill')+ return found+ }+ const keptBefore = await left(kept.tab)+ await purgeDeletedSwarms(db, purgeFiles(w.attachments), w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS)+ expect(await left(gone.tab)).toEqual([])+ expect(await left(kept.tab)).toEqual(keptBefore)+ expect(keptBefore.length).toBe(targets.length + 1)+ })++ it('reads the due Swarms, an owner\'s deleted list and a Workspace\'s deleted Swarms by their indexes', async () => {+ const w = world(), f = await swarm(w)+ // Someone in this Swarm alone, so removing them from the Workspace touches no other test's Swarms.+ const leaver = user(6, 'leaver')+ await db.user.upsert({ where: { id: leaver.sub }, create: { id: leaver.sub, externalId: `fixture-${leaver.sub}`, email: leaver.email, autonomousEnv: 'prod' }, update: {} })+ const invitation = await f.execute({ type: 'invite.create', email: leaver.email, role: 'viewer', conversationId: 'lead' })+ await f.execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, leaver)+ await f.execute({ type: 'swarm.delete', name: 'Lampos' })+ const plans = async (read: () => Promise<unknown>) => {+ await db.$runCommandRaw({ profile: 2 })+ await read()+ await db.$runCommandRaw({ profile: 0 })+ const found = await db.$runCommandRaw({ find: 'system.profile', filter: { ns: { $regex: '\\.SuperTab$' }, 'command.profile': { $exists: false } }, batchSize: 1000 }) as+ unknown as { cursor: { firstBatch: Array<{ planSummary?: string; command?: { pipeline?: unknown } }> } }+ await db.$runCommandRaw({ drop: 'system.profile' })+ return [...new Set(found.cursor.firstBatch.flatMap(row => row.planSummary && row.command?.pipeline ? [row.planSummary] : []))]+ }+ expect(await plans(() => w.store.deletedList(owner))).toEqual(['IXSCAN { autonomousEnv: 1, ownerId: 1, _id: 1 }'])+ expect(await plans(() => purgeDeletedSwarms(db, null, w.clock.now))).toEqual(['IXSCAN { purgeAt: 1 }'])+ // A Workspace removal reads the person's Swarms by the member index and the Workspace's deleted ones by its own.+ const workspaceId = (await db.superTab.findUniqueOrThrow({ where: { id: f.tab }, select: { workspaceId: true } })).workspaceId!+ const removal = await plans(async () => expect(await w.store.workspaces.remove(owner, workspaceId, leaver.sub)).toEqual({ userId: leaver.sub, pending: 0 }))+ expect(removal).toEqual(expect.arrayContaining(['IXSCAN { autonomousEnv: 1, memberIds: 1, _id: 1 }', 'IXSCAN { autonomousEnv: 1, workspaceId: 1 }']))+ expect(removal.filter(plan => !plan.startsWith('IXSCAN'))).toEqual([])+ })++ it('never lets Swarms it cannot finish hold back one newly due', async () => {+ // Earlier than every other test's Swarms, so theirs are never due in these passes.+ const w = world(1_700_000_000_000), stuck = await swarm(w, 'Stuck'), fresh = await swarm(w, 'Fresh')+ await stuck.execute({ type: 'swarm.delete', name: 'Stuck' })+ w.clock.now += 1000+ await fresh.execute({ type: 'swarm.delete', name: 'Fresh' })+ const after = w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS+ const broken = { chat: { delete: async () => { throw Object.assign(new Error('storage down'), { code: 503 }) } }, prefix: 'super-tabs', avatars: null, avatarPrefix: 'super-tabs' }+ // The stuck one fails first; afterwards, with room for one Swarm a pass, the fresh one is next, not the stuck one again.+ await db.superTabAttachment.deleteMany({ where: { tabId: fresh.tab } })+ await purgeDeletedSwarms(db, broken, after - 1000, 1)+ expect(await db.superTab.count({ where: { id: stuck.tab } })).toBe(1)+ await purgeDeletedSwarms(db, broken, after, 1)+ expect(await db.superTab.count({ where: { id: fresh.tab } })).toBe(0)+ })+})diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.tsindex 7ae435f07..f6b69bbc0 100644--- a/backend/integration/superTabGithub.test.ts+++ b/backend/integration/superTabGithub.test.ts@@ -357,6 +357,22 @@ describe('a queued start\'s preparation token', () => {expect(env.approved).toHaveLength(1)})+ it('approves nothing for a Swarm deleted since the link was made, and says so as for an expired link', async () => {+ const signIn = { authorizeUrl: (state: string) => `https://github.test/login/oauth/authorize?state=${state}`,+ permission: async () => ({ login: 'olive', push: true }) } as unknown as GitHubSignIn+ teamAccounts()+ const env = await fresh({ approveAll: false, signIn })+ const { tab } = await queued(env)+ const asked = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/projects/lead/github/approve`,+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { scope: 'project' } })+ const state = new URL((asked.json().data as { authorizeUrl: string }).authorizeUrl).searchParams.get('state')!+ await env.run(tab, { type: 'swarm.delete', name: 'Pool' } as Command)+ const late = await env.app.inject({ method: 'GET', url: `/api/github/callback?code=c&state=${encodeURIComponent(state)}` })+ expect(late.statusCode).toBe(400)+ expect(late.body).toContain('This link has expired')+ expect(env.approved).toEqual([])+ })+it('says nothing was approved when the person cancels GitHub\'s sign-in', async () => {const signIn = { authorizeUrl: (state: string) => `https://github.test/login/oauth/authorize?state=${state}`,permission: async () => ({ login: 'olive', push: true }) } as unknown as GitHubSignIndiff --git a/backend/integration/superTabLegacyDrop.test.ts b/backend/integration/superTabLegacyDrop.test.tsindex fa981e294..e045d09db 100644--- a/backend/integration/superTabLegacyDrop.test.ts+++ b/backend/integration/superTabLegacyDrop.test.ts@@ -271,6 +271,6 @@ describe('the automatic removal after a release', () => {const row = await new SuperTabStore(db).row(db, user, tabId)- expect(Object.keys(row).sort()).toEqual(['format', 'id', 'ownerId', 'revision'])+ expect(Object.keys(row).sort()).toEqual(['deletedAt', 'format', 'id', 'ownerId', 'revision'])})})diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.tsindex 74b4dc98d..a5beaf320 100644--- a/backend/integration/superTabNotAvailable.test.ts+++ b/backend/integration/superTabNotAvailable.test.ts@@ -158,6 +158,21 @@ describe('a Swarm the caller cannot reach, on every person route', () => {}})+ it('answers a deleted Swarm alike on every route, to its owner and members too, for its chats, Buddy chat and private project', async () => {+ const f = await swarm()+ const execute = (command: Command, as = owner) => store.execute(as, f.tab, { operationId: randomUUID(), command })+ const buddyChat = String((await execute({ type: 'buddy.chat' }, member)).result.conversationId)+ await execute({ type: 'swarm.delete', name: 'Not available' })+ const missing = calls(MISSING, 'lead', 'lead')+ for (const [chat, project] of [['lead', 'lead'], [buddyChat, 'lead'], [f.privateChat, f.privateProject]] as const) {+ for (const [i, call] of calls(f.tab, chat, project).entries()) {+ const cases = { owner: await answer(call, owner), member: await answer(call, member), outsider: await answer(call, outsider), missing: await answer(missing[i]!, owner) }+ const expected = /\/github\/approve$|\/github-token$/.test(call.route) ? cases.missing : { status: 404, body: NOT_AVAILABLE_BODY }+ for (const [name, got] of Object.entries(cases)) expect.soft(got, `${name}: ${call.url}`).toEqual(expected)+ }+ }+ })+it('answers a member alike for a private project\'s chat and project as for ones that do not exist, naming neither', async () => {const f = await swarm()const hidden = calls(f.tab, f.privateChat, f.privateProject), missing = calls(f.tab, MISSING, MISSING)diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 2f5e24aad..971e5ebd0 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1044,9 +1044,17 @@ model SuperTab {legacyState Json?/// The Workspace (SwarmWorkspace) it belongs to, also on its head part. Null only on a Swarm from before Workspaces, until migrated.workspaceId String?+ /// When its owner deleted it (superTabs/deletion.ts): from then every read and write answers as for a Swarm that does not+ /// exist, and its owner can restore it until `purgeAt`, when the sweep removes its records and files. Absent on a live Swarm.+ deletedAt DateTime?+ purgeAt DateTime?+ /// When the purge may try a deleted Swarm again after a pass could not finish it: newly due ones go first (purge.ts).+ purgeRetryAt DateTime?createdAt DateTime @default(now())updatedAt DateTime @updatedAt+ /// Deleted Swarms whose grace is over, oldest first: the purge sweep's read (superTabs/deletion.ts).+ @@index([purgeAt], map: "swarm_deleted_purge")@@index([autonomousEnv, workspaceId])/// An owner's Swarms in id order: the grid poll names it (superTabs/parts/indexed.ts NAMED_INDEX.SuperTab.owner).@@index([autonomousEnv, ownerId, id])diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex baa0c8b1f..2f93201b6 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -353,6 +353,8 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suconst page = (title: string, text: string, status = 200) => reply.status(status).type('text/html; charset=utf-8').send(githubPage(title, text))const request = approvalSecret && req.query.state ? readState(approvalSecret, req.query.state, Date.now()) : nullif (!request) return page('This link has expired', 'Go back to Harness and choose Continue in GitHub again.', 400)+ // A Swarm deleted since the link was made allows nothing, and says so as an expired link does (superTabs/deletion.ts).+ if (!await store.isLive(request.tabId)) return page('This link has expired', 'Go back to Harness and choose Continue in GitHub again.', 400)const named = githubRepository(`https://github.com/${request.repository}`)// Cancel on GitHub's sign-in sends the person back with `error` and no code: they were told Harness was installed// (local Team account run, 2026-10-28).@@ -405,6 +407,8 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Body: z.infer<typeof create> }>('/api/super-tabs', { preHandler: validateBody(create) },(req, reply) => respond(reply, () => store.create(req.user!, req.body.operationId, req.body.name, req.body.projectVisibility, req.body.workspaceId)))// Workspaces (docs/plans/2026-10-27-swarm-workspaces.md): the person's Workspaces and the Swarms they may see in each.+ // The owner's deleted Swarms they can still restore (superTabs/deletion.ts); restoring is the swarm.restore command.+ app.get('/api/super-tabs/deleted', (req, reply) => respond(reply, () => store.deletedList(req.user!)))app.get('/api/super-tabs/workspaces', (req, reply) => respond(reply, () => store.workspaceList(req.user!)))app.post<{ Body: z.infer<typeof workspaceCreate> }>('/api/super-tabs/workspaces', { preHandler: validateBody(workspaceCreate) },(req, reply) => respond(reply, () => { personOnly(req.user!); return store.workspaces.create(req.user!, req.body.operationId, req.body.name) }))diff --git a/backend/src/superTabs/archive.ts b/backend/src/superTabs/archive.tsindex 53d239d30..8b9af9158 100644--- a/backend/src/superTabs/archive.ts+++ b/backend/src/superTabs/archive.ts@@ -73,7 +73,11 @@ export async function markFinishedGroups(db: PrismaClient): Promise<number> {export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperTabStore, 'archiveFinished'>, prs: PullRequests, now: number): Promise<number> {const tidy = new Map<string, boolean>()const tidyOn = async (tabId: string) => {- if (!tidy.has(tabId)) tidy.set(tabId, ((await db.swarmHead.findUnique({ where: { id: `${tabId}:head` } }))?.data as unknown as HeadData | undefined)?.tidy !== false)+ // A deleted Swarm (deletion.ts) is left alone: none of its pull requests is read.+ if (!tidy.has(tabId)) {+ const head = (await db.swarmHead.findUnique({ where: { id: `${tabId}:head` } }))?.data as unknown as HeadData | undefined+ tidy.set(tabId, head?.tidy !== false && !head?.deletion)+ }return tidy.get(tabId)!}// One read per pull request a pass, however many groups link it.diff --git a/backend/src/superTabs/chatSettings.ts b/backend/src/superTabs/chatSettings.tsindex b9ac7e8ae..1339efc11 100644--- a/backend/src/superTabs/chatSettings.ts+++ b/backend/src/superTabs/chatSettings.ts@@ -77,9 +77,10 @@ export async function sweepChatSettings(db: PrismaClient, now: number): Promise<Array<{ _id: string }>let lost = 0for (const { _id: tabId } of tabs) {- const [row] = await readBy(db, 'SuperTab', 'id', [{ $match: { _id: tabId } }, { $project: { memberIds: 1 } }])+ const [row] = await readBy(db, 'SuperTab', 'id', [{ $match: { _id: tabId } }, { $project: { memberIds: 1, deletedAt: 1 } }])if (!row) lost += await deleteWhere(db, { tabId })- else if (Array.isArray(row.memberIds)) lost += await deleteWhere(db, { tabId, personId: { $nin: row.memberIds as string[] } })+ // A deleted Swarm lists nobody while it can be restored (deletion.ts): its settings come back with it; its purge removes them.+ else if (Array.isArray(row.memberIds) && !row.deletedAt) lost += await deleteWhere(db, { tabId, personId: { $nin: row.memberIds as string[] } })}return { expired, lost }}diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 6c7453e51..27958b717 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -17,6 +17,7 @@ import { checkMentions, MAX_MENTIONS, namedIn, saysName, textTags, withTags, typimport { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'import { leadOf, TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest } from './terminal.js'import { leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, waitingForReview } from './liveness.js'+import { DELETED_SWARM_COMMANDS, isPersonalSwarm, notThere, SWARM_DELETE_GRACE_MS } from './deletion.js'import { ABANDONED, askedModel, coordinatorCopy, failureNotice, failureRecipients, MACHINE_REMOVED } from './startFailure.js'import { noteStartFailed, noteStartSucceeded, resumeEngine } from './engineHealth.js'import { reviewCapacityNotice } from './reviewCapacity.js'@@ -129,6 +130,9 @@ export const commandSchema = z.discriminatedUnion('type', [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(),+ // The owner types the Swarm's name to confirm (deletion.ts); the server checks it too, so no client deletes by a slip.+ z.object({ type: z.literal('swarm.delete'), name: z.string().max(160) }).strict(),+ z.object({ type: z.literal('swarm.restore') }).strict(),z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSaveSchema.nullable() }).strict(),z.object({ type: z.literal('tab.tidy'), enabled: z.boolean(), askedIn: askedInSchema.optional() }).strict(),z.object({ type: z.literal('rule.set'), projectId: id.optional(), rule: ruleSchema, text: ruleTextSchema, askedIn: askedInSchema.optional() }).strict(),@@ -348,6 +352,11 @@ export interface CommandContext {confidentialSession?: boolean/** For a command that registers a session or can make one confidential: the other Swarms' registrations (confidential.ts). */registrations?: import('./projects.js').OtherRegistrations+ /** A Workspace removal taking the person out of this Swarm (workspaceStore.ts): it reaches a deleted Swarm too, so a restore+ * never brings them back (security review 2 of #2457). Set by the store alone. */+ workspaceLeave?: true+ /** For a restore: the people no longer in the Swarm's Workspace, read by the store. They do not come back with it. */+ workspaceLost?: string[]/** The machines of this Swarm's pending cleanups whose machine account is deleted, read by the store: no host will ever* confirm those cleanups (Ken's remote-deepseek and WIN-DELL, 2026-10-28), so they go. */deletedMachineIds?: string[]@@ -540,6 +549,8 @@ const SWARM_BUDDY_CHAT_COMMANDS: ReadonlySet<string> = new Set(['message.send',export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return+ // The owner's alone, checked where they apply: everyone else, a viewer too, gets the answer a missing Swarm gets (deletion.ts).+ if (command.type === 'swarm.delete' || command.type === 'swarm.restore') return// Marking one's own tag done changes only one's own list, so a viewer may do it too.// Answering a decision asked of oneself changes only that decision, so a viewer may do it too.// So does choosing one's own username (usernames.ts).@@ -674,6 +685,24 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst effects: CommandEffects = { state, messages: ended, cancelledAgents: [], previousAttempts: [], routeDecisions: [], result }const operationId = stableId(state.id, actorKey(actor), context.operationId)+ // A deleted Swarm (deletion.ts) takes only its hosts' confirmations and its owner's restore; anything else, from anyone,+ // answers as for a Swarm that does not exist. The store refuses before this; this holds for every other caller.+ if (state.deletion && !DELETED_SWARM_COMMANDS.has(command.type) && !(context.workspaceLeave && command.type === 'member.remove')) notThere()+ if (command.type === 'swarm.restore') {+ // Only its owner, only while deleted and before its purge; anyone else learns nothing, not even that it was deleted.+ if (!state.deletion || actor.kind !== 'person' || actor.userId !== state.ownerId || Date.parse(state.deletion.purgeAt) <= context.now) notThere()+ delete state.deletion+ // Whoever left the Workspace meanwhile stays out: the Workspace removal could not take them out of a deleted Swarm's list.+ const lost = new Set((context.workspaceLost ?? []).filter(id => id !== state.ownerId))+ if (lost.size) {+ const emails = new Set(state.people.filter(p => lost.has(p.id)).map(p => p.email))+ state.people = state.people.filter(p => !lost.has(p.id))+ state.invitations = state.invitations.filter(i => !emails.has(i.email))+ }+ result.restored = true+ return effects+ }+// Acceptance is the only operation a non-member can perform; the verified account email owns the invite.if (command.type === 'invite.accept') {if (actor.kind !== 'person') fail('FORBIDDEN', 'A person must accept this invitation.', 403)@@ -695,7 +724,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// 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)+ && actor.kind === 'person' && c.machineOwnerId === actor.userId) ?? (state.deletion ? notThere() : 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@@ -706,7 +735,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma&& actor.kind === 'person' && ownerId === actor.userIdconst 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)+ // Of a deleted Swarm, only a host with a cleanup waiting learns it exists (deletion.ts).+ if (!pool && !cleanup) state.deletion ? notThere() : fail('NOT_FOUND', 'This machine has no cleanup waiting.', 404)// One that already left the list said why then.if (pool) effects.messages.push(...removalEnded(state, pool, 'confirmed'))state.machines = state.machines?.filter(m => m !== pool)@@ -724,6 +754,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commareturn effects}+ // Before any role check: a viewer or an agent is told what anyone without the Swarm is told (deletion.ts).+ if (command.type === 'swarm.delete' && (actor.kind !== 'person' || actor.userId !== state.ownerId)) notThere()const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userIdconst sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username')authorizeCommandAccess(state, actor, command, context)@@ -1146,7 +1178,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma* like one agent, its pending starts fail, routing rules lose it, and a contributed machine stays paused and cleaning* until its host deletes the Swarm's folders there — or leaves at once when that host is offline* (spec 2026-10-23-remove-machine.md). */- const removeMachine = (machineId: string, pool: ContributedMachine | undefined, members: Agent[], how: (machine: string) => string) => {+ const removeMachine = (machineId: string, pool: ContributedMachine | undefined, members: Agent[], how: (machine: string) => string, lead = false) => {const pending = state.starts?.filter(s => s.request.machineId === machineId && !s.harnessId && !s.error) ?? []// A launch already under way would arrive with nowhere to go; it finishes in moments.if (pending.some(s => s.dispatched)) fail('STARTS_PENDING', 'An agent is starting on this machine. Try again in a moment.')@@ -1160,7 +1192,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma|| (group.leadId && removed.has(group.leadId)) || (group.assignment && removed.has(group.assignment.agentId))).map(group => ({ group, names: members.filter(a => group.agentIds.includes(a.id) || group.leadId === a.id || group.assignment?.agentId === a.id).map(a => a.displayName ?? a.name), task: !!group.assignment && removed.has(group.assignment.agentId) && activeWork(group) }))- for (const target of members) removeAgent(target)+ for (const target of members) removeAgent(target, { lead })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() }@@ -1597,6 +1629,25 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (actor.kind === 'agent') coordinatorOrPerson(state, actor)state.paused = command.pausedbreak+ case 'swarm.delete': {+ // Its owner alone; a member, an agent or anyone else is answered as for a Swarm that does not exist (deletion.ts).+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) notThere()+ if (isPersonalSwarm(state)) fail('PERSONAL_SWARM', 'Your Personal Swarm cannot be deleted.', 409)+ if (command.name.trim() !== state.name.trim()) fail('NAME_MISMATCH', 'Type the Swarm\'s name exactly to delete it.', 400)+ // A launch already under way would arrive with nowhere to go; it finishes in moments (removeMachine says the same).+ if (state.starts?.some(s => s.dispatched && !s.harnessId && !s.error)) fail('STARTS_PENDING', 'An agent is starting in this Swarm. Try again in a moment.')+ // Every machine leaves as its owner removing it would: its agents' sessions close and its host deletes the Swarm's+ // folders there. Product Managers go too. A Buddy-only machine goes once its Buddy has (dropIdleBuddyMachines).+ for (const pool of (state.machines ?? []).filter(m => !m.removal && !m.buddyOnly)) {+ removeMachine(pool.machineId, pool, state.agents.filter(a => a.machineId === pool.machineId), machine => `${machine} left the Swarm when it was deleted`, true)+ }+ // Agents on no contributed machine (shared sessions, Buddies), each with its session.+ for (const target of [...state.agents]) if (state.agents.some(a => a.id === target.id)) removeAgent(target, { lead: true })+ for (const start of state.starts ?? []) if (!start.harnessId && !start.error) start.error = 'Its Swarm was deleted.'+ state.deletion = { at: new Date(context.now).toISOString(), by: actor.userId, purgeAt: new Date(context.now + SWARM_DELETE_GRACE_MS).toISOString() }+ result.purgeAt = state.deletion.purgeAt+ break+ }case 'tab.tidy': {swarmOwnerAsked(command.askedIn, 'turns tidying on or off')if (command.enabled) delete state.tidy@@ -2853,7 +2904,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: CommaalertOverlaps(conversation(state, command.type === 'conversation.create' ? result.conversationId as string : command.conversationId))}for (const target of original.agents.filter(a => a.workDecision === 'stop')) {- const acknowledged = command.type === 'agent.remove' && command.agentId === target.id &&+ const acknowledged = command.type === 'swarm.delete' || command.type === 'agent.remove' && command.agentId === target.id &&(actor.kind === 'agent' && actor.agentId === target.id || actor.kind === 'person' && [state.ownerId, target.contributorId].includes(actor.userId))if (!acknowledged && !state.agents.some(a => a.id === target.id)) fail('STOP_REQUESTED', 'Wait for the execution host to finish stopping its workers before withdrawing them.')}diff --git a/backend/src/superTabs/deletion.test.ts b/backend/src/superTabs/deletion.test.tsnew file mode 100644index 000000000..bf1919629--- /dev/null+++ b/backend/src/superTabs/deletion.test.ts@@ -0,0 +1,211 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { createSuperTab, stableId, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'+import { indexesOf } from './parts/commit.js'+import { touchesFor } from './parts/touches.js'+import { isPersonalSwarm, PERSONAL_SWARM_OPERATION, SWARM_DELETE_GRACE_MS } from './deletion.js'++// Deleting a Swarm (deletion.ts): its owner alone, everyone else answered as for a Swarm that does not exist; every agent and+// machine goes with it; it leaves every list in the same write; its owner can restore it during the grace, and nobody after.++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const viewer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'viewer', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const NOW = 1_000_000++function fixture(id = 'tab') {+ let state = createSuperTab(id, 'Lampos', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ const join = (who: Extract<Actor, { kind: 'person' }>, role: 'viewer' | 'collaborator') => {+ const invited = run({ type: 'invite.create', email: who.email, role, conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, who)+ }+ const add = (harnessId: string, machineId = 'host', lead = false) => run({ type: 'agent.add', conversationId: 'lead', machineId, harnessId, name: harnessId,+ configuration: config, lead }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId as string+ const contribute = (machineId = 'host') => {+ state.machines = [...(state.machines ?? []), { machineId, name: 'Studio', contributorId: 'owner', membershipGeneration: state.people[0]!.generation,+ generation: 'g1', cwd: '/repo', engines: ['claude'], maxAgents: 2, paused: false, observation: { generation: 'g1', receivedAt: NOW,+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,+ deviceType: null, chip: null, os: null, gpuPercent: null }, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] } } as never]+ }+ return { run, join, add, contribute, get state(): SuperTabState { return state }, set state(next: SuperTabState) { state = next } }+}++/** What applying [command] as [actor] threw, or 'applied'. */+const refusal = (f: ReturnType<typeof fixture>, command: Command, actor: Actor, context: Partial<CommandContext> = {}) => {+ try { f.run(command, actor, context); return 'applied' } catch (error) {+ const e = error as { code?: string; message: string; status?: number; unreachable?: boolean }+ return { code: e.code, message: e.message, status: e.status, unreachable: e.unreachable }+ }+}+const MISSING = { code: 'NOT_FOUND', message: 'This Super Tab is unavailable.', status: 404, unreachable: false }++describe('swarm.delete', () => {+ it('is its owner\'s alone: a collaborator, a viewer, an agent and a made-up agent are each answered as for a missing Swarm', () => {+ const f = fixture()+ f.join(peer, 'collaborator')+ f.join(viewer, 'viewer')+ const lead = f.add('lead', 'host', true)+ const del = { type: 'swarm.delete', name: 'Lampos' } as const+ for (const actor of [peer, viewer, { kind: 'agent', agentId: lead } as Actor, { kind: 'agent', agentId: 'made-up' } as Actor,+ { kind: 'person', userId: 'stranger', email: '[email protected]' } as Actor]) {+ expect(refusal(f, del, actor)).toEqual(MISSING)+ }+ expect(f.state.deletion).toBeUndefined()+ })++ it('needs the Swarm\'s exact name, and refuses the owner\'s Personal Swarm', () => {+ const f = fixture()+ expect(refusal(f, { type: 'swarm.delete', name: 'lampos' }, owner)).toMatchObject({ code: 'NAME_MISMATCH', status: 400 })+ expect(refusal(f, { type: 'swarm.delete', name: '' }, owner)).toMatchObject({ code: 'NAME_MISMATCH' })+ const personalId = stableId('super-tab', 'prod', 'owner', PERSONAL_SWARM_OPERATION)+ const personal = fixture(personalId)+ expect(isPersonalSwarm(personal.state)).toBe(true)+ expect(refusal(personal, { type: 'swarm.delete', name: 'Lampos' }, owner)).toMatchObject({ code: 'PERSONAL_SWARM', status: 409 })+ expect(personal.state.deletion).toBeUndefined()+ // Another person's Personal Swarm id is not this owner's: only the owner's own request derives it.+ expect(isPersonalSwarm({ ...personal.state, ownerId: 'peer' })).toBe(false)+ })++ it('stops every agent, its Product Manager too, and releases every machine to its host\'s cleanup in the same write', () => {+ const f = fixture()+ f.contribute('host')+ const lead = f.add('lead', 'host', true), worker = f.add('worker', 'host'), shared = f.add('shared', 'elsewhere')+ const effects = f.run({ type: 'swarm.delete', name: ' Lampos ' })+ expect(f.state.agents).toEqual([])+ expect(new Set(effects.cancelledAgents)).toEqual(new Set([lead, worker, shared]))+ // Each session is closed by its host, and the contributed machine stays listed only for its cleanup.+ expect(new Set(f.state.closingSessions!.map(c => c.agentId))).toEqual(new Set([lead, worker, shared]))+ expect(f.state.machines).toEqual([expect.objectContaining({ machineId: 'host', paused: true, removal: expect.objectContaining({ state: 'cleaning' }) })])+ expect(f.state.deletion).toEqual({ at: new Date(NOW).toISOString(), by: 'owner', purgeAt: new Date(NOW + SWARM_DELETE_GRACE_MS).toISOString() })+ expect(effects.result.purgeAt).toBe(f.state.deletion!.purgeAt)+ })++ it('fails starts not yet launched, and waits for one already launching', () => {+ const f = fixture()+ const start = (id: string, dispatched: boolean) => ({ id, creationId: 'c', actorKey: 'person:owner', contributorId: 'owner',+ membershipGeneration: f.state.people[0]!.generation, machineOwnerId: 'owner', hostGrant: null, ...(dispatched ? { dispatched: true } : {}),+ request: { conversationId: 'lead', machineId: 'host', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } }) as never+ f.state.starts = [start('queued', false), start('launching', true)]+ expect(refusal(f, { type: 'swarm.delete', name: 'Lampos' }, owner)).toMatchObject({ code: 'STARTS_PENDING' })+ f.state.starts = [start('queued', false)]+ f.run({ type: 'swarm.delete', name: 'Lampos' })+ expect(f.state.starts![0]!.error).toBe('Its Swarm was deleted.')+ })++ it('leaves every person\'s and invitee\'s lists in the same write, and keeps its machines indexed for their cleanup', () => {+ const f = fixture()+ f.join(peer, 'collaborator')+ f.run({ type: 'invite.create', email: '[email protected]', role: 'viewer', conversationId: 'lead' })+ f.contribute('host')+ f.add('worker', 'host')+ expect(indexesOf(f.state)).toMatchObject({ memberIds: ['owner', 'peer'], invitedEmails: ['[email protected]'], deletedAt: null, purgeAt: null })+ f.run({ type: 'swarm.delete', name: 'Lampos' })+ expect(indexesOf(f.state)).toMatchObject({ memberIds: [], invitedEmails: [], machineIds: ['host'], cleanupMachineIds: ['host'],+ deletedAt: new Date(NOW), purgeAt: new Date(NOW + SWARM_DELETE_GRACE_MS) })+ // People and invitations are kept, for a restore; only the index stops naming them.+ expect(f.state.people.map(p => p.id)).toEqual(['owner', 'peer'])+ })+})++describe('a write racing the delete', () => {+ it('meets it: the delete moves every person\'s part, which each person\'s own write relies on', () => {+ const f = fixture()+ f.join(peer, 'collaborator')+ f.join(viewer, 'viewer')+ const before = f.state+ const effects = f.run({ type: 'swarm.delete', name: 'Lampos' })+ const touched = touchesFor({ type: 'swarm.delete', name: 'Lampos' }, owner, before, effects).filter(t => t.kind === 'member').map(t => t.key)+ expect(new Set(touched)).toEqual(new Set(['owner', 'peer', 'viewer']))+ })+})++describe('a deleted Swarm', () => {+ const deleted = () => {+ const f = fixture()+ f.join(peer, 'collaborator')+ f.contribute('host')+ f.add('worker', 'host')+ f.run({ type: 'swarm.delete', name: 'Lampos' })+ return f+ }++ it('answers every other command, from anyone, its owner too, as a missing Swarm does', () => {+ const f = deleted()+ const commands: Command[] = [{ type: 'message.send', conversationId: 'lead', text: 'hello', replyTo: null, recipientIds: [] },+ { type: 'tab.rename', name: 'Back' }, { type: 'swarm.delete', name: 'Lampos' }, { type: 'invite.create', email: '[email protected]', role: 'viewer', conversationId: 'lead' },+ { type: 'project.create', name: 'New', visibility: 'public', brief: '' } as Command]+ for (const command of commands) for (const actor of [owner, peer]) expect(refusal(f, command, actor)).toEqual(MISSING)+ // An invitation sent before the deletion cannot be accepted either.+ const g = fixture()+ const invite = g.run({ type: 'invite.create', email: peer.email, role: 'viewer', conversationId: 'lead' }).result.inviteId as string+ g.run({ type: 'swarm.delete', name: 'Lampos' })+ expect(refusal(g, { type: 'invite.accept', inviteId: invite }, peer)).toEqual(MISSING)+ })++ it('still takes its hosts\' close and cleanup confirmations, so their agents stop and folders go', () => {+ const f = deleted()+ const closing = f.state.closingSessions![0]!+ f.run({ type: 'agent.sessionClosed', agentId: closing.agentId, harnessId: closing.harnessId } as Command, owner)+ expect(f.state.closingSessions ?? []).toEqual([])+ const removal = f.state.machines![0]!.removal!+ f.run({ type: 'machine.cleaned', machineId: 'host', removalId: removal.id }, owner)+ expect(f.state.machines ?? []).toEqual([])+ expect(indexesOf(f.state)).toMatchObject({ machineIds: [], cleanupMachineIds: [], memberIds: [] })+ })++ it('is restored by its owner alone, during the grace: people, chats and projects come back, without agents or machines', () => {+ const f = deleted()+ for (const actor of [peer, { kind: 'agent', agentId: 'made-up' } as Actor, { kind: 'person', userId: 'stranger', email: '[email protected]' } as Actor]) {+ expect(refusal(f, { type: 'swarm.restore' }, actor)).toEqual(MISSING)+ }+ expect(f.run({ type: 'swarm.restore' }, owner).result).toEqual({ restored: true })+ expect(f.state.deletion).toBeUndefined()+ expect(f.state.agents).toEqual([])+ expect(indexesOf(f.state)).toMatchObject({ memberIds: ['owner', 'peer'], deletedAt: null, purgeAt: null })+ expect(f.state.conversations.some(c => c.id === 'lead')).toBe(true)+ // Live again: it takes commands as before.+ f.run({ type: 'tab.rename', name: 'Lampos again' })+ // And a live Swarm has nothing to restore: answered as missing, telling nothing.+ expect(refusal(f, { type: 'swarm.restore' }, owner)).toEqual(MISSING)+ })++ it('answers a host whose close or cleanup is not waiting as a missing Swarm, never "nothing waiting"', () => {+ const f = deleted()+ expect(refusal(f, { type: 'agent.sessionClosed', agentId: 'made-up', harnessId: 'h' } as Command, owner)).toEqual(MISSING)+ expect(refusal(f, { type: 'machine.cleaned', machineId: 'other', removalId: 'r' }, owner)).toEqual(MISSING)+ // A live Swarm still says what is not waiting.+ const live = fixture()+ expect(refusal(live, { type: 'machine.cleaned', machineId: 'other', removalId: 'r' }, owner)).toMatchObject({ code: 'NOT_FOUND', message: 'This machine has no cleanup waiting.' })+ })++ it('leaves out of a restore whoever the store read as no longer in the Workspace, never its owner', () => {+ const f = deleted()+ f.run({ type: 'swarm.restore' }, owner, { workspaceLost: ['peer', 'owner'] })+ expect(f.state.people.map(p => p.id)).toEqual(['owner'])+ expect(indexesOf(f.state).memberIds).toEqual(['owner'])+ })++ it('lets a Workspace removal take a person out of it, and nothing else', () => {+ const f = deleted()+ expect(refusal(f, { type: 'member.remove', userId: 'peer' }, peer)).toEqual(MISSING)+ f.run({ type: 'member.remove', userId: 'peer' }, peer, { workspaceLeave: true })+ expect(f.state.people.map(p => p.id)).toEqual(['owner'])+ expect(f.state.deletion).toBeDefined()+ })++ it('cannot be restored once its grace is over', () => {+ const f = deleted()+ expect(refusal(f, { type: 'swarm.restore' }, owner, { now: NOW + SWARM_DELETE_GRACE_MS })).toEqual(MISSING)+ expect(f.state.deletion).toBeDefined()+ f.run({ type: 'swarm.restore' }, owner, { now: NOW + SWARM_DELETE_GRACE_MS - 1 })+ expect(f.state.deletion).toBeUndefined()+ })+})diff --git a/backend/src/superTabs/deletion.ts b/backend/src/superTabs/deletion.tsnew file mode 100644index 000000000..50d8a40a6--- /dev/null+++ b/backend/src/superTabs/deletion.ts@@ -0,0 +1,50 @@+import type { Prisma, PrismaClient } from '@prisma/client'+import { fail, stableId, type SuperTabState } from './model.js'+import { readBy } from './parts/indexed.js'++// Deleting a Swarm (Dee, 10-31: "owners can delete a Swarm, like deleting a Slack workspace").+//+// `swarm.delete` (commands.ts), by its owner alone, removes every agent with its session and every machine with the Swarm's+// folders there, as removing them one by one does, and marks the state deleted. In the same write its index row lists no+// member and no invitation (parts/commit.ts indexesOf), so it leaves every person's lists at once, and every read and write+// answers as for a Swarm that does not exist (store.ts row). Its machines' hosts still read what they must close and clean+// up, through the machine index, which stays until they have. Its owner can restore it (`swarm.restore`) until `purgeAt`:+// people, projects, chats and files come back, without agents or machines. After that the sweep (purge.ts) removes its+// records and stored files, and only its own.++/** How long a deleted Swarm can be restored before it is purged. */+export const SWARM_DELETE_GRACE_MS = 7 * 24 * 60 * 60 * 1000++/** The request id Desktop creates the person's Personal Swarm with (desktop super_tabs/swarm_switcher.dart). */+export const PERSONAL_SWARM_OPERATION = 'personal-swarm'++/** The owner's Personal Swarm: its id is derived from the owner and the Personal request (store.ts create). */+export const isPersonalSwarm = (state: Pick<SuperTabState, 'id' | 'environment' | 'ownerId'>): boolean =>+ state.id === stableId('super-tab', state.environment, state.ownerId, PERSONAL_SWARM_OPERATION)++/** What a caller who may not delete or restore this Swarm is told: word for word what the store tells about a Swarm that+ * does not exist (store.ts row), so nobody learns from a refusal whether it exists or was deleted. */+export function notThere(): never {+ return fail('NOT_FOUND', 'This Super Tab is unavailable.', 404)+}++/** Commands that delete or restore the whole Swarm: whoever is refused on the way, for any reason, is told `notThere`. */+export const DELETION_COMMANDS: ReadonlySet<string> = new Set(['swarm.delete', 'swarm.restore'])++/** Commands a deleted Swarm still takes: its machines' hosts confirming the closes and cleanups its deletion asked for, and+ * its owner restoring it. Everything else answers as for a Swarm that does not exist. */+export const DELETED_SWARM_COMMANDS: ReadonlySet<string> = new Set(['agent.sessionClosed', 'machine.cleaned', 'swarm.restore'])++/** For one pass of a background job: whether each Swarm it meets is deleted, read once per Swarm by its id. A deleted Swarm+ * waits for its restore or its purge untouched: no group sleeps, no start expires, no pull request is read for it. */+export function deletedSwarms(db: PrismaClient | Prisma.TransactionClient): (tabId: string) => Promise<boolean> {+ const known = new Map<string, Promise<boolean>>()+ return tabId => {+ let deleted = known.get(tabId)+ if (!deleted) {+ deleted = readBy(db, 'SuperTab', 'id', [{ $match: { _id: tabId } }, { $project: { deletedAt: 1 } }]).then(([row]) => !!row?.deletedAt)+ known.set(tabId, deleted)+ }+ return deleted+ }+}diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex bdbcda53d..b7efe05ba 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -397,6 +397,9 @@ export interface SuperTabState {/** Owner-only sharing configuration; visibleState always removes it. */sharing?: import('./sharing.js').SwarmSharingpaused: boolean+ /** Its owner deleted it (deletion.ts): nobody reads or writes it, its row lists no member, and its owner may restore it until+ * `purgeAt` (ISO times). Absent on a live Swarm. */+ deletion?: { at: string; by: string; purgeAt: string }/** Idle workers stop and finished groups archive by themselves (tidy.ts); false once the owner turns it off. */tidy?: false/** Buddies (buddies.ts) are on in every Swarm; readers are always told so (visibleState), as apps from before 10-29 hidediff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.tsindex dba0f4baf..3b38c5082 100644--- a/backend/src/superTabs/parts/commit.ts+++ b/backend/src/superTabs/parts/commit.ts@@ -73,8 +73,12 @@ export function visibilityChanged(before: SuperTabState, after: SuperTabState):/** The Swarm's index row (SuperTab): what hosts, invitations and member lists are looked up by (design section 2.3). */export function indexesOf(state: SuperTabState) {+ // A deleted Swarm (deletion.ts) lists nobody and is invited to by nobody, so it leaves every person's lists in this write; its+ // machines stay indexed until their hosts have closed its sessions and cleaned up.+ const deletion = state.deletionreturn {- memberIds: state.people.map(p => p.id), invitedEmails: state.invitations.map(i => i.email),+ memberIds: deletion ? [] : state.people.map(p => p.id), invitedEmails: deletion ? [] : state.invitations.map(i => i.email),+ deletedAt: deletion ? new Date(deletion.at) : null, purgeAt: deletion ? new Date(deletion.purgeAt) : null,machineIds: [...new Set([...state.agents.map(a => a.machineId), ...(state.machines ?? []).map(m => m.machineId),...(state.closingSessions ?? []).map(c => c.machineId), ...(state.machineCleanups ?? []).map(c => c.machineId)])],cleanupMachineIds: [...new Set([...(state.machines ?? []).flatMap(m => m.removal ? [m.machineId] : []),diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex e50d304cd..8f2b2d2d6 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -41,6 +41,10 @@ export const NAMED_INDEX = {cleanup: { autonomousEnv: 1, cleanupMachineIds: 1, updatedAt: 1 },/** Swarms by id. */id: { _id: 1 },+ /** A Workspace's Swarms: a Workspace removal reads its deleted ones (workspaceStore.ts). */+ workspace: { autonomousEnv: 1, workspaceId: 1 },+ /** Deleted Swarms by purge time (deletion.ts): the purge sweep. */+ purge: { purgeAt: 1 },},/** Each part kind's changes since a cursor; machines also by when they were last read. */SwarmHead: { changes: { tabId: 1, changedAt: 1 } },diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex e5a0a7d10..931fae723 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -50,6 +50,11 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatefor (const buddy of buddiesHearing(effects.state, effects.messages)) { agent(buddy.id); member(buddy.buddyOf!.personId) }switch (command.type) {+ // Every person's write relies on the Swarm not being deleted (deletion.ts): the delete moves each person's part, so one+ // landing at the same moment retries against it and is refused (security review 2 of #2457).+ case 'swarm.delete':+ for (const person of before.people) member(person.id)+ breakcase 'tab.rename': case 'tab.project': case 'tab.pause':if (actor.kind === 'agent') group('lead')breakdiff --git a/backend/src/superTabs/purge.ts b/backend/src/superTabs/purge.tsnew file mode 100644index 000000000..4a6ba5662--- /dev/null+++ b/backend/src/superTabs/purge.ts@@ -0,0 +1,137 @@+import type { PrismaClient } from '@prisma/client'+import { logger } from '../utils/logger.js'+import { AVATAR_PURPOSE, attachmentsFromEnv, CdnAvatarStore, errorCode, trimPrefix, type Attachments, type AttachmentStore } from './attachments.js'+import { readBy } from './parts/indexed.js'+import { ms } from './parts/light.js'++// The purge of deleted Swarms whose grace is over (deletion.ts). Each goes in three steps, so a pass that stops anywhere is+// finished by the next one: its stored files with their attachment records, then every other record of it, and its row last.+// It touches only records that carry its id and files inside its own folders.++/** Past its purge time by this much before it goes: an owner's restore can no longer be in flight on a slower clock. */+export const PURGE_MARGIN_MS = 60 * 60 * 1000+export const PURGE_SWEEP = { everyMs: 60 * 60 * 1000, swarms: 20, files: 200 } as const+/** How long a Swarm the purge could not finish waits before it is tried again, so it never holds back the others. */+export const PURGE_RETRY_MS = 6 * 60 * 60 * 1000++/** The records of one Swarm, each by its Swarm id (every one has an index led by it, schema.prisma). Attachments are+ * removed apart, with their files. */+export const PURGED_BY_TAB_ID = ['superTabMessage', 'superTabMention', 'superTabReaction', 'superTabActivity', 'superTabChatSetting', 'superTabReadMark',+ 'superTabThreadMark', 'superTabThread', 'superTabDecision', 'superTabOperation', 'superTabNativeContext', 'superTabDelivery', 'superTabReceipt',+ 'superTabRun', 'superTabAttempt', 'superTabRouteDecision', 'superTabModelEvidence', 'superTabModelRecent', 'superTabStopReceipt',+ 'superTabRoleText', 'superTabInstructions', 'superTabInstructionsRevision', 'superTabPmNote', 'superTabConfiguration', 'superTabTerminalRequest',+ 'gitHubRepositoryApproval', 'gitHubApprovalRefusal', 'swarmHead', 'swarmMember', 'swarmGroup', 'swarmAgent', 'swarmMachine', 'swarmStart',+ 'swarmProgress'] as const++/** Removes one stored object; one already gone counts as removed. */+export interface FileRemover { delete(objectKey: string): Promise<void> }+/** Where a Swarm's files are and how each goes: chat files in `prefix/<tabId>/`, avatars in `avatarPrefix/<tabId>/`. */+export interface PurgeFiles { chat: FileRemover | null; prefix: string; avatars: FileRemover | null; avatarPrefix: string }++const removerOf = (store: AttachmentStore | null | undefined): FileRemover | null => {+ if (!store) return null+ if (store instanceof CdnAvatarStore) return removerOf(store.store)+ return 'delete' in store && typeof store.delete === 'function' ? store as unknown as FileRemover : null+}+export function purgeFiles(attachments: Attachments | null): PurgeFiles | null {+ if (!attachments) return null+ return { chat: removerOf(attachments.store), prefix: trimPrefix(attachments.prefix), avatars: removerOf(attachments.avatars ?? null),+ avatarPrefix: trimPrefix(attachments.avatarPrefix ?? attachments.prefix) }+}++const folder = (prefix: string, tabId: string) => [prefix, tabId].filter(Boolean).join('/') + '/'++/** Its stored files, then their records, a page at a time. False when a file could not be removed: the pass stops there and+ * the next one carries on, its record kept so it is found again. */+async function purgeAttachments(db: PrismaClient, tabId: string, files: PurgeFiles | null, page: number): Promise<boolean> {+ for (;;) {+ const rows = await db.superTabAttachment.findMany({ where: { tabId }, select: { id: true, objectKey: true, purpose: true }, take: page })+ for (const row of rows) {+ const avatar = row.purpose === AVATAR_PURPOSE+ const remover = files ? avatar ? files.avatars : files.chat : null+ const own = files ? row.objectKey.startsWith(folder(avatar ? files.avatarPrefix : files.prefix, tabId)) : false+ // A key outside this Swarm's folder is never another's to remove from here: its record goes, the object stays.+ if (remover && own) {+ try { await remover.delete(row.objectKey) } catch (error) {+ logger.warn('[swarm-purge] a stored file could not be removed yet', { tabId, id: row.id, code: errorCode(error) })+ return false+ }+ } else if (files && !own) logger.warn('[swarm-purge] an attachment outside its Swarm\'s folder was left in storage', { tabId, id: row.id })+ // By id without reading it back: a record missing a field never stalls the purge.+ await db.superTabAttachment.deleteMany({ where: { id: row.id } })+ }+ if (rows.length < page) return true+ }+}++/** Purges one deleted Swarm past its grace: `skipped` when it is not due or not deleted, `waiting` when files remain for a+ * later pass. */+export async function purgeSwarm(db: PrismaClient, tabId: string, files: PurgeFiles | null, now: number,+ page: number = PURGE_SWEEP.files): Promise<'purged' | 'skipped' | 'waiting'> {+ const row = await db.superTab.findUnique({ where: { id: tabId }, select: { deletedAt: true, purgeAt: true } })+ // Restored, or not yet due: nothing of it goes.+ if (!row?.deletedAt || !row.purgeAt || row.purgeAt.getTime() + PURGE_MARGIN_MS > now) return 'skipped'+ if (!await purgeAttachments(db, tabId, files, page)) return 'waiting'+ for (const model of PURGED_BY_TAB_ID) {+ await (db[model] as unknown as { deleteMany(args: { where: { tabId: string } }): Promise<unknown> }).deleteMany({ where: { tabId } })+ }+ // Its thread backfill marker, kept by its own id (threadBackfill.ts).+ await db.superTabThreadBackfill.deleteMany({ where: { id: tabId } })+ // Harness shares made for this Swarm (its members' read-only views of agents' terminals).+ await db.harnessShare.deleteMany({ where: { superTabId: tabId } })+ // Last, and only while it is still the deletion this pass read: a later pass finds nothing left of it.+ await db.superTab.deleteMany({ where: { id: tabId, purgeAt: row.purgeAt } })+ return 'purged'+}++/** One pass: deleted Swarms past their grace, by the purge index; never tried first, then those whose retry is due, oldest+ * first. One the pass cannot finish is tried again PURGE_RETRY_MS later, so a few that keep failing never hold back the rest+ * (security review 2 of #2457). */+export async function purgeDeletedSwarms(db: PrismaClient, files: PurgeFiles | null, now: number, limit: number = PURGE_SWEEP.swarms) {+ const at = (time: number) => ({ $date: new Date(time).toISOString() })+ const due = await readBy(db, 'SuperTab', 'purge', [{ $match: { purgeAt: { $lte: at(now - PURGE_MARGIN_MS) },+ $or: [{ purgeRetryAt: null }, { purgeRetryAt: { $lte: at(now) } }] } },+ { $sort: { purgeRetryAt: 1, purgeAt: 1 } }, { $limit: limit }, { $project: { purgeAt: 1 } }])+ let purged = 0, waiting = 0+ const later = async (tabId: string) => {+ await db.superTab.updateMany({ where: { id: tabId }, data: { purgeRetryAt: new Date(now + PURGE_RETRY_MS) } }).catch(() => undefined)+ }+ for (const row of due) {+ const tabId = row._id as string+ try {+ const done = await purgeSwarm(db, tabId, files, now)+ if (done === 'purged') purged+++ if (done === 'waiting') { waiting++; await later(tabId) }+ } catch (error) {+ waiting+++ await later(tabId)+ logger.warn('[swarm-purge] a deleted Swarm could not be purged yet', { tabId, purgeAt: ms(row.purgeAt), code: errorCode(error) })+ }+ }+ return { purged, waiting }+}++/** Runs the purge in the worker every hour. Without a bucket, a Swarm has no stored files, and its records still go. */+export function startSwarmPurge(db: PrismaClient, env: Parameters<typeof attachmentsFromEnv>[0], now: () => number = Date.now): () => void {+ let files: PurgeFiles | null+ try { files = purgeFiles(attachmentsFromEnv(env)) } catch (error) {+ // Invalid settings could leave files behind for good: purge nothing until they are fixed.+ logger.warn('[swarm-purge] off: the attachment settings are invalid', { error: error instanceof Error ? error.message : String(error) })+ return () => {}+ }+ let running = false+ const pass = async () => {+ if (running) return+ running = true+ try {+ const result = await purgeDeletedSwarms(db, files, now())+ if (result.purged || result.waiting) logger.info('[swarm-purge] pass', result)+ } catch (error) {+ logger.warn('[swarm-purge] pass failed', { code: errorCode(error) })+ } finally { running = false }+ }+ void pass()+ const timer = setInterval(() => void pass(), PURGE_SWEEP.everyMs)+ timer.unref()+ return () => clearInterval(timer)+}diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex 329844537..5566abf90 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -374,8 +374,9 @@ export class SwarmReads {* first, as a safety net for one the job did not see (design 6.1), and answers 503 while that cannot be done. */private async read<T>(user: AuthUser, tabId: string, body: (tx: PrismaClient, view: CacheView) => Promise<T>): Promise<T> {// The row's format only: a migrated row still holds its old state, as large as the Swarm, until the owner drops it.- const row = await this.db.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: { format: true } })- if (!row) fail('NOT_FOUND', 'This Super Tab is unavailable.', 404)+ const row = await this.db.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: { format: true, deletedAt: true } })+ // A deleted Swarm reads as one that does not exist (deletion.ts).+ if (!row || row.deletedAt) fail('NOT_FOUND', 'This Super Tab is unavailable.', 404)if (row.format !== 2 && !(await migrateSwarm(this.db, tabId)).ok) fail(SWARM_MIGRATING.code, SWARM_MIGRATING.message, SWARM_MIGRATING.status)return body(this.db, await this.store.view([tabId]))}diff --git a/backend/src/superTabs/readMarks.ts b/backend/src/superTabs/readMarks.tsindex de1ce0648..6dd2a7615 100644--- a/backend/src/superTabs/readMarks.ts+++ b/backend/src/superTabs/readMarks.ts@@ -207,10 +207,11 @@ export async function sweepThreadMarks(db: PrismaClient, now: number, options: {// Past the last Swarm: the next pass starts again from the first.if (tabId === null) { await moveTo(''); break }swarmsChecked++- const [row] = await readBy(db, 'SuperTab', 'id', [{ $match: { _id: tabId } }, { $project: { memberIds: 1 } }])+ const [row] = await readBy(db, 'SuperTab', 'id', [{ $match: { _id: tabId } }, { $project: { memberIds: 1, deletedAt: 1 } }])if (!row) await remove({ tabId })- // A row without memberIds is skipped, never read as having no members.- else if (Array.isArray(row.memberIds)) {+ // A row without memberIds is skipped, never read as having no members. So is a deleted Swarm (deletion.ts): it lists+ // nobody while it can be restored, and its marks come back with it; its purge removes them.+ else if (Array.isArray(row.memberIds) && !row.deletedAt) {const members = new Set(row.memberIds as string[])for (let person = await nextOf(db, { tabId }, 'personId', ''); person !== null; person = await nextOf(db, { tabId }, 'personId', person)) {if (!members.has(person)) await remove({ tabId, personId: person })diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 471a2453a..eb0be3451 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -10,6 +10,7 @@ import { machineAlive } from '../lib/prisma.js'import { isTeamSession, teamMachine, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'import { machineBillingAllowsDataPlane } from '../lib/billingState.js'+import { DELETED_SWARM_COMMANDS, DELETION_COMMANDS, notThere } from './deletion.js'import { applyCommand, authorizeCommandAccess, IGNORED_NOTE, LOOP_NOTICE_AT, mayResumeStart, operationSchema, PAIR_CHAIN_LIMIT, postable, ruleProject, type Command, type CommandContext } from './commands.js'import { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'@@ -44,7 +45,7 @@ import { clock, insertParts, loadActive, loadLightGroups, loadMachineParts, loadimport { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'import { memberSwarms } from './swarmRows.js'import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'-import { loadDeliveryParts } from './parts/light.js'+import { loadDeliveryParts, ms } from './parts/light.js'import { guardedWrite, partId } from './parts/write.js'import { retryable } from './retry.js'import { touchesFor } from './parts/touches.js'@@ -91,7 +92,7 @@ const PROPOSED = 'This file already went with a proposal. Ask your owner to sendconst hash = (value: unknown): string => createHash('sha256').update(JSON.stringify(value)).digest('hex')/** The fields of a Swarm's row the store reads. A migrated row still keeps its whole old state (`legacyState`, about 1 MB* for a busy Swarm) until the maintenance script removes it, and every command and read loads this row. */-const SWARM_ROW = { id: true, ownerId: true, revision: true, format: true } satisfies Prisma.SuperTabSelect+const SWARM_ROW = { id: true, ownerId: true, revision: true, format: true, deletedAt: true } satisfies Prisma.SuperTabSelectexport type SwarmRow = Prisma.SuperTabGetPayload<{ select: typeof SWARM_ROW }>/** A Swarm whose state still waits for its split into parts (design section 6.1) is not served until it is split. */function requireParts(row: SwarmRow): SwarmRow {@@ -663,8 +664,8 @@ export class SuperTabStore {const elsewhere = await tx.swarmMachine.findMany({ where: { machineId: { in: ids }, deleted: false, contributed: true, tabId: { not: state.id } },select: { tabId: true, machineId: true } })if (!elsewhere.length) return []- const rows = await tx.superTab.findMany({ where: { id: { in: [...new Set(elsewhere.map(e => e.tabId))] } }, select: { id: true, workspaceId: true } })- const other = new Set(rows.filter(r => r.workspaceId && r.workspaceId !== state.workspaceId).map(r => r.id))+ const rows = await tx.superTab.findMany({ where: { id: { in: [...new Set(elsewhere.map(e => e.tabId))] } }, select: { id: true, workspaceId: true, deletedAt: true } })+ const other = new Set(rows.filter(r => !r.deletedAt && r.workspaceId && r.workspaceId !== state.workspaceId).map(r => r.id))return [...new Set(elsewhere.filter(e => other.has(e.tabId)).map(e => e.machineId))]}@@ -699,14 +700,16 @@ export class SuperTabStore {}/** Shared with the read API (superTabs/read, design section 7.2). */- async row(tx: Transaction, user: AuthUser, tabId: string) {- return requireParts(await tx.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: SWARM_ROW }) ??- fail('NOT_FOUND', 'This Super Tab is unavailable.', 404))+ /** A deleted Swarm answers as one that does not exist (deletion.ts), unless `deleted` lets the few commands through that+ * still apply to one: its machines' hosts confirming their closes and cleanups, and its owner restoring it. */+ async row(tx: Transaction, user: AuthUser, tabId: string, deleted = false) {+ const row = await tx.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: SWARM_ROW })+ return requireParts(row && (deleted || !row.deletedAt) ? row : fail('NOT_FOUND', 'This Super Tab is unavailable.', 404))}/** The Swarm a caller may address, loaded from its parts. */- async load(tx: Transaction, user: AuthUser, tabId: string, named: Named = {}): Promise<Loaded> {- return loadRow(tx, await this.row(tx, user, tabId), named)+ async load(tx: Transaction, user: AuthUser, tabId: string, named: Named = {}, deleted = false): Promise<Loaded> {+ return loadRow(tx, await this.row(tx, user, tabId, deleted), named)}/** One read's view of these Swarms' stamps (cache.ts), or none: reads then go to Mongo. */@@ -946,6 +949,28 @@ export class SuperTabStore {}), next: rows.length > 100 ? rows[99]!.id : null }}+ /** Whether Swarm [tabId] exists and is not deleted (deletion.ts): for a link made before, outside any person's read. */+ async isLive(tabId: string): Promise<boolean> {+ const [row] = await readBy(this.db, 'SuperTab', 'id', [{ $match: { _id: tabId } }, { $project: { deletedAt: 1 } }])+ return !!row && !row.deletedAt+ }++ /** The owner's deleted Swarms they can still restore, newest first (deletion.ts): names only, from their heads. By the owner+ * index, at most 100. */+ async deletedList(user: AuthUser) {+ this.personOnly(user)+ const now = this.now()+ const rows = (await readBy(this.db, 'SuperTab', 'owner', [{ $match: { autonomousEnv: user.autonomousEnv, ownerId: user.sub, format: 2, deletedAt: { $ne: null } } },+ { $sort: { _id: 1 } }, { $limit: 100 }, { $project: { deletedAt: 1, purgeAt: 1 } }]))+ .map(row => ({ id: row._id as string, deletedAt: ms(row.deletedAt), purgeAt: ms(row.purgeAt) })).filter(row => row.purgeAt > now)+ const heads = await this.heads(rows.map(row => ({ id: row.id, format: 2 })))+ return { tabs: rows.flatMap(row => {+ const head = heads.get(row.id)+ // Only one still deleted in its head, and only its owner's: a restore that has not reached the row yet is not offered.+ return head?.deletion && head.ownerId === user.sub ? [{ id: row.id, name: head.name, deletedAt: row.deletedAt, purgeAt: row.purgeAt }] : []+ }).sort((a, b) => b.deletedAt - a.deletedAt || (a.id < b.id ? -1 : 1)) }+ }+async workspaceList(user: AuthUser) {this.personOnly(user)return { workspaces: await listWorkspaces(this.db, user) }@@ -994,7 +1019,8 @@ export class SuperTabStore {const heads = await this.heads(rows)return rows.flatMap(row => {const state = heads.get(row.id)- if (!state) return []+ // A deleted one invites nobody (deletion.ts), whatever its row still names.+ if (!state || state.deletion) return []return state.invitations.filter(i => i.email === email && i.expiresAt > this.now()).map(i => ({ tabId: row.id, name: state.name, inviteId: i.id, role: i.role, expiresAt: i.expiresAt }))})@@ -1160,7 +1186,7 @@ export class SuperTabStore {// Only one never launched: a repeated dispatch of a launched start is admitted again too, and its agent may be starting.const start = await transaction(this.db, async tx => {const row = await tx.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: SWARM_ROW })- return row?.format === 2 ? (await loadRow(tx, row, { startIds: [command.startId] })).state.starts?.find(s => s.id === command.startId) : undefined+ return row?.format === 2 && !row.deletedAt ? (await loadRow(tx, row, { startIds: [command.startId] })).state.starts?.find(s => s.id === command.startId) : undefined})if (start && !start.dispatched && !start.harnessId && !start.error) {await this.executeOnce(user, tabId, { operationId: `team-refused-${command.startId}`,@@ -1181,7 +1207,9 @@ export class SuperTabStore {ended = []started = []const stamp = clock.next()- const first = await this.load(tx, user, tabId, namedFor(command))+ // A Workspace removal leaves a deleted Swarm too, so its restore cannot bring the person back (security review 2 of #2457).+ const leavingDeleted = workspaceLeave && command.type === 'member.remove' && command.userId === user.sub && !asAgentId+ const first = await this.load(tx, user, tabId, namedFor(command), DELETED_SWARM_COMMANDS.has(command.type) || leavingDeleted)const loaded = await this.ensure(tx, first, await this.moreNamed(tx, tabId, first.state, command, asAgentId ? null : user.sub, asAgentId))const original = loaded.stateconst team = await this.teamHost(tx, user)@@ -1217,6 +1245,8 @@ export class SuperTabStore {: hostMachineId && 'startId' in command? await this.poolHostActor(tx, user, original, hostMachineId, command.startId): await this.actor(tx, user, original, asAgentId, workspaceLeave && command.type === 'member.remove' && command.userId === user.sub && !asAgentId)+ // A made-up or stopped agent, or anyone refused here, is told what a missing Swarm tells (deletion.ts).+ .catch(error => DELETION_COMMANDS.has(command.type) ? notThere() : Promise.reject(error))// A Mac and its Harness Team account leave under one removal, and each host confirms its cleanup as the same person// with the same operation (cli/src/superTabs/machines.ts runCleanup): each machine's confirmation is its own receipt.const receiptId = command.type === 'machine.cleaned' ? stableId(tabId, actorKey(actor), operationId, command.machineId)@@ -1255,7 +1285,12 @@ export class SuperTabStore {return replyOf(prior)}if (command.type !== 'invite.accept' && command.type !== 'agent.sessionClosed' && command.type !== 'machine.cleaned') author(original, actor)- const context: CommandContext = { operationId, now: this.now() }+ const context: CommandContext = { operationId, now: this.now(), ...(leavingDeleted ? { workspaceLeave: true as const } : {}) }+ if (command.type === 'swarm.restore' && original.deletion && original.workspaceId) {+ const lost: string[] = []+ for (const person of original.people) if (!await hasWorkspaceAccess(tx, original, person.id)) lost.push(person.id)+ if (lost.length) context.workspaceLost = lost+ }if (command.type === 'agent.screen' || command.type === 'agent.input') context.confidentialSession = await this.confidential(tx, command.agentId)if (REGISTERS.has(command.type)) context.registrations = await otherRegistrations(tx, original, registeredBy(original, command))if ('startId' in command && ['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) {@@ -1561,7 +1596,7 @@ export class SuperTabStore {if (start?.routeDecisionId) await closeUnassignedStart(tx, tabId, start.routeDecisionId, start.id, 'failed', context.now)}// Starts a removed machine failed, whether its owner removed it or left the Swarm with it, release their route holds.- if (command.type === 'machine.remove' || command.type === 'member.remove') {+ if (command.type === 'machine.remove' || command.type === 'member.remove' || command.type === 'swarm.delete') {for (const start of original.starts ?? []) {if (!start.routeDecisionId || start.harnessId || start.error) continueif (effects.state.starts?.find(s => s.id === start.id)?.error) {@@ -1580,7 +1615,8 @@ export class SuperTabStore {if (effects.notes) await writeNotes(tx, tabId, effects.notes, context.now)if (command.type === 'project.delete') await deleteInstructions(tx, tabId, command.projectId)if (effects.terminal) await this.writeTerminal(tx, tabId, effects.terminal, context.now)- if (this.hooks.accessChanged && watchersLost.length) {+ // A deleted Swarm's observer sockets, on any instance, check again and close (deletion.ts).+ if (this.hooks.accessChanged && (watchersLost.length || command.type === 'swarm.delete')) {const told = this.hooks.accessChangedafterCommit(tx, () => told(tabId))}@@ -2151,7 +2187,7 @@ export class SuperTabStore {for (const row of rows) {if (!states.has(row.tabId)) {const tab = await tx.superTab.findFirst({ where: { id: row.tabId, autonomousEnv: user.autonomousEnv }, select: SWARM_ROW })- states.set(row.tabId, tab?.format === 2 ? (await loadRow(tx, tab)).state : null)+ states.set(row.tabId, tab?.format === 2 && !tab.deletedAt ? (await loadRow(tx, tab)).state : null)}const refusal = now - row.createdAt.getTime() > TERMINAL_PICKUP_MS? 'The agent’s machine did not pick up the request within 10 seconds. It may be offline or asleep.'@@ -2651,7 +2687,8 @@ export class SuperTabStore {async hostGrids(user: AuthUser) {this.personOnly(user)// By the owner index (parts/indexed.ts): Prisma's $expr filter is bounded by the environment alone, every Swarm of it.- const rows = (await readBy(this.db, 'SuperTab', 'owner', [{ $match: { autonomousEnv: user.autonomousEnv, ownerId: user.sub, format: 2 } },+ // Not a deleted one (deletion.ts): its grid goes with it. A raw `deletedAt: null` matches a row that never had the field.+ const rows = (await readBy(this.db, 'SuperTab', 'owner', [{ $match: { autonomousEnv: user.autonomousEnv, ownerId: user.sub, format: 2, deletedAt: null } },{ $sort: { _id: 1 } }, { $limit: 100 }, { $project: { _id: 1 } }])).map(row => ({ id: row._id as string }))return transaction(this.db, async tx => {const heads = await tx.swarmHead.findMany({ where: { tabId: { in: rows.map(row => row.id) }, key: 'head' }, select: { tabId: true, data: true } })@@ -2726,8 +2763,8 @@ export class SuperTabStore {if (!record || stamps?.get(tabId)?.main !== record.stamp || now >= record.deadline || now - record.at >= RECORD_TTL_MS || record.removals) return null// The checks a full report makes with the Swarm, from what the last one saw of it; a refusal is the full report's to say.if ((record.team && !isTeamSession(user)) || !host.owned || !machineBillingAllowsDataPlane(host.owned)) return null- const row = await this.db.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: { format: true } })- if (row?.format !== 2) return null+ const row = await this.db.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv }, select: { format: true, deletedAt: true } })+ if (row?.format !== 2 || row.deletedAt) return nullconst part = loaded !== undefined ? loaded : (await loadMachineParts(this.db, [partId(tabId, machineId)])).get(partId(tabId, machineId))const pool = part && !part.deleted ? part.data.contribution : nullif (!part || !pool || pool.contributorId !== user.sub || pool.generation !== observation.generation || pool.removal) return null@@ -3227,7 +3264,7 @@ export class SuperTabStore {const id = reflectionMessageId(tabId, projectId, on)if (await this.db.superTabMessage.findUnique({ where: { id }, select: { id: true } })) return 'already'const read = await this.db.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })- if (!read) return 'skipped'+ if (!read || read.deletedAt) return 'skipped'const now = this.now(), since = now - 7 * DAY_MSconst { rows, truncated } = await costRows(this.db, tabId, since)const failed = await failedStarts(this.db, tabId, since)@@ -3246,7 +3283,7 @@ export class SuperTabStore {return transaction(this.db, async tx => {if (await tx.superTabMessage.findUnique({ where: { id }, select: { id: true } })) return 'already'const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })- if (!row) return 'skipped'+ if (!row || row.deletedAt) return 'skipped'const loaded = await loadRow(tx, requireParts(row), { groupIds: [at.chat.id] })const state = cloneData(loaded.state)const place = reflectionPlace(state, projectId)@@ -3301,7 +3338,7 @@ export class SuperTabStore {try {closed += await transaction(this.db, async tx => {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })- if (row?.format !== 2) return 0+ if (row?.format !== 2 || row.deletedAt) return 0const { state } = await loadRow(tx, row, { groupIds: conversationIds }), now = this.now()const over = conversationIds.filter(id => { const group = state.conversations.find(c => c.id === id); return !!group && workOver(state, group) })return over.length ? withdrawIn(tx, tabId, over, now, now) : 0@@ -3321,7 +3358,7 @@ export class SuperTabStore {async archiveFinished(tabId: string, groupId: string, checked: Readonly<Record<string, 'merged' | 'closed'>>, reviewOf?: string): Promise<boolean> {return transaction(this.db, async tx => {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })- if (!row) return false+ if (!row || row.deletedAt) return falseconst loaded = await loadRow(tx, requireParts(row), { groupIds: reviewOf ? [groupId, reviewOf] : [groupId] }), state = cloneData(loaded.state)const group = state.conversations.find(c => c.id === groupId)const now = this.now()@@ -3360,7 +3397,7 @@ export class SuperTabStore {return transaction(this.db, async tx => {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })// A Swarm deleted since: nobody can read its deliveries.- const state = row ? (await loadRow(tx, requireParts(row), { groupIds: [...new Set(rows.map(r => r.conversationId))] })).state : null+ const state = row && !row.deletedAt ? (await loadRow(tx, requireParts(row), { groupIds: [...new Set(rows.map(r => r.conversationId))] })).state : nulllet settled = 0for (const delivery of rows) {const reachable = !!state && this.deliveryAllowed(state, delivery)diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.tsindex c5603c297..071454d62 100644--- a/backend/src/superTabs/sweeps.ts+++ b/backend/src/superTabs/sweeps.ts@@ -2,6 +2,7 @@ import type { Prisma, PrismaClient } from '@prisma/client'import type { AgentStart, Conversation } from './model.js'import { clock, guardedWrite, PartConflict, type HeadData, type ProgressData } from './parts/index.js'import { DORMANT_AFTER_MS, RETENTION_MS } from './parts/types.js'+import { deletedSwarms } from './deletion.js'import { logger } from '../utils/logger.js'import { ensureIndex } from '../lib/db/indexes.js'import { swarmTransaction } from './cache.js'@@ -85,11 +86,14 @@ async function sleepQuietGroups(db: PrismaClient, now: number): Promise<number>if (!progress.has(id)) progress.set(id, ((await db.swarmProgress.findUnique({ where: { id } }))?.data as unknown as ProgressData | undefined) ?? null)return progress.get(id)!}+ // A deleted Swarm's groups stay as they are for its restore (deletion.ts).+ const isDeleted = deletedSwarms(db)let slept = 0, after: { at: Date; id: string } | null = nullfor (;;) {const cursor: Prisma.SwarmGroupWhereInput = after ? { AND: [{ OR: [{ lastActivityAt: { gt: after.at } }, { lastActivityAt: after.at, id: { gt: after.id } }] }] } : {}const rows: Array<{ id: string; tabId: string; key: string; version: number; lastActivityAt: Date; data: Prisma.JsonValue }> = await db.swarmGroup.findMany({ where: { ...base, ...cursor }, orderBy: [{ lastActivityAt: 'asc' }, { id: 'asc' }], take: BATCH })for (const row of rows) {+ if (await isDeleted(row.tabId)) continueconst group = row.data as unknown as Conversationconst quiet = row.lastActivityAt.getTime() < now - DORMANT_AFTER_MS && ['done', 'cancelled'].includes(group.assignment?.status ?? '')if (!group.archived && !quiet) continue@@ -111,7 +115,9 @@ async function expireStarts(db: PrismaClient, now: number): Promise<number> {{ $match: { deleted: false, finishedAt: { $lt: { $date: new Date(now - RETENTION_MS).toISOString() } } } }, { $limit: BATCH },{ $project: { tabId: 1, key: 1, version: 1, data: 1 } }])let expired = 0+ const isDeleted = deletedSwarms(db)for (const row of rows) {+ if (await isDeleted(row.tabId as string)) continueif (await guarded(db, { tabId: row.tabId as string, op: 'remove', kind: 'start', key: row.key as string, seen: Number(row.version), data: row.data as unknown as AgentStart })) expired++}return expired@@ -129,6 +135,9 @@ async function expireInvitations(db: PrismaClient, now: number): Promise<number>const head = await db.swarmHead.findUnique({ where: { id: `${tabId as string}:head` } })if (!head || head.deleted) continueconst data = head.data as unknown as HeadData+ // A deleted Swarm is invited to by nobody (deletion.ts): writing its invitations back would list it again. A delete that+ // lands after this read moves the head, so the guarded write below conflicts and is skipped.+ if (data.deletion) continueconst kept = data.invitations.filter(i => i.expiresAt > now)if (kept.length === data.invitations.length) continuetry {diff --git a/backend/src/superTabs/threadBackfill.ts b/backend/src/superTabs/threadBackfill.tsindex 35f433e93..0b0f7009f 100644--- a/backend/src/superTabs/threadBackfill.ts+++ b/backend/src/superTabs/threadBackfill.ts@@ -23,9 +23,11 @@ const EVERY_MS = 15 * 60_000* moves the marker to `now`. A Swarm that fails keeps its marker, is logged and is done at the next run. */export async function backfillThreads(db: PrismaClient, now: number): Promise<{ swarms: number; threads: number }> {const marks = new Map((await db.superTabThreadBackfill.findMany()).map(mark => [mark.id, mark.through.getTime()]))- const swarms = await db.superTab.findMany({ select: { id: true } })+ const swarms = await db.superTab.findMany({ select: { id: true, deletedAt: true } })let done = 0, threads = 0- for (const { id: tabId } of swarms) {+ for (const { id: tabId, deletedAt } of swarms) {+ // A deleted Swarm keeps its summaries for its restore; its purge removes them and its marker (deletion.ts).+ if (deletedAt) continuetry {threads += await backfillSwarm(db, tabId, marks.get(tabId), now)done++diff --git a/backend/src/superTabs/workspaceStore.ts b/backend/src/superTabs/workspaceStore.tsindex f2d70b280..2dc7f5e0f 100644--- a/backend/src/superTabs/workspaceStore.ts+++ b/backend/src/superTabs/workspaceStore.ts@@ -3,6 +3,7 @@ import type { AuthUser } from '../lib/ssoAuth.js'import { fail, stableId, type SuperTabState } from './model.js'import { mayAssignRole, mayManageMember, WORKSPACE_LABEL, workspaceCan, type WorkspaceAction, type WorkspaceRole } from './workspaces.js'import { memberSwarms } from './swarmRows.js'+import { readBy } from './parts/indexed.js'import { logger } from '../utils/logger.js'type Transaction = Prisma.TransactionClient@@ -108,8 +109,9 @@ export async function listWorkspaces(db: PrismaClient, user: AuthUser): Promise<if (!memberships.length) return []// Filtered here, not in the query: Prisma's `null` on Mongo misses a field that was never written.const workspaces = (await db.swarmWorkspace.findMany({ where: { id: { in: memberships.map(m => m.workspaceId) }, autonomousEnv: user.autonomousEnv } })).filter(o => !o.deletedAt)- const rows = workspaces.length ? await db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, workspaceId: { in: workspaces.map(o => o.id) } },- select: { id: true, workspaceId: true, memberIds: true, format: true } }) : []+ // A deleted Swarm (deletion.ts) is listed to nobody, its owner and the Workspace's admins included.+ const rows = (workspaces.length ? await db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, workspaceId: { in: workspaces.map(o => o.id) } },+ select: { id: true, workspaceId: true, memberIds: true, format: true, deletedAt: true } }) : []).filter(row => !row.deletedAt)const split = rows.filter(r => r.format === 2).map(r => `${r.id}:head`)const heads = split.length ? await db.swarmHead.findMany({ where: { id: { in: split } }, select: { tabId: true, data: true } }) : []const headOf = new Map(heads.map(h => [h.tabId, h.data as { name?: string; workspaceVisibility?: 'invite-only' | 'workspace' }]))@@ -234,7 +236,8 @@ export class SwarmWorkspaces {/** Someone who owns one of the Workspace's Swarms stays at least a member, and cannot be removed until it moves. */private async ownsWorkspaceSwarm(tx: Transaction, workspaceId: string, userId: string): Promise<boolean> {- return !!await tx.superTab.findFirst({ where: { workspaceId, ownerId: userId }, select: { id: true } })+ // A deleted one does not count (deletion.ts): restoring it needs its owner in the Workspace again.+ return (await tx.superTab.findMany({ where: { workspaceId, ownerId: userId }, select: { deletedAt: true }, take: 1000 })).some(row => !row.deletedAt)}async setRole(user: AuthUser, workspaceId: string, userId: string, role: WorkspaceRole) {@@ -294,7 +297,15 @@ export class SwarmWorkspaces {* many Swarms could not be left now. */private async finish(removal: SwarmWorkspaceRemoval): Promise<number> {// Every Swarm of theirs in the Workspace: no page limit, as before; a person is in few Swarms.- const rows = await memberSwarms(this.db, removal.autonomousEnv, removal.userId, { workspaceId: removal.workspaceId })+ const rows: Array<{ id: string }> = await memberSwarms(this.db, removal.autonomousEnv, removal.userId, { workspaceId: removal.workspaceId })+ // And the deleted ones they are in (deletion.ts): those list nobody, yet a restore would bring the person back with them.+ // Only the deleted ones, by the Workspace index (re-check 2 of #2457: not every Swarm of the Workspace).+ for (const row of await readBy(this.db, 'SuperTab', 'workspace', [{ $match: { autonomousEnv: removal.autonomousEnv, workspaceId: removal.workspaceId,+ deletedAt: { $ne: null } } }, { $project: { _id: 1 } }])) {+ const id = row._id as string+ const member = await this.db.swarmMember.findUnique({ where: { id: `${id}:${removal.userId}` }, select: { deleted: true } })+ if (member && !member.deleted) rows.push({ id })+ }let pending = 0for (const row of rows) {try { await this.deps.leave(personOf(removal, removal.autonomousEnv), row.id, stableId('workspace-removal', removal.id)) } catch (error) {diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 26d664c42..71a21d542 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -33,6 +33,7 @@ import { machineBillingWorkerService } from './services/MachineBillingWorkerServimport { productUsagePeopleRollupService } from './services/ProductUsagePeopleRollupService.js'import { startReceiptSweep } from './lib/productUsageReceiptSweep.js'import { startPendingUploadSweep } from './lib/pendingUploadSweep.js'+import { startSwarmPurge } from './superTabs/purge.js'import { startRoutingReflection } from './lib/routingReflection.js'import { logger } from './utils/logger.js'@@ -73,6 +74,7 @@ async function start(): Promise<void> {let stopThreadBackfill = (): void => {}let stopReceiptSweep = (): void => {}let stopPendingUploads = (): void => {}+ let stopSwarmPurge = (): void => {}let stopReflection = (): void => {}const shutdown = (signal: string): void => {logger.info(`Received ${signal}, stopping backend worker...`)@@ -87,6 +89,7 @@ async function start(): Promise<void> {stopCompaction()stopReceiptSweep()stopPendingUploads()+ stopSwarmPurge()stopReflection()stopThreadBackfill()// The last partial minute, before the database closes.@@ -103,6 +106,8 @@ async function start(): Promise<void> {stopReceiptSweep = startReceiptSweep(prisma)// Uploads begun on a link and never finished go an hour after the link expired, with what they stored (lib/pendingUploadSweep.ts).stopPendingUploads = startPendingUploadSweep(prisma, env)+ // Deleted Swarms past their 7 days go with their records and stored files (superTabs/purge.ts).+ stopSwarmPurge = startSwarmPurge(prisma, env)// The worker's sweeps and archive write Swarms: they bump the stamps the API processes read by. It reads too little to keep a cache.configureSwarmStamps(redisSwarmStamps(), { reads: false })// Archive notes and Workspace removals write messages too: their recipients' hosts hear of them at once, and of thediff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 28e7071e8..071d6350a 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabThreads.test.ts',- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabDeletion.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/desktop/lib/super_tabs/swarm_delete.dart b/desktop/lib/super_tabs/swarm_delete.dartnew file mode 100644index 000000000..ae069385b--- /dev/null+++ b/desktop/lib/super_tabs/swarm_delete.dart@@ -0,0 +1,299 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'dialog_scope.dart';+import 'model.dart';+import 'swarm_switcher.dart' show PersonalSwarm;++/// Deleting a Swarm (Dee, 10-31: "owners can delete a Swarm, like deleting a+/// Slack workspace"). Its owner picks Delete in the Swarm dropdown and types+/// its name; everyone loses it at once. For 7 days it is listed under the+/// dropdown's Restore rows, its owner's alone (backend superTabs/deletion.ts).++/// One deleted Swarm its owner can still restore.+typedef DeletedSwarm = ({String id, String name, DateTime purgeAt});++/// The signed-in owner's deleted Swarms, read when the dropdown opens and+/// after a delete; and restoring one.+class DeletedSwarms extends ChangeNotifier {+ DeletedSwarms._(this.app);+ static final _of = Expando<DeletedSwarms>();+ static DeletedSwarms of(AppNotifier app) => _of[app] ??= DeletedSwarms._(app);++ final AppNotifier app;+ String? _account;+ List<DeletedSwarm> _items = const [];+ int _reads = 0;+ final _restoring = <String>{};++ /// Why the last restore failed, for the Swarm it was for.+ ({String id, String message})? restoreError;++ /// The signed-in account's list, as last read for it; never another's.+ List<DeletedSwarm> get items =>+ _account != null && _account == app.currentUser?.id ? _items : const [];+ bool restoring(String id) => _restoring.contains(id);++ /// Reads the list again. An answer for an account no longer signed in, or+ /// overtaken by a later read, changes nothing. A failed read keeps what+ /// was shown; a backend from before deletion lists nothing.+ Future<void> read() async {+ final account = app.currentUser?.id;+ if (account == null) return;+ final read = ++_reads;+ try {+ final answer = await app.superTabs.map('GET', '/api/super-tabs/deleted');+ if (read != _reads || account != app.currentUser?.id) return;+ _account = account;+ _items = parseDeletedSwarms(answer);+ } on SuperTabFailure catch (failure) {+ if (read != _reads || account != app.currentUser?.id) return;+ if (failure.statusCode != 404) return;+ _account = account;+ _items = const [];+ } catch (_) {+ return;+ }+ notifyListeners();+ }++ /// Restores [id] and shows it in Swarm tab [tab]; the error for the row+ /// otherwise. One restore per Swarm at a time.+ Future<bool> restore(String id, {String? tab}) async {+ final account = app.currentUser?.id;+ if (account == null || !_restoring.add(id)) return false;+ restoreError = null;+ notifyListeners();+ try {+ await app.superTabs.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(id)}/commands',+ body: {+ 'operationId': superTabOperationId(),+ 'command': {'type': 'swarm.restore'},+ },+ );+ if (account != app.currentUser?.id) return false;+ final name = _items.where((s) => s.id == id).firstOrNull?.name;+ _items = [+ for (final s in _items)+ if (s.id != id) s,+ ];+ // The view that lost it is let go, so the next open reads it afresh.+ app.superTabs.release(id);+ PersonalSwarm.of(app).regained(id);+ await app.superTabs.refreshTabs();+ if (tab != null && account == app.currentUser?.id) {+ app.showSuperTabIn(tab, id, name ?? 'Swarm');+ }+ return true;+ } catch (failure) {+ if (account == app.currentUser?.id) {+ restoreError = (+ id: id,+ message: failure is SuperTabFailure && failure.statusCode == 404+ ? 'This Swarm can no longer be restored.'+ : 'Could not restore this Swarm. Try again.',+ );+ // Gone for good, or restored elsewhere: the list says which.+ unawaited(read());+ }+ return false;+ } finally {+ _restoring.remove(id);+ notifyListeners();+ }+ }+}++/// The deleted Swarms a `GET /api/super-tabs/deleted` answer names, newest+/// first. A row it cannot read is left out rather than failing the list.+List<DeletedSwarm> parseDeletedSwarms(Map<String, dynamic> answer) {+ final tabs = answer['tabs'];+ if (tabs is! List) return const [];+ return [+ for (final raw in tabs)+ if (raw is Map &&+ raw['id'] is String &&+ raw['name'] is String &&+ raw['purgeAt'] is num)+ (+ id: raw['id'] as String,+ name: raw['name'] as String,+ purgeAt: DateTime.fromMillisecondsSinceEpoch(+ (raw['purgeAt'] as num).toInt(),+ ),+ ),+ ];+}++/// "7 days left" just after a delete, "1 day left", or "Less than a day+/// left" until [purgeAt]: whole days to the nearest, a last day said so.+String restoreTimeLeft(DateTime purgeAt, DateTime now) {+ final left = purgeAt.difference(now);+ if (left < const Duration(days: 1)) return 'Less than a day left';+ final days = (left.inMinutes / Duration.minutesPerDay).round();+ return days == 1 ? '1 day left' : '$days days left';+}++/// The people and agents who lose this Swarm, as the open Swarm says.+String swarmDeleteCounts(SuperTabSnapshot snapshot) {+ String count(int n, String one, String many) => '$n ${n == 1 ? one : many}';+ return '${count(snapshot.people.length, 'person', 'people')}, '+ '${count(snapshot.agents.length, 'agent', 'agents')}';+}++/// Asks the owner to type the Swarm's name, then deletes it. True once the+/// server confirmed. Closes by itself if the Swarm stops being theirs.+Future<bool> showDeleteSwarmDialog(+ BuildContext context,+ SuperTabController c,+) async {+ final deleted = await showAppDialog<bool>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ child: _DeleteSwarmDialog(controller: c),+ ),+ );+ return deleted ?? false;+}++class _DeleteSwarmDialog extends StatefulWidget {+ const _DeleteSwarmDialog({required this.controller});+ final SuperTabController controller;++ @override+ State<_DeleteSwarmDialog> createState() => _DeleteSwarmDialogState();+}++class _DeleteSwarmDialogState extends State<_DeleteSwarmDialog> {+ final _typed = TextEditingController();+ bool _busy = false;++ /// The name as it was when the dialog opened: a rename meanwhile does not+ /// make the typed name delete a Swarm it no longer names.+ late final String _name = widget.controller.snapshot?.name.trim() ?? '';++ SuperTabController get c => widget.controller;++ @override+ void initState() {+ super.initState();+ _typed.addListener(() => setState(() {}));+ }++ @override+ void dispose() {+ _typed.dispose();+ super.dispose();+ }++ bool get _pending {+ final pending = c.pendingCommand;+ return pending?['type'] == 'swarm.delete';+ }++ Future<void> _delete() async {+ setState(() => _busy = true);+ final result = _pending+ ? await c.retry()+ : await c.command({'type': 'swarm.delete', 'name': _typed.text.trim()});+ if (!mounted) return;+ if (result != null) {+ Navigator.pop(context, true);+ } else {+ setState(() => _busy = false);+ }+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: c,+ builder: (context, _) {+ final snapshot = c.snapshot;+ final matches = _name.isNotEmpty && _typed.text.trim() == _name;+ final canDelete =+ !_busy &&+ !c.saving &&+ c.isOwner &&+ (_pending || (!c.hasPendingAction && matches));+ return PopScope(+ canPop: !_busy,+ child: AlertDialog(+ key: const ValueKey('swarm-delete-dialog'),+ title: Text('Delete “$_name”?'),+ content: SizedBox(+ width: 420,+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'Everyone loses access at once: '+ '${snapshot == null ? '' : swarmDeleteCounts(snapshot)}.',+ key: const ValueKey('swarm-delete-counts'),+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(+ 'Its chats and files are removed after 7 days. Until '+ 'then you can restore it from the Swarm menu, without '+ 'its agents and machines.',+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: grid.AppDesktop.groupGap),+ Text(+ 'Type the Swarm’s name to confirm',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ TextField(+ key: const ValueKey('swarm-delete-name'),+ controller: _typed,+ autofocus: true,+ enabled: !_busy && !_pending,+ decoration: InputDecoration(hintText: _name),+ onSubmitted: (_) {+ if (canDelete) unawaited(_delete());+ },+ ),+ if (c.operationError != null) ...[+ const SizedBox(height: grid.AppDesktop.controlGap),+ Text(+ c.operationError!,+ key: const ValueKey('swarm-delete-error'),+ style: DesktopChrome.metadata(+ color: grid.AppPalette.dangerFill,+ ),+ ),+ ],+ ],+ ),+ ),+ ),+ actions: [+ TextButton(+ key: const ValueKey('swarm-delete-cancel'),+ onPressed: _busy ? null : () => Navigator.pop(context, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const ValueKey('swarm-delete-confirm'),+ style: grid.dangerButtonStyle(),+ onPressed: canDelete ? () => unawaited(_delete()) : null,+ child: Text(_pending ? 'Retry' : 'Delete Swarm'),+ ),+ ],+ ),+ );+ },+ );+}diff --git a/desktop/lib/super_tabs/swarm_switcher.dart b/desktop/lib/super_tabs/swarm_switcher.dartindex 40928171f..a3c6d4953 100644--- a/desktop/lib/super_tabs/swarm_switcher.dart+++ b/desktop/lib/super_tabs/swarm_switcher.dart@@ -12,6 +12,7 @@ import 'buddy_rows.dart' show SuperTabCountBadge;import 'controller.dart';import 'machines.dart' show contributeComputer;import 'section_heading.dart' show SuperTabSectionHeading;+import 'swarm_delete.dart';/// The Swarm dropdown at the top of a Swarm tab's left bar (Dee, 10-30): the/// Swarm the tab shows, and in its menu Personal, every other Swarm the@@ -99,6 +100,12 @@ class PersonalSwarm extends ChangeNotifier {/// Whether Swarm [id] was taken away from the signed-in person while shown.bool lost(String id) => _lost[_account]?.contains(id) ?? false;+ /// [id] is the account's again (a deleted Swarm restored): listed once+ /// more, and lost again only by a new loss.+ void regained(String id) {+ if (_lost[_account]?.remove(id) ?? false) notifyListeners();+ }+/// A Swarm the person owns named Personal, of those they belong to, with/// no one else in it when it has been read.String? _owned(String account) {@@ -402,6 +409,24 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {app.showSuperTabIn(tab, choice.id, choice.name);}+ DeletedSwarms get deleted => DeletedSwarms.of(app);++ /// Asks its owner to confirm; once deleted, it leaves this dropdown and+ /// its tab moves on as for any Swarm taken away.+ Future<void> _delete(BuildContext context) async {+ _menu.close();+ final c = widget.controller;+ if (!await showDeleteSwarmDialog(context, c)) return;+ unawaited(app.superTabs.refreshTabs());+ unawaited(deleted.read());+ }++ /// Restores a deleted Swarm and shows it in this tab.+ void _restore(String id) {+ _menu.close();+ unawaited(deleted.restore(id, tab: _tab));+ }+void _pickPersonal() {_menu.close();final tab = _tab;@@ -410,7 +435,7 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {@overrideWidget build(BuildContext context) => ListenableBuilder(- listenable: Listenable.merge([app, personal, widget.controller]),+ listenable: Listenable.merge([app, personal, deleted, widget.controller]),builder: (context, _) {grid.AppTheme.watch(context);final c = widget.controller;@@ -423,6 +448,7 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {? 'Swarm': app.superTabName(current) ?? c.snapshot?.name ?? 'Swarm';final choices = swarmChoices(app);+ final restorable = deleted.items;final personalWaiting = personalId == null || isPersonal? 0: swarmWaiting(app, personalId);@@ -441,6 +467,7 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {style: grid.AppMenu.style(minWidth: width, maxWidth: width),onOpen: () {if (_tab case final tab?) personal.clearError(tab);+ unawaited(deleted.read());},// As wide as the row it opens from.menuChildren: [@@ -483,6 +510,40 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {widget.onNewSwarm();},),+ // Its owner's alone, never Personal (backend deletion.ts).+ if (current != null &&+ !isPersonal &&+ c.isOwner &&+ c.snapshot != null)+ AppMenuItem(+ key: const ValueKey('swarm-switch-delete'),+ label: 'Delete “$label”…',+ icon: AppIcons.trash2,+ danger: true,+ expandLabel: true,+ onPressed: () => _delete(context),+ ),+ if (restorable.isNotEmpty) const AppMenuDivider(),+ for (final swarm in restorable)+ AppMenuItem(+ key: ValueKey('swarm-switch-restore-${swarm.id}'),+ label: 'Restore “${swarm.name}”',+ icon: AppIcons.undo2,+ expandLabel: true,+ detail: deleted.restoreError?.id == swarm.id+ ? deleted.restoreError!.message+ : 'Deleted · '+ '${restoreTimeLeft(swarm.purgeAt, DateTime.now())}',+ trailing: deleted.restoring(swarm.id)+ ? const SizedBox.square(+ dimension: 12,+ child: CircularProgressIndicator(+ strokeWidth: 1.5,+ ),+ )+ : null,+ onPressed: () => _restore(swarm.id),+ ),])SizedBox(width: width, child: item),],diff --git a/desktop/test/super_tab_swarm_delete_test.dart b/desktop/test/super_tab_swarm_delete_test.dartnew file mode 100644index 000000000..2b8ac8295--- /dev/null+++ b/desktop/test/super_tab_swarm_delete_test.dart@@ -0,0 +1,631 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/project_sidebar.dart';+import 'package:harness/super_tabs/swarm_delete.dart';+import 'package:harness/super_tabs/swarm_switcher.dart';+import 'package:harness/ws/ws_conn.dart';++import 'support/capture.dart';+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show MemoryStore, createApp;++/// The backend as deleting a Swarm meets it (backend superTabs/deletion.ts):+/// the account's list, each Swarm's reads and commands, `swarm.delete` by its+/// owner with its exact name, then every read answering as for a missing+/// Swarm, the owner's Recently deleted list, and `swarm.restore`.+class _Backend {+ final tabs = <Map<String, dynamic>>[];+ final servers = <String, ConversationServer>{};+ final deleted = <String, int>{};+ final commands = <(String, String, Map)>[];+ String account = 'owner';+ int now = DateTime.now().millisecondsSinceEpoch;++ /// While set, the deleted list answers only once it completes.+ Completer<void>? holdDeletedList;++ /// The deleted list fails this many more times.+ int failDeletedList = 0;++ /// While set, swarm.delete is refused with it.+ SuperTabFailure? refuseDelete;+ Completer<void>? holdDelete;++ ConversationServer add(+ String id,+ String name, {+ String owner = 'owner',+ List<String> members = const ['owner'],+ int agents = 0,+ }) {+ final server = ConversationServer();+ server.state+ ..['id'] = id+ ..['name'] = name+ ..['ownerId'] = owner+ ..['people'] = [+ for (final person in members)+ {+ 'id': person,+ 'email': '[email protected]',+ 'role': person == owner ? 'owner' : 'collaborator',+ },+ ];+ for (var i = 0; i < agents; i++) {+ (server.state['agents'] as List).add({+ 'id': 'agent-$id-$i',+ 'name': 'Agent $i',+ 'machineId': 'm',+ 'harnessId': 'h-$id-$i',+ 'contributorId': owner,+ 'projectId': 'lead',+ 'configuration': {'engine': 'codex'},+ });+ }+ servers[id] = server;+ tabs.add({'id': id, 'name': name, 'ownerId': owner, 'members': members});+ return server;+ }++ static const missing = SuperTabFailure(+ 'NOT_FOUND',+ 'This is not available to you. It may have been removed, or your access changed.',+ statusCode: 404,+ );++ Future<Object?> request(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ final uri = Uri.parse(path);+ if (uri.path == '/api/super-tabs/list') {+ return {+ 'tabs': [+ for (final tab in tabs)+ if ((tab['members'] as List).contains(account) &&+ !deleted.containsKey(tab['id']))+ {'id': tab['id'], 'name': tab['name'], 'ownerId': tab['ownerId']},+ ],+ 'next': null,+ };+ }+ if (uri.path == '/api/super-tabs/deleted') {+ if (holdDeletedList case final hold?) await hold.future;+ if (failDeletedList > 0) {+ failDeletedList--;+ throw const SuperTabFailure(+ 'SERVICE_UNAVAILABLE',+ 'Busy.',+ statusCode: 503,+ );+ }+ return {+ 'tabs': [+ for (final MapEntry(key: id, value: at) in deleted.entries)+ if (tabs.firstWhere((t) => t['id'] == id)['ownerId'] == account)+ {+ 'id': id,+ 'name': tabs.firstWhere((t) => t['id'] == id)['name'],+ 'deletedAt': at,+ 'purgeAt': at + const Duration(days: 7).inMilliseconds,+ },+ ],+ };+ }+ final swarm = RegExp(r'^/api/super-tabs/([^/]+)/').firstMatch(uri.path);+ final id = swarm?.group(1);+ final server = servers[id];+ if (server == null) throw missing;+ final tab = tabs.firstWhere((t) => t['id'] == id);+ final command = method == 'POST' && uri.path.endsWith('/commands')+ ? body!['command'] as Map+ : null;+ if (command != null) commands.add((account, id!, command));+ if (command?['type'] == 'swarm.restore') {+ if (!deleted.containsKey(id) || tab['ownerId'] != account) throw missing;+ deleted.remove(id);+ return {+ 'result': {'restored': true},+ 'revision': 1,+ };+ }+ // A deleted Swarm reads, and takes commands, as one that does not exist.+ if (deleted.containsKey(id) ||+ !(tab['members'] as List).contains(account)) {+ throw missing;+ }+ if (command?['type'] == 'swarm.delete') {+ if (holdDelete case final hold?) await hold.future;+ if (refuseDelete case final refusal?) throw refusal;+ if (tab['ownerId'] != account) throw missing;+ if (command!['name'] != tab['name']) {+ throw const SuperTabFailure(+ 'NAME_MISMATCH',+ 'Type the Swarm\'s name exactly to delete it.',+ statusCode: 400,+ );+ }+ deleted[id!] = now;+ return {+ 'result': {'purgeAt': now + const Duration(days: 7).inMilliseconds},+ 'revision': 1,+ };+ }+ return server.request(method, path, body: body);+ }+}++class _Connection extends WsConn {+ _Connection(this.backend, String machineId)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final _Backend backend;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type != 'super_tabs' || payload['action'] != 'backend') return {};+ return {+ 'value': await backend.request(+ payload['method'] as String,+ payload['path'] as String,+ body: payload['body'] as Map<String, dynamic>?,+ ),+ };+ }+}++AppNotifier _computer(_Backend backend, {String account = 'owner'}) {+ final app = createApp(+ store: MemoryStore(),+ connected: true,+ connectionForTest: (machineId) => _Connection(backend, machineId),+ );+ app.machineStates['m']!.localOnly = true;+ app.status = AppStatus.authenticated;+ app.currentUser = CurrentUserProfile(+ id: account,+ email: '[email protected]',+ );+ app.enterSuperTabs();+ addTearDown(app.dispose);+ return app;+}++Future<void> _settle() async {+ for (var i = 0; i < 30; i++) {+ await Future<void>.delayed(Duration.zero);+ }+}++/// Alpha (owner, a member and two agents) shown in a tab, and Beta.+Future<(AppNotifier, _Backend)> _swarms({String account = 'owner'}) async {+ final backend = _Backend()+ ..account = account+ ..add('alpha', 'Alpha', members: ['owner', 'member'], agents: 2)+ ..add('beta', 'Beta', members: ['owner', 'member']);+ final app = _computer(backend, account: account);+ await app.superTabs.refreshTabs();+ app.selectSwarm(app.swarms.firstWhere((s) => s.superTabId == 'alpha').id);+ return (app, backend);+}++Future<SuperTabController> _pump(+ WidgetTester tester,+ AppNotifier app, {+ Brightness brightness = Brightness.dark,+}) async {+ await tester.binding.setSurfaceSize(const Size(900, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ late SuperTabController shown;+ await tester.runAsync(() async {+ shown = await app.superTabs.open(app.activeSwarm.superTabId!);+ await shown.refresh();+ });+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: 300,+ child: ListenableBuilder(+ listenable: app,+ builder: (context, _) =>+ switch (app.superTabs.peek(app.activeSwarm.superTabId!)) {+ null => const SizedBox(),+ final c => ListenableBuilder(+ listenable: c,+ builder: (context, _) => ProjectSidebar(+ key: ValueKey(c.tabId),+ controller: c,+ app: app,+ onAddAgent: (_) {},+ needsHuman: (_) => 0,+ onSelect: c.select,+ onNewProject: () {},+ onNewSwarm: () {},+ ),+ ),+ },+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ await tester.pump();+ return shown;+}++Future<void> _releaseAll(WidgetTester tester, AppNotifier app) async {+ await tester.pumpWidget(const SizedBox());+ for (final c in app.superTabs.loadedControllers.toList()) {+ app.superTabs.release(c.tabId);+ }+ await tester.runAsync(_settle);+}++Future<void> _openMenu(WidgetTester tester) async {+ await tester.tap(find.byKey(const ValueKey('super-swarm-switcher')));+ await tester.runAsync(_settle);+ await tester.pump();+ await tester.pump();+}++const _deleteItem = ValueKey('swarm-switch-delete');+const _confirm = ValueKey('swarm-delete-confirm');+const _nameField = ValueKey('swarm-delete-name');++/// Through the fake transport, then the frames it changed.+Future<void> _run(WidgetTester tester) async {+ await tester.runAsync(_settle);+ await tester.pump();+ await tester.pump();+}++Future<void> _openDialog(WidgetTester tester) async {+ await _openMenu(tester);+ await tester.tap(find.byKey(_deleteItem));+ await tester.pump();+ await tester.pump();+}++bool _confirmEnabled(WidgetTester tester) =>+ tester.widget<FilledButton>(find.byKey(_confirm)).onPressed != null;++final _shots = Platform.environment['SWARM_DELETE_SHOTS'];++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ setUpAll(() => loadCaptureFonts(_shots));++ testWidgets('the dropdown offers Delete to the owner of the shown Swarm '+ 'alone: not to a member, and never for Personal', (tester) async {+ late AppNotifier app;+ await tester.runAsync(() async => (app, _) = await _swarms());+ await _pump(tester, app);+ await _openMenu(tester);+ expect(find.byKey(_deleteItem), findsOneWidget);+ expect(find.text('Delete “Alpha”…'), findsOneWidget);+ await _releaseAll(tester, app);++ // The owner's Personal Swarm, shown in the tab: never offered.+ late AppNotifier mine;+ await tester.runAsync(() async {+ late _Backend backend;+ (mine, backend) = await _swarms();+ backend.add('personal', 'Personal');+ await mine.superTabs.refreshTabs();+ final tab = mine.swarms.firstWhere((s) => s.superTabId == 'alpha');+ mine.showSuperTabIn(tab.id, 'personal', 'Personal');+ await (await mine.superTabs.open('personal')).refresh();+ });+ await _pump(tester, mine);+ expect(mine.activeSwarm.superTabId, 'personal');+ expect(PersonalSwarm.of(mine).id, 'personal');+ await _openMenu(tester);+ expect(find.byKey(const ValueKey('swarm-switch-personal')), findsOneWidget);+ expect(find.byKey(_deleteItem), findsNothing);+ await _releaseAll(tester, mine);++ late AppNotifier member;+ await tester.runAsync(+ () async => (member, _) = await _swarms(account: 'member'),+ );+ await _pump(tester, member);+ await _openMenu(tester);+ expect(find.byKey(const ValueKey('swarm-switch-alpha')), findsOneWidget);+ expect(find.byKey(_deleteItem), findsNothing);+ await _releaseAll(tester, member);+ });++ testWidgets('the dialog names who loses access and deletes only once the '+ 'exact name is typed; Cancel sends nothing', (tester) async {+ late AppNotifier app;+ late _Backend backend;+ await tester.runAsync(() async => (app, backend) = await _swarms());+ await _pump(tester, app);+ await _openDialog(tester);+ expect(find.text('Delete “Alpha”?'), findsOneWidget);+ expect(+ find.text('Everyone loses access at once: 2 people, 2 agents.'),+ findsOneWidget,+ );+ expect(_confirmEnabled(tester), isFalse);+ for (final wrong in ['alpha', 'Alph', 'Alpha!']) {+ await tester.enterText(find.byKey(_nameField), wrong);+ await tester.pump();+ expect(_confirmEnabled(tester), isFalse, reason: wrong);+ }+ await tester.enterText(find.byKey(_nameField), ' Alpha ');+ await tester.pump();+ expect(_confirmEnabled(tester), isTrue);+ await tester.tap(find.byKey(const ValueKey('swarm-delete-cancel')));+ await tester.pump();+ await tester.pump();+ expect(find.byKey(const ValueKey('swarm-delete-dialog')), findsNothing);+ expect(+ backend.commands.where((c) => c.$3['type'] == 'swarm.delete'),+ isEmpty,+ );+ expect(backend.deleted, isEmpty);+ await _releaseAll(tester, app);+ });++ testWidgets('deleting takes the Swarm out of the dropdown at once and lists '+ 'it under Restore; restoring brings it back into this tab', (+ tester,+ ) async {+ late AppNotifier app;+ late _Backend backend;+ await tester.runAsync(() async => (app, backend) = await _swarms());+ final shown = await _pump(tester, app);+ await _openDialog(tester);+ await tester.enterText(find.byKey(_nameField), 'Alpha');+ await tester.pump();+ await tester.tap(find.byKey(_confirm));+ await _run(tester);+ await _run(tester);++ expect(+ [+ for (final (who, id, command) in backend.commands)+ if (command['type'] == 'swarm.delete') (who, id, command['name']),+ ],+ [('owner', 'alpha', 'Alpha')],+ );+ expect(find.byKey(const ValueKey('swarm-delete-dialog')), findsNothing);+ // Gone from this computer at once: its view lets go of it, the dropdown+ // no longer lists it, and nothing of it stays readable here.+ expect(shown.accessRevoked, isTrue);+ expect(shown.snapshot, isNull);+ expect(swarmChoices(app).map((c) => c.id), isNot(contains('alpha')));+ expect(app.superTabs.ownerOf('alpha'), isNull);++ await _openMenu(tester);+ expect(find.byKey(const ValueKey('swarm-switch-alpha')), findsNothing);+ expect(find.text('Restore “Alpha”'), findsOneWidget);+ expect(find.text('Deleted · 7 days left'), findsOneWidget);++ await tester.tap(find.byKey(const ValueKey('swarm-switch-restore-alpha')));+ await _run(tester);+ await _run(tester);+ final (who, id, command) = backend.commands.last;+ expect((who, id, command['type']), ('owner', 'alpha', 'swarm.restore'));+ expect(backend.deleted, isEmpty);+ expect(swarmChoices(app).map((c) => c.id), contains('alpha'));+ expect(app.activeSwarm.superTabId, 'alpha');+ expect(DeletedSwarms.of(app).items, isEmpty);+ await _releaseAll(tester, app);+ });++ testWidgets('a member\'s computer loses the deleted Swarm on its next read, '+ 'with its chat and agents cleared', (tester) async {+ late AppNotifier member;+ late _Backend backend;+ late SuperTabController alpha;+ await tester.runAsync(() async {+ (member, backend) = await _swarms(account: 'member');+ alpha = await member.superTabs.open('alpha');+ await alpha.refresh();+ expect(alpha.snapshot?.agents, hasLength(2));+ backend.deleted['alpha'] = backend.now;+ await alpha.refresh();+ await member.superTabs.refreshTabs();+ });+ expect(alpha.accessRevoked, isTrue);+ expect(alpha.snapshot, isNull);+ expect(swarmChoices(member).map((c) => c.id), isNot(contains('alpha')));+ // And a member is never offered its restore.+ await tester.runAsync(() => DeletedSwarms.of(member).read());+ expect(DeletedSwarms.of(member).items, isEmpty);+ member.superTabs.release('alpha');+ await tester.runAsync(_settle);+ });++ testWidgets('a refusal keeps the dialog open with its reason, and deletes '+ 'nothing', (tester) async {+ late AppNotifier app;+ late _Backend backend;+ await tester.runAsync(() async => (app, backend) = await _swarms());+ backend.refuseDelete = const SuperTabFailure(+ 'STARTS_PENDING',+ 'An agent is starting in this Swarm. Try again in a moment.',+ statusCode: 409,+ );+ final shown = await _pump(tester, app);+ await _openDialog(tester);+ await tester.enterText(find.byKey(_nameField), 'Alpha');+ await tester.pump();+ await tester.tap(find.byKey(_confirm));+ await _run(tester);+ expect(find.byKey(const ValueKey('swarm-delete-dialog')), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-delete-error')), findsOneWidget);+ expect(shown.accessRevoked, isFalse);+ expect(swarmChoices(app).map((c) => c.id), contains('alpha'));+ await tester.tap(find.byKey(const ValueKey('swarm-delete-cancel')));+ await tester.pump();+ await _releaseAll(tester, app);+ });++ testWidgets('access lost while the dialog is open closes what it showed; a '+ 'late answer changes nothing', (tester) async {+ late AppNotifier app;+ await tester.runAsync(() async => (app, _) = await _swarms());+ final shown = await _pump(tester, app);+ await _openDialog(tester);+ expect(find.text('Delete “Alpha”?'), findsOneWidget);+ shown.revokeAccess('You no longer have access to this Swarm.');+ await tester.pump();+ await tester.pump();+ // The dialog no longer names the Swarm, its people or its agents.+ expect(find.text('Delete “Alpha”?'), findsNothing);+ expect(find.textContaining('2 people'), findsNothing);+ expect(find.byKey(_nameField), findsNothing);+ expect(find.text('This action is no longer available.'), findsOneWidget);+ await _releaseAll(tester, app);+ });++ test('a Recently deleted read that answers for another account, or after a '+ 'newer read, changes nothing; a failed first read recovers', () async {+ final (app, backend) = await _swarms();+ backend.deleted['beta'] = backend.now;+ final list = DeletedSwarms.of(app);++ // Asked as the owner, answered once another account is signed in.+ backend.holdDeletedList = Completer();+ final stale = list.read();+ app.currentUser = const CurrentUserProfile(+ id: 'member',+ email: '[email protected]',+ );+ backend.holdDeletedList!.complete();+ backend.holdDeletedList = null;+ await stale;+ expect(list.items, isEmpty);++ app.currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );+ backend.failDeletedList = 1;+ await list.read();+ expect(list.items, isEmpty);+ await list.read();+ expect(list.items.map((s) => s.id), ['beta']);++ // Signed out: no account's list is shown, and none is read.+ app.currentUser = null;+ expect(list.items, isEmpty);+ });++ test('a restore the server refuses says why on its row and reads the list '+ 'again', () async {+ final (app, backend) = await _swarms();+ backend.deleted['beta'] = backend.now;+ final list = DeletedSwarms.of(app);+ await list.read();+ // Purged meanwhile: the server answers as for a missing Swarm.+ backend.deleted.clear();+ backend.servers.remove('beta');+ expect(await list.restore('beta'), isFalse);+ expect(list.restoreError, (+ id: 'beta',+ message: 'This Swarm can no longer be restored.',+ ));+ await _settle();+ expect(list.items, isEmpty);+ });++ test('parses the deleted list, leaving out rows it cannot read, and says '+ 'how long is left', () {+ final rows = parseDeletedSwarms({+ 'tabs': [+ {'id': 'a', 'name': 'A', 'purgeAt': 1000},+ {'id': 'b', 'name': 2, 'purgeAt': 1000},+ {'id': 'c', 'name': 'C'},+ 'nonsense',+ ],+ });+ expect(rows.map((r) => r.id), ['a']);+ expect(parseDeletedSwarms({'tabs': 'x'}), isEmpty);+ final now = DateTime(2026, 10, 31);+ expect(+ restoreTimeLeft(now.add(const Duration(days: 7)), now),+ '7 days left',+ );+ expect(+ restoreTimeLeft(now.add(const Duration(hours: 30)), now),+ '1 day left',+ );+ expect(+ restoreTimeLeft(now.add(const Duration(hours: 3)), now),+ 'Less than a day left',+ );+ });++ for (final brightness in Brightness.values) {+ testWidgets('pictures of Delete Swarm in ${brightness.name}', (+ tester,+ ) async {+ if (_shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ tester.view.devicePixelRatio = 2;+ tester.view.physicalSize = const Size(1800, 1300);+ addTearDown(tester.view.reset);+ late AppNotifier app;+ late _Backend backend;+ await tester.runAsync(() async {+ (app, backend) = await _swarms();+ backend.add('old', 'test-1');+ backend.deleted['old'] =+ backend.now - const Duration(days: 1).inMilliseconds;+ await app.superTabs.refreshTabs();+ });+ await _pump(tester, app, brightness: brightness);+ await _openMenu(tester);+ await captureWindow(+ tester,+ _shots,+ 'swarm-delete-menu-${brightness.name}',+ );+ await tester.tap(find.byKey(_deleteItem));+ await tester.pump();+ await tester.pump();+ await tester.enterText(find.byKey(_nameField), 'Alp');+ await tester.pump();+ await captureWindow(+ tester,+ _shots,+ 'swarm-delete-dialog-${brightness.name}',+ );+ await tester.tap(find.byKey(const ValueKey('swarm-delete-cancel')));+ await tester.pump();+ await _releaseAll(tester, app);+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+ }+}diff --git a/docs/swarms.md b/docs/swarms.mdindex 8fd397273..1b3af7854 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -1039,6 +1039,35 @@ again when the error changes, and otherwise at most every 5 minutes, and it saysThis comes from 2026-10-30. A backend release made every claim of a person's message to their own Buddy end busy fortwo hours. Nothing was lost, but nobody could tell.+## Deleting a Swarm++A Swarm's owner can delete it from the Swarm dropdown on its name: **Delete "name"…**, then type its name. Personal+cannot be deleted, and only the owner sees the item.++- Everyone loses it at once: it leaves every member's and invitee's list in the same write, and every open app is told.+ From then on, every read and write answers exactly as for a Swarm that does not exist, its owner's included.+- Its agents stop, its Product Managers too, and its machines are released: each machine's host closes the sessions and+ deletes the Swarm's folders there, as when a machine is removed. A start already launching makes the delete wait a moment.+- For 7 days its owner can restore it from the same dropdown (**Restore "name"**, with the days left). People, projects,+ chats and files come back; agents and machines do not, and are added again.+- After the 7 days the worker removes its records and stored files, and only its own (`backend/src/superTabs/purge.ts`).+ Chat file links keep working until then.++Design (`backend/src/superTabs/deletion.ts`):++- Growth: the purge removes everything of a deleted Swarm 7 days after the delete; nothing is kept after it.+- Concurrency: delete and restore are ordinary Swarm commands, one write at the head level; the purge runs only an hour+ after the restore window closed, and deletes the row only if it is still that deletion.+- Read cost: lists read the same indexes as before (a deleted Swarm lists no member); one extra field on the row reads.+- Scale: the purge reads due Swarms by their own index, 20 a pass; deleting a Swarm with 10x the messages is one+ indexed delete per collection.+- Compatibility: older apps see the Swarm leave their list and its reads refused, as when access is lost.+- Migration + rollback: two optional row fields, no migration. A rollback serves a deleted Swarm again to its members.+- Audience: the server checks the owner on every delete and restore; anyone else is told what a missing Swarm tells.+- Identity: the signed-in person's own; a Harness Team account sign-in never deletes.+- Failure: a refused delete says why; a file the purge cannot remove keeps its Swarm for the next pass.+- Platforms: Desktop deletes and restores; the phone and the web drop a deleted Swarm from their lists.+## Switching Swarms off on a computerSwarms are on by default. To run a computer's daemon without them, setdiff --git a/mobile/lib/swarm/swarm_inbox.dart b/mobile/lib/swarm/swarm_inbox.dartindex e26ffeffc..0790ed337 100644--- a/mobile/lib/swarm/swarm_inbox.dart+++ b/mobile/lib/swarm/swarm_inbox.dart@@ -456,6 +456,9 @@ class SwarmInbox extends ChangeNotifier {if (row['id'] is! String || row['name'] is! String) {throw const FormatException('Invalid tab');}+ // A deleted Swarm is never the person's to show, whatever lists it+ // (backend superTabs/deletion.ts): one marked so is left out.+ if (row['deletedAt'] != null) continue;final id = row['id'] as String;listed[id] = (id: id, name: row['name'] as String);changedAt[id] = (row['lastChangedAt'] as num?)?.toInt() ?? 0;diff --git a/mobile/test/swarm/swarm_inbox_test.dart b/mobile/test/swarm/swarm_inbox_test.dartindex b9d0633ad..4c3576b48 100644--- a/mobile/test/swarm/swarm_inbox_test.dart+++ b/mobile/test/swarm/swarm_inbox_test.dart@@ -154,6 +154,36 @@ void main() {expect(i.needs, isEmpty);});+ test('a Swarm its owner deleted leaves the switcher on the next read, and '+ 'a row marked deleted is never listed', () async {+ final fake = backend({+ 'a': [groupData('g1', status: 'needs_human')],+ 'b': [],+ 'c': [],+ });+ final i = inbox(fake);+ await i.refresh();+ expect([for (final s in i.swarms) s.id], ['a', 'b', 'c']);++ // Deleted: the server lists it to nobody, and its reads answer as for a+ // Swarm that does not exist.+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ listing('b', 'Swarm b'),+ {...listing('c', 'Swarm c'), 'deletedAt': 100},+ ],+ 'next': null,+ };+ fake.routes.remove('/api/super-tabs/a/parts');+ fake.routes.remove('/api/super-tabs/a/changes');+ await i.refresh();++ expect([for (final s in i.swarms) s.id], ['b']);+ expect(i.reader('a'), isNull);+ expect(i.reader('c'), isNull);+ expect(i.needs, isEmpty);+ });+test('a Swarm the person left takes its chat off a screen still holding it',() async {