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.

Let a Buddy switch engines without losing its chat (#3390)

harness-for-autonomous[bot]81988b9b23fc
diff --git a/.github/workflows/cli-e2e.yml b/.github/workflows/cli-e2e.yml
index 1cd4b1037..9fc785951 100644
--- a/.github/workflows/cli-e2e.yml
+++ b/.github/workflows/cli-e2e.yml
@@ -143,7 +143,7 @@ jobs:
BUDDY_RESULT: ${{ runner.temp }}/buddy-result.json
run: >-
node -e 'const r = JSON.parse(require("node:fs").readFileSync(process.env.BUDDY_RESULT, "utf8"));
- if (r.numPassedTests !== 1 || r.numPendingTests !== 0 || r.numFailedTests !== 0) process.exit(1)'
+ if (r.numPassedTests !== 2 || r.numPendingTests !== 0 || r.numFailedTests !== 0) process.exit(1)'
- name: Preserve the native Buddy result
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.ts
index fde37f26d..033049c6d 100644
--- a/backend/src/superTabs/buddies.ts
+++ b/backend/src/superTabs/buddies.ts
@@ -278,7 +278,7 @@ export const buddyReady = (name: string): string => `${name} is ready. Tell it w
* model, a terminal alert, its own stop). Every other command is refused, so it can never assign, start, route, ask
* decisions or change anything for its owner (spec constraint: PRIVACY-CRITICAL). */
const BUDDY_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'buddy.propose', 'agent.configuration', 'agent.alert',
- 'agent.stopLease', 'agent.stopRefused', 'agent.remove', 'buddy.modelResult'])
+ 'agent.stopLease', 'agent.stopRefused', 'agent.remove', 'buddy.modelResult', 'agent.switchClaim', 'agent.switchResult', 'agent.rebind'])
export function requireBuddyCommand(buddy: Agent, command: { type: string; conversationId?: unknown; agentId?: unknown }, groups: readonly Conversation[]): void {
if (command.type === 'proposal.answer') return // The card handler checks the current sender and question before receipt replay.
diff --git a/backend/src/superTabs/buddyEngine.test.ts b/backend/src/superTabs/buddyEngine.test.ts
new file mode 100644
index 000000000..7c05be513
--- /dev/null
+++ b/backend/src/superTabs/buddyEngine.test.ts
@@ -0,0 +1,238 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command } from './commands.js'
+import { createSuperTab, type Actor } from './model.js'
+import type { ContributedMachine } from './machines.js'
+import { staleSwitches } from './tidy.js'
+import { hostTab } from './read/hostRows.js'
+import { touchesFor } from './parts/touches.js'
+
+const NOW = 1_800_000_000_000
+const person: Actor = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+function setup() {
+ let state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ state.people.push({ id: 'peer', email: '[email protected]', role: 'collaborator', generation: 'first' })
+ state.machines = [{ machineId: 'mac', name: 'My computer', contributorId: 'peer', membershipGeneration: 'first', generation: 'g1',
+ cwd: '/swarm', scope: 'swarm', engines: ['claude', 'codex'], maxAgents: 4, paused: false,
+ observation: { generation: 'g1', receivedAt: NOW, sessionKind: 'computer',
+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null,
+ projectDiskFreeBytes: null, deviceType: null, chip: null, os: null, gpuPercent: null },
+ tools: {}, quotas: [], runningHarnessIds: ['h-old'], stoppedHarnessIds: [], capabilities: ['swarmBuddy', 'buddyModel', 'buddyEngine'],
+ readiness: { engines: [{ engine: 'claude', installed: true, signedIn: true }, { engine: 'codex', installed: true, signedIn: true }] } } } satisfies ContributedMachine]
+ let operation = 0
+ const run = (command: Record<string, unknown>, actor = person, now = NOW) => {
+ const effects = applyCommand(state, actor, command as Command, { operationId: `op${++operation}`, now,
+ contribution: { machineOwnerId: 'peer', contributorId: 'peer', hostGrant: null } })
+ state = effects.state
+ return effects
+ }
+ const startId = run({ type: 'buddy.create', machineId: 'mac', engine: 'claude' }).result.startId
+ const id = run({ type: 'agent.started', startId, harnessId: 'h-old', configuration }).result.agentId as string
+ run({ type: 'agent.startSettled', startId, warning: null })
+ const chat = state.conversations.find(c => c.agentIds.includes(id))!.id
+ const host: Actor = { kind: 'agent', agentId: id, machineOwnerId: 'peer' }
+ const target = () => state.agents.find(a => a.id === id)!
+ const request = () => target().switchRequest!.id
+ const rebind = () => run({ type: 'agent.rebind', agentId: id, machineId: 'mac', previousHarnessId: 'h-old', harnessId: 'h-new',
+ configuration: { ...configuration, engine: 'codex' } }, host)
+ return { run, target, request, rebind, id, chat, host, get state() { return state }, pool: () => state.machines![0]! }
+}
+
+function addBuddy(f: ReturnType<typeof setup>) {
+ const startId = f.run({ type: 'buddy.create', machineId: 'mac', engine: 'claude', name: 'Moss' }).result.startId
+ const id = f.run({ type: 'agent.started', startId, harnessId: 'h-moss', configuration }).result.agentId as string
+ f.run({ type: 'agent.startSettled', startId, warning: null })
+ const chat = f.state.conversations.find(c => c.agentIds.includes(id))!.id
+ return { id, chat, target: () => f.state.agents.find(a => a.id === id)!,
+ host: { kind: 'agent', agentId: id, machineOwnerId: 'peer' } as Actor }
+}
+
+describe('a person switching their Buddy engine', () => {
+ it('wakes a sleeping Buddy before requesting its engine switch', () => {
+ const f = setup()
+ f.target().asleep = { since: NOW - 60_000 }
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ expect(f.target().asleep).toBeUndefined()
+ expect(f.target().switchRequest?.engine).toBe('codex')
+ expect(f.target().harnessId).toBe('h-old')
+ expect(f.state.conversations.find(c => c.id === f.chat)?.agentIds).toEqual([f.id])
+ })
+
+ it.each(['named', 'default'])('guards the %s Buddy’s machine against a concurrent readiness change', choice => {
+ const f = setup(), second = addBuddy(f)
+ f.state.machines!.push({ ...structuredClone(f.pool()), machineId: 'second-mac' })
+ second.target().machineId = 'second-mac'
+ if (choice === 'default') f.run({ type: 'buddy.default', conversationId: second.chat })
+ const command: Command = { type: 'buddy.engine', engine: 'codex', ...(choice === 'named' ? { conversationId: second.chat } : {}) }
+ const before = structuredClone(f.state)
+ const effects = f.run(command)
+ expect(second.target().switchRequest?.engine).toBe('codex')
+ expect(touchesFor(command, person, before, effects).filter(t => t.kind === 'machine'))
+ .toEqual([{ kind: 'machine', key: 'second-mac' }])
+ })
+
+ it('switches the default Buddy when an older client names no chat', () => {
+ const f = setup(), second = addBuddy(f)
+ f.run({ type: 'buddy.default', conversationId: second.chat })
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ expect(second.target().switchRequest?.engine).toBe('codex')
+ expect(f.target().switchRequest).toBeUndefined()
+ })
+
+ it('switches exactly the named Buddy even when another is the default, preserving its private chat', () => {
+ const f = setup(), second = addBuddy(f)
+ f.run({ type: 'buddy.engine', engine: 'codex', conversationId: second.chat })
+ expect(f.target().switchRequest).toBeUndefined()
+ const switchId = second.target().switchRequest!.id
+ f.run({ type: 'agent.switchClaim', agentId: second.id, switchId }, second.host)
+ f.run({ type: 'agent.rebind', agentId: second.id, machineId: 'mac', previousHarnessId: 'h-moss', harnessId: 'h-moss-new',
+ configuration: { ...configuration, engine: 'codex' } }, second.host)
+ const result = f.run({ type: 'agent.switchResult', agentId: second.id, switchId, ok: true }, second.host)
+ expect(result.messages).toEqual([expect.objectContaining({ conversationId: second.chat, text: 'Your Buddy now runs on Codex.' })])
+ expect(f.state.agents).toHaveLength(2)
+ expect(f.state.conversations.find(c => c.id === second.chat)?.agentIds).toEqual([second.id])
+ expect(f.target().configuration.engine).toBe('claude')
+ })
+
+ it('refuses another person, archived, missing or old-membership chat instead of falling back', () => {
+ for (const kind of ['other person', 'archived', 'missing', 'old membership']) {
+ const f = setup(), second = addBuddy(f)
+ const chat = f.state.conversations.find(c => c.id === second.chat)!
+ if (kind === 'archived') chat.archived = true
+ if (kind === 'old membership') chat.audience!.people[0]!.generation = 'old'
+ const actor = kind === 'other person' ? { kind: 'person', userId: 'owner', email: '[email protected]' } as Actor : person
+ expect(() => f.run({ type: 'buddy.engine', engine: 'codex', conversationId: kind === 'missing' ? 'gone' : second.chat }, actor))
+ .toThrow(/unavailable/)
+ expect(f.target().switchRequest).toBeUndefined()
+ expect(second.target().switchRequest).toBeUndefined()
+ }
+ })
+
+ it('reports a failed or expired named Buddy switch in that Buddy chat', () => {
+ for (const expire of [false, true]) {
+ const f = setup(), second = addBuddy(f)
+ second.target().switchRequest = { id: 'switch-moss', engine: 'codex', profileId: 'default', requestedBy: 'peer', at: new Date(NOW).toISOString() }
+ const messages = expire ? staleSwitches(f.state, NOW + 120_001)
+ : f.run({ type: 'agent.switchResult', agentId: second.id, switchId: 'switch-moss', ok: false, error: 'signed out' }, second.host).messages
+ expect(messages).toEqual([expect.objectContaining({ conversationId: second.chat, text: expect.stringMatching(/Couldn't switch/) })])
+ }
+ })
+
+ it('gives the host each Buddy’s own private chat and keeps its subscription alert there', async () => {
+ const f = setup(), second = addBuddy(f)
+ const rows = await hostTab('swarm', f.state, 'mac', { sub: 'peer', email: '[email protected]' } as never, NOW,
+ { people: [], confidential: new Set(), agentGrant: async () => {}, teams: [], githubApp: false })
+ expect(rows.roster.find(r => 'agent' in r && r.agent.id === second.id)).toMatchObject({ buddyConversationId: second.chat })
+ expect(rows.roster.find(r => 'agent' in r && r.agent.id === f.id)).toMatchObject({ buddyConversationId: f.chat })
+ expect(f.run({ type: 'agent.alert', agentId: second.id, alert: 'limit', active: true }, second.host).messages)
+ .toEqual([expect.objectContaining({ conversationId: second.chat, text: expect.stringMatching(/subscription limit/) })])
+ })
+
+ it('keeps the same Buddy and chat through claim, replacement and result', () => {
+ const f = setup(), before = structuredClone(f.state.conversations.find(c => c.id === f.chat))
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ expect(f.target().switchRequest).toMatchObject({ engine: 'codex', profileId: 'default', requestedBy: 'peer' })
+ const switchId = f.request()
+ f.run({ type: 'agent.switchClaim', agentId: f.id, switchId }, f.host)
+ f.rebind()
+ const result = f.run({ type: 'agent.switchResult', agentId: f.id, switchId, ok: true }, f.host)
+ expect(f.state.agents).toHaveLength(1)
+ expect(f.target()).toMatchObject({ id: f.id, harnessId: 'h-new', buddyScope: 'swarm', buddyOf: { personId: 'peer', generation: 'first' }, configuration: { engine: 'codex' } })
+ expect(f.state.conversations.find(c => c.id === f.chat)).toMatchObject({ id: before!.id, agentIds: before!.agentIds, audience: before!.audience })
+ expect(result.messages).toEqual([expect.objectContaining({ conversationId: f.chat, recipients: [], text: 'Your Buddy now runs on Codex.' })])
+ expect(f.target().switchRequest).toBeUndefined()
+ })
+
+ it.each([false, null])('refuses a destination with sign-in %s before changing the Buddy', signedIn => {
+ const f = setup()
+ f.pool().observation!.readiness!.engines![1]!.signedIn = signedIn
+ expect(() => f.run({ type: 'buddy.engine', engine: 'codex' })).toThrow(/signed in/i)
+ expect(f.target().harnessId).toBe('h-old')
+ expect(f.target().switchRequest).toBeUndefined()
+ })
+
+ it('refuses an engine not installed, a missing reading, a stale reading and an old host', () => {
+ for (const edit of [
+ (f: ReturnType<typeof setup>) => { f.pool().observation!.readiness!.engines![1]!.installed = false },
+ (f: ReturnType<typeof setup>) => { delete f.pool().observation!.readiness!.engines },
+ (f: ReturnType<typeof setup>) => { f.pool().observation!.receivedAt -= 600_000 },
+ (f: ReturnType<typeof setup>) => { f.pool().observation!.capabilities = ['swarmBuddy'] },
+ ]) {
+ const f = setup(); edit(f)
+ expect(() => f.run({ type: 'buddy.engine', engine: 'codex' })).toThrow()
+ expect(f.target().switchRequest).toBeUndefined()
+ }
+ })
+
+ it('allows a Buddy-only machine but never another person or the Buddy to request the switch', () => {
+ const f = setup()
+ f.pool().buddyOnly = true
+ for (const actor of [{ kind: 'person', userId: 'owner', email: '[email protected]' } as Actor, f.host]) {
+ expect(() => f.run({ type: 'buddy.engine', engine: 'codex' }, actor)).toThrow()
+ }
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ expect(f.target().switchRequest?.engine).toBe('codex')
+ })
+
+ it('refuses an owner machine whose account became a Team account', () => {
+ const f = setup()
+ f.pool().observation!.sessionKind = 'team'
+ expect(() => f.run({ type: 'buddy.engine', engine: 'codex' })).toThrow(/own machine/i)
+ expect(f.target().switchRequest).toBeUndefined()
+ expect(f.target().harnessId).toBe('h-old')
+ })
+
+ it('excludes concurrent engine and model changes in both directions', () => {
+ const f = setup()
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ expect(() => f.run({ type: 'buddy.engine', engine: 'codex' })).toThrow(/already switching/i)
+ expect(() => f.run({ type: 'buddy.model', gridModel: null })).toThrow(/already switching/i)
+ const g = setup()
+ g.run({ type: 'buddy.model', gridModel: null })
+ expect(() => g.run({ type: 'buddy.engine', engine: 'codex' })).toThrow(/already switching/i)
+ })
+
+ it('refuses a Buddy replacement without its own claimed switch or for a different engine', () => {
+ const f = setup()
+ expect(() => f.rebind()).toThrow()
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ expect(() => f.rebind()).toThrow()
+ f.run({ type: 'agent.switchClaim', agentId: f.id, switchId: f.request() }, f.host)
+ expect(() => f.run({ type: 'agent.rebind', agentId: f.id, machineId: 'mac', previousHarnessId: 'h-old', harnessId: 'h-new', configuration }, f.host)).toThrow()
+ f.rebind()
+ expect(() => f.rebind()).not.toThrow()
+ })
+
+ it('reports failure privately, keeps the old engine, and rejects a stale outcome', () => {
+ const f = setup()
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ const switchId = f.request()
+ const result = f.run({ type: 'agent.switchResult', agentId: f.id, switchId, ok: false, error: 'that account is signed out' }, f.host)
+ expect(result.messages).toEqual([expect.objectContaining({ conversationId: f.chat, text: expect.stringMatching(/signed out.*Claude Code/) })])
+ expect(f.target().configuration.engine).toBe('claude')
+ expect(() => f.run({ type: 'agent.switchResult', agentId: f.id, switchId, ok: true }, f.host)).toThrow()
+ })
+
+ it('expires a host that never answers with a private visible failure', () => {
+ const f = setup()
+ f.run({ type: 'buddy.engine', engine: 'codex' })
+ const lines = staleSwitches(f.state, NOW + 120_001)
+ expect(lines).toEqual([expect.objectContaining({ conversationId: f.chat, text: expect.stringMatching(/Couldn't switch.*machine did not answer/) })])
+ expect(f.target().switchRequest).toBeUndefined()
+ })
+
+ it('offers an engine switch once per subscription-limit episode in its own chat', () => {
+ const f = setup()
+ const alert = { type: 'agent.alert', agentId: f.id, alert: 'limit', active: true }
+ const lines = f.run(alert, f.host).messages
+ expect(lines).toEqual([expect.objectContaining({ conversationId: f.chat, text: expect.stringMatching(/subscription limit.*[Ss]witch.*engine/), source: expect.objectContaining({ alert: 'limit' }) })])
+ expect(f.run(alert, f.host).messages).toEqual([])
+ })
+
+ it('gives only its host the Buddy chat needed to restart in place', async () => {
+ const f = setup()
+ const rows = await hostTab('swarm', f.state, 'mac', { sub: 'peer', email: '[email protected]' } as never, NOW,
+ { people: [], confidential: new Set(), agentGrant: async () => {}, teams: [], githubApp: false })
+ expect(rows.roster.find(r => 'agent' in r && r.agent.id === f.id)).toMatchObject({ buddyConversationId: f.chat })
+ })
+})
diff --git a/backend/src/superTabs/buddyEngine.ts b/backend/src/superTabs/buddyEngine.ts
new file mode 100644
index 000000000..489614bd1
--- /dev/null
+++ b/backend/src/superTabs/buddyEngine.ts
@@ -0,0 +1,45 @@
+/** A person's explicit engine switch keeps their Buddy's identity and private chat. The host uses the same durable handoff
+ * as Change agent; a backend request alone never changes the engine the Buddy is recorded as running. */
+import { buddyChatOf, buddyChatsOf, defaultBuddy, isSwarmBuddy, swarmBuddyChatId } from './buddies.js'
+import { mainBuddyOf } from './buddySessions.js'
+import { wakeCrewMember } from './crewKeep.js'
+import { startWake } from './crewTimes.js'
+import { machineOffline } from './machines.js'
+import { fail, person, type Actor, type Agent, type SuperTabState } from './model.js'
+
+export const BUDDY_ENGINE_CAPABILITY = 'buddyEngine'
+export const buddyEngineName = (engine: string): string => engine === 'claude' ? 'Claude Code' : engine === 'codex' ? 'Codex' : engine
+export const buddyEngineChat = (state: SuperTabState, buddy: Agent): string => buddyChatOf(state, buddy)?.id
+ ?? swarmBuddyChatId({ id: buddy.buddyOf!.personId, generation: buddy.buddyOf!.generation })
+
+export function askBuddyEngine(state: SuperTabState, actor: Actor, engine: string, id: string, now: number, conversationId?: string): void {
+ if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person switches their own Buddy.', 403)
+ const me = person(state, actor.userId)
+ const chat = conversationId ? buddyChatsOf(state, me).find(c => c.id === conversationId)
+ ?? fail('NOT_FOUND', 'This conversation is unavailable.', 404) : undefined
+ const buddy = (chat ? mainBuddyOf(state, chat) : defaultBuddy(state, me.id)) ?? fail('NO_BUDDY', 'You have no Buddy running.', 404)
+ if (!isSwarmBuddy(buddy) || buddy.buddyOf!.personId !== me.id || buddy.buddyOf!.generation !== me.generation) {
+ fail('NO_BUDDY', 'You have no Buddy running.', 404)
+ }
+ if (buddy.switchRequest || buddy.switchLanded || buddy.modelRequest) fail('BUDDY_SWITCHING', 'Your Buddy is already switching.', 409)
+ const pool = state.machines?.find(m => m.machineId === buddy.machineId && m.contributorId === me.id && !m.removal && !m.hostMachineId)
+ if (!pool || buddy.machineOwnerId !== me.id || pool.observation?.sessionKind === 'team') {
+ fail('BUDDY_OWN_MACHINE', 'A Buddy switches only on your own machine.', 403)
+ }
+ if (machineOffline(pool, now)) fail('MACHINE_OFFLINE', `Wait for a fresh reading from ${pool.name}.`, 409)
+ if (!pool.observation?.capabilities?.includes(BUDDY_ENGINE_CAPABILITY)) fail('HOST_OUTDATED', `Update Harness on ${pool.name} to switch your Buddy's engine.`, 409)
+ const offered = pool.observation.readiness?.engines?.find(e => e.engine === engine)
+ if (offered?.installed !== true || offered.signedIn !== true) fail('BUDDY_ENGINE_UNAVAILABLE', `${buddyEngineName(engine)} must be installed and signed in on your Buddy's machine.`, 409)
+ if (buddy.configuration.engine === engine && !buddy.gridModel) return
+ if (wakeCrewMember(buddy, now)) { buddy.keptAt = now; startWake(buddy, buddyEngineChat(state, buddy), now) }
+ buddy.switchRequest = { id, engine, profileId: 'default', requestedBy: me.id, at: new Date(now).toISOString() }
+}
+
+/** Only a claimed, still-live request can rebind a Buddy; ordinary pane replacements cannot change its account or role. */
+export function checkBuddyRebind(buddy: Agent, engine: string, profileId: string | undefined, now: number): void {
+ const request = buddy.switchRequest
+ if (!isSwarmBuddy(buddy) || buddy.buddySession || !request?.claimedUntil || Date.parse(request.claimedUntil) <= now
+ || request.engine !== engine || (profileId && profileId !== 'default')) {
+ fail('STALE_SWITCH', 'Only your Buddy\'s claimed engine switch can replace its session.', 409)
+ }
+}
diff --git a/backend/src/superTabs/buddyModel.ts b/backend/src/superTabs/buddyModel.ts
index 31fc3d77b..a1537d937 100644
--- a/backend/src/superTabs/buddyModel.ts
+++ b/backend/src/superTabs/buddyModel.ts
@@ -78,7 +78,7 @@ export function askBuddyModel(state: SuperTabState, actor: Actor, gridModel: str
const buddy = ownBuddy(state, actor, conversationId)
const can = switchable(state, buddy, now)
if (!can.ok) fail(can.code, can.message, 409)
- if (buddy.modelRequest) fail('BUDDY_SWITCHING', 'Your Buddy is already switching.', 409)
+ if (buddy.modelRequest || buddy.switchRequest || buddy.switchLanded) fail('BUDDY_SWITCHING', 'Your Buddy is already switching.', 409)
const shown = gridModel === null ? {} : served(state, gridModel, now)
if (!shown) fail('BUDDY_MODEL_UNAVAILABLE', 'Nobody in the Swarm serves that model now.', 409)
// The grid its machine moves it onto (agent_retarget's gridName): the Swarm's own, the one the models were checked on.
@@ -93,7 +93,7 @@ export function sendBuddyHome(state: SuperTabState, from: Agent, reason: 'limit'
// The main Buddy of [from]'s own chat (task #3818: a person may have several), else theirs as before.
const chat = buddyChatOf(state, from)
const buddy = (chat && mainBuddyOf(state, chat)) ?? mainBuddy(state, from.buddyOf.personId, from.buddyOf.generation)
- if (!buddy?.gridModel || buddy.modelRequest || !switchable(state, buddy, now).ok) return
+ if (!buddy?.gridModel || buddy.modelRequest || buddy.switchRequest || buddy.switchLanded || !switchable(state, buddy, now).ok) return
buddy.modelRequest = { id: requestId, gridModel: null, name: current(state, buddy, now), reason,
requestedBy: buddy.buddyOf!.personId, at: new Date(now).toISOString() }
}
diff --git a/backend/src/superTabs/buddySleep.test.ts b/backend/src/superTabs/buddySleep.test.ts
index 84cced25f..c9a3aa50e 100644
--- a/backend/src/superTabs/buddySleep.test.ts
+++ b/backend/src/superTabs/buddySleep.test.ts
@@ -27,6 +27,13 @@ function fixture() {
}
describe('server-owned Buddy sleep', () => {
+ it.each(['requested', 'landed'])('does not sleep during a %s engine switch', phase => {
+ const f = fixture()
+ if (phase === 'requested') f.buddy.switchRequest = { id: 'switch', engine: 'codex', profileId: 'default', requestedBy: 'owner', at: new Date(NOW).toISOString() }
+ else f.buddy.switchLanded = { id: 'switch', requestedBy: 'owner' }
+ expect(buddySleepCandidates(f.state, NOW)).toEqual([])
+ })
+
it('keeps private engine-idle proof out of member reads', () => {
const f = fixture()
const visible = visibleState(f.state, { kind: 'person', userId: f.owner.id, email: f.owner.email }, NOW)
diff --git a/backend/src/superTabs/buddySleep.ts b/backend/src/superTabs/buddySleep.ts
index 454850eaf..9125f2548 100644
--- a/backend/src/superTabs/buddySleep.ts
+++ b/backend/src/superTabs/buddySleep.ts
@@ -27,7 +27,7 @@ export function buddySleepManaged(state: SuperTabState, agent: Agent): boolean {
export function buddySleepCandidates(state: SuperTabState, now: number): Agent[] {
if (state.paused) return []
return state.agents.filter(agent => {
- if (agent.asleep || agent.modelRequest || !buddySleepManaged(state, agent)) return false
+ if (agent.asleep || agent.modelRequest || agent.switchRequest || agent.switchLanded || !buddySleepManaged(state, agent)) return false
const pool = state.machines?.find(m => m.machineId === agent.machineId), reading = pool?.observation
if (!pool || pool.paused || pool.removal || !reading || now - reading.receivedAt > MACHINE_FRESH_MS
|| !reading.runningHarnessIds.includes(agent.harnessId) || !reading.idleBuddyHarnessIds?.includes(agent.harnessId)) return false
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index a3b200ca9..d0f1a80ff 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -73,6 +73,7 @@ import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liv
import { BUDDY_REQUIREMENTS, buddyCapOf, buddyCapRefusal, buddyChatId, buddyChatOf, buddyChatsOf, buddyCount, defaultBuddy, defaultBuddyChat, hasBuddy, dropBuddyChat, MAX_BUDDY_CAP, openNewBuddyChat, setDefaultBuddy, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, okayedWords, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalBrief, proposalSentText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'
import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'
+import { askBuddyEngine, buddyEngineChat, buddyEngineName, checkBuddyRebind } from './buddyEngine.js'
import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadEffort, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'
import { ACK_ONLY_HINT, isAcknowledgement } from './acknowledgements.js'
import { isProjectChat, inMainChat, requireChatContent, requireChatPost, recordChatAsk, recordChatPost, requireChatAnswer, recordChatAnswer } from './chatLimits.js'
@@ -373,6 +374,7 @@ export const commandSchema = z.discriminatedUnion('type', [
// A person ends a thread session of their own Buddy chat (buddySessions.ts): `ended` from their app, `idle` and `stopped` from
// their machine's host, which acts as them. Idempotent: a thread with no session is told so and nothing changes.
// The person's own Buddy onto a model the Swarm's grid serves now, or back to their subscription (null): buddyModel.ts.
+ z.object({ type: z.literal('buddy.engine'), engine: swarmEngine, conversationId: id.optional() }).strict(),
// `conversationId`: which of the person's Buddies, by its chat (task #3818); without it, their default.
z.object({ type: z.literal('buddy.model'), gridModel: z.string().trim().min(1).max(200).nullable(), conversationId: id.optional() }).strict(),
// What the Buddy's machine reports once it carried the request out: `fresh` when the conversation was too long for the model.
@@ -415,7 +417,7 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('crew.remove'), agentId: id }).strict(),
z.object({ type: z.literal('agent.sessionClosed'), agentId: id, harnessId: id }).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,
+ z.object({ type: z.literal('agent.rebind'), agentId: id, machineId: id, projectId: id.optional(),
previousHarnessId: id, harnessId: id, configuration, profileId: z.string().regex(/^([0-9a-f]{16}|default)$/).optional(),
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(),
@@ -823,7 +825,7 @@ function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabS
/** What may name a person's one Buddy chat: posts, reactions, proposals, naming the Buddy and ending a session. */
const SWARM_BUDDY_CHAT_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'message.edit', 'message.delete', 'buddy.propose', 'buddy.rename', 'buddy.sessionEnd',
// Which of a person's several Buddies (task #3818).
- 'buddy.create', 'buddy.remove', 'buddy.default', 'buddy.model'])
+ 'buddy.create', 'buddy.remove', 'buddy.default', 'buddy.model', 'buddy.engine'])
function viewerProposal(state: SuperTabState, actor: Actor, command: Command): boolean {
if (command.type === 'proposal.create' || command.type === 'proposal.answer') return true
if (command.type !== 'buddy.propose' || actor.kind !== 'agent') return false
@@ -3305,6 +3307,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
case 'buddy.rename':
renameBuddy(state, actor, readConversation(state, actor, command.conversationId), command.name, context.buddyNames)
break
+ case 'buddy.engine':
+ askBuddyEngine(state, actor, command.engine, operationId, context.now, command.conversationId)
+ break
case 'buddy.model':
askBuddyModel(state, actor, command.gridModel, operationId, context.now, command.conversationId)
break
@@ -3678,7 +3683,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
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)) {
+ || command.machineId !== target.machineId || (isSwarmBuddy(target) ? command.projectId !== undefined : 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.')
@@ -3686,6 +3691,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
fail('SESSION_CONTRIBUTED', 'The replacement terminal already belongs to another member.')
}
if (target.harnessId === command.harnessId && target.replacement?.previousHarnessId === command.previousHarnessId) break
+ if (isBuddy(target)) checkBuddyRebind(target, command.configuration.engine, storedProfileId(target.machineId, command.configuration.engine, command.profileId), context.now)
if (target.harnessId !== command.previousHarnessId || command.harnessId === command.previousHarnessId) {
fail('AGENT_CHANGED', 'The member’s terminal changed. Read its current binding before replacing it.')
}
@@ -3810,6 +3816,17 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const asked = (landed ?? target.switchRequest)?.requestedBy
// A rebind already moved the PM: a failure the host reported as it landed is not what happened.
const moved = command.ok || !!landed
+ if (isBuddy(target)) {
+ if (moved && !landed) fail('STALE_SWITCH', 'The Buddy has not confirmed its new session yet.', 409)
+ delete target.switchRequest
+ delete target.switchLanded
+ const engine = buddyEngineName(target.configuration.engine)
+ const error = command.error?.replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/[.\s]+$/, '')
+ effects.messages.push({ id: operationId, conversationId: buddyEngineChat(state, target), author: sender, replyTo: null, recipients: [], source: SYSTEM_ROW,
+ text: moved ? `Your Buddy now runs on ${engine}.`
+ : `Couldn't switch your Buddy: ${error || 'it failed'}. ${command.down ? `It has not come back on ${engine} yet; its machine keeps trying.` : `It is back on ${engine}.`}` })
+ break
+ }
if (moved && !landed && target.switchRequest) moveToProfile(target, target.switchRequest.engine, target.switchRequest.profileId)
delete target.switchRequest
delete target.switchLanded
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index 542885d9a..cfe488400 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -5,6 +5,8 @@ import { agentProjectId, canReadProject, groupProject, projectsOf } from '../pro
import type { Touch } from './commit.js'
import { waitsNow } from '../leaderboard/record.js'
import { buddiesHearing } from '../buddyNews.js'
+import { defaultBuddy } from '../buddies.js'
+import { mainBuddyOf } from '../buddySessions.js'
/**
* The parts a command relies on without writing them (design section 1.2, column T). A part the command also writes is
@@ -61,6 +63,13 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
case 'machine.contribute':
if (!before.machines?.some(m => m.machineId === command.machineId)) head()
break
+ case 'buddy.engine': {
+ const chat = before.conversations.find(c => c.id === command.conversationId)
+ const buddy = command.conversationId ? chat && mainBuddyOf(before, chat)
+ : actor.kind === 'person' ? defaultBuddy(before, actor.userId) : undefined
+ if (buddy) machine(buddy.machineId)
+ break
+ }
case 'proposal.create':
head()
group(leadGroupOf(command.projectId))
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 86b0a5709..047768f99 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -297,6 +297,8 @@ export type HostRosterRow =
| { tabId: string; cleanup: { machineId: string; removalId: string } }
| { tabId: string; joinTeam: { machineId: string; name: string; maxAgents: number } }
export interface HostAgentRow {
+ /** A main Buddy's private chat, used only by its own host to restart it on another engine. */
+ buddyConversationId?: string
tabId: string
tabName: string
lastChangedAt: number | null
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index 435c344b5..abba3820d 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -7,6 +7,7 @@ import { buddySleepManaged } from '../buddySleep.js'
import type { AuthUser } from '../../lib/ssoAuth.js'
import { activeWork, agent, isLeads, SuperTabError, conversation, type Agent, type SuperTabState } from '../model.js'
import { buddyChatOf, isSwarmBuddy, isSwarmBuddyChat } from '../buddies.js'
+import { buddyEngineChat } from '../buddyEngine.js'
import { hostLocalGrid, machineContribution, machineLimitReached, machineRoom, type MachineCleanup } from '../machines.js'
import { agentProjectId, agentSetRole, canWatchAgent, isConfidential, groupProject, ledProject, projectsOf, skillModeOf, startProject, skillSetOf, watchClosed } from '../projects.js'
import type { HostAgentRow, HostPool, HostRosterRow, HostTabRows } from './contract.js'
@@ -79,6 +80,7 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
const home = projectsOf(state).find(p => p.id === agentProjectId(state, target))
const custom = home && skillSetOf(home) === 'custom' ? home : null
const chosen = custom ? agentSetRole(state, custom, target) : null
+ const buddyChat = isSwarmBuddy(target) || (target.buddySession && target.buddyOf) ? buddyChatOf(state, target) : undefined
return {
tabId, tabName: state.name, lastChangedAt, paused: state.paused,
// `active` lets the host release members that are only in archived groups to automatic cleanup.
@@ -110,6 +112,7 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
// The conversation it leads: the chat its host rebuilds its start prompt from when it switches it (cli leadSwitchRequest.ts).
// A field of its own: an older host reads leadsConversationId as "only this conversation's deliveries" (cli host.ts).
ledConversationId: ledProject(state, target.id)?.leadConversationId ?? null,
+ ...(isSwarmBuddy(target) && !target.buddySession ? { buddyConversationId: buddyChat?.id ?? buddyEngineChat(state, target) } : {}),
stopRequested: target.workDecision === 'stop' && !state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id),
observers: lookups.people.filter(p => p.id !== user.sub && canWatchAgent(state, { kind: 'person', userId: p.id, email: p.email }, target, closed))
.map(p => ({ email: p.email, userId: p.id })),
@@ -118,7 +121,7 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
// But for this Swarm's current Lead: its listed observers watch it while this row is in force (Ken, 2026-10-28).
membersWatch: isConfidential(state, target, closed) && !watchClosed(state, target, closed),
// Which of its person's Buddies' chats it is in (task #3818).
- ...isSwarmBuddy(target) || (target.buddySession && target.buddyOf) ? { buddyChatId: buddyChatOf(state, target)?.id ?? null } : {},
+ ...isSwarmBuddy(target) || (target.buddySession && target.buddyOf) ? { buddyChatId: buddyChat?.id ?? null } : {},
}
}
diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.ts
index 0004f9825..07ec9849d 100644
--- a/backend/src/superTabs/terminal.ts
+++ b/backend/src/superTabs/terminal.ts
@@ -178,7 +178,9 @@ export function terminalAlert(state: SuperTabState, actor: Actor, sender: Author
const reset = command.resetAt && Date.parse(command.resetAt) > now ? Date.parse(command.resetAt) : now + LIMIT_FALLBACK_MS
target.limitedUntil = source.limitedUntil = new Date(reset).toISOString()
// The PM's line has no time: Desktop shows `limitedUntil` in the reader's local time, next to the line.
- if (ledProject(state, target.id)) {
+ if (isBuddy(target) && !target.gridModel) {
+ text = 'Your Buddy reached its subscription limit. Switch engine in the Buddy header to continue.'
+ } else if (ledProject(state, target.id)) {
text = `${nameOf(target)} hit a usage limit.`
source.lead = true
} else text = `${nameOf(target)} hit a usage limit. Routing skips it until ${target.limitedUntil.slice(11, 16)} UTC.`
diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.ts
index a55ee0262..474ade12a 100644
--- a/backend/src/superTabs/tidy.ts
+++ b/backend/src/superTabs/tidy.ts
@@ -1,5 +1,6 @@
import { checksOpenWork, isStep, taskEnded } from './steps.js'
-import { isBuddy } from './buddies.js'
+import { isBuddy, isSwarmBuddy } from './buddies.js'
+import { buddyEngineChat } from './buddyEngine.js'
import { isCrew } from './crew.js'
import { expiredModelRequests, unservedBuddyModels } from './buddyModel.js'
import { agentDisplayName } from './agentNames.js'
@@ -107,12 +108,13 @@ export function staleSwitches(state: SuperTabState, now: number): MessageDraft[]
const rows: MessageDraft[] = []
for (const pm of state.agents) {
const request = pm.switchRequest, project = request && ledProject(state, pm.id)
- if (!request || !project) continue
+ const chat = isSwarmBuddy(pm) && !pm.buddySession ? buddyEngineChat(state, pm) : project?.leadConversationId
+ if (!request || !chat) continue
if (!switchExpired(request, now)) continue
delete pm.switchRequest
- rows.push({ id: stableId('switch-stale', pm.id, request.id), conversationId: project.leadConversationId, replyTo: null, recipients: [],
+ rows.push({ id: stableId('switch-stale', pm.id, request.id), conversationId: chat, replyTo: null, recipients: [],
author: { kind: 'agent', id: pm.id, name: pm.name, displayName: agentDisplayName(state.agents, pm.id), membershipGeneration: pm.membershipGeneration },
- text: "Couldn't switch the PM: its machine did not answer.", source: { kind: 'switch', agentId: pm.id } })
+ text: `Couldn't switch ${isBuddy(pm) ? 'your Buddy' : 'the PM'}: its machine did not answer.`, source: { kind: 'switch', agentId: pm.id } })
}
return rows
}
diff --git a/cli/e2e/superTabSwarmBuddy.e2e.ts b/cli/e2e/superTabSwarmBuddy.e2e.ts
index 3372eae73..6fc2d75ef 100644
--- a/cli/e2e/superTabSwarmBuddy.e2e.ts
+++ b/cli/e2e/superTabSwarmBuddy.e2e.ts
@@ -1,6 +1,7 @@
-/** A person's Buddy on the real native protocol: a private daemon, tmux and data dir, a fake Claude engine and backend.
- * Its home copies a local fixture project without a GitHub token. Sleep releases the engine and terminal; its person's
- * message resumes the same conversation and preserved folder. Server sleep/wake policy is tested through the real store. */
+/** A person's one Buddy started on their own machine in the Swarm, on the real native protocol: a private daemon, tmux and
+ * data dir, a fake Claude engine and the fake backend. It has no project, so nothing is cloned and no GitHub token is asked
+ * for, and the folder its start names is never made: 2026-11-02, each of those failed every such start while unit tests,
+ * which faked the steps either side, passed. */
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
@@ -9,8 +10,9 @@ import { LocalClient } from './harness/client.js'
import { IsolatedDaemon, until } from './harness/daemon.js'
import { FakeBackend } from './harness/fakeBackend.js'
import { signedInDaemon } from './harness/fleet.js'
-import { overOldRoutes } from './harness/swarmReads.js'
+import { isTeamAccount } from '../src/team/config.js'
import { isTeamDaemon } from '../src/superTabs/teamDaemon.js'
+import { overOldRoutes } from './harness/swarmReads.js'
const TAB = 'buddy-tab'
const ME = { machineId: 'd3'.repeat(16), computerId: 'one-buddy-fixture', name: 'Buddy fixture', token: 'fixture-buddy-token', account: 'person', email: '[email protected]' }
@@ -21,6 +23,114 @@ afterEach(async () => {
await relay?.close(); relay = undefined
})
+// A Team OS account must refuse every real Buddy launch; approved CI runs this flow on an isolated runner account.
+it.skipIf(isTeamAccount())('starts and switches its engine in the same folder and private chat, with one Buddy and no app token', async () => {
+ const backend = await FakeBackend.start(); relay = backend
+ backend.addMachine(ME)
+ backend.me = { id: 'person', email: ME.email }
+ // As a real engine does: it asks about a folder it has no answer for, in a terminal no Swarm view shows.
+ const d = await signedInDaemon(backend, ME, { ANTHROPIC_API_KEY: 'fixture-only' }, undefined, true); daemon = d
+ writeFileSync(join(d.env.HOME!, '.claude.json'), '{}')
+ mkdirSync(d.env.CODEX_HOME!, { recursive: true })
+ writeFileSync(join(d.env.CODEX_HOME!, 'auth.json'), JSON.stringify({ OPENAI_API_KEY: 'fixture-only' }), { mode: 0o600 })
+ const project = join(d.projectsDir, 'api'); mkdirSync(project, { recursive: true })
+ const git = (...args: string[]) => execFileSync('git', ['-c', 'user.name=Fixture', '-c', '[email protected]', ...args], { cwd: project, stdio: 'ignore' })
+ git('init', '-q'); writeFileSync(join(project, 'README.md'), 'fixture\n'); git('add', '.'); git('commit', '-qm', 'fixture')
+ const cwd = join(d.env.HOME!, 'harnesses', 'swarms', TAB)
+ const pool = { machineId: ME.machineId, generation: 'grant-1', cwd, scope: 'swarm', engines: ['claude'], maxAgents: 2, paused: false }
+ const start: Record<string, any> = { id: 'start-buddy', machineOwnerId: 'person', contributorId: 'person', poolGeneration: 'grant-1', creationId: 'super-start-buddy', dispatched: false, harnessId: null, error: null,
+ request: { conversationId: 'buddy-chat', machineId: ME.machineId, engine: 'claude', name: "person's Buddy", cwd: `${cwd}/.buddy-person`, worktree: false,
+ requirements: { memoryBytes: 0, diskBytes: 1, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false },
+ buddyOf: { personId: 'person', generation: 'g' }, buddyScope: 'swarm', buddyProjects: [{ id: 'p1', name: 'API', cwd: project }] } }
+ const agents: Array<Record<string, any>> = [], asked: string[] = []
+ const outcomes: Record<string, any>[] = []
+ let rebinds = 0, claims = 0
+ backend.superTabs = overOldRoutes(async (method, raw, body) => {
+ const path = new URL(raw, backend.httpUrl).pathname
+ if (path.endsWith('/github-token')) { asked.push(path); throw Object.assign(new Error('This start has no project folder to prepare.'), { status: 404, code: 'NOT_FOUND' }) }
+ if (path.endsWith('/pools')) return { data: [{ tabId: TAB, machine: pool, projects: [], starts: [], buddyStarts: start.harnessId && start.poolSettled ? [] : [start], githubApp: true, harnessIds: agents.map(a => a.harnessId) }] }
+ if (path.includes('/hosts/') && path.includes('/starts/')) {
+ if (method === 'GET') return { data: start }
+ const c = body.command
+ if (c.type === 'agent.startDispatch') start.dispatched = true
+ else if (c.type === 'agent.started') { start.harnessId = c.harnessId; agents.push({ id: 'buddy', machineId: ME.machineId, harnessId: c.harnessId, buddyScope: 'swarm', buddyOf: { personId: 'person', generation: 'g' }, configuration: c.configuration }) }
+ else if (c.type === 'agent.startSettled') start.poolSettled = true
+ else if (c.type === 'agent.startFailed') start.error = c.error
+ return { data: { result: {} } }
+ }
+ if (path.endsWith('/assignments')) return { data: [] }
+ if (path.includes('/hosts/')) return { data: agents.map(agent => ({ tabId: TAB, active: true, buddyConversationId: 'buddy-chat', agent })) }
+ if (path.endsWith('/commands')) {
+ const command = body.command, buddy = agents[0]
+ if (command.type === 'agent.switchClaim') { expect(body.asAgentId).toBe('buddy'); claims++ }
+ else if (command.type === 'agent.rebind') {
+ expect(command).toMatchObject({ agentId: 'buddy', previousHarnessId: buddy.harnessId, configuration: { engine: 'codex' } })
+ expect(command).not.toHaveProperty('projectId')
+ // Like the real backend, retain the completed request until the host reports its outcome.
+ buddy.switchLanded = { id: buddy.switchRequest.id, requestedBy: buddy.switchRequest.requestedBy }
+ buddy.harnessId = command.harnessId; buddy.configuration = command.configuration; delete buddy.switchRequest; rebinds++
+ } else if (command.type === 'agent.switchResult') {
+ outcomes.push(command); delete buddy.switchRequest; delete buddy.switchLanded
+ } else if (command.type === 'agent.configuration') buddy.configuration = command.configuration
+ else throw new Error(`Unexpected command ${command.type}`)
+ return { data: { result: {} } }
+ }
+ if (path.includes('/machines/')) return { data: { revision: 1 } }
+ if (path === `/api/super-tabs/${TAB}`) return { data: { state: { id: TAB, agents, projects: [], conversations: [] }, revision: 1 } }
+ if (path.endsWith('/deliveries') || path.endsWith('/grids')) return { data: [] }
+ throw new Error(`Unexpected request ${path}`)
+ })
+ onTestFailed(() => console.log(d.log().split('\n').slice(-80).join('\n')))
+ await d.start()
+ await until('the machine connected', () => backend.nodeUp(ME.machineId), 30000)
+ client = await LocalClient.connect(d, { machineId: ME.machineId })
+ await client.request('super_tabs', { action: 'wake' }, 30000)
+ await until('its Buddy started', () => {
+ expect(start.error).toBeNull()
+ return start.harnessId
+ }, 90000, 250)
+ expect(asked).toEqual([])
+ expect((await client.request('agents_list')).agents.map((a: Record<string, any>) => a.id)).toContain(start.harnessId)
+ const homes = join(d.env.HOME!, 'harnesses', 'worktrees', 'buddy-home'), folders = readdirSync(homes)
+ expect(folders).toHaveLength(1)
+ expect(existsSync(join(homes, folders[0]!, 'projects', 'API', 'README.md'))).toBe(true)
+ expect(existsSync(start.request.cwd)).toBe(false)
+ const original = agents[0].harnessId
+ const registered = (id: string) => JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8'))
+ .find((agent: Record<string, any>) => agent.agentId === id)
+ const originalCwd = registered(original).cwd
+ expect(originalCwd).toBe(join(homes, folders[0]!))
+ const before = await until('the original Buddy to bind its native conversation', async () => {
+ const row = (await client!.request('agents_list')).agents.find((agent: Record<string, any>) => agent.id === original)
+ return row?.sessionId ? row : null
+ }, 30_000, 100)
+ const close = { agentId: original, sessionId: before.sessionId, createdAt: before.createdAt }
+ await until('the host to retain the Buddy', async () => (await client!.request('agent_close', { ...close, mode: 'inspect' })).keptRunning === true || null, 15_000, 100)
+ // Ordinary Close still keeps a Buddy running; the engine switch alone carries its prepared handoff permit.
+ expect(await client.request('agent_close', { ...close, mode: 'now' })).toMatchObject({ error: 'BUDDY_PROTECTED' })
+ agents[0].switchRequest = { id: 'engine-switch', engine: 'codex', profileId: 'default', requestedBy: 'person' }
+ await client.request('super_tabs', { action: 'wake' }, 30_000)
+ await until('the Buddy engine switch to settle', () => outcomes.length > 0 || null, 60_000, 100)
+ expect(outcomes).toEqual([{ type: 'agent.switchResult', agentId: 'buddy', switchId: 'engine-switch', ok: true }])
+ expect(claims).toBe(1)
+ expect(rebinds).toBe(1)
+ const live = (await client.request('agents_list')).agents
+ expect(live).toHaveLength(1)
+ expect(live[0]).toMatchObject({ id: agents[0].harnessId, engine: 'codex' })
+ expect(live[0].id).not.toBe(original)
+ const saved = registered(live[0].id)
+ expect(saved.cwd).toBe(originalCwd)
+ expect(saved.swarmSkill).toMatchObject({ role: 'buddy' })
+ expect(saved.swarmSkill.github).not.toBe(true)
+ // Codex receives its first prompt on launch, before the switch reports success.
+ const launches = readFileSync(join(d.root, 'launch-argv'), 'utf8').split('\n').filter(Boolean)
+ .map(line => JSON.parse(line) as { engine: string; args: string[] })
+ expect(launches.some(({ engine, args }) => engine === 'codex' && args.some(prompt =>
+ prompt.includes('Your chat with your owner is conversation buddy-chat') && prompt.includes('Context handoff:')))).toBe(true)
+ expect(agents[0]).toMatchObject({ id: 'buddy', buddyOf: { personId: 'person', generation: 'g' } })
+ expect(asked).toEqual([])
+})
+
// A Buddy is forbidden on a Team OS account even in an isolated daemon; this native flow needs an owner's account.
it.skipIf(isTeamDaemon())('releases an idle Buddy session and wakes the same conversation on its person’s message', async () => {
const backend = await FakeBackend.start(); relay = backend
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 2356bb5c4..518e75674 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2925,7 +2925,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
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),
+ buddyProtected: (agentId: string, changeId?: string) => swarm.buddyCloseProtected(env.ADAPTER_DATA_DIR, agentId, changeId),
} : {}),
})
backend.closeAgentService = closing.closeAgentService
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index a19ab8d10..c40870b5d 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -859,3 +859,15 @@ it('waits on a real timer when no sleep is given', async () => {
expect(await closing).toEqual({ closed: true })
expect(Date.now() - start).toBe(1_000)
})
+
+
+it('passes the prepared change id to the Buddy guard only for an immediate switch, and records its stop', async () => {
+ const changeId = 'a'.repeat(32)
+ const ended = vi.fn()
+ const buddyProtected = (id: string, change?: string) => id === row.agentId && change !== changeId
+ const svc = new CloseAgentService({ ...deps, buddyProtected, leadSwitchEnded: ended })
+ expect(await svc.request({ ...request('idle'), changeId })).toMatchObject({ error: 'BUDDY_PROTECTED' })
+ expect(await svc.request({ ...request('now'), changeId })).toEqual({ closed: true })
+ expect(ended).toHaveBeenCalledWith(row.agentId, changeId, true)
+ svc.dispose()
+})
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index d71f81ba7..c35b24943 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -130,9 +130,8 @@ export interface CloseAgentServiceDeps {
/** 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`): ordinary closes never stop it.
- * Only the internal idle sleep permit or Stop Harness may do so. */
- buddyProtected?(agentId: string): boolean
+ /** A Buddy refuses ordinary closes; its prepared engine switch or internal idle sleep permit grants one stop. */
+ buddyProtected?(agentId: string, changeId?: string): boolean
/** Whether its pane shows a question the engine asks before any conversation: the folder's trust, or an MCP server the
* folder brings (`trust_open`). */
atStartupQuestion?(s: RegisteredSession): Promise<boolean>
@@ -194,7 +193,7 @@ export class CloseAgentService {
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
+ const buddy = this.deps.buddyProtected?.(request.agentId, changeId) === true
if (buddy && request.mode !== 'inspect' && !(request.mode === 'idle' && typeof request.buddySleep === 'function' && request.buddySleep())) {
return Promise.resolve({ error: 'BUDDY_PROTECTED', detail: BUDDY_PROTECTED_DETAIL, keptRunning: true })
}
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index f6c399af2..6bef67e19 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -33,6 +33,7 @@ import type { attachedFiles as attachedFilesType } from './attachments.js'
import { backend, writeJournal, removeStaleJournalTemps, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmListedFor, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
import { ADDED_MAX } from './deliveryContext.js'
import { SWITCH_ADOPT_MS, SWITCH_HOLD_MS } from './leadSwitch.js'
+import { switchChangeId } from './leadSwitchRequest.js'
import { TerminalHost } from './terminal.js'
import { hostForm, swarmReply } from './fixtures/read/index.js'
import { CREW_CONTINUE } from './crew.js'
@@ -4751,12 +4752,31 @@ describe('keeping a Swarm Lead alive', () => {
// 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 switched = (t: ReturnType<typeof lifeFixture>, at = 0, changeId = 'f'.repeat(32)) => {
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 })
+ JSON.stringify({ version: 1, agentId: 'harness', changeId, targetEngine: 'codex', at }), { mode: 0o600 })
}
+
+ it('reports a Buddy switch after the backend replaces its request with the landed receipt', async () => {
+ const buddy = { tabId: 'tab', active: true, buddyConversationId: 'private-chat', agent: {
+ id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyScope: 'swarm',
+ buddyOf: { personId: 'peer', generation: 'g' },
+ switchRequest: { id: 'buddy-switch', engine: 'codex', requestedBy: 'peer' },
+ } }
+ const t = lifeFixture([buddy])
+ switched(t, 0, switchChangeId('buddy-switch'))
+ await t.poll()
+ const results = () => t.commands.map(body => body.command as Record<string, unknown>)
+ .filter(command => command.type === 'agent.switchResult')
+ expect(results()).toEqual([])
+ // Same-machine agent.rebind keeps this receipt, without the cross-machine candidateAgentId.
+ t.rows.splice(0, 1, { ...buddy, agent: { ...buddy.agent, harnessId: 'replacement', switchRequest: undefined,
+ switchLanded: { id: 'buddy-switch', requestedBy: 'peer' } } })
+ await t.poll(5_000)
+ expect(results()).toEqual([{ type: 'agent.switchResult', agentId: 'agent', switchId: 'buddy-switch', ok: true }])
+ })
/** 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
@@ -4833,6 +4853,78 @@ describe('keeping a Swarm Lead alive', () => {
expect(u.closeMember).not.toHaveBeenCalled()
})
+ it('recovers a switching Buddy across restart and closes a late replacement before the original stays alone', async () => {
+ const buddy = { ...leadRow({ lead: false, buddyConversationId: 'private-chat' }), agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyOf: { personId: 'peer', generation: 'g' } } }
+ const t = lifeFixture([buddy])
+ switched(t)
+ await t.poll()
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ t.host.stop()
+ const again = t.open()
+ t.wait(SWITCH_HOLD_MS + 1)
+ await again.tick()
+ await vi.waitFor(() => expect(t.keepLeadAlive).toHaveBeenCalledWith('harness'))
+ replacement(t, () => true, () => true)
+ t.wait(5_000)
+ await again.tick()
+ await vi.waitFor(() => expect(t.closeMember).toHaveBeenCalledWith('new-session', 'f'.repeat(32)))
+ })
+
+ it('does not reopen the original Buddy until an unadopted replacement is confirmed closed', async () => {
+ const buddy = { ...leadRow({ lead: false }), agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyOf: { personId: 'peer', generation: 'g' } } }
+ const t = lifeFixture([buddy])
+ switched(t)
+ replacement(t, () => true)
+ t.closeMember.mockResolvedValue({ error: 'AGENT_CHANGED' })
+ await t.poll(SWITCH_ADOPT_MS + 1)
+ expect(t.closeMember).toHaveBeenCalledWith('new-session', 'f'.repeat(32))
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ t.closeMember.mockResolvedValue({ closed: true })
+ await t.poll(5_000)
+ await vi.waitFor(() => expect(t.keepLeadAlive).toHaveBeenCalledWith('harness'))
+ })
+
+ it('wakes a managed Buddy after switch rollback, without reopening an explicit Stop', async () => {
+ const buddy = { ...leadRow({ lead: false, buddySleepManaged: true }), agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyOf: { personId: 'peer', generation: 'g' } } }
+ const t = lifeFixture([buddy])
+ t.keepLeadAlive.mockResolvedValue({ ok: true })
+ switched(t)
+ await t.poll(SWITCH_HOLD_MS + 1)
+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)
+ t.live(true)
+ Object.assign(buddy.agent, { asleep: { since: 1 } })
+ await t.poll(1_000)
+ expect(t.closeMember).toHaveBeenCalledTimes(1)
+ t.live(false)
+ delete (buddy.agent as Record<string, unknown>).asleep
+ t.host.stop()
+ const again = t.open()
+ t.wait(60_000)
+ await again.tick()
+ await vi.waitFor(() => expect(t.keepLeadAlive).toHaveBeenCalledTimes(2))
+ Object.assign(buddy, { stopRequested: true })
+ t.wait(60_000)
+ await again.tick()
+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps Stop Harness effective after Buddy rollback, across host restart, while removing a late replacement', async () => {
+ const buddy = { ...leadRow({ lead: false }), agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyOf: { personId: 'peer', generation: 'g' } } }
+ const t = lifeFixture([buddy])
+ t.keepLeadAlive.mockResolvedValue({ ok: true })
+ switched(t)
+ await t.poll(SWITCH_HOLD_MS + 1)
+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)
+ t.host.stop()
+ // The person's Stop happens after recovery; the host restarts with the original stopped again.
+ const again = t.open()
+ replacement(t, () => true)
+ t.wait(5_000)
+ await again.tick()
+ await vi.waitFor(() => expect(t.closeMember).toHaveBeenCalledWith('new-session', 'f'.repeat(32)))
+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)
+ })
+
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 b78190ca3..8579d972e 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -54,7 +54,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 { leadSwitchOf, leadSwitchRecovered, SWITCH_ADOPT_MS, SWITCH_RECOVERY_MS, switchWithin, type LeadSwitch } from './leadSwitch.js'
import { backend, ENDED_WORK, identifier, object, SuperTabHostError, within } from './wire.js'
import { parseSwarmSkill, recordSwarmSkillNotice, refreshSwarmSkill, wireRole, type CustomSwarmRole, type SkillRefresh, type SwarmSkill, type SwarmSkillGrant,
type SwarmSkillMode } from '../lib/swarmSkills.js'
@@ -383,7 +383,7 @@ const HELD_RECLAIM_MS = 120_000
const HELD_LIST_MS = 30_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 LATE_REPLACEMENT_MS = SWITCH_RECOVERY_MS
const LEAD_RETRY_MAX_MS = 30 * 60_000
const LEAD_REOPEN_WAIT_MS = 60_000
/** How often a running Product Manager is checked for a hang (watchLead): its owed ask's time is in minutes. */
@@ -640,7 +640,9 @@ export class SuperTabHost {
builtInHash: string | null; builtIn: string | null; history: { summary: string | null; savedAt: number | null } | null; failedSince?: number }>()
private skillsRunning: Promise<void> | null = null
private missing = new Map<string, number>()
- /** Per Lead harness here: a reopen in progress, its failures, when the next may run, and the reason last logged. */
+ /** A Buddy with no pending switch is checked once at roster admission, never on idle passes. */
+ private readonly buddySwitches = new Map<string, number>()
+ /** Per protected harness here: its reopen, failures, retry time and last logged reason. */
private readonly keepAlives = new Map<string, { running: boolean; failures: number; retryAt: number; reason?: string }>()
/** Per Product Manager harness here (watchLead): when it was last checked, since when it has been in one turn, the owed ask
* it was last restarted for, a check or restart in progress, and until when the keep-alive leaves its relaunch be. */
@@ -1247,12 +1249,13 @@ export class SuperTabHost {
/** Every delivery of those lists, also those after one whose claim threw: only a list read without it says it is gone. */
const listed = new Set<string>()
const running: HostAgent[] = []
- const leads = new Set<string>(), ended = new Set<string>()
+ const leads = new Set<string>(), ended = new Set<string>(), rosterHarnesses = new Set<string>()
this.serveBuddyModels(data)
for (const item of data) {
const row = object(item), agent = object(row.agent)
if (!identifier(row.tabId) || !identifier(agent.id) || !identifier(agent.harnessId) || agent.machineId !== this.machineId) continue
const target = row as unknown as HostAgent
+ rosterHarnesses.add(target.agent.harnessId)
// A row still marked Lead is never closed (owner, 2026-10-23); one marked both is neither closed nor reopened.
if (row.closeSession === true) {
ended.add(endingKey(target))
@@ -1289,11 +1292,17 @@ export class SuperTabHost {
.finally(() => { this.restoring.delete(restKey) }))
}
if ((target.agent as { crew?: unknown }).crew) this.pruneCrewBranches(target.tabId, target.agent.harnessId)
- if (row.lead === true || target.agent.switchLanded) {
- if (row.lead === true) leads.add(target.agent.harnessId)
- this.keepAlive(target.agent.harnessId)
+ const buddy = isBuddy(agent) && !agent.buddySession
+ if (buddy && (!this.buddySwitches.has(target.agent.harnessId) || agent.switchRequest)) {
+ const record = leadSwitchOf(this.core.dataDir, target.agent.harnessId)
+ this.buddySwitches.set(target.agent.harnessId, record ? record.at + SWITCH_RECOVERY_MS : agent.switchRequest ? this.now() + SWITCH_RECOVERY_MS : -Infinity)
+ }
+ const buddySwitch = buddy && this.now() <= (this.buddySwitches.get(target.agent.harnessId) ?? -Infinity)
+ if (row.lead === true || target.agent.switchLanded || buddySwitch) {
+ leads.add(target.agent.harnessId)
+ this.keepAlive(target.agent.harnessId, buddy ? row.buddySleepManaged === true ? 'buddy' : 'buddy-switch' : 'pm')
if (row.lead === true) this.watchLead(target.agent.harnessId, row.owed)
- void this.leadSwitches.serve(target as unknown as SwitchRow).catch(error => this.log(`PM switch: ${error instanceof Error ? error.name : typeof error}`))
+ void this.leadSwitches.serve(target as unknown as SwitchRow).catch(error => this.log(`Engine switch: ${error instanceof Error ? error.name : typeof error}`))
} else if (isCrewRow(row)) {
// A project's crew is kept alive as its PM is (task #3397): reopened in place, then told to continue its task.
leads.add(target.agent.harnessId)
@@ -1415,6 +1424,7 @@ export class SuperTabHost {
}
if (this.stopped) return
// A Lead the roster no longer marks (its project deleted) is never reopened again.
+ for (const harnessId of this.buddySwitches.keys()) if (!rosterHarnesses.has(harnessId)) this.buddySwitches.delete(harnessId)
for (const [harnessId, state] of this.keepAlives) if (!leads.has(harnessId) && !state.running) this.keepAlives.delete(harnessId)
for (const [harnessId, watch] of this.leadWatches) if (!leads.has(harnessId) && !watch.checking && !watch.restarting) this.leadWatches.delete(harnessId)
for (const [key, state] of this.endings) if (!ended.has(key) && !state.running) this.endings.delete(key)
@@ -1518,8 +1528,8 @@ export class SuperTabHost {
} finally { if (this.buddyRestChecks.get(key) === check) this.buddyRestChecks.delete(key) }
}
- private keepAlive(harnessId: string, kind: 'pm' | 'crew' | 'buddy' = 'pm'): void {
- const crew = kind === 'crew'
+ private keepAlive(harnessId: string, kind: 'pm' | 'crew' | 'buddy' | 'buddy-switch' = 'pm'): void {
+ const crew = kind === 'crew', buddy = kind === 'buddy' || kind === 'buddy-switch'
const reopen = this.core.agents.keepLeadAlive
if (!reopen) return
const state = this.keepAlives.get(harnessId) ?? { running: false, failures: 0, retryAt: 0 }
@@ -1532,11 +1542,16 @@ export class SuperTabHost {
if (watch && (watch.restarting || now < watch.settleUntil)) return
// Its owner switched its engine from its pane (leadSwitch.ts), stopping it once the stop went through.
const switched = leadSwitchOf(this.core.dataDir, harnessId)
+ const held: boolean = switchWithin(switched, now)
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)) {
+ if (switched && !held && switchWithin(switched, now, LATE_REPLACEMENT_MS)) {
+ if (buddy && !switched.recovered) {
+ try { leadSwitchRecovered(this.core.dataDir, harnessId, switched.changeId) }
+ catch (error) { this.log(`Buddy recovery record failed: ${error instanceof Error ? error.name : typeof error}`) }
+ }
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 })
@@ -1547,21 +1562,28 @@ export class SuperTabHost {
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 ${kind === 'buddy' ? 'Buddy' : crew ? 'crew member' : 'Product Manager'} ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)
+ if (reason !== state.reason) this.log(`Could not reopen the ${buddy ? 'Buddy' : crew ? 'crew member' : 'Product Manager'} ${harnessId.slice(0, 8)}: ${reason}. Trying again with backoff.`)
state.reason = reason
}
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)
+ if (buddy && switched.recovered) {
+ // Unmanaged Buddies get only rollback authority. A managed Buddy may still wake after a later sleep.
+ if (replacement && !await this.closeReplacement(replacement, switched)) return failed('the new session could not be closed')
+ if (kind === 'buddy-switch') return
+ } else {
+ // 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)) return failed('the new session could not be closed')
+ }
}
const result = await reopen(harnessId)
if (!result.ok) return failed(result.detail ?? result.error)
+ if (buddy && switched) leadSwitchRecovered(this.core.dataDir, harnessId, switched.changeId)
if (crew) this.crew.reopened(harnessId)
state.failures = 0
state.retryAt = this.now() + LEAD_REOPEN_WAIT_MS
@@ -1626,11 +1648,12 @@ export class SuperTabHost {
}
/** 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> {
+ private async closeReplacement(agentId: string, switched: LeadSwitch): Promise<boolean> {
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'}.`)
+ ? `Closed the new session ${agentId.slice(0, 8)} of a protected session's switch the Swarm did not take in.`
+ : `Could not close the new session ${agentId.slice(0, 8)} of a protected session's switch: ${closed?.error ?? 'unsupported'}.`)
+ return closed?.closed === true
}
/** 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 c9f5b5123..a80b6edab 100644
--- a/cli/src/superTabs/inCore.ts
+++ b/cli/src/superTabs/inCore.ts
@@ -23,6 +23,6 @@ export { typesWhileBusy } from './inCore/deliveries.js'
export { mayBeBuddy, retainedHarnesses, retainedLeads, retainedSleepingBuddies } from './retention.js'
export { recordCleanupClose } from './cleanupCloses.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 { buddyCloseProtected, 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/inCore/buddySleep.spec.ts b/cli/src/superTabs/inCore/buddySleep.spec.ts
index aebf16947..69be6e680 100644
--- a/cli/src/superTabs/inCore/buddySleep.spec.ts
+++ b/cli/src/superTabs/inCore/buddySleep.spec.ts
@@ -22,7 +22,7 @@ afterEach(() => {
// Keep the real Swarm authority, retention, close guard and idle recheck together. Faking closeMember hid the native
// refusal in #3824: the host correctly asked to sleep, but the ordinary Buddy close guard always kept it running.
-function fixture(options: { phase?: 'activity' | 'checkpoint' | 'stop'; revoke?: 'wake' | 'corrupt'; activity?: 'working' | 'unknown' } = {}) {
+function fixture(options: { phase?: 'activity' | 'checkpoint' | 'stop'; revoke?: 'wake' | 'corrupt' | 'switch'; activity?: 'working' | 'unknown' } = {}) {
const row = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%88' }], cwd: dir })!
Object.assign(row, { sessionId: 'kept-conversation', startedBy: 'agent' })
const hostRow = (agent: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) => ({ tabId: 'tab', active: true, buddySleepManaged: true,
@@ -32,6 +32,7 @@ function fixture(options: { phase?: 'activity' | 'checkpoint' | 'stop'; revoke?:
const revoke = (phase: string) => {
if (options.phase !== phase) return
if (options.revoke === 'corrupt') writeFileSync(retention.retentionFile(dir), '{')
+ else if (options.revoke === 'switch') roster({ switchRequest: { id: 'switch', engine: 'codex', requestedBy: 'person' } })
else roster({ asleep: undefined })
}
const deps: CloseAgentServiceDeps = { registry,
@@ -82,6 +83,8 @@ it('an unreadable retention revokes sleep after the checkpoint', async () => {
it.each([
['awake', { asleep: undefined }, {}],
['thread', { buddySession: { thread: 'root' } }, {}],
+ ['engine request', { switchRequest: { id: 'switch', engine: 'codex', requestedBy: 'person' } }, {}],
+ ['landed switch', { switchLanded: { id: 'switch', requestedBy: 'person' } }, {}],
['model request', { modelRequest: { id: 'request' } }, {}],
['Team session', { teamAccount: true }, {}],
['unmanaged', {}, { buddySleepManaged: undefined }],
@@ -101,3 +104,9 @@ it('never sleeps a Buddy on a Team daemon or grants a normal window close the sl
expect(await f.swarm.closeMember(f.row.agentId)).toMatchObject({ error: 'BUDDY_PROTECTED' })
expect(registry.byAgent(f.row.agentId)).toBe(f.row)
})
+
+it.each(['activity', 'checkpoint', 'stop'] as const)('an engine switch revokes an in-flight sleep during %s', async phase => {
+ const f = fixture({ phase, revoke: 'switch' })
+ expect(await f.swarm.closeMember(f.row.agentId)).toMatchObject({ error: expect.any(String) })
+ expect(registry.byAgent(f.row.agentId)).toBe(f.row)
+})
diff --git a/cli/src/superTabs/leadSwitch.spec.ts b/cli/src/superTabs/leadSwitch.spec.ts
index 11a76524b..4cd048640 100644
--- a/cli/src/superTabs/leadSwitch.spec.ts
+++ b/cli/src/superTabs/leadSwitch.spec.ts
@@ -3,9 +3,9 @@ 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,
+import { buddyCloseProtected, leadCloseProtected, leadSwitchEnded, leadSwitching, leadSwitchOf, mayBeLead, resetLeadSwitchPassesForTest, SWITCH_ARM_MS,
SWITCH_HOLD_MS, switchWithin } from './leadSwitch.js'
-import { retainContributions } from './retention.js'
+import { retainedLeads, retainContributions } from './retention.js'
const roots: string[] = []
const LEAD = 'lead-harness', WORKER = 'worker-harness'
@@ -160,3 +160,21 @@ it('reads no switch from an unreadable record, and holds none from a clock far a
expect(leadSwitchOf(dir, LEAD)).toBeNull()
expect(switchWithin(null, now)).toBe(false)
})
+
+
+it('grants a Buddy only the one prepared switch close while ordinary closes stay protected', () => {
+ const dir = machine(), now = Date.now()
+ retainContributions(dir, 'machine', [{ tabId: 'tab', agent: { harnessId: WORKER, machineId: 'machine', buddyOf: { personId: 'owner' } } }], now)
+ expect(retainedLeads(dir).has(WORKER)).toBe(false)
+ expect(buddyCloseProtected(dir, WORKER, undefined, now)).toBe(true)
+ expect(buddyCloseProtected(dir, WORKER, CHANGE, now)).toBe(true)
+ prepared(dir, WORKER, CHANGE, now)
+ expect(buddyCloseProtected(dir, WORKER, CHANGE, now)).toBe(false)
+ expect(buddyCloseProtected(dir, WORKER, CHANGE, now)).toBe(true)
+ leadSwitchEnded(dir, WORKER, CHANGE, true, now)
+ expect(leadSwitchOf(dir, WORKER)).toMatchObject({ agentId: WORKER, changeId: CHANGE, targetEngine: 'codex' })
+ expect(buddyCloseProtected(dir, WORKER, undefined, now)).toBe(true)
+ expect(retainedLeads(dir).has(WORKER)).toBe(true)
+ // Buddy Stop Harness remains available.
+ expect(mayBeLead(dir, WORKER)).toBe(false)
+})
diff --git a/cli/src/superTabs/leadSwitch.ts b/cli/src/superTabs/leadSwitch.ts
index e912d6e3b..2e5ce696a 100644
--- a/cli/src/superTabs/leadSwitch.ts
+++ b/cli/src/superTabs/leadSwitch.ts
@@ -23,7 +23,7 @@ import { existsSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSyn
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 { mayBeBuddy, 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). */
@@ -32,6 +32,8 @@ export const SWITCH_ARM_MS = 2 * 60_000
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
+/** Keep failed Buddy switches recoverable, and fence late starts, for this bounded window. */
+export const SWITCH_RECOVERY_MS = 30 * 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}$/
@@ -39,7 +41,7 @@ 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 }
+export interface LeadSwitch { version: 1; agentId: string; changeId: string; targetEngine: string; at: number; recovered?: true }
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`)
@@ -59,7 +61,7 @@ export function leadSwitchOf(dataDir: string, agentId: string): LeadSwitch | nul
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
+ || (row.recovered !== undefined && row.recovered !== true) || !identifier(row.targetEngine) || typeof row.at !== 'number' || !Number.isFinite(row.at)) return null
return row as unknown as LeadSwitch
} catch { return null }
}
@@ -99,6 +101,13 @@ function write(dataDir: string, row: LeadSwitch, now: number): void {
} finally { if (existsSync(temporary)) unlinkSync(temporary) }
}
+/** A successful Buddy rollback is durable: a later Stop Harness must never be mistaken for a failed launch. */
+export function leadSwitchRecovered(dataDir: string, agentId: string, changeId: string): void {
+ const row = leadSwitchOf(dataDir, agentId)
+ if (!row || row.changeId !== changeId || row.recovered) return
+ write(dataDir, { ...row, recovered: true }, Date.now())
+}
+
/** 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)
@@ -111,6 +120,16 @@ export function leadSwitching(dataDir: string, agentId: string, changeId: string
* 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
+ return switchCloseProtected(dataDir, agentId, changeId, now)
+}
+
+/** A Buddy's close gets the same one-use handoff permit; Stop Harness keeps its ordinary behavior. */
+export function buddyCloseProtected(dataDir: string, agentId: string, changeId?: string, now = Date.now()): boolean {
+ if (!mayBeBuddy(dataDir, agentId, now)) return false
+ return switchCloseProtected(dataDir, agentId, changeId, now)
+}
+
+function switchCloseProtected(dataDir: string, agentId: string, changeId: string | undefined, now: number): boolean {
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
diff --git a/cli/src/superTabs/leadSwitchRequest.spec.ts b/cli/src/superTabs/leadSwitchRequest.spec.ts
index 796648b9f..11c1a6698 100644
--- a/cli/src/superTabs/leadSwitchRequest.spec.ts
+++ b/cli/src/superTabs/leadSwitchRequest.spec.ts
@@ -1,18 +1,26 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { parse as parseToml } from 'smol-toml'
import type { Daemon } from '../agentClient/daemon.js'
+import { markBuddyOwner, writeBuddyAccount } from '../lib/buddyGuard.js'
import { fakeCore } from '../testing/fakeCore.js'
+import { processCoreApi } from '../services/processCoreApi.js'
import { FIXTURE, readFixture } from './fixtures/read/index.js'
+// Each trust fixture moves the engine homes; do not reuse a login-shell snapshot captured by another fixture.
+vi.mock('../engines/kit/launchExecutable.js', async original => ({ ...await original<object>(),
+ launchEnvironment: async () => Object.fromEntries(['HOME', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME'].filter(key => process.env[key] !== undefined).map(key => [key, process.env[key]])) }))
import { LeadSwitchRequests, profileSignedIn, switchChangeId, type SwitchRow } from './leadSwitchRequest.js'
+afterEach(() => { vi.unstubAllEnvs() })
+
const request = { id: 'sw1', engine: 'claude', profileId: 'p1' }
const row = (over: Record<string, unknown> = {}, top: Record<string, unknown> = {}): SwitchRow => ({ tabId: 'tab', ledConversationId: 'conv1', roleName: 'Product Manager',
agent: { id: 'a1', harnessId: 'h1', switchRequest: request, ...over }, ...top })
const NOW = 1_800_000_000_000
-const PM = { agentId: 'h1', engine: 'codex', cwd: '/work', permissionMode: 'ask', bypassPermission: false, defaultName: 'PM', startedBy: 'agent',
+const PM = { agentId: 'h1', sessionId: 'native-old', registeredAt: NOW, engine: 'codex', cwd: '/work', permissionMode: 'ask', bypassPermission: false, defaultName: 'PM', startedBy: 'agent',
swarmSkill: { role: 'coordinator', key: 'swarm-lead', mode: 'orchestration', github: true } }
function writeRecord(dataDir: string, changeId: string, at: number) {
@@ -62,7 +70,7 @@ function setup(options: { claim?: boolean; home?: string | null; team?: boolean;
const switches = new LeadSwitchRequests(core, 'm1', { now: () => clock.now, home: () => home, signedIn: async () => options.signedIn !== false,
open: async () => daemon, profiles: profiles as never, team: () => options.team === true,
readHandoff: () => 'Earlier project state.' })
- return { switches, calls, posted, daemon, profiles, operationIds, home, dataDir, clock, reopen: () => { live = true } }
+ return { core, switches, calls, posted, daemon, profiles, operationIds, home, dataDir, clock, reopen: () => { live = true } }
}
describe('a PM host carrying out a switch the Swarm asked for', () => {
@@ -73,7 +81,7 @@ describe('a PM host carrying out a switch the Swarm asked for', () => {
expect(t.calls.map(c => c[0])).toEqual(['agent_handoff_prepare', 'agent_close', 'agent_create', 'agent_handoff_complete'])
const changeId = String(t.calls[0][1].changeId)
expect(changeId).toMatch(/^[0-9a-f]{32}$/)
- expect(t.calls[1][1]).toEqual({ agentId: 'h1', mode: 'now', changeId })
+ expect(t.calls[1][1]).toEqual({ agentId: 'h1', sessionId: 'native-old', createdAt: '2027-01-15T08:00:00.000Z', mode: 'now', changeId })
expect(t.calls[2][1]).toMatchObject({ engine: 'claude', cwd: '/work', creationId: changeId, claudeHome: '/home/p1', permissionMode: 'ask', name: 'PM' })
expect(String(t.calls[2][1].prompt)).toContain(`.harness/handoff/h1-${changeId}.md`)
expect(t.calls[3][1]).toEqual({ agentId: 'h1', replacementId: 'h2', changeId, targetEngine: 'claude' })
@@ -316,7 +324,7 @@ describe('a PM host carrying out a switch the Swarm asked for', () => {
await t.switches.serve(row({ switchRequest: undefined, switchLanded: { id: 'sw1', candidateAgentId: 'm2-h2' } }))
expect(t.calls.map(c => c[0])).toEqual(['agent_handoff_prepare', 'agent_close'])
- expect(t.calls.at(-1)![1]).toEqual({ agentId: 'h1', mode: 'now', changeId })
+ expect(t.calls.at(-1)![1]).toEqual({ agentId: 'h1', sessionId: 'native-old', createdAt: '2027-01-15T08:00:00.000Z', mode: 'now', changeId })
expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: true })
})
@@ -385,3 +393,143 @@ describe('whether a profile folder holds a sign-in', () => {
expect(vi.mocked(switches['core'].account.backend).mock.calls.at(-1)![2]).toMatchObject({ command: { type: 'agent.switchResult', ok: false, error: 'that account is signed out' } })
})
})
+
+
+const buddyRow = (over: Record<string, unknown> = {}, top: Record<string, unknown> = {}): SwitchRow => row({
+ buddyOf: { personId: 'owner', generation: 'g' }, buddyScope: 'swarm',
+ switchRequest: { id: 'sw1', engine: 'codex', profileId: 'default', requestedBy: 'owner' }, ...over,
+}, { ledConversationId: undefined, buddyConversationId: 'private-chat', ...top })
+const buddySetup = (options: Parameters<typeof setup>[0] = {}) => {
+ const t = setup({ home: 'default', ...options, old: { engine: 'claude', swarmSkill: { role: 'buddy', key: 'swarm-buddy', mode: 'orchestration' }, ...options.old } })
+ vi.stubEnv('CLAUDE_CONFIG_DIR', t.home)
+ vi.stubEnv('CODEX_HOME', t.home)
+ // A signed-in daemon has already installed Codex's hooks in this fixture's own config.
+ writeFileSync(join(t.home, 'config.toml'), '')
+ markBuddyOwner('work', 'owner', t.dataDir)
+ writeBuddyAccount('owner', t.dataDir)
+ vi.mocked(t.core.account.identity).mockResolvedValue({ accountId: 'owner', email: '[email protected]' })
+ return t
+}
+
+describe('a Buddy engine handoff', () => {
+ it('waits for a sleeping Buddy to reopen before claiming its switch', async () => {
+ const t = buddySetup({ live: false })
+ await t.switches.serve(buddyRow())
+ expect(t.posted).toEqual([])
+ expect(t.calls).toEqual([])
+ t.reopen()
+ await t.switches.serve(buddyRow())
+ expect(t.posted.map(command => command.type)).toEqual(['agent.switchClaim'])
+ expect(t.calls.map(call => call[0])).toEqual(['agent_handoff_prepare', 'agent_close', 'agent_create', 'agent_handoff_complete'])
+ })
+
+ it.each(['owner', 'other', null])('checks the core account through the service process API (%s)', async accountId => {
+ const t = buddySetup()
+ const core = processCoreApi(t.dataDir, 'superTabs', {
+ live: () => [t.core.agents.byAgent('h1')!],
+ ask: async (query, payload) => {
+ if (query === 'account') return accountId ? { accountId, email: `${accountId}@example.com` } : {}
+ if (query === 'backend') return t.core.account.backend(String(payload.method), String(payload.path), payload.body)
+ throw new Error(`Unexpected query ${query}`)
+ },
+ })
+ const switches = new LeadSwitchRequests(core, 'm1', {
+ now: () => NOW, open: async () => t.daemon, profiles: (() => 'default') as never, signedIn: async () => true,
+ })
+ await switches.serve(buddyRow())
+ if (accountId === 'owner') {
+ expect(t.calls.map(c => c[0])).toEqual(['agent_handoff_prepare', 'agent_close', 'agent_create', 'agent_handoff_complete'])
+ expect(t.calls[2][1]).toMatchObject({ engine: 'codex', cwd: '/work', swarmRole: 'buddy' })
+ } else {
+ expect(t.calls).toEqual([])
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false })
+ }
+ })
+
+ it.each(['codex', 'claude'])('answers %s folder trust for its existing Swarm Buddy home before stopping the source', async engine => {
+ const t = buddySetup({ old: { engine: engine === 'codex' ? 'claude' : 'codex' } })
+ const config = join(t.home, engine === 'codex' ? 'config.toml' : '.claude.json')
+ const request = vi.mocked(t.daemon.request).getMockImplementation()!
+ vi.mocked(t.daemon.request).mockImplementation(async (type, payload, timeout) => {
+ if (type === 'agent_close') {
+ expect(existsSync(config), 'the target engine must not ask a hidden folder question').toBe(true)
+ const saved = engine === 'codex' ? parseToml(readFileSync(config, 'utf8')) : JSON.parse(readFileSync(config, 'utf8'))
+ expect(saved.projects['/work']).toMatchObject(engine === 'codex' ? { trust_level: 'trusted' } : { hasTrustDialogAccepted: true })
+ }
+ return request(type, payload, timeout)
+ })
+ await t.switches.serve(buddyRow({ switchRequest: { id: 'sw1', engine, profileId: 'default', requestedBy: 'owner' } }))
+ expect(existsSync(config), 'the target engine must have its folder-trust answer').toBe(true)
+ expect(t.calls.map(c => c[0])).toEqual(['agent_handoff_prepare', 'agent_close', 'agent_create', 'agent_handoff_complete'])
+ })
+
+ it('leaves a project Buddy folder to its own trust question', async () => {
+ const t = buddySetup()
+ const config = join(t.home, 'config.toml')
+ await t.switches.serve(buddyRow({}, { agent: { ...buddyRow().agent, buddyScope: undefined } }))
+ expect(readFileSync(config, 'utf8')).toBe('')
+ })
+
+ it('switches Claude Code to Codex in its folder as a Buddy in the same private chat, without PM authority', async () => {
+ const t = buddySetup()
+ await t.switches.serve(buddyRow())
+ expect(t.calls.map(c => c[0])).toEqual(['agent_handoff_prepare', 'agent_close', 'agent_create', 'agent_handoff_complete'])
+ const create = t.calls[2][1]
+ expect(create).toMatchObject({ engine: 'codex', cwd: '/work', swarmRole: 'buddy', swarmSkillMode: 'orchestration', creationId: t.calls[1][1].changeId })
+ expect(create).not.toHaveProperty('swarmGitHub')
+ expect(String(create.prompt)).toContain('Your chat with your owner is conversation private-chat')
+ expect(String(create.prompt)).toContain('Context handoff:')
+ expect(String(create.prompt)).not.toContain('Product Manager of the project')
+ })
+
+ it.each(['different-owner', 'unknown-owner', 'missing-folder-owner', 'signed-out', 'team', 'no-chat', 'model-pending'])(
+ 'refuses %s before preparing or closing the Buddy', async reason => {
+ const t = buddySetup({ signedIn: reason !== 'signed-out', team: reason === 'team' })
+ if (reason === 'different-owner') writeBuddyAccount('other', t.dataDir)
+ if (reason === 'unknown-owner') writeBuddyAccount(null, t.dataDir)
+ if (reason === 'missing-folder-owner') markBuddyOwner('work', 'other', t.dataDir)
+ const r = buddyRow(reason === 'model-pending' ? { modelRequest: { id: 'model1' } } : {}, reason === 'no-chat' ? { buddyConversationId: undefined } : {})
+ await t.switches.serve(r)
+ expect(t.calls).toEqual([])
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false })
+ })
+
+ it('rechecks the owner after an awaited handoff before trusting the folder or closing the original Buddy', async () => {
+ const t = buddySetup()
+ const config = join(t.home, 'config.toml')
+ const request = vi.mocked(t.daemon.request).getMockImplementation()!
+ vi.mocked(t.daemon.request).mockImplementation(async (type, payload, timeout) => {
+ const reply = await request(type, payload, timeout)
+ if (type === 'agent_handoff_prepare') writeBuddyAccount('other', t.dataDir)
+ return reply
+ })
+ await t.switches.serve(buddyRow())
+ expect(t.calls.map(c => c[0])).toEqual(['agent_handoff_prepare'])
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false })
+ expect(readFileSync(config, 'utf8')).toBe('')
+ })
+
+ it('does not create twice across duplicate polls or a restarted host, and accepts a late successful rebind', async () => {
+ const t = buddySetup({ createTimesOut: true })
+ await t.switches.serve(buddyRow())
+ await t.switches.serve(buddyRow())
+ const restart = new LeadSwitchRequests(fakeCore({ dataDir: t.dataDir }), 'm1', { now: () => t.clock.now, open: async () => { throw new Error('must not launch twice') } })
+ await restart.serve(buddyRow())
+ expect(t.calls.filter(c => c[0] === 'agent_create')).toHaveLength(1)
+ t.clock.now += 60_000
+ await t.switches.serve(buddyRow({ harnessId: 'h2', switchRequest: undefined }))
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: true })
+ })
+
+ it('reports a failed launch only after the original Buddy is back', async () => {
+ const t = buddySetup({ refuse: 'SPAWN_LIMIT' })
+ await t.switches.serve(buddyRow())
+ expect(t.posted.map(c => c.type)).toEqual(['agent.switchClaim'])
+ t.clock.now += 3 * 60_000 + 1
+ await t.switches.serve(buddyRow())
+ expect(t.posted.map(c => c.type)).toEqual(['agent.switchClaim'])
+ t.reopen()
+ await t.switches.serve(buddyRow())
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false, error: 'the new session could not start' })
+ })
+})
diff --git a/cli/src/superTabs/leadSwitchRequest.ts b/cli/src/superTabs/leadSwitchRequest.ts
index 61aeb7bff..5154b4e71 100644
--- a/cli/src/superTabs/leadSwitchRequest.ts
+++ b/cli/src/superTabs/leadSwitchRequest.ts
@@ -1,5 +1,5 @@
/**
- * A PM's host carrying out the switch the Swarm asked for (docs/superpowers/specs/2026-11-02-pm-switch-engine-account-design.md,
+ * A PM or Buddy's host carrying out the switch the Swarm asked for (docs/superpowers/specs/2026-11-02-pm-switch-engine-account-design.md,
* section 7). It does what Desktop's Change agent does for its owner, over this machine's own daemon socket (which answers as
* the machine owner), so #2493's guards (leadSwitch.ts) apply unchanged: prepare the handoff, close with the change id, create
* the new session with that id as its creation id, complete the handoff. Success is the PM rebinding to the new session.
@@ -12,11 +12,13 @@ import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'
import type { CoreApi } from '../core/api.js'
import type { AgentEngine } from '../engines/types.js'
import { asRecord, jwtClaims, parseJson, readClaudeStored, readText, stringField, type CredentialReadDeps } from '../lib/agentCredentials.js'
+import { buddyAccountFile, buddyOwnerOf, signedInAccount } from '../lib/buddyGuard.js'
import { handoffBaseName } from '../lib/agentHandoff.js'
import { profileHome } from '../lib/claudeProfiles.js'
import { defaultCodexHome } from '../lib/codexProfiles.js'
import { permissionModeApproves, permissionModeFlags } from '../lib/engineLaunch.js'
import { parseSwarmSkill, wireRole } from '../lib/swarmSkills.js'
+import { trustBuddyHome } from './buddyHome.js'
import { leadSwitchOf, leadSwitching, SWITCH_ADOPT_MS, switchWithin } from './leadSwitch.js'
import { githubPromptLine, LAUNCH_MODEL_REFUSALS, leadPrompt } from './start.js'
import { pmEngineHome } from './teamDaemon.js'
@@ -24,7 +26,7 @@ import { backend, identifier, object } from './wire.js'
const GONE = 'that account is no longer on this machine'
const NO_HANDOFF = 'the handoff could not be prepared'
-const NO_STOP = 'the PM could not be stopped'
+const NO_STOP = 'the session could not be stopped'
const NO_START = 'the new session could not start'
const LATE = 'the new session did not start in time'
const SIGNED_OUT = 'that account is signed out'
@@ -34,13 +36,15 @@ const RETRY_MS = 10_000
const CLAUDE_KEY_VARIABLES = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN']
const LABELS: Record<string, string> = { claude: 'Claude', codex: 'Codex' }
-/** The row of a PM of this machine, as the host reads it (cli read/hostRows.ts). */
+/** The row of a PM or Buddy on this machine, as the host reads it (cli read/hostRows.ts). */
export interface SwitchRow {
tabId: string
/** The conversation the PM leads and the name of its role, as the host row has them (backend read/hostRows.ts). */
ledConversationId?: unknown
roleName?: unknown
- agent: { id: string; harnessId: string; switchRequest?: { id?: unknown; engine?: unknown; profileId?: unknown; model?: unknown; effort?: unknown; targetMachineId?: unknown };
+ /** A Buddy's private chat; never substitute the project's PM conversation. */
+ buddyConversationId?: unknown
+ agent: { id: string; harnessId: string; buddyOf?: unknown; buddyScope?: unknown; buddySession?: unknown; modelRequest?: unknown; switchRequest?: { id?: unknown; engine?: unknown; profileId?: unknown; model?: unknown; effort?: unknown; targetMachineId?: unknown; requestedBy?: unknown };
switchLanded?: { id?: unknown; candidateAgentId?: unknown } }
}
export interface LeadSwitchDeps {
@@ -136,6 +140,8 @@ export class LeadSwitchRequests {
return
}
if (leadSwitching(this.core.dataDir, agent.harnessId, changeId, now)) return
+ // A sleeping Buddy is reopened by the host first; claiming now would fail its handoff before that resume finishes.
+ if (agent.buddyOf && !this.core.agents.byAgent(agent.harnessId)) return
// Held before the claim is awaited, so a poll that comes while it is in flight starts nothing.
const created: Run = { switchId, harnessId: agent.harnessId, changeId, busy: true, closed: false,
crossMachine: identifier(request.targetMachineId) && request.targetMachineId !== this.machineId }
@@ -144,7 +150,7 @@ export class LeadSwitchRequests {
await this.post(tabId, agent.id, operationId('claim', switchId), { type: 'agent.switchClaim', agentId: agent.id, switchId })
} catch { this.runs.delete(agent.id); this.claimRetryAt.set(switchId, now + RETRY_MS); return }
try { created.outcome = await this.carryOut(row, created, request) } catch (error) {
- this.deps.log(`PM switch failed: ${error instanceof Error ? error.name : typeof error}`)
+ this.deps.log(`Engine switch failed: ${error instanceof Error ? error.name : typeof error}`)
if (created.closed) created.failed = NO_START
else created.outcome = { ok: false, error: NO_HANDOFF }
} finally { created.busy = false }
@@ -161,8 +167,23 @@ export class LeadSwitchRequests {
const old = this.core.agents.byAgent(run.harnessId)
// The PM comes back as a Swarm PM, from what it was started as: with no saved role or no conversation to rebuild its prompt
// from, it would come back role-less, with no Swarm skill and the machine owner's own GitHub login.
- const skill = parseSwarmSkill(old?.swarmSkill), conversation = row.ledConversationId
+ const skill = parseSwarmSkill(old?.swarmSkill), buddy = !!row.agent.buddyOf
+ const conversation = buddy ? row.buddyConversationId : row.ledConversationId
if (!old?.cwd || !skill || !identifier(conversation)) return { ok: false, error: NO_HANDOFF }
+ const buddyOwnerCurrent = async () => {
+ const owner = object(row.agent.buddyOf).personId
+ // A separate service has no synchronous sign-in state. Ask the core for its account, then check the sign-out mark.
+ const identity = await this.core.account.identity().catch(() => null)
+ return identifier(owner) && identity?.accountId === owner && request.requestedBy === owner
+ && buddyOwnerOf(old.cwd!, this.core.dataDir) === owner && signedInAccount(buddyAccountFile(this.core.dataDir)) === owner
+ }
+ if (buddy) {
+ // Check before the handoff stops anything: the launch guard also checks the recorded owner when the new engine starts.
+ if (team || skill.role !== 'buddy' || row.agent.buddySession || row.agent.modelRequest || !['claude', 'codex'].includes(engine)
+ || home !== 'default' || run.crossMachine || !await buddyOwnerCurrent()) {
+ return { ok: false, error: 'the Buddy owner or session could not be verified on this computer' }
+ }
+ }
// The default account too; a Team daemon's is signed in through its owner's relay (team/relay.ts), which this cannot read.
if (!team && !await this.deps.signedIn(engine, home)) return { ok: false, error: SIGNED_OUT }
const daemon = await this.deps.open({ dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId })
@@ -184,19 +205,28 @@ export class LeadSwitchRequests {
switchId: run.switchId, handoffChangeId: changeId, note })
return undefined
}
- const closed = await daemon.request('agent_close', { agentId, mode: 'now', changeId }, 60_000)
+ if (buddy && !await buddyOwnerCurrent()) return { ok: false, error: 'the Buddy owner or session could not be verified on this computer' }
+ if (buddy && row.agent.buddyScope === 'swarm') {
+ // The same Harness-owned home was trusted for the source engine; the target otherwise waits in a hidden pane.
+ await trustBuddyHome(old.cwd, engine)
+ if (!await buddyOwnerCurrent()) return { ok: false, error: 'the Buddy owner or session could not be verified on this computer' }
+ }
+ const closed = await daemon.request('agent_close', { agentId, sessionId: old.sessionId ?? '', createdAt: new Date(old.registeredAt).toISOString(), mode: 'now', changeId }, 60_000)
if (closed.error || closed.closed !== true) return { ok: false, error: NO_STOP }
run.closed = true
// What superTabs/start.ts sends when it first starts a Lead: its start prompt first, then the handoff.
const roleName = typeof row.roleName === 'string' ? row.roleName.replace(/\s+/g, ' ').trim().slice(0, 80) : ''
- const prompt = `${leadPrompt(row.tabId, conversation, roleName)}${skill.github ? ` ${githubPromptLine()}` : ''}${handoff ? ` ${handoff}` : ''}`
+ const startPrompt = buddy
+ ? `You are a person's ${row.agent.buddyScope === 'swarm' ? 'one Buddy for every project they read' : 'Buddy'} in a shared Super Tab. Your chat with your owner is conversation ${conversation}: read it with harness super-tab --tab ${row.tabId} messages ${conversation}, and reply there with harness super-tab --tab ${row.tabId} post ${conversation} 'your message' UNIQUE_OPERATION_ID. Continue helping your owner in that chat.`
+ : leadPrompt(row.tabId, conversation, roleName)
+ const prompt = `${startPrompt}${!buddy && skill.github ? ` ${githubPromptLine()}` : ''}${handoff ? ` ${handoff}` : ''}`
// Desktop's rule (_changeAgent): a mode the new engine lacks becomes ask, and bypass follows the mode.
const mode = old.permissionMode && permissionModeFlags(engine as AgentEngine, old.permissionMode) ? old.permissionMode : old.permissionMode ? 'ask' : undefined
// A Team user's Codex PM keeps an engine home of its own, as at its first start (start.ts, security re-check 2 of #2089).
const pmHome = pmEngineHome(engine, changeId, team, this.deps.home())
if (pmHome) mkdirSync(pmHome, { recursive: true, mode: 0o700 })
const payload: Record<string, unknown> = { engine, cwd: old.cwd, creationId: changeId, startedBy: 'agent',
- swarmRole: wireRole(skill), ...(skill.mode ? { swarmSkillMode: skill.mode } : {}), ...(skill.github ? { swarmGitHub: true } : {}),
+ swarmRole: wireRole(skill), ...(skill.mode ? { swarmSkillMode: skill.mode } : {}), ...(!buddy && skill.github ? { swarmGitHub: true } : {}),
...(mode ? { permissionMode: mode, bypassPermission: permissionModeApproves(mode) } : old.bypassPermission !== undefined ? { bypassPermission: old.bypassPermission } : {}),
...(old.defaultName ? { name: old.defaultName } : {}),
...(pmHome ? { codexHome: pmHome } : home !== 'default' ? { [engine === 'claude' ? 'claudeHome' : 'codexHome']: home } : {}),
@@ -231,7 +261,7 @@ export class LeadSwitchRequests {
try {
const daemon = await this.deps.open({ dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId })
try {
- const closed = await daemon.request('agent_close', { agentId: run.harnessId, mode: 'now', changeId: run.changeId }, 60_000)
+ const closed = await daemon.request('agent_close', { agentId: run.harnessId, sessionId: old.sessionId ?? '', createdAt: new Date(old.registeredAt).toISOString(), mode: 'now', changeId: run.changeId }, 60_000)
if (closed.error || closed.closed !== true) { run.retryAt = now + RETRY_MS; return }
} finally { daemon.close() }
} catch { run.retryAt = now + RETRY_MS; return }
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 50822418d..c8e0ffa11 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -355,7 +355,7 @@ describe('contributed machine executor', () => {
Object.assign(f.pool, { capabilitiesWanted: true })
await f.machine.tick()
const posted = (g: typeof f) => g.backend.mock.calls.filter(c => c[1] === 'POST').map(c => c[3] as Record<string, unknown>)
- expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'leadSwitch', 'buddyModel', 'turnInbox'] })
+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'leadSwitch', 'buddyModel', 'buddyEngine', 'turnInbox'] })
// A backend from before them does not ask, and would refuse the field.
const older = fixture()
await older.machine.tick()
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index edb7ef5d2..65dfe6a0b 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -199,6 +199,8 @@ CAPABILITIES.push('leadSwitch')
/** What this host does for a Buddy's model switch (task #2354, superTabs/buddyModel.ts): the backend refuses a switch to a host
* that does not say so. */
CAPABILITIES.push('buddyModel')
+// Buddy engine switches use the same owner-checked handoff and recovery as a PM's.
+CAPABILITIES.push('buddyEngine')
/** This host sends its PM's turn with the PM's delivery list read (host.ts, task #3545): only then does the backend keep people's
* messages and crew needs to that PM for its inbox, which goes when its turn ends. */
CAPABILITIES.push('turnInbox')
diff --git a/cli/src/superTabs/replacements.spec.ts b/cli/src/superTabs/replacements.spec.ts
index 59dbb42c4..f931ac472 100644
--- a/cli/src/superTabs/replacements.spec.ts
+++ b/cli/src/superTabs/replacements.spec.ts
@@ -144,3 +144,15 @@ it('a new backend gets profileId, and any other failure is thrown, not remembere
await expect(sender.post(observation)).rejects.toThrow('bad')
expect(bad).toHaveBeenCalledTimes(4)
})
+
+it('rebinds a Swarm Buddy under its stable identity without inventing a project', async () => {
+ const f = fixture()
+ await recordReplacement(f.core, f.payload)
+ const row = { tabId: 'tab', buddyConversationId: 'private-chat', agent: { id: 'buddy', harnessId: 'old', machineId: 'machine',
+ buddyScope: 'swarm', buddyOf: { personId: 'owner', generation: 'g' } } }
+ const observations = await replacementObservations(f.core, 'machine', [row])
+ expect(observations).toHaveLength(1)
+ expect(observations[0].body).toMatchObject({ asAgentId: 'buddy', command: {
+ type: 'agent.rebind', agentId: 'buddy', machineId: 'machine', previousHarnessId: 'old', harnessId: 'new' } })
+ expect(observations[0].body.command).not.toHaveProperty('projectId')
+})
diff --git a/cli/src/superTabs/replacements.ts b/cli/src/superTabs/replacements.ts
index 15b6fa249..458783e8b 100644
--- a/cli/src/superTabs/replacements.ts
+++ b/cli/src/superTabs/replacements.ts
@@ -138,7 +138,8 @@ export async function replacementObservations(core: CoreApi, machineId: string,
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, profileId: accountId(machineId, target), machineId, projectId: agent.projectId ?? 'lead',
+ const command = { type: 'agent.rebind', agentId: agent.id, profileId: accountId(machineId, target), machineId,
+ ...(agent.buddyScope === 'swarm' && agent.buddyOf ? {} : { 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 } })
diff --git a/cli/src/superTabs/retention.ts b/cli/src/superTabs/retention.ts
index 54f982165..06abd6743 100644
--- a/cli/src/superTabs/retention.ts
+++ b/cli/src/superTabs/retention.ts
@@ -8,6 +8,7 @@
* discussion and running assignments continue. */
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, utimesSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
+import { leadSwitchOf, SWITCH_RECOVERY_MS, switchWithin } from './leadSwitch.js'
import { isCrewRow } from './crew.js'
import { identifier, object } from './wire.js'
import { isTeamDaemon } from './teamDaemon.js'
@@ -54,10 +55,17 @@ export function retainedHarnesses(dataDir: string, now = Date.now()): Set<string
return new Set(read(file).harnesses)
}
-/** The sessions here the host may reopen, the Leads, crew and managed main Buddies: only those a valid roster named. The core reads it as its
- * Leads (core/main.ts, inCore/agents.ts keepLeadAlive), so a crew member reopens exactly as a Lead does. */
+/** Sessions a valid roster lets the core reopen: Leads, crew, managed main Buddies and a Buddy whose engine switch needs
+ * rollback. A recovered unmanaged Buddy is excluded so its person's later Stop Harness stays effective. */
export function retainedLeads(dataDir: string): Set<string> {
- try { const kept = read(retentionFile(dataDir)); return new Set([...kept.leads ?? [], ...kept.crew ?? [], ...kept.wakeableBuddies ?? []]) } catch { return new Set() }
+ try {
+ const kept = read(retentionFile(dataDir))
+ const switching = (kept.buddies ?? []).filter(id => {
+ const switched = leadSwitchOf(dataDir, id)
+ return !switched?.recovered && switchWithin(switched, Date.now(), SWITCH_RECOVERY_MS)
+ })
+ return new Set([...kept.leads ?? [], ...kept.crew ?? [], ...kept.wakeableBuddies ?? [], ...switching])
+ } catch { return new Set() }
}
/** Only the server's current sleep instruction grants an idle close, never a window's Close or a Team purge. A new
@@ -120,7 +128,7 @@ export function retainContributions(dataDir: string, machineId: string, rows: un
buddies.add(agent.harnessId)
if (row.buddySleepManaged === true && !agent.buddySession && row.stopRequested !== true) {
wakeableBuddies.add(agent.harnessId)
- if (agent.asleep && !agent.modelRequest && !agent.teamAccount) sleepingBuddies.add(agent.harnessId)
+ if (agent.asleep && !agent.modelRequest && !agent.switchRequest && !agent.switchLanded && !agent.teamAccount) sleepingBuddies.add(agent.harnessId)
}
}
if (row.lead === true) leads.add(agent.harnessId)
diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dart
index 4644a3606..9ef8d1549 100644
--- a/desktop/lib/super_tabs/buddies.dart
+++ b/desktop/lib/super_tabs/buddies.dart
@@ -11,6 +11,7 @@ import 'private_project_lock.dart';
import 'controller.dart';
import 'buddy_machines.dart';
import 'buddy_model.dart';
+import 'buddy_engine.dart';
import 'dialog_scope.dart';
import 'identity.dart';
import 'model.dart';
@@ -622,7 +623,11 @@ class SuperTabBuddyBar extends StatelessWidget {
/// a copy ([SuperTabController.newestFirst]), so the scan stops at this
/// Buddy's newest system line.
bool _mustStartAgain(SuperTabController c, SuperTabAgent agent) {
- if (!chat.isSwarmBuddyChat || agent.modelRequest != null) return false;
+ if (!chat.isSwarmBuddyChat ||
+ agent.modelRequest != null ||
+ agent.switchRequest != null) {
+ return false;
+ }
final conversation = c.snapshot?.conversation(chat.id);
if (conversation == null ||
c.hasNewer(chat.id) ||
@@ -687,7 +692,13 @@ class SuperTabBuddyBar extends StatelessWidget {
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
final c = controller;
- final agent = c.buddy(chat.projectId);
+ final agent = chat.isSwarmBuddyChat && c.snapshot!.buddyCap != null
+ ? chat.agentIds
+ .map(c.snapshot!.agent)
+ .whereType<SuperTabAgent>()
+ .where((a) => a.isMainBuddy && a.buddyOf == c.accountId)
+ .firstOrNull
+ : c.buddy(chat.projectId);
if (agent == null) return _starting(c);
final name = c.snapshot!.agentName(agent.id, fallback: agent.name);
final machine = buddyMachineName(c, agent.machineId, app: app);
@@ -698,7 +709,10 @@ class SuperTabBuddyBar extends StatelessWidget {
? 'only you can read this chat'
: '${buddyPersonName(c, agent.machineOwnerId)} can see its terminal';
final where = [
- '${buddyEngineName(agent.engine)} on $machine',
+ if (chat.isSwarmBuddyChat && buddyEngineCapable(c.snapshot!, agent))
+ machine
+ else
+ '${buddyEngineName(agent.engine)} on $machine',
if (project != null) '#${project.name}',
// The one Buddy for the whole Swarm (spec 2026-10-31-one-buddy-per-swarm).
if (chat.isSwarmBuddyChat) 'reads all your projects',
@@ -746,6 +760,31 @@ class SuperTabBuddyBar extends StatelessWidget {
)
else
Text(where, style: DesktopChrome.metadata()),
+ if (chat.isSwarmBuddyChat &&
+ agent.gridModel == null &&
+ agent.downSince == null &&
+ agent.switchRequest == null &&
+ agent.modelRequest == null &&
+ agent.limitedUntil?.isAfter(DateTime.now()) == true &&
+ buddyEngineCapable(c.snapshot!, agent))
+ Row(
+ key: const ValueKey('super-buddy-engine-limit'),
+ children: [
+ Expanded(
+ child: Text(
+ 'Limit reached.',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ BuddyEnginePicker(
+ controller: c,
+ agent: agent,
+ limitAction: true,
+ ),
+ ],
+ ),
if (offer)
Row(
key: const ValueKey('super-buddy-start-again'),
diff --git a/desktop/lib/super_tabs/buddy_engine.dart b/desktop/lib/super_tabs/buddy_engine.dart
new file mode 100644
index 000000000..42e1bdec1
--- /dev/null
+++ b/desktop/lib/super_tabs/buddy_engine.dart
@@ -0,0 +1,183 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_menu.dart';
+import '../widgets/desktop_chrome.dart';
+import '../widgets/finger_target.dart';
+import 'controller.dart';
+import 'model.dart';
+
+String buddyEngineLabel(String engine) => switch (engine) {
+ 'claude' => 'Claude Code',
+ 'codex' => 'Codex',
+ _ => engine,
+};
+
+/// Match backend buddyEngine.ts: the owning computer must implement the
+/// handoff. A Team subscription is never the person's Buddy account.
+bool buddyEngineCapable(SuperTabSnapshot snapshot, SuperTabAgent agent) {
+ final pool = snapshot.pool(agent.machineId);
+ final observation = pool?['observation'];
+ return pool != null &&
+ pool['removal'] == null &&
+ pool['hostMachineId'] == null &&
+ pool['contributorId'] == agent.buddyOf &&
+ agent.machineOwnerId == agent.buddyOf &&
+ observation is Map &&
+ observation['sessionKind'] != 'team' &&
+ observation['capabilities'] is List &&
+ (observation['capabilities'] as List).contains('buddyEngine');
+}
+
+/// Sign-in is useful only in the machine's current reading. No fallback to
+/// installed engines or the contributor's other machines and accounts.
+List<String> buddyEngineOffers(
+ SuperTabSnapshot snapshot,
+ SuperTabAgent agent, {
+ required DateTime now,
+}) {
+ if (!buddyEngineCapable(snapshot, agent)) return const [];
+ final observation = superTabMap(
+ snapshot.pool(agent.machineId)?['observation'],
+ );
+ final at = observation['receivedAt'];
+ if (at is! num || now.millisecondsSinceEpoch - at > 45000) return const [];
+ final readiness = superTabMap(observation['readiness']);
+ final rows = readiness['engines'];
+ if (rows is! List) return const [];
+ return [
+ for (final engine in ['claude', 'codex'])
+ if (rows.any(
+ (r) =>
+ r is Map &&
+ r['engine'] == engine &&
+ r['installed'] == true &&
+ r['signedIn'] == true,
+ ))
+ engine,
+ ];
+}
+
+/// The compact header control and the limit notice share the same menu and
+/// request. Only observations change its offers; it never probes a login.
+class BuddyEnginePicker extends StatefulWidget {
+ const BuddyEnginePicker({
+ super.key,
+ required this.controller,
+ required this.agent,
+ this.limitAction = false,
+ });
+
+ final SuperTabController controller;
+ final SuperTabAgent agent;
+ final bool limitAction;
+
+ @override
+ State<BuddyEnginePicker> createState() => _BuddyEnginePickerState();
+}
+
+class _BuddyEnginePickerState extends State<BuddyEnginePicker> {
+ final _menu = MenuController();
+
+ @override
+ Widget build(BuildContext context) {
+ final c = widget.controller;
+ final agent = widget.agent;
+ final snapshot = c.snapshot!;
+ final severalBuddies = snapshot.buddyCap != null;
+ final chat = severalBuddies
+ ? snapshot.conversations
+ .where(
+ (chat) =>
+ chat.isSwarmBuddyChat &&
+ chat.buddyOwnerId == c.accountId &&
+ chat.agentIds.contains(agent.id),
+ )
+ .firstOrNull
+ : null;
+ final request = agent.switchRequest;
+ if (request != null && !widget.limitAction) {
+ return Text(
+ 'Switching to ${buddyEngineLabel(request['engine'] as String? ?? '')}…',
+ style: DesktopChrome.metadata(),
+ );
+ }
+ final phone = workspaceIsCompact(context);
+ final busy =
+ !c.canWrite ||
+ c.saving ||
+ c.hasPendingAction ||
+ request != null ||
+ agent.modelRequest != null ||
+ (severalBuddies && chat == null) ||
+ agent.downSince != null;
+ final offers = buddyEngineOffers(c.snapshot!, agent, now: DateTime.now());
+ return AppDropdown(
+ controller: _menu,
+ children: [
+ for (final engine in offers)
+ fingerTarget(
+ enabled: phone,
+ AppMenuItem(
+ label: buddyEngineLabel(engine),
+ icon: engine == agent.engine && agent.gridModel == null
+ ? AppIcons.check
+ : null,
+ onPressed: busy
+ ? null
+ : () {
+ _menu.close();
+ if (engine == agent.engine && agent.gridModel == null) {
+ return;
+ }
+ unawaited(
+ c.switchBuddyEngine(engine, conversationId: chat?.id),
+ );
+ },
+ ),
+ ),
+ if (offers.isEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.groupGap,
+ vertical: grid.AppDesktop.menuInset,
+ ),
+ child: Text(
+ 'No signed-in engine in a fresh machine reading.',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ ],
+ builder: (context, menu, _) => fingerTarget(
+ enabled: phone,
+ InkWell(
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ onTap: busy ? null : () => menu.isOpen ? menu.close() : menu.open(),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Flexible(
+ child: Text(
+ widget.limitAction
+ ? 'Switch engine'
+ : buddyEngineLabel(agent.engine),
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.foreground,
+ ),
+ ),
+ ),
+ Icon(
+ AppIcons.chevronDown,
+ size: AppIcons.inlineSize,
+ color: DesktopChrome.muted,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/buddy_model.dart b/desktop/lib/super_tabs/buddy_model.dart
index 52a5304d3..377c90afd 100644
--- a/desktop/lib/super_tabs/buddy_model.dart
+++ b/desktop/lib/super_tabs/buddy_model.dart
@@ -7,6 +7,7 @@ import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_menu.dart';
import '../widgets/desktop_chrome.dart';
import '../widgets/finger_target.dart';
+import 'buddy_engine.dart';
import 'controller.dart';
import 'identity.dart';
import 'model.dart';
@@ -103,7 +104,9 @@ class _BuddyModelLineState extends State<BuddyModelLine> {
final snapshot = c.snapshot!;
final agent = widget.agent;
final now = DateTime.now();
- final offers = buddyModelOffers(snapshot, now: now);
+ final offers = agent.engine == 'claude'
+ ? buddyModelOffers(snapshot, now: now)
+ : <BuddyModelOffer>[];
final current = agent.gridModel;
final on = offers.where((o) => o.model == current).firstOrNull;
// A model gone quiet is still named by the last reading that served it.
@@ -117,7 +120,11 @@ class _BuddyModelLineState extends State<BuddyModelLine> {
model;
final request = agent.modelRequest;
final phone = workspaceIsCompact(context);
- final busy = !c.canWrite || c.saving || c.hasPendingAction;
+ final busy =
+ !c.canWrite ||
+ c.saving ||
+ c.hasPendingAction ||
+ agent.switchRequest != null;
final after = [
if (request == null && current != null)
on == null ? 'not served now' : _servers(on),
@@ -136,20 +143,22 @@ class _BuddyModelLineState extends State<BuddyModelLine> {
phone: phone,
busy: busy,
);
- return Text.rich(
- TextSpan(
- children: [
- WidgetSpan(
- alignment: PlaceholderAlignment.middle,
- child: KeyedSubtree(
- key: const ValueKey('super-buddy-model'),
- child: picker,
- ),
+ // Text.rich scales inline widgets as well as the Text they contain.
+ // Ordinary children scale once and wrap naturally on a narrow header.
+ return Wrap(
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ if (buddyEngineCapable(snapshot, agent)) ...[
+ BuddyEnginePicker(
+ key: const ValueKey('super-buddy-engine'),
+ controller: c,
+ agent: agent,
),
- TextSpan(text: ' · $after'),
+ Text(' · ', style: DesktopChrome.metadata()),
],
- ),
- style: DesktopChrome.metadata(),
+ KeyedSubtree(key: const ValueKey('super-buddy-model'), child: picker),
+ Text(' · $after', style: DesktopChrome.metadata()),
+ ],
);
}
@@ -179,35 +188,37 @@ class _BuddyModelLineState extends State<BuddyModelLine> {
AppMenuItem(
icon: current == null ? AppIcons.check : null,
label: 'Your subscription',
- note: 'Claude Code',
- onPressed: () => _pick(null),
+ note: buddyEngineLabel(widget.agent.engine),
+ onPressed: busy ? null : () => _pick(null),
),
),
- const AppMenuDivider(),
- words('SHARED IN THIS SWARM'),
- // A Buddy-only machine never joins the Swarm's grid (backend
- // read/hostRows.ts), so nothing shared reaches a Buddy there.
- if (pool == null || pool['buddyOnly'] == true)
- words(
- "Add ${widget.machine} to the Swarm's Machines to use shared models.",
- )
- else if (offers.isEmpty)
- words('Nobody shares a model in this Swarm yet.')
- else
- for (final offer in offers)
- row(
- AppMenuItem(
- icon: offer.model == current ? AppIcons.check : null,
- label: offer.name,
- // Under the name: a list of servers would be cut short beside it.
- detail: _servers(offer),
- onPressed: () => _pick(offer.model),
+ if (widget.agent.engine == 'claude') ...[
+ const AppMenuDivider(),
+ words('SHARED IN THIS SWARM'),
+ // A Buddy-only machine never joins the Swarm's grid (backend
+ // read/hostRows.ts), so nothing shared reaches a Buddy there.
+ if (pool == null || pool['buddyOnly'] == true)
+ words(
+ "Add ${widget.machine} to the Swarm's Machines to use shared models.",
+ )
+ else if (offers.isEmpty)
+ words('Nobody shares a model in this Swarm yet.')
+ else
+ for (final offer in offers)
+ row(
+ AppMenuItem(
+ icon: offer.model == current ? AppIcons.check : null,
+ label: offer.name,
+ // Under the name: a list of servers would be cut short beside it.
+ detail: _servers(offer),
+ onPressed: busy ? null : () => _pick(offer.model),
+ ),
),
- ),
- const AppMenuDivider(),
- words(
- 'What your Buddy reads and writes goes to the machine or API that serves the model you pick.',
- ),
+ const AppMenuDivider(),
+ words(
+ 'What your Buddy reads and writes goes to the machine or API that serves the model you pick.',
+ ),
+ ],
],
builder: (context, menu, _) => fingerTarget(
enabled: phone,
@@ -217,9 +228,13 @@ class _BuddyModelLineState extends State<BuddyModelLine> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- Text(
- label,
- style: DesktopChrome.metadata(color: DesktopChrome.foreground),
+ Flexible(
+ child: Text(
+ label,
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.foreground,
+ ),
+ ),
),
Icon(
AppIcons.chevronDown,
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index ca88acee6..087e22f43 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -3430,6 +3430,19 @@ class SuperTabController extends ChangeNotifier {
Future<bool> switchBuddyModel(String? gridModel) async =>
await command({'type': 'buddy.model', 'gridModel': gridModel}) != null;
+ /// Requests a handoff on the Buddy's own machine, keeping its chat and
+ /// folder. The host's switchRequest remains visible until it settles.
+ Future<bool> switchBuddyEngine(
+ String engine, {
+ String? conversationId,
+ }) async =>
+ await command({
+ 'type': 'buddy.engine',
+ 'engine': engine,
+ 'conversationId': ?conversationId,
+ }) !=
+ null;
+
/// Whether [group] is out of the app: there is no private channel to the
/// PM (Ken, 10-29), so no private chat but a Buddy chat is listed or opened,
/// the reader's old Chat with PM that an older server still sends included.
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 95f490513..05b64988f 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -231,8 +231,8 @@ class SuperTabAgent {
/// while it waits at a prompt in its terminal, gone once that is answered.
final List<String> alerting;
- /// A Product Manager's switch to another engine or account that is asked for
- /// and not yet done (backend `switchRequest`); null otherwise.
+ /// A Product Manager or Buddy's engine switch that is asked for and not yet
+ /// done (backend `switchRequest`); null otherwise.
final Map<String, dynamic>? switchRequest;
/// The model on the Swarm's grid it runs on; null on its own subscription
diff --git a/desktop/test/benchmarks/buddy_bar_benchmark.dart b/desktop/test/benchmarks/buddy_bar_benchmark.dart
index 242611dc5..ed356d565 100644
--- a/desktop/test/benchmarks/buddy_bar_benchmark.dart
+++ b/desktop/test/benchmarks/buddy_bar_benchmark.dart
@@ -12,7 +12,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/buddies.dart';
-import '../support/buddy_fixture.dart';
+import '../support/buddy_engine_fixture.dart';
const sizes = [100, 2000, 10000];
const rebuilds = 300;
@@ -22,8 +22,7 @@ void main() {
for (final refusalLast in [true, false]) {
final label = refusalLast ? 'refusal last' : 'no Buddy line';
testWidgets('Buddy bar rebuild, $size held, $label', (tester) async {
- final server = oneBuddySwarm();
- giveSwarmBuddy(server);
+ final server = buddyEngineSwarm();
for (var i = 0; i < size - 1; i++) {
server.append('message $i', conversationId: 'swarm-buddy-peer');
server.messages.last['author'] = {
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-large-narrow-dark.png b/desktop/test/screenshots/buddy-engine/buddy-engine-large-narrow-dark.png
new file mode 100644
index 000000000..5013fc5cb
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-large-narrow-dark.png differ
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-large-narrow-light.png b/desktop/test/screenshots/buddy-engine/buddy-engine-large-narrow-light.png
new file mode 100644
index 000000000..3d7d6f697
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-large-narrow-light.png differ
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-limit-narrow-dark.png b/desktop/test/screenshots/buddy-engine/buddy-engine-limit-narrow-dark.png
new file mode 100644
index 000000000..c6e4cef3f
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-limit-narrow-dark.png differ
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-limit-narrow-light.png b/desktop/test/screenshots/buddy-engine/buddy-engine-limit-narrow-light.png
new file mode 100644
index 000000000..ccfa2838c
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-limit-narrow-light.png differ
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-menu-dark.png b/desktop/test/screenshots/buddy-engine/buddy-engine-menu-dark.png
new file mode 100644
index 000000000..df7a62da9
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-menu-dark.png differ
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-menu-light.png b/desktop/test/screenshots/buddy-engine/buddy-engine-menu-light.png
new file mode 100644
index 000000000..fc8d4e475
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-menu-light.png differ
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-pending-dark.png b/desktop/test/screenshots/buddy-engine/buddy-engine-pending-dark.png
new file mode 100644
index 000000000..2b9689735
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-pending-dark.png differ
diff --git a/desktop/test/screenshots/buddy-engine/buddy-engine-pending-light.png b/desktop/test/screenshots/buddy-engine/buddy-engine-pending-light.png
new file mode 100644
index 000000000..0aea87efc
Binary files /dev/null and b/desktop/test/screenshots/buddy-engine/buddy-engine-pending-light.png differ
diff --git a/desktop/test/super_tab_buddy_engine_shots_test.dart b/desktop/test/super_tab_buddy_engine_shots_test.dart
new file mode 100644
index 000000000..57a2c5142
--- /dev/null
+++ b/desktop/test/super_tab_buddy_engine_shots_test.dart
@@ -0,0 +1,60 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+
+import 'support/buddy_engine_fixture.dart';
+import 'support/capture.dart';
+
+final shots = Platform.environment['SUPER_TAB_BUDDY_ENGINE_SHOTS'];
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+ for (final brightness in Brightness.values) {
+ for (final state in ['menu', 'limit-narrow', 'pending', 'large-narrow']) {
+ testWidgets('Buddy engine $state in ${brightness.name}', (tester) async {
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final c = await showBuddyEngine(
+ tester,
+ buddyEngineSwarm(
+ limited: state != 'pending',
+ switchRequest: state == 'pending'
+ ? {
+ 'id': 'request',
+ 'engine': 'codex',
+ 'profileId': 'default',
+ 'requestedBy': 'peer',
+ 'at': DateTime.now().toUtc().toIso8601String(),
+ }
+ : null,
+ ),
+ brightness: brightness,
+ narrow: state.endsWith('narrow'),
+ textScale: state == 'large-narrow' ? 2 : 1,
+ );
+ expect(
+ find.byKey(const ValueKey('super-buddy-engine')),
+ findsOneWidget,
+ );
+ if (state == 'menu' || state == 'limit-narrow') {
+ await tester.tap(
+ state == 'menu'
+ ? find.byKey(const ValueKey('super-buddy-engine'))
+ : find.text('Switch engine'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Codex'), findsOneWidget);
+ }
+ await captureWindow(
+ tester,
+ shots,
+ 'buddy-engine-$state-${brightness.name}',
+ );
+ await closeBuddyEngine(tester, c);
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+ }
+ }
+}
diff --git a/desktop/test/super_tab_buddy_engine_test.dart b/desktop/test/super_tab_buddy_engine_test.dart
new file mode 100644
index 000000000..a2ee12504
--- /dev/null
+++ b/desktop/test/super_tab_buddy_engine_test.dart
@@ -0,0 +1,335 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/widgets/app_menu.dart';
+import 'package:harness/super_tabs/buddy_engine.dart';
+
+import 'support/buddy_engine_fixture.dart';
+import 'support/super_tab_fixture.dart';
+
+ConversationServer namedBuddySwarm({
+ String firstEngine = 'claude',
+ bool secondLimited = false,
+}) {
+ final server = buddyEngineSwarm(engine: firstEngine);
+ server.state['buddyCap'] = 5;
+ final first = (server.state['agents'] as List).cast<Map>().firstWhere(
+ (a) => a['id'] == 'wren',
+ );
+ server.state['agents'] = <dynamic>[
+ ...server.state['agents'] as List,
+ {
+ ...first,
+ 'id': 'moss',
+ 'name': 'Moss',
+ 'harnessId': 'h-moss',
+ 'configuration': {'engine': 'claude', 'model': 'default'},
+ if (secondLimited)
+ 'limitedUntil': DateTime.now()
+ .add(const Duration(hours: 1))
+ .toUtc()
+ .toIso8601String(),
+ },
+ ];
+ final firstChat = (server.state['conversations'] as List)
+ .cast<Map>()
+ .firstWhere((g) => g['id'] == 'swarm-buddy-peer');
+ server.state['conversations'] = <dynamic>[
+ ...server.state['conversations'] as List,
+ {
+ ...firstChat,
+ 'id': 'swarm-buddy-peer-moss',
+ 'title': 'Moss',
+ 'buddyName': 'Moss',
+ 'buddyDefault': true,
+ 'agentIds': ['moss'],
+ },
+ ];
+ return server;
+}
+
+void main() {
+ final picker = find.byKey(const ValueKey('super-buddy-engine'));
+ final model = find.byKey(const ValueKey('super-buddy-model'));
+ Finder row(String name) => find.widgetWithText(AppMenuItem, name);
+ List<Map> commands(ConversationServer server) => [
+ for (final post in server.posts)
+ if ((post['command'] as Map)['type'] == 'buddy.engine')
+ post['command'] as Map,
+ ];
+ Future<void> open(WidgetTester tester) async {
+ expect(picker, findsOneWidget);
+ await tester.tap(picker);
+ await tester.pumpAndSettle();
+ }
+
+ // Catches a wrong engine payload or a second command for the current engine.
+ testWidgets('selecting Codex submits the engine and keeps the Buddy chat', (
+ tester,
+ ) async {
+ final server = buddyEngineSwarm();
+ final c = await showBuddyEngine(tester, server);
+ await open(tester);
+ expect(row('Claude Code'), findsOneWidget);
+ expect(row('Codex'), findsOneWidget);
+ expect(row('OpenCode'), findsNothing);
+ await tester.tap(row('Claude Code'));
+ await tester.pumpAndSettle();
+ expect(commands(server), isEmpty);
+ await open(tester);
+ await tester.tap(row('Codex'));
+ await tester.pumpAndSettle();
+ expect(commands(server), [
+ {'type': 'buddy.engine', 'engine': 'codex'},
+ ]);
+ expect(c.selectedId, 'swarm-buddy-peer');
+ expect(c.buddy('')!.id, 'wren');
+ await closeBuddyEngine(tester, c);
+ });
+
+ // A named Buddy must not inherit the person's first Buddy as its target.
+ // Exercise the picker with the actual agent it was given: the second chat
+ // is both selected and default, and both Buddies belong to the same owner.
+ testWidgets('a named Buddy engine picker targets its own selected chat', (
+ tester,
+ ) async {
+ final server = namedBuddySwarm();
+ final c = server.controller(account: 'peer');
+ await c.refresh();
+ await c.select('swarm-buddy-peer-moss');
+ addTearDown(c.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: BuddyEnginePicker(
+ key: const ValueKey('super-buddy-engine'),
+ controller: c,
+ agent: c.snapshot!.agent('moss')!,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await open(tester);
+ await tester.tap(row('Codex'));
+ await tester.pumpAndSettle();
+ expect(commands(server), [
+ {
+ 'type': 'buddy.engine',
+ 'engine': 'codex',
+ 'conversationId': 'swarm-buddy-peer-moss',
+ },
+ ]);
+ expect(c.selectedId, 'swarm-buddy-peer-moss');
+ expect(c.snapshot!.conversation('swarm-buddy-peer')!.agentIds, ['wren']);
+ expect(c.snapshot!.conversation('swarm-buddy-peer-moss')!.agentIds, [
+ 'moss',
+ ]);
+ });
+
+ for (final limitAction in [false, true]) {
+ testWidgets(
+ 'named Buddy full header targets its chat, limit=$limitAction',
+ (tester) async {
+ final server = namedBuddySwarm(
+ firstEngine: limitAction ? 'claude' : 'codex',
+ secondLimited: limitAction,
+ );
+ final c = await showBuddyEngine(tester, server);
+ addTearDown(c.dispose);
+ await c.select('swarm-buddy-peer-moss');
+ await tester.pumpAndSettle();
+ if (limitAction) {
+ final notice = find.byKey(const ValueKey('super-buddy-engine-limit'));
+ expect(notice, findsOneWidget);
+ await tester.tap(
+ find.descendant(of: notice, matching: find.text('Switch engine')),
+ );
+ await tester.pumpAndSettle();
+ } else {
+ expect(
+ find.descendant(of: picker, matching: find.text('Claude Code')),
+ findsOneWidget,
+ );
+ await open(tester);
+ }
+ await tester.tap(row('Codex'));
+ await tester.pumpAndSettle();
+ expect(commands(server), [
+ {
+ 'type': 'buddy.engine',
+ 'engine': 'codex',
+ 'conversationId': 'swarm-buddy-peer-moss',
+ },
+ ]);
+ expect(c.selectedId, 'swarm-buddy-peer-moss');
+ expect(c.snapshot!.conversation('swarm-buddy-peer')!.agentIds, [
+ 'wren',
+ ]);
+ expect(c.snapshot!.conversation('swarm-buddy-peer-moss')!.agentIds, [
+ 'moss',
+ ]);
+ },
+ );
+ }
+
+ // Catches interpreting unknown authentication, installation or old readings
+ // as an offer. Values are independent of the production eligibility helper.
+ for (final (label, signedIn, installed, ageMs) in [
+ ('signed out', false, true, 0),
+ ('unknown sign-in', null, true, 0),
+ ('missing installation', true, false, 0),
+ ('stale reading', true, true, 45001),
+ ]) {
+ testWidgets('$label never offers Codex', (tester) async {
+ final c = await showBuddyEngine(
+ tester,
+ buddyEngineSwarm(
+ codexSignIn: signedIn,
+ installed: installed,
+ ageMs: ageMs,
+ ),
+ );
+ await open(tester);
+ expect(row('Codex'), findsNothing);
+ await closeBuddyEngine(tester, c);
+ });
+ }
+
+ testWidgets('an older host has no engine action', (tester) async {
+ final c = await showBuddyEngine(
+ tester,
+ buddyEngineSwarm(capable: false, limited: true),
+ );
+ expect(picker, findsNothing);
+ expect(find.text('Switch engine'), findsNothing);
+ await closeBuddyEngine(tester, c);
+ });
+
+ testWidgets('a Team session never offers its subscription to a Buddy', (
+ tester,
+ ) async {
+ final c = await showBuddyEngine(
+ tester,
+ buddyEngineSwarm(sessionKind: 'team', limited: true),
+ );
+ expect(picker, findsNothing);
+ expect(find.text('Switch engine'), findsNothing);
+ await closeBuddyEngine(tester, c);
+ });
+
+ testWidgets('an engine handoff names its target and disables model changes', (
+ tester,
+ ) async {
+ final server = buddyEngineSwarm(
+ switchRequest: {
+ 'id': 'engine-request',
+ 'engine': 'codex',
+ 'profileId': 'default',
+ 'requestedBy': 'peer',
+ 'at': DateTime.now().toUtc().toIso8601String(),
+ },
+ );
+ final c = await showBuddyEngine(tester, server);
+ expect(find.text('Switching to Codex…'), findsOneWidget);
+ await tester.tap(model);
+ await tester.pumpAndSettle();
+ expect(find.byType(AppMenuItem), findsNothing);
+ expect(commands(server), isEmpty);
+ await closeBuddyEngine(tester, c);
+ });
+
+ testWidgets('a model switch disables engine changes', (tester) async {
+ final c = await showBuddyEngine(
+ tester,
+ buddyEngineSwarm(
+ modelRequest: {'id': 'model-request', 'gridModel': null},
+ ),
+ );
+ await open(tester);
+ expect(find.byType(AppMenuItem), findsNothing);
+ await closeBuddyEngine(tester, c);
+ });
+
+ testWidgets('a refused engine request shows the actionable server reason', (
+ tester,
+ ) async {
+ final server = buddyEngineSwarm();
+ server.refuse = {
+ 'code': 'BUDDY_ENGINE_UNAVAILABLE',
+ 'message': 'Sign in to Codex on your Buddy’s machine.',
+ };
+ final c = await showBuddyEngine(tester, server);
+ await open(tester);
+ await tester.tap(row('Codex'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Sign in to Codex on your Buddy’s machine.'),
+ findsOneWidget,
+ );
+ await closeBuddyEngine(tester, c);
+ });
+
+ testWidgets('a Codex Buddy model menu names the Codex subscription', (
+ tester,
+ ) async {
+ final c = await showBuddyEngine(tester, buddyEngineSwarm(engine: 'codex'));
+ await tester.tap(model);
+ await tester.pumpAndSettle();
+ final subscription = row('Your subscription');
+ expect(
+ find.descendant(of: subscription, matching: find.text('Codex')),
+ findsOneWidget,
+ );
+ expect(find.text('Claude Code'), findsNothing);
+ expect(find.text('SHARED IN THIS SWARM'), findsNothing);
+ await closeBuddyEngine(tester, c);
+ });
+
+ testWidgets('header selectors scale their text once at 200 percent', (
+ tester,
+ ) async {
+ final label = find.descendant(
+ of: picker,
+ matching: find.text('Claude Code'),
+ );
+ final normal = await showBuddyEngine(tester, buddyEngineSwarm());
+ final normalHeight = tester.getRect(label).height;
+ await closeBuddyEngine(tester, normal);
+ final large = await showBuddyEngine(
+ tester,
+ buddyEngineSwarm(),
+ textScale: 2,
+ );
+ expect(tester.getRect(label).height, closeTo(normalHeight * 2, 1));
+ await closeBuddyEngine(tester, large);
+ });
+
+ for (final narrow in [false, true]) {
+ testWidgets(
+ 'subscription limit opens the same engine menu, narrow=$narrow',
+ (tester) async {
+ final server = buddyEngineSwarm(limited: true);
+ final c = await showBuddyEngine(tester, server, narrow: narrow);
+ final notice = find.byKey(const ValueKey('super-buddy-engine-limit'));
+ expect(notice, findsOneWidget);
+ expect(find.text('Limit reached.'), findsOneWidget);
+ final action = find.descendant(
+ of: notice,
+ matching: find.text('Switch engine'),
+ );
+ expect(action, findsOneWidget);
+ await tester.tap(action);
+ await tester.pumpAndSettle();
+ await tester.tap(row('Codex'));
+ await tester.pumpAndSettle();
+ expect(commands(server), [
+ {'type': 'buddy.engine', 'engine': 'codex'},
+ ]);
+ expect(tester.takeException(), isNull);
+ await closeBuddyEngine(tester, c);
+ },
+ );
+ }
+}
diff --git a/desktop/test/support/buddy_engine_fixture.dart b/desktop/test/support/buddy_engine_fixture.dart
new file mode 100644
index 000000000..2a5de050e
--- /dev/null
+++ b/desktop/test/support/buddy_engine_fixture.dart
@@ -0,0 +1,104 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/workspace_chrome.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'buddy_fixture.dart';
+import 'super_tab_fixture.dart';
+
+/// Memory-backed Swarm with fake machine sign-in observations, never local
+/// accounts or processes. The host's reading has the backend's full readiness
+/// shape for the two engines this release supports.
+ConversationServer buddyEngineSwarm({
+ String engine = 'claude',
+ Object? codexSignIn = true,
+ bool installed = true,
+ int ageMs = 0,
+ bool capable = true,
+ String sessionKind = 'computer',
+ bool limited = false,
+ Map<String, dynamic>? switchRequest,
+ Map<String, dynamic>? modelRequest,
+}) {
+ final server = oneBuddySwarm();
+ giveSwarmBuddy(server);
+ final buddy = (server.state['agents'] as List).cast<Map>().firstWhere(
+ (a) => a['id'] == 'wren',
+ );
+ buddy['configuration'] = {'engine': engine, 'model': 'default'};
+ if (switchRequest != null) buddy['switchRequest'] = switchRequest;
+ if (modelRequest != null) buddy['modelRequest'] = modelRequest;
+ if (limited) {
+ buddy['limitedUntil'] = DateTime.now()
+ .add(const Duration(hours: 1))
+ .toUtc()
+ .toIso8601String();
+ }
+ final machine = (server.state['machines'] as List).first as Map;
+ machine['observation'] = {
+ 'receivedAt': DateTime.now().millisecondsSinceEpoch - ageMs,
+ 'sessionKind': sessionKind,
+ 'capabilities': ['buddySessions', 'swarmBuddy', if (capable) 'buddyEngine'],
+ 'readiness': {
+ 'engines': [
+ {'engine': 'claude', 'installed': true, 'signedIn': true},
+ {'engine': 'codex', 'installed': installed, 'signedIn': codexSignIn},
+ {'engine': 'opencode', 'installed': true, 'signedIn': true},
+ ],
+ },
+ };
+ return server;
+}
+
+Future<SuperTabController> showBuddyEngine(
+ WidgetTester tester,
+ ConversationServer server, {
+ Brightness brightness = Brightness.light,
+ bool narrow = false,
+ double textScale = 1,
+}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = narrow
+ ? const Size(390, 844)
+ : const Size(1200, 700);
+ addTearDown(tester.view.reset);
+ final c = server.controller(account: 'peer');
+ await c.refresh();
+ await c.select('swarm-buddy-peer');
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(textScale)),
+ child: child!,
+ ),
+ home: WorkspaceChromeScope(
+ chrome: WorkspaceChrome(compactBelow: 720),
+ child: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Kens-MacBook',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+Future<void> closeBuddyEngine(
+ WidgetTester tester,
+ SuperTabController controller,
+) async {
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+}
diff --git a/docs/plans/2026-11-06-buddy-engine-switch-plan.md b/docs/plans/2026-11-06-buddy-engine-switch-plan.md
new file mode 100644
index 000000000..b3b751e65
--- /dev/null
+++ b/docs/plans/2026-11-06-buddy-engine-switch-plan.md
@@ -0,0 +1,75 @@
+# Buddy engine switch implementation plan
+
+> Implement natively, task by task, with failing tests committed before their implementation and one independent review of the finished pull request.
+
+**Goal:** Let a person switch their Buddy to another signed-in engine when its subscription runs out, keeping its chat and folder.
+
+**Architecture:** Add an owner-only `buddy.engine` request. Reuse the pane/PM engine handoff, durable switch receipt, replacement binding and rollback; keep model and engine switches mutually exclusive. The Buddy header reads the same machine sign-in observations the server validates and offers the same menu after a subscription-limit report.
+
+**Tech Stack:** TypeScript backend and daemon; Flutter Desktop; Vitest and Flutter widget tests. No new dependencies.
+
+**Spec:** Swarm task #3833, conversation `45894032d75e4f44a6a34c21`. Requested by dee through Harness. The task's mockup is posted there. PM ruling: ship Claude Code and Codex here; other engines and their sign-in probes are follow-up #3839.
+
+## Global Constraints
+
+- Keep the Buddy's chat history and its folder; one Buddy stays one Buddy.
+- Offer only engines signed in on that machine. Unknown sign-in is unavailable.
+- No secret in any log. Never copy an account or login to another machine.
+- Desktop tests use a memory store and a fake sign-in; works on Windows the same (`docs/windows-rules.md`).
+- Small and fast: no redesign of the Buddy header. Reuse existing process launch and handoff paths.
+- Backend ships first. Gate new requests on the host's `buddyEngine` capability.
+
+## Design
+
+- Growth: reuse the single pending `switchRequest` per Buddy and existing expiring switch/operation receipts; no new collection. Completion or the existing bounded lease clears a request.
+- Concurrency: existing serialized Swarm command applies requests; engine/model switches exclude one another. Daemon handoff receipts fence duplicate stops/starts and survive restart; a bounded recovered marker keeps a later Stop Harness stopped after rollback.
+- Read cost: use current agent and machine observations; no new polling, database queries or transcript scan on idle passes. A switch reads the existing bounded handoff only on demand.
+- Scale: bounded machine engine list and existing host fan-out; measure header build cost and command cost on the same fixture before/after. Switch latency uses the existing bounded claim/start leases.
+- Compatibility: additive command/capability and Buddy host chat field; old hosts cannot receive a switch. Existing model commands and clients remain valid.
+- Migration/rollback: no migration. Roll back clients first; backend additions may remain. A failed new session uses existing handoff recovery, with a visible failure line.
+- Audience: only the Buddy's owner can request its switch; only its execution host can claim, bind and report that pending switch. Outcomes remain in the private Buddy chat.
+- Identity: same machine, default engine account, same Buddy ownership and launch guard. No PM role or GitHub authority is inherited.
+- Failure: stale readings, signed-out engines, busy switches, failed handoffs, timeout and rollback produce actionable visible results; logs contain failure categories only.
+- Platforms: backend Linux; CLI macOS/Linux/Windows via existing hidden launch path; shared Flutter UI on macOS/Linux/Windows/web (and compact layout). macOS widget evidence here; Windows native window evidence remains an independent platform check.
+
+## Review Focus
+
+1. Another person or Buddy trying to switch or rebind this Buddy: refuse without changing its identity.
+2. Engine/model changes racing, or a replay after host restart: at most one replacement, same chat and folder.
+3. Missing, stale or signed-out engine readings: no selectable offer, server refuses before stopping anything.
+4. A new session failing or arriving late: restore the original and never leave two running Buddies.
+5. Subscription-limit and pending states in a narrow header: actionable text, no overflow, both themes.
+
+### Task 1: Backend owner request and private outcome
+
+**Files:** `backend/src/superTabs/buddies.ts`, new `buddyEngine.ts` and `buddyEngine.test.ts`, `commands.ts`, `buddyModel.ts`, `tidy.ts`, `terminal.ts`, `read/hostRows.ts`; focused tests of their callers.
+
+**Interfaces:** `buddy.engine {engine, conversationId?}` selects the named owned Buddy chat, or the default Buddy for older clients, and writes the existing `Agent.switchRequest` with default profile, owner and operation id. Host rows expose that Buddy’s actual `buddyConversationId`; result, failure and expiry lines stay in the same chat when the person has several Buddies. Existing `agent.switchClaim`, `agent.rebind`, and `agent.switchResult` settle only the requested Buddy switch. `buddyEngine` is the new host capability.
+
+- [x] Commit failing caller-level tests for owner-only admission, signed-in/fresh/capable host, mutual exclusion, rebind preserving chat, duplicate/stale results, expiry and limit notice.
+- [x] Run the new tests and record their expected failures.
+- [x] Implement request validation and private result/expiry lines using existing switch state; preserve Buddy-specific authorization.
+- [x] Run the new tests and affected Buddy/model/terminal/rebind tests; commit and push the passing implementation.
+
+### Task 2: Host handoff and recovery
+
+**Files:** `cli/src/superTabs/leadSwitchRequest.ts`, `leadSwitch.ts`, `retention.ts`, `host.ts`, `machines.ts`, `inCore.ts`; `cli/src/lib/closeAgentService.ts`, its tests, and minimal wiring in `cli/src/core/main.ts` if required.
+
+**Interfaces:** Consume Task 1's request/chat field; use `agent_handoff_prepare`, `agent_close`, `agent_create`, `agent_handoff_complete` with one deterministic creation id. Preserve Buddy role, owner guard, folder and chat prompt. Reuse the handoff-backed one-use close permit and rollback window.
+
+- [x] Commit failing tests: Claude Code to Codex launch in the same folder with Buddy role/chat; no sign-in or stale owner refuses before close; duplicate/restarted request does not create twice; failed/late start recovers; ordinary close remains protected.
+- [x] Run those tests and record their expected failures.
+- [x] Extend existing handoff/recovery to Buddies, advertise capability only with the path implemented, and keep model switches exclusive.
+- [x] Run affected host, switch, replacement, close and Windows launch guard tests; typecheck and applicable non-CI coverage gates; commit and push.
+
+### Task 3: Header engine menu and limit action
+
+**Files:** new `desktop/lib/super_tabs/buddy_engine.dart`, `buddy_model.dart`, `buddies.dart`, `controller.dart`, `model.dart`; new `desktop/test/super_tab_buddy_engine_test.dart`, screenshot test and existing Buddy test support.
+
+**Interfaces:** `switchBuddyEngine(String engine, {String? conversationId})` submits Task 1's command for the selected chat on snapshots advertising several Buddies (`buddyCap`); older snapshots keep the no-id command. Offers come from a fresh machine `observation.readiness.engines` with installed/signedIn both true. `switchRequest` drives pending text and disables model changes.
+
+- [x] Commit failing widget tests with memory store/fake sign-in for selecting Codex, hidden signed-out/unknown/stale engines, pending state, command refusal and limit-action menu.
+- [x] Run them and record the expected failures.
+- [x] Add a compact shared-menu engine picker beside the model picker; reuse it in the one-line limit notice. Keep engine labels accurate in the model menu.
+- [x] Run affected Buddy tests on macOS, light/dark screenshot runs and narrow-layout tests. Record baseline/changed header timings and analyze changed files; commit and push.
+- [x] Update the PR with red/green evidence, screenshots, platform limits and timings; mark ready and hand to the Integrator for independent review/test and release.