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.

Swarm: a PM's pane switches its engine with Change agent, as any pane (Dee) (#2493)

0xken155470f4782303
diff --git a/cli/e2e/swarmSwitch.e2e.ts b/cli/e2e/swarmSwitch.e2e.ts
index d88abdf4d..762276365 100644
--- a/cli/e2e/swarmSwitch.e2e.ts
+++ b/cli/e2e/swarmSwitch.e2e.ts
@@ -130,6 +130,45 @@ describe('the Swarm switch', () => {
expect(loaded.some((url) => url.includes('/src/services/superTabsProcess.ts'))).toBe(true)
}, 240_000)
+ // Dee, 11-01: a Product Manager's engine is switched from its pane, as any pane's (Change agent). Its machine lets its stop
+ // through only as that switch, which its owner prepared moments before; every other close, and a second switch while it
+ // runs, is refused, and the switch is kept on disk so its host holds off reopening it (superTabs/leadSwitch.ts).
+ it('on, a Lead stops only for the engine switch its owner prepared, once, and its switch is kept for its host', async () => {
+ const { d, client } = await fresh({ HARNESS_SWARM: '' })
+ const agent = await create(d, client, 'swarm-lead-switch')
+ await turn(client, agent.id, 'a Product Manager plans the work')
+ await until('the Swarm\'s process, woken by its saved state', () => swarmStarts(d) > 0 || null, 60_000, 200)
+ swarmState(d, agent.id)
+ const CHANGE = '0123456789abcdef0123456789abcdef', OTHER = 'fedcba9876543210fedcba9876543210'
+ const named = (changeId: string) => client.request('agent_close', { agentId: agent.id, sessionId: agent.sessionId, createdAt: agent.createdAt,
+ mode: 'now', changeId }, 60_000)
+ const refused = { error: 'LEAD_PROTECTED', detail: 'This harness is the Product Manager of a Swarm project. Delete its project first to stop it.' }
+ // Not a switch, or one nobody prepared: refused as before.
+ expect(await close(client, agent)).toMatchObject(refused)
+ expect(await named(CHANGE)).toMatchObject(refused)
+ const prepared = await client.request('agent_handoff_prepare', { agentId: agent.id, changeId: CHANGE, targetEngine: 'codex' }, 30_000)
+ expect(prepared.error, JSON.stringify(prepared)).toBeUndefined()
+ // Prepared, but a plain close or another switch's close still is not it.
+ expect(await close(client, agent)).toMatchObject(refused)
+ expect(await named(OTHER)).toMatchObject(refused)
+ expect((await row(client, agent.id))?.status).toBe('active')
+ expect(await named(CHANGE)).toMatchObject({ closed: true })
+ await until('the switch to stop the Product Manager', async () => ((await row(client, agent.id))?.status ?? 'stopped') !== 'active' || null, 60_000, 500)
+ // A second switch while this one runs is refused.
+ expect(await named(OTHER)).toMatchObject({ error: 'LEAD_SWITCHING' })
+ expect(readdirSync(join(d.dataDir, 'super-tabs', 'lead-switch'))).toHaveLength(1)
+ // Security reviews 1 and 2 of #2493: nothing else gets through in the moments after, whoever asks. Stop Harness and the
+ // deletion of its saved conversation, which its host reopens, are refused with today's words. A script's close of it is
+ // answered as for any session closed already, and changes nothing: its saved conversation stays for its host to reopen.
+ expect(await client.request('agent_delete', { agentId: agent.id }, 60_000)).toMatchObject(refused)
+ const createdAt = Date.parse(agent.createdAt)
+ const review = await client.request('agent_purge', { agentId: agent.id, sessionId: agent.sessionId, createdAt, mode: 'inspect' }, 60_000)
+ expect(await client.request('agent_purge', { agentId: agent.id, sessionId: agent.sessionId, createdAt, mode: 'delete', reviewId: review.reviewId }, 60_000))
+ .toMatchObject(refused)
+ expect(await close(client, agent)).toMatchObject({ closed: true })
+ expect(await row(client, agent.id)).toMatchObject({ sessionId: agent.sessionId, status: expect.not.stringMatching(/^active$/) })
+ }, 240_000)
+
// Diego's Buddy, 10-30: closing the tab that showed it stopped it. A close (a window's, `harness close`, the cleanup) never
// stops a Buddy the host keeps, and says it kept running; Stop Harness, the machine owner's own action, still stops it
// (the Product Manager, 10-30).
diff --git a/cli/src/core/agents/close.spec.ts b/cli/src/core/agents/close.spec.ts
index 826cdfc1c..fc0b26387 100644
--- a/cli/src/core/agents/close.spec.ts
+++ b/cli/src/core/agents/close.spec.ts
@@ -54,8 +54,11 @@ describe('closing agents no window shows', () => {
// Diego's Buddy, 10-30: the close service refuses a Buddy only if the guard the core is handed reaches it.
it('hands the close service the Lead and Buddy guards it was given', () => {
const leadProtected = (id: string) => id === 'lead', buddyProtected = (id: string) => id === 'buddy'
- const { close } = setup({ leadProtected, buddyProtected })
+ const leadSwitching = (id: string) => id === 'lead', leadSwitchEnded = vi.fn()
+ const { close } = setup({ leadProtected, leadSwitching, leadSwitchEnded, buddyProtected })
expect([close.leadProtected?.('lead'), close.buddyProtected?.('buddy'), close.buddyProtected?.('lead')]).toEqual([true, true, false])
+ expect(close.leadSwitching).toBe(leadSwitching)
+ expect(close.leadSwitchEnded).toBe(leadSwitchEnded)
})
it('reads from its pane whether it waits at a question its engine asks before any conversation', async () => {
@@ -287,6 +290,17 @@ describe('agent_close', () => {
ask({ request: vi.fn(async () => ({})) }, { ...target, mode: 'now', onlyIfHidden: 'yes' })
})
+ // Dee, 11-01: a Swarm Product Manager's close passes its guard only as the switch it names (lib/closeAgentService.ts).
+ it('passes on the Change agent switch a close names, only in the shape Change agent makes it', () => {
+ const request = vi.fn(async () => ({}))
+ ask({ request }, { ...target, mode: 'now', changeId: 'e'.repeat(32) })
+ expect(request).toHaveBeenLastCalledWith({ ...target, mode: 'now', changeId: 'e'.repeat(32) })
+ for (const changeId of ['E'.repeat(32), 'e'.repeat(31), 7, '../x']) {
+ ask({ request }, { ...target, mode: 'now', changeId })
+ expect(request).toHaveBeenLastCalledWith({ ...target, mode: 'now' })
+ }
+ })
+
it('refuses a request it cannot read, and says when the close failed or there is no service to ask', async () => {
const request = vi.fn(async () => { throw new Error('tmux gone') })
for (const wrong of [{ ...target, mode: 'later' }, { ...target, mode: 3 }, { ...target, createdAt: 7, mode: 'now' }, { ...target, sessionId: null, mode: 'now' }, { mode: 'now' }]) {
diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.ts
index 4d5827068..01c8ba695 100644
--- a/cli/src/core/agents/close.ts
+++ b/cli/src/core/agents/close.ts
@@ -36,7 +36,11 @@ export interface ClosingDeps {
/** The agents stopped and kept: a close of one already closed is answered closed. */
stoppedAgents?: Pick<StoppedAgentStore, 'get' | 'resumeReservedAt'>
/** Whether the agent may be a Lead, which is never closed, as core/main.ts hands it in; absent, none is. */
- leadProtected?: (agentId: string) => boolean
+ leadProtected?: (agentId: string, changeId?: string) => boolean
+ /** Whether another switch of a Lead's engine is running, as core/main.ts hands it in; absent, none is. */
+ leadSwitching?: (agentId: string, changeId: string) => boolean
+ /** A Lead's switch's close ended, as core/main.ts hands it in; absent, nothing is told. */
+ leadSwitchEnded?: (agentId: string, changeId: string, stopped: boolean) => void
/** Whether the agent may be a Swarm Buddy, which a close never stops, as core/main.ts hands it in; absent, none is. */
buddyProtected?: (agentId: string) => boolean
}
@@ -46,7 +50,7 @@ export const CLOSE_READ_RECONNECT_MS = 10_000
export function createAgentClosing({
readScreen, registry, cleanupTabs, watcher, captureTerminal, sessionTurnState, openQuestions, terminals, sessionCheckpoints,
- stopAgent, announceSession, engineReady, stoppedAgents, nativeRecoveryReady = () => true, leadProtected, buddyProtected,
+ stopAgent, announceSession, engineReady, stoppedAgents, nativeRecoveryReady = () => true, leadProtected, leadSwitching, leadSwitchEnded, buddyProtected,
}: ClosingDeps) {
const ready = (s: RegisteredSession): boolean =>
!s.identityHold && !s.admissionHold && !s.interpretationHold && nativeRecoveryReady(s)
@@ -103,6 +107,8 @@ export function createAgentClosing({
stop: stopAgent,
changed: announceSession,
leadProtected,
+ leadSwitching,
+ leadSwitchEnded,
buddyProtected,
// Not live, not being resumed, and kept as stopped with the conversation the close names: it was closed. A record
// that cannot be read says nothing, and the close is answered as changed, as before.
@@ -161,7 +167,9 @@ export function createCloseRequests({ cleanupPreview, closeAgentService }: {
}
// Saving/exit may take seconds; terminal input and unrelated agents keep flowing.
void service.request({ agentId, sessionId, createdAt, mode: mode as CloseMode,
- ...(payload.onlyIfHidden === true ? { onlyIfHidden: true } : {}) })
+ ...(payload.onlyIfHidden === true ? { onlyIfHidden: true } : {}),
+ // Change agent names its switch, which a Swarm Product Manager's close guard checks (lib/closeAgentService.ts).
+ ...(typeof payload.changeId === 'string' && /^[0-9a-f]{32}$/.test(payload.changeId) ? { changeId: payload.changeId } : {}) })
.then(result => reply(result), () => reply({ error: 'CLOSE_FAILED' }))
}
return { preview, close }
diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.ts
index 7eb4ac8d1..18e5f9a5e 100644
--- a/cli/src/core/agents/lifecycle.spec.ts
+++ b/cli/src/core/agents/lifecycle.spec.ts
@@ -116,6 +116,21 @@ describe('stopping, purging and resuming an agent', () => {
expect(stop).toHaveBeenCalledWith('gone', undefined)
})
+ // Security review 1 of #2493: only the stop a Product Manager's switch makes carries that switch to the guard; every other
+ // stop asks without one (superTabs/leadSwitch.ts decides).
+ it('asks the Lead guard with the switch a stop carries, and without one for any other stop', async () => {
+ const CHANGE = 'a'.repeat(32)
+ const leadProtected = vi.fn((agentId: string, leadSwitch?: string) => agentId === 'a1' && leadSwitch !== CHANGE)
+ const { lifecycle } = setup({ leadProtected })
+ const stop = vi.mocked(createStopAgentService).mock.results[0].value as ReturnType<typeof vi.fn>
+ await expect(lifecycle.stopAgent('a1')).rejects.toBeInstanceOf(LeadProtectedError)
+ await expect(lifecycle.stopAgent('a1', { leadSwitch: 'b'.repeat(32) })).rejects.toBeInstanceOf(LeadProtectedError)
+ expect(stop).not.toHaveBeenCalled()
+ await lifecycle.stopAgent('a1', { leadSwitch: CHANGE })
+ expect(stop).toHaveBeenCalledWith('a1', { leadSwitch: CHANGE })
+ expect(leadProtected.mock.calls.map(call => call[1])).toEqual([undefined, 'b'.repeat(32), CHANGE])
+ })
+
describe('purge', () => {
it('sees live and stopped agents, stops through the stop service, and checkpoints where stop does', () => {
const { deps, lifecycle, purge } = setup()
@@ -125,6 +140,15 @@ describe('stopping, purging and resuming an agent', () => {
expect(purge.stopped).toBe(deps.stoppedAgents)
expect(purge.checkpoints).toBe(deps.sessionCheckpoints)
expect(purge.stop).toBe(lifecycle.stopAgent)
+ expect(purge.leadProtected).toBeUndefined()
+ })
+
+ // Security review 2 of #2493: a Product Manager's saved conversation is never deleted; the purge asks the same guard.
+ it('hands the purge the Lead guard, asked without a switch', () => {
+ const leadProtected = vi.fn((agentId: string) => agentId === 'a1')
+ const { purge } = setup({ leadProtected })
+ expect([purge.leadProtected?.('a1'), purge.leadProtected?.('a2')]).toEqual([true, false])
+ expect(leadProtected.mock.calls).toEqual([['a1'], ['a2']])
})
it('asks the pane, through the core, whether an agent waits at its folder-trust question', () => {
diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.ts
index 922617fc9..015ccd2bb 100644
--- a/cli/src/core/agents/lifecycle.ts
+++ b/cli/src/core/agents/lifecycle.ts
@@ -62,7 +62,7 @@ export interface LifecycleDeps {
/** An agent a move a dead daemon left may still run beside (main.ts `moveHeld`): no engine of it starts this start. */
moveHeld?: (agentId: string) => boolean
/** Whether the agent is a Lead the core must never stop, as core/main.ts hands it in; absent, none is. */
- leadProtected?: (agentId: string) => boolean
+ leadProtected?: (agentId: string, leadSwitch?: string) => boolean
}
/** The owner, 2026-10-23: the Lead of an active project is never stopped, in any case; deleting its project closes it. */
@@ -94,13 +94,14 @@ export function createAgentLifecycle({
*/
const stopAgent: typeof stop = (target, options) => {
const agentId = registry.resolve(target)?.agentId ?? target
- if (leadProtected?.(agentId)) return Promise.reject(new LeadProtectedError())
+ if (leadProtected?.(agentId, options?.leadSwitch)) return Promise.reject(new LeadProtectedError())
return stop(target, options).then(() => { stopped?.(agentId) })
}
const purgeAgentService = new PurgeAgentService({
live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stoppedAgents.list()],
stopped: stoppedAgents, checkpoints: sessionCheckpoints, stop: stopAgent,
restarting: id => restartJobs.busy(id) || stopJobs.has(id),
+ ...(leadProtected ? { leadProtected: (id: string) => leadProtected(id) } : {}),
atFolderTrust,
atEmptyComposer,
deleted: s => {
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index f18c1a9d4..cbda2d1da 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2878,7 +2878,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
stopped: (agentId) => ports.agentCleanup?.closed(agentId),
moveHeld: (agentId) => moveHeld.has(agentId),
// The Lead of an active Swarm project is never stopped (owner, 2026-10-23); its host keeps the list (superTabs/retention.ts).
- ...(swarm ? { leadProtected: (agentId: string) => swarm.mayBeLead(env.ADAPTER_DATA_DIR, agentId) } : {}),
+ ...(swarm ? { leadProtected: (agentId: string, leadSwitch?: string) => swarm.mayBeLead(env.ADAPTER_DATA_DIR, agentId, leadSwitch) } : {}),
})
const stopJobs = lifecycle.stopJobs
launchCancelled = id => stopJobs.has(id)
@@ -2906,7 +2906,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
stoppedAgents,
// A Swarm Buddy keeps running when a window closes its view (Diego, 10-30); Stop Harness above still stops it.
...(swarm ? {
- leadProtected: (agentId: string) => swarm.mayBeLead(env.ADAPTER_DATA_DIR, agentId),
+ leadProtected: (agentId: string, changeId?: string) => swarm.leadCloseProtected(env.ADAPTER_DATA_DIR, agentId, changeId),
+ leadSwitching: (agentId: string, changeId: string) => swarm.leadSwitching(env.ADAPTER_DATA_DIR, agentId, changeId),
+ leadSwitchEnded: (agentId: string, changeId: string, stopped: boolean) => swarm.leadSwitchEnded(env.ADAPTER_DATA_DIR, agentId, changeId, stopped),
buddyProtected: (agentId: string) => swarm.mayBeBuddy(env.ADAPTER_DATA_DIR, agentId),
} : {}),
})
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index c4eb65d2f..a19ab8d10 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -1,6 +1,6 @@
import { screenFor } from '../engines/screens.js'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { BUDDY_PROTECTED_DETAIL, CloseAgentService, LEAD_PROTECTED_DETAIL, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'
+import { BUDDY_PROTECTED_DETAIL, CloseAgentService, LEAD_PROTECTED_DETAIL, LEAD_SWITCHING_DETAIL, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'
import { registry, type RegisteredSession } from './registry.js'
import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
@@ -65,6 +65,63 @@ it.each(['now', 'idle', 'after_task'] as const)('refuses to close a Swarm Lead (
svc.dispose()
})
+// Dee, 11-01: a Product Manager's engine is switched from its pane, as any pane's. Only the `now` close of the switch its owner
+// prepared passes the Lead guard (superTabs/leadSwitch.ts decides); every other close of it is refused with today's words.
+it('hands a Lead guard the switch only a now close names, and stops the Lead its switch was let through for', async () => {
+ const CHANGE = 'c'.repeat(32)
+ const leadProtected = vi.fn((id: string, changeId?: string) => id === row.agentId && changeId !== CHANGE)
+ const leadSwitchEnded = vi.fn()
+ const svc = new CloseAgentService({ ...deps, leadProtected, leadSwitchEnded })
+ for (const mode of ['idle', 'after_task'] as const) {
+ expect(await svc.request({ ...request(mode), changeId: CHANGE })).toEqual({ error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL })
+ }
+ expect(leadProtected.mock.calls.map(call => call[1])).toEqual([undefined, undefined])
+ expect(await svc.request(request('now'))).toEqual({ error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL })
+ expect(LEAD_PROTECTED_DETAIL).toBe('This harness is the Product Manager of a Swarm project. Delete its project first to stop it.')
+ expect(deps.stop).not.toHaveBeenCalled()
+ expect(await svc.request({ ...request('now'), changeId: CHANGE })).toEqual({ closed: true })
+ expect(leadProtected).toHaveBeenLastCalledWith(row.agentId, CHANGE)
+ expect(deps.stop).toHaveBeenCalledTimes(1)
+ // The switch rides with that one stop, so the core's stop guard lets it, and only it, through (security review 1 of #2493).
+ expect(vi.mocked(deps.stop).mock.calls[0][1]).toMatchObject({ leadSwitch: CHANGE })
+ // Its end is told once, stopped; the refused closes before it told nothing (security review 2 of #2493).
+ expect(leadSwitchEnded.mock.calls).toEqual([[row.agentId, CHANGE, true]])
+ svc.dispose()
+})
+
+// Security review 2 of #2493: a switch's close that fails ends its pass too, so nothing stays open after it.
+it('tells a switch\'s end when its close fails or throws, unstopped, and no stop carries a switch but its own', async () => {
+ const CHANGE = 'e'.repeat(32)
+ const leadSwitchEnded = vi.fn()
+ vi.mocked(deps.checkpoint).mockRejectedValueOnce(new Error('disk full'))
+ const svc = new CloseAgentService({ ...deps, leadProtected: () => false, leadSwitchEnded })
+ expect(await svc.request({ ...request('now'), changeId: CHANGE })).toMatchObject({ error: expect.any(String) })
+ expect(leadSwitchEnded).toHaveBeenLastCalledWith(row.agentId, CHANGE, false)
+ vi.spyOn(svc as unknown as { execute: () => Promise<unknown> }, 'execute').mockRejectedValueOnce(new Error('gone'))
+ await expect(svc.request({ ...request('now'), changeId: CHANGE })).rejects.toThrow('gone')
+ expect(leadSwitchEnded).toHaveBeenLastCalledWith(row.agentId, CHANGE, false)
+ // A close that names no switch tells nothing and hands its stop none.
+ leadSwitchEnded.mockClear()
+ expect(await svc.request(request('now'))).toEqual({ closed: true })
+ expect(leadSwitchEnded).not.toHaveBeenCalled()
+ expect(vi.mocked(deps.stop).mock.calls.at(-1)![1]).not.toHaveProperty('leadSwitch')
+ svc.dispose()
+})
+
+// A second switch from another window: the first may have stopped the Lead already, where a close is answered closed and
+// would start a second replacement. Refused before the agent is even looked at.
+it('refuses a Lead switch while another runs, before the agent is looked at', async () => {
+ const leadSwitching = vi.fn((_id: string, changeId: string) => changeId === 'd'.repeat(32))
+ const svc = new CloseAgentService({ ...deps, leadSwitching, closedAlready: () => true })
+ registry.removeAgent(row.agentId)
+ expect(await svc.request({ ...request('now'), changeId: 'd'.repeat(32) })).toEqual({ error: 'LEAD_SWITCHING', detail: LEAD_SWITCHING_DETAIL })
+ // Not a switch: answered as before.
+ expect(await svc.request({ ...request('idle'), changeId: 'd'.repeat(32) })).toEqual({ closed: true })
+ expect(await svc.request(request('now'))).toEqual({ closed: true })
+ expect(leadSwitching).toHaveBeenCalledTimes(1)
+ svc.dispose()
+})
+
// Diego's Buddy, 10-30: closing the tab that showed it stopped it, and two proposals waited 30 minutes. A close of a Buddy
// is refused at once, before anything is read, saved or stopped, and says it kept running: a window closes only its view.
it.each(['now', 'idle', 'after_task'] as const)('refuses to close a Swarm Buddy (%s), which keeps running', async mode => {
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index e5023b4b2..39dc05131 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -18,10 +18,12 @@ export type AgentClosePlan = {
}
/** Why the Lead of an active Swarm project is not closed (owner, 2026-10-23: it is never stopped, in any case). */
export const LEAD_PROTECTED_DETAIL = 'This harness is the Product Manager of a Swarm project. Delete its project first to stop it.'
+export const LEAD_SWITCHING_DETAIL = 'This Product Manager is already switching its agent. Wait for it to finish.'
/** Why a Swarm Buddy is not closed (Diego, 10-30: closing the tab that showed his Buddy stopped it, and two proposals
* waited 30 minutes). A window closes only its view; the machine's owner still stops it with Stop Harness. */
export const BUDDY_PROTECTED_DETAIL = 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.'
-export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean; onlyIfOriginalLaunch?: boolean; expiresAt?: number }
+/** `changeId`: the Change agent switch this `now` close is part of, which its handoff was prepared for (superTabs/leadSwitch.ts). */
+export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean; onlyIfOriginalLaunch?: boolean; expiresAt?: number; changeId?: string }
/** `withoutConversation`: closed while still starting, before Harness could read its conversation, so none is kept. */
/** `keptRunning`: a close refused for a session that keeps running on purpose (a Swarm Buddy): a window closes its view and
* stops nothing, as it does for a Swarm pane (desktop app_state.dart `canStop`). */
@@ -118,8 +120,14 @@ export interface CloseAgentServiceDeps {
openTabs?: { assertHidden(s: RegisteredSession): Promise<void>; isHidden(s: RegisteredSession): boolean }
/** Whether the conversation [request] names is closed already: no longer live, and kept as stopped. */
closedAlready?(request: AgentCloseRequest): boolean
- /** Whether the agent may be the Lead of an active Swarm project (superTabs/retention.ts `mayBeLead`): never closed. */
- leadProtected?(agentId: string): boolean
+ /** Whether the agent may be the Lead of an active Swarm project (superTabs/leadSwitch.ts `leadCloseProtected`): never closed,
+ * but by the `now` close of a switch of its engine its owner prepared ([changeId]). */
+ leadProtected?(agentId: string, changeId?: string): boolean
+ /** Whether another switch of this Lead's engine than [changeId] is running (superTabs/leadSwitch.ts `leadSwitching`). */
+ leadSwitching?(agentId: string, changeId: string): boolean
+ /** The `now` close naming switch [changeId] ended, [stopped] or not (superTabs/leadSwitch.ts `leadSwitchEnded`): the pass its
+ * stop was given is gone either way. */
+ leadSwitchEnded?(agentId: string, changeId: string, stopped: boolean): void
/** Whether the agent may be a Swarm Buddy (superTabs/retention.ts `mayBeBuddy`): a close never stops it. Stop Harness does. */
buddyProtected?(agentId: string): boolean
/** Whether its pane shows a question the engine asks before any conversation: the folder's trust, or an MCP server the
@@ -171,10 +179,16 @@ export class CloseAgentService {
request(request: AgentCloseRequest): Promise<AgentCloseResult> {
const current = this.deps.registry.byAgent(request.agentId)
+ // A Product Manager's switch named while another runs is refused before anything else: the first one may have stopped it
+ // already, and a stopped agent's close would answer closed, starting a second replacement (Lead, 11-01).
+ const changeId = request.mode === 'now' ? request.changeId : undefined
+ if (changeId && this.deps.leadSwitching?.(request.agentId, changeId)) {
+ return Promise.resolve({ error: 'LEAD_SWITCHING', detail: LEAD_SWITCHING_DETAIL })
+ }
if (!matches(current, request, this.now())) return Promise.resolve(this.changed(request))
if (request.mode === 'cancel') { this.cancel(request.agentId); return Promise.resolve({ cancelled: true }) }
// Refused before anything is read or saved: a Close after task once answered a Lead "deferred" (the review of #1635).
- if (request.mode !== 'inspect' && this.deps.leadProtected?.(request.agentId)) {
+ if (request.mode !== 'inspect' && this.deps.leadProtected?.(request.agentId, changeId)) {
return Promise.resolve({ error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL })
}
const buddy = this.deps.buddyProtected?.(request.agentId) === true
@@ -200,7 +214,15 @@ export class CloseAgentService {
})
this.jobs.set(key, job)
this.queues.set(request.agentId, job)
- return buddy ? job.then(keptRunning) : job
+ // A switch's close ends its pass, stopped or not: nothing is left open after it (security review 2 of #2493).
+ const answered = !changeId ? job : job.then(result => {
+ this.deps.leadSwitchEnded?.(request.agentId, changeId, result.closed === true)
+ return result
+ }, (error: unknown) => {
+ this.deps.leadSwitchEnded?.(request.agentId, changeId, false)
+ throw error
+ })
+ return buddy ? answered.then(keptRunning) : answered
}
/**
@@ -321,6 +343,8 @@ export class CloseAgentService {
if (request.mode === 'idle' && activity !== 'idle') return { error: 'SESSION_NOT_IDLE', activity }
await this.deps.stop(s.agentId, {
...(withoutConversation ? { withoutConversation: () => { unkept = true } } : {}),
+ // The pass a Product Manager's switch earned rides with this one stop, and with no other (security review 1 of #2493).
+ ...(request.mode === 'now' && request.changeId ? { leadSwitch: request.changeId } : {}),
current: () => {
const latest = current()
if (!latest) return false
diff --git a/cli/src/lib/purgeAgentService.spec.ts b/cli/src/lib/purgeAgentService.spec.ts
index 309cf744a..630f90475 100644
--- a/cli/src/lib/purgeAgentService.spec.ts
+++ b/cli/src/lib/purgeAgentService.spec.ts
@@ -151,6 +151,21 @@ it('previews without stopping, then deletes only reviewed history and checkpoint
expect(await remove(plan.reviewId)).toHaveProperty('error')
expect(stop).toHaveBeenCalledOnce()
})
+// Security review 2 of #2493: a Swarm Product Manager stopped by its engine's switch, or by a crash, is reopened on its saved
+// conversation; deleting it left nothing to reopen. Its review is read as any other; its deletion is refused before anything.
+it('refuses to delete a Swarm Product Manager\'s saved conversation, live or stopped, deleting and stopping nothing', async () => {
+ const leadProtected = vi.fn((id: string) => id === session.agentId)
+ const svc = new PurgeAgentService({ live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stopped.list()],
+ stopped, checkpoints, stop, restarting: () => false, deleted, now: () => now, leadProtected })
+ const plan = await svc.request({ ...target, mode: 'inspect' })
+ expect(plan.reviewId).toEqual(expect.any(String))
+ expect(await svc.request({ ...target, mode: 'delete', reviewId: String(plan.reviewId) }))
+ .toEqual({ error: 'LEAD_PROTECTED', detail: 'This harness is the Product Manager of a Swarm project. Delete its project first to stop it.' })
+ expect(existsSync(session.transcriptPath!)).toBe(true)
+ expect(stop).not.toHaveBeenCalled()
+ expect(deleted).not.toHaveBeenCalled()
+})
+
it('rejects an absent, expired, rotated or replaced review before stopping', async () => {
expect(await remove('never-reviewed')).toHaveProperty('error')
const expired = await review(); now += 120_001
diff --git a/cli/src/lib/purgeAgentService.ts b/cli/src/lib/purgeAgentService.ts
index ca626efd1..d18f7a16f 100644
--- a/cli/src/lib/purgeAgentService.ts
+++ b/cli/src/lib/purgeAgentService.ts
@@ -16,7 +16,7 @@ import { sqliteReadAll } from './sqliteRead.js'
import type { StoppedAgentStore } from './stoppedAgents.js'
import type { SessionCheckpointStore } from './sessionCheckpoint.js'
import type { StopAgentOptions } from './stopAgentService.js'
-import { unusedChat } from './closeAgentService.js'
+import { LEAD_PROTECTED_DETAIL, unusedChat } from './closeAgentService.js'
import { inspectWorkspace, inspectWorktree, removeReviewedWorktree, type WorktreeReview } from './worktreeDeletion.js'
const exec = promisify(execFile)
@@ -203,6 +203,10 @@ export interface PurgeDeps {
inspect?: typeof inspectNativeHistory
erase?: typeof eraseNativeHistory
now?: () => number
+ /** Whether the agent may be the Product Manager of an active Swarm project (superTabs/leadSwitch.ts `mayBeLead`): never
+ * deleted, live or stopped. Its host reopens a stopped one on its saved conversation, and deleting it left nothing to reopen,
+ * in the moments after its engine's switch stopped it among others (security review 2 of #2493). */
+ leadProtected?(agentId: string): boolean
}
/**
@@ -318,6 +322,7 @@ export class PurgeAgentService {
const worktreeData = request.choices?.worktreeData === true
try {
if (this.busy(request.agentId)) return { error: 'DELETE_IN_PROGRESS', detail: 'This harness is already being deleted.' }
+ if (request.mode !== 'inspect' && this.deps.leadProtected?.(request.agentId)) return { error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL }
const now = this.deps.now?.() ?? Date.now()
for (const [id, review] of this.reviews) if (review.expires <= now) this.reviews.delete(id)
const current = this.current(request, request.mode === 'inspect' ? !request.includeWorktree : sessionData)
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index 33d8a5825..95670a253 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -61,6 +61,9 @@ export interface StopAgentOptions {
* conversation cannot be read, it is stopped without one, and this is called. Never for a conversation once bound.
*/
withoutConversation?(): void
+ /** The Change agent switch this stop is the close of (closeAgentService.ts): a Swarm Product Manager's stop guard lets only
+ * that switch's own stop through (superTabs/leadSwitch.ts). No other stop carries it: Stop Harness, a delete or a purge. */
+ leadSwitch?: string
}
// Hooks rebuild registry objects. Compare stable values, never JavaScript object
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index e48f4233a..c27cf6910 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -18,6 +18,7 @@ import type { BackendNotice, CoreApi, TurnDelivery } from '../core/api.js'
import { fakeCore } from '../testing/fakeCore.js'
import type { attachedFiles as attachedFilesType } from './attachments.js'
import { backend, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
+import { SWITCH_ADOPT_MS, SWITCH_HOLD_MS } from './leadSwitch.js'
import { TerminalHost } from './terminal.js'
import { hostForm, swarmReply } from './fixtures/read/index.js'
import { CONTINUE } from './limitResume.js'
@@ -3741,6 +3742,91 @@ describe('keeping a Swarm Lead alive', () => {
expect(t.keepLeadAlive).toHaveBeenCalledTimes(calls + 3)
})
+ // Dee, 11-01: its owner switches a Product Manager's engine from its pane. The host holds off reopening the old session while
+ // the new one takes its place, and reopens the old one on its old engine when none started in time; a restart keeps the
+ // hold, so a project never has two, and never none for long (superTabs/leadSwitch.ts).
+ const switched = (t: ReturnType<typeof lifeFixture>, at = 0) => {
+ const folder = join(t.dir, 'super-tabs', 'lead-switch')
+ mkdirSync(folder, { recursive: true, mode: 0o700 })
+ writeFileSync(join(folder, `${createHash('sha256').update('harness').digest('hex')}.json`),
+ JSON.stringify({ version: 1, agentId: 'harness', changeId: 'f'.repeat(32), targetEngine: 'codex', at }), { mode: 0o600 })
+ }
+ /** The switch's new session [id], running here when [runs] says so, by its creation receipt. */
+ const replacement = (t: ReturnType<typeof lifeFixture>, runs: () => boolean, old: () => boolean = () => false, id = 'new-session') => {
+ t.core.agents.byAgent = vi.fn((agentId: string) => (agentId === id ? runs() : agentId === 'harness' && old()) ? { agentId } : undefined) as never
+ t.core.agents.creationStatus = vi.fn(async (creationId: string) => ({ creationId, state: 'created' as const, agentId: id }))
+ }
+
+ it('holds a switching Lead\'s reopen until the switch\'s time limit, across a restart, then reopens it', async () => {
+ const t = lifeFixture([leadRow()])
+ switched(t)
+ await t.poll()
+ await t.poll(60_000)
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ // The host restarts mid-switch: the hold is on disk.
+ t.host.stop()
+ const again = t.open()
+ const poll = async (advance: number) => { t.wait(advance); await again.tick(); for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve)) }
+ await poll(0)
+ await poll(SWITCH_HOLD_MS - 60_000)
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ await poll(1)
+ expect(t.keepLeadAlive).toHaveBeenCalledWith('harness')
+ expect(t.closeMember).not.toHaveBeenCalled()
+ })
+
+ // Security review 2 of #2493: a new session the Swarm did not take in must not run unlinked beside the reopened one.
+ it('waits for the Swarm to take in a running new session, and closes it before reopening the old one when it did not', async () => {
+ const t = lifeFixture([leadRow()])
+ switched(t)
+ replacement(t, () => true)
+ await t.poll()
+ await t.poll(SWITCH_HOLD_MS + 1)
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ await t.poll(SWITCH_ADOPT_MS - SWITCH_HOLD_MS - 1)
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ await t.poll(1)
+ await vi.waitFor(() => expect(t.keepLeadAlive).toHaveBeenCalledWith('harness'))
+ expect(t.closeMember).toHaveBeenCalledWith('new-session', 'f'.repeat(32))
+ expect(t.closeMember.mock.invocationCallOrder[0]).toBeLessThan(t.keepLeadAlive.mock.invocationCallOrder[0])
+ expect(t.log).toHaveBeenCalledWith(expect.stringContaining('Closed the new session new-sess'))
+ })
+
+ it('closes a new session of the switch that starts after the old one was reopened, and says when it cannot', async () => {
+ const t = lifeFixture([leadRow()])
+ switched(t)
+ let late = false
+ replacement(t, () => late, () => true)
+ await t.poll()
+ await t.poll(SWITCH_HOLD_MS + 1)
+ expect(t.closeMember).not.toHaveBeenCalled()
+ late = true
+ t.closeMember.mockResolvedValueOnce({ error: 'AGENT_CHANGED' })
+ await t.poll(5_000)
+ await vi.waitFor(() => expect(t.closeMember).toHaveBeenCalledWith('new-session', 'f'.repeat(32)))
+ await vi.waitFor(() => expect(t.log).toHaveBeenCalledWith(expect.stringContaining('Could not close the new session new-sess')))
+ // Its own new session never counts, nor one from long ago.
+ t.closeMember.mockClear()
+ await t.poll(30 * 60_000)
+ expect(t.closeMember).not.toHaveBeenCalled()
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ })
+
+ it('reads no new session from a creation that did not run here, or names the old session itself', async () => {
+ const t = lifeFixture([leadRow()])
+ switched(t)
+ t.core.agents.creationStatus = vi.fn(async (creationId: string) => ({ creationId, state: 'pending' as const }))
+ await t.poll()
+ await t.poll(SWITCH_HOLD_MS + 1)
+ await vi.waitFor(() => expect(t.keepLeadAlive).toHaveBeenCalledTimes(1))
+ const u = lifeFixture([leadRow()])
+ switched(u)
+ u.core.agents.creationStatus = vi.fn(async (creationId: string) => ({ creationId, state: 'created' as const, agentId: 'harness' }))
+ await u.poll(SWITCH_HOLD_MS + 1)
+ await vi.waitFor(() => expect(u.keepLeadAlive).toHaveBeenCalledTimes(1))
+ expect(u.closeMember).not.toHaveBeenCalled()
+ })
+
it('waits a minute after a reopen it asked for before asking again', async () => {
const t = lifeFixture([leadRow()])
t.keepLeadAlive.mockResolvedValue({ ok: true })
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index c015269d5..070a97e6a 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -37,6 +37,7 @@ const agentCommandOf = (entry: Entry, prefix: string, buddy = false) =>
const readCommand = (entry: Entry, prefix: string, group: string, id: string, buddy = false) =>
`${agentCommandOf(entry, prefix, buddy)} message ${shellQuote(group)} ${shellQuote(id)}`
export { backend, identifier, object, SuperTabHostError } from './wire.js'
+import { leadSwitchOf, SWITCH_ADOPT_MS, switchWithin, type LeadSwitch } from './leadSwitch.js'
import { backend, ENDED_WORK, identifier, object, SuperTabHostError } from './wire.js'
import { parseSwarmSkill, recordSwarmSkillNotice, refreshSwarmSkill, wireRole, type CustomSwarmRole, type SkillRefresh, type SwarmSkill, type SwarmSkillGrant,
type SwarmSkillMode } from '../lib/swarmSkills.js'
@@ -295,6 +296,8 @@ const DELIVERY_FALLBACK_MS = 30_000
* this process started after the last one), every list is read each second again. */
const PUSH_LEASE_MS = 10 * 60_000
const LEAD_RETRY_MS = 5_000
+/** How long after a Product Manager's switch its host still closes a new session of it that starts late (leadSwitch.ts). */
+const LATE_REPLACEMENT_MS = 30 * 60_000
const LEAD_RETRY_MAX_MS = 30 * 60_000
const LEAD_REOPEN_WAIT_MS = 60_000
/** Prod 10-30: acknowledgements failed through two hours of SWARM_BUSY, past the backend's 10-minute claim quiet time
@@ -1119,20 +1122,58 @@ export class SuperTabHost {
const state = this.keepAlives.get(harnessId) ?? { running: false, failures: 0, retryAt: 0 }
this.keepAlives.set(harnessId, state)
if (state.running) return
- if (this.core.agents.byAgent(harnessId)) { state.failures = 0; state.retryAt = 0; delete state.reason; return }
- if (this.now() < state.retryAt) return
+ const now = this.now()
+ // Its owner switched its engine from its pane (leadSwitch.ts), stopping it once the stop went through.
+ const switched = leadSwitchOf(this.core.dataDir, harnessId)
+ if (this.core.agents.byAgent(harnessId)) {
+ state.failures = 0; state.retryAt = 0; delete state.reason
+ // Reopened here after its switch's hold: a new session of that switch that runs now is unlinked beside it, and is
+ // closed (security review 2 of #2493).
+ if (switched && !switchWithin(switched, now) && switchWithin(switched, now, LATE_REPLACEMENT_MS)) {
+ state.running = true
+ void this.switchReplacement(switched).then(id => id ? this.closeReplacement(id, switched) : undefined)
+ .catch(() => { /* Checked again on the next poll. */ }).finally(() => { state.running = false })
+ }
+ return
+ }
+ if (now < state.retryAt) return
state.running = true
const failed = (reason: string) => {
state.retryAt = this.now() + Math.min(LEAD_RETRY_MAX_MS, LEAD_RETRY_MS * 2 ** state.failures++)
if (reason !== state.reason) this.log(`Could not reopen the Product Manager ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)
state.reason = reason
}
- void reopen(harnessId).then(result => {
+ void (async () => {
+ if (switched) {
+ const replacement = await this.switchReplacement(switched)
+ // Its new session runs: the Swarm takes it in its place (recordReplacements), within its time.
+ if (replacement && switchWithin(switched, now, SWITCH_ADOPT_MS)) return
+ // Its new session has not started yet: waited for, within its time.
+ if (!replacement && switchWithin(switched, now)) return
+ // Not taken in: closed before the old one reopens, so the two never run side by side.
+ if (replacement) await this.closeReplacement(replacement, switched)
+ }
+ const result = await reopen(harnessId)
if (!result.ok) return failed(result.detail ?? result.error)
state.failures = 0
state.retryAt = this.now() + LEAD_REOPEN_WAIT_MS
delete state.reason
- }, error => failed(error instanceof Error ? error.message : String(error))).finally(() => { state.running = false })
+ })().catch(error => failed(error instanceof Error ? error.message : String(error))).finally(() => { state.running = false })
+ }
+
+ /** The new session [switched] started, when it runs here: its native creation receipt is the switch's own change id. */
+ private async switchReplacement(switched: LeadSwitch): Promise<string | null> {
+ const receipt = await this.core.agents.creationStatus?.(switched.changeId)
+ if (receipt?.state !== 'created' || receipt.creationId !== switched.changeId || receipt.agentId === switched.agentId) return null
+ return this.core.agents.byAgent(receipt.agentId) ? receipt.agentId : null
+ }
+
+ /** Closes the new session [agentId] of a switch the Swarm did not take in, by its creation receipt (closeMember). */
+ private async closeReplacement(agentId: string, switched: LeadSwitch): Promise<void> {
+ const closed = await this.core.agents.closeMember?.(agentId, switched.changeId)
+ this.log(closed && 'closed' in closed && closed.closed
+ ? `Closed the new session ${agentId.slice(0, 8)} of a Product Manager's switch the Swarm did not take in.`
+ : `Could not close the new session ${agentId.slice(0, 8)} of a Product Manager's switch: ${closed?.error ?? 'unsupported'}.`)
}
/** A Buddy's thread sessions (spec 2026-10-30-buddy-thread-sessions) end on their own, so none is left running on its
diff --git a/cli/src/superTabs/inCore.ts b/cli/src/superTabs/inCore.ts
index ca93f97e8..5ed4a920d 100644
--- a/cli/src/superTabs/inCore.ts
+++ b/cli/src/superTabs/inCore.ts
@@ -19,6 +19,8 @@ export { createSwarmAgents } from './inCore/agents.js'
export { SWARM_LAUNCH } from './inCore/launch.js'
export { createConfidentialPurge, isTeamDaemon, purgeRecord, teamAppPolicyFor } from './inCore/teamApps.js'
export { typesWhileBusy } from './inCore/deliveries.js'
-export { mayBeBuddy, mayBeLead, retainedHarnesses, retainedLeads } from './retention.js'
+export { mayBeBuddy, retainedHarnesses, retainedLeads } from './retention.js'
+// A Product Manager switched from its pane (Change agent) is the one stop of a Lead its close guard and stop guard let through.
+export { leadCloseProtected, leadSwitchEnded, leadSwitching, mayBeLead } from './leadSwitch.js'
export { forwardAttachmentUpload } from '../lib/superTabAttachmentProxy.js'
export { startSuperTabs } from '../services/superTabs.js'
diff --git a/cli/src/superTabs/leadSwitch.spec.ts b/cli/src/superTabs/leadSwitch.spec.ts
new file mode 100644
index 000000000..11a76524b
--- /dev/null
+++ b/cli/src/superTabs/leadSwitch.spec.ts
@@ -0,0 +1,162 @@
+import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it } from 'vitest'
+import { handoffHash } from '../lib/handoffAuthority.js'
+import { leadCloseProtected, leadSwitchEnded, leadSwitching, leadSwitchOf, mayBeLead, resetLeadSwitchPassesForTest, SWITCH_ARM_MS,
+ SWITCH_HOLD_MS, switchWithin } from './leadSwitch.js'
+import { retainContributions } from './retention.js'
+
+const roots: string[] = []
+const LEAD = 'lead-harness', WORKER = 'worker-harness'
+const CHANGE = 'a'.repeat(32), OTHER = 'b'.repeat(32)
+afterEach(() => {
+ resetLeadSwitchPassesForTest()
+ for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+/** A data folder whose host keeps [LEAD] as a Product Manager and [WORKER] as a member. */
+function machine(now = Date.now()) {
+ const dir = mkdtempSync(join(tmpdir(), 'lead-switch-')); roots.push(dir)
+ retainContributions(dir, 'machine', [
+ { tabId: 'tab', lead: true, agent: { harnessId: LEAD, machineId: 'machine' } },
+ { tabId: 'tab', agent: { harnessId: WORKER, machineId: 'machine' } }], now)
+ return dir
+}
+
+/** The receipt `agent_handoff_prepare` leaves for its owner's switch (lib/handoffPublication.ts), written [at]. */
+function prepared(dir: string, agentId: string, changeId: string, at = Date.now(), receipt: Record<string, unknown> = {}) {
+ const folder = join(dir, 'handoff-receipts'); mkdirSync(folder, { recursive: true })
+ const file = join(folder, `${handoffHash(JSON.stringify([agentId, changeId]))}.json`)
+ writeFileSync(file, JSON.stringify({ version: 1, committed: true, prepared: { request: { agentId, changeId, targetEngine: 'codex' } }, ...receipt }))
+ utimesSync(file, at / 1000, at / 1000)
+}
+
+it('refuses a plain close or stop of a Product Manager, and one naming a switch nobody prepared, as before', () => {
+ const dir = machine(), now = Date.now()
+ expect(leadCloseProtected(dir, LEAD, undefined, now)).toBe(true)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(true)
+ prepared(dir, LEAD, 'not-a-change-id', now)
+ expect(leadCloseProtected(dir, LEAD, 'not-a-change-id', now)).toBe(true)
+ // Stop Harness, a delete or a purge carries no switch; a stop naming one that was never let through is refused too.
+ expect(mayBeLead(dir, LEAD)).toBe(true)
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(true)
+ // A member that is no Product Manager closes and stops as ever.
+ expect(leadCloseProtected(dir, WORKER, undefined, now)).toBe(false)
+ expect(mayBeLead(dir, WORKER)).toBe(false)
+})
+
+it('refuses a switch whose handoff is another agent\'s, another switch\'s, uncommitted, unreadable or too old', () => {
+ const dir = machine(), now = Date.now()
+ prepared(dir, WORKER, CHANGE, now)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(true)
+ prepared(dir, LEAD, OTHER, now)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(true)
+ prepared(dir, LEAD, CHANGE, now, { committed: false })
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(true)
+ prepared(dir, LEAD, CHANGE, now, { prepared: { request: { agentId: WORKER, changeId: CHANGE, targetEngine: 'codex' } } })
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(true)
+ writeFileSync(join(dir, 'handoff-receipts', `${handoffHash(JSON.stringify([LEAD, CHANGE]))}.json`), '{')
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(true)
+ prepared(dir, LEAD, CHANGE, now - SWITCH_ARM_MS - 1)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(true)
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(true)
+ expect(leadSwitchOf(dir, LEAD)).toBeNull()
+})
+
+// Security reviews 1 and 2 of #2493: the pass goes from the switch's close to the one stop it starts, and to nothing else.
+it('lets only the one stop its owner\'s switch starts through, once, and records the switch once that stop went through', () => {
+ const dir = machine(), now = Date.now()
+ prepared(dir, LEAD, CHANGE, now)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(false)
+ // Nothing is recorded, and no hold starts, before the stop went through.
+ expect(leadSwitchOf(dir, LEAD)).toBeNull()
+ // Stop Harness, a delete or a script's close right after carries no switch, or another: refused.
+ expect(mayBeLead(dir, LEAD)).toBe(true)
+ expect(mayBeLead(dir, LEAD, OTHER)).toBe(true)
+ expect(leadCloseProtected(dir, LEAD, undefined, now)).toBe(true)
+ // The switch's own stop passes, once.
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(false)
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(true)
+ leadSwitchEnded(dir, LEAD, CHANGE, true, now + 1_000)
+ expect(leadSwitchOf(dir, LEAD)).toEqual({ version: 1, agentId: LEAD, changeId: CHANGE, targetEngine: 'codex', at: now + 1_000 })
+ // The same switch is never let through again, nor its end recorded twice.
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now + 2_000)).toBe(true)
+ leadSwitchEnded(dir, LEAD, CHANGE, true, now + 5_000)
+ expect(leadSwitchOf(dir, LEAD)?.at).toBe(now + 1_000)
+ // Held from its stop to the limit.
+ expect(switchWithin(leadSwitchOf(dir, LEAD), now + 1_000 + SWITCH_HOLD_MS)).toBe(true)
+ expect(switchWithin(leadSwitchOf(dir, LEAD), now + 1_000 + SWITCH_HOLD_MS + 1)).toBe(false)
+ const records = readdirSync(join(dir, 'super-tabs', 'lead-switch'))
+ expect(records).toHaveLength(1)
+ expect(statSync(join(dir, 'super-tabs', 'lead-switch', records[0])).mode & 0o777).toBe(0o600)
+})
+
+it('leaves nothing open after a close that failed: no pass, no record, and another switch may start at once', () => {
+ const dir = machine(), now = Date.now()
+ prepared(dir, LEAD, CHANGE, now)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(false)
+ // The save failed before the stop: the close ends unstopped.
+ leadSwitchEnded(dir, LEAD, CHANGE, false, now + 1_000)
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(true)
+ expect(leadSwitchOf(dir, LEAD)).toBeNull()
+ // Its repeat is not let through; a new switch is, at once.
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now + 2_000)).toBe(true)
+ prepared(dir, LEAD, OTHER, now + 2_000)
+ expect(leadSwitching(dir, LEAD, OTHER, now + 2_000)).toBe(false)
+ expect(leadCloseProtected(dir, LEAD, OTHER, now + 2_000)).toBe(false)
+ // An end for a switch never let through records nothing.
+ leadSwitchEnded(dir, WORKER, CHANGE, true, now)
+ expect(leadSwitchOf(dir, WORKER)).toBeNull()
+})
+
+it('refuses a second switch while one runs, from its close to its time limit, and takes a new one after', () => {
+ const dir = machine(), now = Date.now()
+ prepared(dir, LEAD, CHANGE, now)
+ prepared(dir, LEAD, OTHER, now)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(false)
+ // Its close under way.
+ expect(leadSwitching(dir, LEAD, OTHER, now)).toBe(true)
+ expect(leadSwitching(dir, LEAD, CHANGE, now)).toBe(false)
+ expect(leadCloseProtected(dir, LEAD, OTHER, now)).toBe(true)
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(false)
+ leadSwitchEnded(dir, LEAD, CHANGE, true, now)
+ // Its new session awaited.
+ expect(leadSwitching(dir, LEAD, OTHER, now + 1_000)).toBe(true)
+ expect(leadCloseProtected(dir, LEAD, OTHER, now + 1_000)).toBe(true)
+ // Ended by its time limit: a new switch is let through.
+ const later = now + SWITCH_HOLD_MS + 1
+ prepared(dir, LEAD, OTHER, later)
+ expect(leadSwitching(dir, LEAD, OTHER, later)).toBe(false)
+ expect(leadCloseProtected(dir, LEAD, OTHER, later)).toBe(false)
+})
+
+it('across a restart, keeps the hold of a switch that stopped, and refuses the stop of one that had not', () => {
+ const dir = machine(), now = Date.now()
+ prepared(dir, LEAD, CHANGE, now)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(false)
+ // The daemon restarts between the close's pass and its stop: the stop is refused, and nothing was recorded.
+ resetLeadSwitchPassesForTest()
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(true)
+ expect(leadSwitchOf(dir, LEAD)).toBeNull()
+ // A switch that stopped keeps its record and limit across one.
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(false)
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(false)
+ leadSwitchEnded(dir, LEAD, CHANGE, true, now)
+ resetLeadSwitchPassesForTest()
+ expect(switchWithin(leadSwitchOf(dir, LEAD), now + 1)).toBe(true)
+ expect(mayBeLead(dir, LEAD)).toBe(true)
+})
+
+it('reads no switch from an unreadable record, and holds none from a clock far ahead', () => {
+ const dir = machine(), now = Date.now()
+ prepared(dir, LEAD, CHANGE, now)
+ expect(leadCloseProtected(dir, LEAD, CHANGE, now)).toBe(false)
+ expect(mayBeLead(dir, LEAD, CHANGE)).toBe(false)
+ leadSwitchEnded(dir, LEAD, CHANGE, true, now)
+ expect(switchWithin(leadSwitchOf(dir, LEAD), now - 2 * 60_000)).toBe(false)
+ const folder = join(dir, 'super-tabs', 'lead-switch')
+ writeFileSync(join(folder, readdirSync(folder)[0]), '{')
+ expect(leadSwitchOf(dir, LEAD)).toBeNull()
+ expect(switchWithin(null, now)).toBe(false)
+})
diff --git a/cli/src/superTabs/leadSwitch.ts b/cli/src/superTabs/leadSwitch.ts
new file mode 100644
index 000000000..e912d6e3b
--- /dev/null
+++ b/cli/src/superTabs/leadSwitch.ts
@@ -0,0 +1,151 @@
+/**
+ * A project's Product Manager switched to another engine from its own pane, as any pane is (Change agent; Dee, 11-01: "PM is
+ * just an agent/pane like in v1"). Its stop is the one exception to "a Lead is never closed" (retention.ts mayBeLead), and a
+ * narrow one (Lead, 11-01; security reviews 1 and 2 of #2493):
+ * - Only a `now` close that names the switch's change id is considered, and only when this machine's own handoff receipt
+ * shows that very switch of that very agent was prepared moments ago. `agent_handoff_prepare` answers the machine's owner
+ * alone: the owner's apps, or any process on the owner's Mac, agents with a shell included, which could already stop the
+ * Product Manager's process or type into its terminal.
+ * - That close gets a one-time pass, held in this process, which only the stop it starts carries (lib/closeAgentService.ts
+ * hands it to lib/stopAgentService.ts options). No other stop carries it, whoever asks: Stop Harness (a paired dial's
+ * included), a delete, a purge, a script's close. The stop uses it up; the close's end clears it, stopped or not; the same
+ * switch is never let through twice. A restart forgets it, which only refuses.
+ * - The switch is recorded only once its stop went through, one per Product Manager. While it runs, a second switch is refused,
+ * and the host does not reopen the stopped one (superTabs/host.ts keepAlive), so the new session can take its place: the
+ * existing replacement report and the backend's agent.rebind keep the same Swarm agent, its lead and its work.
+ * - The new session not started within SWITCH_HOLD_MS, the hold ends and the host reopens the old one on its old engine. A new
+ * session that runs but is not taken into the Swarm by SWITCH_ADOPT_MS, or starts after the old one was reopened, is closed
+ * by the host first, so no unlinked session runs beside the Product Manager. A project never has two, and never none for long.
+ * The record is a file, so a restart in the middle keeps the hold and its limits.
+ */
+import { createHash, randomUUID } from 'node:crypto'
+import { existsSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { handoffHash } from '../lib/handoffAuthority.js'
+import { readPrivateStateFile, secureStateDirectory, syncStateDirectory } from '../lib/secureState.js'
+import { mayBeLead as retainedLead } from './retention.js'
+import { identifier, object } from './wire.js'
+
+/** How soon after its owner prepared the switch its close must come (Desktop closes at once after preparing). */
+export const SWITCH_ARM_MS = 2 * 60_000
+/** How long, from its stop, the host waits for the new session before it reopens the old one. */
+export const SWITCH_HOLD_MS = 3 * 60_000
+/** How long, from its stop, the host waits for the Swarm to take in a new session that runs (agent.rebind, every 5 s). */
+export const SWITCH_ADOPT_MS = 10 * 60_000
+/** Ended records go after a day; each Product Manager has at most one. */
+const KEEP_MS = 24 * 60 * 60_000
+const CHANGE_ID = /^[0-9a-f]{32}$/
+const MAX_RECEIPT_BYTES = 20 * 1024 * 1024
+/** The switches this process let through, so none is let through twice; the oldest are forgotten past this many. */
+const MAX_USED = 256
+
+export interface LeadSwitch { version: 1; agentId: string; changeId: string; targetEngine: string; at: number }
+
+const folder = (dataDir: string) => join(dataDir, 'super-tabs', 'lead-switch')
+const fileOf = (dataDir: string, agentId: string) => join(folder(dataDir), `${createHash('sha256').update(agentId).digest('hex')}.json`)
+
+/** The pass a switch's close holds for the one stop it starts, by Product Manager: its change id. */
+const passes = new Map<string, string>()
+/** Every switch this process let through (`agentId:changeId`), with its engine: none is let through twice, and only these
+ * record. The oldest are forgotten past MAX_USED. */
+const issued = new Map<string, string>()
+/** The issued switches whose close ended. */
+const ended = new Set<string>()
+
+/** The switch recorded for [agentId], whether running or ended; null when none or unreadable. */
+export function leadSwitchOf(dataDir: string, agentId: string): LeadSwitch | null {
+ const file = fileOf(dataDir, agentId)
+ if (!existsSync(file)) return null
+ try {
+ const row = object(JSON.parse(readPrivateStateFile(file, 4_096)))
+ if (row.version !== 1 || row.agentId !== agentId || typeof row.changeId !== 'string' || !CHANGE_ID.test(row.changeId)
+ || !identifier(row.targetEngine) || typeof row.at !== 'number' || !Number.isFinite(row.at)) return null
+ return row as unknown as LeadSwitch
+ } catch { return null }
+}
+
+/** Running: recorded [limit] ago or less, and not in the future (a clock set back holds no longer than this). */
+export const switchWithin = (row: LeadSwitch | null, now: number, limit = SWITCH_HOLD_MS): row is LeadSwitch =>
+ !!row && row.at <= now + 60_000 && now - row.at <= limit
+
+/** The engine its owner prepared [agentId]'s switch [changeId] to, when this machine's handoff receipt shows it was done
+ * within SWITCH_ARM_MS; else null. The receipt is written only for the machine's owner (services/handoffRequest.ts). */
+function prepared(dataDir: string, agentId: string, changeId: string, now: number): string | null {
+ const file = join(dataDir, 'handoff-receipts', `${handoffHash(JSON.stringify([agentId, changeId]))}.json`)
+ try {
+ if (!existsSync(file)) return null
+ const age = now - statSync(file).mtimeMs
+ if (age > SWITCH_ARM_MS || age < -60_000) return null
+ const receipt = object(JSON.parse(readPrivateStateFile(file, MAX_RECEIPT_BYTES)))
+ const request = object(object(receipt.prepared).request)
+ if (receipt.version !== 1 || receipt.committed !== true || request.agentId !== agentId || request.changeId !== changeId
+ || !identifier(request.targetEngine)) return null
+ return request.targetEngine as string
+ } catch { return null }
+}
+
+function write(dataDir: string, row: LeadSwitch, now: number): void {
+ const dir = folder(dataDir)
+ secureStateDirectory(dir)
+ for (const name of readdirSync(dir)) {
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue
+ try { if (now - statSync(join(dir, name)).mtimeMs > KEEP_MS) unlinkSync(join(dir, name)) } catch { /* Gone already. */ }
+ }
+ const file = fileOf(dataDir, row.agentId), temporary = `${file}.${randomUUID()}.next`
+ try {
+ writeFileSync(temporary, JSON.stringify(row), { mode: 0o600, flush: true, flag: 'wx' })
+ renameSync(temporary, file)
+ syncStateDirectory(dir)
+ } finally { if (existsSync(temporary)) unlinkSync(temporary) }
+}
+
+/** Another switch of [agentId] than [changeId] is running, its close under way or its new session awaited: refused. */
+export function leadSwitching(dataDir: string, agentId: string, changeId: string, now = Date.now()): boolean {
+ const pass = passes.get(agentId)
+ if (pass && pass !== changeId) return true
+ const row = leadSwitchOf(dataDir, agentId)
+ return switchWithin(row, now) && row.changeId !== changeId
+}
+
+/** Whether the close guard (lib/closeAgentService.ts) refuses a close of [agentId] naming [changeId] (a `now` close of Change
+ * agent) or none: refused for a Product Manager unless it is that switch's close, which then gets the pass for its one stop. */
+export function leadCloseProtected(dataDir: string, agentId: string, changeId?: string, now = Date.now()): boolean {
+ if (!retainedLead(dataDir, agentId)) return false
+ if (!changeId || !CHANGE_ID.test(changeId)) return true
+ const key = `${agentId}:${changeId}`
+ if (issued.has(key) || passes.has(agentId) || switchWithin(leadSwitchOf(dataDir, agentId), now)) return true
+ const engine = prepared(dataDir, agentId, changeId, now)
+ if (!engine) return true
+ passes.set(agentId, changeId)
+ issued.set(key, engine)
+ if (issued.size > MAX_USED) issued.delete(issued.keys().next().value!)
+ return false
+}
+
+/** The core's stop guard (core/agents/lifecycle.ts): a Product Manager is never stopped, but by the one stop of its switch's
+ * close, which carries the switch [leadSwitch] and uses its pass up. */
+export function mayBeLead(dataDir: string, agentId: string, leadSwitch?: string): boolean {
+ if (!retainedLead(dataDir, agentId)) return false
+ if (!leadSwitch || passes.get(agentId) !== leadSwitch) return true
+ passes.delete(agentId)
+ return false
+}
+
+/** The switch's close ended (lib/closeAgentService.ts): its pass, used or not, is gone; stopped, the switch is recorded and the
+ * host's hold starts now. A close that failed records nothing, so its owner may switch again at once and a crashed Product
+ * Manager is reopened as ever. Only the close that was given the pass records: [changeId] must be one this process let
+ * through, and once. */
+export function leadSwitchEnded(dataDir: string, agentId: string, changeId: string, stopped: boolean, now = Date.now()): void {
+ if (passes.get(agentId) === changeId) passes.delete(agentId)
+ const key = `${agentId}:${changeId}`, engine = issued.get(key)
+ if (!stopped || engine === undefined || ended.has(key)) return
+ ended.add(key)
+ if (ended.size > MAX_USED) ended.delete(ended.values().next().value!)
+ try { write(dataDir, { version: 1, agentId, changeId, targetEngine: engine, at: now }, now) } catch (error) {
+ // Unrecorded, the host reopens the old one as for any stopped Product Manager: never none.
+ console.warn(`[super-tabs] could not record the switch of ${agentId.slice(0, 8)}: ${error instanceof Error ? error.name : 'unknown'}`)
+ }
+}
+
+/** Tests: forget this process's passes, as a restart does. */
+export function resetLeadSwitchPassesForTest(): void { passes.clear(); issued.clear(); ended.clear() }
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 9045f29d0..00d7db8ca 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -278,6 +278,10 @@ class _AgentChange {
bool preservingViews = false;
bool handoffHeld = false;
bool contextLoaded = false;
+
+ /// Its machine prepared the handoff under this switch's id: its stop names
+ /// the switch (a Swarm Product Manager's machine checks the two match).
+ bool handoffPrepared = false;
String? handoff;
/// The handoff ran and left the new agent without a first prompt: say so once the switch is done.
@@ -4197,10 +4201,15 @@ class AppNotifier extends ChangeNotifier {
}
/// Capture once before showing a prompt. Old/replaced targets cannot inherit its answer.
+ /// [changeId]: the Change agent switch this close is part of, whose
+ /// handoff was prepared under that id. A Swarm Product Manager's machine
+ /// lets its stop through only for that switch (cli superTabs/leadSwitch.ts);
+ /// any other close of one is refused as before.
Future<Map<String, dynamic>> Function(String) prepareSessionClose(
String machineId,
- Agent agent,
- ) {
+ Agent agent, {
+ String? changeId,
+ }) {
final machine = stateOf(machineId);
final revision = _authRevision;
final removal = machine?._agentRemovals[agent.id];
@@ -4239,6 +4248,7 @@ class AppNotifier extends ChangeNotifier {
'sessionId': agent.sessionId ?? '',
'createdAt': agent.createdAt!.toUtc().toIso8601String(),
'mode': mode,
+ 'changeId': ?changeId,
},
);
} on WsRequestFailure catch (failure) {
@@ -17350,6 +17360,7 @@ class AppNotifier extends ChangeNotifier {
sourceLabel: engineIdentity(source.engine).label,
);
if (accepted.accepted) {
+ change.handoffPrepared = true;
change.handoff = accepted.prompt;
change.handoffEmpty = accepted.prompt == null;
change.handoffFailed = false;
@@ -17447,7 +17458,13 @@ class AppNotifier extends ChangeNotifier {
(latest.project?.cwd ?? machine.projectOf(latest)?.cwd) != folder) {
return 'The conversation changed. Reopen Change agent.';
}
- final close = prepareSessionClose(machineId, latest);
+ // Named only after its handoff was prepared under this id: a Swarm
+ // Product Manager's machine checks the two belong to one switch.
+ final close = prepareSessionClose(
+ machineId,
+ latest,
+ changeId: change.handoffPrepared ? change.creation._id : null,
+ );
change.preservingViews = true;
if (!latest.isStopped) {
final saved = await close('now');
diff --git a/desktop/test/agent_change_test.dart b/desktop/test/agent_change_test.dart
index e0c27c0e6..c844dc67e 100644
--- a/desktop/test/agent_change_test.dart
+++ b/desktop/test/agent_change_test.dart
@@ -46,6 +46,7 @@ class SwitchConnection extends MonitorConnection {
final handoffTimeouts = <Duration>[];
final eventsAtHandoff = <List<String>>[];
final completedHandoffs = <Map<String, dynamic>>[];
+ final closeRequests = <Map<String, dynamic>>[];
String? completionError;
Object? completionThrows;
@@ -73,6 +74,7 @@ class SwitchConnection extends MonitorConnection {
return recent;
}
if (type == 'agent_close') {
+ closeRequests.add(Map.of(payload));
events.add('save/stop');
expect(payload['mode'], 'now');
expect(payload['sessionId'], 'saved-conversation');
@@ -1199,6 +1201,69 @@ void main() {
expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
});
+ // Dee, 11-01: a Swarm Product Manager's engine is switched from its pane,
+ // as any pane's. Its machine lets the stop through only for the switch
+ // whose handoff it prepared, so the stop names that switch.
+ test(
+ 'a switch names the change its handoff was prepared for on the stop',
+ () async {
+ final connection = SwitchConnection()..handoff = handoffOk;
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ final changeId = connection.handoffCalls.single['changeId'] as String;
+ expect(changeId, matches(RegExp(r'^[0-9a-f]{32}$')));
+ expect(connection.closeRequests.single['changeId'], changeId);
+ expect(connection.closeRequests.single['mode'], 'now');
+ },
+ );
+
+ test(
+ 'a stop with no prepared handoff, or any other close, names no change',
+ () async {
+ final connection = SwitchConnection();
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ expect(connection.closeRequests.single.containsKey('changeId'), isFalse);
+ final other = SwitchConnection();
+ final plain = fixture(other);
+ addTearDown(plain.dispose);
+ await plain.prepareSessionClose('m', plain.stateOf('m')!.agents.first)(
+ 'now',
+ );
+ expect(other.closeRequests.single.containsKey('changeId'), isFalse);
+ },
+ );
+
+ test('a Product Manager its machine will not stop keeps its agent and pane, with the machine\'s words', () async {
+ for (final refusal in [
+ {
+ 'error': 'LEAD_PROTECTED',
+ 'detail': 'This harness is the Product Manager of a Swarm project. Delete its project first to stop it.',
+ },
+ {
+ 'error': 'LEAD_SWITCHING',
+ 'detail': 'This Product Manager is already switching its agent. Wait for it to finish.',
+ },
+ ]) {
+ final connection = SwitchConnection()
+ ..handoff = handoffOk
+ ..closeRefusal = refusal;
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final pane = app.panes.single;
+ expect(await app.changeAgent('m', 'a0', 'claude'), refusal['detail']);
+ expect(connection.creations, isEmpty);
+ expect(app.panes.single, same(pane));
+ expect(pane.agentId, 'a0');
+ expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
+ }
+ });
+
test('a failed launch preserves the stopped session and permits a different agent', () async {
final connection = SwitchConnection()
..creationError = 'OpenCode is missing';