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-05 i1650: #3148 #3137 #3138 #3142 (#3155)

0xken158704f62c4805
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 1a772fc36..f31b23694 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -13,6 +13,7 @@ import { modelMatches } from './rules.js'
import { appendRouting, instructionsHash } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
import { DEFAULT_ROUTING_POLICY, effectivePolicy } from './routingPolicy.js'
+import { LEAD_CAPABILITY, leadHost } from './leadStart.js'
import { NOW, owner as richOwner, peer as richPeer, richSwarm } from './read/fixture.test-support.js'
import { groupView } from './read/views.js'
import { weekStart } from './leaderboard/week.js'
@@ -3494,6 +3495,25 @@ describe('machine.remove', () => {
requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as never]
}
+ // Task #3212: Desktop's join add leaves out a computer its person took out of the Swarm, reading this record; Add machine
+ // brings it back. The record is per Swarm, person and computer, and only that person reads it.
+ it('remembers a machine its person took out, only for them, until they add it again', () => {
+ const f = fixture()
+ f.invite()
+ contribute(f, 'peer', 'peer-mac', null)
+ f.run({ type: 'machine.remove', machineId: 'peer-mac' }, peer)
+ expect(f.state.removedMachines).toEqual([{ machineId: 'peer-mac', contributorId: 'peer' }])
+ expect(visibleState(f.state, peer).removedMachines).toEqual(['peer-mac'])
+ expect(visibleState(f.state, owner).removedMachines).toBeUndefined()
+
+ for (const cleanup of f.state.machineCleanups ?? []) cleanup.requestedAt = new Date(-60 * 60_000).toISOString()
+ f.run({ type: 'machine.contribute', machineId: 'peer-mac', name: 'Peer Mac', cwd: '/repo', scope: 'swarm', engines: ['claude'], maxAgents: 2,
+ teamAccountOnly: true }, peer, { contribution: { machineOwnerId: 'peer', contributorId: 'peer', hostGrant: null } })
+ expect(f.state.machines!.some(m => m.machineId === 'peer-mac' && !m.removal)).toBe(true)
+ expect(f.state.removedMachines).toBeUndefined()
+ expect(visibleState(f.state, peer).removedMachines).toBeUndefined()
+ })
+
// The phone and the web offer Pause/Resume only to the person who lent the machine; the server holds the same line.
it('lets only the contributor pause or resume a machine', () => {
const f = fixture()
@@ -6132,3 +6152,47 @@ describe('agent.rename (renaming a harness renames its agent, task #2912)', () =
expect(removed).toEqual(['github'])
})
})
+
+// Task #3211 (vie, 11-05): a project whose lead started in a folder with no GitHub origin has nothing to clone, so its work
+// starts on other machines in an empty folder of its own, without a worktree; a project with a repository keeps today's rule.
+describe('a start for a project with no repository', () => {
+ const pool = (machineId: string) => ({ machineId, name: machineId, contributorId: 'owner', membershipGeneration: 'pilot', generation: 'g1',
+ cwd: '/data/swarm-projects/tab', scope: 'swarm' as const, engines: ['claude'], maxAgents: 4, paused: false,
+ observation: { generation: 'g1', receivedAt: 1000, capabilities: [LEAD_CAPABILITY], 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 setUp = (repositoryUrl: string | null) => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group()
+ f.state.machines = [{ ...pool('source'), membershipGeneration: f.state.people[0]!.generation }, { ...pool('other'), membershipGeneration: f.state.people[0]!.generation }]
+ f.state.projects![0]!.repository = { machineId: 'source', cwd: '/Users/vie/outreach', repositoryUrl }
+ return { f, lead, group }
+ }
+ const start = (repositoryUrl: string | null, machineId: string, cwd: string) => {
+ const { f, lead, group } = setUp(repositoryUrl)
+ const actor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }
+ const request = { conversationId: group, machineId, engine: 'claude', name: 'Writer', cwd, worktree: true, branchRef: 'refs/remotes/origin/main',
+ requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: [], devices: [], quotaRequired: false } }
+ f.run({ type: 'agent.start', request, ...via } as Command, actor, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' }, ...decisionIn(group) })
+ return f.state.starts!.at(-1)!.request
+ }
+
+ it('starts on another machine in the project\'s own folder there, without a worktree', () => {
+ const request = start(null, 'other', '/data/swarm-projects/tab/lead')
+ expect(request).toMatchObject({ machineId: 'other', cwd: '/data/swarm-projects/tab/lead', worktree: false })
+ expect(request.branchRef).toBeUndefined()
+ })
+
+ it('keeps a worktree on the machine whose folder it started in, and wherever it has a repository', () => {
+ expect(start(null, 'source', '/Users/vie/outreach')).toMatchObject({ worktree: true, branchRef: 'refs/remotes/origin/main' })
+ expect(start('https://github.com/vie/outreach', 'other', '/data/swarm-projects/tab/lead')).toMatchObject({ worktree: true, branchRef: 'refs/remotes/origin/main' })
+ })
+
+ it('starts its Product Manager on another machine without a worktree too', () => {
+ const { f } = setUp(null)
+ const project = f.state.projects![0]!
+ const leadFor = { projectId: project.id, personId: 'owner', generation: f.state.people[0]!.generation }
+ expect(leadHost(f.state, project, 'other', { engine: 'claude' }, leadFor, { now: 1000 })).toMatchObject({ cwd: '/data/swarm-projects/tab/lead', worktree: false })
+ f.state.projects![0]!.repository!.repositoryUrl = 'https://github.com/vie/outreach'
+ expect(leadHost(f.state, project, 'other', { engine: 'claude' }, leadFor, { now: 1000 })).toMatchObject({ worktree: true })
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index c757a3217..d41dbb6e8 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,6 +1,6 @@
import { applyPushOrigin, failPushUnknown, failTeamWritten, hasStep, mainAccountMembers, markTeamWritten, mayName, requireNameable, requireTeamWrittenAccount, requireTeamWrittenMachine, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
import type { PushOrigin } from '../github/pushOrigin.js'
-import { admitByRoom, admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machineLimitReached, MACHINE_LIMIT_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, movedToTeamAccount, type ContributedMachine } from './machines.js'
+import { admitByRoom, admitMachineStart, noRepositoryStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machineLimitReached, MACHINE_LIMIT_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, movedToTeamAccount, type ContributedMachine } from './machines.js'
import { movableEntry } from './computerMoves.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
import { addedAgentName, renameAgentTo } from './agentRename.js'
@@ -2540,7 +2540,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (written) requireTeamWrittenMachine(state, startGroup, moved.machineId)
// A branch GitHub cannot place stays out of the main account too, unmarked, as it may yet read clean.
else if (context.pushOrigin === 'unknown' && !teamAccountPool(state.machines?.find(m => m.machineId === moved.machineId))) failPushUnknown()
- const request: AgentStartRequest = written ? { ...moved, projectSettings: 'off' } : moved
+ const request: AgentStartRequest = noRepositoryStart(state.machines?.find(m => m.machineId === moved.machineId), home,
+ written ? { ...moved, projectSettings: 'off' } : moved)
const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)
// Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).
if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
diff --git a/backend/src/superTabs/leadStart.ts b/backend/src/superTabs/leadStart.ts
index 74bb9004a..938219c02 100644
--- a/backend/src/superTabs/leadStart.ts
+++ b/backend/src/superTabs/leadStart.ts
@@ -5,7 +5,7 @@
* names the machine: only they know which one stays on (Ken, 10-29). Desktop's own-machine flow (project.create, a local
* start, agent.add) is unchanged. */
import { admitMachineStart, contributedEngines, failTeamWork, machineContribution, projectFolder, projectsOnMachine, teamAccountPool, teamPoolOf,
- slotCounter, teamWorkRefusal, ownAccountWork, type ContributedMachine } from './machines.js'
+ noRepositoryStart, slotCounter, teamWorkRefusal, ownAccountWork, type ContributedMachine } from './machines.js'
import { actorKey, fail, person, SuperTabError, type AgentStart, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'
import { BUILT_IN_ROLE_DEFAULTS, ownsProject, projectsOf, type SwarmProject } from './projects.js'
import { failureNotice, publicReason } from './startFailure.js'
@@ -89,7 +89,7 @@ export function leadHost(state: SuperTabState, project: SwarmProject, machineId:
const listed = state.machines?.find(m => m.machineId === machineId)
if (listed && !state.people.some(p => p.id === listed.contributorId)) fail('CONTRIBUTION_REVOKED', 'This machine contribution was withdrawn.', 403)
const named = machineContribution(state, machineId) ?? fail('MACHINE_NOT_LISTED', 'Add this machine to the Swarm first.', 403)
- const startIn = (pool: ContributedMachine): AgentStartRequest => ({ conversationId: project.leadConversationId, machineId: pool.machineId,
+ const startIn = (pool: ContributedMachine): AgentStartRequest => noRepositoryStart(pool, project, { conversationId: project.leadConversationId, machineId: pool.machineId,
engine: request.engine, ...(request.model ? { model: request.model } : {}), ...(request.effort ? { effort: request.effort } : {}), name: coordinatorNameOf(project),
cwd: projectFolder(pool, project), worktree: true, ...(request.branchRef ? { branchRef: request.branchRef } : {}), requirements: LEAD_REQUIREMENTS, leadFor })
const teamMachines = context.teamMachines ?? []
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index ec1099e1e..4547fd76b 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -550,6 +550,18 @@ export function projectFolder(pool: ContributedMachine, project: SwarmProject):
: pool.cwd
}
+/** [request] as [pool] can carry it out for [project]: a project whose folder is recorded without a repository address has
+ * nothing to clone or branch from on any machine but the one that folder is on, so elsewhere it starts in the project's own
+ * empty folder without a worktree (task #3211); its host makes that folder (cli superTabs/projectFolder.ts). A project with
+ * no folder recorded yet is left alone: its first start records one. Any other start is unchanged. */
+export function noRepositoryStart(pool: ContributedMachine | undefined, project: SwarmProject | undefined, request: AgentStartRequest): AgentStartRequest {
+ const repository = project?.repository
+ if (!pool || pool.scope !== 'swarm' || !repository || repository.repositoryUrl || repository.machineId === pool.machineId) return request
+ if (!request.worktree && !request.branchRef) return request
+ const { branchRef: _branchRef, ...rest } = request
+ return { ...rest, worktree: false }
+}
+
/** What a host reports (`capabilities`) when it runs a Swarm-wide Buddy in its folder of project worktrees (Dee, 10-31). */
export const SWARM_BUDDY_CAPABILITY = 'swarmBuddy'
/** At most this many projects' worktrees in a Swarm-wide Buddy's folder (spec: Staying within one context). */
@@ -701,7 +713,7 @@ export function removalPreview(state: SuperTabState, actor: Actor, machineId: st
...(task ? { task: task.title } : {}) }
}),
hiddenAgentCount: members.length - visibleAgents.length,
- // Their code is only on this machine: no other machine can start agents for them until someone shares a repository.
+ // Their code is only on this machine: agents elsewhere start in an empty folder until someone shares a repository (#3211).
soleSourceProjects: visibleSoleSourceProjects.map(p => ({ id: p.id, name: p.name })),
hiddenSoleSourceProjectCount: soleSourceProjects.length - visibleSoleSourceProjects.length,
}
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index eca813da1..8e59623c7 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -3495,7 +3495,7 @@ describe('adding this Mac\'s Harness Team account where this Mac was added', ()
await host.tick()
if (prepareTeam.mock.calls.length > tries) await vi.waitFor(() => expect(commands.length + log.mock.calls.length).toBeGreaterThan(heard))
}
- return { core, rows, commands, refusals, prepareTeam, prepare, log, pass }
+ return { core, host, rows, commands, refusals, prepareTeam, prepare, log, pass }
}
it('adds it once, prepared by its own daemon, with this Mac\'s name and slots', async () => {
@@ -3510,17 +3510,31 @@ describe('adding this Mac\'s Harness Team account where this Mac was added', ()
expect(t.prepareTeam).toHaveBeenCalledTimes(1)
})
- it.each(['MACHINES_FULL', 'MACHINE_LIMIT_PER_PERSON', 'OWNER_REQUIRED'])('stops after %s until the roster stops asking', async code => {
+ // Amon, 11-05 (#3215): after Repair his Mac read "joining" for good. A refusal stopped the join until the daemon restarted,
+ // and nothing on the row said why. Each is retried with the usual backoff: the roster stops asking when it no longer
+ // applies (backend hostRows.ts joinTeam, within the machine's room).
+ it.each(['MACHINES_FULL', 'MACHINE_LIMIT_PER_PERSON', 'OWNER_REQUIRED'])('retries after %s with the usual backoff, and says why', async code => {
const t = joining()
t.refusals.push(code)
await t.pass(0)
- await t.pass(24 * 60 * 60_000)
+ expect(t.host.teamJoinFailure()).toBe(`Refused: ${code}`)
+ await t.pass(59_000)
expect(t.prepareTeam).toHaveBeenCalledTimes(1)
- const row = t.rows.splice(0, 1)
- await t.pass(24 * 60 * 60_000 + 1)
- t.rows.unshift(...row)
- await t.pass(24 * 60 * 60_000 + 2)
+ await t.pass(60_000)
expect(t.prepareTeam).toHaveBeenCalledTimes(2)
+ expect(t.host.teamJoinFailure()).toBeNull()
+ })
+
+ it('tries again at once when its person asks (Retry on the row), not after the backoff', async () => {
+ const t = joining()
+ t.prepareTeam.mockRejectedValueOnce(new Error('That machine is not reachable now.'))
+ await t.pass(0)
+ expect(t.host.teamJoinFailure()).toBe('That machine is not reachable now.')
+ t.host.retryTeamJoins()
+ await t.pass(1_000)
+ expect(t.prepareTeam).toHaveBeenCalledTimes(2)
+ expect(t.commands).toHaveLength(1)
+ expect(t.host.teamJoinFailure()).toBeNull()
})
it('backs off while the team account cannot prepare (offline, signed out), and says why', async () => {
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index b141be83c..1794fecbe 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -479,7 +479,7 @@ export class SuperTabHost {
/** Per tab the roster marks, the add in progress or when the next may run. */
private readonly joins = new Map<string, { running: boolean; failures: number; retryAt: number }>()
/** This Mac's Harness Team account being added to a Swarm, by `tabId:machineId` (joinTeams). */
- private readonly teamJoins = new Map<string, { running: boolean; failures: number; retryAt: number }>()
+ private readonly teamJoins = new Map<string, { running: boolean; failures: number; retryAt: number; error?: string }>()
/** Each delivery's downloaded files, so input held by a busy terminal is not downloaded again on every retry. Only a
* complete download is kept: a failed one is tried again before the next delivery of the same message. */
private readonly files = new Map<string, { text: string; paths: string[] }>()
@@ -1795,14 +1795,28 @@ export class SuperTabHost {
type: 'machine.contribute', machineId: team.machineId, name: typeof team.name === 'string' && team.name ? team.name : this.core.account.machineName() ?? hostname(),
cwd: prepared.cwd, scope: 'swarm', engines: prepared.engines,
maxAgents: typeof team.maxAgents === 'number' ? team.maxAgents : prepared.maxAgents, ifMissing: true } })
- })().then(() => { join.failures = 0; join.retryAt = this.now() + JOIN_RETRY_MS }, error => {
- join.retryAt = error instanceof SuperTabHostError && JOIN_FINAL.has(error.code) ? Infinity
- : this.now() + Math.min(JOIN_RETRY_MAX_MS, JOIN_RETRY_MS * 2 ** join.failures++)
- this.log(`Could not add this Mac's Harness Team account to its Swarm: ${error instanceof Error ? error.message : String(error)}`)
+ })().then(() => { join.failures = 0; join.retryAt = this.now() + JOIN_RETRY_MS; delete join.error }, error => {
+ // Every refusal is tried again with the backoff, never for good (Amon, #3215: one stopped the join until a restart, and
+ // the row read "joining" with no reason). The roster stops asking once it no longer applies (backend hostRows.ts).
+ join.retryAt = this.now() + Math.min(JOIN_RETRY_MAX_MS, JOIN_RETRY_MS * 2 ** join.failures++)
+ join.error = error instanceof Error ? error.message : String(error)
+ this.log(`Could not add this Mac's Harness Team account to its Swarm: ${join.error}`)
}).finally(() => { join.running = false })
}
}
+ /** Why adding this Mac's Harness Team account to a Swarm last failed, while it still fails; null when none does: what this
+ * Mac's own row says instead of "joining" (service.ts teamJoinStatus). */
+ teamJoinFailure(): string | null {
+ for (const join of this.teamJoins.values()) if (join.error) return join.error
+ return null
+ }
+
+ /** Retry on the row: each Team account join that failed is tried on the next poll, not after its backoff. */
+ retryTeamJoins(): void {
+ for (const join of this.teamJoins.values()) if (join.error) join.retryAt = 0
+ }
+
/** Its owner removed this machine from a Swarm: the roster names the cleanup until this host acknowledges it, so a host
* that restarted part-way cleans again. Off the poll: deleting folders never delays deliveries. */
private cleanRemoved(rows: unknown[]): void {
diff --git a/cli/src/superTabs/projectFolder.spec.ts b/cli/src/superTabs/projectFolder.spec.ts
index da5519e9a..cd9133ee8 100644
--- a/cli/src/superTabs/projectFolder.spec.ts
+++ b/cli/src/superTabs/projectFolder.spec.ts
@@ -1,8 +1,11 @@
+import { execFileSync } from 'node:child_process'
+import { lstat, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { ProjectFolderError, RepositoryAccessError } from '../lib/projectFolder.js'
-import { PrepareRetryError, prepareSwarmProject, prepareSwarmStart, startGitHub } from './projectFolder.js'
+import { PrepareRetryError, prepareEmptyProjectFolder, prepareSwarmProject, prepareSwarmStart, startGitHub } from './projectFolder.js'
import { SuperTabHostError } from './wire.js'
function fixture() {
@@ -13,8 +16,9 @@ function fixture() {
projects: [{ id: 'project-a', repository, conversationIds: ['work'] }] }
const start = { dispatched: false, request: { conversationId: 'work', cwd: join(root, 'project-a') } }
const prepare = vi.fn(async () => start.request.cwd)
- return { core, root, repository, row, start, prepare,
- run: () => prepareSwarmProject(core, row, start, prepare) }
+ const empty = vi.fn(async (folderRoot: string, projectId: string) => join(folderRoot, projectId))
+ return { core, root, repository, row, start, prepare, empty,
+ run: () => prepareSwarmProject(core, row, start, prepare, undefined, undefined, empty) }
}
describe('per-project checkouts on a contributed swarm machine', () => {
@@ -59,12 +63,36 @@ describe('per-project checkouts on a contributed swarm machine', () => {
f.start.request.conversationId = 'unknown'
await expect(f.run()).rejects.toThrow('no authorized project')
})
- it('tells the lead how to share a project recorded without a repository address', async () => {
+ // Task #3211: a project recorded without a repository address has nothing to clone; its work runs here in its own empty folder.
+ it('starts a project with no repository in its own empty folder here, without cloning anything', async () => {
const f = fixture()
f.repository.repositoryUrl = null as unknown as string
- await expect(f.run()).rejects.toThrow(/Share a GitHub repository.*project\.repository command/)
+ await f.run()
+ expect(f.empty).toHaveBeenCalledExactlyOnceWith(f.root, 'project-a')
expect(f.prepare).not.toHaveBeenCalled()
})
+ it('refuses a worktree start of a project with no repository, and a folder that is not the project\'s', async () => {
+ const f = fixture()
+ f.repository.repositoryUrl = null as unknown as string
+ Object.assign(f.start.request, { worktree: true })
+ await expect(f.run()).rejects.toThrow(/no repository.*without a worktree/)
+ Object.assign(f.start.request, { worktree: false, cwd: join(f.root, 'project-b') })
+ await expect(f.run()).rejects.toThrow('outside this project')
+ Object.assign(f.start.request, { cwd: join(f.root, 'project-a') })
+ f.empty.mockResolvedValueOnce('/elsewhere')
+ await expect(f.run()).rejects.toThrow('does not match')
+ expect(f.empty).toHaveBeenCalledOnce()
+ expect(f.prepare).not.toHaveBeenCalled()
+ })
+ it('keeps cloning a project with a repository, and says to move aside a folder left from before it was shared', async () => {
+ const f = fixture()
+ await f.run()
+ expect(f.prepare).toHaveBeenCalledOnce()
+ expect(f.empty).not.toHaveBeenCalled()
+ f.prepare.mockRejectedValueOnce(new ProjectFolderError('PROJECT_EXISTS', '“project-a” already exists. Select that folder from your projects.'))
+ await expect(f.run()).rejects.toMatchObject({ code: 'PROJECT_EXISTS',
+ message: expect.stringMatching(/already has a folder for this project.*before its repository was shared.*Move it aside/) })
+ })
it('clones over SSH when GitHub refuses this machine over the shared HTTPS address, and the reverse', async () => {
const refused = () => new RepositoryAccessError('CLONE_FAILED', 'Could not access this repository.')
for (const [shared, first, second] of [
@@ -106,7 +134,7 @@ describe('per-project checkouts on a contributed swarm machine', () => {
})
it('refuses missing or unsafe repositories and a mismatched prepared checkout', async () => {
const f = fixture()
- for (const url of [undefined, 'file:///private/repo', 'https://[email protected]/example/project', 'ext::command']) {
+ for (const url of ['file:///private/repo', 'https://[email protected]/example/project', 'ext::command']) {
f.repository.repositoryUrl = url as string
await expect(f.run()).rejects.toThrow()
}
@@ -264,7 +292,9 @@ describe('preparing another person\'s start with the Harness GitHub App', () =>
await expect(f.ready()).rejects.toThrow("could not clone the project repository with the Harness GitHub App's token")
expect(f.prepare).toHaveBeenCalledTimes(1)
f.prepare.mockRejectedValueOnce(new ProjectFolderError('PROJECT_EXISTS', 'taken'))
- await expect(f.ready()).rejects.toThrow('taken')
+ // A folder already in the clone's place is named, with what to do (#3211), and not tried again either.
+ await expect(f.ready()).rejects.toMatchObject({ code: 'PROJECT_EXISTS', message: expect.stringContaining('Move it aside') })
+ expect(f.prepare).toHaveBeenCalledTimes(2)
})
// 11-05: six first starts on four machines failed on one failed or stalled clone, which GitHub or the network often serves seconds later.
@@ -336,3 +366,53 @@ describe('preparing another person\'s start with the Harness GitHub App', () =>
expect(await startGitHub(f.core, f.row, f.start, { backend: f.backend, team: false })).toEqual({ token: TOKEN, repository: 'example/project', requester: '[email protected]' })
})
})
+
+describe('a project\'s own empty folder, for a project with no repository (#3211)', () => {
+ const withRoot = async (body: (root: string) => Promise<void>) => {
+ const scratch = await realpath(await mkdtemp(join(tmpdir(), 'swarm-empty-folder-')))
+ try { await body(join(scratch, 'swarm-projects', 'tab')) } finally { await rm(scratch, { recursive: true, force: true }) }
+ }
+ it('makes it once, its owner\'s alone, as a git folder with no remote and no commit, and finds it again', async () => withRoot(async root => {
+ const folder = await prepareEmptyProjectFolder(root, 'project-a')
+ expect(folder).toBe(join(root, 'project-a'))
+ // Its owner's alone, as the work in it is (security review 1 of #3137, Minor).
+ expect((await lstat(folder)).mode & 0o777).toBe(0o700)
+ expect((await lstat(join(folder, '.git'))).isDirectory()).toBe(true)
+ expect(execFileSync('git', ['remote'], { cwd: folder, encoding: 'utf8' })).toBe('')
+ await writeFile(join(folder, 'notes.md'), 'kept')
+ expect(await prepareEmptyProjectFolder(root, 'project-a')).toBe(folder)
+ expect((await lstat(join(folder, 'notes.md'))).isFile()).toBe(true)
+ }))
+ it('refuses a link or a file where the folder goes, and never follows a link out of the Swarm\'s folder', async () => withRoot(async root => {
+ await mkdir(root, { recursive: true })
+ const outside = await mkdtemp(join(tmpdir(), 'swarm-outside-'))
+ try {
+ await symlink(outside, join(root, 'project-a'))
+ await expect(prepareEmptyProjectFolder(root, 'project-a')).rejects.toThrow(/not this project's own folder/)
+ await expect(lstat(join(outside, '.git'))).rejects.toMatchObject({ code: 'ENOENT' })
+ await writeFile(join(root, 'project-b'), 'a file')
+ await expect(prepareEmptyProjectFolder(root, 'project-b')).rejects.toThrow(/not this project's own folder/)
+ } finally { await rm(outside, { recursive: true, force: true }) }
+ }))
+})
+
+describe('preparing a start of a project with no repository (#3211)', () => {
+ it('asks for no GitHub token, on the owner\'s account or a Team account, as there is nothing to clone', async () => {
+ for (const team of [false, true]) {
+ const f = hosted()
+ f.repository.repositoryUrl = null as unknown as string
+ f.start.request.worktree = false
+ f.prepare.mockImplementation(async () => { throw new Error('nothing to clone') })
+ expect(await prepareSwarmStart(f.core, f.row, f.start, { backend: f.backend, team, prepare: f.prepare, fetch: f.fetch, revoke: f.revoke, empty: f.empty })).toBeNull()
+ expect(f.backend).not.toHaveBeenCalled()
+ expect(f.empty).toHaveBeenCalledExactlyOnceWith(f.root, 'project-a')
+ expect(f.fetch).not.toHaveBeenCalled()
+ }
+ })
+ it('still asks for a project with a repository', async () => {
+ const f = hosted()
+ await f.ready()
+ expect(f.backend).toHaveBeenCalledOnce()
+ expect(f.empty).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.ts
index 226a2ceff..ef82ed3b4 100644
--- a/cli/src/superTabs/projectFolder.ts
+++ b/cli/src/superTabs/projectFolder.ts
@@ -1,4 +1,7 @@
+import { execFile } from 'node:child_process'
+import { lstat, mkdir, realpath } from 'node:fs/promises'
import { isAbsolute, join, resolve } from 'node:path'
+import { promisify } from 'node:util'
import type { CoreApi } from '../core/api.js'
import { fetchStartBase } from '../lib/gitProject.js'
import { otherGitHubTransport, parseProjectFolder, prepareProjectFolder, ProjectFolderError, RepositoryAccessError } from '../lib/projectFolder.js'
@@ -74,16 +77,23 @@ async function revokeQuietly(token: string, revoke = revokeGitHubToken): Promise
*/
export async function prepareSwarmStart(core: CoreApi, row: Json, start: Json,
deps: { backend: Backend; team: boolean; prepare?: typeof prepareProjectFolder; fetch?: typeof fetchStartBase; revoke?: (token: string) => Promise<void>
- sleep?: (ms: number) => Promise<void> }):
+ empty?: typeof prepareEmptyProjectFolder; sleep?: (ms: number) => Promise<void> }):
Promise<{ requester: string } | null> {
const request = object(start.request)
// A person's one Buddy has no project: its launch makes its folder from the checkouts already here and fetches nothing
// (buddyHome.ts). Asking for a token anyway was refused with a 404, which failed every such start (2026-11-02).
if (request.buddyScope === 'swarm') return null
+ // Nor does a project with no repository address (task #3211): there is nothing to clone, and the server refuses a token
+ // for it. Its work starts in a folder of its own, made without any login (prepareSwarmProject).
+ const project = startProject(row, request)
+ if (project && typeof object(project.repository).repositoryUrl !== 'string') {
+ if (object(row.machine).scope === 'swarm') await prepareSwarmProject(core, row, start, deps.prepare, undefined, deps.sleep, deps.empty)
+ return null
+ }
const github = await startGitHub(core, row, start, deps)
const gitEnv = github ? swarmGitPrepareEnv(github.token) : undefined
try {
- if (object(row.machine).scope === 'swarm') await prepareSwarmProject(core, row, start, deps.prepare, gitEnv, deps.sleep)
+ if (object(row.machine).scope === 'swarm') await prepareSwarmProject(core, row, start, deps.prepare, gitEnv, deps.sleep, deps.empty)
if (gitEnv && request.worktree === true && typeof request.cwd === 'string' && isAbsolute(request.cwd)) {
// The branch the start names, when it names one: a project clone has only the default branch (lib/projectFolder.ts).
await (deps.fetch ?? fetchStartBase)(resolve(request.cwd), gitEnv, ...(typeof request.branchRef === 'string' ? [request.branchRef] : []))
@@ -102,17 +112,49 @@ function sameFolder(requested: unknown, folder: unknown): boolean {
return typeof requested === 'string' && typeof folder === 'string' && isAbsolute(requested) && resolve(requested) === resolve(folder)
}
+/** The project a queued start is for, of those this machine was told of. A project session of a person's one Buddy chat
+ * names its project: that chat is in no project's list (backend hostRows.ts). */
+function startProject(row: Json, request: Json): Json | undefined {
+ const session = object(request.buddySession).projectId
+ return (Array.isArray(row.projects) ? row.projects.map(object) : [])
+ .find(p => session ? p.id === session : Array.isArray(p.conversationIds) && p.conversationIds.includes(request.conversationId))
+}
+
+const NOT_OWN_FOLDER = 'This machine has something that is not this project\'s own folder where its folder goes. Its owner can move it aside, then start again.'
+
+/**
+ * [projectId]'s own folder in [root], a Swarm's folder of project checkouts, for a project with no repository (task #3211):
+ * made empty the first time, found again after. It is `git init`ed, with no remote and no commit, so the trust step that
+ * lets agents work in a Swarm's checkouts (cloneTrust.ts) takes it as it takes a clone, and its work can be committed
+ * there. Anything at that place that is not a plain folder there (a link, a file) is refused, never followed or replaced.
+ */
+export async function prepareEmptyProjectFolder(root: string, projectId: string,
+ init: (folder: string) => Promise<unknown> = folder => promisify(execFile)('git', ['init', '--quiet'], { cwd: folder, timeout: 15_000,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } })): Promise<string> {
+ await mkdir(root, { recursive: true })
+ const folder = join(root, projectId)
+ // Its owner's alone, as the work in it is (security review 1 of #3137).
+ await mkdir(folder, { mode: 0o700 }).catch(error => { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error })
+ const found = await lstat(folder)
+ if (!found.isDirectory() || await realpath(folder) !== join(await realpath(root), projectId)) throw new Error(NOT_OWN_FOLDER)
+ const git = await lstat(join(folder, '.git')).catch(error => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw error
+ })
+ if (!git) await init(folder)
+ else if (!git.isDirectory()) throw new Error(NOT_OWN_FOLDER)
+ return folder
+}
+
/** The owner granted a swarm workspace, not caller-selected filesystem paths.
- * Prepare the queued project's repository there before reserving or launching. */
+ * Prepare the queued project's repository there before reserving or launching: a clone, or for a project with no
+ * repository its own empty folder ([empty]). */
export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json, prepare = prepareProjectFolder, gitEnv?: NodeJS.ProcessEnv,
- sleep: (ms: number) => Promise<void> = ms => new Promise(done => setTimeout(done, ms))): Promise<void> {
+ sleep: (ms: number) => Promise<void> = ms => new Promise(done => setTimeout(done, ms)), empty = prepareEmptyProjectFolder): Promise<void> {
const pool = object(row.machine)
if (pool.scope !== 'swarm' || start.dispatched) return
const request = object(start.request)
- // A project session of a person's one Buddy chat names its project: that chat is in no project's list (backend hostRows.ts).
- const session = object(request.buddySession).projectId
- const project = (Array.isArray(row.projects) ? row.projects.map(object) : [])
- .find(p => session ? p.id === session : Array.isArray(p.conversationIds) && p.conversationIds.includes(request.conversationId))
+ const project = startProject(row, request)
if (!project || !identifier(project.id) || !identifier(row.tabId)) throw new Error('This start has no authorized project.')
const repository = object(project.repository)
const expectedRoot = swarmCloneRoot(core.dataDir, row.tabId, pool.cwd)
@@ -120,8 +162,14 @@ export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json,
if (repository.machineId === core.daemon.machineId() && sameFolder(request.cwd, repository.cwd)) return
const expected = join(expectedRoot, project.id)
if (!sameFolder(request.cwd, expected)) throw new Error('The requested folder is outside this project.')
- // The Lead reads this from the failed start; it can record its checkout's origin and start again.
- if (typeof repository.repositoryUrl !== 'string') throw new Error('Share a GitHub repository for this project before starting agents on another machine. Its lead can share its checkout\'s GitHub origin with the project.repository command, then start again.')
+ // Nothing to clone (task #3211): its own empty folder here, with no worktree, which has nothing to branch from. The
+ // backend starts it that way (machines.ts noRepositoryStart); an older one asks for a worktree, refused in words.
+ if (typeof repository.repositoryUrl !== 'string') {
+ if (request.worktree === true) throw new Error('This project has no repository, so its agents on other machines start in an empty folder without a worktree. Start again with worktree off, or share a GitHub repository for the project first.')
+ if (await empty(expectedRoot, project.id) !== expected) throw new Error('The prepared folder does not match the authorized project.')
+ await repairSwarmCloneTrust(core, row, typeof request.codexHome === 'string' ? request.codexHome : undefined)
+ return
+ }
const source = parseProjectFolder({ projectSource: 'remote', repositoryUrl: repository.repositoryUrl })
if (source?.source !== 'remote') throw new Error('This project repository is unavailable.')
let cwd: string
@@ -141,12 +189,14 @@ export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json,
cwd = await clone()
}
} catch (error) {
+ if (error instanceof ProjectFolderError && error.code === 'PROJECT_EXISTS') throw folderLeftBehind(expected)
if (!(error instanceof ProjectFolderError) || !['CLONE_FAILED', 'CLONE_TIMEOUT'].includes(error.code)) throw error
throw new ProjectFolderError(error.code, `This machine could not clone the project repository with the Harness GitHub App's token: ${error.message}`)
}
} else {
try { cwd = await prepare({ ...source, name: project.id }, { root: expectedRoot }) }
catch (error) {
+ if (error instanceof ProjectFolderError && error.code === 'PROJECT_EXISTS') throw folderLeftBehind(expected)
// The shared address names the repository, not how this machine signs in to GitHub: a credential helper for HTTPS,
// a key for SSH. Desktop shares HTTPS because the daemon's remote no longer says which one the lead used.
const other = error instanceof RepositoryAccessError ? otherGitHubTransport(source.repositoryUrl) : null
@@ -161,3 +211,10 @@ export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json,
if (cwd !== expected) throw new Error('The prepared checkout does not match the authorized project.')
await repairSwarmCloneTrust(core, row, typeof request.codexHome === 'string' ? request.codexHome : undefined)
}
+
+/** A folder in the place of a project's clone that is no clone of its repository: most likely the empty folder its work
+ * used here before its repository was shared (task #3211). Its files are the project's, so it is never removed here. */
+function folderLeftBehind(folder: string): ProjectFolderError {
+ return new ProjectFolderError('PROJECT_EXISTS', `This machine already has a folder for this project that is not a clone of its repository (${folder}), `
+ + 'probably one its agents used before its repository was shared. Move it aside so the repository can be cloned there, then start again.')
+}
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 3663d1f4b..a7abc49d7 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1256,6 +1256,54 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {
expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: false })
})
+ // Amon, 11-05 (#3215): his Mac's entry was moved into the Swarm by the server (backend computerMoves.ts), so this daemon kept
+ // no host record and never started its host: the Team account it should add sat "joining" for good, and nothing was sent.
+ it("starts its Swarm host when the server says one of its Swarms changed, though it keeps no host record", async () => {
+ const heard = new Set<(notice: never) => void>()
+ const start = vi.fn()
+ const core = fakeCore({ account: { onNotice: vi.fn(fn => { heard.add(fn as never); return () => { heard.delete(fn as never) } }) } })
+ const service = superTabService(core, { team: () => false, host: () => ({ machineId: 'machine-1', start, stop: vi.fn() }) as unknown as SuperTabHost })
+ service.port.connected()
+ expect(start).not.toHaveBeenCalled()
+ // The server's word that it pushes names no Swarm: it says nothing of this machine's.
+ for (const fn of heard) fn({ type: 'swarm_host_changed' } as never)
+ expect(start).not.toHaveBeenCalled()
+ for (const fn of heard) fn({ type: 'swarm_host_changed', tabId: 'tab', lastChangedAt: 1 } as never)
+ expect(start).toHaveBeenCalledOnce()
+ service.port.disconnected()
+ expect(heard.size).toBe(0)
+ })
+
+ it('Retry on the row starts a Swarm host that never ran, and the status says whether it runs', async () => {
+ const start = vi.fn(), retryTeamJoins = vi.fn()
+ const service = superTabService(fakeCore(), { team: () => false,
+ host: () => ({ machineId: 'machine-1', start, stop: vi.fn(), teamJoinFailure: () => null, retryTeamJoins }) as unknown as SuperTabHost })
+ expect(await service.requests.super_tabs({ action: 'teamJoinStatus' }, owner)).toEqual({ ok: true, failure: null, hostRunning: false })
+ expect(await service.requests.super_tabs({ action: 'teamJoinRetry' }, owner)).toEqual({ ok: true })
+ expect(start).toHaveBeenCalledOnce()
+ expect(retryTeamJoins).toHaveBeenCalledOnce()
+ expect(await service.requests.super_tabs({ action: 'teamJoinStatus' }, owner)).toEqual({ ok: true, failure: null, hostRunning: true })
+ })
+
+ // Amon, 11-05 (#3215): his row read "joining" while this host's join of the Team account kept failing, and only the log said
+ // why. This Mac's own Desktop reads the reason, and its Retry tries again at once.
+ it("tells this Mac's Desktop why its Team account has not joined, and retries at once when asked", async () => {
+ const retryTeamJoins = vi.fn()
+ const host = { machineId: 'machine-1', start: vi.fn(), stop: vi.fn(), teamJoinFailure: vi.fn(() => 'Refused: OWNER_REQUIRED'), retryTeamJoins }
+ const service = superTabService(fakeCore(), { host: () => host as unknown as SuperTabHost })
+ // A host that never ran has nothing to say, and is not started by asking.
+ expect(await service.requests.super_tabs({ action: 'teamJoinStatus' }, owner)).toEqual({ ok: true, failure: null, hostRunning: false })
+ await service.requests.super_tabs({ action: 'wake' }, owner)
+ expect(await service.requests.super_tabs({ action: 'teamJoinStatus' }, owner)).toEqual({ ok: true, failure: 'Refused: OWNER_REQUIRED', hostRunning: true })
+ expect(await service.requests.super_tabs({ action: 'teamJoinRetry' }, owner)).toEqual({ ok: true })
+ expect(retryTeamJoins).toHaveBeenCalledOnce()
+ for (const asker of [visitor, { local: false, owner: true, accountOwner: true }]) {
+ expect(await service.requests.super_tabs({ action: 'teamJoinStatus' }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(await service.requests.super_tabs({ action: 'teamJoinRetry' }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })
+ }
+ expect(retryTeamJoins).toHaveBeenCalledOnce()
+ })
+
it('tells only Desktop on this Mac why there is no account, asking nothing and starting nothing', async () => {
const offer = vi.fn(async () => ({ state: 'started' as const }))
const status = vi.fn(async () => ({ state: 'failed' as const, detail: 'launchd would not start it' }))
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index ad0d076fc..49103cd36 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -400,7 +400,9 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
;(options.teamNodeTools ?? (() => linkTeamNodeTools(realTeamNodeToolsDeps())))()
}
}
- const disconnect = () => { preparations.clear(); host?.stop(); host = null; held = null; book?.stop(); book = null; bookMachine = null; swarmCards?.want(false); swarmCards = null; cardsMachine = null; tokens.stop(); engines.stop() }
+ // The server's word that one of this machine's Swarms changed, heard while no host runs (Amon, #3215).
+ let hostWake: (() => void) | null = null
+ const disconnect = () => { hostWake?.(); hostWake = null; preparations.clear(); host?.stop(); host = null; held = null; book?.stop(); book = null; bookMachine = null; swarmCards?.want(false); swarmCards = null; cardsMachine = null; tokens.stop(); engines.stop() }
const port = {
connected: () => {
tokens.start()
@@ -412,6 +414,13 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
// check, so the Swarm read the account as offline and never sent it a teammate's work (third VM run).
if (identifier(core.daemon.machineId()) && (existsSync(hostJournalFile(core.dataDir, core.daemon.machineId()))
|| (options.team ?? (() => readAuthSession()?.kind === 'team'))())) wake()
+ // A machine can be in a Swarm without this daemon ever adding it (Amon, #3215: the server moved his computer's entry to his
+ // account, backend computerMoves.ts), so it keeps no host record and the check above never starts its host. The server says
+ // when one of this machine's Swarms changes, naming it: that starts the host. Its word that it pushes names none.
+ hostWake?.()
+ hostWake = core.account.onNotice(notice => {
+ if (!host && notice.type === 'swarm_host_changed' && identifier(notice.tabId) && identifier(core.daemon.machineId())) wake()
+ })
},
disconnected: disconnect,
stop: () => { disconnect(); void relay.stop() },
@@ -452,6 +461,15 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
// `teamSetupCheck` only says whether it is wanted, so Desktop explains it before macOS asks; `teamSetupDecline` is
// that explanation's "Not now". Both are new names, so an older daemon refuses them rather than asking unexplained.
// `teamSetupStatus`: why there is no account yet, for this Mac's own machine row (cancelled, failed and why, running).
+ // Why this Mac's Harness Team account has not joined a Swarm, while adding it fails (host.ts joinTeams), and Retry on the
+ // row (Amon, #3215: "joining" for good, the reason only in the log). Only a client on this computer asks, as for teamSetup.
+ // The status starts nothing; Retry starts the host if it never ran, which then reads its roster as any start does.
+ if (payload.action === 'teamJoinStatus' || payload.action === 'teamJoinRetry') {
+ if (!asker.local) return { error: 'OWNER_REQUIRED' }
+ // Retry starts a host that never ran (Amon, #3215): it then reads its Swarms in full, the Team account's join among them.
+ if (payload.action === 'teamJoinRetry') { wake().retryTeamJoins(); return { ok: true } }
+ return { ok: true, failure: host?.teamJoinFailure() ?? null, hostRunning: !!host }
+ }
if (payload.action === 'teamSetup' || payload.action === 'teamSetupCheck' || payload.action === 'teamSetupDecline'
|| payload.action === 'teamSetupStatus') {
if (!asker.local) return { error: 'OWNER_REQUIRED' }
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index f5238c09d..b155f840e 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2666,6 +2666,42 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Why this Mac's Harness Team account, signed in, has not joined a Swarm
+ /// yet (cli superTabs/service.ts `teamJoinStatus`, #3215): [failure], the
+ /// last refusal or error of this Mac's join, and [hostRunning], whether this
+ /// Mac's Swarm work runs at all. Null when it cannot say (a daemon too old).
+ Future<({String? failure, bool hostRunning})?> teamJoinStatus() async {
+ final here = _teamAccountHere();
+ if (here == null) return null;
+ try {
+ final answer = await superTabMachineRequest(here, {
+ 'action': 'teamJoinStatus',
+ });
+ final failure = answer['failure'];
+ final running = answer['hostRunning'];
+ if (running is! bool) return null;
+ return (
+ failure: failure is String ? failure : null,
+ hostRunning: running,
+ );
+ } catch (error) {
+ appLog.debug('super-tabs', 'team join status not read: $error');
+ return null;
+ }
+ }
+
+ /// Retry on this Mac's row: its Swarm work starts if it never ran, and the
+ /// Team account's join is tried at once (cli superTabs/service.ts).
+ Future<void> retryTeamJoin() async {
+ final here = _teamAccountHere();
+ if (here == null) return;
+ try {
+ await superTabMachineRequest(here, {'action': 'teamJoinRetry'});
+ } catch (error) {
+ appLog.debug('super-tabs', 'team join retry not sent: $error');
+ }
+ }
+
/// Why this Mac has no Harness Team account, as its own daemon remembers
/// it (cli/src/team/autoSetup.ts `status`): `{state: declined}` after a
/// cancel, `{state: failed, detail}`, `running`, `exists` or `none`. Null
diff --git a/desktop/lib/super_tabs/join_machine.dart b/desktop/lib/super_tabs/join_machine.dart
index 0266752c2..b0ad77eca 100644
--- a/desktop/lib/super_tabs/join_machine.dart
+++ b/desktop/lib/super_tabs/join_machine.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import '../core/machine_resources.dart';
+import '../core/models.dart' show sameMachineId;
import 'controller.dart';
/// What one more agent needs to start, the CLI's own figure
@@ -102,8 +103,9 @@ class SwarmJoinedMachine {
/// person's own projects.
///
/// Only a new collaborator's computer, in a Swarm that uses Harness Team
-/// accounts: a viewer, a computer already in the Swarm and a Swarm whose
-/// server does not try Team accounts yet are left as they are.
+/// accounts: a viewer, a computer already in the Swarm, one its person took
+/// out of it, and a Swarm whose server does not try Team accounts yet are left
+/// as they are.
class SwarmJoinMachine {
SwarmJoinMachine({
required this.machineRequest,
@@ -142,6 +144,12 @@ class SwarmJoinMachine {
final me = snapshot.people.where((p) => p.id == c.accountId).firstOrNull;
if (me?.role != 'collaborator') return null;
if (snapshot.machines.any((m) => m['machineId'] == machineId)) return null;
+ // Its person took it out, on any computer, a reinstall of this one
+ // included: it stays out until they add it with Add machine (backend
+ // commands.ts machine.remove; task #3212).
+ if (snapshot.removedMachines.any((id) => sameMachineId(id, machineId))) {
+ return null;
+ }
SwarmJoinedMachine note([String? problem]) => SwarmJoinedMachine(
tabId: c.tabId,
swarmName: snapshot.name,
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index ef39bb483..f5bab0f61 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -868,6 +868,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
/// ([AppNotifier.teamSetupStatus]), for its own row's line; null until read
/// or when it cannot say.
({String state, String? detail})? _teamSetup;
+
+ /// This Mac's daemon's word on why its Team account, signed in, has not
+ /// joined (#3215); null unless this Mac's own row reads joining.
+ ({String? failure, bool hostRunning})? _teamJoin;
bool _teamSetupReading = false;
/// This Mac's setup while it runs in the background (#3169), for its row's
@@ -1015,21 +1019,26 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
Future<void> _readTeamSetup() async {
final app = widget.app;
if (app == null || _teamSetupReading || !app.canSetUpTeamAccount) return;
- final own = c.snapshot?.machines.any(
- (m) =>
- m['contributorId'] == c.accountId &&
- app.stateOf(m['machineId'] as String)?.isLocalMachine == true &&
- (m['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_REQUIRED',
- );
- if (own != true) {
- _teamSetup = null;
- return;
- }
+ bool own(String code) =>
+ c.snapshot?.machines.any(
+ (m) =>
+ m['contributorId'] == c.accountId &&
+ app.stateOf(m['machineId'] as String)?.isLocalMachine == true &&
+ (m['teamWork'] as Map?)?['code'] == code,
+ ) ==
+ true;
+ final setup = own('TEAM_ACCOUNT_REQUIRED'),
+ joining = own('TEAM_ACCOUNT_JOINING');
+ if (!setup) _teamSetup = null;
+ if (!joining) _teamJoin = null;
+ if (!setup && !joining) return;
_teamSetupReading = true;
try {
- final read = await app.teamSetupStatus();
+ final read = setup ? await app.teamSetupStatus() : null;
+ final join = joining ? await app.teamJoinStatus() : null;
if (!mounted) return;
- _teamSetup = read;
+ if (setup) _teamSetup = read;
+ if (joining) _teamJoin = join;
// Running and nobody following it (the app opened while it ran, or it
// was started from a terminal): followed from here, so it ends in a
// notice too.
@@ -1573,6 +1582,19 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
app != null &&
app.canSetUpTeamAccount &&
app.stateOf(id)?.isLocalMachine == true;
+ // A Team account signed in but not joined (#3215): this Mac's own person reads why, and Retry.
+ final join = _teamJoin;
+ final joinLine =
+ line != null &&
+ team == null &&
+ (shared?['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_JOINING' &&
+ contributor == c.accountId &&
+ app != null &&
+ app.canSetUpTeamAccount &&
+ app.stateOf(id)?.isLocalMachine == true &&
+ join != null
+ ? superTabTeamJoinLine(join)
+ : null;
// While setup runs, its step and the time left, and that the person may
// go on working (#3169); otherwise its own person reads why: they
// cancelled, or setup failed and why.
@@ -1581,7 +1603,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
? '$progress\nKeep working. We\'ll tell you when it\'s ready.'
: setUpTeam
? superTabTeamSetupLine(_teamSetup) ?? line
- : line;
+ : joinLine ?? line;
return _MachineView(
apiModels: apiModels,
localModels: localModels,
@@ -1590,8 +1612,11 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
problem: problem,
history: superTabMachineHistory(shared, snapshot.people),
// Set up would ask for the password again while one setup runs.
- setUpTeam: setUpTeam && progress == null,
- setUpTeamLabel: superTabTeamSetupAction(_teamSetup),
+ setUpTeam: (setUpTeam && progress == null) || joinLine != null,
+ retryJoin: joinLine != null,
+ setUpTeamLabel: joinLine != null
+ ? 'Retry'
+ : superTabTeamSetupAction(_teamSetup),
owner: person,
contributor: contributor,
shared: shared,
@@ -2241,7 +2266,12 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
onMore: BrowserMenuGuard.inBrowser
? (at) => _menu(view, at)
: null,
- onSetUpTeam: view.setUpTeam
+ onSetUpTeam: view.retryJoin
+ ? () async {
+ await widget.app!.retryTeamJoin();
+ await _readTeamSetup();
+ }
+ : view.setUpTeam
? () async {
await showTeamAccountSetup(
context,
@@ -2868,6 +2898,7 @@ class _MachineView {
this.problem,
this.history,
this.setUpTeam = false,
+ this.retryJoin = false,
this.setUpTeamLabel = 'Set up',
this.apiModels = const [],
this.localModels = const [],
@@ -2882,6 +2913,9 @@ class _MachineView {
/// Its [problem] is this Mac's, its own person looking: no Harness Team account yet, which they can set up here.
final bool setUpTeam;
+ /// The row's button retries this Mac's join of its Team account (#3215), not its setup.
+ final bool retryJoin;
+
/// Its button's word: Repair for an account that is there with a part missing (#2765), else Set up.
final String setUpTeamLabel;
@@ -2986,6 +3020,20 @@ String? superTabTeamSetupLine(({String state, String? detail})? setup) {
return why == null ? null : "Teammates' agents paused: $why";
}
+/// This Mac's own row while its Team account, signed in, has not joined (#3215): the last refusal or error of its join, or
+/// that this Mac's Swarm work is not running; null while the join simply runs.
+String? superTabTeamJoinLine(({String? failure, bool hostRunning}) join) {
+ final failure = join.failure?.trim().replaceFirst(RegExp(r'[.]+$'), '');
+ final why = failure != null && failure.isNotEmpty
+ ? failure
+ : join.hostRunning
+ ? null
+ : 'this computer is not adding it';
+ return why == null
+ ? null
+ : "Teammates' agents paused: Harness Team could not join: $why";
+}
+
/// The row's button for this Mac's own setup: Repair when the account is there but a part of it is not (#2765), or it
/// works for another account (#3122), else Set up.
String superTabTeamSetupAction(({String state, String? detail})? setup) =>
@@ -3236,17 +3284,19 @@ class _MachineLine extends StatelessWidget {
overflow: TextOverflow.ellipsis,
style: DesktopChrome.metadata(),
),
+ // The design system's secondary action, as themed (desktop-design-system.md): no local style.
if (problem != null && onSetUpTeam != null)
- TextButton(
- key: ValueKey('super-machine-team-setup-${view.id}'),
- onPressed: onSetUpTeam,
- style: TextButton.styleFrom(
- padding: EdgeInsets.zero,
- minimumSize: const Size(0, 22),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- alignment: Alignment.centerLeft,
+ Padding(
+ padding: const EdgeInsets.only(
+ top: grid.AppDesktop.controlGap,
+ ),
+ child: OutlinedButton(
+ key: ValueKey(
+ 'super-machine-team-setup-${view.id}',
+ ),
+ onPressed: onSetUpTeam,
+ child: Text(view.setUpTeamLabel),
),
- child: Text(view.setUpTeamLabel),
),
],
);
diff --git a/desktop/lib/super_tabs/project_options.dart b/desktop/lib/super_tabs/project_options.dart
index cf23f0685..25f43a80e 100644
--- a/desktop/lib/super_tabs/project_options.dart
+++ b/desktop/lib/super_tabs/project_options.dart
@@ -1,5 +1,9 @@
+import 'dart:async';
+import 'dart:io';
+
import 'package:flutter/material.dart';
+import '../core/github_repository.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../widgets/desktop_chrome.dart';
@@ -14,12 +18,40 @@ import 'project_visibility.dart';
const _gap = DesktopChrome.controlGap;
const _halfGap = _gap / 2;
+/// How many branches a repository has, by `git ls-remote --heads` with this
+/// computer's own git login, or null when it could not be reached. One with
+/// none has no commit yet.
+typedef RepositoryBranchCount = Future<int?> Function(String url);
+
+Future<int?> _branchCount(String url) async {
+ try {
+ final result = await Process.run(
+ 'git',
+ ['ls-remote', '--heads', '--', url],
+ // Never a prompt for a password nobody sees, and only GitHub's ways in.
+ environment: {
+ 'GIT_TERMINAL_PROMPT': '0',
+ 'GIT_ALLOW_PROTOCOL': 'https:ssh',
+ },
+ ).timeout(const Duration(seconds: 20));
+ if (result.exitCode != 0) return null;
+ return '${result.stdout}'
+ .split('\n')
+ .where((l) => l.trim().isNotEmpty)
+ .length;
+ } on Object {
+ return null;
+ }
+}
+
/// A project's details, read only: its description, repository, coordinator and whether teammates' agents can
-/// push there, in the shared details frame (Ken, 2026-10-28).
+/// push there, in the shared details frame (Ken, 2026-10-28). Its owner can share a repository from the Repository
+/// row while none is set (task #3211): other machines then clone it instead of starting in an empty folder.
Future<void> _showProjectDetails(
BuildContext context,
SuperTabController c,
SuperTabProject project,
+ RepositoryBranchCount branches,
) => showAppDialog<void>(
context: context,
builder: (context) => SuperTabDialogScope(
@@ -50,11 +82,24 @@ Future<void> _showProjectDetails(
),
SuperTabDetailRow(
label: 'Repository',
- child: SelectableText(
- current?.repository?['repositoryUrl'] as String? ??
- current?.repository?['cwd'] as String? ??
- 'Not set',
- style: DesktopChrome.control(),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SelectableText(
+ current?.repository?['repositoryUrl'] as String? ??
+ current?.repository?['cwd'] as String? ??
+ 'Not set',
+ style: DesktopChrome.control(),
+ ),
+ if (current != null &&
+ current.ownerId == c.accountId &&
+ current.repository?['repositoryUrl'] == null)
+ TextButton(
+ onPressed: () =>
+ _shareRepository(context, c, current, branches),
+ child: const Text('Share repository'),
+ ),
+ ],
),
),
SuperTabDetailRow(
@@ -165,14 +210,15 @@ Future<void> showProjectAction(
BuildContext context,
SuperTabController c,
SuperTabProject project,
- String action,
-) async {
+ String action, {
+ RepositoryBranchCount? branches,
+}) async {
if (action == 'delete') {
await _deleteProject(context, c, project);
return;
}
if (action == 'details') {
- await _showProjectDetails(context, c, project);
+ await _showProjectDetails(context, c, project, branches ?? _branchCount);
return;
}
var name = project.name;
@@ -405,3 +451,117 @@ Future<void> _deleteProject(
),
);
}
+
+/// The owner shares the project's GitHub repository (task #3211): checked on
+/// this computer to have a commit, since other machines clone and branch from
+/// it, then sent as the address any machine can use.
+Future<void> _shareRepository(
+ BuildContext context,
+ SuperTabController c,
+ SuperTabProject project,
+ RepositoryBranchCount branches,
+) async {
+ var address = '';
+ String? problem;
+ var busy = false;
+ await showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ projectId: project.id,
+ requireWrite: true,
+ child: StatefulBuilder(
+ builder: (context, update) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ Future<void> share() async {
+ final repository = GitHubRepository.parse(address);
+ if (repository == null) {
+ update(
+ () => problem = 'Enter a GitHub repository, such as https://github.com/owner/repository.',
+ );
+ return;
+ }
+ update(() {
+ busy = true;
+ problem = null;
+ });
+ final count = await branches(repository.url);
+ if (!context.mounted) return;
+ if (count == null || count == 0) {
+ update(() {
+ busy = false;
+ problem = count == null
+ ? 'This computer can’t reach ${repository.slug} on GitHub. Check the address, and that you can open the repository with your GitHub account.'
+ : '${repository.slug} has no commits yet. Add one, for example a README, then share it.';
+ });
+ return;
+ }
+ final result = await c.command({
+ 'type': 'project.repository',
+ 'projectId': project.id,
+ 'repositoryUrl': repository.shareableUrl,
+ });
+ if (!context.mounted) return;
+ if (result != null) {
+ Navigator.pop(context);
+ } else {
+ update(() => busy = false);
+ }
+ }
+
+ return AlertDialog(
+ title: const Text('Share repository'),
+ content: SizedBox(
+ width: 400,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Agents on other machines clone this repository instead of starting in an empty folder. It needs at least one commit.',
+ style: DesktopChrome.text(),
+ ),
+ const SizedBox(height: _gap),
+ TextField(
+ autofocus: true,
+ enabled: !busy,
+ decoration: const InputDecoration(
+ hintText: 'https://github.com/owner/repository',
+ ),
+ onChanged: (value) => update(() {
+ address = value;
+ problem = null;
+ }),
+ onSubmitted: (_) => busy ? null : share(),
+ ),
+ if (problem ?? c.operationError case final shown?) ...[
+ const SizedBox(height: _gap),
+ Text(shown, style: DesktopChrome.metadata()),
+ ],
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed:
+ busy ||
+ c.saving ||
+ c.hasPendingAction ||
+ address.trim().isEmpty
+ ? null
+ : share,
+ child: const Text('Share'),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/test/super_tab_computer_move_test.dart b/desktop/test/super_tab_computer_move_test.dart
index bbd4c1fb2..d1c123e3c 100644
--- a/desktop/test/super_tab_computer_move_test.dart
+++ b/desktop/test/super_tab_computer_move_test.dart
@@ -13,6 +13,9 @@ import 'swarm_state_test.dart' show createApp;
class _TeamDaemon extends RenameConnection {
Map<String, dynamic> status = {'ok': true, 'state': 'exists'};
final setups = <Map<String, dynamic>>[];
+ String? joinFailure;
+ bool hostRunning = true;
+ int joinRetries = 0;
@override
Future<Map<String, dynamic>> request(
@@ -23,6 +26,15 @@ class _TeamDaemon extends RenameConnection {
if (type == 'super_tabs' && payload['action'] == 'teamSetupStatus') {
return Future.value(status);
}
+ if (type == 'super_tabs' && payload['action'] == 'teamJoinStatus') {
+ return Future.value({'ok': true, 'failure': joinFailure, 'hostRunning': hostRunning});
+ }
+ if (type == 'super_tabs' && payload['action'] == 'teamJoinRetry') {
+ joinRetries++;
+ joinFailure = null;
+ hostRunning = true;
+ return Future.value({'ok': true});
+ }
if (type == 'super_tabs' && payload['action'] == 'teamSetup') {
setups.add(Map.of(payload));
status = {'ok': true, 'state': 'running'};
@@ -202,6 +214,107 @@ void main() {
app.dispose();
});
+ // Amon, 11-05: the row's Repair looked out of place. Set up and Repair are the design system's own secondary action, a
+ // themed outlined button as drawn everywhere else, never a text button squeezed to the line's height.
+ testWidgets('Set up and Repair on the row are the standard secondary button', (tester) async {
+ final daemon = _TeamDaemon();
+ final app = createApp(connectionForTest: (_) => daemon, connected: true)
+ ..teamAccountHereForTest = true;
+ app.machineStates['m']!.localOnly = true;
+ final c = await _mount(
+ tester,
+ _swarm(
+ _pool(
+ teamWork: {
+ 'allowed': false,
+ 'code': 'TEAM_ACCOUNT_REQUIRED',
+ 'reason': 'Refused.',
+ },
+ ),
+ ),
+ app: app,
+ );
+ final button = tester.widget<ButtonStyleButton>(
+ find.byKey(const ValueKey('super-machine-team-setup-m')),
+ );
+ expect(button, isA<OutlinedButton>());
+ expect(button.style, isNull);
+ await _unmount(tester, c);
+ app.dispose();
+ });
+
+ // Amon, 11-05 (#3215): after Repair the row read "joining" for good while this Mac kept failing to add the Team account,
+ // and only the log said why. The row says why, and Retry tries again at once.
+ testWidgets('a Team account that cannot join says why on this Mac\'s row, with Retry', (
+ tester,
+ ) async {
+ final daemon = _TeamDaemon()
+ ..joinFailure = 'The Harness Team account is not reachable now.';
+ final app = createApp(connectionForTest: (_) => daemon, connected: true)
+ ..teamAccountHereForTest = true;
+ app.machineStates['m']!.localOnly = true;
+ final c = await _mount(
+ tester,
+ _swarm(
+ _pool(
+ teamWork: {
+ 'allowed': false,
+ 'code': 'TEAM_ACCOUNT_JOINING',
+ 'reason': 'Joining.',
+ },
+ ),
+ ),
+ app: app,
+ );
+ expect(
+ _text(tester, 'super-machine-problem-m'),
+ "Teammates' agents paused: Harness Team could not join: The Harness Team account is not reachable now",
+ );
+ final retry = find.byKey(const ValueKey('super-machine-team-setup-m'));
+ expect(find.descendant(of: retry, matching: find.text('Retry')), findsOneWidget);
+ await tester.tap(retry);
+ await tester.pumpAndSettle();
+ expect(daemon.joinRetries, 1);
+ // Retried and no longer failing: back to joining, with no button.
+ expect(
+ _text(tester, 'super-machine-problem-m'),
+ "Teammates' agents paused: Harness Team is joining",
+ );
+ expect(retry, findsNothing);
+ await _unmount(tester, c);
+
+ // A Mac whose Swarm work never started (it was moved into the Swarm, #3215) says so, and Retry starts it.
+ daemon
+ ..hostRunning = false
+ ..joinRetries = 0;
+ final idle = await _mount(
+ tester,
+ _swarm(
+ _pool(
+ teamWork: {
+ 'allowed': false,
+ 'code': 'TEAM_ACCOUNT_JOINING',
+ 'reason': 'Joining.',
+ },
+ ),
+ ),
+ app: app,
+ );
+ expect(
+ _text(tester, 'super-machine-problem-m'),
+ "Teammates' agents paused: Harness Team could not join: this computer is not adding it",
+ );
+ await tester.tap(find.byKey(const ValueKey('super-machine-team-setup-m')));
+ await tester.pumpAndSettle();
+ expect(daemon.joinRetries, 1);
+ expect(
+ _text(tester, 'super-machine-problem-m'),
+ "Teammates' agents paused: Harness Team is joining",
+ );
+ await _unmount(tester, idle);
+ app.dispose();
+ });
+
test("the row's button reads Repair for an account already here, Set up otherwise", () {
expect(superTabTeamSetupAction((state: 'exists', detail: null)), 'Repair');
expect(superTabTeamSetupAction((state: 'none', detail: null)), 'Set up');
diff --git a/desktop/test/super_tab_share_repository_test.dart b/desktop/test/super_tab_share_repository_test.dart
new file mode 100644
index 000000000..26dfbba68
--- /dev/null
+++ b/desktop/test/super_tab_share_repository_test.dart
@@ -0,0 +1,169 @@
+// Task #3211 (vie, 11-05): a project whose Product Manager started in a folder with no GitHub origin has no repository,
+// so its agents elsewhere start in an empty folder. Its owner shares one from the project's details; one with no commit
+// is refused in plain words, since other machines clone and branch from it.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/project_options.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ late ConversationServer server;
+ late List<Map<String, dynamic>> sent;
+ late List<String> checked;
+ int? branches;
+
+ setUp(() {
+ server = ConversationServer();
+ sent = [];
+ checked = [];
+ branches = 1;
+ });
+
+ /// The Swarm's one project, its folder on the owner's Mac recorded with [repositoryUrl], read as [accountId].
+ Future<SuperTabController> mount(
+ WidgetTester tester, {
+ String accountId = 'owner',
+ String? repositoryUrl,
+ }) async {
+ server.state['projects'] = [
+ {
+ ...projectFixture('lead', 'Outreach', 'lead'),
+ 'repository': {
+ 'machineId': 'mac',
+ 'cwd': '/Users/vie/outreach',
+ 'repositoryUrl': repositoryUrl,
+ },
+ },
+ ];
+ final c = SuperTabController(
+ tabId: 'tab',
+ accountId: accountId,
+ request: (method, path, {body}) async {
+ if (body?['command'] case final Map<String, dynamic> command) {
+ sent.add(command);
+ }
+ return server.request(method, path, body: body);
+ },
+ save: server.save,
+ upload: server.upload,
+ initial: const {},
+ pollInterval: Duration.zero,
+ );
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showProjectAction(
+ context,
+ c,
+ c.snapshot!.projects.first,
+ 'details',
+ branches: (url) async {
+ checked.add(url);
+ return branches;
+ },
+ ),
+ child: const Text('Open details'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open details'));
+ await tester.pumpAndSettle();
+ return c;
+ }
+
+ Future<void> share(WidgetTester tester, String address) async {
+ await tester.enterText(find.byType(TextField), address);
+ await tester.pump();
+ await tester.tap(find.widgetWithText(FilledButton, 'Share'));
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets(
+ 'offers Share repository to the owner of a project with none, and to nobody else',
+ (tester) async {
+ await mount(tester);
+ expect(find.text('/Users/vie/outreach'), findsOneWidget);
+ expect(find.text('Share repository'), findsOneWidget);
+ },
+ );
+
+ testWidgets('offers nothing to another member', (tester) async {
+ await mount(tester, accountId: 'peer');
+ expect(find.text('Share repository'), findsNothing);
+ });
+
+ testWidgets('offers nothing once a repository is shared', (tester) async {
+ await mount(tester, repositoryUrl: 'https://github.com/vie/outreach.git');
+ expect(find.text('https://github.com/vie/outreach.git'), findsOneWidget);
+ expect(find.text('Share repository'), findsNothing);
+ });
+
+ testWidgets(
+ 'refuses a repository with no commit in plain words, and sends nothing',
+ (tester) async {
+ await mount(tester);
+ await tester.tap(find.text('Share repository'));
+ await tester.pumpAndSettle();
+ branches = 0;
+ await share(tester, 'vie/outreach');
+ expect(checked, ['https://github.com/vie/outreach.git']);
+ expect(
+ find.text(
+ 'vie/outreach has no commits yet. Add one, for example a README, then share it.',
+ ),
+ findsOneWidget,
+ );
+ expect(sent.where((c) => c['type'] == 'project.repository'), isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'refuses an address that is not GitHub before running git, and one this computer cannot reach',
+ (tester) async {
+ await mount(tester);
+ await tester.tap(find.text('Share repository'));
+ await tester.pumpAndSettle();
+ await share(tester, 'https://gitlab.com/vie/outreach');
+ expect(
+ find.text(
+ 'Enter a GitHub repository, such as https://github.com/owner/repository.',
+ ),
+ findsOneWidget,
+ );
+ expect(checked, isEmpty);
+ branches = null;
+ await share(tester, 'vie/outreach');
+ expect(
+ find.textContaining('can’t reach vie/outreach on GitHub'),
+ findsOneWidget,
+ );
+ expect(sent.where((c) => c['type'] == 'project.repository'), isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'shares a repository with a commit as the address any machine can use, and closes',
+ (tester) async {
+ await mount(tester);
+ await tester.tap(find.text('Share repository'));
+ await tester.pumpAndSettle();
+ branches = 2;
+ await share(tester, '[email protected]:vie/outreach.git');
+ expect(sent.where((c) => c['type'] == 'project.repository'), [
+ {
+ 'type': 'project.repository',
+ 'projectId': 'lead',
+ 'repositoryUrl': '[email protected]:vie/outreach.git',
+ },
+ ]);
+ expect(find.widgetWithText(FilledButton, 'Share'), findsNothing);
+ },
+ );
+}
diff --git a/desktop/test/swarm_join_any_test.dart b/desktop/test/swarm_join_any_test.dart
index 8eea65d8f..9fbbffd43 100644
--- a/desktop/test/swarm_join_any_test.dart
+++ b/desktop/test/swarm_join_any_test.dart
@@ -160,6 +160,35 @@ void main() {
expect(_contributions(f), hasLength(1));
});
+ // Task #3212: a reinstall (an empty record here) added this Mac back to a
+ // Swarm its person had taken it out of.
+ test(
+ 'after its person took this Mac out, a fresh install does not add it back',
+ () async {
+ final f = _computer();
+ // As the Swarm tells this person: their own removed computers.
+ f.connection.server.state['removedMachines'] = ['m'];
+ await _discover(f);
+ expect(_contributions(f), isEmpty);
+ expect(_teamOffers(f), isEmpty);
+ // Decided for this Swarm: the next discovery does not read it again.
+ final loads = _firstLoads(f);
+ await _discover(f);
+ expect(_firstLoads(f), loads);
+ },
+ );
+
+ test(
+ 'a fresh install still adds this Mac to a Swarm it was never taken out of',
+ () async {
+ final f = _computer();
+ f.connection.server.state['removedMachines'] = ['another-computer'];
+ await _discover(f);
+ expect(_contributions(f), hasLength(1));
+ expect(_teamOffers(f), hasLength(1));
+ },
+ );
+
group('a failed step shows the person a note', () {
test(
'a Team account this Mac could not be offered says where to set it up',
diff --git a/desktop/test/swarm_join_machine_test.dart b/desktop/test/swarm_join_machine_test.dart
index 3c8449c76..0ea84145d 100644
--- a/desktop/test/swarm_join_machine_test.dart
+++ b/desktop/test/swarm_join_machine_test.dart
@@ -171,6 +171,39 @@ void main() {
}
});
+ // Task #3212: a reinstall added a Mac back to a Swarm its person had taken
+ // it out of. The Swarm tells each reader their own removed computers.
+ test(
+ 'leaves out a computer its person took out of the Swarm, and only that one',
+ () async {
+ server.state['removedMachines'] = ['MATE-MAC'];
+ final c = server.controller(account: 'mate');
+ await c.refresh();
+ final note = await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ expect(note, isNull);
+ expect(contributions(), isEmpty);
+ expect(daemon.asked, isEmpty);
+
+ // Another of their computers, taken out: this one is still added.
+ server.state['removedMachines'] = ['mate-old-laptop'];
+ await c.refresh();
+ final added = await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ expect(added?.added, isTrue);
+ expect(contributions(), hasLength(1));
+ c.dispose();
+ },
+ );
+
test('says why it could not add it: no Claude Code or Codex, Harness too old, or refused', () async {
Future<SwarmJoinedMachine?> attempt() async {
final c = server.controller(account: 'mate');
diff --git a/docs/plans/2026-11-05-no-repository-projects-plan.md b/docs/plans/2026-11-05-no-repository-projects-plan.md
new file mode 100644
index 000000000..08cde1abd
--- /dev/null
+++ b/docs/plans/2026-11-05-no-repository-projects-plan.md
@@ -0,0 +1,95 @@
+# A project without a repository can run on other machines, and the owner can share one in the app (task #3211) Plan
+
+> Worked by the Engineer, test first (superpowers test-driven-development): each task's failing test is committed and
+> seen red before the code that passes it.
+
+**Goal:** Work that isn't code is no longer pinned to the one machine its Product Manager started on. A project with no
+shared repository starts agents on any machine of the Swarm in an empty folder of its own. Its owner can share a GitHub
+repository from the app; one with no commit is refused with a plain message.
+
+**Architecture:**
+- Backend (`backend/src/superTabs/machines.ts`): `noRepositoryStart(pool, project, request)` turns a start on a machine
+ other than the project's source machine, for a project with no repository address, into a start without a worktree
+ (`worktree: false`, no `branchRef`). `agent.start` (commands.ts) and the Product Manager's start (leadStart.ts) both
+ apply it, so the request the host receives is the one it can carry out.
+- CLI host (`cli/src/superTabs/projectFolder.ts`): for such a project, `prepareSwarmStart` asks for no GitHub token
+ (there is nothing to clone, and the token route refuses a project with no address), and `prepareSwarmProject` makes
+ the project's own folder (`<the Swarm's clone root>/<projectId>`), refusing a folder that is a link or resolves
+ anywhere else, `git init`s it so the existing trust step (cloneTrust.ts) records Claude Code's and Codex's folder
+ trust for it, and refuses a worktree start (an older backend). A project with a repository keeps today's path.
+- Desktop (`desktop/lib/super_tabs/project_options.dart`): the project details' Repository row gets a "Share
+ repository" action for the owner when none is set. It takes a GitHub URL, checks on this Mac with `git ls-remote
+ --heads` (the owner's own login) that the repository has a commit, and sends `project.repository`.
+
+**Tech Stack:** TypeScript (backend: vitest; CLI: its spec runner), Flutter/Dart (Desktop: flutter test, check-ui-style).
+
+**Spec:** task #3211 brief.
+
+## Global Constraints
+
+- Owned: `cli/src/superTabs/projectFolder.ts`, `backend/src/superTabs`, `desktop/lib/super_tabs/project_options.dart`,
+ with their tests and this plan.
+- A project that has a repository keeps today's rule: a clone on other machines, and the address-required refusal is
+ only gone for projects with no address at all.
+- Swarm code stays out of `cli/src/core`. Desktop keeps the dialog's layout (Dee's rule); #3194 (PR #3133) is changing
+ Project settings in the same file, so this adds one action to the details dialog's Repository row and nothing else.
+
+## Design
+
+- growth: no new record. One folder per project per machine, as a clone takes today; removed with the Swarm's folders.
+- concurrency: the start's request is decided in its command's transaction, as today. Two starts making the same folder
+ race on `mkdir`; the second finds it and checks it is a plain directory at the expected place.
+- read cost: none new on the backend; the host reads the project row it already has.
+- scale: unchanged at 10x.
+- compatibility: an older host refuses a no-repository start on another machine, as today ("Share a GitHub
+ repository…"). A newer host with an older backend gets `worktree: true` and refuses it plainly. An older Desktop shows
+ Repository read-only, as today.
+- migration + rollback: none. Rollback brings back the refusal; the empty folders stay, harmless.
+- audience: `project.repository` stays owner-or-lead only on the server (commands.ts); the app shows the action only to
+ the owner. Start admission is unchanged: the folder must still be the project's own (`projectFolder`).
+- identity: the commit check runs with the signed-in owner's own git login on their own Mac; hosts use no login at all
+ for a no-repository project.
+- failure: every refusal says what to do: a repository with no commit ("add one, for example a README"), an address
+ that can't be reached, a folder that isn't the project's, a folder left from before a repository was shared.
+- platforms: macOS, Linux and Windows hosts (paths through `node:path`); Desktop on macOS, Windows, Linux.
+
+## Review Focus
+
+- The folder a no-repository start gets: always `<clone root>/<projectId>` (`sameFolder`), never a link, never a
+ worktree of anything, and no GitHub token requested.
+- The backend change only for a project with no address on a machine other than its source machine.
+- The share action: owner only in the app, owner or lead on the server; URL limited to GitHub before git runs.
+
+## Task 1: The backend starts a no-repository project without a worktree on other machines
+
+**Files:** `backend/src/superTabs/machines.ts`, `backend/src/superTabs/commands.ts`, `backend/src/superTabs/leadStart.ts`,
+their unit tests.
+
+**Interfaces:** `noRepositoryStart(pool: ContributedMachine | undefined, project: SwarmProject, request: AgentStartRequest): AgentStartRequest`.
+
+- [ ] Test: `agent.start` for a project with no address on a machine other than its source records `worktree: false`
+ and no `branchRef`; the same start on the source machine, and any start for a project with an address, keep
+ `worktree: true`.
+- [ ] Test: a Product Manager's start on another machine for a project with no address has no worktree.
+- [ ] Red, then code, then green.
+
+## Task 2: The host prepares an empty folder for a no-repository project
+
+**Files:** `cli/src/superTabs/projectFolder.ts`, `cli/src/superTabs/projectFolder.spec.ts`.
+
+- [ ] Test: a start of a project with no repository on another machine makes `<root>/<projectId>`, a git folder with no
+ remote, asks for no token (even on a Team account with the app), and records trust.
+- [ ] Test: a worktree start of such a project is refused plainly; a link at the folder is refused; a folder outside
+ the project is refused as today.
+- [ ] Test: a project with a repository still clones, and a folder left from before a repository was shared is refused
+ with a message saying to move it aside.
+- [ ] Red, then code, then green.
+
+## Task 3: The owner shares a repository from the app
+
+**Files:** `desktop/lib/super_tabs/project_options.dart`, a Desktop widget test.
+
+- [ ] Test: the owner sees Share repository on a project with none; another member doesn't; a project with one doesn't.
+- [ ] Test: a repository with no commit is refused with "add one (for example a README)" and nothing is sent; one with
+ a commit sends `project.repository` with the address; a non-GitHub address is refused before git runs.
+- [ ] Red, then code, then green; `check-ui-style`.
diff --git a/mobile/integration_test/swarm_change_agent_e2e_test.dart b/mobile/integration_test/swarm_change_agent_e2e_test.dart
new file mode 100644
index 000000000..641ecf69c
--- /dev/null
+++ b/mobile/integration_test/swarm_change_agent_e2e_test.dart
@@ -0,0 +1,245 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/main.dart' as app;
+import 'package:harness_mobile/phone/phone_shell.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/phone/welcome/onboarding_copy.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/widgets/engine_identity.dart';
+
+/// Change agent on a Swarm Product Manager's pane, end to end on a real
+/// phone: the real app, signed in to its owner's account, switching a PM that
+/// runs on one of the account's own computers to another engine, then back.
+///
+/// It WRITES: the PM's machine saves and stops the PM's agent and starts the
+/// other engine in its place, twice. Run it only on a test project's PM, on
+/// the owner's own phone, when they ask for it. Opt-in with
+/// `SWARM_CHANGE_AGENT_E2E=true`; it skips otherwise, so no CI or simulator
+/// run reaches a real account.
+///
+/// flutter drive -d <phone> --keep-app-running \
+/// --driver=test_driver/journey_driver.dart \
+/// --target=integration_test/swarm_change_agent_e2e_test.dart \
+/// --dart-define=SWARM_CHANGE_AGENT_E2E=true \
+/// --dart-define=SWARM_E2E_PM_AGENT=<the PM's harness id> \
+/// [--dart-define=SWARM_E2E_TO_ENGINE=codex] \
+/// [--dart-define=SWARM_E2E_SWITCH_BACK=false]
+///
+/// Each switch must end on a running agent of the chosen engine, in the same
+/// folder, with the old one stopped and no refusal said: before the PM's
+/// machine knew the switch (`agent_close` naming its `changeId`), it refused
+/// a PM's close with LEAD_PROTECTED. Then the terminal's menu names the new
+/// engine on its Change agent row. `--keep-app-running` always: without it
+/// `flutter drive` uninstalls the app (`integration_test/README.md`).
+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).
+void main() {
+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+ const run = bool.fromEnvironment('SWARM_CHANGE_AGENT_E2E');
+ const pmAgent = String.fromEnvironment('SWARM_E2E_PM_AGENT');
+ const toEngine = String.fromEnvironment(
+ 'SWARM_E2E_TO_ENGINE',
+ defaultValue: 'codex',
+ );
+ const switchBack = bool.fromEnvironment(
+ 'SWARM_E2E_SWITCH_BACK',
+ defaultValue: true,
+ );
+
+ testWidgets(
+ 'Change agent on a Swarm PM, for its signed-in owner',
+ (tester) async {
+ expect(pmAgent, isNotEmpty, reason: 'Name the PM: SWARM_E2E_PM_AGENT');
+ var step = 0;
+ Future<void> wait([int ms = 600]) async {
+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ Future<void> shot(String name) async {
+ // Past any page or sheet transition.
+ await wait(900);
+ step++;
+ await binding.takeScreenshot(
+ 'change-agent-${step.toString().padLeft(2, '0')}-$name',
+ );
+ }
+
+ Future<void> waitFor(Finder finder, {int seconds = 30}) async {
+ for (var i = 0; i < seconds * 10; i++) {
+ if (finder.evaluate().isNotEmpty) return;
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ await shot('never-appeared');
+ fail('never appeared: $finder');
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ await app.main();
+ // The signed-in shell, whatever its home shows; or the welcome, which
+ // this run cannot pass.
+ final shell = find.byType(PhoneShell);
+ for (var i = 0; i < 900 && shell.evaluate().isEmpty; i++) {
+ if (find.text(OnboardingCopy.welcome).evaluate().isNotEmpty) {
+ fail('Sign in on the phone first, then run this again.');
+ }
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ if (shell.evaluate().isEmpty) {
+ await shot('no-shell');
+ fail('the signed-in shell never appeared');
+ }
+ final notifier = tester.widget<PhoneShell>(shell).notifier;
+
+ /// The machine that runs [agentId] and the agent as it reads now.
+ (String, Agent)? locate(String agentId) {
+ for (final MapEntry(key: machineId, value: machine)
+ in notifier.machineStates.entries) {
+ for (final agent in machine.agents) {
+ if (agent.id == agentId) return (machineId, agent);
+ }
+ }
+ return null;
+ }
+
+ // The PM, once its machine has listed its agents.
+ (String, Agent)? found;
+ for (var i = 0; i < 900 && found == null; i++) {
+ found = locate(pmAgent);
+ if (found == null) await tester.pump(const Duration(milliseconds: 100));
+ }
+ await shot('home');
+ expect(found, isNotNull, reason: 'the PM $pmAgent on a linked machine');
+ final machineId = found!.$1;
+ final firstEngine = found.$2.engine!;
+ expect(
+ AppNotifier.canChangeAgent(found.$2),
+ isTrue,
+ reason: 'Change agent is offered on the PM',
+ );
+ debugPrint('[change-agent] PM $pmAgent on $machineId runs $firstEngine');
+
+ // Its terminal, as the project team's Open terminal opens it.
+ tester
+ .widget<PhoneShellScope>(find.byType(PhoneShellScope).first)
+ .onOpenAgent(machineId, pmAgent);
+ await waitFor(key('terminal-title'), seconds: 60);
+ await wait(3000);
+ await shot('pm-terminal');
+
+ /// Change agent from the terminal's menu to [engine], chosen by its
+ /// [title] in the picker; returns the agent that took over.
+ Future<String> change(
+ String fromId,
+ String engine,
+ String title,
+ String label,
+ ) async {
+ final before = {
+ for (final agent
+ in notifier.machineStates[machineId]?.agents ?? const <Agent>[])
+ agent.id,
+ };
+ await tester.tap(key('terminal-title'));
+ await waitFor(find.text('Change agent'));
+ await shot('menu-before-$engine');
+ await tester.tap(find.text('Change agent'));
+ await waitFor(find.text(title));
+ await shot('picker-$engine');
+ await tester.tap(find.text(title).last);
+ final started = DateTime.now();
+ String? said;
+ String? next;
+ // Saving and stopping the old agent, then starting the new one.
+ for (var i = 0; i < 3000 && next == null; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ final snack = find.descendant(
+ of: find.byType(SnackBar),
+ matching: find.byType(Text),
+ );
+ if (snack.evaluate().isNotEmpty) {
+ final text = tester.widget<Text>(snack.first).data;
+ if (text != null && text != said) {
+ said = text;
+ debugPrint('[change-agent] said: $text');
+ }
+ }
+ final old = locate(fromId)?.$2;
+ for (final agent
+ in notifier.machineStates[machineId]?.agents ?? const <Agent>[]) {
+ if (!before.contains(agent.id) &&
+ agent.engine == engine &&
+ !agent.isStopped &&
+ (old == null || old.isStopped)) {
+ next = agent.id;
+ }
+ }
+ }
+ if (next == null) {
+ await shot('switch-failed-$engine');
+ fail('no running $engine agent took over; said: $said');
+ }
+ debugPrint(
+ '[change-agent] $fromId → $next ($engine) in '
+ '${DateTime.now().difference(started).inSeconds} s; said: $said',
+ );
+ expect(
+ said,
+ anyOf(
+ isNull,
+ isNot(
+ anyOf(
+ contains('Product Manager of a Swarm project'),
+ contains('already switching'),
+ contains('Could not'),
+ ),
+ ),
+ ),
+ reason: 'no refusal',
+ );
+ // The new agent's own page, its menu naming the new engine.
+ await waitFor(key('terminal-title'), seconds: 60);
+ await wait(4000);
+ await shot('after-$engine');
+ await tester.tap(key('terminal-title'));
+ await waitFor(find.text('Change agent'));
+ expect(
+ find.textContaining(label),
+ findsWidgets,
+ reason: 'the Change agent row names $label',
+ );
+ await shot('menu-after-$engine');
+ // Closed again by a tap above it, as the person would.
+ await tester.tapAt(const Offset(20, 120));
+ await wait(1200);
+ return next;
+ }
+
+ // The picker's titles and the menu row's value, as terminal_page.dart
+ // writes them.
+ String titleOf(String engine) =>
+ engine == 'claude' ? 'Claude Code' : engineIdentity(engine).label;
+ String labelOf(String engine) => engineIdentity(engine).label;
+
+ final switched = await change(
+ pmAgent,
+ toEngine,
+ titleOf(toEngine),
+ labelOf(toEngine),
+ );
+ if (!switchBack || firstEngine == toEngine) return;
+ await change(
+ switched,
+ firstEngine,
+ titleOf(firstEngine),
+ labelOf(firstEngine),
+ );
+ },
+ skip: !run,
+ timeout: const Timeout(Duration(minutes: 15)),
+ );
+}
diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dart
index e37be018c..fb9b3e385 100644
--- a/mobile/lib/e2ee/envelope.dart
+++ b/mobile/lib/e2ee/envelope.dart
@@ -39,6 +39,8 @@ const Set<String> encryptedDownTypes = {
// refuses them unsealed (E2EE_REQUIRED) — without them the switch could never start.
'agent_handoff_prepare',
'agent_close',
+ // Then which harness took over (`AppNotifier._reportReplacement`): a `MACHINE_REQUESTS` type too.
+ 'agent_handoff_complete',
// Delete Harness (`AppNotifier.purgeAgent`): reviewed, then deleted under that review. A
// `MACHINE_REQUESTS` type in the CLI, refused unsealed (E2EE_REQUIRED).
'agent_purge',
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index f09793c3a..b81756445 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -3460,7 +3460,7 @@ class _TerminalPageState extends State<TerminalPage>
),
// Another engine on the same project — what to reach for when a subscription runs out. The
// desktop's pane agent selector. Named by the agent it is on now, as the Model row is.
- if (AppNotifier.canChangeAgent(agent))
+ if (widget.notifier.offersChangeAgent(widget.machineId, agent))
PhoneSheetAction(
icon: LucideIcons.arrowLeftRight300,
label: 'Change agent',
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index c7de1f888..b0c8c82a3 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -299,6 +299,15 @@ class _AgentChange {
/// The handoff was settled (the record written, or confirmed empty), so a retry reads nothing.
bool contextLoaded = false;
+ /// The machine prepared the handoff under this switch's id (`agent_handoff_prepare`), so its
+ /// close names the switch — a Swarm Product Manager's machine stops it only for that switch
+ /// (cli superTabs/leadSwitch.ts). Never set by the older machines' `agent_recent` road.
+ bool handoffPrepared = false;
+
+ /// The machine recorded which harness took over (`agent_handoff_complete`), so a retry of this
+ /// switch reports nothing again.
+ bool replacementReported = false;
+
/// The switch is held on the handoff, with the old agent still running: only the same engine
/// carries it on.
bool handoffHeld = false;
@@ -9086,6 +9095,18 @@ class AppNotifier extends ChangeNotifier {
static bool canChangeAgent(Agent agent) =>
agent.engine != null && agent.dsh == null && agent.engine != 'terminal';
+ /// Whether the terminal's menu offers Change agent on [agent] of [machineId]: an agent it can
+ /// switch ([canChangeAgent]), on this person's own machine while it is online, as the desktop's
+ /// pane header does. Another account's shared machine answers the handoff for its owner alone
+ /// (cli superTabs/leadSwitch.ts), so the switch could never go through from here.
+ bool offersChangeAgent(String machineId, Agent agent) {
+ final machine = machineStates[machineId];
+ return canChangeAgent(agent) &&
+ machine != null &&
+ !machine.machine.shared &&
+ machine.nodeOnline != false;
+ }
+
/// The engines a harness can be switched to, in the desktop picker's order: OpenCode first, the
/// rest by name. The current one is listed too, as the one it is on.
static List<String> agentChangeEngines() {
@@ -9111,6 +9132,12 @@ class AppNotifier extends ChangeNotifier {
/// 2. The old agent is saved and stopped (`agent_close`, `now`). Never before step 1: a switch
/// that cannot carry the conversation leaves the old agent running.
/// 3. The new agent starts in the same folder, in the same permission mode where it has one.
+ /// 4. The machine is told which harness took over (`agent_handoff_complete`), best effort.
+ ///
+ /// Steps 1 to 4 share one id: the handoff's `changeId`, the close's (only once step 1 prepared
+ /// the handoff), the start's `creationId` and the report's. A Swarm Product Manager's machine
+ /// stops it only for a close that names the switch it prepared (otherwise LEAD_PROTECTED), and
+ /// finds its new session by that id (#2493).
///
/// One switch per harness at a time. Choosing the same engine again while one runs joins it;
/// once one fails it is carried on by the same choice, receipt and all, until it is safe to drop
@@ -9130,6 +9157,13 @@ class AppNotifier extends ChangeNotifier {
if (source.engine == engine) {
return Future.value(AgentChangeResult(agentId: agentId));
}
+ if (machine.machine.shared) {
+ return Future.value(
+ const AgentChangeResult(
+ error: 'Only the person whose machine runs this agent can change it.',
+ ),
+ );
+ }
if (!canChangeAgent(source) || !allEngines.any((e) => e.id == engine)) {
return Future.value(
const AgentChangeResult(
@@ -9257,7 +9291,13 @@ class AppNotifier extends ChangeNotifier {
change.preservingViews = true;
if (!latest.isStopped && !change.closed) {
_logChange(change, 'saving and stopping the old agent');
- final refused = await _closeAgentNow(machineId, latest);
+ // Named only after its handoff was prepared under this id: a Swarm Product Manager's machine
+ // checks the two belong to one switch, and refuses its close otherwise (LEAD_PROTECTED).
+ final refused = await _closeAgentNow(
+ machineId,
+ latest,
+ changeId: change.handoffPrepared ? change.creation._id : null,
+ );
if (refused != null) {
change.preservingViews = false;
return AgentChangeResult(error: refused);
@@ -9303,6 +9343,20 @@ class AppNotifier extends ChangeNotifier {
error: target!.launchDetail ?? 'The new agent could not start.',
);
}
+ // Before the switch is let go: while it is reported, choosing an agent again joins this one
+ // rather than starting a second harness off the stopped one. Unreported, a Swarm Product
+ // Manager's machine never takes the new session in and closes it once its time is up (cli
+ // superTabs/host.ts, SWITCH_ADOPT_MS), so the switch is not done until it is: choosing again
+ // reports it, as the desktop does.
+ if (!change.replacementReported) {
+ if (!await _reportReplacement(machineId, change, nextId)) {
+ return const AgentChangeResult(
+ error: 'The new agent started. Choose it again to finish the switch.',
+ );
+ }
+ change.replacementReported = true;
+ if (!live()) return inactive;
+ }
_agentChanges.remove((machineId, source.id));
unawaited(agentPreference.select(change.engine));
String? notice;
@@ -9316,6 +9370,50 @@ class AppNotifier extends ChangeNotifier {
return AgentChangeResult(agentId: nextId, notice: notice);
}
+ /// Tells the machine which harness took over (`agent_handoff_complete`), the desktop's
+ /// replacement report, so a Swarm keeps the same agent on the new session (`agent.rebind`).
+ /// Whether it is done: recorded, or a machine too old to take one (`UNSUPPORTED`), as the
+ /// desktop counts it. A refusal or no answer in time is logged, and the switch waits for it.
+ Future<bool> _reportReplacement(
+ String machineId,
+ _AgentChange change,
+ String replacementId,
+ ) async {
+ try {
+ final reply = await _conn(machineId).request(
+ 'agent_handoff_complete',
+ payload: {
+ 'agentId': change.source.id,
+ 'replacementId': replacementId,
+ 'changeId': change.creation._id,
+ 'targetEngine': change.engine,
+ },
+ timeout: const Duration(seconds: 5),
+ );
+ final recorded = reply['ok'] == true;
+ _logChange(
+ change,
+ recorded
+ ? 'the machine recorded the replacement'
+ : 'the replacement report was not confirmed',
+ );
+ return recorded;
+ } on WsRequestFailure catch (failure) {
+ if (failure.code == 'UNSUPPORTED') {
+ _logChange(change, 'the machine takes no replacement report');
+ return true;
+ }
+ _logChange(
+ change,
+ 'the replacement report was refused (${failure.code})',
+ );
+ return false;
+ } catch (error) {
+ _logChange(change, 'the replacement report was not answered ($error)');
+ return false;
+ }
+ }
+
/// Fills [change]'s handoff for the new agent, or says why the switch must not go on — the
/// desktop's `_loadSwitchHandoff`. Both reads happen BEFORE the old agent is closed.
///
@@ -9369,6 +9467,7 @@ class AppNotifier extends ChangeNotifier {
..handoffEmpty = accepted.prompt == null
..handoffFailed = false
..contextLoaded = true
+ ..handoffPrepared = true
..handoffHeld = false;
return null;
} on WsRequestFailure catch (failure) {
@@ -9448,9 +9547,14 @@ class AppNotifier extends ChangeNotifier {
///
/// ⚠️ **A lost reply never sends a second Stop.** The machine's own list is read instead, and only
/// a harness it lists as stopped, the same one, counts as closed.
- Future<String?> _closeAgentNow(String machineId, Agent agent) async {
- const notChanged =
- 'Could not save and stop this conversation. Its agent has not been changed.';
+ ///
+ /// [changeId]: the switch whose handoff the machine prepared — see
+ /// [_AgentChange.handoffPrepared].
+ Future<String?> _closeAgentNow(
+ String machineId,
+ Agent agent, {
+ String? changeId,
+ }) async {
final machine = machineStates[machineId];
final revision = _authRevision;
try {
@@ -9461,13 +9565,13 @@ class AppNotifier extends ChangeNotifier {
'sessionId': agent.sessionId ?? '',
'createdAt': agent.createdAt!.toUtc().toIso8601String(),
'mode': 'now',
+ 'changeId': ?changeId,
},
// Saving the conversation and letting the engine exit can take seconds on the machine.
timeout: const Duration(seconds: 30),
);
if (result['closed'] == true) return null;
- final detail = result['detail'];
- return detail is String && detail.isNotEmpty ? detail : notChanged;
+ return closeRefusalMessage(result['error'], result['detail']);
} on WsRequestFailure catch (failure) {
appLog.info(
'agents',
@@ -9476,8 +9580,7 @@ class AppNotifier extends ChangeNotifier {
if (failure.code == 'AGENT_CHANGED') {
return 'The conversation changed. Reopen Change agent.';
}
- final detail = failure.detail;
- return detail != null && detail.isNotEmpty ? detail : notChanged;
+ return closeRefusalMessage(failure.code, failure.detail);
} catch (error) {
appLog.warn(
'agents',
@@ -9509,6 +9612,27 @@ class AppNotifier extends ChangeNotifier {
static const _closeUnconfirmed =
'Could not confirm the close. Check the machine connection and try again.';
+ /// What Change agent says when the machine will not save and stop the old agent: the machine's
+ /// own [detail] when it sends one, as the desktop does; otherwise the CLI's sentence for [code]
+ /// (lib/closeAgentService.ts), never the bare code. A Swarm Product Manager's machine refuses
+ /// any close but its prepared switch's (LEAD_PROTECTED), and a second switch while one runs
+ /// (LEAD_SWITCHING).
+ @visibleForTesting
+ static String closeRefusalMessage(Object? code, Object? detail) =>
+ detail is String && detail.isNotEmpty
+ ? detail
+ : switch (code) {
+ 'LEAD_PROTECTED' =>
+ 'This harness is the Product Manager of a Swarm project. '
+ 'Delete its project first to stop it.',
+ 'LEAD_SWITCHING' =>
+ 'This Product Manager is already switching its agent. '
+ 'Wait for it to finish.',
+ _ =>
+ 'Could not save and stop this conversation. '
+ 'Its agent has not been changed.',
+ };
+
/// How long a lost close waits for its socket to come back before it reads the machine's list.
static const _closeRecheckReady = Duration(seconds: 15);
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index 369ed59ac..f34127f9f 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -1054,6 +1054,30 @@ void main() {
await focus.close();
});
+ testWidgets('Change agent is offered on the person\'s own machine, online '
+ 'only, as on the desktop', (tester) async {
+ var focus = await _Focus.open(tester, agents: [switchable()]);
+ final state = focus.app.stateOf('m')!;
+ state.machine = Machine(
+ machineId: 'm',
+ authMode: state.machine.authMode,
+ name: state.machine.name,
+ status: state.machine.status,
+ shared: true,
+ );
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ expect(find.text('Change agent'), findsNothing, reason: 'shared');
+ await focus.close();
+
+ focus = await _Focus.open(tester, agents: [switchable()]);
+ focus.app.stateOf('m')!.nodeOnline = false;
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ expect(find.text('Change agent'), findsNothing, reason: 'offline');
+ await focus.close();
+ });
+
testWidgets('Change agent: the desktop picker’s rows, then the agent picked '
'opens in place of this one', (tester) async {
final conn = EdgeConn({
@@ -1065,6 +1089,7 @@ void main() {
'degraded': <String>[],
},
'agent_close': {'closed': true},
+ 'agent_handoff_complete': {'ok': true},
}, startsAgents)..handshaken = true;
final focus = await _Focus.open(
tester,
diff --git a/mobile/test/state/change_agent_refusal_shots_test.dart b/mobile/test/state/change_agent_refusal_shots_test.dart
new file mode 100644
index 000000000..090c7560f
--- /dev/null
+++ b/mobile/test/state/change_agent_refusal_shots_test.dart
@@ -0,0 +1,129 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+/// Review screenshots of what Change agent says when a Swarm Product
+/// Manager's machine refuses to save and stop it: the CLI's sentence for
+/// LEAD_PROTECTED and LEAD_SWITCHING, never the bare code, on the snackbar
+/// the terminal page shows it on (`terminal_page.dart` `_changeAgent`). On a
+/// 390-point phone in both phone themes, to the folder
+/// `CHANGE_AGENT_SHOTS` names. Skipped otherwise.
+final shots = Platform.environment['CHANGE_AGENT_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ // Every name the app's text asks for; one left out draws as blocks.
+ for (final family in {
+ '.AppleSystemUIFont',
+ 'Roboto',
+ AppFont.sans,
+ ...AppFont.sansFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in {
+ '.AppleSystemUIFontMonospaced',
+ 'monospace',
+ AppFont.mono,
+ ...AppFont.monoFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('a PM machine refusing Change agent, in both phone themes', (
+ tester,
+ ) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ const size = Size(390, 844);
+ tester.view
+ ..physicalSize = size * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final boundary = GlobalKey();
+ final messenger = GlobalKey<ScaffoldMessengerState>();
+ final theme = buildAppTheme(brightness: brightness);
+ // The theme's snackbar style names no family: a phone draws it in its
+ // system face, which is AppFont.sans; `flutter test` would draw its own
+ // test face instead.
+ final snackBar = theme.snackBarTheme;
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: theme.copyWith(
+ snackBarTheme: snackBar.copyWith(
+ contentTextStyle: snackBar.contentTextStyle?.copyWith(
+ fontFamily: AppFont.sans,
+ fontFamilyFallback: AppFont.sansFallback,
+ ),
+ ),
+ ),
+ scaffoldMessengerKey: messenger,
+ home: const Scaffold(body: SizedBox.expand()),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ for (final (name, code) in [
+ ('lead-protected', 'LEAD_PROTECTED'),
+ ('lead-switching', 'LEAD_SWITCHING'),
+ ]) {
+ final said = AppNotifier.closeRefusalMessage(code, null);
+ expect(said, isNot(contains(code)), reason: 'a sentence, not a code');
+ // As terminal_page.dart says a refused switch.
+ messenger.currentState!
+ ..hideCurrentSnackBar()
+ ..showSnackBar(SnackBar(content: Text(said)));
+ await tester.pumpAndSettle();
+ expect(find.text(said), findsOneWidget);
+ await tester.runAsync(() async {
+ expect(tester.takeException(), isNull);
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File(
+ '$shots/phone-change-agent-$name-${brightness.name}-390.png',
+ ).writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ await tester.pumpWidget(const SizedBox());
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/state/change_agent_test.dart b/mobile/test/state/change_agent_test.dart
index 4b96c2479..bde8b58e9 100644
--- a/mobile/test/state/change_agent_test.dart
+++ b/mobile/test/state/change_agent_test.dart
@@ -70,6 +70,8 @@ void main() {
'state': 'created',
'agent': agentJson('b', engine: p['engine'] as String),
};
+ // The machine records which harness took over, as a current CLI does.
+ answers['agent_handoff_complete'] = (_) => {'ok': true};
await rig.app.bootstrap();
await settle();
rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
@@ -130,6 +132,9 @@ void main() {
'sessionId': 's1',
'createdAt': created,
'mode': 'now',
+ // The switch the handoff was prepared for: a Swarm Product Manager's machine stops it only
+ // for that switch, and any other machine reads past it.
+ 'changeId': create['creationId'],
});
expect(create['engine'], 'codex');
expect(create['cwd'], '/work');
@@ -413,6 +418,294 @@ void main() {
});
});
+ // A Swarm's Product Manager is switched from its pane like any harness (#2493). Its machine stops
+ // it only for a `now` close that names the switch whose handoff it prepared moments before, and
+ // only once (cli superTabs/leadSwitch.ts); any other close is refused LEAD_PROTECTED.
+ group('a Swarm Product Manager', () {
+ const protectedWords =
+ 'This harness is the Product Manager of a Swarm project. '
+ 'Delete its project first to stop it.';
+ const switchingWords =
+ 'This Product Manager is already switching its agent. '
+ 'Wait for it to finish.';
+
+ /// A machine that runs `a` as a Swarm's Product Manager, guarding its close as the CLI does.
+ /// [words]: whether its refusal carries the CLI's sentence.
+ Future<ViewerRig> leadRig({bool words = true}) async {
+ final rig = await rigWith([source()]);
+ final answers = rig.conn('m').answers;
+ final prepare = answers['agent_handoff_prepare']!;
+ final prepared = <String>{}, used = <String>{};
+ answers['agent_handoff_prepare'] = (p) {
+ prepared.add(p['changeId'] as String);
+ return prepare(p);
+ };
+ answers['agent_close'] = (p) {
+ final change = p['changeId'];
+ if (p['mode'] != 'now' ||
+ change is! String ||
+ !prepared.contains(change) ||
+ !used.add(change)) {
+ throw refusal(
+ 'LEAD_PROTECTED',
+ detail: words ? protectedWords : null,
+ );
+ }
+ return {'closed': true};
+ };
+ answers['agent_handoff_complete'] = (_) => {'ok': true};
+ return rig;
+ }
+
+ bool stillRunning(ViewerRig rig) =>
+ !rig.app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a').isStopped;
+
+ test('its close names the switch its handoff was prepared for, so its '
+ 'machine stops it; then the machine hears which harness took '
+ 'over', () async {
+ final rig = await leadRig();
+
+ final result = await finished(
+ rig,
+ rig.app.changeAgent('m', 'a', 'codex'),
+ );
+
+ expect(result.error, isNull);
+ expect(result.agentId, 'b');
+ final conn = rig.conn('m');
+ final changeId = conn
+ .payloadsOf('agent_handoff_prepare')
+ .single['changeId'];
+ expect(changeId, matches(RegExp(r'^[0-9a-f]{32}$')));
+ expect(conn.payloadsOf('agent_close').single['changeId'], changeId);
+ expect(
+ conn.payloadsOf('agent_create').single['creationId'],
+ changeId,
+ reason: 'its machine finds the new session by the same id',
+ );
+ expect(conn.payloadsOf('agent_handoff_complete').single, {
+ 'agentId': 'a',
+ 'replacementId': 'b',
+ 'changeId': changeId,
+ 'targetEngine': 'codex',
+ });
+ expect(
+ conn.asked.indexOf('agent_handoff_complete'),
+ greaterThan(conn.asked.indexOf('agent_create')),
+ reason: 'reported only once the new harness runs',
+ );
+ });
+
+ test('no handoff prepared, no change named: its machine refuses, its '
+ 'words are said, and it keeps running with nothing started', () async {
+ // An engine that takes no first message gets no handoff; an older machine hands over the
+ // last requests instead. Neither prepared this switch on the machine.
+ for (final older in [false, true]) {
+ final rig = await leadRig();
+ if (older) {
+ final answers = rig.conn('m').answers;
+ answers['agent_handoff_prepare'] = (_) =>
+ throw refusal('UNSUPPORTED');
+ answers['agent_recent'] = (_) => {
+ 'agentId': 'a',
+ 'asks': ['plan the release'],
+ };
+ }
+
+ final result = await rig.app.changeAgent(
+ 'm',
+ 'a',
+ older ? 'codex' : 'cursor',
+ );
+
+ expect(result.error, protectedWords);
+ final conn = rig.conn('m');
+ expect(
+ conn.payloadsOf('agent_close').single.containsKey('changeId'),
+ isFalse,
+ );
+ expect(conn.payloadsOf('agent_create'), isEmpty);
+ expect(conn.payloadsOf('agent_handoff_complete'), isEmpty);
+ expect(stillRunning(rig), isTrue);
+ expect(rig.app.agentChanging('m', 'a'), isFalse);
+ }
+ });
+
+ test('a refusal without words is said in a sentence, never as its '
+ 'code', () async {
+ final rig = await leadRig(words: false);
+
+ final result = await rig.app.changeAgent('m', 'a', 'cursor');
+
+ expect(result.error, protectedWords);
+ expect(result.error, isNot(contains('LEAD_PROTECTED')));
+
+ // The same refusal in the reply itself rather than as an error frame.
+ rig.conn('m').answers['agent_close'] = (_) => {'error': 'LEAD_SWITCHING'};
+ final again = await rig.app.changeAgent('m', 'a', 'cursor');
+ expect(again.error, switchingWords);
+ expect(rig.conn('m').payloadsOf('agent_create'), isEmpty);
+ expect(stillRunning(rig), isTrue);
+ });
+
+ test('refused while another switch runs: choosing it again prepares a new '
+ 'switch under a new id, never the refused one', () async {
+ final rig = await leadRig();
+ final answers = rig.conn('m').answers;
+ final guarded = answers['agent_close']!;
+ var closes = 0;
+ answers['agent_close'] = (p) => closes++ == 0
+ ? throw refusal('LEAD_SWITCHING', detail: switchingWords)
+ : guarded(p);
+
+ final first = await rig.app.changeAgent('m', 'a', 'codex');
+
+ expect(first.error, switchingWords);
+ expect(rig.conn('m').payloadsOf('agent_create'), isEmpty);
+ expect(stillRunning(rig), isTrue);
+
+ final second = await finished(
+ rig,
+ rig.app.changeAgent('m', 'a', 'codex'),
+ );
+
+ expect(second.error, isNull);
+ expect(second.agentId, 'b');
+ final conn = rig.conn('m');
+ final [one, two] = conn.payloadsOf('agent_handoff_prepare');
+ expect(two['changeId'], isNot(one['changeId']));
+ final [refused, closed] = conn.payloadsOf('agent_close');
+ expect(refused['changeId'], one['changeId']);
+ expect(closed['changeId'], two['changeId']);
+ expect(
+ conn.payloadsOf('agent_create').single['creationId'],
+ two['changeId'],
+ );
+ });
+ });
+
+ test(
+ 'an older machine that has no replacement report: the switch is done',
+ () async {
+ final rig = await rigWith([source()]);
+ rig.conn('m').answers['agent_handoff_complete'] = (_) =>
+ throw refusal('UNSUPPORTED');
+
+ final result = await finished(
+ rig,
+ rig.app.changeAgent('m', 'a', 'codex'),
+ );
+
+ expect(result.error, isNull);
+ expect(result.agentId, 'b');
+ expect(rig.app.agentChanging('m', 'a'), isFalse);
+ expect(
+ rig.conn('m').timeouts['agent_handoff_complete'],
+ const Duration(seconds: 5),
+ );
+ },
+ );
+
+ test(
+ 'a replacement report refused or never answered is not the end of the '
+ 'switch: it says so, and choosing again reports it, as the desktop does',
+ () async {
+ // Unreported, a Swarm Product Manager's machine never takes the new session in, and closes it
+ // once its time is up (cli superTabs/host.ts, SWITCH_ADOPT_MS): the switch would undo itself.
+ for (final answer
+ in <Map<String, dynamic> Function(Map<String, dynamic>)>[
+ (_) => throw const WsRequestTimeout('agent_handoff_complete'),
+ (_) => {'error': 'HANDOFF_UNAVAILABLE'},
+ (_) => throw refusal('LEAD_SWITCHING'),
+ ]) {
+ final rig = await rigWith([source()]);
+ rig.conn('m').answers['agent_handoff_complete'] = answer;
+
+ final first = await finished(
+ rig,
+ rig.app.changeAgent('m', 'a', 'codex'),
+ );
+
+ expect(
+ first.error,
+ 'The new agent started. Choose it again to finish the switch.',
+ );
+
+ rig.conn('m').answers['agent_handoff_complete'] = (_) => {'ok': true};
+ final again = await finished(
+ rig,
+ rig.app.changeAgent('m', 'a', 'codex'),
+ );
+
+ expect(again.error, isNull);
+ expect(again.agentId, 'b');
+ expect(rig.app.agentChanging('m', 'a'), isFalse);
+ expect(
+ rig.conn('m').payloadsOf('agent_handoff_complete'),
+ hasLength(2),
+ );
+ expect(rig.conn('m').payloadsOf('agent_close'), hasLength(1));
+ expect(rig.conn('m').payloadsOf('agent_create'), hasLength(1));
+ }
+ },
+ );
+
+ test('while the replacement is reported the switch is still on its way: '
+ 'choosing again joins it, and no second harness starts', () async {
+ final rig = await rigWith([source()]);
+ final reported = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_handoff_complete'] = (_) => reported.future;
+
+ final first = rig.app.changeAgent('m', 'a', 'codex');
+ for (
+ var i = 0;
+ i < 20 && rig.conn('m').payloadsOf('agent_handoff_complete').isEmpty;
+ i++
+ ) {
+ await finished(rig, Future.value());
+ }
+
+ expect(rig.conn('m').payloadsOf('agent_handoff_complete'), hasLength(1));
+ expect(rig.app.agentChanging('m', 'a'), isTrue);
+ expect(identical(rig.app.changeAgent('m', 'a', 'codex'), first), isTrue);
+
+ reported.complete({'ok': true});
+ final result = await first;
+
+ expect(result.agentId, 'b');
+ expect(rig.app.agentChanging('m', 'a'), isFalse);
+ expect(rig.conn('m').payloadsOf('agent_create'), hasLength(1));
+ });
+
+ test('a refused close is said in the machine’s words, else in a sentence '
+ 'for its code', () {
+ const generic =
+ 'Could not save and stop this conversation. '
+ 'Its agent has not been changed.';
+ expect(
+ AppNotifier.closeRefusalMessage('CLOSE_FAILED', 'Disk is full'),
+ 'Disk is full',
+ );
+ expect(
+ AppNotifier.closeRefusalMessage('LEAD_PROTECTED', 'Machine words.'),
+ 'Machine words.',
+ );
+ for (final detail in [null, '', 7]) {
+ expect(
+ AppNotifier.closeRefusalMessage('LEAD_PROTECTED', detail),
+ 'This harness is the Product Manager of a Swarm project. '
+ 'Delete its project first to stop it.',
+ );
+ expect(
+ AppNotifier.closeRefusalMessage('LEAD_SWITCHING', detail),
+ 'This Product Manager is already switching its agent. '
+ 'Wait for it to finish.',
+ );
+ expect(AppNotifier.closeRefusalMessage('CLOSE_FAILED', detail), generic);
+ expect(AppNotifier.closeRefusalMessage(null, detail), generic);
+ }
+ });
+
test(
'every step is in the app log, and nothing of the conversation',
() async {
@@ -422,6 +715,8 @@ void main() {
final rig = await rigWith([source()]);
rig.conn('m').answers['agent_handoff_prepare'] = (_) =>
throw refusal('UNSUPPORTED');
+ rig.conn('m').answers['agent_handoff_complete'] = (_) =>
+ throw refusal('UNSUPPORTED');
rig.conn('m').answers['agent_recent'] = (_) => {
'agentId': 'a',
'asks': ['the secret plan'],
@@ -441,6 +736,7 @@ void main() {
'saving and stopping the old agent',
'the old agent is saved and stopped',
'starting codex in the same folder (with the handoff)',
+ 'the machine takes no replacement report',
'switched; b opens',
]);
expect(recording.lines.join('\n'), isNot(contains('secret plan')));
@@ -581,6 +877,27 @@ void main() {
expect(steps(rig), isEmpty);
});
+ test('a machine another account shares: never switched from the phone, and '
+ 'nothing is sent, as on the desktop', () async {
+ final rig = await rigWith([source()]);
+ final state = rig.app.machineStates['m']!;
+ // The desktop offers Change agent on its owner's own machine only, and the machine answers
+ // the handoff for its owner alone (cli superTabs/leadSwitch.ts).
+ state.machine = Machine(
+ machineId: 'm',
+ authMode: state.machine.authMode,
+ name: state.machine.name,
+ status: state.machine.status,
+ shared: true,
+ );
+
+ expect(
+ (await rig.app.changeAgent('m', 'a', 'codex')).error,
+ 'Only the person whose machine runs this agent can change it.',
+ );
+ expect(steps(rig), isEmpty);
+ });
+
test('offered for a plain engine only', () {
Agent agent(Map<String, dynamic> json) => Agent.fromJson(json);
expect(AppNotifier.canChangeAgent(agent(source())), isTrue);