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.

Keep Swarm members connected after Change agent (#1593)

tony496s9c06787fef40
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 96bff3b4a..d5caff04b 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -71,6 +71,48 @@ afterAll(async () => {
await replica?.stop()
})
+describe('Change agent on a Swarm member', () => {
+ it('moves active execution and keeps queued, held, answered and uncertain receipts; Send again uses the current member', async () => {
+ const { tab, lead } = await fixture()
+ const before = (await store.read(owner, tab)).state.agents.find(a => a.id === lead)!
+ const group = (await run(tab, { type: 'conversation.create', title: 'Replacement', brief: 'Continue work',
+ checks: [{ description: 'Receives messages', independent: false }] })).result.conversationId as string
+ await run(tab, { type: 'conversation.agent', conversationId: group, agentId: lead, present: true, lead: false })
+ await run(tab, { type: 'work.assign', conversationId: group, agentId: lead })
+ const receiptIds: string[] = []
+ for (const status of ['queued', 'claimed', 'uncertain', 'answered']) {
+ const sent = await run(tab, { ...message(`Before ${status}`), recipientIds: [lead] } as Command)
+ const delivery = (await store.deliveries(host, tab, lead)).find(d => d.messageId === sent.result.messageId)!
+ await db.superTabDelivery.update({ where: { id: delivery.id }, data: { status, ...(status !== 'queued' ? { claimId: `claim-${status}`, receipt: `receipt-${status}` } : {}),
+ ...(status === 'claimed' ? { holdReason: 'team_busy', holdSince: new Date() } : {}) } })
+ receiptIds.push(delivery.id)
+ }
+ const receipts = await db.superTabDelivery.findMany({ where: { id: { in: receiptIds } }, orderBy: { id: 'asc' } })
+ const command: Command = { type: 'agent.rebind', agentId: lead, machineId: 'test-host', projectId: 'lead',
+ previousHarnessId: before.harnessId, harnessId: randomUUID(), configuration: { ...config, engine: 'claude', model: 'sonnet' } }
+ const operation = randomUUID()
+ const changed = await run(tab, command, host, lead, operation)
+ const after = (await store.read(owner, tab)).state
+ expect(after.agents.find(a => a.id === lead)).toMatchObject({ ...before, harnessId: command.harnessId,
+ configuration: command.configuration, configurationVersion: expect.any(String) })
+ expect(after.conversations[0]!.leadId).toBe(lead)
+ expect(await db.superTabRun.findUnique({ where: { id: lead } })).toMatchObject({ harnessId: command.harnessId })
+ expect(await db.superTabDelivery.findMany({ where: { id: { in: receiptIds } }, orderBy: { id: 'asc' } })).toEqual(receipts)
+ expect(await run(tab, command, host, lead, operation)).toEqual(changed)
+ const uncertain = receipts.find(d => d.status === 'uncertain')!
+ await run(tab, { type: 'delivery.resolve', deliveryId: uncertain.id, resolution: 'resend' })
+ const resent = (await store.deliveries(host, tab, lead)).find(d => d.id !== uncertain.id && !receiptIds.includes(d.id) && d.status === 'queued')!
+ expect(resent).toMatchObject({ agentId: lead, status: 'queued' })
+ })
+ it('refuses a replacement already contributed in another tab', async () => {
+ const first = await fixture(), second = await fixture()
+ const previous = (await store.read(owner, first.tab)).state.agents[0]!
+ const occupied = (await store.read(owner, second.tab)).state.agents[0]!
+ await expect(run(first.tab, { type: 'agent.rebind', agentId: first.lead, machineId: 'test-host', projectId: 'lead',
+ previousHarnessId: previous.harnessId, harnessId: occupied.harnessId, configuration: config }, host, first.lead)).rejects.toMatchObject({ code: 'SESSION_CONTRIBUTED' })
+ })
+})
+
describe('five-part task persistence', () => {
it('stores structured tasks through the API and delivers all parts to the worker', async () => {
const { tab, lead } = await fixture()
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index b551f6fd4..6f6b9f80e 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -84,6 +84,9 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('agent.remove'), agentId: id, releaseId: id.optional() }).strict(),
z.object({ type: z.literal('agent.release'), agentId: id, decision: z.enum(['keep', 'stop']) }).strict(),
z.object({ type: z.literal('agent.configuration'), previousVersion: id.nullable(), configuration }).strict(),
+ z.object({ type: z.literal('agent.rebind'), agentId: id, machineId: id, projectId: id,
+ previousHarnessId: id, harnessId: id, configuration,
+ startedSession: z.object({ creationId: id, sessionId: id, createdAt: z.iso.datetime() }).strict().optional() }).strict(),
z.object({ type: z.literal('conversation.agent'), conversationId: id, agentId: id, present: z.boolean(), lead: z.boolean() }).strict(),
z.object({ type: z.literal('invite.create'), email: z.email().max(320), role: z.enum(['collaborator', 'viewer']), conversationId: id }).strict(),
z.object({ type: z.literal('invite.revoke'), inviteId: id }).strict(),
@@ -649,6 +652,34 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
break
}
+ case 'agent.rebind': {
+ const target = agent(state, command.agentId)
+ if (actor.kind !== 'agent' || actor.agentId !== target.id || actor.machineOwnerId !== target.machineOwnerId
+ || command.machineId !== target.machineId || command.projectId !== agentProjectId(state, target)) {
+ fail('HOST_REQUIRED', 'Only this project’s execution host can report a replacement.', 403)
+ }
+ if (target.workDecision === 'stop') fail('STOP_REQUESTED', 'This member is stopping; reconcile its stop first.')
+ if (state.agents.some(a => a.id !== target.id && a.machineId === target.machineId && a.harnessId === command.harnessId)) {
+ fail('SESSION_CONTRIBUTED', 'The replacement terminal already belongs to another member.')
+ }
+ if (target.harnessId === command.harnessId && target.replacement?.previousHarnessId === command.previousHarnessId) break
+ if (target.harnessId !== command.previousHarnessId || command.harnessId === command.previousHarnessId) {
+ fail('AGENT_CHANGED', 'The member’s terminal changed. Read its current binding before replacing it.')
+ }
+ target.harnessId = command.harnessId
+ target.replacement = { previousHarnessId: command.previousHarnessId, harnessId: command.harnessId }
+ target.configuration = command.configuration
+ target.configurationVersion = operationId
+ if (command.startedSession) target.startedSession = command.startedSession
+ else delete target.startedSession
+ for (const group of state.conversations) {
+ if (!activeWork(group) || group.assignment?.agentId !== target.id) continue
+ group.assignment.execution.harnessId = target.harnessId
+ group.assignment.configuration = command.configuration
+ }
+ result.agentId = target.id
+ break
+ }
case 'agent.release': {
const target = agent(state, command.agentId)
const project = projectOf(state, agentProjectId(state, target))
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 6c9e38e87..f089a58d9 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -34,6 +34,8 @@ export interface Agent {
configuration: AgentConfiguration
/** The last configuration operation fences delayed observations, including re-contribution. */
configurationVersion?: string
+ /** Fences a repeated Change agent report without rolling back later model observations. */
+ replacement?: { previousHarnessId: string; harnessId: string }
}
export type AgentRole = 'builder' | 'reviewer'
export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?? 'builder'
diff --git a/backend/src/superTabs/rebind.test.ts b/backend/src/superTabs/rebind.test.ts
new file mode 100644
index 000000000..b396fb7a8
--- /dev/null
+++ b/backend/src/superTabs/rebind.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, commandSchema } from './commands.js'
+import { createSuperTab, SuperTabError, type Actor } from './model.js'
+import { projectsOf } from './projects.js'
+
+const config = { engine: 'codex', model: 'old', effort: 'high', contextWindow: null, engineVersion: null }
+const next = { ...config, engine: 'claude', model: 'sonnet' }
+const person: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }
+function fixture() {
+ let state = createSuperTab('tab', 'Work', { id: 'owner', email: '[email protected]' }, 'prod')
+ state = applyCommand(state, person, { type: 'agent.add', conversationId: 'lead', machineId: 'machine', harnessId: 'old', name: 'Lead', lead: true, configuration: config },
+ { now: 1, operationId: 'add', contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).state
+ const member = state.agents[0]!
+ member.workDecision = 'keep'
+ state.conversations[0]!.assignment = { id: 'work', agentId: member.id, status: 'working', configuration: config,
+ execution: { machineId: 'machine', machineOwnerId: 'owner', harnessId: 'old' }, result: null }
+ const actor: Actor = { kind: 'agent', agentId: member.id, machineOwnerId: 'owner' }
+ const command = { type: 'agent.rebind', agentId: member.id, machineId: 'machine', projectId: 'lead', previousHarnessId: 'old', harnessId: 'new', configuration: next }
+ const run = (input = command, who: Actor = actor) => applyCommand(state, who, commandSchema.parse(input), { now: 2, operationId: 'replace' })
+ return { state, member, actor, command, run }
+}
+
+describe('Change agent keeps the Swarm member', () => {
+ it('moves only terminal and current configuration, preserving the Lead and active assignment', () => {
+ const f = fixture(), changed = f.run()
+ expect(changed.state.agents[0]).toMatchObject({ ...f.member, harnessId: 'new', configuration: next, configurationVersion: expect.any(String) })
+ expect(changed.state.conversations[0]).toMatchObject({ leadId: f.member.id, agentIds: [f.member.id], assignment: {
+ id: 'work', agentId: f.member.id, status: 'working', configuration: next, execution: { harnessId: 'new' } } })
+ expect(changed.cancelledAgents).toEqual([])
+ expect(f.state.agents[0]!.harnessId).toBe('old')
+ })
+ it('repeating the same replacement is a no-op and cannot roll back newer configuration', () => {
+ const f = fixture(), changed = f.run().state
+ changed.agents[0]!.configuration.model = 'opus'
+ expect(applyCommand(changed, f.actor, commandSchema.parse(f.command), { now: 3, operationId: 'retry' }).state).toEqual(changed)
+ })
+ it.each(['person', 'account', 'machine', 'project', 'old', 'occupied', 'self', 'stopping'])('refuses %s without changing state', kind => {
+ const f = fixture(), before = structuredClone(f.state)
+ let who: Actor = f.actor
+ const command = { ...f.command }
+ if (kind === 'person') who = person
+ if (kind === 'account') who = { ...f.actor, machineOwnerId: 'other' } as Actor
+ if (kind === 'machine') command.machineId = 'other'
+ if (kind === 'project') {
+ f.state.projects = [...projectsOf(f.state), { ...projectsOf(f.state)[0]!, id: 'other', leadConversationId: 'other-lead' }]
+ command.projectId = 'other'
+ }
+ if (kind === 'old') command.previousHarnessId = 'other'
+ if (kind === 'self') command.harnessId = 'old'
+ if (kind === 'stopping') f.member.workDecision = 'stop'
+ if (kind === 'occupied') f.state.agents.push({ ...f.member, id: 'another', harnessId: 'new' })
+ const code = kind === 'account' ? 'FORBIDDEN' : kind === 'project' ? 'NOT_FOUND' : kind === 'occupied' ? 'SESSION_CONTRIBUTED'
+ : kind === 'old' || kind === 'self' ? 'AGENT_CHANGED' : kind === 'stopping' ? 'STOP_REQUESTED' : 'HOST_REQUIRED'
+ try { f.run(command, who); expect.fail('A mismatched replacement must be refused') } catch (error) {
+ expect(error).toBeInstanceOf(SuperTabError)
+ expect(error).toMatchObject({ code })
+ }
+ expect(f.state.agents[0]!.harnessId).toBe(before.agents[0]!.harnessId)
+ })
+})
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 2d8f36f29..31a6e1777 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -423,6 +423,23 @@ export class SuperTabStore {
const dispatched = command.type === 'agent.startDispatch' ? original.starts?.find(s => s.id === command.startId)?.routeDecisionId : undefined
if (dispatched) context.routeDecision = await readDecision(tx, tabId, dispatched) ?? undefined
const effects = applyCommand(original, actor, command, context)
+ if (command.type === 'agent.rebind') {
+ const target = agent(effects.state, command.agentId)
+ // A terminal can already belong to a different project or Swarm on this host. The pure
+ // transition checks this tab; inspect the other registrations inside the same transaction.
+ const registrations = await tx.superTab.findMany({ where: { autonomousEnv: original.environment,
+ machineIds: { has: target.machineId } } })
+ if (registrations.some(row => stateOf(row).agents.some(a => a.machineId === target.machineId
+ && a.harnessId === command.harnessId && a.id !== target.id))) {
+ fail('SESSION_CONTRIBUTED', 'The replacement terminal already belongs to another member.')
+ }
+ if (target.harnessId !== agent(original, target.id).harnessId) {
+ // Preserve the stable member's scope and also reserve the new native identity's scope.
+ await bindSession(tx, effects.state, { ...target, id: stableId(target.machineId, target.harnessId) }, context.now)
+ await tx.superTabRun.updateMany({ where: { id: target.id, tabId, machineId: target.machineId,
+ harnessId: command.previousHarnessId }, data: { harnessId: target.harnessId } })
+ }
+ }
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, context.now)
@@ -439,7 +456,7 @@ export class SuperTabStore {
status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled', holdReason: null, holdSince: null } })
}
const revision = row.revision + 1
- if (command.type === 'agent.add' || command.type === 'agent.started' || command.type === 'agent.configuration') {
+ if (command.type === 'agent.add' || command.type === 'agent.started' || command.type === 'agent.configuration' || command.type === 'agent.rebind') {
for (const target of effects.state.agents) {
if (target.configurationVersion !== receiptId) continue
const previous = original.agents.find(a => a.id === target.id)
diff --git a/cli/e2e/superTabs.e2e.ts b/cli/e2e/superTabs.e2e.ts
index 691f942e4..39bc12c16 100644
--- a/cli/e2e/superTabs.e2e.ts
+++ b/cli/e2e/superTabs.e2e.ts
@@ -1,7 +1,7 @@
/** Super Tab on the actual native protocol: real master/services, private tmux,
* fake engines and loopback coordination. Database authorization/transactions
* are covered separately by backend's replica-set integration tests. */
-import { createHash } from 'node:crypto'
+import { createHash, randomUUID } from 'node:crypto'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, expect, it, onTestFailed } from 'vitest'
@@ -371,3 +371,79 @@ it('starts either engine once, posts to its captured group and delivers shared i
expect(denied.code).toBe(1)
expect(posts.some(p => p.text === 'not allowed')).toBe(false)
}, 300_000)
+
+it.each(['reported', 'legacy'] as const)('Change agent keeps its member and delivers once after a %s handoff', async mode => {
+ const relay = await FakeBackend.start(); backend = relay; relay.addMachine(ME)
+ const d = await IsolatedDaemon.create({ submissionGate: true, env: {
+ BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,
+ ANTHROPIC_API_KEY: 'fixture-not-a-credential', OPENAI_API_KEY: 'fixture-not-a-credential',
+ } }); daemon = d
+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({ version: 1, accessToken: ME.token,
+ autonomousEnv: 'prod', computerId: ME.computerId, machineId: ME.machineId,
+ expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',
+ }), { mode: 0o600 })
+ const agents: Array<Record<string, any>> = []
+ let rebinds = 0
+ const delivery = { id: 'replacement-delivery', status: 'queued', claimId: null as string | null }
+ relay.superTabs = async (method, raw, body) => {
+ const path = new URL(raw, relay.httpUrl).pathname
+ if (path.endsWith('/pools') || path.endsWith('/assignments')) return { data: [] }
+ if (path === `/api/super-tabs/hosts/${ME.machineId}`) return { data: agents.map(agent => ({ tabId: TAB, agent, observers: [] })) }
+ if (path === `/api/super-tabs/${TAB}`) return { data: { state: { agents, conversations: [{ id: 'feature', leadId: 'stable-member', agentIds: ['stable-member'] }] } } }
+ if (path.endsWith('/commands')) {
+ const command = object(body.command), member = agents[0]
+ if (command.type === 'agent.rebind') {
+ expect(body.asAgentId).toBe('stable-member')
+ expect(command).toMatchObject({ agentId: 'stable-member', previousHarnessId: member.harnessId,
+ machineId: ME.machineId, projectId: 'project', configuration: { engine: 'claude' } })
+ member.harnessId = command.harnessId; member.configuration = command.configuration; rebinds++
+ } else if (command.type === 'agent.configuration') member.configuration = command.configuration
+ else throw new Error(`Unexpected command ${command.type}`)
+ return { data: { result: {} } }
+ }
+ if (path.includes('/deliveries')) {
+ if (method === 'GET') return { data: path.endsWith('/deliveries') ? rebinds && delivery.status !== 'delivered' ? [delivery] : [] : delivery }
+ if (body.type === 'claim') delivery.claimId = body.claimId
+ else delivery.status = body.uncertain ? 'uncertain' : 'delivered'
+ return { data: { message: { id: 'replacement-message', conversationId: 'feature', author: { name: 'Fixture human' }, text: `verify-switched-${mode}` } } }
+ }
+ throw new Error(`Unexpected request ${method} ${path}`)
+ }
+ await d.start()
+ onTestFailed(() => console.log(d.log().split('\n').slice(-100).join('\n')))
+ const client = await LocalClient.connect(d, { machineId: ME.machineId }); clients.push(client)
+ const cwd = join(d.projectsDir, 'switch-project'); mkdirSync(cwd, { recursive: true })
+ const source = await client.request('agent_create', { engine: 'codex', cwd, bypassPermission: true, prompt: 'Remember this project before the switch.' }, 90_000)
+ expect(source.error, JSON.stringify(source)).toBeUndefined()
+ await until('source conversation to finish', () => client.frames.some(frame => frame.type === 'turn_ended' && frame.agentId === source.agent.id && !frame.replay) || null, 30_000, 100)
+ agents.push({ id: 'stable-member', harnessId: source.agent.id, machineId: ME.machineId, projectId: 'project', name: 'Lead', configuration: { engine: 'codex' } })
+ expect(await client.request('super_tabs', { action: 'wake' })).toMatchObject({ ok: true })
+ const hostPid = Number([...d.log().matchAll(/service superTabs started \(pid (\d+)\)/g)].at(-1)?.[1])
+ expect(hostPid).toBeGreaterThan(0)
+ if (mode === 'legacy') process.kill(hostPid, 'SIGSTOP')
+ const changeId = randomUUID().replaceAll('-', '')
+ const handoff = await client.request('agent_handoff_prepare', { agentId: source.agent.id, changeId, targetEngine: 'claude' }, 10_000)
+ expect(handoff.error, JSON.stringify(handoff)).toBeUndefined()
+ const current = (await client.request('agents_list')).agents.find((a: Record<string, any>) => a.id === source.agent.id)
+ expect(await client.request('agent_close', { agentId: current.id, sessionId: current.sessionId, createdAt: current.createdAt, mode: 'now' }, 60_000)).toMatchObject({ closed: true })
+ const target = await client.request('agent_create', { creationId: changeId, engine: 'claude', cwd, bypassPermission: true, prompt: 'Acknowledge the handoff and wait.' }, 90_000)
+ expect(target.error, JSON.stringify(target)).toBeUndefined()
+ if (mode === 'reported') expect(await client.request('agent_handoff_complete', { agentId: source.agent.id, replacementId: target.agent.id, changeId, targetEngine: 'claude' })).toMatchObject({ ok: true })
+ // Restart just the Swarm service: its own saved host receipt wakes it, and legacy recovery has no
+ // completion report. Both paths must bind the exact creation receipt rather than guess by folder.
+ if (mode === 'legacy') {
+ process.kill(hostPid, 'SIGKILL')
+ await until('a new Swarm host after the earlier Change agent', () => {
+ const current = Number([...d.log().matchAll(/service superTabs started \(pid (\d+)\)/g)].at(-1)?.[1])
+ return current > 0 && current !== hostPid || null
+ }, 15_000, 100)
+ }
+ await until('member to follow the replacement terminal', () => agents[0].harnessId === target.agent.id || null, 30_000, 100)
+ await until('one native input receipt on the replacement', () => delivery.status === 'delivered' || null, 30_000, 100)
+ await until('one execution of the delivered input', () => {
+ const prompts = readFileSync(join(d.root, 'submitted-prompts'), 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line) as string)
+ return prompts.filter(prompt => prompt.includes(`verify-switched-${mode}`)).length === 1 || null
+ }, 30_000, 100)
+ expect(rebinds).toBe(1)
+ expect(agents[0]).toMatchObject({ id: 'stable-member', name: 'Lead', configuration: { engine: 'claude' } })
+}, 180_000)
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index c86ffb6e6..71ee0878b 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -659,7 +659,7 @@ export const PROJECTS_REQUESTS = ['git_pull_request', 'git_pull_requests_status'
/** A window's name for its repo and its work, by a small model in the background (services/windowNames.ts). */
export const WINDOW_NAMES_REQUESTS = ['window_name'] as const
/** Change agent's handoff file, prepared in the edge host (services/handoff.ts). */
-export const HANDOFF_REQUESTS = ['agent_handoff_prepare'] as const
+export const HANDOFF_REQUESTS = ['agent_handoff_prepare', 'agent_handoff_complete'] as const
/** Connected services for every local agent, and their MCP bridge, in the edge host (services/connectors.ts). */
export const CONNECTORS_REQUESTS = ['connectors'] as const
/** Sharing this machine with other accounts, and adding machines shared with this one, in the edge host
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index 26790b255..385c993e7 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -25,7 +25,7 @@ const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.
const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'scm_project_info', 'git_pull_request', 'git_pull_requests_status', 'machine_resources', 'api_connections', 'connectors', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare',
// A held launch's cancellation and its receipt contain the client's private request identity.
- 'agent_create_cancel',
+ 'agent_create_cancel', 'agent_handoff_complete',
// Memories (services/memory.ts): what this machine's agents remember, and About You and its on/off choice.
'memory_snapshot', 'memory_about_put', 'memory_deliver',
// Cloud agents (services/cloud.ts): a cloud harness's conversation, the person's words for it, which are connected.
diff --git a/cli/src/services/handoff.spec.ts b/cli/src/services/handoff.spec.ts
index f4dd01715..6d213fece 100644
--- a/cli/src/services/handoff.spec.ts
+++ b/cli/src/services/handoff.spec.ts
@@ -4,11 +4,29 @@ import type { HandoffDeps } from '../lib/agentHandoff.js'
import type { RegisteredSession } from '../lib/registry.js'
import { fakeCore } from '../testing/fakeCore.js'
import { HANDOFF_REQUESTS, startHandoff } from './handoff.js'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
const request = { agentId: 'agent', changeId: '0123456789abcdef0123456789abcdef', targetEngine: 'codex' }
const owner = { owner: true, local: true }
describe('the change-agent handoff service', () => {
+ it('records a completed switch only for the owner with current native facts', async () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'handoff-complete-'))
+ try {
+ const old = { agentId: 'old', cwd: '/repo', resumeOnly: true }, target = { agentId: 'new', cwd: '/repo', engine: 'claude' }
+ const core = fakeCore({ dataDir, conversations: { resolve: vi.fn(async id => (id === 'old' ? old : target) as never) } })
+ const handler = startHandoff(core).agent_handoff_complete!
+ const payload = { agentId: 'old', replacementId: 'new', changeId: '0123456789abcdef', targetEngine: 'claude' }
+ expect(await handler(payload, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(await handler(payload, owner)).toEqual({ ok: true })
+ expect(await handler(payload, owner)).toEqual({ ok: true })
+ expect(await handler({ ...payload, replacementId: 'old' }, owner)).toMatchObject({ error: 'HANDOFF_UNAVAILABLE' })
+ const closed = new AbortController(); closed.abort()
+ expect(await handler(payload, owner, closed.signal)).toMatchObject({ error: 'HANDOFF_UNAVAILABLE' })
+ } finally { rmSync(dataDir, { recursive: true, force: true }) }
+ })
it('uses the real provider by default and preserves its unknown-agent answer', async () => {
const handlers = startHandoff(fakeCore())
expect(Object.keys(handlers)).toEqual([...HANDOFF_REQUESTS])
diff --git a/cli/src/services/handoff.ts b/cli/src/services/handoff.ts
index 74d0fde08..d10469659 100644
--- a/cli/src/services/handoff.ts
+++ b/cli/src/services/handoff.ts
@@ -4,6 +4,7 @@ import { performance } from 'node:perf_hooks'
import { HANDOFF_REQUESTS, type CoreApi, type CorePorts, type ServiceRequests } from '../core/api.js'
import { prepareAgentHandoff, type HandoffDeps } from '../lib/agentHandoff.js'
import { createHandoffRequest } from './handoffRequest.js'
+import { recordReplacement } from '../superTabs/replacements.js'
export { HANDOFF_REQUESTS }
@@ -27,5 +28,12 @@ export function startHandoff(core: CoreApi, _ports?: CorePorts, prepare = prepar
const answer = createHandoffRequest({ prepare: (request) => prepare({ ...deps, permit,
publish: (prepared, _permit) => reads.publish(prepared, permit) }, request) })
return new Promise(reply => answer(payload, asker, reply))
+ }, agent_handoff_complete: async (payload, asker, closed) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ try {
+ if (closed?.aborted) return { error: 'HANDOFF_UNAVAILABLE' }
+ await recordReplacement(core, payload)
+ return { ok: true }
+ } catch { return { error: 'HANDOFF_UNAVAILABLE' } }
} }
}
diff --git a/cli/src/services/handoffProcess.spec.ts b/cli/src/services/handoffProcess.spec.ts
index ce9c843f5..29e884104 100644
--- a/cli/src/services/handoffProcess.spec.ts
+++ b/cli/src/services/handoffProcess.spec.ts
@@ -99,6 +99,7 @@ describe('the handoff in the edge host', () => {
start: core => { api = core; return { agent_handoff_prepare: async () => ({ value: await core.conversations.resolve('a') }) } },
})
expect(options).toMatchObject({ name: 'handoff', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ expect(api.daemon.machineId()).toBe('m')
await expect(api.conversations.resolve('a')).rejects.toMatchObject({ code: 'HANDOFF_UNAVAILABLE' })
const query = vi.fn(async () => ({ value: { agentId: 'a' } }))
options.onConnected!({ query })
diff --git a/cli/src/services/handoffProcess.ts b/cli/src/services/handoffProcess.ts
index 968c75c79..dd935894c 100644
--- a/cli/src/services/handoffProcess.ts
+++ b/cli/src/services/handoffProcess.ts
@@ -76,6 +76,7 @@ export interface HandoffServiceOptions {
export function runHandoffService(options: HandoffServiceOptions): ServiceProcess {
let connection: CoreConnection | null = null
const core = handoffCoreApi(options.dataDir, (query, payload) => connection?.query(query, payload) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }))
+ core.daemon = { ...core.daemon, machineId: () => options.machineId }
return (options.run ?? runServiceProcess)({
name: 'handoff', socketPath: options.socketPath, machineId: options.machineId, token: options.token,
requests: (options.start ?? startHandoff)(core),
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 35ae767e9..c1c4dfbd2 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -45,7 +45,7 @@ function setup(messageFields: Record<string, unknown> = {}) {
for (const fn of listeners) fn({ deliveryId: 'team:service:superTabs:delivery', sessionId: 'harness', state, reason })
}
const saved = () => JSON.parse(readFileSync(hostJournalFile(dir, 'machine-1'), 'utf8'))
- return { core, call, open, event, receipts, holds, log, wait: (ms: number) => { clock += ms }, saved, dir, remove: () => { removed = true }, revoke: (value = true) => { revoked = value }, foreignClaim: () => { claimId = 'another-process' } }
+ return { core, call, open, event, receipts, holds, log, row, wait: (ms: number) => { clock += ms }, saved, dir, remove: () => { removed = true }, revoke: (value = true) => { revoked = value }, foreignClaim: () => { claimId = 'another-process' } }
}
describe('current Swarm role lookup', () => {
@@ -93,6 +93,29 @@ describe('current Swarm role lookup', () => {
})
describe('Super Tab native delivery handoff', () => {
+ it('revokes an in-flight old-terminal lease when the member is rebound, preserving uncertainty', async () => {
+ const t = setup(), host = t.open()
+ await host.tick()
+ t.row.agent.harnessId = 'new-harness'
+ await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ expect(t.core.turns.cancelDelivery).toHaveBeenCalledWith('team:service:superTabs:delivery')
+ expect(t.saved().entries.delivery.stage).toBe('uncertain')
+ expect(t.receipts.at(-1)).toMatchObject({ uncertain: true })
+ })
+ it('retargets held input after Change agent without retargeting uncertain input', async () => {
+ const t = setup(), host = t.open()
+ await host.tick(); t.event('rejected', 'team_waiting_busy')
+ t.row.agent.harnessId = 'new-harness'
+ await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenLastCalledWith('new-harness', expect.any(String), 'team:service:superTabs:delivery')
+ expect(t.saved().entries.delivery.harnessId).toBe('new-harness')
+ host.stop()
+ const fresh = t.open()
+ await fresh.tick()
+ expect(t.saved().entries.delivery.stage).toBe('uncertain')
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(2)
+ })
it('names all five task parts in the worker delivery header', async () => {
const t = setup()
await t.open().tick()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index ea82f2728..d59f29c7c 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -16,6 +16,7 @@ import { noticeReason, WithheldDeliveries } from './withheld.js'
import { attentionOf } from './attention.js'
import { prepareContribution } from './contribution.js'
import { hostname } from 'node:os'
+import { replacementObservations } from './replacements.js'
type Json = Record<string, unknown>
export class SuperTabHostError extends Error {
@@ -152,6 +153,8 @@ export class SuperTabHost {
private prefix: Promise<string> | null = null
private configurationsRunning: Promise<void> | null = null
private nextConfigurationsAt = 0
+ private replacementsRunning: Promise<void> | null = null
+ private nextReplacementsAt = 0
private timer: ReturnType<typeof setTimeout> | null = null
private native: NativeRecorder | null = null
private machines: ContributedMachines | null = null
@@ -441,6 +444,14 @@ export class SuperTabHost {
this.observers(this.core.dataDir, this.machineId, data, requestedAt + 2500)
this.publishAttention(data)
this.joinSwarms(data)
+ // Recovery can wait on a native receipt. Run it beside leases, so another worker's input
+ // never expires while an old Change agent is being reconciled.
+ if (!this.replacementsRunning && this.now() >= this.nextReplacementsAt) {
+ this.replacementsRunning = this.recordReplacements(data).finally(() => {
+ this.replacementsRunning = null
+ this.nextReplacementsAt = this.now() + 5_000
+ })
+ }
// Runtime observations cannot delay the live input leases. A stale host
// observation is fenced by the backend's per-agent configuration version.
if (!this.configurationsRunning && this.now() >= this.nextConfigurationsAt) {
@@ -624,6 +635,19 @@ export class SuperTabHost {
if (delivery.claimId) this.core.turns.cancelDelivery(typedId(entry))
}
const id = typedId(entry)
+ if (entry.harnessId !== target.agent.harnessId) {
+ // Only an explicit withheld native write proves input was never submitted. Ambiguous and
+ // delivered receipts keep their original terminal and are never replayed on replacement.
+ this.authorized.delete(id)
+ const active = this.active.delete(id)
+ if (entry.stage === 'prepared') entry.harnessId = target.agent.harnessId
+ else if (entry.stage === 'submitting') {
+ entry.stage = 'uncertain'
+ entry.receipt = 'The member changed terminals before native submission was confirmed. Inspect the earlier session before retrying.'
+ }
+ this.persist()
+ if (active) this.core.turns.cancelDelivery(id)
+ }
if (entry.stage === 'submitting' && !this.active.has(id)) {
entry.stage = 'uncertain'
entry.receipt = 'Native submission was interrupted. Inspect the session before retrying.'
@@ -679,6 +703,15 @@ export class SuperTabHost {
}
}
+ private async recordReplacements(rows: unknown[]): Promise<void> {
+ try {
+ for (const observation of await replacementObservations(this.core, this.machineId, rows)) {
+ if (this.stopped) return
+ await backend(this.core, 'POST', observation.path, observation.body)
+ }
+ } catch (error) { this.log(error instanceof Error ? error.message : String(error)) }
+ }
+
private prompt(entry: Entry, message: Json, files: string, prefix: string): string {
const command = `${prefix} --tab ${shellQuote(entry.tabId)} --agent ${shellQuote(entry.agentId)}`
const group = message.conversationId as string
diff --git a/cli/src/superTabs/replacements.spec.ts b/cli/src/superTabs/replacements.spec.ts
new file mode 100644
index 000000000..129f9e181
--- /dev/null
+++ b/cli/src/superTabs/replacements.spec.ts
@@ -0,0 +1,90 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { handoffIntentHash, type PreparedHandoff } from '../lib/handoffAuthority.js'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { fakeCore } from '../testing/fakeCore.js'
+import { recordReplacement, replacementObservations } from './replacements.js'
+
+const roots: string[] = []
+afterEach(() => { for (const dir of roots.splice(0)) rmSync(dir, { force: true, recursive: true }) })
+function fixture() {
+ const dataDir = mkdtempSync(join(tmpdir(), 'swarm-replacement-')); roots.push(dataDir)
+ const old = { agentId: 'old', cwd: '/repo', engine: 'codex', active: false, registeredAt: 1 }
+ const next = { agentId: 'new', cwd: '/repo', engine: 'claude', sessionId: 'native', registeredAt: 2 }
+ const core = fakeCore({ dataDir, daemon: { machineId: () => 'machine' }, conversations: { resolve: vi.fn(async id => (id === 'old' ? old : next) as never) },
+ agents: { byAgent: vi.fn(id => id === 'new' ? next as never : undefined), stopped: vi.fn(async () => true), terminalAvailable: () => true,
+ creationStatus: vi.fn(async creationId => ({ creationId, state: 'created' as const, agentId: 'new' })), runtimeProfile: () => 'runtime-v1:new:claude:sonnet@high' } })
+ const payload = { agentId: 'old', replacementId: 'new', changeId: '1234567890abcdef', targetEngine: 'claude' }
+ const row = { tabId: 'tab', agent: { id: 'member', harnessId: 'old', machineId: 'machine', projectId: 'project' } }
+ return { core, payload, row, old, next }
+}
+
+it('durably reports Change agent, and a new host can recover the exact replacement', async () => {
+ const f = fixture()
+ await recordReplacement(f.core, f.payload)
+ await recordReplacement(f.core, f.payload)
+ const observations = await replacementObservations(f.core, 'machine', [f.row])
+ expect(observations).toHaveLength(1)
+ expect(observations[0]).toMatchObject({ path: '/api/super-tabs/tab/commands', body: { asAgentId: 'member', command: {
+ type: 'agent.rebind', agentId: 'member', machineId: 'machine', projectId: 'project', previousHarnessId: 'old', harnessId: 'new',
+ configuration: { engine: 'claude', model: 'sonnet', effort: 'high', contextWindow: null, engineVersion: null } } } })
+ expect(await replacementObservations(f.core, 'machine', [f.row])).toEqual(observations)
+})
+
+it.each(['source-live', 'different-folder', 'different-engine', 'different-receipt', 'not-live', 'foreign-machine', 'stopping'])('holds a replacement with %s', async kind => {
+ const f = fixture()
+ await recordReplacement(f.core, f.payload)
+ if (kind === 'source-live') vi.mocked(f.core.agents.stopped!).mockResolvedValue(false)
+ if (kind === 'different-folder') f.next.cwd = '/another'
+ if (kind === 'different-engine') f.next.engine = 'codex'
+ if (kind === 'different-receipt') vi.mocked(f.core.agents.creationStatus!).mockResolvedValue({ creationId: f.payload.changeId, state: 'created', agentId: 'another' })
+ if (kind === 'not-live') vi.mocked(f.core.agents.byAgent).mockReturnValue(undefined)
+ if (kind === 'foreign-machine') f.row.agent.machineId = 'another'
+ if (kind === 'stopping') Object.assign(f.row, { stopRequested: true })
+ expect(await replacementObservations(f.core, 'machine', [f.row])).toEqual([])
+})
+
+it('refuses to record unrelated or incomplete native facts', async () => {
+ const f = fixture()
+ f.next.cwd = '/another'
+ await expect(recordReplacement(f.core, f.payload)).rejects.toThrow()
+ f.next.cwd = '/repo'; f.old.active = true
+ await expect(recordReplacement(f.core, f.payload)).rejects.toThrow()
+ await expect(recordReplacement(f.core, { ...f.payload, changeId: '../bad' })).rejects.toThrow()
+})
+
+function legacy(core: ReturnType<typeof fakeCore>, changeId = 'a'.repeat(32), invalid = '') {
+ const route = [{ path: '/repo', identity: 'fixture-native-key' }]
+ const prepared: PreparedHandoff = { request: { agentId: 'old', changeId, targetEngine: 'claude' },
+ sessions: [{ agentId: 'old', fingerprint: 'f'.repeat(64) }], reads: [],
+ project: { cwd: '/repo', path: '/repo', fileKey: 'fixture', route },
+ result: { cwd: '/repo', file: null, gitRepo: false, degraded: [] }, documents: null, exclude: null,
+ git: { exclude: null, route, files: [] } }
+ const dir = join(core.dataDir, 'handoff-receipts'); mkdirSync(dir, { mode: 0o700 })
+ writeFileSync(join(dir, `${'b'.repeat(64)}.json`), JSON.stringify({ version: 1,
+ committed: invalid !== 'uncommitted', prepared,
+ fingerprint: invalid === 'checksum' ? 'incorrect' : handoffIntentHash(prepared) }), { mode: 0o600 })
+}
+
+it('recovers an earlier switch from a committed private handoff and its exact launch receipt', async () => {
+ const f = fixture(); legacy(f.core)
+ expect(await replacementObservations(f.core, 'machine', [f.row])).toMatchObject([{ body: { command: {
+ previousHarnessId: 'old', harnessId: 'new', configuration: { engine: 'claude' } } } }])
+ vi.mocked(f.core.agents.creationStatus!).mockResolvedValue(null)
+ expect(await replacementObservations(f.core, 'machine', [f.row])).toEqual([])
+})
+
+it.each(['uncommitted', 'checksum'])('does not recover a %s handoff', async invalid => {
+ const f = fixture(); legacy(f.core, 'a'.repeat(32), invalid)
+ expect(await replacementObservations(f.core, 'machine', [f.row])).toEqual([])
+})
+
+it('does no history scan for a member whose current terminal is live', async () => {
+ const f = fixture()
+ // This invalid folder would throw if recovery tried to inspect it.
+ mkdirSync(join(f.core.dataDir, 'handoff-receipts'), { mode: 0o777 })
+ vi.mocked(f.core.agents.byAgent).mockReturnValue(f.old as never)
+ expect(await replacementObservations(f.core, 'machine', [f.row])).toEqual([])
+ expect(f.core.agents.creationStatus).not.toHaveBeenCalled()
+})
diff --git a/cli/src/superTabs/replacements.ts b/cli/src/superTabs/replacements.ts
new file mode 100644
index 000000000..125be5986
--- /dev/null
+++ b/cli/src/superTabs/replacements.ts
@@ -0,0 +1,114 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { existsSync, linkSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { CoreApi } from '../core/api.js'
+import { readPrivateStateFile, secureStateDirectory, syncStateDirectory } from '../lib/secureState.js'
+import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'
+import { handoffIntentHash } from '../lib/handoffAuthority.js'
+import { validateHandoff } from '../lib/handoffValidation.js'
+import { identifier, object } from './wire.js'
+
+interface Replacement { machineId: string; previousHarnessId: string; harnessId: string; changeId: string; cwd: string; engine: string }
+const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')
+const folder = (core: CoreApi) => join(core.dataDir, 'super-tabs', 'replacements')
+const valid = (row: Replacement) => [row.machineId, row.previousHarnessId, row.harnessId, row.changeId, row.engine].every(identifier)
+ && row.changeId.length >= 16 && row.changeId.length <= 96 && row.previousHarnessId !== row.harnessId && typeof row.cwd === 'string' && !!row.cwd
+
+/** The UI reports only a completed launch. Persist its native identities before answering, so a
+ * disconnected UI or restarted Swarm host does not strand the member on the stopped terminal. */
+export async function recordReplacement(core: CoreApi, payload: Record<string, unknown>): Promise<void> {
+ const previousHarnessId = String(payload.agentId ?? ''), harnessId = String(payload.replacementId ?? '')
+ const row: Replacement = { machineId: core.daemon.machineId(), previousHarnessId, harnessId,
+ changeId: String(payload.changeId ?? ''), engine: String(payload.targetEngine ?? ''), cwd: '' }
+ if (![row.machineId, previousHarnessId, harnessId, row.changeId, row.engine].every(identifier)
+ || row.changeId.length < 16 || row.changeId.length > 96 || previousHarnessId === harnessId) throw new Error('Invalid agent replacement.')
+ const source = await core.conversations.resolve(previousHarnessId), target = await core.conversations.resolve(harnessId)
+ if (!source || source.active !== false && !source.resumeOnly || !source.cwd || !target || target.resumeOnly || target.agentId !== harnessId
+ || source.agentId !== previousHarnessId || target.cwd !== source.cwd || target.engine !== row.engine) throw new Error('The switched conversations changed.')
+ row.cwd = source.cwd
+ const dir = folder(core)
+ mkdirSync(dir, { recursive: true, mode: 0o700 }); secureStateDirectory(dir)
+ const file = join(dir, `${digest([row.machineId, row.changeId])}.json`)
+ if (existsSync(file)) {
+ if (readPrivateStateFile(file, 16_384) !== JSON.stringify(row)) throw new Error('This replacement intent already names another terminal.')
+ syncStateDirectory(dir)
+ return
+ }
+ const temporary = `${file}.${randomUUID()}.next`
+ try {
+ writeFileSync(temporary, JSON.stringify(row), { mode: 0o600, flush: true, flag: 'wx' })
+ try { linkSync(temporary, file) } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST' || readPrivateStateFile(file, 16_384) !== JSON.stringify(row)) throw error
+ }
+ syncStateDirectory(dir)
+ } finally { if (existsSync(temporary)) unlinkSync(temporary) }
+}
+
+/** Read only private daemon receipts, never a project's editable handoff markdown. The exact
+ * successful creation ID joins an old committed handoff to its replacement; a folder match alone
+ * used to leave Launch Builder unassignable after Change agent on 2026-10-22. */
+async function candidates(core: CoreApi, machineId: string): Promise<Replacement[]> {
+ const result: Replacement[] = []
+ const read = (dir: string, max: number, accept: (raw: Record<string, unknown>) => void) => {
+ if (!existsSync(dir)) return
+ secureStateDirectory(dir, false)
+ const names = readdirSync(dir).filter(name => /^[a-f0-9]{64}\.json$/.test(name))
+ if (names.length > 4096) throw new Error('Reconcile the agent replacement receipts before continuing.')
+ for (const name of names) {
+ try { accept(object(JSON.parse(readPrivateStateFile(join(dir, name), max)))) } catch { /* Partial or invalid evidence never adopts a terminal. */ }
+ }
+ }
+ read(folder(core), 16_384, raw => {
+ const row = raw as unknown as Replacement
+ if (valid(row) && row.machineId === machineId) result.push(row)
+ })
+ read(join(core.dataDir, 'handoff-receipts'), 20 * 1024 * 1024, raw => {
+ if (raw.version !== 1 || raw.committed !== true) return
+ const prepared = raw.prepared as Parameters<typeof validateHandoff>[0]
+ validateHandoff(prepared)
+ if (raw.fingerprint !== handoffIntentHash(prepared)) return
+ // Creation status belongs to the core, and is consulted below only for roster members.
+ result.push({ machineId, previousHarnessId: prepared.request.agentId, harnessId: '', changeId: prepared.request.changeId,
+ cwd: prepared.project.cwd, engine: prepared.request.targetEngine })
+ })
+ return result
+}
+
+export async function replacementObservations(core: CoreApi, machineId: string, rows: unknown[]) {
+ // Healthy members need no recovery or disk scan. In particular, do not reread every historical
+ // handoff and its transcript on a machine with live Swarm members every five seconds.
+ rows = rows.filter(value => {
+ const row = object(value), agent = object(row.agent)
+ return identifier(row.tabId) && identifier(agent.id) && identifier(agent.harnessId) && agent.machineId === machineId
+ && row.stopRequested !== true && agent.workDecision !== 'stop' && !core.agents.byAgent(String(agent.harnessId))
+ })
+ if (!rows.length) return []
+ const reports = await candidates(core, machineId)
+ const observations: Array<{ path: string; body: Record<string, unknown> }> = []
+ for (const value of rows) {
+ const row = object(value), agent = object(row.agent)
+ if (!identifier(row.tabId) || !identifier(agent.id) || !identifier(agent.harnessId)
+ || agent.machineId !== machineId || row.stopRequested === true || agent.workDecision === 'stop') continue
+ const matches: Array<{ report: Replacement; target: NonNullable<ReturnType<CoreApi['agents']['byAgent']>> }> = []
+ for (const report of reports.filter(r => r.previousHarnessId === agent.harnessId)) {
+ if (!await core.agents.stopped?.(report.previousHarnessId)) continue
+ const receipt = await core.agents.creationStatus?.(report.changeId)
+ if (receipt?.state !== 'created' || receipt.creationId !== report.changeId || report.harnessId && receipt.agentId !== report.harnessId) continue
+ const target = core.agents.byAgent(receipt.agentId)
+ if (!target || target.resumeOnly || target.agentId === report.previousHarnessId || target.cwd !== report.cwd
+ || target.engine !== report.engine || !core.agents.terminalAvailable(target.agentId)) continue
+ matches.push({ report, target })
+ }
+ if (new Set(matches.map(m => m.target.agentId)).size !== 1) continue
+ const { report, target } = matches[0]
+ const profile = parseRuntimeProfile(core.agents.runtimeProfile(target))
+ const known = profile?.sessionId === target.agentId && profile.engine === target.engine
+ const configuration = { engine: target.engine, model: known ? profile.model : null, effort: known ? profile.effort : null,
+ contextWindow: null, engineVersion: null }
+ const command = { type: 'agent.rebind', agentId: agent.id, machineId, projectId: agent.projectId ?? 'lead',
+ previousHarnessId: agent.harnessId, harnessId: target.agentId, configuration }
+ observations.push({ path: `/api/super-tabs/${row.tabId}/commands`, body: {
+ operationId: `replacement-${digest([row.tabId, agent.id, report.changeId, target.agentId])}`, asAgentId: agent.id, command } })
+ }
+ return observations
+}
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index f8fafc7f2..a00e6a6e2 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -59,6 +59,14 @@ const recorded = (s: ReturnType<typeof scoped>) => s.mock.calls.find(c => c[0].a
const labels = (s: ReturnType<typeof scoped>) => (recorded(s).command.decision.candidates as Array<{ label: string }>).map(c => c.label)
describe('routeTask', () => {
+ it('offers the same member after Change agent when only its replacement terminal is live', async () => {
+ const rebound = tab()
+ rebound.state.agents = agents.map(a => a.id === 'a1' ? { ...a, harnessId: 'replacement' } : a)
+ const s = scoped({ tab: rebound })
+ const result = await routeTask(input, s, where as never, opener(id => daemon(id, { agents: ['replacement'] })), () => 'op')
+ expect(result).toMatchObject({ ok: true, pick: { kind: 'member', agentId: 'a1' } })
+ expect(recorded(s).command.decision.excluded.some((c: { title: string }) => c.title.startsWith('Multiply'))).toBe(false)
+ })
it('collects members and new agents, records and returns the first in the order, and never asks Jev', async () => {
const s = scoped()
const result = await routeTask(input, s, where as never, opener(), () => 'op')
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 2c1e89228..6fac3c599 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -197,6 +197,16 @@ it('resolves a native caller to its exact contribution and rechecks it before ev
expect(await t.ask({ action: 'status', tabId: 'tab', agentId: t.agentId }, owner)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })
})
+it('resolves a replacement terminal to the original stable member', async () => {
+ const t = setup()
+ t.agent.harnessId = 'replacement'
+ t.call.mockImplementation(async (_method, path) => ({ status: 200, body: { data: path.includes('/hosts/')
+ ? [{ tabId: 'tab', agent: t.agent }] : { state: { agents: [t.agent] } } } }))
+ expect(await t.ask({ action: 'status', tabId: 'tab', harnessId: 'replacement' }, owner)).toMatchObject({ ok: true })
+ expect(t.call).toHaveBeenLastCalledWith('GET', `/api/super-tabs/tab?asAgentId=${t.agentId}`, undefined)
+ expect(await t.ask({ action: 'status', tabId: 'tab', harnessId: 'native' }, owner)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })
+})
+
it('tells the Lead which branch a started agent works from, and how to choose another', async () => {
const t = setup()
const help = (await t.ask({ action: 'help' }, owner)).help as { start: string; startRequest: Record<string, unknown> }
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 3e9065a75..dc056f536 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -176,15 +176,22 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
return { ok: true, value }
}
if (payload.action === 'help') return { ok: true, help: HELP }
- const agentId = identifier(payload.agentId) ? payload.agentId
+ let agentId = identifier(payload.agentId) ? payload.agentId
: identifier(payload.harnessId) ? createHash('sha256').update(JSON.stringify([core.daemon.machineId(), payload.harnessId])).digest('hex').slice(0, 24) : null
if (!identifier(payload.tabId) || !agentId) return { error: 'INVALID_REQUEST' }
+ if (!identifier(payload.agentId) && identifier(payload.harnessId)) {
+ const rows = await backend(core, 'GET', `/api/super-tabs/hosts/${core.daemon.machineId()}`)
+ const member = list(rows).find(row => row.tabId === payload.tabId && object(row.agent).machineId === core.daemon.machineId()
+ && object(row.agent).harnessId === payload.harnessId && row.stopRequested !== true)
+ if (identifier(object(member?.agent).id)) agentId = String(object(member?.agent).id)
+ }
const path = `/api/super-tabs/${payload.tabId}`
const identity = `asAgentId=${agentId}`
const answer = object(await backend(core, 'GET', `${path}?${identity}`))
const state = object(answer.state)
const agent = Array.isArray(state.agents) ? state.agents.map(object).find(a => a.id === agentId) : undefined
- if (!agent || agent.machineId !== core.daemon.machineId() || typeof agent.harnessId !== 'string' || !core.agents.byAgent(agent.harnessId)) {
+ if (!agent || agent.machineId !== core.daemon.machineId() || typeof agent.harnessId !== 'string'
+ || identifier(payload.harnessId) && agent.harnessId !== payload.harnessId || !core.agents.byAgent(agent.harnessId)) {
return { error: 'AGENT_UNAVAILABLE', detail: 'This agent is not a running contribution on this machine.' }
}
wake()
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 6d1263e7b..91fda8015 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -65,6 +65,7 @@ const Set<String> encryptedDownTypes = {
'agent_recent',
// Writes the conversation record a switched agent reads (cli/src/lib/agentHandoff.ts).
'agent_handoff_prepare',
+ 'agent_handoff_complete',
'agent_update',
'agent_files',
'agent_read_file',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 551c8c001..8adab1ebd 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -279,6 +279,7 @@ class _AgentChange {
bool handoffFailed = false;
String? companionTarget;
bool launchFailed = false;
+ bool replacementReported = false;
}
class AgentCreationAttempt {
@@ -16024,6 +16025,29 @@ class AppNotifier extends ChangeNotifier {
return target?.launchDetail ??
'The new terminal is not available yet. Choose the agent again to check.';
}
+ if (!change.replacementReported && source.dsh != 'autonomous/pair') {
+ try {
+ final reported = await _conn(machineId).request(
+ 'agent_handoff_complete',
+ payload: {
+ 'agentId': source.id,
+ 'replacementId': nextId,
+ 'changeId': change.creation._id,
+ 'targetEngine': change.engine,
+ },
+ timeout: const Duration(seconds: 5),
+ );
+ if (reported['ok'] != true && reported['error'] != 'UNSUPPORTED') {
+ return 'The new agent started. Choose it again to finish the switch.';
+ }
+ change.replacementReported = true;
+ } catch (_) {
+ return 'The new agent started. Choose it again to finish the switch.';
+ }
+ if (!_machineWorkCurrent(machine, change.revision)) {
+ return 'This switch is no longer active.';
+ }
+ }
final terminals = allPanes
.where((p) => p.machineId == machineId && p.agentId == source.id)
.toList();
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index 3e6de8810..66d6649da 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -663,6 +663,8 @@ class WsConn {
// Conversation-derived: file names and the project folder.
'agent_handoff_prepare',
'agent_handoff_prepare_result',
+ 'agent_handoff_complete',
+ 'agent_handoff_complete_result',
'project_preview',
'project_preview_result',
// A name made from the panes' titles, asked again every few seconds
diff --git a/desktop/test/agent_change_test.dart b/desktop/test/agent_change_test.dart
index 0f9cf1fb8..218e588cd 100644
--- a/desktop/test/agent_change_test.dart
+++ b/desktop/test/agent_change_test.dart
@@ -43,6 +43,8 @@ class SwitchConnection extends MonitorConnection {
final handoffCalls = <Map<String, dynamic>>[];
final handoffTimeouts = <Duration>[];
final eventsAtHandoff = <List<String>>[];
+ final completedHandoffs = <Map<String, dynamic>>[];
+ String? completionError;
@override
Future<Map<String, dynamic>> request(
@@ -50,6 +52,10 @@ class SwitchConnection extends MonitorConnection {
Map<String, dynamic> payload = const {},
Duration timeout = const Duration(seconds: 20),
}) async {
+ if (type == 'agent_handoff_complete') {
+ completedHandoffs.add(Map.of(payload));
+ return completionError == null ? {'ok': true} : {'error': completionError};
+ }
if (type == 'agent_handoff_prepare') {
handoffCalls.add(Map.of(payload));
handoffTimeouts.add(timeout);
@@ -176,6 +182,32 @@ class SwitchDeskApi extends ApiClient {
}
void main() {
+ test('a lost completion report retries the same replacement without another launch', () async {
+ final connection = SwitchConnection()..completionError = 'SERVICE_UNAVAILABLE';
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(await app.changeAgent('m', 'a0', 'claude'), contains('new agent started'));
+ expect(app.panes.single.agentId, 'a0');
+ expect(connection.creations, hasLength(1));
+ connection.completionError = null;
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ expect(connection.creations, hasLength(1));
+ expect(connection.completedHandoffs, hasLength(2));
+ expect(connection.completedHandoffs.first, connection.completedHandoffs.last);
+ expect(connection.events, ['save/stop', 'start']);
+ });
+
+ test('an older daemon can finish Change agent without the new completion request', () async {
+ final connection = SwitchConnection()..completionError = 'UNSUPPORTED';
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ expect(connection.completedHandoffs, hasLength(1));
+ expect(app.panes.single.agentId, isNot('a0'));
+ });
+
test('Devices offers every agent while absent from the public catalog', () {
final connection = SwitchConnection();
final app = fixture(connection, harnessId: devicesHarnessId);
@@ -256,6 +288,12 @@ void main() {
expect(await app.changeAgent('m', 'a0', engine.id), isNull);
expect(connection.events, ['save/stop', 'start']);
+ expect(connection.completedHandoffs.single, {
+ 'agentId': 'a0',
+ 'replacementId': 'manager',
+ 'changeId': connection.creations.single['creationId'],
+ 'targetEngine': engine.id,
+ });
expect(connection.creations.single, containsPair('engine', engine.id));
expect(
connection.creations.single,
diff --git a/desktop/test/super_tab_roster_test.dart b/desktop/test/super_tab_roster_test.dart
index c900c046d..6889630d6 100644
--- a/desktop/test/super_tab_roster_test.dart
+++ b/desktop/test/super_tab_roster_test.dart
@@ -537,6 +537,29 @@ void main() {
},
);
+ testWidgets(
+ 'a replaced member keeps its identity and shows its new engine',
+ (tester) async {
+ final f = await fixture(tester);
+ await f.show(tester);
+ final agents = f.server.state['agents'] as List;
+ agents[0]['harnessId'] = 'replacement';
+ agents[0]['configuration'] = {'engine': 'claude', 'model': 'sonnet'};
+ await f.controller.refresh();
+ await tester.pumpAndSettle();
+ expect(f.controller.snapshot!.agents.first.id, 'agent-0');
+ expect(f.controller.snapshot!.agents.first.harnessId, 'replacement');
+ expect(f.controller.snapshot!.agents.first.engine, 'claude');
+ await tester.tap(f.row(0));
+ await tester.pumpAndSettle();
+ expect(find.text('Claude'), findsOneWidget);
+ expect(find.text('sonnet'), findsOneWidget);
+ await tester.tap(find.widgetWithText(TextButton, 'Close'));
+ await tester.pumpAndSettle();
+ await f.close(tester);
+ },
+ );
+
testWidgets(
'owner confirms Remove from Swarm without stopping the native session',
(tester) async {
diff --git a/docs/superpowers/specs/2026-10-22-swarm-agent-replacement-design.md b/docs/superpowers/specs/2026-10-22-swarm-agent-replacement-design.md
new file mode 100644
index 000000000..d05cc7092
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-22-swarm-agent-replacement-design.md
@@ -0,0 +1,53 @@
+# Swarm membership after Change agent
+
+Approved by the workgroup Lead on 2026-10-22.
+
+## Contract
+
+- SR-1: A successful Change agent preserves the member ID, name, display name,
+ project, groups, Lead role, assignment, work decision and message history.
+- SR-2: Only the recorded machine's authenticated host may replace its terminal.
+ The old terminal, machine, account and project must match; a terminal already
+ held by another member is refused. Repeating the same replacement is a no-op.
+- SR-3: The current engine and observed model follow the replacement. Delayed
+ configuration observations cannot overwrite a newer replacement.
+- SR-4: Pending input moves only with proof it was not submitted. Answered,
+ delivered and uncertain receipts remain intact. Send again addresses the
+ current terminal. Active execution follows the replacement.
+- SR-5: The host recovers switches made before this change from a committed
+ handoff and the exact successful creation receipt. A matching folder alone
+ never authorizes replacement. Missing or ambiguous evidence withholds it.
+
+## Design
+
+Keep the stable member and add a fenced, authenticated replacement command.
+Change agent reports its source, replacement and creation intent after launch.
+The service verifies retained native facts and saves a durable replacement
+record. The host reconciles records before delivery, and also discovers legacy
+committed handoffs whose creation intent identifies a live replacement in the
+same project. Backend state and active execution change transactionally.
+Deliveries already address the stable member; host journal entries that were
+held before submission change terminal without replaying submitted input.
+Desktop reads the member's current configuration as it does today.
+
+Remove/re-add was rejected because it loses identity. Inferring replacements
+from folder or engine alone was rejected because unrelated sessions share them.
+
+## Validation and delivery
+
+First add failing backend, CLI and caller regression tests. Run affected tests
+and typechecks, required CLI coverage gates, isolated Swarm end-to-end tests,
+and the available real multiplexer checks. Automatic PR CI supplies the full
+affected component suites. Keep independent checks concurrent within capacity.
+Use a draft PR while work changes, mark ready once final, and do not merge.
+Prove a disposable switch and one delivery with the isolated daemon and local
+backend fixtures before marking the PR ready. Per the Lead's clarification,
+the owner's Launch Builder recovery and assignability check are post-release;
+record them as unverified here until the Lead runs them with the Builder.
+
+Release backend first, then CLI; Desktop and TUI ship caller reporting changes
+after the CLI supports them. Older clients recover through verified handoffs.
+No publication or merge is authorized by this workgroup assignment.
+
+Self-review: all requirements have acceptance evidence planned; no schema
+migration is expected, and no unresolved design placeholders remain.
diff --git a/tui/src/agent_switch.rs b/tui/src/agent_switch.rs
index 8fd9825b1..eb9da4651 100644
--- a/tui/src/agent_switch.rs
+++ b/tui/src/agent_switch.rs
@@ -21,7 +21,7 @@ impl Selection {
}
#[derive(Clone, Copy, Debug, PartialEq)]
-enum Stage { Handoff, Recent, Stop, Create, Check, Terminal, Failed }
+enum Stage { Handoff, Recent, Stop, Create, Check, Terminal, Report, Failed }
#[derive(Clone)]
struct Change {
@@ -38,6 +38,7 @@ struct Change {
closed: bool,
creation_sent: bool,
creation_finished: bool,
+ replacement_reported: bool,
next: Option<String>,
next_row: Option<Value>,
error: String,
@@ -416,7 +417,7 @@ pub fn choose(app: &mut App, mut picker: Picker, selected: &str) {
let context_loaded = retained.is_some();
let handoff = retained.filter(|_| crate::agent_handoff::supported(engine)).and_then(|c| c.handoff.clone());
app.agent_switch.changes.insert(id.clone(), Change { id: id.clone(), source, identity: selection.identity, engine: engine.into(), stage: Stage::Handoff,
- handoff, context_loaded, handoff_failed: retained.is_some_and(|c| c.handoff_failed), handoff_conflict: false, preserving: closed, closed, creation_sent: false, creation_finished: false, next: None, next_row: None, error: String::new(), since: Instant::now() });
+ handoff, context_loaded, handoff_failed: retained.is_some_and(|c| c.handoff_failed), handoff_conflict: false, preserving: closed, closed, creation_sent: false, creation_finished: false, replacement_reported: false, next: None, next_row: None, error: String::new(), since: Instant::now() });
app.modal = Some(Modal::Picker { kind: PickerKind::AgentSwitch, picker });
if closed && context_loaded { create(app, &id); } else { prepare(app, &id); }
}
@@ -626,6 +627,12 @@ fn attach(app: &mut App, id: &str) {
}
return;
}
+ if !c.replacement_reported {
+ let payload = json!({"agentId":c.source.id, "replacementId":next, "changeId":id, "targetEngine":c.engine});
+ app.agent_switch.changes.get_mut(id).unwrap().stage = Stage::Report;
+ request(app, id, "agent_handoff_complete", payload, 5, reported);
+ return;
+ }
let machine = c.source.machine_id.clone(); let old = c.source.id.clone(); let next = next.clone();
let target = theme::engine_label(&c.engine).to_string();
let no_history = c.context_loaded && c.handoff.is_none();
@@ -646,6 +653,18 @@ fn attach(app: &mut App, id: &str) {
app.say(message, theme::ONLINE);
}
+fn reported(app: &mut App, id: &str, reply: Reply) {
+ if !valid(app, id) { return }
+ // Older daemons recover supported handoffs on their next host startup. A transient failure
+ // on a new daemon keeps this same launch intent, so retry can finish without another launch.
+ let accepted = reply.as_ref().ok().is_some_and(|r| r["ok"] == true || r["error"] == "UNSUPPORTED")
+ || reply.as_ref().err().is_some_and(|e| e.code == "UNSUPPORTED");
+ if !accepted { fail(app, id, "The new agent started. Choose it again to finish the switch."); return }
+ let c = app.agent_switch.changes.get_mut(id).unwrap();
+ c.replacement_reported = true; c.stage = Stage::Terminal;
+ attach(app, id);
+}
+
/// Keep a view while its source has stopped and the replacement is being checked, including
/// an ambiguous launch. An explicit close still removes that view normally.
pub fn preserves(app: &App, pane: u64) -> bool {
@@ -708,6 +727,43 @@ mod tests {
fn sent(app: &App, ty: &str) -> Vec<Value> { app.agent_switch.sent.iter().filter(|(_, t, _)| t == ty).map(|(_, _, p)| p.clone()).collect() }
+ // Existing view/layout fixtures acknowledge the newly added report just as their daemon
+ // acknowledges creation. The report-specific fixtures below control that reply explicitly.
+ fn acknowledge_reports(app: &mut App) {
+ let ids: Vec<_> = app.agent_switch.changes.iter().filter(|(_, c)| c.stage == Stage::Report).map(|(id, _)| id.clone()).collect();
+ for id in ids { reported(app, &id, Ok(json!({"ok":true}))); }
+ }
+ fn created(app: &mut App, id: &str, reply: Reply) { super::created(app, id, reply); acknowledge_reports(app); }
+ fn checked(app: &mut App, id: &str, reply: Reply) { super::checked(app, id, reply); acknowledge_reports(app); }
+ fn tick(app: &mut App) { super::tick(app); acknowledge_reports(app); }
+
+ #[tokio::test]
+ async fn completed_change_reports_the_native_replacement_before_moving_views() {
+ let mut app = app();
+ let id = start(&mut app, "claude"); handoff(&mut app, &id);
+ stopped(&mut app, &id, Ok(json!({"closed":true})));
+ super::created(&mut app, &id, Ok(ready(&id, true)));
+ assert_eq!(sent(&app, "agent_handoff_complete"), vec![json!({"agentId":"a1", "replacementId":"replacement", "changeId":id, "targetEngine":"claude"})]);
+ assert_eq!(app.panes[&1].agent_id, "a1");
+ reported(&mut app, &id, Ok(json!({"ok":true})));
+ assert_eq!(app.panes[&1].agent_id, "replacement");
+ }
+
+ #[tokio::test]
+ async fn a_lost_replacement_report_retries_the_same_launch_without_another_stop() {
+ let mut app = app(); let id = start(&mut app, "claude"); handoff(&mut app, &id);
+ stopped(&mut app, &id, Ok(json!({"closed":true})));
+ super::created(&mut app, &id, Ok(ready(&id, true)));
+ reported(&mut app, &id, Err(RpcError::new("TIMEOUT", "")));
+ assert_eq!(app.panes[&1].agent_id, "a1");
+ select(&mut app, "claude");
+ checked(&mut app, &id, Ok(ready(&id, true)));
+ assert_eq!(app.panes[&1].agent_id, "replacement");
+ assert_eq!(sent(&app, "agent_create").len(), 1);
+ assert_eq!(sent(&app, "agent_close").len(), 1);
+ assert_eq!(sent(&app, "agent_handoff_complete").len(), 2);
+ }
+
#[tokio::test]
async fn replacement_keeps_its_view_until_workspace_ack_and_retry_does_not_launch_again() {
for mode in [DeskMode::Sync, DeskMode::Account] {