Skip to content

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

Merge batch 11-02 1102-j: #2527 #2528 #2529 #2552 #2555 #2558 (#2565)

0xken15ee8e33044849
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index b783a0a83..ecb01858a 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -2007,4 +2007,47 @@ describe('the morning digest', () => {
await f.leadInbox()
expect(await digests()).toHaveLength(2)
})
+
+ it('drops a PM switch nobody claimed on another machine\'s next report, with one line in the project chat', async () => {
+ const f = await swarm()
+ await f.observe('lead-host', [f.harness.lead], { capabilities: ['leadSwitch'] })
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ await f.execute({ type: 'lead.switch', projectId, engine: 'codex', profileId: 'default' })
+ const pending = async () => (await f.timed.read(owner, f.tab)).state.agents.find(a => a.id === f.lead)!.switchRequest
+ expect(await pending()).toBeDefined()
+ const lines = async () => (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => (m.source as { kind?: string } | null)?.kind === 'switch')
+ f.clock.now += 2 * MINUTE + 1000
+ await f.observe('test-host', [f.harness.worker])
+ expect(await pending()).toBeUndefined()
+ expect((await lines()).map(m => m.text)).toEqual(["Couldn't switch the PM: its machine did not answer."])
+ f.clock.now += MINUTE
+ await f.observe('test-host', [f.harness.worker])
+ expect(await lines()).toHaveLength(1)
+ })
+
+ it('tells the machine owner in their quiet Buddy chat after a rebind, and never opens that chat twice', async () => {
+ const f = await swarm()
+ const WORK = 'a'.repeat(16)
+ const reading = { capabilities: ['leadSwitch'], profiles: [{ engine: 'codex' as const, id: WORK, label: 'Work', leftPercent: 80, resetsAt: null }] }
+ await f.observe('lead-host', [f.harness.lead], reading)
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ const notices = async () => (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => (m.source as { kind?: string } | null)?.kind === 'pm-switch-notice')
+ /** What a real host sends: its claim, then the rebind, and only then the result. */
+ const move = async (previousHarnessId: string, harnessId: string) => {
+ const asked = await f.execute({ type: 'lead.switch', projectId, engine: 'codex', profileId: WORK })
+ const switchId = (await f.timed.read(owner, f.tab)).state.agents.find(a => a.id === f.lead)!.switchRequest!.id
+ expect(asked).toBeDefined()
+ await f.execute({ type: 'agent.switchClaim', agentId: f.lead, switchId }, host, f.lead)
+ await f.execute({ type: 'agent.rebind', agentId: f.lead, machineId: 'lead-host', projectId, previousHarnessId, harnessId, profileId: WORK, configuration: config }, host, f.lead)
+ await f.execute({ type: 'agent.switchResult', agentId: f.lead, switchId, ok: true }, host, f.lead)
+ }
+ await move(f.harness.lead, 'second-session')
+ const [first] = await notices()
+ expect(first!.text).toContain('your Codex account "Work"')
+ await db.swarmGroup.update({ where: { id: `${f.tab}:${first!.conversationId}` }, data: { dormant: true } })
+ await f.observe('lead-host', ['second-session'], reading)
+ await move('second-session', 'third-session')
+ expect((await notices()).map(m => m.conversationId)).toEqual([first!.conversationId, first!.conversationId])
+ expect(await db.swarmGroup.count({ where: { tabId: f.tab, key: first!.conversationId } })).toBe(1)
+ })
})
diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.ts
index c90403929..baa4c8be1 100644
--- a/backend/integration/superTabRead.test.ts
+++ b/backend/integration/superTabRead.test.ts
@@ -429,6 +429,9 @@ describe('host form (design 4.10)', () => {
const readers = [{ email: peer.email, userId: peer.sub }, { email: outsider.email, userId: outsider.sub }]
expect(rows.get(s.lead)).toMatchObject({ lead: true, active: true, leadsConversationId: null, lastChangedAt: MIGRATED, observers: readers,
confidential: true, membersWatch: true })
+ // The chat a PM's host rebuilds its start prompt from when it switches it, a real id (2026-11-02, both reviews of #2527).
+ expect((rows.get(s.lead) as Row & { ledConversationId?: string }).ledConversationId).toBe('lead')
+ expect(rows.get(s.worker)).toMatchObject({ ledConversationId: null })
expect(rows.get(s.worker)).toMatchObject({ observers: readers, confidential: false, membersWatch: false })
// Its only group is finished and dormant, yet not archived: the host must not hand it to automatic cleanup.
expect(rows.get(s.more.idle)).toMatchObject({ lead: false, active: true })
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 3c36154c1..d3feb7140 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -3,7 +3,8 @@ import { storeOldLeads } from './leads.test-support.js'
import { applyCommand, commandSchema, LOOP_NOTICE_AT, PAIR_CHAIN_LIMIT, swarmGridName, withoutCredentials, type Command, type CommandContext } from './commands.js'
import { CREDENTIAL_MARKER, type CredentialKind } from './credentials.js'
import { sweepLiveness } from './liveness.js'
-import { hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'
+import { SWITCH_UNCLAIMED_MS } from './tidy.js'
+import { defaultProfileId, hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'
import { activeWork, agentOnly, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'
import type { RouteDecision } from './routeRecord.js'
import { startFinished } from './parts/write.js'
@@ -4560,3 +4561,274 @@ describe('the state a command works on', () => {
.toThrow(/cannot copy a Map at stray/)
})
})
+
+describe('lead.switch', () => {
+ const WORK = 'a'.repeat(16)
+ const setup = (capabilities: string[] | undefined = ['leadSwitch'], contributorId = 'owner') => {
+ const f = fixture()
+ f.invite()
+ const pm = f.add('pm', contributorId, 'lead', true)
+ const team = { sessionKind: 'team' as const, privacy: { mode: 'dedicated' as const, seenAt: 1000 } }
+ f.state.machines = [{ machineId: 'host', name: 'Studio', contributorId, membershipGeneration: f.state.people.find(p => p.id === contributorId)!.generation,
+ generation: 'g1', cwd: '/repo', engines: ['claude', 'codex'], maxAgents: 2, paused: false, observation: { generation: 'g1', receivedAt: 1000, ...team,
+ ...(capabilities ? { capabilities } : {}),
+ profiles: [{ engine: 'codex', id: WORK, label: 'Work', leftPercent: 80, resetsAt: null }],
+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,
+ deviceType: null, chip: null, os: null, gpuPercent: null }, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] } }]
+ const agent = () => f.state.agents.find(a => a.id === pm)!
+ const as: Actor = { kind: 'agent', agentId: pm, machineOwnerId: 'host-owner' }
+ const sid = () => agent().switchRequest!.id
+ const request = { type: 'lead.switch', projectId: 'lead', engine: 'codex', profileId: WORK } as const
+ return { f, pm, agent, as, request, sid }
+ }
+ const code = (run: () => unknown) => { try { run() } catch (error) { return (error as { code?: string }).code } }
+
+ it('lets the project owner and the PM machine\'s owner switch, and refuses a member', () => {
+ const mine = setup()
+ mine.f.run(mine.request)
+ expect(mine.agent().switchRequest).toMatchObject({ engine: 'codex', profileId: WORK, requestedBy: 'owner' })
+ const theirs = setup(['leadSwitch'], 'peer')
+ theirs.agent().machineOwnerId = 'peer'
+ theirs.f.run(theirs.request, peer)
+ expect(theirs.agent().switchRequest).toMatchObject({ requestedBy: 'peer' })
+ const other = setup()
+ expect(code(() => other.f.run(other.request, peer))).toBe('PROJECT_OWNER_REQUIRED')
+ })
+
+ it('refuses NO_LEAD, MACHINE_OFFLINE, HOST_OUTDATED, LEAD_SWITCHING, PROFILE_UNKNOWN and ENGINE_NOT_OFFERED', () => {
+ const none = fixture()
+ expect(code(() => none.run({ type: 'lead.switch', projectId: 'lead', engine: 'codex', profileId: 'default' }))).toBe('NO_LEAD')
+ const offline = setup()
+ expect(code(() => offline.f.run(offline.request, owner, { now: 1000 + 60_000 }))).toBe('MACHINE_OFFLINE')
+ const old = setup([])
+ expect(code(() => old.f.run(old.request))).toBe('HOST_OUTDATED')
+ const twice = setup()
+ twice.f.run(twice.request)
+ expect(code(() => twice.f.run({ ...twice.request, profileId: 'default' }))).toBe('LEAD_SWITCHING')
+ const unknown = setup()
+ expect(code(() => unknown.f.run({ ...unknown.request, profileId: 'b'.repeat(16) }))).toBe('PROFILE_UNKNOWN')
+ expect(code(() => unknown.f.run({ ...unknown.request, engine: 'claude', profileId: WORK }))).toBe('PROFILE_UNKNOWN')
+ unknown.f.run({ ...unknown.request, profileId: 'default' })
+ const missing = setup()
+ missing.f.state.machines![0]!.engines = ['claude']
+ expect(code(() => missing.f.run(missing.request))).toBe('ENGINE_NOT_OFFERED')
+ })
+
+ it('works while the Swarm is paused', () => {
+ const s = setup()
+ s.f.state.paused = true
+ s.f.run(s.request)
+ expect(s.agent().switchRequest).toBeDefined()
+ })
+
+ it('lets only the PM itself claim, with a 15 minute lease', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const claim = { type: 'agent.switchClaim', agentId: s.pm, switchId: s.sid() } as const
+ expect(code(() => s.f.run(claim))).toBe('STALE_SWITCH')
+ expect(code(() => s.f.run({ ...claim, switchId: 'other' }, s.as))).toBe('STALE_SWITCH')
+ const claimed = s.f.run(claim, s.as)
+ expect(claimed.result).toMatchObject({ expiresAt: 1000 + 15 * 60_000 })
+ expect(s.agent().switchRequest!.claimedUntil).toBe(new Date(1000 + 15 * 60_000).toISOString())
+ })
+
+ it('writes the result in the PM chat and clears the request', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const done = s.f.run({ type: 'agent.switchResult', agentId: s.pm, switchId: s.sid(), ok: true }, s.as)
+ expect(done.messages).toMatchObject([{ conversationId: 'lead', recipients: [], text: 'PM moved to Codex · Work.' }])
+ expect(s.agent().switchRequest).toBeUndefined()
+ expect(s.agent().profileId).toBe(WORK)
+ const plain = setup()
+ plain.f.run({ ...plain.request, profileId: 'default' })
+ expect(plain.f.run({ type: 'agent.switchResult', agentId: plain.pm, switchId: plain.sid(), ok: true }, plain.as).messages[0]!.text).toBe('PM moved to Codex.')
+ const bad = setup()
+ bad.f.run(bad.request)
+ expect(code(() => bad.f.run({ type: 'agent.switchResult', agentId: bad.pm, switchId: 'nope', ok: true }, bad.as))).toBe('STALE_SWITCH')
+ const failed = bad.f.run({ type: 'agent.switchResult', agentId: bad.pm, switchId: bad.sid(), ok: false, error: 'no sign-in' }, bad.as)
+ expect(failed.messages[0]!.text).toBe('Couldn\'t switch the PM: no sign-in. It is back on Codex.')
+ expect(bad.agent().switchRequest).toBeUndefined()
+ expect(bad.agent().profileId).toBeUndefined()
+ })
+
+ it('refuses a borrower of a lent machine, and lets the machine\'s lender and a Team account\'s owner switch', () => {
+ // Tony (peer) borrowed Ken's Mac: the pool's contributor is Tony, the machine's owner is Ken.
+ const lent = setup(['leadSwitch'], 'peer')
+ lent.agent().machineOwnerId = 'ken'
+ expect(code(() => lent.f.run(lent.request, peer))).toBe('PROJECT_OWNER_REQUIRED')
+ const lender = setup(['leadSwitch'], 'peer')
+ lender.agent().machineOwnerId = 'peer'
+ lender.f.run(lender.request, peer)
+ expect(lender.agent().switchRequest).toMatchObject({ requestedBy: 'peer' })
+ const team = setup(['leadSwitch'], 'peer')
+ team.f.state.machines![0]!.observation!.sessionKind = 'team'
+ team.agent().machineOwnerId = 'peer'
+ team.f.run(team.request, peer)
+ expect(team.agent().switchRequest).toBeDefined()
+ })
+
+ it('tells the machine owner, in their Buddy chat, when another person moves the PM onto one of their other accounts', () => {
+ const lent = () => { const s = setup(['leadSwitch'], 'peer'); s.agent().machineOwnerId = 'peer'; return s }
+ const done = (s: ReturnType<typeof setup>) => s.f.run({ type: 'agent.switchResult', agentId: s.pm, switchId: s.sid(), ok: true }, { ...s.as, machineOwnerId: 'peer' })
+ const s = lent()
+ s.f.run(s.request)
+ const told = done(s).messages.filter(m => (m.source as { kind?: string } | undefined)?.kind === 'pm-switch-notice')
+ expect(told).toEqual([expect.objectContaining({ conversationId: s.f.state.conversations.find(c => c.kind === 'swarm-buddy')!.id,
+ text: 'owner moved the PM of Pilot on Studio to your Codex account "Work".', source: { kind: 'pm-switch-notice', machineId: 'host' } })])
+ const def = lent()
+ def.f.run({ ...def.request, profileId: 'default' })
+ expect(done(def).messages).toHaveLength(1)
+ const own = lent()
+ own.f.run(own.request, peer)
+ expect(done(own).messages).toHaveLength(1)
+ })
+
+ it('serves a machine\'s accounts only to its owner and the owners of projects whose PM runs there', () => {
+ const s = setup(['leadSwitch'], 'peer')
+ s.agent().machineOwnerId = 'peer'
+ s.f.state.people.push({ id: 'third', email: '[email protected]', role: 'member', generation: 'g' } as never)
+ const read = (actor: Actor) => visibleState(s.f.state, actor, 1000).machines?.[0]?.observation?.profiles
+ expect(read(owner)).toHaveLength(1)
+ expect(read(peer)).toHaveLength(1)
+ expect(read({ kind: 'person', userId: 'third', email: '[email protected]' })).toBeUndefined()
+ expect(read({ ...s.as, machineOwnerId: 'peer' })).toBeUndefined()
+ })
+
+ it('drops a request nobody claimed on any machine\'s report, and refuses a late claim', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const claim = { type: 'agent.switchClaim', agentId: s.pm, switchId: s.sid() } as const
+ expect(code(() => s.f.run(claim, s.as, { now: 1000 + SWITCH_UNCLAIMED_MS }))).toBe('STALE_SWITCH')
+ const swept = sweepLiveness(s.f.state, 1000 + SWITCH_UNCLAIMED_MS)
+ expect(swept).toMatchObject([{ text: "Couldn't switch the PM: its machine did not answer." }])
+ expect(s.agent().switchRequest).toBeUndefined()
+ })
+
+ it('does not extend a claim\'s lease by claiming again', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const claim = { type: 'agent.switchClaim', agentId: s.pm, switchId: s.sid() } as const
+ s.f.run(claim, s.as)
+ const again = s.f.run(claim, s.as, { now: 1000 + 10 * 60_000 })
+ expect(again.result).toMatchObject({ expiresAt: 1000 + 15 * 60_000 })
+ expect(s.agent().switchRequest!.claimedUntil).toBe(new Date(1000 + 15 * 60_000).toISOString())
+ })
+
+ it('agent.rebind that keeps the account leaves the limit mark, one that moves it clears it', () => {
+ const s = setup()
+ s.agent().limitedUntil = new Date(5_000_000).toISOString()
+ s.agent().alerting = ['limit', 'prompt']
+ s.f.run(s.request)
+ const rebind = (patch: object, from: string, to: string) => s.f.run({ type: 'agent.rebind', agentId: s.pm, machineId: 'host', projectId: 'lead',
+ previousHarnessId: from, harnessId: to, configuration: config, ...patch } as never, s.as)
+ // Same engine (codex), no profile: the limited account stays, though a request for another one was pending.
+ rebind({}, 'pm', 'pm-2')
+ expect(s.agent()).toMatchObject({ alerting: ['limit', 'prompt'], limitedUntil: new Date(5_000_000).toISOString() })
+ expect(s.agent().switchRequest).toBeUndefined()
+ // Same engine, another account reported: the mark goes.
+ rebind({ profileId: WORK }, 'pm-2', 'pm-3')
+ expect(s.agent()).toMatchObject({ alerting: ['prompt'], limitedUntil: null, profileId: WORK })
+ // Another engine without a profile: back to the default account.
+ rebind({ configuration: { ...config, engine: 'claude' } }, 'pm-3', 'pm-4')
+ expect(s.agent().profileId).toBeUndefined()
+ // Same engine, no profile: kept.
+ s.agent().profileId = WORK
+ rebind({ configuration: { ...config, engine: 'claude' } }, 'pm-4', 'pm-5')
+ expect(s.agent().profileId).toBe(WORK)
+ })
+
+ it('names the default account by one id: a rebind that keeps it never clears the limit', () => {
+ const s = setup()
+ const DEFAULT = defaultProfileId('host', 'codex')
+ s.agent().limitedUntil = new Date(5_000_000).toISOString()
+ s.agent().alerting = ['limit']
+ const rebind = (profileId: string, from: string, to: string) => s.f.run({ type: 'agent.rebind', agentId: s.pm, machineId: 'host', projectId: 'lead',
+ previousHarnessId: from, harnessId: to, configuration: config, profileId } as never, s.as)
+ rebind(DEFAULT, 'pm', 'pm-2')
+ expect(s.agent()).toMatchObject({ alerting: ['limit'], limitedUntil: new Date(5_000_000).toISOString() })
+ expect(s.agent().profileId).toBeUndefined()
+ rebind('default', 'pm-2', 'pm-3')
+ expect(s.agent().limitedUntil).toBe(new Date(5_000_000).toISOString())
+ // A legacy stored hex default counts as the default too.
+ s.agent().profileId = DEFAULT
+ rebind('default', 'pm-3', 'pm-4')
+ expect(s.agent().limitedUntil).toBe(new Date(5_000_000).toISOString())
+ expect(s.agent().profileId).toBeUndefined()
+ // The Claude default is not the Codex default.
+ rebind(defaultProfileId('host', 'claude'), 'pm-4', 'pm-5')
+ expect(s.agent()).toMatchObject({ limitedUntil: null, profileId: defaultProfileId('host', 'claude') })
+ })
+
+ it('stores a literal default switch as the default account\'s id, and reports it with no label', () => {
+ const s = setup()
+ s.f.run({ ...s.request, profileId: 'default' })
+ expect(s.agent().switchRequest!.profileId).toBe(defaultProfileId('host', 'codex'))
+ const done = s.f.run({ type: 'agent.switchResult', agentId: s.pm, switchId: s.sid(), ok: true }, s.as)
+ expect(done.messages[0]!.text).toBe('PM moved to Codex.')
+ expect(s.agent().profileId).toBeUndefined()
+ const hex = setup()
+ hex.f.run({ ...hex.request, profileId: defaultProfileId('host', 'codex') })
+ expect(hex.agent().switchRequest!.profileId).toBe(defaultProfileId('host', 'codex'))
+ const other = setup()
+ expect(code(() => other.f.run({ ...other.request, profileId: defaultProfileId('host', 'claude') }))).toBe('PROFILE_UNKNOWN')
+ })
+
+ it('writes one line per switch: a late or repeated result writes nothing', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const switchId = s.sid()
+ const result = { type: 'agent.switchResult', agentId: s.pm, switchId, ok: true } as const
+ // The sweep gave up on it first: the host's late result is stale.
+ const late = setup()
+ late.f.run(late.request)
+ const lateId = late.sid()
+ sweepLiveness(late.f.state, 1000 + SWITCH_UNCLAIMED_MS)
+ expect(code(() => late.f.run({ ...result, switchId: lateId }, late.as))).toBe('STALE_SWITCH')
+ // The rebind landed it: the result still tells the chat once, and a retry with a new operation id does not.
+ s.f.run({ type: 'agent.rebind', agentId: s.pm, machineId: 'host', projectId: 'lead', previousHarnessId: 'pm', harnessId: 'pm-2',
+ configuration: { ...config, engine: 'claude' } }, s.as)
+ expect(s.f.run(result, s.as).messages[0]!.text).toBe('PM moved to Claude.')
+ expect(code(() => s.f.run(result, s.as))).toBe('STALE_SWITCH')
+ // A made-up id with nothing pending is refused too.
+ expect(code(() => s.f.run({ ...result, switchId: 'made-up' }, s.as))).toBe('STALE_SWITCH')
+ })
+
+ it('tells the machine owner after a real switch, where the rebind lands before the result', () => {
+ const s = setup(['leadSwitch'], 'peer')
+ s.agent().machineOwnerId = 'peer'
+ s.f.run(s.request)
+ const switchId = s.sid(), requester = s.agent().switchRequest!.requestedBy
+ s.f.run({ type: 'agent.rebind', agentId: s.pm, machineId: 'host', projectId: 'lead', previousHarnessId: 'pm', harnessId: 'pm-2', profileId: WORK,
+ configuration: { ...config, engine: 'codex' } }, { ...s.as, machineOwnerId: 'peer' })
+ expect(s.agent().switchRequest).toBeUndefined()
+ expect(s.agent().switchLanded).toEqual({ id: switchId, requestedBy: requester })
+ const done = s.f.run({ type: 'agent.switchResult', agentId: s.pm, switchId, ok: true }, { ...s.as, machineOwnerId: 'peer' })
+ expect(done.messages.filter(m => (m.source as { kind?: string } | undefined)?.kind === 'pm-switch-notice')).toEqual([expect.objectContaining({
+ text: 'owner moved the PM of Pilot on Studio to your Codex account "Work".' })])
+ expect(s.agent().switchLanded).toBeUndefined()
+ })
+
+ it('never says a landed switch failed: a rebind that beat a failure report wins', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const switchId = s.sid()
+ s.f.run({ type: 'agent.rebind', agentId: s.pm, machineId: 'host', projectId: 'lead', previousHarnessId: 'pm', harnessId: 'pm-2', profileId: WORK,
+ configuration: { ...config, engine: 'codex' } }, s.as)
+ const done = s.f.run({ type: 'agent.switchResult', agentId: s.pm, switchId, ok: false, error: 'the new session did not start in time' }, s.as)
+ expect(done.messages[0]!.text).toBe('PM moved to Codex · Work.')
+ })
+
+ it('says a PM that has not come back is not back', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const failed = s.f.run({ type: 'agent.switchResult', agentId: s.pm, switchId: s.sid(), ok: false, error: 'the new session could not start', down: true }, s.as)
+ expect(failed.messages[0]!.text).toBe("Couldn't switch the PM: the new session could not start. It has not come back on Codex yet; its machine keeps trying.")
+ })
+
+ it('writes the host\'s error as one clean line', () => {
+ const s = setup()
+ s.f.run(s.request)
+ const failed = s.f.run({ type: 'agent.switchResult', agentId: s.pm, switchId: s.sid(), ok: false, error: 'signed out.\nplease\tretry.. ' }, s.as)
+ expect(failed.messages[0]!.text).toBe("Couldn't switch the PM: signed out. please retry. It is back on Codex.")
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index be4d57f37..2cb392dda 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,6 +1,6 @@
-import { admitMachineStart, BUDDY_WINDOWS_REFUSAL, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, machineSlots, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
+import { admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
-import { keepUsernames, setUsername, swarmUsernames } from './usernames.js'
+import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'
import { z } from 'zod'
import { tokensByModelSchema } from './costs/tokens.js'
import {
@@ -35,6 +35,7 @@ import { shipNotice, shippedAt } from './ship.js'
import { assignedNotice, tellBuddies } from './buddyNews.js'
import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged } from './cards.js'
import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'
+import { switchExpired } from './tidy.js'
import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, canReadProject, deleteProject, isConfidential, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'
import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
@@ -51,6 +52,15 @@ const NO_REASON = 'No reason given.'
export const IGNORED_NOTE = 'Routing and roles live in each project\'s instructions now. Update Harness to edit them there.'
const title = z.string().trim().min(1).max(160)
const reason = z.string().trim().min(1).max(300)
+/** What a host reports it can do for a Product Manager's switch; a host from before it is never asked (HOST_OUTDATED). */
+const SWITCH_CAPABILITY = 'leadSwitch'
+const SWITCH_LEASE_MS = 15 * 60_000
+/** The engines as people read them in a switch's line. */
+const ENGINE_NAMES: Record<string, string> = { claude: 'Claude', codex: 'Codex' }
+const moveToProfile = (target: Agent, engine: string, profileId: string | undefined) => {
+ const stored = storedProfileId(target.machineId, engine, profileId)
+ if (stored === undefined) delete target.profileId; else target.profileId = stored
+}
const text = z.string().trim().min(1).max(32_000)
const swarmEngine = z.string().min(1).max(80).refine((engine): boolean => engine === 'claude' || engine === 'codex', 'A Swarm agent runs only Claude Code or Codex.')
const configuration = z.object({
@@ -164,6 +174,8 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('lead.start'), projectId: id, machineId: id.nullable(), engine: swarmEngine,
model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional(),
branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(), repositoryUrl: repositoryUrl.optional() }).strict(),
+ z.object({ type: z.literal('lead.switch'), projectId: id, engine: swarmEngine, profileId: id,
+ model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional() }).strict(),
z.object({ type: z.literal('project.skills'), projectId: id, mode: z.enum(['default', 'orchestration', 'custom']), askedIn: askedInSchema.optional() }).strict(),
z.object({ type: z.literal('project.roles.create'), projectId: id, roles: roleSet }).strict(),
z.object({ type: z.literal('project.role.set'), projectId: id, role }).strict(),
@@ -227,13 +239,16 @@ export const commandSchema = z.discriminatedUnion('type', [
configuration: configuration.optional() }).strict(),
z.object({ type: z.literal('agent.startFailed'), startId: id, error: text }).strict(),
z.object({ type: z.literal('agent.stopLease'), agentId: id, releaseId: id }).strict(),
+ z.object({ type: z.literal('agent.switchClaim'), agentId: id, switchId: id }).strict(),
+ // The host's own words for why it failed: free text, so capped and redacted.
+ z.object({ type: z.literal('agent.switchResult'), agentId: id, switchId: id, ok: z.boolean(), error: z.string().trim().min(1).max(300).optional(), down: z.boolean().optional() }).strict(),
z.object({ type: z.literal('agent.stopRefused'), agentId: id, releaseId: id }).strict(),
z.object({ type: z.literal('agent.remove'), agentId: id, releaseId: id.optional() }).strict(),
z.object({ type: z.literal('agent.release'), agentId: id, decision: z.enum(['keep', 'stop']) }).strict(),
z.object({ type: z.literal('agent.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,
- previousHarnessId: id, harnessId: id, configuration,
+ 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(),
z.object({ type: z.literal('invite.create'), email: z.email().max(320), role: z.enum(['collaborator', 'viewer']), conversationId: id }).strict(),
@@ -304,6 +319,7 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {
'agent.add': ['name', 'initialMessage'],
'agent.start': ['request.name', 'overrideReason'],
'agent.startFailed': ['error'],
+ 'agent.switchResult': ['error'],
'agent.startSettled': ['warning'],
'conversation.create': ['title', 'brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'task.review.focus', 'checks[].description'],
'conversation.rename': ['title'],
@@ -1400,6 +1416,30 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
Object.assign(result, { startId: start.id, machineId: start.request.machineId })
break
}
+ case 'lead.switch': {
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person moves a project\'s coordinator.', 403)
+ const project = projectOf(state, command.projectId)
+ const home = conversation(state, project.leadConversationId)
+ const pm = state.agents.find(a => a.id === home.leadId && home.agentIds.includes(a.id))
+ const pool = state.machines?.find(m => m.machineId === pm?.machineId)
+ // The project's owner, or the owner of the machine the PM runs on (not whoever contributed it: a lent machine's borrower).
+ if (pm?.machineOwnerId === actor.userId && actor.userId !== project.ownerId) author(state, actor, true)
+ else manageProject(state, actor, project.id)
+ const name = coordinatorNameOf(project)
+ if (!pm || !pool) fail('NO_LEAD', `This project has no running ${name}.`)
+ if (machineOffline(pool, context.now)) fail('MACHINE_OFFLINE', `Wait for a fresh reading from ${pool.name}.`)
+ if (!pool.observation!.capabilities?.includes(SWITCH_CAPABILITY)) fail('HOST_OUTDATED', `Update Harness on ${pool.name} to move the ${name}.`, 409)
+ if (pm.switchRequest) fail('LEAD_SWITCHING', `The ${name} is already being moved.`, 409)
+ if (!contributedEngines(pool).includes(command.engine)) fail('ENGINE_NOT_OFFERED', `${ENGINE_NAMES[command.engine]} isn’t offered on ${pool.name}.`, 403)
+ // The default account has one id (a literal 'default' is the same account), and the request stores that id.
+ const profileId = command.profileId === 'default' ? defaultProfileId(pool.machineId, command.engine) : command.profileId
+ if (profileId !== defaultProfileId(pool.machineId, command.engine) && !pool.observation!.profiles?.some(p => p.engine === command.engine && p.id === profileId)) {
+ fail('PROFILE_UNKNOWN', `That account isn’t on ${pool.name} any more.`, 409)
+ }
+ const { type: _type, projectId: _projectId, ...asked } = command
+ pm.switchRequest = { id: operationId, ...asked, profileId, requestedBy: actor.userId, at: new Date(context.now).toISOString() }
+ break
+ }
case 'project.skills':
// Skill modes are the project's instructions now: whoever reads the project is answered, and nothing is kept.
readProject(state, actor, command.projectId)
@@ -2313,6 +2353,20 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (target.harnessId !== command.previousHarnessId || command.harnessId === command.previousHarnessId) {
fail('AGENT_CHANGED', 'The member’s terminal changed. Read its current binding before replacing it.')
}
+ // The new account is not limited: only a switch that kept the engine and the account leaves the limit mark.
+ // The account is what the host reports; without it, a new engine means its default and the same engine keeps the account.
+ const engineChanged = command.configuration.engine !== target.configuration?.engine
+ // Compared as stored: the default account is absent whether it is reported as 'default' or by its id.
+ const engine = command.configuration.engine
+ const landed = storedProfileId(target.machineId, engine, command.profileId ?? (engineChanged ? undefined : target.profileId))
+ if (engineChanged || landed !== storedProfileId(target.machineId, target.configuration?.engine ?? engine, target.profileId)) {
+ target.limitedUntil = null
+ target.alerting = target.alerting?.filter(a => a !== 'limit')
+ }
+ moveToProfile(target, engine, landed)
+ // Whatever request was pending is settled; its result, when it comes, is still the one line the chat gets.
+ if (target.switchRequest) target.switchLanded = { id: target.switchRequest.id, requestedBy: target.switchRequest.requestedBy }
+ delete target.switchRequest
target.harnessId = command.harnessId
target.replacement = { previousHarnessId: command.previousHarnessId, harnessId: command.harnessId }
// A new terminal is not the session that lost its task, nor one started on a grid model: it reports its own.
@@ -2373,6 +2427,48 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
target.keptAt = context.now
break
}
+ case 'agent.switchClaim': {
+ const target = agent(state, command.agentId)
+ if (actor.kind !== 'agent' || actor.agentId !== target.id || target.switchRequest?.id !== command.switchId || switchExpired(target.switchRequest, context.now)) {
+ fail('STALE_SWITCH', 'Only the execution host can claim the current switch.', 403)
+ }
+ // Covers #2493's 3 minute prepare and 10 minute create limits. A second claim gets the same lease back, never a longer one.
+ target.switchRequest.claimedUntil ??= new Date(context.now + SWITCH_LEASE_MS).toISOString()
+ result.leaseId = operationId
+ result.expiresAt = Date.parse(target.switchRequest.claimedUntil)
+ break
+ }
+ case 'agent.switchResult': {
+ const target = agent(state, command.agentId)
+ // agent.rebind clears a request whose new session started but keeps its id, so the result of either is the one to answer.
+ if (actor.kind !== 'agent' || actor.agentId !== target.id || ![target.switchRequest?.id, target.switchLanded?.id].includes(command.switchId)) {
+ fail('STALE_SWITCH', 'Only the execution host can report the current switch.', 403)
+ }
+ const project = ledProject(state, target.id), landed = target.switchLanded?.id === command.switchId ? target.switchLanded : undefined
+ 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 (moved && !landed && target.switchRequest) moveToProfile(target, target.switchRequest.engine, target.switchRequest.profileId)
+ delete target.switchRequest
+ delete target.switchLanded
+ if (!project) break
+ const error = command.error?.replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/[.\s]+$/, '')
+ const engine = ENGINE_NAMES[target.configuration?.engine ?? ''] ?? 'its engine'
+ const label = target.profileId && state.machines?.find(m => m.machineId === target.machineId)?.observation?.profiles
+ ?.find(p => p.engine === target.configuration?.engine && p.id === target.profileId)?.label
+ effects.messages.push({ id: operationId, conversationId: project.leadConversationId, author: sender, replyTo: null, recipients: [], source: SYSTEM_ROW,
+ text: moved ? `PM moved to ${engine}${label ? ` · ${label}` : ''}.`
+ : `Couldn't switch the PM: ${error || 'it failed'}. ${command.down ? `It has not come back on ${engine} yet; its machine keeps trying.` : `It is back on ${engine}.`}` })
+ // The machine owner hears when their non-default account runs another person's PM; the project line may be out of their reach.
+ const owner = state.people.find(p => p.id === target.machineOwnerId), pool = state.machines?.find(m => m.machineId === target.machineId)
+ if (moved && label && asked && owner && asked !== owner.id) {
+ const who = usernameOf(state, asked) ?? state.people.find(p => p.id === asked)?.email ?? 'Someone'
+ effects.messages.push({ id: stableId(operationId, 'pm-switch-notice'), conversationId: openSwarmBuddyChat(state, owner).id, author: sender, replyTo: null, recipients: [],
+ source: { kind: 'pm-switch-notice', machineId: target.machineId },
+ text: `${who} moved the PM of ${project.name} on ${pool?.name ?? target.machineId} to your ${engine} account "${label}".` })
+ }
+ break
+ }
case 'agent.stopLease': {
const target = agent(state, command.agentId)
if (actor.kind !== 'agent' || actor.agentId !== target.id || target.workDecision !== 'stop' || command.releaseId !== target.releaseId) {
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 20b0bf95d..adefa258a 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -8,6 +8,7 @@ import { askedModel, coordinatorCopy, failureNotice, failureRecipients, leadPick
import { leadOf, toLead } from './terminal.js'
import { dropIdleBuddyMachines, MACHINE_FRESH_MS } from './machines.js'
import { leadStartFailed } from './leadStart.js'
+import { staleSwitches } from './tidy.js'
import { ledProject, projectsOf } from './projects.js'
import { coordinatorNameOf } from './instructions.js'
import { waitedOn } from './leaderboard/record.js'
@@ -286,7 +287,7 @@ function leadNotice(state: SuperTabState, start: AgentStart, text: string | null
/** The time checks, run on the Lead's poll and on any machine's report: every worker task with a reason is lost, and
* every start dispatched over 3 minutes ago that is not running fails, unless its machine is still preparing it. */
export function sweepLiveness(state: SuperTabState, now: number): MessageDraft[] {
- const drafts = [...loseTasks(state, now), ...failStalledStarts(state, now), ...unpurged(state, now)]
+ const drafts = [...loseTasks(state, now), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now)]
// A Buddy start that timed out may have been the last on its Buddy-only machine (security review 1 of #2234).
dropIdleBuddyMachines(state, now)
return drafts
diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.ts
index 0fe589c6b..0bfdc0589 100644
--- a/backend/src/superTabs/machines.test.ts
+++ b/backend/src/superTabs/machines.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { createSuperTab, SuperTabError, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
-import { admitMachineStart, machineSlots, machineObservationSchema, preparableStart, readingOnly, servedLocalModels, storedObservation, type ContributedMachine,
+import { admitMachineStart, defaultProfileId, machineSlots, machineObservationSchema, preparableStart, readingOnly, servedLocalModels, storedObservation, type ContributedMachine,
type MachineObservation } from './machines.js'
const NOW = 1_000_000
@@ -202,6 +202,33 @@ it('keeps durable release receipts authoritative over stale observations and ret
expect(machineSlots(f.state, pool)).toBe(1)
})
+describe('reported engine profiles', () => {
+ const { receivedAt: _receivedAt, ...sent } = observation
+ const profile = { engine: 'claude', id: '0123456789abcdef', label: 'Work', leftPercent: 40, resetsAt: '2026-11-02T10:00:00.000Z' }
+ const ok = (profiles: unknown) => machineObservationSchema.safeParse({ ...sent, profiles }).success
+
+ it('accepts up to 16 profiles and refuses a 17th', () => {
+ expect(ok(Array(16).fill(profile))).toBe(true)
+ expect(ok(Array(17).fill(profile))).toBe(false)
+ expect(ok([{ ...profile, leftPercent: null, resetsAt: null }])).toBe(true)
+ })
+ it('refuses a label with @, and any other malformed profile', () => {
+ expect(ok([{ ...profile, label: '[email protected]' }])).toBe(false)
+ expect(ok([{ ...profile, label: '' }])).toBe(false)
+ expect(ok([{ ...profile, id: 'ABC' }])).toBe(false)
+ expect(ok([{ ...profile, engine: 'gemini' }])).toBe(false)
+ expect(ok([{ ...profile, leftPercent: 101 }])).toBe(false)
+ expect(ok([{ ...profile, extra: 1 }])).toBe(false)
+ })
+ it('keeps profiles of contributed engines only', () => {
+ const pool: ContributedMachine = { machineId: 'host', name: 'Mac', contributorId: 'owner', membershipGeneration: 'tab', generation: 'g1',
+ cwd: '/x', engines: ['claude'], maxAgents: 2, paused: false }
+ const kept = storedObservation(pool, { ...sent, profiles: [profile, { ...profile, engine: 'codex' }] } as MachineObservation,
+ { team: false, now: NOW, preparable: () => true })
+ expect(kept.profiles).toEqual([profile])
+ })
+})
+
describe('a machine\'s reading as a report stores it (DB 2.5)', () => {
const { receivedAt: _receivedAt, ...sent } = observation
const pool = (extra: Partial<ContributedMachine> = {}): ContributedMachine => ({ machineId: 'host', name: 'Mac', contributorId: 'owner',
@@ -261,3 +288,7 @@ describe('a machine\'s reading as a report stores it (DB 2.5)', () => {
expect(readingOnly(before, team)).toBe(false)
})
})
+
+it('names the default account the same way the CLI and Desktop do', () => {
+ expect(defaultProfileId('m', 'claude')).toBe('71dc90339553114c')
+})
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 972cd3dc0..b29704d95 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import { z } from 'zod'
import { engineUnusable } from './engineHealth.js'
import { MAX_HARNESSES, tokensByModelSchema } from './costs/tokens.js'
@@ -69,6 +70,14 @@ export const cleanupOverdue = (cleanup: MachineCleanup, now: number): boolean =>
export type RemovalEnd = 'confirmed' | 'offline' | 'timedOut'
/** Older contributions may name engines that Swarm no longer starts. Their fresh
* observation lists the supported engines that are actually installed. */
+/** The default account's id for an engine on a machine: the CLI and Desktop compute the same 16 hex (sha256 of `machine:engine:default`). */
+export const defaultProfileId = (machineId: string, engine: string): string =>
+ createHash('sha256').update(`${machineId}:${engine}:default`).digest('hex').slice(0, 16)
+
+/** A profile id as the agent stores it: the default account (literal or hashed) is absent. */
+export const storedProfileId = (machineId: string, engine: string, profileId: string | undefined): string | undefined =>
+ profileId === undefined || profileId === 'default' || profileId === defaultProfileId(machineId, engine) ? undefined : profileId
+
export function contributedEngines(pool: ContributedMachine, observation: MachineObservation | undefined = pool.observation): string[] {
const supported = (engine: string) => engine === 'claude' || engine === 'codex'
return pool.engines.some(engine => !supported(engine))
@@ -156,6 +165,11 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16
/** What this host can launch beyond workers: `leadStart`, a project's Product Manager (leadStart.ts). Absent from hosts
* before it, which are never given one. */
capabilities: z.array(z.string().regex(/^[a-zA-Z]{1,40}$/)).max(16).optional(),
+ /** The accounts a Product Manager could move to, per engine (cli superTabs/profiles): `id` is a stable 16-hex handle,
+ * `label` a name its owner chose (never an email, so no '@'), `leftPercent` the allowance left. Absent from hosts before it. */
+ profiles: z.array(z.object({ engine: z.enum(['claude', 'codex']), id: z.string().regex(/^[0-9a-f]{16}$/),
+ label: z.string().min(1).max(40).refine(l => !l.includes('@')), leftPercent: z.number().int().min(0).max(100).nullable(),
+ resetsAt: z.string().datetime().nullable() }).strict()).max(16).optional(),
}).strict()
export type MachineObservation = z.infer<typeof machineObservationSchema>
@@ -177,13 +191,15 @@ export const preparableStart = (start: AgentStart, machineId: string): boolean =
*/
export function storedObservation(pool: ContributedMachine, observation: MachineObservation,
opts: { team: boolean; now: number; preparable: (startId: string) => boolean }): StoredReading {
- const { privacy: reported, harnessProgress, harnessTokens, preparingStartIds, ...reading } = observation
+ const { privacy: reported, harnessProgress, harnessTokens, preparingStartIds, profiles, ...reading } = observation
const running = (id: string) => observation.runningHarnessIds.includes(id)
const progress = harnessProgress && Object.fromEntries(Object.entries(harnessProgress).filter(([id]) => running(id)))
const tokens = harnessTokens && Object.fromEntries(Object.entries(harnessTokens).filter(([id]) => running(id)))
const preparing = preparingStartIds?.filter(opts.preparable)
const privacy = observedPrivacy(pool.observation?.privacy, reported, opts.team, opts.now)
- return { ...reading, quotas: observation.quotas.filter(q => contributedEngines(pool, observation).includes(q.engine)), receivedAt: opts.now,
+ const engines = contributedEngines(pool, observation)
+ return { ...reading, quotas: observation.quotas.filter(q => engines.includes(q.engine)), receivedAt: opts.now,
+ ...(profiles ? { profiles: profiles.filter(p => engines.includes(p.engine)) } : {}),
sessionKind: opts.team ? 'team' : 'computer', ...(privacy ? { privacy } : {}), ...(progress ? { harnessProgress: progress } : {}),
...(tokens ? { harnessTokens: tokens } : {}), ...(preparing ? { preparingStartIds: preparing } : {}) }
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index ca267a7b2..a6e426150 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -63,6 +63,14 @@ export interface Agent {
* close it (agent.stopRefused). */
idleStop?: { previous: 'awaiting' | 'keep' | null }
releaseId?: string
+ /** A person's request to move this Product Manager to another engine or account (lead.switch), carried out by its host.
+ * `id` is the operation that asked; `claimedUntil` is set once the host took it (agent.switchClaim). */
+ /** The switch request the last rebind settled, until its result arrives: that result is the one line the chat gets, and
+ * it still tells the machine owner who asked. */
+ switchLanded?: { id: string; requestedBy: string }
+ switchRequest?: { id: string; engine: string; profileId: string; model?: string; effort?: string; requestedBy: string; at: string; claimedUntil?: string }
+ /** The account it runs in on its machine once a switch moved it; absent for the machine's default account. */
+ profileId?: string
/** Captured from the original Swarm launch, never inferred from a later live session with the same id. */
startedSession?: { creationId: string; sessionId: string; createdAt: string }
/** The model on the Swarm's grid its start named, which its engine never reports. Kept here because a command does not
@@ -533,6 +541,10 @@ export const NOTICE_READERS = {
// longer written (the automatic review's `auto-review`, a routing rule's `rule`) read as people's, as any kind not listed does.
'review-capacity': 'recipients',
// #2177's rulings: a failed start and a terminal's alert or typed input stay the people's to see.
+ // A PM switch nobody answered, in its project chat (tidy.ts staleSwitches).
+ switch: 'people',
+ // The machine owner's one line when another person moves a PM onto one of their non-default accounts (commands.ts agent.switchResult).
+ 'pm-switch-notice': 'people',
'start-timeout': 'people', 'terminal-alert': 'people', 'terminal-input': 'people',
} as const satisfies Record<string, 'people' | 'recipients' | 'agent'>
const readersOf = (kind: unknown): 'people' | 'recipients' | 'agent' =>
@@ -796,6 +808,16 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
const privacy = pool.observation?.privacy
if (privacy && 'detail' in privacy && !(actor.kind === 'person' && actor.userId === pool.contributorId)) delete (privacy as { detail?: string }).detail
}
+ // A machine's accounts (labels, percent left) are for those who may switch a PM running there: its owner, and the owners of
+ // projects whose PM runs on it. Agents and everyone else read the machine without them.
+ for (const pool of visible.machines ?? []) {
+ if (!pool.observation?.profiles) continue
+ const there = state.agents.filter(a => a.machineId === pool.machineId)
+ const owners = new Set(there.length ? there.map(a => a.machineOwnerId) : [pool.contributorId])
+ const mayMove = actor.kind === 'person' && (owners.has(actor.userId) ||
+ there.some(a => projectsOf(state).some(p => p.ownerId === actor.userId && state.conversations.some(c => c.id === p.leadConversationId && c.leadId === a.id))))
+ if (!mayMove) delete pool.observation.profiles
+ }
expireRemovals(visible, now)
// A read never hands out the cleanup records it just applied (read/hostRows.ts delivers them to the machine's host).
delete visible.machineCleanups
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index ff57c2f35..ebfb648d0 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -257,6 +257,8 @@ export interface HostAgentRow {
lead: boolean
/** New: lets the host decide what it may read without a full Swarm read. */
leadsConversationId: string | null
+ /** The conversation this agent leads, when it is a project's Product Manager. */
+ ledConversationId: string | null
stopRequested: boolean
observers: Array<{ email: string; userId: string }>
/** Its session is confidential in some Swarm: the host refuses every share of it, ordinary ones too (Critical 1). */
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index 628e0c012..a9abcf714 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -91,6 +91,9 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
lead: !!ledProject(state, target.id),
// Removed (model.ts leadsRemoved); an older CLI still reads the field, so it stays, always empty.
leadsConversationId: null,
+ // 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,
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 })),
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index f042f3b0c..437b246b1 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -786,6 +786,8 @@ export class SuperTabStore {
// And their one Buddy chat, which takes it too (spec: Guard).
if (asked && command.delegate) swarmChat(asked.personId)
}
+ // A switch's result tells the machine's owner in their one Buddy chat, quiet or not (commands.ts agent.switchResult).
+ if (command.type === 'agent.switchResult') swarmChat(state.agents.find(a => a.id === command.agentId)?.machineOwnerId)
// A project's sharing ends its sessions in the one Buddy chats of whoever loses it (commands.ts endLostProjectSessions).
if (command.type === 'project.sharing') {
for (const owner of new Set([...state.agents.filter(a => a.buddySession?.projectId === command.projectId).map(a => a.buddyOf!.personId),
diff --git a/backend/src/superTabs/terminal.test.ts b/backend/src/superTabs/terminal.test.ts
index 2eccf7cb5..0f8956bcc 100644
--- a/backend/src/superTabs/terminal.test.ts
+++ b/backend/src/superTabs/terminal.test.ts
@@ -273,6 +273,9 @@ describe('terminal alerts', () => {
const lead = s.run({ type: 'agent.alert', agentId: s.lead, alert: 'limit', active: true }, as(s.lead))
expect(s.state.agents.find(a => a.id === s.lead)!.limitedUntil).toBe(new Date(1_000_000 + 3_600_000).toISOString())
expect(lead.messages[0]).toMatchObject({ conversationId: 'lead', recipients: [] })
+ // The PM's line names it with no time (Desktop shows `limitedUntil` in local time); a worker's row keeps the UTC time.
+ expect(lead.messages[0]).toMatchObject({ text: `${name(s, s.lead)} hit a usage limit.`, source: { lead: true, limitedUntil: expect.any(String) } })
+ expect(effects.messages[0].source).not.toHaveProperty('lead')
})
it('tells the Lead when an agent cannot get answers from its model, once per episode', () => {
diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.ts
index ecdc7c495..186c3ae5c 100644
--- a/backend/src/superTabs/terminal.ts
+++ b/backend/src/superTabs/terminal.ts
@@ -164,7 +164,11 @@ export function terminalAlert(state: SuperTabState, actor: Actor, sender: Author
if (command.alert === 'limit') {
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()
- text = `${nameOf(target)} hit a usage limit. Routing skips it until ${target.limitedUntil.slice(11, 16)} UTC.`
+ // 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)) {
+ 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.`
}
// Its engine has been retrying its model for 10 minutes (2026-10-24: a Builder on a small local model retried for an
// hour while its Lead waited on it).
diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.ts
index fb39e77be..7bea43290 100644
--- a/backend/src/superTabs/tidy.test.ts
+++ b/backend/src/superTabs/tidy.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { agentOnly, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'
-import { ARCHIVE_QUIET_MS, archivable, IDLE_NOTICE_MS, idleNotices, linkPending, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'
+import { ARCHIVE_QUIET_MS, archivable, IDLE_NOTICE_MS, idleNotices, linkPending, staleSwitches, SWITCH_UNCLAIMED_MS, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'
const MINUTE = 60_000
const START = Date.parse('2026-10-27T08:00:00.000Z')
@@ -221,3 +221,26 @@ describe('which reviews nobody reviews may close', () => {
author: { kind: 'agent', id: 'L' }, source: { kind: 'auto-archive' }, text: 'Closed: #2288 merged, #2290 closed; no Swarm review is needed now.' })
})
})
+
+describe('staleSwitches', () => {
+ const request = (patch = {}) => ({ id: 'op1', engine: 'codex', profileId: 'p', requestedBy: 'p', at: iso(START), ...patch })
+ const asked = (switchRequest?: Agent['switchRequest']) => { const state = swarm(); target(state, 'L').switchRequest = switchRequest; return state }
+ const line = { conversationId: 'lead', recipients: [], text: "Couldn't switch the PM: its machine did not answer." }
+
+ it('drops a request nobody claimed in 2 minutes, with one line in the project chat', () => {
+ const state = asked(request())
+ expect(staleSwitches(state, START + SWITCH_UNCLAIMED_MS - 1)).toEqual([])
+ expect(target(state, 'L').switchRequest).toBeDefined()
+ expect(staleSwitches(state, START + SWITCH_UNCLAIMED_MS)).toMatchObject([line])
+ expect(target(state, 'L').switchRequest).toBeUndefined()
+ expect(staleSwitches(state, START + 3 * SWITCH_UNCLAIMED_MS)).toEqual([])
+ })
+
+ it('keeps a claimed request while its lease lasts and drops it once it lapsed', () => {
+ const state = asked(request({ claimedUntil: iso(START + 15 * MINUTE) }))
+ expect(staleSwitches(state, START + 10 * MINUTE)).toEqual([])
+ expect(target(state, 'L').switchRequest).toBeDefined()
+ expect(staleSwitches(state, START + 15 * MINUTE)).toMatchObject([line])
+ expect(target(state, 'L').switchRequest).toBeUndefined()
+ })
+})
diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.ts
index dbf4b5171..c866a96b7 100644
--- a/backend/src/superTabs/tidy.ts
+++ b/backend/src/superTabs/tidy.ts
@@ -2,7 +2,7 @@ import { onlyStepsHeld } from './steps.js'
import { isBuddy } from './buddies.js'
import { agentDisplayName } from './agentNames.js'
import { activeWork, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
-import { agentProjectId, groupProject, projectsOf } from './projects.js'
+import { agentProjectId, groupProject, ledProject, projectsOf } from './projects.js'
import { toLead } from './terminal.js'
// Nobody has to tidy a Swarm by hand (roadmap, December). The server stops no agent (project instructions, phase 4): an agent
@@ -12,6 +12,9 @@ import { toLead } from './terminal.js'
/** How long an agent has no open task before its coordinator is told. */
export const IDLE_NOTICE_MS = 15 * 60_000
+/** How long a PM's switch request waits for its machine to claim it (agent.switchClaim) before it is dropped. */
+export const SWITCH_UNCLAIMED_MS = 2 * 60_000
+
const time = (value: string | undefined) => value === undefined ? undefined : Date.parse(value)
/** The loaded groups an agent belongs to or worked in. */
@@ -73,6 +76,26 @@ export function idleNotices(state: SuperTabState, projectId: string, now: number
return rows
}
+/** Whether a switch request ran out: nobody claimed it in 2 minutes, or its claim's lease lapsed. */
+export const switchExpired = (request: NonNullable<Agent['switchRequest']>, now: number): boolean =>
+ now >= (request.claimedUntil === undefined ? Date.parse(request.at) + SWITCH_UNCLAIMED_MS : Date.parse(request.claimedUntil))
+
+/** A switch request that ran out is dropped (the PM keeps its engine), and its project chat says so once: the host that never
+ * answered cannot. Run by the liveness sweep, which any machine's report drives, as the PM's own host may be the one down. */
+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
+ if (!switchExpired(request, now)) continue
+ delete pm.switchRequest
+ rows.push({ id: stableId('switch-stale', pm.id, request.id), conversationId: project.leadConversationId, 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 } })
+ }
+ return rows
+}
+
/** A linked task (`reviewOf`) the Swarm does not archive by itself: none of its checks carries evidence, nobody cancelled it,
* and the task it links to is still going. Once that task is done or cancelled the link is moot. By hand any agent of the
* project or a person archives it (project instructions, phase 4). */
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index 6f13bc278..8d011d233 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -143,7 +143,7 @@ export const PRODUCT_USAGE_SETUP_METRICS = [...PRODUCT_USAGE_SURFACES.flatMap(su
* codes (listed below). Codes only, never a message. */
export const LAUNCH_ERROR_CODES = [
// What a new harness asked for, refused before anything starts (core/agents/launches.ts, lib/engineLaunch.ts).
- 'invalid_codex_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session',
+ 'invalid_codex_home', 'invalid_claude_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session',
'invalid_started_by', 'agent_unsupported', 'invalid_runtime_profile', 'grid_engine_unsupported', 'codex_cli_too_old',
'invalid_launch_model', 'launch_model_unsupported',
// A new project's folder (lib/projectFolder.ts) and the launch's durable receipt (lib/agentCreationReceipt.ts).
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 17edf760c..43a4edd2e 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -158,6 +158,8 @@ export class BackendSocket {
grid: GridLaunchOverride | null
/** A Codex CODEX_HOME folder to launch this agent against instead of `~/.codex`; codex only. */
codexHome: string | null
+ /** A Claude CLAUDE_CONFIG_DIR folder (a profile) to launch this agent against; claude only. Absent for the default account. */
+ claudeHome?: string | null
/** The domain-specific harness to create this agent as (installed here, base engine = `engine`). */
dsh: string | null
/** The message the session opens with, already submitted (`FIRST_PROMPT_ARGS` in engineLaunch.ts);
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index 397449055..097b0f941 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -123,7 +123,7 @@ export function createAgentCreator({
const stale = () => ({ ok: false as const, error: 'LAUNCH_AUTHORITY_CHANGED', unavailable: 'launch', detail: 'Waiting for the original launch request’s authority.' })
if (!authority.current()) return stale()
if (input.swarmRole && !swarmLaunch) return { ok: false, error: 'SWARM_SKILL_FAILED', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' }
- let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy, parentAgentId, launchModel } = input
+ let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, claudeHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy, parentAgentId, launchModel } = input
let createBackend = initialBackend
if (!createBackend && recoverBackend) {
createBackend = await recoverBackend()
@@ -262,7 +262,7 @@ export function createAgentCreator({
if (emptyBefore && materialized.created.some((item) => item.startsWith('template'))) {
try {
// In the agent's own profile when it has one: that config.toml is the one a Codex agent reads.
- folderTrust(engine, codexHome)?.record(cwd)
+ folderTrust(engine, engine === 'claude' ? claudeHome : codexHome)?.record(cwd)
} catch (error) { console.warn(`[dsh] pre-trust ${cwd} · ${error instanceof Error ? error.message : error}`) }
}
} catch (error) {
@@ -333,7 +333,7 @@ export function createAgentCreator({
if ((empty || trustSwarmFolder) && workspaceIdentity() === originalWorkspace) {
files.verify()
const environment = native ? { ...native.environment, ...gridLaunch?.env, ...dshEnv } : undefined
- const profile = engine === 'codex' && environment ? nativeHookLocations(environment).CODEX_HOME : codexHome
+ const profile = engine === 'codex' && environment ? nativeHookLocations(environment).CODEX_HOME : engine === 'claude' ? claudeHome : codexHome
folderTrust(engine, profile, environment)?.record(cwd)
}
} catch (error) { console.warn(`[agent] pre-trust ${cwd} · ${error instanceof Error ? error.message : error}`) }
@@ -446,6 +446,7 @@ export function createAgentCreator({
gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
scmLaunchRecord: scmLaunchRecord ?? null,
codexHome,
+ claudeHome,
dsh,
dshRuntime: dsh ? label : null,
...(swarmSkill ? { swarmSkill } : {}),
diff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.ts
index 8ce934839..41dbc4f65 100644
--- a/cli/src/core/agents/fork.spec.ts
+++ b/cli/src/core/agents/fork.spec.ts
@@ -184,6 +184,11 @@ describe('forking an agent', () => {
if (engine === 'codex') expect(request.codexHome).toBe(finalHome)
})
+ it('keeps its source\'s Claude account on its row', async () => {
+ expect(await setup(source({ claudeHome: '/profiles/work' })).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ ok: true })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0]![0].claudeHome).toBe('/profiles/work')
+ })
+
it('does not open instruction files or install API notes while its harness waits for the Store', async () => {
vi.mocked(installedDsh).mockReturnValueOnce({ manifest: { name: 'Fixture' } } as never)
launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_UNAVAILABLE', detail: 'Waiting for the Store.', unavailable: 'store' })
diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.ts
index e16ab0af3..83d1657a3 100644
--- a/cli/src/core/agents/fork.ts
+++ b/cli/src/core/agents/fork.ts
@@ -196,6 +196,8 @@ export function createAgentForker({
scmLaunchRecord: source.scmLaunch ?? null,
codexHome: engine === 'codex' && built.overrides.native
? nativeHookLocations(built.overrides.native.environment).CODEX_HOME : source.codexHome ?? null,
+ // Its account, as its source's restart keeps it: on the row, or a restart of the fork runs on the default account.
+ claudeHome: source.claudeHome ?? null,
dshRuntime: source.dsh ? label : null,
dsh: source.dsh ?? null,
agent: source.agent ?? null,
diff --git a/cli/src/core/agents/launchAuthority.ts b/cli/src/core/agents/launchAuthority.ts
index f898c875b..cf61d43c8 100644
--- a/cli/src/core/agents/launchAuthority.ts
+++ b/cli/src/core/agents/launchAuthority.ts
@@ -4,7 +4,7 @@ import { terminalRouteKey } from '../../lib/terminalRuntime.js'
const identity = (row: RegisteredSession | undefined) => row && JSON.stringify([
row.registeredAt, row.boundAt, row.sessionId, row.engine, row.cwd, row.processIdentity,
- row.codexHome, row.dsh, row.dshRuntime, row.swarmSkill, row.agent, row.gridLaunch, row.scmLaunch,
+ row.codexHome, row.claudeHome, row.dsh, row.dshRuntime, row.swarmSkill, row.agent, row.gridLaunch, row.scmLaunch,
row.subscriptionModel, row.permissionMode, row.bypassPermission, row.active,
row.runtimes.map(terminalRouteKey).sort(), row.launch, row.externalResume,
])
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 2f05a4562..dfc1e4e72 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -252,6 +252,31 @@ describe('agent_create, refused before any pane exists', () => {
expect(vi.mocked(create!).mock.calls.map(([input]) => input.codexHome)).toEqual([null, null, null, null])
})
+ it('claudeHome is refused for codex and with a grid (INVALID_CLAUDE_HOME), and dropped when it is not a plain absolute path', async () => {
+ const { ask, create } = setup()
+ const refused = { error: 'INVALID_CLAUDE_HOME', detail: 'claudeHome is only valid for claude, without a grid' }
+ expect(await ask({ engine: 'codex', cwd: '/w', claudeHome: '/homes/claude' })).toStrictEqual(refused)
+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)
+ expect(await ask({ engine: 'claude', cwd: '/w', claudeHome: '/homes/claude' })).toStrictEqual(refused)
+ expect(create).not.toHaveBeenCalled()
+ for (const claudeHome of ['relative', '/with\nnewline', `/${'x'.repeat(4096)}`, 7]) await ask({ engine: 'claude', cwd: '/w', claudeHome })
+ expect(vi.mocked(create!).mock.calls.map(([input]) => 'claudeHome' in input)).toEqual([false, false, false, false])
+ })
+
+ it('claudeHome is accepted only when it is a profile this machine offers', async () => {
+ const { ask, create } = setup({ claudeHomeOffered: (home) => home === '/homes/offered' })
+ expect(await ask({ engine: 'claude', cwd: '/w', claudeHome: '/homes/other' })).toStrictEqual({ error: 'INVALID_CLAUDE_HOME', detail: 'claudeHome is not a Claude profile of this machine' })
+ expect(create).not.toHaveBeenCalled()
+ await ask({ engine: 'claude', cwd: '/w', claudeHome: '/homes/offered' })
+ expect(vi.mocked(create!).mock.calls[0][0]).toMatchObject({ claudeHome: '/homes/offered' })
+ })
+
+ it('claudeHome reaches the create input', async () => {
+ const { ask, create } = setup()
+ await ask({ engine: 'claude', cwd: '/w', claudeHome: '/homes/claude' })
+ expect(vi.mocked(create!).mock.calls[0][0]).toMatchObject({ engine: 'claude', claudeHome: '/homes/claude' })
+ })
+
it('a harness that is not an id, not installed here, a viewer, or not for this engine', async () => {
const { ask, create } = setup()
expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'not an id' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' })
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 875d93ec2..86043a42d 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -77,12 +77,14 @@ export interface LaunchRequestDeps {
guestCreate?: () => GuestCreate | null
/** Which Swarm roles and skill modes a start may ask for (superTabs/inCore/launch.ts); absent while the Swarm is off. */
swarmLaunch?: Pick<SwarmLaunch, 'role' | 'mode'>
+ /** Whether a `claudeHome` is a Claude profile of this machine (lib/claudeProfiles.ts claudeHomeOffered); absent, any is. */
+ claudeHomeOffered?: (claudeHome: string) => boolean
}
type Reply = (result: Record<string, unknown>) => void
type CreateInput = Parameters<CreateAgent>[0]
-export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget, guestCreate, swarmLaunch }: LaunchRequestDeps) {
+export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget, guestCreate, swarmLaunch, claudeHomeOffered }: LaunchRequestDeps) {
const validateInstalled = async (input: CreateInput, known?: ReturnType<typeof installedDsh>): Promise<{ error: string; detail: string } | null> => {
if (input.dsh) {
const installed = known ?? installedDsh(input.dsh)
@@ -148,7 +150,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
const swarmCheckout = swarmAgent && (projectFolder.source === 'remote' || (projectFolder.source === 'worktree' && local))
try {
// A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.
- const engineTrust = folderTrust(input.engine, input.codexHome)
+ const engineTrust = folderTrust(input.engine, input.codexHome ?? input.claudeHome ?? null)
if (engineTrust && (projectFolder.source === 'new' || swarmCheckout
|| (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {
engineTrust.record(preparedFolder)
@@ -171,7 +173,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// DSH trust is decided in cli.ts, where the template count is known; leave that to it.
try {
const empty = await readdir(input.cwd).then((names) => names.length === 0, () => false)
- if (empty) folderTrust(input.engine, input.codexHome)?.record(input.cwd)
+ if (empty) folderTrust(input.engine, input.codexHome ?? input.claudeHome ?? null)?.record(input.cwd)
} catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }
}
const result = await invoke(preparedFolder ? { ...input, cwd: preparedFolder, scmLaunchRecord } : input)
@@ -393,6 +395,20 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
reply({ error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' })
return
}
+ // Claude profiles (CLAUDE_CONFIG_DIR) follow the same rule: Claude only, without a grid.
+ const rawClaudeHome = typeof payload.claudeHome === 'string' ? payload.claudeHome : null
+ const claudeHome = rawClaudeHome && rawClaudeHome.startsWith('/') && rawClaudeHome.length <= 4096
+ && !/[\x00-\x1f\x7f]/.test(rawClaudeHome)
+ ? rawClaudeHome
+ : null
+ if (claudeHome && (engine !== 'claude' || grid.state === 'ok')) {
+ reply({ error: 'INVALID_CLAUDE_HOME', detail: 'claudeHome is only valid for claude, without a grid' })
+ return
+ }
+ if (claudeHome && claudeHomeOffered && !claudeHomeOffered(claudeHome)) {
+ reply({ error: 'INVALID_CLAUDE_HOME', detail: 'claudeHome is not a Claude profile of this machine' })
+ return
+ }
// A DSH is refused, never approximated: an agent created as its plain base engine would look
// like it worked and have none of the skills the user picked the tile for.
let dsh: string | null = null
@@ -522,6 +538,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
resumeSessionId,
takeOver,
// Only when set: a person's create keeps the fingerprint its receipt was recorded with before the field.
+ ...(claudeHome ? { claudeHome } : {}),
...(payload.startedBy === 'agent' ? { startedBy: 'agent' as const } : {}),
...(launchModel.state === 'ok' ? { launchModel: launchModel.launchModel } : {}),
...(parentAgentId ? { parentAgentId } : {}),
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index e8457de71..7c8fad9b6 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -729,6 +729,7 @@ export const MODELS_REQUESTS = [
'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop',
'grid_fleet_run', 'grid_fleet_cancel', 'grid_swarm_sync', 'grid_swarm_api_share', 'grid_swarm_api_shares', 'grid_swarm_offer', 'grid_swarm_offers', 'grid_swarm_heal',
'api_connections', 'codex_profiles_list', 'codex_profile_link',
+ 'claude_profiles_list', 'claude_profile_link', 'swarm_account_offer',
] as const
const MINUTE = 60_000
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index cbda2d1da..87eb5d962 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -50,6 +50,7 @@ import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'
import { enableOffThreadExec } from '../lib/offThreadExec.js'
import type { AppSwarms } from '../cable/cableSession.js'
import type { UnreadNotification } from '../lib/notificationRead.js'
+import { claudeHomeOffered } from '../lib/claudeProfiles.js'
import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from '../lib/registry.js'
import { engineSessionTitle } from '../lib/sessionTitle.js'
import { machineNames } from '../lib/machineNames.js'
@@ -3009,6 +3010,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// (core/agents/launches.ts). The orchestrator and the cable create and fork through the socket's slots.
const launches = createLaunchRequests({
...(swarm ? { swarmLaunch: swarm.SWARM_LAUNCH } : {}),
+ claudeHomeOffered: (home) => claudeHomeOffered(home, machineIdNow()),
receipts: new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations')),
createAgent: () => backend.onCreateAgent, forkAgent: () => backend.onForkAgent,
prepareCreate: creator.prepare, prepareEngine: prepareNativeLaunch,
diff --git a/cli/src/engines/nativeLaunch.spec.ts b/cli/src/engines/nativeLaunch.spec.ts
index 5833d2c26..da21cc7dd 100644
--- a/cli/src/engines/nativeLaunch.spec.ts
+++ b/cli/src/engines/nativeLaunch.spec.ts
@@ -305,7 +305,16 @@ it.each([
expect(await result.launch.prepareHooks(19473, () => true, kind === 'generated' ? { [variable]: home } : {})).toBe(true)
expect(result.launch.environment[variable]).toBe(home)
expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
- expect(confirmHome).not.toHaveBeenCalled()
+ // An explicit Claude profile is adopted (above); Codex's and generated ones belong to their row.
+ expect(confirmHome).toHaveBeenCalledTimes(engine === 'claude' && kind === 'explicit' ? 2 : 0)
+})
+
+it('an explicit claudeHome is adopted as a known home, so its transcripts bind', async () => {
+ const confirmHome = vi.fn()
+ const result = await inspectNativeLaunch('claude', { claudeHome: '/fixture/profile' }, { confirmHome })
+ if (!result.ok) throw Error(result.detail)
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(confirmHome).toHaveBeenCalledWith('claude', '/fixture/profile')
})
// Windows has no launch script to probe Codex's owned-process flag before each run (engines/kit/launchStartup.ts):
diff --git a/cli/src/engines/nativeLaunch.ts b/cli/src/engines/nativeLaunch.ts
index 9c26f4ade..2e8feaf8c 100644
--- a/cli/src/engines/nativeLaunch.ts
+++ b/cli/src/engines/nativeLaunch.ts
@@ -218,6 +218,8 @@ export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLau
// adopting them globally would refresh a held package's hooks at boot
// before its Store dependencies are ready.
if ((engine === 'claude' || engine === 'codex') && home === implicitHome) deps.confirmHome?.(engine, home)
+ // A Claude profile is adopted too, or its transcripts fall outside every root and the agent never binds.
+ else if (engine === 'claude' && source.claudeHome === home) deps.confirmHome?.(engine, home)
if (!executable.current() || !owner() || [...dependencies, ...confirmed].some(proof => !proof.current())) return false
// The command locations and the proofs become dispatch authority together.
// A failed or pending replacement can never expose B with A's proof set.
diff --git a/cli/src/lib/accountOffers.ts b/cli/src/lib/accountOffers.ts
new file mode 100644
index 000000000..e9fe56135
--- /dev/null
+++ b/cli/src/lib/accountOffers.ts
@@ -0,0 +1,62 @@
+/**
+ * The accounts this machine's owner offered the Swarm: other people's Product Managers on this machine can then run on them and
+ * spend their usage. One explicit, reversible choice, kept apart from the folders a machine merely knows (linked in New Harness,
+ * made by Add Claude account, found by discovery). The default account of a contributed engine needs no entry.
+ *
+ * Kept by real folder, on this machine only; the file holds paths, so it never leaves it. A file that cannot be read offers
+ * nothing: a lost offer costs the owner one tap, a wrong one spends their account.
+ */
+import { randomUUID } from 'crypto'
+import { closeSync, constants, fchmodSync, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'fs'
+import { join } from 'path'
+import { env } from '../config/env.js'
+import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
+
+export type OfferEngine = 'claude' | 'codex'
+
+const FILE = join(env.ADAPTER_DATA_DIR, 'swarm-account-offers.json')
+/** Far above what a machine reports (8 per engine); only stops a runaway file. A withdraw is what removes an entry. */
+export const MAX_OFFERS = 64
+
+const keyOf = (engine: OfferEngine, folder: string) => `${engine}:${folder}`
+
+function read(): Set<string> {
+ try {
+ const raw = JSON.parse(readPrivateStateFile(FILE, 1024 * 1024)) as unknown
+ if (Array.isArray(raw)) return new Set(raw.filter((k): k is string => typeof k === 'string').slice(0, MAX_OFFERS))
+ } catch { /* None offered: see above. */ }
+ return new Set()
+}
+
+function write(keys: Set<string>): void {
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
+ hardenPrivateStateFileIfPresent(FILE)
+ const temporary = `${FILE}.${process.pid}.${randomUUID()}.tmp`
+ let renamed = false
+ try {
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(fd, JSON.stringify([...keys], null, 2))
+ fchmodSync(fd, 0o600)
+ fsyncSync(fd)
+ } finally { closeSync(fd) }
+ renameSync(temporary, FILE)
+ renamed = true
+ } finally { if (!renamed) rmSync(temporary, { force: true }) }
+}
+
+/** The real folders offered for [engine]. */
+export function offeredFolders(engine: OfferEngine): Set<string> {
+ const prefix = keyOf(engine, '')
+ return new Set([...read()].filter(k => k.startsWith(prefix)).map(k => k.slice(prefix.length)))
+}
+
+/** Records the owner's choice for a real folder; false when the list is full. Synchronous, in the one daemon that writes it. */
+export function recordOffer(engine: OfferEngine, folder: string, offered: boolean): boolean {
+ const keys = read(), key = keyOf(engine, folder)
+ if (offered === keys.has(key)) return true
+ if (offered && keys.size >= MAX_OFFERS) return false
+ if (offered) keys.add(key); else keys.delete(key)
+ write(keys)
+ return true
+}
diff --git a/cli/src/lib/accountUsage.spec.ts b/cli/src/lib/accountUsage.spec.ts
index 67c6a9e8d..53f53eb3e 100644
--- a/cli/src/lib/accountUsage.spec.ts
+++ b/cli/src/lib/accountUsage.spec.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -9,6 +10,7 @@ import {
readAccountUsage,
type AccountUsageDeps,
} from './accountUsage.js'
+import { claudeKeychainAccount, claudeKeychainService, readClaudeKeychain } from './agentCredentials.js'
let home: string
@@ -192,3 +194,65 @@ describe('readAccountUsage', () => {
expect(readings.map((r) => r.outcome)).toEqual(['signedOut', 'signedOut'])
})
})
+
+describe('usage per profile', () => {
+ const sha8 = (text: string) => createHash('sha256').update(text).digest('hex').slice(0, 8)
+
+ it('names the Keychain service after the config dir as given', () => {
+ expect(claudeKeychainService('/x/home', {})).toBe(`Claude Code-credentials-${sha8('/x/home')}`)
+ expect(claudeKeychainService(undefined, {})).toBe('Claude Code-credentials')
+ expect(claudeKeychainService('', {})).toBe('Claude Code-credentials')
+ })
+
+ it('lets CLAUDE_SECURESTORAGE_CONFIG_DIR override the dir, and empty means the plain name', () => {
+ expect(claudeKeychainService('/x/home', { CLAUDE_SECURESTORAGE_CONFIG_DIR: '/y' })).toBe(`Claude Code-credentials-${sha8('/y')}`)
+ expect(claudeKeychainService('/x/home', { CLAUDE_SECURESTORAGE_CONFIG_DIR: '' })).toBe('Claude Code-credentials')
+ })
+
+ it('uses USER as the Keychain account when it is a plain name, else the placeholder', () => {
+ expect(claudeKeychainAccount({ USER: 'ana.b-1_x' })).toBe('ana.b-1_x')
+ expect(claudeKeychainAccount({ USER: 'a b' })).toBe('claude-code-user')
+ expect(claudeKeychainAccount({})).toMatch(/^[a-zA-Z0-9._-]+$|^claude-code-user$/)
+ })
+
+ it('the keychain read passes -a and -s', async () => {
+ // A fake `security` first on PATH, so nothing touches the real Keychain.
+ const bin = join(home, 'bin')
+ mkdirSync(bin)
+ writeFileSync(join(bin, 'security'), '#!/bin/sh\nprintf "%s\\n" "$@" > "$(dirname "$0")/args"\necho \'{}\'\n', { mode: 0o755 })
+ const path = process.env.PATH
+ process.env.PATH = `${bin}:${path}`
+ try {
+ expect(await readClaudeKeychain({ platform: 'darwin', configDir: '/x/home' })).toBe('{}')
+ } finally {
+ process.env.PATH = path
+ }
+ const { readFileSync } = await import('node:fs')
+ const args = readFileSync(join(bin, 'args'), 'utf8').trim().split('\n')
+ expect(args[args.indexOf('-a') + 1]).toBe(claudeKeychainAccount())
+ expect(args[args.indexOf('-s') + 1]).toBe(`Claude Code-credentials-${sha8('/x/home')}`)
+ })
+
+ it('a Claude profile reads <dir>/.credentials.json and <dir>/.claude.json, and only Claude', async () => {
+ write('p/.credentials.json', { claudeAiOauth: { accessToken: CLAUDE_TOKEN } })
+ write('p/.claude.json', { oauthAccount: { accountUuid: 'acct-123', emailAddress: '[email protected]' } })
+ const { calls, fetchImpl } = vendor()
+ const readings = await readAccountUsage(deps({ fetchImpl, claudeHome: join(home, 'p') }))
+ expect(readings).toEqual([expect.objectContaining({ provider: 'claude', account: accountKey('claude', 'acct-123'), email: '[email protected]', outcome: 'answered' })])
+ expect(calls.map((c) => c.url)).toEqual([CLAUDE_USAGE_URL])
+ })
+
+ it('a Codex profile reads <dir>/auth.json, and only Codex', async () => {
+ write('c/auth.json', { tokens: { access_token: CODEX_TOKEN, account_id: 'acct-123' } })
+ const { calls, fetchImpl } = vendor()
+ const readings = await readAccountUsage(deps({ fetchImpl, codexHome: join(home, 'c') }))
+ expect(readings).toEqual([expect.objectContaining({ provider: 'codex', account: accountKey('codex', 'acct-123') })])
+ expect(calls.map((c) => c.url)).toEqual([CODEX_USAGE_URL])
+ })
+
+ it('`only` limits a default reading to one provider; both homes read both', async () => {
+ expect((await readAccountUsage(deps({ only: 'codex' }))).map((r) => r.provider)).toEqual(['codex'])
+ expect((await readAccountUsage(deps({ only: 'claude' }))).map((r) => r.provider)).toEqual(['claude'])
+ expect((await readAccountUsage(deps({ claudeHome: home, codexHome: home }))).map((r) => r.provider)).toEqual(['claude', 'codex'])
+ })
+})
diff --git a/cli/src/lib/accountUsage.ts b/cli/src/lib/accountUsage.ts
index c3db7d51d..b386188c1 100644
--- a/cli/src/lib/accountUsage.ts
+++ b/cli/src/lib/accountUsage.ts
@@ -25,6 +25,7 @@
*/
import { createHash } from 'node:crypto'
import { homedir } from 'node:os'
+import { join } from 'node:path'
import {
asRecord,
claudeProfilePath,
@@ -86,6 +87,11 @@ export function accountKey(provider: UsageProviderId, accountId: string): string
* network. Production passes nothing. */
export interface AccountUsageDeps {
home?: string
+ /** A Claude profile's CLAUDE_CONFIG_DIR / a Codex profile's CODEX_HOME. Given alone, it limits the reading to that provider. */
+ claudeHome?: string
+ codexHome?: string
+ /** Read one provider's default account only. */
+ only?: UsageProviderId
platform?: NodeJS.Platform
fetchImpl?: typeof fetch
readKeychain?: () => Promise<string | null>
@@ -94,18 +100,22 @@ export interface AccountUsageDeps {
/** Both accounts, asked at once — one being slow says nothing about the other. */
export async function readAccountUsage(deps: AccountUsageDeps = {}): Promise<AccountUsageReading[]> {
- return Promise.all([readClaude(deps), readCodex(deps)])
+ const only = deps.only ?? (deps.claudeHome && !deps.codexHome ? 'claude' : deps.codexHome && !deps.claudeHome ? 'codex' : undefined)
+ return Promise.all([
+ ...(only !== 'codex' ? [readClaude(deps)] : []),
+ ...(only !== 'claude' ? [readCodex(deps)] : []),
+ ])
}
async function readClaude(deps: AccountUsageDeps): Promise<AccountUsageReading> {
const home = deps.home ?? homedir()
// The Keychain first and the file second (`agentCredentials.ts`).
- const stored = (await readClaudeStored(deps))?.raw ?? null
+ const stored = (await readClaudeStored({ ...deps, configDir: deps.claudeHome }))?.raw ?? null
const oauth = asRecord(asRecord(parseJson(stored))?.claudeAiOauth)
const token = stringField(oauth?.accessToken)
// The account lives beside the token rather than in it: `~/.claude.json` is where Claude Code
// records who it is signed in as, on every platform.
- const profile = asRecord(asRecord(parseJson(await readText(claudeProfilePath(home))))?.oauthAccount)
+ const profile = asRecord(asRecord(parseJson(await readText(deps.claudeHome ? join(deps.claudeHome, '.claude.json') : claudeProfilePath(home))))?.oauthAccount)
const accountId = stringField(profile?.accountUuid)
const email = emailField(profile?.emailAddress)
const account = accountId ? accountKey('claude', accountId) : null
@@ -131,7 +141,7 @@ async function readClaude(deps: AccountUsageDeps): Promise<AccountUsageReading>
async function readCodex(deps: AccountUsageDeps): Promise<AccountUsageReading> {
const home = deps.home ?? homedir()
- const tokens = asRecord(asRecord(parseJson(await readText(codexAuthPath(home))))?.tokens)
+ const tokens = asRecord(asRecord(parseJson(await readText(deps.codexHome ? join(deps.codexHome, 'auth.json') : codexAuthPath(home))))?.tokens)
const token = stringField(tokens?.access_token)
const accountId = stringField(tokens?.account_id)
const account = accountId ? accountKey('codex', accountId) : null
diff --git a/cli/src/lib/agentCredentials.ts b/cli/src/lib/agentCredentials.ts
index 5299efb9a..bfb31cb24 100644
--- a/cli/src/lib/agentCredentials.ts
+++ b/cli/src/lib/agentCredentials.ts
@@ -9,8 +9,9 @@
* token anywhere but to its caller.
*/
import { execFile } from 'node:child_process'
+import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
-import { homedir } from 'node:os'
+import { homedir, userInfo } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
@@ -19,9 +20,33 @@ const execFileAsync = promisify(execFile)
/** The Keychain service Claude Code stores its OAuth sign-in under (no `CLAUDE_CONFIG_DIR`). */
export const CLAUDE_KEYCHAIN_SERVICE = 'Claude Code-credentials'
+/**
+ * The Keychain service Claude Code uses for a CLAUDE_CONFIG_DIR: the plain name, or the name plus
+ * `-<sha256(dir)[0..8]>` of the directory exactly as given. `CLAUDE_SECURESTORAGE_CONFIG_DIR` wins
+ * over the directory, and an empty one means the plain name — the rule of
+ * `desktop/lib/usage/usage_credentials.dart` `keychainService`.
+ */
+export function claudeKeychainService(configDir?: string, environment: NodeJS.ProcessEnv = process.env): string {
+ const secure = environment.CLAUDE_SECURESTORAGE_CONFIG_DIR
+ const hashed = secure ?? configDir
+ if (!hashed) return CLAUDE_KEYCHAIN_SERVICE
+ return `${CLAUDE_KEYCHAIN_SERVICE}-${createHash('sha256').update(hashed).digest('hex').slice(0, 8)}`
+}
+
+/**
+ * The Keychain account Claude Code writes under. Without `-a`, `security` answers with whichever
+ * item matches the service first, which can be a stale one under another user name.
+ */
+export function claudeKeychainAccount(environment: NodeJS.ProcessEnv = process.env): string {
+ const name = environment.USER ?? userInfo().username
+ return /^[a-zA-Z0-9._-]+$/.test(name) ? name : 'claude-code-user'
+}
+
/** Everything reading reaches outside for, so a spec never touches a real home or Keychain. */
export interface CredentialReadDeps {
home?: string
+ /** A profile's CLAUDE_CONFIG_DIR: its Keychain item and files instead of the default account's. */
+ configDir?: string
platform?: NodeJS.Platform
/** The Keychain item's secret (its JSON), or null. Production asks `security`. */
readKeychain?: () => Promise<string | null>
@@ -43,7 +68,7 @@ export async function readClaudeStored(
): Promise<{ raw: string; source: ClaudeCredentialSource } | null> {
const keychain = await readClaudeKeychain(deps)
if (keychain !== null) return { raw: keychain, source: 'keychain' }
- const file = await readText(claudeCredentialsPath(deps.home ?? homedir()))
+ const file = await readText(deps.configDir ? join(deps.configDir, '.credentials.json') : claudeCredentialsPath(deps.home ?? homedir()))
return file !== null ? { raw: file, source: 'file' } : null
}
@@ -55,7 +80,7 @@ export async function readClaudeKeychain(deps: CredentialReadDeps = {}): Promise
try {
const { stdout } = await execFileAsync(
'security',
- ['find-generic-password', '-s', CLAUDE_KEYCHAIN_SERVICE, '-w'],
+ ['find-generic-password', '-a', claudeKeychainAccount(), '-s', claudeKeychainService(deps.configDir), '-w'],
{ timeout: 5_000 },
)
const out = stdout.trim()
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 912dfb17d..f2b19e73b 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -86,6 +86,8 @@ export type AgentFrame = {
selectedModel: string | null
grid: GridFrameBlock | null
codexHome: string | null
+ /** The Claude profile folder (CLAUDE_CONFIG_DIR) this agent launched against; absent or null for the default account. */
+ claudeHome?: string | null
/** The workspace as its SCM describes it, with `kind` (`git`, or `none` for a folder no SCM claims);
* every other field is exactly what `agentProject` reports (scm/types.ts). */
project: ScmDescription | null
@@ -257,6 +259,7 @@ export async function agentFrame(
// engine's own login. Codex only; null is a real answer ("uses ~/.codex") for the same reason
// `grid: null` is above.
codexHome: s.codexHome ?? null,
+ claudeHome: s.claudeHome ?? null,
project,
gitContext,
// All five are real answers when null, for the reason the module doc gives: a frame that omits
diff --git a/cli/src/lib/apiConnectionsRpc.spec.ts b/cli/src/lib/apiConnectionsRpc.spec.ts
index f327271c9..bd623c117 100644
--- a/cli/src/lib/apiConnectionsRpc.spec.ts
+++ b/cli/src/lib/apiConnectionsRpc.spec.ts
@@ -15,7 +15,7 @@ function socketWithModels(): BackendSocket {
const socket = relaySocket('fixture')
const host = createServiceHost(emptyPorts())
// Served alone, under a name of its own: `models` is a port's name, which `serve` keeps for `start`.
- host.serve('launch-targets', (core) => launchTargetRequests(core, async () => {}), fakeCore(), ['api_connections', 'codex_profiles_list', 'codex_profile_link'])
+ host.serve('launch-targets', (core) => launchTargetRequests(core, async () => {}), fakeCore(), ['api_connections', 'codex_profiles_list', 'codex_profile_link', 'claude_profiles_list', 'claude_profile_link', 'swarm_account_offer'])
socket.serviceRouter = host.route
return socket
}
diff --git a/cli/src/lib/claudeProfiles.test.ts b/cli/src/lib/claudeProfiles.test.ts
new file mode 100644
index 000000000..ac1af7e39
--- /dev/null
+++ b/cli/src/lib/claudeProfiles.test.ts
@@ -0,0 +1,290 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import type * as ClaudeProfilesModule from './claudeProfiles.js'
+
+let dataDir = ''
+let home = ''
+const machineId = 'machine-1'
+
+async function loadModule(): Promise<typeof ClaudeProfilesModule> {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ return import('./claudeProfiles.js')
+}
+
+function account(folder: string, oauthAccount: Record<string, string>): void {
+ mkdirSync(folder, { recursive: true })
+ writeFileSync(join(folder, '.claude.json'), JSON.stringify({ oauthAccount }))
+}
+
+describe('claudeProfiles', () => {
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'claude-profiles-data-'))
+ // Real path: macOS's tmpdir sits behind a /var -> /private/var link. Always inside tmpdir, never the real home.
+ home = realpathSync(mkdtempSync(join(tmpdir(), 'claude-profiles-home-')))
+ })
+
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ rmSync(home, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ })
+
+ it('names the default account by its hex id, marked default, and pins the id vector', async () => {
+ const { listClaudeProfiles, profileId } = await loadModule()
+ expect(profileId('m', 'claude', 'default')).toBe('71dc90339553114c')
+ account(home, { displayName: 'Me' })
+ account(join(home, '.claude-work'), { displayName: 'Work' })
+ const profiles = listClaudeProfiles([], { home, environment: {}, machineId })
+ expect(profiles.map((p) => p.id)).toEqual([profileId(machineId, 'claude', 'default'), expect.stringMatching(/^[0-9a-f]{16}$/)])
+ expect(profiles[0]).toMatchObject({ path: home, label: 'Me', reportLabel: expect.not.stringContaining('Me'), offered: true, default: true })
+ expect(profiles[1]).not.toHaveProperty('default')
+ expect(profiles[1]).toMatchObject({ path: join(home, '.claude-work'), label: 'Work' })
+ })
+
+ it('lists the default account even with no .claude.json, and folders without Claude files are not offered', async () => {
+ const { listClaudeProfiles, profileId } = await loadModule()
+ mkdirSync(join(home, '.claude-empty'))
+ const profiles = listClaudeProfiles([], { home, environment: {}, machineId })
+ expect(profiles).toEqual([{ id: profileId(machineId, 'claude', 'default'), default: true, path: home, label: expect.any(String), reportLabel: expect.any(String), offered: true }])
+ })
+
+ it('finds the inherited CLAUDE_CONFIG_DIR and a folder holding only settings.json', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ const inherited = join(home, 'elsewhere')
+ mkdirSync(inherited)
+ writeFileSync(join(inherited, 'settings.json'), '{}')
+ const profiles = listClaudeProfiles([], { home, environment: { CLAUDE_CONFIG_DIR: inherited }, machineId })
+ expect(profiles.map((p) => p.path)).toEqual([home, inherited])
+ })
+
+ it('finds Orca profiles', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ const folder = join(home, 'Library/Application Support/orca/claude-profiles/ab12cd34-0000-4000-8000-000000000000/home')
+ account(folder, { emailAddress: '[email protected]' })
+ const orca = listClaudeProfiles([], { home, environment: {}, machineId })[1]
+ expect(orca).toMatchObject({ label: '[email protected]', reportLabel: 'Orca ab12' })
+ })
+
+ it('uses displayName for the label when present', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ account(join(home, '.claude-w'), { displayName: 'Work', emailAddress: '[email protected]' })
+ expect(listClaudeProfiles([], { home, environment: {}, machineId })[1]).toMatchObject({ label: 'Work', reportLabel: '.claude-w' })
+ })
+
+ it('never reports a person: the label is the folder, Orca by its id, Harness-made as Claude <n>', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ account(join(home, '.claude-w'), { displayName: 'Jane Doe', emailAddress: '[email protected]' })
+ account(join(home, '.harness/claude-profiles/acct1'), { displayName: 'Jane Doe' })
+ const rows = listClaudeProfiles([], { home, environment: {}, machineId })
+ expect(rows.map((p) => p.reportLabel)).toEqual(expect.arrayContaining(['.claude-w', 'Claude acct1']))
+ expect(JSON.stringify(rows.map((p) => p.reportLabel))).not.toContain('Jane')
+ })
+
+ it('offers only the default account and what the owner offered: linking or Add Claude account never does, and a withdraw takes it back', async () => {
+ const { listClaudeProfiles, linkClaudeProfile, offerAccount } = await loadModule()
+ const orca = join(home, 'Library/Application Support/orca/claude-profiles/ab12cd34-0000-4000-8000-000000000000/home')
+ account(orca, { displayName: 'Ken' })
+ account(join(home, '.claude-w'), {})
+ account(join(home, '.harness/claude-profiles/acct1'), {})
+ const offered = () => Object.fromEntries(listClaudeProfiles([], { home, environment: {}, machineId }).map((p) => [p.path === home ? 'default' : p.reportLabel, p.offered]))
+ expect(offered()).toEqual({ default: true, 'Orca ab12': false, '.claude-w': false, 'Claude acct1': false })
+ linkClaudeProfile(orca, machineId)
+ expect(offered()['Orca ab12']).toBe(false)
+ expect(offerAccount('claude', orca, true, { home, environment: {} })).toEqual({ offered: true })
+ expect(offered()['Orca ab12']).toBe(true)
+ expect(offerAccount('claude', orca, false, { home, environment: {} })).toEqual({ offered: false })
+ expect(offered()['Orca ab12']).toBe(false)
+ })
+
+ it('offers by the real folder, refuses the default account and a missing folder, and withdraws a folder that is gone', async () => {
+ const { offerAccount, listClaudeProfiles } = await loadModule()
+ const real = join(home, '.claude-w'), link = join(home, 'link-to-w')
+ account(real, {})
+ symlinkSync(real, link)
+ const where = { home, environment: {} }
+ expect(offerAccount('claude', link, true, where)).toEqual({ offered: true })
+ expect(listClaudeProfiles([], { ...where, machineId }).find((p) => p.path === real)?.offered).toBe(true)
+ expect(offerAccount('claude', home, true, where)).toEqual({ error: 'DEFAULT_ACCOUNT' })
+ expect(offerAccount('claude', join(home, 'ghost'), true, where)).toEqual({ error: 'NOT_FOUND' })
+ expect(offerAccount('claude', 'relative', true, where)).toEqual({ error: 'INVALID_PATH' })
+ expect(offerAccount('grok', real, true, where)).toEqual({ error: 'INVALID_ENGINE' })
+ rmSync(real, { recursive: true })
+ expect(offerAccount('claude', real, false, where)).toEqual({ offered: false })
+ })
+
+ it('a damaged offers file offers nothing', async () => {
+ const { offerAccount, listClaudeProfiles } = await loadModule()
+ const folder = join(home, '.claude-w')
+ account(folder, {})
+ offerAccount('claude', folder, true, { home, environment: {} })
+ writeFileSync(join(dataDir, 'swarm-account-offers.json'), '{not json', { mode: 0o600 })
+ expect(listClaudeProfiles([], { home, environment: {}, machineId }).find((p) => p.path === folder)?.offered).toBe(false)
+ })
+
+ it('drops a report label containing @', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ account(join(home, '.claude-w'), { displayName: '[email protected]' })
+ const profile = listClaudeProfiles([], { home, environment: {}, machineId })[1]
+ expect(profile).toMatchObject({ label: '[email protected]', reportLabel: '.claude-w' })
+ })
+
+ it('falls back to a plain word when even the folder name has an @', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ account(join(home, '[email protected]'), {})
+ expect(listClaudeProfiles([], { home, environment: {}, machineId })[1].reportLabel).toBe('Claude')
+ })
+
+ it('cuts it at 40 characters', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ account(join(home, '.claude-' + 'x'.repeat(60)), {})
+ expect(listClaudeProfiles([], { home, environment: {}, machineId })[1].reportLabel).toBe(('.claude-' + 'x'.repeat(60)).slice(0, 40))
+ })
+
+ it('ignores a malformed or oversized account file', async () => {
+ const { listClaudeProfiles } = await loadModule()
+ mkdirSync(join(home, '.claude-bad'))
+ writeFileSync(join(home, '.claude-bad', '.claude.json'), 'not json')
+ expect(listClaudeProfiles([], { home, environment: {}, machineId })[1]).toMatchObject({ label: '.claude-bad' })
+ })
+
+ it('links a folder and keeps it across reads', async () => {
+ const { linkClaudeProfile, listClaudeProfiles } = await loadModule()
+ const folder = join(home, 'custom')
+ mkdirSync(folder)
+ const linked = linkClaudeProfile(folder, machineId)
+ expect(linked).toEqual({ profile: expect.objectContaining({ path: folder, label: 'custom' }) })
+ const again = await loadModule()
+ expect(again.listClaudeProfiles([], { home, environment: {}, machineId }).map((p) => p.path)).toEqual([home, folder])
+ expect(listClaudeProfiles([folder, join(home, 'gone'), 'relative'], { home, environment: {}, machineId })).toHaveLength(2)
+ })
+
+ it('refuses a relative path with INVALID_PATH, a missing folder or file with NOT_FOUND', async () => {
+ const { linkClaudeProfile } = await loadModule()
+ expect(linkClaudeProfile('relative/x', machineId)).toEqual({ error: 'INVALID_PATH' })
+ expect(linkClaudeProfile('/tmp/a\nb', machineId)).toEqual({ error: 'INVALID_PATH' })
+ expect(linkClaudeProfile(join(home, 'nope'), machineId)).toEqual({ error: 'NOT_FOUND' })
+ writeFileSync(join(home, 'file'), '')
+ expect(linkClaudeProfile(join(home, 'file'), machineId)).toEqual({ error: 'NOT_FOUND' })
+ })
+
+ it('profileId is stable, 16 hex and depends on machine, engine and path', async () => {
+ const { profileId } = await loadModule()
+ const id = profileId('m', 'claude', '/a')
+ expect(id).toMatch(/^[0-9a-f]{16}$/)
+ expect(profileId('m', 'claude', '/a')).toBe(id)
+ expect(new Set([id, profileId('n', 'claude', '/a'), profileId('m', 'codex', '/a'), profileId('m', 'claude', '/b')]).size).toBe(4)
+ })
+})
+
+describe('Desktop-added accounts', () => {
+ it('finds <home>/.harness/claude-profiles/* folders once they hold Claude files', async () => {
+ dataDir = mkdtempSync(join(tmpdir(), 'claude-profiles-data-'))
+ home = realpathSync(mkdtempSync(join(tmpdir(), 'claude-profiles-home-')))
+ const { listClaudeProfiles } = await loadModule()
+ const base = join(home, '.harness', 'claude-profiles')
+ account(join(base, 'acct1'), { displayName: 'Desk' })
+ mkdirSync(join(base, 'empty'), { recursive: true })
+ const labels = listClaudeProfiles([], { home, environment: {}, machineId }).map((p) => p.label)
+ expect(labels).toContain('Desk')
+ expect(labels).not.toContain('empty')
+ rmSync(dataDir, { recursive: true, force: true }); rmSync(home, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ })
+})
+
+describe('profileHome', () => {
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'claude-profiles-data-'))
+ home = realpathSync(mkdtempSync(join(tmpdir(), 'claude-profiles-home-')))
+ })
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ rmSync(home, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ })
+
+ it('maps a reported id back to its folder, the default account to default, and an unknown id to null', async () => {
+ const { listClaudeProfiles, profileHome, profileId } = await loadModule()
+ account(join(home, '.claude-work'), { displayName: 'Work' })
+ const options = { home, environment: {} }
+ const work = listClaudeProfiles([], { ...options, machineId })[1]
+ expect(profileHome('claude', work.id, machineId, options)).toBe(work.path)
+ expect(profileHome('claude', 'default', machineId, options)).toBe('default')
+ expect(profileHome('claude', profileId(machineId, 'claude', 'default'), machineId, options)).toBe('default')
+ expect(profileHome('codex', profileId(machineId, 'codex', 'default'), machineId, options)).toBe('default')
+ expect(profileHome('claude', 'f'.repeat(16), machineId, options)).toBeNull()
+ expect(profileHome('codex', 'f'.repeat(16), machineId, options)).toBeNull()
+ expect(profileHome('gemini', 'default', machineId, options)).toBeNull()
+ })
+
+ it('with offeredOnly, an account the owner never offered is as good as gone, and only an offer brings it back', async () => {
+ const { listClaudeProfiles, profileHome, linkClaudeProfile, offerAccount, profileId } = await loadModule()
+ const folder = join(home, '.claude-work')
+ account(folder, {})
+ const codex = join(home, '.codex-two')
+ mkdirSync(codex)
+ writeFileSync(join(codex, 'auth.json'), '{}')
+ const options = { home, environment: {}, offeredOnly: true }
+ const work = listClaudeProfiles([], { home, environment: {}, machineId })[1]
+ expect(profileHome('claude', work.id, machineId, options)).toBeNull()
+ expect(profileHome('claude', work.id, machineId, { home, environment: {} })).toBe(folder)
+ expect(profileHome('codex', profileId(machineId, 'codex', codex), machineId, options)).toBeNull()
+ expect(profileHome('claude', 'default', machineId, options)).toBe('default')
+ linkClaudeProfile(folder, machineId)
+ expect(profileHome('claude', work.id, machineId, options)).toBeNull()
+ offerAccount('claude', folder, true, options)
+ expect(profileHome('claude', work.id, machineId, options)).toBe(folder)
+ offerAccount('codex', codex, true, options)
+ expect(profileHome('codex', profileId(machineId, 'codex', codex), machineId, options)).toBe(codex)
+ // Withdrawn while a switch is on its way: its host finds the account gone before it closes the PM.
+ offerAccount('claude', folder, false, options)
+ expect(profileHome('claude', work.id, machineId, options)).toBeNull()
+ })
+
+ it('finds a Codex folder by its id', async () => {
+ const { profileHome, profileId, codexReportLabel } = await loadModule()
+ const codex = join(home, '.codex-two')
+ mkdirSync(codex)
+ writeFileSync(join(codex, 'auth.json'), '{}')
+ const found = profileHome('codex', profileId(machineId, 'codex', codex), machineId, { home, environment: {} })
+ expect(found).toBe(codex)
+ expect(codexReportLabel('/x/.codex-two')).toBe('.codex-two')
+ expect(codexReportLabel('/x/jane@corp')).toBe('Codex')
+ })
+
+ it('keeps a symlinked folder as it was given (Claude Code hashes that path), with the id of its real path', async () => {
+ const { linkClaudeProfile, listClaudeProfiles, profileHome, profileId } = await loadModule()
+ const real = join(home, 'real-claude')
+ mkdirSync(real)
+ const given = join(home, '.claude-link')
+ symlinkSync(real, given)
+ const linked = linkClaudeProfile(given, machineId)
+ expect(linked).toMatchObject({ profile: { path: given, id: profileId(machineId, 'claude', real) } })
+ const listed = listClaudeProfiles([], { home, environment: {}, machineId })
+ expect(listed.filter((p) => p.path === given)).toHaveLength(1)
+ expect(profileHome('claude', profileId(machineId, 'claude', real), machineId, { home, environment: {} })).toBe(given)
+ })
+
+ it('the default Codex home answers as the default account, by the id of its path too', async () => {
+ const { profileHome, profileId } = await loadModule()
+ const codex = join(home, '.codex')
+ mkdirSync(codex)
+ writeFileSync(join(codex, 'auth.json'), '{}')
+ expect(profileHome('codex', profileId(machineId, 'codex', codex), machineId, { home, environment: {} })).toBe('default')
+ })
+
+ it('offers a claudeHome that is a listed profile or a folder under ~/.harness/claude-profiles, never the default or any other path', async () => {
+ const { claudeHomeOffered } = await loadModule()
+ const work = join(home, '.claude-work')
+ account(work, { displayName: 'Work' })
+ const options = { home, environment: {} }
+ expect(claudeHomeOffered(work, machineId, options)).toBe(true)
+ expect(claudeHomeOffered(join(home, '.harness', 'claude-profiles', 'new-one'), machineId, options)).toBe(true)
+ expect(claudeHomeOffered(join(home, '.harness', 'claude-profiles', '..', '..', 'elsewhere'), machineId, options)).toBe(false)
+ expect(claudeHomeOffered(home, machineId, options)).toBe(false)
+ expect(claudeHomeOffered(join(home, 'not-listed'), machineId, options)).toBe(false)
+ })
+})
diff --git a/cli/src/lib/claudeProfiles.ts b/cli/src/lib/claudeProfiles.ts
new file mode 100644
index 000000000..b2d605579
--- /dev/null
+++ b/cli/src/lib/claudeProfiles.ts
@@ -0,0 +1,250 @@
+/**
+ * Claude profiles — CLAUDE_CONFIG_DIR folders this machine can point a Claude agent at, the Claude
+ * counterpart of `codexProfiles.ts` (same persistence, same "answered on the machine in question").
+ * The default account (no CLAUDE_CONFIG_DIR) is always first, marked `default`; its id is the one every component uses for
+ * it, `profileId(machine, 'claude', 'default')`. A profile's `path` is the folder as it was given or linked, which is what
+ * Claude Code hashes for its Keychain item and what CLAUDE_CONFIG_DIR must hold; its id is of the real path.
+ *
+ * Two labels: `label` is for the machine's owner (may be an email); `reportLabel` is what leaves the
+ * machine, so it comes from the folder alone and never names a person. `offered` marks what the owner put on the Swarm: the
+ * default account and what they offered by name (lib/accountOffers.ts); every other folder, linked or made by Add Claude account
+ * included, stays the owner's own to pick in Change agent.
+ */
+
+import { createHash, randomUUID } from 'crypto'
+import { closeSync, constants, fchmodSync, fsyncSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
+import { homedir } from 'os'
+import { basename, join, resolve, sep } from 'path'
+import { env } from '../config/env.js'
+import { offeredFolders, recordOffer } from './accountOffers.js'
+import { defaultCodexHome, listCodexProfiles, resolveCodexProfilePath } from './codexProfiles.js'
+import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
+
+export interface ClaudeProfile {
+ id: string
+ path: string
+ label: string
+ reportLabel: string
+ offered: boolean
+ /** Set on the default account alone. */
+ default?: true
+}
+
+export type ClaudeProfileError = { error: 'INVALID_PATH' | 'NOT_FOUND' }
+
+const FILE = join(env.ADAPTER_DATA_DIR, 'claude-profiles.json')
+const MAX_LINKED = 256
+const MAX_ENTRIES = 512
+// A real ~/.claude.json grows with the project history; this only stops a runaway file.
+const MAX_ACCOUNT_FILE_BYTES = 16 * 1024 * 1024
+const REPORT_LABEL_MAX = 40
+const CONTROL_CHARS_RE = /[\x00-\x1f\x7f]/
+const ORCA_HOME_RE = /\/claude-profiles\/([0-9a-f][0-9a-f-]*)\/home$/i
+
+/** Opaque, stable per machine: no path or account name leaves the machine through it. */
+export function profileId(machineId: string, engine: 'claude' | 'codex', realpath: string): string {
+ return createHash('sha256').update(`${machineId}:${engine}:${realpath}`).digest('hex').slice(0, 16)
+}
+
+function accountOf(folder: string): { displayName?: string; emailAddress?: string } {
+ try {
+ const file = join(folder, '.claude.json')
+ if (statSync(file).size > MAX_ACCOUNT_FILE_BYTES) return {}
+ const account = (JSON.parse(readFileSync(file, 'utf8')) as { oauthAccount?: Record<string, unknown> }).oauthAccount
+ const text = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
+ return { displayName: text(account?.displayName), emailAddress: text(account?.emailAddress) }
+ } catch {
+ return {}
+ }
+}
+
+function harnessFolder(home: string): string {
+ return join(home, '.harness', 'claude-profiles') + sep
+}
+
+/** The folder's name, never the account's: a display name is a person's, and this label is served to the whole Swarm. */
+function reportLabelFor(path: string, home: string): string {
+ const orca = ORCA_HOME_RE.exec(path)
+ const name = orca ? `Orca ${orca[1].slice(0, 4)}` : path.startsWith(harnessFolder(home)) ? `Claude ${basename(path)}` : basename(path)
+ return (name.includes('@') ? 'Claude' : name).slice(0, REPORT_LABEL_MAX)
+}
+
+function profileFor(machineId: string, path: string, real: string, home: string, offered: boolean, isDefault = false): ClaudeProfile {
+ const { displayName, emailAddress } = accountOf(path)
+ return {
+ id: profileId(machineId, 'claude', isDefault ? 'default' : real),
+ ...(isDefault ? { default: true as const } : {}),
+ path,
+ label: displayName ?? emailAddress ?? basename(path),
+ reportLabel: reportLabelFor(path, home),
+ offered: offered || isDefault,
+ }
+}
+
+function readLinkedPaths(): Set<string> {
+ try {
+ const raw = JSON.parse(readPrivateStateFile(FILE, 1024 * 1024)) as unknown
+ if (Array.isArray(raw)) return new Set(raw.filter((p): p is string => typeof p === 'string').slice(0, MAX_LINKED))
+ } catch {
+ // Discovery still works when the optional saved list is unavailable/unreadable/malformed.
+ }
+ return new Set()
+}
+
+function writeLinkedPaths(paths: Set<string>): void {
+ secureStateDirectory(env.ADAPTER_DATA_DIR)
+ hardenPrivateStateFileIfPresent(FILE)
+ const temporary = `${FILE}.${process.pid}.${randomUUID()}.tmp`
+ let renamed = false
+ try {
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ writeFileSync(fd, JSON.stringify([...paths].slice(0, MAX_LINKED), null, 2))
+ fchmodSync(fd, 0o600)
+ fsyncSync(fd)
+ } finally {
+ closeSync(fd)
+ }
+ renameSync(temporary, FILE)
+ renamed = true
+ } finally {
+ if (!renamed) rmSync(temporary, { force: true })
+ }
+}
+
+/** Validate + resolve a folder path the same way for linking and for re-checking a saved one. */
+function resolveFolder(path: string): string | ClaudeProfileError {
+ if (!path.startsWith('/') || path.length > 4096 || CONTROL_CHARS_RE.test(path)) return { error: 'INVALID_PATH' }
+ try {
+ if (!statSync(path).isDirectory()) return { error: 'NOT_FOUND' }
+ const resolved = realpathSync(path)
+ return resolved.length > 4096 || CONTROL_CHARS_RE.test(resolved) ? { error: 'INVALID_PATH' } : resolved
+ } catch {
+ return { error: 'NOT_FOUND' }
+ }
+}
+
+/** Link a folder as a Claude profile, persisted on this machine so it survives future requests. */
+export function linkClaudeProfile(path: string, machineId: string): { profile: ClaudeProfile } | ClaudeProfileError {
+ const resolved = resolveFolder(path)
+ if (typeof resolved !== 'string') return resolved
+ const linked = readLinkedPaths()
+ linked.add(path)
+ writeLinkedPaths(linked)
+ return { profile: profileFor(machineId, path, resolved, homedir(), offeredFolders('claude').has(resolved)) }
+}
+
+function holdsProfile(folder: string): boolean {
+ return ['.claude.json', 'settings.json'].some((name) => {
+ try {
+ return statSync(join(folder, name)).isFile()
+ } catch {
+ return false
+ }
+ })
+}
+
+function entries(folder: string): string[] {
+ try {
+ return readdirSync(folder).slice(0, MAX_ENTRIES).map((name) => join(folder, name))
+ } catch {
+ return []
+ }
+}
+
+/** The inherited CLAUDE_CONFIG_DIR, conventional `~/.claude-*` folders and Orca's per-profile homes and Desktop's own. */
+function discover(home: string, environment: NodeJS.ProcessEnv): string[] {
+ const found: string[] = []
+ const inherited = environment.CLAUDE_CONFIG_DIR
+ if (inherited) found.push(inherited)
+ found.push(...entries(home).filter((e) => basename(e).startsWith('.claude-')))
+ const orca = join(home, 'Library', 'Application Support', 'orca', 'claude-profiles')
+ found.push(...entries(orca).map((e) => join(e, 'home')))
+ // Where Desktop's "Add Claude account…" puts the folders it creates.
+ found.push(...entries(join(home, '.harness', 'claude-profiles')))
+ return found.filter(holdsProfile)
+}
+
+/**
+ * Every Claude profile this machine can offer: the default account, linked folders, `observedPaths`
+ * (folders the caller already knows from this machine's other agents) and discovered ones. Never
+ * throws; a folder that vanished or is malformed is just not offered.
+ */
+export function listClaudeProfiles(
+ observedPaths: readonly string[] = [],
+ options: { home?: string; environment?: NodeJS.ProcessEnv; machineId: string },
+): ClaudeProfile[] {
+ const home = options.home ?? homedir()
+ const linkedPaths = readLinkedPaths()
+ const offered = offeredFolders('claude')
+ const candidates = new Set<string>([...linkedPaths, ...observedPaths, ...discover(home, options.environment ?? process.env)])
+ const defaultPath = resolveFolder(home)
+ const defaultProfile = profileFor(options.machineId, home, typeof defaultPath === 'string' ? defaultPath : home, home, true, true)
+ const profiles = new Map<string, ClaudeProfile>()
+ for (const candidate of candidates) {
+ const resolved = resolveFolder(candidate)
+ // De-duplicated by the real folder; the path kept is the first one given.
+ if (typeof resolved === 'string' && resolved !== (typeof defaultPath === 'string' ? defaultPath : home) && !profiles.has(resolved)) {
+ profiles.set(resolved, profileFor(options.machineId, candidate, resolved, home, offered.has(resolved)))
+ }
+ }
+ const others = [...profiles.values()].sort((a, b) => a.label.toLowerCase().localeCompare(b.label.toLowerCase()) || a.path.localeCompare(b.path))
+ return [defaultProfile, ...others]
+}
+
+/**
+ * The owner's choice for one account: offered, other people's PMs on this machine can run on it and spend it; withdrawn, the next
+ * report drops it and a switch on its way finds it gone (`profileHome` with offeredOnly). A PM already running on it stays until
+ * someone moves it. A folder that is gone can still be withdrawn.
+ */
+export function offerAccount(
+ engine: string, path: string, offered: boolean, options: { home?: string; environment?: Record<string, string | undefined> } = {},
+): { offered: boolean } | { error: 'INVALID_ENGINE' | 'INVALID_PATH' | 'NOT_FOUND' | 'DEFAULT_ACCOUNT' | 'TOO_MANY' } {
+ if (engine !== 'claude' && engine !== 'codex') return { error: 'INVALID_ENGINE' }
+ if (!path.startsWith('/') || path.length > 4096 || CONTROL_CHARS_RE.test(path)) return { error: 'INVALID_PATH' }
+ const home = options.home ?? homedir()
+ const found = engine === 'claude' ? resolveFolder(path) : (() => { const r = resolveCodexProfilePath(path); return 'error' in r ? r : r.path })()
+ if (typeof found !== 'string') {
+ if (offered || found.error === 'INVALID_PATH') return found
+ recordOffer(engine, path, false)
+ return { offered: false }
+ }
+ const defaultFolder = engine === 'claude' ? resolveFolder(home) : defaultCodexHome(home, options.environment ?? process.env)
+ if (found === defaultFolder) return { error: 'DEFAULT_ACCOUNT' }
+ return recordOffer(engine, found, offered) ? { offered } : { error: 'TOO_MANY' }
+}
+
+/** What leaves the machine for a Codex folder: its name, and never one holding an '@' (an email). */
+export function codexReportLabel(path: string): string {
+ const name = basename(path)
+ return (name.includes('@') ? 'Codex' : name).slice(0, REPORT_LABEL_MAX)
+}
+
+/**
+ * The folder a reported profile id stands for: 'default' for the engine's default account (the literal 'default', which an
+ * older backend sends, or its reported id), a path for a profile this machine still has, null for an unknown or gone one.
+ */
+export function profileHome(
+ engine: string, id: string, machineId: string, options: { home?: string; environment?: NodeJS.ProcessEnv; offeredOnly?: boolean } = {},
+): string | 'default' | null {
+ if (engine !== 'claude' && engine !== 'codex') return null
+ if (id === 'default' || id === profileId(machineId, engine, 'default')) return 'default'
+ if (engine === 'claude') return listClaudeProfiles([], { ...options, machineId }).find((p) => p.id === id && (p.offered || !options.offeredOnly))?.path ?? null
+ const discovery = options.home ? { home: options.home, environment: (options.environment ?? {}) as Record<string, string> } : undefined
+ const found = listCodexProfiles([], discovery).find((p) => profileId(machineId, 'codex', p.path) === id && (p.offered || !options.offeredOnly))?.path ?? null
+ // The default Codex home is the default account, whichever of its two ids was asked.
+ return found === defaultCodexHome(options.home, options.environment) ? 'default' : found
+}
+
+/**
+ * Whether [claudeHome] may be handed to an agent as its CLAUDE_CONFIG_DIR: a profile this machine lists (the default account
+ * has none), or a folder under `~/.harness/claude-profiles/`, where Desktop's "Add Claude account" makes a new one before it
+ * holds any file. Any other path would be written into (hooks, folder trust) and adopted for good (core/agents/launches.ts).
+ */
+export function claudeHomeOffered(
+ claudeHome: string, machineId: string, options: { home?: string; environment?: NodeJS.ProcessEnv } = {},
+): boolean {
+ const own = join(options.home ?? homedir(), '.harness', 'claude-profiles') + sep
+ if (resolve(claudeHome) === claudeHome && claudeHome.startsWith(own)) return true
+ return listClaudeProfiles([], { ...options, machineId }).some((p) => !p.default && p.path === claudeHome)
+}
diff --git a/cli/src/lib/codexProfiles.test.ts b/cli/src/lib/codexProfiles.test.ts
index 1de3b73f2..bd04e507f 100644
--- a/cli/src/lib/codexProfiles.test.ts
+++ b/cli/src/lib/codexProfiles.test.ts
@@ -79,7 +79,8 @@ describe('codexProfiles', () => {
const folder = join(home, '.codex-linked')
mkdirSync(folder)
linkCodexProfile(folder)
- expect(listCodexProfiles([], emptyDiscovery)).toEqual([{ path: folder, label: '.codex-linked' }])
+ // A link is a folder this machine knows (New Harness makes them): it is not an offer to the Swarm.
+ expect(listCodexProfiles([], emptyDiscovery)).toEqual([{ path: folder, label: '.codex-linked', offered: false }])
})
it('listCodexProfiles drops a linked folder that has since vanished', async () => {
@@ -95,7 +96,7 @@ describe('codexProfiles', () => {
const { listCodexProfiles } = await loadModule()
const folder = join(home, '.codex-observed')
mkdirSync(folder)
- expect(listCodexProfiles([folder], emptyDiscovery)).toEqual([{ path: folder, label: '.codex-observed' }])
+ expect(listCodexProfiles([folder], emptyDiscovery)).toEqual([{ path: folder, label: '.codex-observed', offered: false }])
})
it('listCodexProfiles includes freshly discovered folders', async () => {
@@ -103,7 +104,7 @@ describe('codexProfiles', () => {
mkdirSync(join(home, '.codex'))
writeFileSync(join(home, '.codex', 'auth.json'), '{}')
expect(listCodexProfiles([], { home, environment: {} })).toEqual([
- { path: join(home, '.codex'), label: '.codex' },
+ { path: join(home, '.codex'), label: '.codex', offered: true },
])
})
@@ -113,7 +114,8 @@ describe('codexProfiles', () => {
mkdirSync(folder)
writeFileSync(join(folder, 'auth.json'), '{}')
linkCodexProfile(folder)
- expect(listCodexProfiles([folder], { home, environment: {} })).toEqual([{ path: folder, label: '.codex' }])
+ // The default account: offered with no offer of its own.
+ expect(listCodexProfiles([folder], { home, environment: {} })).toEqual([{ path: folder, label: '.codex', offered: true }])
})
it('listCodexProfiles sorts by label (case-insensitive), then by path', async () => {
@@ -123,8 +125,8 @@ describe('codexProfiles', () => {
mkdirSync(a)
mkdirSync(b)
expect(listCodexProfiles([a, b], emptyDiscovery)).toEqual([
- { path: a, label: '.codex-alpha' },
- { path: b, label: '.codex-Beta' },
+ { path: a, label: '.codex-alpha', offered: false },
+ { path: b, label: '.codex-Beta', offered: false },
])
})
diff --git a/cli/src/lib/codexProfiles.ts b/cli/src/lib/codexProfiles.ts
index af9733b5d..73bf915db 100644
--- a/cli/src/lib/codexProfiles.ts
+++ b/cli/src/lib/codexProfiles.ts
@@ -15,11 +15,14 @@ import { homedir } from 'os'
import { join } from 'path'
import { env } from '../config/env.js'
import { discoverCodexProfiles } from './codexProfileDiscovery.js'
+import { offeredFolders } from './accountOffers.js'
import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
export interface CodexProfile {
path: string
label: string
+ /** The default account or one the owner offered (lib/accountOffers.ts); any other is the owner's own to pick, not the Swarm's. */
+ offered?: boolean
}
export type CodexProfileError = { error: 'INVALID_PATH' | 'NOT_FOUND' }
@@ -102,6 +105,12 @@ export function linkCodexProfile(path: string): CodexProfile | CodexProfileError
return profile
}
+/** The Codex account that needs no CODEX_HOME: an inherited CODEX_HOME, or ~/.codex. */
+export function defaultCodexHome(home: string = homedir(), environment: Record<string, string | undefined> = process.env): string {
+ const folder = environment.CODEX_HOME || join(home, '.codex')
+ try { return realpathSync(folder) } catch { return folder }
+}
+
function processEnvironment(): Record<string, string> {
const environment: Record<string, string> = {}
for (const [key, value] of Object.entries(process.env)) {
@@ -124,6 +133,7 @@ export function listCodexProfiles(
environment: processEnvironment(),
},
): CodexProfile[] {
+ const offered = offeredFolders('codex')
const candidates = new Set<string>([...readLinkedPaths(), ...observedPaths])
try {
for (const path of discoverCodexProfiles(discoveryOptions)) {
@@ -132,11 +142,12 @@ export function listCodexProfiles(
} catch {
// A discovery failure must not hide linked/observed profiles that are still good.
}
+ const defaultHome = defaultCodexHome(discoveryOptions.home, discoveryOptions.environment)
const profiles = new Map<string, CodexProfile>()
for (const path of candidates) {
const resolved = resolveCodexProfilePath(path)
// A vanished folder or a malformed persisted entry must not be offered as a working profile.
- if (!('error' in resolved)) profiles.set(resolved.path, resolved)
+ if (!('error' in resolved)) profiles.set(resolved.path, { ...resolved, offered: offered.has(resolved.path) || resolved.path === defaultHome })
}
return [...profiles.values()].sort((a, b) => {
const byLabel = a.label.toLowerCase().localeCompare(b.label.toLowerCase())
diff --git a/cli/src/lib/connectors/README.md b/cli/src/lib/connectors/README.md
index a1af40e7c..4c4085157 100644
--- a/cli/src/lib/connectors/README.md
+++ b/cli/src/lib/connectors/README.md
@@ -77,14 +77,19 @@ them in `~/.local/share/harness-os/connections`; they are moved here the first t
## Agents and the bridge
Agent configs never hold a token (`agents.ts`). Each connection with tools (an MCP server, or REST tools
-the bridge serves) becomes an entry
-pointing at `http://127.0.0.1:51793/<capability>/<code>/mcp`:
+the bridge serves) becomes an entry that runs `mcp-shim.mjs --socket <path> <code>` with Harness's node: a small stdio shim
+in this folder, to the bridge's 0600 socket (`mcpShimSource.ts`). It holds no key, because reaching the socket is the credential, and it never
+falls back to a port, so whoever holds a port hears no tool call:
| Agent | File | Entry |
| --- | --- | --- |
-| Claude Code | `~/.claude.json` (`$CLAUDE_CONFIG_DIR`) | `mcpServers.<code> = {type: http, url}` |
-| Codex | `~/.codex/config.toml` (`$CODEX_HOME`) | `[mcp_servers.<code>] url = …` |
-| OpenCode | `~/.config/opencode/opencode.json` | `mcp.<code> = {type: remote, url, enabled}` |
+| Claude Code | `~/.claude.json` (`$CLAUDE_CONFIG_DIR`) | `mcpServers.<code> = {type: stdio, command, args}` |
+| Codex | `~/.codex/config.toml` (`$CODEX_HOME`) | `[mcp_servers.<code>] command = … args = …` |
+| OpenCode | `~/.config/opencode/opencode.json` | `mcp.<code> = {type: local, command, enabled}` |
+
+Where no socket can be (Windows, or a folder too long for one), the entry is still the address
+`http://127.0.0.1:51793/<capability>/<code>/mcp`. The port also stays for clients already running on it until they
+restart, and for Harness's own cloud agents.
Only names recorded in `projections.json` are changed or removed; a server the person added keeps its
name and contents, a config that is not plain JSON is left alone, and a symlinked config is written
diff --git a/cli/src/lib/connectors/agents.ts b/cli/src/lib/connectors/agents.ts
index 8239d1baf..b5d789cd4 100644
--- a/cli/src/lib/connectors/agents.ts
+++ b/cli/src/lib/connectors/agents.ts
@@ -1,7 +1,8 @@
/**
- * Connected services, given to each agent as an MCP server on the local bridge. Agent configs hold only a
- * 127.0.0.1 address with this user's capability in it; the bridge adds the credential to each request
- * (Grid's design). A renewed token needs no config change, and an agent already running keeps working.
+ * Connected services, given to each agent as an MCP server on the local bridge. Agent configs hold only the command of a stdio
+ * shim to the bridge's 0600 socket (mcpShimSource.ts), or where no socket can be (Windows, a folder too long for one) a 127.0.0.1
+ * address with this user's capability in it; the bridge adds the credential to each request (Grid's design). A renewed token
+ * needs no config change, and an agent already running keeps working.
*
* Only entries Harness made are changed or removed: their names are recorded in projections.json, so a
* server the person added by hand keeps its name and contents. A config that is not plain JSON (comments)
@@ -11,6 +12,8 @@ import { randomBytes } from 'node:crypto'
import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync, mkdirSync, statSync } from 'node:fs'
import { homedir } from 'node:os'
import { delimiter, dirname, join } from 'node:path'
+import { managedNodePath } from '../nodeRuntime.js'
+import { MCP_SHIM_SOURCE } from './mcpShimSource.js'
import { CODE, locked, writePrivate, type Store } from './store.js'
import { transport } from './rest.js'
@@ -68,6 +71,35 @@ export function bridgeUrl(key: string, code: string, port = bridgePort()): strin
return `http://127.0.0.1:${port}/${key}/${code}/mcp`
}
+/** sockaddr_un has 104 bytes on macOS and the socket is staged under a name no longer (lib/localSocket.ts). */
+const MAX_SOCKET_PATH_BYTES = 96
+
+/** The bridge's 0600 socket for MCP clients, in the vault's private folder, or null where there is none. */
+export function bridgeSocketPath(vault: Store, platform: NodeJS.Platform = process.platform): string | null {
+ if (platform === 'win32') return null
+ const path = join(vault.root, 'bridge.sock')
+ return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null
+}
+
+/** How an MCP client reaches one connection. */
+export type McpEntry = { url: string } | { command: string; args: string[] }
+
+/**
+ * The shim, written fresh into the vault's private folder (mcpShimSource.ts). Its node is Harness's managed one, as an agent started
+ * outside Harness may have neither `harness` nor a node on its PATH. That path names a version, or this process's node where no runtime
+ * is recorded: the daemon's next start writes the entries again.
+ */
+function writeShim(vault: Store): string {
+ const path = join(vault.root, 'mcp-shim.mjs')
+ mkdirSync(vault.root, { recursive: true, mode: 0o700 })
+ if (!existsSync(path) || readFileSync(path, 'utf8') !== MCP_SHIM_SOURCE) {
+ const staged = `${path}.${process.pid}.tmp`
+ writeFileSync(staged, MCP_SHIM_SOURCE, { mode: 0o600 })
+ renameSync(staged, path)
+ }
+ return path
+}
+
function home(env: NodeJS.ProcessEnv): string { return env.HOME || homedir() }
function onPath(binary: string, env: NodeJS.ProcessEnv): boolean {
@@ -88,17 +120,17 @@ function replace(file: string, text: string): void {
export interface Agent {
name: string
installed(): boolean
- /** Make `wanted` (name → bridge address) the Harness entries; returns the names now Harness's. */
- apply(wanted: Record<string, string>, owned: string[]): string[]
+ /** Make `wanted` (name → how to reach it) the Harness entries; returns the names now Harness's. */
+ apply(wanted: Record<string, McpEntry>, owned: string[]): string[]
}
class JsonAgent implements Agent {
constructor(readonly name: string, private readonly binary: string, private readonly path: string,
- private readonly env: NodeJS.ProcessEnv, private readonly key: string, private readonly entry: (url: string) => Record<string, unknown>) {}
+ private readonly env: NodeJS.ProcessEnv, private readonly key: string, private readonly entry: (reach: McpEntry) => Record<string, unknown>) {}
installed(): boolean { return existsSync(this.path) || onPath(this.binary, this.env) }
- apply(wanted: Record<string, string>, owned: string[]): string[] {
+ apply(wanted: Record<string, McpEntry>, owned: string[]): string[] {
let data: Record<string, unknown> = {}
if (existsSync(this.path)) {
try { data = JSON.parse(readFileSync(this.path, 'utf8')) } catch { return owned }
@@ -109,9 +141,9 @@ class JsonAgent implements Agent {
const servers = { ...(current as Record<string, unknown> | undefined) }
for (const name of owned) if (!(name in wanted)) delete servers[name]
const result: string[] = []
- for (const [name, url] of Object.entries(wanted)) {
+ for (const [name, reach] of Object.entries(wanted)) {
if (name in servers && !owned.includes(name)) continue // The person's own server with this name.
- servers[name] = this.entry(url)
+ servers[name] = this.entry(reach)
result.push(name)
}
if (Object.keys(servers).length) data[this.key] = servers
@@ -133,7 +165,7 @@ class CodexAgent implements Agent {
return new RegExp(`^\\s*\\[\\s*mcp_servers\\s*\\.\\s*(?:${escaped}|"${escaped}")\\s*(?:\\.[^\\]]*)?\\]\\s*$`)
}
- apply(wanted: Record<string, string>, owned: string[]): string[] {
+ apply(wanted: Record<string, McpEntry>, owned: string[]): string[] {
let lines: string[] = []
if (existsSync(this.path)) {
try { lines = readFileSync(this.path, 'utf8').split('\n') } catch { return owned }
@@ -147,9 +179,11 @@ class CodexAgent implements Agent {
}
while (kept.length && !kept.at(-1)!.trim()) kept.pop()
const result: string[] = []
- for (const [name, url] of Object.entries(wanted).sort(([a], [b]) => a.localeCompare(b))) {
+ for (const [name, reach] of Object.entries(wanted).sort(([a], [b]) => a.localeCompare(b))) {
if (kept.some(line => CodexAgent.header(name).test(line))) continue // The person's own server.
- kept.push('', `[mcp_servers.${name}]`, `url = ${JSON.stringify(url)}`)
+ // JSON's strings and arrays of them are TOML's too.
+ kept.push('', `[mcp_servers.${name}]`, ...'url' in reach ? [`url = ${JSON.stringify(reach.url)}`]
+ : [`command = ${JSON.stringify(reach.command)}`, `args = ${JSON.stringify(reach.args)}`])
result.push(name)
}
while (kept.length && !kept[0].trim()) kept.shift()
@@ -162,18 +196,22 @@ export function agents(env: NodeJS.ProcessEnv = process.env): Agent[] {
const config = env.XDG_CONFIG_HOME || join(home(env), '.config')
return [
new JsonAgent('claude', 'claude', join(env.CLAUDE_CONFIG_DIR || home(env), '.claude.json'), env, 'mcpServers',
- url => ({ type: 'http', url })),
+ reach => 'url' in reach ? { type: 'http', url: reach.url } : { type: 'stdio', command: reach.command, args: reach.args }),
new CodexAgent(join(env.CODEX_HOME || join(home(env), '.codex'), 'config.toml'), env),
new JsonAgent('opencode', 'opencode', join(config, 'opencode', 'opencode.json'), env, 'mcp',
- url => ({ type: 'remote', url, enabled: true })),
+ reach => 'url' in reach ? { type: 'remote', url: reach.url, enabled: true } : { type: 'local', command: [reach.command, ...reach.args], enabled: true }),
]
}
/** Give every installed agent exactly the connections that have MCP tools (their own, or REST served as MCP). */
export function sync(vault: Store, env: NodeJS.ProcessEnv = process.env, list: Agent[] = agents(env)): Record<string, string[]> {
const codes = Object.entries(vault.tokens()).filter(([code, token]) => transport(token) !== 'none' && CODE.test(code)).map(([code]) => code)
- const key = codes.length ? bridgeKey(vault) : ''
- const wanted = Object.fromEntries(codes.map(code => [code, bridgeUrl(key, code, bridgePort(env, vault))]))
+ const socket = bridgeSocketPath(vault)
+ const shim = codes.length && socket ? writeShim(vault) : ''
+ const key = codes.length && !socket ? bridgeKey(vault) : ''
+ const wanted = Object.fromEntries(codes.map((code): [string, McpEntry] => [code, socket
+ ? { command: managedNodePath(), args: [shim, '--socket', socket, code] }
+ : { url: bridgeUrl(key, code, bridgePort(env, vault)) }]))
return locked(vault.root, () => {
const record = vault.file('projections.json') as Record<string, unknown>
const changed: Record<string, string[]> = {}
diff --git a/cli/src/lib/connectors/bridge.ts b/cli/src/lib/connectors/bridge.ts
index 1f26a6e88..99b344aba 100644
--- a/cli/src/lib/connectors/bridge.ts
+++ b/cli/src/lib/connectors/bridge.ts
@@ -4,14 +4,21 @@
* the answer back (event streams included). A service reached by REST (no MCP server the grant can use) is
* answered here instead, its REST tools served as MCP (rest.ts). Runs in the daemon (services/connectors.ts).
*
+ * MCP clients come through a stdio shim (mcpShimSource.ts) to a second listener on a 0600 socket (serveBridgeSocket), so no tool call
+ * goes to a port another account can hold. The port stays for clients still running on it, Windows, and a folder too long for
+ * a socket.
+ *
* Two more addresses serve Harness's own cloud agents (services/cloud.ts), which hold no credential either:
* - `/<key>/connections`: what is connected, by address and with no secret, so the service finds the
* connection that signs in Fo or Devin by where it points rather than by what the person named it;
* - `/<key>/<code>/api/<path>`: one request to a key-only connection's own API (`api_entry`), with its key.
*/
import { timingSafeEqual } from 'node:crypto'
-import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
+import { chmodSync, mkdirSync } from 'node:fs'
+import { createServer, type IncomingMessage, type RequestListener, type Server, type ServerResponse } from 'node:http'
+import { dirname } from 'node:path'
import { Readable } from 'node:stream'
+import { listenLocalSocket, type LocalSocketServer } from '../localSocket.js'
import { label } from './catalog.js'
import { bearer, needsRefresh, refreshable, type Store, type Token } from './store.js'
import { refresh } from './renew.js'
@@ -51,13 +58,32 @@ export interface BridgeOptions {
/** Harness's own capability (agents.ts harnessKey), never in an agent's configuration: only it lists the
* connections or calls a key-only connection's API. Absent, those two addresses answer nothing. */
harnessKey?: () => string
+ /** Served on the 0600 socket, whose peers have no address: the filesystem has already said who they are. */
+ socket?: boolean
/** Whether a caller runs as this OS account (lib/peerAccount.ts). A test's stand-in for another account. */
peerAccount?: PeerAccount
}
type Target = { kind: 'mcp'; code: string } | { kind: 'api'; code: string; path: string } | { kind: 'list' }
+/** What stands for the capability on the socket, where reaching it is the credential: the filesystem lets only this account. */
+export const SOCKET_KEY = 'local'
+
export function createBridge(vault: Store, options: BridgeOptions): Server {
+ return createServer(bridgeHandler(vault, options))
+}
+
+/** The bridge for MCP clients on its 0600 socket: their MCP servers only, as an agent's key reaches (no Harness key here). */
+export async function serveBridgeSocket(vault: Store, path: string): Promise<LocalSocketServer> {
+ // The socket's privacy rests on this folder too, which may be older than this code.
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
+ chmodSync(dirname(path), 0o700)
+ const listening = await listenLocalSocket(bridgeHandler(vault, { key: () => SOCKET_KEY, socket: true }), path)
+ listening.server.unref()
+ return listening
+}
+
+function bridgeHandler(vault: Store, options: BridgeOptions): RequestListener {
const target = (url: string): Target | null => {
const parts = new URL(url, 'http://127.0.0.1').pathname.replace(/^\/|\/$/g, '').split('/')
const given = Buffer.from(parts[0])
@@ -149,14 +175,15 @@ export function createBridge(vault: Store, options: BridgeOptions): Server {
const relay = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {
// Only a process on this computer that knows this user's key gets through; never a web page.
- if (request.headers.origin || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(request.socket.remoteAddress ?? '')) {
+ if (request.headers.origin || (!options.socket && !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(request.socket.remoteAddress ?? ''))) {
fail(response, 403, 'Forbidden.'); return
}
const address = target(request.url ?? '/')
// An MCP client can only speak HTTP to the address in its configuration, so it cannot check who holds this port,
// and another account that took it during a restart hears the key (audit H1). A key heard must open nothing. Answered
// as an unknown key is, so the answer does not say the key was right.
- if (!address || !await (options.peerAccount ?? peerIsThisAccount)(request.socket)) {
+ // On the 0600 socket the filesystem has already said who the caller is, and a socket's peer has no port to look up.
+ if (!address || (!options.socket && !await (options.peerAccount ?? peerIsThisAccount)(request.socket))) {
fail(response, 404, 'Unknown connection address. Run harness connections sync.'); return
}
if (address.kind === 'list') { list(response); return }
@@ -201,7 +228,7 @@ export function createBridge(vault: Store, options: BridgeOptions): Server {
Readable.fromWeb(answer.body as import('node:stream/web').ReadableStream).on('error', () => response.destroy()).pipe(response)
}
- return createServer((request, response) => {
+ return (request, response) => {
relay(request, response).catch(() => { if (!response.headersSent) fail(response, 500, 'The bridge failed.'); else response.destroy() })
- })
+ }
}
diff --git a/cli/src/lib/connectors/connectors.spec.ts b/cli/src/lib/connectors/connectors.spec.ts
index a69b2b089..2716c7569 100644
--- a/cli/src/lib/connectors/connectors.spec.ts
+++ b/cli/src/lib/connectors/connectors.spec.ts
@@ -8,6 +8,7 @@ import { createServer, request as httpRequest } from 'node:http'
import type { AddressInfo } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { managedNodePath } from '../nodeRuntime.js'
import { FakeGateway, FakeService } from '../../testing/connectorServers.js'
import { bridgeKey, harnessKey, sync } from './agents.js'
import { createBridge } from './bridge.js'
@@ -270,7 +271,7 @@ describe('key-only connections for the cloud agents', () => {
})
describe('agent configs', () => {
- it('gives each agent bridge addresses and keeps its own servers', () => {
+ it('gives each agent the shim and keeps its own servers', () => {
const claude = join(home, '.claude.json')
writeFileSync(claude, JSON.stringify({ numStartups: 3, mcpServers: { notion: { command: 'my-notion' } } }))
const codex = join(home, '.codex', 'config.toml')
@@ -282,15 +283,16 @@ describe('agent configs', () => {
for (const code of ['linear', 'notion']) vault.save(code, { access_token: 'secret-' + code, source: 'dcr', mcp_entry: { url: `https://mcp.${code}.example/mcp`, headers: { Authorization: 'Bearer secret-' + code } } })
vault.save('github', { access_token: 'secret-github', source: 'gateway' })
expect(sync(vault, env)).toEqual({ claude: ['linear'], codex: ['linear', 'notion'], opencode: ['linear', 'notion'] })
- const key = bridgeKey(vault)
+ const socket = join(vault.root, 'bridge.sock')
+ const shim = (code: string) => [join(vault.root, 'mcp-shim.mjs'), '--socket', socket, code]
const data = JSON.parse(readFileSync(claude, 'utf8'))
expect(data.numStartups).toBe(3)
expect(data.mcpServers.notion).toEqual({ command: 'my-notion' })
- expect(data.mcpServers.linear).toEqual({ type: 'http', url: `http://127.0.0.1:51793/${key}/linear/mcp` })
+ expect(data.mcpServers.linear).toEqual({ type: 'stdio', command: managedNodePath(), args: shim('linear') })
const toml = readFileSync(codex, 'utf8')
expect(toml.startsWith('model = "gpt-5"\n\n[mcp_servers.mine]\ncommand = "mine"\n')).toBe(true)
- expect(toml).toContain(`[mcp_servers.notion]\nurl = "http://127.0.0.1:51793/${key}/notion/mcp"`)
- expect(JSON.parse(readFileSync(opencode, 'utf8')).mcp.linear.type).toBe('remote')
+ expect(toml).toContain(`[mcp_servers.notion]\ncommand = ${JSON.stringify(managedNodePath())}\nargs = ${JSON.stringify(shim('notion'))}`)
+ expect(JSON.parse(readFileSync(opencode, 'utf8')).mcp.linear).toEqual({ type: 'local', command: [managedNodePath(), ...shim('linear')], enabled: true })
for (const path of [claude, codex, opencode]) expect(readFileSync(path, 'utf8')).not.toContain('secret-')
vault.disconnect('linear')
vault.disconnect('notion')
diff --git a/cli/src/lib/connectors/mcpShim.spec.ts b/cli/src/lib/connectors/mcpShim.spec.ts
new file mode 100644
index 000000000..05750f6e2
--- /dev/null
+++ b/cli/src/lib/connectors/mcpShim.spec.ts
@@ -0,0 +1,424 @@
+/**
+ * MCP clients reach the bridge through a stdio shim, over a 0600 socket (follow-up of audit H1): whoever holds the bridge's old
+ * port hears no tool call, however the daemon is doing.
+ */
+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
+import { createServer, request as httpRequest, type Server } from 'node:http'
+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { managedNodePath } from '../nodeRuntime.js'
+import { bridgeSocketPath, sync } from './agents.js'
+import { serveBridgeSocket } from './bridge.js'
+import { MCP_SHIM_SOURCE } from './mcpShimSource.js'
+import { Store, writePrivate } from './store.js'
+
+let home: string
+let vault: Store
+let env: NodeJS.ProcessEnv
+const closers: Array<() => void> = []
+
+const listen = (server: Server): Promise<number> => new Promise(resolve => {
+ server.listen(0, '127.0.0.1', () => resolve((server.address() as { port: number }).port))
+ closers.push(() => { server.closeAllConnections(); server.close() })
+})
+
+/** The service's MCP server: answers each request as JSON, or tools/call as an event stream. */
+async function upstream(): Promise<{ url: string; heard: Array<{ method: string; session?: string; auth?: string; version?: string }> }> {
+ const heard: Array<{ method: string; session?: string; auth?: string; version?: string }> = []
+ const server = createServer((request, response) => {
+ let raw = ''
+ request.on('data', chunk => { raw += chunk })
+ request.on('end', () => {
+ const message = JSON.parse(raw) as { id?: number; method: string }
+ heard.push({ method: message.method, session: request.headers['mcp-session-id'] as string | undefined,
+ auth: request.headers.authorization, version: request.headers['mcp-protocol-version'] as string | undefined })
+ if (message.id === undefined) { response.writeHead(202).end(); return }
+ if (message.method === 'tools/call') {
+ response.writeHead(200, { 'Content-Type': 'text/event-stream' })
+ response.end(`event: message\ndata: ${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/progress', params: { progress: 1 } })}\n\ndata: ${JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { content: 'done' } })}\n\n`)
+ return
+ }
+ const result = message.method === 'initialize' ? { protocolVersion: '2025-06-18' } : { tools: [] }
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Mcp-Session-Id': 'session-1' })
+ response.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }))
+ })
+ })
+ return { url: `http://127.0.0.1:${await listen(server)}/mcp`, heard }
+}
+
+/** A process of another account on the bridge's old port, hearing everything sent there. */
+async function holder(): Promise<{ port: number; heard: string[] }> {
+ const heard: string[] = []
+ const server = createServer((request, response) => {
+ heard.push(request.url ?? '')
+ response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: 'false answer' } }))
+ })
+ return { port: await listen(server), heard }
+}
+
+/** The shim as a real process, as a client runs it from its entry. */
+function shimProcess(code: string, socket: string, grace = 5000): ChildProcessWithoutNullStreams {
+ const shim = join(vault.root, 'mcp-shim.mjs')
+ mkdirSync(vault.root, { recursive: true })
+ writeFileSync(shim, MCP_SHIM_SOURCE)
+ return spawn(process.execPath, [shim, '--socket', socket, code, '--grace-ms', String(grace)])
+}
+
+/** Speak to the shim as an MCP client: newline-delimited JSON-RPC over its stdin and stdout. */
+function client(code: string, socket: string): { send(message: unknown): void; end(): void; lines: unknown[]; done: Promise<number | null> } {
+ const child = shimProcess(code, socket), lines: unknown[] = []
+ let held = ''
+ child.stdout.on('data', chunk => {
+ held += String(chunk)
+ for (let at = held.indexOf('\n'); at >= 0; at = held.indexOf('\n')) { lines.push(JSON.parse(held.slice(0, at))); held = held.slice(at + 1) }
+ })
+ return { send: message => child.stdin.write(JSON.stringify(message) + '\n'), end: () => child.stdin.end(), lines,
+ done: new Promise(resolve => child.on('exit', resolve)) }
+}
+
+/** The shim's arguments as Claude Code's entry names them. */
+function claudeEntry(code: string): { type?: string; url?: string; command?: string; args?: string[] } {
+ return (JSON.parse(readFileSync(join(home, '.claude.json'), 'utf8')) as { mcpServers: Record<string, never> }).mcpServers[code]
+}
+const socketOf = (entry: { args?: string[] }): string => entry.args![entry.args!.indexOf('--socket') + 1]
+
+beforeEach(() => {
+ home = mkdtempSync('/tmp/hmcp-')
+ env = { HOME: home, PATH: '', XDG_CONFIG_HOME: join(home, '.config'), CODEX_HOME: join(home, '.codex') }
+ mkdirSync(join(home, '.codex'))
+ vault = new Store(join(home, 'c'), env)
+})
+afterEach(() => { while (closers.length) closers.pop()!(); rmSync(home, { recursive: true, force: true }) })
+
+describe.skipIf(process.platform === 'win32')('the MCP clients\' way to the bridge', () => {
+ it('a holder of the old port receives no tool call, and tools still work through the shim', async () => {
+ const fake = await upstream(), port = await holder()
+ env.HARNESS_CONNECTIONS_PORT = String(port.port)
+ vault.save('linear', { access_token: 'secret-linear', source: 'dcr', mcp_entry: { url: fake.url, headers: { authorization: 'Bearer secret-linear' } } })
+ // What a client's configuration names is all it has: no address, so the holder is never asked.
+ writeJson(join(home, '.claude.json'))
+ sync(vault, { ...env, CLAUDE_CONFIG_DIR: home })
+ const entry = claudeEntry('linear')
+ expect(JSON.stringify(entry)).not.toContain(String(port.port))
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ expect(lstatSync(socketOf(entry)).mode & 0o777).toBe(0o600)
+
+ const shim = client('linear', socketOf(entry))
+ shim.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} })
+ shim.send({ jsonrpc: '2.0', method: 'notifications/initialized' })
+ shim.send({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'x' } })
+ shim.end()
+ await shim.done
+
+ expect(port.heard).toEqual([])
+ expect(fake.heard.map(h => h.method)).toEqual(['initialize', 'notifications/initialized', 'tools/call'])
+ expect(fake.heard[1]).toMatchObject({ session: 'session-1', version: '2025-06-18' })
+ expect(fake.heard[2]).toMatchObject({ session: 'session-1', auth: 'Bearer secret-linear' })
+ expect(shim.lines).toEqual([
+ { jsonrpc: '2.0', id: 1, result: { protocolVersion: '2025-06-18' } },
+ { jsonrpc: '2.0', method: 'notifications/progress', params: { progress: 1 } },
+ { jsonrpc: '2.0', id: 2, result: { content: 'done' } },
+ ])
+ })
+
+ it('with the daemon down, says so and sends nothing to the port', async () => {
+ const port = await holder()
+ env.HARNESS_CONNECTIONS_PORT = String(port.port)
+ const shim = client('linear', bridgeSocketPath(vault)!)
+ shim.send({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: {} })
+ shim.send({ jsonrpc: '2.0', method: 'notifications/cancelled' })
+ shim.end()
+ await shim.done
+ expect(port.heard).toEqual([])
+ expect(shim.lines).toEqual([{ jsonrpc: '2.0', id: 7, error: { code: -32001, message: expect.stringContaining('Harness is not running') } }])
+ })
+
+ it('says the bridge\'s refusal under the id of the request it answers', async () => {
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const shim = client('nothing-here', bridgeSocketPath(vault)!)
+ shim.send({ jsonrpc: '2.0', id: 9, method: 'tools/list' })
+ shim.end()
+ await shim.done
+ expect(shim.lines).toEqual([{ jsonrpc: '2.0', id: 9, error: { code: -32001, message: expect.any(String) } }])
+ })
+
+ it('the socket reaches MCP servers only: no list of the connections, no key-only API, and no other address', async () => {
+ const fake = await upstream()
+ vault.save('linear', { access_token: 'secret-linear', source: 'dcr', mcp_entry: { url: fake.url, headers: {} } })
+ const socket = bridgeSocketPath(vault)!
+ const local = await serveBridgeSocket(vault, socket)
+ closers.push(() => local.close())
+ const ask = (path: string, headers: Record<string, string> = {}): Promise<number> => new Promise((resolve, reject) => {
+ const sent = httpRequest({ socketPath: socket, path, method: 'POST', headers }, answer => { answer.resume(); resolve(answer.statusCode ?? 0) })
+ sent.on('error', reject)
+ sent.end('{}')
+ })
+ expect(await ask('/local/connections')).toBe(404)
+ expect(await ask('/local/linear/api/x')).toBe(404)
+ expect(await ask('/other/linear/mcp')).toBe(404)
+ // A page cannot reach a socket; a request naming one is refused all the same.
+ expect(await ask('/local/linear/mcp', { origin: 'https://evil.example' })).toBe(403)
+ expect(fake.heard).toEqual([])
+ })
+
+ it('answers a request the service left unanswered, so the client does not wait for ever', async () => {
+ const silent = createServer((_request, response) => response.writeHead(200, { 'Content-Type': 'text/event-stream' }).end())
+ const port = await listen(silent)
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: `http://127.0.0.1:${port}/mcp`, headers: {} } })
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const shim = client('linear', bridgeSocketPath(vault)!)
+ shim.send({ jsonrpc: '2.0', id: 4, method: 'tools/list' })
+ shim.end()
+ await shim.done
+ expect(shim.lines).toEqual([{ jsonrpc: '2.0', id: 4, error: { code: -32001, message: expect.stringContaining('could not be read') } }])
+ })
+
+ it('a line that is no JSON-RPC is answered as a parse error, and the next still goes', async () => {
+ const fake = await upstream()
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: fake.url, headers: {} } })
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const child = shimProcess('linear', bridgeSocketPath(vault)!)
+ const out: string[] = []
+ child.stdout.on('data', chunk => out.push(String(chunk)))
+ child.stdin.write('not json\n')
+ child.stdin.end(JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'tools/list' }) + '\n')
+ await new Promise(resolve => child.on('exit', resolve))
+ const lines = out.join('').trim().split('\n').map(line => JSON.parse(line) as { id: unknown; error?: { code: number } })
+ expect(lines[0]).toMatchObject({ id: null, error: { code: -32700 } })
+ expect(lines[1]).toMatchObject({ id: 3 })
+ })
+
+ it('the entries name the shim, with no port and no key, for every client', () => {
+ env.HARNESS_CONNECTIONS_PORT = '51793'
+ vault.save('linear', { access_token: 'secret-linear', source: 'dcr', mcp_entry: { url: 'https://mcp.linear.app/mcp', headers: {} } })
+ mkdirSync(join(home, '.config', 'opencode'), { recursive: true })
+ const paths = { CLAUDE_CONFIG_DIR: home }
+ // `claude` on the PATH and an empty Codex config make them installed.
+ const claude = join(home, '.claude.json'), codex = join(home, '.codex', 'config.toml'), opencode = join(home, '.config', 'opencode', 'opencode.json')
+ for (const path of [claude, opencode]) writeJson(path)
+ writeJson(codex, '')
+ sync(vault, { ...env, ...paths })
+ const entry = claudeEntry('linear')
+ expect(entry).toMatchObject({ type: 'stdio', command: expect.any(String) })
+ expect(entry.url).toBeUndefined()
+ expect(entry.args!.slice(-3)).toEqual(['--socket', bridgeSocketPath(vault), 'linear'])
+ expect(socketOf(entry)).toBe(bridgeSocketPath(vault))
+ const texts = [claude, codex, opencode].map(path => readFileSync(path, 'utf8'))
+ for (const text of texts) {
+ expect(text).not.toContain('127.0.0.1')
+ expect(text).not.toContain('51793')
+ expect(text).toContain('mcp-shim.mjs')
+ }
+ expect(texts[1]).toContain('[mcp_servers.linear]\ncommand = ')
+ expect(JSON.parse(texts[2]).mcp.linear).toMatchObject({ type: 'local', enabled: true, command: expect.arrayContaining(['--socket', 'linear']) })
+ })
+
+ it('an entry names no running script: the shim in the private folder, by Harness\'s own node', () => {
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: 'https://mcp.linear.app/mcp', headers: {} } })
+ writeJson(join(home, '.claude.json'))
+ sync(vault, { ...env, CLAUDE_CONFIG_DIR: home })
+ const entry = claudeEntry('linear')
+ expect(entry.command).toBe(managedNodePath())
+ expect(entry.args).toEqual([join(vault.root, 'mcp-shim.mjs'), '--socket', bridgeSocketPath(vault), 'linear'])
+ expect(JSON.stringify(entry)).not.toContain(process.argv[1])
+ expect(readFileSync(entry.args![0], 'utf8')).toBe(MCP_SHIM_SOURCE)
+ expect(lstatSync(entry.args![0]).mode & 0o777).toBe(0o600)
+ })
+
+ it('the entry a daemon writes from a lean bundle runs: nothing in it depends on the daemon\'s own script', async () => {
+ const fake = await upstream()
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: fake.url, headers: {} } })
+ writeJson(join(home, '.claude.json'))
+ const running = process.argv[1]
+ process.argv[1] = '/lean/0123/harnessd.mjs'
+ try { sync(vault, { ...env, CLAUDE_CONFIG_DIR: home }) } finally { process.argv[1] = running }
+ const entry = claudeEntry('linear')
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const child = spawn(entry.command!, entry.args!)
+ const out: string[] = []
+ child.stdout.on('data', chunk => out.push(String(chunk)))
+ child.stdin.end(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) + '\n')
+ expect(await new Promise(resolve => child.on('exit', resolve))).toBe(0)
+ expect(JSON.parse(out.join(''))).toMatchObject({ id: 1, result: { protocolVersion: '2025-06-18' } })
+ })
+
+ it('opens a new session when the service forgets this one, once, and the client never hears of it', async () => {
+ const heard: Array<{ method: string; session?: string }> = []
+ let live = 'one', opens = 0
+ const server = createServer((request, response) => {
+ let raw = ''
+ request.on('data', chunk => { raw += chunk })
+ request.on('end', () => {
+ const message = JSON.parse(raw) as { id?: number; method: string }
+ heard.push({ method: message.method, session: request.headers['mcp-session-id'] as string | undefined })
+ if (message.method === 'initialize') {
+ live = `session-${++opens}`
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Mcp-Session-Id': live }).end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { protocolVersion: '2025-06-18', opens } }))
+ return
+ }
+ if (request.headers['mcp-session-id'] !== live) { response.writeHead(404).end(); return }
+ if (message.id === undefined) { response.writeHead(202).end(); return }
+ response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { ok: true } }))
+ })
+ })
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: `http://127.0.0.1:${await listen(server)}/mcp`, headers: {} } })
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const shim = client('linear', bridgeSocketPath(vault)!)
+ shim.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} })
+ shim.send({ jsonrpc: '2.0', method: 'notifications/initialized' })
+ await vi.waitFor(() => expect(heard.map(h => h.method)).toContain('notifications/initialized'))
+ live = 'gone'
+ shim.send({ jsonrpc: '2.0', id: 2, method: 'tools/list' })
+ shim.end()
+ await shim.done
+ expect(heard.map(h => h.method)).toEqual(['initialize', 'notifications/initialized', 'tools/list', 'initialize', 'notifications/initialized', 'tools/list'])
+ expect(heard.at(-1)!.session).toBe('session-2')
+ expect(shim.lines).toEqual([{ jsonrpc: '2.0', id: 1, result: { protocolVersion: '2025-06-18', opens: 1 } }, { jsonrpc: '2.0', id: 2, result: { ok: true } }])
+ })
+
+ it('a 404 while reopening does not wait on itself: the request is answered and the shim ends', async () => {
+ let initializes = 0
+ const server = createServer((request, response) => {
+ let raw = ''
+ request.on('data', chunk => { raw += chunk })
+ request.on('end', () => {
+ const message = JSON.parse(raw) as { id?: number; method: string }
+ if (message.method === 'initialize') {
+ initializes++
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Mcp-Session-Id': `s${initializes}` }).end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} }))
+ return
+ }
+ // The first notification is taken; from then on nothing but `initialize` is, a connection going away.
+ if (message.method === 'notifications/initialized' && initializes === 1) { response.writeHead(202).end(); return }
+ response.writeHead(404).end()
+ })
+ })
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: `http://127.0.0.1:${await listen(server)}/mcp`, headers: {} } })
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const child = shimProcess('linear', bridgeSocketPath(vault)!, 60_000)
+ const out: string[] = []
+ child.stdout.on('data', chunk => out.push(String(chunk)))
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) + '\n')
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
+ child.stdin.end(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' }) + '\n')
+ expect(await new Promise(resolve => child.on('exit', resolve))).toBe(0)
+ const lines = out.join('').trim().split('\n').map(line => JSON.parse(line) as { id: number; error?: unknown })
+ expect(lines.find(line => line.id === 2)).toMatchObject({ error: { code: -32001 } })
+ })
+
+ it('a 404 with no session behind it is the answer, and a new session is tried only once', async () => {
+ let posts = 0
+ const server = createServer((request, response) => {
+ request.resume()
+ request.on('end', () => {
+ posts++
+ if (posts === 1) { response.writeHead(200, { 'Content-Type': 'application/json', 'Mcp-Session-Id': 's' }).end(JSON.stringify({ jsonrpc: '2.0', id: 1, result: {} })); return }
+ response.writeHead(posts === 2 ? 404 : 500).end()
+ })
+ })
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: `http://127.0.0.1:${await listen(server)}/mcp`, headers: {} } })
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const shim = client('linear', bridgeSocketPath(vault)!)
+ shim.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} })
+ shim.send({ jsonrpc: '2.0', id: 2, method: 'tools/list' })
+ shim.end()
+ await shim.done
+ expect(posts).toBe(3)
+ expect(shim.lines.at(-1)).toMatchObject({ id: 2, error: { code: -32001 } })
+ })
+
+ it('a service\'s event that is no JSON is skipped, and the answer after it still comes', async () => {
+ const server = createServer((request, response) => {
+ request.resume()
+ request.on('end', () => response.writeHead(200, { 'Content-Type': 'text/event-stream' })
+ .end(`data: keep-alive\n\ndata: ${JSON.stringify({ jsonrpc: '2.0', id: 5, result: { ok: 1 } })}\n\n`))
+ })
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: `http://127.0.0.1:${await listen(server)}/mcp`, headers: {} } })
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const shim = client('linear', bridgeSocketPath(vault)!)
+ shim.send({ jsonrpc: '2.0', id: 5, method: 'tools/list' })
+ shim.end()
+ await shim.done
+ expect(shim.lines).toEqual([{ jsonrpc: '2.0', id: 5, result: { ok: 1 } }])
+ })
+
+ it('a client gone leaves no process: a hung stream is dropped after a short grace', async () => {
+ const hung = createServer((request, response) => {
+ request.resume()
+ request.on('end', () => { response.writeHead(200, { 'Content-Type': 'text/event-stream' }); response.write(': still here\n\n') })
+ })
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: `http://127.0.0.1:${await listen(hung)}/mcp`, headers: {} } })
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ const child = shimProcess('linear', bridgeSocketPath(vault)!, 50)
+ child.stdin.end(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call' }) + '\n')
+ expect(await new Promise(resolve => child.on('exit', resolve))).toBe(0)
+ })
+
+ it('refuses a socket that is not private: too open, or in an open folder, or not a socket', async () => {
+ const socket = bridgeSocketPath(vault)!
+ const local = await serveBridgeSocket(vault, socket)
+ closers.push(() => local.close())
+ const ask = async (): Promise<unknown> => {
+ const shim = client('linear', socket)
+ shim.send({ jsonrpc: '2.0', id: 1, method: 'tools/list' })
+ shim.end()
+ await shim.done
+ return shim.lines[0]
+ }
+ const refused = { id: 1, error: { message: expect.stringContaining('not private') } }
+ chmodSync(socket, 0o666)
+ expect(await ask()).toMatchObject(refused)
+ chmodSync(socket, 0o600)
+ chmodSync(vault.root, 0o777)
+ expect(await ask()).toMatchObject(refused)
+ chmodSync(vault.root, 0o700)
+ await local.close()
+ writeFileSync(socket, 'not a socket')
+ expect(await ask()).toMatchObject(refused)
+ })
+
+ it('tightens a folder older than this code when it listens', async () => {
+ mkdirSync(vault.root, { recursive: true })
+ chmodSync(vault.root, 0o755)
+ const local = await serveBridgeSocket(vault, bridgeSocketPath(vault)!)
+ closers.push(() => local.close())
+ expect(lstatSync(vault.root).mode & 0o777).toBe(0o700)
+ })
+
+ it('a client\'s reply to the service is no request: an error under its id would answer the client\'s own', async () => {
+ const shim = client('linear', bridgeSocketPath(vault)!)
+ shim.send({ jsonrpc: '2.0', id: 8, result: { fine: true } })
+ shim.end()
+ await shim.done
+ expect(shim.lines).toEqual([])
+ })
+
+ it('moves an entry from the old address, and keeps the address where no socket fits', () => {
+ env.HARNESS_CONNECTIONS_PORT = '51793'
+ vault.save('linear', { access_token: 't', source: 'dcr', mcp_entry: { url: 'https://mcp.linear.app/mcp', headers: {} } })
+ const claude = join(home, '.claude.json')
+ writeJson(claude, JSON.stringify({ mcpServers: { linear: { type: 'http', url: 'http://127.0.0.1:51793/k/linear/mcp' } } }))
+ writePrivate(join(vault.root, 'projections.json'), { claude: ['linear'] })
+ sync(vault, { ...env, CLAUDE_CONFIG_DIR: home })
+ expect(claudeEntry('linear').url).toBeUndefined()
+ const long = new Store(join(home, 'x'.repeat(120)), env)
+ expect(bridgeSocketPath(long)).toBeNull()
+ expect(bridgeSocketPath(vault, 'win32')).toBeNull()
+ })
+})
+
+function writeJson(path: string, text = '{}'): void {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, text)
+}
diff --git a/cli/src/lib/connectors/mcpShimSource.ts b/cli/src/lib/connectors/mcpShimSource.ts
new file mode 100644
index 000000000..6a3b80053
--- /dev/null
+++ b/cli/src/lib/connectors/mcpShimSource.ts
@@ -0,0 +1,164 @@
+/**
+ * What an MCP client runs to reach a connection (follow-up of audit H1, docs/plans/2026-11-02-connections-bridge-stdio-shim-plan.md).
+ * A client on a loopback address talks to whoever holds that port, so another account that took it could read its tool calls and
+ * feed false answers to the owner's running agents. This talks stdio to the client and HTTP to the bridge over its 0600 socket. It
+ * holds no key, as reaching that socket is the credential, and it never falls back to a port: with the socket gone the daemon is
+ * down, and the client is told so.
+ *
+ * Its own small script, written into the vault's private folder as lib/buddyGuard.ts writes its guard, for three reasons found in
+ * review of #2558. An entry naming the running script would name the lean bundle from the daemon, which has no CLI, and from any
+ * `harness connections` a worktree that may be removed. An entry naming cli.js would load all of it, about 45 MiB, once per
+ * connection per agent. And the updater ships only cli.js and notify.mjs, so a third file there would need its manifest changed.
+ * Node's built-ins only: nothing else is beside it.
+ *
+ * The client's stream is newline-delimited JSON-RPC (MCP's stdio transport). Each message becomes one POST of MCP's HTTP transport,
+ * whose answer is JSON or an event stream. `initialize` goes first and alone: its answer names the session the rest carry. A
+ * service's own unprompted stream (GET) is not opened, so `notifications/*_changed` are not relayed.
+ */
+import { SOCKET_KEY } from './bridge.js'
+
+export const MCP_SHIM_SOURCE = String.raw`#!/usr/bin/env node
+// Written by Harness (lib/connectors/mcpShimSource.ts); it is replaced at each daemon start.
+import { lstatSync } from 'node:fs'
+import { request as httpRequest } from 'node:http'
+import { dirname } from 'node:path'
+import { createInterface } from 'node:readline'
+
+const NOT_RUNNING = 'Harness is not running on this computer, so this connection cannot be reached. Start it and try again.'
+const UNREADABLE = "The connection's answer could not be read. Try again."
+const NOT_PRIVATE = "Harness's connection socket is not private to this account, so it was not used. Restart Harness."
+
+const [flag, socket, code, graceFlag, grace] = process.argv.slice(2)
+if (flag !== '--socket' || !socket || !code) { console.error('usage: mcp-shim --socket PATH CODE'); process.exit(2) }
+// How long open requests get once the client has gone, so a hung stream does not leave a process behind.
+const graceMs = graceFlag === '--grace-ms' ? Number(grace) : 5000
+const path = '/${SOCKET_KEY}/' + encodeURIComponent(code) + '/mcp'
+
+// Whether the socket is what the daemon made: 0600, this account's, in a folder only this account can write to.
+function socketState() {
+ try {
+ const uid = process.getuid?.()
+ const file = lstatSync(socket), folder = lstatSync(dirname(socket))
+ if (!file.isSocket() || (file.mode & 0o777) !== 0o600 || !folder.isDirectory() || (folder.mode & 0o022) !== 0) return 'open'
+ return uid !== undefined && (file.uid !== uid || folder.uid !== uid) ? 'open' : 'private'
+ } catch (error) {
+ return error.code === 'ENOENT' ? 'absent' : 'open'
+ }
+}
+
+// A client that went away closes this stream: nothing more to say, and no reason to fall over saying it.
+process.stdout.on('error', () => {})
+let closing = false
+const say = (message) => { if (!closing) process.stdout.write(JSON.stringify(message) + '\n') }
+const refuse = (id, errorCode, message) => say({ jsonrpc: '2.0', id, error: { code: errorCode, message } })
+let session, version
+// The client's initialize and what it sent after, to open a new session when the service forgets this one.
+let opening = null, opened = null
+const open = new Set()
+
+// One answer: JSON, or an event stream whose every data is a message of its own. quiet: for this shim alone.
+const relay = (answer, sent, quiet) => new Promise((resolve, reject) => {
+ const header = answer.headers['mcp-session-id']
+ if (typeof header === 'string') session = header
+ const status = answer.statusCode ?? 500
+ const streaming = String(answer.headers['content-type'] ?? '').includes('text/event-stream')
+ const asked = sent.method !== undefined && sent.id !== undefined
+ let held = '', answered = false
+ const take = (raw) => {
+ let message
+ // Not ours to read, a service's keep-alive say: it must not end the client's connection.
+ try { message = JSON.parse(raw) } catch { return }
+ answered ||= message.id === sent.id
+ if (sent.method === 'initialize' && typeof message.result?.protocolVersion === 'string') version = message.result.protocolVersion
+ if (!quiet) say(message)
+ }
+ // An event ends at a blank line; its data lines joined are its message.
+ const events = () => {
+ for (let at = held.search(/\r?\n\r?\n/); at >= 0; at = held.search(/\r?\n\r?\n/)) {
+ const event = held.slice(0, at)
+ held = held.slice(at).replace(/^\r?\n\r?\n/, '')
+ const data = event.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n')
+ if (data) take(data)
+ }
+ }
+ answer.setEncoding('utf8')
+ answer.on('data', (chunk) => { held += chunk; if (streaming) events() })
+ answer.on('error', reject)
+ answer.on('end', () => {
+ if (streaming) { held += '\n\n'; events() }
+ else if (held.trim() && status < 300) take(held)
+ else if (status >= 300 && asked) {
+ // The bridge's refusal names no request: this one is what it answers.
+ let reason = 'The connection answered ' + status + '.'
+ try { reason = JSON.parse(held).error?.message ?? reason } catch { /* not its JSON */ }
+ if (!quiet) refuse(sent.id, -32001, reason)
+ answered = true
+ }
+ // A client would wait for ever on a request nothing answered.
+ if (asked && !answered && !quiet) refuse(sent.id, -32001, UNREADABLE)
+ resolve()
+ })
+})
+
+// One POST; its status, or 0 when none came.
+const post = (raw, sent, quiet = false, retried = false) => new Promise((resolve) => {
+ const asked = sent.method !== undefined && sent.id !== undefined
+ const failed = (reason) => { if (asked && !quiet) refuse(sent.id, -32001, reason); resolve(0) }
+ const state = socketState()
+ if (state !== 'private') { failed(state === 'absent' ? NOT_RUNNING : NOT_PRIVATE); return }
+ const request = httpRequest({ socketPath: socket, method: 'POST', path,
+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream',
+ ...(session ? { 'mcp-session-id': session } : {}), ...(version ? { 'mcp-protocol-version': version } : {}) } },
+ (answer) => {
+ open.delete(request)
+ // The service forgot the session (it restarted, or it expired). An HTTP client opens another on a 404; a stdio client
+ // cannot know to, so an agent running for days would lose this connection until it restarts.
+ if (answer.statusCode === 404 && session && !retried && sent.method !== 'initialize' && opening) {
+ answer.resume()
+ reopen().then((ok) => {
+ if (ok) post(raw, sent, quiet, true).then(resolve)
+ else failed(code + ' could not be reached. Try again.')
+ })
+ return
+ }
+ relay(answer, sent, quiet).then(() => resolve(answer.statusCode ?? 0), () => failed(UNREADABLE))
+ })
+ open.add(request)
+ request.on('error', () => { open.delete(request); failed(closing ? UNREADABLE : NOT_RUNNING) })
+ request.end(raw)
+})
+
+// A new session from the client's own initialize, its answer kept to this shim. Requests that fail together share it.
+let reopening = null
+const reopen = () => reopening ??= (async () => {
+ session = undefined
+ // Each marked as retried: a 404 here must not wait on the very reopen that sent it.
+ const status = await post(opening, JSON.parse(opening), true, true)
+ if (status >= 300 || status === 0) return false
+ if (opened) await post(opened, JSON.parse(opened), true, true)
+ return true
+})().finally(() => { reopening = null })
+
+const running = new Set()
+let first = null
+for await (const raw of createInterface({ input: process.stdin, crlfDelay: Infinity })) {
+ if (!raw.trim()) continue
+ let sent
+ try {
+ sent = JSON.parse(raw)
+ if (!sent || typeof sent !== 'object') throw new Error('not a message')
+ } catch { refuse(null, -32700, 'That line is not JSON.'); continue }
+ // initialize alone: nothing else goes until its answer has named the session. Its notification goes in order too.
+ if (first) await first
+ if (sent.method === 'initialize') opening = raw
+ else if (sent.method === 'notifications/initialized') opened = raw
+ const send = post(raw, sent)
+ if (sent.method === 'initialize' || sent.id === undefined) first = send
+ running.add(send)
+ send.finally(() => { running.delete(send) })
+}
+// The client has gone. What is open gets a moment; a hung stream must not keep this process.
+await Promise.race([Promise.all(running), new Promise((resolve) => { setTimeout(resolve, graceMs).unref() })])
+closing = true
+process.exit(0)
+`
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index 015820bca..fa6f26208 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -38,6 +38,7 @@ export interface CreateAgentPaneDeps<Ref extends TerminalRuntimeRef = TerminalRu
gridLaunchRecord?: GridLaunchRecord | null
scmLaunchRecord?: ScmLaunchRecord | null
codexHome?: string | null
+ claudeHome?: string | null
dsh?: string | null
swarmSkill?: SwarmSkill
dshRuntime?: string | null
@@ -80,6 +81,8 @@ export interface CreateAgentPaneDeps<Ref extends TerminalRuntimeRef = TerminalRu
scmLaunchRecord?: ScmLaunchRecord | null
/** The CODEX_HOME folder this agent was launched against, if the caller chose one; codex only. */
codexHome?: string | null
+ /** The CLAUDE_CONFIG_DIR folder (a Claude profile) this agent was launched against, if the caller chose one; claude only. */
+ claudeHome?: string | null
/** The domain-specific harness this agent is created as, if any. */
dsh?: string | null
swarmSkill?: SwarmSkill
@@ -141,6 +144,7 @@ export async function createAndRegisterPane<Ref extends TerminalRuntimeRef = Ter
gridLaunchRecord: deps.gridLaunchRecord,
scmLaunchRecord: deps.scmLaunchRecord,
codexHome: deps.codexHome,
+ claudeHome: deps.claudeHome,
dsh: deps.dsh,
dshRuntime: deps.dshRuntime,
...(deps.swarmSkill ? { swarmSkill: deps.swarmSkill } : {}),
diff --git a/cli/src/lib/engineHomes.spec.ts b/cli/src/lib/engineHomes.spec.ts
index 50870a34b..2e2610b22 100644
--- a/cli/src/lib/engineHomes.spec.ts
+++ b/cli/src/lib/engineHomes.spec.ts
@@ -5,7 +5,7 @@ import { dirname, join, resolve } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { env } from '../config/env.js'
import {
- adoptEngineHomes, adoptHomes, claudeProjectsRoots, codexHomeRoots, launchClaudeConfigDir, launchCodexHome, movedEngineHomes, movedHomes,
+ adoptEngineHomes, adoptHomes, claudeProjectsRoots, codexHomeRoots, launchClaudeConfigDir, launchCodexHome, launchHomeOf, movedEngineHomes, movedHomes,
ownHomeOf, profileEnvironment, resetEngineHomes, sessionClaudeHome, sessionCodexHome, sessionFolderOf, sessionRoots,
confirmHomes, durableEngineHomes, nativeSessionRoots, recoverEngineHomes, engineHomeSnapshot,
} from './engineHomes.js'
@@ -287,6 +287,12 @@ describe('the home an engine launched now uses', () => {
expect(launchClaudeConfigDir({})).toBe(homedir())
})
+ it('launchHomeOf honours the profile for CLAUDE_CONFIG_DIR homes (the trust file resolves into it)', () => {
+ const trustHome = { variable: 'CLAUDE_CONFIG_DIR', otherwise: 'home' } as const
+ expect(launchHomeOf(trustHome, '/profiles/work', { CLAUDE_CONFIG_DIR: '/moved' })).toBe('/profiles/work')
+ expect(launchHomeOf(trustHome, null, { CLAUDE_CONFIG_DIR: '/moved' })).toBe('/moved')
+ })
+
it('reads the login shell\'s environment over the daemon\'s own: the profile is what the pane runs', () => {
vi.stubEnv('CODEX_HOME', '/daemon-codex')
vi.stubEnv('CLAUDE_CONFIG_DIR', '/daemon-claude')
diff --git a/cli/src/lib/engineHomes.ts b/cli/src/lib/engineHomes.ts
index 3891dd8b2..439a0ec9a 100644
--- a/cli/src/lib/engineHomes.ts
+++ b/cli/src/lib/engineHomes.ts
@@ -370,7 +370,7 @@ export function launchClaudeConfigDir(environment: NodeJS.ProcessEnv = launchEnv
export function launchHomeOf(home: LaunchHome, profile: string | null | undefined, environment: NodeJS.ProcessEnv = launchEnvironment()): string {
if ('setting' in home) return launchHome(home.setting, profile, environment)
const personal = launchPersonalHome(environment)
- return movedHome(environment[home.variable]) || (home.otherwise === 'home' ? personal : join(personal, home.otherwise.folder))
+ return movedHome(profile || environment[home.variable]) || (home.otherwise === 'home' ? personal : join(personal, home.otherwise.folder))
}
/** The person's home folder for a launch made now: the HOME its shell sets, else this process's. */
diff --git a/cli/src/lib/ownerSubscriptions.spec.ts b/cli/src/lib/ownerSubscriptions.spec.ts
index f428cf418..23d9d33de 100644
--- a/cli/src/lib/ownerSubscriptions.spec.ts
+++ b/cli/src/lib/ownerSubscriptions.spec.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
@@ -10,6 +10,20 @@ import {
type OwnerSubscriptionDeps,
} from './ownerSubscriptions.js'
+// The `security` tool: a Keychain with the owner's item and a stale one under another account, each found by its -a.
+const security = vi.hoisted(() => ({ calls: [] as string[][], stdin: [] as string[] }))
+vi.mock('node:child_process', () => ({
+ execFile: (_command: string, args: string[], _options: unknown, done: (error: Error | null, out?: { stdout: string; stderr: string }) => void) => {
+ security.calls.push(args)
+ const account = args[args.indexOf('-a') + 1]
+ // Without -a the first match is the stale item.
+ const stdout = account === 'owner1' ? JSON.stringify({ claudeAiOauth: { accessToken: 'old', refreshToken: 'r-old', expiresAt: 1 } })
+ : ' "acct"<blob>="stale"\n'
+ done(null, { stdout, stderr: '' })
+ },
+ spawn: () => ({ on: (event: string, cb: (code: number) => void) => { if (event === 'close') setTimeout(cb, 0, 0) }, stdin: { end: (text: string) => { security.stdin.push(text) } } }),
+}))
+
let home: string
beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'owner-subscriptions-')) })
afterEach(() => { rmSync(home, { recursive: true, force: true }) })
@@ -97,6 +111,19 @@ describe('refreshing Claude', () => {
expect(JSON.parse(k.writes[0]!.secret).claudeAiOauth).toMatchObject({ accessToken: 'new', refreshToken: 'r-old', subscriptionType: 'max' })
})
+ it('writes the refreshed sign-in to the very Keychain item it read (same service and account), never a stale one', async () => {
+ process.env.USER = 'owner1'
+ security.calls.length = 0; security.stdin.length = 0
+ const vendor = tokenEndpoint({ access_token: 'new', refresh_token: 'r-new', expires_in: 60 })
+ const owner = createOwnerSubscriptions({ home, platform: 'darwin', now: () => NOW, lockDir: join(home, 'locks'), fetchImpl: vendor.fetchImpl })
+ expect(await owner.refresh('claude', await owner.read('claude'))).toMatchObject({ accessToken: 'new' })
+ const read = security.calls.find((args) => args.includes('-w'))!
+ const readItem = [read[read.indexOf('-s') + 1], read[read.indexOf('-a') + 1]]
+ const written = /-s "([^"]*)" -a "([^"]*)"/.exec(security.stdin.join(''))!
+ expect([written[1], written[2]]).toEqual(readItem)
+ expect(readItem).toEqual(['Claude Code-credentials', 'owner1'])
+ })
+
it('refreshes once when several requests find the token expired at the same time', async () => {
write('.claude/.credentials.json', claudeFile({ accessToken: 'old', refreshToken: 'r-old', expiresAt: NOW - 1 }))
const vendor = tokenEndpoint({ access_token: 'new', refresh_token: 'r-new', expires_in: 3600 })
diff --git a/cli/src/lib/ownerSubscriptions.ts b/cli/src/lib/ownerSubscriptions.ts
index ff08a2a18..a595c58e6 100644
--- a/cli/src/lib/ownerSubscriptions.ts
+++ b/cli/src/lib/ownerSubscriptions.ts
@@ -15,15 +15,15 @@
* ⚠️ Undocumented vendor contracts, see the constants below for what was verified and what is
* assumed.
*/
-import { execFile, spawn } from 'node:child_process'
+import { spawn } from 'node:child_process'
import { open, rename, stat, unlink, mkdir, writeFile } from 'node:fs/promises'
-import { homedir, userInfo } from 'node:os'
+import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
-import { promisify } from 'node:util'
import {
asRecord,
- CLAUDE_KEYCHAIN_SERVICE,
claudeCredentialsPath,
+ claudeKeychainAccount,
+ claudeKeychainService,
codexAuthPath,
jwtClaims,
parseJson,
@@ -33,8 +33,6 @@ import {
type ClaudeCredentialSource,
} from './agentCredentials.js'
-const execFileAsync = promisify(execFile)
-
/**
* Claude Code's OAuth refresh. **Verified** against the Claude Code 2.1.283 binary on the author's
* machine (2026-10-19): `TOKEN_URL: "https://platform.claude.com/v1/oauth/token"` and
@@ -149,7 +147,7 @@ export function createOwnerSubscriptions(deps: OwnerSubscriptionDeps = {}): Owne
}
const root = JSON.stringify({ ...stored.root, claudeAiOauth: oauth })
if (stored.source === 'keychain') {
- const account = (await keychain.account()) ?? userInfo().username
+ const account = (await keychain.account()) ?? claudeKeychainAccount()
await keychain.write(account, root)
} else {
await writeKeepingMode(claudeCredentialsPath(home), root)
@@ -305,16 +303,8 @@ async function acquireLock(path: string): Promise<() => Promise<void>> {
*/
export function securityKeychain(): KeychainWriter {
return {
- async account() {
- try {
- // Attributes only — no `-w`, so the secret is not printed.
- const { stdout } = await execFileAsync('security', ['find-generic-password', '-s', CLAUDE_KEYCHAIN_SERVICE], { timeout: 5_000 })
- const match = /"acct"<blob>="([^"]*)"/.exec(stdout)
- return match?.[1] || null
- } catch {
- return null
- }
- },
+ // The item the read asks for (agentCredentials.ts readClaudeKeychain), so the write replaces that one and no other.
+ async account() { return claudeKeychainAccount() },
write(account, secret) {
return new Promise((resolve, reject) => {
const child = spawn('security', ['-i'], { stdio: ['pipe', 'ignore', 'ignore'] })
@@ -324,7 +314,7 @@ export function securityKeychain(): KeychainWriter {
child.on('close', (code) => code === 0
? resolve()
: reject(new OwnerSubscriptionError('Could not save the refreshed sign-in to the Keychain.')))
- child.stdin.end(`add-generic-password -U -s ${quoted(CLAUDE_KEYCHAIN_SERVICE)} -a ${quoted(account)} -X ${hex}\n`)
+ child.stdin.end(`add-generic-password -U -s ${quoted(claudeKeychainService())} -a ${quoted(account)} -X ${hex}\n`)
})
},
}
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index 6f13bc278..8d011d233 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -143,7 +143,7 @@ export const PRODUCT_USAGE_SETUP_METRICS = [...PRODUCT_USAGE_SURFACES.flatMap(su
* codes (listed below). Codes only, never a message. */
export const LAUNCH_ERROR_CODES = [
// What a new harness asked for, refused before anything starts (core/agents/launches.ts, lib/engineLaunch.ts).
- 'invalid_codex_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session',
+ 'invalid_codex_home', 'invalid_claude_home', 'invalid_prompt', 'prompt_too_long', 'prompt_unsupported', 'invalid_agent', 'invalid_session',
'invalid_started_by', 'agent_unsupported', 'invalid_runtime_profile', 'grid_engine_unsupported', 'codex_cli_too_old',
'invalid_launch_model', 'launch_model_unsupported',
// A new project's folder (lib/projectFolder.ts) and the launch's durable receipt (lib/agentCreationReceipt.ts).
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index b2f5d8b1a..552a2a1a7 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -181,6 +181,12 @@ export interface RegisteredSession {
* to a different grid.
*/
codexHome?: string | null
+ /**
+ * The CLAUDE_CONFIG_DIR folder (a Claude profile) this agent was launched against, if one was chosen instead of
+ * `~/.claude`. Claude only. Chosen once at creation like `codexHome`; the row is the relaunch source, so restart and
+ * resume come back in the same account.
+ */
+ claudeHome?: string | null
/**
* The Hermes home this session's history lives in — `~/.hermes/profiles/<name>` for an agent started
* with `hermes -p <name>`, null for this machine's default home.
@@ -1344,6 +1350,7 @@ class Registry {
gateway: raw.gateway === 'ori' ? 'ori' : null,
grid: normalizedGridAssignment(raw.grid),
codexHome: typeof rawCodexHome === 'string' && rawCodexHome ? rawCodexHome : null,
+ claudeHome: typeof raw?.claudeHome === 'string' && raw.claudeHome ? raw.claudeHome : null,
hermesHome: typeof raw?.hermesHome === 'string' && raw.hermesHome ? raw.hermesHome : null,
...normalizedForkedFrom((raw as { forkedFrom?: unknown }).forkedFrom),
dsh: normalizedDshId((raw as { dsh?: unknown }).dsh),
@@ -1509,6 +1516,7 @@ class Registry {
codexHome?: string | null
/** The Hermes home this session's store lives in, if it is not the default. Fill-only. */
hermesHome?: string | null
+ claudeHome?: string | null
/** The DSH read off the process's `HARNESS_DSH`, if any. Fill-only, like `codexHome`. */
dsh?: string | null
}):
@@ -1573,6 +1581,7 @@ class Registry {
if (input.gateway !== undefined) existing.gateway = input.gateway
if (input.grid !== undefined) existing.grid = input.grid
if (input.codexHome && !existing.codexHome) existing.codexHome = input.codexHome
+ if (input.claudeHome && !existing.claudeHome) existing.claudeHome = input.claudeHome
if (input.hermesHome && !existing.hermesHome) existing.hermesHome = input.hermesHome
if (input.dsh && !existing.dsh) existing.dsh = input.dsh
if (rowFingerprint(persistedRow(existing)) !== before) existing.touchedAt = Date.now()
@@ -1618,6 +1627,7 @@ class Registry {
gridWebSearch: null,
codexHome: input.codexHome ?? null,
hermesHome: input.hermesHome ?? null,
+ claudeHome: input.claudeHome ?? null,
dsh: input.dsh ?? null,
// A discovered pane's named agent is only visible in its argv; nothing here reads it, so the
// row cannot relaunch it as one. Fill-only, like `dsh`.
@@ -1657,6 +1667,7 @@ class Registry {
/** What the prepared workspace's SCM needs on every relaunch — see RegisteredSession.scmLaunch. */
scmLaunchRecord?: ScmLaunchRecord | null
codexHome?: string | null
+ claudeHome?: string | null
dsh?: string | null
dshRuntime?: string | null
swarmSkill?: SwarmSkill
@@ -1703,6 +1714,7 @@ class Registry {
gridWebSearch: input.gridLaunchRecord?.webSearch ?? null,
...(input.scmLaunchRecord ? { scmLaunch: input.scmLaunchRecord } : {}),
codexHome: input.codexHome ?? null,
+ claudeHome: input.claudeHome ?? null,
// A pane Harness opens starts in the default home; `hermes -p` is the person's own doing, and
// the row learns it from the session that lands in it. See RegisteredSession.hermesHome.
hermesHome: null,
@@ -2052,6 +2064,7 @@ class Registry {
// re-reads off the live process on every discovery) — a hook-triggered bind must carry it
// forward or the very first SessionStart hook would silently wipe the agent's chosen profile.
codexHome: existing?.codexHome ?? null,
+ claudeHome: existing?.claudeHome ?? null,
// The home the gate looked this session up in, or whatever the row already knew. Carried
// forward like every field here: a bind REBUILDS the row, and a home dropped at the first hook
// would send the mirror back to the default store (openharness#191).
diff --git a/cli/src/services/connectors.ts b/cli/src/services/connectors.ts
index dbced176d..aa2daafe0 100644
--- a/cli/src/services/connectors.ts
+++ b/cli/src/services/connectors.ts
@@ -1,6 +1,6 @@
/**
- * Connected services (lib/connectors): the MCP bridge every local agent's connector entries point at
- * (127.0.0.1:51793), and `connectors`, the desktop app's Connectors screen. Agents' entries are written
+ * Connected services (lib/connectors): the MCP bridge every local agent's connector entries reach, through a stdio shim to
+ * its 0600 socket (and on 127.0.0.1:51793 for clients still running on that address), and `connectors`, the desktop app's Connectors screen. Agents' entries are written
* again as it starts, so an agent installed since a service was connected gets it too.
*
* `connectors` takes `{action}`: `list`, `connect` {connector}, `flow` {flow}, `disconnect` {connector},
@@ -16,9 +16,9 @@
import type { Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import type { CoreApi, ServiceRequests } from '../core/api.js'
-import { bridgePort, saveBridgePort, sync } from '../lib/connectors/agents.js'
+import { bridgePort, bridgeSocketPath, saveBridgePort, sync } from '../lib/connectors/agents.js'
import { portHolderIsThisAccount } from '../lib/peerAccount.js'
-import { createBridge } from '../lib/connectors/bridge.js'
+import { createBridge, serveBridgeSocket } from '../lib/connectors/bridge.js'
import { services, type GatewayRow } from '../lib/connectors/catalog.js'
import { addApiKey, addCustom, cards, disconnect, Flows, signInFor } from '../lib/connectors/connect.js'
import * as gateway from '../lib/connectors/gateway.js'
@@ -83,6 +83,15 @@ function listen(bridge: Server, port: number, retryMs: number, moving?: Moving):
bridge.listen(port, '127.0.0.1')
}
+/** The MCP clients' way in (lib/connectors/mcpShimSource.ts). While a live socket is there (a core handing over), try again.
+ * Said once: its clients are told Harness is not running, though it is. */
+function listenSocket(vault: Store, path: string, retryMs: number, said = false): void {
+ serveBridgeSocket(vault, path).catch((error: unknown) => {
+ if (!said) console.warn(`[connectors] the bridge's socket is not listening (${path}), trying again: ${error instanceof Error ? error.message : String(error)}`)
+ setTimeout(() => listenSocket(vault, path, retryMs, true), retryMs).unref()
+ })
+}
+
export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps> & { holderIsMine?: (port: number) => Promise<boolean | null> } = {}): ServiceRequests {
const env = overrides.env ?? process.env
const store = overrides.vault ?? new Store(undefined, env)
@@ -110,6 +119,8 @@ export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps
listen(old, from, deps.retryMs)
},
} : undefined)
+ const socket = bridgeSocketPath(vault)
+ if (socket) listenSocket(vault, socket, deps.retryMs)
try { sync(vault, env) } catch { /* A config that cannot be written now is written at the next connect. */ }
// Connections the same on every computer of the account: read now, at each `connectors_changed`, and
diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.ts
index 6a692f4ab..c045f6c1d 100644
--- a/cli/src/services/models.spec.ts
+++ b/cli/src/services/models.spec.ts
@@ -23,6 +23,7 @@ import type { RuntimeModelOption } from '../lib/runtimeProfile.js'
import { ensureManagedGrid, startGridPinRecheck } from '../lib/runtimeInstall.js'
import { ApiConnections, apiConnectionsRequest } from '../lib/apiConnections.js'
import { apiModelsRequest, apiTargetAnswer, refreshApiFor, rememberSavedApis } from '../lib/apiModels.js'
+import { linkClaudeProfile, listClaudeProfiles, profileId } from '../lib/claudeProfiles.js'
import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'
import { fakeCore } from '../testing/fakeCore.js'
import { compactRuntimePickerModels, launchTarget, MODELS_REQUESTS, startModels, swarmLaunchTarget } from './models.js'
@@ -96,7 +97,14 @@ vi.mock('../lib/apiModels.js', () => ({
refreshApiFor: vi.fn(() => (override: unknown) => ({ override, apiBase: 'https://api.example.test/v1' })),
apiTargetAnswer: vi.fn(async () => ({ detail: 'This API is not saved. Add it in Models → APIs.' })),
}))
+vi.mock('../lib/claudeProfiles.js', async (importOriginal) => ({
+ profileId: (await importOriginal<typeof import('../lib/claudeProfiles.js')>()).profileId,
+ listClaudeProfiles: vi.fn((observed: string[]) => observed.map((path) => ({ id: 'p', path, label: 'Claude', reportLabel: 'Claude' }))),
+ offerAccount: vi.fn((_engine: string, path: string, offered: boolean) => (path ? { offered } : { error: 'INVALID_PATH' })),
+ linkClaudeProfile: vi.fn((path: string) => (path ? { profile: { id: 'p', path, label: 'Linked', reportLabel: 'Linked' } } : { error: 'INVALID_PATH' })),
+}))
vi.mock('../lib/codexProfiles.js', () => ({
+ defaultCodexHome: () => '/home/me/.codex',
listCodexProfiles: vi.fn((observed: string[]) => observed.map((path) => ({ path, label: 'Codex' }))),
linkCodexProfile: vi.fn((path: string) => (path ? { path, label: 'Linked' } : { error: 'INVALID_PATH' })),
}))
@@ -939,8 +947,12 @@ describe('the models service', () => {
it('codex_profiles_list: the folders this machine offers, with the ones the asker has seen; a failed scan is said', async () => {
const { ask } = setup()
- expect(await ask('codex_profiles_list', { observedPaths: ['/home/me/.codex-work', 7] })).toEqual({ profiles: [{ path: '/home/me/.codex-work', label: 'Codex' }] })
- expect(listCodexProfiles).toHaveBeenLastCalledWith(['/home/me/.codex-work'])
+ const { core } = setup()
+ const id = (path: string) => profileId(core.daemon.machineId(), 'codex', path)
+ expect(await ask('codex_profiles_list', { observedPaths: ['/home/me/.codex-work', 7] })).toEqual({ profiles: [{ path: '/home/me/.codex-work', label: 'Codex', id: id('/home/me/.codex-work') }] })
+ // The default Codex home answers with the one id of the default account, marked default.
+ expect(await ask('codex_profiles_list', { observedPaths: ['/home/me/.codex'] })).toEqual({ profiles: [{ path: '/home/me/.codex', label: 'Codex', id: id('default'), default: true }] })
+ expect(listCodexProfiles).toHaveBeenLastCalledWith(['/home/me/.codex'])
expect(await ask('codex_profiles_list')).toEqual({ profiles: [] })
vi.mocked(listCodexProfiles).mockImplementationOnce(() => { throw new Error('unreadable') })
expect(await ask('codex_profiles_list')).toEqual({ error: 'CODEX_PROFILES_FAILED' })
@@ -957,6 +969,37 @@ describe('the models service', () => {
expect(log).toHaveBeenCalledWith('[backend] dispatch codex_profile_link failed:', expect.any(Error))
log.mockRestore()
})
+
+ it('swarm_account_offer: takes the owner\'s explicit choice, and nothing less', async () => {
+ const { ask } = setup()
+ expect(await ask('swarm_account_offer', { engine: 'claude', path: '/p', offered: true })).toEqual({ offered: true })
+ expect(await ask('swarm_account_offer', { engine: 'codex', path: '/p', offered: false })).toEqual({ offered: false })
+ expect(await ask('swarm_account_offer', { engine: 'claude', path: '/p' })).toEqual({ error: 'INVALID_OFFER' })
+ expect(await ask('swarm_account_offer', { engine: 'claude', path: 42, offered: true })).toEqual({ error: 'INVALID_PATH' })
+ })
+
+ it('the Claude and Codex profile requests answer OWNER_REQUIRED to a guest', async () => {
+ const { requests } = setup()
+ for (const type of ['claude_profiles_list', 'claude_profile_link', 'codex_profiles_list', 'codex_profile_link', 'swarm_account_offer']) {
+ expect(await requests[type]!({ path: '/x' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ }
+ })
+
+ it('claude_profiles_list: the folders this machine offers under its own machine id; a failed scan is said', async () => {
+ const { ask, core } = setup()
+ expect(await ask('claude_profiles_list', { observedPaths: ['/home/me/.claude-work', 7] })).toEqual({ profiles: [{ id: 'p', path: '/home/me/.claude-work', label: 'Claude', reportLabel: 'Claude' }] })
+ expect(listClaudeProfiles).toHaveBeenLastCalledWith(['/home/me/.claude-work'], { machineId: core.daemon.machineId() })
+ expect(await ask('claude_profiles_list')).toEqual({ profiles: [] })
+ vi.mocked(listClaudeProfiles).mockImplementationOnce(() => { throw new Error('unreadable') })
+ expect(await ask('claude_profiles_list')).toEqual({ error: 'CLAUDE_PROFILES_FAILED' })
+ })
+
+ it('claude_profile_link: links the folder and answers the profile, or why not', async () => {
+ const { ask, core } = setup()
+ expect(await ask('claude_profile_link', { path: '/home/me/.claude-work' })).toEqual({ profile: { id: 'p', path: '/home/me/.claude-work', label: 'Linked', reportLabel: 'Linked' } })
+ expect(await ask('claude_profile_link', { path: 42 })).toEqual({ error: 'INVALID_PATH' })
+ expect(linkClaudeProfile).toHaveBeenLastCalledWith('', core.daemon.machineId())
+ })
})
})
})
diff --git a/cli/src/services/models.ts b/cli/src/services/models.ts
index cb9b4cf09..24ae783f7 100644
--- a/cli/src/services/models.ts
+++ b/cli/src/services/models.ts
@@ -19,7 +19,8 @@ import { installedDsh } from '../dsh/installed.js'
import { ApiConnections, apiConnectionsRequest } from '../lib/apiConnections.js'
import { apiModelsRequest, apiTargetAnswer, refreshApiFor, rememberSavedApis } from '../lib/apiModels.js'
import { appEngineOps, scanAppModels } from '../lib/appModels.js'
-import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'
+import { linkClaudeProfile, listClaudeProfiles, profileId, offerAccount } from '../lib/claudeProfiles.js'
+import { defaultCodexHome, linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'
import { createGridAccess, gridNamesLocal, reconcileGridAttach } from '../lib/gridAttach.js'
import { deriveHarnessGridName, resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'
import { ensureHarnessGrid } from '../lib/gridEnsure.js'
@@ -527,23 +528,55 @@ export function launchTargetRequests(core: CoreApi, onRemove: (connectionId: str
// Which CODEX_HOME folders THIS machine can offer — answered here, on the machine in question, for
// the same reason `engines_probe` is: a Codex profile is a folder on disk, and a folder on a Mac means
// nothing on the Docker rig it was asked about instead.
- codex_profiles_list: internalOnThrow('codex_profiles_list', (payload) => {
+ codex_profiles_list: internalOnThrow('codex_profiles_list', (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
const observed = Array.isArray(payload.observedPaths)
? payload.observedPaths.filter((p): p is string => typeof p === 'string')
: []
try {
- return { profiles: listCodexProfiles(observed) }
+ const machineId = core.daemon.machineId(), defaultHome = defaultCodexHome()
+ // Each account's one id (the default's is shared with the machine report); the default is marked, as Claude's is.
+ return { profiles: listCodexProfiles(observed).map((p) => p.path === defaultHome
+ ? { ...p, id: profileId(machineId, 'codex', 'default'), default: true } : { ...p, id: profileId(machineId, 'codex', p.path) }) }
} catch {
return { error: 'CODEX_PROFILES_FAILED' }
}
}),
- codex_profile_link: internalOnThrow('codex_profile_link', (payload) => {
+ codex_profile_link: internalOnThrow('codex_profile_link', (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
const path = typeof payload.path === 'string' ? payload.path : ''
const result = linkCodexProfile(path)
if ('error' in result) return { error: result.error }
return { profile: result }
}),
+
+ // The Claude counterpart: CLAUDE_CONFIG_DIR folders, with the ids and labels the Swarm switch picks from.
+ // Paths and account names are the owner's alone, so a guest gets nothing.
+ claude_profiles_list: internalOnThrow('claude_profiles_list', (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ const observed = Array.isArray(payload.observedPaths)
+ ? payload.observedPaths.filter((p): p is string => typeof p === 'string')
+ : []
+ try {
+ return { profiles: listClaudeProfiles(observed, { machineId: core.daemon.machineId() }) }
+ } catch {
+ return { error: 'CLAUDE_PROFILES_FAILED' }
+ }
+ }),
+
+ claude_profile_link: internalOnThrow('claude_profile_link', (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ return linkClaudeProfile(typeof payload.path === 'string' ? payload.path : '', core.daemon.machineId())
+ }),
+
+ // The owner's own choice to offer an account to the Swarm, or to take it back (lib/accountOffers.ts). Like the requests above it
+ // is theirs alone, and not sealed for the relay: Desktop asks this computer's own daemon.
+ swarm_account_offer: internalOnThrow('swarm_account_offer', (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ if (typeof payload.offered !== 'boolean') return { error: 'INVALID_OFFER' }
+ return offerAccount(String(payload.engine), typeof payload.path === 'string' ? payload.path : '', payload.offered)
+ }),
}
}
diff --git a/cli/src/services/usage.spec.ts b/cli/src/services/usage.spec.ts
index ed6ad53dd..e737d70d0 100644
--- a/cli/src/services/usage.spec.ts
+++ b/cli/src/services/usage.spec.ts
@@ -1,7 +1,12 @@
+import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { startUsage, startUsageInCore, USAGE_REQUESTS } from './usage.js'
import { emptyPorts } from '../core/api.js'
+import { linkClaudeProfile, profileId } from '../lib/claudeProfiles.js'
+import { linkCodexProfile } from '../lib/codexProfiles.js'
import { usageTarget } from '../lib/agentUsageWire.js'
const ASKER = { local: false, owner: true }
@@ -29,4 +34,63 @@ describe('the usage service', () => {
const requests = startUsage(fakeCore(), { read: async () => { throw new Error('keychain locked') } })
expect(await requests.usage_read!({}, ASKER)).toEqual({ error: 'USAGE_READ_FAILED' })
})
+
+ it('usage_read without a payload asks the reader for nothing in particular', async () => {
+ const read = vi.fn(async () => [])
+ await startUsage(fakeCore(), { read }).usage_read!({}, ASKER)
+ expect(read).toHaveBeenCalledWith(undefined)
+ })
+
+ it('usage_read with an unknown profile id answers PROFILE_UNKNOWN', async () => {
+ const read = vi.fn(async () => [])
+ const requests = startUsage(fakeCore(), { read })
+ for (const profile of [{ engine: 'claude', id: 'nope' }, { engine: 'codex', id: 'nope' }, { engine: 'gemini', id: 'default' }]) {
+ expect(await requests.usage_read!({ profile }, ASKER)).toEqual({ error: 'PROFILE_UNKNOWN' })
+ }
+ expect(read).not.toHaveBeenCalled()
+ })
+
+ it('usage_read for a profile is the owner\'s alone', async () => {
+ const read = vi.fn(async () => [])
+ expect(await startUsage(fakeCore(), { read }).usage_read!({ profile: { engine: 'claude', id: 'default' } }, { local: false, owner: false }))
+ .toEqual({ error: 'OWNER_REQUIRED' })
+ expect(read).not.toHaveBeenCalled()
+ })
+
+ it('usage_read for a default profile reads that provider only', async () => {
+ const read = vi.fn(async () => [])
+ await startUsage(fakeCore(), { read }).usage_read!({ profile: { engine: 'codex', id: 'default' } }, ASKER)
+ expect(read).toHaveBeenCalledWith({ only: 'codex' })
+ })
+
+ it('usage_read takes the default account by its hex id too, for both engines', async () => {
+ const read = vi.fn(async () => [])
+ const core = fakeCore()
+ const requests = startUsage(core, { read })
+ for (const engine of ['claude', 'codex'] as const) {
+ await requests.usage_read!({ profile: { engine, id: profileId(core.daemon.machineId(), engine, 'default') } }, ASKER)
+ }
+ expect(read.mock.calls).toEqual([[{ only: 'claude' }], [{ only: 'codex' }]])
+ })
+
+ it('usage_read finds a Claude and a Codex profile by id', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'usage-profile-'))
+ try {
+ const claude = join(dir, 'claude')
+ const codex = join(dir, 'codex')
+ mkdirSync(claude)
+ mkdirSync(codex)
+ const real = realpathSync(dir)
+ const core = fakeCore()
+ expect(linkClaudeProfile(claude, 'machine-1')).toHaveProperty('profile')
+ linkCodexProfile(codex)
+ const read = vi.fn(async () => [])
+ const requests = startUsage(core, { read })
+ await requests.usage_read!({ profile: { engine: 'claude', id: profileId('machine-1', 'claude', join(real, 'claude')) } }, ASKER)
+ await requests.usage_read!({ profile: { engine: 'codex', id: profileId('machine-1', 'codex', join(real, 'codex')) } }, ASKER)
+ expect(read.mock.calls).toEqual([[{ claudeHome: join(dir, 'claude') }], [{ codexHome: join(real, 'codex') }]])
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
})
diff --git a/cli/src/services/usage.ts b/cli/src/services/usage.ts
index 9242e4d50..c9feb98d5 100644
--- a/cli/src/services/usage.ts
+++ b/cli/src/services/usage.ts
@@ -8,7 +8,8 @@ import type { CorePorts } from '../core/api.js'
* the socket's switch as it was (docs/design/2026-10-06-core-boundary-next.md, step 4).
*/
import type { CoreApi, ServiceRequests } from '../core/api.js'
-import { readAccountUsage, type AccountUsageReading } from '../lib/accountUsage.js'
+import { readAccountUsage, type AccountUsageDeps, type AccountUsageReading } from '../lib/accountUsage.js'
+import { profileHome } from '../lib/claudeProfiles.js'
import { internalOnThrow } from './requestErrors.js'
/** The request usage answers for the apps, declared in core/api.ts for the core to route. */
@@ -16,18 +17,38 @@ export { USAGE_REQUESTS } from '../core/api.js'
export interface UsageDeps {
/** The vendors' answers. Injected so a spec reads no real home, Keychain or network. */
- read: () => Promise<AccountUsageReading[]>
+ read: (profile?: Pick<AccountUsageDeps, 'claudeHome' | 'codexHome' | 'only'>) => Promise<AccountUsageReading[]>
}
-export function startUsage(_core: CoreApi, deps: UsageDeps = { read: readAccountUsage }): ServiceRequests {
+/** The reader's arguments for one profile the machine knows (by the shared id rule, lib/claudeProfiles.ts profileHome), or null. */
+function readerOf(core: CoreApi, engine: unknown, id: unknown): Pick<AccountUsageDeps, 'claudeHome' | 'codexHome' | 'only'> | null {
+ if (typeof id !== 'string' || (engine !== 'claude' && engine !== 'codex')) return null
+ const home = profileHome(engine, id, core.daemon.machineId())
+ if (home === null) return null
+ return home === 'default' ? { only: engine } : engine === 'claude' ? { claudeHome: home } : { codexHome: home }
+}
+
+export function startUsage(core: CoreApi, deps: UsageDeps = { read: readAccountUsage }): ServiceRequests {
return {
// Two vendor round trips (up to 8s each, lib/accountUsage.ts). Answered when they settle, never in the
// connection's line: it is asked on connect beside the requests the terminal needs, and with no
// network it held them past the app's timeout while it was the socket's.
- usage_read: internalOnThrow('usage_read', () => deps.read().then(
- (providers) => ({ providers }),
- () => ({ error: 'USAGE_READ_FAILED' }),
- )),
+ // With a profile it answers for that one account only, and only to the machine's owner: the
+ // default reading is already open to guests, a second account's is not.
+ usage_read: internalOnThrow('usage_read', (payload, asker) => {
+ const wanted = (payload as { profile?: { engine?: unknown; id?: unknown } } | undefined)?.profile
+ let home: Pick<AccountUsageDeps, 'claudeHome' | 'codexHome' | 'only'> | undefined
+ if (wanted) {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ const found = readerOf(core, wanted.engine, wanted.id)
+ if (!found) return { error: 'PROFILE_UNKNOWN' }
+ home = found
+ }
+ return deps.read(home).then(
+ (providers) => ({ providers }),
+ () => ({ error: 'USAGE_READ_FAILED' }),
+ )
+ }),
}
}
diff --git a/cli/src/superTabs/fixtures/read/host-full.json b/cli/src/superTabs/fixtures/read/host-full.json
index ce19bc351..039600908 100644
--- a/cli/src/superTabs/fixtures/read/host-full.json
+++ b/cli/src/superTabs/fixtures/read/host-full.json
@@ -49,7 +49,8 @@
"email": "[email protected]",
"userId": "6a0000000000000000000002"
}
- ]
+ ],
+ "ledConversationId": "c00000000000000000000001"
},
{
"tabId": "f1a5c0de0000000000000001",
@@ -91,7 +92,8 @@
"email": "[email protected]",
"userId": "6a0000000000000000000002"
}
- ]
+ ],
+ "ledConversationId": null
}
],
"pool": {
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 0ca7f35a6..9b9c85442 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -20,9 +20,11 @@ import { attentionOf } from './attention.js'
import { prepareContribution, prepareTeamContribution } from './contribution.js'
import { homedir, hostname } from 'node:os'
import { recordsOtherFolder, scrubClaudeSession, type PurgeTarget, type ScrubTold } from './inCore/teamPurge.js'
-import { replacementObservations } from './replacements.js'
+import { RebindSender, replacementObservations } from './replacements.js'
import { TerminalHost } from './terminal.js'
import { LimitResume } from './limitResume.js'
+import { LeadSwitchRequests, type SwitchRow } from './leadSwitchRequest.js'
+import { isTeamDaemon } from './teamDaemon.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
import { placeLine, threadLine, workLine } from './deliveryContext.js'
@@ -446,6 +448,9 @@ export class SuperTabHost {
private running: Promise<void> | null = null
private stopsRunning: Promise<void> | null = null
private readonly releases = new Set<string>()
+ /** The switches the Swarm asked of this machine's PMs (leadSwitchRequest.ts). */
+ private readonly leadSwitches: LeadSwitchRequests
+ private readonly rebinds: RebindSender
/** Eligibility and failures belong to this stop and native runtime; a new runtime or stop gets a fresh decision. */
/** `failures` counts final answers toward the five tries; `waits` the transient ones behind the current backoff. */
private readonly releaseAttempts = new Map<string, { signature: string; failures: number; waits: number; retryAt: number; closed?: true }>()
@@ -533,6 +538,8 @@ export class SuperTabHost {
this.limitResume = new LimitResume(core, machineId, { now: this.now, log: this.log,
owns: async (tabId, assignmentId, harnessId) => (await this.sources.feed.fresh()).assignments
.some(a => a.tabId === tabId && a.assignmentId === assignmentId && a.harnessId === harnessId) })
+ this.rebinds = new RebindSender((path, body) => backend(this.core, 'POST', path, body), this.now)
+ this.leadSwitches = new LeadSwitchRequests(core, machineId, { now: this.now, log: this.log, team: isTeamDaemon })
this.sources = options.sources ?? { feed: new HostFeed(core, machineId, { now: this.now }), reads: new SwarmReads(core) }
this.journal = { version: 1, machineId, entries: {} }
if (existsSync(this.file)) {
@@ -1004,6 +1011,7 @@ export class SuperTabHost {
if (row.lead === true) {
leads.add(target.agent.harnessId)
this.keepAlive(target.agent.harnessId)
+ void this.leadSwitches.serve(target as unknown as SwitchRow).catch(error => this.log(`PM switch: ${error instanceof Error ? error.name : typeof error}`))
}
// Never adopt another live session as a replacement for the recorded harness.
if (!this.core.agents.byAgent(target.agent.harnessId) || !this.core.agents.terminalAvailable(target.agent.harnessId)) continue
@@ -1988,7 +1996,7 @@ export class SuperTabHost {
try {
for (const observation of await replacementObservations(this.core, this.machineId, rows)) {
if (this.stopped) return
- await backend(this.core, 'POST', observation.path, observation.body)
+ await this.rebinds.post(observation)
}
} catch (error) { this.log(error instanceof Error ? error.message : String(error)) }
}
diff --git a/cli/src/superTabs/leadSwitchRequest.spec.ts b/cli/src/superTabs/leadSwitchRequest.spec.ts
new file mode 100644
index 000000000..bdba0a228
--- /dev/null
+++ b/cli/src/superTabs/leadSwitchRequest.spec.ts
@@ -0,0 +1,362 @@
+import { mkdirSync, mkdtempSync, 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 type { Daemon } from '../agentClient/daemon.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { FIXTURE, readFixture } from './fixtures/read/index.js'
+import { LeadSwitchRequests, profileSignedIn, switchChangeId, type SwitchRow } from './leadSwitchRequest.js'
+
+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',
+ swarmSkill: { role: 'coordinator', key: 'swarm-lead', mode: 'orchestration', github: true } }
+
+function writeRecord(dataDir: string, changeId: string, at: number) {
+ const dir = join(dataDir, 'super-tabs', 'lead-switch')
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
+ writeFileSync(join(dir, `${createHash('sha256').update('h1').digest('hex')}.json`), JSON.stringify({ version: 1, agentId: 'h1', changeId, targetEngine: 'claude', at }), { mode: 0o600 })
+}
+
+function setup(options: { claim?: boolean; home?: string | null; team?: boolean; refuse?: string; live?: boolean; resultStale?: boolean; old?: Record<string, unknown>; signedIn?: boolean;
+ claimGate?: Promise<void>; claimFails?: boolean; createTimesOut?: boolean; createHeld?: boolean; noRecord?: boolean } = {}) {
+ const clock = { now: NOW }
+ const dataDir = mkdtempSync(join(tmpdir(), 'lead-switch-'))
+ const calls: Array<[string, Record<string, unknown>]> = []
+ const posted: Array<Record<string, unknown>> = []
+ const operationIds: string[] = []
+ const home = mkdtempSync(join(tmpdir(), 'lead-switch-home-'))
+ let live = options.live ?? true
+ const backend = vi.fn(async (_method: string, _path: string, body: unknown) => {
+ operationIds.push((body as { operationId: string }).operationId)
+ const command = (body as { command: Record<string, unknown> }).command
+ posted.push(command)
+ if (command.type === 'agent.switchClaim' && options.claimGate) await options.claimGate
+ if (command.type === 'agent.switchClaim' && options.claimFails) throw new Error('offline')
+ if (command.type === 'agent.switchClaim' && options.claim === false) return { status: 403, body: { success: false, error: { code: 'STALE_SWITCH', message: 'no' } } }
+ if (command.type === 'agent.switchResult' && options.resultStale) return { status: 403, body: { success: false, error: { code: 'STALE_SWITCH', message: 'settled' } } }
+ return { status: 200, body: { success: true, data: { result: {} } } }
+ })
+ const daemon: Daemon = { machineId: 'm1', close: vi.fn(), request: vi.fn(async (type, payload = {}) => {
+ calls.push([type, payload])
+ if (type === 'agent_handoff_prepare') {
+ return { agentId: 'h1', file: `.harness/handoff/h1-${payload.changeId}.md`, gitRepo: true, cwd: '/work', degraded: [] }
+ }
+ if (type === 'agent_close') {
+ live = false
+ // What the real close does once its stop went through (leadSwitch.ts leadSwitchEnded): the hold starts.
+ if (!options.noRecord) writeRecord(dataDir, String(payload.changeId), clock.now)
+ return { closed: true }
+ }
+ if (type === 'agent_create' && options.createTimesOut) throw new Error('timed out')
+ if (type === 'agent_create' && options.createHeld) return { creationId: payload.creationId, state: 'pending' }
+ if (type === 'agent_create') return options.refuse ? { error: options.refuse } : { agent: { id: 'h2' } }
+ return {}
+ }) }
+ const core = fakeCore({ dataDir, account: { backend },
+ agents: { byAgent: vi.fn((id: string) => id === 'h1' && live ? { ...PM, ...options.old } as never : undefined) } })
+ const profiles = vi.fn(() => options.home === undefined ? '/home/p1' : options.home)
+ 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 })
+ return { switches, calls, posted, daemon, profiles, operationIds, home, dataDir, clock, reopen: () => { live = true } }
+}
+
+describe('a PM host carrying out a switch the Swarm asked for', () => {
+ it('claims, prepares the handoff, closes with the change id, creates with creationId = changeId and the profile home, completes the handoff', async () => {
+ const t = setup()
+ await t.switches.serve(row())
+ expect(t.posted.map(c => c.type)).toEqual(['agent.switchClaim'])
+ 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[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' })
+ })
+
+ it('recreates the PM as a Swarm PM: its role, skill mode, GitHub token, start prompt, then the handoff', async () => {
+ const t = setup()
+ await t.switches.serve(row())
+ const create = t.calls.find(c => c[0] === 'agent_create')![1]
+ expect(create).toMatchObject({ swarmRole: 'lead', swarmSkillMode: 'orchestration', swarmGitHub: true, startedBy: 'agent', name: 'PM' })
+ const prompt = String(create.prompt)
+ expect(prompt.startsWith('You are the Product Manager of the project whose conversation is conv1')).toBe(true)
+ expect(prompt).toContain('Harness GitHub App token')
+ expect(prompt.indexOf('Context handoff')).toBeGreaterThan(prompt.indexOf('Harness GitHub App token'))
+ })
+
+ it('keeps a PM without GitHub off the token and names the role the row gives', async () => {
+ const t = setup({ old: { swarmSkill: { role: 'coordinator', key: 'swarm-lead' } } })
+ await t.switches.serve(row({}, { roleName: 'Lead dev' }))
+ const create = t.calls.find(c => c[0] === 'agent_create')![1]
+ expect(create).toMatchObject({ swarmRole: 'lead' })
+ expect(create).not.toHaveProperty('swarmGitHub')
+ expect(create).not.toHaveProperty('swarmSkillMode')
+ expect(String(create.prompt)).toContain('as its Lead dev')
+ })
+
+ it('refuses before closing a PM that has no Swarm skill or no conversation to rebuild its prompt from', async () => {
+ for (const [t, r] of [[setup({ old: { swarmSkill: undefined } }), row()], [setup(), row({}, { ledConversationId: undefined })]] as const) {
+ await t.switches.serve(r)
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false, error: 'the handoff could not be prepared' })
+ expect(t.calls).toEqual([])
+ }
+ })
+
+ it('asks the machine for offered accounts only, so one the owner never offered is refused as gone', async () => {
+ const t = setup({ home: null })
+ await t.switches.serve(row({ switchRequest: { id: 'sw1', engine: 'claude', profileId: 'abcdef0123456789' } }))
+ expect(t.profiles).toHaveBeenCalledWith('claude', 'abcdef0123456789', expect.anything(), { offeredOnly: true })
+ })
+
+ it('maps a permission mode the target engine lacks to ask, as Desktop does, and bypass follows the mode', async () => {
+ const t = setup({ old: { permissionMode: 'acceptEdits', bypassPermission: true } })
+ await t.switches.serve(row({ switchRequest: { id: 'sw1', engine: 'codex', profileId: 'p1' } }))
+ expect(t.calls.find(c => c[0] === 'agent_create')![1]).toMatchObject({ engine: 'codex', permissionMode: 'ask', bypassPermission: false })
+ const f = setup({ old: { permissionMode: 'full', bypassPermission: true } })
+ await f.switches.serve(row())
+ expect(f.calls.find(c => c[0] === 'agent_create')![1]).toMatchObject({ permissionMode: 'full', bypassPermission: true })
+ })
+
+ it('creates again without the model and effort when this machine refuses them, as a first start does', async () => {
+ const t = setup()
+ let creates = 0
+ vi.mocked(t.daemon.request).mockImplementation(async (type, payload = {}) => {
+ t.calls.push([type, { ...payload }])
+ if (type === 'agent_handoff_prepare') return { agentId: 'h1', file: `.harness/handoff/h1-${payload.changeId}.md`, gitRepo: true, cwd: '/work', degraded: [] }
+ if (type === 'agent_close') return { closed: true }
+ if (type === 'agent_create') return ++creates === 1 ? { error: 'LAUNCH_MODEL_UNSUPPORTED' } : { agent: { id: 'h2' } }
+ return {}
+ })
+ await t.switches.serve(row({ switchRequest: { ...request, model: 'opus', effort: 'high' } }))
+ const creating = t.calls.filter(c => c[0] === 'agent_create')
+ expect(creating).toHaveLength(2)
+ expect(creating[0][1]).toMatchObject({ model: 'opus', effort: 'high' })
+ expect(creating[1][1]).not.toHaveProperty('model')
+ expect(creating[1][1]).not.toHaveProperty('effort')
+ expect(t.calls.at(-1)![0]).toBe('agent_handoff_complete')
+ })
+
+ it('a second poll while the claim is in flight starts nothing and the run reports once', async () => {
+ let release!: () => void
+ const t = setup({ claimGate: new Promise<void>(r => { release = r }) })
+ const first = t.switches.serve(row())
+ await t.switches.serve(row())
+ release()
+ await first
+ expect(t.posted.filter(c => c.type === 'agent.switchClaim')).toHaveLength(1)
+ expect(t.calls.filter(c => c[0] === 'agent_handoff_prepare')).toHaveLength(1)
+ await t.switches.serve({ tabId: 'tab', agent: { id: 'a1', harnessId: 'h2' } })
+ expect(t.posted.filter(c => c.type === 'agent.switchResult')).toEqual([{ type: 'agent.switchResult', agentId: 'a1', switchId: 'sw1', ok: true }])
+ })
+
+ it('a claim that fails is not posted again on the next poll', async () => {
+ const t = setup({ claimFails: true })
+ await t.switches.serve(row())
+ await t.switches.serve(row())
+ expect(t.posted.filter(c => c.type === 'agent.switchClaim')).toHaveLength(1)
+ })
+
+ it('keeps the operation ids within the backend cap for a long switch id', async () => {
+ const t = setup()
+ const long = 'x'.repeat(160)
+ await t.switches.serve(row({ switchRequest: { ...request, id: long } }))
+ await t.switches.serve({ tabId: 'tab', agent: { id: 'a1', harnessId: 'h2' } })
+ expect(t.operationIds.length).toBe(2)
+ expect(t.operationIds.every(id => id.length <= 160)).toBe(true)
+ })
+
+ describe('after a restart of the host in the middle of a switch', () => {
+ const record = (t: ReturnType<typeof setup>, at: number) => writeRecord(t.dataDir, switchChangeId('sw1'), at)
+ it('does not claim or run again, and reports ok when the rebind lands', async () => {
+ const t = setup({ live: false })
+ record(t, NOW - 4 * 60_000)
+ await t.switches.serve(row())
+ expect(t.posted).toEqual([])
+ expect(t.calls).toEqual([])
+ await t.switches.serve({ tabId: 'tab', agent: { id: 'a1', harnessId: 'h2' } })
+ expect(t.posted).toEqual([{ type: 'agent.switchResult', agentId: 'a1', switchId: 'sw1', ok: true }])
+ })
+ it('reports the failure, without running again, once the old PM was reopened past its hold', async () => {
+ const t = setup()
+ record(t, NOW - 5 * 60_000)
+ await t.switches.serve(row())
+ expect(t.posted).toEqual([{ type: 'agent.switchResult', agentId: 'a1', switchId: 'sw1', ok: false, error: 'the new session did not start in time' }])
+ expect(t.calls).toEqual([])
+ })
+ it('starts normally when the record is older than the adoption window', async () => {
+ const t = setup()
+ record(t, NOW - 11 * 60_000)
+ await t.switches.serve(row())
+ expect(t.posted[0]).toMatchObject({ type: 'agent.switchClaim' })
+ })
+ })
+
+ it('reports ok once agent.rebind is seen for the PM', async () => {
+ const t = setup()
+ await t.switches.serve(row())
+ await t.switches.serve(row())
+ expect(t.posted.map(c => c.type)).toEqual(['agent.switchClaim'])
+ await t.switches.serve({ tabId: 'tab', agent: { id: 'a1', harnessId: 'h2' } })
+ expect(t.posted.at(-1)).toEqual({ type: 'agent.switchResult', agentId: 'a1', switchId: 'sw1', ok: true })
+ })
+
+ describe('a switch that failed after closing the PM', () => {
+ const HOLD = 3 * 60_000
+ const failure = { type: 'agent.switchResult', agentId: 'a1', switchId: 'sw1', ok: false, error: 'the new session could not start' }
+ const results = (t: ReturnType<typeof setup>) => t.posted.filter(c => c.type === 'agent.switchResult')
+
+ it('says nothing while the old PM is still closed, and reports once it is back past its hold', async () => {
+ const t = setup({ refuse: 'SPAWN_LIMIT' })
+ await t.switches.serve(row())
+ expect(t.calls.map(c => c[0])).toEqual(['agent_handoff_prepare', 'agent_close', 'agent_create'])
+ expect(results(t)).toEqual([])
+ t.clock.now += HOLD + 1000
+ await t.switches.serve(row())
+ expect(results(t)).toEqual([])
+ t.reopen()
+ await t.switches.serve(row())
+ expect(results(t)).toEqual([failure])
+ })
+
+ it('says the PM has not come back when it never reopened', async () => {
+ const t = setup({ refuse: 'SPAWN_LIMIT' })
+ await t.switches.serve(row())
+ t.clock.now += 10 * 60_000 + 1000
+ await t.switches.serve(row())
+ expect(results(t)).toEqual([{ ...failure, down: true }])
+ })
+
+ for (const [name, option] of [['times out', { createTimesOut: true }], ['is held', { createHeld: true }]] as const) {
+ it(`a create that ${name} can still start: no failure line, and the rebind reports ok`, async () => {
+ const t = setup(option)
+ await t.switches.serve(row())
+ expect(results(t)).toEqual([])
+ t.clock.now += 2 * 60_000
+ await t.switches.serve({ tabId: 'tab', agent: { id: 'a1', harnessId: 'h2' } })
+ expect(results(t)).toEqual([{ type: 'agent.switchResult', agentId: 'a1', switchId: 'sw1', ok: true }])
+ })
+ }
+
+ it('a new switch right after a failed one is carried out, not read as the old one', async () => {
+ const t = setup()
+ writeRecord(t.dataDir, switchChangeId('earlier'), NOW - 4 * 60_000)
+ await t.switches.serve(row())
+ expect(t.posted[0]).toMatchObject({ type: 'agent.switchClaim', switchId: 'sw1' })
+ expect(t.calls.map(c => c[0])).toContain('agent_close')
+ expect(t.calls[1][1]).toMatchObject({ changeId: switchChangeId('sw1') })
+ })
+ })
+
+ it('rebuilds the prompt from the chat the backend\'s own host row names', async () => {
+ const t = setup()
+ const real = readFixture<{ tabs: Array<{ roster: Array<Record<string, unknown>> }> }>('host-full').tabs[0].roster.find(r => r.lead === true)!
+ await t.switches.serve({ ...real, tabId: 'tab', agent: { id: 'a1', harnessId: 'h1', switchRequest: request } } as unknown as SwitchRow)
+ expect(String(t.calls.find(c => c[0] === 'agent_create')![1].prompt)).toContain(`conversation is ${FIXTURE.leadGroup}`)
+ })
+
+ it('refuses a signed-out default account before closing the PM, outside Team only', async () => {
+ const t = setup({ home: 'default', signedIn: false })
+ await t.switches.serve(row())
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false, error: 'that account is signed out' })
+ expect(t.calls).toEqual([])
+ const team = setup({ home: 'default', signedIn: false, team: true })
+ await team.switches.serve(row())
+ expect(team.calls.map(c => c[0])).toContain('agent_close')
+ })
+
+ it('refuses a signed-out account without closing the PM', async () => {
+ const t = setup({ signedIn: false })
+ await t.switches.serve(row())
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false, error: 'that account is signed out' })
+ expect(t.calls).toEqual([])
+ })
+
+ it('a Team daemon switches to its default account (the hex id counts), and a Codex PM keeps an engine home of its own', async () => {
+ const t = setup({ team: true, home: 'default' })
+ await t.switches.serve(row({ switchRequest: { id: 'sw1', engine: 'codex', profileId: 'abcdef0123456789' } }))
+ const create = t.calls.find(c => c[0] === 'agent_create')![1]
+ const changeId = String(create.creationId)
+ expect(create).toMatchObject({ engine: 'codex', codexHome: join(t.home, '.harness-pm-homes', changeId, 'codex') })
+ expect(create).not.toHaveProperty('claudeHome')
+ const c = setup({ team: true, home: 'default' })
+ await c.switches.serve(row())
+ expect(c.calls.find(x => x[0] === 'agent_create')![1]).not.toHaveProperty('claudeHome')
+ })
+
+ it('refuses a gone profile without closing the PM, and a Team daemon any profile but the default', async () => {
+ for (const t of [setup({ home: null }), setup({ team: true })]) {
+ await t.switches.serve(row())
+ expect(t.posted.at(-1)).toMatchObject({ type: 'agent.switchResult', ok: false, error: 'that account is no longer on this machine' })
+ expect(t.calls).toEqual([])
+ }
+ })
+
+ it('does nothing for a request it cannot claim', async () => {
+ const t = setup({ claim: false })
+ await t.switches.serve(row())
+ expect(t.posted.map(c => c.type)).toEqual(['agent.switchClaim'])
+ expect(t.calls).toEqual([])
+ })
+
+ it('treats a result the Swarm already settled as done', async () => {
+ const t = setup({ resultStale: true })
+ await t.switches.serve(row())
+ await t.switches.serve({ tabId: 'tab', agent: { id: 'a1', harnessId: 'h2' } })
+ const sent = t.posted.length
+ await t.switches.serve(row())
+ expect(t.posted.length).toBe(sent)
+ })
+})
+
+describe('whether a profile folder holds a sign-in', () => {
+ it('reads the default account where its engine keeps it', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'lead-switch-default-'))
+ const keychain = (raw: string | null) => ({ home, platform: 'linux' as const, readKeychain: async () => raw })
+ const good = JSON.stringify({ claudeAiOauth: { accessToken: 't', expiresAt: NOW + 1000 } })
+ expect(await profileSignedIn('claude', 'default', NOW, keychain(null), {})).toBe(false)
+ expect(await profileSignedIn('claude', 'default', NOW, keychain(good), {})).toBe(true)
+ expect(await profileSignedIn('claude', 'default', NOW, keychain(null), { ANTHROPIC_API_KEY: 'k' })).toBe(true)
+ expect(await profileSignedIn('codex', 'default', NOW, { home }, {})).toBe(false)
+ mkdirSync(join(home, '.codex'))
+ writeFileSync(join(home, '.codex', 'auth.json'), JSON.stringify({ OPENAI_API_KEY: 'k' }))
+ expect(await profileSignedIn('codex', 'default', NOW, { home }, {})).toBe(true)
+ })
+
+ const folder = () => mkdtempSync(join(tmpdir(), 'profile-signed-in-'))
+ const claude = (oauth: unknown) => ({ platform: 'linux' as const, readKeychain: async () => JSON.stringify({ claudeAiOauth: oauth }) })
+ const jwt = (claims: Record<string, unknown>) => ['e30', Buffer.from(JSON.stringify(claims)).toString('base64url'), 'sig'].join('.')
+ const codex = (tokens: unknown) => { const dir = folder(); writeFileSync(join(dir, 'auth.json'), JSON.stringify({ tokens })); return dir }
+
+ it('Claude: a token that has not expired, or one its refresh token renews, is signed in; none is not', async () => {
+ expect(await profileSignedIn('claude', folder(), NOW, { platform: 'linux', readKeychain: async () => null })).toBe(false)
+ expect(await profileSignedIn('claude', folder(), NOW, claude({ refreshToken: 'r' }))).toBe(false)
+ expect(await profileSignedIn('claude', folder(), NOW, claude({ accessToken: 'a' }))).toBe(true)
+ expect(await profileSignedIn('claude', folder(), NOW, claude({ accessToken: 'a', expiresAt: NOW + 1 }))).toBe(true)
+ expect(await profileSignedIn('claude', folder(), NOW, claude({ accessToken: 'a', expiresAt: NOW - 1, refreshToken: 'r' }))).toBe(true)
+ expect(await profileSignedIn('claude', folder(), NOW, claude({ accessToken: 'a', expiresAt: NOW - 1 }))).toBe(false)
+ })
+
+ it('Codex: the same rule over auth.json and the token\'s own expiry', async () => {
+ expect(await profileSignedIn('codex', folder(), NOW)).toBe(false)
+ expect(await profileSignedIn('codex', codex({}), NOW)).toBe(false)
+ expect(await profileSignedIn('codex', codex({ access_token: 'opaque' }), NOW)).toBe(true)
+ expect(await profileSignedIn('codex', codex({ access_token: jwt({ exp: NOW / 1000 + 60 }) }), NOW)).toBe(true)
+ expect(await profileSignedIn('codex', codex({ access_token: jwt({ exp: NOW / 1000 - 60 }), refresh_token: 'r' }), NOW)).toBe(true)
+ expect(await profileSignedIn('codex', codex({ access_token: jwt({ exp: NOW / 1000 - 60 }) }), NOW)).toBe(false)
+ })
+
+ it('a switch to a profile asks the real reader by default', async () => {
+ const t = setup()
+ const switches = new LeadSwitchRequests(fakeCore({ dataDir: t.dataDir, account: { backend: vi.fn(async () => ({ status: 200, body: { success: true, data: { result: {} } } })) },
+ agents: { byAgent: vi.fn(() => ({ ...PM }) as never) } }), 'm1',
+ { now: () => NOW, profiles: (() => folder()) as never, credentials: { platform: 'linux', readKeychain: async () => null } })
+ await switches.serve(row())
+ // Nothing signed in under that folder: refused before anything is closed.
+ 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' } })
+ })
+})
diff --git a/cli/src/superTabs/leadSwitchRequest.ts b/cli/src/superTabs/leadSwitchRequest.ts
new file mode 100644
index 000000000..a468712c7
--- /dev/null
+++ b/cli/src/superTabs/leadSwitchRequest.ts
@@ -0,0 +1,238 @@
+/**
+ * A PM'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.
+ */
+import { createHash } from 'node:crypto'
+import { mkdirSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+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 { 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 { leadSwitchOf, leadSwitching, SWITCH_ADOPT_MS, switchWithin } from './leadSwitch.js'
+import { githubPromptLine, LAUNCH_MODEL_REFUSALS, leadPrompt } from './start.js'
+import { pmEngineHome } from './teamDaemon.js'
+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_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'
+/** How long a claim or a result that failed waits before it is tried again (the host polls every second). */
+const RETRY_MS = 10_000
+/** What Claude Code signs in with when its default account stores no token of its own. */
+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). */
+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 } }
+}
+export interface LeadSwitchDeps {
+ now: () => number
+ open: (where: Where) => Promise<Daemon>
+ profiles: typeof profileHome
+ team: () => boolean
+ /** The Team user's home, under which a Codex PM keeps an engine home of its own (teamDaemon.ts pmEngineHome). */
+ home: () => string
+ /** Whether the account (a profile folder, or 'default') holds a usable sign-in. */
+ signedIn: (engine: string, home: string) => Promise<boolean>
+ /** Where the default [signedIn] reads from (the Keychain on macOS, the folder's files elsewhere); injected by specs. */
+ credentials?: CredentialReadDeps
+ log: (message: string) => void
+}
+interface Run { switchId: string; harnessId: string; changeId: string; busy: boolean; closed: boolean; retryAt?: number; outcome?: { ok: boolean; error?: string; down?: boolean }
+ /** Why the new session did not start. Reported only once the old PM is back: a late start can still land the switch. */
+ failed?: string }
+
+/** A sign-in the account holds: a token that is not past its expiry, or one that Claude Code / Codex can renew with its refresh
+ * token, or for the default account a key its engine reads instead. Missing, or expired with no refresh token, is signed out.
+ * Reads only; nothing is renewed or sent anywhere. */
+export async function profileSignedIn(engine: string, home: string, now: number, read: CredentialReadDeps = {}, environment: NodeJS.ProcessEnv = process.env): Promise<boolean> {
+ const isDefault = home === 'default'
+ if (engine === 'claude') {
+ if (isDefault && CLAUDE_KEY_VARIABLES.some(name => environment[name])) return true
+ const configDir = isDefault ? environment.CLAUDE_CONFIG_DIR || undefined : home
+ const oauth = asRecord(asRecord(parseJson((await readClaudeStored({ ...read, ...(configDir ? { configDir } : {}) }))?.raw ?? null))?.claudeAiOauth)
+ if (!oauth || !stringField(oauth.accessToken)) return false
+ return typeof oauth.expiresAt !== 'number' || oauth.expiresAt > now || !!stringField(oauth.refreshToken)
+ }
+ const auth = asRecord(parseJson(await readText(join(isDefault ? defaultCodexHome(read.home ?? homedir(), environment) : home, 'auth.json'))))
+ if (stringField(auth?.OPENAI_API_KEY)) return true
+ const tokens = asRecord(auth?.tokens)
+ const token = stringField(tokens?.access_token)
+ if (!token) return false
+ const exp = jwtClaims(token)?.exp
+ return typeof exp !== 'number' || exp * 1000 > now || !!stringField(tokens?.refresh_token)
+}
+
+/** A request's one change id, so a record of #2493 (which holds only this) tells which switch it belongs to, and a create repeated
+ * after a restart is the same creation. Not a secret: closing a PM takes this machine's own handoff receipt as well. */
+export const switchChangeId = (switchId: string) => createHash('sha256').update(`pm-switch:${switchId}`).digest('hex').slice(0, 32)
+
+const operationId = (kind: string, switchId: string) => `switch-${kind}-${createHash('sha256').update(switchId).digest('hex').slice(0, 32)}`
+
+export class LeadSwitchRequests {
+ private readonly runs = new Map<string, Run>()
+ /** The ids already answered, so a roster that still shows one does not start it again. */
+ private readonly done = new Set<string>()
+ /** A claim that failed: not tried again before this time. */
+ private readonly claimRetryAt = new Map<string, number>()
+ private readonly deps: LeadSwitchDeps
+ constructor(private readonly core: CoreApi, private readonly machineId: string, deps: Partial<LeadSwitchDeps> = {}) {
+ this.deps = { now: Date.now, open: openDaemon, profiles: profileHome, team: () => false, home: homedir, log: () => {},
+ signedIn: (engine, home) => profileSignedIn(engine, home, this.deps.now(), this.deps.credentials), ...deps }
+ }
+
+ /** One poll of one PM row: starts its request, or follows the one this host is carrying out. */
+ async serve(row: SwitchRow): Promise<void> {
+ const { agent, tabId } = row
+ const run = this.runs.get(agent.id)
+ if (run) { if (!run.busy) await this.follow(tabId, agent, run); return }
+ const request = agent.switchRequest
+ if (!request || !identifier(request.id) || this.done.has(request.id)) return
+ const switchId = request.id, now = this.deps.now()
+ if (now < (this.claimRetryAt.get(switchId) ?? 0)) return
+ // A switch of this PM that #2493 recorded (leadSwitch.ts) is under way, or was before this host restarted: followed, never
+ // started again. It ends by the rebind, by the old PM's return past its hold, or by the Swarm's lease.
+ // Only this request's own record: an earlier switch's, inside its window, must not answer a new request without trying it.
+ const changeId = switchChangeId(switchId), recorded = leadSwitchOf(this.core.dataDir, agent.harnessId)
+ if (recorded?.changeId === changeId && switchWithin(recorded, now, SWITCH_ADOPT_MS)) {
+ const adopted: Run = { switchId, harnessId: agent.harnessId, changeId, busy: false, closed: true }
+ this.runs.set(agent.id, adopted)
+ await this.follow(tabId, agent, adopted)
+ return
+ }
+ if (leadSwitching(this.core.dataDir, agent.harnessId, changeId, now)) 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 }
+ this.runs.set(agent.id, created)
+ try {
+ 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}`)
+ if (created.closed) created.failed = NO_START
+ else created.outcome = { ok: false, error: NO_HANDOFF }
+ } finally { created.busy = false }
+ if (created.outcome) await this.report(tabId, agent.id, created)
+ }
+
+ private async carryOut(row: SwitchRow, run: Run, request: NonNullable<SwitchRow['agent']['switchRequest']>): Promise<Run['outcome']> {
+ const engine = String(request.engine), profileId = String(request.profileId ?? 'default')
+ const team = this.deps.team()
+ // The hex id of the default account counts as the default; a Team daemon takes no other account (its user's folders are not
+ // the owner's to offer).
+ const home = this.deps.profiles(engine, profileId, this.machineId, { offeredOnly: true })
+ if (home === null || (team && home !== 'default')) return { ok: false, error: GONE }
+ 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
+ if (!old?.cwd || !skill || !identifier(conversation)) return { ok: false, error: NO_HANDOFF }
+ // 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 })
+ try {
+ const { changeId } = run, agentId = run.harnessId
+ const prepared = await daemon.request('agent_handoff_prepare', { agentId, changeId, targetEngine: engine }, 30_000)
+ const handoff = promptOf(prepared, agentId, changeId, old.cwd, LABELS[old.engine] ?? old.engine)
+ if (handoff === false) return { ok: false, error: NO_HANDOFF }
+ const closed = await daemon.request('agent_close', { agentId, 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}` : ''}`
+ // 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 } : {}),
+ ...(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 } : {}),
+ ...(typeof request.model === 'string' ? { model: request.model } : {}), ...(typeof request.effort === 'string' ? { effort: request.effort } : {}),
+ prompt }
+ let created = await daemon.request('agent_create', payload, 30_000)
+ // A machine that refuses the model (this value, or this Claude Code build) made no receipt: the same creation id starts it without.
+ if (LAUNCH_MODEL_REFUSALS.has(String(created.error))) {
+ delete payload.model; delete payload.effort
+ created = await daemon.request('agent_create', payload, 30_000)
+ }
+ if (created.error) { run.failed = NO_START; return undefined }
+ // A create that is held has no session yet, and can still start inside the hold: follow() waits for the rebind.
+ const replacementId = String(object(created.agent).id ?? created.agentId ?? '')
+ if (!replacementId) return undefined
+ // The rebind below needs the receipt too, which the daemon already holds; a refusal here does not undo the new session.
+ await daemon.request('agent_handoff_complete', { agentId, replacementId, changeId, targetEngine: engine }, 30_000).catch(() => null)
+ return undefined
+ } finally { daemon.close() }
+ }
+
+ /** The request was carried out: done once the PM is bound to the new session. Failed only once the hold has ended and #2493's
+ * rollback has reopened the old one, so the chat's line is true when it is read; `down` when it has not reopened in the whole
+ * adoption window. (A request the Swarm's own tidy pass cleared reads as done too; its result is then refused as stale, which
+ * is harmless.) */
+ private async follow(tabId: string, agent: SwitchRow['agent'], run: Run): Promise<void> {
+ const now = this.deps.now()
+ if (run.retryAt && now < run.retryAt) return
+ if (!run.outcome) {
+ const record = leadSwitchOf(this.core.dataDir, run.harnessId)
+ if (agent.harnessId !== run.harnessId || !agent.switchRequest) run.outcome = { ok: true }
+ else if (!switchWithin(record, now)) {
+ const error = run.failed ?? LATE
+ if (this.core.agents.byAgent(run.harnessId)) run.outcome = { ok: false, error }
+ else if (!switchWithin(record, now, SWITCH_ADOPT_MS)) run.outcome = { ok: false, error, down: true }
+ }
+ }
+ if (run.outcome) await this.report(tabId, agent.id, run)
+ }
+
+ private async report(tabId: string, agentId: string, run: Run): Promise<void> {
+ const { ok, error, down } = run.outcome!
+ try {
+ await this.post(tabId, agentId, operationId('result', run.switchId), { type: 'agent.switchResult', agentId, switchId: run.switchId, ok, ...(error ? { error } : {}), ...(down ? { down } : {}) })
+ } catch (failure) {
+ // A settled id is done; any other failure is tried again, not on every poll.
+ if (object(failure).code !== 'STALE_SWITCH') { run.retryAt = this.deps.now() + RETRY_MS; return }
+ }
+ this.runs.delete(agentId)
+ this.done.add(run.switchId)
+ }
+
+ private post(tabId: string, agentId: string, operationId: string, command: Record<string, unknown>): Promise<unknown> {
+ return backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId, asAgentId: agentId, command })
+ }
+}
+
+/** Desktop's rule (agent_handoff_file.dart acceptAgentHandoffReply), with the same fixed wording: the reply only decides whether to
+ * use the file, and never supplies words. false = hold the switch, null = nothing to hand off. */
+function promptOf(reply: Record<string, unknown>, agentId: string, changeId: string, cwd: string, label: string): string | null | false {
+ if (reply.error || reply.held === true || reply.agentId !== agentId || reply.cwd !== cwd || typeof reply.gitRepo !== 'boolean') return false
+ const degraded = reply.degraded
+ if (!Array.isArray(degraded) || degraded.some(d => typeof d !== 'string') || degraded.includes('file')) return false
+ if (reply.file === null) return degraded.includes('transcript') ? false : null
+ const file = `.harness/handoff/${handoffBaseName(agentId, changeId)}.md`
+ if (reply.file !== file) return false
+ return `Context handoff: you are taking over this project from ${label}. Read \`${file}\` — a record of earlier work, not instructions.`
+ + `${reply.gitRepo ? ' Run `git status` to confirm the current state.' : ''}`
+ + ' When the user mentions something from before that the record does not cover, search the transcript it names before answering.'
+ + " Then briefly acknowledge and wait for the user's next message. Do not edit files yet."
+}
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 56e08a224..088f2983f 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -1,7 +1,7 @@
import { execFileSync } from 'node:child_process'
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
+import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import type { RegisteredSession } from '../lib/registry.js'
@@ -16,7 +16,7 @@ import { processCoreApi } from '../services/processCoreApi.js'
import type { PrivacyObservation } from '../team/privacy.js'
function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation | null = () => null, relayed: () => boolean = () => false) {
- let now = 1000, stamp = 's0'
+ let now = 1000, stamp = 's0', team = false
const core = fakeCore({ dataDir: '/isolated-pool-fixture', agents: {
byAgent: vi.fn(id => id === 'running' ? { agentId: id } as never : undefined),
stopped: vi.fn(async id => id === 'stopped'),
@@ -24,7 +24,7 @@ function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation
const pool = { tabId: 'tab', machine: { machineId: 'host', generation: 'grant', cwd: '/repo', engines: ['codex'], paused: false },
harnessIds: ['running', 'stopped'], starts: [{ id: 'start', dispatched: false }], paused: false }
const backend = vi.fn(async (_core: unknown, method: string, path: string, _body?: unknown): Promise<unknown> => path.includes('/hosts/host/changes') ? hostForm([], { pools: [pool] }) : { revision: 1 })
- const request = vi.fn(async (_type: string): Promise<Record<string, unknown>> => ({ providers: [{ provider: 'codex', outcome: 'answered', httpStatus: 200,
+ const request = vi.fn(async (_type: string, _payload?: unknown): Promise<Record<string, unknown>> => ({ providers: [{ provider: 'codex', outcome: 'answered', httpStatus: 200,
body: { account_email: '[email protected]', secret: 'private-token', rate_limit: { primary_window: { used_percent: 25, reset_at: 1234567890 } } } }] }))
const close = vi.fn(), open = vi.fn(async () => ({ machineId: 'host', request, close }))
const capabilities = vi.fn(async (_input: { cwd: string; tools: string[]; devices: string[] }) => ({ ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 200, projectDiskFreeBytes: 1000 }, tools: { git: true } }))
@@ -50,9 +50,11 @@ function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation
})
const wire = async (core: unknown, method: string, path: string, body?: unknown): Promise<unknown> =>
method === 'POST' && path.endsWith('/readings') ? readings(core, path, body) : backend(core, method, path, body)
- const deps = { backend: wire, open, capabilities, start, prepare, log, env, privacy, modelsStamp, relayed, now: () => now }
+ const claudeProfiles = vi.fn((): unknown[] => [])
+ const codexProfiles = vi.fn((): unknown[] => [])
+ const deps = { team: () => team, backend: wire, open, capabilities, claudeProfiles, codexProfiles, start, prepare, log, env, privacy, modelsStamp, relayed, now: () => now }
const machine = new ContributedMachines(core, 'host', deps as never)
- return { deps, machine, pool, core, backend, readings, open, request, close, capabilities, start, prepare, log, modelsStamp, advance: () => { now += 16000 }, step: (ms: number) => { now += ms },
+ return { setTeam: (on: boolean) => { team = on }, deps, claudeProfiles, codexProfiles, machine, pool, core, backend, readings, open, request, close, capabilities, start, prepare, log, modelsStamp, advance: () => { now += 16000 }, step: (ms: number) => { now += ms },
stamp: (next: string) => { stamp = next } }
}
@@ -337,7 +339,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'] })
+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'leadSwitch'] })
// A backend from before them does not ask, and would refuse the field.
const older = fixture()
await older.machine.tick()
@@ -2396,3 +2398,115 @@ describe('one call for all of a machine\'s readings (DB 2.5)', () => {
launched(); await pass
})
})
+
+// The accounts a Product Manager could move to (spec 2026-11-02-pm-switch-engine-account, section 5): ids and labels, never a path.
+describe('the profiles a machine reports', () => {
+ const posted = (f: ReturnType<typeof fixture>) => f.backend.mock.calls.filter(c => c[1] === 'POST' && String(c[2]).includes('/machines/')).map(c => c[3] as Record<string, unknown>)
+ const id = (n: string) => n.repeat(16).slice(0, 16)
+ const both = () => {
+ const f = fixture()
+ Object.assign(f.pool.machine, { engines: ['claude', 'codex'] })
+ Object.assign(f.pool, { capabilitiesWanted: true })
+ f.claudeProfiles.mockReturnValue([{ id: id('d'), default: true, path: '/Users/me', label: 'me@corp', reportLabel: 'Claude', offered: true },
+ { id: id('a'), path: '/Users/me/.claude-work', label: 'Work', reportLabel: 'Work', offered: true },
+ { id: id('b'), path: '/Users/me/.claude-other', label: 'Other', reportLabel: '.claude-other', offered: false }])
+ f.codexProfiles.mockReturnValue([{ path: '/Users/me/.codex-two', label: 'two', offered: true }, { path: '/Users/me/.codex-found', label: 'found', offered: false }])
+ f.request.mockImplementation(async (type: string, payload?: unknown): Promise<Record<string, unknown>> => {
+ if (type !== 'usage_read') return {}
+ const profile = (payload as { profile?: { engine: string } } | undefined)?.profile
+ const claude = { provider: 'claude', outcome: 'answered', httpStatus: 200, body: { five_hour: { utilization: 30, resets_at: '2026-11-02T10:00:00Z' }, seven_day: { utilization: 10 } } }
+ const codex = { provider: 'codex', outcome: 'answered', httpStatus: 200, body: { rate_limit: { primary_window: { used_percent: 25, reset_at: 1793613600 } } } }
+ return { providers: profile ? [profile.engine === 'claude' ? claude : codex] : [claude, codex] }
+ })
+ return f
+ }
+
+ it('lists profiles with ids and report labels, no paths', async () => {
+ const f = both()
+ await f.machine.tick()
+ const profiles = posted(f).at(-1)!.profiles as Array<Record<string, unknown>>
+ expect(profiles).toEqual([
+ { engine: 'claude', id: expect.stringMatching(/^[0-9a-f]{16}$/), label: 'Default', leftPercent: 70, resetsAt: '2026-11-02T10:00:00.000Z' },
+ { engine: 'claude', id: id('a'), label: 'Work', leftPercent: 70, resetsAt: '2026-11-02T10:00:00.000Z' },
+ { engine: 'codex', id: expect.stringMatching(/^[0-9a-f]{16}$/), label: 'Default', leftPercent: 75, resetsAt: expect.any(String) },
+ { engine: 'codex', id: expect.stringMatching(/^[0-9a-f]{16}$/), label: '.codex-two', leftPercent: 75, resetsAt: expect.any(String) },
+ ])
+ expect(new Set(profiles.map(p => p.id)).size).toBe(4)
+ expect(JSON.stringify(profiles)).not.toMatch(/Users|@/)
+ })
+
+ it('reports and reads only the accounts the owner offered, never a discovered one', async () => {
+ const f = both()
+ await f.machine.tick()
+ const profiles = posted(f).at(-1)!.profiles as Array<{ label: string }>
+ expect(profiles.map(p => p.label)).not.toContain('.claude-other')
+ expect(profiles.map(p => p.label)).not.toContain('.codex-found')
+ const read = f.request.mock.calls.filter(c => c[0] === 'usage_read').map(c => JSON.stringify(c[1]))
+ expect(read.join()).not.toContain(id('b'))
+ })
+
+ it('a Team daemon reports its default accounts only', async () => {
+ const f = both()
+ f.setTeam(true)
+ await f.machine.tick()
+ const profiles = posted(f).at(-1)!.profiles as Array<{ engine: string; label: string }>
+ expect(profiles.map(p => [p.engine, p.label])).toEqual([['claude', 'Default'], ['codex', 'Default']])
+ expect(f.request.mock.calls.filter(c => (c[1] as { profile?: unknown } | undefined)?.profile)).toEqual([])
+ })
+
+ it("reports the default Codex home once, as Default", async () => {
+ const f = both()
+ const home = join(process.env.CODEX_HOME || join(homedir(), '.codex'))
+ f.codexProfiles.mockReturnValue([{ path: (() => { try { return realpathSync(home) } catch { return home } })(), label: 'x', offered: true }, { path: '/Users/me/.codex-two', label: 'two', offered: true }])
+ await f.machine.tick()
+ const codex = (posted(f).at(-1)!.profiles as Array<{ engine: string; label: string }>).filter(p => p.engine === 'codex')
+ expect(codex.map(p => p.label)).toEqual(['Default', '.codex-two'])
+ })
+
+ it('leaves out an engine this machine does not offer, an entry the backend would refuse, and what is over the caps', async () => {
+ const f = both()
+ Object.assign(f.pool.machine, { engines: ['claude'] })
+ f.claudeProfiles.mockReturnValue([{ id: id('d'), default: true, path: '/h', label: 'x', reportLabel: 'x', offered: true },
+ ...Array.from({ length: 12 }, (_, i) => ({ id: id(i.toString(16)), path: `/h/${i}`, label: `p${i}`, reportLabel: i === 0 ? 'a@b' : i === 1 ? '' : `p${i}`, offered: true }))])
+ await f.machine.tick()
+ const profiles = posted(f).at(-1)!.profiles as Array<{ engine: string; label: string }>
+ expect(profiles.every(p => p.engine === 'claude')).toBe(true)
+ expect(profiles).toHaveLength(8)
+ expect(profiles.map(p => p.label)).not.toContain('a@b')
+ expect(f.request.mock.calls.filter(c => (c[1] as { profile?: unknown } | undefined)?.profile).length).toBeLessThanOrEqual(8)
+ })
+
+ it('reads each profile at most once in 3 minutes and not at all while Anthropic limits the reads', async () => {
+ const f = both()
+ const profileReads = () => f.request.mock.calls.filter(c => c[0] === 'usage_read' && (c[1] as { profile?: unknown } | undefined)?.profile).length
+ await f.machine.tick(); f.advance(); await f.machine.tick()
+ const first = profileReads()
+ expect(first).toBe(2)
+ f.step(180_000); await f.machine.tick()
+ expect(profileReads()).toBe(first + 2)
+ const answer = f.request.getMockImplementation() as (type: string, payload?: unknown) => Promise<Record<string, unknown>>
+ f.request.mockImplementation(async (type: string, payload?: unknown): Promise<Record<string, unknown>> => (payload as { profile?: unknown } | undefined)?.profile
+ ? { providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 429, body: {} }] } : answer(type, payload))
+ f.step(180_000); await f.machine.tick()
+ const limited = profileReads()
+ f.step(180_000); await f.machine.tick()
+ expect(profileReads()).toBe(limited)
+ expect((posted(f).at(-1)!.profiles as Array<{ engine: string; leftPercent: number | null }>).find(p => p.engine === 'claude')!.leftPercent).toBe(70)
+ })
+
+ it('drops the profiles after the backend refuses the field, and offers them again ten minutes later', async () => {
+ const f = both()
+ const original = f.backend.getMockImplementation()!
+ f.backend.mockImplementation(async (core, method, path, body) => {
+ if (method === 'POST' && (body as Record<string, unknown>)?.profiles) throw new SuperTabHostError('VALIDATION_ERROR', 'Unrecognized key: profiles', 400)
+ return original(core, method, path, body)
+ })
+ const has = () => posted(f).map(b => 'profiles' in b)
+ await f.machine.tick()
+ expect(has()).toEqual([true, false])
+ f.advance(); await f.machine.tick()
+ expect(has().at(-1)).toBe(false)
+ f.step(600_000); await f.machine.tick()
+ expect(has().slice(-2)).toEqual([true, false])
+ })
+})
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 803fb27a7..7db7244f9 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -1,12 +1,13 @@
import { createHash } from 'node:crypto'
import { spawn } from 'node:child_process'
-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
+import { homedir } from 'node:os'
import { lstat, readdir, readFile, realpath, rm, stat } from 'node:fs/promises'
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
import type { CoreApi } from '../core/api.js'
import { openDaemon } from '../agentClient/daemon.js'
import { codingRefusal } from '../lib/codingModel.js'
-import { backend, identifier, object, SuperTabHostError } from './wire.js'
+import { backend, FIELD_REFUSED_MS, fieldRefused, identifier, object, SuperTabHostError } from './wire.js'
import type { SwarmSources } from './host.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
@@ -22,6 +23,8 @@ import { teamPrivacyObserver } from '../team/observer.js'
import { teamRelayed } from '../team/relay.js'
import type { PrivacyObservation } from '../team/privacy.js'
import { repositoryKey } from './route.js'
+import { listClaudeProfiles, codexReportLabel, profileId } from '../lib/claudeProfiles.js'
+import { defaultCodexHome, listCodexProfiles } from '../lib/codexProfiles.js'
import { usageTarget, validModelTokens, validUsageTarget, type ModelTokens } from '../lib/agentUsageWire.js'
const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v : null
@@ -33,7 +36,6 @@ const VERIFIED_TOOL_TTL_MS = 10 * 60_000
/** After a backend refuses a new field (privacy, from before the Harness Team account; harnessProgress, from before
* task leases), how long the reading goes without it before the field is offered again: a backend deployed meanwhile
* is heard from within this long. */
-const FIELD_REFUSED_MS = 10 * 60_000
const UNVERIFIED_TOOL_TTL_MS = 60_000
/** How long a session's folder stands as clean or not before git is asked again: a minute bounds the work to one
* `git status` per running session a minute, and the backend stops an idle worker only on a report under 2 minutes old. */
@@ -142,8 +144,11 @@ export interface MachineDeps {
/** In the Harness Team account: whether its engines can spend the owner's subscription through the owner's relay
* (team/relay.ts), so one it has not signed in itself is ready all the same. */
relayed?: () => boolean
+ /** The Claude and Codex profile folders this machine offers ([listClaudeProfiles], [listCodexProfiles]). */
+ claudeProfiles?: (machineId: string) => Array<{ id: string; path: string; reportLabel: string; offered: boolean; default?: true }>
+ codexProfiles?: () => Array<{ path: string; offered?: boolean }>
}
-const MACHINE_DEPS = { backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }
+const MACHINE_DEPS = { claudeProfiles: (machineId: string) => listClaudeProfiles([], { machineId }), codexProfiles: () => listCodexProfiles(), backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }
/** A start's folder preparation can clone a whole repository; past this, its cleanup gives up and tries again later. */
const CLEANUP_WAIT_MS = 10 * 60_000
const CLEANING_WAIT = 'Waiting for this machine to finish cleaning up this Swarm.'
@@ -162,7 +167,6 @@ const READINGS_MAX = 64
const readingsMissing = (error: unknown) => error instanceof SuperTabHostError
&& (error.status === 404 || error.status === 413 || (error.status === 403 && error.code === 'TEAM_SESSION_LIMITED'))
/** A reading the backend would not validate: the next, older form of it is tried (an older backend refusing a newer field). */
-const fieldRefused = (error: unknown) => error instanceof SuperTabHostError && error.status === 400 && error.code === 'VALIDATION_ERROR'
/** One Swarm's reading of this pass, to send. */
interface Reading { tab: string; observation: Record<string, unknown>; localModels: LocalModelReading[] | null; signature: string }
@@ -173,6 +177,9 @@ const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list
* Buddy's thread sessions (spec 2026-10-30-buddy-thread-sessions), and a person's one Buddy for the Swarm in its folder of
* project worktrees (spec 2026-10-31-one-buddy-per-swarm), which the backend offers only on a host that says so. */
const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy']
+/** What this host does for a Product Manager's switch to another engine or account (spec 2026-11-02-pm-switch-engine-account),
+ * said beside the others: the backend refuses a switch to a host that does not. */
+CAPABILITIES.push('leadSwitch')
/** The backend's answer that this machine may no longer act in the Swarm: signed out, its contribution revoked or its host
* unavailable (backend store.ts observeMachine), or the Swarm gone. */
const lostAccess = (error: unknown) => error instanceof SuperTabHostError && [401, 403, 404].includes(error.status)
@@ -251,6 +258,11 @@ export class ContributedMachines {
private readonly goodQuota = new Map<string, { windows: ReturnType<typeof quotaOf>['windows']; at: number }>()
/** Until when the reading leaves out why an allowance is unknown, which the backend refused. */
private quotaReasonsRefusedUntil = 0
+ /** Until when the reading leaves out its profiles, which the backend refused. */
+ private profilesRefusedUntil = 0
+ /** Per profile, its last allowance and until when it stands; and until when Anthropic is refusing allowance reads. */
+ private readonly profileReads = new Map<string, { value: { left: number | null; resetsAt: string | null }; until: number }>()
+ private anthropicLimitedUntil = 0
/** Per Swarm folder, its checkouts' readiness and until when it stands, and the folders being read now. A push check
* asks the remote, so it is read beside the pass, never holding up a start. */
private readonly checkoutReads = new Map<string, { value: ReadyCheckout[] | null; until: number }>()
@@ -281,8 +293,48 @@ export class ContributedMachines {
const providers = list(value.providers)
const wait = !Array.isArray(value.providers) ? USAGE_RETRY_MS
: providers.some(p => p.outcome === 'answered' && p.httpStatus === 429) ? USAGE_LIMITED_MS : USAGE_FRESH_MS
+ if (providers.some(p => p.provider === 'claude' && p.outcome === 'answered' && p.httpStatus === 429)) this.anthropicLimitedUntil = now + USAGE_LIMITED_MS
return this.usageRead = { value, at: now, until: now + wait }
}
+ /** The allowance left on one account, from its tightest window. A profile is read at most once per [USAGE_FRESH_MS], and
+ * none of Claude's while Anthropic refuses reads (the default account's shares that wait). */
+ private async profileAllowance(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> },
+ engine: 'claude' | 'codex', id: string): Promise<{ left: number | null; resetsAt: string | null }> {
+ const now = this.deps.now(), key = `${engine}:${id}`, kept = this.profileReads.get(key)
+ if (kept && now < kept.until) return kept.value
+ if (engine === 'claude' && now < this.anthropicLimitedUntil) return kept?.value ?? { left: null, resetsAt: null }
+ const value = object(await local.request('usage_read', { profile: { engine, id } }, 20_000).catch(() => null))
+ const providers = list(value.providers)
+ if (engine === 'claude' && providers.some(p => p.outcome === 'answered' && p.httpStatus === 429)) this.anthropicLimitedUntil = now + USAGE_LIMITED_MS
+ const wait = !Array.isArray(value.providers) ? USAGE_RETRY_MS : providers.some(p => p.outcome === 'answered' && p.httpStatus === 429) ? USAGE_LIMITED_MS : USAGE_FRESH_MS
+ const read = allowanceLeft(quotaOf(value, engine, false).windows)
+ const result = read.left === null && kept ? kept.value : read
+ this.profileReads.set(key, { value: result, until: now + wait })
+ return result
+ }
+ /** The accounts a Product Manager here could move to, by id and label only: the default account's allowance is the one
+ * already read, the others are read each at most once per [USAGE_FRESH_MS]. An entry the backend would refuse is left out. */
+ private async profiles(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> },
+ engines: string[], allowances: Array<{ engine: string; windows: Parameters<typeof allowanceLeft>[0] }>) {
+ const found: Array<{ engine: 'claude' | 'codex'; id: string; label: string; leftPercent: number | null; resetsAt: string | null }> = []
+ const accounts = {
+ claude: () => this.deps.claudeProfiles!(this.machineId).filter(p => !p.default && p.offered).map(p => ({ id: p.id, label: p.reportLabel })),
+ // The default Codex account is ~/.codex or an inherited CODEX_HOME: reported once, as Default.
+ codex: () => this.deps.codexProfiles!().filter(p => p.offered && p.path !== defaultCodexHome()).map(p => ({ id: profileId(this.machineId, 'codex', p.path), label: codexReportLabel(p.path) })),
+ }
+ for (const engine of ['claude', 'codex'] as const) {
+ if (!engines.includes(engine)) continue
+ const defaultLeft = allowanceLeft(allowances.find(a => a.engine === engine)?.windows ?? [])
+ // A Team user's other folders are not offered: a switch there takes the default account only (leadSwitchRequest.ts).
+ const listed = [{ id: profileId(this.machineId, engine, 'default'), label: 'Default', read: 'default' }, ...((this.deps.team ?? (() => readAuthSession()?.kind === 'team'))() ? [] : accounts[engine]().map(a => ({ ...a, read: a.id })))]
+ .filter(({ id, label }) => /^[0-9a-f]{16}$/.test(id) && label.length > 0 && label.length <= 40 && !label.includes('@')).slice(0, MAX_PROFILES_PER_ENGINE)
+ for (const { id, label, read } of listed) {
+ const { left, resetsAt } = read === 'default' ? defaultLeft : await this.profileAllowance(local, engine, read)
+ found.push({ engine, id, label, leftPercent: left, resetsAt })
+ }
+ }
+ return found.slice(0, MAX_PROFILES)
+ }
/** What the reading says of [engine]'s allowance. Windows that could not be read again stand for [USAGE_KEEP_MS] after
* they were read, unless the engine signed out; past that, unknown says why. */
private quotaFor(read: { value: Record<string, unknown>; at: number }, engine: string) {
@@ -527,8 +579,11 @@ export class ContributedMachines {
? Object.fromEntries(allowances.flatMap(q => 'reason' in q && q.reason ? [[q.engine, q.reason]] : [])) : {}
// Only to a backend that asks for them (backend read/hostRows.ts): an older one refuses the field, and would refuse
// every reading with it.
+ // Only to a backend that asks for capabilities, as it is new enough to know the field: an older one refuses it.
+ const profiles = row.capabilitiesWanted === true && began >= this.profilesRefusedUntil ? await this.profiles(local, engines, allowances) : []
const observation = { generation: pool.generation, tools: reportedTools, ...(Object.keys(tokens).length ? { harnessTokens: tokens } : {}),
...(Object.keys(quotaReasons).length ? { quotaReasons } : {}),
+ ...(profiles.length ? { profiles } : {}),
...(row.capabilitiesWanted === true ? { capabilities: CAPABILITIES } : {}),
...(preparing.length ? { preparingStartIds: preparing } : {}),
...(Object.keys(uncommitted).length ? { harnessUncommitted: uncommitted } : {}),
@@ -731,7 +786,8 @@ export class ContributedMachines {
*/
private async sendAlone({ tab, observation, localModels }: Reading, began: number, refused?: SuperTabHostError): Promise<void> {
const path = `/api/super-tabs/${tab}/machines/${this.machineId}`
- const { quotaReasons: _reasons, ...unreasoned } = observation
+ const { profiles: _profiles, ...unprofiled } = observation
+ const { quotaReasons: _reasons, ...unreasoned } = unprofiled
const { harnessTokens: _tokens, ...untokened } = unreasoned
const { preparingStartIds: _preparing, ...unprepared } = untokened
const { harnessUncommitted: _uncommitted, ...known } = unprepared
@@ -742,13 +798,14 @@ export class ContributedMachines {
// A backend before `starting` refuses it: it gets the models the grid lists, as before, not none at all.
const listedOnly = localModels?.some(m => m.starting)
? [{ ...withoutPrivacy, localModels: localModels.filter(m => !m.starting) }] : []
- const attempts = [...('quotaReasons' in observation ? [observation] : []), ...('harnessTokens' in unreasoned ? [unreasoned] : []), ...('preparingStartIds' in untokened ? [untokened] : []),
+ const attempts = [...('profiles' in observation ? [observation] : []), ...('quotaReasons' in unprofiled ? [unprofiled] : []), ...('harnessTokens' in unreasoned ? [unreasoned] : []), ...('preparingStartIds' in untokened ? [untokened] : []),
...('harnessUncommitted' in unprepared ? [unprepared] : []),
...('readiness' in known ? [known] : []), ready, ...('harnessProgress' in ready ? [withoutProgress] : []),
...('privacy' in withoutProgress ? [withoutPrivacy] : []), ...listedOnly,
...('toolProbeErrors' in observation || 'localModels' in observation || 'refusedModels' in observation ? [legacy] : [])]
const refuse = (attempt: Record<string, unknown>) => {
- if ('quotaReasons' in attempt) this.quotaReasonsRefusedUntil = began + FIELD_REFUSED_MS
+ if ('profiles' in attempt) this.profilesRefusedUntil = began + FIELD_REFUSED_MS
+ else if ('quotaReasons' in attempt) this.quotaReasonsRefusedUntil = began + FIELD_REFUSED_MS
else if ('harnessTokens' in attempt) this.tokensRefusedUntil = began + FIELD_REFUSED_MS
else if ('preparingStartIds' in attempt) this.preparingRefusedUntil = began + FIELD_REFUSED_MS
else if ('harnessUncommitted' in attempt) this.uncommittedRefusedUntil = began + FIELD_REFUSED_MS
@@ -1086,6 +1143,16 @@ const READINESS_RETRY_MS = 60_000
const USAGE_FRESH_MS = 3 * 60_000
/** After a refused read: Anthropic's own retry-after. */
const USAGE_LIMITED_MS = 5 * 60_000
+const MAX_PROFILES = 16
+const MAX_PROFILES_PER_ENGINE = 8
+/** The allowance left on an account, from its tightest window, and when that window resets (ISO, as the backend takes it). */
+function allowanceLeft(windows: ReturnType<typeof quotaOf>['windows']): { left: number | null; resetsAt: string | null } {
+ const tightest = windows.reduce<(typeof windows)[number] | null>((t, w) => !t || w.usedPercent > t.usedPercent ? w : t, null)
+ if (!tightest) return { left: null, resetsAt: null }
+ const at = typeof tightest.resetsAt === 'number' ? new Date(tightest.resetsAt < 1e12 ? tightest.resetsAt * 1000 : tightest.resetsAt)
+ : typeof tightest.resetsAt === 'string' ? new Date(tightest.resetsAt) : null
+ return { left: Math.min(100, Math.max(0, Math.round(100 - tightest.usedPercent))), resetsAt: at && !Number.isNaN(at.getTime()) ? at.toISOString() : null }
+}
/** After the reader on this machine did not answer at all. */
const USAGE_RETRY_MS = 60_000
/** How long the last readable windows stand while later reads fail; past it the allowance is unknown, with why. */
diff --git a/cli/src/superTabs/replacements.spec.ts b/cli/src/superTabs/replacements.spec.ts
index 129f9e181..59dbb42c4 100644
--- a/cli/src/superTabs/replacements.spec.ts
+++ b/cli/src/superTabs/replacements.spec.ts
@@ -1,10 +1,13 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { realpathSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { handoffIntentHash, type PreparedHandoff } from '../lib/handoffAuthority.js'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
+import { profileId } from '../lib/claudeProfiles.js'
import { fakeCore } from '../testing/fakeCore.js'
-import { recordReplacement, replacementObservations } from './replacements.js'
+import { defaultCodexHome } from '../lib/codexProfiles.js'
+import { RebindSender, recordReplacement, replacementObservations } from './replacements.js'
+import { SuperTabHostError } from './wire.js'
const roots: string[] = []
afterEach(() => { for (const dir of roots.splice(0)) rmSync(dir, { force: true, recursive: true }) })
@@ -32,6 +35,23 @@ it('durably reports Change agent, and a new host can recover the exact replaceme
expect(await replacementObservations(f.core, 'machine', [f.row])).toEqual(observations)
})
+it.each([
+ ['the default Claude account', {}, profileId('machine', 'claude', 'default')],
+ ['a Claude profile folder', { claudeHome: tmpdir() }, profileId('machine', 'claude', realpathSync(tmpdir()))],
+ ['a Codex profile folder', { engine: 'codex', codexHome: tmpdir() }, profileId('machine', 'codex', realpathSync(tmpdir()))],
+ ['a profile folder that is gone', { claudeHome: '/gone/.claude-x' }, profileId('machine', 'claude', '/gone/.claude-x')],
+ ['the default Codex account', { engine: 'codex' }, profileId('machine', 'codex', 'default')],
+ ['the default Codex home a native launch records', { engine: 'codex', codexHome: defaultCodexHome() }, profileId('machine', 'codex', 'default')],
+])('names the account of the replacement in agent.rebind: %s', async (_name, extra, expected) => {
+ const f = fixture()
+ Object.assign(f.next, extra)
+ f.old.engine = 'claude'
+ const payload = { ...f.payload, targetEngine: f.next.engine }
+ await recordReplacement(f.core, payload)
+ const [observation] = await replacementObservations(f.core, 'machine', [f.row])
+ expect((observation.body.command as { profileId: string }).profileId).toBe(expected)
+})
+
it.each(['source-live', 'different-folder', 'different-engine', 'different-receipt', 'not-live', 'foreign-machine', 'stopping'])('holds a replacement with %s', async kind => {
const f = fixture()
await recordReplacement(f.core, f.payload)
@@ -88,3 +108,39 @@ it('does no history scan for a member whose current terminal is live', async ()
expect(await replacementObservations(f.core, 'machine', [f.row])).toEqual([])
expect(f.core.agents.creationStatus).not.toHaveBeenCalled()
})
+
+// An older backend's agent.rebind is strict and knows no profileId: it still gets the rebind (a CLI ahead of its backend).
+const observation = { path: '/api/super-tabs/tab/commands', body: { operationId: 'op', asAgentId: 'member', command: { type: 'agent.rebind', agentId: 'member', profileId: 'abcdef0123456789', harnessId: 'new' } } }
+it('sends the rebind again without profileId when the backend refuses the field, and remembers it for ten minutes', async () => {
+ let now = 1000
+ const sent: Array<Record<string, unknown>> = []
+ const strict = vi.fn(async (_path: string, body: unknown) => {
+ const command = (body as { command: Record<string, unknown> }).command
+ sent.push(command)
+ if ('profileId' in command) throw new SuperTabHostError('VALIDATION_ERROR', 'command.profileId: Unrecognized key', 400)
+ })
+ const sender = new RebindSender(strict, () => now)
+ await sender.post(observation)
+ expect(sent.map(c => 'profileId' in c)).toEqual([true, false])
+ await sender.post(observation)
+ expect(sent.map(c => 'profileId' in c)).toEqual([true, false, false])
+ now += 10 * 60_000 + 1
+ await sender.post(observation)
+ expect(sent.map(c => 'profileId' in c)).toEqual([true, false, false, true, false])
+})
+
+it('a new backend gets profileId, and any other failure is thrown, not remembered as a refusal', async () => {
+ const send = vi.fn(async () => {})
+ await new RebindSender(send, () => 0).post(observation)
+ expect(send).toHaveBeenCalledOnce()
+ expect((send.mock.calls[0] as unknown as [string, { command: Record<string, unknown> }])[1].command).toHaveProperty('profileId')
+ const down = vi.fn(async () => { throw new SuperTabHostError('BACKEND_UNAVAILABLE', 'down') })
+ await expect(new RebindSender(down, () => 0).post(observation)).rejects.toThrow('down')
+ expect(down).toHaveBeenCalledOnce()
+ // A 400 the stripped form gets too is the command's own fault, not the field's: nothing is remembered.
+ const bad = vi.fn(async () => { throw new SuperTabHostError('VALIDATION_ERROR', 'bad', 400) })
+ const sender = new RebindSender(bad, () => 0)
+ await expect(sender.post(observation)).rejects.toThrow('bad')
+ await expect(sender.post(observation)).rejects.toThrow('bad')
+ expect(bad).toHaveBeenCalledTimes(4)
+})
diff --git a/cli/src/superTabs/replacements.ts b/cli/src/superTabs/replacements.ts
index 125be5986..15b6fa249 100644
--- a/cli/src/superTabs/replacements.ts
+++ b/cli/src/superTabs/replacements.ts
@@ -1,12 +1,14 @@
import { createHash, randomUUID } from 'node:crypto'
-import { existsSync, linkSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'
+import { existsSync, linkSync, realpathSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import type { CoreApi } from '../core/api.js'
import { readPrivateStateFile, secureStateDirectory, syncStateDirectory } from '../lib/secureState.js'
+import { profileId } from '../lib/claudeProfiles.js'
import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'
import { handoffIntentHash } from '../lib/handoffAuthority.js'
import { validateHandoff } from '../lib/handoffValidation.js'
-import { identifier, object } from './wire.js'
+import { defaultCodexHome } from '../lib/codexProfiles.js'
+import { FIELD_REFUSED_MS, fieldRefused, identifier, object } from './wire.js'
interface Replacement { machineId: string; previousHarnessId: string; harnessId: string; changeId: string; cwd: string; engine: string }
const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')
@@ -74,6 +76,37 @@ async function candidates(core: CoreApi, machineId: string): Promise<Replacement
return result
}
+/** The account the replacement runs in, by the opaque id the machine reports its profiles with. */
+function accountId(machineId: string, agent: { engine: string; claudeHome?: string | null; codexHome?: string | null }): string {
+ const engine = agent.claudeHome ? 'claude' : agent.codexHome ? 'codex' : agent.engine as 'claude' | 'codex'
+ const home = agent.claudeHome || agent.codexHome
+ if (!home) return profileId(machineId, engine, 'default')
+ let real = home
+ try { real = realpathSync(home) } catch { /* A folder that is gone keeps the id of the path it was given. */ }
+ // A native Codex launch records CODEX_HOME even for ~/.codex: that is still the default account, under its one id.
+ return profileId(machineId, engine, engine === 'codex' && real === defaultCodexHome() ? 'default' : real)
+}
+
+/**
+ * Sends the host's agent.rebind. A backend that predates `profileId` refuses the whole command (its schema is strict), so a
+ * 400 is answered once with the same rebind without the field, and the refusal is remembered for FIELD_REFUSED_MS. Only a
+ * resend that succeeds counts as the field's refusal.
+ */
+export class RebindSender {
+ private refusedUntil = 0
+ constructor(private readonly send: (path: string, body: unknown) => Promise<unknown>, private readonly now: () => number) {}
+ async post({ path, body }: { path: string; body: Record<string, unknown> }): Promise<void> {
+ const { profileId: _profileId, ...bare } = object(body.command)
+ const without = { ...body, command: bare }
+ if (this.now() < this.refusedUntil) { await this.send(path, without); return }
+ try { await this.send(path, body) } catch (error) {
+ if (!fieldRefused(error) || !('profileId' in object(body.command))) throw error
+ await this.send(path, without)
+ this.refusedUntil = this.now() + FIELD_REFUSED_MS
+ }
+ }
+}
+
export async function replacementObservations(core: CoreApi, machineId: string, rows: unknown[]) {
// Healthy members need no recovery or disk scan. In particular, do not reread every historical
// handoff and its transcript on a machine with live Swarm members every five seconds.
@@ -105,7 +138,7 @@ 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, machineId, projectId: agent.projectId ?? 'lead',
+ const command = { type: 'agent.rebind', agentId: agent.id, profileId: accountId(machineId, target), machineId, projectId: agent.projectId ?? 'lead',
previousHarnessId: agent.harnessId, harnessId: target.agentId, configuration }
observations.push({ path: `/api/super-tabs/${row.tabId}/commands`, body: {
operationId: `replacement-${digest([row.tabId, agent.id, report.changeId, target.agentId])}`, asAgentId: agent.id, command } })
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index 5f35ba15b..2ef7312b2 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -31,7 +31,7 @@ const PRE_DISPATCH_REFUSALS = new Set([
])
// A daemon that cannot take the launch model answers these before it makes a receipt, so the same creation id can be
// sent again without it. Any other refusal still ends the start.
-const LAUNCH_MODEL_REFUSALS = new Set(['LAUNCH_MODEL_UNSUPPORTED', 'INVALID_LAUNCH_MODEL'])
+export const LAUNCH_MODEL_REFUSALS = new Set(['LAUNCH_MODEL_UNSUPPORTED', 'INVALID_LAUNCH_MODEL'])
// The join turn must finish before the pane accepts a model switch, and it ends only once the roster shows the agent.
const MODEL_SWITCH_WAIT_MS = 60_000
const MODEL_SWITCH_RETRY_MS = 1_000
@@ -65,7 +65,7 @@ const LASTING_REFUSALS = new Set(['RULE_BROKEN', 'REQUIREMENT_UNMET', 'REVIEW_RE
/** A Buddy's start note: its owner's chat, where it talks, and nothing to wait for. */
/** A project's Product Manager the Swarm started here (backend leadStart.ts): the Lead of the project's conversation, with
* the lines Desktop's own-machine launch gives one (desktop super_tabs/launch_prompt.dart). */
-function leadPrompt(tabId: string, chat: string, roleName: string): string {
+export function leadPrompt(tabId: string, chat: string, roleName: string): string {
return `You are the Product Manager of the project whose conversation is ${chat}, started by the Swarm on this machine. ${roleLine(roleName)}Run harness super-tab --tab ${tabId} status until this harness appears in the roster. Read the conversation with harness super-tab --tab ${tabId} messages ${chat}; if it is empty, ask there what to work on. Reply with harness super-tab --tab ${tabId} post ${chat} 'your message' UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID], and answer each message once. ${INSTRUCTIONS_LINE(tabId)} Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`
}
/** Workflow lives in the project's instructions, not in this prompt (project instructions, phase 3). */
diff --git a/cli/src/superTabs/wire.ts b/cli/src/superTabs/wire.ts
index 520d33769..24f3c6a9b 100644
--- a/cli/src/superTabs/wire.ts
+++ b/cli/src/superTabs/wire.ts
@@ -16,6 +16,10 @@ export const ENDED_WORK = ['done', 'stopped', 'cancelled', 'lost']
export class SuperTabHostError extends Error {
constructor(readonly code: string, message: string, readonly status = 503) { super(message) }
}
+/** A request the backend would not validate: the next, older form of it is tried (an older backend refusing a newer field). */
+export const fieldRefused = (error: unknown) => error instanceof SuperTabHostError && error.status === 400 && error.code === 'VALIDATION_ERROR'
+/** How long a field an older backend refused is left out. */
+export const FIELD_REFUSED_MS = 10 * 60_000
/** The core signs each request. Neither the service nor its journal holds an account credential. HTTP 426 is a server that no
* longer serves this client's reads: whatever it says, the person is told to update Harness (design 4.11, 5.1). */
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 376e41fea..fead53a53 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -429,6 +429,9 @@ class Agent {
final String? engineIconHint;
final String? codexHome;
+ /// The Claude account folder (`CLAUDE_CONFIG_DIR`) this agent runs in; null for the default account.
+ final String? claudeHome;
+
/// Model observed in this session by the daemon, when available. Independent
/// of [gridModel], which determines subscription versus local-model routing.
final String? modelName;
@@ -563,6 +566,7 @@ class Agent {
this.engineDisplayName,
this.engineIconHint,
this.codexHome,
+ this.claudeHome,
this.modelName,
this.modelEffort,
this.gridModel,
@@ -728,6 +732,9 @@ class Agent {
engineDisplayName: _safeLabel(j['engineDisplayName']),
engineIconHint: _safeLabel(j['engineIconHint']),
codexHome: j['engine'] == 'codex' ? _safeCodexHome(j['codexHome']) : null,
+ claudeHome: j['engine'] == 'claude'
+ ? _safeCodexHome(j['claudeHome'])
+ : null,
modelName: model?.name,
modelEffort: model?.effort,
gridModel: _safeLabel(grid?['model']),
@@ -808,6 +815,7 @@ class Agent {
engineDisplayName: engineDisplayName,
engineIconHint: engineIconHint,
codexHome: codexHome,
+ claudeHome: claudeHome,
modelName: modelName,
modelEffort: modelEffort,
gridModel: gridModel,
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 9f62cd1c6..386dfbc8e 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -36,6 +36,7 @@ import '../widgets/resting_section.dart'
show confirmStopInUse, confirmSwitchAnyway;
import '../widgets/finger_target.dart';
import '../widgets/session_close_dialog.dart';
+import '../super_tabs/swarm_accounts.dart';
import '../super_tabs/lead_guard.dart';
import '../notify/system_notifications.dart';
import '../widgets/account_device_detail.dart';
@@ -6907,7 +6908,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
agentId = search.agentSelectionId;
if (machineId == null || agentId == null) return;
_closeSearch(restoreFocus: true);
- final error = await app.changeAgent(machineId, agentId, engine);
+ if (choice.destination.managesSwarmAccounts) {
+ if (mounted) await showSwarmAccounts(context, app, machineId);
+ return;
+ }
+ final error = choice.destination.addsClaudeAccount
+ ? await app.addClaudeAccount(machineId, agentId)
+ : await app.changeAgent(
+ machineId,
+ agentId,
+ engine,
+ profile: choice.destination.agentProfile,
+ );
if (mounted && error != null) _showPaneActionHint(error);
return;
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 08c219f97..227015fe4 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1,4 +1,5 @@
import '../core/home_dir.dart';
+import '../usage/usage_account_key.dart';
import '../measurement/product_measurement.dart';
import '../measurement/product_runtime_health.dart';
import '../measurement/product_connections.dart';
@@ -96,6 +97,7 @@ import '../settings/config_store.dart';
import '../settings/experimental_features.dart';
import '../core/local_key_value_store.dart';
import '../core/harness_file_store.dart';
+import '../super_tabs/swarm_accounts.dart';
import '../super_tabs/attachment_upload.dart';
import '../super_tabs/avatar_upload.dart';
import '../super_tabs/backend_transport.dart';
@@ -104,7 +106,8 @@ import '../super_tabs/controller.dart';
import '../super_tabs/join_machine.dart';
import '../super_tabs/identity.dart' show superTabMachineName;
import '../super_tabs/view_store.dart';
-import '../super_tabs/notifications.dart' show superTabChatNotice, superTabMentionNotice;
+import '../super_tabs/notifications.dart'
+ show superTabChatNotice, superTabMentionNotice;
import '../measurement/setup_preference_store.dart';
import '../devices/device_hosts.dart';
import '../stats/harness_stats.dart';
@@ -266,12 +269,50 @@ class AgentForkAttempt {
Future<ForkAgentResult>? get pending => _inFlight;
}
+/// One account an engine can run under on a machine, as Change agent offers it.
+class AgentProfile {
+ const AgentProfile({
+ required this.id,
+ required this.key,
+ required this.label,
+ this.path,
+ this.percentLeft,
+ this.offered = true,
+ this.canOffer = false,
+ });
+
+ /// False when the machine's owner has not offered this account to the Swarm. Using it does not:
+ /// only Swarm accounts… does ([AppNotifier.setAccountOffered]).
+ final bool offered;
+
+ /// Not the default account, on a CLI that says what is offered: Swarm accounts… can list it.
+ final bool canOffer;
+
+ /// The account's Swarm profile id ([swarmProfileId]): what `usage_read` and the current-account check use.
+ final String id;
+
+ /// What [AppNotifier.changeAgent] is given: the folder, or `'default'` for the default account.
+ final String key;
+ final String label;
+ final String? path;
+
+ /// Null when the machine could not read this account's usage.
+ final int? percentLeft;
+}
+
+/// Null and `'default'` both mean the machine's default account.
+bool sameAgentProfile(String? a, String? b) =>
+ (a ?? 'default') == (b ?? 'default');
+
/// One deliberate creation, retained by the form if its reply is lost. Reusing
/// it checks the original request; opening New agent starts a fresh intent.
class _AgentChange {
- _AgentChange(this.source, this.engine, this.revision);
+ _AgentChange(this.source, this.engine, this.revision, [this.profile]);
final Agent source;
final String engine;
+
+ /// The account folder to start in ([AgentProfile.key]); null keeps the default.
+ final String? profile;
final int revision;
final creation = AgentCreationAttempt(background: true);
Future<String?>? pending;
@@ -723,6 +764,8 @@ enum AttachIntent { person, automatic }
/// select there, or the first phone or app.
typedef MachinesRequest = ({String? devicePub, bool phones});
+const buddyKeepsItsEngine = 'A Buddy keeps its engine for now';
+
/// Change agent on a Swarm Buddy, which keeps running and so keeps its agent
/// (hn's `BUDDY_KEEPS_ITS_AGENT`, word for word).
const buddyKeepsItsAgent =
@@ -10824,6 +10867,7 @@ class AppNotifier extends ChangeNotifier {
prev.engineDisplayName != agent.engineDisplayName ||
prev.engineIconHint != agent.engineIconHint ||
prev.codexHome != agent.codexHome ||
+ prev.claudeHome != agent.claudeHome ||
prev.modelName != agent.modelName ||
prev.modelEffort != agent.modelEffort ||
prev.gridModel != agent.gridModel ||
@@ -15164,6 +15208,262 @@ class AppNotifier extends ChangeNotifier {
}
}
+ Future<Map<String, dynamic>> listClaudeProfiles(
+ String machineId, {
+ Set<String> observedPaths = const {},
+ }) async {
+ try {
+ return await _conn(machineId).request(
+ 'claude_profiles_list',
+ payload: {'observedPaths': observedPaths.toList()},
+ timeout: const Duration(seconds: 10),
+ );
+ } catch (error) {
+ return {'error': 'UNREACHABLE'};
+ }
+ }
+
+ final _addingClaude = <String>{};
+
+ /// This computer's accounts its owner can offer to the Swarm or take back. Throws when it cannot
+ /// tell, so the screen says so and never reads a failure as "no accounts".
+ Future<List<SwarmAccount>> swarmAccounts(String machineId) async {
+ if (stateOf(machineId)?.isLocalMachine != true) {
+ throw StateError('not this computer');
+ }
+ final agents = stateOf(machineId)?.agents ?? const <Agent>[];
+ return [
+ for (final engine in const ['claude', 'codex'])
+ ...await () async {
+ final reply = engine == 'claude'
+ ? await listClaudeProfiles(
+ machineId,
+ observedPaths: {for (final a in agents) ?a.claudeHome},
+ )
+ : await listCodexProfiles(
+ machineId,
+ observedPaths: {for (final a in agents) ?a.codexHome},
+ );
+ final rows = reply['profiles'];
+ if (rows is! List) throw StateError('no list');
+ return [
+ for (final row in rows)
+ if (row is Map &&
+ row['path'] is String &&
+ row['offered'] is bool &&
+ row['default'] != true)
+ SwarmAccount(
+ engine: engine,
+ path: row['path'] as String,
+ label: row['label'] as String? ?? row['path'] as String,
+ offered: row['offered'] as bool,
+ ),
+ ];
+ }(),
+ ];
+ }
+
+ /// Offers an account of this computer to the Swarm, or takes it back. Null when done, or what to
+ /// tell the owner.
+ Future<String?> setAccountOffered(
+ String machineId,
+ String engine,
+ String path,
+ bool offered,
+ ) async {
+ if (stateOf(machineId)?.isLocalMachine != true) {
+ return 'Accounts can be offered on their own computer only.';
+ }
+ String? code;
+ try {
+ final reply = await _conn(machineId).request(
+ 'swarm_account_offer',
+ payload: {'engine': engine, 'path': path, 'offered': offered},
+ timeout: const Duration(seconds: 10),
+ );
+ code = reply['error'] as String?;
+ } on WsRequestFailure catch (failure) {
+ code = failure.code;
+ } catch (_) {
+ code = 'UNREACHABLE';
+ }
+ return switch (code) {
+ null => null,
+ 'NOT_FOUND' => 'That account’s folder is gone.',
+ 'UNSUPPORTED' ||
+ 'UNKNOWN_TYPE' => 'Update Harness on this computer to offer accounts.',
+ 'TOO_MANY' => 'Too many accounts are offered. Withdraw one first.',
+ _ => 'Couldn’t reach this computer. Try again.',
+ };
+ }
+
+ /// What `usage_read` last said per account, kept so opening the picker again does not call the vendors again.
+ final _usageCache = <(String, String, String), ({DateTime at, int? left})>{};
+ static const _usageFresh = Duration(minutes: 5);
+ static const _usageReadsPerEngine = 8;
+
+ /// Where Codex keeps the default account, which the picker names `'default'`.
+ static String _codexDefaultHome() =>
+ Platform.environment['CODEX_HOME'] ?? '${homeDir()}/.codex';
+
+ /// The accounts [engine] runs under on [machineId], each with the share of its limit left when
+ /// the machine can read it. Empty for any other engine or when the machine does not answer.
+ Future<List<AgentProfile>> agentProfiles(
+ String machineId,
+ String engine,
+ ) async {
+ if (engine != 'claude' && engine != 'codex') return const [];
+ // Profile requests are not sealed for the relay, so only this computer's own daemon is asked.
+ if (stateOf(machineId)?.isLocalMachine != true) return const [];
+ final observed = {
+ for (final a in stateOf(machineId)?.agents ?? const <Agent>[])
+ ?(engine == 'claude' ? a.claudeHome : a.codexHome),
+ };
+ final Map<String, dynamic> reply;
+ try {
+ reply = engine == 'claude'
+ ? await listClaudeProfiles(machineId, observedPaths: observed)
+ : await listCodexProfiles(machineId, observedPaths: observed);
+ } catch (_) {
+ return const [];
+ }
+ final rows = reply['profiles'];
+ if (rows is! List) return const [];
+ final defaultId = swarmProfileId(machineId, engine, 'default');
+ final profiles = [
+ for (final row in rows)
+ if (row is Map && row['path'] is String)
+ () {
+ final path = row['path'] as String;
+ final rowId = row['id'] as String?;
+ // An old Claude CLI names its default account with the literal 'default'.
+ final legacy = engine == 'claude' && rowId == 'default';
+ // The CLI marks the default row; an old Codex CLI sends no flag, so its env folder is it.
+ final isDefault =
+ row['default'] == true ||
+ legacy ||
+ rowId == defaultId ||
+ (engine == 'codex' &&
+ row['default'] == null &&
+ path == _codexDefaultHome());
+ return (
+ path: path,
+ offered: row['offered'] != false,
+ canOffer: row['offered'] is bool && !isDefault,
+ label: row['label'] as String? ?? path,
+ id: isDefault
+ ? defaultId
+ : (rowId ?? swarmProfileId(machineId, engine, path)),
+ isDefault: isDefault,
+ legacy: legacy,
+ );
+ }(),
+ ];
+ // One account has no choice to show, so its usage is not worth a vendor call.
+ var budget = profiles.length > 1 ? _usageReadsPerEngine : 0;
+ return Future.wait([
+ for (final p in profiles)
+ () async {
+ final key = (machineId, engine, p.id);
+ var cached = _usageCache[key];
+ if ((cached == null ||
+ clock.now().difference(cached.at) >= _usageFresh) &&
+ budget > 0) {
+ budget--;
+ int? left;
+ try {
+ // An old CLI does not know profile reads: its plain read answers both
+ // engines' default accounts, so take the one for this engine.
+ final usage = parseUsageReadResult(
+ await _conn(machineId).request(
+ 'usage_read',
+ payload: p.legacy
+ ? const {}
+ : {
+ 'profile': {'engine': engine, 'id': p.id},
+ },
+ timeout: const Duration(seconds: 10),
+ ),
+ );
+ final tightest =
+ (p.legacy
+ ? usage
+ .where((u) => u.provider.name == engine)
+ .firstOrNull
+ : usage.firstOrNull)
+ ?.tightest;
+ if (tightest != null) {
+ left = (100 - tightest.usedPercent).round().clamp(0, 100);
+ }
+ } catch (_) {}
+ cached = _usageCache[key] = (at: clock.now(), left: left);
+ }
+ return AgentProfile(
+ id: p.id,
+ key: p.isDefault ? 'default' : p.path,
+ label: p.label,
+ path: p.path,
+ percentLeft: cached?.left,
+ offered: p.offered,
+ canOffer: p.canOffer,
+ );
+ }(),
+ ]);
+ }
+
+ /// Opens a Claude that is signed out in a new account folder beside the others on [machineId]:
+ /// the picker lists it once the person has run /login there. A pane cannot be given an
+ /// environment, so Claude is started with `claudeHome` instead of `CLAUDE_CONFIG_DIR`.
+ Future<String?> addClaudeAccount(String machineId, String agentId) async {
+ if (stateOf(machineId)?.isLocalMachine != true) {
+ return 'A Claude account can be added on this computer only.';
+ }
+ final source = stateOf(machineId)?.agents
+ .where((a) => a.id == agentId)
+ .firstOrNull;
+ final folder =
+ source?.project?.cwd ??
+ (source == null ? null : stateOf(machineId)?.projectOf(source)?.cwd);
+ if (folder == null) {
+ return 'This harness has no project folder to open Claude in.';
+ }
+ // One add at a time per machine: a second click would pick the same folder.
+ if (!_addingClaude.add(machineId)) {
+ return 'A Claude account is already being added.';
+ }
+ try {
+ final listed = await listClaudeProfiles(machineId);
+ final rows =
+ (listed['profiles'] as List?)?.whereType<Map>().toList() ?? [];
+ final home = rows.isEmpty ? null : rows.first['path'] as String?;
+ if (home == null) return 'Could not reach this machine.';
+ // A folder is free when the machine does not list it and no agent here runs in it.
+ final taken = {
+ for (final r in rows) r['path'],
+ for (final a in stateOf(machineId)?.agents ?? const <Agent>[])
+ a.claudeHome,
+ };
+ var n = 1;
+ while (taken.contains('$home/.harness/claude-profiles/$n')) {
+ n++;
+ }
+ final path = '$home/.harness/claude-profiles/$n';
+ // The folder only exists once Claude has signed in there; the machine finds it by itself then.
+ final error = await createAgent(
+ machineId,
+ engine: 'claude',
+ folder: folder,
+ claudeHome: path,
+ );
+ if (error == null) {
+ agentChangeNotice?.call('Run /login, then pick it again');
+ }
+ return error;
+ } finally {
+ _addingClaude.remove(machineId);
+ }
+ }
+
/// Starts an agent, or recovers this form's earlier request after a lost reply.
/// Returns null on success, or an inline message; [attempt] tells the form
/// whether to offer Check status instead of inviting another creation.
@@ -15213,6 +15513,7 @@ class AppNotifier extends ChangeNotifier {
bool bypassPermission = true,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
@@ -15237,6 +15538,7 @@ class AppNotifier extends ChangeNotifier {
// dialog derives from the same choice.
'permissionMode': ?permissionMode,
'codexHome': ?codexHome,
+ 'claudeHome': ?claudeHome,
// The harness this agent is created from. `engine` above is its BASE —
// the machine refuses the pair when they disagree (`INVALID_DSH`).
'dsh': ?dsh,
@@ -15706,6 +16008,9 @@ class AppNotifier extends ChangeNotifier {
? null
: _creationPlacementError(targetId, split, placement: placement);
if (placementError != null) return placementError;
+ if (choices['claudeHome'] != null && choices['engine'] != 'claude') {
+ return 'Choose a Claude account only for Claude';
+ }
if (choices['codexHome'] != null) {
if (choices['engine'] != 'codex') {
return 'Choose a Codex profile only for Codex';
@@ -17301,6 +17606,24 @@ class AppNotifier extends ChangeNotifier {
/// top, which shows it as a snack bar; null when no screen is listening.
void Function(String message)? agentChangeNotice;
+ /// Whether [agentId] is a Swarm Buddy, as any open Swarm's roster says. Its machine refuses to
+ /// stop it, so Change agent cannot switch it.
+ @visibleForTesting
+ final buddyAgentsForTest = <(String, String)>{};
+
+ bool isSwarmBuddy(String machineId, String agentId) =>
+ buddyAgentsForTest.contains((machineId, agentId)) ||
+ superTabs.loadedControllers.any(
+ (c) =>
+ c.snapshot?.agents.any(
+ (a) =>
+ a.isBuddy &&
+ a.machineId == machineId &&
+ a.harnessId == agentId,
+ ) ==
+ true,
+ );
+
List<String> agentSwitchEngines(String machineId, Agent source) {
if (source.dsh == 'autonomous/pair') {
return const ['opencode', 'codex', 'claude'];
@@ -17322,14 +17645,25 @@ class AppNotifier extends ChangeNotifier {
/// One switch intent owns its creation receipt. Save the old conversation,
/// then move all views as soon as the replacement terminal can be attached.
- Future<String?> changeAgent(String machineId, String agentId, String engine) {
+ Future<String?> changeAgent(
+ String machineId,
+ String agentId,
+ String engine, {
+ String? profile,
+ }) {
final source = stateOf(machineId)?.agents
.where((a) => a.id == agentId)
.firstOrNull;
if (source == null) {
return Future.value('This harness is no longer available.');
}
- if (source.engine == engine) return Future.value();
+ final currentProfile = source.engine == 'claude'
+ ? source.claudeHome
+ : source.codexHome;
+ if (source.engine == engine &&
+ (profile == null || sameAgentProfile(profile, currentProfile))) {
+ return Future.value();
+ }
if (stateOf(machineId)?.machine.isShared != false) {
return Future.value('Shared harnesses are view-only.');
}
@@ -17343,6 +17677,9 @@ class AppNotifier extends ChangeNotifier {
'This agent is not supported by the installed harness.',
);
}
+ if (isSwarmBuddy(machineId, agentId)) {
+ return Future.value(buddyKeepsItsEngine);
+ }
final key = (machineId, agentId);
if (source.dsh == 'autonomous/pair' &&
_agentChanges[key] == null &&
@@ -17354,25 +17691,35 @@ class AppNotifier extends ChangeNotifier {
}
var operation = _agentChanges[key];
if (operation?.pending case final pending?) {
- return operation!.engine == engine
+ return operation!.engine == engine &&
+ sameAgentProfile(operation.profile, profile)
? pending
: Future.value('The agent is already switching.');
}
if (operation != null &&
((!operation.preservingViews &&
- (!operation.handoffHeld || operation.engine != engine)) ||
+ (!operation.handoffHeld ||
+ operation.engine != engine ||
+ !sameAgentProfile(operation.profile, profile))) ||
operation.launchFailed ||
(operation.creation._finished &&
operation.creation.agentId == null))) {
_agentChanges.remove(key);
operation = null;
}
- if (operation != null && operation.engine != engine) {
+ if (operation != null &&
+ (operation.engine != engine ||
+ !sameAgentProfile(operation.profile, profile))) {
return Future.value(
'Check the pending switch to ${operation.engine} before choosing another agent.',
);
}
- final change = operation ??= _AgentChange(source, engine, _authRevision);
+ final change = operation ??= _AgentChange(
+ source,
+ engine,
+ _authRevision,
+ profile,
+ );
_agentChanges[key] = change;
return change.pending = _changeAgent(
machineId,
@@ -17578,6 +17925,12 @@ class AppNotifier extends ChangeNotifier {
engine: change.engine,
folder: folder,
dsh: source.dsh,
+ codexHome: change.engine == 'codex' && change.profile != 'default'
+ ? change.profile
+ : null,
+ claudeHome: change.engine == 'claude' && change.profile != 'default'
+ ? change.profile
+ : null,
name: source.displayName,
permissionMode: mode,
bypassPermission: mode == 'auto' || mode == 'full',
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 463304d17..28a449bd2 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -317,6 +317,9 @@ class SwarmDestination {
this.agentId,
this.modelId,
this.agentEngine,
+ this.agentProfile,
+ this.addsClaudeAccount = false,
+ this.managesSwarmAccounts = false,
this.storeId,
this.engine,
this.closedId,
@@ -365,6 +368,15 @@ class SwarmDestination {
final String? swarmId, machineId, agentId, engine;
final String? modelId;
final String? agentEngine;
+
+ /// The account to run [agentEngine] under ([AgentProfile.key]); null when the machine has one.
+ final String? agentProfile;
+
+ /// The row that opens a new Claude account folder to sign in to.
+ final bool addsClaudeAccount;
+
+ /// The row that opens Swarm accounts, where an account is offered or taken back.
+ final bool managesSwarmAccounts;
bool get isAgentChoice => agentEngine != null;
bool get isModel => modelId != null;
final String? storeId;
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 1d381d3c6..ae476ffa9 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -11,6 +11,7 @@ import '../models/local_model.dart';
import '../models/model_search_catalog.dart';
import '../models/swarm_models_target.dart';
import '../usage/models_menu_controller.dart' show subscriptionSearchId;
+import '../usage/usage_account_key.dart';
import '../core/dsh_catalog.dart';
import '../store/experimental_harnesses.dart';
import '../core/machine_resources.dart';
@@ -1197,15 +1198,29 @@ class SwarmSearchController extends ChangeNotifier {
?.agents
.where((a) => a.id == agentSelectionId)
.firstOrNull;
+
+ /// The accounts of each engine on the selected agent's machine, read when it is selected.
+ final _agentProfiles = <String, List<AgentProfile>>{};
void setAgentSelection(String machineId, String agentId) {
agentSelectionMachineId = machineId;
agentSelectionId = agentId;
+ _agentProfiles.clear();
_filter();
notifyListeners();
+ if (app.isSwarmBuddy(machineId, agentId)) return;
+ for (final engine in const ['claude', 'codex']) {
+ app.agentProfiles(machineId, engine).then((profiles) {
+ if (agentSelectionMachineId != machineId || profiles.isEmpty) return;
+ _agentProfiles[engine] = profiles;
+ _filter(keepOrder: true);
+ notifyListeners();
+ });
+ }
}
bool canSelectAgent(String engine) =>
agentSelection != null &&
+ !app.isSwarmBuddy(agentSelectionMachineId!, agentSelection!.id) &&
app.stateOf(agentSelectionMachineId!)?.machine.isShared == false &&
app
.agentSwitchEngines(agentSelectionMachineId!, agentSelection!)
@@ -1967,30 +1982,96 @@ class SwarmSearchController extends ChangeNotifier {
? 1
: a.label.compareTo(b.label),
);
+ final current = agentSelection;
+ final isBuddy =
+ current != null &&
+ app.isSwarmBuddy(agentSelectionMachineId!, current.id);
+ // The agent's account id: its folder's, or the engine's default.
+ final currentHome = current?.engine == 'claude'
+ ? current?.claudeHome
+ : current?.codexHome;
+ final currentId = current == null
+ ? null
+ : swarmProfileId(
+ agentSelectionMachineId!,
+ current.engine ?? '',
+ currentHome ?? 'default',
+ );
+ SwarmDestination row(
+ EngineIdentity engine, {
+ AgentProfile? profile,
+ bool several = false,
+ }) {
+ final isCurrent =
+ current?.engine == engine.id &&
+ (!several || profile!.id == currentId);
+ final base = engine.id == 'claude' ? 'Claude Code' : engine.label;
+ return SwarmDestination(
+ id: 'engine:${engine.id}${several ? ':${profile!.key}' : ''}',
+ agentEngine: engine.id,
+ agentProfile: several ? profile!.key : null,
+ engine: engine.id,
+ title: several
+ ? '${engine.id == 'claude' ? 'Claude' : engine.label} · ${profile!.label}'
+ : base,
+ detail: current == null
+ ? 'Focus a harness to change its agent'
+ : isBuddy
+ ? buddyKeepsItsEngine
+ : !canSelectAgent(engine.id)
+ ? 'Not supported by this harness'
+ : several && !profile!.offered
+ ? 'Not offered to the Swarm'
+ : several && profile!.percentLeft != null
+ ? '${profile.percentLeft}% left'
+ : isCurrent
+ ? 'Current agent'
+ : engine.id == 'opencode'
+ ? 'Muse Spark 1.3 · continue with recent context'
+ : supportsAgentHandoff(engine.id)
+ ? 'Continue this project with recent context'
+ : 'New conversation in the same project',
+ swarmId: null,
+ current: isCurrent,
+ );
+ }
+
rows = [
for (final engine in engines)
if ('${engine.label} ${engine.id}'.toLowerCase().contains(
matchQuery.toLowerCase(),
))
- SwarmDestination(
- id: 'engine:${engine.id}',
- agentEngine: engine.id,
- engine: engine.id,
- title: engine.id == 'claude' ? 'Claude Code' : engine.label,
- detail: agentSelection == null
- ? 'Focus a harness to change its agent'
- : !canSelectAgent(engine.id)
- ? 'Not supported by this harness'
- : agentSelection?.engine == engine.id
- ? 'Current agent'
- : engine.id == 'opencode'
- ? 'Muse Spark 1.3 · continue with recent context'
- : supportsAgentHandoff(engine.id)
- ? 'Continue this project with recent context'
- : 'New conversation in the same project',
- swarmId: null,
- current: agentSelection?.engine == engine.id,
- ),
+ if ((_agentProfiles[engine.id]?.length ?? 0) > 1)
+ for (final profile in _agentProfiles[engine.id]!)
+ row(engine, profile: profile, several: true)
+ else
+ row(engine),
+ // Only a machine that listed its Claude accounts can open another folder.
+ if (_agentProfiles['claude'] != null &&
+ 'add claude account'.contains(matchQuery.toLowerCase()) &&
+ canSelectAgent('claude'))
+ SwarmDestination(
+ id: 'engine:claude:add',
+ agentEngine: 'claude',
+ addsClaudeAccount: true,
+ engine: 'claude',
+ title: 'Add Claude account…',
+ detail: 'Opens Claude to sign in. Yours until you offer it',
+ swarmId: null,
+ current: false,
+ ),
+ if (_agentProfiles.values.any((l) => l.any((p) => p.canOffer)) &&
+ 'swarm accounts'.contains(matchQuery.toLowerCase()))
+ SwarmDestination(
+ id: 'engine:swarm-accounts',
+ agentEngine: 'claude',
+ managesSwarmAccounts: true,
+ engine: 'claude',
+ title: 'Swarm accounts…',
+ detail: 'Choose what other people’s PMs can use',
+ swarmId: null,
+ current: false,
+ ),
];
total = engines.length;
matchCount = rows.length;
diff --git a/desktop/lib/super_tabs/agent_line.dart b/desktop/lib/super_tabs/agent_line.dart
index 0dc5bdbf8..38ab5e3d4 100644
--- a/desktop/lib/super_tabs/agent_line.dart
+++ b/desktop/lib/super_tabs/agent_line.dart
@@ -55,6 +55,7 @@ SuperTabAgentGlance superTabAgentGlance(
final until = agent.limitedUntil?.toLocal();
String two(int n) => n.toString().padLeft(2, '0');
final label = switch (null) {
+ _ when agent.switchRequest != null => 'Switching…',
_ when work == 'lost' => 'Lost',
_
when agent.downSince != null ||
diff --git a/desktop/lib/super_tabs/attention.dart b/desktop/lib/super_tabs/attention.dart
index 80a99ed0e..229ae1fd1 100644
--- a/desktop/lib/super_tabs/attention.dart
+++ b/desktop/lib/super_tabs/attention.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:math';
+import 'package:clock/clock.dart';
import 'package:flutter/foundation.dart';
import 'controller.dart';
@@ -54,6 +55,28 @@ class SuperTabFollowedThread {
/// from the server's followed-threads read, read again when the Swarm moves,
/// at most every [quietGap] (every [openGap] while the Threads view is open).
/// One per controller.
+/// One of the reader's replies on a Threads card ([SuperTabAttention.ownReplies]).
+class SuperTabOwnReply {
+ const SuperTabOwnReply(this.text, this.at, {this.outgoing});
+ final String text;
+
+ /// What its row says: a reply of files alone has no text of its own.
+ String get shownText => text.isEmpty ? 'Files' : text;
+
+ /// When it was seen on its way this visit; null for one that failed earlier.
+ final DateTime? at;
+
+ /// Where it stands while the transcript does not hold it; null once it does.
+ final SuperTabOutgoing? outgoing;
+
+ /// On its way, nothing back from the server yet.
+ bool get sending => outgoing?.state == SuperTabOutgoingState.sending;
+
+ /// The server took it.
+ bool get sent =>
+ outgoing == null || outgoing!.state == SuperTabOutgoingState.confirmed;
+}
+
class SuperTabAttention extends ChangeNotifier {
SuperTabAttention._(this.controller, {DateTime Function()? now})
: mentions = SuperTabMentions.of(controller),
@@ -111,6 +134,12 @@ class SuperTabAttention extends ChangeNotifier {
final Map<String, List<SuperTabMessage>> newReplies = {};
final Set<String> _readingReplies = {};
+ /// The replies seen on their way from this view this visit, by thread and
+ /// then by receipt: what [ownReplies] still shows, as sent, once the
+ /// transcript holds them and they leave [SuperTabController.outgoing].
+ final Map<String, Map<String, ({String text, DateTime at})>> _ownThisVisit =
+ {};
+
/// Threads whose replies failed to read this visit: not asked again until
/// the next one, so a failing read is not repeated on every redraw.
final Set<String> _repliesFailed = {};
@@ -246,6 +275,7 @@ class SuperTabAttention extends ChangeNotifier {
_newThisVisit.clear();
_counts.clear();
newReplies.clear();
+ _ownThisVisit.clear();
_repliesFailed.clear();
if (!_disposed) notifyListeners();
}
@@ -258,6 +288,7 @@ class SuperTabAttention extends ChangeNotifier {
_newThisVisit.clear();
_counts.clear();
newReplies.clear();
+ _ownThisVisit.clear();
_readingReplies.clear();
_repliesFailed.clear();
_trailing?.cancel();
@@ -266,6 +297,7 @@ class SuperTabAttention extends ChangeNotifier {
void _changed() {
if (_disposed) return;
+ if (_open) _noteOwnReplies();
if (controller.accessRevoked) {
if (loaded || unread.isNotEmpty || read.isNotEmpty) {
_clear();
@@ -443,6 +475,76 @@ class SuperTabAttention extends ChangeNotifier {
}
}
+ /// Whether [message] is a reply to [thread].
+ static bool _repliesTo(
+ SuperTabOutgoing message,
+ SuperTabFollowedThread thread,
+ ) => message.replyTo == thread.rootId || message.thread == thread.rootId;
+
+ /// Whether [message] failed: refused, or sent with no answer. Never called
+ /// sent; a Retry brings it back on its way.
+ static bool _failed(SuperTabOutgoing message) =>
+ message.state == SuperTabOutgoingState.refused ||
+ message.state == SuperTabOutgoingState.unconfirmed;
+
+ /// Notes the replies on their way from each thread listed, on every change
+ /// of the controller and not only when a frame draws: a send can go from on
+ /// its way to read back between two frames.
+ void _noteOwnReplies() {
+ final threads = [...unread, ...read];
+ for (final conversationId in {for (final t in threads) t.conversationId}) {
+ final rows = controller.outgoing(conversationId);
+ if (rows.isEmpty) continue;
+ for (final thread in threads) {
+ if (thread.conversationId != conversationId) continue;
+ for (final message in rows) {
+ final operationId = message.operationId;
+ if (operationId == null || !_repliesTo(message, thread)) continue;
+ final kept = _ownThisVisit[thread.key] ??= {};
+ if (_failed(message)) {
+ kept.remove(operationId);
+ } else if (message.state == SuperTabOutgoingState.sending) {
+ // First seen on its way only: a sent reply stays in that list
+ // until its chat's transcript loads, and one from an earlier visit
+ // must not come back as new (review of #2555).
+ kept.putIfAbsent(
+ operationId,
+ () => (text: message.text, at: clock.now()),
+ );
+ }
+ }
+ }
+ }
+ }
+
+ /// The reader's own replies to [thread] that its card shows beside
+ /// [newReplies], oldest first: on their way, failed, or sent during this
+ /// visit (Scholes, 2026-11-02: a reply showed only after an agent answered,
+ /// so it looked unsent). One [newReplies] already holds is not shown twice.
+ List<SuperTabOwnReply> ownReplies(SuperTabFollowedThread thread) {
+ final rows = [
+ for (final message in controller.outgoing(thread.conversationId))
+ if (_repliesTo(message, thread)) message,
+ ];
+ final live = {for (final m in rows) ?m.operationId: m};
+ final read = {for (final m in newReplies[thread.key] ?? const []) m.id};
+ return [
+ for (final MapEntry(key: operationId, :value)
+ in (_ownThisVisit[thread.key] ?? const {}).entries)
+ if (!read.contains(
+ superTabMessageId(
+ tabId: controller.tabId,
+ accountId: controller.accountId,
+ operationId: operationId,
+ ),
+ ))
+ SuperTabOwnReply(value.text, value.at, outgoing: live[operationId]),
+ for (final message in rows)
+ if (_failed(message))
+ SuperTabOwnReply(message.text, null, outgoing: message),
+ ];
+ }
+
/// Follows (true) or unfollows (false) [thread] on every device of the
/// reader; false when the server did not keep it.
Future<bool> setFollow(SuperTabFollowedThread thread, bool follow) async {
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 70897e33c..2efae341e 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -154,6 +154,10 @@ class SuperTabAgent {
alerting = List.unmodifiable(
(row['alerting'] as List?)?.whereType<String>() ?? const <String>[],
),
+ switchRequest = row['switchRequest'] is Map
+ ? Map.unmodifiable(superTabMap(row['switchRequest']))
+ : null,
+ profileId = row['profileId'] as String?,
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),
confidential = row['confidential'] == true,
@@ -171,6 +175,14 @@ 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.
+ final Map<String, dynamic>? switchRequest;
+
+ /// The account on its machine it runs in; `default` when none is chosen.
+ /// Null until the backend reports it: the engine's default account.
+ final String? profileId;
+
/// Since when its machine has reported its session gone, or its host confirmed a stop (backend machines.ts). Null
/// while it runs.
final DateTime? downSince;
@@ -674,6 +686,23 @@ class SuperTabSnapshot {
bool isLead(String agentId) => leadProjectForAgent(agentId) != null;
+ /// [projectId]'s Product Manager, while it has one.
+ SuperTabAgent? leadOf(String projectId) {
+ final id = conversation(projectById(projectId)?.leadConversationId ?? '')
+ ?.leadId;
+ return id == null ? null : agent(id);
+ }
+
+ /// Whether [accountId] may switch [projectId]'s Product Manager: the project's
+ /// owner, or the owner of the machine it runs on (the backend decides again).
+ bool maySwitchLead(String projectId, String? accountId) {
+ final lead = leadOf(projectId);
+ return lead != null &&
+ accountId != null &&
+ (projectById(projectId)?.ownerId == accountId ||
+ lead.machineOwnerId == accountId);
+ }
+
/// What [projectId] calls its coordinator: its `coordinatorName`, or [kDefaultCoordinatorName] from a backend
/// that names none.
String coordinatorNameOf(String projectId) =>
@@ -900,6 +929,37 @@ List<SuperTabServedModel> superTabServedModels(
];
}
+/// One account of a machine as its report lists it (backend
+/// `observation.profiles`): opaque id, a label with no path or email, and what
+/// is left of its allowance when known.
+typedef SuperTabProfile = ({
+ String engine,
+ String id,
+ String label,
+ int? leftPercent,
+ DateTime? resetsAt,
+});
+
+/// The accounts [pool] reports; empty from a machine that reports none.
+List<SuperTabProfile> superTabProfilesOf(Map<String, dynamic>? pool) {
+ final observation = pool?['observation'];
+ final rows = observation is Map ? observation['profiles'] : null;
+ return [
+ for (final p in rows is List ? rows : const [])
+ if (p is Map &&
+ p['engine'] is String &&
+ p['id'] is String &&
+ p['label'] is String)
+ (
+ engine: p['engine'] as String,
+ id: p['id'] as String,
+ label: p['label'] as String,
+ leftPercent: (p['leftPercent'] as num?)?.toInt(),
+ resetsAt: DateTime.tryParse(p['resetsAt'] as String? ?? ''),
+ ),
+ ];
+}
+
class SuperTabRouteChoice {
const SuperTabRouteChoice(this.id, this.title);
final String id, title;
@@ -1198,6 +1258,14 @@ class SuperTabMessage {
? source['agentId'] as String?
: null;
+ /// The Product Manager a usage-limit note is about; null for any other row.
+ String? get leadLimitAgentId =>
+ source['kind'] == 'terminal-alert' &&
+ source['alert'] == 'limit' &&
+ source['lead'] == true
+ ? source['agentId'] as String?
+ : null;
+
/// A note the backend writes about a terminal: a Lead's typing, or an alert.
bool get terminalEvent =>
source['kind'] == 'terminal-input' || source['kind'] == 'terminal-alert';
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index cec41d891..7aa123c85 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -437,7 +437,8 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
].join('\n');
// The row's details line (Dee, 2026-10-30): the task in plain words and
// how long since its last progress; with no task, the state in a word.
- final limited = glance.label.startsWith('Limited until')
+ final limited =
+ glance.label.startsWith('Limited until') || glance.label == 'Switching…'
? glance.label
: null;
final detail = work == null
diff --git a/desktop/lib/super_tabs/swarm_accounts.dart b/desktop/lib/super_tabs/swarm_accounts.dart
new file mode 100644
index 000000000..5daeceaa6
--- /dev/null
+++ b/desktop/lib/super_tabs/swarm_accounts.dart
@@ -0,0 +1,165 @@
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+import '../widgets/desktop_chrome.dart';
+
+/// One account of this computer the owner can offer to the Swarm or take back.
+class SwarmAccount {
+ const SwarmAccount({
+ required this.engine,
+ required this.path,
+ required this.label,
+ required this.offered,
+ });
+ final String engine;
+ final String path;
+ final String label;
+ final bool offered;
+}
+
+/// The one place an account is offered to the Swarm. Everything else (linking a
+/// folder, Add Claude account, picking a row in Change agent) keeps it private:
+/// an offer lets other people's PMs spend it, so it is a choice of its own.
+Future<void> showSwarmAccounts(
+ BuildContext context,
+ AppNotifier app,
+ String machineId,
+) => showAppDialog<void>(
+ context: context,
+ builder: (context) => SwarmAccountsDialog(
+ load: () => app.swarmAccounts(machineId),
+ setOffered: (account, offered) =>
+ app.setAccountOffered(machineId, account.engine, account.path, offered),
+ ),
+);
+
+class SwarmAccountsDialog extends StatefulWidget {
+ const SwarmAccountsDialog({
+ super.key,
+ required this.load,
+ required this.setOffered,
+ });
+ final Future<List<SwarmAccount>> Function() load;
+
+ /// Null when done, or what to tell the owner.
+ final Future<String?> Function(SwarmAccount account, bool offered) setOffered;
+
+ @override
+ State<SwarmAccountsDialog> createState() => _SwarmAccountsDialogState();
+}
+
+class _SwarmAccountsDialogState extends State<SwarmAccountsDialog> {
+ List<SwarmAccount>? _accounts;
+ var _loading = true, _readFailed = false, _busy = false;
+ String? _error;
+
+ /// Only the newest read may change the list.
+ var _read = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ _reload();
+ }
+
+ Future<void> _reload() async {
+ final read = ++_read;
+ setState(() {
+ _loading = true;
+ _readFailed = false;
+ });
+ List<SwarmAccount>? accounts;
+ try {
+ accounts = await widget.load();
+ } catch (_) {
+ accounts = null;
+ }
+ if (!mounted || read != _read) return;
+ setState(() {
+ _loading = false;
+ _readFailed = accounts == null;
+ if (accounts != null) _accounts = accounts;
+ });
+ }
+
+ Future<void> _set(SwarmAccount account, bool offered) async {
+ if (_busy) return;
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final error = await widget.setOffered(account, offered);
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ if (error == null) await _reload();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final accounts = _accounts;
+ return AlertDialog(
+ title: const Text('Swarm accounts'),
+ content: SizedBox(
+ width: 400,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Other people’s PMs on this Mac can run on an offered account and spend its usage.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: 12),
+ if (_readFailed) ...[
+ const Text('Couldn’t read this computer’s accounts.'),
+ TextButton(onPressed: _reload, child: const Text('Try again')),
+ ] else if (accounts == null)
+ const Center(child: CircularProgressIndicator())
+ else if (accounts.isEmpty)
+ const Text('No other accounts on this computer yet.')
+ else
+ for (final account in accounts)
+ ListTile(
+ key: ValueKey(
+ 'swarm-account-${account.engine}-${account.path}',
+ ),
+ dense: true,
+ contentPadding: EdgeInsets.zero,
+ title: Text(
+ '${account.engine == 'claude' ? 'Claude' : 'Codex'} · ${account.label}',
+ ),
+ subtitle: Text(account.offered ? 'Offered' : 'Not offered'),
+ trailing: TextButton(
+ onPressed: _busy || _loading
+ ? null
+ : () => _set(account, !account.offered),
+ child: Text(account.offered ? 'Withdraw' : 'Offer'),
+ ),
+ ),
+ if (_error != null) ...[
+ const SizedBox(height: 12),
+ Text(_error!),
+ ],
+ const SizedBox(height: 12),
+ Text(
+ 'A PM already on a withdrawn account keeps running until someone moves it.',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.maybePop(context),
+ child: const Text('Done'),
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/switch_pm.dart b/desktop/lib/super_tabs/switch_pm.dart
new file mode 100644
index 000000000..6b300cb50
--- /dev/null
+++ b/desktop/lib/super_tabs/switch_pm.dart
@@ -0,0 +1,192 @@
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../state/lead_placement.dart';
+import '../usage/usage_account_key.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'dialog_scope.dart';
+import 'model.dart';
+
+/// "2:00 PM" for today, "Nov 3, 2:00 PM" for another day this year, with the
+/// year after that, in the reader's time.
+String switchPmTime(BuildContext context, DateTime at) {
+ final local = at.toLocal(), now = DateTime.now();
+ final l10n = MaterialLocalizations.of(context);
+ final time = l10n.formatTimeOfDay(TimeOfDay.fromDateTime(local));
+ if (local.year == now.year &&
+ local.month == now.month &&
+ local.day == now.day) {
+ return time;
+ }
+ final day = local.year == now.year
+ ? l10n.formatShortMonthDay(local)
+ : l10n.formatShortDate(local);
+ return '$day, $time';
+}
+
+/// Moves [projectId]'s Product Manager to another engine or account on the
+/// machine it runs on (spec 2026-11-02-pm-switch-engine-account-design.md). The
+/// machine's host does the switch; this sends `lead.switch` and shows a refusal.
+Future<void> showSwitchPm(
+ BuildContext context,
+ SuperTabController c,
+ String projectId,
+) {
+ ({String engine, String id})? picked;
+ var busy = false;
+ // An earlier refusal belongs to that dialog, not to this one.
+ if (!c.hasPendingAction) c.operationError = null;
+ return showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ projectId: projectId,
+ requireWrite: true,
+ child: StatefulBuilder(
+ builder: (context, update) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ final snapshot = c.snapshot;
+ final lead = snapshot?.leadOf(projectId);
+ final pool = snapshot?.pool(lead?.machineId ?? '');
+ var profiles = superTabProfilesOf(pool);
+ final reported = profiles.isNotEmpty;
+ if (!reported && lead != null) {
+ // A machine that reports no accounts: its default account, per
+ // engine it offers.
+ final offered = (pool?['engines'] as List?)?.whereType<String>();
+ profiles = [
+ for (final engine in kLeadEngines)
+ if (offered?.contains(engine) ?? engine == lead.engine)
+ (
+ engine: engine,
+ id: 'default',
+ label: 'Default',
+ leftPercent: null,
+ resetsAt: null,
+ ),
+ ];
+ }
+ profiles.sort(
+ (a, b) =>
+ kLeadEngines.indexOf(a.engine) -
+ kLeadEngines.indexOf(b.engine),
+ );
+ // A PM that reports no account runs its engine's default one.
+ final currentId =
+ lead?.profileId ??
+ (reported
+ ? swarmProfileId(
+ lead?.machineId ?? '',
+ lead?.engine ?? '',
+ 'default',
+ )
+ : 'default');
+ bool current(SuperTabProfile p) =>
+ p.engine == lead?.engine && p.id == currentId;
+ final switching = lead?.switchRequest != null;
+ return AlertDialog(
+ title: const Text('Switch PM'),
+ content: SizedBox(
+ width: 400,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ for (final p in profiles)
+ ListTile(
+ key: ValueKey('switch-pm-${p.engine}-${p.id}'),
+ dense: true,
+ contentPadding: EdgeInsets.zero,
+ enabled: !current(p) && p.leftPercent != 0,
+ selected:
+ picked?.engine == p.engine && picked?.id == p.id,
+ title: Text(
+ '${leadEngineLabel(p.engine)} · ${p.label}',
+ ),
+ subtitle: Text(
+ [
+ if (current(p)) 'Current',
+ if (p.leftPercent != null)
+ '${p.leftPercent}% left',
+ if (p.resetsAt != null)
+ 'resets ${switchPmTime(context, p.resetsAt!)}',
+ ].join(' · '),
+ ),
+ onTap: () => update(
+ () => picked = (engine: p.engine, id: p.id),
+ ),
+ ),
+ if (lead != null &&
+ lead.machineOwnerId != c.accountId) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'Only accounts its owner offered are listed.',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ const SizedBox(height: 12),
+ Text(
+ 'The new session starts fresh and reads a handoff note. Tasks and chat stay.',
+ style: DesktopChrome.text(),
+ ),
+ if (c.operationError != null) ...[
+ const SizedBox(height: 12),
+ Text(c.operationError!),
+ ],
+ if (c.hasPendingAction)
+ TextButton(
+ onPressed: c.saving
+ ? null
+ : () async {
+ final result = await c.retry();
+ if (context.mounted && result != null) {
+ Navigator.pop(context);
+ }
+ },
+ child: const Text('Check pending action'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed:
+ busy ||
+ c.saving ||
+ c.hasPendingAction ||
+ switching ||
+ picked == null
+ ? null
+ : () async {
+ update(() => busy = true);
+ final result = await c.command({
+ 'type': 'lead.switch',
+ 'projectId': projectId,
+ 'engine': picked!.engine,
+ 'profileId': picked!.id,
+ });
+ if (!context.mounted) return;
+ if (result != null) {
+ Navigator.pop(context);
+ } else {
+ update(() => busy = false);
+ }
+ },
+ child: const Text('Switch'),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/terminal_row.dart b/desktop/lib/super_tabs/terminal_row.dart
index b5b9fe160..39b8ed560 100644
--- a/desktop/lib/super_tabs/terminal_row.dart
+++ b/desktop/lib/super_tabs/terminal_row.dart
@@ -3,8 +3,11 @@ import 'package:flutter/material.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../widgets/desktop_chrome.dart';
+import '../widgets/finger_target.dart';
+import 'controller.dart';
import 'message_row.dart';
import 'model.dart';
+import 'switch_pm.dart';
/// A Lead's typing into a worker's terminal, or a worker's machine telling its
/// Lead it waits at a prompt or hit a usage limit
@@ -13,8 +16,56 @@ import 'model.dart';
/// happened as one sentence; it is a note in the group, not chat from the
/// agent, so it has no author heading, reply or receipt.
class SuperTabTerminalRow extends StatelessWidget {
- const SuperTabTerminalRow({super.key, required this.message});
+ const SuperTabTerminalRow({
+ super.key,
+ required this.message,
+ required this.controller,
+ });
final SuperTabMessage message;
+ final SuperTabController controller;
+
+ /// Switch PM… on the Product Manager's own limit note, for whoever may switch
+ /// it, while its machine still alerts about the limit (as a prompt note
+ /// stops saying anything once answered, prompt_alerts.dart).
+ bool get _canSwitch {
+ final id = message.leadLimitAgentId, snapshot = controller.snapshot;
+ final lead = id == null ? null : snapshot?.agent(id);
+ final project = id == null ? null : snapshot?.leadProjectForAgent(id);
+ return lead != null &&
+ project != null &&
+ controller.canWrite &&
+ lead.alerting.contains('limit') &&
+ lead.switchRequest == null &&
+ snapshot!.maySwitchLead(project.id, controller.accountId);
+ }
+
+ Widget _action(BuildContext context, String label, VoidCallback onPressed) =>
+ TextButton(
+ onPressed: onPressed,
+ style:
+ TextButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.onSurfaceVariant,
+ backgroundColor: Colors.transparent,
+ side: BorderSide.none,
+ // A phone's action is a finger's size.
+ minimumSize: workspaceIsCompact(context)
+ ? const Size.square(kFingerTarget)
+ : const Size(0, 28),
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ vertical: grid.AppDesktop.menuInset,
+ ),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ textStyle: DesktopChrome.metadata(),
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.focused)
+ ? TextButtonTheme.of(context).style?.side?.resolve(states)
+ : BorderSide.none,
+ ),
+ ),
+ child: Text(label),
+ );
@override
Widget build(BuildContext context) {
@@ -23,6 +74,13 @@ class SuperTabTerminalRow extends StatelessWidget {
final style = DesktopChrome.metadata(
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
+ // The backend names the time in UTC; the reader reads their own.
+ final until = message.leadLimitAgentId == null
+ ? null
+ : DateTime.tryParse(message.source['limitedUntil'] as String? ?? '');
+ final project = message.leadLimitAgentId == null
+ ? null
+ : controller.snapshot?.leadProjectForAgent(message.leadLimitAgentId!);
return Padding(
padding: const EdgeInsets.fromLTRB(
SuperTabMessageRow.bodyInset,
@@ -41,7 +99,23 @@ class SuperTabTerminalRow extends StatelessWidget {
color: alert ? grid.AppPalette.warn : style.color,
),
),
- Expanded(child: Text.rich(_typed(message.text, style), style: style)),
+ Expanded(
+ child: Wrap(
+ spacing: 4,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ Text.rich(_typed(message.text, style), style: style),
+ if (until != null)
+ Text('until ${switchPmTime(context, until)}', style: style),
+ if (project != null && _canSwitch)
+ _action(
+ context,
+ 'Switch PM…',
+ () => showSwitchPm(context, controller, project.id),
+ ),
+ ],
+ ),
+ ),
],
),
);
diff --git a/desktop/lib/super_tabs/threads_view.dart b/desktop/lib/super_tabs/threads_view.dart
index f3111e495..c7869d4c7 100644
--- a/desktop/lib/super_tabs/threads_view.dart
+++ b/desktop/lib/super_tabs/threads_view.dart
@@ -5,11 +5,13 @@ import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../widgets/desktop_chrome.dart';
import 'attention.dart';
+import 'composer_newline.dart' show kComposerMaxLength;
import 'composer_tags.dart';
import '../shared/theme/app_icons.dart';
import 'controller.dart';
import 'identity.dart';
import 'message_more_menu.dart';
+import 'message_receipt.dart';
import 'machine_status.dart' show superTabAgo;
import 'model.dart';
import 'reply_box.dart';
@@ -420,6 +422,65 @@ class _ThreadCardState extends State<_ThreadCard> {
if (mounted) setState(() {});
}
+ /// What the box says, unless a failed reply above it already says the same.
+ String? _boxError() {
+ final error = _c.threadComposerError(
+ _thread.conversationId,
+ _thread.rootId,
+ );
+ return widget.attention
+ .ownReplies(_thread)
+ .any((reply) => reply.outgoing?.error == error)
+ ? null
+ : error;
+ }
+
+ /// The reader's own reply: as sent, or the thread pane's Sending… and Not
+ /// sent with Retry and Delete. A failed one keeps its text here.
+ Widget _ownReply(SuperTabOwnReply reply) {
+ final outgoing = reply.outgoing;
+ return Padding(
+ padding: const EdgeInsets.only(
+ left: _indent,
+ top: grid.AppDesktop.controlGap,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _message(
+ {'kind': 'person', 'id': _c.accountId},
+ reply.shownText,
+ at: reply.at,
+ strong: !reply.sending,
+ // A failed one whole: this row is all that is left of its text.
+ lines: reply.sent || reply.sending ? 4 : kComposerMaxLength,
+ ),
+ Padding(
+ padding: const EdgeInsets.only(left: _indent),
+ child: reply.sent || outgoing == null
+ ? Semantics(
+ liveRegion: true,
+ child: Text('Sent', style: DesktopChrome.metadata()),
+ )
+ : SuperTabOutgoingReceipt(
+ inline: true,
+ message: outgoing,
+ // A refused reply goes again only when nothing else is on
+ // its way.
+ onRetry:
+ _c.saving ||
+ (outgoing.state == SuperTabOutgoingState.refused &&
+ _c.hasPendingAction)
+ ? null
+ : () => unawaited(_c.retryOutgoing(outgoing)),
+ onDelete: () => _c.discardOutgoing(outgoing),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
Future<void> _follow(bool follow) async {
final kept = await widget.attention.setFollow(_thread, follow);
if (!mounted || kept) return;
@@ -559,6 +620,27 @@ class _ThreadCardState extends State<_ThreadCard> {
lines: 4,
),
),
+ // Its own listener: a send moves on with no change to the list.
+ ListenableBuilder(
+ listenable: _c,
+ builder: (context, _) {
+ // Sent ones only while the card is new; one on its way or
+ // failed always.
+ final own = [
+ for (final reply in a.ownReplies(_thread))
+ if (fresh || !reply.sent) reply,
+ ];
+ return own.isEmpty
+ ? const SizedBox.shrink()
+ : Column(
+ key: ValueKey(
+ 'super-thread-own-reply-${_thread.key}',
+ ),
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [for (final r in own) _ownReply(r)],
+ );
+ },
+ ),
if (canReply && buddyThread)
Padding(
padding: const EdgeInsets.only(
@@ -620,10 +702,7 @@ class _ThreadCardState extends State<_ThreadCard> {
enabled: _c.canWrite,
writable: _writable,
busy: _busy,
- error: _c.threadComposerError(
- _thread.conversationId,
- _thread.rootId,
- ),
+ error: _boxError(),
onEdited: _edited,
onSend: () => unawaited(_send()),
surfaceKey: ValueKey(
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index dde2eb838..f13b9e336 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -65,6 +65,7 @@ import 'project_sidebar.dart';
import 'buddy_sessions.dart';
import 'swarm_switcher.dart' show fallBackToPersonal;
import 'project_options.dart';
+import 'switch_pm.dart';
import 'project_status_card.dart';
import 'pane_layout.dart';
import '../widgets/dial_list_scroll.dart';
@@ -1392,6 +1393,11 @@ class _SuperTabViewState extends State<SuperTabView>
}
return;
}
+ if (action == 'switch-pm') {
+ final project = c.snapshot?.projectFor(group.id);
+ if (project != null) await showSwitchPm(context, c, project.id);
+ return;
+ }
if (c.snapshot?.isProjectLead(group.id) == true && action != 'archived') {
final project = c.snapshot!.projectFor(group.id);
if (project != null) await showProjectAction(context, c, project, action);
@@ -2449,6 +2455,12 @@ class _SuperTabViewState extends State<SuperTabView>
// them sends no coordinatorName.
if (project?.hasInstructions == true)
item('Instructions', () => _groupAction('instructions', group)),
+ // While the PM has a switch under way, there is nothing to ask for.
+ if (editable &&
+ project != null &&
+ c.snapshot?.maySwitchLead(project.id, c.accountId) == true &&
+ c.snapshot?.leadOf(project.id)?.switchRequest == null)
+ item('Switch PM…', () => _groupAction('switch-pm', group)),
if (editable && project?.ownerId == c.accountId)
item('Delete Project', () => _groupAction('delete', group)),
] else if (_isBuddyChat(group)) ...[
@@ -2699,6 +2711,7 @@ class _SuperTabViewState extends State<SuperTabView>
'${inThread ? 'super-thread-message' : 'super-message'}-${message.id}',
),
message: message,
+ controller: c,
);
}
if (SuperTabShipRow.shows(message)) {
diff --git a/desktop/lib/usage/usage_account_key.dart b/desktop/lib/usage/usage_account_key.dart
index e55b9271f..bca88eadb 100644
--- a/desktop/lib/usage/usage_account_key.dart
+++ b/desktop/lib/usage/usage_account_key.dart
@@ -19,10 +19,18 @@ import 'usage_window.dart';
/// different account, so the strip prints one subscription twice. Both suites
/// pin the same vector (`test/usage_account_key_test.dart` here,
/// `accountUsage.spec.ts` there) for exactly that reason.
-String usageAccountKey(UsageProvider provider, String accountId) {
- final digest = const DartSha256().hashSync(
- utf8.encode('${provider.name}:$accountId'),
- );
+String usageAccountKey(UsageProvider provider, String accountId) =>
+ _sha16('${provider.name}:$accountId');
+
+/// A Swarm profile (an engine account of a machine), as the CLI, the backend and
+/// this app all name it: the first 16 hex characters of
+/// sha256(`<machineId>:<engine>:<realpath>`), or `...:default` for the engine's
+/// default account. Same contract as the CLI's `profileId`.
+String swarmProfileId(String machineId, String engine, String pathOrDefault) =>
+ _sha16('$machineId:$engine:$pathOrDefault');
+
+String _sha16(String text) {
+ final digest = const DartSha256().hashSync(utf8.encode(text));
final hex = StringBuffer();
for (final byte in digest.bytes) {
hex.write(byte.toRadixString(16).padLeft(2, '0'));
diff --git a/desktop/test/agent_change_test.dart b/desktop/test/agent_change_test.dart
index c844dc67e..9d6feb73f 100644
--- a/desktop/test/agent_change_test.dart
+++ b/desktop/test/agent_change_test.dart
@@ -6,17 +6,21 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/api/api_client.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
+import 'package:harness/core/home_dir.dart';
import 'package:harness/e2ee/envelope.dart';
import 'package:harness/state/agent_handoff_file.dart';
import 'package:harness/state/agent_switch_handoff.dart';
-import 'package:harness/ws/ws_conn.dart' show WsRequestFailure, WsRequestTimeout;
+import 'package:harness/ws/ws_conn.dart'
+ show WsRequestFailure, WsRequestTimeout;
import 'package:harness/state/desk_sync.dart';
import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/models.dart';
import 'package:harness/devices/devices_harness_controller.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/usage/usage_account_key.dart';
import 'package:harness/widgets/engine_identity.dart';
import 'support/harness_monitor.dart';
@@ -28,6 +32,7 @@ class SwitchConnection extends MonitorConnection {
late AppNotifier app;
final events = <String>[];
String? closeError;
+
/// The machine's whole refusal, as a daemon sends it (a Swarm Buddy's, say).
Map<String, dynamic>? closeRefusal;
Completer<void>? holdClose;
@@ -59,7 +64,9 @@ class SwitchConnection extends MonitorConnection {
if (type == 'agent_handoff_complete') {
completedHandoffs.add(Map.of(payload));
if (completionThrows case final error?) throw error;
- return completionError == null ? {'ok': true} : {'error': completionError};
+ return completionError == null
+ ? {'ok': true}
+ : {'error': completionError};
}
if (type == 'agent_handoff_prepare') {
handoffCalls.add(Map.of(payload));
@@ -121,6 +128,123 @@ class SwitchConnection extends MonitorConnection {
}
}
+/// A machine with two Claude accounts and two Codex ones, as the daemon would list them.
+class ProfileConnection extends SwitchConnection {
+ final links = <String>[];
+ final offers = <Map<String, dynamic>>[];
+ Map<String, dynamic>? offerReply;
+ final requests = <String>[];
+ final usageReads = <Map<String, dynamic>>[];
+ var plainUsage = false;
+ Map<String, dynamic> linkReply = {'error': 'NOT_FOUND'};
+ List<Map<String, dynamic>>? codexRows;
+ var claudeRows = <Map<String, dynamic>>[
+ {
+ 'id': '71dc90339553114c',
+ 'path': '/home/me',
+ 'label': 'Default',
+ 'reportLabel': 'Default',
+ 'default': true,
+ },
+ {
+ 'id': '5629f1d572da7cc4',
+ 'path': '/home/me/.claude-work',
+ 'label': 'Work',
+ 'reportLabel': 'Work',
+ 'default': false,
+ },
+ ];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ requests.add(type);
+ switch (type) {
+ case 'swarm_account_offer':
+ offers.add(Map.of(payload));
+ return offerReply ?? {'offered': payload['offered']};
+ case 'claude_profiles_list':
+ return {'profiles': claudeRows};
+ case 'claude_profile_link':
+ links.add(payload['path'] as String);
+ return linkReply;
+ case 'codex_profile_link':
+ links.add(payload['path'] as String);
+ return linkReply;
+ case 'codex_profiles_list':
+ if (codexRows != null) return {'profiles': codexRows};
+ return {
+ 'profiles': [
+ {'path': '${homeDir()}/.codex', 'label': 'Default'},
+ {'path': '/home/me/.codex-a', 'label': 'A'},
+ {'path': '/home/me/.codex-b', 'label': 'B'},
+ ],
+ };
+ case 'usage_read':
+ usageReads.add(Map.of(payload));
+ if (plainUsage && payload['profile'] == null) {
+ return {
+ 'providers': [
+ for (final e in ['claude', 'codex'])
+ {
+ 'provider': e,
+ 'outcome': 'answered',
+ 'httpStatus': 200,
+ 'body': e == 'claude'
+ ? {
+ 'five_hour': {
+ 'utilization': 88,
+ 'resets_at': '2099-01-01T00:00:00Z',
+ },
+ }
+ : {
+ 'rate_limit': {
+ 'primary_window': {
+ 'used_percent': 40,
+ 'limit_window_seconds': 18000,
+ 'reset_after_seconds': 100,
+ },
+ },
+ },
+ },
+ ],
+ };
+ }
+ final id = (payload['profile'] as Map)['id'];
+ if (id == '77103ab28be2ebd0') throw StateError('no reading');
+ return {
+ 'providers': [
+ {
+ 'provider': (payload['profile'] as Map)['engine'],
+ 'outcome': 'answered',
+ 'httpStatus': 200,
+ 'body': (payload['profile'] as Map)['engine'] == 'claude'
+ ? {
+ 'five_hour': {
+ 'utilization': 88,
+ 'resets_at': '2099-01-01T00:00:00Z',
+ },
+ }
+ : {
+ 'rate_limit': {
+ 'primary_window': {
+ 'used_percent': 40,
+ 'limit_window_seconds': 18000,
+ 'reset_after_seconds': 100,
+ },
+ },
+ },
+ },
+ ],
+ };
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
+
/// A daemon's good answer: the file it wrote for this exact change, in the harness's own folder.
Map<String, dynamic> handoffOk(Map<String, dynamic> p) => {
'agentId': p['agentId'],
@@ -136,6 +260,8 @@ AppNotifier fixture(
bool companion = false,
String? harnessId,
String sourceEngine = 'codex',
+ String? claudeHome,
+ String? codexHome,
}) {
final app = createApp(connectionForTest: (_) => connection, connected: true);
connection.app = app;
@@ -148,6 +274,8 @@ AppNotifier fixture(
closeSupported: true,
terminalAvailable: true,
permissionMode: 'ask',
+ claudeHome: claudeHome,
+ codexHome: codexHome,
project: const AgentProject(name: 'work', cwd: '/projects/work'),
dsh:
harnessId ??
@@ -196,53 +324,62 @@ class SwitchDeskApi extends ApiClient {
}
void main() {
- test('a wire UNSUPPORTED completion opens the replacement terminal', () async {
- final connection = SwitchConnection()
- ..completionThrows = const WsRequestFailure(
- responseType: 'agent_handoff_complete_result',
- code: 'UNSUPPORTED',
- );
- final app = fixture(connection);
- addTearDown(app.dispose);
- await app.addAgentToSwarm('m', 'a0');
- final pane = app.panes.single;
- expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
- expect(app.panes.single, same(pane));
- expect(pane.agentId, 'local-session');
- expect(connection.creations.single['engine'], 'claude');
- });
+ test(
+ 'a wire UNSUPPORTED completion opens the replacement terminal',
+ () async {
+ final connection = SwitchConnection()
+ ..completionThrows = const WsRequestFailure(
+ responseType: 'agent_handoff_complete_result',
+ code: 'UNSUPPORTED',
+ );
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final pane = app.panes.single;
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ expect(app.panes.single, same(pane));
+ expect(pane.agentId, 'local-session');
+ expect(connection.creations.single['engine'], 'claude');
+ },
+ );
- test('a wire UNSUPPORTED preparation uses the older history protocol', () async {
- final connection = SwitchConnection()
- ..handoffThrows = const WsRequestFailure(
- responseType: 'agent_handoff_prepare_result',
- code: 'UNSUPPORTED',
- );
- final app = fixture(connection);
- addTearDown(app.dispose);
- await app.addAgentToSwarm('m', 'a0');
- expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
- expect(connection.recentReads, 1);
- expect(connection.creations, hasLength(1));
- });
+ test(
+ 'a wire UNSUPPORTED preparation uses the older history protocol',
+ () async {
+ final connection = SwitchConnection()
+ ..handoffThrows = const WsRequestFailure(
+ responseType: 'agent_handoff_prepare_result',
+ code: 'UNSUPPORTED',
+ );
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
+ expect(connection.recentReads, 1);
+ expect(connection.creations, hasLength(1));
+ },
+ );
- test('a wire identity hold retains its restart guidance without stopping', () async {
- final connection = SwitchConnection()
- ..handoffThrows = const WsRequestFailure(
- responseType: 'agent_handoff_prepare_result',
- code: 'IDENTITY_UNAVAILABLE',
- payload: {'held': true, 'hold': 'PROGRAM_REPLACED'},
+ test(
+ 'a wire identity hold retains its restart guidance without stopping',
+ () async {
+ final connection = SwitchConnection()
+ ..handoffThrows = const WsRequestFailure(
+ responseType: 'agent_handoff_prepare_result',
+ code: 'IDENTITY_UNAVAILABLE',
+ payload: {'held': true, 'hold': 'PROGRAM_REPLACED'},
+ );
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(
+ await app.changeAgent('m', 'a0', 'claude'),
+ contains('Use Restart Harness'),
);
- final app = fixture(connection);
- addTearDown(app.dispose);
- await app.addAgentToSwarm('m', 'a0');
- expect(
- await app.changeAgent('m', 'a0', 'claude'),
- contains('Use Restart Harness'),
- );
- expect(connection.events, isEmpty);
- expect(connection.recentReads, 0);
- });
+ expect(connection.events, isEmpty);
+ expect(connection.recentReads, 0);
+ },
+ );
test('a lost completion report retries the same replacement without another launch', () async {
final connection = SwitchConnection()
@@ -253,14 +390,20 @@ void main() {
final app = fixture(connection);
addTearDown(app.dispose);
await app.addAgentToSwarm('m', 'a0');
- expect(await app.changeAgent('m', 'a0', 'claude'), contains('new agent started'));
+ expect(
+ await app.changeAgent('m', 'a0', 'claude'),
+ contains('new agent started'),
+ );
expect(app.panes.single.agentId, 'a0');
expect(connection.creations, hasLength(1));
connection.completionThrows = null;
expect(await app.changeAgent('m', 'a0', 'claude'), isNull);
expect(connection.creations, hasLength(1));
expect(connection.completedHandoffs, hasLength(2));
- expect(connection.completedHandoffs.first, connection.completedHandoffs.last);
+ expect(
+ connection.completedHandoffs.first,
+ connection.completedHandoffs.last,
+ );
expect(connection.events, ['save/stop', 'start']);
});
@@ -1178,28 +1321,30 @@ void main() {
expect(connection.creations.single['engine'], 'claude');
});
- test('a Buddy keeps its agent, and the refusal says how to use another', () async {
- // The daemon's refusal speaks of Stop Harness, which is no help to someone changing the agent.
- final connection = SwitchConnection()
- ..closeRefusal = {
- 'error': 'BUDDY_PROTECTED',
- 'detail':
- 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.',
- 'keptRunning': true,
- };
- final app = fixture(connection);
- addTearDown(app.dispose);
- await app.addAgentToSwarm('m', 'a0');
- final pane = app.panes.single;
- expect(
- await app.changeAgent('m', 'a0', 'opencode'),
- 'A Swarm Buddy keeps its agent. To use another agent, its person removes the Buddy and adds a new one.',
- );
- expect(connection.creations, isEmpty);
- expect(app.panes.single, same(pane));
- expect(pane.agentId, 'a0');
- expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
- });
+ test(
+ 'a Buddy keeps its agent, and the refusal says how to use another',
+ () async {
+ // The daemon's refusal speaks of Stop Harness, which is no help to someone changing the agent.
+ final connection = SwitchConnection()
+ ..closeRefusal = {
+ 'error': 'BUDDY_PROTECTED',
+ 'detail': 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.',
+ 'keptRunning': true,
+ };
+ final app = fixture(connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final pane = app.panes.single;
+ expect(
+ await app.changeAgent('m', 'a0', 'opencode'),
+ 'A Swarm Buddy keeps its agent. To use another agent, its person removes the Buddy and adds a new one.',
+ );
+ expect(connection.creations, isEmpty);
+ expect(app.panes.single, same(pane));
+ expect(pane.agentId, 'a0');
+ expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
+ },
+ );
// Dee, 11-01: a Swarm Product Manager's engine is switched from its pane,
// as any pane's. Its machine lets the stop through only for the switch
@@ -1307,6 +1452,484 @@ void main() {
},
);
+ group('accounts', () {
+ test('the picker lists one row per account with % left', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ final search = SwarmSearchController(app, []);
+ addTearDown(search.dispose);
+ search.setQuery('&');
+ search.setAgentSelection('m', 'a0');
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ final titles = [for (final r in search.rows) r.title];
+ expect(
+ titles,
+ containsAll([
+ 'Claude · Default',
+ 'Claude · Work',
+ 'Codex · A',
+ 'Codex · B',
+ ]),
+ );
+ expect(titles, isNot(contains('Claude Code')));
+ final work = search.rows.firstWhere((r) => r.title == 'Claude · Work');
+ expect(work.detail, '12% left');
+ expect(work.agentProfile, '/home/me/.claude-work');
+ expect(
+ search.rows.firstWhere((r) => r.title == 'Claude · Default').current,
+ isTrue,
+ );
+ expect(
+ search.rows.firstWhere((r) => r.title == 'Codex · A').detail,
+ '60% left',
+ );
+ // A reading that failed leaves the row without a percent.
+ expect(
+ search.rows.firstWhere((r) => r.title == 'Codex · B').detail,
+ isNot(contains('%')),
+ );
+ expect(search.rows.last.addsClaudeAccount, isTrue);
+ expect([
+ for (final r in connection.usageReads) (r['profile'] as Map)['id'],
+ ], contains('5629f1d572da7cc4'));
+ });
+
+ test('a same-engine change to another account closes and creates with claudeHome', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(
+ await app.changeAgent(
+ 'm',
+ 'a0',
+ 'claude',
+ profile: '/home/me/.claude-work',
+ ),
+ isNull,
+ );
+ expect(connection.events, ['save/stop', 'start']);
+ expect(
+ connection.creations.single,
+ containsPair('claudeHome', '/home/me/.claude-work'),
+ );
+ expect(connection.creations.single, isNot(contains('codexHome')));
+ });
+
+ test(
+ 'using an account that is not offered runs this pane on it and offers nothing',
+ () async {
+ final connection = ProfileConnection();
+ connection.claudeRows[1]['offered'] = false;
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final rows = await app.agentProfiles('m', 'claude');
+ expect(rows.map((r) => r.offered), [true, false]);
+ expect(
+ await app.changeAgent('m', 'a0', 'claude', profile: rows.last.key),
+ isNull,
+ );
+ expect(connection.links, isEmpty);
+ expect(connection.offers, isEmpty);
+ expect(
+ connection.creations.single,
+ containsPair('claudeHome', '/home/me/.claude-work'),
+ );
+ },
+ );
+
+ test('the owner offers and withdraws an account by asking this computer', () async {
+ final connection = ProfileConnection();
+ connection.claudeRows[1]['offered'] = false;
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ expect(await app.setAccountOffered('m', 'claude', '/home/me/.claude-work', true), isNull);
+ expect(await app.setAccountOffered('m', 'claude', '/home/me/.claude-work', false), isNull);
+ expect(connection.offers, [
+ {'engine': 'claude', 'path': '/home/me/.claude-work', 'offered': true},
+ {'engine': 'claude', 'path': '/home/me/.claude-work', 'offered': false},
+ ]);
+ connection.offerReply = {'error': 'NOT_FOUND'};
+ expect(await app.setAccountOffered('m', 'claude', '/gone', true), 'That account’s folder is gone.');
+ connection.offerReply = {'error': 'UNSUPPORTED'};
+ expect(await app.setAccountOffered('m', 'claude', '/x', true), 'Update Harness on this computer to offer accounts.');
+ });
+
+ test('accounts of another computer cannot be offered from here', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'codex');
+ addTearDown(app.dispose);
+ expect(await app.setAccountOffered('m', 'claude', '/home/me/.claude-work', true), 'Accounts can be offered on their own computer only.');
+ expect(connection.offers, isEmpty);
+ });
+
+ test('only an account a current CLI marks can be offered: never the default, never an old CLI row', () async {
+ final connection = ProfileConnection();
+ connection.claudeRows[1]['offered'] = false;
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ expect((await app.agentProfiles('m', 'claude')).map((r) => r.canOffer), [false, true]);
+ connection.claudeRows[1].remove('offered');
+ expect((await app.agentProfiles('m', 'claude')).map((r) => r.canOffer), [false, false]);
+ });
+
+ test(
+ 'an offered account, the default and an old CLI row link nothing',
+ () async {
+ final connection = ProfileConnection();
+ connection.claudeRows[1]['offered'] = true;
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final rows = await app.agentProfiles('m', 'claude');
+ expect(rows.every((r) => r.offered), isTrue);
+ await app.changeAgent('m', 'a0', 'claude', profile: rows.last.key);
+ expect(connection.links, isEmpty);
+ },
+ );
+
+ test('picking the current engine and account does nothing', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(
+ await app.changeAgent('m', 'a0', 'claude', profile: 'default'),
+ isNull,
+ );
+ expect(connection.events, isEmpty);
+ expect(connection.creations, isEmpty);
+ });
+
+ test('the default row (default: true) is keyed default, never by the home folder', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ // Whatever id the row carries, the flag decides.
+ connection.claudeRows[0]['id'] = 'ffffffffffffffff';
+ final rows = await app.agentProfiles('m', 'claude');
+ expect(rows.first.key, 'default');
+ expect(rows.first.path, '/home/me');
+ await app.changeAgent('m', 'a0', 'claude', profile: rows.first.key);
+ expect(connection.creations.single, isNot(contains('claudeHome')));
+ });
+
+ test('a Codex row marked default is keyed default', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ connection.codexRows = [
+ {
+ 'path': '/elsewhere/codex',
+ 'label': 'Default',
+ 'id': swarmProfileId('m', 'codex', 'default'),
+ 'default': true,
+ },
+ {'path': '/home/me/.codex-a', 'label': 'A'},
+ ];
+ final rows = await app.agentProfiles('m', 'codex');
+ expect(rows.first.key, 'default');
+ });
+
+ test('an old CLI: literal default id maps to the default row and reads the plain usage', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ connection.claudeRows = [
+ {'id': 'default', 'path': '/home/me', 'label': 'Default'},
+ {
+ 'id': '5629f1d572da7cc4',
+ 'path': '/home/me/.claude-work',
+ 'label': 'Work',
+ },
+ ];
+ connection.plainUsage = true;
+ final rows = await app.agentProfiles('m', 'claude');
+ expect(rows.first.key, 'default');
+ expect(rows.first.id, swarmProfileId('m', 'claude', 'default'));
+ // The plain read answers Claude first, then Codex: Claude's 88% used wins.
+ expect(rows.first.percentLeft, 12);
+ expect(connection.usageReads.any((r) => r.isEmpty), isTrue);
+ });
+
+ test('the default account passes no claudeHome', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(
+ await app.changeAgent('m', 'a0', 'claude', profile: 'default'),
+ isNull,
+ );
+ expect(connection.creations.single, isNot(contains('claudeHome')));
+ });
+
+ test('a Codex account passes codexHome', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ app.stateOf('m')!.engines.replace(const [
+ EngineAvailability(
+ engine: 'codex',
+ installed: true,
+ supportsCodexHome: true,
+ ),
+ ]);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(
+ await app.changeAgent('m', 'a0', 'codex', profile: '/home/me/.codex-b'),
+ isNull,
+ );
+ expect(
+ connection.creations.single,
+ containsPair('codexHome', '/home/me/.codex-b'),
+ );
+ });
+
+ Future<SwarmSearchController> pick(AppNotifier app) async {
+ final search = SwarmSearchController(app, []);
+ addTearDown(search.dispose);
+ search.setQuery('&');
+ search.setAgentSelection('m', 'a0');
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ return search;
+ }
+
+ test('a row not offered says so, and Swarm accounts… is listed only where an account can be offered', () async {
+ final connection = ProfileConnection();
+ connection.claudeRows[1]['offered'] = false;
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ final search = await pick(app);
+ final work = search.rows.firstWhere((r) => r.title == 'Claude · Work');
+ expect(work.detail, 'Not offered to the Swarm');
+ expect(search.rows.where((r) => r.managesSwarmAccounts).single.title, 'Swarm accounts…');
+ expect(search.rows.where((r) => r.addsClaudeAccount).single.detail, contains('Yours until you offer it'));
+ connection.claudeRows[1].remove('offered');
+ final old = await pick(app);
+ expect(old.rows.where((r) => r.managesSwarmAccounts), isEmpty);
+ });
+
+ test('Swarm accounts lists offerable rows of both engines, and a failed list throws rather than reading as none', () async {
+ final connection = ProfileConnection();
+ connection.claudeRows[1]['offered'] = false;
+ connection.codexRows = [
+ {'path': '${homeDir()}/.codex', 'label': 'Default', 'default': true, 'offered': true},
+ {'path': '/home/me/.codex-a', 'label': 'A', 'offered': true},
+ ];
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ final rows = await app.swarmAccounts('m');
+ expect(rows.map((r) => (r.engine, r.label, r.offered)), [('claude', 'Work', false), ('codex', 'A', true)]);
+ connection.claudeRows = [];
+ final other = fixture(ProfileConnection(), sourceEngine: 'codex');
+ addTearDown(other.dispose);
+ await expectLater(other.swarmAccounts('m'), throwsStateError);
+ });
+
+ test('a Codex pane on the default account has the default row current and no change', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ final search = await pick(app);
+ final row = search.rows.firstWhere((r) => r.title == 'Codex · Default');
+ expect(row.current, isTrue);
+ expect(row.agentProfile, 'default');
+ expect(
+ search.rows.firstWhere((r) => r.title == 'Codex · A').current,
+ isFalse,
+ );
+ await app.addAgentToSwarm('m', 'a0');
+ expect(
+ await app.changeAgent('m', 'a0', 'codex', profile: 'default'),
+ isNull,
+ );
+ expect(connection.events, isEmpty);
+ expect(connection.creations, isEmpty);
+ });
+
+ test('Codex and default accounts are read by their computed ids', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await pick(app);
+ final ids = [
+ for (final r in connection.usageReads) (r['profile'] as Map)['id'],
+ ];
+ expect(ids, contains('07f54db4cdffbb30')); // codex default
+ expect(ids, contains(swarmProfileId('m', 'codex', '/home/me/.codex-a')));
+ expect(ids, isNot(contains('/home/me/.codex-a')));
+ });
+
+ test(
+ 'a Claude agent on a folder marks the row whose id is that folder\'s',
+ () async {
+ final connection = ProfileConnection();
+ final app = fixture(
+ connection,
+ sourceEngine: 'claude',
+ claudeHome: '/home/me/.claude-work',
+ );
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ final search = await pick(app);
+ expect(
+ search.rows.firstWhere((r) => r.title == 'Claude · Work').current,
+ isTrue,
+ );
+ expect(
+ search.rows.firstWhere((r) => r.title == 'Claude · Default').current,
+ isFalse,
+ );
+ },
+ );
+
+ test('usage is cached for five minutes and read for at most 8 accounts per engine', () async {
+ final connection = ProfileConnection();
+ for (var i = 0; i < 10; i++) {
+ connection.claudeRows.add({
+ 'id': swarmProfileId('m', 'claude', '/home/me/.c$i'),
+ 'path': '/home/me/.c$i',
+ 'label': 'C$i',
+ });
+ }
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ await pick(app);
+ int claudeReads() => connection.usageReads
+ .where((r) => (r['profile'] as Map)['engine'] == 'claude')
+ .length;
+ expect(claudeReads(), 8);
+ // Opening again reads only the accounts it could not reach the first time.
+ await pick(app);
+ final ids = [
+ for (final r in connection.usageReads) (r['profile'] as Map)['id'],
+ ];
+ expect(ids.toSet().length, ids.length);
+ expect(claudeReads(), 12);
+ });
+
+ test('Add Claude account… skips folders that are listed or used by an agent, and a double click adds one', () async {
+ final connection = ProfileConnection();
+ connection.claudeRows.add({
+ 'id': '39f7292d285c38ed',
+ 'path': '/home/me/.harness/claude-profiles/1',
+ 'label': 'One',
+ });
+ final app = fixture(
+ connection,
+ sourceEngine: 'codex',
+ claudeHome: '/home/me/.harness/claude-profiles/2',
+ );
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ final results = await Future.wait([
+ app.addClaudeAccount('m', 'a0'),
+ app.addClaudeAccount('m', 'a0'),
+ ]);
+ expect(results.where((r) => r == null), hasLength(1));
+ expect(connection.creations, hasLength(1));
+ expect(
+ connection.creations.single,
+ containsPair('claudeHome', '/home/me/.harness/claude-profiles/3'),
+ );
+ // Settled: the next one may go.
+ expect(await app.addClaudeAccount('m', 'a0'), isNull);
+ });
+
+ test(
+ 'Add Claude account… links the next free folder and opens Claude in it',
+ () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'codex');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ String? notice;
+ app.agentChangeNotice = (m) => notice = m;
+ expect(await app.addClaudeAccount('m', 'a0'), isNull);
+ // The folder does not exist yet, so there is nothing to link.
+ expect(connection.links, isEmpty);
+ expect(connection.creations.single, containsPair('engine', 'claude'));
+ expect(
+ connection.creations.single,
+ containsPair('claudeHome', '/home/me/.harness/claude-profiles/1'),
+ );
+ expect(notice, 'Run /login, then pick it again');
+ },
+ );
+ test(
+ 'a remote machine is never asked for accounts and offers none',
+ () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ addTearDown(app.dispose);
+ final search = SwarmSearchController(app, []);
+ addTearDown(search.dispose);
+ search.setQuery('&');
+ search.setAgentSelection('m', 'a0');
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ expect(
+ connection.requests.where((t) => t.endsWith('profiles_list')),
+ isEmpty,
+ );
+ expect(
+ search.rows.any((r) => r.agentProfile != null || r.addsClaudeAccount),
+ isFalse,
+ );
+ expect(await app.addClaudeAccount('m', 'a0'), isNotNull);
+ },
+ );
+
+ test('a Swarm Buddy keeps its engine: rows disabled, no change', () async {
+ final connection = ProfileConnection();
+ final app = fixture(connection, sourceEngine: 'claude');
+ app.stateOf('m')!.localOnly = true;
+ addTearDown(app.dispose);
+ app.buddyAgentsForTest.add(('m', 'a0'));
+ final search = SwarmSearchController(app, []);
+ addTearDown(search.dispose);
+ search.setQuery('&');
+ search.setAgentSelection('m', 'a0');
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ expect(
+ search.rows.every(
+ (r) => r.detail == 'A Buddy keeps its engine for now',
+ ),
+ isTrue,
+ );
+ expect(search.canSubmit(search.rows.first), isFalse);
+ expect(
+ connection.requests.where((t) => t.endsWith('profiles_list')),
+ isEmpty,
+ );
+ expect(
+ await app.changeAgent('m', 'a0', 'codex'),
+ 'A Buddy keeps its engine for now',
+ );
+ expect(connection.creations, isEmpty);
+ });
+ });
+
test('& searches all agents and only submits supported choices for its exact source', () {
final connection = SwitchConnection();
final app = fixture(connection, viewer: true);
diff --git a/desktop/test/desktop_compact_launch_test.dart b/desktop/test/desktop_compact_launch_test.dart
index dffdda215..bd16dd517 100644
--- a/desktop/test/desktop_compact_launch_test.dart
+++ b/desktop/test/desktop_compact_launch_test.dart
@@ -101,6 +101,7 @@ class _CompactApp extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/desktop_composer_layout_test.dart b/desktop/test/desktop_composer_layout_test.dart
index 920228c16..a6fd17163 100644
--- a/desktop/test/desktop_composer_layout_test.dart
+++ b/desktop/test/desktop_composer_layout_test.dart
@@ -129,6 +129,7 @@ class _ReviewApp extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/desktop_new_harness_edge_test.dart b/desktop/test/desktop_new_harness_edge_test.dart
index 83b53436a..9552884a3 100644
--- a/desktop/test/desktop_new_harness_edge_test.dart
+++ b/desktop/test/desktop_new_harness_edge_test.dart
@@ -134,6 +134,7 @@ class _App extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/first_arrival_test.dart b/desktop/test/first_arrival_test.dart
index 59aee2531..68af5bd3d 100644
--- a/desktop/test/first_arrival_test.dart
+++ b/desktop/test/first_arrival_test.dart
@@ -105,6 +105,7 @@ class _OpeningApp extends _PreparingApp {
bool bypassPermission = true,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
GridModel? model,
String? prompt,
@@ -140,6 +141,7 @@ class _AnsweredApp extends _OpeningApp {
bool bypassPermission = true,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
GridModel? model,
String? prompt,
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 3829849c7..feccda0e8 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -83,6 +83,7 @@ class _FirstUseApp extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_agent_choices_layout_test.dart b/desktop/test/new_agent_choices_layout_test.dart
index 93c6b9f68..3b4dc6da1 100644
--- a/desktop/test/new_agent_choices_layout_test.dart
+++ b/desktop/test/new_agent_choices_layout_test.dart
@@ -66,6 +66,7 @@ class _ChoicesApp extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? swarmId,
PaneSplitRequest? split,
String? dsh,
diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dart
index de8e4632f..418ba08e3 100644
--- a/desktop/test/new_agent_codex_profile_test.dart
+++ b/desktop/test/new_agent_codex_profile_test.dart
@@ -132,6 +132,7 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_agent_dsh_test.dart b/desktop/test/new_agent_dsh_test.dart
index f266a090a..80dfb6039 100644
--- a/desktop/test/new_agent_dsh_test.dart
+++ b/desktop/test/new_agent_dsh_test.dart
@@ -112,6 +112,7 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_agent_engine_check_test.dart b/desktop/test/new_agent_engine_check_test.dart
index a170c0562..cbb4aa503 100644
--- a/desktop/test/new_agent_engine_check_test.dart
+++ b/desktop/test/new_agent_engine_check_test.dart
@@ -316,6 +316,7 @@ class _RetryNotifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_agent_permission_mode_test.dart b/desktop/test/new_agent_permission_mode_test.dart
index c16cfb5ba..616eb2112 100644
--- a/desktop/test/new_agent_permission_mode_test.dart
+++ b/desktop/test/new_agent_permission_mode_test.dart
@@ -58,6 +58,7 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_agent_project_picker_test.dart b/desktop/test/new_agent_project_picker_test.dart
index 033d71a91..01c37bfbb 100644
--- a/desktop/test/new_agent_project_picker_test.dart
+++ b/desktop/test/new_agent_project_picker_test.dart
@@ -69,6 +69,7 @@ class _App extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? swarmId,
PaneSplitRequest? split,
String? dsh,
diff --git a/desktop/test/new_agent_rows_and_task_test.dart b/desktop/test/new_agent_rows_and_task_test.dart
index 882e54c62..c115f8090 100644
--- a/desktop/test/new_agent_rows_and_task_test.dart
+++ b/desktop/test/new_agent_rows_and_task_test.dart
@@ -124,6 +124,7 @@ class _App extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_agent_terminal_test.dart b/desktop/test/new_agent_terminal_test.dart
index 86e450fcd..e0c6aa38f 100644
--- a/desktop/test/new_agent_terminal_test.dart
+++ b/desktop/test/new_agent_terminal_test.dart
@@ -66,6 +66,7 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_harness_attachments_test.dart b/desktop/test/new_harness_attachments_test.dart
index 3c2b1cd49..10514e3ad 100644
--- a/desktop/test/new_harness_attachments_test.dart
+++ b/desktop/test/new_harness_attachments_test.dart
@@ -105,6 +105,7 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_harness_guest_test.dart b/desktop/test/new_harness_guest_test.dart
index 5e76b98eb..6035a4277 100644
--- a/desktop/test/new_harness_guest_test.dart
+++ b/desktop/test/new_harness_guest_test.dart
@@ -85,6 +85,7 @@ class _GuestApp extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/new_harness_install_pane_test.dart b/desktop/test/new_harness_install_pane_test.dart
index 29001dfe2..5adedbb4c 100644
--- a/desktop/test/new_harness_install_pane_test.dart
+++ b/desktop/test/new_harness_install_pane_test.dart
@@ -144,6 +144,7 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dart
index c44ab65e1..6682bcb1c 100644
--- a/desktop/test/remote_folder_picker_test.dart
+++ b/desktop/test/remote_folder_picker_test.dart
@@ -51,6 +51,7 @@ class _Folders extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/store_showcase_test.dart b/desktop/test/store_showcase_test.dart
index fd45cd712..9a634bcdb 100644
--- a/desktop/test/store_showcase_test.dart
+++ b/desktop/test/store_showcase_test.dart
@@ -86,6 +86,7 @@ class _Notifier extends AppNotifier {
bool bypassPermission = false,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/desktop/test/super_tab_attention_test.dart b/desktop/test/super_tab_attention_test.dart
index c1b93f7d1..cb988534c 100644
--- a/desktop/test/super_tab_attention_test.dart
+++ b/desktop/test/super_tab_attention_test.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -9,6 +10,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/attention.dart';
import 'package:harness/super_tabs/buddy_rows.dart';
import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
import 'package:harness/super_tabs/threads_view.dart';
import 'package:harness/widgets/desktop_chrome.dart';
@@ -883,6 +885,233 @@ void main() {
});
});
+ // Scholes, 2026-11-02: a reply sent from a card did not show until an agent
+ // answered, so it looked unsent.
+ group('a reply sent from the Threads view', () {
+ const field = ValueKey('super-thread-reply-lead/message-1');
+ const send = ValueKey('super-thread-send-lead/message-1');
+ const own = ValueKey('super-thread-own-reply-lead/message-1');
+
+ Future<(ConversationServer, SuperTabController, SuperTabAttention)> shown(
+ WidgetTester tester,
+ ) async {
+ final server = projectServer();
+ fromLead(server, 'Root');
+ fromLead(server, 'Fresh reply');
+ server.messages.last['thread'] = 'message-1';
+ conversation(server, 'lead')['lastMainSequence'] = 1;
+ server.followedThreads = {
+ 'unread': [unreadThread('message-1', 2, text: 'Root')],
+ 'read': const [],
+ 'more': false,
+ };
+ final c = await openHere(server);
+ final attention = SuperTabAttention.of(c);
+ await attention.load();
+ await tester.binding.setSurfaceSize(const Size(700, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabThreadsView(attention: attention, onOpen: (_, _) {}),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return (server, c, attention);
+ }
+
+ Finder inOwn(Finder what) =>
+ find.descendant(of: find.byKey(own), matching: what);
+
+ testWidgets('shows at once as sending, then sent, and stays', (
+ tester,
+ ) async {
+ final (server, c, attention) = await shown(tester);
+ final hold = server.holdCommands = Completer<void>();
+ await tester.enterText(find.byKey(field), 'On it');
+ await tester.pump();
+ await tester.tap(find.byKey(send));
+ await tester.pump();
+ await tester.pump();
+ // Before any answer, and before the server has answered at all.
+ expect(inOwn(find.text('On it')), findsOneWidget);
+ expect(inOwn(find.text('Sending…')), findsOneWidget);
+ expect(inOwn(find.text('Sent')), findsNothing);
+ expect(tester.widget<TextField>(find.byKey(field)).controller!.text, '');
+ hold.complete();
+ server.holdCommands = null;
+ await tester.pumpAndSettle();
+ expect(inOwn(find.text('On it')), findsOneWidget);
+ expect(inOwn(find.text('Sent')), findsOneWidget);
+ expect(inOwn(find.text('Sending…')), findsNothing);
+ // An agent answers, and the transcript holds the reply: it stays, once.
+ await c.loadMessages('lead');
+ fromLead(server, 'Answer');
+ server.messages.last['thread'] = 'message-1';
+ await c.refresh();
+ await attention.load();
+ await tester.pumpAndSettle();
+ expect(find.text('On it'), findsOneWidget);
+ expect(inOwn(find.text('Sent')), findsOneWidget);
+ await close(tester, c);
+ });
+
+ testWidgets('failed: its text stays, with Retry, and Retry sends it', (
+ tester,
+ ) async {
+ final (server, c, _) = await shown(tester);
+ server.refuse = {'code': 'SWARM_BUSY', 'message': 'Busy, try again.'};
+ await tester.enterText(find.byKey(field), 'On it');
+ await tester.pump();
+ await tester.tap(find.byKey(send));
+ await tester.pumpAndSettle();
+ expect(inOwn(find.text('On it')), findsOneWidget);
+ expect(inOwn(find.text('Not sent')), findsOneWidget);
+ expect(inOwn(find.text('Sent')), findsNothing);
+ // Why it failed is said once, on the reply, not again in the box.
+ expect(find.text('Busy, try again.'), findsOneWidget);
+ server.refuse = null;
+ final posts = server.posts.length;
+ await tester.tap(inOwn(find.text('Retry')));
+ await tester.pumpAndSettle();
+ expect(server.posts.length, posts + 1);
+ expect((server.posts.last['command'] as Map)['text'], 'On it');
+ expect(inOwn(find.text('Sent')), findsOneWidget);
+ expect(inOwn(find.text('Not sent')), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('failed: Delete takes it away, and it is never called sent', (
+ tester,
+ ) async {
+ final (server, c, _) = await shown(tester);
+ server.refuse = {'code': 'SWARM_BUSY', 'message': 'Busy, try again.'};
+ await tester.enterText(find.byKey(field), 'On it');
+ await tester.pump();
+ await tester.tap(find.byKey(send));
+ await tester.pumpAndSettle();
+ await tester.tap(inOwn(find.text('Delete')));
+ await tester.pumpAndSettle();
+ expect(find.text('On it'), findsNothing);
+ expect(find.text('Sent'), findsNothing);
+ await close(tester, c);
+ });
+
+ // Review of #2555: a sent reply stays in the controller's list until its
+ // chat's transcript loads, and must not come back as new on a later visit.
+ testWidgets('a reply from an earlier visit does not come back as new', (
+ tester,
+ ) async {
+ // A chat that is not open: its transcript never loads here.
+ final server = projectServer();
+ fromLead(server, 'Root', conversationId: 'offline');
+ fromLead(server, 'Fresh reply', conversationId: 'offline');
+ server.messages.last['thread'] = 'message-1';
+ conversation(server, 'offline')['lastMainSequence'] = 1;
+ Map<String, dynamic> listed(int lastReply) => {
+ 'unread': [
+ unreadThread(
+ 'message-1',
+ lastReply,
+ conversationId: 'offline',
+ text: 'Root',
+ ),
+ ],
+ 'read': const [],
+ 'more': false,
+ };
+ server.followedThreads = listed(2);
+ final c = await openHere(server);
+ final attention = SuperTabAttention.of(c);
+ await attention.load();
+ await tester.binding.setSurfaceSize(const Size(700, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabThreadsView(attention: attention, onOpen: (_, _) {}),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ const reply = ValueKey('super-thread-reply-offline/message-1');
+ const ownHere = ValueKey('super-thread-own-reply-offline/message-1');
+ await tester.enterText(find.byKey(reply), 'On it');
+ await tester.pump();
+ await tester.tap(
+ find.byKey(const ValueKey('super-thread-send-offline/message-1')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byKey(ownHere), findsOneWidget);
+ // Still in the list: this chat's transcript has not loaded.
+ expect(c.outgoing('offline').where((m) => m.text == 'On it'), isNotEmpty);
+ attention.closed();
+ server.followedThreads = listed(9);
+ attention.opened();
+ await attention.load();
+ await tester.pumpAndSettle();
+ expect(attention.isNew(attention.shown.single), isTrue);
+ expect(find.byKey(ownHere), findsNothing);
+ await close(tester, c);
+ });
+
+ test('a reply with only files says so', () {
+ expect(const SuperTabOwnReply('', null).shownText, 'Files');
+ expect(const SuperTabOwnReply('On it', null).shownText, 'On it');
+ });
+
+ testWidgets('failed: its whole text shows, not cut short', (tester) async {
+ final (server, c, _) = await shown(tester);
+ server.refuse = {'code': 'SWARM_BUSY', 'message': 'Busy, try again.'};
+ final long = List.generate(9, (i) => 'line $i').join('\n');
+ await tester.enterText(find.byKey(field), long);
+ await tester.pump();
+ await tester.tap(find.byKey(send));
+ await tester.pumpAndSettle();
+ final row = tester.renderObject<RenderParagraph>(inOwn(find.text(long)));
+ expect(row.didExceedMaxLines, isFalse);
+ await close(tester, c);
+ });
+
+ testWidgets('a reply the card already read back is not shown twice', (
+ tester,
+ ) async {
+ final (server, c, attention) = await shown(tester);
+ await tester.enterText(find.byKey(field), 'On it');
+ await tester.pump();
+ await tester.tap(find.byKey(send));
+ await tester.pumpAndSettle();
+ final thread = attention.shown.single;
+ final operationId = server.posts.last['operationId'] as String;
+ final id = superTabMessageId(
+ tabId: c.tabId,
+ accountId: c.accountId,
+ operationId: operationId,
+ );
+ attention.newReplies[thread.key] = [
+ ...attention.newReplies[thread.key]!,
+ SuperTabMessage.fromJson({
+ 'id': id,
+ 'conversationId': 'lead',
+ 'sequence': 90,
+ 'author': {'kind': 'person', 'id': c.accountId, 'name': 'Me'},
+ 'text': 'On it',
+ 'thread': 'message-1',
+ 'replyTo': 'message-1',
+ 'createdAt': '2026-11-02T00:00:00Z',
+ }),
+ ];
+ await attention.load();
+ await tester.pumpAndSettle();
+ expect(find.text('On it'), findsOneWidget);
+ expect(find.byKey(own), findsNothing);
+ await close(tester, c);
+ });
+ });
+
testWidgets('the Threads view shows new replies under their root with a '
'reply box, the rest after, and Unfollow', (tester) async {
final server = projectServer();
diff --git a/desktop/test/super_tab_swarm_accounts_test.dart b/desktop/test/super_tab_swarm_accounts_test.dart
new file mode 100644
index 000000000..fffeaac4a
--- /dev/null
+++ b/desktop/test/super_tab_swarm_accounts_test.dart
@@ -0,0 +1,177 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/swarm_accounts.dart';
+
+const work = SwarmAccount(
+ engine: 'claude',
+ path: '/h/.claude-work',
+ label: 'Work',
+ offered: false,
+);
+const two = SwarmAccount(
+ engine: 'codex',
+ path: '/h/.codex-two',
+ label: 'Two',
+ offered: true,
+);
+
+void main() {
+ Future<void> open(
+ WidgetTester tester, {
+ required Future<List<SwarmAccount>> Function() load,
+ Future<String?> Function(SwarmAccount, bool)? set,
+ }) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SwarmAccountsDialog(
+ load: load,
+ setOffered: set ?? (_, _) async => null,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ }
+
+ testWidgets(
+ 'says who can spend an offered account before anything is offered',
+ (tester) async {
+ await open(tester, load: () async => [work, two]);
+ expect(
+ find.textContaining(
+ 'Other people’s PMs on this Mac can run on an offered account and spend its usage.',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining('keeps running until someone moves it'),
+ findsOneWidget,
+ );
+ expect(find.text('Claude · Work'), findsOneWidget);
+ expect(find.text('Not offered'), findsOneWidget);
+ expect(find.text('Codex · Two'), findsOneWidget);
+ expect(find.widgetWithText(TextButton, 'Offer'), findsOneWidget);
+ expect(find.widgetWithText(TextButton, 'Withdraw'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'offers and withdraws only what was pressed, and reads the list back',
+ (tester) async {
+ final asked = <(String, bool)>[];
+ var rows = [work, two];
+ await open(
+ tester,
+ load: () async => rows,
+ set: (a, on) async {
+ asked.add((a.label, on));
+ rows = [
+ for (final r in rows)
+ r.label == a.label
+ ? SwarmAccount(
+ engine: r.engine,
+ path: r.path,
+ label: r.label,
+ offered: on,
+ )
+ : r,
+ ];
+ return null;
+ },
+ );
+ expect(asked, isEmpty);
+ await tester.tap(find.widgetWithText(TextButton, 'Offer'));
+ await tester.pump();
+ expect(asked, [('Work', true)]);
+ expect(find.widgetWithText(TextButton, 'Offer'), findsNothing);
+ await tester.tap(find.widgetWithText(TextButton, 'Withdraw').first);
+ await tester.pump();
+ expect(asked, [('Work', true), ('Work', false)]);
+ },
+ );
+
+ testWidgets('a refusal is shown and changes nothing', (tester) async {
+ await open(
+ tester,
+ load: () async => [work],
+ set: (_, _) async => 'That account’s folder is gone.',
+ );
+ await tester.tap(find.widgetWithText(TextButton, 'Offer'));
+ await tester.pump();
+ expect(find.text('That account’s folder is gone.'), findsOneWidget);
+ expect(find.text('Not offered'), findsOneWidget);
+ });
+
+ testWidgets('a failed read is no stuck Loading, and Try again recovers', (
+ tester,
+ ) async {
+ var fail = true;
+ await open(
+ tester,
+ load: () async {
+ if (fail) throw StateError('unreachable');
+ return [work];
+ },
+ );
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(
+ find.text('Couldn’t read this computer’s accounts.'),
+ findsOneWidget,
+ );
+ fail = false;
+ await tester.tap(find.text('Try again'));
+ await tester.pump();
+ expect(find.text('Claude · Work'), findsOneWidget);
+ expect(find.text('Couldn’t read this computer’s accounts.'), findsNothing);
+ });
+
+ testWidgets('says so when no other account is on this computer', (
+ tester,
+ ) async {
+ await open(tester, load: () async => const []);
+ expect(
+ find.text('No other accounts on this computer yet.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a second press while one is on its way sends nothing', (
+ tester,
+ ) async {
+ final gate = Completer<String?>();
+ var calls = 0;
+ await open(
+ tester,
+ load: () async => [work],
+ set: (_, _) {
+ calls++;
+ return gate.future;
+ },
+ );
+ await tester.tap(find.widgetWithText(TextButton, 'Offer'));
+ await tester.pump();
+ await tester.tap(
+ find.widgetWithText(TextButton, 'Offer'),
+ warnIfMissed: false,
+ );
+ await tester.pump();
+ expect(calls, 1);
+ gate.complete(null);
+ await tester.pump();
+ });
+
+ testWidgets(
+ 'an answer that arrives after the dialog closed changes nothing',
+ (tester) async {
+ final gate = Completer<List<SwarmAccount>>();
+ await open(tester, load: () => gate.future);
+ await tester.pumpWidget(const MaterialApp(home: SizedBox()));
+ gate.complete([work]);
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ },
+ );
+}
diff --git a/desktop/test/super_tab_switch_pm_test.dart b/desktop/test/super_tab_switch_pm_test.dart
new file mode 100644
index 000000000..080b679c4
--- /dev/null
+++ b/desktop/test/super_tab_switch_pm_test.dart
@@ -0,0 +1,305 @@
+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/super_tabs/controller.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Switch PM (spec 2026-11-02-pm-switch-engine-account-design.md, section 8):
+/// who is offered it, what its dialog lists and what Confirm sends.
+void main() {
+ // sha256('m:claude:default') and sha256('m:codex:default'), first 16 hex.
+ const claudeDefault = '71dc90339553114c', codexDefault = '07f54db4cdffbb30';
+ ConversationServer swarm({Map<String, dynamic> pm = const {}}) {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'mac', 'email': '[email protected]', 'role': 'collaborator'},
+ {'id': 'member', 'email': '[email protected]', 'role': 'member'},
+ ];
+ server.state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'name': 'Team Mac',
+ 'contributorId': 'mac',
+ 'engines': ['claude', 'codex'],
+ 'observation': {
+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,
+ 'profiles': [
+ {
+ 'engine': 'claude',
+ 'id': claudeDefault,
+ 'label': 'Default',
+ 'leftPercent': 40,
+ 'resetsAt': null,
+ },
+ {
+ 'engine': 'claude',
+ 'id': 'aaaaaaaaaaaaaaaa',
+ 'label': 'Work',
+ 'leftPercent': 0,
+ 'resetsAt': '2099-01-02T15:00:00.000Z',
+ },
+ {
+ 'engine': 'codex',
+ 'id': codexDefault,
+ 'label': 'Default',
+ 'leftPercent': 90,
+ 'resetsAt': null,
+ },
+ {
+ 'engine': 'codex',
+ 'id': 'bbbbbbbbbbbbbbbb',
+ 'label': 'Side',
+ 'leftPercent': 70,
+ 'resetsAt': null,
+ },
+ ],
+ },
+ },
+ ];
+ server.state['agents'] = [
+ {
+ 'id': 'pm',
+ 'name': 'Lead',
+ 'displayName': 'Wren',
+ 'machineId': 'm',
+ 'harnessId': 'pm',
+ 'contributorId': 'mac',
+ 'machineOwnerId': 'mac',
+ 'configuration': {'engine': 'claude'},
+ ...pm,
+ },
+ ];
+ ((server.state['conversations'] as List)[0] as Map)['leadId'] = 'pm';
+ return server;
+ }
+
+ Future<SuperTabController> mount(
+ WidgetTester tester,
+ ConversationServer server,
+ String account,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(1400, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller(account: account);
+ await c.refresh();
+ addTearDown(c.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ onNewProject: () {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+ }
+
+ Future<void> openMenu(WidgetTester tester) async {
+ await tester.tap(find.byTooltip('Project options'));
+ await tester.pumpAndSettle();
+ }
+
+ final item = find.widgetWithText(MenuItemButton, 'Switch PM…');
+
+ Future<void> finish(WidgetTester tester) async {
+ await tester.pump(const Duration(milliseconds: 250));
+ await tester.pumpWidget(const SizedBox());
+ }
+
+ testWidgets(
+ 'the project owner and the PM machine\'s owner see Switch PM…; a member does not',
+ (tester) async {
+ for (final (account, shown) in [
+ ('owner', true),
+ ('mac', true),
+ ('member', false),
+ ]) {
+ await mount(tester, swarm(), account);
+ await openMenu(tester);
+ expect(item, shown ? findsOneWidget : findsNothing, reason: account);
+ await finish(tester);
+ }
+ },
+ );
+
+ testWidgets('the menu item is gone while the PM is switching', (
+ tester,
+ ) async {
+ final server = swarm(
+ pm: {
+ 'switchRequest': {
+ 'id': 'r',
+ 'engine': 'codex',
+ 'profileId': 'bbbbbbbbbbbbbbbb',
+ 'requestedBy': 'owner',
+ 'at': 1,
+ },
+ },
+ );
+ await mount(tester, server, 'owner');
+ await openMenu(tester);
+ expect(item, findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets(
+ 'the dialog lists the PM machine\'s profiles with % left, marks the current one and disables 0%',
+ (tester) async {
+ await mount(tester, swarm(), 'owner');
+ await openMenu(tester);
+ await tester.tap(item);
+ await tester.pumpAndSettle();
+ expect(find.text('Claude Code · Default'), findsOneWidget);
+ expect(find.text('Current · 40% left'), findsOneWidget);
+ expect(find.text('Claude Code · Work'), findsOneWidget);
+ expect(find.textContaining('0% left · resets '), findsOneWidget);
+ expect(find.text('Codex · Side'), findsOneWidget);
+ expect(find.text('Codex · Default'), findsOneWidget);
+ expect(find.text('70% left'), findsOneWidget);
+ expect(
+ find.text(
+ 'The new session starts fresh and reads a handoff note. Tasks and chat stay.',
+ ),
+ findsOneWidget,
+ );
+ ListTile row(String key) =>
+ tester.widget<ListTile>(find.byKey(ValueKey(key)));
+ expect(row('switch-pm-claude-$claudeDefault').enabled, isFalse);
+ expect(row('switch-pm-claude-aaaaaaaaaaaaaaaa').enabled, isFalse);
+ expect(row('switch-pm-codex-bbbbbbbbbbbbbbbb').enabled, isTrue);
+ await tester.tap(find.text('Cancel'));
+ await finish(tester);
+ },
+ );
+
+ testWidgets(
+ 'the dialog says only offered accounts are listed on a machine the reader does not own',
+ (tester) async {
+ const line = 'Only accounts its owner offered are listed.';
+ for (final (account, shown) in [('owner', true), ('mac', false)]) {
+ await mount(tester, swarm(), account);
+ await openMenu(tester);
+ await tester.tap(item);
+ await tester.pumpAndSettle();
+ expect(find.text(line), shown ? findsOneWidget : findsNothing);
+ await tester.tap(find.text('Cancel'));
+ await finish(tester);
+ }
+ },
+ );
+
+ testWidgets(
+ 'a machine that reports no profiles offers each engine\'s default',
+ (tester) async {
+ final server = swarm();
+ ((server.state['machines'] as List).first as Map).remove('observation');
+ await mount(tester, server, 'owner');
+ await openMenu(tester);
+ await tester.tap(item);
+ await tester.pumpAndSettle();
+ expect(find.text('Codex · Default'), findsOneWidget);
+ expect(find.text('Current'), findsOneWidget);
+ expect(
+ tester
+ .widget<ListTile>(
+ find.byKey(const ValueKey('switch-pm-codex-default')),
+ )
+ .enabled,
+ isTrue,
+ );
+ await tester.tap(find.text('Cancel'));
+ await finish(tester);
+ },
+ );
+
+ testWidgets('confirm sends lead.switch with engine and profileId', (
+ tester,
+ ) async {
+ final server = swarm();
+ await mount(tester, server, 'owner');
+ await openMenu(tester);
+ await tester.tap(item);
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<FilledButton>(find.widgetWithText(FilledButton, 'Switch'))
+ .onPressed,
+ isNull,
+ );
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(FilledButton, 'Switch'));
+ await tester.pumpAndSettle();
+ final sent = [
+ for (final post in server.posts)
+ if ((post['command'] as Map?)?['type'] == 'lead.switch')
+ post['command'] as Map,
+ ];
+ expect(sent, hasLength(1));
+ expect(sent.single['projectId'], 'lead');
+ expect(sent.single['engine'], 'codex');
+ expect(sent.single['profileId'], 'bbbbbbbbbbbbbbbb');
+ expect(find.byType(AlertDialog), findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets(
+ 'the PM\'s own profileId marks its row; no id means its engine\'s default',
+ (tester) async {
+ await mount(
+ tester,
+ swarm(pm: {'profileId': 'aaaaaaaaaaaaaaaa'}),
+ 'owner',
+ );
+ await openMenu(tester);
+ await tester.tap(item);
+ await tester.pumpAndSettle();
+ ListTile row(String key) =>
+ tester.widget<ListTile>(find.byKey(ValueKey(key)));
+ expect(row('switch-pm-claude-$claudeDefault').enabled, isTrue);
+ expect(find.textContaining('Current'), findsOneWidget);
+ await tester.tap(find.text('Cancel'));
+ await finish(tester);
+ },
+ );
+
+ testWidgets('a lent machine\'s borrower does not see Switch PM…', (
+ tester,
+ ) async {
+ final server = swarm(pm: {'machineOwnerId': 'ken'});
+ await mount(tester, server, 'mac');
+ await openMenu(tester);
+ expect(item, findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets('the PM row shows Switching… while switchRequest is set', (
+ tester,
+ ) async {
+ final server = swarm(
+ pm: {
+ 'switchRequest': {
+ 'id': 'r',
+ 'engine': 'codex',
+ 'profileId': 'bbbbbbbbbbbbbbbb',
+ 'requestedBy': 'owner',
+ 'at': 1,
+ },
+ },
+ );
+ await mount(tester, server, 'owner');
+ expect(find.textContaining('Switching…'), findsWidgets);
+ await finish(tester);
+ });
+}
diff --git a/desktop/test/super_tab_terminal_rows_test.dart b/desktop/test/super_tab_terminal_rows_test.dart
index 50c8d853e..cc157aa28 100644
--- a/desktop/test/super_tab_terminal_rows_test.dart
+++ b/desktop/test/super_tab_terminal_rows_test.dart
@@ -273,4 +273,116 @@ void main() {
controller.dispose();
},
);
+
+ testWidgets(
+ 'the PM\'s limit line shows local time and Switch PM… until the limit alert ends',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(900, 520));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ final pm = <String, dynamic>{
+ 'id': 'pm',
+ 'name': 'Lead',
+ 'displayName': 'Wren',
+ 'machineId': 'm',
+ 'harnessId': 'pm',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ 'alerting': ['limit'],
+ };
+ server.state['agents'] = [pm];
+ ((server.state['conversations'] as List)[0] as Map)['leadId'] = 'pm';
+ server.append('Wren hit a usage limit.', conversationId: 'lead');
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'pm',
+ 'name': 'Agent',
+ };
+ server.messages.last['source'] = {
+ 'kind': 'terminal-alert',
+ 'agentId': 'pm',
+ 'alert': 'limit',
+ 'limitedUntil': '2099-01-02T14:00:00.000Z',
+ 'lead': true,
+ };
+ final controller = server.controller(
+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'lead'},
+ );
+ await controller.refresh();
+ Future<void> show() async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ await show();
+ final local = DateTime.utc(2099, 1, 2, 14).toLocal();
+ final time = MaterialLocalizations.of(
+ tester.element(find.byType(SuperTabTerminalRow)),
+ ).formatTimeOfDay(TimeOfDay.fromDateTime(local));
+ // The backend's sentence stays verbatim; the reset time is its own muted text.
+ expect(find.text('Wren hit a usage limit.'), findsOneWidget);
+ expect(find.textContaining('until '), findsOneWidget);
+ expect(find.textContaining(time), findsOneWidget);
+ final button = find.widgetWithText(TextButton, 'Switch PM…');
+ expect(button, findsOneWidget);
+
+ // The limit is over (the machine stopped alerting): the line stays, the button goes.
+ pm['alerting'] = <String>[];
+ server.revision++;
+ await controller.refresh();
+ await tester.pumpAndSettle();
+ expect(find.byType(SuperTabTerminalRow), findsOneWidget);
+ expect(button, findsNothing);
+ expect(tester.takeException(), isNull);
+
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+
+ testWidgets('a pm-switch-notice line renders as a plain message', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(900, 520));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ server.append('Your PM now runs on Codex.', conversationId: 'offline');
+ server.messages.last['source'] = {'kind': 'pm-switch-notice'};
+ final controller = server.controller(
+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'offline'},
+ );
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Your PM now runs on Codex.'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
}
diff --git a/desktop/test/usage_account_key_test.dart b/desktop/test/usage_account_key_test.dart
index b08a1ad90..3ebb4f3ee 100644
--- a/desktop/test/usage_account_key_test.dart
+++ b/desktop/test/usage_account_key_test.dart
@@ -24,4 +24,15 @@ void main() {
isNot(usageAccountKey(UsageProvider.codex, 'same')),
);
});
+
+ test(
+ 'a Swarm profile id is the first 16 hex of sha256(machine:engine:path)',
+ () {
+ expect(swarmProfileId('m', 'claude', 'default'), '71dc90339553114c');
+ expect(
+ swarmProfileId('m', 'codex', '/home/me/.codex-b'),
+ '77103ab28be2ebd0',
+ );
+ },
+ );
}
diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dart
index c8122e401..378a8687a 100644
--- a/desktop/test/workspace_start_guide_test.dart
+++ b/desktop/test/workspace_start_guide_test.dart
@@ -103,6 +103,7 @@ class _FirstApp extends AppNotifier {
bool bypassPermission = true,
String? permissionMode,
String? codexHome,
+ String? claudeHome,
String? dsh,
String? swarmRole,
String? swarmSkillMode,
diff --git a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
index cbbd893bb..14854dde0 100644
--- a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
+++ b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
@@ -1393,11 +1393,12 @@ static void face_buddy_ring(ht_scene_t *f)
{
ht_ring_arc(f, 233 * 16, 233 * 16, 230 * 16, 3 * 16, 90, 180, color(mix_black(BUDDY_LILAC, 32)));
}
-// The upper dot lit on the PM side, the lower one (lilac) on the Buddy side.
-static void face_buddy_dots(ht_scene_t *f, bool buddy)
+// The upper dot lit on the PM side, the lower one (lilac) on the Buddy side. [replied]: on the PM side, the Buddy has a word
+// not yet heard, so the lower dot takes its colour, at its own place and size.
+static void face_buddy_dots(ht_scene_t *f, bool buddy, bool replied)
{
face_buddy_disc(f, 442, 218, buddy ? 9 : 12, buddy ? 0x55565fu : 0xeaeaf0u);
- face_buddy_disc(f, 442, 248, buddy ? 12 : 9, buddy ? BUDDY_LILAC : 0x55565fu);
+ face_buddy_disc(f, 442, 248, buddy ? 12 : 9, buddy || replied ? BUDDY_LILAC : 0x55565fu);
}
/*
* Desktop's agent pattern (avatar_art.dart superTabAgentPattern; the daemon sends its 15 half bits and colour): mirrored on
@@ -1433,7 +1434,7 @@ static void render_buddy_empty(ht_scene_t *f, const ht_lead_t *l)
focus_put(f, 63, 238, 340, &ht_lv_inter_28.base, color(0x8a8a99), BG, "No Buddy here yet", true);
focus_put(f, 63, 280, 340, &ht_lv_inter_20.base, color(0x6b6d78), BG, "Add one in the Harness app.", true);
face_buddy_ring(f);
- face_buddy_dots(f, true);
+ face_buddy_dots(f, true, false);
s.hits[s.hit_count++] = (hit_t){{83, 0, 300, 66}, A_AGENTS, 0, true};
}
/*
@@ -1519,13 +1520,12 @@ static void render_swarm_face(ht_scene_t *f)
face_buddy_ring(f);
}
if (l->buddies) {
- // The PM side's quiet badge for the Buddy's word: on the lower dot, and a line on the lower arc unless the bell or
- // the face has it. Empty runs in their place otherwise, so the count never moves.
- face_buddy_dots(f, buddy);
+ // The PM side's quiet sign of the Buddy's word: the lower dot's colour, and a line on the lower arc unless the bell or
+ // the face has it. Empty runs in their place, so the count never moves.
bool heard = !buddy && swarm_heard_of(l->id) >= 0, lower = bell && !told;
+ face_buddy_dots(f, buddy, heard);
for (int i = 0; i < f->count; i++) lower |= f->runs[i].arc == 2 && f->runs[i].text[0];
- if (heard) { face_buddy_disc(f, 449, 241, 14, 0x000000u); face_buddy_disc(f, 449, 241, 10, BUDDY_LILAC); }
- else { ht_box(f, 0, 0, 1, 1, 0, BG, BG); ht_box(f, 0, 0, 1, 1, 0, BG, BG); }
+ ht_box(f, 0, 0, 1, 1, 0, BG, BG); ht_box(f, 0, 0, 1, 1, 0, BG, BG);
if (heard && !lower) ht_arc_status_face(f, color(BUDDY_LILAC), "Your Buddy replied", &ht_arc_inter_lower);
else ht_text(f, 0, 0, 1, &ht_lv_inter_20.base, BG, BG, "");
}
diff --git a/devices/harness-device/firmware/test/test_touch_ui.py b/devices/harness-device/firmware/test/test_touch_ui.py
index f9537fedc..6864ee51e 100644
--- a/devices/harness-device/firmware/test/test_touch_ui.py
+++ b/devices/harness-device/firmware/test/test_touch_ui.py
@@ -2083,7 +2083,16 @@ static bool clear_of_text(void) {
static bool pm_dots(void) { return disc_at(442, 218, 12, 0xeaeaf0) && disc_at(442, 248, 9, 0x55565f); }
static bool buddy_dots(void) { return disc_at(442, 218, 9, 0x55565f) && disc_at(442, 248, 12, 0xc49bff); }
static bool any_dot(void) { return disc_at(442, 218, 12, 0xeaeaf0) || disc_at(442, 218, 9, 0x55565f); }
-static bool badge(void) { return disc_at(449, 241, 14, 0x000000) && disc_at(449, 241, 10, 0xc49bff); }
+// The Buddy's unheard word on the PM side: the lower dot itself turns lilac, at its own place and size.
+static bool badge(void) { return disc_at(442, 218, 12, 0xeaeaf0) && disc_at(442, 248, 9, 0xc49bff); }
+// Nothing drawn off the dots' line: the old badge, 7 px off the lower dot, smeared the two together.
+static bool offset_disc(void) {
+ for (int i = 0; i < scene.count; i++) {
+ const ht_run_t *r = &scene.runs[i];
+ if (r->box.h > 1 && r->x + r->w / 2 == 449 && r->y + r->box.h / 2 == 241) return true;
+ }
+ return false;
+}
/*
* Diego's dial, 2026-11-02: every daemon restart (each CLI update) dropped the dial on the tabs list, because the Swarm cards
* took 5-40 s to come back. The face comes back on its Swarm, Lead and side whenever the cards do, unless the person moved on.
@@ -2290,16 +2299,16 @@ static void swarm_buddy_checks(const char *dir) {
assert(scene_says("No Buddy here yet") && lilac_ring());
{ int before = starts; tap(fake_ms + 2000, 233, 260); assert(starts == before); }
- // 7d the quiet notice: on the PM side the Buddy's word is a lilac badge and a line on the lower arc, with no beep, no
- // inbox entry and no wake. The run count holds.
+ // 7d the quiet notice: on the PM side the Buddy's word turns the lower dot lilac and writes a line on the lower arc, with
+ // no beep, no inbox entry and no wake. The run count holds.
buddy_setup();
ui_supertab_recap("s1", "B0", "lead-web", "Assigned #2083 to web-api. I'll post here when the PR is up.", 1792560000u, false);
scene_take(); pm_runs = scene.count;
- assert(!badge() && !scene_says("Your Buddy replied"));
+ assert(!badge() && pm_dots() && !offset_disc() && !scene_says("Your Buddy replied"));
int entries = s.notice_count; int woke = wakes;
assert(!ui_supertab_notice("s1", "B0", HT_CHAT_BUDDY, "b0", "Cache it.", 1792560002u));
scene_take();
- assert(s.notice_count == entries && wakes == woke && badge() && scene_says("Your Buddy replied") && scene.count == pm_runs);
+ assert(s.notice_count == entries && wakes == woke && badge() && !pm_dots() && !offset_disc() && scene_says("Your Buddy replied") && scene.count == pm_runs);
FOCUS_PAGE("buddy-7d");
// Another project shows none; back on web-api it is still there.
swipe_next(); assert(!badge() && !scene_says("Your Buddy replied"));
@@ -2309,8 +2318,8 @@ static void swarm_buddy_checks(const char *dir) {
// The resting face keeps its own line on the lower arc: there the badge alone tells it.
ui_supertab_recap("s1", "B0", "lead-web", "", 1792560000u, true);
assert(!ui_supertab_notice("s1", "B0", HT_CHAT_BUDDY, "b0", "Later.", 1792560002u));
- scene_take(); assert(badge() && !scene_says("Your Buddy replied"));
- swipe_up(); swipe_down(); assert(!badge());
+ scene_take(); assert(badge() && !offset_disc() && !scene_says("Your Buddy replied"));
+ swipe_up(); swipe_down(); assert(!badge() && pm_dots());
// A Buddy word while its side is open is read there; the desktop opening the Buddy chat reads one too.
swipe_up(); buddy_card("buddy");
assert(!ui_supertab_notice("s1", "B0", HT_CHAT_BUDDY, "b0", "Done.", 1792560003u));
diff --git a/docs/plans/2026-11-02-connections-bridge-stdio-shim-plan.md b/docs/plans/2026-11-02-connections-bridge-stdio-shim-plan.md
new file mode 100644
index 000000000..040aa8609
--- /dev/null
+++ b/docs/plans/2026-11-02-connections-bridge-stdio-shim-plan.md
@@ -0,0 +1,45 @@
+# Connections bridge: MCP clients through a stdio shim: plan
+
+**Goal:** MCP clients reach the connections bridge without a port another account can hold. Whoever holds the bridge's fixed
+port can otherwise read tool calls and feed false answers to the owner's running agents. Task #2066, the follow-up that task #2016's
+security review made a condition of #2550.
+
+## Design
+
+- **The shim.** A client's entry runs Harness's node on `mcp-shim.mjs --socket <path> <code>`, a small script written into the vault's
+ private folder, as the Buddy guard is written. An entry naming the running script would name the lean bundle from the daemon, which has
+ no CLI, or a worktree; naming cli.js would load all of it per connection per agent; the updater ships only cli.js and notify.mjs. It speaks MCP's stdio transport to the client
+ and MCP's HTTP transport to the bridge over the socket. It streams answers, tracks the session, and sends one POST per message.
+- **The socket.** The bridge's handler gets a second listener at `<vault>/bridge.sock`, 0600, through `listenLocalSocket`. It sits
+ in the vault's private folder because a daemon and a `harness connections sync` from anywhere agree on that path, and the entry
+ names it. It is not the daemon's own socket: the bridge is its own service, and this needs no new route in the hook server.
+- **No key.** Reaching a 0600 socket is the credential, so the entry and the shim hold none. The socket answers MCP servers only: no
+ list of connections and no key-only API, as an agent's key does.
+- **No fallback.** With the socket gone the daemon is down, and the client is told so. Nothing goes to a port.
+- **What stays on the port:** clients running from an old entry until they restart, Windows, a vault path too long for a socket, and
+ Harness's own cloud agents. Moving Store agents, companions and old clients is the second follow-up, out of this task.
+
+## Design rules
+
+- Growth: N/A because nothing grows: one socket file and one script, replaced at each start and removed with the folder.
+- Concurrency: requests run side by side as they do over HTTP; `initialize` and notifications go first and in order. The vault's
+ own lock still guards its files. A second daemon on the vault finds a live socket and retries, as the port's listener does.
+- Read cost: N/A because each message is the one request it was before. Each client now holds one shim process open.
+- Scale: one node process per MCP server per running agent: 18 MB of memory footprint each (12 for a bare node; 50 and 39 MiB resident),
+ measured on an idle Mac 2026-11-02. Process count warns first. 3 connections on 43 agent sessions is about 130 processes, about 2.3 GB of
+ footprint; 10x that is too much for one Mac, so review this at 300 shim processes.
+- Compatibility: entries are rewritten at each daemon start. A running client keeps its old address until it restarts, and the port
+ still answers it. A server's own unprompted stream (GET) is not relayed, so `*_changed` notifications are lost.
+- Migration and rollback: no data migration. A rollback writes URL entries again at the next start, and the key is still in
+ `bridge.json` or made on demand.
+- Audience: the filesystem enforces it: 0700 folder, 0600 socket, this account only.
+- Identity: the socket's owner is the OS account running the daemon; no login is read.
+- Failure: each failure answers the request by its id, so a client never waits for ever: daemon down, service refusal, an unreadable
+ answer, or a socket not private. A forgotten session is reopened once. A socket that cannot bind is logged once.
+- Platforms: macOS and Linux. Windows keeps the address until it has its own way.
+
+## Steps
+
+1. Spec: a holder of the old port hears nothing while a tool call works through the entry's shim; daemon down; socket boundaries.
+2. `mcpShimSource.ts`, written by `sync`, `serveBridgeSocket`, entries in `agents.ts`, the listener in `services/connectors.ts`.
+3. A real process check with a built CLI, Claude Code and Codex, in a throwaway home.
diff --git a/docs/plans/2026-11-02-pm-switch-review-fixes-plan.md b/docs/plans/2026-11-02-pm-switch-review-fixes-plan.md
new file mode 100644
index 000000000..c0a19d57c
--- /dev/null
+++ b/docs/plans/2026-11-02-pm-switch-review-fixes-plan.md
@@ -0,0 +1,35 @@
+# PM switch: fixes from the two security reviews
+
+**Goal:** the switch of #2527, #2528 and #2529 works for real, tells the machine owner, cannot leave no working PM, says only what
+is true, and spends another person's account only after that person offered it and while they keep offering it.
+
+**Architecture:** no new flow. The backend gives the host the chat id and keeps the requester through the rebind. The host checks
+every account's sign-in before closing, and reports a post-close failure only when the old PM is back. Offers move to their own
+file, apart from linked folders. Desktop gets one dialog to offer and withdraw.
+
+## Backend (#2527)
+1. Test: the real host row has the PM's chat. Add `ledConversationId`. `leadsConversationId` stays null, because an older host reads
+ it as a delivery filter (cli `host.ts`).
+2. Test: rebind, then result, tells the machine owner. `switchLanded` keeps `requestedBy`.
+3. Test (integration): a quiet owner's Buddy chat takes the second notice; no second chat. `moreNamed` loads it.
+4. Test: a failure report after the rebind reads as moved; `down` says the PM has not come back.
+
+## CLI (#2528)
+5. Test: the prompt is built from the recorded host row. Read `ledConversationId`.
+6. Test: a signed-out default account is refused before the close, outside Team.
+7. Tests: after the close, a refused, timed-out or held create posts nothing until the rebind (ok) or the old PM's return past the
+ hold (failed), or the end of the adoption window (`down`). This covers both "back on <engine>" findings; polling the creation
+ status is not needed, as the rebind reads the daemon's receipts itself.
+8. Test: a new request inside an old switch's window is carried out. The change id comes from the request id, so a record names
+ its own switch.
+9. Test: a fork keeps `claudeHome`.
+10. Tests: `lib/accountOffers.ts` and `swarm_account_offer`. Linked and Harness-made folders are not offered (Codex links made in
+ New Harness were about to be offered too); a withdraw ends it; a damaged file offers nothing; the owner alone may ask.
+
+## Desktop (#2529)
+11. Tests: picking a "Not offered to the Swarm" row runs the pane on it and sends no offer.
+12. Tests: "Swarm accounts…" lists this computer's accounts, offers only after the sentence saying who can spend it, withdraws, and
+ survives a refusal or an older CLI. Add Claude account says it stays private until offered.
+
+## Not done here
+No live switch on this project's PM. Withdrawing does not move a PM already on that account: the dialog says so.
diff --git a/docs/plans/2026-11-02-threads-reply-shows-at-once-plan.md b/docs/plans/2026-11-02-threads-reply-shows-at-once-plan.md
new file mode 100644
index 000000000..a8f754e9f
--- /dev/null
+++ b/docs/plans/2026-11-02-threads-reply-shows-at-once-plan.md
@@ -0,0 +1,37 @@
+# Threads page: your reply shows at once
+
+Task #2054, asked for by Scholes on 2026-11-02.
+
+**Problem:** a reply sent from the box on a Threads card did not appear on the card. The card lists the replies it read
+when it first showed, so the reader's own reply appeared only on a later visit, after an agent had answered, and looked unsent.
+
+## Change
+
+- `SuperTabAttention.ownReplies` gives a card the reader's replies: on their way or failed, from
+ `SuperTabController.outgoing`, and those sent during this visit, which it notes on every controller change, because a
+ send can go from on its way to read back between two frames.
+- The card shows each under its replies: Sending…, then Sent, or the thread pane's Not sent with Retry and Delete.
+- Only a reply first seen on its way is noted: a sent one stays in `outgoing` until its chat's transcript loads, and one
+ from an earlier visit must not come back as new (review).
+- A reply of files alone says Files.
+- A failed reply keeps its whole text in that row. Text whose files fail to upload stays in the box, as today.
+- A reply the card already read back is not shown twice (the same message id).
+- A sent one shows only while the card is new; one on its way or failed shows on any card.
+
+## Tests (each fails on main)
+
+In `desktop/test/super_tab_attention_test.dart`: shows at once and stays after an answer, failed then Retry, failed then
+Delete, not shown twice, not back as new on a later visit, and a failed reply's whole text.
+
+## Design
+
+- growth: `_ownThisVisit` holds one short entry per reply sent this visit, cleared when the view closes.
+- concurrency: N/A because all of it runs on the UI isolate; sends keep the controller's one send lane.
+- read cost: no new reads; `outgoing` is walked for each listed chat on a controller change while the view is open.
+- scale: N/A; a person's own replies during one visit.
+- compatibility: N/A; Desktop and web share this view, and no frame or endpoint changes.
+- migration + rollback: none; revert the PR.
+- audience: N/A; only the reader's own sends, and the server still enforces who may post.
+- identity: the row is the signed-in account's own person row.
+- failure: a refused or unanswered reply says Not sent and is never called sent.
+- platforms: Desktop and the web build, which share `threads_view.dart`; the phone app is out.
diff --git a/docs/superpowers/plans/2026-11-02-pm-switch-engine-account.md b/docs/superpowers/plans/2026-11-02-pm-switch-engine-account.md
new file mode 100644
index 000000000..7371017a1
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-02-pm-switch-engine-account.md
@@ -0,0 +1,223 @@
+# Switch a Swarm PM to another engine or account: Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A person who may manage a project moves its PM to another engine or another account on the same machine in one action, and the PM stays the same Swarm agent.
+
+**Architecture:** The CLI learns Claude profiles (`CLAUDE_CONFIG_DIR` folders) as it knows Codex profiles, launches Claude in one, reads usage per profile and reports opaque profile ids to the backend. The backend gains `lead.switch`, which the PM's host claims and carries out with #2493's Change agent steps over its own local daemon socket. Desktop's Change agent picks engine and profile, and the Swarm offers **Switch PM…** in the project menu and on the PM's limit line.
+
+**Tech Stack:** TypeScript (cli, backend, vitest), Flutter/Dart (desktop).
+
+**Spec:** `docs/superpowers/specs/2026-11-02-pm-switch-engine-account-design.md`
+
+## Global Constraints
+
+- Every switch uses #2493's handoff file; no transcript is copied between accounts.
+- No path, email, account id or plan leaves the machine. Reported profile labels are at most 40 characters and dropped if they contain `@`.
+- Profile id = first 16 hex of sha256(`<machine id>:<engine>:<realpath>`). The default account's id is `'default'`.
+- Claude Keychain service for a profile: `Claude Code-credentials-<first 8 hex of sha256(CLAUDE_CONFIG_DIR as given, no trailing slash)>`, read with `-a <$USER if /^[a-zA-Z0-9._-]+$/ else claude-code-user>`.
+- At most 256 linked Claude paths, 16 reported profiles per machine, 8 usage reads per engine, one usage read per profile per `USAGE_FRESH_MS`.
+- `lead.switch` is allowed for the project owner (`manageProject`) and the owner of the PM's machine. Error codes: `LEAD_SWITCHING`, `PROFILE_UNKNOWN`, `HOST_OUTDATED`, `ENGINE_NOT_OFFERED`, `PROJECT_OWNER_REQUIRED`, `NO_LEAD`, `MACHINE_OFFLINE`.
+- Switch claim lease: 15 minutes. Unclaimed request expires after 2 minutes.
+- Copy, verbatim: menu item `Switch PM…`; dialog note `The new session starts fresh and reads a handoff note. Tasks and chat stay.`; result lines `PM moved to <Engine> · <label>.` / `Couldn't switch the PM: <error>. It is back on <Engine>.` / `Couldn't switch the PM: its machine did not answer.`; limit line `<PM name> hit a usage limit.`
+- One PR per part (A CLI profiles + launch + usage + report, B backend, C host, D Desktop), each test first, Reviewer in its own group, `make merge-pr` once `ci/required` is green. CLI files under `src/core` and `src/services` keep 100% coverage (`npm run test:core`).
+
+## Review Focus
+
+- A profile folder deleted or signed out after it was reported: the host refuses `PROFILE_UNKNOWN` (gone) or the new session fails; either way the old PM is back and a line says so. Test in Task 8.
+- A `lead.switch` for a PM whose machine runs an old CLI: refused `HOST_OUTDATED`, never left pending. Test in Task 6.
+- Two people press Switch PM at once: the second gets `LEAD_SWITCHING`. Test in Task 6.
+- An Orca profile folder named `home` with an `oauthAccount.emailAddress` and no `displayName`: the reported label is `Orca <4 hex>`, never the email. Test in Task 1.
+- Change agent on a pane whose current profile is the one picked: nothing happens (no close, no create). Test in Task 9.
+
+---
+
+## Part A: CLI (one PR)
+
+### Task 1: Claude profiles: list, link, discover
+
+**Files:**
+- Create: `cli/src/lib/claudeProfiles.ts`, `cli/src/lib/claudeProfiles.test.ts`
+- Modify: `cli/src/services/models.ts:511-546` (`launchTargetRequests`), `cli/src/core/api.ts:727-732` (`MODELS_REQUESTS`), `cli/src/services/models.spec.ts` (never `cli/src/lib/e2ee/core.ts` or `desktop/lib/e2ee/envelope.dart`: the RPCs serve the local machine only)
+
+**Interfaces:**
+- Produces: `interface ClaudeProfile { id: string; path: string; label: string; reportLabel: string }`; `listClaudeProfiles(observedPaths?: string[], options?: { home?: string; environment?: NodeJS.ProcessEnv; machineId: string }): ClaudeProfile[]`; `linkClaudeProfile(path: string, machineId: string): { profile: ClaudeProfile } | { error: 'INVALID_PATH' | 'NOT_FOUND' }`; `profileId(machineId: string, engine: 'claude' | 'codex', realpath: string): string`; RPCs `claude_profiles_list { observedPaths }` → `{ profiles }`, `claude_profile_link { path }` → `{ profile } | { error }`.
+
+- [ ] **Step 1: Write the failing tests** in `claudeProfiles.test.ts`:
+ - `lists the default account first with id 'default'`.
+ - `finds Orca profiles`: a temp home with `Library/Application Support/orca/claude-profiles/ab12cd34-…/home/.claude.json` holding `{"oauthAccount":{"emailAddress":"[email protected]"}}` → one row with `label` `'[email protected]'` and `reportLabel` `'Orca ab12'`.
+ - `uses displayName for the label when present` → `reportLabel === 'Work'` for `{"oauthAccount":{"displayName":"Work"}}`.
+ - `drops a report label containing @` and `cuts it at 40 characters`.
+ - `links a folder and keeps it across reads`; `refuses a relative path with INVALID_PATH`.
+ - `profileId is stable and 16 hex`.
+ - In `models.spec.ts`: `claude_profiles_list and codex_profiles_list answer OWNER_REQUIRED to a guest`.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/claudeProfiles.test.ts src/services/models.spec.ts`. Expected: FAIL (module missing; codex RPC answers a guest).
+- [ ] **Step 3: Implement** by copying `codexProfiles.ts`/`codexProfileDiscovery.ts` patterns (file `claude-profiles.json`, 0600, atomic, 256 cap; a folder counts when it holds `.claude.json` or `settings.json`; discovery = inherited `CLAUDE_CONFIG_DIR`, `~/.claude-*`, Orca `claude-profiles/*/home`). Add the two RPCs beside the Codex pair with `if (!asker.owner) reply({ error: 'OWNER_REQUIRED' })` on all four, and add the types to `MODELS_REQUESTS` only.
+- [ ] **Step 4: Run** the same command, then `npm run test:core`. Expected: PASS, 100% for `services/models.ts`.
+- [ ] **Step 5: Commit** `feat(cli): Claude profiles, listed and linked like Codex profiles`.
+
+### Task 2: Start Claude in a profile
+
+**Files:**
+- Modify: `cli/src/core/agents/launches.ts:375-386,506`, `cli/src/core/agents/create.ts`, `cli/src/lib/registry.ts:178-192`, `cli/src/core/agents/launchAuthority.ts:5-10`, `cli/src/lib/agentFrame.ts:88,259`, `cli/src/engines/nativeLaunch.ts:216-218`, `cli/src/lib/engineHomes.ts:370-374`, `cli/src/backendSocket.ts:153-160`
+- Test: `cli/src/core/agents/launches.spec.ts`, `cli/src/engines/nativeLaunch.spec.ts`, `cli/src/lib/engineHomes.spec.ts`
+
+**Interfaces:**
+- Consumes: none.
+- Produces: `agent_create` payload field `claudeHome?: string`; `RegisteredSession.claudeHome?: string | null`; agent frame field `claudeHome`; error `INVALID_CLAUDE_HOME`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - launches.spec: `claudeHome is refused for codex and with a grid (INVALID_CLAUDE_HOME)`; `claudeHome reaches the create input and the registry row`.
+ - nativeLaunch.spec: `an explicit claudeHome is adopted as a known home` (`confirmHome` called with `('claude', home)`).
+ - engineHomes.spec: `launchHomeOf honours the profile for CLAUDE_CONFIG_DIR homes` (trust file resolves to `<profile>/.claude.json`).
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/core/agents/launches.spec.ts src/engines/nativeLaunch.spec.ts src/lib/engineHomes.spec.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement:** validate like `codexHome` (absolute, ≤4096, no control characters, engine claude, no grid); put it on `CreateAgent`; store it on the row as `hermesHome` is; add it to the authority fingerprint and agent frame; call `confirmHome` for an explicit Claude home; in `launchHomeOf`'s variable branch use `profile ||` before the environment.
+- [ ] **Step 4: Run** the same tests and `npm run test:core`. Expected: PASS, coverage 100%.
+- [ ] **Step 5: Commit** `feat(cli): agents start Claude in a chosen profile (CLAUDE_CONFIG_DIR)`.
+
+### Task 3: Usage per profile
+
+**Files:**
+- Modify: `cli/src/lib/agentCredentials.ts`, `cli/src/lib/accountUsage.ts`, `cli/src/services/usage.ts`
+- Test: `cli/src/lib/accountUsage.spec.ts`, `cli/src/services/usage.spec.ts`
+
+**Interfaces:**
+- Produces: `claudeKeychainService(configDir?: string): string`; `readAccountUsage(deps & { claudeHome?: string; codexHome?: string })`; `usage_read { profile?: { engine: 'claude' | 'codex'; id: string } }` → `{ providers }` for that profile.
+
+- [ ] **Step 1: Write the failing tests:** `claudeKeychainService('/x/home')` equals `'Claude Code-credentials-' + sha256('/x/home').slice(0, 8)`; `the keychain read passes -a`; `a Claude profile reads <dir>/.credentials.json and <dir>/.claude.json`; `a Codex profile reads <dir>/auth.json`; `usage_read without a payload answers as before`; `usage_read with an unknown profile id answers PROFILE_UNKNOWN`.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/accountUsage.spec.ts src/services/usage.spec.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement** the service rule and `-a` account rule (port `desktop/lib/usage/usage_credentials.dart:56-91`), the per-home paths, and the payload lookup through `listClaudeProfiles` / `listCodexProfiles` by id.
+- [ ] **Step 4: Run** the same tests and `npm run test:core`. Expected: PASS.
+- [ ] **Step 5: Commit** `feat(cli): read each Claude and Codex profile's usage`.
+
+### Task 4: Report profiles and the leadSwitch capability
+
+**Files:**
+- Modify: `cli/src/superTabs/machines.ts` (observation literal ~:530-547, `CAPABILITIES` :175, `sendAlone` :731-760)
+- Test: `cli/src/superTabs/machines.spec.ts`
+
+**Interfaces:**
+- Consumes: Task 1 `listClaudeProfiles`, Task 3 per-profile usage.
+- Produces: observation field `profiles: { engine: 'claude' | 'codex'; id: string; label: string; leftPercent: number | null; resetsAt: string | null }[]` (≤16); capability `'leadSwitch'`.
+
+- [ ] **Step 1: Write the failing tests:** `the report lists profiles with ids and report labels, no paths`; `profiles are dropped after the backend refuses the field`; `capabilities include leadSwitch when asked`; `usage is read at most once per profile per USAGE_FRESH_MS`.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/superTabs/machines.spec.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement** with the existing readiness/quota caches; `leftPercent` = 100 − the tightest window's `usedPercent`.
+- [ ] **Step 4: Run** the same test. Expected: PASS.
+- [ ] **Step 5: Commit** `feat(cli): machines report their engine profiles and can switch a PM`, then open PR A.
+
+## Part B: Backend (one PR)
+
+### Task 5: Store reported profiles
+
+**Files:**
+- Modify: `backend/src/superTabs/machines.ts:114-187` (`machineObservationSchema`, `storedObservation`), `backend/src/superTabs/model.ts:805-815`
+- Test: `backend/src/superTabs/machines.test.ts`
+
+**Interfaces:**
+- Produces: `StoredReading.profiles` (same shape as Task 4), kept only for contributed engines and sent to clients with `pool.observation`.
+
+- [ ] **Step 1: Write the failing tests:** `accepts up to 16 profiles and refuses a 17th`; `refuses a label with @`; `keeps profiles of contributed engines only`.
+- [ ] **Step 2: Run** `cd backend && npx vitest run src/superTabs/machines.test.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement** a strict, capped zod schema and the `storedObservation` filter.
+- [ ] **Step 4: Run** the same test. Expected: PASS.
+- [ ] **Step 5: Commit** `feat(swarm): store each machine's reported engine profiles`.
+
+### Task 6: `lead.switch`, claim and result
+
+**Files:**
+- Modify: `backend/src/superTabs/commands.ts` (schema :121-287; handlers beside `lead.start` :1343 and `agent.stopLease` :2315; `agent.rebind` :2241), `backend/src/superTabs/model.ts` (`Agent.switchRequest`)
+- Test: `backend/src/superTabs/commands.test.ts`, `backend/integration/superTabLiveness.test.ts`
+
+**Interfaces:**
+- Consumes: Task 5 `profiles`.
+- Produces: commands `lead.switch { projectId, engine, profileId, model?, effort? }`, `agent.switchClaim { agentId, switchId }` → `{ leaseId, expiresAt }`, `agent.switchResult { agentId, switchId, ok, error? }`; `Agent.switchRequest?: { id: string; engine: string; profileId: string; model?: string; effort?: string; requestedBy: string; at: string; claimedUntil?: string }`.
+
+- [ ] **Step 1: Write the failing tests (commands.test.ts):**
+ - `the project owner and the PM machine's owner may switch; a member may not (PROJECT_OWNER_REQUIRED)`.
+ - `refuses NO_LEAD, MACHINE_OFFLINE (no fresh reading), HOST_OUTDATED (no leadSwitch capability), LEAD_SWITCHING (second request), PROFILE_UNKNOWN, ENGINE_NOT_OFFERED`.
+ - `works while the Swarm is paused`.
+ - `switchClaim only by the PM agent itself; lease 15 minutes`.
+ - `switchResult ok writes "PM moved to Codex · Work." and clears the request`; `ok:false writes "Couldn't switch the PM: <error>. It is back on Claude."`.
+ - `agent.rebind clears switchRequest, limitedUntil and the limit alert when engine or account changed`.
+- [ ] **Step 2: Run** `cd backend && npx vitest run src/superTabs/commands.test.ts -t "lead.switch|switchClaim|switchResult|rebind clears"`. Expected: FAIL.
+- [ ] **Step 3: Implement** the three commands with `manageProject` or `[pool.ownerId]` for the PM machine; `switchRequest.id = operationId`.
+- [ ] **Step 4: Run** the same command and `npx vitest run --config vitest.super-tabs.config.ts integration/superTabLiveness.test.ts`. Expected: PASS.
+- [ ] **Step 5: Commit** `feat(swarm): lead.switch asks a PM's host to move it to another engine or account`.
+
+### Task 7: The PM's limit line, and stale switches
+
+**Files:**
+- Modify: `backend/src/superTabs/terminal.ts:150-176` (`terminalAlert`), `backend/src/superTabs/tidy.ts` (beside `idleNotices`), `backend/src/superTabs/store.ts:3097`
+- Test: `backend/src/superTabs/terminal.test.ts`, `backend/src/superTabs/tidy.test.ts`
+
+**Interfaces:**
+- Produces: limit row text `<PM name> hit a usage limit.` with `source.limitedUntil` and `source.lead: true` when the target is the project's PM; `staleSwitches(state: SuperTabState, now: number): MessageDraft[]`.
+
+- [ ] **Step 1: Write the failing tests:** `a PM's limit row says "<name> hit a usage limit." and marks source.lead`; `a worker's row is unchanged`; `staleSwitches drops an unclaimed request after 2 minutes and a lapsed claim, with "Couldn't switch the PM: its machine did not answer."`.
+- [ ] **Step 2: Run** `cd backend && npx vitest run src/superTabs/terminal.test.ts src/superTabs/tidy.test.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement**; call `staleSwitches` where `idleNotices` runs (store.ts:3097).
+- [ ] **Step 4: Run** the same tests. Expected: PASS.
+- [ ] **Step 5: Commit** `feat(swarm): the PM's limit line names it, and a switch nobody answered ends with a line`, then open PR B.
+
+## Part C: Host (one PR, after A and B are merged)
+
+### Task 8: The host carries out a switch request
+
+**Files:**
+- Create: `cli/src/superTabs/leadSwitchRequest.ts`, `cli/src/superTabs/leadSwitchRequest.spec.ts`
+- Modify: `cli/src/superTabs/host.ts` (poll beside `releaseWorker` :948 and `keepAlive` :984-987)
+
+**Interfaces:**
+- Consumes: Task 6 commands and `switchRequest`; Task 1/3 profile lookup by id; Task 2 `claudeHome`; #2493 `leadSwitch.ts` unchanged.
+- Produces: `serveLeadSwitch(row: HostRow, deps: { backend; daemon: LocalDaemon; profiles: (engine, id) => string | null | 'default'; now }): Promise<void>`.
+
+- [ ] **Step 1: Write the failing tests (leadSwitchRequest.spec.ts)** against a fake backend and a fake daemon:
+ - `claims, then prepares the handoff, closes with the change id, creates with creationId = changeId and the profile's home, completes the handoff` (assert the four daemon calls and one shared 32-hex `changeId`).
+ - `reports ok once agent.rebind is seen for the PM`.
+ - `reports ok:false with the error and leaves the old PM to #2493's rollback when the create is refused`.
+ - `refuses PROFILE_UNKNOWN without closing the PM when the profile is gone`.
+ - `does nothing for a request it cannot claim`.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/superTabs/leadSwitchRequest.spec.ts`. Expected: FAIL.
+- [ ] **Step 3: Implement** over the local daemon socket (`openDaemon(where)` as `start.ts` does); the handoff prompt is the one `agent_handoff_prepare` returns; Team daemons offer only `'default'`.
+- [ ] **Step 4: Run** the spec, `npx vitest run src/superTabs/host.spec.ts src/superTabs/leadSwitch.spec.ts`. Expected: PASS.
+- [ ] **Step 5: Commit** `feat(cli): a PM's host switches it when the Swarm asks`, then open PR C.
+
+## Part D: Desktop (one PR; Task 9 may ship after A alone)
+
+### Task 9: Change agent picks engine and profile
+
+**Files:**
+- Modify: `desktop/lib/state/swarm_search.dart` (`_filter` ~:1959-1993), `desktop/lib/state/swarm_navigation.dart:319,367`, `desktop/lib/state/app_state.dart` (`_AgentChange` :271, `changeAgent` :17255-17262, `_changeAgent` :17506, add `listClaudeProfiles`/`linkClaudeProfile` beside :15109-15130, `createAgent` `claudeHome` beside `codexHome`)
+- Test: `desktop/test/agent_change_test.dart`
+
+**Interfaces:**
+- Consumes: Task 1 RPCs, Task 2 `claudeHome`, Task 3 `usage_read { profile }`.
+- Produces: `SwarmDestination.agentProfile: String?` (profile id); `AppNotifier.changeAgent(machineId, agentId, engine, {String? profile})`.
+
+- [ ] **Step 1: Write the failing tests:** `the picker lists one row per profile with % left`; `a same-engine change to another profile closes and creates with claudeHome`; `picking the current engine and profile does nothing`; `a Codex profile passes codexHome`; `Add Claude account… opens a pane running claude with a new CLAUDE_CONFIG_DIR and links it`.
+- [ ] **Step 2: Run** `cd desktop && flutter test test/agent_change_test.dart`. Expected: FAIL.
+- [ ] **Step 3: Implement**; compare `(engine, profile)` in `changeAgent`; the handoff request stays as it is.
+- [ ] **Step 4: Run** the same test and `flutter analyze lib/state`. Expected: PASS, no issues.
+- [ ] **Step 5: Commit** `feat(desktop): Change agent picks the engine and the account`.
+
+### Task 10: Switch PM in the Swarm
+
+**Files:**
+- Create: `desktop/lib/super_tabs/switch_pm.dart`
+- Modify: `desktop/lib/super_tabs/view.dart` (`_options` ~:2401, `SuperTabTerminalRow` ~:2686), `desktop/lib/super_tabs/model.dart` (read `observation.profiles`, `agent.switchRequest`)
+- Test: `desktop/test/super_tab_switch_pm_test.dart`, `desktop/test/super_tab_terminal_rows_test.dart`
+
+**Interfaces:**
+- Consumes: Task 5 `profiles`, Task 6 `lead.switch` and `switchRequest`, Task 7 `source.lead`.
+- Produces: `showSwitchPm(BuildContext, SuperTabController, String projectId)`.
+
+- [ ] **Step 1: Write the failing tests:** `the project owner and the PM machine's owner see Switch PM…; a member does not`; `the dialog lists the PM machine's profiles with % left, marks the current one and disables 0%`; `confirm sends lead.switch with engine and profileId`; `the PM row shows Switching… while switchRequest is set`; `the PM's limit line shows local time and Switch PM… until the limit alert ends`.
+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_switch_pm_test.dart test/super_tab_terminal_rows_test.dart`. Expected: FAIL.
+- [ ] **Step 3: Implement**; copy `SuperTabRouteRow._action` (route_row.dart:76) for the row button and `showProjectAction` (project_options.dart:82) for the menu item.
+- [ ] **Step 4: Run** the same tests and `flutter analyze lib/super_tabs`. Expected: PASS, no issues.
+- [ ] **Step 5: Commit** `feat(desktop): Switch PM from the project menu and the PM's limit line`, then open PR D.
+
+### Task 11: Manual check on Diego's Mac
+
+- [ ] With all four PRs merged and released, from the Swarm menu: switch a PM from the default Claude account to an Orca Claude account, then to Codex, then back. Record each line the PM chat shows and that the PM kept its tasks. Note the result in PR D.
diff --git a/docs/superpowers/specs/2026-11-02-pm-switch-engine-account-design.md b/docs/superpowers/specs/2026-11-02-pm-switch-engine-account-design.md
new file mode 100644
index 000000000..b32021952
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-02-pm-switch-engine-account-design.md
@@ -0,0 +1,248 @@
+# Switch a Swarm PM to another engine or account
+
+Date: 2026-11-02. Requested by Diego.
+
+## Problem
+
+Two reports from 11-01:
+
+1. The Product Manager (PM) of a project runs on a Mac Studio, and its Claude account reached its usage limit. Nobody could
+ move it to another account, so the PM stopped working until the limit reset.
+2. Diego's own PM reached its Claude limit. He wanted to move it to Codex or to his second Claude account. Exiting Claude in
+ the terminal and starting Codex there did not work, because the Swarm host reopens the PM on its old engine within about
+ 5 s (`cli/src/superTabs/host.ts` `keepAlive`), and a hand-started process is not the PM.
+
+What exists today:
+
+- PR #2493 (CLI 0.5.19, Desktop 1.3.45) lets the **machine owner** change a PM's **engine** with the pane header's Agent
+ control (Change agent). The PM keeps its Swarm agent id, role and tasks (`agent.rebind`); the new engine reads a handoff
+ file. The PM's conversation is never purged, and a failed switch reopens the old PM.
+- A machine has **several Codex accounts** (Codex profiles, `CODEX_HOME` folders, `cli/src/lib/codexProfiles.ts`), but
+ Change agent never passes one, so a switch always lands on the default `~/.codex`.
+- A machine has **one Claude account**. Claude Code does support several: each `CLAUDE_CONFIG_DIR` keeps its own sign-in in
+ the macOS Keychain under `Claude Code-credentials-<first 8 hex of sha256(dir)>` (checked on Diego's Mac against an Orca
+ profile: `79cb9be9`). Harness never starts Claude with one.
+- When the PM itself hits a limit, the host's screen watch posts `agent.alert limit`; the backend writes one row in the
+ project's PM chat, "… hit a usage limit. Routing skips it until HH:MM UTC.", with no recipients and no action
+ (`backend/src/superTabs/terminal.ts:150-176`). Nothing offers a way out.
+- The person who owns the project is often not the owner of the machine running its PM (a teammate's Mac Studio, a Harness
+ Team account). Change agent is refused for them (`OWNER_REQUIRED`, `services/handoffRequest.ts:19`).
+
+## Goal
+
+A person who may manage a project can move its PM to another engine **or another account on the same machine** in one
+action, from the project's menu or from the limit line, whoever owns that machine. The PM stays the same Swarm agent.
+
+## Decisions (Diego, 11-02)
+
+- Manual, one button (option B). No automatic switch on a limit.
+- "Another account" means another sign-in **on the same machine** (option a). Moving the PM to another machine is out of
+ scope.
+
+## Scope
+
+1. **Claude profiles.** A machine lists, links and launches several Claude accounts, each a `CLAUDE_CONFIG_DIR` folder, the
+ way it does Codex profiles. It finds Orca's profiles (`~/Library/Application Support/orca/claude-profiles/*/home`).
+ Adding one opens a pane running `claude` with the new folder, where the person signs in with `/login`. Harness never
+ reads or stores a token except to read usage, as it already does for the default account.
+2. **Usage per profile.** Each Claude and Codex profile gets its own usage reading (remaining percent of its tightest
+ window).
+3. **Change agent picks engine and profile.** The picker lists `Claude · <profile> (12% left)` and `Codex · <profile>` rows.
+ A switch to another profile of the same engine is allowed.
+4. **Switch PM from the Swarm.** A new backend command asks the PM's host to switch. The host runs the same steps Desktop's
+ Change agent runs, over its own local daemon socket, and #2493's guards apply unchanged.
+5. **Limit line with an action.** When the PM hits a limit, its line says so in local time and offers **Switch PM…**. The
+ project's ⋮ menu also has **Switch PM…**.
+
+## Non-goals
+
+- Automatic switching on a limit.
+- Moving the PM to another machine.
+- Keeping the whole native conversation across a switch. Every switch, including Claude to Claude on another account,
+ uses #2493's handoff file: the new session starts fresh and reads it. The Swarm's state (tasks, groups, chat, decisions)
+ lives on the backend and is not affected. Resuming the same Claude conversation in another account (copy the transcript
+ into the other `CLAUDE_CONFIG_DIR`, then `claude --resume`) is a follow-up, to be tried as a spike first: the other
+ account also needs its own folder trust, settings and hooks, and per-project memory does not follow.
+- The phone. It gets the same menu item and limit button in a follow-up.
+- Switching a Builder or a Reviewer from the Swarm. Change agent already works on their panes for the machine owner.
+
+## Design
+
+### 1. Claude profiles on the machine (CLI)
+
+- `cli/src/lib/claudeProfiles.ts` mirrors `codexProfiles.ts`: `listClaudeProfiles(observed)`, `linkClaudeProfile(path)`,
+ `resolveClaudeProfilePath(path)`, persisted as `claude-profiles.json` (paths only, 0600, atomic, at most 256).
+ - A folder counts when it holds `.claude.json` or `settings.json`.
+ - Discovery: an inherited `CLAUDE_CONFIG_DIR`, conventional `~/.claude-*` folders, and Orca's
+ `claude-profiles/*/home`, and the folders Desktop's "Add Claude account…" makes under `~/.harness/claude-profiles/`.
+ The default account (no `CLAUDE_CONFIG_DIR`) is always the first row, marked `default: true`.
+ - Local label (the owner's own windows): the account's `displayName`, else the folder name. Reported label (leaves the
+ machine): from the folder only, never a name or email: the folder name, `Orca <first 4 of the uuid>` for Orca's `home`,
+ `Claude <n>` for Harness's own folders.
+ - **Offered** (owner's consent; both security reviews of #2528): a row is `offered` when it is the default account or the
+ owner offered it by name (`swarm_account_offer {engine, path, offered}`, `lib/accountOffers.ts`). Linking a folder, Add
+ Claude account and using an account in Change agent never offer it. Only offered accounts are reported to the Swarm (see 5).
+ A withdraw drops it from the next report, and a switch on its way finds it gone; a PM already on it stays until moved.
+- RPCs `claude_profiles_list {observedPaths}` and `claude_profile_link {path}` sit beside the Codex pair in
+ `services/models.ts` `launchTargetRequests` and in `core/api.ts` `MODELS_REQUESTS`. They stay off the E2EE type lists
+ (`lib/e2ee/core.ts` is pinned by the interop keystone and is not edited for this work), so they serve the machine's own
+ windows and its host; a relayed window does not list another machine's accounts. Both answer the machine owner only (`OWNER_REQUIRED`), and so do
+ the Codex pair from now on: they disclose folder paths.
+- Every profile has an opaque `id`: the first 16 hex of sha256(`<machine id>:<engine>:<realpath>`); the default account's id
+ is sha256(`<machine id>:<engine>:default`)[0..16]. The CLI, the backend and Desktop compute the same value and each pins the
+ vector `('m', 'claude') -> 71dc90339553114c`. Only the machine maps an id back to a folder. The path given to Claude Code
+ (and hashed for its Keychain item) is the folder as linked, not its realpath.
+
+### 2. Starting Claude in a profile (CLI)
+
+- `agent_create` takes `claudeHome`, validated as `codexHome` is (`core/agents/launches.ts:375-386`): absolute, at most
+ 4096 characters, no control characters, engine `claude`, no grid, and a listed non-default Claude profile of this machine
+ or a folder under `~/.harness/claude-profiles/`; otherwise `INVALID_CLAUDE_HOME`. A default account is started with no
+ `claudeHome` / `codexHome`.
+- It travels on the `CreateAgent` input to the native launch, which already maps `NativeLaunchSource.claudeHome` to
+ `CLAUDE_CONFIG_DIR` and installs the hooks there (`engines/nativeLaunch.ts:141-143`, `:210`).
+- The registry row keeps it (`RegisteredSession.claudeHome`, as `hermesHome`), so restart, resume and the PM's rollback
+ relaunch in the same account. It joins the launch-authority fingerprint (`core/agents/launchAuthority.ts`) and the agent
+ frame (`lib/agentFrame.ts`).
+- The native launch adopts an explicit `claudeHome` into the machine's known homes (`confirmHome`, today called only for
+ the implicit home at `nativeLaunch.ts:218`), so the session's transcript is inside the transcript roots and binds.
+- `launchHomeOf` (`lib/engineHomes.ts:370-374`) honours `profile` for variable homes, so folder trust (`.claude.json`) and
+ `settings.json` writes go to the profile.
+- A Harness Team account keeps its own rule for a Codex PM (`pmEngineHome`, `superTabs/start.ts:425-430`); a switch on a
+ Team daemon offers its default account only.
+
+### 3. Usage per profile (CLI)
+
+- `readAccountUsage` takes an optional `claudeHome` or `codexHome`:
+ - Claude: Keychain service `Claude Code-credentials-<sha256(dir)[0..8]>` with `-a <$USER or claude-code-user>`
+ (the rule Desktop already has in `desktop/lib/usage/usage_credentials.dart:56-91`); file fallback
+ `<dir>/.credentials.json`; account from `<dir>/.claude.json`.
+ - Codex: `<dir>/auth.json`.
+ - The default reading also passes `-a`, which fixes the stale Keychain item the CLI can read today.
+- `usage_read` accepts an optional `{ profile: { engine, id } }`. Without it the answer is unchanged (old clients).
+- Profile readings share the Anthropic throttle the machine report already respects: at most one read per profile per
+ `USAGE_FRESH_MS`, and at most 8 profiles per engine.
+
+### 4. Change agent with a profile (Desktop)
+
+- The picker's engine rows (`desktop/lib/state/swarm_search.dart` `_filter`, ~:1959-1993) become one row per
+ `(engine, profile)` on the pane's machine, read with `claude_profiles_list` / `codex_profiles_list` and `usage_read`:
+ `Claude · Work (12% left)`. A machine with one account shows today's rows.
+- `SwarmDestination` carries `agentProfile` beside `agentEngine` (`swarm_navigation.dart`). `_AgentChange` carries the
+ chosen profile (`app_state.dart:271`).
+- `changeAgent` compares `(engine, profile)`, not the engine alone (`app_state.dart:17262`), so a move to another account of
+ the same engine runs.
+- `_changeAgent` passes `claudeHome` / `codexHome` to `createAgent` (`:17506`). The handoff request is unchanged: the
+ handoff file does not depend on the account, and `leadSwitch.ts` reads only `targetEngine` from its receipt.
+- "Add Claude account…" at the end of the Claude rows opens a pane on the same machine running `claude` with a new
+ `CLAUDE_CONFIG_DIR` under `~/.harness/claude-profiles/<n>` (the next free `n`, one add at a time) and says "Run /login,
+ then pick it again". The CLI finds that folder by itself once Claude has created it.
+- Change agent asks for accounts only on this computer's own panes (the list RPCs are local only). A Swarm Buddy's pane offers
+ no engine or account change ("A Buddy keeps its engine for now"). Rows not offered to the Swarm say "Not offered to the Swarm";
+ picking one runs this pane on it and offers nothing. "Swarm accounts…" opens the one place to offer or withdraw, which says who
+ can then spend the account.
+
+### 5. The machine reports its profiles (CLI → backend)
+
+- The machine report gains `profiles: [{ engine, id, label, leftPercent, resetsAt }]`, at most 16, beside `readiness`:
+ the **offered** accounts only (see 1), the default one of each engine included. A Team daemon reports its default accounts
+ only. `label` is the reported label, at most 40 characters, never containing `@`. No path, email, account id or plan is
+ sent. It is sent only to a backend that asks for capabilities.
+- The backend's `machineObservationSchema` accepts it (strict, capped). `storedObservation` keeps it for contributed engines
+ only, and serves it only to people who may switch a PM on that machine (its owner, owners of projects whose PM runs there);
+ everyone else and every agent gets the reading without it. An old backend refuses the field and the CLI drops it through
+ the existing `sendAlone` chain.
+- The CLI advertises a `leadSwitch` capability (`machines.ts` `CAPABILITIES`), which the backend requires before it sends a
+ switch, as `leadStart` is today.
+
+### 6. Switch PM (backend)
+
+- New person command `lead.switch { projectId, engine, profileId, model?, effort? }`.
+ - Allowed for the project's owner (`manageProject`, as `lead.start`) and for the real owner of the machine running the PM
+ (`machineOwnerId`; a borrower of a lent machine is not its owner).
+ - A literal `'default'` profileId means the default id of the requested engine. The agent's `profileId` is absent for a
+ default account.
+ - Refused when: the project has no running PM (`NO_LEAD`); the PM's machine is offline (`MACHINE_OFFLINE`); its host lacks `leadSwitch`
+ (`HOST_OUTDATED`); a switch is already pending (`LEAD_SWITCHING`); `profileId` is not in that machine's reported
+ profiles for `engine` (`PROFILE_UNKNOWN`); the engine is not offered on that machine (`ENGINE_NOT_OFFERED`).
+ - It is allowed while the Swarm is paused: it starts no new work.
+- It sets `switchRequest = { id: operationId, engine, profileId, model, effort, requestedBy, at }` on the PM's agent row.
+ The row already reaches its host (`read/hostRows.ts:77`).
+- `agent.switchClaim { agentId, switchId }`: the host claims it (actor must be that agent), as `agent.stopLease` does.
+ Answers `{ leaseId, expiresAt }` (15 minutes, covering #2493's 3 + 10 minute limits).
+- `agent.switchResult { agentId, switchId, ok, error? }`: the host reports the end. It clears `switchRequest` and writes one
+ line in the project's PM chat: "PM moved to Codex · Work." or "Couldn't switch the PM: <error>. It is back on Claude."
+- `agent.rebind` takes an optional `profileId` (what actually started; an old backend refuses the field and the CLI resends
+ once without it). It clears `switchRequest` (remembering it as landed, so exactly one result line is written), and clears
+ `limitedUntil` and the `limit` alert only when the engine or the normalized account changed.
+- When a switch lands on a non-default account and the person who asked is not the machine's owner, the owner gets one line
+ in their Buddy chat: `<requester> moved the PM of <project> on <machine> to your <Engine> account "<label>".`
+- An unclaimed request older than 2 minutes, or a claim whose lease ran out with no result, is dropped by the liveness
+ sweep that runs on any machine's report (`staleSwitches`, `backend/src/superTabs/tidy.ts`) with the line "Couldn't switch
+ the PM: its machine did not answer." An expired request cannot be claimed.
+
+### 7. Switch PM (host)
+
+- `cli/src/superTabs/leadSwitchRequest.ts` serves the PM rows of this machine whose agent has a `switchRequest`:
+ 1. claim it (`agent.switchClaim`);
+ 2. map `profileId` to a folder with the profile lists (refuse `PROFILE_UNKNOWN` if it is gone);
+ 3. over the local daemon socket (which is the machine owner, `backendSocket.ts:1024`), with a fresh 32-hex `changeId`:
+ `agent_handoff_prepare { agentId, changeId, targetEngine }`, then `agent_close { mode: 'now', changeId }`, then
+ `agent_create { engine, cwd, creationId: changeId, claudeHome | codexHome, model, effort, the old PM's Swarm role, skill
+ and GitHub fields, startedBy: 'agent', prompt: <the Lead start prompt, then the handoff> }` (the PM comes back as a
+ Swarm PM, exactly as its first start made it), then `agent_handoff_complete`;
+ Before the close it refuses an account that is not offered or not signed in, and an old PM with no saved Swarm skill.
+ 4. report `agent.switchResult`. Success is when `agent.rebind` lands for that agent; failure is any refused step, or
+ #2493's rollback reopening the old PM.
+- #2493's `leadSwitch.ts` guards are unchanged. The host's own handoff receipt is what lets the close through.
+- One switch per PM at a time (the run is recorded before the claim); a restart mid-switch follows #2493's record instead of
+ running again. A Team daemon allows the default account only, and a Codex PM there keeps its own engine home (`pmEngineHome`).
+- Result errors are fixed phrases, never paths or raw errors.
+
+### 8. Where people see it (Desktop)
+
+- Project ⋮ menu (`desktop/lib/super_tabs/view.dart` `_options`, ~:2401): **Switch PM…** for whoever may switch (see 6),
+ shown while the project has a PM.
+- The PM's limit line (`SuperTabTerminalRow`, `view.dart` ~:2686): the backend writes "<PM> hit a usage limit." with
+ `source.limitedUntil`; Desktop shows "until 2:00 PM" in local time, and **Switch PM…** while the PM's `alerting` still has
+ `limit` (the pattern of `answeredPromptAlerts`).
+- The Switch PM dialog lists the PM machine's reported profiles: engine, label, `% left` and reset time, the current one
+ marked, the ones at 0% shown but not selectable. Below the list: "The new session starts fresh and reads a handoff note.
+ Tasks and chat stay." When the reader does not own that machine: "Only accounts its owner offered are listed." Confirm
+ sends `lead.switch`. While it runs, the PM row shows "Switching…".
+
+## Design checklist (docs/feature-design-rules.md)
+
+- **Growth:** `claude-profiles.json` is capped at 256 paths, the report at 16 profiles, `switchRequest` is one field per PM
+ cleared on result or rebind. The handoff files are #2493's.
+- **Concurrency:** one switch per PM, enforced by the backend (`LEAD_SWITCHING`) and by the host's #2493 record. The command
+ writes only the PM's agent row in the Swarm's state transaction.
+- **Read cost:** profiles ride the existing machine report (every 15 s heartbeat, unchanged size class). Usage per profile
+ is throttled per profile. No new poll.
+- **Scale:** 10x profiles per machine is capped at 16 reported; the warning metric is Anthropic 429s on usage reads, already
+ logged by `machines.ts`.
+- **Compatibility:** an old host never gets a switch (`leadSwitch` capability). An old backend refuses `profiles` and the
+ CLI drops it. An old Desktop ignores the new fields and the new command. `usage_read` without a payload answers as today.
+- **Migration and rollback:** no data migration. Rolling back the backend leaves `switchRequest` unread; rolling back the
+ CLI leaves `claude-profiles.json` unused. A failed switch reopens the old PM (#2493).
+- **Audience:** the backend checks who may switch. Profile ids are opaque; paths stay on the machine; the list RPCs answer
+ the machine owner only.
+- **Identity:** the PM runs in the account the person chose on that machine, never the project owner's own login. The
+ switch is done by the machine's own daemon, as Change agent is.
+- **Failure:** every refusal and every rollback is a line in the PM chat. A profile that lost its sign-in reads as
+ "signed out" in the dialog and cannot be picked.
+- **Platforms:** Claude profiles' Keychain rule is macOS; Linux uses `<dir>/.credentials.json`. Windows: the same file rule,
+ untested, not offered until tested.
+
+## Testing
+
+- CLI: `claudeProfiles` list/link/discover (Orca layout, label rules, no email in the reported label); `agent_create` with
+ `claudeHome` sets `CLAUDE_CONFIG_DIR`, writes trust into the profile and binds the transcript; `readAccountUsage` per
+ profile (suffixed Keychain service, `-a`); the host's switch request end to end against a fake backend (claim, the four
+ daemon calls with one `changeId`, result on rebind, result on rollback).
+- Backend: `lead.switch` permissions and refusals; `switchClaim` / `switchResult`; `agent.rebind` clears the request and the
+ limit; the limit line for a PM; the stale request pass.
+- Desktop: picker rows per profile; a same-engine profile change runs; the ⋮ item and the limit button show for the right
+ people and hide once the limit ends; the dialog sends `lead.switch`.
+- One manual run on Diego's Mac: a PM on the default Claude account switched to his Orca Claude account, then to Codex, then
+ back, from the Swarm menu.
diff --git a/docs/swarms.md b/docs/swarms.md
index cba292766..607348f2d 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -247,7 +247,7 @@ Buddies are on in every Swarm; there is no setting. They replaced Chat with PM (
on the desktop puts the dial back on what the desktop shows. A project without a Buddy shows "No Buddy here yet". Tap
to talk works on both screens: on the Buddy screen the words go to the Buddy chat, with the Buddy's engine
listening, and a refused post shows as an error on the dial, never as words in a terminal. A new line from the
- Buddy is quiet: no beep and no inbox entry, only a lilac badge on the lower dot and "Your Buddy replied", until you
+ Buddy is quiet: no beep and no inbox entry, only the lower dot turning lilac and "Your Buddy replied", until you
open the Buddy screen.
- **The product manager's lines to one person.** What the product manager tells one person directly goes to that
person's Buddy chat in the project (a line it sends with `person.tell`, and the line saying what it chose for a
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 947be28f3..5db4ecd94 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -154,6 +154,10 @@ class SuperTabAgent {
alerting = List.unmodifiable(
(row['alerting'] as List?)?.whereType<String>() ?? const <String>[],
),
+ switchRequest = row['switchRequest'] is Map
+ ? Map.unmodifiable(superTabMap(row['switchRequest']))
+ : null,
+ profileId = row['profileId'] as String?,
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),
workDecision = switch (row['workDecision']) {
@@ -183,6 +187,16 @@ 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`), as the desktop's model reads
+ /// it; null otherwise. Not drawn on the phone yet.
+ final Map<String, dynamic>? switchRequest;
+
+ /// The account on its machine it runs in; `default` when none is chosen.
+ /// Null until the backend reports it: the engine's default account. As the
+ /// desktop's model reads it; not drawn on the phone yet.
+ final String? profileId;
+
/// Since when its machine has reported its session gone, or its host confirmed a stop (backend machines.ts). Null
/// while it runs.
final DateTime? downSince;