Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

A closed tab's Personal project is deleted when empty, archived otherwise (#3929) (#3433)

harness-for-autonomous[bot]fd8d30065891
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 137f18f5c..dde39a142 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -22,6 +22,7 @@ import { sweepPendingUploads } from '../src/lib/pendingUploadSweep.js'
import { IGNORED_NOTE, type Command } from '../src/superTabs/commands.js'
import { nextMachineShareGrants } from '../src/lib/machineSharePolicy.js'
import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'
+import { SEED_RULES } from '../src/superTabs/policy.js'
import { stableId, type Agent, type SuperTabState } from '../src/superTabs/model.js'
import { agentDisplayName } from '../src/superTabs/agentNames.js'
import { roleVersion } from '../src/superTabs/projects.js'
@@ -5578,3 +5579,114 @@ describe('a migrated Swarm\'s kept old state (Stability 2.1)', () => {
for (const id of [tab, own]) expect((await db.superTab.findUnique({ where: { id }, select: { legacyState: true } }))!.legacyState).toEqual(OLD_STATE)
})
})
+
+// Task #3929 (for Diego's #3903): a closed tab's Personal project is deleted only if it has no message at that moment, in the same
+// write; a message that lands meanwhile makes it archived instead. Desktop sends it under one operation id from every computer.
+describe('a closed tab\'s Personal project', () => {
+ const person: AuthUser = { sub: '100000000000000000000391', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+ const personal = async (visibility: 'private' | 'public' = 'private') => {
+ await db.user.upsert({ where: { id: person.sub }, create: { id: person.sub, externalId: `fixture-${person.sub}`, email: person.email,
+ autonomousEnv: person.autonomousEnv }, update: {} })
+ const tab = (await store.create(person, 'personal-swarm', 'Personal', 'private')).id
+ const tabOperation = `personal-tab-${randomUUID()}`
+ const projectId = String((await run(tab, { type: 'project.create', name: 'Untitled tab', visibility, brief: '' }, person, undefined,
+ tabOperation)).result.projectId)
+ const chat = (await store.read(person, tab)).state.projects!.find(p => p.id === projectId)!.leadConversationId
+ return { tab, projectId, chat, tabOperation }
+ }
+
+ it('archives it when a message lands while it is being closed', async () => {
+ const { tab, projectId, chat, tabOperation } = await personal()
+ let sent = false
+ const raced = new SuperTabStore(beforeFirstWrite(db, async () => {
+ if (sent) return
+ sent = true
+ await run(tab, { type: 'message.send', conversationId: chat, text: 'Written as the tab closed', replyTo: null, recipientIds: [] }, person)
+ }))
+ const closed = await raced.execute(person, tab, { operationId: randomUUID(), command: { type: 'project.closeTab', projectId, tabOperation } as Command })
+ expect(sent).toBe(true)
+ expect(closed.result).toMatchObject({ outcome: 'archived' })
+ expect((await store.read(person, tab)).state.projects!.find(p => p.id === projectId)).toMatchObject({ archived: true })
+ })
+
+ // Security review 2 (Phonecheck2): a project whose instructions or rules the person saved is kept, also when the save lands
+ // while the tab closes.
+ const instructions = { type: 'instructions.save', baseRevision: 1, text: '# Mine\n\nKeep this.', summary: 'My own' }
+ const rulesSave = { type: 'rules.set', baseRevision: 0, rules: { ...SEED_RULES, mergeTrain: { enabled: true, everyMinutes: 10 } }, summary: 'My own rules' }
+ const kept = async (tab: string, projectId: string) => {
+ expect((await store.read(person, tab)).state.projects!.find(p => p.id === projectId)).toMatchObject({ archived: true })
+ expect(await db.superTabInstructionsRevision.count({ where: { tabId: tab, projectId } })).toBeGreaterThan(0)
+ }
+ for (const [what, save] of [['instructions', instructions], ['rules', rulesSave]] as const) {
+ it(`archives it, keeping what was written, when its ${what} were saved before the close`, async () => {
+ const { tab, projectId, tabOperation } = await personal()
+ await run(tab, { ...save, projectId } as Command, person)
+ const closed = await store.execute(person, tab, { operationId: randomUUID(), command: { type: 'project.closeTab', projectId, tabOperation } as Command })
+ expect(closed.result).toMatchObject({ outcome: 'archived' })
+ await kept(tab, projectId)
+ if (what === 'rules') expect(await db.superTabProjectRules.count({ where: { tabId: tab, projectId } })).toBe(1)
+ })
+ it(`archives it, keeping what was written, when its ${what} are saved while it is being closed`, async () => {
+ const { tab, projectId, tabOperation } = await personal()
+ let saved = false
+ const raced = new SuperTabStore(beforeFirstWrite(db, async () => {
+ if (saved) return
+ saved = true
+ await run(tab, { ...save, projectId } as Command, person)
+ }))
+ const closed = await raced.execute(person, tab, { operationId: randomUUID(), command: { type: 'project.closeTab', projectId, tabOperation } as Command })
+ expect(saved).toBe(true)
+ expect(closed.result).toMatchObject({ outcome: 'archived' })
+ await kept(tab, projectId)
+ if (what === 'rules') expect(await db.superTabProjectRules.count({ where: { tabId: tab, projectId } })).toBe(1)
+ })
+ }
+
+ // Security review 2, second pass (Phonecheck2): another person's first rules save shares a guard with the close, and with a
+ // project delete, through the project's Lead chat, so the two never both commit on the same project.
+ const collaborator: AuthUser = { sub: '100000000000000000000392', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+ const withCollaborator = async () => {
+ const made = await personal('public')
+ await db.user.upsert({ where: { id: collaborator.sub }, create: { id: collaborator.sub, externalId: `fixture-${collaborator.sub}`,
+ email: collaborator.email, autonomousEnv: collaborator.autonomousEnv }, update: {} })
+ // The person has one Personal Swarm: the collaborator joins it once.
+ if (!(await store.read(person, made.tab)).state.people.some(p => p.id === collaborator.sub)) {
+ const invited = await run(made.tab, { type: 'invite.create', email: collaborator.email, role: 'collaborator', conversationId: 'lead' }, person)
+ await run(made.tab, { type: 'invite.accept', inviteId: invited.result.inviteId as string }, collaborator)
+ }
+ return made
+ }
+ const racing = (tab: string, projectId: string, saved: { done: boolean }) => new SuperTabStore(beforeFirstWrite(db, async () => {
+ if (saved.done) return
+ saved.done = true
+ await run(tab, { ...rulesSave, projectId } as Command, collaborator)
+ }))
+ it('archives it, keeping the rules, when another person saves its first rules while it is being closed', async () => {
+ const { tab, projectId, tabOperation } = await withCollaborator()
+ const saved = { done: false }
+ const closed = await racing(tab, projectId, saved).execute(person, tab, { operationId: randomUUID(),
+ command: { type: 'project.closeTab', projectId, tabOperation } as Command })
+ expect(saved.done).toBe(true)
+ expect(closed.result).toMatchObject({ outcome: 'archived' })
+ expect((await store.read(person, tab)).state.projects!.find(p => p.id === projectId)).toMatchObject({ archived: true })
+ expect(await db.superTabProjectRules.count({ where: { tabId: tab, projectId } })).toBe(1)
+ })
+ it('leaves no rules behind when another person saves its first rules while it is deleted', async () => {
+ const { tab, projectId } = await withCollaborator()
+ const saved = { done: false }
+ await racing(tab, projectId, saved).execute(person, tab, { operationId: randomUUID(), command: { type: 'project.delete', projectId } })
+ expect(saved.done).toBe(true)
+ expect((await store.read(person, tab)).state.projects!.some(p => p.id === projectId)).toBe(false)
+ expect(await db.superTabProjectRules.count({ where: { tabId: tab, projectId } })).toBe(0)
+ })
+
+ it('does its work once under one operation id, from any of the person\'s computers', async () => {
+ const { tab, projectId, tabOperation } = await personal()
+ const operationId = `close-tab-${randomUUID()}`
+ const first = await store.execute(person, tab, { operationId, command: { type: 'project.closeTab', projectId, tabOperation } as Command })
+ const again = await store.execute(person, tab, { operationId, command: { type: 'project.closeTab', projectId, tabOperation } as Command })
+ expect(first.result).toMatchObject({ outcome: 'deleted' })
+ expect(again.result).toEqual(first.result)
+ expect((await store.read(person, tab)).state.projects!.some(p => p.id === projectId)).toBe(false)
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index d0f1a80ff..71419c5e4 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -250,6 +250,9 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('project.create'), name: title, visibility: z.enum(['public', 'private']), brief: z.string().trim().max(8000).default('') }).strict(),
z.object({ type: z.literal('project.rename'), projectId: id, name: title }).strict(),
z.object({ type: z.literal('project.delete'), projectId: id }).strict(),
+ // A closed tab's project in the person's own Personal Swarm (task #3929, desktop personal_projects.dart): deleted when none of
+ // its conversations has a message, archived otherwise. `tabOperation`: the request that created it, `personal-tab-…`.
+ z.object({ type: z.literal('project.closeTab'), projectId: id, tabOperation: z.string().regex(/^personal-tab-[A-Za-z0-9_-]{1,120}$/) }).strict(),
z.object({ type: z.literal('project.sharing'), projectId: id, visibility: z.enum(['public', 'private']), memberIds: z.array(id).max(200) }).strict(),
// A project's Board settings (boardRights.ts, task #3819), set by its owner or the Swarm's owner.
z.object({ type: z.literal('project.boardMode'), projectId: id, on: z.boolean() }).strict(),
@@ -1039,6 +1042,18 @@ function placeAnswer(command: Command, context: CommandContext): Command {
return reply && reply.id === command.answers && inThread(reply) ? { ...command, replyTo: command.answers, answers: undefined } : command
}
+/** The project `project.closeTab` may close (task #3929): a no-repo tab's, in the caller's own Personal Swarm, by that person.
+ * Desktop creates a tab's project with the request `personal-tab-…` (desktop personal_projects.dart personalProjectOperation),
+ * and `project.create` makes its id from that request and its sender (applyCommandOnce `operationId`), so [tabOperation]
+ * proves the project is that person's tab's: it must make exactly [projectId]. Anything else reads as a project not there. */
+function closingTabProject(state: SuperTabState, actor: Actor, projectId: string, tabOperation: string): SwarmProject {
+ const tabs = actor.kind === 'person' && actor.userId === state.ownerId && isPersonalSwarm(state)
+ && stableId(state.id, actorKey(actor), tabOperation) === projectId
+ const project = tabs ? projectsOf(state).find(p => p.id === projectId) : undefined
+ if (!project || project.repository) fail('NOT_FOUND', 'This project is unavailable.', 404)
+ return project
+}
+
function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command, context: CommandContext): CommandEffects {
// A credential someone pasted, or an agent echoed from its terminal, is gone before anything is stored or delivered
// (Oct 2026: a Harness access token in a shared Lead chat). The sender's result says what went.
@@ -1616,6 +1631,20 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
?? state.conversations.find(c => c.id === start.request.conversationId && !isSwarmBuddyChat(c))?.projectId
/** Deleting its project is the only removal that takes a Lead. `close: false` when its host already closed the session. */
+ /** [project] deleted with its own agents, its Lead included (their hosts close their sessions), its starts and machines' lists. */
+ const deleteWholeProject = (project: SwarmProject) => {
+ // Read before its agents go: a contributed start still settling whose agent is already gone never settles (projects.ts).
+ const orphaned = new Set((state.starts ?? []).filter(s => s.poolGeneration && s.harnessId && !s.poolSettled && !s.error
+ && !state.agents.some(a => a.machineId === s.request.machineId && a.harnessId === s.harnessId)).map(s => s.id))
+ for (const target of state.agents.filter(a => agentProjectId(state, a) === project.id)) removeAgent(target, { lead: true })
+ // Its sessions still starting in people's one Buddy chats go with it (their chats belong to no project).
+ for (const start of state.starts ?? []) {
+ if (start.request.buddySession?.projectId === project.id && !start.harnessId && !start.error) start.error = 'Its project was deleted.'
+ }
+ deleteProject(state, actor, project.id, orphaned, context.now)
+ // No machine keeps it any more; one kept only for it now serves none (machines.ts machineProjectRefusal).
+ for (const pool of state.machines ?? []) if (pool.projects) pool.projects = pool.projects.filter(id => id !== project.id)
+ }
const removeAgent = (target: Agent, { lead = false, close = true } = {}) => {
// A person's removal stands: a record of this session must not bring it back when it reopens (closedAgents.ts).
dropRemovedRecord(state, target.machineId, target.harnessId)
@@ -2115,18 +2144,30 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
case 'project.delete': {
// Its owner confirmed a permanent delete, so the project takes its own agents with it, its Lead included, and their
// hosts close their sessions. The Swarm's owner deletes one nobody owns (task #3073).
- const project = deletableProject(state, actor, command.projectId)
- // Read before its agents go: a contributed start still settling whose agent is already gone never settles (projects.ts).
- const orphaned = new Set((state.starts ?? []).filter(s => s.poolGeneration && s.harnessId && !s.poolSettled && !s.error
- && !state.agents.some(a => a.machineId === s.request.machineId && a.harnessId === s.harnessId)).map(s => s.id))
- for (const target of state.agents.filter(a => agentProjectId(state, a) === project.id)) removeAgent(target, { lead: true })
- // Its sessions still starting in people's one Buddy chats go with it (their chats belong to no project).
- for (const start of state.starts ?? []) {
- if (start.request.buddySession?.projectId === project.id && !start.harnessId && !start.error) start.error = 'Its project was deleted.'
+ deleteWholeProject(deletableProject(state, actor, command.projectId))
+ break
+ }
+ case 'project.closeTab': {
+ // The Personal Swarm's owner closes a tab's project (task #3929): deleted only if none of its conversations, dormant ones
+ // loaded with it, has a message now. A message written meanwhile changes one of those parts, so this write conflicts and
+ // runs again on it, and archives instead.
+ const project = closingTabProject(state, actor, command.projectId, command.tabOperation)
+ const groups = state.conversations.filter(c => c.projectId === project.id || c.id === project.leadConversationId)
+ // What the person wrote without a message is theirs too (security review 2, review of #3929): instructions saved past the
+ // built-in first revision, a note told to its PM, or any rules record. A save meanwhile changes the project's part, or is
+ // read in this write (store.ts). Rules that could not be read (undefined) count as written: nothing is deleted unchecked.
+ const written = (project.instructionsRevision ?? 0) > 1 || (project.notesRevision ?? 0) > 0 || context.projectRules !== null
+ if (!written && groups.every(c => !c.lastMessageSequence)) {
+ deleteWholeProject(project)
+ result.outcome = 'deleted'
+ break
}
- deleteProject(state, actor, command.projectId, orphaned, context.now)
- // No machine keeps it any more; one kept only for it now serves none (machines.ts machineProjectRefusal).
- for (const pool of state.machines ?? []) if (pool.projects) pool.projects = pool.projects.filter(id => id !== project.id)
+ // Kept, read-only (an archived conversation is written no more: store.ts) and out of the sidebar; its agents leave.
+ for (const target of state.agents.filter(a => agentProjectId(state, a) === project.id)) removeAgent(target, { lead: true })
+ mutableProjects(state)
+ projectOf(state, project.id).archived = true
+ for (const group of groups) group.archived = true
+ result.outcome = 'archived'
break
}
case 'project.sharing': {
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index cfe488400..0e1581b28 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -112,9 +112,15 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
break
case 'project.report': case 'project.repository':
// The coordinator's own writes check it leads the project, which a concurrent Lead change ends (review of phase 2).
- case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName': case 'rules.set':
+ case 'instructions.save': case 'note.add': case 'note.remove': case 'project.coordinatorName':
leadCheck(command.projectId)
break
+ // A rules save writes its own collection, no part of the project: by anyone, it guards on the project's Lead chat, which a
+ // project delete and a tab's close write, so a first save never lands on a project being deleted (security review 2 of
+ // #3929). The Lead check above is part of the same touch.
+ case 'rules.set':
+ group(leadGroupOf(command.projectId))
+ break
// An older CLI's rule is a save to its project's instructions, the coordinator's like instructions.save (commands.ts).
case 'rule.set':
leadCheck(command.projectId ?? (actor.kind === 'agent' ? agentProject(actor.agentId) : undefined))
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index dab665824..7600024a8 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -112,6 +112,8 @@ export interface SwarmProject {
/** Its owner's last "New repository" from New Project (task #1788): asked, then what GitHub's sign-in made of it. The
* app that asked starts the Product Manager in it once `created`; the next ask replaces it. */
repositoryCreation?: RepositoryCreation
+ /** A closed tab's project that had messages (commands.ts project.closeTab, task #3929): read-only and out of the sidebar. */
+ archived?: true
}
/** A new repository asked for a project (store.ts startRepositoryCreation, finishRepositoryCreation). [at] (ms) and [by]
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 2f247019e..6c17182bd 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -247,7 +247,7 @@ function namedFor(command: Command): Named {
// Deleting a project or changing who reads it reaches every one of its groups, dormant ones too: their terminal
// contexts are revoked from the groups the command loaded (native.ts revokeNativeContexts).
return { groupIds, startIds: has('startId') ? [field('startId')!] : [],
- projectIds: command.type === 'project.delete' || command.type === 'project.sharing' ? [command.projectId] : [] }
+ projectIds: command.type === 'project.delete' || command.type === 'project.sharing' || command.type === 'project.closeTab' ? [command.projectId] : [] }
}
/** What a receipt keeps of a command's reply besides its result: the parts it wrote and when (design section 4.7). */
@@ -1900,7 +1900,7 @@ export class SuperTabStore {
const selfLeave = actor.kind === 'person' && command.type === 'member.remove' && command.userId === actor.userId
if (!selfLeave) {
if (command.type === 'agent.remove' && !original.agents.some(a => a.id === command.agentId) ||
- command.type === 'project.delete' && !projectsOf(original).some(p => p.id === command.projectId)) {
+ (command.type === 'project.delete' || command.type === 'project.closeTab') && !projectsOf(original).some(p => p.id === command.projectId)) {
// Retrying one's own completed removal returns only its empty
// receipt. The removed object no longer exists to authorize against.
author(original, actor, true)
@@ -2033,6 +2033,8 @@ export class SuperTabStore {
if (command.type === 'note.add' || command.type === 'note.remove') context.notes = await readNotes(tx, tabId, command.projectId)
// A stale rules save is refused with the newest revision, to merge (policy.ts); null is the seed.
if (command.type === 'rules.set') context.projectRules = await readRules(tx, tabId, command.projectId, true)
+ // A closed tab's project with a rules record of the person's is kept, not deleted (commands.ts project.closeTab).
+ if (command.type === 'project.closeTab') context.projectRules = await readRules(tx, tabId, command.projectId, true)
// A start or an assignment meets its project's machine rules (machineRules.ts): one indexed read of the newest revision.
// Only the machine rules are read here, so a record broken elsewhere still applies those that pass (security review 1).
if (command.type === 'agent.start' || command.type === 'work.assign') {
@@ -2352,13 +2354,15 @@ export class SuperTabStore {
stableId(s.request.machineId, s.harnessId) === command.agentId)
if (start?.routeDecisionId) await closeUnassignedStart(tx, tabId, start.routeDecisionId, start.id, 'stopped', context.now)
}
- // Role texts are written no more (project instructions): a deleted project takes the ones it had.
- if (command.type === 'project.delete') await tx.superTabRoleText.deleteMany({ where: { tabId, projectId: command.projectId } })
+ // Role texts are written no more (project instructions): a deleted project takes the ones it had. A closed tab's project
+ // deleted because it was empty is a deleted project too (task #3929).
+ const deleted = command.type === 'project.delete' || (command.type === 'project.closeTab' && effects.result.outcome === 'deleted') ? command.projectId : null
+ if (deleted) await tx.superTabRoleText.deleteMany({ where: { tabId, projectId: deleted } })
if (effects.instructions) await writeInstructions(tx, tabId, effects.instructions)
if (effects.notes) await writeNotes(tx, tabId, effects.notes, context.now)
if (effects.projectRules) await writeRules(tx, tabId, effects.projectRules)
- if (command.type === 'project.delete') await deleteInstructions(tx, tabId, command.projectId)
- if (command.type === 'project.delete') await deleteRules(tx, tabId, command.projectId)
+ if (deleted) await deleteInstructions(tx, tabId, deleted)
+ if (deleted) await deleteRules(tx, tabId, deleted)
if (effects.terminal) await this.writeTerminal(tx, tabId, effects.terminal, context.now)
// 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')) {
diff --git a/backend/src/superTabs/tabProjectClose.test.ts b/backend/src/superTabs/tabProjectClose.test.ts
new file mode 100644
index 000000000..f63041c0e
--- /dev/null
+++ b/backend/src/superTabs/tabProjectClose.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, stableId, type Actor } from './model.js'
+import { PERSONAL_SWARM_OPERATION } from './deletion.js'
+import { SEED_RULES } from './policy.js'
+
+// Task #3929 (for Diego's #3903): a no-repo tab's project in the Personal Swarm goes when the tab closes, if it never had a
+// message; otherwise it is archived, read-only and out of the sidebar. Only the Personal Swarm's owner, only a tab's project.
+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 configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+
+function setup({ personal = true } = {}) {
+ const id = personal ? stableId('super-tab', 'test', 'owner', PERSONAL_SWARM_OPERATION) : 'team-swarm'
+ let state = createSuperTab(id, 'Personal', { id: 'owner', email: owner.email }, 'test')
+ state.people.push({ id: 'peer', email: peer.email, role: 'collaborator', generation: 'first' })
+ let next = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}, operationId = `op${next++}`) => {
+ const effects = applyCommand(state, actor, command, { operationId, now: 1000, contribution: { machineOwnerId: 'owner', contributorId: 'owner' }, ...context })
+ state = effects.state
+ return effects
+ }
+ const create = (operationId: string) => run({ type: 'project.create', name: 'Untitled tab', visibility: 'private', brief: '' }, owner, {}, operationId)
+ .result.projectId as string
+ /** Desktop's close of the tab whose project request was [tabOperation]. */
+ const close = (projectId: string, tabOperation: string, actor: Actor = owner) => run({ type: 'project.closeTab', projectId, tabOperation } as Command, actor,
+ { projectRules: null })
+ const project = (projectId: string) => state.projects?.find(p => p.id === projectId)
+ const chatOf = (projectId: string) => state.conversations.find(c => c.id === project(projectId)?.leadConversationId)
+ const refusal = (body: () => unknown): string | null => { try { body(); return null } catch (error) { return (error as { code?: string }).code ?? 'thrown' } }
+ return { run, create, close, project, chatOf, refusal, get state() { return state } }
+}
+
+describe('closing a tab\'s Personal project', () => {
+ it('deletes it when none of its conversations has a message', () => {
+ const f = setup()
+ const tab = f.create('personal-tab-abc')
+ const chat = f.chatOf(tab)!.id
+ expect(f.close(tab, 'personal-tab-abc').result).toMatchObject({ outcome: 'deleted' })
+ expect(f.project(tab)).toBeUndefined()
+ expect(f.state.conversations.some(c => c.id === chat)).toBe(false)
+ })
+
+ it('archives it, read-only and with its agents gone, when one of its conversations has a message', () => {
+ const f = setup()
+ const tab = f.create('personal-tab-abc')
+ const chat = f.chatOf(tab)!.id
+ f.run({ type: 'message.send', conversationId: chat, text: 'A note to keep', replyTo: null, recipientIds: [] })
+ // The store numbers the message as it writes it (parts/commit.ts numberMessages): its chat's sequence moves.
+ f.chatOf(tab)!.lastMessageSequence = 1
+ const lead = f.run({ type: 'agent.add', conversationId: chat, machineId: 'owner-mac', harnessId: 'pm', name: 'pm', configuration, lead: true }).result.agentId as string
+ expect(f.close(tab, 'personal-tab-abc').result).toMatchObject({ outcome: 'archived' })
+ expect(f.project(tab)).toMatchObject({ archived: true })
+ expect(f.chatOf(tab)).toMatchObject({ archived: true })
+ expect(f.state.agents.some(a => a.id === lead)).toBe(false)
+ })
+
+ // Security review 2 (Phonecheck2): what the person wrote without a message, saved instructions or a rules record, is kept.
+ it('archives it, never deletes it, when the person saved its instructions or its rules without a message', () => {
+ const f = setup()
+ const written = f.create('personal-tab-instructions')
+ f.run({ type: 'instructions.save', projectId: written, baseRevision: 1, text: '# Mine\n\nKeep this.', summary: 'My own' } as Command,
+ owner, { instructions: { revision: 1, text: 'template' } } as Partial<CommandContext>)
+ expect(f.project(written)!.instructionsRevision).toBe(2)
+ expect(f.close(written, 'personal-tab-instructions').result).toMatchObject({ outcome: 'archived' })
+ expect(f.project(written)).toMatchObject({ archived: true })
+ const ruled = f.create('personal-tab-rules')
+ expect(f.run({ type: 'project.closeTab', projectId: ruled, tabOperation: 'personal-tab-rules' } as Command, owner,
+ { projectRules: { revision: 1, rules: SEED_RULES } }).result).toMatchObject({ outcome: 'archived' })
+ expect(f.project(ruled)).toMatchObject({ archived: true })
+ // A note the person told its PM is theirs too (review of #3929): it goes with a delete.
+ const noted = f.create('personal-tab-noted')
+ const pm = f.run({ type: 'agent.add', conversationId: f.chatOf(noted)!.id, machineId: 'owner-mac', harnessId: 'pm-noted', name: 'pm', configuration, lead: true }).result.agentId as string
+ f.run({ type: 'note.add', projectId: noted, text: 'Ship on Fridays', askedBy: 'owner' } as Command, { kind: 'agent', agentId: pm, machineOwnerId: 'owner' }, { notes: [] })
+ expect(f.close(noted, 'personal-tab-noted').result).toMatchObject({ outcome: 'archived' })
+ // The built-in instructions it started with, and no rules record, are not the person's: an untouched tab still goes.
+ const untouched = f.create('personal-tab-untouched')
+ expect(f.run({ type: 'project.closeTab', projectId: untouched, tabOperation: 'personal-tab-untouched' } as Command, owner,
+ { projectRules: null }).result).toMatchObject({ outcome: 'deleted' })
+ })
+
+ it('refuses a repo project, a project that is not a tab\'s, another person, an agent, and a Swarm that is not Personal', () => {
+ const f = setup()
+ const repo = f.create('personal-repo-abc')
+ expect(f.refusal(() => f.close(repo, 'personal-repo-abc'))).not.toBeNull()
+ // A tab's request that did not make this project: another project of theirs is never closed under a tab's name.
+ const other = f.create('some-other-project')
+ expect(f.refusal(() => f.close(other, 'personal-tab-abc'))).toBe('NOT_FOUND')
+ const tab = f.create('personal-tab-with-repo')
+ f.state.projects!.find(p => p.id === tab)!.repository = { machineId: 'owner-mac', cwd: '/code/app', repositoryUrl: null }
+ expect(f.refusal(() => f.close(tab, 'personal-tab-with-repo'))).toBe('NOT_FOUND')
+ const mine = f.create('personal-tab-def')
+ expect(f.refusal(() => f.close(mine, 'personal-tab-def', peer))).not.toBeNull()
+ expect(f.refusal(() => f.close(mine, 'personal-tab-def', { kind: 'agent', agentId: 'pm', machineOwnerId: 'owner' }))).not.toBeNull()
+ expect(f.project(mine)).toBeDefined()
+ const team = setup({ personal: false })
+ const theirs = team.create('personal-tab-abc')
+ expect(team.refusal(() => team.close(theirs, 'personal-tab-abc'))).toBe('NOT_FOUND')
+ expect(team.project(theirs)).toBeDefined()
+ })
+})
diff --git a/docs/plans/2026-11-06-tab-project-close-plan.md b/docs/plans/2026-11-06-tab-project-close-plan.md
new file mode 100644
index 000000000..193941006
--- /dev/null
+++ b/docs/plans/2026-11-06-tab-project-close-plan.md
@@ -0,0 +1,57 @@
+# A closed tab's Personal project: deleted when empty, archived otherwise: implementation plan
+
+> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,
+> the failing test committed before its code. No Execution Handoff.
+
+**Goal:** One server command, `project.closeTab { projectId, tabOperation }`, that the person's Desktop sends when a no-repo tab closes
+(#3903): in the caller's own Personal Swarm, a tab's project is deleted if none of its conversations has a message at that
+moment, and archived (read-only, out of the sidebar) otherwise. Anything else is refused (task #3929, requested by Diego
+through Harness).
+
+**Architecture:** A tab's project is created with the operation id `personal-tab-<hash>` (desktop personal_projects.dart
+`personalProjectOperation`), which becomes its id (commands.ts `project.create`). The command:
+
+- **Who and what:** a person, the Swarm's owner, in their own Personal Swarm (`deletion.ts isPersonalSwarm`); a project with no
+ repository whose id is the one `project.create` made from `tabOperation` (a `personal-tab-…` request) and this caller. A
+ project's id is a hash of the Swarm, its sender and the request, so this proves it is the caller's tab's project, with no
+ marker stored, and covers tab projects made before. A repo project (`personal-repo-`, or any with a repository), another
+ Swarm, another person, or an agent: refused, in the words a missing project gets.
+- **Empty:** every conversation of the project, dormant ones loaded (the command names its project, as `project.delete`
+ does), has `lastMessageSequence` 0, its instructions are still the built-in first revision, no note was told to its PM, and it has no rules record (read
+ in the same write; unreadable counts as written). What the person wrote without a message is theirs (security review 2,
+ Phonecheck2). Then it is deleted exactly as `project.delete` deletes (its agents, starts, machines'
+ lists). Otherwise the project is marked `archived: true` and each of its conversations archived, its Lead chat included,
+ and its agents leave; posts there are then refused (store.ts: an archived conversation is not written).
+- **Atomic:** the check and the delete are one write. A message written meanwhile changes the same conversation part, so the
+ two writes conflict and the command runs again on the new state, which archives instead. So does an instructions save (it
+ changes the project's part) and a rules save, by anyone, which guards on the project's Lead chat (parts/touches.ts) that the close and a delete write
+ (tested with another person saving the first rules during a close and during a delete).
+- **Idempotent:** Desktop sends it under one operation id from every computer: the receipt replays the first answer
+ (`result.outcome`: `deleted` or `archived`).
+
+**Tech Stack:** TypeScript backend, vitest, Mongo integration.
+
+## Global Constraints
+- Never a repo project, never another person's Swarm or project, never a project with a message: the server decides.
+- Two independent security reviews (it deletes data).
+
+## Design
+- growth: removes data; an archived project stays, as before closing, and leaves the sidebar.
+- concurrency: the project's conversation parts and the head, in the Swarm's usual write; a concurrent message conflicts.
+- read cost: the project's own groups, dormant ones included, by its id, as `project.delete` reads them.
+- scale: one command per closed tab; no scan.
+- compatibility: a new command; older apps never send it; an archived project reads as a project with `archived` set.
+- migration + rollback: none. Rollback leaves archived projects archived; nothing is read differently.
+- audience: the Personal Swarm's owner alone, enforced by the server.
+- identity: the person's own command; no agent may send it.
+- failure: a refusal says the project is not there; a race archives rather than deletes.
+- platforms: backend; Desktop's #3903 sends it.
+
+## Review Focus
+- No path deletes a project with any message, a repo project, or one outside the caller's own Personal Swarm.
+
+## Task 1: the command
+- [x] Test first (unit): an empty tab project is deleted; one with a message is archived (project and conversations, read-only);
+ a repo project, another person, an agent and a Swarm that is not Personal are refused.
+- [x] Test first (integration): a message sent during the call archives it instead; the same operation id twice is a no-op.
+- [x] Code.