Skip to content

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

feat(swarms): add private projects and Cmd-S creation (#1464)

Deedd16a4bba72a
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index c0adc1d65..c0ed6cb02 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -69,6 +69,132 @@ afterAll(async () => {
await replica?.stop()
})
+describe('private swarm projects on the real control API', () => {
+ it('uses one contributed machine across projects with a separate authorized checkout for each', async () => {
+ const { tab } = await fixture()
+ const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
+ const machineId = 'swarm-pool-host'
+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: 'fixture-swarm-pool', managerId: 'fixture',
+ autonomousEnv: 'prod', authMode: 'remote' } })
+ const project = (await run(tab, { type: 'project.create', name: 'Second project', visibility: 'private', brief: '' })).result
+ const conversationId = String(project.conversationId), projectId = String(project.projectId)
+ await run(tab, { type: 'agent.add', conversationId, machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Project lead', configuration: config, lead: true,
+ project: { cwd: '/lead/second', repositoryUrl: 'https://github.com/example/second' } })
+ await run(tab, { type: 'machine.contribute', machineId, name: 'Shared capacity', cwd: '/swarm-root',
+ engines: ['codex'], maxAgents: 2 }, host)
+ await expect(run(tab, { type: 'tab.project', machineId, project: { cwd: '/unrelated', repositoryUrl: null } }))
+ .rejects.toMatchObject({ code: 'HOST_REQUIRED' })
+ const request = { conversationId, machineId, engine: 'codex', name: 'Builder',
+ cwd: `/swarm-root/${projectId}`, worktree: true,
+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
+ await expect(run(tab, { type: 'agent.start', request })).rejects.toMatchObject({ code: 'PROJECT_CONTRIBUTION' })
+ await run(tab, { type: 'machine.contribute', machineId, name: 'Shared capacity', cwd: '/swarm-root',
+ scope: 'swarm', engines: ['codex'], maxAgents: 2 }, host)
+ const pool = (await store.hostPools(host, machineId))[0]!
+ await store.observeMachine(host, tab, machineId, { generation: pool.machine.generation,
+ resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, projectDiskFreeBytes: 100e9,
+ diskFreeBytes: 100e9, diskTotalBytes: 500e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [] })
+ expect(pool.projects).toEqual([])
+ await expect(run(tab, { type: 'agent.start', request: { ...request, cwd: '/swarm-root/lead' } }))
+ .rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })
+ const secondStart = (await run(tab, { type: 'agent.start', request })).result.startId as string
+ await run(tab, { type: 'agent.start', request: { ...request, conversationId: 'lead', cwd: '/swarm-root/lead' } })
+ const queued = (await store.hostPools(host, machineId))[0]!
+ expect(queued.starts).toHaveLength(2)
+ expect(queued.projects!.find(p => p.id === projectId)).toMatchObject({
+ repository: { machineId: 'test-host', cwd: '/lead/second', repositoryUrl: 'https://github.com/example/second' },
+ conversationIds: [conversationId],
+ })
+ expect((await store.read(host, tab)).state.projects!.some(p => p.id === projectId)).toBe(false)
+ const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, machineId)
+ await hostRun({ type: 'agent.startDispatch', startId: secondStart })
+ const started = await hostRun({ type: 'agent.started', startId: secondStart, harnessId: 'second-builder', configuration: config })
+ await hostRun({ type: 'agent.startSettled', startId: secondStart, warning: null })
+ const agentId = String(started.result.agentId)
+ expect((await store.read(host, tab, agentId)).state.conversations.map(c => c.id)).toEqual([conversationId])
+ await expect(store.messages(host, tab, 'lead', {}, agentId)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ expect(await db.machineShare.findUnique({ where: { machineId } })).toBeNull()
+ })
+
+ it('revokes chat, terminal observers, native contexts and old receipts together', async () => {
+ const { tab } = await fixture()
+ await invite(tab)
+ const project = (await run(tab, { type: 'project.create', name: 'Private project', visibility: 'private', brief: '' })).result
+ const conversationId = String(project.conversationId), projectId = String(project.projectId)
+ const harnessId = randomUUID()
+ const agentId = String((await run(tab, { type: 'agent.add', conversationId, machineId: 'test-host', harnessId,
+ name: 'Private lead', configuration: config, lead: true })).result.agentId)
+ await run(tab, { ...message('Private result'), conversationId } as Command)
+ expect((await store.read(peer, tab)).state.projects!.map(p => p.id)).not.toContain(projectId)
+ await expect(store.messages(peer, tab, conversationId, {})).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(store.native.open(peer, tab, { operationId: randomUUID(), conversationId, agentId })).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ expect(await store.mayObserve(peer, tab, 'test-host', harnessId, host.sub)).toBe(false)
+ expect((await store.hostTabs(host, 'test-host')).find(t => t.agent.id === agentId)!.observers.map(p => p.userId)).not.toContain(peer.sub)
+ await expect(store.messages(host, tab, 'lead', {}, agentId)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+
+ await run(tab, { type: 'project.sharing', projectId, visibility: 'private', memberIds: [peer.sub] })
+ expect((await store.messages(peer, tab, conversationId, {})).messages.map(m => m.text)).toContain('Private result')
+ expect(await store.mayObserve(peer, tab, 'test-host', harnessId, host.sub)).toBe(true)
+ const context = await store.native.open(peer, tab, { operationId: randomUUID(), conversationId, agentId })
+ const command = { ...message('Shared review'), conversationId } as Command
+ const operationId = randomUUID()
+ await run(tab, command, peer, undefined, operationId)
+ await run(tab, { type: 'project.sharing', projectId, visibility: 'private', memberIds: [] })
+ await expect(run(tab, command, peer, undefined, operationId)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(store.native.read(host, tab, context.contextId)).rejects.toMatchObject({ code: 'NATIVE_CONTEXT_REVOKED' })
+ expect(await store.mayObserve(peer, tab, 'test-host', harnessId, host.sub)).toBe(false)
+
+ // Removing a roster row cannot erase the terminal's private history.
+ await run(tab, { type: 'agent.remove', agentId })
+ const other = await fixture()
+ await expect(run(other.tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId,
+ name: 'Moved lead', configuration: config, lead: false })).rejects.toMatchObject({ code: 'PROJECT_SESSION' })
+ })
+
+ it('requests one consolidation after five minutes and remains quiet without new reports', async () => {
+ let now = 10_000
+ const timed = new SuperTabStore(db, () => now)
+ const tab = (await timed.create(owner, randomUUID(), 'Updates', 'public')).id
+ const execute = (command: Command, asAgentId?: string) => timed.execute(asAgentId ? host : owner, tab,
+ { operationId: randomUUID(), command }, asAgentId)
+ const lead = String((await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'test-host',
+ harnessId: randomUUID(), name: 'Lead', configuration: config, lead: true })).result.agentId)
+ const updates = async () => (await timed.deliveries(host, tab, lead)).filter(d => d.conversationId === 'lead')
+ const group = String((await execute({ type: 'conversation.create', title: 'Work', brief: 'Implement it',
+ checks: [{ description: 'Verified', independent: true }] })).result.conversationId)
+ expect(await updates()).toEqual([])
+ now += 299_999
+ expect(await updates()).toEqual([])
+ now++
+ const polls = await Promise.all(Array.from({ length: 3 }, () => updates()))
+ const ids = new Set(polls.flat().map(d => d.id))
+ expect(ids.size).toBe(1)
+ const requests = await db.superTabMessage.findMany({ where: { tabId: tab, conversationId: 'lead' } })
+ expect(requests).toHaveLength(1)
+ expect(requests[0]!.source).toMatchObject({ kind: 'update-request' })
+ await execute({ ...message('New evidence'), conversationId: group } as Command)
+ now += 300_000
+ expect((await updates()).map(d => d.id)).toEqual([...ids])
+ const revision = (await timed.read(owner, tab)).revision
+ await execute({ type: 'project.report', projectId: 'lead', throughRevision: revision,
+ text: 'The implementation is ready. Verification is next.' }, lead)
+ expect(await updates()).toEqual([])
+ now += 3_600_000
+ expect(await updates()).toEqual([])
+ expect((await db.superTabMessage.findMany({ where: { tabId: tab, conversationId: 'lead' } })).filter(m =>
+ (m.source as Record<string, unknown>)?.kind === 'project-report')).toHaveLength(1)
+ await execute({ type: 'project.cadence', projectId: 'lead', minutes: 15 })
+ await execute({ ...message('Tests passed'), conversationId: group } as Command)
+ now += 899_999
+ expect(await updates()).toEqual([])
+ now++
+ expect(await updates()).toHaveLength(1)
+ })
+})
+
describe('Super Tabs on a real Mongo replica set', () => {
it('contributes project capacity without sharing the computer and fences host execution', async () => {
const tab = (await store.create(owner, randomUUID(), 'Machine pool')).id
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 0d45ba980..7bbb0e07d 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -999,6 +999,16 @@ model SuperTab {
@@index([autonomousEnv, machineIds])
}
+// A terminal retains its history when removed from a roster. These bindings
+// prevent contributing a private session to another project's audience later.
+model SuperTabSessionScope {
+ id String @id @map("_id")
+ scopeIds String[]
+ privateScope String?
+
+ @@index([scopeIds])
+}
+
model SuperTabMessage {
id String @id @map("_id")
tabId String
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 4b37b105b..7f16f6c7a 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -13,7 +13,7 @@ import { machineObservationSchema } from '../superTabs/machines.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const tabParams = z.object({ tabId: id })
const agentQuery = z.object({ asAgentId: id.optional() }).strict()
-const create = z.object({ operationId: id, name: z.string().trim().min(1).max(160) }).strict()
+const create = z.object({ operationId: id, name: z.string().trim().min(1).max(160), projectVisibility: z.enum(['public', 'private']).optional() }).strict()
const operation = operationSchema.extend({ asAgentId: id.optional() })
const listQuery = z.object({ after: id.optional() }).strict()
const startParams = tabParams.extend({ startId: id })
@@ -75,7 +75,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
app.get<{ Querystring: z.infer<typeof listQuery> }>('/api/super-tabs', { preHandler: validateQuery(listQuery) },
(req, reply) => respond(reply, () => store.list(req.user!, req.query.after)))
app.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, reply) => respond(reply, () => store.create(req.user!, req.body.operationId, req.body.name, req.body.projectVisibility)))
app.get('/api/super-tabs/invitations', (req, reply) => respond(reply, () => store.invitations(req.user!)))
app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId', { preHandler: validateParams(hostParams) },
(req, reply) => respond(reply, () => store.hostTabs(req.user!, req.params.machineId)))
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 0a117cb4b..69f66ee57 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -6,6 +6,7 @@ import {
} from './model.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSchema } from './routingPolicy.js'
+import { agentProjectId, groupProject, manageProject, mutableProjects, projectMembers, projectOf, readAgent, readConversation, readProject, sameProject } from './projects.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const title = z.string().trim().min(1).max(160)
@@ -39,13 +40,18 @@ export const startRequestSchema = z.object({
const check = z.object({ description: z.string().trim().min(1).max(1000), independent: z.boolean() }).strict()
export const commandSchema = z.discriminatedUnion('type', [
- z.object({ type: z.literal('machine.contribute'), machineId: id, name: title, cwd: path, engines: z.array(z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)).min(1).max(32), maxAgents: z.number().int().min(1).max(16) }).strict(),
+ z.object({ type: z.literal('machine.contribute'), machineId: id, name: title, cwd: path, scope: z.literal('swarm').optional(), engines: z.array(z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)).min(1).max(32), maxAgents: z.number().int().min(1).max(16) }).strict(),
z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),
z.object({ type: z.literal('tab.rename'), name: title }).strict(),
z.object({ type: z.literal('tab.project'), machineId: id, project }).strict(),
z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),
z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSchema.nullable() }).strict(),
- z.object({ type: z.literal('conversation.create'), title, brief: z.string().trim().max(8000), checks: z.array(check).max(40) }).strict(),
+ 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.sharing'), projectId: id, visibility: z.enum(['public', 'private']), memberIds: z.array(id).max(200) }).strict(),
+ z.object({ type: z.literal('project.cadence'), projectId: id, minutes: z.union([z.literal(1), z.literal(5), z.literal(15), z.literal(30)]) }).strict(),
+ z.object({ type: z.literal('project.report'), projectId: id, throughRevision: z.number().int().nonnegative().safe(), text: text.nullable() }).strict(),
+ z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000), checks: z.array(check).max(40) }).strict(),
z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),
z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),
z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), initialMessage: text.optional() }).strict(),
@@ -93,10 +99,34 @@ export interface CommandContext {
}
function controls(state: SuperTabState, actor: Actor, conversationId = 'lead'): void {
- if (actor.kind === 'agent' && conversation(state, conversationId).leadId !== actor.agentId) {
+ const group = readConversation(state, actor, conversationId)
+ if (actor.kind === 'agent' && group.leadId !== actor.agentId) {
fail('LEAD_REQUIRED', 'The coordinating lead owns this action.', 403)
}
}
+
+/** Also checked before returning an idempotent receipt: a retry does not retain
+ * access after the person has been removed from a private project. */
+export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {
+ if (command.type === 'invite.accept') return
+ const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
+ author(state, actor, !leaving)
+ if ('conversationId' in command) readConversation(state, actor, command.conversationId)
+ if ('projectId' in command && command.projectId) readProject(state, actor, command.projectId)
+ if ('agentId' in command) readAgent(state, actor, command.agentId)
+ if (command.type === 'agent.start') readConversation(state, actor, command.request.conversationId)
+ if ('startId' in command && command.type !== 'route.modelResult') {
+ const start = state.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
+ readConversation(state, actor, start.request.conversationId)
+ }
+ if (context.delivery) readConversation(state, actor, context.delivery.conversationId)
+ if (context.routeDecision) {
+ const groupId = command.type === 'agent.start' ? command.request.conversationId
+ : 'conversationId' in command ? command.conversationId : null
+ if (groupId && groupId !== context.routeDecision.conversationId) fail('ROUTE_MISMATCH', 'This routing decision belongs to another group.')
+ readConversation(state, actor, context.routeDecision.conversationId)
+ }
+}
function owner(state: SuperTabState, actor: Actor): void {
if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can manage invitations.', 403)
}
@@ -131,6 +161,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
const sender = author(state, actor, !leaving)
+ authorizeCommandAccess(state, actor, command, context)
const rememberAttempt = (group: ReturnType<typeof conversation>) => {
if (group.assignment) effects.previousAttempts.push(structuredClone({ conversationId: group.id,
brief: group.brief, checks: group.checks, assignment: group.assignment }))
@@ -171,6 +202,47 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
switch (command.type) {
+ case 'project.report': {
+ const project = readProject(state, actor, command.projectId)
+ const group = conversation(state, project.leadConversationId)
+ if (actor.kind !== 'agent' || group.leadId !== actor.agentId) fail('LEAD_REQUIRED', 'The project lead writes its progress updates.', 403)
+ if (project.progress) project.progress.summarizedRevision = Math.max(project.progress.summarizedRevision,
+ Math.min(command.throughRevision, project.progress.dirtyRevision))
+ if (command.text) message(group.id, command.text, [], null, { kind: 'project-report' })
+ break
+ }
+ case 'project.create': {
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person creates a project and chooses its lead.', 403)
+ if (state.paused) fail('PAUSED', 'New work is paused in this swarm.')
+ const projects = mutableProjects(state)
+ if (projects.length >= 100) fail('PROJECTS_FULL', 'A swarm can have up to 100 projects.')
+ const leadConversationId = `project-${operationId}`
+ projects.push({ id: operationId, name: command.name, ownerId: actor.userId, leadConversationId,
+ visibility: command.visibility, members: [], updateMinutes: 5 })
+ state.conversations.push({ id: leadConversationId, projectId: operationId, title: 'Lead', leadId: null,
+ agentIds: [], archived: false, brief: command.brief, checks: [], assignment: null, lastMessageSequence: 0 })
+ result.projectId = operationId
+ result.conversationId = leadConversationId
+ break
+ }
+ case 'project.rename': {
+ const project = manageProject(state, actor, command.projectId)
+ project.name = command.name
+ break
+ }
+ case 'project.sharing': {
+ const project = manageProject(state, actor, command.projectId)
+ project.members = projectMembers(state, command.memberIds)
+ project.visibility = command.visibility
+ break
+ }
+ case 'project.cadence': {
+ const project = readProject(state, actor, command.projectId)
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person chooses the update cadence.', 403)
+ mutableProjects(state)
+ projectOf(state, project.id).updateMinutes = command.minutes
+ break
+ }
case 'tab.project': {
controls(state, actor)
if (actor.kind === 'person') owner(state, actor)
@@ -186,6 +258,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (state.starts?.some(s => s.request.machineId === command.machineId && (!s.harnessId || (s.poolGeneration && !s.poolSettled)) && !s.error)) fail('STARTS_PENDING', 'Reconcile pending starts before changing this contribution.')
state.machines = state.machines.filter(m => m.machineId !== command.machineId)
state.machines.push({ machineId: command.machineId, name: command.name, cwd: command.cwd, engines: [...new Set(command.engines)], maxAgents: command.maxAgents,
+ ...(command.scope ? { scope: command.scope } : {}),
contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused: false })
break
}
@@ -209,14 +282,17 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
else delete state.routingPolicy
break
case 'conversation.create': {
- controls(state, actor)
+ const project = readProject(state, actor, command.projectId ??
+ (actor.kind === 'agent' ? agentProjectId(state, agent(state, actor.agentId)) : 'lead'))
+ controls(state, actor, project.leadConversationId)
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
if (actor.kind === 'agent' && (!command.brief || !command.checks.length)) {
fail('BRIEF_REQUIRED', 'Delegated work needs a brief and acceptance checks.', 400)
}
- const leadId = conversation(state, 'lead').leadId
+ const leadId = conversation(state, project.leadConversationId).leadId
const number = Math.max(0, ...state.conversations.map(c => c.number ?? 0)) + 1
- state.conversations.push({ id: operationId, number, title: command.title, leadId, agentIds: leadId ? [leadId] : [],
+ state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),
+ number, title: command.title, leadId, agentIds: leadId ? [leadId] : [],
archived: false, brief: command.brief, assignment: null, lastMessageSequence: 0,
checks: command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null })),
})
@@ -232,7 +308,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'conversation.archive': {
controls(state, actor, command.conversationId)
const group = conversation(state, command.conversationId)
- if (group.id === 'lead') fail('LEAD_CONVERSATION', 'The Lead conversation stays available.')
+ if (group.id === groupProject(state, group).leadConversationId) fail('LEAD_CONVERSATION', 'The Lead conversation stays available.')
if (command.archived && activeWork(group)) fail('WORK_ACTIVE', 'Resolve the active assignment before archiving this conversation.')
group.archived = command.archived
break
@@ -240,6 +316,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'agent.add': {
controls(state, actor, command.conversationId)
const group = open(state, command.conversationId)
+ const project = groupProject(state, group)
+ if (state.projects && group.id === project.leadConversationId && command.lead && command.project) {
+ project.repository ??= { machineId: command.machineId, ...command.project }
+ }
if (group.id === 'lead' && command.lead && command.project && !state.project) {
state.project = { machineId: command.machineId, ...command.project }
}
@@ -248,7 +328,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (contributor.role === 'viewer') fail('READ_ONLY', 'A viewer cannot contribute agents.', 403)
const agentId = stableId(command.machineId, command.harnessId)
const existing = state.agents.find(a => a.id === agentId)
+ if (existing) sameProject(state, group, existing)
if (!existing) state.agents.push({ id: agentId, machineId: command.machineId, harnessId: command.harnessId,
+ ...(state.projects ? { projectId: project.id } : {}),
machineOwnerId: grant.machineOwnerId, contributorId: grant.contributorId, membershipGeneration: contributor.generation,
hostGrant: grant.hostGrant ?? null,
name: command.name, configuration: command.configuration, configurationVersion: operationId })
@@ -343,6 +425,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const agentId = stableId(start.request.machineId, command.harnessId)
if (state.agents.some(a => a.id === agentId)) fail('ALREADY_SHARED', 'This native harness is already in the tab.')
state.agents.push({ id: agentId, machineId: start.request.machineId, harnessId: command.harnessId,
+ ...(state.projects ? { projectId: groupProject(state, group).id } : {}),
machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,
hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId })
group.agentIds.push(agentId)
@@ -376,7 +459,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'conversation.agent': {
controls(state, actor, command.conversationId)
const group = open(state, command.conversationId)
- agent(state, command.agentId)
+ sameProject(state, group, agent(state, command.agentId))
if (!command.present) {
if (activeWork(group) && (group.assignment?.agentId === command.agentId || group.leadId === command.agentId)) {
fail('WORK_ACTIVE', 'Reconcile this agent’s assignment before removing it from the conversation.')
@@ -524,6 +607,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (activeWork(group)) fail('WORK_ACTIVE', 'The current assignment must finish or be reconciled before reassignment.')
if (!group.brief || !group.checks.length) fail('BRIEF_REQUIRED', 'Record the brief and acceptance checks before assigning work.', 400)
const worker = agent(state, command.agentId)
+ sameProject(state, group, worker)
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
if (!group.agentIds.includes(worker.id)) group.agentIds.push(worker.id)
rememberAttempt(group)
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 90199c1c3..fe3c25812 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -1,5 +1,7 @@
import { z } from 'zod'
import { fail, person, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
+import { groupProject } from './projects.js'
+import { conversation } from './model.js'
/** An explicit grant for this tab and project. It never creates a MachineShare. */
export interface ContributedMachine {
@@ -9,6 +11,7 @@ export interface ContributedMachine {
membershipGeneration: string
generation: string
cwd: string
+ scope?: 'swarm'
engines: string[]
maxAgents: number
paused: boolean
@@ -63,7 +66,12 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
if (!pool) return null
if (start && start.poolGeneration !== pool.generation) fail('CONTRIBUTION_REVOKED', 'This machine contribution changed. Reconcile the original start.', 403)
if (pool.paused) fail('MACHINE_PAUSED', 'New work is paused on this machine.')
- if (request.cwd !== pool.cwd || !pool.engines.includes(request.engine)
+ const project = groupProject(state, conversation(state, request.conversationId))
+ if (!pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')
+ const cwd = pool.scope === 'swarm'
+ ? project.repository?.machineId === pool.machineId ? project.repository.cwd : `${pool.cwd.replace(/\/+$/, '')}/${project.id}`
+ : pool.cwd
+ if (request.cwd !== cwd || !pool.engines.includes(request.engine)
|| request.codexHome || request.gridModel || request.gridName || request.permissionMode) {
fail('OUTSIDE_CONTRIBUTION', 'Use the contributed project, engine and default account settings.', 403)
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index beffc7c7e..4102f69ea 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -1,5 +1,6 @@
import { createHash } from 'node:crypto'
import type { RouteDecisionEffect } from './routeRecord.js'
+import { canReadAgent, canReadProject, groupProject, projectsOf, type ProjectVisibility, type SwarmProject } from './projects.js'
export type Role = 'owner' | 'collaborator' | 'viewer'
export interface Person { id: string; email: string; role: Role; generation: string }
@@ -12,6 +13,7 @@ export interface AgentConfiguration {
}
export interface Agent {
id: string
+ projectId?: string
machineId: string
harnessId: string
machineOwnerId: string
@@ -73,6 +75,7 @@ export interface Assignment {
}
export interface Conversation {
id: string
+ projectId?: string
/** Stable, tab-local workgroup reference. Lead has no number. */
number?: number
title: string
@@ -96,6 +99,7 @@ export interface SuperTabState {
id: string
name: string
project?: { machineId: string; cwd: string; repositoryUrl: string | null }
+ projects?: SwarmProject[]
ownerId: string
environment: string
/** Fields this tab overrides from its owner's account routing policy (routingPolicy.ts). */
@@ -160,8 +164,9 @@ export function conversation(state: SuperTabState, id: string): Conversation {
* numbers are never reassigned; the store serializes concurrent additions. */
export function numberConversations(state: SuperTabState): void {
let next = Math.max(0, ...state.conversations.map(c => c.number ?? 0)) + 1
+ const leads = new Set(projectsOf(state).map(p => p.leadConversationId))
for (const group of state.conversations) {
- if (group.id !== 'lead' && group.number == null) group.number = next++
+ if (!leads.has(group.id) && group.number == null) group.number = next++
}
}
export function author(state: SuperTabState, actor: Actor, write = false): Author {
@@ -176,13 +181,15 @@ export function author(state: SuperTabState, actor: Actor, write = false): Autho
return { kind: 'agent', id: member.id, name: member.name, membershipGeneration: member.membershipGeneration }
}
-export function createSuperTab(id: string, name: string, owner: { id: string; email: string }, environment: string): SuperTabState {
- return {
+export function createSuperTab(id: string, name: string, owner: { id: string; email: string }, environment: string, visibility?: ProjectVisibility): SuperTabState {
+ const state: SuperTabState = {
version: 1, id, name, ownerId: owner.id, environment, paused: false,
people: [{ ...owner, email: owner.email.trim().toLowerCase(), role: 'owner', generation: id }],
agents: [], invitations: [],
conversations: [{ id: 'lead', title: 'Lead', leadId: null, agentIds: [], archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0 }],
}
+ if (visibility) state.projects = [{ ...projectsOf(state)[0]!, visibility }]
+ return state
}
/** Pending invitations are management data, not part of the shared conversation. */
@@ -190,6 +197,23 @@ export function visibleState(state: SuperTabState, actor: Actor): SuperTabState
author(state, actor)
const visible = structuredClone(state)
numberConversations(visible)
+ if (visible.projects) {
+ visible.projects = visible.projects.filter(p => canReadProject(state, actor, p))
+ visible.conversations = visible.conversations.filter(c => canReadProject(state, actor, groupProject(state, c)))
+ visible.agents = visible.agents.filter(a => canReadAgent(state, actor, a))
+ visible.starts = visible.starts?.filter(s => visible.conversations.some(c => c.id === s.request.conversationId))
+ if (!visible.projects.some(p => p.id === 'lead')) {
+ delete visible.project
+ visible.machines = visible.machines?.filter(m => m.scope === 'swarm')
+ }
+ const harnesses = new Set([...visible.agents.map(a => a.harnessId), ...(visible.starts ?? []).flatMap(s => s.harnessId ? [s.harnessId] : [])])
+ for (const pool of visible.machines ?? []) {
+ if (!pool.observation) continue
+ pool.observation.runningHarnessIds = pool.observation.runningHarnessIds.filter(id => harnesses.has(id))
+ pool.observation.stoppedHarnessIds = pool.observation.stoppedHarnessIds.filter(id => harnesses.has(id))
+ }
+ visible.invitations = visible.invitations.filter(i => visible.conversations.some(c => c.id === i.conversationId))
+ }
if (actor.kind !== 'person' || actor.userId !== state.ownerId) visible.invitations = []
return visible
}
diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.ts
index b10a72556..bdbefdef6 100644
--- a/backend/src/superTabs/native.ts
+++ b/backend/src/superTabs/native.ts
@@ -4,6 +4,8 @@ import { z } from 'zod'
import type { AuthUser } from '../lib/ssoAuth.js'
import { activeWork, agent, author, conversation, fail, stableId, SuperTabError,
type Actor, type Agent, type Author, type SuperTabState } from './model.js'
+import { canReadProject, groupProject, readConversation } from './projects.js'
+import { noteProjectReports } from './projectUpdates.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
export const openNativeSchema = z.object({ operationId: id, conversationId: id, agentId: id }).strict()
@@ -38,7 +40,7 @@ export class SuperTabNativeStore {
const binding = record.binding as unknown as Binding
const operator = author(state, { kind: 'person', userId: binding.operator.id, email: binding.operator.name }, true)
const target = agent(state, record.agentId)
- const group = conversation(state, record.conversationId)
+ const group = readConversation(state, { kind: 'person', userId: binding.operator.id, email: binding.operator.name }, record.conversationId)
if (operator.membershipGeneration !== binding.operator.membershipGeneration || group.archived || !group.agentIds.includes(target.id)
|| target.harnessId !== binding.harnessId || target.machineId !== binding.machineId || target.machineOwnerId !== binding.machineOwnerId
|| target.contributorId !== binding.contributorId || target.membershipGeneration !== binding.contributionGeneration
@@ -62,7 +64,8 @@ export class SuperTabNativeStore {
return this.deps.transaction(async tx => {
const { state } = await this.deps.row(tx, user, tabId)
const operator = author(state, { kind: 'person', userId: user.sub, email: user.email }, true)
- const target = agent(state, request.agentId), group = conversation(state, request.conversationId)
+ const target = agent(state, request.agentId)
+ const group = readConversation(state, { kind: 'person', userId: user.sub, email: user.email }, request.conversationId)
if (group.archived || !group.agentIds.includes(target.id)) fail('AGENT_UNAVAILABLE', 'Choose an agent in this conversation.')
await this.deps.agentGrant(tx, state, target)
const grant = await this.deps.contribution(tx, state, { kind: 'person', userId: user.sub, email: user.email }, target)
@@ -141,6 +144,8 @@ export class SuperTabNativeStore {
membershipGeneration: lead.membershipGeneration, authorKind: 'person', authorId: binding.operator.id,
authorGeneration: binding.operator.membershipGeneration } })
}
+ noteProjectReports(state, [{ id: eventId, conversationId: group.id, author: observedBy, text,
+ replyTo: null, recipients }], revision, Date.now())
await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { revision, state: json(state) } })
await tx.superTabNativeContext.update({ where: { id: contextId }, data: { lastEventId: eventId } })
const result = { eventId, revision }
@@ -162,6 +167,11 @@ export async function revokeNativeContexts(tx: Transaction, before: SuperTabStat
const current = after.conversations.find(c => c.id === group.id)
if (!current || current.archived) conditions.push({ conversationId: group.id })
else {
+ for (const member of after.people) {
+ if (!canReadProject(after, { kind: 'person', userId: member.id, email: member.email }, groupProject(after, current))) {
+ conditions.push({ conversationId: group.id, userId: member.id })
+ }
+ }
const removed = group.agentIds.filter(id => !current.agentIds.includes(id))
if (removed.length) conditions.push({ conversationId: group.id, agentId: { in: removed } })
}
diff --git a/backend/src/superTabs/projectUpdates.ts b/backend/src/superTabs/projectUpdates.ts
new file mode 100644
index 000000000..5057a2040
--- /dev/null
+++ b/backend/src/superTabs/projectUpdates.ts
@@ -0,0 +1,38 @@
+import { author, conversation, stableId, type Agent, type MessageDraft, type SuperTabState } from './model.js'
+import { agentProjectId, groupProject, projectOf } from './projects.js'
+
+/** Workgroup reports mark a project dirty. No per-message model or timer is
+ * needed; the existing execution host's delivery poll requests consolidation. */
+export function noteProjectReports(state: SuperTabState, messages: MessageDraft[], revision: number, now: number) {
+ if (!state.projects) return
+ for (const message of messages) {
+ const group = conversation(state, message.conversationId), project = groupProject(state, group)
+ if (group.id === project.leadConversationId) continue
+ project.progress ??= { dirtyRevision: revision, summarizedRevision: 0, requestedRevision: 0, since: now }
+ if (project.progress.dirtyRevision <= project.progress.summarizedRevision) project.progress.since = now
+ project.progress.dirtyRevision = revision
+ }
+}
+
+export function projectUpdateRequest(state: SuperTabState, target: Agent, now: number): MessageDraft | null {
+ if (!state.projects || state.paused) return null
+ const project = projectOf(state, agentProjectId(state, target))
+ const group = conversation(state, project.leadConversationId), progress = project.progress
+ if (group.leadId !== target.id || group.archived || !progress ||
+ progress.dirtyRevision <= progress.summarizedRevision ||
+ progress.dirtyRevision <= progress.requestedRevision ||
+ now < Math.max(progress.requestedAt ?? 0, progress.since) + project.updateMinutes * 60_000) return null
+ const id = stableId('project-update', state.id, project.id, String(progress.dirtyRevision))
+ const text = `Consolidate new reports for project ${JSON.stringify(project.name)}. ` +
+ `Read this project's workgroups with lastMessageSequence after ${progress.summarizedRevision}; inspect their new messages and current work. ` +
+ 'At your next natural checkpoint, tell the people what changed, what is blocked, and what comes next. Include useful workgroup references and result links. ' +
+ 'Do not copy the terminal log or repeat unchanged status. This is a scheduled request, not a new task. ' +
+ `Use harness super-tab --tab ${state.id} command UNIQUE_OPERATION_ID ` +
+ `JSON with {"type":"project.report","projectId":"${project.id}","throughRevision":${progress.dirtyRevision},"text":"your update"}. ` +
+ 'Use text:null to acknowledge if nothing merits an update. Reuse the same operation ID after a lost reply. ' +
+ 'Keep reporting human questions, serious blockers, and completion immediately; do not wait for this cadence.'
+ return { id, conversationId: group.id,
+ author: author(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }),
+ text, replyTo: null, recipients: [target.id],
+ source: { kind: 'update-request', projectId: project.id, throughRevision: progress.dirtyRevision } }
+}
diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.ts
new file mode 100644
index 000000000..2693e7027
--- /dev/null
+++ b/backend/src/superTabs/projects.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command } from './commands.js'
+import { createSuperTab, visibleState, type Actor } from './model.js'
+import { canReadAgent, projectsOf, readConversation } from './projects.js'
+
+const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Actor = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const configuration = { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null }
+function setup() {
+ let state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ state.people.push({ id: 'peer', email: '[email protected]', role: 'collaborator', generation: 'first' })
+ let next = 0
+ const run = (command: Command, actor = owner) => {
+ const effect = applyCommand(state, actor, command, { operationId: `op${next++}`, now: 1000,
+ contribution: { machineOwnerId: 'host', contributorId: actor.kind === 'person' ? actor.userId : 'owner' } })
+ state = effect.state
+ return effect.result
+ }
+ const project = (visibility: 'private' | 'public' = 'private', actor = owner) =>
+ run({ type: 'project.create', name: 'Other project', visibility, brief: 'Its own outcome' }, actor) as { projectId: string; conversationId: string }
+ const add = (conversationId: string, harnessId: string, lead = true) =>
+ run({ type: 'agent.add', conversationId, harnessId, machineId: 'machine', name: harnessId, configuration, lead }).agentId as string
+ return { run, project, add, get state() { return state } }
+}
+
+describe('projects inside an invite-only swarm', () => {
+ it('keeps existing conversation identities and numbers while adding independent project leads', () => {
+ const f = setup()
+ expect(projectsOf(f.state)[0]).toMatchObject({ name: 'Team', leadConversationId: 'lead', updateMinutes: 5 })
+ const original = f.run({ type: 'conversation.create', title: 'First', brief: '', checks: [] })
+ const p = f.project()
+ const next = f.run({ type: 'conversation.create', projectId: p.projectId, title: 'Second', brief: '', checks: [] })
+ expect(f.state.conversations.map(c => c.number)).toEqual([undefined, 1, undefined, 2])
+ expect(f.state.conversations.map(c => c.id)).toContain(original.conversationId)
+ expect(next.number).toBe(2)
+ expect(() => f.run({ type: 'conversation.archive', conversationId: p.conversationId, archived: true })).toThrow('stays available')
+ })
+
+ it('hides private project metadata, groups, agents, starts and message access from other members', () => {
+ const f = setup(), p = f.project()
+ const id = f.add(p.conversationId, 'private-lead')
+ const visible = visibleState(f.state, peer)
+ expect(visible.projects!.map(p => p.id)).toEqual(['lead'])
+ expect(visible.conversations.map(c => c.id)).toEqual(['lead'])
+ expect(visible.agents).toEqual([])
+ expect(canReadAgent(f.state, peer, f.state.agents[0]!)).toBe(false)
+ expect(() => readConversation(f.state, peer, p.conversationId)).toThrow('unavailable')
+ expect(() => f.run({ type: 'message.send', conversationId: p.conversationId, text: 'Guessing an ID', replyTo: null, recipientIds: [] }, peer)).toThrow('unavailable')
+ expect(() => f.run({ type: 'agent.remove', agentId: id }, peer)).toThrow('unavailable')
+ })
+
+ it('does not grant the swarm owner access to another person’s private project', () => {
+ const f = setup(), p = f.project('private', peer)
+ expect(visibleState(f.state, owner).projects!.some(item => item.id === p.projectId)).toBe(false)
+ expect(() => f.run({ type: 'project.sharing', projectId: p.projectId, visibility: 'public', memberIds: [] })).toThrow('unavailable')
+ })
+
+ it('makes public projects readable within the swarm and lets only their owner change sharing', () => {
+ const f = setup(), p = f.project('public')
+ expect(readConversation(f.state, peer, p.conversationId).id).toBe(p.conversationId)
+ expect(() => f.run({ type: 'project.sharing', projectId: p.projectId, visibility: 'private', memberIds: [] }, peer)).toThrow('Only the project owner')
+ f.run({ type: 'project.sharing', projectId: p.projectId, visibility: 'private', memberIds: ['peer'] })
+ expect(readConversation(f.state, peer, p.conversationId).id).toBe(p.conversationId)
+ f.state.people.find(p => p.id === 'peer')!.generation = 'rejoined'
+ expect(() => readConversation(f.state, peer, p.conversationId)).toThrow('unavailable')
+ })
+
+ it('keeps one terminal across workgroups in its project and refuses another project’s audience', () => {
+ const f = setup(), p = f.project()
+ const lead = f.add(p.conversationId, 'lead')
+ const actor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host' }
+ const work = f.run({ type: 'conversation.create', title: 'Work', brief: 'Deliver it', checks: [{ description: 'It works', independent: true }] }, actor)
+ expect(f.state.conversations.find(c => c.id === work.conversationId)).toMatchObject({ projectId: p.projectId, agentIds: [lead], leadId: lead })
+ expect(visibleState(f.state, actor).projects!.map(p => p.id)).toEqual([p.projectId])
+ expect(() => f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: lead, present: true, lead: false })).toThrow('separate agent')
+ expect(() => f.add('lead', 'lead')).toThrow('separate agent')
+ expect(() => f.run({ type: 'message.send', conversationId: 'lead', text: 'Cross project', replyTo: null, recipientIds: [] }, actor)).toThrow('unavailable')
+ })
+
+ it('stores the cadence per project and keeps the other project’s setting', () => {
+ const f = setup(), p = f.project()
+ f.run({ type: 'project.cadence', projectId: p.projectId, minutes: 15 })
+ expect(projectsOf(f.state).map(p => p.updateMinutes)).toEqual([5, 15])
+ expect(() => f.run({ type: 'project.cadence', projectId: p.projectId, minutes: 1 }, peer)).toThrow('unavailable')
+ })
+})
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
new file mode 100644
index 000000000..24d5563b7
--- /dev/null
+++ b/backend/src/superTabs/projects.ts
@@ -0,0 +1,107 @@
+import { agent, author, conversation, fail, person, type Actor, type Agent, type Conversation, type SuperTabState } from './model.js'
+
+export type ProjectVisibility = 'public' | 'private'
+export interface SwarmProject {
+ id: string
+ name: string
+ ownerId: string
+ leadConversationId: string
+ /** Public means every member of this invite-only swarm. */
+ visibility: ProjectVisibility
+ members: Array<{ id: string; generation: string }>
+ updateMinutes: 1 | 5 | 15 | 30
+ progress?: {
+ dirtyRevision: number
+ summarizedRevision: number
+ since: number
+ requestedRevision: number
+ requestedAt?: number
+ requestMessageId?: string
+ }
+ repository?: { machineId: string; cwd: string; repositoryUrl: string | null }
+}
+
+/** Existing tabs are one project; their conversation IDs and messages stay intact. */
+export function projectsOf(state: SuperTabState): SwarmProject[] {
+ return state.projects ?? [{
+ id: 'lead', name: state.name, ownerId: state.ownerId, leadConversationId: 'lead',
+ visibility: 'public', members: [], updateMinutes: 5,
+ ...(state.project ? { repository: state.project } : {}),
+ }]
+}
+
+export function projectOf(state: SuperTabState, projectId: string): SwarmProject {
+ return projectsOf(state).find(p => p.id === projectId) ?? fail('NOT_FOUND', 'This project is unavailable.', 404)
+}
+
+export function groupProject(state: SuperTabState, group: Conversation): SwarmProject {
+ return projectOf(state, group.projectId ?? 'lead')
+}
+
+export function agentProjectId(state: SuperTabState, target: Agent): string {
+ return target.projectId ?? state.conversations.find(c => c.agentIds.includes(target.id))?.projectId ?? 'lead'
+}
+
+export function canReadProject(state: SuperTabState, actor: Actor, project: SwarmProject): boolean {
+ if (actor.kind === 'agent') {
+ const target = state.agents.find(a => a.id === actor.agentId)
+ return !!target && target.machineOwnerId === actor.machineOwnerId && agentProjectId(state, target) === project.id
+ }
+ const member = state.people.find(p => p.id === actor.userId)
+ return !!member && (project.visibility === 'public' || project.ownerId === member.id ||
+ project.members.some(p => p.id === member.id && p.generation === member.generation))
+}
+
+export function readProject(state: SuperTabState, actor: Actor, projectId: string): SwarmProject {
+ author(state, actor)
+ const project = projectOf(state, projectId)
+ if (!canReadProject(state, actor, project)) fail('NOT_FOUND', 'This project is unavailable.', 404)
+ return project
+}
+
+export function readConversation(state: SuperTabState, actor: Actor, conversationId: string): Conversation {
+ const group = conversation(state, conversationId)
+ readProject(state, actor, groupProject(state, group).id)
+ return group
+}
+
+export function canReadAgent(state: SuperTabState, actor: Actor, target: Agent): boolean {
+ return canReadProject(state, actor, projectOf(state, agentProjectId(state, target)))
+}
+
+export function readAgent(state: SuperTabState, actor: Actor, agentId: string): Agent {
+ const target = agent(state, agentId)
+ if (!canReadAgent(state, actor, target)) fail('AGENT_UNAVAILABLE', 'This agent is unavailable.', 404)
+ return target
+}
+
+/** A terminal contains its session's entire history. Joining another project's
+ * chat must never expose that history to a different audience. */
+export function sameProject(state: SuperTabState, group: Conversation, target: Agent): void {
+ if (agentProjectId(state, target) !== groupProject(state, group).id) {
+ fail('PROJECT_SESSION', 'Start a separate agent for another project. This terminal belongs to its original project.')
+ }
+}
+
+export function mutableProjects(state: SuperTabState): SwarmProject[] {
+ return state.projects ??= projectsOf(state)
+}
+
+export function manageProject(state: SuperTabState, actor: Actor, projectId: string): SwarmProject {
+ const project = readProject(state, actor, projectId)
+ author(state, actor, true)
+ if (actor.kind !== 'person' || actor.userId !== project.ownerId) {
+ fail('PROJECT_OWNER_REQUIRED', 'Only the project owner can change its sharing.', 403)
+ }
+ mutableProjects(state)
+ return projectOf(state, projectId)
+}
+
+/** Capture current swarm membership so leaving and rejoining does not restore
+ * an old private-project invitation. */
+export function projectMembers(state: SuperTabState, ids: string[]) {
+ return [...new Set(ids)].map(id => {
+ const member = person(state, id)
+ return { id, generation: member.generation }
+ })
+}
diff --git a/backend/src/superTabs/sessionScope.ts b/backend/src/superTabs/sessionScope.ts
new file mode 100644
index 000000000..1c59e08ed
--- /dev/null
+++ b/backend/src/superTabs/sessionScope.ts
@@ -0,0 +1,41 @@
+import type { Prisma } from '@prisma/client'
+import { fail, stableId, type Agent, type SuperTabState } from './model.js'
+import { agentProjectId, projectOf } from './projects.js'
+
+const scopeId = (state: SuperTabState, projectId: string) => stableId(state.id, projectId)
+
+export async function bindSession(tx: Prisma.TransactionClient, state: SuperTabState, target: Agent) {
+ const project = projectOf(state, agentProjectId(state, target))
+ const scope = scopeId(state, project.id)
+ const id = stableId('swarm-session', state.environment, target.machineOwnerId, target.id)
+ const prior = await tx.superTabSessionScope.findUnique({ where: { id } })
+ let scopes = prior?.scopeIds ?? []
+ if (!prior) {
+ // Sessions contributed before project privacy existed may already appear
+ // in more than one tab. Inspect those registrations before binding one.
+ const rows = await tx.superTab.findMany({ where: { autonomousEnv: state.environment, machineIds: { has: target.machineId } } })
+ scopes = rows.flatMap(row => {
+ const other = row.state as unknown as SuperTabState
+ const contributed = other.agents.find(a => a.id === target.id && a.machineOwnerId === target.machineOwnerId)
+ return contributed ? [scopeId(other, agentProjectId(other, contributed))] : []
+ })
+ }
+ if (prior?.privateScope && prior.privateScope !== scope ||
+ project.visibility === 'private' && scopes.some(id => id !== scope)) {
+ fail('PROJECT_SESSION', 'This terminal has been shared with another project. Start a new agent for private work.')
+ }
+ const data = { scopeIds: [...new Set([...scopes, scope])],
+ privateScope: prior?.privateScope ?? (project.visibility === 'private' ? scope : null) }
+ if (prior) await tx.superTabSessionScope.update({ where: { id }, data })
+ else await tx.superTabSessionScope.create({ data: { id, ...data } })
+}
+
+export async function makeProjectPrivate(tx: Prisma.TransactionClient, state: SuperTabState, projectId: string) {
+ const scope = scopeId(state, projectId)
+ for (const target of state.agents.filter(a => agentProjectId(state, a) === projectId)) await bindSession(tx, state, target)
+ const bindings = await tx.superTabSessionScope.findMany({ where: { scopeIds: { has: scope } } })
+ if (bindings.some(b => b.scopeIds.some(id => id !== scope))) {
+ fail('PROJECT_SESSION', 'An agent terminal from this project was shared elsewhere. Create a new private project for private work.')
+ }
+ await tx.superTabSessionScope.updateMany({ where: { scopeIds: { has: scope } }, data: { privateScope: scope } })
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 76af85d4e..70f2b9715 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -5,7 +5,10 @@ import type { AuthUser } from '../lib/ssoAuth.js'
import { machineAlive } from '../lib/prisma.js'
import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
-import { applyCommand, operationSchema, type Command, type CommandContext } from './commands.js'
+import { applyCommand, authorizeCommandAccess, operationSchema, type Command, type CommandContext } from './commands.js'
+import { canReadAgent, canReadProject, groupProject, projectsOf, readConversation, type ProjectVisibility } from './projects.js'
+import { bindSession, makeProjectPrivate } from './sessionScope.js'
+import { noteProjectReports, projectUpdateRequest } from './projectUpdates.js'
import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
import {
activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState,
@@ -140,16 +143,16 @@ export class SuperTabStore {
return { machineOwnerId: machine.userId, contributorId, hostGrant }
}
- async create(user: AuthUser, operationId: string, name: string) {
+ async create(user: AuthUser, operationId: string, name: string, projectVisibility?: ProjectVisibility) {
const id = stableId('super-tab', user.autonomousEnv, user.sub, operationId)
- const requestHash = hash({ name })
+ const requestHash = hash({ name, ...(projectVisibility ? { projectVisibility } : {}) })
return transaction(this.db, async tx => {
const prior = await tx.superTabOperation.findUnique({ where: { id } })
if (prior) {
if (prior.requestHash !== requestHash) fail('OPERATION_REUSED', 'Use a new operation ID for a different request.')
return { id, revision: prior.revision }
}
- const state = createSuperTab(id, name, { id: user.sub, email: user.email }, user.autonomousEnv)
+ const state = createSuperTab(id, name, { id: user.sub, email: user.email }, user.autonomousEnv, projectVisibility)
await tx.superTab.create({ data: { id, ownerId: user.sub, autonomousEnv: user.autonomousEnv, ...indexes(state), state: json(state) } })
await tx.superTabOperation.create({ data: { id, tabId: id, actorKey: `person:${user.sub}`, requestHash, revision: 0, result: { id } } })
return { id, revision: 0 }
@@ -180,7 +183,10 @@ export class SuperTabStore {
const row = await this.row(tx, user, tabId)
const state = stateOf(row)
const actor = await this.actor(tx, user, state, asAgentId)
- return { revision: row.revision, state: { ...visibleState(state, actor), machines: state.machines?.map(pool => ({ ...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, pool)) })) } }
+ const visible = visibleState(state, actor)
+ return { revision: row.revision, state: { ...visible, machines: visible.machines?.map(pool => ({
+ ...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, state.machines!.find(m => m.machineId === pool.machineId)!)),
+ })) } }
})
}
@@ -193,7 +199,7 @@ export class SuperTabStore {
if (start.actorKey !== actorKey(actor) || person(state, start.contributorId).generation !== start.membershipGeneration) {
fail('FORBIDDEN', 'Only the original initiating lead can resume this start.', 403)
}
- const group = conversation(state, start.request.conversationId)
+ const group = readConversation(state, actor, start.request.conversationId)
if (actor.kind === 'agent' && group.leadId !== actor.agentId) fail('LEAD_REQUIRED', 'The coordinating lead changed.', 403)
if (group.archived) fail('ARCHIVED', 'This conversation is archived.')
if (state.paused && !start.harnessId && !start.dispatched) fail('PAUSED', 'New work is paused in this Super Tab.')
@@ -221,7 +227,24 @@ export class SuperTabStore {
if (prior.requestHash !== requestHash) fail('OPERATION_REUSED', 'Use a new operation ID for a different request.')
// A leave may be retried by its original author. Nothing except that operation's receipt is returned.
const selfLeave = actor.kind === 'person' && command.type === 'member.remove' && command.userId === actor.userId
- if (!selfLeave) author(original, actor)
+ if (!selfLeave) {
+ if (command.type === 'agent.remove' && !original.agents.some(a => a.id === command.agentId)) {
+ // Retrying one's own completed removal returns only its empty
+ // receipt. The removed agent no longer exists to authorize against.
+ author(original, actor, true)
+ } else {
+ authorizeCommandAccess(original, actor, command)
+ }
+ if (command.type === 'delivery.resolve') {
+ const delivery = await tx.superTabDelivery.findFirst({ where: { id: command.deliveryId, tabId } })
+ if (!delivery) fail('NOT_FOUND', 'This delivery is unavailable.', 404)
+ readConversation(original, actor, delivery.conversationId)
+ }
+ if ('decisionId' in command) {
+ const decision = await readDecision(tx, tabId, command.decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
+ readConversation(original, actor, decision.conversationId)
+ }
+ }
return { revision: prior.revision, result: prior.result }
}
if (command.type !== 'invite.accept') author(original, actor)
@@ -249,7 +272,9 @@ export class SuperTabStore {
// The native receipt remains intact; the operation records the person's resolution.
} })
}
- if (command.type === 'machine.contribute' || command.type === 'agent.add') context.contribution = await this.contribution(tx, original, actor, command)
+ if (command.type === 'machine.contribute' || command.type === 'agent.add' || command.type === 'tab.project') {
+ context.contribution = await this.contribution(tx, original, actor, command)
+ }
if (command.type === 'agent.start') context.contribution = await this.contribution(tx, original, actor, command.request, true)
if (command.type === 'agent.started' || command.type === 'agent.startDispatch') {
const start = original.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
@@ -270,6 +295,13 @@ export class SuperTabStore {
: command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined
if (decisionId) context.routeDecision = await readDecision(tx, tabId, decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
const effects = applyCommand(original, actor, command, context)
+ if (command.type === 'agent.add' || command.type === 'agent.started') {
+ const target = agent(effects.state, effects.result.agentId as string)
+ await bindSession(tx, effects.state, target)
+ }
+ if (command.type === 'project.sharing' && command.visibility === 'private') {
+ await makeProjectPrivate(tx, effects.state, command.projectId)
+ }
await revokeNativeContexts(tx, original, effects.state)
const revision = row.revision + 1
if (command.type === 'agent.add' || command.type === 'agent.started' || command.type === 'agent.configuration') {
@@ -286,6 +318,7 @@ export class SuperTabStore {
}
}
for (const message of effects.messages) conversation(effects.state, message.conversationId).lastMessageSequence = revision
+ noteProjectReports(effects.state, effects.messages, revision, context.now)
if (command.type === 'work.assign') {
const assigned = conversation(effects.state, command.conversationId).assignment!
const running = await tx.superTabRun.findUnique({ where: { id: assigned.agentId } })
@@ -314,6 +347,13 @@ export class SuperTabStore {
await tx.superTabDelivery.updateMany({ where: { tabId, messageId: command.replyTo, agentId: actor.agentId,
status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'answered' } })
}
+ if (command.type === 'project.report' && actor.kind === 'agent') {
+ const progress = projectsOf(original).find(p => p.id === command.projectId)?.progress
+ if (progress?.requestMessageId && command.throughRevision >= progress.requestedRevision) {
+ await tx.superTabDelivery.updateMany({ where: { tabId, agentId: actor.agentId, messageId: progress.requestMessageId,
+ status: { in: ['queued', 'claimed', 'uncertain', 'delivered'] } }, data: { status: 'answered' } })
+ }
+ }
const revoked = [
...original.people.filter(p => !effects.state.people.some(n => n.id === p.id && n.generation === p.generation))
.map(p => ({ authorKind: 'person', authorId: p.id, authorGeneration: p.generation })),
@@ -357,8 +397,7 @@ export class SuperTabStore {
return transaction(this.db, async tx => {
const row = await this.row(tx, user, tabId)
const state = stateOf(row)
- author(state, await this.actor(tx, user, state, asAgentId))
- conversation(state, conversationId)
+ readConversation(state, await this.actor(tx, user, state, asAgentId), conversationId)
const forward = cursor.after !== undefined
const rows = await tx.superTabMessage.findMany({ where: { tabId, conversationId,
...(cursor.messageId ? { id: cursor.messageId } : {}),
@@ -381,8 +420,7 @@ export class SuperTabStore {
async attempts(user: AuthUser, tabId: string, conversationId: string, asAgentId?: string) {
return transaction(this.db, async tx => {
const state = stateOf(await this.row(tx, user, tabId))
- author(state, await this.actor(tx, user, state, asAgentId))
- conversation(state, conversationId)
+ readConversation(state, await this.actor(tx, user, state, asAgentId), conversationId)
const rows = await tx.superTabAttempt.findMany({ where: { tabId, conversationId }, orderBy: { createdAt: 'desc' }, take: 50 })
return rows.map(row => {
const assignment = (row.snapshot as unknown as { assignment: Assignment }).assignment
@@ -394,8 +432,9 @@ export class SuperTabStore {
async routeDecisions(user: AuthUser, tabId: string, asAgentId?: string) {
return transaction(this.db, async tx => {
const state = stateOf(await this.row(tx, user, tabId))
- author(state, await this.actor(tx, user, state, asAgentId))
- const rows = await tx.superTabRouteDecision.findMany({ where: { tabId }, orderBy: { createdAt: 'desc' }, take: 100 })
+ const actor = await this.actor(tx, user, state, asAgentId)
+ const groups = visibleState(state, actor).conversations.map(c => c.id)
+ const rows = await tx.superTabRouteDecision.findMany({ where: { tabId, conversationId: { in: groups } }, orderBy: { createdAt: 'desc' }, take: 100 })
return rows.map(timedDecisionOf)
})
}
@@ -403,8 +442,10 @@ export class SuperTabStore {
async routeDecision(user: AuthUser, tabId: string, decisionId: string, asAgentId?: string) {
return transaction(this.db, async tx => {
const state = stateOf(await this.row(tx, user, tabId))
- author(state, await this.actor(tx, user, state, asAgentId))
+ const actor = await this.actor(tx, user, state, asAgentId)
+ author(state, actor)
const row = await tx.superTabRouteDecision.findFirst({ where: { id: decisionId, tabId } })
+ if (row) readConversation(state, actor, row.conversationId)
return row ? timedDecisionOf(row) : fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
})
}
@@ -444,7 +485,12 @@ export class SuperTabStore {
try { pool = machineContribution(state, machineId) } catch (error) { if (error instanceof SuperTabError) return []; throw error }
if (!pool || pool.contributorId !== user.sub) return []
const starts = (state.starts ?? []).filter(s => s.request.machineId === machineId && s.poolGeneration === pool.generation && (!s.harnessId || !s.poolSettled) && !s.error)
- return [{ tabId: row.id, paused: state.paused, machine: pool, starts, harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])] }]
+ return [{ tabId: row.id, paused: state.paused, machine: pool, starts,
+ ...(pool.scope === 'swarm' ? { projects: projectsOf(state).filter(p => starts.some(s =>
+ groupProject(state, conversation(state, s.request.conversationId)).id === p.id))
+ .map(p => ({ id: p.id, leadConversationId: p.leadConversationId, repository: p.repository,
+ conversationIds: state.conversations.filter(c => groupProject(state, c).id === p.id).map(c => c.id) })) } : {}),
+ harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])] }]
})
})
}
@@ -478,7 +524,9 @@ export class SuperTabStore {
// `active` lets the host release members that are only in archived groups to automatic cleanup.
const active = state.conversations.some(c => !c.archived && c.agentIds.includes(target.id))
result.push({ tabId: row.id, revision: row.revision, paused: state.paused, active, agent: target,
- observers: people.filter(p => p.id !== user.sub).map(p => ({ email: p.email, userId: p.id })) })
+ observers: people.filter(p => p.id !== user.sub &&
+ canReadAgent(state, { kind: 'person', userId: p.id, email: p.email }, target))
+ .map(p => ({ email: p.email, userId: p.id })) })
}
}
return result
@@ -493,6 +541,7 @@ export class SuperTabStore {
const target = state.agents.find(a => a.machineId === machineId && a.harnessId === harnessId && a.machineOwnerId === machineOwnerId)
if (!target) return false
agent(state, target.id)
+ if (!canReadAgent(state, { kind: 'person', userId: user.sub, email: user.email }, target)) return false
await this.agentGrant(tx, state, target)
return true
})
@@ -520,6 +569,12 @@ export class SuperTabStore {
if (!target || target.membershipGeneration !== delivery.membershipGeneration || !group || group.archived || !group.agentIds.includes(target.id)) return false
const sender = delivery.authorKind === 'person' ? state.people.find(p => p.id === delivery.authorId) : state.agents.find(a => a.id === delivery.authorId)
if (!sender) return false
+ const actor: Actor = delivery.authorKind === 'person'
+ ? { kind: 'person', userId: delivery.authorId, email: '' }
+ : { kind: 'agent', agentId: delivery.authorId, machineOwnerId: (sender as Agent).machineOwnerId }
+ if (!canReadProject(state, actor, groupProject(state, group))) return false
+ if (!canReadAgent(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }, target) ||
+ !canReadProject(state, { kind: 'agent', agentId: target.id, machineOwnerId: target.machineOwnerId }, groupProject(state, group))) return false
const generation = 'generation' in sender ? sender.generation : sender.membershipGeneration
return generation === delivery.authorGeneration && (!('role' in sender) || sender.role !== 'viewer')
}
@@ -536,6 +591,24 @@ export class SuperTabStore {
const row = await this.row(tx, user, tabId)
const state = stateOf(row)
author(state, await this.actor(tx, user, state, agentId), true)
+ const target = agent(state, agentId)
+ const update = projectUpdateRequest(state, target, this.now())
+ if (update) {
+ const project = groupProject(state, conversation(state, update.conversationId))
+ const progress = project.progress!
+ const pending = progress.requestMessageId
+ ? await tx.superTabDelivery.findFirst({ where: { tabId, agentId, messageId: progress.requestMessageId,
+ status: { in: ['queued', 'claimed', 'uncertain', 'delivered'] } } })
+ : null
+ if (!pending) {
+ progress.requestedRevision = progress.dirtyRevision
+ progress.requestedAt = this.now()
+ progress.requestMessageId = update.id
+ const revision = row.revision + 1
+ await this.writeMessages(tx, tabId, state, [update], revision)
+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { revision, state: json(state) } })
+ }
+ }
const rows = await tx.superTabDelivery.findMany({ where: { tabId, agentId, status: { in: ['queued', 'claimed', 'uncertain'] } },
orderBy: { createdAt: 'asc' }, take: 100 })
const allowed: SuperTabDelivery[] = []
diff --git a/cli/e2e/superTabMachines.e2e.ts b/cli/e2e/superTabMachines.e2e.ts
index 522a25a73..d3d7f7538 100644
--- a/cli/e2e/superTabMachines.e2e.ts
+++ b/cli/e2e/superTabMachines.e2e.ts
@@ -18,7 +18,7 @@ afterEach(async () => {
await relay?.close(); relay = undefined
})
-it('queues a teammate start without granting general machine access and resumes the same native receipt', async () => {
+it.each(['project', 'swarm'])('queues a teammate start with %s capacity and resumes the same native receipt', async scope => {
const backend = await FakeBackend.start(); relay = backend
const specs = [
{ machineId: 'd1'.repeat(16), computerId: 'pool-lead-fixture', name: 'Lead fixture', token: 'fixture-lead-token', account: 'lead', email: '[email protected]' },
@@ -34,13 +34,17 @@ it('queues a teammate start without granting general machine access and resumes
const project = join(b.projectsDir, 'contributed'); mkdirSync(project, { recursive: true })
const agents: Array<Record<string, any>> = [], starts = new Map<string, Record<string, any>>()
let generation = 'grant-1', observations = 0
- const pool = { machineId: memberMachine.machineId, generation, cwd: project, engines: ['codex'], maxAgents: 2, paused: false }
+ const pool = { machineId: memberMachine.machineId, generation,
+ cwd: scope === 'swarm' ? join(b.dataDir, 'swarm-projects', 'pool-tab') : project,
+ ...(scope === 'swarm' ? { scope } : {}), engines: ['codex'], maxAgents: 2, paused: false }
+ const projects = scope === 'swarm' ? [{ id: 'lead', conversationIds: ['lead'],
+ repository: { machineId: memberMachine.machineId, cwd: project, repositoryUrl: null } }] : undefined
const id = (machine: string, harness: string) => createHash('sha256').update(JSON.stringify([machine, harness])).digest('hex').slice(0, 24)
backend.superTabs = async (method, raw, body, caller) => {
const path = new URL(raw, backend.httpUrl).pathname
if (path.endsWith('/pools')) {
expect(path.split('/')[4]).toBe(caller.machineId)
- return { data: caller.machineId === memberMachine.machineId && generation ? [{ tabId: 'pool-tab', machine: pool, starts: [...starts.values()].filter(s => !s.harnessId || !s.poolSettled), harnessIds: agents.filter(a => a.machineId === caller.machineId).map(a => a.harnessId) }] : [] }
+ return { data: caller.machineId === memberMachine.machineId && generation ? [{ tabId: 'pool-tab', machine: pool, projects, starts: [...starts.values()].filter(s => !s.harnessId || !s.poolSettled), harnessIds: agents.filter(a => a.machineId === caller.machineId).map(a => a.harnessId) }] : [] }
}
if (path.includes('/hosts/') && path.includes('/starts/')) {
expect(caller.account).toBe('member')
@@ -57,7 +61,7 @@ it('queues a teammate start without granting general machine access and resumes
}
if (path.includes('/hosts/')) return { data: path.endsWith('/assignments') ? [] : agents.filter(a => a.machineId === caller.machineId).map(agent => ({ tabId: 'pool-tab', agent, observers: [] })) }
if (path.includes('/machines/')) { expect(caller.account).toBe('member'); expect(body.generation).toBe(generation); observations++; return { data: { revision: observations } } }
- if (path === '/api/super-tabs/pool-tab') return { data: { state: { id: 'pool-tab', agents, project: { machineId: memberMachine.machineId, cwd: project, repositoryUrl: null } }, revision: observations } }
+ if (path === '/api/super-tabs/pool-tab') return { data: { state: { id: 'pool-tab', agents, projects, project: { machineId: memberMachine.machineId, cwd: project, repositoryUrl: null } }, revision: observations } }
if (path.includes('/starts/')) return { data: starts.get(path.split('/').at(-1)!) }
if (path.endsWith('/commands')) {
const c = body.command
@@ -77,13 +81,14 @@ it('queues a teammate start without granting general machine access and resumes
await Promise.all(daemons.map(d => d.start()))
await until('both fixture accounts connected', () => backend.nodeUp(leadMachine.machineId) && backend.nodeUp(memberMachine.machineId), 30000)
const onA = await LocalClient.connect(a, { machineId: leadMachine.machineId }), onB = await LocalClient.connect(b, { machineId: memberMachine.machineId }); clients.push(onA, onB)
- const setup = { action: 'prepareContribution', tabId: 'pool-tab', operationId: 'fixture-setup' }
+ const setup = { action: 'prepareContribution', tabId: 'pool-tab', operationId: 'fixture-setup', ...(scope === 'swarm' ? { scope } : {}) }
const prepared = await until('one-field machine preparation', async () => {
const value = await onB.request('super_tabs', setup, 30000)
expect(value.error, JSON.stringify(value)).toBeUndefined()
return value.state === 'ready' ? value : null
}, 45000, 250)
- expect(prepared.cwd).toBe(project)
+ expect(prepared.cwd).toBe(pool.cwd)
+ if (scope === 'swarm') expect(prepared.scope).toBe('swarm')
expect(prepared.engines).toEqual(expect.arrayContaining(['claude', 'codex']))
expect(prepared.maxAgents).toBeGreaterThan(0)
expect((await onB.request('agents_list')).agents).toHaveLength(0)
diff --git a/cli/e2e/superTabsCollaboration.e2e.ts b/cli/e2e/superTabsCollaboration.e2e.ts
index 9c2d0b4de..eb7e5ca62 100644
--- a/cli/e2e/superTabsCollaboration.e2e.ts
+++ b/cli/e2e/superTabsCollaboration.e2e.ts
@@ -22,7 +22,7 @@ afterEach(async () => {
await backend?.close(); backend = undefined
})
-it('lets one person’s lead use a teammate’s shared machine while preserving account and conversation boundaries', async () => {
+it('coordinates an owner-contributed agent while keeping guest machine access separate', async () => {
const relay = await FakeBackend.start(); backend = relay
const specs = [
{ machineId: 'a6'.repeat(16), computerId: 'super-tab-starter', name: 'Starter Mac', token: 'fixture-starter-token', account: 'starter', email: '[email protected]', identity: newIdentity() },
@@ -55,7 +55,7 @@ it('lets one person’s lead use a teammate’s shared machine while preserving
}
if (!contributionAllowed) return failure()
if (path === `/api/super-tabs/${TAB}/native` && method === 'POST') {
- expect(caller.account).toBe(starter.account)
+ expect(caller.account).toBe(member.account)
const target = agents.find(agent => agent.id === body.agentId)!
contexts.set(body.operationId, { contextId: body.operationId, tabId: TAB, conversationId: body.conversationId,
harnessId: target.harnessId, machineId: target.machineId, operatorAccount: caller.account, lastEventId: null })
@@ -78,6 +78,14 @@ it('lets one person’s lead use a teammate’s shared machine while preserving
if (path.endsWith('/commands')) {
const command = body.command, author = body.asAgentId ? agents.find(agent => agent.id === body.asAgentId)! : null
if (author) expect(author.machineId).toBe(caller.machineId)
+ if (command.type === 'agent.add') {
+ expect(caller.account).toBe(member.account)
+ expect(command.machineId).toBe(member.machineId)
+ const id = agentId(command.machineId, command.harnessId)
+ agents.push({ id, machineId: command.machineId, harnessId: command.harnessId, configuration: command.configuration })
+ groups.get(GROUP)!.add(id)
+ return { data: { result: { agentId: id } } }
+ }
if (command.type === 'agent.start') {
const startId = `start-${body.operationId}`
if (!starts.has(startId)) starts.set(startId, { id: startId, creationId: `super-${startId}`, request: command.request, dispatched: false, harnessId: null })
@@ -146,19 +154,27 @@ it('lets one person’s lead use a teammate’s shared machine while preserving
}
const request = { conversationId: GROUP, machineId: member.machineId, engine: 'codex', name: 'Member builder', cwd: projectB,
worktree: false, permissionMode: 'auto', requirements: { memoryBytes: 0, diskBytes: 1, maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false } }
- let started = await run(['start', 'remote-builder', JSON.stringify(request)])
- if (started.answer.error === 'START_PENDING') started = await until('remote creation receipt', async () => {
- const next = await run(['resume', 'start-remote-builder']); return next.answer.error === 'START_PENDING' ? null : next
- }, 60_000, 500)
- expect(started.code, JSON.stringify(started.answer)).toBe(0)
- expect((await run(['start', 'remote-builder', JSON.stringify(request)])).answer.harnessId).toBe(started.answer.harnessId)
- const workerId = agentId(member.machineId, started.answer.harnessId)
+ const attempted = await run(['start', 'remote-builder', JSON.stringify(request)])
+ expect(attempted.answer).toMatchObject({ error: 'CONTRIBUTION_REQUIRED', detail: expect.stringContaining('Add machine') })
+ expect((await onB.request('agents_list')).agents).toHaveLength(0)
+ // Sharing now gives a guest its own OS user, not the owner's Swarm controls.
+ // The owner can contribute a running agent; owner-dispatched machine starts
+ // are exercised separately in superTabMachines.e2e.ts.
+ const owned = await onB.request('agent_create', { engine: 'codex', cwd: projectB }, 90_000)
+ expect(owned.error, JSON.stringify(owned)).toBeUndefined()
+ const harnessId = owned.agent.id as string
+ const workerId = agentId(member.machineId, harnessId)
+ expect(await onB.request('super_tabs', { action: 'backend', method: 'POST', path: `/api/super-tabs/${TAB}/commands`,
+ body: { operationId: 'contribute-worker', command: { type: 'agent.add', conversationId: GROUP,
+ machineId: member.machineId, harnessId, name: 'Member builder', configuration: { engine: 'codex' }, lead: false } } }))
+ .toMatchObject({ value: { result: { agentId: workerId } } })
+ await onB.request('super_tabs', { action: 'wake' })
expect((await onB.request('agents_list')).agents).toHaveLength(1)
expect((await onA.request('agents_list')).agents).toHaveLength(1)
const viaA = await LocalClient.connect(a, { machineId: member.machineId }); clients.push(viaA)
// Machine control does not make the member's account a proxy for the starter.
expect(await viaA.request('super_tabs', { action: 'backend', method: 'GET', path: `/api/super-tabs/${TAB}` }))
- .toMatchObject({ error: 'OWNER_REQUIRED' })
+ .toMatchObject({ error: 'GUEST_NOT_ALLOWED' })
expect((await run(['command', 'assign-instruction', JSON.stringify({ type: 'message.send', conversationId: GROUP,
text: 'Verify offline editing on the member machine', replyTo: null, recipientIds: [workerId] })])).code).toBe(0)
await until('member host delivers the lead instruction', () => pending.get(workerId)?.status === 'delivered' || null, 45_000)
@@ -171,19 +187,20 @@ it('lets one person’s lead use a teammate’s shared machine while preserving
expect((await run(['command', 'reuse-member', JSON.stringify({ type: 'conversation.agent', conversationId: 'onboarding', agentId: workerId, present: true, lead: false })])).code).toBe(0)
expect(groups.get('onboarding')!.has(workerId)).toBe(true)
expect((await onB.request('agents_list')).agents).toHaveLength(1)
- const contextId = 'starter-on-member-terminal'
- expect(await onA.request('super_tabs', { action: 'backend', method: 'POST', path: `/api/super-tabs/${TAB}/native`,
+ const contextId = 'member-on-own-terminal'
+ expect(await onB.request('super_tabs', { action: 'backend', method: 'POST', path: `/api/super-tabs/${TAB}/native`,
body: { operationId: contextId, conversationId: GROUP, agentId: workerId } })).toMatchObject({ value: { contextId } })
- expect(await viaA.request('super_tabs', { action: 'prepareNative', tabId: TAB, contextId })).toMatchObject({ inputContext: contextId })
- const ready = viaA.next(frame => frame.type === 'terminal_ready' && frame.payload?.requestId === 'member-terminal')
- viaA.send('terminal_open', { requestId: 'member-terminal', protocolVersion: 3, agentId: started.answer.harnessId, cols: 100, rows: 30, inputContext: contextId })
+ expect(await viaA.request('super_tabs', { action: 'prepareNative', tabId: TAB, contextId })).toMatchObject({ error: 'GUEST_NOT_ALLOWED' })
+ expect(await onB.request('super_tabs', { action: 'prepareNative', tabId: TAB, contextId })).toMatchObject({ inputContext: contextId })
+ const ready = onB.next(frame => frame.type === 'terminal_ready' && frame.payload?.requestId === 'member-terminal')
+ onB.send('terminal_open', { requestId: 'member-terminal', protocolVersion: 3, agentId: harnessId, cols: 100, rows: 30, inputContext: contextId })
const streamId = (await ready).payload!.streamId as string
- await viaA.waitForBinary(frame => frame.streamId === streamId && frame.kind === TerminalBinaryKind.keyframe)
- viaA.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 0, compressed: false, bytes: Buffer.from('Keep this change focused') })
- viaA.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 1, compressed: false, bytes: Buffer.from('\r') })
+ await onB.waitForBinary(frame => frame.streamId === streamId && frame.kind === TerminalBinaryKind.keyframe)
+ onB.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 0, compressed: false, bytes: Buffer.from('Keep this change focused') })
+ onB.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 1, compressed: false, bytes: Buffer.from('\r') })
await until('remote terminal observation', () => observations.length >= 2 || null, 30_000)
expect(observations.map(row => row.kind)).toEqual(['prompt', 'answer'])
- expect(observations.every(row => row.operatorAccount === starter.account && row.executionAccount === member.account && row.conversationId === GROUP)).toBe(true)
+ expect(observations.every(row => row.operatorAccount === member.account && row.executionAccount === member.account && row.conversationId === GROUP)).toBe(true)
expect([...relay.webSent.values()].flat().filter(frame => ['super_tabs', 'agent_create', 'terminal_open'].includes(String(frame.type)))
.every(frame => !!(frame.payload as any)?.__e2e)).toBe(true)
contributionAllowed = false
diff --git a/cli/src/superTabs/contribution.spec.ts b/cli/src/superTabs/contribution.spec.ts
index e5d65fe48..7fc4f3291 100644
--- a/cli/src/superTabs/contribution.spec.ts
+++ b/cli/src/superTabs/contribution.spec.ts
@@ -1,6 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { ContributionPreparations, prepareContribution } from './contribution.js'
+import { mkdtemp, rm, stat } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
const GiB = 1024 ** 3
function fixture() {
@@ -23,6 +26,20 @@ function fixture() {
return { run, state, deps, core, request, close }
}
describe('one-field machine preparation', () => {
+ it('contributes a swarm workspace without asking for a project or cloning one', async () => {
+ const f = fixture()
+ const dataDir = await mkdtemp(join(tmpdir(), 'harness-swarm-contribution-'))
+ try {
+ delete f.state.project
+ const core = fakeCore({ dataDir })
+ const result = await prepareContribution(core, { tabId: 'tab', scope: 'swarm' }, f.deps as never)
+ const cwd = join(dataDir, 'swarm-projects', 'tab')
+ expect(result).toMatchObject({ scope: 'swarm', cwd, engines: ['claude', 'pi'] })
+ expect((await stat(cwd)).isDirectory()).toBe(true)
+ expect(f.deps.prepare).not.toHaveBeenCalled()
+ expect(f.deps.capacity).toHaveBeenCalledWith({ cwd, tools: ['git'], devices: [] })
+ } finally { await rm(dataDir, { recursive: true, force: true }) }
+ })
it('uses the lead project on its host and probes all engines without inventing authentication', async () => {
const f = fixture()
expect(await f.run()).toEqual({ ok: true, state: 'ready', cwd: '/repo', engines: ['claude', 'pi'], maxAgents: 4 })
diff --git a/cli/src/superTabs/contribution.ts b/cli/src/superTabs/contribution.ts
index 18d1e9b8c..ddf358cc9 100644
--- a/cli/src/superTabs/contribution.ts
+++ b/cli/src/superTabs/contribution.ts
@@ -3,6 +3,8 @@ import { openDaemon } from '../agentClient/daemon.js'
import { parseProjectFolder, prepareProjectFolder } from '../lib/projectFolder.js'
import { readCapabilities } from './capacity.js'
import { backend, identifier, object } from './host.js'
+import { mkdir } from 'node:fs/promises'
+import { join } from 'node:path'
type Json = Record<string, unknown>
const GiB = 1024 ** 3
@@ -17,7 +19,9 @@ export async function prepareContribution(core: CoreApi, input: Json, deps = {
const state = object(answer.state), project = object(state.project)
const machineId = core.daemon.machineId()
const existing = (Array.isArray(state.machines) ? state.machines.map(object) : []).find(m => m.machineId === machineId)
- let cwd = existing?.cwd
+ const swarm = input.scope === 'swarm' || Array.isArray(state.projects)
+ let cwd = swarm ? join(core.dataDir, 'swarm-projects', input.tabId) : existing?.cwd
+ if (swarm) await mkdir(cwd as string, { recursive: true })
if (typeof cwd !== 'string') {
if (project.machineId === machineId && typeof project.cwd === 'string') cwd = project.cwd
else {
@@ -44,7 +48,7 @@ export async function prepareContribution(core: CoreApi, input: Json, deps = {
// A conservative ceiling; each actual start still reserves measured memory
// and disk and rechecks the engine's current subscription allowance.
const maxAgents = Math.max(1, Math.min(8, Math.floor(available / (4 * GiB))))
- return { ok: true, state: 'ready', cwd, engines: [...new Set(engines)], maxAgents }
+ return { ok: true, state: 'ready', cwd, engines: [...new Set(engines)], maxAgents, ...(swarm ? { scope: 'swarm' } : {}) }
} finally { connection.close() }
}
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 40bc198a2..0b518703a 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -17,11 +17,29 @@ function fixture() {
const close = vi.fn(), open = vi.fn(async () => ({ machineId: 'host', request, close }))
const capabilities = vi.fn(async () => ({ ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 200, projectDiskFreeBytes: 1000 }, tools: { git: true } }))
const start = vi.fn(async () => ({ ok: true }))
- const machine = new ContributedMachines(core, 'host', { backend, open, capabilities, start, now: () => now } as never)
- return { machine, pool, core, backend, open, close, capabilities, start, advance: () => { now += 16000 } }
+ const prepare = vi.fn(async () => {})
+ const machine = new ContributedMachines(core, 'host', { backend, open, capabilities, start, prepare, now: () => now } as never)
+ return { machine, pool, core, backend, open, close, capabilities, start, prepare, advance: () => { now += 16000 } }
}
describe('contributed machine executor', () => {
+ it('prepares a swarm project before dispatch and durably rejects an unsafe checkout', async () => {
+ const f = fixture()
+ Object.assign(f.pool.machine, { scope: 'swarm' })
+ await f.machine.tick()
+ expect(f.prepare).toHaveBeenCalledWith(f.core, f.pool, f.pool.starts[0])
+ expect(f.prepare.mock.invocationCallOrder[0]).toBeLessThan(f.start.mock.invocationCallOrder[0]!)
+ f.prepare.mockRejectedValueOnce(new Error('Project checkout unavailable'))
+ f.advance()
+ await f.machine.tick()
+ expect(f.start).toHaveBeenCalledTimes(1)
+ expect(f.backend.mock.calls.some(c => JSON.stringify(c[3] ?? {}).includes('Project checkout unavailable'))).toBe(true)
+ f.pool.starts[0]!.dispatched = true
+ f.advance()
+ await f.machine.tick()
+ expect(f.prepare).toHaveBeenCalledTimes(2)
+ expect(f.start).toHaveBeenCalledTimes(2)
+ })
it('publishes only scoped measurements and executes through the owner start endpoint', async () => {
const f = fixture()
await f.machine.tick()
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 83596fd5d..e3766f074 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -4,6 +4,7 @@ import { backend } from './host.js'
import { identifier, object } from './wire.js'
import { readCapabilities, quotaOf } from './capacity.js'
import { startAgent, type ScopedRequest } from './start.js'
+import { prepareSwarmProject } from './projectFolder.js'
const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v : null
const list = (v: unknown) => Array.isArray(v) ? v.map(object) : []
@@ -16,7 +17,9 @@ export class ContributedMachines {
private next = 0
private readonly cursors = new Map<string, number>()
constructor(private readonly core: CoreApi, private readonly machineId: string,
- private readonly deps = { backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }) {}
+ private readonly deps: { backend: typeof backend; open: typeof openDaemon; capabilities: typeof readCapabilities;
+ start: typeof startAgent; now: () => number; prepare?: typeof prepareSwarmProject } =
+ { backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }) {}
stop() { this.stopped = true }
tick(): Promise<void> {
if (this.stopped || this.deps.now() < this.next) return Promise.resolve()
@@ -67,6 +70,15 @@ export class ContributedMachines {
input.action === 'startStatus' ? 'GET' : 'POST', path,
input.action === 'startStatus' ? undefined : { operationId: input.operationId, command: input.command }) })
try {
+ if (pool.scope === 'swarm' && !start.dispatched) {
+ try { await (this.deps.prepare ?? prepareSwarmProject)(this.core, row, start) }
+ catch (error) {
+ await scoped({ action: 'command', operationId: `prepare-failed-${start.id}`,
+ command: { type: 'agent.startFailed', startId: start.id,
+ error: error instanceof Error ? error.message : 'Could not prepare this project on the machine.' } })
+ continue
+ }
+ }
const result = await this.deps.start({ tabId: row.tabId, startId: start.id, hostDispatch: true }, scoped, where, this.deps.open)
if (result.ok === true && identifier(result.harnessId)) await scoped({ action: 'command', operationId: `settled-${start.id}`,
command: { type: 'agent.startSettled', startId: start.id, warning: result.modelWarning ?? null } })
diff --git a/cli/src/superTabs/projectFolder.spec.ts b/cli/src/superTabs/projectFolder.spec.ts
new file mode 100644
index 000000000..525e9a92d
--- /dev/null
+++ b/cli/src/superTabs/projectFolder.spec.ts
@@ -0,0 +1,61 @@
+import { join } from 'node:path'
+import { describe, expect, it, vi } from 'vitest'
+import { fakeCore } from '../testing/fakeCore.js'
+import { prepareSwarmProject } from './projectFolder.js'
+
+function fixture() {
+ const core = fakeCore({ dataDir: '/isolated-project-fixture' })
+ const root = join(core.dataDir, 'swarm-projects', 'tab')
+ const repository = { machineId: 'other', cwd: '/other/repo', repositoryUrl: 'https://github.com/example/project' }
+ const row = { tabId: 'tab', machine: { scope: 'swarm', cwd: root },
+ projects: [{ id: 'project-a', repository, conversationIds: ['work'] }] }
+ const start = { dispatched: false, request: { conversationId: 'work', cwd: join(root, 'project-a') } }
+ const prepare = vi.fn(async () => start.request.cwd)
+ return { core, root, repository, row, start, prepare,
+ run: () => prepareSwarmProject(core, row, start, prepare) }
+}
+
+describe('per-project checkouts on a contributed swarm machine', () => {
+ it('prepares the exact project checkout and leaves unrelated projects alone', async () => {
+ const f = fixture()
+ await f.run()
+ expect(f.prepare).toHaveBeenCalledExactlyOnceWith({
+ source: 'remote', repositoryUrl: 'https://github.com/example/project.git', name: 'project-a',
+ }, { root: f.root })
+ f.start.dispatched = true
+ await f.run()
+ expect(f.prepare).toHaveBeenCalledTimes(1)
+ })
+ it('uses a project already on this host without cloning it', async () => {
+ const f = fixture()
+ f.repository.machineId = f.core.daemon.machineId()
+ f.start.request.cwd = f.repository.cwd
+ await f.run()
+ expect(f.prepare).not.toHaveBeenCalled()
+ })
+ it('does not widen a legacy contribution or substitute a different filesystem path', async () => {
+ const f = fixture()
+ f.row.machine.scope = ''
+ await f.run()
+ expect(f.prepare).not.toHaveBeenCalled()
+ f.row.machine.scope = 'swarm'
+ f.row.machine.cwd = '/unrelated'
+ await expect(f.run()).rejects.toThrow('authorize its swarm workspace')
+ f.row.machine.cwd = f.root
+ f.start.request.cwd = join(f.root, 'project-b')
+ await expect(f.run()).rejects.toThrow('outside this project')
+ f.start.request.conversationId = 'unknown'
+ await expect(f.run()).rejects.toThrow('no authorized project')
+ })
+ it('refuses missing or unsafe repositories and a mismatched prepared checkout', async () => {
+ const f = fixture()
+ for (const url of [undefined, 'file:///private/repo', 'https://[email protected]/example/project', 'ext::command']) {
+ f.repository.repositoryUrl = url as string
+ await expect(f.run()).rejects.toThrow()
+ }
+ expect(f.prepare).not.toHaveBeenCalled()
+ f.repository.repositoryUrl = 'https://github.com/example/project'
+ f.prepare.mockResolvedValueOnce('/different')
+ await expect(f.run()).rejects.toThrow('does not match')
+ })
+})
diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.ts
new file mode 100644
index 000000000..b95d25ad9
--- /dev/null
+++ b/cli/src/superTabs/projectFolder.ts
@@ -0,0 +1,28 @@
+import { join, resolve } from 'node:path'
+import type { CoreApi } from '../core/api.js'
+import { parseProjectFolder, prepareProjectFolder } from '../lib/projectFolder.js'
+import { identifier, object } from './wire.js'
+
+type Json = Record<string, unknown>
+
+/** The owner granted a swarm workspace, not caller-selected filesystem paths.
+ * Prepare the queued project's repository there before reserving or launching. */
+export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json, prepare = prepareProjectFolder): Promise<void> {
+ const pool = object(row.machine)
+ if (pool.scope !== 'swarm' || start.dispatched) return
+ const request = object(start.request)
+ const project = (Array.isArray(row.projects) ? row.projects.map(object) : [])
+ .find(p => Array.isArray(p.conversationIds) && p.conversationIds.includes(request.conversationId))
+ if (!project || !identifier(project.id) || !identifier(row.tabId)) throw new Error('This start has no authorized project.')
+ const repository = object(project.repository)
+ const expectedRoot = join(core.dataDir, 'swarm-projects', row.tabId)
+ if (typeof pool.cwd !== 'string' || resolve(pool.cwd) !== resolve(expectedRoot)) throw new Error('Add this machine again to authorize its swarm workspace.')
+ if (repository.machineId === core.daemon.machineId() && typeof repository.cwd === 'string' && request.cwd === repository.cwd) return
+ const expected = join(expectedRoot, project.id)
+ if (request.cwd !== expected) throw new Error('The requested folder is outside this project.')
+ if (typeof repository.repositoryUrl !== 'string') throw new Error('Share a GitHub repository for this project before starting agents on another machine.')
+ const source = parseProjectFolder({ projectSource: 'remote', repositoryUrl: repository.repositoryUrl })
+ if (source?.source !== 'remote') throw new Error('This project repository is unavailable.')
+ const cwd = await prepare({ ...source, name: project.id }, { root: expectedRoot })
+ if (cwd !== expected) throw new Error('The prepared checkout does not match the authorized project.')
+}
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 6e62c9598..75c064996 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -581,8 +581,10 @@ describe('routing contributed capacity', () => {
const healthy = () => ({ machineId: 'm1', name: 'Contributed laptop', cwd: '/owner/project', engines: ['claude'], paused: false,
observation: { receivedAt: Date.now(), resources: { memoryTotalBytes: 32e9, memoryUsedBytes: 2e9, projectDiskFreeBytes: 200e9 },
tools: { git: true }, runningHarnessIds: [], quotas: [{ engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 20, resetsAt: Date.now() + 3600000 }] }] } })
- async function runPool(pool: Record<string, any>, members = false, needs: Record<string, unknown> = {}) {
- const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: { state: { id: 'tab', agents: members ? agents : [agents[1]], conversations: conversations(), machines: [pool] } }, policy: { policy, warnings: [] }, machines: [] } } })
+ async function runPool(pool: Record<string, any>, members = false, needs: Record<string, unknown> = {}, project?: Record<string, unknown>) {
+ const groups = conversations()
+ if (project) Object.assign(groups[1]!, { projectId: project.id })
+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: { state: { id: 'tab', agents: members ? agents : [agents[1]], conversations: groups, machines: [pool], ...(project ? { projects: [project] } : {}) } }, policy: { policy, warnings: [] }, machines: [] } } })
const open = opener()
const answer = await routeTask({ ...input, assessment: { ...input.assessment, needs } }, s, where, open)
expect(open).not.toHaveBeenCalled()
@@ -595,6 +597,16 @@ describe('routing contributed capacity', () => {
const member = await runPool(healthy(), true)
expect(member.answer.ok).toBe(true)
})
+ it('routes each swarm project to its own checkout and never widens an old folder grant', async () => {
+ const project = { id: 'project-two', repository: { machineId: 'other', cwd: '/elsewhere', repositoryUrl: 'https://github.com/example/two' } }
+ expect((await runPool(healthy(), false, {}, project)).answer.ok).not.toBe(true)
+ const shared = { ...healthy(), scope: 'swarm', cwd: '/swarm-root' }
+ expect((await runPool(shared, false, {}, project)).answer.next).toContain('/swarm-root/project-two')
+ project.repository.machineId = 'm1'
+ expect((await runPool(shared, false, {}, project)).answer.next).toContain('/elsewhere')
+ expect((await runPool(shared, false, {}, { id: 'project-two' })).answer.ok).not.toBe(true)
+ expect((await runPool(shared)).answer.ok).not.toBe(true)
+ })
it.each([
['stale', (p: any) => { p.observation.receivedAt = 0 }],
['paused', (p: any) => { p.paused = true }],
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index e410325c3..e8cbf5267 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -111,6 +111,8 @@ export async function routeTask(input: { tabId: string; conversationId: string;
const group = conversations.find(c => c.id === input.conversationId)
if (!group) return { error: 'NOT_FOUND', detail: 'No such group in this Super Tab.' }
if (group.leadId !== value.agentId) return { error: 'LEAD_REQUIRED', detail: 'Only the Lead of this group routes its work.' }
+ const projectId = String(group.projectId ?? 'lead')
+ const project = list(state.projects).find(p => p.id === projectId)
// The group's Lead and the tab Lead coordinate; neither is a worker candidate even when idle.
const busy = new Set([String(group.leadId), String(conversations.find(c => c.id === 'lead')?.leadId),
...conversations.filter(c => active(c.assignment)).map(c => String(object(c.assignment).agentId))])
@@ -122,7 +124,17 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// The Lead's own machine is the account's even when the list could not be read.
if (!machines.has(where.machineId)) machines.set(where.machineId, { name: where.machineId, status: 'unknown', account: true })
for (const m of members) if (!machines.has(String(m.machineId))) machines.set(String(m.machineId), { name: String(m.machineId), status: 'unknown', account: false })
- for (const pool of list(state.machines)) machines.set(String(pool.machineId), { name: String(pool.name), status: 'contributed', account: false, pool })
+ for (const original of list(state.machines)) {
+ const repository = object(project?.repository)
+ const pool: Json = { ...original,
+ ...(original.scope === 'swarm' ? { cwd: repository.machineId === original.machineId
+ ? repository.cwd : `${String(original.cwd).replace(/\/+$/, '')}/${projectId}` } : {}),
+ ...(original.scope !== 'swarm' && projectId !== 'lead' ? { projectUnavailable: true } : {}),
+ ...(original.scope === 'swarm' && repository.machineId !== original.machineId && typeof repository.repositoryUrl !== 'string'
+ ? { repositoryUnavailable: true } : {}),
+ }
+ machines.set(String(pool.machineId), { name: String(pool.name), status: 'contributed', account: false, pool })
+ }
const enabled = policy.models.filter(m => m.enabled)
// The probes do not wait for the context reads: the machines, the task's folder and the group's talk and log are read
@@ -206,6 +218,8 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
const blocked = [...(!fresh ? [OFFLINE] : []), ...(pool.paused ? ['New work is paused on this machine.'] : [])]
const needs = startRequirements(a.needs), tools = object(observed.tools)
const newReasons = [...blocked,
+ ...(pool.projectUnavailable === true ? ['Its owner must add this machine to the swarm again to support other projects.'] : []),
+ ...(pool.repositoryUnavailable === true ? ['Share a repository for this project before starting agents on this machine.'] : []),
...(pool.availableSlots === 0 ? ['This machine has no available agent slots.'] : []),
...(!finite(resources.projectDiskFreeBytes) || resources.projectDiskFreeBytes < needs.diskBytes ? ['The project has insufficient measured free disk.'] : []),
...(!finite(resources.memoryTotalBytes) || !finite(resources.memoryUsedBytes) || resources.memoryTotalBytes - resources.memoryUsedBytes < needs.memoryBytes ? ['Insufficient measured free memory.'] : []),
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 676048555..50c9efa62 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -23,6 +23,7 @@ const HELP = {
model: 'opus', effort: 'high', routeDecisionId: 'DECISION' },
command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request.',
commands: [
+ { type: 'project.report', projectId: 'PROJECT', throughRevision: 123, text: 'What changed, what is blocked, and what comes next. Use null when nothing merits repeating.' },
{ type: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },
{ type: 'conversation.create', title: 'Outcome', brief: 'An independently assignable result', checks: [{ description: 'Observable acceptance evidence', independent: false }] },
{ type: 'conversation.agent', conversationId: 'GROUP', agentId: 'AGENT', present: true, lead: false },
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index a043199e3..63e8e6e4b 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { startAgent } from './start.js'
const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }
-function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; refuseModel?: string; frame?: string } = {}) {
+function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; refuseModel?: string; frame?: string; guest?: boolean } = {}) {
const start = { creationId: 'super-native-receipt', error: null as string | null, request: { machineId: 'target', conversationId: 'group', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,
requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }, dispatched: false }
let nativeState = 'missing', lostJoin = false
@@ -22,6 +22,7 @@ function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?:
if (type === 'engines_probe') return { engines: [{ engine: (payload.engines as string[])[0], installed: true }] }
if (type === 'usage_read') return { providers: [] }
if (type === 'super_tabs') {
+ if (options.guest) return { error: 'GUEST_NOT_ALLOWED' }
if (payload.action === 'reserveCapacity') return { ok: true, reservationId: start.creationId }
if (payload.action === 'observeCapacity') return { ok: true, reservationId: start.creationId, harnessId: 'native', released: nativeState === 'cancelled' }
return { ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 100, projectDiskFreeBytes: 1000 }, tools: { git: true }, devices: {},
@@ -50,6 +51,14 @@ const expectSwitchTo = (f: Parameters<typeof switchCall>[0], selectedModel: stri
expect(call[2]).toBeGreaterThan(50_000)
expect(call[2]).toBeLessThanOrEqual(60_000)
}
+it('asks for an owner contribution instead of widening a guest machine connection', async () => {
+ const f = fixture({ guest: true })
+ expect(await startAgent({ action: 'start', tabId: 'tab', operationId: 'guest-start', request: f.start.request }, f.scoped, where, f.open))
+ .toMatchObject({ error: 'CONTRIBUTION_REQUIRED', detail: expect.stringContaining('Add machine') })
+ expect(f.request.mock.calls.some(c => c[0] === 'agent_create')).toBe(false)
+ expect(f.close).toHaveBeenCalledOnce()
+})
+
it('uses one native creation receipt and joins its captured group after a lost join reply', async () => {
const f = fixture(); f.loseJoin()
const input = { action: 'start', tabId: 'tab', operationId: 'user-intent', request: f.start.request }
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index e9aee27eb..9b0c6efa9 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -102,6 +102,10 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher
if (start.dispatched) return { error: 'START_UNCERTAIN', startId, creationId,
detail: 'This start was submitted but its machine has no receipt. Inspect the machine before creating another agent.' }
const resources = await inspectCapacity(target, request)
+ if (resources.capacity.error === 'GUEST_NOT_ALLOWED') return {
+ error: 'CONTRIBUTION_REQUIRED', startId,
+ detail: 'Ask the machine owner to use Add machine in this Swarm, or to add a running agent. Guest machine sharing does not grant access to the owner’s Swarm controls.',
+ }
if (!resources.allowed) return { error: 'CAPACITY_UNAVAILABLE', startId, ...resources }
const reservation = await target.request('super_tabs', { action: 'reserveCapacity', creationId,
cwd: request.cwd, worktree: request.worktree === true, requirements: request.requirements }, 20_000).catch(() => null)
diff --git a/desktop/integration_test/super_tab_native_test.dart b/desktop/integration_test/super_tab_native_test.dart
index 271136a7b..457ce9bd7 100644
--- a/desktop/integration_test/super_tab_native_test.dart
+++ b/desktop/integration_test/super_tab_native_test.dart
@@ -17,6 +17,8 @@ import 'package:harness/widgets/terminal_panel.dart';
import '../test/super_tab_launch_test.dart'
show SuperTabFixtureConnection, SuperTabLaunchFixture, tabId;
+import '../test/support/super_tab_fixture.dart'
+ show projectFixture, conversationFixture;
/// A real Flutter/macOS surface with in-memory accounts and native protocol
/// fixtures. It never opens a production daemon, account, harness or database.
@@ -25,9 +27,9 @@ void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized()
..framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;
testWidgets(
- 'native Super Tab keeps group context, people and terminal in one workspace',
+ 'native Swarm keeps group context, people and terminal in one workspace',
(tester) async {
- debugPrint('Super Tab fixture: initialize window');
+ debugPrint('Swarm fixture: initialize window');
await windowManager.ensureInitialized().timeout(
const Duration(seconds: 10),
);
@@ -36,7 +38,7 @@ void main() {
.timeout(const Duration(seconds: 10));
await windowManager.show().timeout(const Duration(seconds: 10));
await windowManager.focus().timeout(const Duration(seconds: 10));
- debugPrint('Super Tab fixture: create lead');
+ debugPrint('Swarm fixture: create lead');
final f = SuperTabLaunchFixture();
f.connection.nativeName = 'hi';
f.connection.nativeSurface = true;
@@ -49,10 +51,24 @@ void main() {
reason: box.error,
);
});
- debugPrint('Super Tab fixture: show conversation');
+ debugPrint('Swarm fixture: show conversation');
f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];
final server = f.connection.server;
- server.state['name'] = 'Pilot';
+ server.state['name'] = 'Company';
+ server.state['projects'] = [
+ projectFixture('lead', 'Lamp OS', 'lead'),
+ projectFixture(
+ 'design',
+ 'Design',
+ 'design-lead',
+ visibility: 'private',
+ ),
+ ];
+ (server.state['conversations'] as List)[1]['number'] = 12;
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('design-lead', 'Lead'),
+ 'projectId': 'design',
+ });
server.state['machines'] = [
{
'machineId': 'm',
@@ -101,7 +117,7 @@ void main() {
(server.state['conversations'] as List)[0]['leadId'] = 'lead-agent';
(server.state['people'] as List).addAll(
List.generate(
- 19,
+ 2,
(i) => {
'id': 'person-$i',
'email': '[email protected]',
@@ -120,18 +136,19 @@ void main() {
server.append(
'Keep changes on the device and sync when the connection returns.',
);
- debugPrint('Super Tab fixture: load conversation controller');
+ debugPrint('Swarm fixture: load conversation controller');
final c = await tester.runAsync(() async {
final controller = await f.app.superTabs
.open(tabId)
.timeout(const Duration(seconds: 10));
- debugPrint('Super Tab fixture: refresh conversation');
+ debugPrint('Swarm fixture: refresh conversation');
await controller.refresh().timeout(const Duration(seconds: 10));
+ controller.toggleProject('lead');
return controller;
});
expect(c, isNotNull);
debugPrint(
- 'Super Tab fixture: render first frame '
+ 'Swarm fixture: render first frame '
'(lifecycle=${binding.lifecycleState}, '
'framesEnabled=${binding.framesEnabled}, '
'visible=${await windowManager.isVisible()}, '
@@ -152,19 +169,20 @@ void main() {
app: f.app,
canvas: PaneGrid(notifier: f.app, swarmMode: true),
onAddAgent: (_) {},
+ onNewProject: () {},
),
),
),
),
),
);
- debugPrint('Super Tab fixture: first frame painted');
+ debugPrint('Swarm fixture: first frame painted');
await tester.pumpAndSettle(
const Duration(milliseconds: 100),
EnginePhase.sendSemanticsUpdate,
const Duration(seconds: 10),
);
- debugPrint('Super Tab fixture: conversation settled');
+ debugPrint('Swarm fixture: conversation settled');
expect(find.byTooltip('Invite people'), findsOneWidget);
expect(find.text('CHATS'), findsNothing);
expect(find.text('New group'), findsNothing);
@@ -183,17 +201,25 @@ void main() {
}
await shot('conversation');
+ await tester.tap(find.byTooltip('Project options'));
+ await tester.pumpAndSettle();
+ await shot('project-menu');
+ await tester.tap(find.text('Update cadence'));
+ await tester.pumpAndSettle();
+ await shot('project-cadence');
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
await tester.tap(
find.byKey(ValueKey('super-member-${c!.snapshot!.agents.single.id}')),
);
- debugPrint('Super Tab fixture: terminal requested');
+ debugPrint('Swarm fixture: terminal requested');
for (var i = 0; i < 30 && f.app.activeSwarm.panes.isEmpty; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
expect(f.app.activeSwarm.panes, hasLength(1));
final machine = f.app.machineStates['m']!;
debugPrint(
- 'Super Tab fixture: native prerequisites '
+ 'Swarm fixture: native prerequisites '
'online=${machine.nodeOnline} capability=${machine.terminalCapabilityAvailable} '
'agents=${machine.agents.map((a) => '${a.id}:${a.terminalAvailable}').join(',')} '
'session=${f.app.activeSwarm.panes.single.session?.status}',
@@ -214,7 +240,7 @@ void main() {
);
expect(f.app.activeSwarm.panes.single.inputContext, isNotNull);
await tester.pump(const Duration(milliseconds: 100));
- debugPrint('Super Tab fixture: terminal ready');
+ debugPrint('Swarm fixture: terminal ready');
await shot('terminal');
expect(find.byType(PaneGrid), findsOneWidget);
expect(
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 0c986eb6c..4abcde8a0 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -275,7 +275,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
bool _deviceRevealInFlight = false;
StreamSubscription<void>? _modelsRequests;
StreamSubscription<String>? _superTabClosures;
- // The one Super Tab notice: whether it exists (queued or shown), whether it
+ // The one Swarm notice: whether it exists (queued or shown), whether it
// is on screen, and the closed tab its Reopen restores.
int _superTabNoticeSerial = 0;
bool _superTabNoticeLive = false, _superTabNoticeShowing = false;
@@ -526,9 +526,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
: null,
// What to pick up, opened into this tab the way Cmd-P opens it: a harness
// as itself, a conversation Harness did not start as a harness resuming it.
- // Super Tab creation uses the same form as Cmd-N, without recent sessions.
+ // Swarm creation uses the same form as Cmd-N, without recent sessions.
app: app.activeSwarm.isSuperTab ? null : app,
- // The palette lists the same getter. A Super Tab draft has no recents but
+ // The palette lists the same getter. A Swarm draft has no recents but
// still offers these.
closedSuperTabs: app.closedSuperTabs,
onOpenSuperTab: _openClosedSuperTab,
@@ -2966,10 +2966,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
'type': 'tab.rename',
'name': name,
});
- if (result == null && mounted)
+ if (result == null && mounted) {
_showPaneActionHint(
- controller.operationError ?? 'Could not rename the Super Tab.',
+ controller.operationError ?? 'Could not rename the Swarm.',
);
+ }
} else {
app.renameSwarm(id, name);
}
@@ -2983,10 +2984,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
'type': 'tab.pause',
'paused': controller.snapshot?.paused != true,
});
- if (result == null && mounted)
+ if (result == null && mounted) {
_showPaneActionHint(
controller.operationError ?? 'Could not change new work.',
);
+ }
}
/// The tab a native action names, or the active one (File's rows).
@@ -3634,11 +3636,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? projectName,
String? task,
String? superTabConversationId,
+ bool newSwarmProject = false,
HarnessPlacement? placement,
_NewHarnessSource source = _NewHarnessSource.workspace,
bool Function()? stillCurrent,
}) async {
- if (_newHarnessEmbedded &&
+ if (!newSwarmProject &&
+ _newHarnessEmbedded &&
_newHarness != null &&
source == _NewHarnessSource.workspace &&
split == null &&
@@ -3660,7 +3664,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
final superTab = app.swarms
.where((s) => s.id == target && s.isSuperTab)
.firstOrNull;
- final conversation = superTabConversationId ??
+ final conversation =
+ superTabConversationId ??
(superTab?.superTabId == null
? 'lead'
: search != null && _superTabAddTarget?.swarmId == target
@@ -3744,7 +3749,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
requestedSplit == null &&
placement != HarnessPlacement.newTab) {
try {
- integration = await SuperTabLaunch.open(app, superTab, conversation);
+ integration = await SuperTabLaunch.open(
+ app,
+ superTab,
+ newSwarmProject ? 'new-project' : conversation,
+ newProject: newSwarmProject,
+ );
} catch (failure) {
_showPaneActionHint(failure.toString());
return;
@@ -4277,7 +4287,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.openClosedSuperTab(tabId, intoSwarmId: app.activeSwarmId);
}
- /// Closing a Super Tab asks nothing, so the way back is said right after.
+ /// Closing a Swarm asks nothing, so the way back is said right after.
/// A second close replaces this notice rather than queueing behind it.
void _offerSuperTabReopen(String historyId) {
if (!mounted) return;
@@ -6192,6 +6202,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
final groupTitle = superTabTarget == null
? null
: contribution?.snapshot?.conversation(superTabTarget.groupId)?.title;
+ final contributionProject = superTabTarget == null
+ ? null
+ : contribution?.snapshot?.projectFor(superTabTarget.groupId);
_search = SwarmSearchController(
app,
_navigation.recent,
@@ -6199,21 +6212,36 @@ class _SwarmScreenState extends State<SwarmScreen> {
? null
: HarnessPickerContext(
title: 'Add agent to ${groupTitle ?? 'conversation'}',
- description: 'Shared with everyone in ${app.activeSwarm.name}.',
+ description: contributionProject?.isPrivate == true
+ ? 'Shared with members of ${contributionProject!.name}.'
+ : 'Shared with everyone in ${app.activeSwarm.name}.',
action: 'Add agent',
unavailable: (row) {
- final shared = app.superTabs.peek(superTabTarget.tabId)?.snapshot;
- final agent = shared?.agents.where(
- (agent) => agent.machineId == row.machineId &&
- agent.harnessId == row.agentId,
- ).firstOrNull;
+ final shared = app.superTabs
+ .peek(superTabTarget.tabId)
+ ?.snapshot;
+ final agent = shared?.agents
+ .where(
+ (agent) =>
+ agent.machineId == row.machineId &&
+ agent.harnessId == row.agentId,
+ )
+ .firstOrNull;
if (agent != null) {
- return shared!.conversation(superTabTarget.groupId)
- ?.agentIds.contains(agent.id) == true
+ if (agent.projectId != contributionProject?.id) {
+ return 'This agent belongs to another project. Create a new agent here.';
+ }
+ return shared!
+ .conversation(superTabTarget.groupId)
+ ?.agentIds
+ .contains(agent.id) ==
+ true
? 'Already in this conversation.'
: null;
}
- final native = app.stateOf(row.machineId ?? '')?.agents
+ final native = app
+ .stateOf(row.machineId ?? '')
+ ?.agents
.where((agent) => agent.id == row.agentId)
.firstOrNull;
return native != null &&
@@ -6275,13 +6303,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (contribution != null && superTabTarget != null) {
void guardContribution() {
if (!mounted || !identical(_search, deviceSearch)) return;
- final group = contribution.snapshot?.conversation(superTabTarget.groupId);
+ final group = contribution.snapshot?.conversation(
+ superTabTarget.groupId,
+ );
if (!contribution.canWrite || group == null || group.archived) {
_closeSearch();
} else {
deviceSearch.refreshAvailability();
}
}
+
contribution.addListener(guardContribution);
_stopSuperTabPickerWatch = () =>
contribution.removeListener(guardContribution);
@@ -6937,7 +6968,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (superTabTarget != null) {
final controller = app.superTabs.peek(superTabTarget.tabId);
final group = controller?.snapshot?.conversation(superTabTarget.groupId);
- if (controller?.canWrite != true || group == null || group.archived) return;
+ if (controller?.canWrite != true || group == null || group.archived) {
+ return;
+ }
}
_openSearch(
adding: true,
@@ -7788,13 +7821,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
shortcut: _keymap.hint(command.id),
searchFields: [command.id, ...command.keywords],
),
- // Where New Super Tab lives: the tabs closed here, back by name.
+ // Where New Swarm lives: the tabs closed here, back by name.
if (_canExecuteCommand('super_tab.new'))
for (final tab in app.closedSuperTabs)
SwarmDestination(
id: 'command:$_closedSuperTabCommand${tab.id}',
title: tab.name,
- detail: 'Closed Super Tabs',
+ detail: 'Closed Swarms',
swarmId: null,
current: false,
commandId: '$_closedSuperTabCommand${tab.id}',
@@ -8035,7 +8068,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
!_creatureEnabled) ||
app.activeSwarm.isOrchestrator,
child: Padding(
- padding: app.panes.isEmpty || app.activeSwarm.isSuperTab
+ padding:
+ app.panes.isEmpty ||
+ app.activeSwarm.isSuperTab
? EdgeInsets.zero
: const EdgeInsets.fromLTRB(
kWorkspaceInset,
@@ -8045,6 +8080,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
child: SuperTabWorkspace(
app: app,
+ onNewProject: () => unawaited(
+ _newAgent(newSwarmProject: true),
+ ),
onAddAgent: (group) => unawaited(
_addAgent(conversationId: group.id),
),
@@ -9177,7 +9215,7 @@ class _SuperTabClosedTextState extends State<_SuperTabClosedText> {
@override
Widget build(BuildContext context) =>
- const Text('Super Tab closed. Its agents keep running.');
+ const Text('Swarm closed. Its agents keep running.');
}
/// What covers the workspace, as the titlebar sees it
diff --git a/desktop/lib/settings/sections/routing_section.dart b/desktop/lib/settings/sections/routing_section.dart
index e1c4bd370..8f3762dab 100644
--- a/desktop/lib/settings/sections/routing_section.dart
+++ b/desktop/lib/settings/sections/routing_section.dart
@@ -7,8 +7,8 @@ import '../../state/app_state.dart';
import '../../super_tabs/routing_policy.dart';
import '../../super_tabs/routing_policy_form.dart';
-/// Settings ▸ Routing: the account's routing default for every Super Tab it
-/// owns. A Super Tab can override single fields from its own Routing dialog.
+/// Settings ▸ Routing: the account's routing default for every Swarm it
+/// owns. A Swarm can override single fields from its own Routing dialog.
class RoutingSection extends StatefulWidget {
const RoutingSection({super.key, required this.notifier});
final AppNotifier notifier;
@@ -83,7 +83,7 @@ class _RoutingSectionState extends State<RoutingSection> {
final theme = Theme.of(context);
return SectionScaffold(
title: 'Routing',
- subtitle: 'How a Super Tab Lead chooses who does each task. Each Super Tab you own can override these.',
+ subtitle: 'How a Swarm Lead chooses who does each task. Each Swarm you own can override these.',
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
diff --git a/desktop/lib/settings/sections/tab_invites_section.dart b/desktop/lib/settings/sections/tab_invites_section.dart
index 40afd40dc..d03bc4b4a 100644
--- a/desktop/lib/settings/sections/tab_invites_section.dart
+++ b/desktop/lib/settings/sections/tab_invites_section.dart
@@ -127,7 +127,7 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
if (_loadingSuper) const LinearProgressIndicator(),
if (_superError != null)
SettingRow(
- title: 'Could not load Super Tabs',
+ title: 'Could not load Swarms',
detail: _superError,
control: TextButton(
onPressed: _refreshSuper,
@@ -138,7 +138,7 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
SettingRow(
title: invite['name'] as String,
detail:
- 'Super Tab · ${invite['role'] == 'viewer' ? 'Can view' : 'Can collaborate'}',
+ 'Swarm · ${invite['role'] == 'viewer' ? 'Can view' : 'Can collaborate'}',
control: FilledButton(
onPressed: _accepting == null
? () => _acceptSuper(invite)
@@ -151,7 +151,7 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
for (final tab in _superTabs)
SettingRow(
title: tab['name'] as String,
- detail: 'Super Tab',
+ detail: 'Swarm',
control: TextButton(
onPressed: () {
widget.notifier.openSuperTab(
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
index 8d318acca..c7fcc24a3 100644
--- a/desktop/lib/shared/theme/app_icons.dart
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -76,6 +76,7 @@ abstract final class AppIcons {
static const dot = LucideIcons.dot400;
static const download = LucideIcons.download400;
static const ellipsis = LucideIcons.ellipsis400;
+ static const ellipsisVertical = LucideIcons.ellipsisVertical400;
static const externalLink = LucideIcons.externalLink400;
static const eye = LucideIcons.eye400;
static const eyeOff = LucideIcons.eyeOff400;
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index a7e67d2e1..5c5dbf26d 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -5,7 +5,7 @@ import 'package:flutter/widgets.dart';
import '../logging/debug_surface.dart';
/// Harness uses Command as a direct prefix for frequent workspace actions.
-/// T opens a tab, N creates a harness. S opens Store, M machines, I models,
+/// T opens a tab, N creates a harness. S creates a Swarm, M machines, I models,
/// O projects, P harnesses, and Shift-P commands.
/// Shift-L chooses a layout. H/J/K/L and arrows focus panes; B routes a task.
/// The same definitions feed live keys, help and search.
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 25f0914a5..f6d6687cf 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -618,7 +618,7 @@ final harnessCommands = <HarnessCommand>[
'app.store',
'Harness Store',
ShortcutGroup.actions,
- extraKeys: ['cmd+s'],
+ extraKeys: ['cmd+ctrl+s'],
keywords: ['install', 'browse harnesses', 'packages', 'extensions'],
nativeAction: 'store',
),
@@ -691,9 +691,9 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'super_tab.new',
- 'New Super Tab',
+ 'New Swarm',
ShortcutGroup.actions,
- extraKeys: ['cmd+alt+shift+t'],
+ extraKeys: ['cmd+s'],
hidden: true,
),
if (kDebugSurfaceEnabled)
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 232d0be05..67b2fa88d 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1672,7 +1672,9 @@ class AppNotifier extends ChangeNotifier {
final namesChanged = !mapEquals(names, _superTabNames);
_superTabNames = names;
for (final tab in tabs) {
- final existing = swarms.where((s) => s.superTabId == tab.id).firstOrNull;
+ final existing = swarms
+ .where((s) => s.superTabId == tab.id)
+ .firstOrNull;
if (existing != null) {
if (existing.name != tab.name || !existing.nameIsCustom) {
existing.name = tab.name;
@@ -1713,7 +1715,7 @@ class AppNotifier extends ChangeNotifier {
if (target == null) {
throw const SuperTabFailure(
'MACHINE_UNAVAILABLE',
- 'Connect one of your machines to open Super Tab.',
+ 'Connect one of your machines to open Swarm.',
);
}
final result = await superTabMachineRequest(target.machine.machineId, {
@@ -1730,11 +1732,11 @@ class AppNotifier extends ChangeNotifier {
final StreamController<String> _superTabClosures =
StreamController<String>.broadcast();
- /// Closing a Super Tab only hides it here, which looks like losing it. Each
+ /// Closing a Swarm only hides it here, which looks like losing it. Each
/// closure announces its history id so the screen can offer to reopen it.
Stream<String> get superTabClosures => _superTabClosures.stream;
- /// Super Tabs hidden on this computer that the account still belongs to,
+ /// Swarms hidden on this computer that the account still belongs to,
/// by name. Saved with the hidden set, so a restart keeps them.
List<({String id, String name})> get closedSuperTabs {
final open = {for (final s in swarms) s.superTabId};
@@ -1744,7 +1746,7 @@ class AppNotifier extends ChangeNotifier {
(
id: id,
name: _superTabNames[id]!.trim().isEmpty
- ? 'Super Tab'
+ ? 'Swarm'
: _superTabNames[id]!,
),
]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
@@ -1766,7 +1768,7 @@ class AppNotifier extends ChangeNotifier {
if (result['error'] != null) {
throw SuperTabFailure(
result['error'].toString(),
- result['detail'] as String? ?? 'Could not reach this Super Tab.',
+ result['detail'] as String? ?? 'Could not reach this Swarm.',
statusCode: (result['status'] as num?)?.toInt() ?? 0,
);
}
@@ -1785,9 +1787,10 @@ class AppNotifier extends ChangeNotifier {
if (swarm == null) return;
// A discovery response can beat the creation response back to this
// computer. Keep the lead form's tab and retain any already-open panes.
- for (final duplicate in swarms
- .where((s) => s.id != swarmId && s.superTabId == tabId)
- .toList()) {
+ for (final duplicate
+ in swarms
+ .where((s) => s.id != swarmId && s.superTabId == tabId)
+ .toList()) {
for (final pane in duplicate.panes) {
if (!swarm.panes.contains(pane)) swarm.panes.add(pane);
}
@@ -1806,7 +1809,7 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
- /// The one way to show a Super Tab: focus its view if it is open, else give
+ /// The one way to show a Swarm: focus its view if it is open, else give
/// it one. An untouched New Tab page named by [intoSwarmId] becomes the view
/// instead of being left behind. Any history entry for the tab is dropped, so
/// Reopen later cannot add a second view.
@@ -1848,9 +1851,11 @@ class AppNotifier extends ChangeNotifier {
void _rememberSuperTabVisibility(String tabId, bool visible) {
if (localStore == null) return;
- unawaited(superTabs.setTabVisible(tabId, visible).catchError((Object error) {
- appLog.warn('super-tab', 'Could not save tab visibility: $error');
- }));
+ unawaited(
+ superTabs.setTabVisible(tabId, visible).catchError((Object error) {
+ appLog.warn('super-tab', 'Could not save tab visibility: $error');
+ }),
+ );
}
void markSuperTabDraft(String swarmId) {
@@ -3183,7 +3188,7 @@ class AppNotifier extends ChangeNotifier {
}
}
- /// Close removes these views. Super Tabs own work independently of their
+ /// Close removes these views. Swarms own work independently of their
/// views; ordinary tabs stop a session only when its last view closes.
Future<void> requestCloseSwarm(String id) {
final tab = swarms.where((s) => s.id == id).firstOrNull;
@@ -3237,9 +3242,9 @@ class AppNotifier extends ChangeNotifier {
if (_disposed) return Future.value();
if (_viewCloseRequests[key] case final pending?) return pending;
bool canStop(String machineId, String agentId) {
- // A Super Tab pane is only a view into shared work. This guard also covers
+ // A Swarm pane is only a view into shared work. This guard also covers
// the close shortcut, native menu and whole-tab dismissal, including a
- // regular tab becoming a Super Tab while a close review is pending.
+ // regular tab becoming a Swarm while a close review is pending.
if (tab.isSuperTab) return false;
if (!swarms.contains(tab) ||
(wholeTab &&
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
index d63ecd307..cc8d21835 100644
--- a/desktop/lib/state/harness_launch_integration.dart
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -14,8 +14,12 @@ class HarnessLaunchIntegration {
this.resolveAttachments,
this.resume,
this.actionLabel = 'New Harness',
+ this.projectVisibility,
+ this.projectVisibilityLocked = false,
});
final String creationId, actionLabel;
+ String? projectVisibility;
+ bool projectVisibilityLocked;
final Future<String> Function(String machineId, String task) prepare;
final Future<void> Function(String machineId, String harnessId) complete;
final Future<void> Function(String machineId, String creationId) beforeSubmit;
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 300912eaf..30f7538ae 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -57,9 +57,7 @@ class SuperTabClient {
_visibility.clear();
discoveryError = null;
for (final controller in _loaded.values) {
- controller.revokeAccess(
- 'The account changed. Open this Super Tab again.',
- );
+ controller.revokeAccess('The account changed. Open this Swarm again.');
}
for (final future in _controllers.values) {
unawaited(
@@ -187,14 +185,14 @@ class SuperTabClient {
Map<String, dynamic>? body,
}) async {
if (_account == null) {
- throw const SuperTabFailure('SIGNED_OUT', 'Sign in to use Super Tab.');
+ throw const SuperTabFailure('SIGNED_OUT', 'Sign in to use Swarm.');
}
final generation = _generation;
final result = await transport(method, path, body: body);
if (generation != _generation) {
throw const SuperTabFailure(
'ACCOUNT_CHANGED',
- 'The account changed. Open this Super Tab again.',
+ 'The account changed. Open this Swarm again.',
);
}
return result;
@@ -219,7 +217,7 @@ class SuperTabClient {
final account = _account;
final generation = _generation;
if (account == null) {
- throw const SuperTabFailure('SIGNED_OUT', 'Sign in to use Super Tab.');
+ throw const SuperTabFailure('SIGNED_OUT', 'Sign in to use Swarm.');
}
final key = 'super_tab.$account.$id';
final raw = await storage.read(key);
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 6d3008876..0590ffd65 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -39,6 +39,9 @@ class SuperTabController extends ChangeNotifier {
this.pollInterval = const Duration(seconds: 3),
}) {
if (initial['tabId'] == tabId && initial['accountId'] == accountId) {
+ expandedProjects.addAll(
+ (initial['expandedProjects'] as List? ?? const []).whereType<String>(),
+ );
selectedId = initial['selectedId'] as String? ?? 'lead';
final drafts = initial['drafts'];
if (drafts is Map) {
@@ -107,6 +110,13 @@ class SuperTabController extends ChangeNotifier {
final _messages = <String, List<SuperTabMessage>>{};
final _before = <String, int?>{};
final _reading = <String>{};
+ final expandedProjects = <String>{};
+
+ void toggleProject(String id) {
+ if (!expandedProjects.remove(id)) expandedProjects.add(id);
+ _saveSoon();
+ _changed();
+ }
String get _path => '/api/super-tabs/${Uri.encodeComponent(tabId)}';
SuperTabConversation? get selected => snapshot?.conversation(selectedId);
@@ -164,8 +174,11 @@ class SuperTabController extends ChangeNotifier {
_changed();
}
- List<SuperTabMessage> messages(String id) =>
- List.unmodifiable(_messages[id] ?? const []);
+ List<SuperTabMessage> messages(String id) => List.unmodifiable(
+ (_messages[id] ?? const <SuperTabMessage>[]).where(
+ (m) => m.source['kind'] != 'update-request',
+ ),
+ );
bool hasOlder(String id) => _before[id] != null;
bool unread(SuperTabConversation group) =>
group.lastMessageSequence > (_readAt[group.id] ?? 0);
@@ -199,6 +212,7 @@ class SuperTabController extends ChangeNotifier {
'tabId': tabId,
'accountId': accountId,
'selectedId': selectedId,
+ 'expandedProjects': expandedProjects.toList(),
'drafts': Map<String, String>.of(_drafts),
'terminals': Map<String, String>.of(_terminals),
@@ -256,6 +270,9 @@ class SuperTabController extends ChangeNotifier {
void select(String id) {
if (snapshot?.conversation(id) == null || id == selectedId) return;
+ if (!snapshot!.isProjectLead(id)) {
+ expandedProjects.add(snapshot!.conversation(id)!.projectId);
+ }
selectedId = id;
_saveSoon();
_changed();
@@ -287,13 +304,37 @@ class SuperTabController extends ChangeNotifier {
final nextRevision = (answer['revision'] as num).toInt();
final next = SuperTabSnapshot.fromJson(superTabMap(answer['state']));
if (next.id != tabId) {
- throw const FormatException('A different Super Tab was returned.');
+ throw const FormatException('A different Swarm was returned.');
}
if (nextRevision >= revision) {
snapshot = next;
- if (next.conversation(selectedId) == null) selectedId = 'lead';
+ final allowed = next.conversations.map((c) => c.id).toSet();
+ final localAccessChanged =
+ !allowed.contains(selectedId) ||
+ [
+ ..._drafts.keys,
+ ..._terminals.keys,
+ ..._mentions.keys,
+ ..._readAt.keys,
+ ].any((id) => !allowed.contains(id)) ||
+ expandedProjects.any(
+ (id) => !next.projects.any((project) => project.id == id),
+ );
+ _messages.removeWhere((id, _) => !allowed.contains(id));
+ _drafts.removeWhere((id, _) => !allowed.contains(id));
+ _terminals.removeWhere((id, _) => !allowed.contains(id));
+ _mentions.removeWhere((id, _) => !allowed.contains(id));
+ _before.removeWhere((id, _) => !allowed.contains(id));
+ _readAt.removeWhere((id, _) => !allowed.contains(id));
+ expandedProjects.removeWhere(
+ (id) => !next.projects.any((project) => project.id == id),
+ );
+ if (!allowed.contains(selectedId)) {
+ selectedId = next.projects.firstOrNull?.leadConversationId ?? 'lead';
+ }
revision = nextRevision;
error = null;
+ if (localAccessChanged) _saveSoon();
}
await loadMessages(selectedId);
} catch (failure) {
@@ -304,12 +345,13 @@ class SuperTabController extends ChangeNotifier {
}
}
- void _readFailure(Object failure) {
+ void _readFailure(Object failure, {bool revokeTab = true}) {
if (_disposed) return;
error = failure is SuperTabFailure
? failure.message
: 'Could not refresh this conversation. Try again.';
- if (failure is SuperTabFailure &&
+ if (revokeTab &&
+ failure is SuperTabFailure &&
const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
accessRevoked = true;
snapshot = null;
@@ -351,7 +393,9 @@ class SuperTabController extends ChangeNotifier {
'$_path/conversations/${Uri.encodeComponent(id)}/messages?before=${tail + 1}',
);
}
- if (_disposed || accessRevoked) return;
+ if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
+ return;
+ }
final incoming = (answer['messages'] as List)
.map((m) => SuperTabMessage.fromJson(superTabMap(m)))
.toList();
@@ -369,7 +413,12 @@ class SuperTabController extends ChangeNotifier {
}
_changed();
} catch (failure) {
- _readFailure(failure);
+ _readFailure(failure, revokeTab: false);
+ if (failure is SuperTabFailure &&
+ const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
+ _messages.remove(id);
+ unawaited(refresh());
+ }
_changed();
} finally {
_reading.remove(id);
diff --git a/desktop/lib/super_tabs/dialog_scope.dart b/desktop/lib/super_tabs/dialog_scope.dart
index f7de67f2b..daf6bd9ab 100644
--- a/desktop/lib/super_tabs/dialog_scope.dart
+++ b/desktop/lib/super_tabs/dialog_scope.dart
@@ -10,11 +10,14 @@ class SuperTabDialogScope extends StatelessWidget {
required this.controller,
required this.child,
this.requireWrite = true,
+ this.projectId,
+ this.conversationId,
});
final SuperTabController controller;
final Widget child;
final bool requireWrite;
+ final String? projectId, conversationId;
@override
Widget build(BuildContext context) => ListenableBuilder(
@@ -22,6 +25,10 @@ class SuperTabDialogScope extends StatelessWidget {
builder: (context, _) {
if (!controller.accessRevoked &&
controller.snapshot != null &&
+ (projectId == null ||
+ controller.snapshot!.projects.any((p) => p.id == projectId)) &&
+ (conversationId == null ||
+ controller.snapshot!.conversation(conversationId!) != null) &&
(!requireWrite || controller.canWrite)) {
// The shared backdrop owns a fallback focus node for Escape. A form
// gets its own scope so its initial editor wins that fallback.
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
index 8dfa279c9..d640290e0 100644
--- a/desktop/lib/super_tabs/launch.dart
+++ b/desktop/lib/super_tabs/launch.dart
@@ -25,14 +25,12 @@ class SuperTabLaunch {
static Future<HarnessLaunchIntegration> open(
AppNotifier app,
Swarm tab,
- String conversationId,
- ) async {
+ String conversationId, {
+ bool newProject = false,
+ }) async {
final account = app.currentUser?.id;
if (account == null) {
- throw const SuperTabFailure(
- 'SIGNED_OUT',
- 'Sign in to create a Super Tab.',
- );
+ throw const SuperTabFailure('SIGNED_OUT', 'Sign in to create a Swarm.');
}
final key = 'super_tab.launch.$account.${tab.id}.$conversationId';
final raw = await app.superTabs.storage.read(key);
@@ -45,7 +43,11 @@ class SuperTabLaunch {
'joinId': superTabOperationId(),
'tabId': tab.superTabId,
'conversationId': conversationId,
- 'lead': tab.superTabId == null,
+ 'lead': tab.superTabId == null || newProject,
+ 'newSwarm': tab.superTabId == null,
+ 'newProject': newProject,
+ 'visibility': 'public',
+ if (!newProject) 'projectId': 'lead',
}
: superTabMap(jsonDecode(raw));
final launch = SuperTabLaunch._(app, tab.id, account, key, saved);
@@ -54,8 +56,29 @@ class SuperTabLaunch {
late final HarnessLaunchIntegration integration;
integration = HarnessLaunchIntegration(
creationId: saved['creationId'] as String? ?? superTabOperationId(),
- actionLabel: saved['lead'] == true ? 'New Super Tab' : 'New Harness',
- prepare: launch.prepare,
+ actionLabel: saved['newProject'] == true
+ ? 'New project'
+ : saved['lead'] == true
+ ? 'New Swarm'
+ : 'New Harness',
+ projectVisibility: saved['lead'] == true
+ ? saved['visibility'] as String? ?? 'public'
+ : null,
+ projectVisibilityLocked:
+ saved['projectPrepared'] == true || saved['creationRequest'] != null,
+ prepare: (machine, task) async {
+ if (saved['projectPrepared'] != true &&
+ saved['creationRequest'] == null) {
+ saved['visibility'] = integration.projectVisibility ?? 'public';
+ }
+ try {
+ return await launch.prepare(machine, task);
+ } finally {
+ integration.projectVisibilityLocked =
+ saved['projectPrepared'] == true ||
+ saved['creationRequest'] != null;
+ }
+ },
beforeSubmit: (machine, receipt) async {
saved['machineId'] = machine;
saved['creationId'] = receipt;
@@ -105,24 +128,59 @@ class SuperTabLaunch {
Future<String> prepare(String machine, String task) async {
checkAccount();
+ if (app.stateOf(machine)?.belongsToOtherAccount == true) {
+ throw const SuperTabFailure(
+ 'CONTRIBUTION_REQUIRED',
+ 'Choose one of your machines. To use another person’s machine in this Swarm, ask its owner to add the machine or an agent.',
+ );
+ }
saved['initialMessage'] = task;
saved['machineId'] = machine;
await persist();
if (saved['tabId'] == null) {
+ saved['creationRequest'] ??= {
+ 'operationId': saved['operationId'],
+ 'name': 'Swarm',
+ 'projectVisibility': saved['visibility'] ?? 'public',
+ };
+ await persist();
final created = await app.superTabs.map(
'POST',
'/api/super-tabs',
- body: {'operationId': saved['operationId'], 'name': 'Super Tab'},
+ body: superTabMap(saved['creationRequest']),
);
saved['tabId'] = created['id'];
+ saved['projectPrepared'] = true;
app.superTabs.deferTabDiscovery(saved['tabId'] as String);
await persist();
}
+ if (saved['newProject'] == true && saved['projectPrepared'] != true) {
+ saved['creationRequest'] ??= {
+ 'operationId': saved['operationId'],
+ 'command': {
+ 'type': 'project.create',
+ 'name': 'New project',
+ 'visibility': saved['visibility'] ?? 'public',
+ 'brief': String.fromCharCodes(task.runes.take(4000)),
+ },
+ };
+ await persist();
+ final created = await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/${saved['tabId']}/commands',
+ body: superTabMap(saved['creationRequest']),
+ );
+ final result = superTabMap(created['result']);
+ saved['projectId'] = result['projectId'];
+ saved['conversationId'] = result['conversationId'];
+ saved['projectPrepared'] = true;
+ await persist();
+ }
app.superTabs.deferTabDiscovery(saved['tabId'] as String);
final command = 'harness super-tab --tab ${saved['tabId']}';
final prompt =
- 'You are an agent in a shared Harness Super Tab. '
- '${saved['lead'] == true ? 'You are its coordinating lead. Start by discussing the person’s request; build after they authorize it.' : 'Join the conversation before beginning the person’s request.'}\n'
+ 'You are an agent in a Harness Swarm. '
+ '${saved['lead'] == true ? 'You are this project’s coordinating lead. Start by discussing the person’s request; build after they authorize it.' : 'Join the conversation before beginning the person’s request.'}\n'
'First run `$command status`. Registration may still be finishing: if it reports AGENT_UNAVAILABLE, wait briefly and retry. '
'Do not start work or post until it confirms your participation.\n'
'Read the conversation: `$command messages ${saved['conversationId']}`. '
@@ -139,6 +197,7 @@ class SuperTabLaunch {
'Do not describe your own tools or permission prompts unless that blocks what they asked. '
'Answer each message once: post with --reply-to MESSAGE_ID. If you have already answered a message, do not post again. '
'When you hand over finished work, give the result with the revision and links they need.\n\n'
+ '${saved['lead'] == true ? 'Keep people informed in your project Lead conversation ${saved['conversationId']}: explain your plan, substantive progress, blockers and next steps. Consolidate new workgroup reports about every five minutes while active; the project setting controls scheduled requests. Answer human questions, serious blockers and completion immediately. A scheduled update request tells you which reports are new; read them and use project.report to post one useful update, or acknowledge with text:null when nothing merits repeating. Do not run an extra summarizer over every terminal turn. Workgroups you create belong to your project; each project has separate agent sessions. ' : ''}'
'The person’s request:\n${task.isEmpty ? 'Ask what they would like to work on.' : task}';
saved['launchPrompt'] = prompt;
await persist();
@@ -218,7 +277,7 @@ class SuperTabLaunch {
final name = Swarm.titleFor(native);
final title =
saved['title'] as String? ??
- (name == Swarm.defaultName ? 'Super Tab' : name);
+ (name == Swarm.defaultName ? 'New project' : name);
saved['title'] = title;
await persist();
await app.superTabs.map(
@@ -226,10 +285,27 @@ class SuperTabLaunch {
'/api/super-tabs/$tabId/commands',
body: {
'operationId': '${saved['joinId']}-name',
- 'command': {'type': 'tab.rename', 'name': title},
+ 'command': {
+ 'type': 'project.rename',
+ 'projectId': saved['projectId'] ?? 'lead',
+ 'name': title,
+ },
},
);
checkAccount();
+ if (saved['newProject'] != true) {
+ await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/$tabId/commands',
+ body: {
+ 'operationId': '${saved['joinId']}-swarm-name',
+ 'command': {
+ 'type': 'tab.rename',
+ 'name': saved['visibility'] == 'private' ? 'Swarm' : title,
+ },
+ },
+ );
+ }
}
final controller = await app.superTabs.open(tabId);
await controller.refresh();
@@ -262,9 +338,14 @@ class SuperTabLaunch {
saved.remove('files');
await persist();
}
- if (saved['lead'] == true) {
- app.bindSuperTab(swarmId, tabId, saved['title'] as String);
+ if (saved['lead'] == true && saved['newProject'] != true) {
+ app.bindSuperTab(
+ swarmId,
+ tabId,
+ saved['visibility'] == 'private' ? 'Swarm' : saved['title'] as String,
+ );
}
+ controller.select(saved['conversationId'] as String);
await app.superTabs.storage.delete(key);
}
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 2afe84208..d92d3cdfb 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -200,39 +200,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
error = null;
});
try {
- // Older tabs can record the project already chosen for their lead.
- // No folder is inferred across machines from a matching path.
- if (c.snapshot?.project == null) {
- final lead = c.snapshot?.agents
- .where((a) => c.snapshot!.isLead(a.id))
- .firstOrNull;
- final host = lead == null
- ? null
- : app.stateOf(lead.machineId);
- final native = host?.agents
- .where((a) => a.id == lead?.harnessId)
- .firstOrNull;
- final project = native == null
- ? null
- : host?.projectOf(native);
- if (project != null && c.isOwner) {
- final recorded = await c.command({
- 'type': 'tab.project',
- 'machineId': lead!.machineId,
- 'project': {
- 'cwd': project.root ?? project.cwd,
- 'repositoryUrl': superTabRepositoryUrl(project.remote),
- },
- });
- if (recorded == null) {
- throw SuperTabFailure(
- 'PROJECT_UNAVAILABLE',
- c.operationError ??
- 'Could not read the lead’s project.',
- );
- }
- }
- }
setupId ??= superTabOperationId();
final deadline = DateTime.now().add(const Duration(minutes: 5));
Map<String, dynamic> prepared;
@@ -241,9 +208,13 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
prepared = await app.superTabMachineRequest(selected, {
'action': 'prepareContribution',
'tabId': c.tabId,
+ 'scope': 'swarm',
'operationId': setupId,
});
- if (prepared['state'] == 'ready') break;
+ if (prepared['state'] == 'ready' &&
+ prepared['scope'] == 'swarm') {
+ break;
+ }
if (prepared['state'] != 'preparing') {
throw const SuperTabFailure(
'UPDATE_REQUIRED',
@@ -267,6 +238,8 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
'machineId': selected,
'name': machine!.machine.displayName,
'cwd': prepared['cwd'],
+ if (prepared['scope'] != null)
+ 'scope': prepared['scope'],
'engines': prepared['engines'],
'maxAgents': prepared['maxAgents'],
});
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 5e6b0e568..4e6a35276 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -94,7 +94,7 @@ class SuperTabMessageRow extends StatefulWidget {
}
class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
- final _focus = FocusNode(debugLabel: 'Super Tab message actions');
+ final _focus = FocusNode(debugLabel: 'Swarm message actions');
bool _hovered = false, _focused = false;
@override
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 7c893826d..63e4111b3 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -1,16 +1,16 @@
/// Backend records are independent of the desktop's visible panes and tab layout.
Map<String, dynamic> superTabMap(Object? value) => value is Map
? Map<String, dynamic>.from(value)
- : throw const FormatException('Invalid Super Tab response.');
+ : throw const FormatException('Invalid Swarm response.');
String _text(Map<String, dynamic> value, String key) => value[key] is String
? value[key] as String
- : throw FormatException('Missing Super Tab $key.');
+ : throw FormatException('Missing Swarm $key.');
List<T> _list<T>(Object? value, T Function(Map<String, dynamic>) read) =>
value is List
? List.unmodifiable(value.map((row) => read(superTabMap(row))))
- : throw const FormatException('Invalid Super Tab list.');
+ : throw const FormatException('Invalid Swarm list.');
class SuperTabPerson {
SuperTabPerson.fromJson(Map<String, dynamic> row)
@@ -24,12 +24,13 @@ class SuperTabPerson {
class SuperTabAgent {
SuperTabAgent.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
+ projectId = row['projectId'] as String? ?? 'lead',
name = _text(row, 'name'),
machineId = _text(row, 'machineId'),
harnessId = _text(row, 'harnessId'),
contributorId = _text(row, 'contributorId'),
configuration = Map.unmodifiable(superTabMap(row['configuration']));
- final String id, name, machineId, harnessId, contributorId;
+ final String id, projectId, name, machineId, harnessId, contributorId;
final Map<String, dynamic> configuration;
String get engine => configuration['engine'] as String? ?? '';
}
@@ -37,6 +38,7 @@ class SuperTabAgent {
class SuperTabConversation {
SuperTabConversation.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
+ projectId = row['projectId'] as String? ?? 'lead',
number = (row['number'] as num?)?.toInt(),
title = _text(row, 'title'),
leadId = row['leadId'] as String?,
@@ -51,7 +53,7 @@ class SuperTabConversation {
assignment = row['assignment'] == null
? null
: Map.unmodifiable(superTabMap(row['assignment']));
- final String id, title, brief;
+ final String id, projectId, title, brief;
final int? number;
String get label => number == null ? title : '#$number $title';
final String? leadId;
@@ -62,6 +64,28 @@ class SuperTabConversation {
final Map<String, dynamic>? assignment;
}
+class SuperTabProject {
+ SuperTabProject.fromJson(Map<String, dynamic> row)
+ : id = _text(row, 'id'),
+ name = _text(row, 'name'),
+ ownerId = _text(row, 'ownerId'),
+ leadConversationId = _text(row, 'leadConversationId'),
+ isPrivate = row['visibility'] == 'private',
+ memberIds = [
+ for (final member in row['members'] as List? ?? const [])
+ superTabMap(member)['id'] as String,
+ ],
+ updateMinutes = (row['updateMinutes'] as num?)?.toInt() ?? 5,
+ repository = row['repository'] is Map
+ ? Map.unmodifiable(superTabMap(row['repository']))
+ : null;
+ final String id, name, ownerId, leadConversationId;
+ final bool isPrivate;
+ final List<String> memberIds;
+ final int updateMinutes;
+ final Map<String, dynamic>? repository;
+}
+
class SuperTabSnapshot {
SuperTabSnapshot.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
@@ -86,8 +110,24 @@ class SuperTabSnapshot {
(row) => Map<String, dynamic>.unmodifiable(row),
) {
if (row['version'] != 1) {
- throw const FormatException('Update Harness to open this Super Tab.');
+ throw const FormatException('Update Harness to open this Swarm.');
}
+ projects = _list(
+ row['projects'] ??
+ [
+ {
+ 'id': 'lead',
+ 'name': name,
+ 'ownerId': ownerId,
+ 'leadConversationId': 'lead',
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ if (project != null) 'repository': project,
+ },
+ ],
+ SuperTabProject.fromJson,
+ );
}
final String id, name, ownerId;
final Map<String, dynamic>? project;
@@ -96,13 +136,24 @@ class SuperTabSnapshot {
final List<SuperTabAgent> agents;
final List<Map<String, dynamic>> machines;
final List<SuperTabConversation> conversations;
+ late final List<SuperTabProject> projects;
final List<Map<String, dynamic>> invitations;
SuperTabConversation? conversation(String id) =>
conversations.where((c) => c.id == id).firstOrNull;
SuperTabAgent? agent(String id) =>
agents.where((a) => a.id == id).firstOrNull;
- bool isLead(String agentId) => conversation('lead')?.leadId == agentId;
+ SuperTabProject? projectFor(String conversationId) {
+ final group = conversation(conversationId);
+ return projects.where((p) => p.id == group?.projectId).firstOrNull;
+ }
+
+ bool isProjectLead(String conversationId) =>
+ projects.any((p) => p.leadConversationId == conversationId);
+
+ bool isLead(String agentId) => projects.any(
+ (p) => conversation(p.leadConversationId)?.leadId == agentId,
+ );
String agentName(String id, {String fallback = 'Agent'}) =>
isLead(id) ? 'Lead' : agent(id)?.name ?? fallback;
diff --git a/desktop/lib/super_tabs/pane.dart b/desktop/lib/super_tabs/pane.dart
index d5fd2eeaf..46041b639 100644
--- a/desktop/lib/super_tabs/pane.dart
+++ b/desktop/lib/super_tabs/pane.dart
@@ -1,6 +1,6 @@
import 'package:flutter/widgets.dart';
-/// A Super Tab's view of an existing terminal. The renderer and session stay
+/// A Swarm's view of an existing terminal. The renderer and session stay
/// shared with ordinary panes; presentation belongs to this placement only.
/// Group membership owns the visible panes; individual panes cannot be closed.
class SuperPane extends InheritedWidget {
diff --git a/desktop/lib/super_tabs/project_options.dart b/desktop/lib/super_tabs/project_options.dart
new file mode 100644
index 000000000..3d3d538d8
--- /dev/null
+++ b/desktop/lib/super_tabs/project_options.dart
@@ -0,0 +1,212 @@
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'dialog_scope.dart';
+import 'model.dart';
+import 'project_visibility.dart';
+
+Future<void> showProjectAction(
+ BuildContext context,
+ SuperTabController c,
+ SuperTabProject project,
+ String action,
+) async {
+ var name = project.name;
+ var visibility = project.isPrivate ? 'private' : 'public';
+ final members = project.memberIds.toSet();
+ var minutes = project.updateMinutes;
+ var busy = false;
+ await showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ projectId: project.id,
+ requireWrite: action != 'details',
+ child: StatefulBuilder(
+ builder: (context, update) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ final current = c.snapshot?.projects
+ .where((p) => p.id == project.id)
+ .firstOrNull;
+ final group = c.snapshot?.conversation(project.leadConversationId);
+ final canManage = current?.ownerId == c.accountId;
+ final readOnly = action == 'details';
+ return AlertDialog(
+ title: Text(switch (action) {
+ 'rename' => 'Rename project',
+ 'sharing' => 'Sharing',
+ 'cadence' => 'Project updates',
+ _ => 'Project details',
+ }),
+ content: SizedBox(
+ width: 400,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (action == 'rename')
+ TextFormField(
+ autofocus: true,
+ initialValue: name,
+ maxLength: 160,
+ onChanged: (value) => update(() => name = value),
+ ),
+ if (action == 'sharing') ...[
+ ProjectVisibility(
+ value: visibility,
+ onChanged: busy || !canManage
+ ? null
+ : (value) => update(() => visibility = value),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ visibility == 'public'
+ ? 'Everyone in this swarm can open this project.'
+ : 'Only the people below can open this project.',
+ style: DesktopChrome.text(),
+ ),
+ if (visibility == 'private')
+ for (final person
+ in c.snapshot?.people ?? const <SuperTabPerson>[])
+ CheckboxListTile(
+ dense: true,
+ contentPadding: EdgeInsets.zero,
+ title: Text(
+ person.email,
+ style: DesktopChrome.control(),
+ ),
+ subtitle: person.id == project.ownerId
+ ? const Text('Project owner')
+ : null,
+ value:
+ person.id == project.ownerId ||
+ members.contains(person.id),
+ onChanged:
+ busy ||
+ !canManage ||
+ person.id == project.ownerId
+ ? null
+ : (value) => update(
+ () => value == true
+ ? members.add(person.id)
+ : members.remove(person.id),
+ ),
+ ),
+ ],
+ if (action == 'cadence') ...[
+ Text(
+ 'The lead consolidates new workgroup reports while work is active.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 12),
+ DropdownButton<int>(
+ value: minutes,
+ items: [
+ for (final value in const [1, 5, 15, 30])
+ DropdownMenuItem(
+ value: value,
+ child: Text(
+ 'Every $value ${value == 1 ? 'minute' : 'minutes'}',
+ ),
+ ),
+ ],
+ onChanged: busy
+ ? null
+ : (value) => update(() => minutes = value!),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Questions, blockers and completion are reported immediately. No new progress means no update.',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ if (readOnly) ...[
+ Text(
+ current?.name ?? project.name,
+ style: DesktopChrome.text(medium: true),
+ ),
+ const SizedBox(height: 12),
+ Text(
+ group?.brief.isNotEmpty == true ? group!.brief : 'Discuss the project with its lead to define the work.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 16),
+ Text('Repository', style: DesktopChrome.metadata()),
+ SelectableText(
+ current?.repository?['repositoryUrl'] as String? ??
+ current?.repository?['cwd'] as String? ??
+ 'Not set',
+ ),
+ const SizedBox(height: 16),
+ Text('Lead', style: DesktopChrome.metadata()),
+ Text(
+ group?.leadId == null
+ ? 'Starting…'
+ : c.snapshot!.agentName(group!.leadId!),
+ ),
+ ],
+ if (c.operationError != null) ...[
+ const SizedBox(height: 12),
+ Text(c.operationError!),
+ ],
+ if (c.hasPendingAction)
+ TextButton(
+ onPressed: c.saving ? null : c.retry,
+ child: const Text('Check pending action'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: busy ? null : () => Navigator.pop(context),
+ child: Text(readOnly ? 'Close' : 'Cancel'),
+ ),
+ if (!readOnly)
+ FilledButton(
+ onPressed:
+ busy ||
+ c.saving ||
+ c.hasPendingAction ||
+ name.trim().isEmpty ||
+ (action != 'cadence' && !canManage)
+ ? null
+ : () async {
+ update(() => busy = true);
+ final result = await c.command({
+ 'type':
+ 'project.${action == 'rename'
+ ? 'rename'
+ : action == 'sharing'
+ ? 'sharing'
+ : 'cadence'}',
+ 'projectId': project.id,
+ if (action == 'rename') 'name': name.trim(),
+ if (action == 'sharing') ...{
+ 'visibility': visibility,
+ 'memberIds': members.toList(),
+ },
+ if (action == 'cadence') 'minutes': minutes,
+ });
+ if (!context.mounted) return;
+ if (result != null) {
+ Navigator.pop(context);
+ } else {
+ update(() => busy = false);
+ }
+ },
+ child: const Text('Save'),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
new file mode 100644
index 000000000..bad85715a
--- /dev/null
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -0,0 +1,170 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_icon_button.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'model.dart';
+
+class ProjectSidebar extends StatelessWidget {
+ const ProjectSidebar({
+ super.key,
+ required this.controller,
+ required this.onSelect,
+ required this.needsHuman,
+ this.onNewProject,
+ });
+ final SuperTabController controller;
+ final ValueChanged<String> onSelect;
+ final int Function(SuperTabConversation group) needsHuman;
+ final VoidCallback? onNewProject;
+
+ Widget _row(SuperTabConversation group, {SuperTabProject? project}) {
+ final selected = controller.selectedId == group.id;
+ final groups = project == null
+ ? [group]
+ : controller.snapshot!.conversations.where(
+ (g) => g.projectId == project.id && !g.archived,
+ );
+ final waiting = groups.any((g) => needsHuman(g) > 0);
+ final unread = groups.any(controller.unread);
+ return Semantics(
+ selected: selected,
+ child: ListTile(
+ key: ValueKey('super-group-${group.id}'),
+ dense: true,
+ contentPadding: const EdgeInsets.symmetric(horizontal: 10),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ ),
+ selected: selected,
+ selectedTileColor: DesktopChrome.activeSelection,
+ title: Row(
+ children: [
+ if (project?.isPrivate == true) ...[
+ Icon(
+ AppIcons.lock,
+ size: 14,
+ color: selected
+ ? DesktopChrome.onSelection
+ : DesktopChrome.muted,
+ ),
+ const SizedBox(width: 6),
+ ],
+ Expanded(
+ child: Text(
+ project?.name ?? group.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ medium: project != null || unread,
+ color: selected ? DesktopChrome.onSelection : null,
+ ),
+ ),
+ ),
+ ],
+ ),
+ trailing: waiting
+ ? Tooltip(
+ message: 'Needs a human',
+ child: Text(
+ '?',
+ style: DesktopChrome.control(
+ color: grid.AppPalette.warn,
+ medium: true,
+ ),
+ ),
+ )
+ : unread
+ ? Semantics(
+ label: 'Unread messages',
+ child: Container(
+ width: 6,
+ height: 6,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: selected
+ ? DesktopChrome.onSelection
+ : DesktopChrome.accent,
+ ),
+ ),
+ )
+ : null,
+ onTap: () => onSelect(group.id),
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final snapshot = controller.snapshot;
+ return Material(
+ color: DesktopChrome.surface,
+ child: Column(
+ children: [
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
+ children: [
+ for (final project
+ in snapshot?.projects ?? const <SuperTabProject>[])
+ if (snapshot?.conversation(project.leadConversationId)
+ case final lead?)
+ Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ children: [
+ AppIconButton(
+ key: ValueKey(
+ 'super-project-expand-${project.id}',
+ ),
+ icon:
+ controller.expandedProjects.contains(
+ project.id,
+ )
+ ? AppIcons.chevronDown
+ : AppIcons.chevronRight,
+ tooltip:
+ '${controller.expandedProjects.contains(project.id) ? 'Collapse' : 'Expand'} ${project.name}',
+ onPressed: () =>
+ controller.toggleProject(project.id),
+ ),
+ Expanded(child: _row(lead, project: project)),
+ ],
+ ),
+ if (controller.expandedProjects.contains(project.id))
+ for (final group in snapshot!.conversations)
+ if (group.projectId == project.id &&
+ group.id != project.leadConversationId &&
+ !group.archived)
+ Padding(
+ padding: const EdgeInsets.only(
+ left: 32,
+ bottom: 2,
+ ),
+ child: _row(group),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton.icon(
+ key: const ValueKey('super-new-project'),
+ onPressed: controller.canWrite ? onNewProject : null,
+ icon: const Icon(AppIcons.plus, size: 16),
+ label: const Text('Project'),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/project_visibility.dart b/desktop/lib/super_tabs/project_visibility.dart
new file mode 100644
index 000000000..749520854
--- /dev/null
+++ b/desktop/lib/super_tabs/project_visibility.dart
@@ -0,0 +1,57 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../widgets/desktop_chrome.dart';
+
+class ProjectVisibility extends StatelessWidget {
+ const ProjectVisibility({
+ super.key,
+ required this.value,
+ required this.onChanged,
+ });
+ final String value;
+ final ValueChanged<String>? onChanged;
+
+ @override
+ Widget build(BuildContext context) => MenuAnchor(
+ menuChildren: [
+ for (final (id, title, detail) in const [
+ ('public', 'Public', 'Everyone in this swarm'),
+ ('private', 'Private', 'Only people you invite to this project'),
+ ])
+ MenuItemButton(
+ onPressed: onChanged == null ? null : () => onChanged!(id),
+ leadingIcon: Icon(
+ id == 'private' ? AppIcons.lock : AppIcons.users,
+ size: 16,
+ ),
+ trailingIcon: id == value
+ ? const Icon(AppIcons.check, size: 16)
+ : null,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title, style: DesktopChrome.control()),
+ Text(detail, style: DesktopChrome.metadata()),
+ ],
+ ),
+ ),
+ ),
+ ],
+ builder: (context, menu, _) => DesktopPill(
+ label: value == 'private' ? 'Private' : 'Public',
+ semanticLabel: 'Project visibility',
+ icon: value == 'private' ? AppIcons.lock : AppIcons.users,
+ capsule: true,
+ textSize: 13,
+ tooltip: value == 'private'
+ ? 'Only invited project members'
+ : 'Everyone in this swarm',
+ onPressed: onChanged == null
+ ? null
+ : () => menu.isOpen ? menu.close() : menu.open(),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/pull_requests.dart b/desktop/lib/super_tabs/pull_requests.dart
index 67daced8c..a086f7bbc 100644
--- a/desktop/lib/super_tabs/pull_requests.dart
+++ b/desktop/lib/super_tabs/pull_requests.dart
@@ -63,9 +63,15 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
int _revision = 0;
Timer? _timer;
SuperTabController get c => widget.controller;
+ bool get _projectScope =>
+ _all || c.snapshot?.isProjectLead(c.selectedId) == true;
List<SuperTabConversation> get _groups =>
c.snapshot?.conversations
- .where((g) => _all || g.id == c.selectedId)
+ .where(
+ (g) => _projectScope
+ ? g.projectId == c.selected?.projectId
+ : g.id == c.selectedId,
+ )
.toList() ??
const [];
@@ -88,7 +94,8 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
}
void _changed() {
- final scope = '${c.accountId}:${c.tabId}:${_all ? '*' : c.selectedId}';
+ final scope =
+ '${c.accountId}:${c.tabId}:${c.selected?.projectId}:${_projectScope ? '*' : c.selectedId}';
if (scope != _scope) {
_scope = scope;
_observed.clear();
@@ -103,7 +110,7 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
_timer?.cancel();
setState(() => _loading = true);
final groups = _groups;
- if (_all) {
+ if (_projectScope) {
// The controller owns paging and caches; this never changes selection.
for (final group in groups) {
if (!mounted || revision != _revision) return;
@@ -191,19 +198,22 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
style: DesktopChrome.text(medium: true),
),
),
- DropdownButton<bool>(
- value: _all,
- underline: const SizedBox.shrink(),
- items: const [
- DropdownMenuItem(value: false, child: Text('This group')),
- DropdownMenuItem(value: true, child: Text('All groups')),
- ],
- onChanged: (value) {
- if (value == null) return;
- setState(() => _all = value);
- _changed();
- },
- ),
+ if (c.snapshot?.isProjectLead(c.selectedId) == true)
+ Text('This project', style: DesktopChrome.metadata())
+ else
+ DropdownButton<bool>(
+ value: _all,
+ underline: const SizedBox.shrink(),
+ items: const [
+ DropdownMenuItem(value: false, child: Text('This group')),
+ DropdownMenuItem(value: true, child: Text('This project')),
+ ],
+ onChanged: (value) {
+ if (value == null) return;
+ setState(() => _all = value);
+ _changed();
+ },
+ ),
],
),
),
@@ -239,7 +249,7 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
),
subtitle: Text(
[
- if (_all) pr.groups.join(' · '),
+ if (_projectScope) pr.groups.join(' '),
pr.state ?? 'View status on GitHub',
].join('\n'),
style: DesktopChrome.metadata(),
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index 30b9433eb..d247057ca 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -142,6 +142,9 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
Widget _agent(SuperTabAgent agent) {
final name = c.snapshot!.agentName(agent.id), activity = _activity(agent);
+ final project = c.snapshot!.projects
+ .where((p) => p.id == agent.projectId)
+ .firstOrNull;
final waiting = activity == 'Needs you';
return GestureDetector(
onSecondaryTapUp: (event) async {
@@ -183,7 +186,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
],
),
subtitle: Text(
- activity,
+ '${project?.name ?? ''} $activity'.trim(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: DesktopChrome.metadata(
@@ -207,8 +210,6 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
return ListView(
padding: const EdgeInsets.only(bottom: 12),
children: [
- _heading('Leads'),
- for (final agent in leads) _agent(agent),
_heading(
'Humans',
add: c.isOwner ? widget.onInvite : null,
@@ -256,7 +257,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
: null,
tooltip: 'Add agent',
),
- for (final agent in agents) _agent(agent),
+ for (final agent in [...leads, ...agents]) _agent(agent),
],
);
}
@@ -284,12 +285,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
(_membersFraction + event.delta.dy / size.maxHeight)
.clamp(.25, .75),
),
- child: SizedBox(
- height: 9,
- child: Center(
- child: Divider(height: 1, color: DesktopChrome.rim),
- ),
- ),
+ child: const SizedBox(height: 9),
),
),
),
diff --git a/desktop/lib/super_tabs/route_row.dart b/desktop/lib/super_tabs/route_row.dart
index a9ec5cf89..d16ffc09a 100644
--- a/desktop/lib/super_tabs/route_row.dart
+++ b/desktop/lib/super_tabs/route_row.dart
@@ -326,7 +326,7 @@ class _ChangeDialogState extends State<_ChangeDialog> {
}
}
-/// Opens this Super Tab's routing policy: the effective policy, with the
+/// Opens this Swarm's routing policy: the effective policy, with the
/// fields it overrides marked. Only the owner can change it.
Future<void> showSuperTabRouting(BuildContext context, SuperTabController c) =>
showAppDialog<void>(
@@ -349,7 +349,7 @@ class _RoutingDialogState extends State<_RoutingDialog> {
RoutingPolicy? _policy;
// The owner's account policy: what a field shows after Use account default.
RoutingPolicy? _account;
- // The fields this Super Tab overrides; the rest follow the account default.
+ // The fields this Swarm overrides; the rest follow the account default.
final _overridden = <String>{};
List<String> _warnings = const [];
String? _problem;
@@ -429,7 +429,7 @@ class _RoutingDialogState extends State<_RoutingDialog> {
return ListenableBuilder(
listenable: _c,
builder: (context, _) => AlertDialog(
- title: const Text('Routing for this Super Tab'),
+ title: const Text('Routing for this Swarm'),
content: SizedBox(
width: 560,
child: SingleChildScrollView(
diff --git a/desktop/lib/super_tabs/routing_policy.dart b/desktop/lib/super_tabs/routing_policy.dart
index 39bac23f3..db683be64 100644
--- a/desktop/lib/super_tabs/routing_policy.dart
+++ b/desktop/lib/super_tabs/routing_policy.dart
@@ -48,7 +48,7 @@ class RoutingModel {
'${effort == 'default' ? '' : ' $effort'}';
}
-/// The Super Tab routing policy: which models may be chosen, the quality each
+/// The Swarm routing policy: which models may be chosen, the quality each
/// difficulty needs, and how much quota to keep back.
class RoutingPolicy {
const RoutingPolicy({
@@ -108,7 +108,7 @@ class RoutingPolicy {
_ => copyWith(notes: other.notes),
};
- /// Only the named fields, for a Super Tab override.
+ /// Only the named fields, for a Swarm override.
Map<String, dynamic> fields(Set<String> names) => {
for (final e in toJson().entries)
if (names.contains(e.key)) e.key: e.value,
diff --git a/desktop/lib/super_tabs/routing_policy_form.dart b/desktop/lib/super_tabs/routing_policy_form.dart
index 7dcbb5517..b014427be 100644
--- a/desktop/lib/super_tabs/routing_policy_form.dart
+++ b/desktop/lib/super_tabs/routing_policy_form.dart
@@ -5,7 +5,7 @@ import '../shared/widgets/setting_row.dart';
import 'routing_policy.dart';
/// The routing policy editor, used by Settings ▸ Routing (the account default)
-/// and by a Super Tab's Routing dialog (override mode, with Use account
+/// and by a Swarm's Routing dialog (override mode, with Use account
/// default).
///
/// A number outside what the backend accepts is flagged under its field and is
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index bd89c44b8..17ecd3630 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -17,6 +17,8 @@ import 'model.dart';
import 'message_row.dart';
import 'route_row.dart';
import 'work_details.dart';
+import 'project_sidebar.dart';
+import 'project_options.dart';
/// The contents of one app tab. Its title stays in the app's existing tab bar.
/// [terminal] is the existing native pane, with its own controls and input.
@@ -33,6 +35,8 @@ class SuperTabView extends StatefulWidget {
this.onOpenGroupTerminals,
this.terminalsVisible = false,
this.app,
+ this.onNewProject,
+ this.onChooseAgentTerminal,
});
final SuperTabController controller;
final VoidCallback onInvite;
@@ -43,6 +47,8 @@ class SuperTabView extends StatefulWidget {
final VoidCallback? onCloseTerminal, onOpenGroupTerminals;
final bool terminalsVisible;
final AppNotifier? app;
+ final VoidCallback? onNewProject;
+ final ValueChanged<SuperTabAgent>? onChooseAgentTerminal;
@override
State<SuperTabView> createState() => _SuperTabViewState();
@@ -50,7 +56,7 @@ class SuperTabView extends StatefulWidget {
class _SuperTabViewState extends State<SuperTabView> {
final _composer = TextEditingController();
- final _focus = FocusNode(debugLabel: 'Super Tab message');
+ final _focus = FocusNode(debugLabel: 'Swarm message');
final _scroll = <String, ScrollController>{};
final _latest = <String, int>{};
final _following = <String, bool>{};
@@ -111,6 +117,9 @@ class _SuperTabViewState extends State<SuperTabView> {
_replies.clear();
_newAfter.clear();
}
+ final visible =
+ c.snapshot?.conversations.map((g) => g.id).toSet() ?? <String>{};
+ _replies.removeWhere((id, _) => !visible.contains(id));
final id = c.selectedId;
final firstView = !_scroll.containsKey(id);
final scroll = _scroll.putIfAbsent(id, ScrollController.new);
@@ -307,6 +316,15 @@ class _SuperTabViewState extends State<SuperTabView> {
Future<void> _groupAction(String action, SuperTabConversation group) async {
final c = this.c;
+ if (action == 'routing') {
+ await showSuperTabRouting(context, c);
+ return;
+ }
+ if (c.snapshot?.isProjectLead(group.id) == true && action != 'archived') {
+ final project = c.snapshot!.projectFor(group.id);
+ if (project != null) await showProjectAction(context, c, project, action);
+ return;
+ }
if (action == 'archived') {
await _archived();
return;
@@ -328,6 +346,7 @@ class _SuperTabViewState extends State<SuperTabView> {
context: context,
builder: (context) => SuperTabDialogScope(
controller: c,
+ conversationId: group.id,
child: StatefulBuilder(
builder: (context, update) => AlertDialog(
title: const Text('Rename conversation'),
@@ -385,6 +404,7 @@ class _SuperTabViewState extends State<SuperTabView> {
.where(
(group) =>
group.archived &&
+ group.projectId == c.selected?.projectId &&
group.title.toLowerCase().contains(query),
)
.toList() ??
@@ -443,96 +463,14 @@ class _SuperTabViewState extends State<SuperTabView> {
c.select(selected);
}
- Widget _sidebar() => Material(
- color: DesktopChrome.surface,
- child: Column(
- children: [
- Expanded(
- child: ListView(
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
- children: [
- for (final group
- in c.snapshot?.conversations ?? <SuperTabConversation>[])
- if (!group.archived)
- Padding(
- padding: const EdgeInsets.only(bottom: 2),
- child: Semantics(
- selected: c.selectedId == group.id,
- child: ListTile(
- key: ValueKey('super-group-${group.id}'),
- dense: true,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(
- DesktopChrome.rowRadius,
- ),
- ),
- selected: c.selectedId == group.id,
- selectedTileColor: DesktopChrome.activeSelection,
- title: Text(
- group.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(
- medium: c.unread(group),
- color: c.selectedId == group.id
- ? DesktopChrome.onSelection
- : null,
- ),
- ),
- trailing: _needsHuman(group).isNotEmpty
- ? Tooltip(
- message: 'Needs a human',
- child: Text(
- '? ${_needsHuman(group).length}',
- style: DesktopChrome.control(
- medium: true,
- color: grid.AppPalette.warn,
- ),
- ),
- )
- : c.unread(group)
- ? Semantics(
- label: 'Unread messages',
- child: Container(
- width: 6,
- height: 6,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- color: c.selectedId == group.id
- ? DesktopChrome.onSelection
- : DesktopChrome.accent,
- ),
- ),
- )
- : null,
- onTap: () {
- c.select(group.id);
- _closeSidebar();
- },
- ),
- ),
- ),
- ],
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
- child: Align(
- alignment: Alignment.centerLeft,
- child: AppIconButton(
- icon: AppIcons.settings,
- tooltip: 'Super Tab settings',
- onPressed: c.snapshot == null
- ? null
- : () {
- _closeSidebar();
- unawaited(showSuperTabRouting(context, c));
- },
- ),
- ),
- ),
- ],
- ),
+ Widget _sidebar() => ProjectSidebar(
+ controller: c,
+ onNewProject: widget.onNewProject,
+ needsHuman: (group) => _needsHuman(group).length,
+ onSelect: (id) {
+ c.select(id);
+ _closeSidebar();
+ },
);
List<SuperTabAgent> _needsHuman(SuperTabConversation group) =>
@@ -559,153 +497,157 @@ class _SuperTabViewState extends State<SuperTabView> {
bool get _terminalsVisible =>
widget.terminalsVisible || widget.terminal != null;
- Widget _header(
- SuperTabConversation? group,
- bool narrow,
- bool showRoster,
- ) => Container(
- constraints: const BoxConstraints(minHeight: 52),
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
- decoration: BoxDecoration(
- border: Border(bottom: BorderSide(color: DesktopChrome.rim)),
- ),
- child: Row(
- children: [
- if (narrow)
- AppIconButton(
- icon: AppIcons.columns2,
- tooltip: 'Conversations',
- onPressed: () => setState(() => _sidebarOpen = !_sidebarOpen),
- ),
- Expanded(
- child: Align(
- alignment: Alignment.centerLeft,
- child: group == null
- ? Text('Loading conversation…', style: DesktopChrome.text())
- : PopupMenuButton<String>(
- key: const ValueKey('super-group-options'),
- tooltip: 'Workgroup options',
- position: PopupMenuPosition.under,
- onSelected: (action) =>
- unawaited(_groupAction(action, group)),
- itemBuilder: (_) => [
- const PopupMenuItem(
- value: 'work',
- child: Text('Work details'),
- ),
- if (c.snapshot?.conversations.any((g) => g.archived) ==
- true)
- const PopupMenuItem(
- value: 'archived',
- child: Text('Archived conversations'),
- ),
- if (c.canWrite && !c.hasPendingAction && !c.saving) ...[
- const PopupMenuItem(
- value: 'rename',
- child: Text('Rename'),
- ),
- if (group.id != 'lead')
- PopupMenuItem(
- value: 'archive',
- enabled:
- group.assignment == null ||
- const [
- 'done',
- 'stopped',
- ].contains(group.assignment!['status']),
- child: Text(
- group.archived
- ? 'Reopen conversation'
- : 'Archive',
- ),
- ),
- ],
- ],
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 4,
- vertical: 8,
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Flexible(
- child: Text(
- group.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.text(medium: true),
- ),
- ),
- const SizedBox(width: 6),
- Icon(
- AppIcons.chevronDown,
- size: 16,
- color: DesktopChrome.muted,
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- AppIconButton(
- key: const ValueKey('super-chat'),
- icon: AppIcons.messageSquareText,
- size: 20,
- tooltip: 'Chat',
- selected: !_terminalsVisible && !_showPullRequests,
- color: !_terminalsVisible && !_showPullRequests
- ? DesktopChrome.accent
- : DesktopChrome.muted,
- onPressed: () {
- setState(() => _showPullRequests = false);
- widget.onCloseTerminal?.call();
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) _focus.requestFocus();
- });
- },
- ),
- const SizedBox(width: 4),
- AppIconButton(
- key: const ValueKey('super-terminals'),
- icon: AppIcons.terminal,
- size: 20,
- tooltip: 'Group terminals (${group?.agentIds.length ?? 0})',
- selected: _terminalsVisible,
- color: _terminalsVisible ? DesktopChrome.accent : DesktopChrome.muted,
- onPressed: group?.agentIds.isNotEmpty == true
- ? () {
- setState(() => _showPullRequests = false);
- widget.onOpenGroupTerminals?.call();
- }
- : null,
+ Widget _header(SuperTabConversation? group, bool narrow, bool showRoster) =>
+ Container(
+ constraints: const BoxConstraints(minHeight: 52),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ decoration: BoxDecoration(
+ border: Border(bottom: BorderSide(color: DesktopChrome.rim)),
),
- const SizedBox(width: 4),
- AppIconButton(
- key: const ValueKey('super-pull-requests'),
- icon: AppIcons.gitPullRequest,
- size: 20,
- tooltip: 'Pull requests',
- selected: !_terminalsVisible && _showPullRequests,
- color: !_terminalsVisible && _showPullRequests
- ? DesktopChrome.accent
- : DesktopChrome.muted,
- onPressed: () {
- widget.onCloseTerminal?.call();
- setState(() => _showPullRequests = true);
- },
+ child: Row(
+ children: [
+ if (narrow)
+ AppIconButton(
+ icon: AppIcons.columns2,
+ tooltip: 'Conversations',
+ onPressed: () => setState(() => _sidebarOpen = !_sidebarOpen),
+ ),
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8),
+ child: Text(
+ group == null
+ ? 'Choose a project'
+ : c.snapshot!.isProjectLead(group.id)
+ ? c.snapshot!.projectFor(group.id)!.name
+ : group.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(medium: true),
+ ),
+ ),
+ ),
+ AppIconButton(
+ key: const ValueKey('super-chat'),
+ icon: AppIcons.messageSquareText,
+ size: 20,
+ tooltip: 'Chat',
+ selected: !_terminalsVisible && !_showPullRequests,
+ color: !_terminalsVisible && !_showPullRequests
+ ? DesktopChrome.accent
+ : DesktopChrome.muted,
+ onPressed: () {
+ setState(() => _showPullRequests = false);
+ widget.onCloseTerminal?.call();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focus.requestFocus();
+ });
+ },
+ ),
+ const SizedBox(width: 4),
+ AppIconButton(
+ key: const ValueKey('super-terminals'),
+ icon: AppIcons.terminal,
+ size: 20,
+ tooltip: 'Group terminals (${group?.agentIds.length ?? 0})',
+ selected: _terminalsVisible,
+ color: _terminalsVisible
+ ? DesktopChrome.accent
+ : DesktopChrome.muted,
+ onPressed: group?.agentIds.isNotEmpty == true
+ ? () {
+ setState(() => _showPullRequests = false);
+ widget.onOpenGroupTerminals?.call();
+ }
+ : null,
+ ),
+ const SizedBox(width: 4),
+ AppIconButton(
+ key: const ValueKey('super-pull-requests'),
+ icon: AppIcons.gitPullRequest,
+ size: 20,
+ tooltip: 'Pull requests',
+ selected: !_terminalsVisible && _showPullRequests,
+ color: !_terminalsVisible && _showPullRequests
+ ? DesktopChrome.accent
+ : DesktopChrome.muted,
+ onPressed: () {
+ widget.onCloseTerminal?.call();
+ setState(() => _showPullRequests = true);
+ },
+ ),
+ if (group != null) _options(group),
+ if (!showRoster)
+ AppIconButton(
+ icon: AppIcons.users,
+ tooltip: 'Members and machines',
+ selected: _rosterOpen,
+ onPressed: () => setState(() => _rosterOpen = !_rosterOpen),
+ ),
+ ],
),
- if (!showRoster)
- AppIconButton(
- icon: AppIcons.users,
- tooltip: 'Members and machines',
- selected: _rosterOpen,
- onPressed: () => setState(() => _rosterOpen = !_rosterOpen),
- ),
+ );
+
+ Widget _options(SuperTabConversation group) {
+ final project = c.snapshot?.projectFor(group.id);
+ final isProject = c.snapshot?.isProjectLead(group.id) == true;
+ final editable = c.canWrite && !c.saving && !c.hasPendingAction;
+ Widget item(String label, VoidCallback? action) => MenuItemButton(
+ style: const ButtonStyle(
+ minimumSize: WidgetStatePropertyAll(Size(208, 32)),
+ side: WidgetStatePropertyAll(BorderSide.none),
+ padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 12)),
+ alignment: Alignment.centerLeft,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ onPressed: action,
+ child: Text(label),
+ );
+ return MenuAnchor(
+ style: const MenuStyle(
+ minimumSize: WidgetStatePropertyAll(Size(220, 0)),
+ padding: WidgetStatePropertyAll(EdgeInsets.all(6)),
+ ),
+ menuChildren: [
+ if (isProject) ...[
+ if (editable && project?.ownerId == c.accountId)
+ item('Rename project', () => _groupAction('rename', group)),
+ item('Project details', () => _groupAction('details', group)),
+ if (editable && project?.ownerId == c.accountId)
+ item('Sharing', () => _groupAction('sharing', group)),
+ if (editable)
+ item('Update cadence', () => _groupAction('cadence', group)),
+ item('Swarm routing', () => _groupAction('routing', group)),
+ ] else ...[
+ item('Work details', () => _groupAction('work', group)),
+ if (editable) ...[
+ item('Rename', () => _groupAction('rename', group)),
+ item(
+ group.archived ? 'Reopen conversation' : 'Archive',
+ group.assignment == null ||
+ const [
+ 'done',
+ 'stopped',
+ ].contains(group.assignment!['status'])
+ ? () => _groupAction('archive', group)
+ : null,
+ ),
+ ],
+ ],
+ if (c.snapshot?.conversations.any(
+ (g) => g.archived && g.projectId == group.projectId,
+ ) ==
+ true)
+ item('Archived conversations', () => _groupAction('archived', group)),
],
- ),
- );
+ builder: (context, menu, _) => AppIconButton(
+ key: const ValueKey('super-group-options'),
+ icon: AppIcons.ellipsisVertical,
+ tooltip: isProject ? 'Project options' : 'Workgroup options',
+ onPressed: () => menu.isOpen ? menu.close() : menu.open(),
+ ),
+ );
+ }
Future<void> _reviewDelivery(
SuperTabMessage message,
@@ -1256,7 +1198,13 @@ class _SuperTabViewState extends State<SuperTabView> {
controller: c,
app: widget.app,
onInvite: widget.onInvite,
- onOpenAgent: _openAgent,
+ onOpenAgent: (agent) {
+ setState(() {
+ _showPullRequests = false;
+ _rosterOpen = false;
+ });
+ (widget.onChooseAgentTerminal ?? widget.onOpenTerminal)(agent);
+ },
onAddAgent: (group) {
setState(() => _rosterOpen = false);
widget.onAddAgent(group);
diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dart
index db8131627..3bc23a82c 100644
--- a/desktop/lib/super_tabs/workspace.dart
+++ b/desktop/lib/super_tabs/workspace.dart
@@ -21,10 +21,12 @@ class SuperTabWorkspace extends StatefulWidget {
required this.app,
required this.canvas,
required this.onAddAgent,
+ this.onNewProject,
});
final AppNotifier app;
final Widget canvas;
final ValueChanged<SuperTabConversation> onAddAgent;
+ final VoidCallback? onNewProject;
@override
State<SuperTabWorkspace> createState() => _SuperTabWorkspaceState();
@@ -180,7 +182,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
if (!current()) return;
String? inputContext;
// A narrowly shared harness remains its existing read-only observer.
- // Controlling a machine and joining a Super Tab are separate grants.
+ // Controlling a machine and joining a Swarm are separate grants.
if (controller.canWrite && machine?.machine.isShared != true) {
final stopped = machine?.agents
.where((a) => a.id == agent.harnessId)
@@ -304,6 +306,89 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
}
}
+ void _focusAgent(
+ SuperTabController controller,
+ String tabId,
+ SuperTabAgent agent,
+ String groupId,
+ ) {
+ if (!mounted ||
+ app.activeSwarmId != tabId ||
+ controller.snapshot
+ ?.conversation(groupId)
+ ?.agentIds
+ .contains(agent.id) !=
+ true) {
+ return;
+ }
+ controller.select(groupId);
+ _terminalRequest = null;
+ _resumeRequest = (groupId, agent.id);
+ controller.selectTerminal(groupId, agent.id);
+ setState(() {});
+ }
+
+ Future<void> _chooseAgentGroup(
+ SuperTabController controller,
+ String tabId,
+ SuperTabAgent agent,
+ ) async {
+ final groups =
+ controller.snapshot?.conversations
+ .where((g) => !g.archived && g.agentIds.contains(agent.id))
+ .toList() ??
+ <SuperTabConversation>[];
+ if (groups.isEmpty) return;
+ if (groups.length == 1) {
+ _focusAgent(controller, tabId, agent, groups.single.id);
+ return;
+ }
+ final chosen = await showAppDialog<String>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: controller,
+ requireWrite: false,
+ projectId: agent.projectId,
+ child: AlertDialog(
+ title: Text(
+ 'Open ${controller.snapshot?.agentName(agent.id) ?? agent.name}',
+ ),
+ content: SizedBox(
+ width: 360,
+ child: ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) => ListView(
+ shrinkWrap: true,
+ children: [
+ for (final group
+ in controller.snapshot?.conversations ??
+ <SuperTabConversation>[])
+ if (!group.archived && group.agentIds.contains(agent.id))
+ ListTile(
+ key: ValueKey('super-agent-group-${group.id}'),
+ title: Text(
+ controller.snapshot!.isProjectLead(group.id)
+ ? '${controller.snapshot!.projectFor(group.id)!.name} lead'
+ : group.label,
+ ),
+ onTap: () => Navigator.pop(context, group.id),
+ ),
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ ],
+ ),
+ ),
+ );
+ if (chosen != null) _focusAgent(controller, tabId, agent, chosen);
+ }
+
@override
Widget build(BuildContext context) {
final canvas = KeyedSubtree(key: _canvasKey, child: widget.canvas);
@@ -368,31 +453,15 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
onInvite: () =>
unawaited(showSuperTabPeople(context, controller)),
onAddAgent: widget.onAddAgent,
- onOpenTerminal: (agent) {
- final group =
- controller.selected?.agentIds.contains(agent.id) == true
- ? controller.selected
- : controller.snapshot?.conversations
- .where(
- (g) =>
- !g.archived &&
- g.assignment?['agentId'] == agent.id,
- )
- .firstOrNull ??
- controller.snapshot?.conversations
- .where(
- (g) =>
- !g.archived &&
- g.agentIds.contains(agent.id),
- )
- .firstOrNull;
- if (group == null) return;
- controller.select(group.id);
- _terminalRequest = null;
- _resumeRequest = (controller.selectedId, agent.id);
- controller.selectTerminal(controller.selectedId, agent.id);
- setState(() {});
- },
+ onNewProject: widget.onNewProject,
+ onOpenTerminal: (agent) => _focusAgent(
+ controller,
+ tab.id,
+ agent,
+ controller.selectedId,
+ ),
+ onChooseAgentTerminal: (agent) =>
+ unawaited(_chooseAgentGroup(controller, tab.id, agent)),
onOpenGroupTerminals: () =>
controller.selectGroupTerminals(controller.selectedId),
terminalsVisible: agents.isNotEmpty,
@@ -482,7 +551,7 @@ class _PeopleState extends State<_People> {
child: AlertDialog(
title: Text(
person.id == c.accountId
- ? 'Leave Super Tab?'
+ ? 'Leave Swarm?'
: 'Remove ${person.email}?',
),
content: const Text(
@@ -517,7 +586,7 @@ class _PeopleState extends State<_People> {
builder: (context, _) {
if (c.accessRevoked) {
return AlertDialog(
- content: Text(c.error ?? 'This Super Tab is no longer available.'),
+ content: Text(c.error ?? 'This Swarm is no longer available.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
@@ -577,12 +646,12 @@ class _PeopleState extends State<_People> {
SelectOption(
value: 'collaborator',
label: 'Can collaborate',
- detail: 'Read every conversation and send messages to the shared agents.',
+ detail: 'Read accessible projects and send messages to their agents.',
),
SelectOption(
value: 'viewer',
label: 'Can view',
- detail: 'Read every conversation without sending messages or changing work.',
+ detail: 'Read accessible projects without sending messages or changing work.',
),
],
onChanged: (role) {
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 0c71f3274..d6c8122ff 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -1,4 +1,7 @@
import 'dart:async';
+
+import '../super_tabs/project_visibility.dart';
+
import 'dart:convert';
import 'dart:math' as math;
@@ -1885,6 +1888,20 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
),
),
+ if (box.integration?.projectVisibility case final visibility?)
+ FocusTraversalOrder(
+ order: const NumericFocusOrder(3.5),
+ child: ProjectVisibility(
+ key: const ValueKey('new-harness-project-visibility'),
+ value: visibility,
+ onChanged:
+ box.locked || box.integration!.projectVisibilityLocked
+ ? null
+ : (value) => setState(
+ () => box.integration!.projectVisibility = value,
+ ),
+ ),
+ ),
],
),
),
diff --git a/desktop/lib/widgets/workspace_welcome.dart b/desktop/lib/widgets/workspace_welcome.dart
index faef9afe6..5f9f9e562 100644
--- a/desktop/lib/widgets/workspace_welcome.dart
+++ b/desktop/lib/widgets/workspace_welcome.dart
@@ -51,7 +51,7 @@ class WorkspaceWelcome extends StatefulWidget {
final ValueChanged<SwarmDestination>? onOpen;
final DateTime Function() now;
- /// Super Tabs closed on this computer, so a tab closed by accident is found
+ /// Swarms closed on this computer, so a tab closed by accident is found
/// on the page a person lands on, not only in the command palette.
final List<({String id, String name})> closedSuperTabs;
final ValueChanged<String>? onOpenSuperTab;
@@ -423,7 +423,7 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
padding: const EdgeInsets.only(bottom: 8, left: 10),
child: Semantics(
header: true,
- child: Text('Closed Super Tabs', style: headerStyle),
+ child: Text('Closed Swarms', style: headerStyle),
),
),
for (final tab in widget.closedSuperTabs)
diff --git a/desktop/macos/Runner/MainFlutterWindow.swift b/desktop/macos/Runner/MainFlutterWindow.swift
index 0c48655c8..ba7dba164 100644
--- a/desktop/macos/Runner/MainFlutterWindow.swift
+++ b/desktop/macos/Runner/MainFlutterWindow.swift
@@ -194,7 +194,7 @@ class MainFlutterWindow: NSWindow {
// key equivalent it is handled by the responder chain first, so it works
// wherever the focus happens to be.
//
- // Cmd-Shift-L matches the workspace keymap; Cmd-S opens the Store.
+ // Cmd-Shift-L matches the workspace keymap.
viewMenu.insertItem(
menuItem(
title: "Layout…",
diff --git a/desktop/test/daemon_review_render_test.dart b/desktop/test/daemon_review_render_test.dart
index 61bee0dec..b8c2851a7 100644
--- a/desktop/test/daemon_review_render_test.dart
+++ b/desktop/test/daemon_review_render_test.dart
@@ -908,7 +908,7 @@ void main() {
'agent.open' => '⌘O',
'pane.split_right' => '⌘R',
'machines.list' => '⌘M',
- 'app.store' => '⌘S',
+ 'app.store' => '⌃⌘S',
'harnesses.list' => '⌘P',
_ => null,
},
diff --git a/desktop/test/desktop_welcome_composer_test.dart b/desktop/test/desktop_welcome_composer_test.dart
index 9d03441d5..b9be6e2c4 100644
--- a/desktop/test/desktop_welcome_composer_test.dart
+++ b/desktop/test/desktop_welcome_composer_test.dart
@@ -197,38 +197,41 @@ void main() {
},
);
- testWidgets('Super Tab shortcut shows only the lead form and preserves existing harnesses', (tester) async {
- await setup(tester, storage: MemoryStore());
- app.currentUser = const CurrentUserProfile(
- id: 'owner',
- email: '[email protected]',
- );
- app.machineStates['m']!.agents = [
- Agent(
- id: 'recent-existing',
- name: 'Continue existing work',
- engine: 'codex',
- terminalAvailable: true,
- lastOpenedAt: DateTime.now(),
- lastActivityAt: DateTime.now(),
- ),
- ];
- final pane = app.adoptSessionForTest(terminal('recent-existing', []));
- final originalTab = app.activeSwarm;
- await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true, shift: true);
- await tester.pumpAndSettle();
- final target = app.activeSwarm;
- expect(target.isSuperTab, isTrue);
- expect(form, findsOneWidget);
- expect(find.text('Continue existing work'), findsNothing);
- expect(find.text('Recent harnesses'), findsNothing);
- expect(target.panes, isEmpty);
- expect(originalTab.panes.single, same(pane));
- expect(connection.starts, isEmpty);
- expect(form, findsOneWidget);
- expect(tester.takeException(), isNull);
- });
+ testWidgets(
+ 'Swarm shortcut shows only the lead form and preserves existing harnesses',
+ (tester) async {
+ await setup(tester, storage: MemoryStore());
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: 'recent-existing',
+ name: 'Continue existing work',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastOpenedAt: DateTime.now(),
+ lastActivityAt: DateTime.now(),
+ ),
+ ];
+ final pane = app.adoptSessionForTest(terminal('recent-existing', []));
+ final originalTab = app.activeSwarm;
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await tester.pumpAndSettle();
+ final target = app.activeSwarm;
+ expect(target.isSuperTab, isTrue);
+ expect(form, findsOneWidget);
+ expect(find.text('Continue existing work'), findsNothing);
+ expect(find.text('Recent harnesses'), findsNothing);
+ expect(target.panes, isEmpty);
+ expect(originalTab.panes.single, same(pane));
+ expect(connection.starts, isEmpty);
+ expect(form, findsOneWidget);
+ expect(tester.takeException(), isNull);
+ },
+ );
testWidgets('Cmd-P round trip opens a fresh form with successful defaults', (
tester,
diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dart
index 587d3cfac..17682cab8 100644
--- a/desktop/test/harness_store_entry_test.dart
+++ b/desktop/test/harness_store_entry_test.dart
@@ -40,7 +40,7 @@ void main() {
if (native) {
await configured.native(tester, 'store');
} else {
- await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true, ctrl: true);
}
await tester.pump();
}
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index a99ed1d04..74ba2b1b0 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -96,7 +96,9 @@ void main() {
('cmd+left', 'pane.focus_left'),
('cmd+enter', 'pane.zoom'),
('cmd+shift+p', 'navigation.commands'),
- ('cmd+s', 'app.store'),
+ ('cmd+s', 'super_tab.new'),
+ ('cmd+ctrl+s', 'app.store'),
+ ('cmd+shift+s', 'agent.share'),
('cmd+m', 'machines.list'),
('cmd+i', 'models.list'),
('cmd+shift+l', 'pane.layout'),
@@ -129,6 +131,7 @@ void main() {
expect(command('cmd+alt+right'), 'swarm.next');
expect(command('cmd+shift+['), isNull);
expect(command('cmd+shift+enter'), isNull);
+ expect(command('cmd+alt+shift+t'), isNull);
expect(command('ctrl+n', KeymapContext.picker), 'picker.next');
expect(command('cmd+t', KeymapContext.picker), 'swarm.new');
expect(command('cmd+['), 'navigation.back');
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
index 2c9082dd0..0ac440317 100644
--- a/desktop/test/new_harness_entry_rules_test.dart
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -130,8 +130,15 @@ void main() {
connections = {
for (final id in ['m', 'studio', 'build']) id: _Connection(id),
};
- app = createApp(connectionForTest: (id) => connections[id]!, store: superTabReady ? MemoryStore() : null);
- if (superTabReady) app.currentUser = const CurrentUserProfile(id: 'owner', email: '[email protected]');
+ app = createApp(
+ connectionForTest: (id) => connections[id]!,
+ store: superTabReady ? MemoryStore() : null,
+ );
+ if (superTabReady)
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
seedMixedAgents(app);
app.machineStates['m']!.localOnly = true;
app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
@@ -206,23 +213,32 @@ void main() {
await acceptSetupOrSearch(tester);
}
- testWidgets('the hidden Super Tab shortcut reuses New Tab without changing Cmd-T', (tester) async {
- await mount(tester, store: false, superTabReady: true);
- final before = app.swarms.length;
- await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true, shift: true);
- await tester.pumpAndSettle();
- expect(app.swarms, hasLength(before + 1));
- expect(app.activeSwarm.isSuperTab, isTrue);
- expect(find.byType(NewHarnessForm), findsOneWidget);
- expect(find.text('New Super Tab'), findsOneWidget);
- expect(box(tester).actionLabel, 'New Super Tab');
- expect(connections.values.expand((c) => c.starts), isEmpty);
- await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- await tester.pumpAndSettle();
- expect(app.activeSwarm.kind, 'harness');
- expect(box(tester).actionLabel, 'New Harness');
- await tester.pumpWidget(const SizedBox());
- });
+ testWidgets(
+ 'the hidden Super Tab shortcut reuses New Tab without changing Cmd-T',
+ (tester) async {
+ await mount(tester, store: false, superTabReady: true);
+ final before = app.swarms.length;
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await tester.pumpAndSettle();
+ expect(app.swarms, hasLength(before + 1));
+ expect(app.activeSwarm.isSuperTab, isTrue);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(find.text('New Swarm'), findsOneWidget);
+ expect(box(tester).actionLabel, 'New Swarm');
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ expect(find.text('Recent harnesses'), findsNothing);
+ await tester.tap(find.text('Public'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Private'));
+ await tester.pumpAndSettle();
+ expect(box(tester).integration!.projectVisibility, 'private');
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
+ expect(app.activeSwarm.kind, 'harness');
+ expect(box(tester).actionLabel, 'New Harness');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
for (final shortcut in [LogicalKeyboardKey.keyN, LogicalKeyboardKey.keyP]) {
testWidgets(
diff --git a/desktop/test/new_harness_guest_test.dart b/desktop/test/new_harness_guest_test.dart
index 37b4cbc39..3d22a4b8e 100644
--- a/desktop/test/new_harness_guest_test.dart
+++ b/desktop/test/new_harness_guest_test.dart
@@ -111,6 +111,36 @@ class _GuestApp extends AppNotifier {
}
void main() {
+ test('switching from an owned machine clears its folder and uses the guest workspace', () async {
+ final app = _GuestApp();
+ app.machineStates['own'] = MachineState(
+ const Machine(
+ machineId: 'own',
+ name: 'My Mac',
+ authMode: MachineAuthMode.self,
+ ),
+ )..nodeOnline = true;
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'own',
+ engine: 'claude',
+ folder: '/Users/me/private-project',
+ );
+ addTearDown(box.dispose);
+ await pumpEventQueue();
+ app.refusedAsks.clear();
+ box.focusField(NewHarnessField.machine);
+ box.accept(box.options.singleWhere((o) => o.id == 'dee'));
+ await pumpEventQueue();
+ expect(box.asGuest, isTrue);
+ expect(box.projectLabel, 'My workspace');
+ expect(app.refusedAsks, isEmpty);
+ expect(await box.create(), isNot(NewHarnessOutcome.failed));
+ // An empty folder asks the guest daemon to use its own workspace.
+ expect(app.launches.single['folder'], '');
+ });
+
test('a guest starts Claude Code or Codex in its own space: no project, harness, model or folder to choose', () async {
final app = _GuestApp();
addTearDown(app.dispose);
diff --git a/desktop/test/routing_policy_test.dart b/desktop/test/routing_policy_test.dart
index 059c65bf4..9d889e73a 100644
--- a/desktop/test/routing_policy_test.dart
+++ b/desktop/test/routing_policy_test.dart
@@ -168,7 +168,7 @@ void main() {
'type': 'tab.routingPolicy',
'policy': {'notes': 'Frontend prefers Claude.'},
});
- expect(find.text('Routing for this Super Tab'), findsNothing);
+ expect(find.text('Routing for this Swarm'), findsNothing);
f.app.superTabs.dispose();
});
@@ -263,7 +263,7 @@ void main() {
await tester.pump();
await tester.tap(find.widgetWithText(FilledButton, 'Save'));
await tester.pumpAndSettle();
- expect(find.text('Routing for this Super Tab'), findsOneWidget);
+ expect(find.text('Routing for this Swarm'), findsOneWidget);
expect(find.textContaining('Only the owner'), findsOneWidget);
f.app.superTabs.dispose();
});
diff --git a/desktop/test/search_workspace_test.dart b/desktop/test/search_workspace_test.dart
index 35b387404..5df941657 100644
--- a/desktop/test/search_workspace_test.dart
+++ b/desktop/test/search_workspace_test.dart
@@ -76,10 +76,10 @@ void main() {
expect(input, isEmpty);
}
- await checkHints('Open Harness · ⌘P', 'Explore Harness Store · ⌘S');
+ await checkHints('Open Harness · ⌘P', 'Explore Harness Store · ⌃⌘S');
map.apply('''{"bindings":[
{"keys":"cmd+p","command":null},
- {"keys":"cmd+s","command":null},
+ {"keys":"cmd+ctrl+s","command":null},
{"keys":"cmd+k","command":"harnesses.list"},
{"keys":"cmd+shift+s","command":"app.store"}
]}''');
@@ -87,7 +87,7 @@ void main() {
await checkHints('Open Harness · ⌘K', 'Explore Harness Store · ⇧⌘S');
map.apply('''{"bindings":[
{"keys":"cmd+p","command":null},
- {"keys":"cmd+s","command":null}
+ {"keys":"cmd+ctrl+s","command":null}
]}''');
await tester.pump();
await checkHints('Open Harness', 'Explore Harness Store');
diff --git a/desktop/test/super_tab_discovery_test.dart b/desktop/test/super_tab_discovery_test.dart
index 87d4848c6..93f7c3c40 100644
--- a/desktop/test/super_tab_discovery_test.dart
+++ b/desktop/test/super_tab_discovery_test.dart
@@ -212,27 +212,30 @@ void main() {
expect(restarted.activeSwarm.superTabId, tab.superTabId);
});
- test('a hidden Super Tab is listed after a restart and opening it shows it', () async {
- final catalog = _Catalog();
- final store = MemoryStore();
- final first = _computer(catalog, store);
- await first.superTabs.refreshTabs();
- expect(first.closedSuperTabs, isEmpty);
- final tab = first.swarms.singleWhere((s) => s.isSuperTab);
- await _close(first, tab);
- final restarted = _computer(catalog, store);
- // Before discovery the app cannot tell which hidden tabs are still ours.
- expect(restarted.closedSuperTabs, isEmpty);
- await restarted.superTabs.refreshTabs();
- expect(restarted.closedSuperTabs.map((t) => (t.id, t.name)), [
- (tab.superTabId, 'Pilot'),
- ]);
- restarted.openSuperTab(tab.superTabId!, 'Pilot');
- expect(restarted.closedSuperTabs, isEmpty);
- expect(restarted.activeSwarm.superTabId, tab.superTabId);
- });
+ test(
+ 'a hidden Swarm is listed after a restart and opening it shows it',
+ () async {
+ final catalog = _Catalog();
+ final store = MemoryStore();
+ final first = _computer(catalog, store);
+ await first.superTabs.refreshTabs();
+ expect(first.closedSuperTabs, isEmpty);
+ final tab = first.swarms.singleWhere((s) => s.isSuperTab);
+ await _close(first, tab);
+ final restarted = _computer(catalog, store);
+ // Before discovery the app cannot tell which hidden tabs are still ours.
+ expect(restarted.closedSuperTabs, isEmpty);
+ await restarted.superTabs.refreshTabs();
+ expect(restarted.closedSuperTabs.map((t) => (t.id, t.name)), [
+ (tab.superTabId, 'Pilot'),
+ ]);
+ restarted.openSuperTab(tab.superTabId!, 'Pilot');
+ expect(restarted.closedSuperTabs, isEmpty);
+ expect(restarted.activeSwarm.superTabId, tab.superTabId);
+ },
+ );
- test('a hidden Super Tab the person left is not offered', () async {
+ test('a hidden Swarm the person left is not offered', () async {
final catalog = _Catalog();
final app = _computer(catalog, MemoryStore());
await app.superTabs.setTabVisible('0123456789abcdef01234567', false);
@@ -241,7 +244,7 @@ void main() {
expect(app.closedSuperTabs, isEmpty);
});
- testWidgets('closing a Super Tab offers Reopen and Reopen shows it again', (
+ testWidgets('closing a Swarm offers Reopen and Reopen shows it again', (
tester,
) async {
final catalog = _Catalog();
@@ -252,12 +255,15 @@ void main() {
final tab = app.swarms.singleWhere((s) => s.isSuperTab);
await app.requestCloseSwarm(tab.id);
await tester.pump();
- expect(find.text('Super Tab closed. Its agents keep running.'), findsOneWidget);
+ expect(find.text('Swarm closed. Its agents keep running.'), findsOneWidget);
expect(app.swarms.where((s) => s.isSuperTab), isEmpty);
await tester.pump(const Duration(milliseconds: 400));
await tester.tap(find.text('Reopen'));
await tester.pump();
- expect(app.swarms.where((s) => s.superTabId == tab.superTabId), hasLength(1));
+ expect(
+ app.swarms.where((s) => s.superTabId == tab.superTabId),
+ hasLength(1),
+ );
expect(app.closedSuperTabs, isEmpty);
expect(app.superTabs.hiddenIds, isEmpty);
await tester.pumpAndSettle();
@@ -266,7 +272,7 @@ void main() {
await tester.pump();
});
- testWidgets('the command palette brings a closed Super Tab back by name', (
+ testWidgets('the command palette brings a closed Swarm back by name', (
tester,
) async {
final catalog = _Catalog();
@@ -285,7 +291,7 @@ void main() {
'>Pilot',
);
await tester.pumpAndSettle();
- expect(find.text('Closed Super Tabs'), findsWidgets);
+ expect(find.text('Closed Swarms'), findsWidgets);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(app.activeSwarm.superTabId, tab.superTabId);
@@ -295,7 +301,7 @@ void main() {
await tester.pump();
});
- testWidgets('the New Tab page shows a closed Super Tab after a restart', (
+ testWidgets('the New Tab page shows a closed Swarm after a restart', (
tester,
) async {
final catalog = _Catalog();
@@ -306,10 +312,10 @@ void main() {
await _close(first, tab);
final app = _computer(catalog, store)..newSwarm(newTabPage: true);
await mount(tester, app);
- expect(find.text('Closed Super Tabs'), findsNothing);
+ expect(find.text('Closed Swarms'), findsNothing);
await app.superTabs.refreshTabs();
await tester.pump();
- expect(find.text('Closed Super Tabs'), findsOneWidget);
+ expect(find.text('Closed Swarms'), findsOneWidget);
await tester.tap(
find.byKey(ValueKey('welcome-closed-super-tab-${tab.superTabId}')),
);
@@ -338,9 +344,7 @@ void main() {
await tester.pumpWidget(const SizedBox.shrink());
});
- testWidgets('closing an ordinary tab shows no Super Tab notice', (
- tester,
- ) async {
+ testWidgets('closing an ordinary tab shows no Swarm notice', (tester) async {
final app = _computer(_Catalog(), MemoryStore());
await mount(tester, app);
await app.superTabs.refreshTabs();
@@ -359,62 +363,74 @@ void main() {
await tester.pump();
});
- test('opening a closed Super Tab twice, from any entry, keeps one view', () async {
- final catalog = _Catalog();
- final app = _computer(catalog, MemoryStore());
- await app.superTabs.refreshTabs();
- final tab = app.swarms.singleWhere((s) => s.isSuperTab);
- final id = tab.superTabId!;
- await _close(app, tab);
- final historyId = app.closedHistory.single.historyId;
- // List first, then Reopen on the notice.
- expect(app.openClosedSuperTab(id), isTrue);
- app.reopenClosedSwarm(historyId: historyId);
- expect(app.swarms.where((s) => s.superTabId == id), hasLength(1));
- expect(app.closedHistory, isEmpty);
- // Reopen first, then the list or Settings.
- await _close(app, app.swarms.singleWhere((s) => s.superTabId == id));
- app.reopenClosedSwarm();
- app.openSuperTab(id, 'Pilot');
- expect(app.openClosedSuperTab(id), isFalse);
- expect(app.swarms.where((s) => s.superTabId == id), hasLength(1));
- expect(app.activeSwarm.superTabId, id);
- });
+ test(
+ 'opening a closed Swarm twice, from any entry, keeps one view',
+ () async {
+ final catalog = _Catalog();
+ final app = _computer(catalog, MemoryStore());
+ await app.superTabs.refreshTabs();
+ final tab = app.swarms.singleWhere((s) => s.isSuperTab);
+ final id = tab.superTabId!;
+ await _close(app, tab);
+ final historyId = app.closedHistory.single.historyId;
+ // List first, then Reopen on the notice.
+ expect(app.openClosedSuperTab(id), isTrue);
+ app.reopenClosedSwarm(historyId: historyId);
+ expect(app.swarms.where((s) => s.superTabId == id), hasLength(1));
+ expect(app.closedHistory, isEmpty);
+ // Reopen first, then the list or Settings.
+ await _close(app, app.swarms.singleWhere((s) => s.superTabId == id));
+ app.reopenClosedSwarm();
+ app.openSuperTab(id, 'Pilot');
+ expect(app.openClosedSuperTab(id), isFalse);
+ expect(app.swarms.where((s) => s.superTabId == id), hasLength(1));
+ expect(app.activeSwarm.superTabId, id);
+ },
+ );
- test('a closed Super Tab opens in the empty New Tab it was chosen from', () async {
- final catalog = _Catalog();
- final app = _computer(catalog, MemoryStore());
- await app.superTabs.refreshTabs();
- final tab = app.swarms.singleWhere((s) => s.isSuperTab);
- await _close(app, tab);
- app.newSwarm(newTabPage: true);
- final page = app.activeSwarm;
- final count = app.swarms.length;
- expect(app.openClosedSuperTab(tab.superTabId!, intoSwarmId: page.id), isTrue);
- expect(app.swarms, hasLength(count));
- expect(page.superTabId, tab.superTabId);
- expect(page.isNewTabPage, isFalse);
- expect(app.activeSwarm, same(page));
- });
+ test(
+ 'a closed Swarm opens in the empty New Tab it was chosen from',
+ () async {
+ final catalog = _Catalog();
+ final app = _computer(catalog, MemoryStore());
+ await app.superTabs.refreshTabs();
+ final tab = app.swarms.singleWhere((s) => s.isSuperTab);
+ await _close(app, tab);
+ app.newSwarm(newTabPage: true);
+ final page = app.activeSwarm;
+ final count = app.swarms.length;
+ expect(
+ app.openClosedSuperTab(tab.superTabId!, intoSwarmId: page.id),
+ isTrue,
+ );
+ expect(app.swarms, hasLength(count));
+ expect(page.superTabId, tab.superTabId);
+ expect(page.isNewTabPage, isFalse);
+ expect(app.activeSwarm, same(page));
+ },
+ );
- test('a tab the person has left is not offered after an account switch', () async {
- final catalog = _Catalog();
- final store = MemoryStore();
- final app = _computer(catalog, store);
- await app.superTabs.refreshTabs();
- final tab = app.swarms.singleWhere((s) => s.isSuperTab);
- await _close(app, tab);
- expect(app.closedSuperTabs, hasLength(1));
- store.values['super_tab.hidden.other'] = '["${tab.superTabId}"]';
- catalog.fail = '/api/super-tabs';
- app.currentUser = const CurrentUserProfile(
- id: 'other',
- email: '[email protected]',
- );
- await app.superTabs.refreshTabs();
- expect(app.superTabs.hiddenIds, {tab.superTabId});
- expect(app.closedSuperTabs, isEmpty);
- });
+ test(
+ 'a tab the person has left is not offered after an account switch',
+ () async {
+ final catalog = _Catalog();
+ final store = MemoryStore();
+ final app = _computer(catalog, store);
+ await app.superTabs.refreshTabs();
+ final tab = app.swarms.singleWhere((s) => s.isSuperTab);
+ await _close(app, tab);
+ expect(app.closedSuperTabs, hasLength(1));
+ store.values['super_tab.hidden.other'] = '["${tab.superTabId}"]';
+ catalog.fail = '/api/super-tabs';
+ app.currentUser = const CurrentUserProfile(
+ id: 'other',
+ email: '[email protected]',
+ );
+ await app.superTabs.refreshTabs();
+ expect(app.superTabs.hiddenIds, {tab.superTabId});
+ expect(app.closedSuperTabs, isEmpty);
+ },
+ );
Future<(AppNotifier, List<Swarm>)> threeTabs(WidgetTester tester) async {
final catalog = _Catalog()
@@ -436,7 +452,7 @@ void main() {
await tester.pump();
}
- final closedNotice = find.text('Super Tab closed. Its agents keep running.');
+ final closedNotice = find.text('Swarm closed. Its agents keep running.');
testWidgets('two closes in the same frame leave one notice for the last', (
tester,
@@ -463,50 +479,53 @@ void main() {
await finishTest(tester, app);
});
- testWidgets('closing three Super Tabs 20 ms apart leaves one notice for the last', (
- tester,
- ) async {
- final (app, tabs) = await threeTabs(tester);
- for (final tab in tabs) {
- await app.requestCloseSwarm(tab.id);
- await tester.pump(const Duration(milliseconds: 20));
- }
- for (var i = 0; i < 12; i++) {
- await tester.pump(const Duration(milliseconds: 300));
- expect(closedNotice.evaluate(), hasLength(lessThanOrEqualTo(1)));
- }
- expect(tester.takeException(), isNull);
- expect(find.text('Reopen'), findsOneWidget);
- await tester.tap(find.text('Reopen'));
- await tester.pump();
- expect(app.swarms.where((s) => s.isSuperTab).map((s) => s.name), [
- tabs.last.name,
- ]);
- await finishTest(tester, app);
- });
+ testWidgets(
+ 'closing three Swarms 20 ms apart leaves one notice for the last',
+ (tester) async {
+ final (app, tabs) = await threeTabs(tester);
+ for (final tab in tabs) {
+ await app.requestCloseSwarm(tab.id);
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ for (var i = 0; i < 12; i++) {
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(closedNotice.evaluate(), hasLength(lessThanOrEqualTo(1)));
+ }
+ expect(tester.takeException(), isNull);
+ expect(find.text('Reopen'), findsOneWidget);
+ await tester.tap(find.text('Reopen'));
+ await tester.pump();
+ expect(app.swarms.where((s) => s.isSuperTab).map((s) => s.name), [
+ tabs.last.name,
+ ]);
+ await finishTest(tester, app);
+ },
+ );
- testWidgets('a close behind an unrelated notice leaves it and then shows ours', (
- tester,
- ) async {
- final (app, tabs) = await threeTabs(tester);
- ScaffoldMessenger.of(tester.element(find.byType(SwarmScreen))).showSnackBar(
- const SnackBar(content: Text('Something else'), persist: false),
- );
- await tester.pump(const Duration(milliseconds: 400));
- await app.requestCloseSwarm(tabs[0].id);
- await app.requestCloseSwarm(tabs[1].id);
- await tester.pump(const Duration(milliseconds: 400));
- expect(find.text('Something else'), findsOneWidget);
- expect(closedNotice, findsNothing);
- // The unrelated one runs its 4 s; ours follows, once.
- await tester.pump(const Duration(seconds: 4));
- await tester.pump(const Duration(seconds: 1));
- await tester.pump(const Duration(milliseconds: 400));
- expect(find.text('Something else'), findsNothing);
- expect(closedNotice, findsOneWidget);
- expect(tester.takeException(), isNull);
- await finishTest(tester, app);
- });
+ testWidgets(
+ 'a close behind an unrelated notice leaves it and then shows ours',
+ (tester) async {
+ final (app, tabs) = await threeTabs(tester);
+ ScaffoldMessenger.of(tester.element(find.byType(SwarmScreen)))
+ .showSnackBar(
+ const SnackBar(content: Text('Something else'), persist: false),
+ );
+ await tester.pump(const Duration(milliseconds: 400));
+ await app.requestCloseSwarm(tabs[0].id);
+ await app.requestCloseSwarm(tabs[1].id);
+ await tester.pump(const Duration(milliseconds: 400));
+ expect(find.text('Something else'), findsOneWidget);
+ expect(closedNotice, findsNothing);
+ // The unrelated one runs its 4 s; ours follows, once.
+ await tester.pump(const Duration(seconds: 4));
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pump(const Duration(milliseconds: 400));
+ expect(find.text('Something else'), findsNothing);
+ expect(closedNotice, findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await finishTest(tester, app);
+ },
+ );
testWidgets('a close after the notice timed out shows a fresh one', (
tester,
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 35533c265..f36cdc306 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -10,6 +10,7 @@ import 'package:harness/state/harness_attachments.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/super_tabs/launch.dart';
import 'package:harness/super_tabs/client.dart';
+import 'package:harness/super_tabs/controller.dart';
import 'package:harness/ws/ws_conn.dart';
import 'support/super_tab_fixture.dart';
@@ -124,7 +125,14 @@ class SuperTabFixtureConnection extends WsConn {
if (type == 'super_tabs') {
if (payload['action'] == 'wake') return {'ok': true};
if (payload['action'] == 'prepareContribution') {
- return {'ok': true, 'state': 'ready', 'cwd': '/work/project', 'engines': ['claude', 'codex', 'pi'], 'maxAgents': 4};
+ return {
+ 'ok': true,
+ 'state': 'ready',
+ 'cwd': '/work/project',
+ 'scope': 'swarm',
+ 'engines': ['claude', 'codex', 'pi'],
+ 'maxAgents': 4,
+ };
}
if (payload['action'] == 'prepareNative' ||
payload['action'] == 'renewNative') {
@@ -149,6 +157,15 @@ class SuperTabFixtureConnection extends WsConn {
};
}
if (payload['path'] == '/api/super-tabs' && payload['method'] == 'POST') {
+ final body = payload['body'] as Map;
+ server.state['projects'] ??= [
+ projectFixture(
+ 'lead',
+ 'Swarm',
+ 'lead',
+ visibility: body['projectVisibility'] as String? ?? 'public',
+ ),
+ ];
return {
'ok': true,
'value': {'id': tabId, 'revision': 0},
@@ -170,10 +187,15 @@ class SuperTabFixtureConnection extends WsConn {
final group = (server.state['conversations'] as List)
.cast<Map>()
.firstWhere((g) => g['id'] == command['conversationId']);
+ (server.state['agents'] as List).last['projectId'] =
+ group['projectId'] ?? 'lead';
(group['agentIds'] as List).add('lead-agent');
if (command['lead'] == true) group['leadId'] = 'lead-agent';
if (command['initialMessage'] is String) {
- server.append(command['initialMessage'] as String);
+ server.append(
+ command['initialMessage'] as String,
+ conversationId: command['conversationId'] as String,
+ );
}
}
}
@@ -289,8 +311,14 @@ class SuperTabLaunchFixture {
Future<NewHarnessController> box({
String engine = 'codex',
HarnessAttachments? attachments,
+ bool newProject = false,
}) async {
- final integration = await SuperTabLaunch.open(app, app.activeSwarm, 'lead');
+ final integration = await SuperTabLaunch.open(
+ app,
+ app.activeSwarm,
+ newProject ? 'new-project' : 'lead',
+ newProject: newProject,
+ );
final box = NewHarnessController(
app,
machineId: 'm',
@@ -308,6 +336,120 @@ class SuperTabLaunchFixture {
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
+ test(
+ 'guest machine access cannot create a Swarm lead under the owner account',
+ () async {
+ final f = SuperTabLaunchFixture();
+ final box = await f.box(engine: 'claude');
+ f.app.machineStates['m']!.machine = const Machine(
+ machineId: 'm',
+ name: 'Shared Mac',
+ authMode: MachineAuthMode.remote,
+ machineShare: MachineShare(
+ ownerName: 'Another owner',
+ ownerEmail: '[email protected]',
+ via: 'email',
+ added: true,
+ ),
+ );
+ await expectLater(
+ box.integration!.prepare('m', 'Start work'),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (e) => e.code,
+ 'code',
+ 'CONTRIBUTION_REQUIRED',
+ ),
+ ),
+ );
+ expect(f.connection.server.posts, isEmpty);
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ },
+ );
+
+ test(
+ 'a private first project does not expose its title as the swarm name',
+ () async {
+ final f = SuperTabLaunchFixture()..connection.nativeName = 'Private work';
+ final box = await f.box();
+ box.integration!.projectVisibility = 'private';
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(f.app.activeSwarm.name, 'Swarm');
+ final project = f.app.superTabs.peek(tabId)!.snapshot!.projects.single;
+ expect(project.name, 'Private work');
+ expect(project.isPrivate, isTrue);
+ final rename = f.connection.server.posts
+ .map((post) => post['command'] as Map)
+ .singleWhere((command) => command['type'] == 'tab.rename');
+ expect(rename['name'], 'Swarm');
+ },
+ );
+ test(
+ 'a new private project keeps the swarm and its other conversations',
+ () async {
+ final f = SuperTabLaunchFixture();
+ f.connection.server.state['name'] = 'Company';
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final localId = f.app.activeSwarmId;
+ final box = await f.box(newProject: true);
+ expect(box.actionLabel, 'New project');
+ box.integration!.projectVisibility = 'private';
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(f.app.swarms, hasLength(1));
+ expect(f.app.activeSwarmId, localId);
+ expect(f.app.activeSwarm.name, 'Company');
+ final c = f.app.superTabs.peek(tabId)!;
+ final project = c.snapshot!.projects.last;
+ expect(project.isPrivate, isTrue);
+ expect(c.selectedId, project.leadConversationId);
+ expect(c.snapshot!.conversation('offline'), isNotNull);
+ expect(
+ f.connection.joins.single['command'],
+ containsPair('conversationId', project.leadConversationId),
+ );
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ expect(
+ f.connection.calls.where((c) => c.$2['path'] == '/api/super-tabs'),
+ isEmpty,
+ );
+ },
+ );
+
+ test(
+ 'a lost project creation reply keeps its visibility and original receipt',
+ () async {
+ final f = SuperTabLaunchFixture();
+ f.connection.server.state['name'] = 'Company';
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ f.connection.server.loseReply = true;
+ final box = await f.box(newProject: true);
+ box.integration!.projectVisibility = 'private';
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.integration!.projectVisibilityLocked, isTrue);
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ final resumed = await f.box(newProject: true);
+ expect(resumed.integration!.projectVisibility, 'private');
+ expect(resumed.integration!.projectVisibilityLocked, isTrue);
+ expect(
+ await resumed.create(),
+ NewHarnessOutcome.created,
+ reason: resumed.error,
+ );
+ final creations = f.connection.server.posts
+ .where((p) => (p['command'] as Map)['type'] == 'project.create')
+ .toList();
+ expect(creations, hasLength(2));
+ expect(creations[0], creations[1]);
+ expect(f.app.superTabs.peek(tabId)!.snapshot!.projects, hasLength(2));
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ },
+ );
test('switching accounts while files are being sent closes the background writer', () async {
final f = SuperTabLaunchFixture()..connection.changeAccountOnUpload = true;
final files = HarnessAttachments()
@@ -465,7 +607,7 @@ void main() {
final f = SuperTabLaunchFixture()..connection.nativeName = 'hi';
final initialTab = f.app.activeSwarmId;
final box = await f.box(engine: engine);
- expect(box.actionLabel, 'New Super Tab');
+ expect(box.actionLabel, 'New Swarm');
expect(
await box.create(),
NewHarnessOutcome.created,
diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dart
index a80643121..d7ca07112 100644
--- a/desktop/test/super_tab_machines_test.dart
+++ b/desktop/test/super_tab_machines_test.dart
@@ -60,6 +60,7 @@ void main() {
f.connection.server.state['project'] = {
'machineId': 'm',
'cwd': '/work/project',
+ 'scope': 'swarm',
'repositoryUrl': null,
};
final c = await f.app.superTabs.open(tabId);
@@ -97,6 +98,7 @@ void main() {
'machineId': 'm',
'name': f.app.stateOf('m')!.machine.displayName,
'cwd': '/work/project',
+ 'scope': 'swarm',
'engines': ['claude', 'codex', 'pi'],
'maxAgents': 4,
});
diff --git a/desktop/test/super_tab_navigation_test.dart b/desktop/test/super_tab_navigation_test.dart
index 157a9f25e..831195237 100644
--- a/desktop/test/super_tab_navigation_test.dart
+++ b/desktop/test/super_tab_navigation_test.dart
@@ -7,7 +7,7 @@ import 'swarm_state_test.dart' show createApp;
void main() {
test(
- 'a successful recent open consumes only the empty Super Tab draft',
+ 'a successful recent open consumes only the empty Swarm draft',
() async {
final app = createApp();
addTearDown(app.dispose);
@@ -32,7 +32,7 @@ void main() {
},
);
- test('a disappeared recent result preserves the Super Tab draft', () async {
+ test('a disappeared recent result preserves the Swarm draft', () async {
final app = createApp();
addTearDown(app.dispose);
final draft = app.activeSwarm;
@@ -54,7 +54,7 @@ void main() {
expect(app.swarms, hasLength(1));
});
- test('ordinary new-tab allocation never consumes a Super Tab draft', () {
+ test('ordinary new-tab allocation never consumes a Swarm draft', () {
final app = createApp();
addTearDown(app.dispose);
final draft = app.activeSwarm;
@@ -71,7 +71,7 @@ void main() {
HarnessPlacement.newTab,
]) {
test(
- 'ordinary search from a completed Super Tab uses its own canvas ($placement)',
+ 'ordinary search from a completed Swarm uses its own canvas ($placement)',
() async {
final app = createApp();
addTearDown(app.dispose);
diff --git a/desktop/test/super_tab_picker_test.dart b/desktop/test/super_tab_picker_test.dart
index eaefd31b7..c7e603484 100644
--- a/desktop/test/super_tab_picker_test.dart
+++ b/desktop/test/super_tab_picker_test.dart
@@ -337,7 +337,7 @@ void main() {
expect(f.connection.joins.single['command'], containsPair('lead', false));
expect(f.app.swarms, hasLength(1));
expect(f.app.panes, isEmpty);
- // A successful join clears its journal; it was never a new Super Tab.
+ // A successful join clears its journal; it was never a new Swarm.
expect(
f.store.values.entries
.where((entry) => entry.key.startsWith('super_tab.launch.'))
diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dart
index 7208b8cc1..686d3b0c7 100644
--- a/desktop/test/super_tab_view_test.dart
+++ b/desktop/test/super_tab_view_test.dart
@@ -81,7 +81,7 @@ void main() {
);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
- await tester.tap(find.byTooltip('Workgroup options'));
+ await tester.tap(find.byTooltip('Project options'));
await tester.pumpAndSettle();
await tester.tap(find.text('Archived conversations'));
await tester.pumpAndSettle();
@@ -155,6 +155,8 @@ void main() {
await tester.tap(find.byTooltip('Conversations'));
await tester.pumpAndSettle();
}
+ await tester.tap(find.byKey(const ValueKey('super-project-expand-lead')));
+ await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-group-offline')));
await tester.pumpAndSettle();
expect(controller.selectedId, 'offline');
@@ -206,6 +208,8 @@ void main() {
expect(server.posts, isEmpty);
await tester.tap(find.byTooltip('Conversations'));
await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-project-expand-lead')));
+ await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('super-group-offline')));
await tester.pumpAndSettle();
expect(controller.selectedId, 'offline');
@@ -219,7 +223,7 @@ void main() {
);
testWidgets(
- 'flat sidebar keeps local actions in its footer without repeating the app tab name',
+ 'projects stay collapsed and creation stays in the sidebar footer',
(tester) async {
await tester.binding.setSurfaceSize(const Size(1100, 700));
addTearDown(() => tester.binding.setSurfaceSize(null));
@@ -240,12 +244,12 @@ void main() {
),
);
await tester.pumpAndSettle();
- expect(find.text('Pilot'), findsNothing);
+ expect(find.text('Pilot'), findsNWidgets(2));
expect(find.text('CHATS'), findsNothing);
expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);
- expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
expect(find.text('New group'), findsNothing);
- expect(find.byTooltip('Super Tab settings'), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-new-project')), findsOneWidget);
expect(find.byTooltip('Invite people'), findsOneWidget);
expect(
tester.getCenter(find.byTooltip('Invite people')).dx,
@@ -264,6 +268,7 @@ void main() {
final server = ConversationServer();
final controller = server.controller();
await controller.refresh();
+ controller.select('offline');
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
diff --git a/desktop/test/super_tab_workspace_test.dart b/desktop/test/super_tab_workspace_test.dart
index e8a863671..bebf914ee 100644
--- a/desktop/test/super_tab_workspace_test.dart
+++ b/desktop/test/super_tab_workspace_test.dart
@@ -26,6 +26,7 @@ void main() {
},
];
(state['conversations'] as List)[1]['agentIds'] = ['a', 'b', 'c', 'd'];
+ (state['conversations'] as List)[0]['agentIds'] = ['b'];
f.app.machineStates['m']!.agents = [
for (final id in ['a', 'b', 'c', 'd'])
Agent.fromJson({
@@ -114,6 +115,26 @@ void main() {
),
isEmpty,
);
+ // The global roster asks for context when a session belongs to more
+ // than one workgroup. The needs-human action above already knew its
+ // group and opened the waiting pane directly.
+ tester
+ .widget<SuperTabView>(find.byType(SuperTabView))
+ .onChooseAgentTerminal!(c.snapshot!.agent('b')!);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('super-agent-group-lead')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('super-agent-group-offline')),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const ValueKey('super-agent-group-lead')));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ expect(f.app.activeSwarm.panes.single.agentId, 'native-b');
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
await tester.pumpWidget(const SizedBox());
await c.flush();
f.app.superTabs.dispose();
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index cd3cc2911..b8e13dc91 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -14,6 +14,21 @@ Map<String, dynamic> conversationFixture(String id, String title) => {
'lastMessageSequence': 0,
};
+Map<String, dynamic> projectFixture(
+ String id,
+ String name,
+ String leadConversationId, {
+ String visibility = 'public',
+}) => {
+ 'id': id,
+ 'name': name,
+ 'ownerId': 'owner',
+ 'leadConversationId': leadConversationId,
+ 'visibility': visibility,
+ 'members': <dynamic>[],
+ 'updateMinutes': 5,
+};
+
class ConversationServer {
int revision = 0;
bool loseReply = false, reject = false, failSave = false, failReads = false;
@@ -99,10 +114,54 @@ class ConversationServer {
} else if (command['type'] == 'conversation.create') {
revision++;
final id = 'group-$revision';
- (state['conversations'] as List).add(
- conversationFixture(id, command['title'] as String),
- );
+ (state['conversations'] as List).add({
+ ...conversationFixture(id, command['title'] as String),
+ 'projectId': command['projectId'] ?? 'lead',
+ });
output['conversationId'] = id;
+ } else if (command['type'] == 'project.create') {
+ revision++;
+ final projects = state['projects'] ??= <dynamic>[
+ projectFixture('lead', state['name'] as String, 'lead'),
+ ];
+ final id = 'project-$revision', leadId = 'lead-$revision';
+ (projects as List).add(
+ projectFixture(
+ id,
+ command['name'] as String,
+ leadId,
+ visibility: command['visibility'] as String,
+ ),
+ );
+ (state['conversations'] as List).add({
+ ...conversationFixture(leadId, 'Lead'),
+ 'projectId': id,
+ 'brief': command['brief'] ?? '',
+ });
+ output.addAll({'projectId': id, 'conversationId': leadId});
+ } else if ([
+ 'project.rename',
+ 'project.cadence',
+ 'project.sharing',
+ ].contains(command['type'])) {
+ final project = (state['projects'] as List?)
+ ?.cast<Map<String, dynamic>>()
+ .where((p) => p['id'] == command['projectId'])
+ .firstOrNull;
+ if (project != null) {
+ if (command['type'] == 'project.rename') {
+ project['name'] = command['name'];
+ } else if (command['type'] == 'project.cadence') {
+ project['updateMinutes'] = command['minutes'];
+ } else {
+ project['visibility'] = command['visibility'];
+ project['members'] = [
+ for (final id in command['memberIds'] as List)
+ {'id': id, 'generation': 'fixture'},
+ ];
+ }
+ revision++;
+ }
}
final result = {'revision': revision, 'result': output};
receipts[operationId] = result;
diff --git a/desktop/test/support/workspace_tools.dart b/desktop/test/support/workspace_tools.dart
index 8641e86aa..ba6554fda 100644
--- a/desktop/test/support/workspace_tools.dart
+++ b/desktop/test/support/workspace_tools.dart
@@ -12,7 +12,7 @@ Future<void> openWorkspaceTool(WidgetTester tester, String tool) async {
'store' => LogicalKeyboardKey.keyS,
_ => LogicalKeyboardKey.keyP,
};
- await key(tester, shortcut, cmd: true);
+ await key(tester, shortcut, cmd: true, ctrl: tool == 'store');
await tester.pump(const Duration(milliseconds: 350));
}
diff --git a/desktop/test/swarm_launch_recovery_test.dart b/desktop/test/swarm_launch_recovery_test.dart
new file mode 100644
index 000000000..7c39479c2
--- /dev/null
+++ b/desktop/test/swarm_launch_recovery_test.dart
@@ -0,0 +1,112 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/harness_launch_integration.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture;
+
+void main() {
+ for (final resend in [false, true]) {
+ testWidgets(
+ 'uncertain Swarm files require an explicit resend=$resend choice',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ final choices = <bool>[];
+ var created = 0;
+ final integration = HarnessLaunchIntegration(
+ creationId: 'file-review',
+ prepare: (_, task) async => task,
+ complete: (_, _) async {},
+ beforeSubmit: (_, _) async {},
+ needsAttachmentReview: () => true,
+ resolveAttachments: (resend) async => choices.add(resend),
+ )..pending = true;
+ final box = NewHarnessController(
+ f.app,
+ machineId: 'm',
+ engine: 'claude',
+ folder: '/work/project',
+ integration: integration,
+ );
+ addTearDown(box.dispose);
+ await tester.binding.setSurfaceSize(const Size(1200, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 850,
+ height: 500,
+ child: NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onClose: () {},
+ onCreated: () => created++,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Review files'));
+ await tester.pumpAndSettle();
+ expect(find.text('Check file delivery'), findsOneWidget);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(choices, isEmpty);
+ expect(created, 0);
+ await tester.tap(find.text('Review files'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text(resend ? 'Send again' : 'Already sent'));
+ await tester.pumpAndSettle();
+ expect(choices, [resend]);
+ expect(created, 1);
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ isEmpty,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ test(
+ 'a Swarm rejects a terminal-only lead before creating a native session',
+ () async {
+ final f = SuperTabLaunchFixture();
+ final box = await f.box(engine: 'terminal');
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('Choose an agent that runs on a machine'));
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ },
+ );
+
+ test(
+ 'failure to persist staged Swarm files prevents native launch',
+ () async {
+ final f = SuperTabLaunchFixture();
+ final box = NewHarnessController(
+ f.app,
+ machineId: 'm',
+ engine: 'claude',
+ folder: '/work/project',
+ integration: HarnessLaunchIntegration(
+ creationId: 'stage-files',
+ prepare: (_, task) async => task,
+ beforeSubmit: (_, _) async {},
+ complete: (_, _) async {},
+ stageAttachments: (_, _) async =>
+ throw StateError('Cannot save staged files'),
+ ),
+ );
+ addTearDown(box.dispose);
+ await pumpEventQueue();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('Cannot save staged files'));
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ },
+ );
+}
diff --git a/desktop/test/swarm_projects_test.dart b/desktop/test/swarm_projects_test.dart
new file mode 100644
index 000000000..b26709f3a
--- /dev/null
+++ b/desktop/test/swarm_projects_test.dart
@@ -0,0 +1,242 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/super_tabs/view.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/project_visibility.dart';
+
+import 'support/super_tab_fixture.dart';
+
+ConversationServer projectsServer() {
+ final server = ConversationServer();
+ server.state['name'] = 'Company';
+ server.state['projects'] = [
+ projectFixture('lead', 'Lamp OS', 'lead'),
+ projectFixture('design', 'Design', 'design-lead', visibility: 'private'),
+ ];
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('design-lead', 'Lead'),
+ 'projectId': 'design',
+ });
+ (server.state['conversations'] as List)[1]['number'] = 12;
+ return server;
+}
+
+void main() {
+ Future<void> mount(
+ WidgetTester tester,
+ SuperTabController c, {
+ VoidCallback? onNewProject,
+ }) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ onNewProject: onNewProject,
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> unmount(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ }
+
+ testWidgets(
+ 'project names open lead chats; chevrons independently reveal numbered workgroups',
+ (tester) async {
+ final server = projectsServer(), c = server.controller();
+ var creations = 0;
+ await mount(tester, c, onNewProject: () => creations++);
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
+ expect(find.byIcon(AppIcons.lock), findsOneWidget);
+ expect(find.text('Leads'), findsNothing);
+ expect(find.text('Humans'), findsOneWidget);
+ expect(find.text('Agents'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('super-project-expand-lead')));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ expect(find.text('#12 Offline editing'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'offline');
+ await tester.tap(find.byKey(const ValueKey('super-group-design-lead')));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'design-lead');
+ expect(c.expandedProjects, {'lead'});
+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ await tester.tap(find.byKey(const ValueKey('super-new-project')));
+ expect(creations, 1);
+ expect(server.posts, isEmpty);
+ expect(tester.takeException(), isNull);
+ await unmount(tester, c);
+ },
+ );
+
+ testWidgets('project pull requests include its workgroups and stay scoped', (
+ tester,
+ ) async {
+ final server = projectsServer(), c = server.controller();
+ server.append(
+ 'Ready: https://github.com/example/lamp/pull/12',
+ conversationId: 'offline',
+ );
+ server.append(
+ 'Design: https://github.com/example/design/pull/8',
+ conversationId: 'design-lead',
+ );
+ await mount(tester, c);
+ await tester.tap(find.byTooltip('Pull requests'));
+ await tester.pumpAndSettle();
+ expect(find.text('example/lamp #12'), findsOneWidget);
+ expect(find.text('example/design #8'), findsNothing);
+ expect(find.text('This project'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('super-group-design-lead')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byTooltip('Pull requests'));
+ await tester.pumpAndSettle();
+ expect(find.text('example/design #8'), findsOneWidget);
+ expect(find.text('example/lamp #12'), findsNothing);
+ await unmount(tester, c);
+ });
+
+ testWidgets('a collapsed project keeps its workgroup attention visible', (
+ tester,
+ ) async {
+ final server = projectsServer(), c = server.controller();
+ server.state['agents'] = [
+ {
+ 'id': 'worker',
+ 'name': 'Builder',
+ 'machineId': 'm',
+ 'harnessId': 'native',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ final group = (server.state['conversations'] as List)[1] as Map;
+ group['agentIds'] = ['worker'];
+ group['assignment'] = {'status': 'needs_human', 'agentId': 'worker'};
+ await mount(tester, c);
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-group-lead')),
+ matching: find.byTooltip('Needs a human'),
+ ),
+ findsOneWidget,
+ );
+ await unmount(tester, c);
+ });
+
+ testWidgets('compact project menu changes cadence for only that project', (
+ tester,
+ ) async {
+ final server = projectsServer(), c = server.controller();
+ await mount(tester, c);
+ await tester.tap(find.byTooltip('Project options'));
+ await tester.pumpAndSettle();
+ expect(find.byIcon(AppIcons.ellipsisVertical), findsOneWidget);
+ await tester.tap(find.text('Update cadence'));
+ await tester.pumpAndSettle();
+ expect(find.text('Every 5 minutes'), findsOneWidget);
+ await tester.tap(find.byType(DropdownButton<int>));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Every 15 minutes').last);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(server.posts.single['command'], {
+ 'type': 'project.cadence',
+ 'projectId': 'lead',
+ 'minutes': 15,
+ });
+ expect(c.snapshot!.projectFor('lead')!.updateMinutes, 15);
+ expect(c.snapshot!.projectFor('design-lead')!.updateMinutes, 5);
+ await unmount(tester, c);
+ });
+
+ testWidgets(
+ 'public means swarm members and private is an explicit project choice',
+ (tester) async {
+ var visibility = 'public';
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: StatefulBuilder(
+ builder: (context, setState) => ProjectVisibility(
+ value: visibility,
+ onChanged: (value) => setState(() => visibility = value),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Public'));
+ await tester.pumpAndSettle();
+ expect(find.text('Everyone in this swarm'), findsOneWidget);
+ expect(
+ find.text('Only people you invite to this project'),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Private'));
+ await tester.pumpAndSettle();
+ expect(visibility, 'private');
+ expect(find.text('Private'), findsOneWidget);
+ expect(find.byIcon(AppIcons.lock), findsOneWidget);
+ },
+ );
+
+ test('project revocation removes cached text, drafts, terminals and expanded state', () async {
+ final server = projectsServer(), c = server.controller();
+ server.append('Private design', conversationId: 'design-lead');
+ await c.refresh();
+ await c.loadMessages('design-lead');
+ c.select('design-lead');
+ c.setDraft('design-lead', 'Private response');
+ c.toggleProject('design');
+ expect(c.messages('design-lead'), hasLength(1));
+ (server.state['projects'] as List).removeLast();
+ (server.state['conversations'] as List).removeLast();
+ server.revision++;
+ await c.refresh();
+ await c.flush();
+ expect(c.selectedId, 'lead');
+ expect(c.messages('design-lead'), isEmpty);
+ expect(c.draft('design-lead'), isEmpty);
+ expect(c.expandedProjects, isNot(contains('design')));
+ expect(
+ (server.saved!['drafts'] as Map).containsKey('design-lead'),
+ isFalse,
+ );
+ c.dispose();
+ });
+
+ test('internal consolidation requests do not appear as chat posts', () async {
+ final server = projectsServer(), c = server.controller();
+ server.append('Internal scheduled request');
+ server.messages.last['source'] = {'kind': 'update-request'};
+ server.append('Verification passed. Review is next.');
+ server.messages.last['source'] = {'kind': 'project-report'};
+ await c.refresh();
+ expect(c.messages('lead').map((m) => m.text), [
+ 'Verification passed. Review is next.',
+ ]);
+ await c.flush();
+ c.dispose();
+ });
+}
diff --git a/desktop/test/toolbar_onboarding_test.dart b/desktop/test/toolbar_onboarding_test.dart
index e9db79013..fe643ad09 100644
--- a/desktop/test/toolbar_onboarding_test.dart
+++ b/desktop/test/toolbar_onboarding_test.dart
@@ -166,7 +166,12 @@ void main() {
LogicalKeyboardKey.keyM,
LogicalKeyboardKey.keyI,
]) {
- await key(tester, shortcut, cmd: true);
+ await key(
+ tester,
+ shortcut,
+ cmd: true,
+ ctrl: shortcut == LogicalKeyboardKey.keyS,
+ );
await tester.pumpAndSettle();
if (shortcut == LogicalKeyboardKey.keyN) {
expect(find.byType(NewHarnessForm), findsOneWidget);
@@ -244,7 +249,7 @@ void main() {
expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true, ctrl: true);
expect(app.activeSwarm.isStore, isTrue);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
await tester.pumpAndSettle();
@@ -326,11 +331,11 @@ void main() {
expect(resourceScope(''), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true, ctrl: true);
expect(app.activeSwarm.isStore, isTrue);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true, ctrl: true);
await tester.pumpAndSettle();
expect(app.activeSwarm.isStore, isTrue);
await key(tester, LogicalKeyboardKey.keyI, cmd: true);
diff --git a/desktop/test/welcome_closed_super_tabs_test.dart b/desktop/test/welcome_closed_super_tabs_test.dart
index e51de77f8..c50b0bd45 100644
--- a/desktop/test/welcome_closed_super_tabs_test.dart
+++ b/desktop/test/welcome_closed_super_tabs_test.dart
@@ -32,13 +32,15 @@ Future<List<String>> _mount(
void main() {
for (final composer in [false, true]) {
final layout = composer ? 'composer' : 'classic';
- testWidgets('$layout welcome lists closed Super Tabs and opens one', (
+ testWidgets('$layout welcome lists closed Swarms and opens one', (
tester,
) async {
final opened = await _mount(tester, composer: composer);
- expect(find.text('Closed Super Tabs'), findsOneWidget);
+ expect(find.text('Closed Swarms'), findsOneWidget);
expect(find.text('Pilot'), findsOneWidget);
- await tester.tap(find.byKey(const ValueKey('welcome-closed-super-tab-tab-2')));
+ await tester.tap(
+ find.byKey(const ValueKey('welcome-closed-super-tab-tab-2')),
+ );
expect(opened, ['tab-2']);
});
@@ -46,7 +48,7 @@ void main() {
tester,
) async {
await _mount(tester, closed: const [], composer: composer);
- expect(find.text('Closed Super Tabs'), findsNothing);
+ expect(find.text('Closed Swarms'), findsNothing);
});
}
}
diff --git a/desktop/test/workspace_account_test.dart b/desktop/test/workspace_account_test.dart
index f544fcc2a..c02626273 100644
--- a/desktop/test/workspace_account_test.dart
+++ b/desktop/test/workspace_account_test.dart
@@ -125,7 +125,7 @@ void main() {
1280 - grid.AppDesktop.tabBarTrailingInset,
);
expect(find.byTooltip('Sign in to Harness'), findsOneWidget);
- expect(find.byTooltip('Explore Harness Store · ⌘S'), findsOneWidget);
+ expect(find.byTooltip('Explore Harness Store · ⌃⌘S'), findsOneWidget);
await _capture(tester, 'tab-row-sign-in');
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
diff --git a/desktop/test/workspace_welcome_test.dart b/desktop/test/workspace_welcome_test.dart
index 03cd0e0a4..57cdc22dd 100644
--- a/desktop/test/workspace_welcome_test.dart
+++ b/desktop/test/workspace_welcome_test.dart
@@ -107,7 +107,7 @@ void main() {
expect(find.text('Harness like a boss.'), findsOneWidget);
expect(find.text('✓'), findsNothing);
expect(find.text('○'), findsNothing);
- for (final hint in ['⌘N', '⌘P', '⌘I', '⌘M', '⌘S']) {
+ for (final hint in ['⌘N', '⌘P', '⌘I', '⌘M', '⌃⌘S']) {
expect(find.text(hint), findsOneWidget);
}
expect(find.text('⌘O'), findsNothing);
diff --git a/desktop/tool/keymap_native_checks.swift b/desktop/tool/keymap_native_checks.swift
index 40d72e911..11e420a87 100644
--- a/desktop/tool/keymap_native_checks.swift
+++ b/desktop/tool/keymap_native_checks.swift
@@ -25,7 +25,7 @@ try checkKeymap(changed.match([stroke("down")], context: "project").binding == n
for (key, command) in [
("cmd+left", "pane.focus_left"), ("cmd+down", "pane.focus_below"),
("cmd+up", "pane.focus_above"), ("cmd+right", "pane.focus_right"),
- ("cmd+s", "app.store"), ("cmd+shift+l", "pane.layout"),
+ ("cmd+ctrl+s", "app.store"), ("cmd+s", "super_tab.new"), ("cmd+shift+l", "pane.layout"),
("cmd+b", "task.route"), ("cmd+t", "swarm.new"),
("cmd+p", "harnesses.list"), ("cmd+o", "agent.open"), ("cmd+shift+p", "navigation.commands"),
("cmd+r", "pane.split_right"), ("cmd+d", "pane.split_down"),
@@ -57,9 +57,11 @@ for context in HarnessNativeKeymap.contexts {
"Command-U has no default workspace action")
try checkKeymap(defaults.match([stroke("cmd+y")], context: context).binding == nil,
"Command-Y has no default workspace action")
- let store = defaults.match([stroke("cmd+s")], context: context).binding
- try checkKeymap(store?.command == "app.store" && store?.menuAction == "store" && store?.hint == "⌘S",
- "Command-S opens Store with the matching native action and hint")
+ let store = defaults.match([stroke("cmd+ctrl+s")], context: context).binding
+ try checkKeymap(store?.command == "app.store" && store?.menuAction == "store" && store?.hint == "⌃⌘S",
+ "Control-Command-S opens Store with the matching native action and hint")
+ try checkKeymap(defaults.match([stroke("cmd+s")], context: context).binding?.command == "super_tab.new",
+ "Command-S opens New Swarm from \(context)")
try checkKeymap(defaults.match([stroke("cmd+o")], context: context).binding?.command == "agent.open",
"Command-O opens the project picker")
try checkKeymap(defaults.match([stroke("cmd+shift+n")], context: context).binding?.command == "agent.clone",
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 714cb60ba..181b9a1c8 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -1407,7 +1407,7 @@ private extension SwarmTabStrip {
func checkTopActions() throws {
var state: [String: Any] = ["enabled": true,
- "searchTooltip": "Open Harness · ⌘P", "addPhoneTooltip": "Add Phone", "storeTooltip": "Explore Harness Store · ⌘S",
+ "searchTooltip": "Open Harness · ⌘P", "addPhoneTooltip": "Add Phone", "storeTooltip": "Explore Harness Store · ⌃⌘S",
"tabs": [["id": "work", "name": "Desktop"]], "activeId": "work",
"focusedContext": ["text": "Office project", "segments": [["text": "Office project"]]]]
var calls: [String] = []
diff --git a/docs/images/swarms/projects.png b/docs/images/swarms/projects.png
new file mode 100644
index 000000000..33508470e
Binary files /dev/null and b/docs/images/swarms/projects.png differ
diff --git a/docs/keyboard.md b/docs/keyboard.md
index 43201baf9..05abd8c66 100644
--- a/docs/keyboard.md
+++ b/docs/keyboard.md
@@ -9,24 +9,25 @@ The defaults, in the workspace:
| Keys | Action |
|---|---|
-| ⌘T | New Swarm — opens the same quiet welcome page shown at startup. Use ⌘N to create a harness, ⌘P to open one, or ⌘S for the store |
+| ⌘T | New tab — opens the same quiet welcome page shown at startup. Use ⌘N to create a harness, ⌘P to open one, or ⌃⌘S for the Store |
| ⌘O / Ctrl+O (Linux) | Open Project — the unified picker starts in projects (`#`), with projects containing open panes first and alphabetical order within each group |
| ⌘P / Ctrl+P (Linux) | Open Harness — the unified picker for harnesses, machines (`@`), projects (`#`), agents (`&`), models (`:`), and Store (`*`). Opens in the current tab and tiles its panes, or focuses the harness if already here |
| ⇧⌘P / Ctrl+Shift+P (Linux) | Search commands; from a selected picker result, search actions for that item |
| ⌘R / ⌘D | Split right / down — open the New Pane picker with the requested direction, then choose an existing harness or create one |
| ⌘N | New Harness — choose an Agent or Harness, Project, and Options, then activate New Harness. Lists filter as you type; Return chooses and Escape returns to the form. Project accepts a folder, a new project name, or a repository. Options include model, permissions, agent profile, branch, and worktree |
| ⌘B | Boss mode: describe a task, it picks the harness |
-| ⌘W · ⇧⌘R | Close swarm · rename swarm |
+| ⌘W · ⇧⌘R | Close tab · rename tab |
| ⇧⌘T | New terminal in the current project |
| ⇧⌘N | Clone Harness — another harness like the focused pane's (same machine, project, harness, Codex profile, permission mode, named agent) with a fresh conversation. No dialog; fork minus the context |
-| ⇧⌘E | Restart Harness — the focused pane's harness starts again in place, resuming its conversation where the engine can. Asks first; the pane, its folder and its settings stay. (Not ⇧⌘R: that renames the swarm) |
-| ⌘1 … ⌘9 | Select swarm by position |
-| ⇧⌘] · ⇧⌘[ · ⌃Tab · ⌃⇧Tab | Next · previous swarm |
+| ⇧⌘E | Restart Harness — the focused pane's harness starts again in place, resuming its conversation where the engine can. Asks first; the pane, its folder and its settings stay. (Not ⇧⌘R: that renames the tab) |
+| ⌘1 … ⌘9 | Select tab by position |
+| ⇧⌘] · ⇧⌘[ · ⌃Tab · ⌃⇧Tab | Next · previous tab |
| ⌘] · ⌘[ · ⌘Y | Forward · back through visited harnesses · full history |
| ⌘H ⌘J ⌘K ⌘L · ⌘arrows | Focus the pane left · below · above · right |
| ⇧⌘arrows | Move the focused pane |
| ⌘⏎ · ⌘; · ⇧⌘W | Zoom or restore · last pane · close pane |
-| ⌘S | Harness Store |
+| ⌘S | New Swarm — the lead creation form, with engine, machine, project and project visibility |
+| ⌃⌘S | Harness Store |
| ⌘M | Machines — connect another computer or set this computer's password |
| ⌘I | Models — subscriptions, local models, shared models, and APIs |
| ⇧⌘L | Layout palette |
@@ -35,11 +36,11 @@ The defaults, in the workspace:
| ⇧⌘I | Harnesses needing input |
| ⌘, · ⌘/ | Settings · keyboard shortcuts |
-First launch and every New Swarm show the same “Follow your curiosity.” page with
+First launch and every new regular tab show the same “Follow your curiosity.” page with
three clickable shortcuts: ⌘N to start a new harness, ⌘P to open a harness, and
-⌘S to browse the harness store. The hints follow the current keyboard bindings.
+⌃⌘S to browse the Harness Store. The hints follow the current keyboard bindings.
-A harness can have views in several swarms, with one view per swarm; closing a pane only removes that view.
+A harness can have views in several regular tabs, with one view per tab; closing a pane only removes that view.
The view closes immediately, without a minimize animation.
Cmd-P opens an empty search field. Cmd-O inserts an editable `#` for projects.
diff --git a/docs/naming-system.md b/docs/naming-system.md
index 2b6357ee1..d7204f6ac 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -53,7 +53,9 @@ and **Browser**. Technical documentation may still call the terminal interface a
| **A harness** in the workspace | A running agent session with its own conversation and working context. | Start three Codex harnesses. |
| **A harness** in the Store | A reusable setup containing agent instructions, tools, and an optional viewer. | Install the Blender harness. |
| **Tab** | A workspace group of harnesses. | Frontend and Backend tabs. |
-| **Super Tab** | A collaborative tab with a lead, member agents and shared conversations. | Discuss the plan with the lead, then follow work in its group conversations. |
+| **Swarm** | An invite-only collaborative tab containing projects, people, agents and contributed machines. | Open your company Swarm beside your regular tabs. |
+| **Project in a Swarm** | An initiative with its own lead, repository, sharing and workgroups. | Discuss Lamp OS with its lead; expand it to follow a workgroup. |
+| **Workgroup** | A numbered conversation for an independently assignable outcome within a project. | Follow #12 Offline editing. |
| **Pane** | A visible view of a harness, terminal, or viewer. | Split right; close pane. |
| **Terminal** | A shell for entering commands. | New terminal. |
| **Project** | The files and working context for the work, on a particular computer. | Choose the website project. |
@@ -79,11 +81,16 @@ no CLI keeps its maker's name (Fo).
A pane is a view, so closing a pane or tab closes views. **Stop Harness** ends the
running harness. Adding harnesses to a tab groups them without a separate team
-setup. **Super Tab** adds shared conversations and coordination across explicitly contributed agents;
-people and agents participate in the same flat conversation list. Its creation flow is experimental
-and hidden during initial validation. Existing tabs keep their behavior. The older **Agent Messages**
-protocol (`harness send`) and stored account settings remain compatible, while Super Tab owns its
-coordination controls. The word *tab* can also name the keyboard key or a browser tab; context
+setup. A **Swarm** occupies one tab in that same tab bar. A person can belong to several Swarms.
+Its project names open their lead chats; a separate chevron reveals each project's workgroups.
+People, agents and machines belong to the Swarm. A project's **Public** visibility means everyone
+in that Swarm; **Private** means its owner and explicitly invited project members. Swarms themselves
+are invite-only. Public communities and a compute marketplace are outside this version.
+Cmd-S opens the existing lead creation form for a new Swarm and its first project; **+ Project**
+reuses that form inside the current Swarm. Store uses Cmd-Control-S. Existing ordinary tabs keep
+their behavior. The internal `superTab` identifiers, `harness super-tab` protocol and stored account
+settings remain compatible; the older internal `Swarm` layout class still represents an ordinary
+workspace tab. The word *tab* can also name the keyboard key or a browser tab; context
distinguishes them.
A project belongs to a computer; identical paths on different computers do not
diff --git a/docs/swarms.md b/docs/swarms.md
new file mode 100644
index 000000000..15a8d056e
--- /dev/null
+++ b/docs/swarms.md
@@ -0,0 +1,102 @@
+# Private Swarms
+
+A Swarm is an invite-only collaborative tab. Regular tabs and multiple Swarms
+share the existing tab bar. Each Swarm contains projects, people, agents and
+contributed machines.
+
+![A project lead chat, expandable workgroups and shared resources](images/swarms/projects.png)
+
+This screenshot uses fixture conversations and resources.
+
+## Starting work
+
+Press **Cmd-S** to create a Swarm and its first project. The form reuses New
+Harness: choose the engine, machine, repository and existing launch settings,
+write the request, and choose the project's visibility. Store uses
+**Cmd-Control-S**.
+
+Use **+ Project** in the left sidebar to create another project in the current
+Swarm. It uses the same form and creates a separate lead session. Clicking a
+project name opens its lead chat. Its chevron expands numbered workgroups.
+The lead can create and coordinate those workgroups; people usually work
+through the project lead.
+
+The center toolbar switches between chat, terminals and pull requests. The
+project's vertical menu contains rename, details, sharing, update cadence and
+Swarm routing. A workgroup keeps its own details, rename and archive actions.
+Pull requests in a project lead view include that project's workgroups.
+
+## People, agents and machines
+
+The right roster belongs to the Swarm, with Humans, Agents and Machines sections.
+Each section's plus button has one purpose:
+
+- Humans invites a person to the Swarm.
+- Agents contributes an existing or newly created agent to the selected project
+ and conversation.
+- Machines lets an owner contribute a machine's available engines and signed-in
+ accounts to the Swarm.
+
+A machine contribution is a workspace grant for this Swarm. The host prepares
+each project's repository before starting an agent. A project on another
+machine needs a shared GitHub repository; a local-only folder is not silently
+replaced with an unrelated directory.
+
+Ordinary guest machine sharing does not authorize Swarm controls under the
+owner's account. The owner contributes the machine or an agent. The lead's
+routing policy still determines eligible engines, capacity and model choices.
+
+Clicking an agent with one workgroup opens its terminal. If it participates in
+several, choose the workgroup and focus the same session there. A needs-human
+message already identifies its workgroup and opens the waiting terminal
+directly. Terminal question forms remain in the terminal.
+
+## Project access
+
+**Public** means every member of this invite-only Swarm. **Private** means the
+project owner and selected current Swarm members. Public communities and paid
+compute sharing are deferred.
+
+Project access is enforced for state, messages, commands, replayed receipts,
+work attempts, routing decisions and native terminal access. Removing access
+also clears the Desktop's cached project messages, drafts and terminal references.
+Leaving and rejoining a Swarm does not restore an old private-project invitation.
+
+An agent can participate in several workgroups within one project. Another
+project uses a separate session: exposing the same terminal would expose its
+history. Historical session bindings also prevent a previously shared terminal
+from being reused for private work after removal.
+
+Private projects control application access. Contributing machine owners are
+trusted execution hosts and can access work running on their computers.
+
+## Lead updates
+
+The default update cadence is five minutes; the project menu also offers one,
+fifteen and thirty minutes. New workgroup reports mark the project for an update.
+The existing delivery poll asks its lead to consolidate those reports at its
+next natural checkpoint. Idle projects do not generate scheduled updates, and
+an outstanding request prevents duplicates.
+
+The lead uses `project.report` to acknowledge the request and post a useful
+summary, or `text: null` when nothing merits another message. Human questions,
+serious blockers and completion are reported immediately. This does not start
+a second summarizing model or forward every terminal turn.
+
+## Compatibility and rollout
+
+The internal `superTab` storage keys and `harness super-tab` command stay stable.
+Existing tabs are read as a single project without rewriting their conversation
+IDs or messages. Existing regular tabs retain their behavior.
+
+Use the matching backend, CLI and Desktop versions together for this feature:
+
+1. Generate the backend Prisma client and apply its additive schema, including
+ `SuperTabSessionScope`, before serving the new project commands.
+2. Update participating hosts to the CLI with Swarm-scoped contributions and
+ project checkout preparation.
+3. Install the Desktop build with the project sidebar and Cmd-S entry point.
+
+A signed internal Desktop artifact alone does not update the backend or host
+CLI. Validate the coordinated versions in an internal environment before a
+public Desktop release.