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.

Merge batch 11-03 bd: #2669 #2668 (#2674)

0xken15396e83f02450
diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.ts
index 6e6f33893..01adaf6d3 100644
--- a/backend/integration/superTabNotAvailable.test.ts
+++ b/backend/integration/superTabNotAvailable.test.ts
@@ -13,7 +13,7 @@ import { MemoryAttachmentStore, MemoryAvatarStore } from '../src/superTabs/attac
import type { Command } from '../src/superTabs/commands.js'
import { SwarmReads } from '../src/superTabs/read/service.js'
import { errorHandler } from '../src/middlewares/errorHandler.js'
-import { NOT_AVAILABLE, NOT_AVAILABLE_ROUTES, superTabRoutes } from '../src/routes/superTabs.js'
+import { NOT_AVAILABLE, superTabRoutes } from '../src/routes/superTabs.js'
// The person routes through the real store and read service (Huy, 10-30, the follow-up of #2306): a Swarm, chat, project,
// decision, file or link the caller cannot reach gets one answer, whether it is missing, refused, revoked or in another
@@ -21,6 +21,7 @@ import { NOT_AVAILABLE, NOT_AVAILABLE_ROUTES, superTabRoutes } from '../src/rout
let replica: MongoMemoryReplSet
let db: PrismaClient
let app: FastifyInstance
+const registeredPersonRoutes = new Set<string>()
let store: SuperTabStore
const user = (n: number, name: string): AuthUser => ({ sub: `40000000000000000000000${n}`, email: `${name}@example.com`, autonomousEnv: 'prod', role: 'user' })
const owner = user(1, 'owner'), member = user(2, 'member'), outsider = user(3, 'outsider'), removed = user(4, 'removed')
@@ -38,6 +39,10 @@ beforeAll(async () => {
store = new SuperTabStore(db, () => Date.now(), { store: new MemoryAttachmentStore(), prefix: 'super-tabs', publicBase: 'https://cdn.example.test',
avatars: new MemoryAvatarStore('https://avatars.example.test') })
app = Fastify()
+ app.addHook('onRoute', route => {
+ if (!/^\/api\/super-tabs\/:tabId(?:\/|$)/.test(route.url)) return
+ for (const method of [route.method].flat()) if (method !== 'HEAD') registeredPersonRoutes.add(`${method} ${route.url}`)
+ })
app.setErrorHandler(errorHandler)
app.addHook('onRequest', async request => { request.user = users.get(String(request.headers['x-user'])) as never })
await app.register(superTabRoutes, { store, reads: new SwarmReads(store), github: null, hosts: {} as never, signIn: null,
@@ -81,6 +86,8 @@ function calls(tab: string, chat: string, project: string) {
json('GET', 'GET /api/super-tabs/:tabId/parts', `${t}/parts`),
json('GET', 'GET /api/super-tabs/:tabId/parts', `${t}/parts?asAgentId=${MISSING}`),
json('GET', 'GET /api/super-tabs/:tabId/changes', `${t}/changes?cursor=abc`),
+ json('GET', 'GET /api/super-tabs/:tabId/activity', `${t}/activity`),
+ json('POST', 'POST /api/super-tabs/:tabId/activity/read', `${t}/activity/read`, { through: '2026-11-01T00:00:00.000Z' }),
json('GET', 'GET /api/super-tabs/:tabId/inbox', `${t}/inbox`),
json('GET', 'GET /api/super-tabs/:tabId/threads', `${t}/threads`),
json('POST', 'POST /api/super-tabs/:tabId/commands', `${t}/commands`,
@@ -101,8 +108,15 @@ function calls(tab: string, chat: string, project: string) {
json('GET', 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages/:messageId/attachments/:attachmentId',
`${t}/conversations/${chat}/messages/${MISSING}/attachments/${MISSING}`),
json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/read', `${t}/conversations/${chat}/read`, { sequence: 1 }),
+ json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/read', `${t}/conversations/${chat}/threads/${MISSING}/read`, { sequence: 1 }),
+ json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/notifications', `${t}/conversations/${chat}/notifications`, { notify: 'all' }),
json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/follow', `${t}/conversations/${chat}/threads/${MISSING}/follow`,
{ follow: true }),
+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/instructions', `${t}/projects/${project}/instructions`),
+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/instructions/revisions', `${t}/projects/${project}/instructions/revisions`),
+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/instructions/revisions/:revision', `${t}/projects/${project}/instructions/revisions/1`),
+ json('POST', 'POST /api/super-tabs/:tabId/attachments/uploads', `${t}/attachments/uploads`, { conversationId: chat, name: 'notes.txt', mime: 'text/plain', size: 12_000_000 }),
+ json('POST', 'POST /api/super-tabs/:tabId/attachments/uploads/:uploadId/complete', `${t}/attachments/uploads/${MISSING}/complete`, {}),
json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/github', `${t}/projects/${project}/github`),
json('POST', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve', `${t}/projects/${project}/github/approve`, { scope: 'project' }),
json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', `${t}/projects/${project}/roles/${MISSING}`),
@@ -149,8 +163,9 @@ describe('a Swarm the caller cannot reach, on every person route', () => {
it('answers one not-available answer: a Swarm that does not exist, one never joined, one left, read with a made-up agent id too', async () => {
const f = await swarm()
const real = calls(f.tab, 'lead', 'lead'), missing = calls(MISSING, 'lead', 'lead')
- // Every person route is called here, so a route added to the list without a test fails.
- expect(new Set(real.map(c => c.route))).toEqual(NOT_AVAILABLE_ROUTES)
+ // Compare against actual registration, so adding a route requires a real refusal test.
+ // The retired full-state read always asks every client to update, without reading a Swarm.
+ expect(new Set([...real.map(c => c.route), 'GET /api/super-tabs/:tabId'])).toEqual(registeredPersonRoutes)
for (const [i, call] of real.entries()) {
const cases = { missing: await answer(missing[i]!, outsider), refused: await answer(call, outsider), revoked: await answer(call, removed) }
// Approving needs the server's GitHub App, which this server has not: it says so to everyone, before any Swarm is read.
@@ -197,6 +212,17 @@ describe('a Swarm the caller cannot reach, on every person route', () => {
}
})
+ it('asks every legacy full-state reader to update without revealing whether the Swarm exists', async () => {
+ const f = await swarm()
+ for (const as of [owner, member, outsider, removed]) {
+ const real = await app.inject({ url: `/api/super-tabs/${f.tab}`, headers: { 'x-user': as.sub } })
+ const missing = await app.inject({ url: `/api/super-tabs/${MISSING}`, headers: { 'x-user': as.sub } })
+ expect(real.statusCode).toBe(426)
+ expect(real.json().error.code).toBe('UPDATE_REQUIRED')
+ expect({ status: real.statusCode, body: real.body }).toEqual({ status: missing.statusCode, body: missing.body })
+ }
+ })
+
it('still reads for a member, and keeps a role refusal\'s own words inside a Swarm they read', async () => {
const f = await swarm()
expect((await answer(calls(f.tab, 'lead', 'lead')[0]!, member)).status).toBe(200)
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index d203e3205..3f88e2582 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -152,29 +152,9 @@ const githubStartToken = z.object({ always: z.boolean().optional() }).strict()
* owner-only) keep their own words: they tell nothing the caller cannot already see. Hosts read 403 and 404 alike as
* access lost (cli superTabs/machines.ts, swarmReads.ts).
*/
-export const NOT_AVAILABLE_ROUTES: ReadonlySet<string> = new Set([
- 'GET /api/super-tabs/:tabId/parts', 'GET /api/super-tabs/:tabId/changes', 'GET /api/super-tabs/:tabId/inbox', 'GET /api/super-tabs/:tabId/threads',
- 'POST /api/super-tabs/:tabId/commands',
- 'GET /api/super-tabs/:tabId/mentions', 'GET /api/super-tabs/:tabId/decisions', 'GET /api/super-tabs/:tabId/leaderboard',
- 'GET /api/super-tabs/:tabId/sharing', 'POST /api/super-tabs/:tabId/sharing', 'GET /api/super-tabs/:tabId/routing-policy',
- 'GET /api/super-tabs/:tabId/groups', 'GET /api/super-tabs/:tabId/groups/:conversationId',
- 'POST /api/super-tabs/:tabId/join', 'POST /api/super-tabs/:tabId/join/preview', 'POST /api/super-tabs/:tabId/native',
- 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages', 'GET /api/super-tabs/:tabId/conversations/:conversationId/catch-up',
- 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages/:messageId/attachments/:attachmentId',
- 'POST /api/super-tabs/:tabId/conversations/:conversationId/read', 'POST /api/super-tabs/:tabId/conversations/:conversationId/threads/:threadId/follow',
- 'GET /api/super-tabs/:tabId/projects/:projectId/github', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve',
- 'GET /api/super-tabs/:tabId/projects/:projectId/ci-load',
- 'GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', 'GET /api/super-tabs/:tabId/route-decisions/:decisionId',
- 'GET /api/super-tabs/:tabId/machines/:machineId/removal',
- 'POST /api/super-tabs/:tabId/attachments', 'POST /api/super-tabs/:tabId/avatars',
- // Reached by any sign-in too (review of #2333): Workspace settings, costs, routing and the host's own reads.
- 'POST /api/super-tabs/:tabId/workspace-visibility', 'POST /api/super-tabs/:tabId/workspace-join', 'GET /api/super-tabs/:tabId/costs',
- 'GET /api/super-tabs/:tabId/route-decisions', 'GET /api/super-tabs/:tabId/starts/:startId',
- 'GET /api/super-tabs/:tabId/conversations/:conversationId/attempts', 'GET /api/super-tabs/:tabId/terminal/:requestId',
- 'GET /api/super-tabs/:tabId/agents/:agentId/deliveries', 'GET /api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',
- 'POST /api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',
- 'GET /api/super-tabs/:tabId/native/:contextId', 'POST /api/super-tabs/:tabId/native/:contextId', 'POST /api/super-tabs/:tabId/github-token',
- 'POST /api/super-tabs/:tabId/machines/:machineId', 'POST /api/super-tabs/:tabId/stopped',
+const NOT_AVAILABLE_EXEMPT_ROUTES: ReadonlyMap<string, string> = new Map([
+ // This retired endpoint never reads a Swarm: all callers must upgrade from full-state reads.
+ ['GET /api/super-tabs/:tabId', 'Always returns UPDATE_REQUIRED without looking up the Swarm.'],
])
/** The one answer on those routes for anything the caller cannot reach. 404 with the code every client already
* reads as gone (Desktop and the phone: FORBIDDEN or NOT_FOUND; the CLI: 403 or 404). */
@@ -192,7 +172,7 @@ const readingsBody = z.object({ readings: z.array(z.object({ tabId: id, observat
.refine(list => new Set(list.map(r => r.tabId)).size === list.length, 'Name each Swarm once.') }).strict()
/** One reading's refusal in a batch, answered as the per-Swarm route answers it: a Swarm the caller cannot reach gets the one
- * NOT_AVAILABLE answer (that route is in NOT_AVAILABLE_ROUTES), anything unexpected a 500 for that Swarm alone, logged. */
+ * NOT_AVAILABLE answer (the default for per-Swarm routes), anything unexpected a 500 for that Swarm alone, logged. */
export function readingError(tabId: string, error: unknown): { code: string; message: string; status: number } {
if (error instanceof ZodError) return { code: 'VALIDATION_ERROR', message: error.issues[0]?.message ?? 'This reading is not valid.', status: 400 }
if (error instanceof SuperTabError) {
@@ -208,7 +188,9 @@ async function respond(reply: FastifyReply, action: () => Promise<unknown>) {
try { sendSuccess(reply, await action()) } catch (error) {
if (error instanceof GitHubAppError) return sendError(reply, error.message, error.code, error.status, error.details)
const { request } = reply
- if (error instanceof SuperTabError && unreachable(error) && NOT_AVAILABLE_ROUTES.has(`${request.method} ${request.routeOptions.url}`)) {
+ if (error instanceof SuperTabError && unreachable(error)
+ && /^\/api\/super-tabs\/:tabId(?:\/|$)/.test(request.routeOptions.url ?? '')
+ && !NOT_AVAILABLE_EXEMPT_ROUTES.has(`${request.method} ${request.routeOptions.url}`)) {
logger.warn('Swarm not available to the caller', { code: error.code, statusCode: error.status, reason: error.message,
path: request.url, method: request.method })
return sendError(reply, NOT_AVAILABLE.message, NOT_AVAILABLE.code, NOT_AVAILABLE.status)
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index cbb4fdd0d..5ad51a57f 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -45,7 +45,7 @@ import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRo
import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'
import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'
-import { launchRefusedLine, leadJoined, leadStartFailed, leadStarting, placeLead } from './leadStart.js'
+import { launchRefusedLine, leadJoined, leadOvertaken, leadStartFailed, leadStarting, placeLead } from './leadStart.js'
import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
@@ -2373,6 +2373,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const group = open(state, start.request.conversationId)
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.')
+ // Answered, not refused: a refusal would take the row with it. Its host closes the session (cli superTabs/start.ts).
+ const overtaken = start.request.leadFor ? leadOvertaken(state, start, group) : null
+ if (overtaken) {
+ start.error = overtaken.reason
+ result.refused = overtaken.reason
+ message(group.id, overtaken.text, [], null, overtaken.source)
+ break
+ }
reserveHarnessSlot(state, start.request.machineId, command.harnessId, operationId)
state.agents.push({ id: agentId, machineId: start.request.machineId, harnessId: command.harnessId,
// A Swarm Buddy chat has no project: its main Buddy and plain sessions read every project their person reads, and a
diff --git a/backend/src/superTabs/leadStart.test.ts b/backend/src/superTabs/leadStart.test.ts
index 1438c6745..efa835538 100644
--- a/backend/src/superTabs/leadStart.test.ts
+++ b/backend/src/superTabs/leadStart.test.ts
@@ -248,6 +248,69 @@ describe('a Product Manager\'s start, once its host reports it', () => {
const messages = (effects: ReturnType<ReturnType<typeof swarm>['run']>, conversationId: string) =>
effects.messages.filter(m => m.conversationId === conversationId).map(m => m.text)
+ // Task #2248, both security reviews of #2636: a person set a coordinator by hand while the Swarm was still starting one.
+ describe('a start that finishes after a person set another coordinator', () => {
+ const late = () => {
+ const f = swarm()
+ const startId = f.lead('mate-mac').result.startId as string
+ const hand = f.run({ type: 'agent.add', conversationId: f.app.conversationId, machineId: 'owner-mac', harnessId: 'by-hand', name: 'Mine',
+ configuration: config, lead: true }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner', hostGrant: null } }).result.agentId as string
+ const home = () => f.state.conversations.find(c => c.id === f.app.conversationId)!
+ const finish = (operation?: string) => f.run({ type: 'agent.started', startId, harnessId: 'pm', configuration: config }, owner, { ...hosted(f, 'mate-team'), ...(operation ? { operationId: operation } : {}) })
+ return { f, startId, hand, home, finish }
+ }
+
+ it('never joins: no agent, the chat keeps its coordinator, and the start fails with the reason', () => {
+ const t = late()
+ const answer = t.finish()
+ expect(answer.result.agentId).toBeUndefined()
+ expect(answer.result.refused).toMatch(/already/)
+ expect(t.f.state.agents.map(a => a.harnessId)).not.toContain('pm')
+ expect(t.home()).toMatchObject({ leadId: t.hand, agentIds: [t.hand] })
+ expect(t.f.state.starts!.find(s => s.id === t.startId)).toMatchObject({ error: answer.result.refused })
+ expect(t.f.state.starts!.find(s => s.id === t.startId)!.harnessId).toBeFalsy()
+ })
+
+ it('leaves one row naming its machine, as a system row, and forgets where it was starting', () => {
+ const t = late()
+ const answer = t.finish()
+ const rows = answer.messages.filter(m => m.conversationId === t.f.app.conversationId)
+ expect(rows.map(m => m.text)).toEqual(['Product Manager started on MacBook Pro, but this project already has Mine as its Product Manager, so it did not join.'])
+ expect(rows[0]!.source).toEqual({ kind: 'system', machine: 'MacBook Pro' })
+ expect(rows[0]!.recipients).toEqual([])
+ expect(t.f.project().lead).toBeUndefined()
+ })
+
+ it('a second report fails as any failed start does, with no second row', () => {
+ const t = late()
+ t.finish()
+ expect(() => t.finish()).toThrow('This start failed')
+ })
+
+ it('takes over when the coordinator set by hand has left', () => {
+ const t = late()
+ Object.assign(t.home(), { leadId: null, agentIds: [] })
+ const pm = t.finish().result.agentId as string
+ expect(t.home()).toMatchObject({ leadId: pm, agentIds: [pm] })
+ })
+
+ it('leaves the PM switch working on the coordinator it left in place', () => {
+ const t = late()
+ t.finish()
+ t.f.machine('owner-mac').observation!.capabilities = ['leadSwitch']
+ t.f.run({ type: 'lead.switch', projectId: t.f.app.projectId, engine: 'codex', profileId: 'default' })
+ expect(t.f.state.agents.find(a => a.id === t.hand)!.switchRequest).toMatchObject({ engine: 'codex', requestedBy: 'owner' })
+ })
+
+ it('a first start with nobody set joins and leads, as before', () => {
+ const f = swarm()
+ const startId = f.lead('mate-mac').result.startId as string
+ const pm = f.run({ type: 'agent.started', startId, harnessId: 'pm', configuration: config }, owner, hosted(f, 'mate-team')).result.agentId as string
+ expect(f.state.conversations.find(c => c.id === f.app.conversationId)).toMatchObject({ leadId: pm, agentIds: [pm] })
+ expect(f.project().lead).toMatchObject({ status: 'started' })
+ })
+ })
+
it('says when it runs another model or effort than it asked for, and nothing when it cannot tell', () => {
const joinedWith = (configuration: AgentConfiguration) => {
const f = swarm()
diff --git a/backend/src/superTabs/leadStart.ts b/backend/src/superTabs/leadStart.ts
index f130d9548..d02096dcc 100644
--- a/backend/src/superTabs/leadStart.ts
+++ b/backend/src/superTabs/leadStart.ts
@@ -166,6 +166,22 @@ const placementOf = (state: SuperTabState, start: AgentStart): LeadPlacement | u
return lead?.startId === start.id ? lead : undefined
}
+/** A person set another coordinator while this start ran (both security reviews of #2636): it never joins the project chat. The
+ * start ends with the reason and its placement is forgotten, as the project has its coordinator. The line its conversation
+ * shows and its source, a system row naming the machine as leadJoined's does; null when no coordinator holds the chat. */
+export function leadOvertaken(state: SuperTabState, start: AgentStart, home: Conversation): { text: string; reason: string; source: { kind: 'system'; machine?: string } } | null {
+ const holder = home.leadId && home.agentIds.includes(home.leadId) ? state.agents.find(a => a.id === home.leadId) : undefined
+ const project = start.request.leadFor && projectsOf(state).find(p => p.id === start.request.leadFor!.projectId)
+ if (!holder || !project) return null
+ const placement = placementOf(state, start)
+ const machine = placement?.machineName ?? state.machines?.find(m => m.machineId === start.request.machineId)?.name
+ if (placement) delete project.lead
+ const name = coordinatorNameOf(project)
+ const reason = `This project already has ${holder.displayName ?? holder.name} as its ${name}.`
+ return { reason, text: `${name} started on ${machine ?? 'its machine'}, but this project already has ${holder.displayName ?? holder.name} as its ${name}, so it did not join.`,
+ source: machine ? { kind: 'system', machine } : { kind: 'system' } }
+}
+
/** Its agent [agentId] joined the project's Lead conversation [home]: it leads it, unless a Lead was added there by hand
* meanwhile, which stays. The line its conversation shows, and its source: a system row naming the machine, so a Buddy reads
* it without the name (store.ts withoutMachineNames; Diego, 10-30). */
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 89f498b0f..2033cb020 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1970,6 +1970,8 @@ export class SuperTabStore {
const row = await transaction(this.db, async tx => {
const { state } = await this.load(tx, user, tabId, {})
const actor = await this.actor(tx, user, state, asAgentId)
+ // Refuse revoked membership before an upload lookup can reveal that the Swarm exists.
+ author(state, actor)
const found = await tx.superTabAttachment.findFirst({ where: { tabId, id: uploadId } })
if (!found || found.actorKey !== actorKey(actor) || found.usedBy || (found.purpose && found.purpose !== PENDING_UPLOAD_PURPOSE)) unavailable()
// Access may have gone while the bytes moved: the actor must still be able to post there.
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index fc74203da..d9a7e2e7e 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -15,7 +15,7 @@ vi.mock('./buddyHome.js', async (original) => ({ ...await original<object>(), pr
const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }
/** A queued start is watched before the Lead moves on (startAgent); these tests read the queued answer at once. */
const noPause = async () => {}
-function fixture(options: { state?: Record<string, unknown> | Error; githubApp?: boolean; refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; acceptedLaunchModel?: { model: string | null; effort: string | null }; refuseModel?: string; frame?: string; guest?: boolean; identity?: { sessionId: string; createdAt: string } } = {}) {
+function fixture(options: { state?: Record<string, unknown> | Error; refused?: string; loseClose?: boolean; githubApp?: boolean; refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; acceptedLaunchModel?: { model: string | null; effort: string | null }; refuseModel?: string; frame?: string; guest?: boolean; identity?: { sessionId: string; createdAt: string } } = {}) {
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
@@ -32,6 +32,7 @@ function fixture(options: { state?: Record<string, unknown> | Error; githubApp?:
start.error = String(cmd.error)
}
if (cmd.type === 'agent.started' && lostJoin) { lostJoin = false; throw new Error('Join interrupted') }
+ if (cmd.type === 'agent.started' && options.refused) { start.error = options.refused; return { ok: true, value: { result: { refused: options.refused } } } }
return { ok: true, value: { result: cmd.type === 'agent.start' ? { startId: 'start' } : { agentId: 'worker' } } }
})
const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}, _ms?: number): Promise<Record<string, unknown>> => {
@@ -51,6 +52,10 @@ function fixture(options: { state?: Record<string, unknown> | Error; githubApp?:
if (options.refuse) return { error: options.refuse, detail: 'This agent does not support that permission mode.' }
nativeState = 'created'; return { creationId: start.creationId, state: 'created', agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high', ...options.identity } }
}
+ if (type === 'agent_close') {
+ if (options.loseClose) throw new Error('Close interrupted')
+ return { closed: true, agentId: payload.agentId }
+ }
if (type === 'agent_create_cancel') {
nativeState = 'cancelled'
if (options.loseCancel) { options.loseCancel = false; throw new Error('Cancellation reply interrupted') }
@@ -72,6 +77,33 @@ async function onFakeClock<T>(run: () => Promise<T>): Promise<T> {
} finally { vi.useRealTimers() }
}
+// Task #2248: the server answered that another coordinator was set while this one started, so it never joined.
+describe('a join the server refused', () => {
+ const closes = (f: { request: { mock: { calls: unknown[][] } } }) => f.request.mock.calls.filter(c => c[0] === 'agent_close')
+ const REASON = 'This project already has Mine as its Product Manager.'
+
+ it('closes the session this start created, and says why, with no model switch', async () => {
+ const f = fixture({ refused: REASON, frame: 'claude-opus-5-5' })
+ const result = await onFakeClock(() => startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open))
+ expect(closes(f)).toEqual([['agent_close', { agentId: 'native', mode: 'now' }, expect.any(Number)]])
+ expect(switchCall(f)).toBeUndefined()
+ expect(result).toMatchObject({ ok: false, error: REASON, startId: 'start', harnessId: 'native', refused: REASON })
+ expect(result).not.toHaveProperty('agentId')
+ })
+
+ it('says so when the session could not be closed', async () => {
+ const f = fixture({ refused: REASON, frame: 'claude-opus-5-5', loseClose: true })
+ const result = await onFakeClock(() => startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open))
+ expect(result).toMatchObject({ ok: false, refused: REASON, closeFailed: true })
+ })
+
+ it('closes nothing on a join that went through', async () => {
+ const f = fixture({ frame: 'claude-opus-5-5' })
+ expect(await onFakeClock(() => startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open))).toMatchObject({ ok: true, agentId: 'worker' })
+ expect(closes(f)).toEqual([])
+ })
+})
+
describe('Swarm permission mode', () => {
it('admits installed Claude when an API environment is opaque to the vendor login probe', async () => {
const f = fixture(), request = f.request.getMockImplementation()!
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index f8be3f748..7a7557ad0 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -534,6 +534,13 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
reply = await scoped({ action: 'command', operationId: `joined-legacy-${startId}`, command: join })
}
joined = requireSuccess(reply)
+ // Another coordinator was set while this one started (backend leadStart.ts leadOvertaken): it is no agent of the Swarm, so
+ // the session this start created goes, and nothing else does.
+ const refused = text(object(joined.result).refused)
+ if (refused) {
+ const closed = await target.request('agent_close', { agentId: nativeId, mode: 'now' }, 60_000).catch((): Json => ({}))
+ return { ok: false, error: refused, refused, startId, machineId: request.machineId, harnessId: nativeId, ...(closed.closed === true ? {} : { closeFailed: true }) }
+ }
}
await target.request('super_tabs', { action: 'wake' }).catch(() => {})
await target.request('harness_share_rosters', {}).catch(() => {})
diff --git a/docs/plans/2026-11-03-late-coordinator-start-plan.md b/docs/plans/2026-11-03-late-coordinator-start-plan.md
new file mode 100644
index 000000000..39d5e59d4
--- /dev/null
+++ b/docs/plans/2026-11-03-late-coordinator-start-plan.md
@@ -0,0 +1,71 @@
+# A Late Coordinator Start Never Joins Implementation Plan
+
+> **How this is worked:** by the project's instructions, task by task, each failing test committed before its code.
+
+**Goal:** A coordinator start that finishes after a person set another coordinator never joins the project chat, says why and leaves a row. The PM switch keeps working.
+
+**Architecture:** `agent.started` for a start with `leadFor` checks the project chat once the start's identity checks have passed. With a live coordinator there, it creates no agent, fails the start with the reason, forgets the placement and writes a system row. The command succeeds so the row is kept (a refusal rolls its write back), and its result says `refused`. The host closes the session it just created.
+
+**Tech Stack:** TypeScript, Vitest, real Mongo for the integration suite.
+
+**Spec:** Task #2248 (Ken), named by both security reviews of #2636 (Luna, Echo).
+
+## Global Constraints
+
+- The PR body starts with: `Requested by [email protected] through Harness.`
+- Two security reviews: Luna and Echo. Full Super Tab integration suite before Ready.
+- Never test a PM switch live on River's project: tests only.
+- Swarm code stays out of `cli/src/core`. No env switch.
+
+## Review Focus
+
+1. A forged or stale report can't remove anyone: the check runs after the start's grant checks, and it only ever refuses the start.
+2. A coordinator that left the chat doesn't block: a start takes over, as before.
+3. The session the host closes is the one this start's own create returned, and nothing else.
+4. A replayed `agent.started` after the refusal fails as any failed start does, and writes no second row.
+5. The row names a machine, so a Buddy reads it without the name (`store.ts withoutMachineNames`).
+
+## Design
+
+- **Growth:** N/A because it adds one row per refused start, and a start can only be refused once.
+- **Concurrency:** written in the start's own command on the project chat's group. A hand-set racing it retries on fresh state, and whichever lands second sees the first.
+- **Read cost:** N/A because it reads only what the command has loaded.
+- **Scale:** N/A because a project has at most one coordinator start at a time.
+- **Compatibility:** an older CLI gets a success with no agent, leaves the session idle with no access to the Swarm, and reports nothing wrong. Only a newer CLI closes it.
+- **Migration and rollback:** none. Rolling back restores the second agent.
+- **Audience:** the server enforces it; no client decides.
+- **Identity:** the host's grant for this start, as today.
+- **Failure:** a failed close leaves the session idle, and the host says so in its answer. Its worktree stays until the machine's cleanup.
+- **Platforms:** N/A beyond the close, which uses the same daemon call on all platforms.
+
+---
+
+### Task 1: The server refuses the late join
+
+**Files:**
+- Modify: `backend/src/superTabs/leadStart.ts`, `backend/src/superTabs/commands.ts`
+- Test: `backend/src/superTabs/leadStart.test.ts`
+
+**Interfaces:**
+- Produces: `leadOvertaken(state, start, home): string | null`; `agent.started` result `refused?: string`.
+
+- [ ] **Step 1: Write the failing tests:** a start finishing after a person set a coordinator makes no agent, keeps the chat's coordinator and members, leaves one row, and fails the start with the reason; the placement is gone; a replay fails and adds no row; a start after the coordinator left still takes over; a first start still joins; `lead.switch` still works on the coordinator.
+- [ ] **Step 2: Run them:** `npm test -- src/superTabs/leadStart.test.ts` in `backend`. Expected: the refusal tests FAIL, and the others pass.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run them.** Expected: PASS.
+- [ ] **Step 5: Commit.**
+
+### Task 2: The host closes the session
+
+**Files:**
+- Modify: `cli/src/superTabs/start.ts`
+- Test: its spec
+
+**Interfaces:**
+- Consumes: `refused` from Task 1.
+
+- [ ] **Step 1: Write the failing test:** a join answered `refused` closes that session and returns the reason, with no model switch; a normal join closes nothing.
+- [ ] **Step 2: Run it.** Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run it.** Expected: PASS.
+- [ ] **Step 5: Commit, run `npm run test:super-tabs`, mark the pull request ready** and ask Luna and Echo.